zulip/zerver/lib/timeout.py

97 lines
3.2 KiB
Python
Raw Normal View History

import ctypes
import logging
import sys
import threading
import time
from types import TracebackType
from typing import Callable, Optional, Tuple, Type, TypeVar
# Based on https://code.activestate.com/recipes/483752/
class TimeoutExpired(Exception):
"""Exception raised when a function times out."""
def __str__(self) -> str:
return "Function call timed out."
ResultT = TypeVar("ResultT")
2016-06-29 00:14:07 +02:00
def timeout(timeout: float, func: Callable[[], ResultT]) -> ResultT:
"""Call the function in a separate thread.
Return its return value, or raise an exception,
within approximately 'timeout' seconds.
The function may receive a TimeoutExpired exception
anywhere in its code, which could have arbitrary
unsafe effects (resources not released, etc.).
It might also fail to receive the exception and
keep running in the background even though
timeout() has returned.
This may also fail to interrupt functions which are
stuck in a long-running primitive interpreter
operation."""
class TimeoutThread(threading.Thread):
def __init__(self) -> None:
threading.Thread.__init__(self)
python: Convert assignment type annotations to Python 3.6 style. This commit was split by tabbott; this piece covers the vast majority of files in Zulip, but excludes scripts/, tools/, and puppet/ to help ensure we at least show the right error messages for Xenial systems. We can likely further refine the remaining pieces with some testing. Generated by com2ann, with whitespace fixes and various manual fixes for runtime issues: - invoiced_through: Optional[LicenseLedger] = models.ForeignKey( + invoiced_through: Optional["LicenseLedger"] = models.ForeignKey( -_apns_client: Optional[APNsClient] = None +_apns_client: Optional["APNsClient"] = None - notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE) - signup_notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE) + notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE) + signup_notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE) - author: Optional[UserProfile] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE) + author: Optional["UserProfile"] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE) - bot_owner: Optional[UserProfile] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) + bot_owner: Optional["UserProfile"] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) - default_sending_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE) - default_events_register_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE) + default_sending_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE) + default_events_register_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE) -descriptors_by_handler_id: Dict[int, ClientDescriptor] = {} +descriptors_by_handler_id: Dict[int, "ClientDescriptor"] = {} -worker_classes: Dict[str, Type[QueueProcessingWorker]] = {} -queues: Dict[str, Dict[str, Type[QueueProcessingWorker]]] = {} +worker_classes: Dict[str, Type["QueueProcessingWorker"]] = {} +queues: Dict[str, Dict[str, Type["QueueProcessingWorker"]]] = {} -AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional[LDAPSearch] = None +AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-22 01:09:50 +02:00
self.result: Optional[ResultT] = None
self.exc_info: Tuple[
Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType],
] = (None, None, None)
# Don't block the whole program from exiting
# if this is the only thread left.
self.daemon = True
def run(self) -> None:
try:
self.result = func()
except BaseException:
self.exc_info = sys.exc_info()
def raise_async_timeout(self) -> None:
# This function is called from another thread; we attempt
# to raise a TimeoutExpired in _this_ thread.
assert self.ident is not None
ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(self.ident),
ctypes.py_object(TimeoutExpired),
)
thread = TimeoutThread()
thread.start()
thread.join(timeout)
if thread.is_alive():
# We need to retry, because an async exception received while
# the thread is in a system call is simply ignored.
for i in range(10):
thread.raise_async_timeout()
time.sleep(0.1)
if not thread.is_alive():
break
if thread.exc_info[1] is not None:
# Re-raise the exception we sent, if possible, so the
# stacktrace originates in the slow code
raise thread.exc_info[1].with_traceback(thread.exc_info[2])
# If we don't have that for some reason (e.g. we failed to
# kill it), just raise from here; the thread _may still be
# running_ because it failed to see any of our exceptions, and
# we just ignore it.
if thread.is_alive():
logging.warning("Failed to time out backend thread")
raise TimeoutExpired
if thread.exc_info[1] is not None:
# Died with some other exception; re-raise it
raise thread.exc_info[1].with_traceback(thread.exc_info[2])
assert thread.result is not None
return thread.result