-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathloop.pyx
3065 lines (2493 loc) · 102 KB
/
loop.pyx
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
# cython: language_level=3, embedsignature=True
import asyncio
cimport cython
from .includes.debug cimport UVLOOP_DEBUG
from .includes cimport uv
from .includes cimport system
from .includes.python cimport PY_VERSION_HEX, \
PyMem_RawMalloc, PyMem_RawFree, \
PyMem_RawCalloc, PyMem_RawRealloc, \
PyUnicode_EncodeFSDefault, \
PyErr_SetInterrupt, \
PyOS_AfterFork, \
_PyImport_AcquireLock, \
_PyImport_ReleaseLock, \
_Py_RestoreSignals, \
PyContext, \
PyContext_CopyCurrent, \
PyContext_Enter, \
PyContext_Exit, \
PyContextVar, \
PyContextVar_Get
from libc.stdint cimport uint64_t
from libc.string cimport memset, strerror, memcpy
from libc cimport errno
from cpython cimport PyObject
from cpython cimport PyErr_CheckSignals, PyErr_Occurred
from cpython cimport PyThread_get_thread_ident
from cpython cimport Py_INCREF, Py_DECREF, Py_XDECREF, Py_XINCREF
from cpython cimport PyObject_GetBuffer, PyBuffer_Release, PyBUF_SIMPLE, \
Py_buffer, PyBytes_AsString, PyBytes_CheckExact, \
Py_SIZE, PyBytes_AS_STRING, PyBUF_WRITABLE
from . import _noop
include "includes/consts.pxi"
include "includes/stdlib.pxi"
include "errors.pyx"
cdef:
int PY37 = PY_VERSION_HEX >= 0x03070000
int PY36 = PY_VERSION_HEX >= 0x03060000
cdef _is_sock_stream(sock_type):
if SOCK_NONBLOCK == -1:
return sock_type == uv.SOCK_STREAM
else:
# Linux's socket.type is a bitmask that can include extra info
# about socket (like SOCK_NONBLOCK bit), therefore we can't do simple
# `sock_type == socket.SOCK_STREAM`, see
# https://github.com/torvalds/linux/blob/v4.13/include/linux/net.h#L77
# for more details.
return (sock_type & 0xF) == uv.SOCK_STREAM
cdef _is_sock_dgram(sock_type):
if SOCK_NONBLOCK == -1:
return sock_type == uv.SOCK_DGRAM
else:
# Read the comment in `_is_sock_stream`.
return (sock_type & 0xF) == uv.SOCK_DGRAM
cdef isfuture(obj):
if aio_isfuture is None:
return isinstance(obj, aio_Future)
else:
return aio_isfuture(obj)
cdef inline socket_inc_io_ref(sock):
if isinstance(sock, socket_socket):
sock._io_refs += 1
cdef inline socket_dec_io_ref(sock):
if isinstance(sock, socket_socket):
sock._decref_socketios()
@cython.no_gc_clear
cdef class Loop:
def __cinit__(self):
cdef int err
# Install PyMem* memory allocators if they aren't installed yet.
__install_pymem()
# Install pthread_atfork handlers
__install_atfork()
self.uvloop = <uv.uv_loop_t*> \
PyMem_RawMalloc(sizeof(uv.uv_loop_t))
if self.uvloop is NULL:
raise MemoryError()
self.slow_callback_duration = 0.1
self._closed = 0
self._debug = 0
self._thread_is_main = 0
self._thread_id = 0
self._running = 0
self._stopping = 0
self._transports = weakref_WeakValueDictionary()
self._processes = set()
# Used to keep a reference (and hence keep the fileobj alive)
# for as long as its registered by add_reader or add_writer.
# This is how the selector module and hence asyncio behaves.
self._fd_to_reader_fileobj = {}
self._fd_to_writer_fileobj = {}
self._timers = set()
self._polls = {}
self._recv_buffer_in_use = 0
err = uv.uv_loop_init(self.uvloop)
if err < 0:
raise convert_error(err)
self.uvloop.data = <void*> self
self._init_debug_fields()
self.active_process_handler = None
self._last_error = None
self._task_factory = None
self._exception_handler = None
self._default_executor = None
self._queued_streams = set()
self._ready = col_deque()
self._ready_len = 0
self.handler_async = UVAsync.new(
self, <method_t>self._on_wake, self)
self.handler_idle = UVIdle.new(
self,
new_MethodHandle(
self, "loop._on_idle", <method_t>self._on_idle, self))
# Needed to call `UVStream._exec_write` for writes scheduled
# during `Protocol.data_received`.
self.handler_check__exec_writes = UVCheck.new(
self,
new_MethodHandle(
self, "loop._exec_queued_writes",
<method_t>self._exec_queued_writes, self))
self._signals = set()
self._ssock = self._csock = None
self._signal_handlers = {}
self._listening_signals = False
self._coroutine_debug_set = False
if hasattr(sys, 'get_asyncgen_hooks'):
# Python >= 3.6
# A weak set of all asynchronous generators that are
# being iterated by the loop.
self._asyncgens = weakref_WeakSet()
else:
self._asyncgens = None
# Set to True when `loop.shutdown_asyncgens` is called.
self._asyncgens_shutdown_called = False
self._servers = set()
def __init__(self):
self.set_debug((not sys_ignore_environment
and bool(os_environ.get('PYTHONASYNCIODEBUG'))))
def __dealloc__(self):
if self._running == 1:
raise RuntimeError('deallocating a running event loop!')
if self._closed == 0:
aio_logger.error("deallocating an open event loop")
return
PyMem_RawFree(self.uvloop)
self.uvloop = NULL
cdef _init_debug_fields(self):
self._debug_cc = bool(UVLOOP_DEBUG)
if UVLOOP_DEBUG:
self._debug_handles_current = col_Counter()
self._debug_handles_closed = col_Counter()
self._debug_handles_total = col_Counter()
else:
self._debug_handles_current = None
self._debug_handles_closed = None
self._debug_handles_total = None
self._debug_uv_handles_total = 0
self._debug_uv_handles_freed = 0
self._debug_stream_read_cb_total = 0
self._debug_stream_read_eof_total = 0
self._debug_stream_read_errors_total = 0
self._debug_stream_read_cb_errors_total = 0
self._debug_stream_read_eof_cb_errors_total = 0
self._debug_stream_shutdown_errors_total = 0
self._debug_stream_listen_errors_total = 0
self._debug_stream_write_tries = 0
self._debug_stream_write_errors_total = 0
self._debug_stream_write_ctx_total = 0
self._debug_stream_write_ctx_cnt = 0
self._debug_stream_write_cb_errors_total = 0
self._debug_cb_handles_total = 0
self._debug_cb_handles_count = 0
self._debug_cb_timer_handles_total = 0
self._debug_cb_timer_handles_count = 0
self._poll_read_events_total = 0
self._poll_read_cb_errors_total = 0
self._poll_write_events_total = 0
self._poll_write_cb_errors_total = 0
self._sock_try_write_total = 0
self._debug_exception_handler_cnt = 0
cdef _setup_signals(self):
if self._listening_signals:
return
self._ssock, self._csock = socket_socketpair()
self._ssock.setblocking(False)
self._csock.setblocking(False)
try:
_set_signal_wakeup_fd(self._csock.fileno())
except (OSError, ValueError):
# Not the main thread
self._ssock.close()
self._csock.close()
self._ssock = self._csock = None
return
self._listening_signals = True
cdef _recv_signals_start(self):
if self._ssock is None:
self._setup_signals()
if self._ssock is None:
# Not the main thread.
return
self._add_reader(
self._ssock,
new_MethodHandle(
self,
"Loop._read_from_self",
<method_t>self._read_from_self,
self))
cdef _recv_signals_stop(self):
if self._ssock is None:
return
self._remove_reader(self._ssock)
cdef _shutdown_signals(self):
if not self._listening_signals:
return
for sig in list(self._signal_handlers):
self.remove_signal_handler(sig)
if not self._listening_signals:
# `remove_signal_handler` will call `_shutdown_signals` when
# removing last signal handler.
return
try:
signal_set_wakeup_fd(-1)
except (ValueError, OSError) as exc:
aio_logger.info('set_wakeup_fd(-1) failed: %s', exc)
self._remove_reader(self._ssock)
self._ssock.close()
self._csock.close()
self._ssock = None
self._csock = None
self._listening_signals = False
def __sighandler(self, signum, frame):
self._signals.add(signum)
cdef inline _ceval_process_signals(self):
# Invoke CPython eval loop to let process signals.
PyErr_CheckSignals()
# Calling a pure-Python function will invoke
# _PyEval_EvalFrameDefault which will process
# pending signal callbacks.
_noop.noop() # Might raise ^C
cdef _read_from_self(self):
cdef bytes sigdata
sigdata = b''
while True:
try:
data = self._ssock.recv(65536)
if not data:
break
sigdata += data
except InterruptedError:
continue
except BlockingIOError:
break
if sigdata:
self._invoke_signals(sigdata)
cdef _invoke_signals(self, bytes data):
cdef set sigs
self._ceval_process_signals()
sigs = self._signals.copy()
self._signals.clear()
for signum in data:
if not signum:
# ignore null bytes written by set_wakeup_fd()
continue
sigs.discard(signum)
self._handle_signal(signum)
for signum in sigs:
# Since not all signals are registered by add_signal_handler()
# (for instance, we use the default SIGINT handler) not all
# signals will trigger loop.__sighandler() callback. Therefore
# we combine two datasources: one is self-pipe, one is data
# from __sighandler; this ensures that signals shouldn't be
# lost even if set_wakeup_fd() couldn't write to the self-pipe.
self._handle_signal(signum)
cdef _handle_signal(self, sig):
cdef Handle handle
try:
handle = <Handle>(self._signal_handlers[sig])
except KeyError:
handle = None
if handle is None:
self._ceval_process_signals()
return
if handle._cancelled:
self.remove_signal_handler(sig) # Remove it properly.
else:
self._call_soon_handle(handle)
self.handler_async.send()
cdef _on_wake(self):
if (self._ready_len > 0 or self._stopping) \
and not self.handler_idle.running:
self.handler_idle.start()
cdef _on_idle(self):
cdef:
int i, ntodo
object popleft = self._ready.popleft
Handle handler
ntodo = len(self._ready)
if self._debug:
for i from 0 <= i < ntodo:
handler = <Handle> popleft()
if handler._cancelled == 0:
try:
started = time_monotonic()
handler._run()
except BaseException as ex:
self._stop(ex)
return
else:
delta = time_monotonic() - started
if delta > self.slow_callback_duration:
aio_logger.warning(
'Executing %s took %.3f seconds',
handler._format_handle(), delta)
else:
for i from 0 <= i < ntodo:
handler = <Handle> popleft()
if handler._cancelled == 0:
try:
handler._run()
except BaseException as ex:
self._stop(ex)
return
if len(self._queued_streams):
self._exec_queued_writes()
self._ready_len = len(self._ready)
if self._ready_len == 0 and self.handler_idle.running:
self.handler_idle.stop()
if self._stopping:
uv.uv_stop(self.uvloop) # void
cdef _stop(self, exc):
if exc is not None:
self._last_error = exc
if self._stopping == 1:
return
self._stopping = 1
if not self.handler_idle.running:
self.handler_idle.start()
cdef __run(self, uv.uv_run_mode mode):
# Although every UVHandle holds a reference to the loop,
# we want to do everything to ensure that the loop will
# never deallocate during the run -- so we do some
# manual refs management.
Py_INCREF(self)
with nogil:
err = uv.uv_run(self.uvloop, mode)
Py_DECREF(self)
if err < 0:
raise convert_error(err)
cdef _run(self, uv.uv_run_mode mode):
cdef int err
if self._closed == 1:
raise RuntimeError('unable to start the loop; it was closed')
if self._running == 1:
raise RuntimeError('this event loop is already running.')
if (aio_get_running_loop is not None and
aio_get_running_loop() is not None):
raise RuntimeError(
'Cannot run the event loop while another loop is running')
# reset _last_error
self._last_error = None
self._thread_id = PyThread_get_thread_ident()
self._thread_is_main = MAIN_THREAD_ID == self._thread_id
self._running = 1
self.handler_check__exec_writes.start()
self.handler_idle.start()
self._recv_signals_start()
if aio_set_running_loop is not None:
aio_set_running_loop(self)
try:
self.__run(mode)
finally:
if aio_set_running_loop is not None:
aio_set_running_loop(None)
self._recv_signals_stop()
self.handler_check__exec_writes.stop()
self.handler_idle.stop()
self._thread_is_main = 0
self._thread_id = 0
self._running = 0
self._stopping = 0
if self._last_error is not None:
# The loop was stopped with an error with 'loop._stop(error)' call
raise self._last_error
cdef _close(self):
cdef int err
if self._running == 1:
raise RuntimeError("Cannot close a running event loop")
if self._closed == 1:
return
self._closed = 1
for cb_handle in self._ready:
cb_handle.cancel()
self._ready.clear()
self._ready_len = 0
if self._polls:
for poll_handle in self._polls.values():
(<UVHandle>poll_handle)._close()
self._polls.clear()
if self._timers:
for timer_cbhandle in tuple(self._timers):
timer_cbhandle.cancel()
# Close all remaining handles
self.handler_async._close()
self.handler_idle._close()
self.handler_check__exec_writes._close()
__close_all_handles(self)
self._shutdown_signals()
# During this run there should be no open handles,
# so it should finish right away
self.__run(uv.UV_RUN_DEFAULT)
if self._fd_to_writer_fileobj:
for fileobj in self._fd_to_writer_fileobj.values():
socket_dec_io_ref(fileobj)
self._fd_to_writer_fileobj.clear()
if self._fd_to_reader_fileobj:
for fileobj in self._fd_to_reader_fileobj.values():
socket_dec_io_ref(fileobj)
self._fd_to_reader_fileobj.clear()
if self._timers:
raise RuntimeError(
"new timers were queued during loop closing: {}"
.format(self._timers))
if self._polls:
raise RuntimeError(
"new poll handles were queued during loop closing: {}"
.format(self._polls))
if self._ready:
raise RuntimeError(
"new callbacks were queued during loop closing: {}"
.format(self._ready))
err = uv.uv_loop_close(self.uvloop)
if err < 0:
raise convert_error(err)
self.handler_async = None
self.handler_idle = None
self.handler_check__exec_writes = None
executor = self._default_executor
if executor is not None:
self._default_executor = None
executor.shutdown(wait=False)
cdef uint64_t _time(self):
# asyncio doesn't have a time cache, neither should uvloop.
uv.uv_update_time(self.uvloop) # void
return uv.uv_now(self.uvloop)
cdef inline _queue_write(self, UVStream stream):
self._queued_streams.add(stream)
if not self.handler_check__exec_writes.running:
self.handler_check__exec_writes.start()
cdef _exec_queued_writes(self):
if len(self._queued_streams) == 0:
if self.handler_check__exec_writes.running:
self.handler_check__exec_writes.stop()
return
cdef:
UVStream stream
int queued_len
if UVLOOP_DEBUG:
queued_len = len(self._queued_streams)
for pystream in self._queued_streams:
stream = <UVStream>pystream
stream._exec_write()
if UVLOOP_DEBUG:
if len(self._queued_streams) != queued_len:
raise RuntimeError(
'loop._queued_streams are not empty after '
'_exec_queued_writes')
self._queued_streams.clear()
if self.handler_check__exec_writes.running:
self.handler_check__exec_writes.stop()
cdef inline _call_soon(self, object callback, object args, object context):
cdef Handle handle
handle = new_Handle(self, callback, args, context)
self._call_soon_handle(handle)
return handle
cdef inline _call_soon_handle(self, Handle handle):
self._check_closed()
self._ready.append(handle)
self._ready_len += 1;
if not self.handler_idle.running:
self.handler_idle.start()
cdef _call_later(self, uint64_t delay, object callback, object args,
object context):
return TimerHandle(self, callback, args, delay, context)
cdef void _handle_exception(self, object ex):
if isinstance(ex, Exception):
self.call_exception_handler({'exception': ex})
else:
# BaseException
self._last_error = ex
# Exit ASAP
self._stop(None)
cdef inline _check_signal(self, sig):
if not isinstance(sig, int):
raise TypeError('sig must be an int, not {!r}'.format(sig))
if not (1 <= sig < signal_NSIG):
raise ValueError(
'sig {} out of range(1, {})'.format(sig, signal_NSIG))
cdef inline _check_closed(self):
if self._closed == 1:
raise RuntimeError('Event loop is closed')
cdef inline _check_thread(self):
if self._thread_id == 0:
return
cdef long thread_id = PyThread_get_thread_ident()
if thread_id != self._thread_id:
raise RuntimeError(
"Non-thread-safe operation invoked on an event loop other "
"than the current one")
cdef inline _new_future(self):
return aio_Future(loop=self)
cdef _track_transport(self, UVBaseTransport transport):
self._transports[transport._fileno()] = transport
cdef _track_process(self, UVProcess proc):
self._processes.add(proc)
cdef _untrack_process(self, UVProcess proc):
self._processes.discard(proc)
cdef _fileobj_to_fd(self, fileobj):
"""Return a file descriptor from a file object.
Parameters:
fileobj -- file object or file descriptor
Returns:
corresponding file descriptor
Raises:
ValueError if the object is invalid
"""
# Copy of the `selectors._fileobj_to_fd()` function.
if isinstance(fileobj, int):
fd = fileobj
else:
try:
fd = int(fileobj.fileno())
except (AttributeError, TypeError, ValueError):
raise ValueError("Invalid file object: "
"{!r}".format(fileobj)) from None
if fd < 0:
raise ValueError("Invalid file descriptor: {}".format(fd))
return fd
cdef _ensure_fd_no_transport(self, fd):
cdef UVBaseTransport tr
try:
tr = <UVBaseTransport>(self._transports[fd])
except KeyError:
pass
else:
if tr._is_alive():
raise RuntimeError(
'File descriptor {!r} is used by transport {!r}'.format(
fd, tr))
cdef _add_reader(self, fileobj, Handle handle):
cdef:
UVPoll poll
self._check_closed()
fd = self._fileobj_to_fd(fileobj)
self._ensure_fd_no_transport(fd)
try:
poll = <UVPoll>(self._polls[fd])
except KeyError:
poll = UVPoll.new(self, fd)
self._polls[fd] = poll
poll.start_reading(handle)
old_fileobj = self._fd_to_reader_fileobj.pop(fd, None)
if old_fileobj is not None:
socket_dec_io_ref(old_fileobj)
self._fd_to_reader_fileobj[fd] = fileobj
socket_inc_io_ref(fileobj)
cdef _remove_reader(self, fileobj):
cdef:
UVPoll poll
fd = self._fileobj_to_fd(fileobj)
self._ensure_fd_no_transport(fd)
mapped_fileobj = self._fd_to_reader_fileobj.pop(fd, None)
if mapped_fileobj is not None:
socket_dec_io_ref(mapped_fileobj)
if self._closed == 1:
return False
try:
poll = <UVPoll>(self._polls[fd])
except KeyError:
return False
result = poll.stop_reading()
if not poll.is_active():
del self._polls[fd]
poll._close()
return result
cdef _add_writer(self, fileobj, Handle handle):
cdef:
UVPoll poll
self._check_closed()
fd = self._fileobj_to_fd(fileobj)
self._ensure_fd_no_transport(fd)
try:
poll = <UVPoll>(self._polls[fd])
except KeyError:
poll = UVPoll.new(self, fd)
self._polls[fd] = poll
poll.start_writing(handle)
old_fileobj = self._fd_to_writer_fileobj.pop(fd, None)
if old_fileobj is not None:
socket_dec_io_ref(old_fileobj)
self._fd_to_writer_fileobj[fd] = fileobj
socket_inc_io_ref(fileobj)
cdef _remove_writer(self, fileobj):
cdef:
UVPoll poll
fd = self._fileobj_to_fd(fileobj)
self._ensure_fd_no_transport(fd)
mapped_fileobj = self._fd_to_writer_fileobj.pop(fd, None)
if mapped_fileobj is not None:
socket_dec_io_ref(mapped_fileobj)
if self._closed == 1:
return False
try:
poll = <UVPoll>(self._polls[fd])
except KeyError:
return False
result = poll.stop_writing()
if not poll.is_active():
del self._polls[fd]
poll._close()
return result
cdef _getaddrinfo(self, object host, object port,
int family, int type,
int proto, int flags,
int unpack):
if isinstance(port, str):
port = port.encode()
elif isinstance(port, int):
port = str(port).encode()
if port is not None and not isinstance(port, bytes):
raise TypeError('port must be a str, bytes or int')
if isinstance(host, str):
host = host.encode('idna')
if host is not None:
if not isinstance(host, bytes):
raise TypeError('host must be a str or bytes')
fut = self._new_future()
def callback(result):
if AddrInfo.isinstance(result):
try:
if unpack == 0:
data = result
else:
data = (<AddrInfo>result).unpack()
except Exception as ex:
if not fut.cancelled():
fut.set_exception(ex)
else:
if not fut.cancelled():
fut.set_result(data)
else:
if not fut.cancelled():
fut.set_exception(result)
traced_context = __traced_context()
if traced_context:
traced_context.current_span().finish()
traced_context = __traced_context()
if traced_context:
traced_context.start_span(
"getaddrinfo",
tags={'host': host, 'port': port}
)
AddrInfoRequest(self, host, port, family, type, proto, flags, callback)
return fut
cdef _getnameinfo(self, system.sockaddr *addr, int flags):
cdef NameInfoRequest nr
fut = self._new_future()
def callback(result):
if isinstance(result, tuple):
fut.set_result(result)
else:
fut.set_exception(result)
nr = NameInfoRequest(self, callback)
nr.query(addr, flags)
return fut
cdef _new_reader_future(self, sock):
def _on_cancel(fut):
# Check if the future was cancelled and if the socket
# is still open, i.e.
#
# loop.remove_reader(sock)
# sock.close()
# fut.cancel()
#
# wasn't called by the user.
if fut.cancelled() and sock.fileno() != -1:
self._remove_reader(sock)
fut = self._new_future()
fut.add_done_callback(_on_cancel)
return fut
cdef _new_writer_future(self, sock):
def _on_cancel(fut):
if fut.cancelled() and sock.fileno() != -1:
self._remove_writer(sock)
fut = self._new_future()
fut.add_done_callback(_on_cancel)
return fut
cdef _sock_recv(self, fut, sock, n):
cdef:
Handle handle
try:
data = sock.recv(n)
except (BlockingIOError, InterruptedError):
# No need to re-add the reader, let's just wait until
# the poll handler calls this callback again.
pass
except Exception as exc:
fut.set_exception(exc)
self._remove_reader(sock)
else:
fut.set_result(data)
self._remove_reader(sock)
cdef _sock_recv_into(self, fut, sock, buf):
cdef:
Handle handle
try:
data = sock.recv_into(buf)
except (BlockingIOError, InterruptedError):
# No need to re-add the reader, let's just wait until
# the poll handler calls this callback again.
pass
except Exception as exc:
fut.set_exception(exc)
self._remove_reader(sock)
else:
fut.set_result(data)
self._remove_reader(sock)
cdef _sock_sendall(self, fut, sock, data):
cdef:
Handle handle
int n
try:
n = sock.send(data)
except (BlockingIOError, InterruptedError):
# Try next time.
return
except Exception as exc:
fut.set_exception(exc)
self._remove_writer(sock)
return
self._remove_writer(sock)
if n == len(data):
fut.set_result(None)
else:
if n:
if not isinstance(data, memoryview):
data = memoryview(data)
data = data[n:]
handle = new_MethodHandle3(
self,
"Loop._sock_sendall",
<method3_t>self._sock_sendall,
self,
fut, sock, data)
self._add_writer(sock, handle)
cdef _sock_accept(self, fut, sock):
cdef:
Handle handle
try:
conn, address = sock.accept()
conn.setblocking(False)
except (BlockingIOError, InterruptedError):
# There is an active reader for _sock_accept, so
# do nothing, it will be called again.
pass
except Exception as exc:
fut.set_exception(exc)
self._remove_reader(sock)
else:
fut.set_result((conn, address))
self._remove_reader(sock)
cdef _sock_connect(self, sock, address):
cdef:
Handle handle
try:
sock.connect(address)
except (BlockingIOError, InterruptedError):
pass
else:
return
fut = self._new_future()
fut.add_done_callback(lambda fut: self._remove_writer(sock))
handle = new_MethodHandle3(
self,
"Loop._sock_connect",
<method3_t>self._sock_connect_cb,
self,
fut, sock, address)
self._add_writer(sock, handle)
return fut
cdef _sock_connect_cb(self, fut, sock, address):
if fut.cancelled():