events.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. """Event loop and event loop policy."""
  2. # Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
  3. # SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
  4. # SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
  5. __all__ = (
  6. 'AbstractEventLoopPolicy',
  7. 'AbstractEventLoop', 'AbstractServer',
  8. 'Handle', 'TimerHandle',
  9. 'get_event_loop_policy', 'set_event_loop_policy',
  10. 'get_event_loop', 'set_event_loop', 'new_event_loop',
  11. 'get_child_watcher', 'set_child_watcher',
  12. '_set_running_loop', 'get_running_loop',
  13. '_get_running_loop',
  14. )
  15. import contextvars
  16. import os
  17. import signal
  18. import socket
  19. import subprocess
  20. import sys
  21. import threading
  22. from . import format_helpers
  23. class Handle:
  24. """Object returned by callback registration methods."""
  25. __slots__ = ('_callback', '_args', '_cancelled', '_loop',
  26. '_source_traceback', '_repr', '__weakref__',
  27. '_context')
  28. def __init__(self, callback, args, loop, context=None):
  29. if context is None:
  30. context = contextvars.copy_context()
  31. self._context = context
  32. self._loop = loop
  33. self._callback = callback
  34. self._args = args
  35. self._cancelled = False
  36. self._repr = None
  37. if self._loop.get_debug():
  38. self._source_traceback = format_helpers.extract_stack(
  39. sys._getframe(1))
  40. else:
  41. self._source_traceback = None
  42. def _repr_info(self):
  43. info = [self.__class__.__name__]
  44. if self._cancelled:
  45. info.append('cancelled')
  46. if self._callback is not None:
  47. info.append(format_helpers._format_callback_source(
  48. self._callback, self._args))
  49. if self._source_traceback:
  50. frame = self._source_traceback[-1]
  51. info.append(f'created at {frame[0]}:{frame[1]}')
  52. return info
  53. def __repr__(self):
  54. if self._repr is not None:
  55. return self._repr
  56. info = self._repr_info()
  57. return '<{}>'.format(' '.join(info))
  58. def get_context(self):
  59. return self._context
  60. def cancel(self):
  61. if not self._cancelled:
  62. self._cancelled = True
  63. if self._loop.get_debug():
  64. # Keep a representation in debug mode to keep callback and
  65. # parameters. For example, to log the warning
  66. # "Executing <Handle...> took 2.5 second"
  67. self._repr = repr(self)
  68. self._callback = None
  69. self._args = None
  70. def cancelled(self):
  71. return self._cancelled
  72. def _run(self):
  73. try:
  74. self._context.run(self._callback, *self._args)
  75. except (SystemExit, KeyboardInterrupt):
  76. raise
  77. except BaseException as exc:
  78. cb = format_helpers._format_callback_source(
  79. self._callback, self._args)
  80. msg = f'Exception in callback {cb}'
  81. context = {
  82. 'message': msg,
  83. 'exception': exc,
  84. 'handle': self,
  85. }
  86. if self._source_traceback:
  87. context['source_traceback'] = self._source_traceback
  88. self._loop.call_exception_handler(context)
  89. self = None # Needed to break cycles when an exception occurs.
  90. class TimerHandle(Handle):
  91. """Object returned by timed callback registration methods."""
  92. __slots__ = ['_scheduled', '_when']
  93. def __init__(self, when, callback, args, loop, context=None):
  94. super().__init__(callback, args, loop, context)
  95. if self._source_traceback:
  96. del self._source_traceback[-1]
  97. self._when = when
  98. self._scheduled = False
  99. def _repr_info(self):
  100. info = super()._repr_info()
  101. pos = 2 if self._cancelled else 1
  102. info.insert(pos, f'when={self._when}')
  103. return info
  104. def __hash__(self):
  105. return hash(self._when)
  106. def __lt__(self, other):
  107. if isinstance(other, TimerHandle):
  108. return self._when < other._when
  109. return NotImplemented
  110. def __le__(self, other):
  111. if isinstance(other, TimerHandle):
  112. return self._when < other._when or self.__eq__(other)
  113. return NotImplemented
  114. def __gt__(self, other):
  115. if isinstance(other, TimerHandle):
  116. return self._when > other._when
  117. return NotImplemented
  118. def __ge__(self, other):
  119. if isinstance(other, TimerHandle):
  120. return self._when > other._when or self.__eq__(other)
  121. return NotImplemented
  122. def __eq__(self, other):
  123. if isinstance(other, TimerHandle):
  124. return (self._when == other._when and
  125. self._callback == other._callback and
  126. self._args == other._args and
  127. self._cancelled == other._cancelled)
  128. return NotImplemented
  129. def cancel(self):
  130. if not self._cancelled:
  131. self._loop._timer_handle_cancelled(self)
  132. super().cancel()
  133. def when(self):
  134. """Return a scheduled callback time.
  135. The time is an absolute timestamp, using the same time
  136. reference as loop.time().
  137. """
  138. return self._when
  139. class AbstractServer:
  140. """Abstract server returned by create_server()."""
  141. def close(self):
  142. """Stop serving. This leaves existing connections open."""
  143. raise NotImplementedError
  144. def get_loop(self):
  145. """Get the event loop the Server object is attached to."""
  146. raise NotImplementedError
  147. def is_serving(self):
  148. """Return True if the server is accepting connections."""
  149. raise NotImplementedError
  150. async def start_serving(self):
  151. """Start accepting connections.
  152. This method is idempotent, so it can be called when
  153. the server is already being serving.
  154. """
  155. raise NotImplementedError
  156. async def serve_forever(self):
  157. """Start accepting connections until the coroutine is cancelled.
  158. The server is closed when the coroutine is cancelled.
  159. """
  160. raise NotImplementedError
  161. async def wait_closed(self):
  162. """Coroutine to wait until service is closed."""
  163. raise NotImplementedError
  164. async def __aenter__(self):
  165. return self
  166. async def __aexit__(self, *exc):
  167. self.close()
  168. await self.wait_closed()
  169. class AbstractEventLoop:
  170. """Abstract event loop."""
  171. # Running and stopping the event loop.
  172. def run_forever(self):
  173. """Run the event loop until stop() is called."""
  174. raise NotImplementedError
  175. def run_until_complete(self, future):
  176. """Run the event loop until a Future is done.
  177. Return the Future's result, or raise its exception.
  178. """
  179. raise NotImplementedError
  180. def stop(self):
  181. """Stop the event loop as soon as reasonable.
  182. Exactly how soon that is may depend on the implementation, but
  183. no more I/O callbacks should be scheduled.
  184. """
  185. raise NotImplementedError
  186. def is_running(self):
  187. """Return whether the event loop is currently running."""
  188. raise NotImplementedError
  189. def is_closed(self):
  190. """Returns True if the event loop was closed."""
  191. raise NotImplementedError
  192. def close(self):
  193. """Close the loop.
  194. The loop should not be running.
  195. This is idempotent and irreversible.
  196. No other methods should be called after this one.
  197. """
  198. raise NotImplementedError
  199. async def shutdown_asyncgens(self):
  200. """Shutdown all active asynchronous generators."""
  201. raise NotImplementedError
  202. async def shutdown_default_executor(self):
  203. """Schedule the shutdown of the default executor."""
  204. raise NotImplementedError
  205. # Methods scheduling callbacks. All these return Handles.
  206. def _timer_handle_cancelled(self, handle):
  207. """Notification that a TimerHandle has been cancelled."""
  208. raise NotImplementedError
  209. def call_soon(self, callback, *args, context=None):
  210. return self.call_later(0, callback, *args, context=context)
  211. def call_later(self, delay, callback, *args, context=None):
  212. raise NotImplementedError
  213. def call_at(self, when, callback, *args, context=None):
  214. raise NotImplementedError
  215. def time(self):
  216. raise NotImplementedError
  217. def create_future(self):
  218. raise NotImplementedError
  219. # Method scheduling a coroutine object: create a task.
  220. def create_task(self, coro, *, name=None, context=None):
  221. raise NotImplementedError
  222. # Methods for interacting with threads.
  223. def call_soon_threadsafe(self, callback, *args, context=None):
  224. raise NotImplementedError
  225. def run_in_executor(self, executor, func, *args):
  226. raise NotImplementedError
  227. def set_default_executor(self, executor):
  228. raise NotImplementedError
  229. # Network I/O methods returning Futures.
  230. async def getaddrinfo(self, host, port, *,
  231. family=0, type=0, proto=0, flags=0):
  232. raise NotImplementedError
  233. async def getnameinfo(self, sockaddr, flags=0):
  234. raise NotImplementedError
  235. async def create_connection(
  236. self, protocol_factory, host=None, port=None,
  237. *, ssl=None, family=0, proto=0,
  238. flags=0, sock=None, local_addr=None,
  239. server_hostname=None,
  240. ssl_handshake_timeout=None,
  241. ssl_shutdown_timeout=None,
  242. happy_eyeballs_delay=None, interleave=None):
  243. raise NotImplementedError
  244. async def create_server(
  245. self, protocol_factory, host=None, port=None,
  246. *, family=socket.AF_UNSPEC,
  247. flags=socket.AI_PASSIVE, sock=None, backlog=100,
  248. ssl=None, reuse_address=None, reuse_port=None,
  249. ssl_handshake_timeout=None,
  250. ssl_shutdown_timeout=None,
  251. start_serving=True):
  252. """A coroutine which creates a TCP server bound to host and port.
  253. The return value is a Server object which can be used to stop
  254. the service.
  255. If host is an empty string or None all interfaces are assumed
  256. and a list of multiple sockets will be returned (most likely
  257. one for IPv4 and another one for IPv6). The host parameter can also be
  258. a sequence (e.g. list) of hosts to bind to.
  259. family can be set to either AF_INET or AF_INET6 to force the
  260. socket to use IPv4 or IPv6. If not set it will be determined
  261. from host (defaults to AF_UNSPEC).
  262. flags is a bitmask for getaddrinfo().
  263. sock can optionally be specified in order to use a preexisting
  264. socket object.
  265. backlog is the maximum number of queued connections passed to
  266. listen() (defaults to 100).
  267. ssl can be set to an SSLContext to enable SSL over the
  268. accepted connections.
  269. reuse_address tells the kernel to reuse a local socket in
  270. TIME_WAIT state, without waiting for its natural timeout to
  271. expire. If not specified will automatically be set to True on
  272. UNIX.
  273. reuse_port tells the kernel to allow this endpoint to be bound to
  274. the same port as other existing endpoints are bound to, so long as
  275. they all set this flag when being created. This option is not
  276. supported on Windows.
  277. ssl_handshake_timeout is the time in seconds that an SSL server
  278. will wait for completion of the SSL handshake before aborting the
  279. connection. Default is 60s.
  280. ssl_shutdown_timeout is the time in seconds that an SSL server
  281. will wait for completion of the SSL shutdown procedure
  282. before aborting the connection. Default is 30s.
  283. start_serving set to True (default) causes the created server
  284. to start accepting connections immediately. When set to False,
  285. the user should await Server.start_serving() or Server.serve_forever()
  286. to make the server to start accepting connections.
  287. """
  288. raise NotImplementedError
  289. async def sendfile(self, transport, file, offset=0, count=None,
  290. *, fallback=True):
  291. """Send a file through a transport.
  292. Return an amount of sent bytes.
  293. """
  294. raise NotImplementedError
  295. async def start_tls(self, transport, protocol, sslcontext, *,
  296. server_side=False,
  297. server_hostname=None,
  298. ssl_handshake_timeout=None,
  299. ssl_shutdown_timeout=None):
  300. """Upgrade a transport to TLS.
  301. Return a new transport that *protocol* should start using
  302. immediately.
  303. """
  304. raise NotImplementedError
  305. async def create_unix_connection(
  306. self, protocol_factory, path=None, *,
  307. ssl=None, sock=None,
  308. server_hostname=None,
  309. ssl_handshake_timeout=None,
  310. ssl_shutdown_timeout=None):
  311. raise NotImplementedError
  312. async def create_unix_server(
  313. self, protocol_factory, path=None, *,
  314. sock=None, backlog=100, ssl=None,
  315. ssl_handshake_timeout=None,
  316. ssl_shutdown_timeout=None,
  317. start_serving=True):
  318. """A coroutine which creates a UNIX Domain Socket server.
  319. The return value is a Server object, which can be used to stop
  320. the service.
  321. path is a str, representing a file system path to bind the
  322. server socket to.
  323. sock can optionally be specified in order to use a preexisting
  324. socket object.
  325. backlog is the maximum number of queued connections passed to
  326. listen() (defaults to 100).
  327. ssl can be set to an SSLContext to enable SSL over the
  328. accepted connections.
  329. ssl_handshake_timeout is the time in seconds that an SSL server
  330. will wait for the SSL handshake to complete (defaults to 60s).
  331. ssl_shutdown_timeout is the time in seconds that an SSL server
  332. will wait for the SSL shutdown to finish (defaults to 30s).
  333. start_serving set to True (default) causes the created server
  334. to start accepting connections immediately. When set to False,
  335. the user should await Server.start_serving() or Server.serve_forever()
  336. to make the server to start accepting connections.
  337. """
  338. raise NotImplementedError
  339. async def connect_accepted_socket(
  340. self, protocol_factory, sock,
  341. *, ssl=None,
  342. ssl_handshake_timeout=None,
  343. ssl_shutdown_timeout=None):
  344. """Handle an accepted connection.
  345. This is used by servers that accept connections outside of
  346. asyncio, but use asyncio to handle connections.
  347. This method is a coroutine. When completed, the coroutine
  348. returns a (transport, protocol) pair.
  349. """
  350. raise NotImplementedError
  351. async def create_datagram_endpoint(self, protocol_factory,
  352. local_addr=None, remote_addr=None, *,
  353. family=0, proto=0, flags=0,
  354. reuse_address=None, reuse_port=None,
  355. allow_broadcast=None, sock=None):
  356. """A coroutine which creates a datagram endpoint.
  357. This method will try to establish the endpoint in the background.
  358. When successful, the coroutine returns a (transport, protocol) pair.
  359. protocol_factory must be a callable returning a protocol instance.
  360. socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
  361. host (or family if specified), socket type SOCK_DGRAM.
  362. reuse_address tells the kernel to reuse a local socket in
  363. TIME_WAIT state, without waiting for its natural timeout to
  364. expire. If not specified it will automatically be set to True on
  365. UNIX.
  366. reuse_port tells the kernel to allow this endpoint to be bound to
  367. the same port as other existing endpoints are bound to, so long as
  368. they all set this flag when being created. This option is not
  369. supported on Windows and some UNIX's. If the
  370. :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
  371. capability is unsupported.
  372. allow_broadcast tells the kernel to allow this endpoint to send
  373. messages to the broadcast address.
  374. sock can optionally be specified in order to use a preexisting
  375. socket object.
  376. """
  377. raise NotImplementedError
  378. # Pipes and subprocesses.
  379. async def connect_read_pipe(self, protocol_factory, pipe):
  380. """Register read pipe in event loop. Set the pipe to non-blocking mode.
  381. protocol_factory should instantiate object with Protocol interface.
  382. pipe is a file-like object.
  383. Return pair (transport, protocol), where transport supports the
  384. ReadTransport interface."""
  385. # The reason to accept file-like object instead of just file descriptor
  386. # is: we need to own pipe and close it at transport finishing
  387. # Can got complicated errors if pass f.fileno(),
  388. # close fd in pipe transport then close f and vice versa.
  389. raise NotImplementedError
  390. async def connect_write_pipe(self, protocol_factory, pipe):
  391. """Register write pipe in event loop.
  392. protocol_factory should instantiate object with BaseProtocol interface.
  393. Pipe is file-like object already switched to nonblocking.
  394. Return pair (transport, protocol), where transport support
  395. WriteTransport interface."""
  396. # The reason to accept file-like object instead of just file descriptor
  397. # is: we need to own pipe and close it at transport finishing
  398. # Can got complicated errors if pass f.fileno(),
  399. # close fd in pipe transport then close f and vice versa.
  400. raise NotImplementedError
  401. async def subprocess_shell(self, protocol_factory, cmd, *,
  402. stdin=subprocess.PIPE,
  403. stdout=subprocess.PIPE,
  404. stderr=subprocess.PIPE,
  405. **kwargs):
  406. raise NotImplementedError
  407. async def subprocess_exec(self, protocol_factory, *args,
  408. stdin=subprocess.PIPE,
  409. stdout=subprocess.PIPE,
  410. stderr=subprocess.PIPE,
  411. **kwargs):
  412. raise NotImplementedError
  413. # Ready-based callback registration methods.
  414. # The add_*() methods return None.
  415. # The remove_*() methods return True if something was removed,
  416. # False if there was nothing to delete.
  417. def add_reader(self, fd, callback, *args):
  418. raise NotImplementedError
  419. def remove_reader(self, fd):
  420. raise NotImplementedError
  421. def add_writer(self, fd, callback, *args):
  422. raise NotImplementedError
  423. def remove_writer(self, fd):
  424. raise NotImplementedError
  425. # Completion based I/O methods returning Futures.
  426. async def sock_recv(self, sock, nbytes):
  427. raise NotImplementedError
  428. async def sock_recv_into(self, sock, buf):
  429. raise NotImplementedError
  430. async def sock_recvfrom(self, sock, bufsize):
  431. raise NotImplementedError
  432. async def sock_recvfrom_into(self, sock, buf, nbytes=0):
  433. raise NotImplementedError
  434. async def sock_sendall(self, sock, data):
  435. raise NotImplementedError
  436. async def sock_sendto(self, sock, data, address):
  437. raise NotImplementedError
  438. async def sock_connect(self, sock, address):
  439. raise NotImplementedError
  440. async def sock_accept(self, sock):
  441. raise NotImplementedError
  442. async def sock_sendfile(self, sock, file, offset=0, count=None,
  443. *, fallback=None):
  444. raise NotImplementedError
  445. # Signal handling.
  446. def add_signal_handler(self, sig, callback, *args):
  447. raise NotImplementedError
  448. def remove_signal_handler(self, sig):
  449. raise NotImplementedError
  450. # Task factory.
  451. def set_task_factory(self, factory):
  452. raise NotImplementedError
  453. def get_task_factory(self):
  454. raise NotImplementedError
  455. # Error handlers.
  456. def get_exception_handler(self):
  457. raise NotImplementedError
  458. def set_exception_handler(self, handler):
  459. raise NotImplementedError
  460. def default_exception_handler(self, context):
  461. raise NotImplementedError
  462. def call_exception_handler(self, context):
  463. raise NotImplementedError
  464. # Debug flag management.
  465. def get_debug(self):
  466. raise NotImplementedError
  467. def set_debug(self, enabled):
  468. raise NotImplementedError
  469. class AbstractEventLoopPolicy:
  470. """Abstract policy for accessing the event loop."""
  471. def get_event_loop(self):
  472. """Get the event loop for the current context.
  473. Returns an event loop object implementing the AbstractEventLoop interface,
  474. or raises an exception in case no event loop has been set for the
  475. current context and the current policy does not specify to create one.
  476. It should never return None."""
  477. raise NotImplementedError
  478. def set_event_loop(self, loop):
  479. """Set the event loop for the current context to loop."""
  480. raise NotImplementedError
  481. def new_event_loop(self):
  482. """Create and return a new event loop object according to this
  483. policy's rules. If there's need to set this loop as the event loop for
  484. the current context, set_event_loop must be called explicitly."""
  485. raise NotImplementedError
  486. # Child processes handling (Unix only).
  487. def get_child_watcher(self):
  488. "Get the watcher for child processes."
  489. raise NotImplementedError
  490. def set_child_watcher(self, watcher):
  491. """Set the watcher for child processes."""
  492. raise NotImplementedError
  493. class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
  494. """Default policy implementation for accessing the event loop.
  495. In this policy, each thread has its own event loop. However, we
  496. only automatically create an event loop by default for the main
  497. thread; other threads by default have no event loop.
  498. Other policies may have different rules (e.g. a single global
  499. event loop, or automatically creating an event loop per thread, or
  500. using some other notion of context to which an event loop is
  501. associated).
  502. """
  503. _loop_factory = None
  504. class _Local(threading.local):
  505. _loop = None
  506. _set_called = False
  507. def __init__(self):
  508. self._local = self._Local()
  509. def get_event_loop(self):
  510. """Get the event loop for the current context.
  511. Returns an instance of EventLoop or raises an exception.
  512. """
  513. if (self._local._loop is None and
  514. not self._local._set_called and
  515. threading.current_thread() is threading.main_thread()):
  516. stacklevel = 2
  517. try:
  518. f = sys._getframe(1)
  519. except AttributeError:
  520. pass
  521. else:
  522. # Move up the call stack so that the warning is attached
  523. # to the line outside asyncio itself.
  524. while f:
  525. module = f.f_globals.get('__name__')
  526. if not (module == 'asyncio' or module.startswith('asyncio.')):
  527. break
  528. f = f.f_back
  529. stacklevel += 1
  530. import warnings
  531. warnings.warn('There is no current event loop',
  532. DeprecationWarning, stacklevel=stacklevel)
  533. self.set_event_loop(self.new_event_loop())
  534. if self._local._loop is None:
  535. raise RuntimeError('There is no current event loop in thread %r.'
  536. % threading.current_thread().name)
  537. return self._local._loop
  538. def set_event_loop(self, loop):
  539. """Set the event loop."""
  540. self._local._set_called = True
  541. if loop is not None and not isinstance(loop, AbstractEventLoop):
  542. raise TypeError(f"loop must be an instance of AbstractEventLoop or None, not '{type(loop).__name__}'")
  543. self._local._loop = loop
  544. def new_event_loop(self):
  545. """Create a new event loop.
  546. You must call set_event_loop() to make this the current event
  547. loop.
  548. """
  549. return self._loop_factory()
  550. # Event loop policy. The policy itself is always global, even if the
  551. # policy's rules say that there is an event loop per thread (or other
  552. # notion of context). The default policy is installed by the first
  553. # call to get_event_loop_policy().
  554. _event_loop_policy = None
  555. # Lock for protecting the on-the-fly creation of the event loop policy.
  556. _lock = threading.Lock()
  557. # A TLS for the running event loop, used by _get_running_loop.
  558. class _RunningLoop(threading.local):
  559. loop_pid = (None, None)
  560. _running_loop = _RunningLoop()
  561. def get_running_loop():
  562. """Return the running event loop. Raise a RuntimeError if there is none.
  563. This function is thread-specific.
  564. """
  565. # NOTE: this function is implemented in C (see _asynciomodule.c)
  566. loop = _get_running_loop()
  567. if loop is None:
  568. raise RuntimeError('no running event loop')
  569. return loop
  570. def _get_running_loop():
  571. """Return the running event loop or None.
  572. This is a low-level function intended to be used by event loops.
  573. This function is thread-specific.
  574. """
  575. # NOTE: this function is implemented in C (see _asynciomodule.c)
  576. running_loop, pid = _running_loop.loop_pid
  577. if running_loop is not None and pid == os.getpid():
  578. return running_loop
  579. def _set_running_loop(loop):
  580. """Set the running event loop.
  581. This is a low-level function intended to be used by event loops.
  582. This function is thread-specific.
  583. """
  584. # NOTE: this function is implemented in C (see _asynciomodule.c)
  585. _running_loop.loop_pid = (loop, os.getpid())
  586. def _init_event_loop_policy():
  587. global _event_loop_policy
  588. with _lock:
  589. if _event_loop_policy is None: # pragma: no branch
  590. from . import DefaultEventLoopPolicy
  591. _event_loop_policy = DefaultEventLoopPolicy()
  592. def get_event_loop_policy():
  593. """Get the current event loop policy."""
  594. if _event_loop_policy is None:
  595. _init_event_loop_policy()
  596. return _event_loop_policy
  597. def set_event_loop_policy(policy):
  598. """Set the current event loop policy.
  599. If policy is None, the default policy is restored."""
  600. global _event_loop_policy
  601. if policy is not None and not isinstance(policy, AbstractEventLoopPolicy):
  602. raise TypeError(f"policy must be an instance of AbstractEventLoopPolicy or None, not '{type(policy).__name__}'")
  603. _event_loop_policy = policy
  604. def get_event_loop():
  605. """Return an asyncio event loop.
  606. When called from a coroutine or a callback (e.g. scheduled with call_soon
  607. or similar API), this function will always return the running event loop.
  608. If there is no running event loop set, the function will return
  609. the result of `get_event_loop_policy().get_event_loop()` call.
  610. """
  611. # NOTE: this function is implemented in C (see _asynciomodule.c)
  612. current_loop = _get_running_loop()
  613. if current_loop is not None:
  614. return current_loop
  615. return get_event_loop_policy().get_event_loop()
  616. def set_event_loop(loop):
  617. """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
  618. get_event_loop_policy().set_event_loop(loop)
  619. def new_event_loop():
  620. """Equivalent to calling get_event_loop_policy().new_event_loop()."""
  621. return get_event_loop_policy().new_event_loop()
  622. def get_child_watcher():
  623. """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
  624. return get_event_loop_policy().get_child_watcher()
  625. def set_child_watcher(watcher):
  626. """Equivalent to calling
  627. get_event_loop_policy().set_child_watcher(watcher)."""
  628. return get_event_loop_policy().set_child_watcher(watcher)
  629. # Alias pure-Python implementations for testing purposes.
  630. _py__get_running_loop = _get_running_loop
  631. _py__set_running_loop = _set_running_loop
  632. _py_get_running_loop = get_running_loop
  633. _py_get_event_loop = get_event_loop
  634. try:
  635. # get_event_loop() is one of the most frequently called
  636. # functions in asyncio. Pure Python implementation is
  637. # about 4 times slower than C-accelerated.
  638. from _asyncio import (_get_running_loop, _set_running_loop,
  639. get_running_loop, get_event_loop)
  640. except ImportError:
  641. pass
  642. else:
  643. # Alias C implementations for testing purposes.
  644. _c__get_running_loop = _get_running_loop
  645. _c__set_running_loop = _set_running_loop
  646. _c_get_running_loop = get_running_loop
  647. _c_get_event_loop = get_event_loop
  648. if hasattr(os, 'fork'):
  649. def on_fork():
  650. # Reset the loop and wakeupfd in the forked child process.
  651. if _event_loop_policy is not None:
  652. _event_loop_policy._local = BaseDefaultEventLoopPolicy._Local()
  653. _set_running_loop(None)
  654. signal.set_wakeup_fd(-1)
  655. os.register_at_fork(after_in_child=on_fork)