File indexing completed on 2024-04-21 05:44:50

0001 # -*- coding: UTF-8 -*-
0002 
0003 """
0004 A timeout decorator.
0005 
0006 Based on SIGALRM from an activeState Python recipe by Chris Wright,
0007 U{http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871}.
0008 
0009 @author: Sébastien Renard <sebastien.renard@digitalfox.org>
0010 @license: GPLv3
0011 """
0012 
0013 import signal
0014 
0015 from pology import PologyError, _, n_
0016 from pology.report import report
0017 
0018 
0019 class TimedOutException (PologyError):
0020 
0021     def __init__ (self, value="timed-out"):
0022 
0023         self.value = value
0024 
0025         PologyError.__init__(str(self))
0026 
0027     def __str__ (self):
0028 
0029         return repr(self.value)
0030 
0031 
0032 def timed_out (timeout):
0033 
0034     def decorate (f):
0035 
0036         def handler (signum, frame):
0037             report(_("@info:progress",
0038                      ">>>>> Operation timed out."))
0039             raise TimedOutException()
0040 
0041         def new_f (*args, **kwargs):
0042             old = signal.signal(signal.SIGALRM, handler)
0043             signal.alarm(timeout)
0044             try:
0045                 result = f(*args, **kwargs)
0046             finally:
0047                 signal.alarm(0)
0048                 signal.signal(signal.SIGALRM, old)
0049             return result
0050 
0051         new_f.__name__ = f.__name__
0052         return new_f
0053 
0054     return decorate
0055