3 \@sddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlmZddlmZddlmZddlmZddlmZddlmZdd lmZd gZd Zd ZeeefZe ed Z!d(Z"ddZ#ddZ$ddZ%ddZ&ddZ'ddZ(dej)dddddZ*e edrNd d!Z+nd"d!Z+d#d$Z,Gd%d&d&ej-Z.Gd'd d ej/Z0dS))N)compat) coroutines)events)futures)tasks) coroutine)logger BaseEventLoopdg?AF_INET6icCs0|j}tt|ddtjr$t|jSt|SdS)N__self__)Z _callback isinstancegetattrrTaskreprrstr)handlecbr+/usr/lib64/python3.6/asyncio/base_events.py_format_handle?s rcCs(|tjkrdS|tjkrdSt|SdS)Nzz) subprocessPIPESTDOUTr)fdrrr _format_pipeHs   rc CsLttdstdn4y|jtjtjdWntk rFtdYnXdS)N SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)hasattrsocket ValueError setsockopt SOL_SOCKETrOSError)sockrrr_set_reuseportQs   r&cCs&ttdr|d@tjkS|tjkSdS)N SOCK_NONBLOCK)rr SOCK_STREAM) sock_typerrr_is_stream_socket\s r+cCs&ttdr|d@tjkS|tjkSdS)Nr'r()rr SOCK_DGRAM)r*rrr_is_dgram_sockeths r-cCsvttdsdS|dtjtjhks(|dkr,dSt|rt|tr|dkrd}n&y t |}Wnt t fk rdSX|tj krtj g}tr|jtjn|g}t|tr|jd}d|krdSxp|D]h}yJtj||tr@|tjkr@|||d||ddffS|||d||ffSWntk rjYnXqWdS)N inet_ptonrZidna%)rr IPPROTO_TCPZ IPPROTO_UDPr+r-rbytesrint TypeErrorr! AF_UNSPECAF_INET _HAS_IPv6appendr decoder.r$)hostportfamilytypeprotoZafsafrrr _ipaddr_infopsL         rA)r=r>r?flagsc CsZ|dd\}}t|||||}|dk r@|j} | j|g| S|j||||||dSdS)N)r=r>r?rB)rA create_future set_result getaddrinfo) addressr=r>r?rBloopr;r<infofutrrr_ensure_resolveds  rK TCP_NODELAYcCs>|jtjtjhkr:t|jr:|jtjkr:|jtjtj ddS)Nr) r=r r7r r+r>r?r2r"rL)r%rrr _set_nodelays  rMcCsdS)Nr)r%rrrrMscCs.|j}t|tr t|t r dS|jjdS)N)Z _exceptionr BaseException Exception_loopstop)rJexcrrr_run_until_complete_cbs   rSc@sHeZdZddZddZddZddZd d Zd d Ze d dZ dS)ServercCs||_||_d|_g|_dS)Nr)rPsockets _active_count_waiters)selfrHrUrrr__init__szServer.__init__cCsd|jj|jfS)Nz<%s sockets=%r>) __class____name__rU)rXrrr__repr__szServer.__repr__cCs|jd7_dS)Nr)rV)rXrrr_attachszServer._attachcCs.|jd8_|jdkr*|jdkr*|jdS)Nrr)rVrU_wakeup)rXrrr_detachszServer._detachcCsH|j}|dkrdSd|_x|D]}|jj|qW|jdkrD|jdS)Nr)rUrPZ _stop_servingrVr^)rXrUr%rrrcloses  z Server.closecCs0|j}d|_x|D]}|js|j|qWdS)N)rWdonerE)rXwaiterswaiterrrrr^s  zServer._wakeupccs<|jdks|jdkrdS|jj}|jj||EdHdS)N)rUrWrPrDr9)rXrcrrr wait_closeds   zServer.wait_closedN) r[ __module__ __qualname__rYr\r]r_r`r^rrdrrrrrTs rTc @seZdZddZddZddZddZd d Zd d Zdd d dddZ ddd d d dddZ dddZ dddZ dddZ edddZddZdd Zd!d"Zd#d$Zd%d&Zed'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zejrd3d4Zd5d6Zd7d8Zd9d:Z d;d<Z!d=d>Z"d?d@Z#dAdBZ$dCdDZ%dEdFZ&dGdHZ'dIdJZ(dKdLZ)dMdMdMdMdNdOdPZ*ddQdRZ+edd dMdMdMd d d dSdTdUZ,eddVdWZ-eddMdMdMd d d d dXdYdZZ.ed[d\Z/ede0j1e0j2d d]d d d d^d_d`Z3ed dadbdcZ4edddeZ5edfdgZ6dhdiZ7ee8j9e8j9e8j9ddjdMdkdldmZ:ee8j9e8j9e8j9dddMdkdndoZ;dpdqZdvdwZ?dxdyZ@dzd{ZAd|d}ZBd~dZCddZDddZEddZFd S)r cCsd|_d|_d|_tj|_g|_d|_d|_d|_ t j dj |_ d|_|jtjj odttjjdd|_d|_d|_d|_ttdrtj|_nd|_d|_dS)NrF monotonicZPYTHONASYNCIODEBUGg?get_asyncgen_hooks) _timer_cancelled_count_closed _stopping collectionsdeque_ready _scheduled_default_executorZ _internal_fds _thread_idtimeZget_clock_infoZ resolution_clock_resolution_exception_handler set_debugsysrBignore_environmentboolosenvirongetslow_callback_duration_current_handle _task_factory_coroutine_wrapper_setrweakrefWeakSet _asyncgens_asyncgens_shutdown_called)rXrrrrYs(   zBaseEventLoop.__init__cCs d|jj|j|j|jfS)Nz"<%s running=%s closed=%s debug=%s>)rZr[ is_running is_closed get_debug)rXrrrr\ s zBaseEventLoop.__repr__cCs tj|dS)N)rH)rZFuture)rXrrrrD%szBaseEventLoop.create_futurecCs@|j|jdkr0tj||d}|jr<|jd=n |j||}|S)N)rHr) _check_closedr~rr_source_traceback)rXcoroZtaskrrr create_task)s   zBaseEventLoop.create_taskcCs$|dk rt| rtd||_dS)Nz'task factory must be a callable or None)callabler5r~)rXfactoryrrrset_task_factory7s zBaseEventLoop.set_task_factorycCs|jS)N)r~)rXrrrget_task_factoryEszBaseEventLoop.get_task_factoryN)extraservercCstdS)N)NotImplementedError)rXr%protocolrcrrrrr_make_socket_transportIsz$BaseEventLoop._make_socket_transportF) server_sideserver_hostnamerrc CstdS)N)r) rXZrawsockr sslcontextrcrrrrrrr_make_ssl_transportNsz!BaseEventLoop._make_ssl_transportcCstdS)N)r)rXr%rrGrcrrrr_make_datagram_transportTsz&BaseEventLoop._make_datagram_transportcCstdS)N)r)rXpiperrcrrrr_make_read_pipe_transportYsz'BaseEventLoop._make_read_pipe_transportcCstdS)N)r)rXrrrcrrrr_make_write_pipe_transport^sz(BaseEventLoop._make_write_pipe_transportc KstdS)N)r) rXrargsshellstdinstdoutstderrbufsizerkwargsrrr_make_subprocess_transportcsz(BaseEventLoop._make_subprocess_transportcCstdS)N)r)rXrrr_write_to_selfjszBaseEventLoop._write_to_selfcCstdS)N)r)rX event_listrrr_process_eventssszBaseEventLoop._process_eventscCs|jrtddS)NzEvent loop is closed)rj RuntimeError)rXrrrrwszBaseEventLoop._check_closedcCs*|jj||js&|j|j|jdS)N)rdiscardrcall_soon_threadsaferaclose)rXagenrrr_asyncgen_finalizer_hook{s z&BaseEventLoop._asyncgen_finalizer_hookcCs,|jrtjdj|t|d|jj|dS)NzNasynchronous generator {!r} was scheduled after loop.shutdown_asyncgens() call)source)rwarningswarnformatResourceWarningradd)rXrrrr_asyncgen_firstiter_hooks  z&BaseEventLoop._asyncgen_firstiter_hookccsd|_|jdkst|j r dSt|j}|jjtjdd|Dd|d}|EdH}x8t||D]*\}}t|t rf|j dj |||dqfWdS)NTcSsg|] }|jqSr)r).0Zagrrr sz4BaseEventLoop.shutdown_asyncgens..)Zreturn_exceptionsrHz?an error occurred during closing of asynchronous generator {!r})message exceptionZasyncgen) rrlenlistclearrgatherziprrOcall_exception_handlerr)rXZ closing_agensZ shutdown_coroZresultsresultrrrrshutdown_asyncgenss"      z BaseEventLoop.shutdown_asyncgensc Cs|j|jrtdtjdk r,td|j|jtj|_ |j dk rft j }t j |j|jdz$tj|x|j|jrtPqtWWdd|_d|_ tjd|jd|j dk rt j |XdS)Nz"This event loop is already runningz7Cannot run the event loop while another loop is running) firstiter finalizerF)rrrrZ_get_running_loop_set_coroutine_wrapper_debug threading get_identrqrrvrhset_asyncgen_hooksrrZ_set_running_loop _run_oncerk)rXZold_agen_hooksrrr run_forevers0          zBaseEventLoop.run_forevercCs|jtj| }tj||d}|r,d|_|jtz>y |jWn,|rj|j rj|j rj|j YnXWd|j tX|j st d|jS)N)rHFz+Event loop stopped before Future completed.)rrZisfuturerZ ensure_futureZ_log_destroy_pendingZadd_done_callbackrSrraZ cancelledrZremove_done_callbackrr)rXZfutureZnew_taskrrrrun_until_completes      z BaseEventLoop.run_until_completecCs d|_dS)NT)rk)rXrrrrQszBaseEventLoop.stopcCsj|jrtd|jrdS|jr,tjd|d|_|jj|jj|j }|dk rfd|_ |j dddS)Nz!Cannot close a running event loopzClose %rTF)wait) rrrjrr debugrnrrorpZshutdown)rXexecutorrrrr`s   zBaseEventLoop.closecCs|jS)N)rj)rXrrrrszBaseEventLoop.is_closedcCs0|js,tjd|t|d|js,|jdS)Nzunclosed event loop %r)r)rrrrrr`)rXrrr__del__ s  zBaseEventLoop.__del__cCs |jdk S)N)rq)rXrrrrszBaseEventLoop.is_runningcCstjS)N)rrrg)rXrrrrrszBaseEventLoop.timecGs,|j|j||f|}|jr(|jd=|S)Nrr)call_atrrr)rXZdelaycallbackrtimerrrr call_later szBaseEventLoop.call_latercGsX|j|jr"|j|j|dtj||||}|jr@|jd=tj|j |d|_ |S)NrrTr) rr _check_thread_check_callbackrZ TimerHandlerheapqheappushro)rXwhenrrrrrrr5s zBaseEventLoop.call_atcGs@|j|jr"|j|j|d|j||}|jr<|jd=|S)N call_soonrr)rrrr _call_soonr)rXrrrrrrrEs   zBaseEventLoop.call_sooncCs>tj|stj|r"tdj|t|s:tdj||dS)Nz#coroutines cannot be used with {}()z0a callable object was expected by {}(), got {!r})rZ iscoroutineZiscoroutinefunctionr5rr)rXrmethodrrrrXs   zBaseEventLoop._check_callbackcCs,tj|||}|jr|jd=|jj||S)Nrr)rZHandlerrnr9)rXrrrrrrrcs  zBaseEventLoop._call_sooncCs,|jdkrdStj}||jkr(tddS)NzMNon-thread-safe operation invoked on an event loop other than the current one)rqrrr)rXZ thread_idrrrrjs  zBaseEventLoop._check_threadcGs@|j|jr|j|d|j||}|jr4|jd=|j|S)Nrrr)rrrrrr)rXrrrrrrr{s  z"BaseEventLoop.call_soon_threadsafecGsZ|j|jr|j|d|dkr@|j}|dkr@tjj}||_tj|j|f||dS)Nrun_in_executor)rH) rrrrp concurrentrZThreadPoolExecutorZ wrap_futureZsubmit)rXrfuncrrrrrs  zBaseEventLoop.run_in_executorcCs ||_dS)N)rp)rXrrrrset_default_executorsz"BaseEventLoop.set_default_executorc Csd||fg}|r |jd||r2|jd||rD|jd||rV|jd|dj|}tjd||j}tj||||||} |j|} d|| d | f}| |jkrtj|n tj|| S) Nz%s:%rz family=%rztype=%rzproto=%rzflags=%rz, zGet address info %sz(Getting address info %s took %.3f ms: %rg@@) r9joinr rrrr rFr|rI) rXr;r<r=r>r?rBmsgt0Zaddrinfodtrrr_getaddrinfo_debugs(      z BaseEventLoop._getaddrinfo_debugr)r=r>r?rBc Cs>|jr |jd|j||||||S|jdtj||||||SdS)N)rrrr rF)rXr;r<r=r>r?rBrrrrFs   zBaseEventLoop.getaddrinfocCs|jdtj||S)N)rr getnameinfo)rXZsockaddrrBrrrrszBaseEventLoop.getnameinfo)sslr=r?rBr% local_addrrc#s| dk r| rtd| dkr2|r2|s.td|} |dk sD|dk r|dk rTtdt||f|tj|||d} | g} | dk rt| |tj|||d} | j| nd} tj| |dEdH| j}|std| dk r| j}|stdg}x|D]B\}}}}}ytj|||d}|j d| dk rx|D]j\}}}}}y|j |PWnHtk r}z*t|j d j ||j j}|j|WYdd}~XnXq.W|jd}w|jrtjd |||j||EdHWn^tk r}z"|dk r|j|j|WYdd}~Xq|dk r,|jYqXPqWt|d krR|d nJt|d tfd d|Dr~|d tdj djdd|Dn,|dkrtdt|jstdj ||j|||| EdH\}}|jr |jd}tjd|||||||fS)Nz+server_hostname is only meaningful with sslz:You must set server_hostname when using ssl without a hostz8host/port and sock can not be specified at the same time)r=r>r?rBrH)rHz!getaddrinfo() returned empty list)r=r>r?Fz2error while attempting to bind on address {!r}: {}zconnect %r to %rrrc3s|]}t|kVqdS)N)r)rrR)modelrr sz2BaseEventLoop.create_connection..zMultiple exceptions: {}z, css|]}t|VqdS)N)r)rrRrrrr#sz5host and port was not specified and no sock specifiedz&A Stream Socket was expected, got {!r}r z%r connected to %s:%r: (%r, %r))r!rKr r)r9rrrr$ setblockingbinderrnorstrerrorlowerr`rr r sock_connectrrallrr+r>_create_connection_transportget_extra_info)rXprotocol_factoryr;r<rr=r?rBr%rrf1fsf2infosZ laddr_infos exceptionsr>ZcnamerG_ZladdrrR transportrr)rrcreate_connections        "        zBaseEventLoop.create_connectionc cs|jd|}|j}|rFt|tr*dn|}|j||||||d} n|j|||} y|EdHWn| jYnX| |fS)NF)rr)rrDrrxrrr`) rXr%rrrrrrcrrrrrr=s  z*BaseEventLoop._create_connection_transport)r=r?rB reuse_address reuse_portallow_broadcastr%c#s8| dk rt| js tdj| s@s@|s@|s@|s@|s@|s@| r~t|||||| d} djdd| jD} tdj| | jdd} n*ps|dkrtd ||fdff}ntj }xdfd ffD]~\}}|dk rt ||t j |||d EdH}|s t d xB|D]:\}}}}}||f}||kr>ddg||<||||<qWqWfd d|jD}|sztdg}|dkrtjdkotjdk}x|D]\\}}\}}d} d} yt j |t j |d} |r| jt jt jd |rt| | r| jt jt jd | jdr,| j|rH|j| |EdH|} Wn^t k r}z"| dk rp| j|j|WYdd}~Xn"| dk r| jYnXPqW|d|}|j}|j| || |}|jr rtjd||ntj d||y|EdHWn|jYnX||fS)Nz#A UDP Socket was expected, got {!r})r remote_addrr=r?rBrrrz, css"|]\}}|rdj||VqdS)z{}={}N)r)rkvrrrrisz9BaseEventLoop.create_datagram_endpoint..zNsocket modifier keyword arguments can not be used when sock is specified. ({})Frzunexpected address familyr)r=r>r?rBrHz!getaddrinfo() returned empty listcs8g|]0\}}r|ddkp*o*|ddks||fqS)rNrr)rkeyZ addr_pair)rrrrrsz:BaseEventLoop.create_datagram_endpoint..zcan not get address informationposixcygwin)r=r>r?z@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))NN)!r-r>r!rdictritemsrrl OrderedDictrKr r,r$rynamervplatformr"r# SO_REUSEADDRr&Z SO_BROADCASTrrr`r9rDrrr rIr)rXrrrr=r?rBrrrr%ZoptsZproblemsZr_addrZaddr_pairs_infoZ addr_infosidxZaddrrZfamrZprorGrrZ local_addressZremote_addressrRrrcrr)rrrcreate_datagram_endpointUs              z&BaseEventLoop.create_datagram_endpointccs4t||f|tj||dEdH}|s0tdj||S)N)r=r>rBrHz%getaddrinfo({!r}) returned empty list)rKr r)r$r)rXr;r<r=rBrrrr_create_server_getaddrinfos  z(BaseEventLoop._create_server_getaddrinfor )r=rBr%backlogrrrc #st|trtd|dk s$dk r|dk r4td| dkrPtjdkoNtjdk} g} |dkrddg} n$t|ts|t|t j  r|g} n|} fdd| D} t j | diEdH}t tjj|}d }z x|D] }|\}}}}}ytj|||}Wn6tjk r2jr,tjd |||d d wYnX| j|| rV|jtjtjd | rdt|tr|tjkrttd r|jtjtjd y|j |Wqt!k r}z t!|j"d||j#j$fWYdd}~XqXqWd }Wd|s x| D]}|j%qWXn2|dkr"tdt&|j's.rHFz:create_server() failed to create socket.socket(%r, %r, %r)T)exc_info IPPROTO_IPV6z0error while attempting to bind on address %r: %sz)Neither host/port nor sock were specifiedz&A Stream Socket was expected, got {!r}z %r is serving).rrxr5r!ryrrvrrrlIterablerrset itertoolschain from_iterabler errorrr warningr9r"r#r r&r8r rrZ IPV6_V6ONLYrr$rrrr`r+r>rrTZlistenrZ_start_servingrI)rXrr;r<r=rBr%r rrrrUZhostsrrZ completedresr@Zsocktyper?Z canonnameZsaerrrr)r=rBr<rXr create_servers     (         zBaseEventLoop.create_server)rccs^t|jstdj||j|||dddEdH\}}|jrV|jd}tjd|||||fS)Nz&A Stream Socket was expected, got {!r}r0T)rr z%r handled: (%r, %r)) r+r>r!rrrrr r)rXrr%rrrrrrconnect_accepted_socketAs   z%BaseEventLoop.connect_accepted_socketc csd|}|j}|j|||}y|EdHWn|jYnX|jr\tjd|j||||fS)Nz Read pipe %r connected: (%r, %r))rDrr`rr rfileno)rXrrrrcrrrrconnect_read_pipeXszBaseEventLoop.connect_read_pipec csd|}|j}|j|||}y|EdHWn|jYnX|jr\tjd|j||||fS)Nz!Write pipe %r connected: (%r, %r))rDrr`rr rr)rXrrrrcrrrrconnect_write_pipeisz BaseEventLoop.connect_write_pipecCs|g}|dk r |jdt||dk rF|tjkrF|jdt|n4|dk r`|jdt||dk rz|jdt|tjdj|dS)Nzstdin=%szstdout=stderr=%sz stdout=%sz stderr=%s )r9rrrr rr)rXrrrrrIrrr_log_subprocesszszBaseEventLoop._log_subprocessT)rrruniversal_newlinesrrc kst|ttfstd|r"td|s.td|dkr>td|} d} |jrfd|} |j| ||||j| |d||||f| EdH} |jr| dk rtjd| | | | fS) Nzcmd must be a stringz universal_newlines must be Falsezshell must be Truerzbufsize must be 0zrun shell command %rTz%s: %r) rr3rr!rrrr rI) rXrcmdrrrr rrrr debug_logrrrrsubprocess_shells$zBaseEventLoop.subprocess_shellcos|r td|rtd|dkr(td|f| } x,| D]$} t| ttfs8tdt| jq8W|} d}|jrd|}|j|||||j | | d||||f| EdH}|jr|dk rt j d|||| fS) Nz universal_newlines must be Falsezshell must be Falserzbufsize must be 0z8program arguments must be a bytes or text string, not %szexecute program %rFz%s: %r) r!rrr3r5r>r[rrrr rI)rXrZprogramrrrr rrrrZ popen_argsargrr"rrrrsubprocess_execs,   zBaseEventLoop.subprocess_execcCs|jS)N)rt)rXrrrget_exception_handlersz#BaseEventLoop.get_exception_handlercCs*|dk r t| r tdj|||_dS)Nz/A callable object or None is expected, got {!r})rr5rrt)rXZhandlerrrrset_exception_handlers z#BaseEventLoop.set_exception_handlerc Cs|jd}|sd}|jd}|dk r6t|||jf}nd}d|kr`|jdk r`|jjr`|jj|d<|g}xt|D]}|d kr~qp||}|dkrdjtj|}d}||j 7}n2|dkrdjtj|}d }||j 7}nt |}|j d j ||qpWt jd j||d dS)Nrz!Unhandled exception in event looprFZsource_tracebackZhandle_tracebackr0z+Object created at (most recent call last): z+Handle created at (most recent call last): z{}: {} )r>rr)r{r> __traceback__r}rsortedr traceback format_listrstriprr9rr r) rXcontextrrrZ log_linesrvaluetbrrrdefault_exception_handlers6    z'BaseEventLoop.default_exception_handlercCs|jdkr>y|j|Wqtk r:tjdddYqXnny|j||Wn\tk r}z@y|jd||dWn"tk rtjdddYnXWYdd}~XnXdS)Nz&Exception in default exception handlerT)rz$Unhandled error in exception handler)rrr.zeException in default exception handler while handling an unexpected error in custom exception handler)rtr1rOr r)rXr.rRrrrrs" z$BaseEventLoop.call_exception_handlercCs|jr dS|jj|dS)N) _cancelledrnr9)rXrrrr _add_callback9szBaseEventLoop._add_callbackcCs|j||jdS)N)r3r)rXrrrr_add_callback_signalsafeAs z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)Nr)rori)rXrrrr_timer_handle_cancelledFsz%BaseEventLoop._timer_handle_cancelledc Cst|j}|tkrd|j|tkrdg}x&|jD]}|jr>d|_q,|j|q,Wtj|||_d|_n8x6|jr|jdjr|jd8_tj |j}d|_qfWd}|j s|j rd}n*|jr|jdj }t td||jt}|jo|dkr|j}|jj|}|j|}|dkrtj} ntj} t|} |dkrLtj| d|d| nD| rntj| d|d|d| n"|dkrtj| d|d|dn |jj|}|j||j|j} xD|jr|jd}|j | krPtj |j}d|_|j j|qWt|j } xt| D]|} |j j}|jr*q|jrzD||_|j}|j|j|}||jkrttj d t!||Wdd|_Xn|jqWd}dS) NFrrg?zpoll took %.3f ms: %s eventsg@@z$poll %.3f ms took %.3f ms: %s eventsz"poll %.3f ms took %.3f ms: timeoutzExecuting %s took %.3f seconds)"rro_MIN_SCHEDULED_TIMER_HANDLESri%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr2r9rheapifyheappoprnrkZ_whenminmaxrrMAXIMUM_SELECT_TIMEOUTrZ _selectorZselectloggingINFODEBUGr logrrsrangepopleftr}Z_runr|rr)rXZ sched_countZ new_scheduledrZtimeoutrrrrlevelZneventZend_timeZntodoirrrrKs                       zBaseEventLoop._run_oncec Csytj}tj}Wntk r$dSXt|}|j|krsT            ;   /