-
-
Notifications
You must be signed in to change notification settings - Fork 348
/
Copy path_run.py
1379 lines (1178 loc) · 51.9 KB
/
_run.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import inspect
import enum
from collections import deque
import threading
from time import monotonic
import os
import random
from contextlib import contextmanager, closing
import select
import sys
from math import inf
import functools
import attr
from sortedcontainers import SortedDict
from async_generator import async_generator, yield_
from .._util import acontextmanager
from .. import _core
from ._exceptions import (
TrioInternalError, RunFinishedError, Cancelled, WouldBlock
)
from ._multierror import MultiError
from ._result import Result, Error, Value
from ._traps import (
yield_briefly_no_cancel, Abort, yield_indefinitely,
)
from ._ki import (
LOCALS_KEY_KI_PROTECTION_ENABLED, currently_ki_protected, ki_manager,
enable_ki_protection
)
from ._wakeup_socketpair import WakeupSocketpair
from . import _public, _hazmat
# At the bottom of this file there's also some "clever" code that generates
# wrapper functions for runner and io manager methods, and adds them to
# __all__. These are all re-exported as part of the 'trio' or 'trio.hazmat'
# namespaces.
__all__ = ["Task", "run", "open_nursery", "open_cancel_scope",
"yield_briefly", "current_task", "current_effective_deadline",
"yield_if_cancelled"]
GLOBAL_RUN_CONTEXT = threading.local()
if os.name == "nt":
from ._io_windows import WindowsIOManager as TheIOManager
elif hasattr(select, "epoll"):
from ._io_epoll import EpollIOManager as TheIOManager
elif hasattr(select, "kqueue"):
from ._io_kqueue import KqueueIOManager as TheIOManager
else: # pragma: no cover
raise NotImplementedError("unsupported platform")
_r = random.Random()
@attr.s(slots=True, frozen=True)
class SystemClock:
# Add a large random offset to our clock to ensure that if people
# accidentally call time.monotonic() directly or start comparing clocks
# between different runs, then they'll notice the bug quickly:
offset = attr.ib(default=attr.Factory(lambda: _r.uniform(10000, 200000)))
def start_clock(self):
pass
def current_time(self):
return self.offset + monotonic()
def deadline_to_sleep_time(self, deadline):
return deadline - self.current_time()
################################################################
# CancelScope and friends
################################################################
@attr.s(slots=True, cmp=False, hash=False)
class CancelScope:
_tasks = attr.ib(default=attr.Factory(set))
_effective_deadline = attr.ib(default=inf)
_deadline = attr.ib(default=inf)
_shield = attr.ib(default=False)
# We want to re-use the same exception object within a given task, to get
# complete tracebacks. This maps {task: exception} for active tasks.
_excs = attr.ib(default=attr.Factory(dict))
cancel_called = attr.ib(default=False)
cancelled_caught = attr.ib(default=False)
@contextmanager
@enable_ki_protection
def _might_change_effective_deadline(self):
try:
yield
finally:
old = self._effective_deadline
if self.cancel_called or not self._tasks:
new = inf
else:
new = self._deadline
if old != new:
self._effective_deadline = new
runner = GLOBAL_RUN_CONTEXT.runner
if old != inf:
del runner.deadlines[old, id(self)]
if new != inf:
runner.deadlines[new, id(self)] = self
@property
def deadline(self):
return self._deadline
@deadline.setter
def deadline(self, new_deadline):
with self._might_change_effective_deadline():
self._deadline = float(new_deadline)
@property
def shield(self):
return self._shield
@shield.setter
def shield(self, new_value):
if not isinstance(new_value, bool):
raise TypeError("shield must be a bool")
self._shield = new_value
if not self._shield:
for task in self._tasks:
task._attempt_delivery_of_any_pending_cancel()
def _cancel_no_notify(self):
# returns the affected tasks
if not self.cancel_called:
with self._might_change_effective_deadline():
self.cancel_called = True
return self._tasks
else:
return set()
@enable_ki_protection
def cancel(self):
for task in self._cancel_no_notify():
task._attempt_delivery_of_any_pending_cancel()
def _add_task(self, task):
self._tasks.add(task)
task._cancel_stack.append(self)
def _remove_task(self, task):
with self._might_change_effective_deadline():
self._tasks.remove(task)
if task in self._excs:
del self._excs[task]
assert task._cancel_stack[-1] is self
task._cancel_stack.pop()
def _make_exc(self, task):
if task not in self._excs:
exc = Cancelled()
exc._scope = self
self._excs[task] = exc
return self._excs[task]
def _exc_filter(self, exc):
if isinstance(exc, Cancelled) and exc._scope is self:
self.cancelled_caught = True
return None
return exc
@contextmanager
@enable_ki_protection
def open_cancel_scope(*, deadline=inf, shield=False):
"""Returns a context manager which creates a new cancellation scope.
"""
task = _core.current_task()
scope = CancelScope()
scope._add_task(task)
scope.deadline = deadline
scope.shield = shield
try:
with MultiError.catch(scope._exc_filter):
yield scope
finally:
scope._remove_task(task)
################################################################
# Nursery and friends
################################################################
@acontextmanager
@async_generator
@enable_ki_protection
async def open_nursery():
"""Returns an async context manager which creates a new nursery.
This context manager's ``__aenter__`` method executes synchronously. Its
``__aexit__`` method blocks until all child tasks have exited.
"""
assert currently_ki_protected()
with open_cancel_scope() as scope:
nursery = Nursery(current_task(), scope)
pending_exc = None
try:
await yield_(nursery)
except BaseException as exc:
pending_exc = exc
assert currently_ki_protected()
await nursery._clean_up(pending_exc)
# I *think* this is equivalent to the above, and it gives *much* nicer
# exception tracebacks... but I'm a little nervous about it because it's much
# trickier code :-(
#
# class NurseryManager:
# @enable_ki_protection
# async def __aenter__(self):
# self._scope_manager = open_cancel_scope()
# scope = self._scope_manager.__enter__()
# self._nursery = Nursery(current_task(), scope)
# return self._nursery
#
# @enable_ki_protection
# async def __aexit__(self, etype, exc, tb):
# try:
# await self._nursery._clean_up(exc)
# except BaseException as new_exc:
# if not self._scope_manager.__exit__(
# type(new_exc), new_exc, new_exc.__traceback__):
# if exc is new_exc:
# return False
# else:
# raise
# else:
# self._scope_manager.__exit__(None, None, None)
# return True
#
# def open_nursery():
# return NurseryManager()
class Nursery:
def __init__(self, parent, cancel_scope):
# the parent task -- only used for introspection, to implement
# task.parent_task
self._parent = parent
# the cancel stack that children inherit - we take a snapshot, so it
# won't be affected by any changes in the parent.
self._cancel_stack = list(parent._cancel_stack)
# the cancel scope that directly surrounds us; used for cancelling all
# children.
self.cancel_scope = cancel_scope
assert self.cancel_scope is self._cancel_stack[-1]
self._children = set()
self._zombies = set()
self.monitor = _core.UnboundedQueue()
self._closed = False
@property
def children(self):
return frozenset(self._children)
@property
def zombies(self):
return frozenset(self._zombies)
def _child_finished(self, task):
self._children.remove(task)
self._zombies.add(task)
self.monitor.put_nowait(task)
def spawn(self, async_fn, *args, name=None):
return GLOBAL_RUN_CONTEXT.runner.spawn_impl(async_fn, args, self, name)
def reap(self, task):
try:
self._zombies.remove(task)
except KeyError:
raise ValueError("{} is not a zombie in this nursery".format(task))
def reap_and_unwrap(self, task):
self.reap(task)
return task.result.unwrap()
async def _clean_up(self, pending_exc):
cancelled_children = False
exceptions = []
if pending_exc is not None:
exceptions.append(pending_exc)
# Careful - the logic in this loop is deceptively subtle, because of
# all the different possible states that we have to handle. (Entering
# with/out an error, with/out unreaped zombies, with/out children
# living, with/out an error that occurs after we enter, ...)
with open_cancel_scope() as clean_up_scope:
if not self._children and not self._zombies:
try:
await _core.yield_briefly()
except BaseException as exc:
exceptions.append(exc)
while self._children or self._zombies:
# First, reap any zombies. They may or may not still be in the
# monitor queue, and they may or may not trigger cancellation
# of remaining tasks, so we have to check first before
# blocking on the monitor queue.
for task in list(self._zombies):
if type(task.result) is Error:
exceptions.append(task.result.error)
self.reap(task)
if exceptions and not cancelled_children:
self.cancel_scope.cancel()
clean_up_scope.shield = True
cancelled_children = True
if self.children:
try:
# We ignore the return value here, and will pick up
# the actual tasks from the zombies set after looping
# around. (E.g. it's possible there are tasks in the
# queue that were already reaped.)
await self.monitor.get_batch()
except (Cancelled, KeyboardInterrupt) as exc:
exceptions.append(exc)
self._closed = True
if exceptions:
mexc = MultiError(exceptions)
if (pending_exc
and mexc.__cause__ is None
and mexc.__context__ is None):
# pending_exc is *part* of this MultiError, so it doesn't
# make sense to also have it as
# __context__. Unfortunately, we can't stop Python from
# setting it as __context__, but we can at least suppress
# it from being printed.
raise mexc from None
else:
# There could potentially be a genuine __context__ that
# should be attached, e.g.:
#
# try:
# ...
# except:
# with open_nursery():
# ...
#
# Or, if len(exceptions) == 1, this could be a regular
# exception that already has __cause__ or __context__
# set.
raise mexc
def __del__(self):
assert not self.children and not self.zombies
################################################################
# Task and friends
################################################################
@attr.s(slots=True, cmp=False, hash=False, repr=False)
class Task:
_nursery = attr.ib()
coro = attr.ib()
_runner = attr.ib()
name = attr.ib()
result = attr.ib(default=None)
# tasks start out unscheduled, and unscheduled tasks have None here
_next_send = attr.ib(default=None)
_abort_func = attr.ib(default=None)
# XX maybe these should be exposed as part of a statistics() method?
_cancel_points = attr.ib(default=0)
_schedule_points = attr.ib(default=0)
def __repr__(self):
return ("<Task {!r} at {:#x}>".format(self.name, id(self)))
# For debugging and visualization:
@property
def parent_task(self):
"""This task's parent task (or None if this is the "init" task).
Example use case: drawing a visualization of the task tree.
"""
if self._nursery is None:
return None
else:
return self._nursery._parent
################
# Monitoring task exit
################
_monitors = attr.ib(default=attr.Factory(set))
def add_monitor(self, queue):
"""Register to be notified when this task exits.
Args:
queue (UnboundedQueue): An :class:`UnboundedQueue` object that this
task object will be put into when it exits.
Raises:
TypeError: if ``queue`` is not a :class:`UnboundedQueue`
ValueError: if ``queue`` is already registered with this task
"""
# Rationale: (a) don't particularly want to create a
# callback-in-disguise API by allowing people to stick in some
# arbitrary object with a put_nowait method, (b) don't want to have to
# figure out how to deal with errors from a user-provided object; if
# UnboundedQueue.put_nowait raises then that's legitimately a bug in
# trio so raising InternalError is justified.
if type(queue) is not _core.UnboundedQueue:
raise TypeError("monitor must be an UnboundedQueue object")
if queue in self._monitors:
raise ValueError("can't add same monitor twice")
if self.result is not None:
queue.put_nowait(self)
else:
self._monitors.add(queue)
def discard_monitor(self, queue):
"""Unregister the given queue from being notified about this task
exiting.
This operation always succeeds, regardless of whether ``queue`` was
previously registered.
Args:
queue (UnboundedQueue): The queue that should no longer recieve
notification.
"""
self._monitors.discard(queue)
async def wait(self):
"""Wait for this task to exit.
"""
q = _core.UnboundedQueue()
self.add_monitor(q)
try:
await q.get_batch()
finally:
self.discard_monitor(q)
################
# Cancellation
################
_cancel_stack = attr.ib(default=attr.Factory(list), repr=False)
def _pending_cancel_scope(self):
# Return the outermost exception that is is not outside a shield.
pending_scope = None
for scope in self._cancel_stack:
# Check shield before _exc, because shield should not block
# processing of *this* scope's exception
if scope.shield:
pending_scope = None
if pending_scope is None and scope.cancel_called:
pending_scope = scope
return pending_scope
def _attempt_abort(self, raise_cancel):
# Either the abort succeeds, in which case we will reschedule the
# task, or else it fails, in which case it will worry about
# rescheduling itself (hopefully eventually calling reraise to raise
# the given exception, but not necessarily).
success = self._abort_func(raise_cancel)
if type(success) is not _core.Abort:
raise TrioInternalError("abort function must return Abort enum")
# We only attempt to abort once per blocking call, regardless of
# whether we succeeded or failed.
self._abort_func = None
if success is Abort.SUCCEEDED:
self._runner.reschedule(self, Result.capture(raise_cancel))
def _attempt_delivery_of_any_pending_cancel(self):
if self._abort_func is None:
return
pending_scope = self._pending_cancel_scope()
if pending_scope is None:
return
exc = pending_scope._make_exc(self)
def raise_cancel():
raise exc
self._attempt_abort(raise_cancel)
def _attempt_delivery_of_pending_ki(self):
assert self._runner.ki_pending
if self._abort_func is None:
return
def raise_cancel():
self._runner.ki_pending = False
raise KeyboardInterrupt
self._attempt_abort(raise_cancel)
################################################################
# The central Runner object
################################################################
@attr.s(frozen=True)
class _RunStatistics:
tasks_living = attr.ib()
tasks_runnable = attr.ib()
seconds_to_next_deadline = attr.ib()
io_statistics = attr.ib()
call_soon_queue_size = attr.ib()
@attr.s(cmp=False, hash=False)
class Runner:
clock = attr.ib()
instruments = attr.ib()
io_manager = attr.ib()
runq = attr.ib(default=attr.Factory(deque))
tasks = attr.ib(default=attr.Factory(set))
r = attr.ib(default=attr.Factory(random.Random))
# {(deadline, id(CancelScope)): CancelScope}
# only contains scopes with non-infinite deadlines that are currently
# attached to at least one task
deadlines = attr.ib(default=attr.Factory(SortedDict))
init_task = attr.ib(default=None)
main_task = attr.ib(default=None)
system_nursery = attr.ib(default=None)
def close(self):
self.io_manager.close()
self.call_soon_wakeup.close()
self.instrument("after_run")
# Methods marked with @_public get converted into functions exported by
# trio.hazmat:
@_public
def current_statistics(self):
"""Returns an object containing run-loop-level debugging information.
Currently the following fields are defined:
* ``tasks_living`` (int): The number of tasks that have been spawned
and not yet exited.
* ``tasks_runnable`` (int): The number of tasks that are currently
queued on the run queue (as opposed to blocked waiting for something
to happen).
* ``seconds_to_next_deadline`` (float): The time until the next
pending cancel scope deadline. May be negative if the deadline has
expired but we haven't yet processed cancellations. May be
:data:`~math.inf` if there are no pending deadlines.
* ``call_soon_queue_size`` (int): The number of unprocessed callbacks
queued via
:func:`trio.hazmat.current_call_soon_thread_and_signal_safe`.
* ``io_statistics`` (object): Some statistics from trio's I/O
backend. This always has an attribute ``backend`` which is a string
naming which operating-system-specific I/O backend is in use; the
other attributes vary between backends.
"""
if self.deadlines:
next_deadline, _ = self.deadlines.keys()[0]
seconds_to_next_deadline = next_deadline - self.current_time()
else:
seconds_to_next_deadline = float("inf")
return _RunStatistics(
tasks_living=len(self.tasks),
tasks_runnable=len(self.runq),
seconds_to_next_deadline=seconds_to_next_deadline,
io_statistics=self.io_manager.statistics(),
call_soon_queue_size=
len(self.call_soon_queue) + len(self.call_soon_idempotent_queue),
)
@_public
def current_time(self):
"""Returns the current time according to trio's internal clock.
Returns:
float: The current time.
Raises:
RuntimeError: if not inside a call to :func:`trio.run`.
"""
return self.clock.current_time()
@_public
def current_clock(self):
"""Returns the current :class:`~trio.abc.Clock`.
"""
return self.clock
################
# Core task handling primitives
################
@_public
@_hazmat
def reschedule(self, task, next_send=Value(None)):
"""Reschedule the given task with the given :class:`~trio.Result`.
See :func:`yield_indefinitely` for the gory details.
There must be exactly one call to :func:`reschedule` for every call to
:func:`yield_indefinitely`. (And when counting, keep in mind that
returning :data:`Abort.SUCCEEDED` from an abort callback is equivalent
to calling :func:`reschedule` once.)
Args:
task (trio.Task): the task to be rescheduled. Must be blocked in a
call to :func:`yield_indefinitely`.
next_send (trio.Result): the value (or error) to return (or raise)
from :func:`yield_indefinitely`.
"""
assert task._runner is self
assert task._next_send is None
task._next_send = next_send
task._abort_func = None
self.runq.append(task)
self.instrument("task_scheduled", task)
def spawn_impl(
self, async_fn, args, nursery, name,
*, ki_protection_enabled=False):
# This sorta feels like it should be a method on nursery, except it
# has to handle nursery=None for init. And it touches the internals of
# all kinds of objects.
if nursery is not None and nursery._closed:
raise RuntimeError("Nursery is closed to new arrivals")
if nursery is None:
assert self.init_task is None
coro = async_fn(*args)
if not inspect.iscoroutine(coro):
raise TypeError("spawn expected an async function")
if name is None:
name = async_fn
if isinstance(name, functools.partial):
name = name.func
if not isinstance(name, str):
try:
name = "{}.{}".format(name.__module__, name.__qualname__)
except AttributeError:
name = repr(name)
task = Task(coro=coro, nursery=nursery, runner=self, name=name)
self.tasks.add(task)
if nursery is not None:
nursery._children.add(task)
for scope in nursery._cancel_stack:
scope._add_task(task)
coro.cr_frame.f_locals.setdefault(
LOCALS_KEY_KI_PROTECTION_ENABLED, ki_protection_enabled)
self.instrument("task_spawned", task)
# Special case: normally next_send should be a Result, but for the
# very first send we have to send a literal unboxed None.
self.reschedule(task, None)
return task
def task_exited(self, task, result):
task.result = result
while task._cancel_stack:
task._cancel_stack[-1]._remove_task(task)
self.tasks.remove(task)
if task._nursery is None:
# the init task should be the last task to exit
assert not self.tasks
else:
task._nursery._child_finished(task)
for monitor in task._monitors:
monitor.put_nowait(task)
task._monitors.clear()
self.instrument("task_exited", task)
################
# System tasks and init
################
@_public
@_hazmat
def spawn_system_task(self, async_fn, *args, name=None):
"""Spawn a "system" task.
System tasks have a few differences from regular tasks:
* They don't need an explicit nursery; instead they go into the
internal "system nursery".
* If a system task raises an exception, then it's converted into a
:exc:`~trio.TrioInternalError` and *all* tasks are cancelled. If you
write a system task, you should be careful to make sure it doesn't
crash.
* System tasks are automatically cancelled when the main task exits.
* By default, system tasks have :exc:`KeyboardInterrupt` protection
*enabled*. If you want your task to be interruptible by control-C,
then you need to use :func:`disable_ki_protection` explicitly.
Args:
async_fn: An async callable.
args: Positional arguments for ``async_fn``. If you want to pass
keyword arguments, use :func:`functools.partial`.
name: The name for this task. Only used for debugging/introspection
(e.g. ``repr(task_obj)``). If this isn't a string,
:func:`spawn_system_task` will try to make it one. A common use
case is if you're wrapping a function before spawning a new
task, you might pass the original function as the ``name=`` to
make debugging easier.
Returns:
Task: the newly spawned task
"""
async def system_task_wrapper(async_fn, args):
PASS = (Cancelled, KeyboardInterrupt, GeneratorExit,
TrioInternalError)
def excfilter(exc):
if isinstance(exc, PASS):
return exc
else:
new_exc = TrioInternalError("system task crashed")
new_exc.__cause__ = exc
return new_exc
with MultiError.catch(excfilter):
await async_fn(*args)
if name is None:
name = async_fn
return self.spawn_impl(
system_task_wrapper, (async_fn, args), self.system_nursery, name,
ki_protection_enabled=True)
async def init(self, async_fn, args):
async with open_nursery() as system_nursery:
self.system_nursery = system_nursery
self.spawn_system_task(self.call_soon_task, name="<call soon task>")
self.main_task = system_nursery.spawn(async_fn, *args)
async for task_batch in system_nursery.monitor:
for task in task_batch:
if task is self.main_task:
system_nursery.cancel_scope.cancel()
return system_nursery.reap_and_unwrap(task)
else:
system_nursery.reap_and_unwrap(task)
################
# Outside Context Problems
################
# XX factor this chunk into another file
# This used to use a queue.Queue. but that was broken, because Queues are
# implemented in Python, and not reentrant -- so it was thread-safe, but
# not signal-safe. deque is implemented in C, so each operation is atomic
# WRT threads (and this is guaranteed in the docs), AND each operation is
# atomic WRT signal delivery (signal handlers can run on either side, but
# not *during* a deque operation). dict makes similar guarantees - and on
# CPython 3.6 and PyPy, it's even ordered!
call_soon_wakeup = attr.ib(default=attr.Factory(WakeupSocketpair))
call_soon_queue = attr.ib(default=attr.Factory(deque))
call_soon_idempotent_queue = attr.ib(default=attr.Factory(dict))
call_soon_done = attr.ib(default=False)
# Must be a reentrant lock, because it's acquired from signal
# handlers. RLock is signal-safe as of cpython 3.2.
# NB that this does mean that the lock is effectively *disabled* when we
# enter from signal context. The way we use the lock this is OK though,
# because when call_soon_thread_and_signal_safe is called from a signal
# it's atomic WRT the main thread -- it just might happen at some
# inconvenient place. But if you look at the one place where the main
# thread holds the lock, it's just to make 1 assignment, so that's atomic
# WRT a signal anyway.
call_soon_lock = attr.ib(default=attr.Factory(threading.RLock))
def call_soon_thread_and_signal_safe(
self, sync_fn, *args, idempotent=False):
with self.call_soon_lock:
if self.call_soon_done:
raise RunFinishedError("run() has exited")
# We have to hold the lock all the way through here, because
# otherwise the main thread might exit *while* we're doing these
# calls, and then our queue item might not be processed, or the
# wakeup call might trigger an OSError b/c the IO manager has
# already been shut down.
if idempotent:
self.call_soon_idempotent_queue[(sync_fn, args)] = None
else:
self.call_soon_queue.append((sync_fn, args))
self.call_soon_wakeup.wakeup_thread_and_signal_safe()
@_public
@_hazmat
def current_call_soon_thread_and_signal_safe(self):
"""Returns a reference to the ``call_soon_thread_and_signal_safe``
function for the current trio run:
.. currentmodule:: None
.. function:: call_soon_thread_and_signal_safe(sync_fn, *args, idempotent=False)
Schedule a call to ``sync_fn(*args)`` to occur in the context of a
trio task. This is safe to call from the main thread, from other
threads, and from signal handlers.
The call is effectively run as part of a system task (see
:func:`~trio.hazmat.spawn_system_task`). In particular this means
that:
* :exc:`KeyboardInterrupt` protection is *enabled* by default; if
you want ``sync_fn`` to be interruptible by control-C, then you
need to use :func:`~trio.hazmat.disable_ki_protection`
explicitly.
* If ``sync_fn`` raises an exception, then it's converted into a
:exc:`~trio.TrioInternalError` and *all* tasks are cancelled. You
should be careful that ``sync_fn`` doesn't crash.
All calls with ``idempotent=False`` are processed in strict
first-in first-out order.
If ``idempotent=True``, then ``sync_fn`` and ``args`` must be
hashable, and trio will make a best-effort attempt to discard any
call submission which is equal to an already-pending call. Trio
will make an attempt to process these in first-in first-out order,
but no guarantees. (Currently processing is FIFO on CPython 3.6 and
PyPy, but not CPython 3.5.)
Any ordering guarantees apply separately to ``idempotent=False``
and ``idempotent=True`` calls; there's no rule for how calls in the
different categories are ordered with respect to each other.
:raises trio.RunFinishedError:
if the associated call to :func:`trio.run`
has already exited. (Any call that *doesn't* raise this error
is guaranteed to be fully processed before :func:`trio.run`
exits.)
.. currentmodule:: trio.hazmat
"""
return self.call_soon_thread_and_signal_safe
async def call_soon_task(self):
assert currently_ki_protected()
# RLock has two implementations: a signal-safe version in _thread, and
# and signal-UNsafe version in threading. We need the signal safe
# version. Python 3.2 and later should always use this anyway, but,
# since the symptoms if this goes wrong are just "weird rare
# deadlocks", then let's make a little check.
# See:
# https://bugs.python.org/issue13697#msg237140
assert self.call_soon_lock.__class__.__module__ == "_thread"
def run_cb(job):
# We run this with KI protection enabled; it's the callbacks
# job to disable it if it wants it disabled. Exceptions are
# treated like system task exceptions (i.e., converted into
# TrioInternalError and cause everything to shut down).
sync_fn, args = job
try:
sync_fn(*args)
except BaseException as exc:
async def kill_everything(exc):
raise exc
self.spawn_system_task(kill_everything, exc)
return True
# This has to be carefully written to be safe in the face of new items
# being queued while we iterate, and to do a bounded amount of work on
# each pass:
def run_all_bounded():
for _ in range(len(self.call_soon_queue)):
run_cb(self.call_soon_queue.popleft())
for job in list(self.call_soon_idempotent_queue):
del self.call_soon_idempotent_queue[job]
run_cb(job)
try:
while True:
run_all_bounded()
if (not self.call_soon_queue
and not self.call_soon_idempotent_queue):
await self.call_soon_wakeup.wait_woken()
else:
await yield_briefly()
except Cancelled:
# Keep the work done with this lock held as minimal as possible,
# because it doesn't protect us against concurrent signal delivery
# (see the comment above). Notice that this could would still be
# correct if written like:
# self.call_soon_done = True
# with self.call_soon_lock:
# pass
# because all we want is to force call_soon_thread_and_signal_safe
# to either be completely before or completely after the write to
# call_soon_done. That's why we don't need the lock to protect
# against signal handlers.
with self.call_soon_lock:
self.call_soon_done = True
# No more jobs will be submitted, so just clear out any residual
# ones:
run_all_bounded()
assert not self.call_soon_queue
assert not self.call_soon_idempotent_queue
################
# KI handling
################
ki_pending = attr.ib(default=False)
# This gets called from signal context
def deliver_ki(self):
self.ki_pending = True
try:
self.call_soon_thread_and_signal_safe(self._deliver_ki_cb)
except RunFinishedError:
pass
def _deliver_ki_cb(self):
if not self.ki_pending:
return
# Can't happen because main_task and call_soon_task are created at the
# same time -- so even if KI arrives before main_task is created, we
# won't get here until afterwards.
assert self.main_task is not None
if self.main_task.result is not None:
# We're already in the process of exiting -- leave ki_pending set
# and we'll check it again on our way out of run().
return
self.main_task._attempt_delivery_of_pending_ki()
################
# Quiescing
################
waiting_for_idle = attr.ib(default=attr.Factory(SortedDict))
@_public
@_hazmat
async def wait_all_tasks_blocked(self, cushion=0.0):
"""Block until there are no runnable tasks.
This is useful in testing code when you want to give other tasks a
chance to "settle down". The calling task is blocked, and doesn't wake
up until all other tasks are also blocked for at least ``cushion``
seconds. (Setting a non-zero ``cushion`` is intended to handle cases
like two tasks talking to each other over a local socket, where we
want to ignore the potential brief moment between a send and receive
when all tasks are blocked.)
Note that ``cushion`` is measured in *real* time, not the trio clock
time.
If there are multiple tasks blocked in :func:`wait_all_tasks_blocked`,
then the one with the shortest ``cushion`` is the one woken (and the
this task becoming unblocked resets the timers for the remaining
tasks). If there are multiple tasks that have exactly the same
``cushion``, then all are woken.
You should also consider :class:`trio.testing.Sequencer`, which
provides a more explicit way to control execution ordering within a
test, and will often produce more readable tests.
Example:
Here's an example of one way to test that trio's locks are fair: we
take the lock in the parent, spawn a child, wait for the child to be
blocked waiting for the lock (!), and then check that we can't
release and immediately re-acquire the lock::
async def lock_taker(lock):
await lock.acquire()
lock.release()
async def test_lock_fairness():
lock = trio.Lock()
await lock.acquire()
async with trio.open_nursery() as nursery:
nursery.spawn(lock_taker, lock)
# child hasn't run yet
assert not lock.locked()
await trio.testing.wait_all_tasks_blocked()
# now the child has run
assert lock.locked()
lock.release()
try:
# The child has a prior claim, so we can't have it
lock.acquire_nowait()
except trio.WouldBlock:
print("PASS")
else:
print("FAIL")
"""
task = current_task()
key = (cushion, id(task))