Python signal.alarm() Examples

The following are 30 code examples for showing how to use signal.alarm(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module signal , or try the search function .

Example 1
Project: sanic   Author: huge-success   File: test_multiprocessing.py    License: MIT License 6 votes vote down vote up
def test_multiprocessing(app):
    """Tests that the number of children we produce is correct"""
    # Selects a number at random so we can spot check
    num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1))
    process_list = set()

    def stop_on_alarm(*args):
        for process in multiprocessing.active_children():
            process_list.add(process.pid)
            process.terminate()

    signal.signal(signal.SIGALRM, stop_on_alarm)
    signal.alarm(3)
    app.run(HOST, PORT, workers=num_workers)

    assert len(process_list) == num_workers 
Example 2
Project: sanic   Author: huge-success   File: test_multiprocessing.py    License: MIT License 6 votes vote down vote up
def test_multiprocessing_with_blueprint(app):
    # Selects a number at random so we can spot check
    num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1))
    process_list = set()

    def stop_on_alarm(*args):
        for process in multiprocessing.active_children():
            process_list.add(process.pid)
            process.terminate()

    signal.signal(signal.SIGALRM, stop_on_alarm)
    signal.alarm(3)

    bp = Blueprint("test_text")
    app.blueprint(bp)
    app.run(HOST, PORT, workers=num_workers)

    assert len(process_list) == num_workers


# this function must be outside a test function so that it can be
# able to be pickled (local functions cannot be pickled). 
Example 3
Project: Sibyl   Author: cea-sec   File: miasm.py    License: GNU General Public License v3.0 6 votes vote down vote up
def run(self, address, timeout_seconds):
        self.jitter.init_run(address)

        try:
            signal.alarm(timeout_seconds)
            self.jitter.continue_run()
        except (AssertionError, RuntimeError, ValueError,
                KeyError, IndexError, TimeoutException) as _:
            return False
        except Exception as error:
            self.logger.exception(error)
            return False
        finally:
            signal.alarm(0)

        return True 
Example 4
Project: rainmachine-developer-resources   Author: sprinkler   File: rmParser.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(cls, name, bases, attrs):
            super(RMParserType, cls).__init__(name, bases, attrs)
            if not hasattr(cls, "parsers"):
                cls.parsers = []
            else:
                cls.registerParser(cls)

            # Add timeout to perform function
            if hasattr(cls, "perform"):
                def timedPerform(self):
                    global USE_THREADING__
                    if not USE_THREADING__:
                        seconds = 10 * 60
                        _old_handler = signal.signal(signal.SIGALRM, _handle_timeout)
                        signal.alarm(seconds)
                    try:
                        result = attrs["perform"](self)
                    except RMTimeoutError, e:
                        log.error("*** Timeout occurred while running parser %s" % self.parserName)
                        log.exception(e)
                        return None
                    finally: 
Example 5
Project: kano-toolset   Author: KanoComputing   File: timeout.py    License: GNU General Public License v2.0 6 votes vote down vote up
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator 
Example 6
Project: scrapy-cluster   Author: istresearch   File: method_timer.py    License: MIT License 6 votes vote down vote up
def timeout(timeout_time, default):
        '''
        Decorate a method so it is required to execute in a given time period,
        or return a default value.
        '''
        def timeout_function(f):
            def f2(*args):
                def timeout_handler(signum, frame):
                    raise MethodTimer.DecoratorTimeout()

                old_handler = signal.signal(signal.SIGALRM, timeout_handler)
                # triger alarm in timeout_time seconds
                signal.alarm(timeout_time)
                try:
                    retval = f(*args)
                except MethodTimer.DecoratorTimeout:
                    return default
                finally:
                    signal.signal(signal.SIGALRM, old_handler)
                signal.alarm(0)
                return retval
            return f2
        return timeout_function 
Example 7
Project: sagemaker-pytorch-training-toolkit   Author: aws   File: timeout.py    License: Apache License 2.0 6 votes vote down vote up
def timeout(seconds=0, minutes=0, hours=0):
    """Add a signal-based timeout to any block of code.
    If multiple time units are specified, they will be added together to determine time limit.
    Usage:
    with timeout(seconds=5):
        my_slow_function(...)
    Args:
        - seconds: The time limit, in seconds.
        - minutes: The time limit, in minutes.
        - hours: The time limit, in hours.
    """

    limit = seconds + 60 * minutes + 3600 * hours

    def handler(signum, frame):
        raise TimeoutError('timed out after {} seconds'.format(limit))

    try:
        signal.signal(signal.SIGALRM, handler)
        signal.alarm(limit)

        yield
    finally:
        signal.alarm(0) 
Example 8
Project: sagemaker-mxnet-inference-toolkit   Author: aws   File: timeout.py    License: Apache License 2.0 6 votes vote down vote up
def timeout(seconds=0, minutes=0, hours=0):
    """
    Add a signal-based timeout to any block of code.
    If multiple time units are specified, they will be added together to determine time limit.
    Usage:
    with timeout(seconds=5):
        my_slow_function(...)
    Args:
        - seconds: The time limit, in seconds.
        - minutes: The time limit, in minutes.
        - hours: The time limit, in hours.
    """

    limit = seconds + 60 * minutes + 3600 * hours

    def handler(signum, frame):
        raise TimeoutError('timed out after {} seconds'.format(limit))

    try:
        signal.signal(signal.SIGALRM, handler)
        signal.alarm(limit)

        yield
    finally:
        signal.alarm(0) 
Example 9
Project: ironpython2   Author: IronLanguages   File: test_signal.py    License: Apache License 2.0 6 votes vote down vote up
def test_wakeup_fd_early(self):
        import select

        signal.alarm(1)
        try:
            before_time = time.time()
            # We attempt to get a signal during the sleep,
            # before select is called
            time.sleep(self.TIMEOUT_FULL)
            mid_time = time.time()
        finally:
            signal.alarm(0)

        self.assertTrue(mid_time - before_time < self.TIMEOUT_HALF)
        select.select([self.read], [], [], self.TIMEOUT_FULL)
        after_time = time.time()
        self.assertTrue(after_time - mid_time < self.TIMEOUT_HALF) 
Example 10
Project: ironpython2   Author: IronLanguages   File: test_io.py    License: Apache License 2.0 6 votes vote down vote up
def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
        """Check that a buffered read, when it gets interrupted (either
        returning a partial result or EINTR), properly invokes the signal
        handler and retries if the latter returned successfully."""
        r, w = os.pipe()
        fdopen_kwargs["closefd"] = False
        def alarm_handler(sig, frame):
            os.write(w, b"bar")
        signal.signal(signal.SIGALRM, alarm_handler)
        try:
            rio = self.io.open(r, **fdopen_kwargs)
            os.write(w, b"foo")
            signal.alarm(1)
            # Expected behaviour:
            # - first raw read() returns partial b"foo"
            # - second raw read() returns EINTR
            # - third raw read() returns b"bar"
            self.assertEqual(decode(rio.read(6)), "foobar")
        finally:
            signal.alarm(0)
            rio.close()
            os.close(w)
            os.close(r) 
Example 11
Project: ironpython2   Author: IronLanguages   File: test_subprocess.py    License: Apache License 2.0 6 votes vote down vote up
def test_communicate_eintr(self):
        # Issue #12493: communicate() should handle EINTR
        def handler(signum, frame):
            pass
        old_handler = signal.signal(signal.SIGALRM, handler)
        self.addCleanup(signal.signal, signal.SIGALRM, old_handler)

        # the process is running for 2 seconds
        args = [sys.executable, "-c", 'import time; time.sleep(2)']
        for stream in ('stdout', 'stderr'):
            kw = {stream: subprocess.PIPE}
            with subprocess.Popen(args, **kw) as process:
                signal.alarm(1)
                try:
                    # communicate() will be interrupted by SIGALRM
                    process.communicate()
                finally:
                    signal.alarm(0) 
Example 12
Project: avocado-vt   Author: avocado-framework   File: virtio_console_guest.py    License: GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        """
        Run guest main thread
        """
        global virt
        global exiting
        virt = VirtioGuestPosix()
        slave = Thread(target=worker, args=(virt,))
        slave.start()
        signal.signal(signal.SIGUSR1, sigusr_handler)
        signal.signal(signal.SIGALRM, sigusr_handler)
        while not exiting:
            signal.alarm(1)
            signal.pause()
            catch = virt.catching_signal()
            if catch:
                signal.signal(signal.SIGIO, virt)
            elif catch is False:
                signal.signal(signal.SIGIO, signal.SIG_DFL)
            if catch is not None:
                virt.use_config.set()
        print("PASS: guest_exit")
        sys.exit(0) 
Example 13
Project: BinderFilter   Author: dxwu   File: test_io.py    License: MIT License 6 votes vote down vote up
def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
        """Check that a buffered read, when it gets interrupted (either
        returning a partial result or EINTR), properly invokes the signal
        handler and retries if the latter returned successfully."""
        r, w = os.pipe()
        fdopen_kwargs["closefd"] = False
        def alarm_handler(sig, frame):
            os.write(w, b"bar")
        signal.signal(signal.SIGALRM, alarm_handler)
        try:
            rio = self.io.open(r, **fdopen_kwargs)
            os.write(w, b"foo")
            signal.alarm(1)
            # Expected behaviour:
            # - first raw read() returns partial b"foo"
            # - second raw read() returns EINTR
            # - third raw read() returns b"bar"
            self.assertEqual(decode(rio.read(6)), "foobar")
        finally:
            rio.close()
            os.close(w)
            os.close(r) 
Example 14
Project: BinderFilter   Author: dxwu   File: test_threadsignals.py    License: MIT License 6 votes vote down vote up
def test_signals(self):
        signalled_all.acquire()
        self.spawnSignallingThread()
        signalled_all.acquire()
        # the signals that we asked the kernel to send
        # will come back, but we don't know when.
        # (it might even be after the thread exits
        # and might be out of order.)  If we haven't seen
        # the signals yet, send yet another signal and
        # wait for it return.
        if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
           or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
            signal.alarm(1)
            signal.pause()
            signal.alarm(0)

        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
                           thread.get_ident())
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
                           thread.get_ident())
        signalled_all.release() 
Example 15
Project: oss-ftp   Author: aliyun   File: test_io.py    License: MIT License 6 votes vote down vote up
def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
        """Check that a buffered read, when it gets interrupted (either
        returning a partial result or EINTR), properly invokes the signal
        handler and retries if the latter returned successfully."""
        r, w = os.pipe()
        fdopen_kwargs["closefd"] = False
        def alarm_handler(sig, frame):
            os.write(w, b"bar")
        signal.signal(signal.SIGALRM, alarm_handler)
        try:
            rio = self.io.open(r, **fdopen_kwargs)
            os.write(w, b"foo")
            signal.alarm(1)
            # Expected behaviour:
            # - first raw read() returns partial b"foo"
            # - second raw read() returns EINTR
            # - third raw read() returns b"bar"
            self.assertEqual(decode(rio.read(6)), "foobar")
        finally:
            rio.close()
            os.close(w)
            os.close(r) 
Example 16
Project: sanic   Author: huge-success   File: test_server_events.py    License: MIT License 5 votes vote down vote up
def start_stop_app(random_name_app, **run_kwargs):
    def stop_on_alarm(signum, frame):
        raise KeyboardInterrupt("SIGINT for sanic to stop gracefully")

    signal.signal(signal.SIGALRM, stop_on_alarm)
    signal.alarm(1)
    try:
        random_name_app.run(HOST, PORT, **run_kwargs)
    except KeyboardInterrupt:
        pass 
Example 17
Project: tartarus   Author: sergiooramas   File: create_spectrograms.py    License: MIT License 5 votes vote down vote up
def do_process(id, audio_file, spectro_file):
	try:
		if config['compute_spectro']:
			#print spectro_file[:spectro_file.rfind('/')+1]
			try:
				if not os.path.exists(spectro_file[:spectro_file.rfind('/')+1]):
					os.makedirs(spectro_file[:spectro_file.rfind('/')+1])
			except:
				pass
			if not os.path.isfile(spectro_file): 
				signal.signal(signal.SIGALRM, signal_handler)
				signal.alarm(50)
				compute_spec(audio_file,spectro_file)
			fw = open(common.SPECTRO_PATH+config['spectro_folder']+"index.tsv","a")
			fw.write("%s\t%s\t%s\n" % (id,spectro_file[len(common.SPECTRO_PATH):],audio_file))
			fw.close()
			print 'Computed spec: %s' % audio_file
		else:
			if os.path.isfile(spectro_file):
				fw = open(common.SPECTRO_PATH+config['spectro_folder']+"index.tsv","a")
				fw.write("%s\t%s\t%s\n" % (id,spectro_file[len(common.SPECTRO_PATH):],audio_file))
				fw.close()
	except Exception as e:
		ferrors = open(common.SPECTRO_PATH+config['spectro_folder']+"errors.txt","a")
		ferrors.write(audio_file+"\n")
		ferrors.write(str(e))
	#	ferrors.close()
		print 'Error computing spec', audio_file
		print str(e) 
Example 18
Project: zun   Author: openstack   File: cni.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    d = jsonutils.load(sys.stdin.buffer)
    cni_conf = utils.CNIConfig(d)
    args = (['--config-file', cni_conf.zun_conf] if 'zun_conf' in d
            else [])

    try:
        if cni_conf.debug:
            args.append('-d')
    except AttributeError:
        pass
    config.init(args)
    if os.environ.get('CNI_COMMAND') == 'VERSION':
        CONF.set_default('use_stderr', True)

    # Initialize o.vo registry.
    os_vif.initialize()

    runner = cni_api.CNIDaemonizedRunner()

    def _timeout(signum, frame):
        runner._write_dict(sys.stdout, {
            'msg': 'timeout',
            'code': consts.CNI_TIMEOUT_CODE,
        })
        LOG.debug('timed out')
        sys.exit(1)

    signal.signal(signal.SIGALRM, _timeout)
    signal.alarm(_CNI_TIMEOUT)
    status = runner.run(os.environ, cni_conf, sys.stdout)
    LOG.debug("Exiting with status %s", status)
    if status:
        sys.exit(status) 
Example 19
Project: pyspider   Author: binux   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def __enter__(self):
            if not isinstance(threading.current_thread(), threading._MainThread):
                logging.warning("timeout only works on main thread, are you running pyspider in threads?")
                self.seconds = 0
            if self.seconds:
                signal.signal(signal.SIGALRM, self.handle_timeout)
                signal.alarm(int(math.ceil(self.seconds))) 
Example 20
Project: pyspider   Author: binux   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def __exit__(self, type, value, traceback):
            if self.seconds:
                signal.alarm(0) 
Example 21
Project: tornado-zh   Author: tao12345666333   File: netutil_test.py    License: MIT License 5 votes vote down vote up
def test_import(self):
        TIMEOUT = 5

        # Test for a deadlock when importing a module that runs the
        # ThreadedResolver at import-time. See resolve_test.py for
        # full explanation.
        command = [
            sys.executable,
            '-c',
            'import tornado.test.resolve_test_helper']

        start = time.time()
        popen = Popen(command, preexec_fn=lambda: signal.alarm(TIMEOUT))
        while time.time() - start < TIMEOUT:
            return_code = popen.poll()
            if return_code is not None:
                self.assertEqual(0, return_code)
                return  # Success.
            time.sleep(0.05)

        self.fail("import timed out")


# We do not test errors with CaresResolver:
# Some DNS-hijacking ISPs (e.g. Time Warner) return non-empty results
# with an NXDOMAIN status code.  Most resolvers treat this as an error;
# C-ares returns the results, making the "bad_host" tests unreliable.
# C-ares will try to resolve even malformed names, such as the
# name with spaces used in this test. 
Example 22
Project: tornado-zh   Author: tao12345666333   File: process_test.py    License: MIT License 5 votes vote down vote up
def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        # In the surviving process, clear the alarm we set earlier
        signal.alarm(0)
        super(ProcessTest, self).tearDown() 
Example 23
Project: tornado-zh   Author: tao12345666333   File: netutil_test.py    License: MIT License 5 votes vote down vote up
def test_import(self):
        TIMEOUT = 5

        # Test for a deadlock when importing a module that runs the
        # ThreadedResolver at import-time. See resolve_test.py for
        # full explanation.
        command = [
            sys.executable,
            '-c',
            'import tornado.test.resolve_test_helper']

        start = time.time()
        popen = Popen(command, preexec_fn=lambda: signal.alarm(TIMEOUT))
        while time.time() - start < TIMEOUT:
            return_code = popen.poll()
            if return_code is not None:
                self.assertEqual(0, return_code)
                return  # Success.
            time.sleep(0.05)

        self.fail("import timed out")


# We do not test errors with CaresResolver:
# Some DNS-hijacking ISPs (e.g. Time Warner) return non-empty results
# with an NXDOMAIN status code.  Most resolvers treat this as an error;
# C-ares returns the results, making the "bad_host" tests unreliable.
# C-ares will try to resolve even malformed names, such as the
# name with spaces used in this test. 
Example 24
Project: tornado-zh   Author: tao12345666333   File: process_test.py    License: MIT License 5 votes vote down vote up
def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        # In the surviving process, clear the alarm we set earlier
        signal.alarm(0)
        super(ProcessTest, self).tearDown() 
Example 25
Project: openSUSE-release-tools   Author: openSUSE   File: ToolBase.py    License: GNU General Public License v2.0 5 votes vote down vote up
def runner(self, workfunc, interval):
        """ runs the specified callback every <interval> minutes or
        once if interval is None or 0
        """
        class ExTimeout(Exception):
            """raised on timeout"""

        if interval:
            def alarm_called(nr, frame):
                raise ExTimeout()
            signal.signal(signal.SIGALRM, alarm_called)

        while True:
            try:
                workfunc()
            except Exception as e:
                logger.exception(e)

            if interval:
                logger.info("sleeping %d minutes. Press enter to check now ..." % interval)
                signal.alarm(interval * 60)
                try:
                    input()
                except ExTimeout:
                    pass
                signal.alarm(0)
                logger.info("recheck at %s" % datetime.datetime.now().isoformat())
                continue
            break 
Example 26
Project: kuryr-kubernetes   Author: openstack   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def run():
    d = jsonutils.load(sys.stdin.buffer)
    cni_conf = utils.CNIConfig(d)
    args = (['--config-file', cni_conf.kuryr_conf] if 'kuryr_conf' in d
            else [])

    try:
        if cni_conf.debug:
            args.append('-d')
    except AttributeError:
        pass
    config.init(args)
    config.setup_logging()

    # Initialize o.vo registry.
    k_objects.register_locally_defined_vifs()
    os_vif.initialize()

    runner = cni_api.CNIDaemonizedRunner()

    def _timeout(signum, frame):
        runner._write_dict(sys.stdout, {
            'msg': 'timeout',
            'code': k_const.CNI_TIMEOUT_CODE,
        })
        LOG.debug('timed out')
        sys.exit(1)

    signal.signal(signal.SIGALRM, _timeout)
    signal.alarm(_CNI_TIMEOUT)
    status = runner.run(os.environ, cni_conf, sys.stdout)
    LOG.debug("Exiting with status %s", status)
    if status:
        sys.exit(status) 
Example 27
Project: mysql_utils   Author: pinterest   File: timeout.py    License: GNU General Public License v2.0 5 votes vote down vote up
def timeout(seconds):
    """ Wrapper for signals handling a timeout for being
    used as a decorator. """
    def timeout_handler(signum, frame):
        pass

    original_handler = signal.signal(signal.SIGALRM, timeout_handler)

    try:
        signal.alarm(seconds)
        yield
    finally:
        signal.alarm(0)
        signal.signal(signal.SIGALRM, original_handler) 
Example 28
Project: omniduct   Author: airbnb   File: processes.py    License: MIT License 5 votes vote down vote up
def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds) 
Example 29
Project: omniduct   Author: airbnb   File: processes.py    License: MIT License 5 votes vote down vote up
def __exit__(self, type, value, traceback):
        signal.alarm(0) 
Example 30
Project: PrivacyScore   Author: PrivacyScore   File: tasks.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __enter__(self):
        def handle_timeout(signum, frame):
            # kill all possible processes
            # TODO: this is a really bad idea
            # TODO: Especially with multiple worker threads, bad things are inevitable
            own_procs = get_processes_of_user(getuser())
            for pid, cmdline in own_procs:
                # TODO: Argh
                if '/tests/' not in cmdline:
                    continue
                os.kill(pid, 9)
            raise TimeoutError

        signal.signal(signal.SIGALRM, handle_timeout)
        signal.alarm(self.seconds)