forked from cockpit-project/bots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeout.py
51 lines (43 loc) · 1.77 KB
/
timeout.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# This file is part of Cockpit.
#
# Copyright (C) 2013 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
import signal
class Timeout:
""" Add a timeout to an operation
Specify machine to ensure that a machine's ssh operations are canceled when the timer expires.
"""
def __init__(self, seconds=1, error_message='Timeout', machine=None):
if signal.getsignal(signal.SIGALRM) != signal.SIG_DFL:
# there is already a different Timeout active
self.seconds = None
return
self.seconds = seconds
self.error_message = error_message
self.machine = machine
def handle_timeout(self, signum, frame):
if self.machine:
if self.machine.ssh_process:
self.machine.ssh_process.terminate()
self.machine.disconnect()
raise RuntimeError(self.error_message)
def __enter__(self):
if self.seconds:
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, _type, value, traceback):
if self.seconds:
signal.alarm(0)
signal.signal(signal.SIGALRM, signal.SIG_DFL)