/home/fresvfqn/waterdamagerestorationandrepairsmithtown.com/Compressed/asyncio.zip
PK[v��4f4f	events.pynu�[���"""Event loop and event loop policy."""

__all__ = (
    'AbstractEventLoopPolicy',
    'AbstractEventLoop', 'AbstractServer',
    'Handle', 'TimerHandle',
    'get_event_loop_policy', 'set_event_loop_policy',
    'get_event_loop', 'set_event_loop', 'new_event_loop',
    'get_child_watcher', 'set_child_watcher',
    '_set_running_loop', 'get_running_loop',
    '_get_running_loop',
)

import contextvars
import os
import socket
import subprocess
import sys
import threading

from . import format_helpers
from . import exceptions


class Handle:
    """Object returned by callback registration methods."""

    __slots__ = ('_callback', '_args', '_cancelled', '_loop',
                 '_source_traceback', '_repr', '__weakref__',
                 '_context')

    def __init__(self, callback, args, loop, context=None):
        if context is None:
            context = contextvars.copy_context()
        self._context = context
        self._loop = loop
        self._callback = callback
        self._args = args
        self._cancelled = False
        self._repr = None
        if self._loop.get_debug():
            self._source_traceback = format_helpers.extract_stack(
                sys._getframe(1))
        else:
            self._source_traceback = None

    def _repr_info(self):
        info = [self.__class__.__name__]
        if self._cancelled:
            info.append('cancelled')
        if self._callback is not None:
            info.append(format_helpers._format_callback_source(
                self._callback, self._args))
        if self._source_traceback:
            frame = self._source_traceback[-1]
            info.append(f'created at {frame[0]}:{frame[1]}')
        return info

    def __repr__(self):
        if self._repr is not None:
            return self._repr
        info = self._repr_info()
        return '<{}>'.format(' '.join(info))

    def cancel(self):
        if not self._cancelled:
            self._cancelled = True
            if self._loop.get_debug():
                # Keep a representation in debug mode to keep callback and
                # parameters. For example, to log the warning
                # "Executing <Handle...> took 2.5 second"
                self._repr = repr(self)
            self._callback = None
            self._args = None

    def cancelled(self):
        return self._cancelled

    def _run(self):
        try:
            self._context.run(self._callback, *self._args)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            cb = format_helpers._format_callback_source(
                self._callback, self._args)
            msg = f'Exception in callback {cb}'
            context = {
                'message': msg,
                'exception': exc,
                'handle': self,
            }
            if self._source_traceback:
                context['source_traceback'] = self._source_traceback
            self._loop.call_exception_handler(context)
        self = None  # Needed to break cycles when an exception occurs.


class TimerHandle(Handle):
    """Object returned by timed callback registration methods."""

    __slots__ = ['_scheduled', '_when']

    def __init__(self, when, callback, args, loop, context=None):
        assert when is not None
        super().__init__(callback, args, loop, context)
        if self._source_traceback:
            del self._source_traceback[-1]
        self._when = when
        self._scheduled = False

    def _repr_info(self):
        info = super()._repr_info()
        pos = 2 if self._cancelled else 1
        info.insert(pos, f'when={self._when}')
        return info

    def __hash__(self):
        return hash(self._when)

    def __lt__(self, other):
        return self._when < other._when

    def __le__(self, other):
        if self._when < other._when:
            return True
        return self.__eq__(other)

    def __gt__(self, other):
        return self._when > other._when

    def __ge__(self, other):
        if self._when > other._when:
            return True
        return self.__eq__(other)

    def __eq__(self, other):
        if isinstance(other, TimerHandle):
            return (self._when == other._when and
                    self._callback == other._callback and
                    self._args == other._args and
                    self._cancelled == other._cancelled)
        return NotImplemented

    def __ne__(self, other):
        equal = self.__eq__(other)
        return NotImplemented if equal is NotImplemented else not equal

    def cancel(self):
        if not self._cancelled:
            self._loop._timer_handle_cancelled(self)
        super().cancel()

    def when(self):
        """Return a scheduled callback time.

        The time is an absolute timestamp, using the same time
        reference as loop.time().
        """
        return self._when


class AbstractServer:
    """Abstract server returned by create_server()."""

    def close(self):
        """Stop serving.  This leaves existing connections open."""
        raise NotImplementedError

    def get_loop(self):
        """Get the event loop the Server object is attached to."""
        raise NotImplementedError

    def is_serving(self):
        """Return True if the server is accepting connections."""
        raise NotImplementedError

    async def start_serving(self):
        """Start accepting connections.

        This method is idempotent, so it can be called when
        the server is already being serving.
        """
        raise NotImplementedError

    async def serve_forever(self):
        """Start accepting connections until the coroutine is cancelled.

        The server is closed when the coroutine is cancelled.
        """
        raise NotImplementedError

    async def wait_closed(self):
        """Coroutine to wait until service is closed."""
        raise NotImplementedError

    async def __aenter__(self):
        return self

    async def __aexit__(self, *exc):
        self.close()
        await self.wait_closed()


class AbstractEventLoop:
    """Abstract event loop."""

    # Running and stopping the event loop.

    def run_forever(self):
        """Run the event loop until stop() is called."""
        raise NotImplementedError

    def run_until_complete(self, future):
        """Run the event loop until a Future is done.

        Return the Future's result, or raise its exception.
        """
        raise NotImplementedError

    def stop(self):
        """Stop the event loop as soon as reasonable.

        Exactly how soon that is may depend on the implementation, but
        no more I/O callbacks should be scheduled.
        """
        raise NotImplementedError

    def is_running(self):
        """Return whether the event loop is currently running."""
        raise NotImplementedError

    def is_closed(self):
        """Returns True if the event loop was closed."""
        raise NotImplementedError

    def close(self):
        """Close the loop.

        The loop should not be running.

        This is idempotent and irreversible.

        No other methods should be called after this one.
        """
        raise NotImplementedError

    async def shutdown_asyncgens(self):
        """Shutdown all active asynchronous generators."""
        raise NotImplementedError

    # Methods scheduling callbacks.  All these return Handles.

    def _timer_handle_cancelled(self, handle):
        """Notification that a TimerHandle has been cancelled."""
        raise NotImplementedError

    def call_soon(self, callback, *args):
        return self.call_later(0, callback, *args)

    def call_later(self, delay, callback, *args):
        raise NotImplementedError

    def call_at(self, when, callback, *args):
        raise NotImplementedError

    def time(self):
        raise NotImplementedError

    def create_future(self):
        raise NotImplementedError

    # Method scheduling a coroutine object: create a task.

    def create_task(self, coro, *, name=None):
        raise NotImplementedError

    # Methods for interacting with threads.

    def call_soon_threadsafe(self, callback, *args):
        raise NotImplementedError

    def run_in_executor(self, executor, func, *args):
        raise NotImplementedError

    def set_default_executor(self, executor):
        raise NotImplementedError

    # Network I/O methods returning Futures.

    async def getaddrinfo(self, host, port, *,
                          family=0, type=0, proto=0, flags=0):
        raise NotImplementedError

    async def getnameinfo(self, sockaddr, flags=0):
        raise NotImplementedError

    async def create_connection(
            self, protocol_factory, host=None, port=None,
            *, ssl=None, family=0, proto=0,
            flags=0, sock=None, local_addr=None,
            server_hostname=None,
            ssl_handshake_timeout=None,
            happy_eyeballs_delay=None, interleave=None):
        raise NotImplementedError

    async def create_server(
            self, protocol_factory, host=None, port=None,
            *, family=socket.AF_UNSPEC,
            flags=socket.AI_PASSIVE, sock=None, backlog=100,
            ssl=None, reuse_address=None, reuse_port=None,
            ssl_handshake_timeout=None,
            start_serving=True):
        """A coroutine which creates a TCP server bound to host and port.

        The return value is a Server object which can be used to stop
        the service.

        If host is an empty string or None all interfaces are assumed
        and a list of multiple sockets will be returned (most likely
        one for IPv4 and another one for IPv6). The host parameter can also be
        a sequence (e.g. list) of hosts to bind to.

        family can be set to either AF_INET or AF_INET6 to force the
        socket to use IPv4 or IPv6. If not set it will be determined
        from host (defaults to AF_UNSPEC).

        flags is a bitmask for getaddrinfo().

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows.

        ssl_handshake_timeout is the time in seconds that an SSL server
        will wait for completion of the SSL handshake before aborting the
        connection. Default is 60s.

        start_serving set to True (default) causes the created server
        to start accepting connections immediately.  When set to False,
        the user should await Server.start_serving() or Server.serve_forever()
        to make the server to start accepting connections.
        """
        raise NotImplementedError

    async def sendfile(self, transport, file, offset=0, count=None,
                       *, fallback=True):
        """Send a file through a transport.

        Return an amount of sent bytes.
        """
        raise NotImplementedError

    async def start_tls(self, transport, protocol, sslcontext, *,
                        server_side=False,
                        server_hostname=None,
                        ssl_handshake_timeout=None):
        """Upgrade a transport to TLS.

        Return a new transport that *protocol* should start using
        immediately.
        """
        raise NotImplementedError

    async def create_unix_connection(
            self, protocol_factory, path=None, *,
            ssl=None, sock=None,
            server_hostname=None,
            ssl_handshake_timeout=None):
        raise NotImplementedError

    async def create_unix_server(
            self, protocol_factory, path=None, *,
            sock=None, backlog=100, ssl=None,
            ssl_handshake_timeout=None,
            start_serving=True):
        """A coroutine which creates a UNIX Domain Socket server.

        The return value is a Server object, which can be used to stop
        the service.

        path is a str, representing a file systsem path to bind the
        server socket to.

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        ssl_handshake_timeout is the time in seconds that an SSL server
        will wait for the SSL handshake to complete (defaults to 60s).

        start_serving set to True (default) causes the created server
        to start accepting connections immediately.  When set to False,
        the user should await Server.start_serving() or Server.serve_forever()
        to make the server to start accepting connections.
        """
        raise NotImplementedError

    async def create_datagram_endpoint(self, protocol_factory,
                                       local_addr=None, remote_addr=None, *,
                                       family=0, proto=0, flags=0,
                                       reuse_address=None, reuse_port=None,
                                       allow_broadcast=None, sock=None):
        """A coroutine which creates a datagram endpoint.

        This method will try to establish the endpoint in the background.
        When successful, the coroutine returns a (transport, protocol) pair.

        protocol_factory must be a callable returning a protocol instance.

        socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
        host (or family if specified), socket type SOCK_DGRAM.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified it will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows and some UNIX's. If the
        :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
        capability is unsupported.

        allow_broadcast tells the kernel to allow this endpoint to send
        messages to the broadcast address.

        sock can optionally be specified in order to use a preexisting
        socket object.
        """
        raise NotImplementedError

    # Pipes and subprocesses.

    async def connect_read_pipe(self, protocol_factory, pipe):
        """Register read pipe in event loop. Set the pipe to non-blocking mode.

        protocol_factory should instantiate object with Protocol interface.
        pipe is a file-like object.
        Return pair (transport, protocol), where transport supports the
        ReadTransport interface."""
        # The reason to accept file-like object instead of just file descriptor
        # is: we need to own pipe and close it at transport finishing
        # Can got complicated errors if pass f.fileno(),
        # close fd in pipe transport then close f and vise versa.
        raise NotImplementedError

    async def connect_write_pipe(self, protocol_factory, pipe):
        """Register write pipe in event loop.

        protocol_factory should instantiate object with BaseProtocol interface.
        Pipe is file-like object already switched to nonblocking.
        Return pair (transport, protocol), where transport support
        WriteTransport interface."""
        # The reason to accept file-like object instead of just file descriptor
        # is: we need to own pipe and close it at transport finishing
        # Can got complicated errors if pass f.fileno(),
        # close fd in pipe transport then close f and vise versa.
        raise NotImplementedError

    async def subprocess_shell(self, protocol_factory, cmd, *,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               **kwargs):
        raise NotImplementedError

    async def subprocess_exec(self, protocol_factory, *args,
                              stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              **kwargs):
        raise NotImplementedError

    # Ready-based callback registration methods.
    # The add_*() methods return None.
    # The remove_*() methods return True if something was removed,
    # False if there was nothing to delete.

    def add_reader(self, fd, callback, *args):
        raise NotImplementedError

    def remove_reader(self, fd):
        raise NotImplementedError

    def add_writer(self, fd, callback, *args):
        raise NotImplementedError

    def remove_writer(self, fd):
        raise NotImplementedError

    # Completion based I/O methods returning Futures.

    async def sock_recv(self, sock, nbytes):
        raise NotImplementedError

    async def sock_recv_into(self, sock, buf):
        raise NotImplementedError

    async def sock_sendall(self, sock, data):
        raise NotImplementedError

    async def sock_connect(self, sock, address):
        raise NotImplementedError

    async def sock_accept(self, sock):
        raise NotImplementedError

    async def sock_sendfile(self, sock, file, offset=0, count=None,
                            *, fallback=None):
        raise NotImplementedError

    # Signal handling.

    def add_signal_handler(self, sig, callback, *args):
        raise NotImplementedError

    def remove_signal_handler(self, sig):
        raise NotImplementedError

    # Task factory.

    def set_task_factory(self, factory):
        raise NotImplementedError

    def get_task_factory(self):
        raise NotImplementedError

    # Error handlers.

    def get_exception_handler(self):
        raise NotImplementedError

    def set_exception_handler(self, handler):
        raise NotImplementedError

    def default_exception_handler(self, context):
        raise NotImplementedError

    def call_exception_handler(self, context):
        raise NotImplementedError

    # Debug flag management.

    def get_debug(self):
        raise NotImplementedError

    def set_debug(self, enabled):
        raise NotImplementedError


class AbstractEventLoopPolicy:
    """Abstract policy for accessing the event loop."""

    def get_event_loop(self):
        """Get the event loop for the current context.

        Returns an event loop object implementing the BaseEventLoop interface,
        or raises an exception in case no event loop has been set for the
        current context and the current policy does not specify to create one.

        It should never return None."""
        raise NotImplementedError

    def set_event_loop(self, loop):
        """Set the event loop for the current context to loop."""
        raise NotImplementedError

    def new_event_loop(self):
        """Create and return a new event loop object according to this
        policy's rules. If there's need to set this loop as the event loop for
        the current context, set_event_loop must be called explicitly."""
        raise NotImplementedError

    # Child processes handling (Unix only).

    def get_child_watcher(self):
        "Get the watcher for child processes."
        raise NotImplementedError

    def set_child_watcher(self, watcher):
        """Set the watcher for child processes."""
        raise NotImplementedError


class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
    """Default policy implementation for accessing the event loop.

    In this policy, each thread has its own event loop.  However, we
    only automatically create an event loop by default for the main
    thread; other threads by default have no event loop.

    Other policies may have different rules (e.g. a single global
    event loop, or automatically creating an event loop per thread, or
    using some other notion of context to which an event loop is
    associated).
    """

    _loop_factory = None

    class _Local(threading.local):
        _loop = None
        _set_called = False

    def __init__(self):
        self._local = self._Local()

    def get_event_loop(self):
        """Get the event loop for the current context.

        Returns an instance of EventLoop or raises an exception.
        """
        if (self._local._loop is None and
                not self._local._set_called and
                isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())

        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)

        return self._local._loop

    def set_event_loop(self, loop):
        """Set the event loop."""
        self._local._set_called = True
        assert loop is None or isinstance(loop, AbstractEventLoop)
        self._local._loop = loop

    def new_event_loop(self):
        """Create a new event loop.

        You must call set_event_loop() to make this the current event
        loop.
        """
        return self._loop_factory()


# Event loop policy.  The policy itself is always global, even if the
# policy's rules say that there is an event loop per thread (or other
# notion of context).  The default policy is installed by the first
# call to get_event_loop_policy().
_event_loop_policy = None

# Lock for protecting the on-the-fly creation of the event loop policy.
_lock = threading.Lock()


# A TLS for the running event loop, used by _get_running_loop.
class _RunningLoop(threading.local):
    loop_pid = (None, None)


_running_loop = _RunningLoop()


def get_running_loop():
    """Return the running event loop.  Raise a RuntimeError if there is none.

    This function is thread-specific.
    """
    # NOTE: this function is implemented in C (see _asynciomodule.c)
    loop = _get_running_loop()
    if loop is None:
        raise RuntimeError('no running event loop')
    return loop


def _get_running_loop():
    """Return the running event loop or None.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    """
    # NOTE: this function is implemented in C (see _asynciomodule.c)
    running_loop, pid = _running_loop.loop_pid
    if running_loop is not None and pid == os.getpid():
        return running_loop


def _set_running_loop(loop):
    """Set the running event loop.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    """
    # NOTE: this function is implemented in C (see _asynciomodule.c)
    _running_loop.loop_pid = (loop, os.getpid())


def _init_event_loop_policy():
    global _event_loop_policy
    with _lock:
        if _event_loop_policy is None:  # pragma: no branch
            from . import DefaultEventLoopPolicy
            _event_loop_policy = DefaultEventLoopPolicy()


def get_event_loop_policy():
    """Get the current event loop policy."""
    if _event_loop_policy is None:
        _init_event_loop_policy()
    return _event_loop_policy


def set_event_loop_policy(policy):
    """Set the current event loop policy.

    If policy is None, the default policy is restored."""
    global _event_loop_policy
    assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
    _event_loop_policy = policy


def get_event_loop():
    """Return an asyncio event loop.

    When called from a coroutine or a callback (e.g. scheduled with call_soon
    or similar API), this function will always return the running event loop.

    If there is no running event loop set, the function will return
    the result of `get_event_loop_policy().get_event_loop()` call.
    """
    # NOTE: this function is implemented in C (see _asynciomodule.c)
    current_loop = _get_running_loop()
    if current_loop is not None:
        return current_loop
    return get_event_loop_policy().get_event_loop()


def set_event_loop(loop):
    """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
    get_event_loop_policy().set_event_loop(loop)


def new_event_loop():
    """Equivalent to calling get_event_loop_policy().new_event_loop()."""
    return get_event_loop_policy().new_event_loop()


def get_child_watcher():
    """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
    return get_event_loop_policy().get_child_watcher()


def set_child_watcher(watcher):
    """Equivalent to calling
    get_event_loop_policy().set_child_watcher(watcher)."""
    return get_event_loop_policy().set_child_watcher(watcher)


# Alias pure-Python implementations for testing purposes.
_py__get_running_loop = _get_running_loop
_py__set_running_loop = _set_running_loop
_py_get_running_loop = get_running_loop
_py_get_event_loop = get_event_loop


try:
    # get_event_loop() is one of the most frequently called
    # functions in asyncio.  Pure Python implementation is
    # about 4 times slower than C-accelerated.
    from _asyncio import (_get_running_loop, _set_running_loop,
                          get_running_loop, get_event_loop)
except ImportError:
    pass
else:
    # Alias C implementations for testing purposes.
    _c__get_running_loop = _get_running_loop
    _c__set_running_loop = _set_running_loop
    _c_get_running_loop = get_running_loop
    _c_get_event_loop = get_event_loop
PK[��,��(�(
transports.pynu�[���"""Abstract Transport class."""

__all__ = (
    'BaseTransport', 'ReadTransport', 'WriteTransport',
    'Transport', 'DatagramTransport', 'SubprocessTransport',
)


class BaseTransport:
    """Base class for transports."""

    __slots__ = ('_extra',)

    def __init__(self, extra=None):
        if extra is None:
            extra = {}
        self._extra = extra

    def get_extra_info(self, name, default=None):
        """Get optional transport information."""
        return self._extra.get(name, default)

    def is_closing(self):
        """Return True if the transport is closing or closed."""
        raise NotImplementedError

    def close(self):
        """Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        """
        raise NotImplementedError

    def set_protocol(self, protocol):
        """Set a new protocol."""
        raise NotImplementedError

    def get_protocol(self):
        """Return the current protocol."""
        raise NotImplementedError


class ReadTransport(BaseTransport):
    """Interface for read-only transports."""

    __slots__ = ()

    def is_reading(self):
        """Return True if the transport is receiving."""
        raise NotImplementedError

    def pause_reading(self):
        """Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        """
        raise NotImplementedError

    def resume_reading(self):
        """Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        """
        raise NotImplementedError


class WriteTransport(BaseTransport):
    """Interface for write-only transports."""

    __slots__ = ()

    def set_write_buffer_limits(self, high=None, low=None):
        """Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        """
        raise NotImplementedError

    def get_write_buffer_size(self):
        """Return the current size of the write buffer."""
        raise NotImplementedError

    def write(self, data):
        """Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        """
        raise NotImplementedError

    def writelines(self, list_of_data):
        """Write a list (or any iterable) of data bytes to the transport.

        The default implementation concatenates the arguments and
        calls write() on the result.
        """
        data = b''.join(list_of_data)
        self.write(data)

    def write_eof(self):
        """Close the write end after flushing buffered data.

        (This is like typing ^D into a UNIX program reading from stdin.)

        Data may still be received.
        """
        raise NotImplementedError

    def can_write_eof(self):
        """Return True if this transport supports write_eof(), False if not."""
        raise NotImplementedError

    def abort(self):
        """Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        """
        raise NotImplementedError


class Transport(ReadTransport, WriteTransport):
    """Interface representing a bidirectional transport.

    There may be several implementations, but typically, the user does
    not implement new transports; rather, the platform provides some
    useful transports that are implemented using the platform's best
    practices.

    The user never instantiates a transport directly; they call a
    utility function, passing it a protocol factory and other
    information necessary to create the transport and protocol.  (E.g.
    EventLoop.create_connection() or EventLoop.create_server().)

    The utility function will asynchronously create a transport and a
    protocol and hook them up by calling the protocol's
    connection_made() method, passing it the transport.

    The implementation here raises NotImplemented for every method
    except writelines(), which calls write() in a loop.
    """

    __slots__ = ()


class DatagramTransport(BaseTransport):
    """Interface for datagram (UDP) transports."""

    __slots__ = ()

    def sendto(self, data, addr=None):
        """Send data to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        addr is target socket address.
        If addr is None use target address pointed on transport creation.
        """
        raise NotImplementedError

    def abort(self):
        """Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        """
        raise NotImplementedError


class SubprocessTransport(BaseTransport):

    __slots__ = ()

    def get_pid(self):
        """Get subprocess id."""
        raise NotImplementedError

    def get_returncode(self):
        """Get subprocess returncode.

        See also
        http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
        """
        raise NotImplementedError

    def get_pipe_transport(self, fd):
        """Get transport for pipe with number fd."""
        raise NotImplementedError

    def send_signal(self, signal):
        """Send signal to subprocess.

        See also:
        docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
        """
        raise NotImplementedError

    def terminate(self):
        """Stop the subprocess.

        Alias for close() method.

        On Posix OSs the method sends SIGTERM to the subprocess.
        On Windows the Win32 API function TerminateProcess()
         is called to stop the subprocess.

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
        """
        raise NotImplementedError

    def kill(self):
        """Kill the subprocess.

        On Posix OSs the function sends SIGKILL to the subprocess.
        On Windows kill() is an alias for terminate().

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
        """
        raise NotImplementedError


class _FlowControlMixin(Transport):
    """All the logic for (write) flow control in a mix-in base class.

    The subclass must implement get_write_buffer_size().  It must call
    _maybe_pause_protocol() whenever the write buffer size increases,
    and _maybe_resume_protocol() whenever it decreases.  It may also
    override set_write_buffer_limits() (e.g. to specify different
    defaults).

    The subclass constructor must call super().__init__(extra).  This
    will call set_write_buffer_limits().

    The user may call set_write_buffer_limits() and
    get_write_buffer_size(), and their protocol's pause_writing() and
    resume_writing() may be called.
    """

    __slots__ = ('_loop', '_protocol_paused', '_high_water', '_low_water')

    def __init__(self, extra=None, loop=None):
        super().__init__(extra)
        assert loop is not None
        self._loop = loop
        self._protocol_paused = False
        self._set_write_buffer_limits()

    def _maybe_pause_protocol(self):
        size = self.get_write_buffer_size()
        if size <= self._high_water:
            return
        if not self._protocol_paused:
            self._protocol_paused = True
            try:
                self._protocol.pause_writing()
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException as exc:
                self._loop.call_exception_handler({
                    'message': 'protocol.pause_writing() failed',
                    'exception': exc,
                    'transport': self,
                    'protocol': self._protocol,
                })

    def _maybe_resume_protocol(self):
        if (self._protocol_paused and
                self.get_write_buffer_size() <= self._low_water):
            self._protocol_paused = False
            try:
                self._protocol.resume_writing()
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException as exc:
                self._loop.call_exception_handler({
                    'message': 'protocol.resume_writing() failed',
                    'exception': exc,
                    'transport': self,
                    'protocol': self._protocol,
                })

    def get_write_buffer_limits(self):
        return (self._low_water, self._high_water)

    def _set_write_buffer_limits(self, high=None, low=None):
        if high is None:
            if low is None:
                high = 64 * 1024
            else:
                high = 4 * low
        if low is None:
            low = high // 4

        if not high >= low >= 0:
            raise ValueError(
                f'high ({high!r}) must be >= low ({low!r}) must be >= 0')

        self._high_water = high
        self._low_water = low

    def set_write_buffer_limits(self, high=None, low=None):
        self._set_write_buffer_limits(high=high, low=low)
        self._maybe_pause_protocol()

    def get_write_buffer_size(self):
        raise NotImplementedError
PK[#ƅ� h h
streams.pynu�[���__all__ = (
    'StreamReader', 'StreamWriter', 'StreamReaderProtocol',
    'open_connection', 'start_server')

import socket
import sys
import warnings
import weakref

if hasattr(socket, 'AF_UNIX'):
    __all__ += ('open_unix_connection', 'start_unix_server')

from . import coroutines
from . import events
from . import exceptions
from . import format_helpers
from . import protocols
from .log import logger
from .tasks import sleep


_DEFAULT_LIMIT = 2 ** 16  # 64 KiB


async def open_connection(host=None, port=None, *,
                          loop=None, limit=_DEFAULT_LIMIT, **kwds):
    """A wrapper for create_connection() returning a (reader, writer) pair.

    The reader returned is a StreamReader instance; the writer is a
    StreamWriter instance.

    The arguments are all the usual arguments to create_connection()
    except protocol_factory; most common are positional host and port,
    with various optional keyword arguments following.

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    (If you want to customize the StreamReader and/or
    StreamReaderProtocol classes, just copy the code -- there's
    really nothing special here except some convenience.)
    """
    if loop is None:
        loop = events.get_event_loop()
    else:
        warnings.warn("The loop argument is deprecated since Python 3.8, "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning, stacklevel=2)
    reader = StreamReader(limit=limit, loop=loop)
    protocol = StreamReaderProtocol(reader, loop=loop)
    transport, _ = await loop.create_connection(
        lambda: protocol, host, port, **kwds)
    writer = StreamWriter(transport, protocol, reader, loop)
    return reader, writer


async def start_server(client_connected_cb, host=None, port=None, *,
                       loop=None, limit=_DEFAULT_LIMIT, **kwds):
    """Start a socket server, call back for each client connected.

    The first parameter, `client_connected_cb`, takes two parameters:
    client_reader, client_writer.  client_reader is a StreamReader
    object, while client_writer is a StreamWriter object.  This
    parameter can either be a plain callback function or a coroutine;
    if it is a coroutine, it will be automatically converted into a
    Task.

    The rest of the arguments are all the usual arguments to
    loop.create_server() except protocol_factory; most common are
    positional host and port, with various optional keyword arguments
    following.  The return value is the same as loop.create_server().

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    The return value is the same as loop.create_server(), i.e. a
    Server object which can be used to stop the service.
    """
    if loop is None:
        loop = events.get_event_loop()
    else:
        warnings.warn("The loop argument is deprecated since Python 3.8, "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning, stacklevel=2)

    def factory():
        reader = StreamReader(limit=limit, loop=loop)
        protocol = StreamReaderProtocol(reader, client_connected_cb,
                                        loop=loop)
        return protocol

    return await loop.create_server(factory, host, port, **kwds)


if hasattr(socket, 'AF_UNIX'):
    # UNIX Domain Sockets are supported on this platform

    async def open_unix_connection(path=None, *,
                                   loop=None, limit=_DEFAULT_LIMIT, **kwds):
        """Similar to `open_connection` but works with UNIX Domain Sockets."""
        if loop is None:
            loop = events.get_event_loop()
        else:
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)
        reader = StreamReader(limit=limit, loop=loop)
        protocol = StreamReaderProtocol(reader, loop=loop)
        transport, _ = await loop.create_unix_connection(
            lambda: protocol, path, **kwds)
        writer = StreamWriter(transport, protocol, reader, loop)
        return reader, writer

    async def start_unix_server(client_connected_cb, path=None, *,
                                loop=None, limit=_DEFAULT_LIMIT, **kwds):
        """Similar to `start_server` but works with UNIX Domain Sockets."""
        if loop is None:
            loop = events.get_event_loop()
        else:
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)

        def factory():
            reader = StreamReader(limit=limit, loop=loop)
            protocol = StreamReaderProtocol(reader, client_connected_cb,
                                            loop=loop)
            return protocol

        return await loop.create_unix_server(factory, path, **kwds)


class FlowControlMixin(protocols.Protocol):
    """Reusable flow control logic for StreamWriter.drain().

    This implements the protocol methods pause_writing(),
    resume_writing() and connection_lost().  If the subclass overrides
    these it must call the super methods.

    StreamWriter.drain() must wait for _drain_helper() coroutine.
    """

    def __init__(self, loop=None):
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
        self._paused = False
        self._drain_waiter = None
        self._connection_lost = False

    def pause_writing(self):
        assert not self._paused
        self._paused = True
        if self._loop.get_debug():
            logger.debug("%r pauses writing", self)

    def resume_writing(self):
        assert self._paused
        self._paused = False
        if self._loop.get_debug():
            logger.debug("%r resumes writing", self)

        waiter = self._drain_waiter
        if waiter is not None:
            self._drain_waiter = None
            if not waiter.done():
                waiter.set_result(None)

    def connection_lost(self, exc):
        self._connection_lost = True
        # Wake up the writer if currently paused.
        if not self._paused:
            return
        waiter = self._drain_waiter
        if waiter is None:
            return
        self._drain_waiter = None
        if waiter.done():
            return
        if exc is None:
            waiter.set_result(None)
        else:
            waiter.set_exception(exc)

    async def _drain_helper(self):
        if self._connection_lost:
            raise ConnectionResetError('Connection lost')
        if not self._paused:
            return
        waiter = self._drain_waiter
        assert waiter is None or waiter.cancelled()
        waiter = self._loop.create_future()
        self._drain_waiter = waiter
        await waiter

    def _get_close_waiter(self, stream):
        raise NotImplementedError


class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
    """Helper class to adapt between Protocol and StreamReader.

    (This is a helper class instead of making StreamReader itself a
    Protocol subclass, because the StreamReader has other potential
    uses, and to prevent the user of the StreamReader to accidentally
    call inappropriate methods of the protocol.)
    """

    _source_traceback = None

    def __init__(self, stream_reader, client_connected_cb=None, loop=None):
        super().__init__(loop=loop)
        if stream_reader is not None:
            self._stream_reader_wr = weakref.ref(stream_reader)
            self._source_traceback = stream_reader._source_traceback
        else:
            self._stream_reader_wr = None
        if client_connected_cb is not None:
            # This is a stream created by the `create_server()` function.
            # Keep a strong reference to the reader until a connection
            # is established.
            self._strong_reader = stream_reader
        self._reject_connection = False
        self._stream_writer = None
        self._transport = None
        self._client_connected_cb = client_connected_cb
        self._over_ssl = False
        self._closed = self._loop.create_future()

    @property
    def _stream_reader(self):
        if self._stream_reader_wr is None:
            return None
        return self._stream_reader_wr()

    def connection_made(self, transport):
        if self._reject_connection:
            context = {
                'message': ('An open stream was garbage collected prior to '
                            'establishing network connection; '
                            'call "stream.close()" explicitly.')
            }
            if self._source_traceback:
                context['source_traceback'] = self._source_traceback
            self._loop.call_exception_handler(context)
            transport.abort()
            return
        self._transport = transport
        reader = self._stream_reader
        if reader is not None:
            reader.set_transport(transport)
        self._over_ssl = transport.get_extra_info('sslcontext') is not None
        if self._client_connected_cb is not None:
            self._stream_writer = StreamWriter(transport, self,
                                               reader,
                                               self._loop)
            res = self._client_connected_cb(reader,
                                            self._stream_writer)
            if coroutines.iscoroutine(res):
                self._loop.create_task(res)
            self._strong_reader = None

    def connection_lost(self, exc):
        reader = self._stream_reader
        if reader is not None:
            if exc is None:
                reader.feed_eof()
            else:
                reader.set_exception(exc)
        if not self._closed.done():
            if exc is None:
                self._closed.set_result(None)
            else:
                self._closed.set_exception(exc)
        super().connection_lost(exc)
        self._stream_reader_wr = None
        self._stream_writer = None
        self._transport = None

    def data_received(self, data):
        reader = self._stream_reader
        if reader is not None:
            reader.feed_data(data)

    def eof_received(self):
        reader = self._stream_reader
        if reader is not None:
            reader.feed_eof()
        if self._over_ssl:
            # Prevent a warning in SSLProtocol.eof_received:
            # "returning true from eof_received()
            # has no effect when using ssl"
            return False
        return True

    def _get_close_waiter(self, stream):
        return self._closed

    def __del__(self):
        # Prevent reports about unhandled exceptions.
        # Better than self._closed._log_traceback = False hack
        closed = self._closed
        if closed.done() and not closed.cancelled():
            closed.exception()


class StreamWriter:
    """Wraps a Transport.

    This exposes write(), writelines(), [can_]write_eof(),
    get_extra_info() and close().  It adds drain() which returns an
    optional Future on which you can wait for flow control.  It also
    adds a transport property which references the Transport
    directly.
    """

    def __init__(self, transport, protocol, reader, loop):
        self._transport = transport
        self._protocol = protocol
        # drain() expects that the reader has an exception() method
        assert reader is None or isinstance(reader, StreamReader)
        self._reader = reader
        self._loop = loop
        self._complete_fut = self._loop.create_future()
        self._complete_fut.set_result(None)

    def __repr__(self):
        info = [self.__class__.__name__, f'transport={self._transport!r}']
        if self._reader is not None:
            info.append(f'reader={self._reader!r}')
        return '<{}>'.format(' '.join(info))

    @property
    def transport(self):
        return self._transport

    def write(self, data):
        self._transport.write(data)

    def writelines(self, data):
        self._transport.writelines(data)

    def write_eof(self):
        return self._transport.write_eof()

    def can_write_eof(self):
        return self._transport.can_write_eof()

    def close(self):
        return self._transport.close()

    def is_closing(self):
        return self._transport.is_closing()

    async def wait_closed(self):
        await self._protocol._get_close_waiter(self)

    def get_extra_info(self, name, default=None):
        return self._transport.get_extra_info(name, default)

    async def drain(self):
        """Flush the write buffer.

        The intended use is to write

          w.write(data)
          await w.drain()
        """
        if self._reader is not None:
            exc = self._reader.exception()
            if exc is not None:
                raise exc
        if self._transport.is_closing():
            # Wait for protocol.connection_lost() call
            # Raise connection closing error if any,
            # ConnectionResetError otherwise
            # Yield to the event loop so connection_lost() may be
            # called.  Without this, _drain_helper() would return
            # immediately, and code that calls
            #     write(...); await drain()
            # in a loop would never call connection_lost(), so it
            # would not see an error when the socket is closed.
            await sleep(0)
        await self._protocol._drain_helper()


class StreamReader:

    _source_traceback = None

    def __init__(self, limit=_DEFAULT_LIMIT, loop=None):
        # The line length limit is  a security feature;
        # it also doubles as half the buffer limit.

        if limit <= 0:
            raise ValueError('Limit cannot be <= 0')

        self._limit = limit
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
        self._buffer = bytearray()
        self._eof = False    # Whether we're done.
        self._waiter = None  # A future used by _wait_for_data()
        self._exception = None
        self._transport = None
        self._paused = False
        if self._loop.get_debug():
            self._source_traceback = format_helpers.extract_stack(
                sys._getframe(1))

    def __repr__(self):
        info = ['StreamReader']
        if self._buffer:
            info.append(f'{len(self._buffer)} bytes')
        if self._eof:
            info.append('eof')
        if self._limit != _DEFAULT_LIMIT:
            info.append(f'limit={self._limit}')
        if self._waiter:
            info.append(f'waiter={self._waiter!r}')
        if self._exception:
            info.append(f'exception={self._exception!r}')
        if self._transport:
            info.append(f'transport={self._transport!r}')
        if self._paused:
            info.append('paused')
        return '<{}>'.format(' '.join(info))

    def exception(self):
        return self._exception

    def set_exception(self, exc):
        self._exception = exc

        waiter = self._waiter
        if waiter is not None:
            self._waiter = None
            if not waiter.cancelled():
                waiter.set_exception(exc)

    def _wakeup_waiter(self):
        """Wakeup read*() functions waiting for data or EOF."""
        waiter = self._waiter
        if waiter is not None:
            self._waiter = None
            if not waiter.cancelled():
                waiter.set_result(None)

    def set_transport(self, transport):
        assert self._transport is None, 'Transport already set'
        self._transport = transport

    def _maybe_resume_transport(self):
        if self._paused and len(self._buffer) <= self._limit:
            self._paused = False
            self._transport.resume_reading()

    def feed_eof(self):
        self._eof = True
        self._wakeup_waiter()

    def at_eof(self):
        """Return True if the buffer is empty and 'feed_eof' was called."""
        return self._eof and not self._buffer

    def feed_data(self, data):
        assert not self._eof, 'feed_data after feed_eof'

        if not data:
            return

        self._buffer.extend(data)
        self._wakeup_waiter()

        if (self._transport is not None and
                not self._paused and
                len(self._buffer) > 2 * self._limit):
            try:
                self._transport.pause_reading()
            except NotImplementedError:
                # The transport can't be paused.
                # We'll just have to buffer all data.
                # Forget the transport so we don't keep trying.
                self._transport = None
            else:
                self._paused = True

    async def _wait_for_data(self, func_name):
        """Wait until feed_data() or feed_eof() is called.

        If stream was paused, automatically resume it.
        """
        # StreamReader uses a future to link the protocol feed_data() method
        # to a read coroutine. Running two read coroutines at the same time
        # would have an unexpected behaviour. It would not possible to know
        # which coroutine would get the next data.
        if self._waiter is not None:
            raise RuntimeError(
                f'{func_name}() called while another coroutine is '
                f'already waiting for incoming data')

        assert not self._eof, '_wait_for_data after EOF'

        # Waiting for data while paused will make deadlock, so prevent it.
        # This is essential for readexactly(n) for case when n > self._limit.
        if self._paused:
            self._paused = False
            self._transport.resume_reading()

        self._waiter = self._loop.create_future()
        try:
            await self._waiter
        finally:
            self._waiter = None

    async def readline(self):
        """Read chunk of data from the stream until newline (b'\n') is found.

        On success, return chunk that ends with newline. If only partial
        line can be read due to EOF, return incomplete line without
        terminating newline. When EOF was reached while no bytes read, empty
        bytes object is returned.

        If limit is reached, ValueError will be raised. In that case, if
        newline was found, complete line including newline will be removed
        from internal buffer. Else, internal buffer will be cleared. Limit is
        compared against part of the line without newline.

        If stream was paused, this function will automatically resume it if
        needed.
        """
        sep = b'\n'
        seplen = len(sep)
        try:
            line = await self.readuntil(sep)
        except exceptions.IncompleteReadError as e:
            return e.partial
        except exceptions.LimitOverrunError as e:
            if self._buffer.startswith(sep, e.consumed):
                del self._buffer[:e.consumed + seplen]
            else:
                self._buffer.clear()
            self._maybe_resume_transport()
            raise ValueError(e.args[0])
        return line

    async def readuntil(self, separator=b'\n'):
        """Read data from the stream until ``separator`` is found.

        On success, the data and separator will be removed from the
        internal buffer (consumed). Returned data will include the
        separator at the end.

        Configured stream limit is used to check result. Limit sets the
        maximal length of data that can be returned, not counting the
        separator.

        If an EOF occurs and the complete separator is still not found,
        an IncompleteReadError exception will be raised, and the internal
        buffer will be reset.  The IncompleteReadError.partial attribute
        may contain the separator partially.

        If the data cannot be read because of over limit, a
        LimitOverrunError exception  will be raised, and the data
        will be left in the internal buffer, so it can be read again.
        """
        seplen = len(separator)
        if seplen == 0:
            raise ValueError('Separator should be at least one-byte string')

        if self._exception is not None:
            raise self._exception

        # Consume whole buffer except last bytes, which length is
        # one less than seplen. Let's check corner cases with
        # separator='SEPARATOR':
        # * we have received almost complete separator (without last
        #   byte). i.e buffer='some textSEPARATO'. In this case we
        #   can safely consume len(separator) - 1 bytes.
        # * last byte of buffer is first byte of separator, i.e.
        #   buffer='abcdefghijklmnopqrS'. We may safely consume
        #   everything except that last byte, but this require to
        #   analyze bytes of buffer that match partial separator.
        #   This is slow and/or require FSM. For this case our
        #   implementation is not optimal, since require rescanning
        #   of data that is known to not belong to separator. In
        #   real world, separator will not be so long to notice
        #   performance problems. Even when reading MIME-encoded
        #   messages :)

        # `offset` is the number of bytes from the beginning of the buffer
        # where there is no occurrence of `separator`.
        offset = 0

        # Loop until we find `separator` in the buffer, exceed the buffer size,
        # or an EOF has happened.
        while True:
            buflen = len(self._buffer)

            # Check if we now have enough data in the buffer for `separator` to
            # fit.
            if buflen - offset >= seplen:
                isep = self._buffer.find(separator, offset)

                if isep != -1:
                    # `separator` is in the buffer. `isep` will be used later
                    # to retrieve the data.
                    break

                # see upper comment for explanation.
                offset = buflen + 1 - seplen
                if offset > self._limit:
                    raise exceptions.LimitOverrunError(
                        'Separator is not found, and chunk exceed the limit',
                        offset)

            # Complete message (with full separator) may be present in buffer
            # even when EOF flag is set. This may happen when the last chunk
            # adds data which makes separator be found. That's why we check for
            # EOF *ater* inspecting the buffer.
            if self._eof:
                chunk = bytes(self._buffer)
                self._buffer.clear()
                raise exceptions.IncompleteReadError(chunk, None)

            # _wait_for_data() will resume reading if stream was paused.
            await self._wait_for_data('readuntil')

        if isep > self._limit:
            raise exceptions.LimitOverrunError(
                'Separator is found, but chunk is longer than limit', isep)

        chunk = self._buffer[:isep + seplen]
        del self._buffer[:isep + seplen]
        self._maybe_resume_transport()
        return bytes(chunk)

    async def read(self, n=-1):
        """Read up to `n` bytes from the stream.

        If n is not provided, or set to -1, read until EOF and return all read
        bytes. If the EOF was received and the internal buffer is empty, return
        an empty bytes object.

        If n is zero, return empty bytes object immediately.

        If n is positive, this function try to read `n` bytes, and may return
        less or equal bytes than requested, but at least one byte. If EOF was
        received before any byte is read, this function returns empty byte
        object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        """

        if self._exception is not None:
            raise self._exception

        if n == 0:
            return b''

        if n < 0:
            # This used to just loop creating a new waiter hoping to
            # collect everything in self._buffer, but that would
            # deadlock if the subprocess sends more than self.limit
            # bytes.  So just call self.read(self._limit) until EOF.
            blocks = []
            while True:
                block = await self.read(self._limit)
                if not block:
                    break
                blocks.append(block)
            return b''.join(blocks)

        if not self._buffer and not self._eof:
            await self._wait_for_data('read')

        # This will work right even if buffer is less than n bytes
        data = bytes(self._buffer[:n])
        del self._buffer[:n]

        self._maybe_resume_transport()
        return data

    async def readexactly(self, n):
        """Read exactly `n` bytes.

        Raise an IncompleteReadError if EOF is reached before `n` bytes can be
        read. The IncompleteReadError.partial attribute of the exception will
        contain the partial read bytes.

        if n is zero, return empty bytes object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        """
        if n < 0:
            raise ValueError('readexactly size can not be less than zero')

        if self._exception is not None:
            raise self._exception

        if n == 0:
            return b''

        while len(self._buffer) < n:
            if self._eof:
                incomplete = bytes(self._buffer)
                self._buffer.clear()
                raise exceptions.IncompleteReadError(incomplete, n)

            await self._wait_for_data('readexactly')

        if len(self._buffer) == n:
            data = bytes(self._buffer)
            self._buffer.clear()
        else:
            data = bytes(self._buffer[:n])
            del self._buffer[:n]
        self._maybe_resume_transport()
        return data

    def __aiter__(self):
        return self

    async def __anext__(self):
        val = await self.readline()
        if val == b'':
            raise StopAsyncIteration
        return val
PK[�xD�JjJjsslproto.pynu�[���import collections
import warnings
try:
    import ssl
except ImportError:  # pragma: no cover
    ssl = None

from . import base_events
from . import constants
from . import protocols
from . import transports
from .log import logger


def _create_transport_context(server_side, server_hostname):
    if server_side:
        raise ValueError('Server side SSL needs a valid SSLContext')

    # Client side may pass ssl=True to use a default
    # context; in that case the sslcontext passed is None.
    # The default is secure for client connections.
    # Python 3.4+: use up-to-date strong settings.
    sslcontext = ssl.create_default_context()
    if not server_hostname:
        sslcontext.check_hostname = False
    return sslcontext


# States of an _SSLPipe.
_UNWRAPPED = "UNWRAPPED"
_DO_HANDSHAKE = "DO_HANDSHAKE"
_WRAPPED = "WRAPPED"
_SHUTDOWN = "SHUTDOWN"


class _SSLPipe(object):
    """An SSL "Pipe".

    An SSL pipe allows you to communicate with an SSL/TLS protocol instance
    through memory buffers. It can be used to implement a security layer for an
    existing connection where you don't have access to the connection's file
    descriptor, or for some reason you don't want to use it.

    An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
    data is passed through untransformed. In wrapped mode, application level
    data is encrypted to SSL record level data and vice versa. The SSL record
    level is the lowest level in the SSL protocol suite and is what travels
    as-is over the wire.

    An SslPipe initially is in "unwrapped" mode. To start SSL, call
    do_handshake(). To shutdown SSL again, call unwrap().
    """

    max_size = 256 * 1024   # Buffer size passed to read()

    def __init__(self, context, server_side, server_hostname=None):
        """
        The *context* argument specifies the ssl.SSLContext to use.

        The *server_side* argument indicates whether this is a server side or
        client side transport.

        The optional *server_hostname* argument can be used to specify the
        hostname you are connecting to. You may only specify this parameter if
        the _ssl module supports Server Name Indication (SNI).
        """
        self._context = context
        self._server_side = server_side
        self._server_hostname = server_hostname
        self._state = _UNWRAPPED
        self._incoming = ssl.MemoryBIO()
        self._outgoing = ssl.MemoryBIO()
        self._sslobj = None
        self._need_ssldata = False
        self._handshake_cb = None
        self._shutdown_cb = None

    @property
    def context(self):
        """The SSL context passed to the constructor."""
        return self._context

    @property
    def ssl_object(self):
        """The internal ssl.SSLObject instance.

        Return None if the pipe is not wrapped.
        """
        return self._sslobj

    @property
    def need_ssldata(self):
        """Whether more record level data is needed to complete a handshake
        that is currently in progress."""
        return self._need_ssldata

    @property
    def wrapped(self):
        """
        Whether a security layer is currently in effect.

        Return False during handshake.
        """
        return self._state == _WRAPPED

    def do_handshake(self, callback=None):
        """Start the SSL handshake.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the handshake is complete. The callback will be
        called with None if successful, else an exception instance.
        """
        if self._state != _UNWRAPPED:
            raise RuntimeError('handshake in progress or completed')
        self._sslobj = self._context.wrap_bio(
            self._incoming, self._outgoing,
            server_side=self._server_side,
            server_hostname=self._server_hostname)
        self._state = _DO_HANDSHAKE
        self._handshake_cb = callback
        ssldata, appdata = self.feed_ssldata(b'', only_handshake=True)
        assert len(appdata) == 0
        return ssldata

    def shutdown(self, callback=None):
        """Start the SSL shutdown sequence.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the shutdown is complete. The callback will be
        called without arguments.
        """
        if self._state == _UNWRAPPED:
            raise RuntimeError('no security layer present')
        if self._state == _SHUTDOWN:
            raise RuntimeError('shutdown in progress')
        assert self._state in (_WRAPPED, _DO_HANDSHAKE)
        self._state = _SHUTDOWN
        self._shutdown_cb = callback
        ssldata, appdata = self.feed_ssldata(b'')
        assert appdata == [] or appdata == [b'']
        return ssldata

    def feed_eof(self):
        """Send a potentially "ragged" EOF.

        This method will raise an SSL_ERROR_EOF exception if the EOF is
        unexpected.
        """
        self._incoming.write_eof()
        ssldata, appdata = self.feed_ssldata(b'')
        assert appdata == [] or appdata == [b'']

    def feed_ssldata(self, data, only_handshake=False):
        """Feed SSL record level data into the pipe.

        The data must be a bytes instance. It is OK to send an empty bytes
        instance. This can be used to get ssldata for a handshake initiated by
        this endpoint.

        Return a (ssldata, appdata) tuple. The ssldata element is a list of
        buffers containing SSL data that needs to be sent to the remote SSL.

        The appdata element is a list of buffers containing plaintext data that
        needs to be forwarded to the application. The appdata list may contain
        an empty buffer indicating an SSL "close_notify" alert. This alert must
        be acknowledged by calling shutdown().
        """
        if self._state == _UNWRAPPED:
            # If unwrapped, pass plaintext data straight through.
            if data:
                appdata = [data]
            else:
                appdata = []
            return ([], appdata)

        self._need_ssldata = False
        if data:
            self._incoming.write(data)

        ssldata = []
        appdata = []
        try:
            if self._state == _DO_HANDSHAKE:
                # Call do_handshake() until it doesn't raise anymore.
                self._sslobj.do_handshake()
                self._state = _WRAPPED
                if self._handshake_cb:
                    self._handshake_cb(None)
                if only_handshake:
                    return (ssldata, appdata)
                # Handshake done: execute the wrapped block

            if self._state == _WRAPPED:
                # Main state: read data from SSL until close_notify
                while True:
                    chunk = self._sslobj.read(self.max_size)
                    appdata.append(chunk)
                    if not chunk:  # close_notify
                        break

            elif self._state == _SHUTDOWN:
                # Call shutdown() until it doesn't raise anymore.
                self._sslobj.unwrap()
                self._sslobj = None
                self._state = _UNWRAPPED
                if self._shutdown_cb:
                    self._shutdown_cb()

            elif self._state == _UNWRAPPED:
                # Drain possible plaintext data after close_notify.
                appdata.append(self._incoming.read())
        except (ssl.SSLError, ssl.CertificateError) as exc:
            exc_errno = getattr(exc, 'errno', None)
            if exc_errno not in (
                    ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE,
                    ssl.SSL_ERROR_SYSCALL):
                if self._state == _DO_HANDSHAKE and self._handshake_cb:
                    self._handshake_cb(exc)
                raise
            self._need_ssldata = (exc_errno == ssl.SSL_ERROR_WANT_READ)

        # Check for record level data that needs to be sent back.
        # Happens for the initial handshake and renegotiations.
        if self._outgoing.pending:
            ssldata.append(self._outgoing.read())
        return (ssldata, appdata)

    def feed_appdata(self, data, offset=0):
        """Feed plaintext data into the pipe.

        Return an (ssldata, offset) tuple. The ssldata element is a list of
        buffers containing record level data that needs to be sent to the
        remote SSL instance. The offset is the number of plaintext bytes that
        were processed, which may be less than the length of data.

        NOTE: In case of short writes, this call MUST be retried with the SAME
        buffer passed into the *data* argument (i.e. the id() must be the
        same). This is an OpenSSL requirement. A further particularity is that
        a short write will always have offset == 0, because the _ssl module
        does not enable partial writes. And even though the offset is zero,
        there will still be encrypted data in ssldata.
        """
        assert 0 <= offset <= len(data)
        if self._state == _UNWRAPPED:
            # pass through data in unwrapped mode
            if offset < len(data):
                ssldata = [data[offset:]]
            else:
                ssldata = []
            return (ssldata, len(data))

        ssldata = []
        view = memoryview(data)
        while True:
            self._need_ssldata = False
            try:
                if offset < len(view):
                    offset += self._sslobj.write(view[offset:])
            except ssl.SSLError as exc:
                # It is not allowed to call write() after unwrap() until the
                # close_notify is acknowledged. We return the condition to the
                # caller as a short write.
                exc_errno = getattr(exc, 'errno', None)
                if exc.reason == 'PROTOCOL_IS_SHUTDOWN':
                    exc_errno = exc.errno = ssl.SSL_ERROR_WANT_READ
                if exc_errno not in (ssl.SSL_ERROR_WANT_READ,
                                     ssl.SSL_ERROR_WANT_WRITE,
                                     ssl.SSL_ERROR_SYSCALL):
                    raise
                self._need_ssldata = (exc_errno == ssl.SSL_ERROR_WANT_READ)

            # See if there's any record level data back for us.
            if self._outgoing.pending:
                ssldata.append(self._outgoing.read())
            if offset == len(view) or self._need_ssldata:
                break
        return (ssldata, offset)


class _SSLProtocolTransport(transports._FlowControlMixin,
                            transports.Transport):

    _sendfile_compatible = constants._SendfileMode.FALLBACK

    def __init__(self, loop, ssl_protocol):
        self._loop = loop
        # SSLProtocol instance
        self._ssl_protocol = ssl_protocol
        self._closed = False

    def get_extra_info(self, name, default=None):
        """Get optional transport information."""
        return self._ssl_protocol._get_extra_info(name, default)

    def set_protocol(self, protocol):
        self._ssl_protocol._set_app_protocol(protocol)

    def get_protocol(self):
        return self._ssl_protocol._app_protocol

    def is_closing(self):
        return self._closed

    def close(self):
        """Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        """
        self._closed = True
        self._ssl_protocol._start_shutdown()

    def __del__(self, _warn=warnings.warn):
        if not self._closed:
            _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
            self.close()

    def is_reading(self):
        tr = self._ssl_protocol._transport
        if tr is None:
            raise RuntimeError('SSL transport has not been initialized yet')
        return tr.is_reading()

    def pause_reading(self):
        """Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        """
        self._ssl_protocol._transport.pause_reading()

    def resume_reading(self):
        """Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        """
        self._ssl_protocol._transport.resume_reading()

    def set_write_buffer_limits(self, high=None, low=None):
        """Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        """
        self._ssl_protocol._transport.set_write_buffer_limits(high, low)

    def get_write_buffer_size(self):
        """Return the current size of the write buffer."""
        return self._ssl_protocol._transport.get_write_buffer_size()

    @property
    def _protocol_paused(self):
        # Required for sendfile fallback pause_writing/resume_writing logic
        return self._ssl_protocol._transport._protocol_paused

    def write(self, data):
        """Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        """
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError(f"data: expecting a bytes-like instance, "
                            f"got {type(data).__name__}")
        if not data:
            return
        self._ssl_protocol._write_appdata(data)

    def can_write_eof(self):
        """Return True if this transport supports write_eof(), False if not."""
        return False

    def abort(self):
        """Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        """
        self._ssl_protocol._abort()
        self._closed = True


class SSLProtocol(protocols.Protocol):
    """SSL protocol.

    Implementation of SSL on top of a socket using incoming and outgoing
    buffers which are ssl.MemoryBIO objects.
    """

    def __init__(self, loop, app_protocol, sslcontext, waiter,
                 server_side=False, server_hostname=None,
                 call_connection_made=True,
                 ssl_handshake_timeout=None):
        if ssl is None:
            raise RuntimeError('stdlib ssl module not available')

        if ssl_handshake_timeout is None:
            ssl_handshake_timeout = constants.SSL_HANDSHAKE_TIMEOUT
        elif ssl_handshake_timeout <= 0:
            raise ValueError(
                f"ssl_handshake_timeout should be a positive number, "
                f"got {ssl_handshake_timeout}")

        if not sslcontext:
            sslcontext = _create_transport_context(
                server_side, server_hostname)

        self._server_side = server_side
        if server_hostname and not server_side:
            self._server_hostname = server_hostname
        else:
            self._server_hostname = None
        self._sslcontext = sslcontext
        # SSL-specific extra info. More info are set when the handshake
        # completes.
        self._extra = dict(sslcontext=sslcontext)

        # App data write buffering
        self._write_backlog = collections.deque()
        self._write_buffer_size = 0

        self._waiter = waiter
        self._loop = loop
        self._set_app_protocol(app_protocol)
        self._app_transport = _SSLProtocolTransport(self._loop, self)
        # _SSLPipe instance (None until the connection is made)
        self._sslpipe = None
        self._session_established = False
        self._in_handshake = False
        self._in_shutdown = False
        # transport, ex: SelectorSocketTransport
        self._transport = None
        self._call_connection_made = call_connection_made
        self._ssl_handshake_timeout = ssl_handshake_timeout

    def _set_app_protocol(self, app_protocol):
        self._app_protocol = app_protocol
        self._app_protocol_is_buffer = \
            isinstance(app_protocol, protocols.BufferedProtocol)

    def _wakeup_waiter(self, exc=None):
        if self._waiter is None:
            return
        if not self._waiter.cancelled():
            if exc is not None:
                self._waiter.set_exception(exc)
            else:
                self._waiter.set_result(None)
        self._waiter = None

    def connection_made(self, transport):
        """Called when the low-level connection is made.

        Start the SSL handshake.
        """
        self._transport = transport
        self._sslpipe = _SSLPipe(self._sslcontext,
                                 self._server_side,
                                 self._server_hostname)
        self._start_handshake()

    def connection_lost(self, exc):
        """Called when the low-level connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        """
        if self._session_established:
            self._session_established = False
            self._loop.call_soon(self._app_protocol.connection_lost, exc)
        else:
            # Most likely an exception occurred while in SSL handshake.
            # Just mark the app transport as closed so that its __del__
            # doesn't complain.
            if self._app_transport is not None:
                self._app_transport._closed = True
        self._transport = None
        self._app_transport = None
        if getattr(self, '_handshake_timeout_handle', None):
            self._handshake_timeout_handle.cancel()
        self._wakeup_waiter(exc)
        self._app_protocol = None
        self._sslpipe = None

    def pause_writing(self):
        """Called when the low-level transport's buffer goes over
        the high-water mark.
        """
        self._app_protocol.pause_writing()

    def resume_writing(self):
        """Called when the low-level transport's buffer drains below
        the low-water mark.
        """
        self._app_protocol.resume_writing()

    def data_received(self, data):
        """Called when some SSL data is received.

        The argument is a bytes object.
        """
        if self._sslpipe is None:
            # transport closing, sslpipe is destroyed
            return

        try:
            ssldata, appdata = self._sslpipe.feed_ssldata(data)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as e:
            self._fatal_error(e, 'SSL error in data received')
            return

        for chunk in ssldata:
            self._transport.write(chunk)

        for chunk in appdata:
            if chunk:
                try:
                    if self._app_protocol_is_buffer:
                        protocols._feed_data_to_buffered_proto(
                            self._app_protocol, chunk)
                    else:
                        self._app_protocol.data_received(chunk)
                except (SystemExit, KeyboardInterrupt):
                    raise
                except BaseException as ex:
                    self._fatal_error(
                        ex, 'application protocol failed to receive SSL data')
                    return
            else:
                self._start_shutdown()
                break

    def eof_received(self):
        """Called when the other end of the low-level stream
        is half-closed.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        """
        try:
            if self._loop.get_debug():
                logger.debug("%r received EOF", self)

            self._wakeup_waiter(ConnectionResetError)

            if not self._in_handshake:
                keep_open = self._app_protocol.eof_received()
                if keep_open:
                    logger.warning('returning true from eof_received() '
                                   'has no effect when using ssl')
        finally:
            self._transport.close()

    def _get_extra_info(self, name, default=None):
        if name in self._extra:
            return self._extra[name]
        elif self._transport is not None:
            return self._transport.get_extra_info(name, default)
        else:
            return default

    def _start_shutdown(self):
        if self._in_shutdown:
            return
        if self._in_handshake:
            self._abort()
        else:
            self._in_shutdown = True
            self._write_appdata(b'')

    def _write_appdata(self, data):
        self._write_backlog.append((data, 0))
        self._write_buffer_size += len(data)
        self._process_write_backlog()

    def _start_handshake(self):
        if self._loop.get_debug():
            logger.debug("%r starts SSL handshake", self)
            self._handshake_start_time = self._loop.time()
        else:
            self._handshake_start_time = None
        self._in_handshake = True
        # (b'', 1) is a special value in _process_write_backlog() to do
        # the SSL handshake
        self._write_backlog.append((b'', 1))
        self._handshake_timeout_handle = \
            self._loop.call_later(self._ssl_handshake_timeout,
                                  self._check_handshake_timeout)
        self._process_write_backlog()

    def _check_handshake_timeout(self):
        if self._in_handshake is True:
            msg = (
                f"SSL handshake is taking longer than "
                f"{self._ssl_handshake_timeout} seconds: "
                f"aborting the connection"
            )
            self._fatal_error(ConnectionAbortedError(msg))

    def _on_handshake_complete(self, handshake_exc):
        self._in_handshake = False
        self._handshake_timeout_handle.cancel()

        sslobj = self._sslpipe.ssl_object
        try:
            if handshake_exc is not None:
                raise handshake_exc

            peercert = sslobj.getpeercert()
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            if isinstance(exc, ssl.CertificateError):
                msg = 'SSL handshake failed on verifying the certificate'
            else:
                msg = 'SSL handshake failed'
            self._fatal_error(exc, msg)
            return

        if self._loop.get_debug():
            dt = self._loop.time() - self._handshake_start_time
            logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)

        # Add extra info that becomes available after handshake.
        self._extra.update(peercert=peercert,
                           cipher=sslobj.cipher(),
                           compression=sslobj.compression(),
                           ssl_object=sslobj,
                           )
        if self._call_connection_made:
            self._app_protocol.connection_made(self._app_transport)
        self._wakeup_waiter()
        self._session_established = True
        # In case transport.write() was already called. Don't call
        # immediately _process_write_backlog(), but schedule it:
        # _on_handshake_complete() can be called indirectly from
        # _process_write_backlog(), and _process_write_backlog() is not
        # reentrant.
        self._loop.call_soon(self._process_write_backlog)

    def _process_write_backlog(self):
        # Try to make progress on the write backlog.
        if self._transport is None or self._sslpipe is None:
            return

        try:
            for i in range(len(self._write_backlog)):
                data, offset = self._write_backlog[0]
                if data:
                    ssldata, offset = self._sslpipe.feed_appdata(data, offset)
                elif offset:
                    ssldata = self._sslpipe.do_handshake(
                        self._on_handshake_complete)
                    offset = 1
                else:
                    ssldata = self._sslpipe.shutdown(self._finalize)
                    offset = 1

                for chunk in ssldata:
                    self._transport.write(chunk)

                if offset < len(data):
                    self._write_backlog[0] = (data, offset)
                    # A short write means that a write is blocked on a read
                    # We need to enable reading if it is paused!
                    assert self._sslpipe.need_ssldata
                    if self._transport._paused:
                        self._transport.resume_reading()
                    break

                # An entire chunk from the backlog was processed. We can
                # delete it and reduce the outstanding buffer size.
                del self._write_backlog[0]
                self._write_buffer_size -= len(data)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            if self._in_handshake:
                # Exceptions will be re-raised in _on_handshake_complete.
                self._on_handshake_complete(exc)
            else:
                self._fatal_error(exc, 'Fatal error on SSL transport')

    def _fatal_error(self, exc, message='Fatal error on transport'):
        if isinstance(exc, OSError):
            if self._loop.get_debug():
                logger.debug("%r: %s", self, message, exc_info=True)
        else:
            self._loop.call_exception_handler({
                'message': message,
                'exception': exc,
                'transport': self._transport,
                'protocol': self,
            })
        if self._transport:
            self._transport._force_close(exc)

    def _finalize(self):
        self._sslpipe = None

        if self._transport is not None:
            self._transport.close()

    def _abort(self):
        try:
            if self._transport is not None:
                self._transport.abort()
        finally:
            self._finalize()
PK[�4/�"�"base_subprocess.pynu�[���import collections
import subprocess
import warnings

from . import protocols
from . import transports
from .log import logger


class BaseSubprocessTransport(transports.SubprocessTransport):

    def __init__(self, loop, protocol, args, shell,
                 stdin, stdout, stderr, bufsize,
                 waiter=None, extra=None, **kwargs):
        super().__init__(extra)
        self._closed = False
        self._protocol = protocol
        self._loop = loop
        self._proc = None
        self._pid = None
        self._returncode = None
        self._exit_waiters = []
        self._pending_calls = collections.deque()
        self._pipes = {}
        self._finished = False

        if stdin == subprocess.PIPE:
            self._pipes[0] = None
        if stdout == subprocess.PIPE:
            self._pipes[1] = None
        if stderr == subprocess.PIPE:
            self._pipes[2] = None

        # Create the child process: set the _proc attribute
        try:
            self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
                        stderr=stderr, bufsize=bufsize, **kwargs)
        except:
            self.close()
            raise

        self._pid = self._proc.pid
        self._extra['subprocess'] = self._proc

        if self._loop.get_debug():
            if isinstance(args, (bytes, str)):
                program = args
            else:
                program = args[0]
            logger.debug('process %r created: pid %s',
                         program, self._pid)

        self._loop.create_task(self._connect_pipes(waiter))

    def __repr__(self):
        info = [self.__class__.__name__]
        if self._closed:
            info.append('closed')
        if self._pid is not None:
            info.append(f'pid={self._pid}')
        if self._returncode is not None:
            info.append(f'returncode={self._returncode}')
        elif self._pid is not None:
            info.append('running')
        else:
            info.append('not started')

        stdin = self._pipes.get(0)
        if stdin is not None:
            info.append(f'stdin={stdin.pipe}')

        stdout = self._pipes.get(1)
        stderr = self._pipes.get(2)
        if stdout is not None and stderr is stdout:
            info.append(f'stdout=stderr={stdout.pipe}')
        else:
            if stdout is not None:
                info.append(f'stdout={stdout.pipe}')
            if stderr is not None:
                info.append(f'stderr={stderr.pipe}')

        return '<{}>'.format(' '.join(info))

    def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
        raise NotImplementedError

    def set_protocol(self, protocol):
        self._protocol = protocol

    def get_protocol(self):
        return self._protocol

    def is_closing(self):
        return self._closed

    def close(self):
        if self._closed:
            return
        self._closed = True

        for proto in self._pipes.values():
            if proto is None:
                continue
            proto.pipe.close()

        if (self._proc is not None and
                # has the child process finished?
                self._returncode is None and
                # the child process has finished, but the
                # transport hasn't been notified yet?
                self._proc.poll() is None):

            if self._loop.get_debug():
                logger.warning('Close running child process: kill %r', self)

            try:
                self._proc.kill()
            except ProcessLookupError:
                pass

            # Don't clear the _proc reference yet: _post_init() may still run

    def __del__(self, _warn=warnings.warn):
        if not self._closed:
            _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
            self.close()

    def get_pid(self):
        return self._pid

    def get_returncode(self):
        return self._returncode

    def get_pipe_transport(self, fd):
        if fd in self._pipes:
            return self._pipes[fd].pipe
        else:
            return None

    def _check_proc(self):
        if self._proc is None:
            raise ProcessLookupError()

    def send_signal(self, signal):
        self._check_proc()
        self._proc.send_signal(signal)

    def terminate(self):
        self._check_proc()
        self._proc.terminate()

    def kill(self):
        self._check_proc()
        self._proc.kill()

    async def _connect_pipes(self, waiter):
        try:
            proc = self._proc
            loop = self._loop

            if proc.stdin is not None:
                _, pipe = await loop.connect_write_pipe(
                    lambda: WriteSubprocessPipeProto(self, 0),
                    proc.stdin)
                self._pipes[0] = pipe

            if proc.stdout is not None:
                _, pipe = await loop.connect_read_pipe(
                    lambda: ReadSubprocessPipeProto(self, 1),
                    proc.stdout)
                self._pipes[1] = pipe

            if proc.stderr is not None:
                _, pipe = await loop.connect_read_pipe(
                    lambda: ReadSubprocessPipeProto(self, 2),
                    proc.stderr)
                self._pipes[2] = pipe

            assert self._pending_calls is not None

            loop.call_soon(self._protocol.connection_made, self)
            for callback, data in self._pending_calls:
                loop.call_soon(callback, *data)
            self._pending_calls = None
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            if waiter is not None and not waiter.cancelled():
                waiter.set_exception(exc)
        else:
            if waiter is not None and not waiter.cancelled():
                waiter.set_result(None)

    def _call(self, cb, *data):
        if self._pending_calls is not None:
            self._pending_calls.append((cb, data))
        else:
            self._loop.call_soon(cb, *data)

    def _pipe_connection_lost(self, fd, exc):
        self._call(self._protocol.pipe_connection_lost, fd, exc)
        self._try_finish()

    def _pipe_data_received(self, fd, data):
        self._call(self._protocol.pipe_data_received, fd, data)

    def _process_exited(self, returncode):
        assert returncode is not None, returncode
        assert self._returncode is None, self._returncode
        if self._loop.get_debug():
            logger.info('%r exited with return code %r', self, returncode)
        self._returncode = returncode
        if self._proc.returncode is None:
            # asyncio uses a child watcher: copy the status into the Popen
            # object. On Python 3.6, it is required to avoid a ResourceWarning.
            self._proc.returncode = returncode
        self._call(self._protocol.process_exited)
        self._try_finish()

        # wake up futures waiting for wait()
        for waiter in self._exit_waiters:
            if not waiter.cancelled():
                waiter.set_result(returncode)
        self._exit_waiters = None

    async def _wait(self):
        """Wait until the process exit and return the process return code.

        This method is a coroutine."""
        if self._returncode is not None:
            return self._returncode

        waiter = self._loop.create_future()
        self._exit_waiters.append(waiter)
        return await waiter

    def _try_finish(self):
        assert not self._finished
        if self._returncode is None:
            return
        if all(p is not None and p.disconnected
               for p in self._pipes.values()):
            self._finished = True
            self._call(self._call_connection_lost, None)

    def _call_connection_lost(self, exc):
        try:
            self._protocol.connection_lost(exc)
        finally:
            self._loop = None
            self._proc = None
            self._protocol = None


class WriteSubprocessPipeProto(protocols.BaseProtocol):

    def __init__(self, proc, fd):
        self.proc = proc
        self.fd = fd
        self.pipe = None
        self.disconnected = False

    def connection_made(self, transport):
        self.pipe = transport

    def __repr__(self):
        return f'<{self.__class__.__name__} fd={self.fd} pipe={self.pipe!r}>'

    def connection_lost(self, exc):
        self.disconnected = True
        self.proc._pipe_connection_lost(self.fd, exc)
        self.proc = None

    def pause_writing(self):
        self.proc._protocol.pause_writing()

    def resume_writing(self):
        self.proc._protocol.resume_writing()


class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
                              protocols.Protocol):

    def data_received(self, data):
        self.proc._pipe_data_received(self.fd, data)
PK[l5Z
�:�:
test_utils.pynu�[���"""Utilities shared by tests."""

import collections
import contextlib
import io
import logging
import os
import re
import socket
import socketserver
import sys
import tempfile
import threading
import time
import unittest
import weakref

from unittest import mock

from http.server import HTTPServer
from wsgiref.simple_server import WSGIRequestHandler, WSGIServer

try:
    import ssl
except ImportError:  # pragma: no cover
    ssl = None

from . import base_events
from . import compat
from . import events
from . import futures
from . import selectors
from . import tasks
from .coroutines import coroutine
from .log import logger
from test import support


if sys.platform == 'win32':  # pragma: no cover
    from .windows_utils import socketpair
else:
    from socket import socketpair  # pragma: no cover


def data_file(filename):
    if hasattr(support, 'TEST_HOME_DIR'):
        fullname = os.path.join(support.TEST_HOME_DIR, filename)
        if os.path.isfile(fullname):
            return fullname
    fullname = os.path.join(os.path.dirname(os.__file__), 'test', filename)
    if os.path.isfile(fullname):
        return fullname
    raise FileNotFoundError(filename)


ONLYCERT = data_file('ssl_cert.pem')
ONLYKEY = data_file('ssl_key.pem')


def dummy_ssl_context():
    if ssl is None:
        return None
    else:
        return ssl.SSLContext(ssl.PROTOCOL_SSLv23)


def run_briefly(loop):
    @coroutine
    def once():
        pass
    gen = once()
    t = loop.create_task(gen)
    # Don't log a warning if the task is not done after run_until_complete().
    # It occurs if the loop is stopped or if a task raises a BaseException.
    t._log_destroy_pending = False
    try:
        loop.run_until_complete(t)
    finally:
        gen.close()


def run_until(loop, pred, timeout=30):
    deadline = time.time() + timeout
    while not pred():
        if timeout is not None:
            timeout = deadline - time.time()
            if timeout <= 0:
                raise futures.TimeoutError()
        loop.run_until_complete(tasks.sleep(0.001, loop=loop))


def run_once(loop):
    """Legacy API to run once through the event loop.

    This is the recommended pattern for test code.  It will poll the
    selector once and run all callbacks scheduled in response to I/O
    events.
    """
    loop.call_soon(loop.stop)
    loop.run_forever()


class SilentWSGIRequestHandler(WSGIRequestHandler):

    def get_stderr(self):
        return io.StringIO()

    def log_message(self, format, *args):
        pass


class SilentWSGIServer(WSGIServer):

    request_timeout = 2

    def get_request(self):
        request, client_addr = super().get_request()
        request.settimeout(self.request_timeout)
        return request, client_addr

    def handle_error(self, request, client_address):
        pass


class SSLWSGIServerMixin:

    def finish_request(self, request, client_address):
        # The relative location of our test directory (which
        # contains the ssl key and certificate files) differs
        # between the stdlib and stand-alone asyncio.
        # Prefer our own if we can find it.
        keyfile = ONLYKEY
        certfile = ONLYCERT
        context = ssl.SSLContext()
        context.load_cert_chain(certfile, keyfile)

        ssock = context.wrap_socket(request, server_side=True)
        try:
            self.RequestHandlerClass(ssock, client_address, self)
            ssock.close()
        except OSError:
            # maybe socket has been closed by peer
            pass


class SSLWSGIServer(SSLWSGIServerMixin, SilentWSGIServer):
    pass


def _run_test_server(*, address, use_ssl=False, server_cls, server_ssl_cls):

    def app(environ, start_response):
        status = '200 OK'
        headers = [('Content-type', 'text/plain')]
        start_response(status, headers)
        return [b'Test message']

    # Run the test WSGI server in a separate thread in order not to
    # interfere with event handling in the main thread
    server_class = server_ssl_cls if use_ssl else server_cls
    httpd = server_class(address, SilentWSGIRequestHandler)
    httpd.set_app(app)
    httpd.address = httpd.server_address
    server_thread = threading.Thread(
        target=lambda: httpd.serve_forever(poll_interval=0.05))
    server_thread.start()
    try:
        yield httpd
    finally:
        httpd.shutdown()
        httpd.server_close()
        server_thread.join()


if hasattr(socket, 'AF_UNIX'):

    class UnixHTTPServer(socketserver.UnixStreamServer, HTTPServer):

        def server_bind(self):
            socketserver.UnixStreamServer.server_bind(self)
            self.server_name = '127.0.0.1'
            self.server_port = 80


    class UnixWSGIServer(UnixHTTPServer, WSGIServer):

        request_timeout = 2

        def server_bind(self):
            UnixHTTPServer.server_bind(self)
            self.setup_environ()

        def get_request(self):
            request, client_addr = super().get_request()
            request.settimeout(self.request_timeout)
            # Code in the stdlib expects that get_request
            # will return a socket and a tuple (host, port).
            # However, this isn't true for UNIX sockets,
            # as the second return value will be a path;
            # hence we return some fake data sufficient
            # to get the tests going
            return request, ('127.0.0.1', '')


    class SilentUnixWSGIServer(UnixWSGIServer):

        def handle_error(self, request, client_address):
            pass


    class UnixSSLWSGIServer(SSLWSGIServerMixin, SilentUnixWSGIServer):
        pass


    def gen_unix_socket_path():
        with tempfile.NamedTemporaryFile() as file:
            return file.name


    @contextlib.contextmanager
    def unix_socket_path():
        path = gen_unix_socket_path()
        try:
            yield path
        finally:
            try:
                os.unlink(path)
            except OSError:
                pass


    @contextlib.contextmanager
    def run_test_unix_server(*, use_ssl=False):
        with unix_socket_path() as path:
            yield from _run_test_server(address=path, use_ssl=use_ssl,
                                        server_cls=SilentUnixWSGIServer,
                                        server_ssl_cls=UnixSSLWSGIServer)


@contextlib.contextmanager
def run_test_server(*, host='127.0.0.1', port=0, use_ssl=False):
    yield from _run_test_server(address=(host, port), use_ssl=use_ssl,
                                server_cls=SilentWSGIServer,
                                server_ssl_cls=SSLWSGIServer)


def make_test_protocol(base):
    dct = {}
    for name in dir(base):
        if name.startswith('__') and name.endswith('__'):
            # skip magic names
            continue
        dct[name] = MockCallback(return_value=None)
    return type('TestProtocol', (base,) + base.__bases__, dct)()


class TestSelector(selectors.BaseSelector):

    def __init__(self):
        self.keys = {}

    def register(self, fileobj, events, data=None):
        key = selectors.SelectorKey(fileobj, 0, events, data)
        self.keys[fileobj] = key
        return key

    def unregister(self, fileobj):
        return self.keys.pop(fileobj)

    def select(self, timeout):
        return []

    def get_map(self):
        return self.keys


class TestLoop(base_events.BaseEventLoop):
    """Loop for unittests.

    It manages self time directly.
    If something scheduled to be executed later then
    on next loop iteration after all ready handlers done
    generator passed to __init__ is calling.

    Generator should be like this:

        def gen():
            ...
            when = yield ...
            ... = yield time_advance

    Value returned by yield is absolute time of next scheduled handler.
    Value passed to yield is time advance to move loop's time forward.
    """

    def __init__(self, gen=None):
        super().__init__()

        if gen is None:
            def gen():
                yield
            self._check_on_close = False
        else:
            self._check_on_close = True

        self._gen = gen()
        next(self._gen)
        self._time = 0
        self._clock_resolution = 1e-9
        self._timers = []
        self._selector = TestSelector()

        self.readers = {}
        self.writers = {}
        self.reset_counters()

        self._transports = weakref.WeakValueDictionary()

    def time(self):
        return self._time

    def advance_time(self, advance):
        """Move test time forward."""
        if advance:
            self._time += advance

    def close(self):
        super().close()
        if self._check_on_close:
            try:
                self._gen.send(0)
            except StopIteration:
                pass
            else:  # pragma: no cover
                raise AssertionError("Time generator is not finished")

    def _add_reader(self, fd, callback, *args):
        self.readers[fd] = events.Handle(callback, args, self)

    def _remove_reader(self, fd):
        self.remove_reader_count[fd] += 1
        if fd in self.readers:
            del self.readers[fd]
            return True
        else:
            return False

    def assert_reader(self, fd, callback, *args):
        if fd not in self.readers:
            raise AssertionError(f'fd {fd} is not registered')
        handle = self.readers[fd]
        if handle._callback != callback:
            raise AssertionError(
                f'unexpected callback: {handle._callback} != {callback}')
        if handle._args != args:
            raise AssertionError(
                f'unexpected callback args: {handle._args} != {args}')

    def assert_no_reader(self, fd):
        if fd in self.readers:
            raise AssertionError(f'fd {fd} is registered')

    def _add_writer(self, fd, callback, *args):
        self.writers[fd] = events.Handle(callback, args, self)

    def _remove_writer(self, fd):
        self.remove_writer_count[fd] += 1
        if fd in self.writers:
            del self.writers[fd]
            return True
        else:
            return False

    def assert_writer(self, fd, callback, *args):
        assert fd in self.writers, 'fd {} is not registered'.format(fd)
        handle = self.writers[fd]
        assert handle._callback == callback, '{!r} != {!r}'.format(
            handle._callback, callback)
        assert handle._args == args, '{!r} != {!r}'.format(
            handle._args, args)

    def _ensure_fd_no_transport(self, fd):
        try:
            transport = self._transports[fd]
        except KeyError:
            pass
        else:
            raise RuntimeError(
                'File descriptor {!r} is used by transport {!r}'.format(
                    fd, transport))

    def add_reader(self, fd, callback, *args):
        """Add a reader callback."""
        self._ensure_fd_no_transport(fd)
        return self._add_reader(fd, callback, *args)

    def remove_reader(self, fd):
        """Remove a reader callback."""
        self._ensure_fd_no_transport(fd)
        return self._remove_reader(fd)

    def add_writer(self, fd, callback, *args):
        """Add a writer callback.."""
        self._ensure_fd_no_transport(fd)
        return self._add_writer(fd, callback, *args)

    def remove_writer(self, fd):
        """Remove a writer callback."""
        self._ensure_fd_no_transport(fd)
        return self._remove_writer(fd)

    def reset_counters(self):
        self.remove_reader_count = collections.defaultdict(int)
        self.remove_writer_count = collections.defaultdict(int)

    def _run_once(self):
        super()._run_once()
        for when in self._timers:
            advance = self._gen.send(when)
            self.advance_time(advance)
        self._timers = []

    def call_at(self, when, callback, *args):
        self._timers.append(when)
        return super().call_at(when, callback, *args)

    def _process_events(self, event_list):
        return

    def _write_to_self(self):
        pass


def MockCallback(**kwargs):
    return mock.Mock(spec=['__call__'], **kwargs)


class MockPattern(str):
    """A regex based str with a fuzzy __eq__.

    Use this helper with 'mock.assert_called_with', or anywhere
    where a regex comparison between strings is needed.

    For instance:
       mock_call.assert_called_with(MockPattern('spam.*ham'))
    """
    def __eq__(self, other):
        return bool(re.search(str(self), other, re.S))


def get_function_source(func):
    source = events._get_function_source(func)
    if source is None:
        raise ValueError("unable to get the source of %r" % (func,))
    return source


class TestCase(unittest.TestCase):
    @staticmethod
    def close_loop(loop):
        executor = loop._default_executor
        if executor is not None:
            executor.shutdown(wait=True)
        loop.close()

    def set_event_loop(self, loop, *, cleanup=True):
        assert loop is not None
        # ensure that the event loop is passed explicitly in asyncio
        events.set_event_loop(None)
        if cleanup:
            self.addCleanup(self.close_loop, loop)

    def new_test_loop(self, gen=None):
        loop = TestLoop(gen)
        self.set_event_loop(loop)
        return loop

    def unpatch_get_running_loop(self):
        events._get_running_loop = self._get_running_loop

    def setUp(self):
        self._get_running_loop = events._get_running_loop
        events._get_running_loop = lambda: None
        self._thread_cleanup = support.threading_setup()

    def tearDown(self):
        self.unpatch_get_running_loop()

        events.set_event_loop(None)

        # Detect CPython bug #23353: ensure that yield/yield-from is not used
        # in an except block of a generator
        self.assertEqual(sys.exc_info(), (None, None, None))

        self.doCleanups()
        support.threading_cleanup(*self._thread_cleanup)
        support.reap_children()

    if not compat.PY34:
        # Python 3.3 compatibility
        def subTest(self, *args, **kwargs):
            class EmptyCM:
                def __enter__(self):
                    pass
                def __exit__(self, *exc):
                    pass
            return EmptyCM()


@contextlib.contextmanager
def disable_logger():
    """Context manager to disable asyncio logger.

    For example, it can be used to ignore warnings in debug mode.
    """
    old_level = logger.level
    try:
        logger.setLevel(logging.CRITICAL+1)
        yield
    finally:
        logger.setLevel(old_level)


def mock_nonblocking_socket(proto=socket.IPPROTO_TCP, type=socket.SOCK_STREAM,
                            family=socket.AF_INET):
    """Create a mock of a non-blocking socket."""
    sock = mock.MagicMock(socket.socket)
    sock.proto = proto
    sock.type = type
    sock.family = family
    sock.gettimeout.return_value = 0.0
    return sock


def force_legacy_ssl_support():
    return mock.patch('asyncio.sslproto._is_sslproto_available',
                      return_value=False)
PK[�pCP	compat.pynu�[���"""Compatibility helpers for the different Python versions."""

import sys

PY34 = sys.version_info >= (3, 4)
PY35 = sys.version_info >= (3, 5)
PY352 = sys.version_info >= (3, 5, 2)


def flatten_list_bytes(list_of_data):
    """Concatenate a sequence of bytes-like objects."""
    if not PY34:
        # On Python 3.3 and older, bytes.join() doesn't handle
        # memoryview.
        list_of_data = (
            bytes(data) if isinstance(data, memoryview) else data
            for data in list_of_data)
    return b''.join(list_of_data)
PK[=�|C|Clocks.pynu�[���"""Synchronization primitives."""

__all__ = ('Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore')

import collections
import types
import warnings

from . import events
from . import futures
from . import exceptions
from .import coroutines


class _ContextManager:
    """Context manager.

    This enables the following idiom for acquiring and releasing a
    lock around a block:

        with (yield from lock):
            <block>

    while failing loudly when accidentally using:

        with lock:
            <block>

    Deprecated, use 'async with' statement:
        async with lock:
            <block>
    """

    def __init__(self, lock):
        self._lock = lock

    def __enter__(self):
        # We have no use for the "as ..."  clause in the with
        # statement for locks.
        return None

    def __exit__(self, *args):
        try:
            self._lock.release()
        finally:
            self._lock = None  # Crudely prevent reuse.


class _ContextManagerMixin:
    def __enter__(self):
        raise RuntimeError(
            '"yield from" should be used as context manager expression')

    def __exit__(self, *args):
        # This must exist because __enter__ exists, even though that
        # always raises; that's how the with-statement works.
        pass

    @types.coroutine
    def __iter__(self):
        # This is not a coroutine.  It is meant to enable the idiom:
        #
        #     with (yield from lock):
        #         <block>
        #
        # as an alternative to:
        #
        #     yield from lock.acquire()
        #     try:
        #         <block>
        #     finally:
        #         lock.release()
        # Deprecated, use 'async with' statement:
        #     async with lock:
        #         <block>
        warnings.warn("'with (yield from lock)' is deprecated "
                      "use 'async with lock' instead",
                      DeprecationWarning, stacklevel=2)
        yield from self.acquire()
        return _ContextManager(self)

    # The flag is needed for legacy asyncio.iscoroutine()
    __iter__._is_coroutine = coroutines._is_coroutine

    async def __acquire_ctx(self):
        await self.acquire()
        return _ContextManager(self)

    def __await__(self):
        warnings.warn("'with await lock' is deprecated "
                      "use 'async with lock' instead",
                      DeprecationWarning, stacklevel=2)
        # To make "with await lock" work.
        return self.__acquire_ctx().__await__()

    async def __aenter__(self):
        await self.acquire()
        # We have no use for the "as ..."  clause in the with
        # statement for locks.
        return None

    async def __aexit__(self, exc_type, exc, tb):
        self.release()


class Lock(_ContextManagerMixin):
    """Primitive lock objects.

    A primitive lock is a synchronization primitive that is not owned
    by a particular coroutine when locked.  A primitive lock is in one
    of two states, 'locked' or 'unlocked'.

    It is created in the unlocked state.  It has two basic methods,
    acquire() and release().  When the state is unlocked, acquire()
    changes the state to locked and returns immediately.  When the
    state is locked, acquire() blocks until a call to release() in
    another coroutine changes it to unlocked, then the acquire() call
    resets it to locked and returns.  The release() method should only
    be called in the locked state; it changes the state to unlocked
    and returns immediately.  If an attempt is made to release an
    unlocked lock, a RuntimeError will be raised.

    When more than one coroutine is blocked in acquire() waiting for
    the state to turn to unlocked, only one coroutine proceeds when a
    release() call resets the state to unlocked; first coroutine which
    is blocked in acquire() is being processed.

    acquire() is a coroutine and should be called with 'await'.

    Locks also support the asynchronous context management protocol.
    'async with lock' statement should be used.

    Usage:

        lock = Lock()
        ...
        await lock.acquire()
        try:
            ...
        finally:
            lock.release()

    Context manager usage:

        lock = Lock()
        ...
        async with lock:
             ...

    Lock objects can be tested for locking state:

        if not lock.locked():
           await lock.acquire()
        else:
           # lock is acquired
           ...

    """

    def __init__(self, *, loop=None):
        self._waiters = None
        self._locked = False
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)

    def __repr__(self):
        res = super().__repr__()
        extra = 'locked' if self._locked else 'unlocked'
        if self._waiters:
            extra = f'{extra}, waiters:{len(self._waiters)}'
        return f'<{res[1:-1]} [{extra}]>'

    def locked(self):
        """Return True if lock is acquired."""
        return self._locked

    async def acquire(self):
        """Acquire a lock.

        This method blocks until the lock is unlocked, then sets it to
        locked and returns True.
        """
        if (not self._locked and (self._waiters is None or
                all(w.cancelled() for w in self._waiters))):
            self._locked = True
            return True

        if self._waiters is None:
            self._waiters = collections.deque()
        fut = self._loop.create_future()
        self._waiters.append(fut)

        # Finally block should be called before the CancelledError
        # handling as we don't want CancelledError to call
        # _wake_up_first() and attempt to wake up itself.
        try:
            try:
                await fut
            finally:
                self._waiters.remove(fut)
        except exceptions.CancelledError:
            if not self._locked:
                self._wake_up_first()
            raise

        self._locked = True
        return True

    def release(self):
        """Release a lock.

        When the lock is locked, reset it to unlocked, and return.
        If any other coroutines are blocked waiting for the lock to become
        unlocked, allow exactly one of them to proceed.

        When invoked on an unlocked lock, a RuntimeError is raised.

        There is no return value.
        """
        if self._locked:
            self._locked = False
            self._wake_up_first()
        else:
            raise RuntimeError('Lock is not acquired.')

    def _wake_up_first(self):
        """Wake up the first waiter if it isn't done."""
        if not self._waiters:
            return
        try:
            fut = next(iter(self._waiters))
        except StopIteration:
            return

        # .done() necessarily means that a waiter will wake up later on and
        # either take the lock, or, if it was cancelled and lock wasn't
        # taken already, will hit this again and wake up a new waiter.
        if not fut.done():
            fut.set_result(True)


class Event:
    """Asynchronous equivalent to threading.Event.

    Class implementing event objects. An event manages a flag that can be set
    to true with the set() method and reset to false with the clear() method.
    The wait() method blocks until the flag is true. The flag is initially
    false.
    """

    def __init__(self, *, loop=None):
        self._waiters = collections.deque()
        self._value = False
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)

    def __repr__(self):
        res = super().__repr__()
        extra = 'set' if self._value else 'unset'
        if self._waiters:
            extra = f'{extra}, waiters:{len(self._waiters)}'
        return f'<{res[1:-1]} [{extra}]>'

    def is_set(self):
        """Return True if and only if the internal flag is true."""
        return self._value

    def set(self):
        """Set the internal flag to true. All coroutines waiting for it to
        become true are awakened. Coroutine that call wait() once the flag is
        true will not block at all.
        """
        if not self._value:
            self._value = True

            for fut in self._waiters:
                if not fut.done():
                    fut.set_result(True)

    def clear(self):
        """Reset the internal flag to false. Subsequently, coroutines calling
        wait() will block until set() is called to set the internal flag
        to true again."""
        self._value = False

    async def wait(self):
        """Block until the internal flag is true.

        If the internal flag is true on entry, return True
        immediately.  Otherwise, block until another coroutine calls
        set() to set the flag to true, then return True.
        """
        if self._value:
            return True

        fut = self._loop.create_future()
        self._waiters.append(fut)
        try:
            await fut
            return True
        finally:
            self._waiters.remove(fut)


class Condition(_ContextManagerMixin):
    """Asynchronous equivalent to threading.Condition.

    This class implements condition variable objects. A condition variable
    allows one or more coroutines to wait until they are notified by another
    coroutine.

    A new Lock object is created and used as the underlying lock.
    """

    def __init__(self, lock=None, *, loop=None):
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)

        if lock is None:
            lock = Lock(loop=loop)
        elif lock._loop is not self._loop:
            raise ValueError("loop argument must agree with lock")

        self._lock = lock
        # Export the lock's locked(), acquire() and release() methods.
        self.locked = lock.locked
        self.acquire = lock.acquire
        self.release = lock.release

        self._waiters = collections.deque()

    def __repr__(self):
        res = super().__repr__()
        extra = 'locked' if self.locked() else 'unlocked'
        if self._waiters:
            extra = f'{extra}, waiters:{len(self._waiters)}'
        return f'<{res[1:-1]} [{extra}]>'

    async def wait(self):
        """Wait until notified.

        If the calling coroutine has not acquired the lock when this
        method is called, a RuntimeError is raised.

        This method releases the underlying lock, and then blocks
        until it is awakened by a notify() or notify_all() call for
        the same condition variable in another coroutine.  Once
        awakened, it re-acquires the lock and returns True.
        """
        if not self.locked():
            raise RuntimeError('cannot wait on un-acquired lock')

        self.release()
        try:
            fut = self._loop.create_future()
            self._waiters.append(fut)
            try:
                await fut
                return True
            finally:
                self._waiters.remove(fut)

        finally:
            # Must reacquire lock even if wait is cancelled
            cancelled = False
            while True:
                try:
                    await self.acquire()
                    break
                except exceptions.CancelledError:
                    cancelled = True

            if cancelled:
                raise exceptions.CancelledError

    async def wait_for(self, predicate):
        """Wait until a predicate becomes true.

        The predicate should be a callable which result will be
        interpreted as a boolean value.  The final predicate value is
        the return value.
        """
        result = predicate()
        while not result:
            await self.wait()
            result = predicate()
        return result

    def notify(self, n=1):
        """By default, wake up one coroutine waiting on this condition, if any.
        If the calling coroutine has not acquired the lock when this method
        is called, a RuntimeError is raised.

        This method wakes up at most n of the coroutines waiting for the
        condition variable; it is a no-op if no coroutines are waiting.

        Note: an awakened coroutine does not actually return from its
        wait() call until it can reacquire the lock. Since notify() does
        not release the lock, its caller should.
        """
        if not self.locked():
            raise RuntimeError('cannot notify on un-acquired lock')

        idx = 0
        for fut in self._waiters:
            if idx >= n:
                break

            if not fut.done():
                idx += 1
                fut.set_result(False)

    def notify_all(self):
        """Wake up all threads waiting on this condition. This method acts
        like notify(), but wakes up all waiting threads instead of one. If the
        calling thread has not acquired the lock when this method is called,
        a RuntimeError is raised.
        """
        self.notify(len(self._waiters))


class Semaphore(_ContextManagerMixin):
    """A Semaphore implementation.

    A semaphore manages an internal counter which is decremented by each
    acquire() call and incremented by each release() call. The counter
    can never go below zero; when acquire() finds that it is zero, it blocks,
    waiting until some other thread calls release().

    Semaphores also support the context management protocol.

    The optional argument gives the initial value for the internal
    counter; it defaults to 1. If the value given is less than 0,
    ValueError is raised.
    """

    def __init__(self, value=1, *, loop=None):
        if value < 0:
            raise ValueError("Semaphore initial value must be >= 0")
        self._value = value
        self._waiters = collections.deque()
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)

    def __repr__(self):
        res = super().__repr__()
        extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
        if self._waiters:
            extra = f'{extra}, waiters:{len(self._waiters)}'
        return f'<{res[1:-1]} [{extra}]>'

    def _wake_up_next(self):
        while self._waiters:
            waiter = self._waiters.popleft()
            if not waiter.done():
                waiter.set_result(None)
                return

    def locked(self):
        """Returns True if semaphore can not be acquired immediately."""
        return self._value == 0

    async def acquire(self):
        """Acquire a semaphore.

        If the internal counter is larger than zero on entry,
        decrement it by one and return True immediately.  If it is
        zero on entry, block, waiting until some other coroutine has
        called release() to make it larger than 0, and then return
        True.
        """
        while self._value <= 0:
            fut = self._loop.create_future()
            self._waiters.append(fut)
            try:
                await fut
            except:
                # See the similar code in Queue.get.
                fut.cancel()
                if self._value > 0 and not fut.cancelled():
                    self._wake_up_next()
                raise
        self._value -= 1
        return True

    def release(self):
        """Release a semaphore, incrementing the internal counter by one.
        When it was zero on entry and another coroutine is waiting for it to
        become larger than zero again, wake up that coroutine.
        """
        self._value += 1
        self._wake_up_next()


class BoundedSemaphore(Semaphore):
    """A bounded semaphore implementation.

    This raises ValueError in release() if it would increase the value
    above the initial value.
    """

    def __init__(self, value=1, *, loop=None):
        if loop:
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)

        self._bound_value = value
        super().__init__(value, loop=loop)

    def release(self):
        if self._value >= self._bound_value:
            raise ValueError('BoundedSemaphore released too many times')
        super().release()
PK[V�CC��windows_utils.pynu�[���"""Various Windows specific bits and pieces."""

import sys

if sys.platform != 'win32':  # pragma: no cover
    raise ImportError('win32 only')

import _winapi
import itertools
import msvcrt
import os
import subprocess
import tempfile
import warnings


__all__ = 'pipe', 'Popen', 'PIPE', 'PipeHandle'


# Constants/globals


BUFSIZE = 8192
PIPE = subprocess.PIPE
STDOUT = subprocess.STDOUT
_mmap_counter = itertools.count()


# Replacement for os.pipe() using handles instead of fds


def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE):
    """Like os.pipe() but with overlapped support and using handles not fds."""
    address = tempfile.mktemp(
        prefix=r'\\.\pipe\python-pipe-{:d}-{:d}-'.format(
            os.getpid(), next(_mmap_counter)))

    if duplex:
        openmode = _winapi.PIPE_ACCESS_DUPLEX
        access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
        obsize, ibsize = bufsize, bufsize
    else:
        openmode = _winapi.PIPE_ACCESS_INBOUND
        access = _winapi.GENERIC_WRITE
        obsize, ibsize = 0, bufsize

    openmode |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE

    if overlapped[0]:
        openmode |= _winapi.FILE_FLAG_OVERLAPPED

    if overlapped[1]:
        flags_and_attribs = _winapi.FILE_FLAG_OVERLAPPED
    else:
        flags_and_attribs = 0

    h1 = h2 = None
    try:
        h1 = _winapi.CreateNamedPipe(
            address, openmode, _winapi.PIPE_WAIT,
            1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)

        h2 = _winapi.CreateFile(
            address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
            flags_and_attribs, _winapi.NULL)

        ov = _winapi.ConnectNamedPipe(h1, overlapped=True)
        ov.GetOverlappedResult(True)
        return h1, h2
    except:
        if h1 is not None:
            _winapi.CloseHandle(h1)
        if h2 is not None:
            _winapi.CloseHandle(h2)
        raise


# Wrapper for a pipe handle


class PipeHandle:
    """Wrapper for an overlapped pipe handle which is vaguely file-object like.

    The IOCP event loop can use these instead of socket objects.
    """
    def __init__(self, handle):
        self._handle = handle

    def __repr__(self):
        if self._handle is not None:
            handle = f'handle={self._handle!r}'
        else:
            handle = 'closed'
        return f'<{self.__class__.__name__} {handle}>'

    @property
    def handle(self):
        return self._handle

    def fileno(self):
        if self._handle is None:
            raise ValueError("I/O operation on closed pipe")
        return self._handle

    def close(self, *, CloseHandle=_winapi.CloseHandle):
        if self._handle is not None:
            CloseHandle(self._handle)
            self._handle = None

    def __del__(self, _warn=warnings.warn):
        if self._handle is not None:
            _warn(f"unclosed {self!r}", ResourceWarning, source=self)
            self.close()

    def __enter__(self):
        return self

    def __exit__(self, t, v, tb):
        self.close()


# Replacement for subprocess.Popen using overlapped pipe handles


class Popen(subprocess.Popen):
    """Replacement for subprocess.Popen using overlapped pipe handles.

    The stdin, stdout, stderr are None or instances of PipeHandle.
    """
    def __init__(self, args, stdin=None, stdout=None, stderr=None, **kwds):
        assert not kwds.get('universal_newlines')
        assert kwds.get('bufsize', 0) == 0
        stdin_rfd = stdout_wfd = stderr_wfd = None
        stdin_wh = stdout_rh = stderr_rh = None
        if stdin == PIPE:
            stdin_rh, stdin_wh = pipe(overlapped=(False, True), duplex=True)
            stdin_rfd = msvcrt.open_osfhandle(stdin_rh, os.O_RDONLY)
        else:
            stdin_rfd = stdin
        if stdout == PIPE:
            stdout_rh, stdout_wh = pipe(overlapped=(True, False))
            stdout_wfd = msvcrt.open_osfhandle(stdout_wh, 0)
        else:
            stdout_wfd = stdout
        if stderr == PIPE:
            stderr_rh, stderr_wh = pipe(overlapped=(True, False))
            stderr_wfd = msvcrt.open_osfhandle(stderr_wh, 0)
        elif stderr == STDOUT:
            stderr_wfd = stdout_wfd
        else:
            stderr_wfd = stderr
        try:
            super().__init__(args, stdin=stdin_rfd, stdout=stdout_wfd,
                             stderr=stderr_wfd, **kwds)
        except:
            for h in (stdin_wh, stdout_rh, stderr_rh):
                if h is not None:
                    _winapi.CloseHandle(h)
            raise
        else:
            if stdin_wh is not None:
                self.stdin = PipeHandle(stdin_wh)
            if stdout_rh is not None:
                self.stdout = PipeHandle(stdout_rh)
            if stderr_rh is not None:
                self.stderr = PipeHandle(stderr_rh)
        finally:
            if stdin == PIPE:
                os.close(stdin_rfd)
            if stdout == PIPE:
                os.close(stdout_wfd)
            if stderr == PIPE:
                os.close(stderr_wfd)
PK[l������tasks.pynu�[���"""Support for tasks, coroutines and the scheduler."""

__all__ = (
    'Task', 'create_task',
    'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
    'wait', 'wait_for', 'as_completed', 'sleep',
    'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
    'current_task', 'all_tasks',
    '_register_task', '_unregister_task', '_enter_task', '_leave_task',
)

import concurrent.futures
import contextvars
import functools
import inspect
import itertools
import types
import warnings
import weakref

from . import base_tasks
from . import coroutines
from . import events
from . import exceptions
from . import futures
from .coroutines import _is_coroutine

# Helper to generate new task names
# This uses itertools.count() instead of a "+= 1" operation because the latter
# is not thread safe. See bpo-11866 for a longer explanation.
_task_name_counter = itertools.count(1).__next__


def current_task(loop=None):
    """Return a currently executed task."""
    if loop is None:
        loop = events.get_running_loop()
    return _current_tasks.get(loop)


def all_tasks(loop=None):
    """Return a set of all tasks for the loop."""
    if loop is None:
        loop = events.get_running_loop()
    # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
    # thread while we do so. Therefore we cast it to list prior to filtering. The list
    # cast itself requires iteration, so we repeat it several times ignoring
    # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
    # details.
    i = 0
    while True:
        try:
            tasks = list(_all_tasks)
        except RuntimeError:
            i += 1
            if i >= 1000:
                raise
        else:
            break
    return {t for t in tasks
            if futures._get_loop(t) is loop and not t.done()}


def _all_tasks_compat(loop=None):
    # Different from "all_task()" by returning *all* Tasks, including
    # the completed ones.  Used to implement deprecated "Tasks.all_task()"
    # method.
    if loop is None:
        loop = events.get_event_loop()
    # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
    # thread while we do so. Therefore we cast it to list prior to filtering. The list
    # cast itself requires iteration, so we repeat it several times ignoring
    # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
    # details.
    i = 0
    while True:
        try:
            tasks = list(_all_tasks)
        except RuntimeError:
            i += 1
            if i >= 1000:
                raise
        else:
            break
    return {t for t in tasks if futures._get_loop(t) is loop}


def _set_task_name(task, name):
    if name is not None:
        try:
            set_name = task.set_name
        except AttributeError:
            pass
        else:
            set_name(name)


class Task(futures._PyFuture):  # Inherit Python Task implementation
                                # from a Python Future implementation.

    """A coroutine wrapped in a Future."""

    # An important invariant maintained while a Task not done:
    #
    # - Either _fut_waiter is None, and _step() is scheduled;
    # - or _fut_waiter is some Future, and _step() is *not* scheduled.
    #
    # The only transition from the latter to the former is through
    # _wakeup().  When _fut_waiter is not None, one of its callbacks
    # must be _wakeup().

    # If False, don't log a message if the task is destroyed whereas its
    # status is still pending
    _log_destroy_pending = True

    @classmethod
    def current_task(cls, loop=None):
        """Return the currently running task in an event loop or None.

        By default the current task for the current event loop is returned.

        None is returned when called not in the context of a Task.
        """
        warnings.warn("Task.current_task() is deprecated since Python 3.7, "
                      "use asyncio.current_task() instead",
                      DeprecationWarning,
                      stacklevel=2)
        if loop is None:
            loop = events.get_event_loop()
        return current_task(loop)

    @classmethod
    def all_tasks(cls, loop=None):
        """Return a set of all tasks for an event loop.

        By default all tasks for the current event loop are returned.
        """
        warnings.warn("Task.all_tasks() is deprecated since Python 3.7, "
                      "use asyncio.all_tasks() instead",
                      DeprecationWarning,
                      stacklevel=2)
        return _all_tasks_compat(loop)

    def __init__(self, coro, *, loop=None, name=None):
        super().__init__(loop=loop)
        if self._source_traceback:
            del self._source_traceback[-1]
        if not coroutines.iscoroutine(coro):
            # raise after Future.__init__(), attrs are required for __del__
            # prevent logging for pending task in __del__
            self._log_destroy_pending = False
            raise TypeError(f"a coroutine was expected, got {coro!r}")

        if name is None:
            self._name = f'Task-{_task_name_counter()}'
        else:
            self._name = str(name)

        self._must_cancel = False
        self._fut_waiter = None
        self._coro = coro
        self._context = contextvars.copy_context()

        self._loop.call_soon(self.__step, context=self._context)
        _register_task(self)

    def __del__(self):
        if self._state == futures._PENDING and self._log_destroy_pending:
            context = {
                'task': self,
                'message': 'Task was destroyed but it is pending!',
            }
            if self._source_traceback:
                context['source_traceback'] = self._source_traceback
            self._loop.call_exception_handler(context)
        super().__del__()

    def _repr_info(self):
        return base_tasks._task_repr_info(self)

    def get_coro(self):
        return self._coro

    def get_name(self):
        return self._name

    def set_name(self, value):
        self._name = str(value)

    def set_result(self, result):
        raise RuntimeError('Task does not support set_result operation')

    def set_exception(self, exception):
        raise RuntimeError('Task does not support set_exception operation')

    def get_stack(self, *, limit=None):
        """Return the list of stack frames for this task's coroutine.

        If the coroutine is not done, this returns the stack where it is
        suspended.  If the coroutine has completed successfully or was
        cancelled, this returns an empty list.  If the coroutine was
        terminated by an exception, this returns the list of traceback
        frames.

        The frames are always ordered from oldest to newest.

        The optional limit gives the maximum number of frames to
        return; by default all available frames are returned.  Its
        meaning differs depending on whether a stack or a traceback is
        returned: the newest frames of a stack are returned, but the
        oldest frames of a traceback are returned.  (This matches the
        behavior of the traceback module.)

        For reasons beyond our control, only one stack frame is
        returned for a suspended coroutine.
        """
        return base_tasks._task_get_stack(self, limit)

    def print_stack(self, *, limit=None, file=None):
        """Print the stack or traceback for this task's coroutine.

        This produces output similar to that of the traceback module,
        for the frames retrieved by get_stack().  The limit argument
        is passed to get_stack().  The file argument is an I/O stream
        to which the output is written; by default output is written
        to sys.stderr.
        """
        return base_tasks._task_print_stack(self, limit, file)

    def cancel(self):
        """Request that this task cancel itself.

        This arranges for a CancelledError to be thrown into the
        wrapped coroutine on the next cycle through the event loop.
        The coroutine then has a chance to clean up or even deny
        the request using try/except/finally.

        Unlike Future.cancel, this does not guarantee that the
        task will be cancelled: the exception might be caught and
        acted upon, delaying cancellation of the task or preventing
        cancellation completely.  The task may also return a value or
        raise a different exception.

        Immediately after this method is called, Task.cancelled() will
        not return True (unless the task was already cancelled).  A
        task will be marked as cancelled when the wrapped coroutine
        terminates with a CancelledError exception (even if cancel()
        was not called).
        """
        self._log_traceback = False
        if self.done():
            return False
        if self._fut_waiter is not None:
            if self._fut_waiter.cancel():
                # Leave self._fut_waiter; it may be a Task that
                # catches and ignores the cancellation so we may have
                # to cancel it again later.
                return True
        # It must be the case that self.__step is already scheduled.
        self._must_cancel = True
        return True

    def __step(self, exc=None):
        if self.done():
            raise exceptions.InvalidStateError(
                f'_step(): already done: {self!r}, {exc!r}')
        if self._must_cancel:
            if not isinstance(exc, exceptions.CancelledError):
                exc = exceptions.CancelledError()
            self._must_cancel = False
        coro = self._coro
        self._fut_waiter = None

        _enter_task(self._loop, self)
        # Call either coro.throw(exc) or coro.send(None).
        try:
            if exc is None:
                # We use the `send` method directly, because coroutines
                # don't have `__iter__` and `__next__` methods.
                result = coro.send(None)
            else:
                result = coro.throw(exc)
        except StopIteration as exc:
            if self._must_cancel:
                # Task is cancelled right before coro stops.
                self._must_cancel = False
                super().cancel()
            else:
                super().set_result(exc.value)
        except exceptions.CancelledError:
            super().cancel()  # I.e., Future.cancel(self).
        except (KeyboardInterrupt, SystemExit) as exc:
            super().set_exception(exc)
            raise
        except BaseException as exc:
            super().set_exception(exc)
        else:
            blocking = getattr(result, '_asyncio_future_blocking', None)
            if blocking is not None:
                # Yielded Future must come from Future.__iter__().
                if futures._get_loop(result) is not self._loop:
                    new_exc = RuntimeError(
                        f'Task {self!r} got Future '
                        f'{result!r} attached to a different loop')
                    self._loop.call_soon(
                        self.__step, new_exc, context=self._context)
                elif blocking:
                    if result is self:
                        new_exc = RuntimeError(
                            f'Task cannot await on itself: {self!r}')
                        self._loop.call_soon(
                            self.__step, new_exc, context=self._context)
                    else:
                        result._asyncio_future_blocking = False
                        result.add_done_callback(
                            self.__wakeup, context=self._context)
                        self._fut_waiter = result
                        if self._must_cancel:
                            if self._fut_waiter.cancel():
                                self._must_cancel = False
                else:
                    new_exc = RuntimeError(
                        f'yield was used instead of yield from '
                        f'in task {self!r} with {result!r}')
                    self._loop.call_soon(
                        self.__step, new_exc, context=self._context)

            elif result is None:
                # Bare yield relinquishes control for one event loop iteration.
                self._loop.call_soon(self.__step, context=self._context)
            elif inspect.isgenerator(result):
                # Yielding a generator is just wrong.
                new_exc = RuntimeError(
                    f'yield was used instead of yield from for '
                    f'generator in task {self!r} with {result!r}')
                self._loop.call_soon(
                    self.__step, new_exc, context=self._context)
            else:
                # Yielding something else is an error.
                new_exc = RuntimeError(f'Task got bad yield: {result!r}')
                self._loop.call_soon(
                    self.__step, new_exc, context=self._context)
        finally:
            _leave_task(self._loop, self)
            self = None  # Needed to break cycles when an exception occurs.

    def __wakeup(self, future):
        try:
            future.result()
        except BaseException as exc:
            # This may also be a cancellation.
            self.__step(exc)
        else:
            # Don't pass the value of `future.result()` explicitly,
            # as `Future.__iter__` and `Future.__await__` don't need it.
            # If we call `_step(value, None)` instead of `_step()`,
            # Python eval loop would use `.send(value)` method call,
            # instead of `__next__()`, which is slower for futures
            # that return non-generator iterators from their `__iter__`.
            self.__step()
        self = None  # Needed to break cycles when an exception occurs.


_PyTask = Task


try:
    import _asyncio
except ImportError:
    pass
else:
    # _CTask is needed for tests.
    Task = _CTask = _asyncio.Task


def create_task(coro, *, name=None):
    """Schedule the execution of a coroutine object in a spawn task.

    Return a Task object.
    """
    loop = events.get_running_loop()
    task = loop.create_task(coro)
    _set_task_name(task, name)
    return task


# wait() and as_completed() similar to those in PEP 3148.

FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
ALL_COMPLETED = concurrent.futures.ALL_COMPLETED


async def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
    """Wait for the Futures and coroutines given by fs to complete.

    The fs iterable must not be empty.

    Coroutines will be wrapped in Tasks.

    Returns two sets of Future: (done, pending).

    Usage:

        done, pending = await asyncio.wait(fs)

    Note: This does not raise TimeoutError! Futures that aren't done
    when the timeout occurs are returned in the second set.
    """
    if futures.isfuture(fs) or coroutines.iscoroutine(fs):
        raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
    if not fs:
        raise ValueError('Set of coroutines/Futures is empty.')
    if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
        raise ValueError(f'Invalid return_when value: {return_when}')

    if loop is None:
        loop = events.get_running_loop()
    else:
        warnings.warn("The loop argument is deprecated since Python 3.8, "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning, stacklevel=2)

    fs = {ensure_future(f, loop=loop) for f in set(fs)}

    return await _wait(fs, timeout, return_when, loop)


def _release_waiter(waiter, *args):
    if not waiter.done():
        waiter.set_result(None)


async def wait_for(fut, timeout, *, loop=None):
    """Wait for the single Future or coroutine to complete, with timeout.

    Coroutine will be wrapped in Task.

    Returns result of the Future or coroutine.  When a timeout occurs,
    it cancels the task and raises TimeoutError.  To avoid the task
    cancellation, wrap it in shield().

    If the wait is cancelled, the task is also cancelled.

    This function is a coroutine.
    """
    if loop is None:
        loop = events.get_running_loop()
    else:
        warnings.warn("The loop argument is deprecated since Python 3.8, "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning, stacklevel=2)

    if timeout is None:
        return await fut

    if timeout <= 0:
        fut = ensure_future(fut, loop=loop)

        if fut.done():
            return fut.result()

        await _cancel_and_wait(fut, loop=loop)
        try:
            fut.result()
        except exceptions.CancelledError as exc:
            raise exceptions.TimeoutError() from exc
        else:
            raise exceptions.TimeoutError()

    waiter = loop.create_future()
    timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
    cb = functools.partial(_release_waiter, waiter)

    fut = ensure_future(fut, loop=loop)
    fut.add_done_callback(cb)

    try:
        # wait until the future completes or the timeout
        try:
            await waiter
        except exceptions.CancelledError:
            if fut.done():
                return fut.result()
            else:
                fut.remove_done_callback(cb)
                # We must ensure that the task is not running
                # after wait_for() returns.
                # See https://bugs.python.org/issue32751
                await _cancel_and_wait(fut, loop=loop)
                raise

        if fut.done():
            return fut.result()
        else:
            fut.remove_done_callback(cb)
            # We must ensure that the task is not running
            # after wait_for() returns.
            # See https://bugs.python.org/issue32751
            await _cancel_and_wait(fut, loop=loop)
            raise exceptions.TimeoutError()
    finally:
        timeout_handle.cancel()


async def _wait(fs, timeout, return_when, loop):
    """Internal helper for wait().

    The fs argument must be a collection of Futures.
    """
    assert fs, 'Set of Futures is empty.'
    waiter = loop.create_future()
    timeout_handle = None
    if timeout is not None:
        timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
    counter = len(fs)

    def _on_completion(f):
        nonlocal counter
        counter -= 1
        if (counter <= 0 or
            return_when == FIRST_COMPLETED or
            return_when == FIRST_EXCEPTION and (not f.cancelled() and
                                                f.exception() is not None)):
            if timeout_handle is not None:
                timeout_handle.cancel()
            if not waiter.done():
                waiter.set_result(None)

    for f in fs:
        f.add_done_callback(_on_completion)

    try:
        await waiter
    finally:
        if timeout_handle is not None:
            timeout_handle.cancel()
        for f in fs:
            f.remove_done_callback(_on_completion)

    done, pending = set(), set()
    for f in fs:
        if f.done():
            done.add(f)
        else:
            pending.add(f)
    return done, pending


async def _cancel_and_wait(fut, loop):
    """Cancel the *fut* future or task and wait until it completes."""

    waiter = loop.create_future()
    cb = functools.partial(_release_waiter, waiter)
    fut.add_done_callback(cb)

    try:
        fut.cancel()
        # We cannot wait on *fut* directly to make
        # sure _cancel_and_wait itself is reliably cancellable.
        await waiter
    finally:
        fut.remove_done_callback(cb)


# This is *not* a @coroutine!  It is just an iterator (yielding Futures).
def as_completed(fs, *, loop=None, timeout=None):
    """Return an iterator whose values are coroutines.

    When waiting for the yielded coroutines you'll get the results (or
    exceptions!) of the original Futures (or coroutines), in the order
    in which and as soon as they complete.

    This differs from PEP 3148; the proper way to use this is:

        for f in as_completed(fs):
            result = await f  # The 'await' may raise.
            # Use result.

    If a timeout is specified, the 'await' will raise
    TimeoutError when the timeout occurs before all Futures are done.

    Note: The futures 'f' are not necessarily members of fs.
    """
    if futures.isfuture(fs) or coroutines.iscoroutine(fs):
        raise TypeError(f"expect an iterable of futures, not {type(fs).__name__}")

    from .queues import Queue  # Import here to avoid circular import problem.
    done = Queue(loop=loop)

    if loop is None:
        loop = events.get_event_loop()
    else:
        warnings.warn("The loop argument is deprecated since Python 3.8, "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning, stacklevel=2)
    todo = {ensure_future(f, loop=loop) for f in set(fs)}
    timeout_handle = None

    def _on_timeout():
        for f in todo:
            f.remove_done_callback(_on_completion)
            done.put_nowait(None)  # Queue a dummy value for _wait_for_one().
        todo.clear()  # Can't do todo.remove(f) in the loop.

    def _on_completion(f):
        if not todo:
            return  # _on_timeout() was here first.
        todo.remove(f)
        done.put_nowait(f)
        if not todo and timeout_handle is not None:
            timeout_handle.cancel()

    async def _wait_for_one():
        f = await done.get()
        if f is None:
            # Dummy value from _on_timeout().
            raise exceptions.TimeoutError
        return f.result()  # May raise f.exception().

    for f in todo:
        f.add_done_callback(_on_completion)
    if todo and timeout is not None:
        timeout_handle = loop.call_later(timeout, _on_timeout)
    for _ in range(len(todo)):
        yield _wait_for_one()


@types.coroutine
def __sleep0():
    """Skip one event loop run cycle.

    This is a private helper for 'asyncio.sleep()', used
    when the 'delay' is set to 0.  It uses a bare 'yield'
    expression (which Task.__step knows how to handle)
    instead of creating a Future object.
    """
    yield


async def sleep(delay, result=None, *, loop=None):
    """Coroutine that completes after a given time (in seconds)."""
    if delay <= 0:
        await __sleep0()
        return result

    if loop is None:
        loop = events.get_running_loop()
    else:
        warnings.warn("The loop argument is deprecated since Python 3.8, "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning, stacklevel=2)

    future = loop.create_future()
    h = loop.call_later(delay,
                        futures._set_result_unless_cancelled,
                        future, result)
    try:
        return await future
    finally:
        h.cancel()


def ensure_future(coro_or_future, *, loop=None):
    """Wrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    """
    if coroutines.iscoroutine(coro_or_future):
        if loop is None:
            loop = events.get_event_loop()
        task = loop.create_task(coro_or_future)
        if task._source_traceback:
            del task._source_traceback[-1]
        return task
    elif futures.isfuture(coro_or_future):
        if loop is not None and loop is not futures._get_loop(coro_or_future):
            raise ValueError('The future belongs to a different loop than '
                             'the one specified as the loop argument')
        return coro_or_future
    elif inspect.isawaitable(coro_or_future):
        return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
    else:
        raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
                        'required')


@types.coroutine
def _wrap_awaitable(awaitable):
    """Helper for asyncio.ensure_future().

    Wraps awaitable (an object with __await__) into a coroutine
    that will later be wrapped in a Task by ensure_future().
    """
    return (yield from awaitable.__await__())

_wrap_awaitable._is_coroutine = _is_coroutine


class _GatheringFuture(futures.Future):
    """Helper for gather().

    This overrides cancel() to cancel all the children and act more
    like Task.cancel(), which doesn't immediately mark itself as
    cancelled.
    """

    def __init__(self, children, *, loop=None):
        super().__init__(loop=loop)
        self._children = children
        self._cancel_requested = False

    def cancel(self):
        if self.done():
            return False
        ret = False
        for child in self._children:
            if child.cancel():
                ret = True
        if ret:
            # If any child tasks were actually cancelled, we should
            # propagate the cancellation request regardless of
            # *return_exceptions* argument.  See issue 32684.
            self._cancel_requested = True
        return ret


def gather(*coros_or_futures, loop=None, return_exceptions=False):
    """Return a future aggregating results from the given coroutines/futures.

    Coroutines will be wrapped in a future and scheduled in the event
    loop. They will not necessarily be scheduled in the same order as
    passed in.

    All futures must share the same event loop.  If all the tasks are
    done successfully, the returned future's result is the list of
    results (in the order of the original sequence, not necessarily
    the order of results arrival).  If *return_exceptions* is True,
    exceptions in the tasks are treated the same as successful
    results, and gathered in the result list; otherwise, the first
    raised exception will be immediately propagated to the returned
    future.

    Cancellation: if the outer Future is cancelled, all children (that
    have not completed yet) are also cancelled.  If any child is
    cancelled, this is treated as if it raised CancelledError --
    the outer Future is *not* cancelled in this case.  (This is to
    prevent the cancellation of one child to cause other children to
    be cancelled.)

    If *return_exceptions* is False, cancelling gather() after it
    has been marked done won't cancel any submitted awaitables.
    For instance, gather can be marked done after propagating an
    exception to the caller, therefore, calling ``gather.cancel()``
    after catching an exception (raised by one of the awaitables) from
    gather won't cancel any other awaitables.
    """
    if not coros_or_futures:
        if loop is None:
            loop = events.get_event_loop()
        else:
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)
        outer = loop.create_future()
        outer.set_result([])
        return outer

    def _done_callback(fut):
        nonlocal nfinished
        nfinished += 1

        if outer.done():
            if not fut.cancelled():
                # Mark exception retrieved.
                fut.exception()
            return

        if not return_exceptions:
            if fut.cancelled():
                # Check if 'fut' is cancelled first, as
                # 'fut.exception()' will *raise* a CancelledError
                # instead of returning it.
                exc = exceptions.CancelledError()
                outer.set_exception(exc)
                return
            else:
                exc = fut.exception()
                if exc is not None:
                    outer.set_exception(exc)
                    return

        if nfinished == nfuts:
            # All futures are done; create a list of results
            # and set it to the 'outer' future.
            results = []

            for fut in children:
                if fut.cancelled():
                    # Check if 'fut' is cancelled first, as
                    # 'fut.exception()' will *raise* a CancelledError
                    # instead of returning it.
                    res = exceptions.CancelledError()
                else:
                    res = fut.exception()
                    if res is None:
                        res = fut.result()
                results.append(res)

            if outer._cancel_requested:
                # If gather is being cancelled we must propagate the
                # cancellation regardless of *return_exceptions* argument.
                # See issue 32684.
                outer.set_exception(exceptions.CancelledError())
            else:
                outer.set_result(results)

    arg_to_fut = {}
    children = []
    nfuts = 0
    nfinished = 0
    for arg in coros_or_futures:
        if arg not in arg_to_fut:
            fut = ensure_future(arg, loop=loop)
            if loop is None:
                loop = futures._get_loop(fut)
            if fut is not arg:
                # 'arg' was not a Future, therefore, 'fut' is a new
                # Future created specifically for 'arg'.  Since the caller
                # can't control it, disable the "destroy pending task"
                # warning.
                fut._log_destroy_pending = False

            nfuts += 1
            arg_to_fut[arg] = fut
            fut.add_done_callback(_done_callback)

        else:
            # There's a duplicate Future object in coros_or_futures.
            fut = arg_to_fut[arg]

        children.append(fut)

    outer = _GatheringFuture(children, loop=loop)
    return outer


def shield(arg, *, loop=None):
    """Wait for a future, shielding it from cancellation.

    The statement

        res = await shield(something())

    is exactly equivalent to the statement

        res = await something()

    *except* that if the coroutine containing it is cancelled, the
    task running in something() is not cancelled.  From the POV of
    something(), the cancellation did not happen.  But its caller is
    still cancelled, so the yield-from expression still raises
    CancelledError.  Note: If something() is cancelled by other means
    this will still cancel shield().

    If you want to completely ignore cancellation (not recommended)
    you can combine shield() with a try/except clause, as follows:

        try:
            res = await shield(something())
        except CancelledError:
            res = None
    """
    if loop is not None:
        warnings.warn("The loop argument is deprecated since Python 3.8, "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning, stacklevel=2)
    inner = ensure_future(arg, loop=loop)
    if inner.done():
        # Shortcut.
        return inner
    loop = futures._get_loop(inner)
    outer = loop.create_future()

    def _inner_done_callback(inner):
        if outer.cancelled():
            if not inner.cancelled():
                # Mark inner's result as retrieved.
                inner.exception()
            return

        if inner.cancelled():
            outer.cancel()
        else:
            exc = inner.exception()
            if exc is not None:
                outer.set_exception(exc)
            else:
                outer.set_result(inner.result())


    def _outer_done_callback(outer):
        if not inner.done():
            inner.remove_done_callback(_inner_done_callback)

    inner.add_done_callback(_inner_done_callback)
    outer.add_done_callback(_outer_done_callback)
    return outer


def run_coroutine_threadsafe(coro, loop):
    """Submit a coroutine object to a given event loop.

    Return a concurrent.futures.Future to access the result.
    """
    if not coroutines.iscoroutine(coro):
        raise TypeError('A coroutine object is required')
    future = concurrent.futures.Future()

    def callback():
        try:
            futures._chain_future(ensure_future(coro, loop=loop), future)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            if future.set_running_or_notify_cancel():
                future.set_exception(exc)
            raise

    loop.call_soon_threadsafe(callback)
    return future


# WeakSet containing all alive tasks.
_all_tasks = weakref.WeakSet()

# Dictionary containing tasks that are currently active in
# all running event loops.  {EventLoop: Task}
_current_tasks = {}


def _register_task(task):
    """Register a new task in asyncio as executed by loop."""
    _all_tasks.add(task)


def _enter_task(loop, task):
    current_task = _current_tasks.get(loop)
    if current_task is not None:
        raise RuntimeError(f"Cannot enter into task {task!r} while another "
                           f"task {current_task!r} is being executed.")
    _current_tasks[loop] = task


def _leave_task(loop, task):
    current_task = _current_tasks.get(loop)
    if current_task is not task:
        raise RuntimeError(f"Leaving task {task!r} does not match "
                           f"the current task {current_task!r}.")
    del _current_tasks[loop]


def _unregister_task(task):
    """Unregister a task."""
    _all_tasks.discard(task)


_py_register_task = _register_task
_py_unregister_task = _unregister_task
_py_enter_task = _enter_task
_py_leave_task = _leave_task


try:
    from _asyncio import (_register_task, _unregister_task,
                          _enter_task, _leave_task,
                          _all_tasks, _current_tasks)
except ImportError:
    pass
else:
    _c_register_task = _register_task
    _c_unregister_task = _unregister_task
    _c_enter_task = _enter_task
    _c_leave_task = _leave_task
PK[�h���
subprocess.pynu�[���__all__ = 'create_subprocess_exec', 'create_subprocess_shell'

import subprocess
import warnings

from . import events
from . import protocols
from . import streams
from . import tasks
from .log import logger


PIPE = subprocess.PIPE
STDOUT = subprocess.STDOUT
DEVNULL = subprocess.DEVNULL


class SubprocessStreamProtocol(streams.FlowControlMixin,
                               protocols.SubprocessProtocol):
    """Like StreamReaderProtocol, but for a subprocess."""

    def __init__(self, limit, loop):
        super().__init__(loop=loop)
        self._limit = limit
        self.stdin = self.stdout = self.stderr = None
        self._transport = None
        self._process_exited = False
        self._pipe_fds = []
        self._stdin_closed = self._loop.create_future()

    def __repr__(self):
        info = [self.__class__.__name__]
        if self.stdin is not None:
            info.append(f'stdin={self.stdin!r}')
        if self.stdout is not None:
            info.append(f'stdout={self.stdout!r}')
        if self.stderr is not None:
            info.append(f'stderr={self.stderr!r}')
        return '<{}>'.format(' '.join(info))

    def connection_made(self, transport):
        self._transport = transport

        stdout_transport = transport.get_pipe_transport(1)
        if stdout_transport is not None:
            self.stdout = streams.StreamReader(limit=self._limit,
                                               loop=self._loop)
            self.stdout.set_transport(stdout_transport)
            self._pipe_fds.append(1)

        stderr_transport = transport.get_pipe_transport(2)
        if stderr_transport is not None:
            self.stderr = streams.StreamReader(limit=self._limit,
                                               loop=self._loop)
            self.stderr.set_transport(stderr_transport)
            self._pipe_fds.append(2)

        stdin_transport = transport.get_pipe_transport(0)
        if stdin_transport is not None:
            self.stdin = streams.StreamWriter(stdin_transport,
                                              protocol=self,
                                              reader=None,
                                              loop=self._loop)

    def pipe_data_received(self, fd, data):
        if fd == 1:
            reader = self.stdout
        elif fd == 2:
            reader = self.stderr
        else:
            reader = None
        if reader is not None:
            reader.feed_data(data)

    def pipe_connection_lost(self, fd, exc):
        if fd == 0:
            pipe = self.stdin
            if pipe is not None:
                pipe.close()
            self.connection_lost(exc)
            if exc is None:
                self._stdin_closed.set_result(None)
            else:
                self._stdin_closed.set_exception(exc)
            return
        if fd == 1:
            reader = self.stdout
        elif fd == 2:
            reader = self.stderr
        else:
            reader = None
        if reader is not None:
            if exc is None:
                reader.feed_eof()
            else:
                reader.set_exception(exc)

        if fd in self._pipe_fds:
            self._pipe_fds.remove(fd)
        self._maybe_close_transport()

    def process_exited(self):
        self._process_exited = True
        self._maybe_close_transport()

    def _maybe_close_transport(self):
        if len(self._pipe_fds) == 0 and self._process_exited:
            self._transport.close()
            self._transport = None

    def _get_close_waiter(self, stream):
        if stream is self.stdin:
            return self._stdin_closed


class Process:
    def __init__(self, transport, protocol, loop):
        self._transport = transport
        self._protocol = protocol
        self._loop = loop
        self.stdin = protocol.stdin
        self.stdout = protocol.stdout
        self.stderr = protocol.stderr
        self.pid = transport.get_pid()

    def __repr__(self):
        return f'<{self.__class__.__name__} {self.pid}>'

    @property
    def returncode(self):
        return self._transport.get_returncode()

    async def wait(self):
        """Wait until the process exit and return the process return code."""
        return await self._transport._wait()

    def send_signal(self, signal):
        self._transport.send_signal(signal)

    def terminate(self):
        self._transport.terminate()

    def kill(self):
        self._transport.kill()

    async def _feed_stdin(self, input):
        debug = self._loop.get_debug()
        self.stdin.write(input)
        if debug:
            logger.debug(
                '%r communicate: feed stdin (%s bytes)', self, len(input))
        try:
            await self.stdin.drain()
        except (BrokenPipeError, ConnectionResetError) as exc:
            # communicate() ignores BrokenPipeError and ConnectionResetError
            if debug:
                logger.debug('%r communicate: stdin got %r', self, exc)

        if debug:
            logger.debug('%r communicate: close stdin', self)
        self.stdin.close()

    async def _noop(self):
        return None

    async def _read_stream(self, fd):
        transport = self._transport.get_pipe_transport(fd)
        if fd == 2:
            stream = self.stderr
        else:
            assert fd == 1
            stream = self.stdout
        if self._loop.get_debug():
            name = 'stdout' if fd == 1 else 'stderr'
            logger.debug('%r communicate: read %s', self, name)
        output = await stream.read()
        if self._loop.get_debug():
            name = 'stdout' if fd == 1 else 'stderr'
            logger.debug('%r communicate: close %s', self, name)
        transport.close()
        return output

    async def communicate(self, input=None):
        if input is not None:
            stdin = self._feed_stdin(input)
        else:
            stdin = self._noop()
        if self.stdout is not None:
            stdout = self._read_stream(1)
        else:
            stdout = self._noop()
        if self.stderr is not None:
            stderr = self._read_stream(2)
        else:
            stderr = self._noop()
        stdin, stdout, stderr = await tasks.gather(stdin, stdout, stderr,
                                                   loop=self._loop)
        await self.wait()
        return (stdout, stderr)


async def create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None,
                                  loop=None, limit=streams._DEFAULT_LIMIT,
                                  **kwds):
    if loop is None:
        loop = events.get_event_loop()
    else:
        warnings.warn("The loop argument is deprecated since Python 3.8 "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning,
                      stacklevel=2
        )

    protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
                                                        loop=loop)
    transport, protocol = await loop.subprocess_shell(
        protocol_factory,
        cmd, stdin=stdin, stdout=stdout,
        stderr=stderr, **kwds)
    return Process(transport, protocol, loop)


async def create_subprocess_exec(program, *args, stdin=None, stdout=None,
                                 stderr=None, loop=None,
                                 limit=streams._DEFAULT_LIMIT, **kwds):
    if loop is None:
        loop = events.get_event_loop()
    else:
        warnings.warn("The loop argument is deprecated since Python 3.8 "
                      "and scheduled for removal in Python 3.10.",
                      DeprecationWarning,
                      stacklevel=2
        )
    protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
                                                        loop=loop)
    transport, protocol = await loop.subprocess_exec(
        protocol_factory,
        program, *args,
        stdin=stdin, stdout=stdout,
        stderr=stderr, **kwds)
    return Process(transport, protocol, loop)
PK[(s8�xxconstants.pynu�[���import enum

# After the connection is lost, log warnings after this many write()s.
LOG_THRESHOLD_FOR_CONNLOST_WRITES = 5

# Seconds to wait before retrying accept().
ACCEPT_RETRY_DELAY = 1

# Number of stack entries to capture in debug mode.
# The larger the number, the slower the operation in debug mode
# (see extract_stack() in format_helpers.py).
DEBUG_STACK_DEPTH = 10

# Number of seconds to wait for SSL handshake to complete
# The default timeout matches that of Nginx.
SSL_HANDSHAKE_TIMEOUT = 60.0

# Used in sendfile fallback code.  We use fallback for platforms
# that don't support sendfile, or for TLS connections.
SENDFILE_FALLBACK_READBUFFER_SIZE = 1024 * 256

# The enum should be here to break circular dependencies between
# base_events and sslproto
class _SendfileMode(enum.Enum):
    UNSUPPORTED = enum.auto()
    TRY_NATIVE = enum.auto()
    FALLBACK = enum.auto()
PK[��yT�T�selector_events.pynu�[���"""Event loop using a selector and related classes.

A selector is a "notify-when-ready" multiplexer.  For a subclass which
also includes support for signal handling, see the unix_events sub-module.
"""

__all__ = 'BaseSelectorEventLoop',

import collections
import errno
import functools
import selectors
import socket
import warnings
import weakref
try:
    import ssl
except ImportError:  # pragma: no cover
    ssl = None

from . import base_events
from . import constants
from . import events
from . import futures
from . import protocols
from . import sslproto
from . import transports
from . import trsock
from .log import logger


def _test_selector_event(selector, fd, event):
    # Test if the selector is monitoring 'event' events
    # for the file descriptor 'fd'.
    try:
        key = selector.get_key(fd)
    except KeyError:
        return False
    else:
        return bool(key.events & event)


def _check_ssl_socket(sock):
    if ssl is not None and isinstance(sock, ssl.SSLSocket):
        raise TypeError("Socket cannot be of type SSLSocket")


class BaseSelectorEventLoop(base_events.BaseEventLoop):
    """Selector event loop.

    See events.EventLoop for API specification.
    """

    def __init__(self, selector=None):
        super().__init__()

        if selector is None:
            selector = selectors.DefaultSelector()
        logger.debug('Using selector: %s', selector.__class__.__name__)
        self._selector = selector
        self._make_self_pipe()
        self._transports = weakref.WeakValueDictionary()

    def _make_socket_transport(self, sock, protocol, waiter=None, *,
                               extra=None, server=None):
        return _SelectorSocketTransport(self, sock, protocol, waiter,
                                        extra, server)

    def _make_ssl_transport(
            self, rawsock, protocol, sslcontext, waiter=None,
            *, server_side=False, server_hostname=None,
            extra=None, server=None,
            ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
        ssl_protocol = sslproto.SSLProtocol(
                self, protocol, sslcontext, waiter,
                server_side, server_hostname,
                ssl_handshake_timeout=ssl_handshake_timeout)
        _SelectorSocketTransport(self, rawsock, ssl_protocol,
                                 extra=extra, server=server)
        return ssl_protocol._app_transport

    def _make_datagram_transport(self, sock, protocol,
                                 address=None, waiter=None, extra=None):
        return _SelectorDatagramTransport(self, sock, protocol,
                                          address, waiter, extra)

    def close(self):
        if self.is_running():
            raise RuntimeError("Cannot close a running event loop")
        if self.is_closed():
            return
        self._close_self_pipe()
        super().close()
        if self._selector is not None:
            self._selector.close()
            self._selector = None

    def _close_self_pipe(self):
        self._remove_reader(self._ssock.fileno())
        self._ssock.close()
        self._ssock = None
        self._csock.close()
        self._csock = None
        self._internal_fds -= 1

    def _make_self_pipe(self):
        # A self-socket, really. :-)
        self._ssock, self._csock = socket.socketpair()
        self._ssock.setblocking(False)
        self._csock.setblocking(False)
        self._internal_fds += 1
        self._add_reader(self._ssock.fileno(), self._read_from_self)

    def _process_self_data(self, data):
        pass

    def _read_from_self(self):
        while True:
            try:
                data = self._ssock.recv(4096)
                if not data:
                    break
                self._process_self_data(data)
            except InterruptedError:
                continue
            except BlockingIOError:
                break

    def _write_to_self(self):
        # This may be called from a different thread, possibly after
        # _close_self_pipe() has been called or even while it is
        # running.  Guard for self._csock being None or closed.  When
        # a socket is closed, send() raises OSError (with errno set to
        # EBADF, but let's not rely on the exact error code).
        csock = self._csock
        if csock is None:
            return

        try:
            csock.send(b'\0')
        except OSError:
            if self._debug:
                logger.debug("Fail to write a null byte into the "
                             "self-pipe socket",
                             exc_info=True)

    def _start_serving(self, protocol_factory, sock,
                       sslcontext=None, server=None, backlog=100,
                       ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
        self._add_reader(sock.fileno(), self._accept_connection,
                         protocol_factory, sock, sslcontext, server, backlog,
                         ssl_handshake_timeout)

    def _accept_connection(
            self, protocol_factory, sock,
            sslcontext=None, server=None, backlog=100,
            ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
        # This method is only called once for each event loop tick where the
        # listening socket has triggered an EVENT_READ. There may be multiple
        # connections waiting for an .accept() so it is called in a loop.
        # See https://bugs.python.org/issue27906 for more details.
        for _ in range(backlog):
            try:
                conn, addr = sock.accept()
                if self._debug:
                    logger.debug("%r got a new connection from %r: %r",
                                 server, addr, conn)
                conn.setblocking(False)
            except (BlockingIOError, InterruptedError, ConnectionAbortedError):
                # Early exit because the socket accept buffer is empty.
                return None
            except OSError as exc:
                # There's nowhere to send the error, so just log it.
                if exc.errno in (errno.EMFILE, errno.ENFILE,
                                 errno.ENOBUFS, errno.ENOMEM):
                    # Some platforms (e.g. Linux keep reporting the FD as
                    # ready, so we remove the read handler temporarily.
                    # We'll try again in a while.
                    self.call_exception_handler({
                        'message': 'socket.accept() out of system resource',
                        'exception': exc,
                        'socket': trsock.TransportSocket(sock),
                    })
                    self._remove_reader(sock.fileno())
                    self.call_later(constants.ACCEPT_RETRY_DELAY,
                                    self._start_serving,
                                    protocol_factory, sock, sslcontext, server,
                                    backlog, ssl_handshake_timeout)
                else:
                    raise  # The event loop will catch, log and ignore it.
            else:
                extra = {'peername': addr}
                accept = self._accept_connection2(
                    protocol_factory, conn, extra, sslcontext, server,
                    ssl_handshake_timeout)
                self.create_task(accept)

    async def _accept_connection2(
            self, protocol_factory, conn, extra,
            sslcontext=None, server=None,
            ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
        protocol = None
        transport = None
        try:
            protocol = protocol_factory()
            waiter = self.create_future()
            if sslcontext:
                transport = self._make_ssl_transport(
                    conn, protocol, sslcontext, waiter=waiter,
                    server_side=True, extra=extra, server=server,
                    ssl_handshake_timeout=ssl_handshake_timeout)
            else:
                transport = self._make_socket_transport(
                    conn, protocol, waiter=waiter, extra=extra,
                    server=server)

            try:
                await waiter
            except BaseException:
                transport.close()
                raise
                # It's now up to the protocol to handle the connection.

        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            if self._debug:
                context = {
                    'message':
                        'Error on transport creation for incoming connection',
                    'exception': exc,
                }
                if protocol is not None:
                    context['protocol'] = protocol
                if transport is not None:
                    context['transport'] = transport
                self.call_exception_handler(context)

    def _ensure_fd_no_transport(self, fd):
        fileno = fd
        if not isinstance(fileno, int):
            try:
                fileno = int(fileno.fileno())
            except (AttributeError, TypeError, ValueError):
                # This code matches selectors._fileobj_to_fd function.
                raise ValueError(f"Invalid file object: {fd!r}") from None
        try:
            transport = self._transports[fileno]
        except KeyError:
            pass
        else:
            if not transport.is_closing():
                raise RuntimeError(
                    f'File descriptor {fd!r} is used by transport '
                    f'{transport!r}')

    def _add_reader(self, fd, callback, *args):
        self._check_closed()
        handle = events.Handle(callback, args, self, None)
        try:
            key = self._selector.get_key(fd)
        except KeyError:
            self._selector.register(fd, selectors.EVENT_READ,
                                    (handle, None))
        else:
            mask, (reader, writer) = key.events, key.data
            self._selector.modify(fd, mask | selectors.EVENT_READ,
                                  (handle, writer))
            if reader is not None:
                reader.cancel()

    def _remove_reader(self, fd):
        if self.is_closed():
            return False
        try:
            key = self._selector.get_key(fd)
        except KeyError:
            return False
        else:
            mask, (reader, writer) = key.events, key.data
            mask &= ~selectors.EVENT_READ
            if not mask:
                self._selector.unregister(fd)
            else:
                self._selector.modify(fd, mask, (None, writer))

            if reader is not None:
                reader.cancel()
                return True
            else:
                return False

    def _add_writer(self, fd, callback, *args):
        self._check_closed()
        handle = events.Handle(callback, args, self, None)
        try:
            key = self._selector.get_key(fd)
        except KeyError:
            self._selector.register(fd, selectors.EVENT_WRITE,
                                    (None, handle))
        else:
            mask, (reader, writer) = key.events, key.data
            self._selector.modify(fd, mask | selectors.EVENT_WRITE,
                                  (reader, handle))
            if writer is not None:
                writer.cancel()

    def _remove_writer(self, fd):
        """Remove a writer callback."""
        if self.is_closed():
            return False
        try:
            key = self._selector.get_key(fd)
        except KeyError:
            return False
        else:
            mask, (reader, writer) = key.events, key.data
            # Remove both writer and connector.
            mask &= ~selectors.EVENT_WRITE
            if not mask:
                self._selector.unregister(fd)
            else:
                self._selector.modify(fd, mask, (reader, None))

            if writer is not None:
                writer.cancel()
                return True
            else:
                return False

    def add_reader(self, fd, callback, *args):
        """Add a reader callback."""
        self._ensure_fd_no_transport(fd)
        return self._add_reader(fd, callback, *args)

    def remove_reader(self, fd):
        """Remove a reader callback."""
        self._ensure_fd_no_transport(fd)
        return self._remove_reader(fd)

    def add_writer(self, fd, callback, *args):
        """Add a writer callback.."""
        self._ensure_fd_no_transport(fd)
        return self._add_writer(fd, callback, *args)

    def remove_writer(self, fd):
        """Remove a writer callback."""
        self._ensure_fd_no_transport(fd)
        return self._remove_writer(fd)

    async def sock_recv(self, sock, n):
        """Receive data from the socket.

        The return value is a bytes object representing the data received.
        The maximum amount of data to be received at once is specified by
        nbytes.
        """
        _check_ssl_socket(sock)
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")
        try:
            return sock.recv(n)
        except (BlockingIOError, InterruptedError):
            pass
        fut = self.create_future()
        fd = sock.fileno()
        self.add_reader(fd, self._sock_recv, fut, sock, n)
        fut.add_done_callback(
            functools.partial(self._sock_read_done, fd))
        return await fut

    def _sock_read_done(self, fd, fut):
        self.remove_reader(fd)

    def _sock_recv(self, fut, sock, n):
        # _sock_recv() can add itself as an I/O callback if the operation can't
        # be done immediately. Don't use it directly, call sock_recv().
        if fut.done():
            return
        try:
            data = sock.recv(n)
        except (BlockingIOError, InterruptedError):
            return  # try again next time
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            fut.set_exception(exc)
        else:
            fut.set_result(data)

    async def sock_recv_into(self, sock, buf):
        """Receive data from the socket.

        The received data is written into *buf* (a writable buffer).
        The return value is the number of bytes written.
        """
        _check_ssl_socket(sock)
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")
        try:
            return sock.recv_into(buf)
        except (BlockingIOError, InterruptedError):
            pass
        fut = self.create_future()
        fd = sock.fileno()
        self.add_reader(fd, self._sock_recv_into, fut, sock, buf)
        fut.add_done_callback(
            functools.partial(self._sock_read_done, fd))
        return await fut

    def _sock_recv_into(self, fut, sock, buf):
        # _sock_recv_into() can add itself as an I/O callback if the operation
        # can't be done immediately. Don't use it directly, call
        # sock_recv_into().
        if fut.done():
            return
        try:
            nbytes = sock.recv_into(buf)
        except (BlockingIOError, InterruptedError):
            return  # try again next time
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            fut.set_exception(exc)
        else:
            fut.set_result(nbytes)

    async def sock_sendall(self, sock, data):
        """Send data to the socket.

        The socket must be connected to a remote socket. This method continues
        to send data from data until either all data has been sent or an
        error occurs. None is returned on success. On error, an exception is
        raised, and there is no way to determine how much data, if any, was
        successfully processed by the receiving end of the connection.
        """
        _check_ssl_socket(sock)
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")
        try:
            n = sock.send(data)
        except (BlockingIOError, InterruptedError):
            n = 0

        if n == len(data):
            # all data sent
            return

        fut = self.create_future()
        fd = sock.fileno()
        fut.add_done_callback(
            functools.partial(self._sock_write_done, fd))
        # use a trick with a list in closure to store a mutable state
        self.add_writer(fd, self._sock_sendall, fut, sock,
                        memoryview(data), [n])
        return await fut

    def _sock_sendall(self, fut, sock, view, pos):
        if fut.done():
            # Future cancellation can be scheduled on previous loop iteration
            return
        start = pos[0]
        try:
            n = sock.send(view[start:])
        except (BlockingIOError, InterruptedError):
            return
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            fut.set_exception(exc)
            return

        start += n

        if start == len(view):
            fut.set_result(None)
        else:
            pos[0] = start

    async def sock_connect(self, sock, address):
        """Connect to a remote socket at address.

        This method is a coroutine.
        """
        _check_ssl_socket(sock)
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")

        if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX:
            resolved = await self._ensure_resolved(
                address, family=sock.family, proto=sock.proto, loop=self)
            _, _, _, _, address = resolved[0]

        fut = self.create_future()
        self._sock_connect(fut, sock, address)
        return await fut

    def _sock_connect(self, fut, sock, address):
        fd = sock.fileno()
        try:
            sock.connect(address)
        except (BlockingIOError, InterruptedError):
            # Issue #23618: When the C function connect() fails with EINTR, the
            # connection runs in background. We have to wait until the socket
            # becomes writable to be notified when the connection succeed or
            # fails.
            fut.add_done_callback(
                functools.partial(self._sock_write_done, fd))
            self.add_writer(fd, self._sock_connect_cb, fut, sock, address)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            fut.set_exception(exc)
        else:
            fut.set_result(None)

    def _sock_write_done(self, fd, fut):
        self.remove_writer(fd)

    def _sock_connect_cb(self, fut, sock, address):
        if fut.done():
            return

        try:
            err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
            if err != 0:
                # Jump to any except clause below.
                raise OSError(err, f'Connect call failed {address}')
        except (BlockingIOError, InterruptedError):
            # socket is still registered, the callback will be retried later
            pass
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            fut.set_exception(exc)
        else:
            fut.set_result(None)

    async def sock_accept(self, sock):
        """Accept a connection.

        The socket must be bound to an address and listening for connections.
        The return value is a pair (conn, address) where conn is a new socket
        object usable to send and receive data on the connection, and address
        is the address bound to the socket on the other end of the connection.
        """
        _check_ssl_socket(sock)
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")
        fut = self.create_future()
        self._sock_accept(fut, False, sock)
        return await fut

    def _sock_accept(self, fut, registered, sock):
        fd = sock.fileno()
        if registered:
            self.remove_reader(fd)
        if fut.done():
            return
        try:
            conn, address = sock.accept()
            conn.setblocking(False)
        except (BlockingIOError, InterruptedError):
            self.add_reader(fd, self._sock_accept, fut, True, sock)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            fut.set_exception(exc)
        else:
            fut.set_result((conn, address))

    async def _sendfile_native(self, transp, file, offset, count):
        del self._transports[transp._sock_fd]
        resume_reading = transp.is_reading()
        transp.pause_reading()
        await transp._make_empty_waiter()
        try:
            return await self.sock_sendfile(transp._sock, file, offset, count,
                                            fallback=False)
        finally:
            transp._reset_empty_waiter()
            if resume_reading:
                transp.resume_reading()
            self._transports[transp._sock_fd] = transp

    def _process_events(self, event_list):
        for key, mask in event_list:
            fileobj, (reader, writer) = key.fileobj, key.data
            if mask & selectors.EVENT_READ and reader is not None:
                if reader._cancelled:
                    self._remove_reader(fileobj)
                else:
                    self._add_callback(reader)
            if mask & selectors.EVENT_WRITE and writer is not None:
                if writer._cancelled:
                    self._remove_writer(fileobj)
                else:
                    self._add_callback(writer)

    def _stop_serving(self, sock):
        self._remove_reader(sock.fileno())
        sock.close()


class _SelectorTransport(transports._FlowControlMixin,
                         transports.Transport):

    max_size = 256 * 1024  # Buffer size passed to recv().

    _buffer_factory = bytearray  # Constructs initial value for self._buffer.

    # Attribute used in the destructor: it must be set even if the constructor
    # is not called (see _SelectorSslTransport which may start by raising an
    # exception)
    _sock = None

    def __init__(self, loop, sock, protocol, extra=None, server=None):
        super().__init__(extra, loop)
        self._extra['socket'] = trsock.TransportSocket(sock)
        try:
            self._extra['sockname'] = sock.getsockname()
        except OSError:
            self._extra['sockname'] = None
        if 'peername' not in self._extra:
            try:
                self._extra['peername'] = sock.getpeername()
            except socket.error:
                self._extra['peername'] = None
        self._sock = sock
        self._sock_fd = sock.fileno()

        self._protocol_connected = False
        self.set_protocol(protocol)

        self._server = server
        self._buffer = self._buffer_factory()
        self._conn_lost = 0  # Set when call to connection_lost scheduled.
        self._closing = False  # Set when close() called.
        if self._server is not None:
            self._server._attach()
        loop._transports[self._sock_fd] = self

    def __repr__(self):
        info = [self.__class__.__name__]
        if self._sock is None:
            info.append('closed')
        elif self._closing:
            info.append('closing')
        info.append(f'fd={self._sock_fd}')
        # test if the transport was closed
        if self._loop is not None and not self._loop.is_closed():
            polling = _test_selector_event(self._loop._selector,
                                           self._sock_fd, selectors.EVENT_READ)
            if polling:
                info.append('read=polling')
            else:
                info.append('read=idle')

            polling = _test_selector_event(self._loop._selector,
                                           self._sock_fd,
                                           selectors.EVENT_WRITE)
            if polling:
                state = 'polling'
            else:
                state = 'idle'

            bufsize = self.get_write_buffer_size()
            info.append(f'write=<{state}, bufsize={bufsize}>')
        return '<{}>'.format(' '.join(info))

    def abort(self):
        self._force_close(None)

    def set_protocol(self, protocol):
        self._protocol = protocol
        self._protocol_connected = True

    def get_protocol(self):
        return self._protocol

    def is_closing(self):
        return self._closing

    def close(self):
        if self._closing:
            return
        self._closing = True
        self._loop._remove_reader(self._sock_fd)
        if not self._buffer:
            self._conn_lost += 1
            self._loop._remove_writer(self._sock_fd)
            self._loop.call_soon(self._call_connection_lost, None)

    def __del__(self, _warn=warnings.warn):
        if self._sock is not None:
            _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
            self._sock.close()

    def _fatal_error(self, exc, message='Fatal error on transport'):
        # Should be called from exception handler only.
        if isinstance(exc, OSError):
            if self._loop.get_debug():
                logger.debug("%r: %s", self, message, exc_info=True)
        else:
            self._loop.call_exception_handler({
                'message': message,
                'exception': exc,
                'transport': self,
                'protocol': self._protocol,
            })
        self._force_close(exc)

    def _force_close(self, exc):
        if self._conn_lost:
            return
        if self._buffer:
            self._buffer.clear()
            self._loop._remove_writer(self._sock_fd)
        if not self._closing:
            self._closing = True
            self._loop._remove_reader(self._sock_fd)
        self._conn_lost += 1
        self._loop.call_soon(self._call_connection_lost, exc)

    def _call_connection_lost(self, exc):
        try:
            if self._protocol_connected:
                self._protocol.connection_lost(exc)
        finally:
            self._sock.close()
            self._sock = None
            self._protocol = None
            self._loop = None
            server = self._server
            if server is not None:
                server._detach()
                self._server = None

    def get_write_buffer_size(self):
        return len(self._buffer)

    def _add_reader(self, fd, callback, *args):
        if self._closing:
            return

        self._loop._add_reader(fd, callback, *args)


class _SelectorSocketTransport(_SelectorTransport):

    _start_tls_compatible = True
    _sendfile_compatible = constants._SendfileMode.TRY_NATIVE

    def __init__(self, loop, sock, protocol, waiter=None,
                 extra=None, server=None):

        self._read_ready_cb = None
        super().__init__(loop, sock, protocol, extra, server)
        self._eof = False
        self._paused = False
        self._empty_waiter = None

        # Disable the Nagle algorithm -- small writes will be
        # sent without waiting for the TCP ACK.  This generally
        # decreases the latency (in some cases significantly.)
        base_events._set_nodelay(self._sock)

        self._loop.call_soon(self._protocol.connection_made, self)
        # only start reading when connection_made() has been called
        self._loop.call_soon(self._add_reader,
                             self._sock_fd, self._read_ready)
        if waiter is not None:
            # only wake up the waiter when connection_made() has been called
            self._loop.call_soon(futures._set_result_unless_cancelled,
                                 waiter, None)

    def set_protocol(self, protocol):
        if isinstance(protocol, protocols.BufferedProtocol):
            self._read_ready_cb = self._read_ready__get_buffer
        else:
            self._read_ready_cb = self._read_ready__data_received

        super().set_protocol(protocol)

    def is_reading(self):
        return not self._paused and not self._closing

    def pause_reading(self):
        if self._closing or self._paused:
            return
        self._paused = True
        self._loop._remove_reader(self._sock_fd)
        if self._loop.get_debug():
            logger.debug("%r pauses reading", self)

    def resume_reading(self):
        if self._closing or not self._paused:
            return
        self._paused = False
        self._add_reader(self._sock_fd, self._read_ready)
        if self._loop.get_debug():
            logger.debug("%r resumes reading", self)

    def _read_ready(self):
        self._read_ready_cb()

    def _read_ready__get_buffer(self):
        if self._conn_lost:
            return

        try:
            buf = self._protocol.get_buffer(-1)
            if not len(buf):
                raise RuntimeError('get_buffer() returned an empty buffer')
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._fatal_error(
                exc, 'Fatal error: protocol.get_buffer() call failed.')
            return

        try:
            nbytes = self._sock.recv_into(buf)
        except (BlockingIOError, InterruptedError):
            return
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._fatal_error(exc, 'Fatal read error on socket transport')
            return

        if not nbytes:
            self._read_ready__on_eof()
            return

        try:
            self._protocol.buffer_updated(nbytes)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._fatal_error(
                exc, 'Fatal error: protocol.buffer_updated() call failed.')

    def _read_ready__data_received(self):
        if self._conn_lost:
            return
        try:
            data = self._sock.recv(self.max_size)
        except (BlockingIOError, InterruptedError):
            return
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._fatal_error(exc, 'Fatal read error on socket transport')
            return

        if not data:
            self._read_ready__on_eof()
            return

        try:
            self._protocol.data_received(data)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._fatal_error(
                exc, 'Fatal error: protocol.data_received() call failed.')

    def _read_ready__on_eof(self):
        if self._loop.get_debug():
            logger.debug("%r received EOF", self)

        try:
            keep_open = self._protocol.eof_received()
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._fatal_error(
                exc, 'Fatal error: protocol.eof_received() call failed.')
            return

        if keep_open:
            # We're keeping the connection open so the
            # protocol can write more, but we still can't
            # receive more, so remove the reader callback.
            self._loop._remove_reader(self._sock_fd)
        else:
            self.close()

    def write(self, data):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError(f'data argument must be a bytes-like object, '
                            f'not {type(data).__name__!r}')
        if self._eof:
            raise RuntimeError('Cannot call write() after write_eof()')
        if self._empty_waiter is not None:
            raise RuntimeError('unable to write; sendfile is in progress')
        if not data:
            return

        if self._conn_lost:
            if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
                logger.warning('socket.send() raised exception.')
            self._conn_lost += 1
            return

        if not self._buffer:
            # Optimization: try to send now.
            try:
                n = self._sock.send(data)
            except (BlockingIOError, InterruptedError):
                pass
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException as exc:
                self._fatal_error(exc, 'Fatal write error on socket transport')
                return
            else:
                data = data[n:]
                if not data:
                    return
            # Not all was written; register write handler.
            self._loop._add_writer(self._sock_fd, self._write_ready)

        # Add it to the buffer.
        self._buffer.extend(data)
        self._maybe_pause_protocol()

    def _write_ready(self):
        assert self._buffer, 'Data should not be empty'

        if self._conn_lost:
            return
        try:
            n = self._sock.send(self._buffer)
        except (BlockingIOError, InterruptedError):
            pass
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._loop._remove_writer(self._sock_fd)
            self._buffer.clear()
            self._fatal_error(exc, 'Fatal write error on socket transport')
            if self._empty_waiter is not None:
                self._empty_waiter.set_exception(exc)
        else:
            if n:
                del self._buffer[:n]
            self._maybe_resume_protocol()  # May append to buffer.
            if not self._buffer:
                self._loop._remove_writer(self._sock_fd)
                if self._empty_waiter is not None:
                    self._empty_waiter.set_result(None)
                if self._closing:
                    self._call_connection_lost(None)
                elif self._eof:
                    self._sock.shutdown(socket.SHUT_WR)

    def write_eof(self):
        if self._closing or self._eof:
            return
        self._eof = True
        if not self._buffer:
            self._sock.shutdown(socket.SHUT_WR)

    def can_write_eof(self):
        return True

    def _call_connection_lost(self, exc):
        super()._call_connection_lost(exc)
        if self._empty_waiter is not None:
            self._empty_waiter.set_exception(
                ConnectionError("Connection is closed by peer"))

    def _make_empty_waiter(self):
        if self._empty_waiter is not None:
            raise RuntimeError("Empty waiter is already set")
        self._empty_waiter = self._loop.create_future()
        if not self._buffer:
            self._empty_waiter.set_result(None)
        return self._empty_waiter

    def _reset_empty_waiter(self):
        self._empty_waiter = None


class _SelectorDatagramTransport(_SelectorTransport):

    _buffer_factory = collections.deque

    def __init__(self, loop, sock, protocol, address=None,
                 waiter=None, extra=None):
        super().__init__(loop, sock, protocol, extra)
        self._address = address
        self._loop.call_soon(self._protocol.connection_made, self)
        # only start reading when connection_made() has been called
        self._loop.call_soon(self._add_reader,
                             self._sock_fd, self._read_ready)
        if waiter is not None:
            # only wake up the waiter when connection_made() has been called
            self._loop.call_soon(futures._set_result_unless_cancelled,
                                 waiter, None)

    def get_write_buffer_size(self):
        return sum(len(data) for data, _ in self._buffer)

    def _read_ready(self):
        if self._conn_lost:
            return
        try:
            data, addr = self._sock.recvfrom(self.max_size)
        except (BlockingIOError, InterruptedError):
            pass
        except OSError as exc:
            self._protocol.error_received(exc)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._fatal_error(exc, 'Fatal read error on datagram transport')
        else:
            self._protocol.datagram_received(data, addr)

    def sendto(self, data, addr=None):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError(f'data argument must be a bytes-like object, '
                            f'not {type(data).__name__!r}')
        if not data:
            return

        if self._address:
            if addr not in (None, self._address):
                raise ValueError(
                    f'Invalid address: must be None or {self._address}')
            addr = self._address

        if self._conn_lost and self._address:
            if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
                logger.warning('socket.send() raised exception.')
            self._conn_lost += 1
            return

        if not self._buffer:
            # Attempt to send it right away first.
            try:
                if self._extra['peername']:
                    self._sock.send(data)
                else:
                    self._sock.sendto(data, addr)
                return
            except (BlockingIOError, InterruptedError):
                self._loop._add_writer(self._sock_fd, self._sendto_ready)
            except OSError as exc:
                self._protocol.error_received(exc)
                return
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException as exc:
                self._fatal_error(
                    exc, 'Fatal write error on datagram transport')
                return

        # Ensure that what we buffer is immutable.
        self._buffer.append((bytes(data), addr))
        self._maybe_pause_protocol()

    def _sendto_ready(self):
        while self._buffer:
            data, addr = self._buffer.popleft()
            try:
                if self._extra['peername']:
                    self._sock.send(data)
                else:
                    self._sock.sendto(data, addr)
            except (BlockingIOError, InterruptedError):
                self._buffer.appendleft((data, addr))  # Try again later.
                break
            except OSError as exc:
                self._protocol.error_received(exc)
                return
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException as exc:
                self._fatal_error(
                    exc, 'Fatal write error on datagram transport')
                return

        self._maybe_resume_protocol()  # May append to buffer.
        if not self._buffer:
            self._loop._remove_writer(self._sock_fd)
            if self._closing:
                self._call_connection_lost(None)
PK[6߾ê�%__pycache__/subprocess.cpython-36.pycnu�[���3


 \��@s�ddgZddlZddlmZddlmZddlmZddlmZdd	lmZdd
l	m
Z
ejZejZej
Z
Gdd�dejej�ZGd
d�d�Zeddddejfdd��Zeddddejd�dd��ZdS)�create_subprocess_exec�create_subprocess_shell�N�)�events)�	protocols)�streams)�tasks)�	coroutine)�loggercsPeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)�SubprocessStreamProtocolz0Like StreamReaderProtocol, but for a subprocess.cs<t�j|d�||_d|_|_|_d|_d|_g|_dS)N)�loopF)	�super�__init__�_limit�stdin�stdout�stderr�
_transport�_process_exited�	_pipe_fds)�self�limitr)�	__class__��*/usr/lib64/python3.6/asyncio/subprocess.pyrsz!SubprocessStreamProtocol.__init__cCsf|jjg}|jdk	r$|jd|j�|jdk	r>|jd|j�|jdk	rX|jd|j�ddj|�S)Nzstdin=%rz	stdout=%rz	stderr=%rz<%s>� )r�__name__r�appendrr�join)r�inforrr�__repr__s



z!SubprocessStreamProtocol.__repr__cCs�||_|jd�}|dk	rDtj|j|jd�|_|jj|�|jj	d�|jd�}|dk	r�tj|j|jd�|_
|j
j|�|jj	d�|jd�}|dk	r�tj||d|jd�|_dS)Nr)rr�r)�protocol�readerr)
r�get_pipe_transportr�StreamReaderr�_looprZ
set_transportrrr�StreamWriterr)r�	transportZstdout_transportZstderr_transportZstdin_transportrrr�connection_made(s&


z(SubprocessStreamProtocol.connection_madecCs:|dkr|j}n|dkr |j}nd}|dk	r6|j|�dS)Nrr!)rrZ	feed_data)r�fd�datar#rrr�pipe_data_received@sz+SubprocessStreamProtocol.pipe_data_receivedcCs�|dkr,|j}|dk	r|j�|j|�dS|dkr<|j}n|dkrL|j}nd}|dkrt|dkrj|j�n
|j|�||jkr�|jj|�|j	�dS)Nrrr!)
r�closeZconnection_lostrrZfeed_eofZ
set_exceptionr�remove�_maybe_close_transport)rr*�exc�piper#rrr�pipe_connection_lostJs$



z-SubprocessStreamProtocol.pipe_connection_lostcCsd|_|j�dS)NT)rr/)rrrr�process_exitedasz'SubprocessStreamProtocol.process_exitedcCs(t|j�dkr$|jr$|jj�d|_dS)Nr)�lenrrrr-)rrrrr/es
z/SubprocessStreamProtocol._maybe_close_transport)r�
__module__�__qualname__�__doc__rr r)r,r2r3r/�
__classcell__rr)rrrs

rc@s~eZdZdd�Zdd�Zedd��Zedd��Zd	d
�Z	dd�Z
d
d�Zedd��Zedd��Z
edd��Zeddd��ZdS)�ProcesscCs8||_||_||_|j|_|j|_|j|_|j�|_dS)N)rZ	_protocolr&rrrZget_pid�pid)rr(r"rrrrrlszProcess.__init__cCsd|jj|jfS)Nz<%s %s>)rrr:)rrrrr uszProcess.__repr__cCs
|jj�S)N)rZget_returncode)rrrr�
returncodexszProcess.returncodeccs|jj�EdHS)zdWait until the process exit and return the process return code.

        This method is a coroutine.N)rZ_wait)rrrr�wait|szProcess.waitcCs|jj|�dS)N)r�send_signal)r�signalrrrr=�szProcess.send_signalcCs|jj�dS)N)r�	terminate)rrrrr?�szProcess.terminatecCs|jj�dS)N)r�kill)rrrrr@�szProcess.killccs�|jj�}|jj|�|r,tjd|t|��y|jj�EdHWn8tt	fk
rx}z|rhtjd||�WYdd}~XnX|r�tjd|�|jj
�dS)Nz%%r communicate: feed stdin (%s bytes)z%r communicate: stdin got %rz%r communicate: close stdin)r&�	get_debugr�writer
�debugr4Zdrain�BrokenPipeError�ConnectionResetErrorr-)r�inputrCr0rrr�_feed_stdin�s
 zProcess._feed_stdincCsdS)Nr)rrrr�_noop�sz
Process._noopccs�|jj|�}|dkr|j}n|dks(t�|j}|jj�rV|dkrDdnd}tjd||�|j	�EdH}|jj�r�|dkrzdnd}tjd||�|j
�|S)Nr!rrrz%r communicate: read %sz%r communicate: close %s)rr$r�AssertionErrorrr&rAr
rC�readr-)rr*r(�stream�name�outputrrr�_read_stream�s

zProcess._read_streamNccs�|dk	r|j|�}n|j�}|jdk	r2|jd�}n|j�}|jdk	rP|jd�}n|j�}tj||||jd�EdH\}}}|j�EdH||fS)Nrr!)r)	rGrHrrNrrZgatherr&r<)rrFrrrrrr�communicate�s


zProcess.communicate)N)rr5r6rr �propertyr;r	r<r=r?r@rGrHrNrOrrrrr9ks	r9c
+sP�dkrtj����fdd�}�j||f|||d�|��EdH\}}	t||	��S)Ncst��d�S)N)rr)rr)rrrr�<lambda>�sz)create_subprocess_shell.<locals>.<lambda>)rrr)r�get_event_loopZsubprocess_shellr9)
�cmdrrrrr�kwds�protocol_factoryr(r"r)rrrr�s)rrrrrc/sT�dkrtj����fdd�}�j||f|�|||d�|��EdH\}	}
t|	|
��S)Ncst��d�S)N)rr)rr)rrrrrQ�sz(create_subprocess_exec.<locals>.<lambda>)rrr)rrRZsubprocess_execr9)Zprogramrrrrr�argsrTrUr(r"r)rrrr�s)�__all__�
subprocess�rrrrZ
coroutinesr	�logr
�PIPEZSTDOUTZDEVNULLZFlowControlMixinZSubprocessProtocolrr9Z_DEFAULT_LIMITrrrrrr�<module>s(X]PK[��)�)__pycache__/__init__.cpython-36.opt-1.pycnu�[���3


 \��@sBdZddlZyddlmZWnek
r8ddlZYnXejdkrryddlmZWnek
rpddlZYnXddlTddlTddl	Tddl
TddlTddlTddl
TddlTddlTddlTddlTejeje	je
jejeje
jejejejejZejdk�r,ddlTeej7ZnddlTeej7ZdS)z'The asyncio package, tracking PEP 3156.�N�)�	selectorsZwin32)�_overlapped)�*)�__doc__�sys�r�ImportError�platformrZbase_eventsZ
coroutinesZeventsZfuturesZlocksZ	protocolsZqueuesZstreams�
subprocessZtasksZ
transports�__all__Zwindows_eventsZunix_events�r
r
�(/usr/lib64/python3.6/asyncio/__init__.py�<module>s8
:PK[@!�)ŘŘ,__pycache__/base_events.cpython-36.opt-1.pycnu�[���3


 \��@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZdgZdZd
ZeeefZ e!e	d�Z"d)Z#dd�Z$dd�Z%dd�Z&dd�Z'dd�Z(dd�Z)de	j*ddd�dd�Z+e!e	d ��rRd!d"�Z,nd#d"�Z,d$d%�Z-Gd&d'�d'ej.�Z/Gd(d�dej0�Z1dS)*a�Base implementation of event loop.

The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.

Whenever a public API takes a callback, subsequent positional
arguments will be passed to the callback if/when it is called.  This
avoids the proliferation of trivial lambdas implementing closures.
Keyword arguments for the callback are not supported; this is a
conscious design decision, leaving the door open for keyword arguments
to modify the meaning of the API call itself.
�N�)�compat)�
coroutines)�events)�futures)�tasks)�	coroutine)�logger�
BaseEventLoop�dg�?�AF_INET6�icCs0|j}tt|dd�tj�r$t|j�St|�SdS)N�__self__)Z	_callback�
isinstance�getattrr�Task�reprr�str)�handle�cb�r�+/usr/lib64/python3.6/asyncio/base_events.py�_format_handle?s
rcCs(|tjkrdS|tjkrdSt|�SdS)Nz<pipe>z<stdout>)�
subprocess�PIPE�STDOUTr)�fdrrr�_format_pipeHs


rcCsLttd�std��n4y|jtjtjd�Wntk
rFtd��YnXdS)N�SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)�hasattr�socket�
ValueError�
setsockopt�
SOL_SOCKETr�OSError)�sockrrr�_set_reuseportQs

r&cCs&ttd�r|d@tjkS|tjkSdS)N�
SOCK_NONBLOCK�)rr �SOCK_STREAM)�	sock_typerrr�_is_stream_socket\s
r+cCs&ttd�r|d@tjkS|tjkSdS)Nr'r()rr �
SOCK_DGRAM)r*rrr�_is_dgram_sockeths
r-cCsvttd�sdS|dtjtjhks(|dkr,dSt|�r<tj}nt|�rLtj}ndS|dkr^d}nVt|t�rv|dkrvd}n>t|t�r�|dkr�d}n&yt	|�}Wnt
tfk
r�dSX|tjkr�tj
g}tr�|jtj�n|g}t|t�r�|jd�}d|k�rdSxp|D]h}yJtj||�t�r@|tjk�r@|||d||ddffS|||d||ffSWntk
�rjYnX�qWdS)N�	inet_ptonr��Zidna�%)rr �IPPROTO_TCPZIPPROTO_UDPr+r-r�bytesr�int�	TypeErrorr!�	AF_UNSPEC�AF_INET�	_HAS_IPv6�appendr�decoder.r$)�host�port�family�type�protoZafs�afrrr�_ipaddr_infopsL





rA)r=r>r?�flagsc
CsZ|dd�\}}t|||||�}|dk	r@|j�}	|	j|g�|	S|j||||||d�SdS)N�)r=r>r?rB)rA�
create_future�
set_result�getaddrinfo)
�addressr=r>r?rB�loopr;r<�info�futrrr�_ensure_resolved�srK�TCP_NODELAYcCs>|jtjtjhkr:t|j�r:|jtjkr:|jtjtj	d�dS)Nr)
r=r r7rr+r>r?r2r"rL)r%rrr�_set_nodelay�s
rMcCsdS)Nr)r%rrrrM�scCs.|j}t|t�r t|t�r dS|jj�dS)N)Z
_exceptionr�
BaseException�	Exception�_loop�stop)rJ�excrrr�_run_until_complete_cb�s

rSc@sHeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Ze	d
d��Z
dS)�ServercCs||_||_d|_g|_dS)Nr)rP�sockets�
_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�_attach�szServer._attachcCs.|jd8_|jdkr*|jdkr*|j�dS)Nrr)rVrU�_wakeup)rXrrr�_detach�szServer._detachcCsH|j}|dkrdSd|_x|D]}|jj|�qW|jdkrD|j�dS)Nr)rUrPZ
_stop_servingrVr^)rXrUr%rrr�close�s

zServer.closecCs0|j}d|_x|D]}|j�s|j|�qWdS)N)rW�donerE)rX�waiters�waiterrrrr^�s

zServer._wakeupccs<|jdks|jdkrdS|jj�}|jj|�|EdHdS)N)rUrWrPrDr9)rXrcrrr�wait_closed�s

zServer.wait_closedN)r[�
__module__�__qualname__rYr\r]r_r`r^rrdrrrrrT�s
rTc
@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd�d
d
d�dd�Z	d�dd
d
d
d�dd�Z
d�dd�Zd�dd�Zd�dd�Z
ed�dd��Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zed'd(��Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zej�r�d3d4�Zd5d6�Zd7d8�Zd9d:�Z d;d<�Z!d=d>�Z"d?d@�Z#dAdB�Z$dCdD�Z%dEdF�Z&dGdH�Z'dIdJ�Z(dKdL�Z)dMdMdMdMdN�dOdP�Z*d�dQdR�Z+ed�d
dMdMdMd
d
d
dS�dTdU��Z,ed�dVdW��Z-ed�dMdMdMd
d
d
d
dX�dYdZ��Z.ed[d\��Z/ed�e0j1e0j2d
d]d
d
d
d^�d_d`��Z3ed
da�dbdc��Z4eddde��Z5edfdg��Z6dhdi�Z7ee8j9e8j9e8j9ddjdMdk�dldm��Z:ee8j9e8j9e8j9dddMdk�dndo��Z;dpdq�Z<drds�Z=dtdu�Z>dvdw�Z?dxdy�Z@dzd{�ZAd|d}�ZBd~d�ZCd�d��ZDd�d��ZEd�d��ZFd
S)�r
cCs�d|_d|_d|_tj�|_g|_d|_d|_d|_	t
jd�j|_
d|_|jtjjodttjjd���d|_d|_d|_d|_ttd�r�tj�|_nd|_d|_dS)NrF�	monotonicZPYTHONASYNCIODEBUGg�������?�get_asyncgen_hooks) �_timer_cancelled_count�_closed�	_stopping�collections�deque�_ready�
_scheduled�_default_executorZ
_internal_fds�
_thread_id�timeZget_clock_infoZ
resolution�_clock_resolution�_exception_handler�	set_debug�sysrB�ignore_environment�bool�os�environ�get�slow_callback_duration�_current_handle�
_task_factory�_coroutine_wrapper_setr�weakref�WeakSet�
_asyncgens�_asyncgens_shutdown_called)rXrrrrY�s(

zBaseEventLoop.__init__cCs d|jj|j�|j�|j�fS)Nz"<%s running=%s closed=%s debug=%s>)rZr[�
is_running�	is_closed�	get_debug)rXrrrr\ szBaseEventLoop.__repr__cCstj|d�S)z,Create a Future object attached to the loop.)rH)rZFuture)rXrrrrD%szBaseEventLoop.create_futurecCs@|j�|jdkr0tj||d�}|jr<|jd=n|j||�}|S)zDSchedule a coroutine object.

        Return a task object.
        N)rHr���)�
_check_closedr~rr�_source_traceback)rX�coroZtaskrrr�create_task)s

zBaseEventLoop.create_taskcCs$|dk	rt|�rtd��||_dS)awSet a task factory that will be used by loop.create_task().

        If factory is None the default task factory will be set.

        If factory is a callable, it should have a signature matching
        '(loop, coro)', where 'loop' will be a reference to the active
        event loop, 'coro' will be a coroutine object.  The callable
        must return a Future.
        Nz'task factory must be a callable or None)�callabler5r~)rX�factoryrrr�set_task_factory7s
zBaseEventLoop.set_task_factorycCs|jS)z<Return a task factory, or None if the default one is in use.)r~)rXrrr�get_task_factoryEszBaseEventLoop.get_task_factoryN)�extra�servercCst�dS)zCreate socket transport.N)�NotImplementedError)rXr%�protocolrcr�r�rrr�_make_socket_transportIsz$BaseEventLoop._make_socket_transportF)�server_side�server_hostnamer�r�c	Cst�dS)zCreate SSL transport.N)r�)	rXZrawsockr��
sslcontextrcr�r�r�r�rrr�_make_ssl_transportNsz!BaseEventLoop._make_ssl_transportcCst�dS)zCreate datagram transport.N)r�)rXr%r�rGrcr�rrr�_make_datagram_transportTsz&BaseEventLoop._make_datagram_transportcCst�dS)zCreate read pipe transport.N)r�)rX�piper�rcr�rrr�_make_read_pipe_transportYsz'BaseEventLoop._make_read_pipe_transportcCst�dS)zCreate write pipe transport.N)r�)rXr�r�rcr�rrr�_make_write_pipe_transport^sz(BaseEventLoop._make_write_pipe_transportc	
Kst�dS)zCreate subprocess transport.N)r�)
rXr��args�shell�stdin�stdout�stderr�bufsizer��kwargsrrr�_make_subprocess_transportcsz(BaseEventLoop._make_subprocess_transportcCst�dS)z�Write a byte to self-pipe, to wake up the event loop.

        This may be called from a different thread.

        The subclass is responsible for implementing the self-pipe.
        N)r�)rXrrr�_write_to_selfjszBaseEventLoop._write_to_selfcCst�dS)zProcess selector events.N)r�)rX�
event_listrrr�_process_eventssszBaseEventLoop._process_eventscCs|jrtd��dS)NzEvent loop is closed)rj�RuntimeError)rXrrrr�wszBaseEventLoop._check_closedcCs*|jj|�|j�s&|j|j|j��dS)N)r��discardr��call_soon_threadsafer��aclose)rX�agenrrr�_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)r��warnings�warn�format�ResourceWarningr��add)rXr�rrr�_asyncgen_firstiter_hook�s
z&BaseEventLoop._asyncgen_firstiter_hookccs�d|_|jdkst|j�r dSt|j�}|jj�tjdd�|D�d|d��}|EdH}x8t||�D]*\}}t|t	�rf|j
dj|�||d��qfWdS)z,Shutdown all active asynchronous generators.TNcSsg|]}|j��qSr)r�)�.0Zagrrr�
<listcomp>�sz4BaseEventLoop.shutdown_asyncgens.<locals>.<listcomp>)Zreturn_exceptionsrHz?an error occurred during closing of asynchronous generator {!r})�message�	exceptionZasyncgen)r�r��len�list�clearr�gather�ziprrO�call_exception_handlerr�)rXZ
closing_agensZ
shutdown_coroZresults�resultr�rrr�shutdown_asyncgens�s"




z BaseEventLoop.shutdown_asyncgenscCs�|j�|j�rtd��tj�dk	r,td��|j|j�tj�|_	|j
dk	rftj�}tj
|j|jd�z$tj|�x|j�|jrtPqtWWdd|_d|_	tjd�|jd�|j
dk	r�tj
|�XdS)zRun until stop() is called.z"This event loop is already runningNz7Cannot run the event loop while another loop is running)�	firstiter�	finalizerF)r�r�r�rZ_get_running_loop�_set_coroutine_wrapper�_debug�	threading�	get_identrqr�rvrh�set_asyncgen_hooksr�r�Z_set_running_loop�	_run_oncerk)rXZold_agen_hooksrrr�run_forever�s0







zBaseEventLoop.run_forevercCs�|j�tj|�}tj||d�}|r,d|_|jt�z>y|j�Wn,|rj|j	�rj|j
�rj|j��YnXWd|jt�X|j	�s�t
d��|j�S)a\Run until the Future is done.

        If the argument is a coroutine, it is wrapped in a Task.

        WARNING: It would be disastrous to call run_until_complete()
        with the same coroutine twice -- it would wrap it in two
        different Tasks and that can't be good.

        Return the Future's result, or raise its exception.
        )rHFNz+Event loop stopped before Future completed.)r�rZisfuturerZ
ensure_futureZ_log_destroy_pendingZadd_done_callbackrSr�raZ	cancelledr�Zremove_done_callbackr�r�)rXZfutureZnew_taskrrr�run_until_complete�s 
z BaseEventLoop.run_until_completecCs
d|_dS)z�Stop running the event loop.

        Every callback already scheduled will still run.  This simply informs
        run_forever to stop looping after a complete iteration.
        TN)rk)rXrrrrQ�szBaseEventLoop.stopcCsj|j�rtd��|jrdS|jr,tjd|�d|_|jj�|jj�|j	}|dk	rfd|_	|j
dd�dS)z�Close the event loop.

        This clears the queues and shuts down the executor,
        but does not wait for the executor to finish.

        The event loop must not be running.
        z!Cannot close a running event loopNzClose %rTF)�wait)r�r�rjr�r	�debugrnr�rorpZshutdown)rX�executorrrrr`�s

zBaseEventLoop.closecCs|jS)z*Returns True if the event loop was closed.)rj)rXrrrr�szBaseEventLoop.is_closedcCs0|j�s,tjd|t|d�|j�s,|j�dS)Nzunclosed event loop %r)r�)r�r�r�r�r�r`)rXrrr�__del__s
zBaseEventLoop.__del__cCs
|jdk	S)z*Returns True if the event loop is running.N)rq)rXrrrr�szBaseEventLoop.is_runningcCstj�S)z�Return the time according to the event loop's clock.

        This is a float expressed in seconds since an epoch, but the
        epoch, precision, accuracy and drift are unspecified and may
        differ per event loop.
        )rrrg)rXrrrrrszBaseEventLoop.timecGs,|j|j�||f|��}|jr(|jd=|S)a8Arrange for a callback to be called at a given time.

        Return a Handle: an opaque object with a cancel() method that
        can be used to cancel the call.

        The delay can be an int or float, expressed in seconds.  It is
        always relative to the current time.

        Each callback will be called exactly once.  If two callbacks
        are scheduled for exactly the same time, it undefined which
        will be called first.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        rr�)�call_atrrr�)rXZdelay�callbackr��timerrrr�
call_later szBaseEventLoop.call_latercGsX|j�|jr"|j�|j|d�tj||||�}|jr@|jd=tj|j	|�d|_	|S)z|Like call_later(), but uses an absolute time.

        Absolute time corresponds to the event loop's time() method.
        r�rTr�)
r�r��
_check_thread�_check_callbackrZTimerHandler��heapq�heappushro)rX�whenr�r�r�rrrr�5szBaseEventLoop.call_atcGs@|j�|jr"|j�|j|d�|j||�}|jr<|jd=|S)aTArrange for a callback to be called as soon as possible.

        This operates as a FIFO queue: callbacks are called in the
        order in which they are registered.  Each callback will be
        called exactly once.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        �	call_soonrr�)r�r�r�r��
_call_soonr�)rXr�r�rrrrr�Es
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})rZiscoroutineZiscoroutinefunctionr5r�r�)rXr��methodrrrr�Xs

zBaseEventLoop._check_callbackcCs,tj|||�}|jr|jd=|jj|�|S)Nrr�)rZHandler�rnr9)rXr�r�rrrrr�cs
zBaseEventLoop._call_sooncCs,|jdkrdStj�}||jkr(td��dS)aoCheck that the current thread is the thread running the event loop.

        Non-thread-safe methods of this class make this assumption and will
        likely behave incorrectly when the assumption is violated.

        Should only be called when (self._debug == True).  The caller is
        responsible for checking this condition for performance reasons.
        NzMNon-thread-safe operation invoked on an event loop other than the current one)rqr�r�r�)rXZ	thread_idrrrr�js	

zBaseEventLoop._check_threadcGs@|j�|jr|j|d�|j||�}|jr4|jd=|j�|S)z"Like call_soon(), but thread-safe.r�rr�)r�r�r�r�r�r�)rXr�r�rrrrr�{sz"BaseEventLoop.call_soon_threadsafecGsZ|j�|jr|j|d�|dkr@|j}|dkr@tjj�}||_tj|j|f|��|d�S)N�run_in_executor)rH)	r�r�r�rp�
concurrentrZThreadPoolExecutorZwrap_futureZsubmit)rXr��funcr�rrrr��s
zBaseEventLoop.run_in_executorcCs
||_dS)N)rp)rXr�rrr�set_default_executor�sz"BaseEventLoop.set_default_executorcCs�d||fg}|r |jd|�|r2|jd|�|rD|jd|�|rV|jd|�dj|�}tjd|�|j�}tj||||||�}	|j�|}
d||
d	|	f}|
|jkr�tj|�n
tj|�|	S)
Nz%s:%rz	family=%rztype=%rzproto=%rzflags=%rz, zGet address info %sz(Getting address info %s took %.3f ms: %rg@�@)	r9�joinr	r�rrr rFr|rI)rXr;r<r=r>r?rB�msg�t0Zaddrinfo�dtrrr�_getaddrinfo_debug�s(


z BaseEventLoop._getaddrinfo_debugr)r=r>r?rBc	Cs>|jr |jd|j||||||�S|jdtj||||||�SdS)N)r�r�r�r rF)rXr;r<r=r>r?rBrrrrF�s


zBaseEventLoop.getaddrinfocCs|jdtj||�S)N)r�r �getnameinfo)rXZsockaddrrBrrrr��szBaseEventLoop.getnameinfo)�sslr=r?rBr%�
local_addrr�c#s|
dk	r|rtd��|
dkr2|r2|s.td��|}
|dk	sD|dk	�r�|dk	rTtd��t||f|tj|||d�}|g}|	dk	r�t|	|tj|||d�}
|j|
�nd}
tj||d�EdH|j�}|s�td��|
dk	r�|
j�}|s�td��g}�x�|D�]B\}}}}}y�tj|||d�}|j	d	�|
dk	�r�x�|D]j\}}}}}y|j
|�PWnHtk
�r�}z*t|jd
j||j
j���}|j|�WYdd}~XnX�q.W|j�d}w�|j�r�tjd||�|j||�EdHWn^tk
�r}z"|dk	�r�|j�|j|�WYdd}~Xq�|dk	�r,|j��Yq�XPq�Wt|�dk�rR|d
�nJt|d
��t�fdd�|D���r~|d
�tdjdjdd�|D�����n,|dk�r�td��t|j��s�tdj|���|j||||
�EdH\}}|j�r
|jd�}tjd|||||�||fS)a�Connect to a TCP server.

        Create a streaming transport connection to a given Internet host and
        port: socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_STREAM. protocol_factory must be
        a callable returning a protocol instance.

        This method is a coroutine which will try to establish the connection
        in the background.  When successful, the coroutine returns a
        (transport, protocol) pair.
        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)r�rR)�modelrr�	<genexpr>sz2BaseEventLoop.create_connection.<locals>.<genexpr>zMultiple exceptions: {}z, css|]}t|�VqdS)N)r)r�rRrrrr�#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)r9rr�r�r$�setblocking�bind�errnor��strerror�lowerr`r�r	r��sock_connectr�r�allr�r+r>�_create_connection_transport�get_extra_info)rX�protocol_factoryr;r<r�r=r?rBr%r�r��f1�fs�f2�infosZladdr_infos�
exceptionsr>ZcnamerG�_ZladdrrR�	transportr�r)r�r�create_connection�s�





"




zBaseEventLoop.create_connectionc
	cs�|jd�|�}|j�}|rFt|t�r*dn|}|j||||||d�}	n|j|||�}	y|EdHWn|	j��YnX|	|fS)NF)r�r�)r�rDrrxr�r�r`)
rXr%r�r�r�r�r�rcr�r�rrrr�=s
z*BaseEventLoop._create_connection_transport)r=r?rB�
reuse_address�
reuse_port�allow_broadcastr%c#s8|
dk	r�t|
j�s tdj|
����s@�s@|s@|s@|s@|s@|s@|	r~t��||||||	d�}djdd�|j�D��}tdj|���|
jd�d}
�n*�p��s�|d	kr�td
��||fdff}n�tj	�}x�d	�fd�ffD]~\}}|dk	r�t
||tj|||d�EdH}|�st
d
��xB|D]:\}}}}}||f}||k�r>ddg||<||||<�qWq�W��fdd�|j�D�}|�sztd��g}|dk�r�tjdk�o�tjdk}�x|D�]\\}}\}}d}
d}
y�tj|tj|d�}
|�r�|
jtjtjd�|�r�t|
�|	�r|
jtjtjd�|
jd���r,|
j|���rH|j|
|�EdH|}
Wn^t
k
�r�}z"|
dk	�rp|
j�|j|�WYdd}~Xn"|
dk	�r�|
j��YnXP�q�W|d	�|�}|j�}|j|
||
|�}|j�r
��r�tjd��||�ntj d�||�y|EdHWn|j��YnX||fS)zCreate datagram connection.Nz#A UDP Socket was expected, got {!r})r��remote_addrr=r?rBr�r�r�z, css"|]\}}|rdj||�VqdS)z{}={}N)r�)r��k�vrrrr�isz9BaseEventLoop.create_datagram_endpoint.<locals>.<genexpr>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||f�qS)rNrr)r��keyZ	addr_pair)r�r�rrr��sz:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address information�posix�cygwin)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!r��dictr��itemsr�rl�OrderedDictrKr r,r$ry�namerv�platformr"r#�SO_REUSEADDRr&ZSO_BROADCASTr�r�r`r9rDr�r�r	rIr�)rXr�r�r�r=r?rBr�r�r�r%ZoptsZproblemsZr_addrZaddr_pairs_infoZ
addr_infos�idxZaddrr�Zfamr�ZprorGrr�Z
local_addressZremote_addressrRr�rcr�r)r�r�r�create_datagram_endpointUs�








z&BaseEventLoop.create_datagram_endpointccs4t||f|tj||d�EdH}|s0tdj|���|S)N)r=r>rBrHz%getaddrinfo({!r}) returned empty list)rKr r)r$r�)rXr;r<r=rBr�rrr�_create_server_getaddrinfo�s
z(BaseEventLoop._create_server_getaddrinfor)r=rBr%�backlogr�r�r�c #s�t|t�rtd��|dk	s$�dk	�r|dk	r4td��|	dkrPtjdkoNtjdk}	g}|dkrddg}n$t|t�s|t|t	j
�r�|g}n|}����fdd�|D�}
tj|
d	�i�EdH}t
tjj|��}d
}�z �x|D�]
}|\}}}}}ytj|||�}Wn6tjk
�r2�j�r,tjd|||dd
�w�YnX|j|�|	�rV|jtjtjd�|
�rdt|�t�r�|tjk�r�ttd��r�|jtjtjd�y|j |�Wq�t!k
�r�}z t!|j"d||j#j$�f��WYdd}~Xq�Xq�Wd}Wd|�sx|D]}|j%��q�WXn2|dk�r"td��t&|j'��s<tdj(|���|g}t)�|�}x4|D],}|j*|�|j+d
��j,|||||��qRW�j�r�tj-d|�|S)a1Create a TCP server.

        The host parameter can be a string, in that case the TCP server is bound
        to host and port.

        The host parameter can also be a sequence of strings and in that case
        the TCP server is bound to all hosts of the sequence. If a host
        appears multiple times (possibly indirectly e.g. when hostnames
        resolve to the same IP address), the server is only bound once to that
        host.

        Return a Server object which can be used to stop the service.

        This method is a coroutine.
        z*ssl argument must be an SSLContext or NoneNz8host/port and sock can not be specified at the same timerrr0csg|]}�j|���d��qS))r=rB)r)r�r;)r=rBr<rXrrr�sz/BaseEventLoop.create_server.<locals>.<listcomp>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!ryrrvrrrl�Iterablerr��set�	itertools�chain�
from_iterabler �errorr�r	�warningr9r"r#r	r&r8rrrZIPV6_V6ONLYr�r$r�r�r�r`r+r>r�rTZlistenr�Z_start_servingrI)rXr�r;r<r=rBr%r
r�r�r�rUZhostsr�r�Z	completed�resr@Zsocktyper?Z	canonnameZsa�errr�r)r=rBr<rXr�
create_server�s�


(





zBaseEventLoop.create_server)r�ccs^t|j�stdj|���|j|||ddd�EdH\}}|jrV|jd�}tjd|||�||fS)aHandle an accepted connection.

        This is used by servers that accept connections outside of
        asyncio but that use asyncio to handle connections.

        This method is a coroutine.  When completed, the coroutine
        returns a (transport, protocol) pair.
        z&A Stream Socket was expected, got {!r}r0T)r�Nr z%r handled: (%r, %r))	r+r>r!r�r�r�r�r	r�)rXr�r%r�r�r�rrr�connect_accepted_socketAs


z%BaseEventLoop.connect_accepted_socketccsd|�}|j�}|j|||�}y|EdHWn|j��YnX|jr\tjd|j�||�||fS)Nz Read pipe %r connected: (%r, %r))rDr�r`r�r	r��fileno)rXr�r�r�rcr�rrr�connect_read_pipeXszBaseEventLoop.connect_read_pipeccsd|�}|j�}|j|||�}y|EdHWn|j��YnX|jr\tjd|j�||�||fS)Nz!Write pipe %r connected: (%r, %r))rDr�r`r�r	r�r)rXr�r�r�rcr�rrr�connect_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	r�r�)rXr�r�r�r�rIrrr�_log_subprocesszszBaseEventLoop._log_subprocessT)r�r�r��universal_newlinesr�r�c
ks�t|ttf�std��|r"td��|s.td��|dkr>td��|�}
d}|jrfd|}|j||||�|j|
|d||||f|	�EdH}|jr�|dk	r�tjd||�||
fS)	Nzcmd must be a stringz universal_newlines must be Falsezshell must be Truerzbufsize must be 0zrun shell command %rTz%s: %r)	rr3rr!r�rr�r	rI)
rXr��cmdr�r�r�r r�r�r�r��	debug_logr�rrr�subprocess_shell�s$zBaseEventLoop.subprocess_shellcos�|rtd��|rtd��|dkr(td��|f|	}x,|D]$}t|ttf�s8tdt|�j��q8W|�}
d}|jr�d|}|j||||�|j	|
|d||||f|
�EdH}|jr�|dk	r�t
jd||�||
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[r�rr�r	rI)rXr�Zprogramr�r�r�r r�r�r�r�Z
popen_args�argr�r"r�rrr�subprocess_exec�s,

zBaseEventLoop.subprocess_execcCs|jS)zKReturn an exception handler, or None if the default one is in use.
        )rt)rXrrr�get_exception_handler�sz#BaseEventLoop.get_exception_handlercCs*|dk	r t|�r tdj|���||_dS)a�Set handler as the new event loop exception handler.

        If handler is None, the default exception handler will
        be set.

        If handler is a callable object, it should have a
        signature matching '(loop, context)', where 'loop'
        will be a reference to the active event loop, 'context'
        will be a dict object (see `call_exception_handler()`
        documentation for details about context).
        Nz/A callable object or None is expected, got {!r})r�r5r�rt)rXZhandlerrrr�set_exception_handler�sz#BaseEventLoop.set_exception_handlerc	Cs|jd�}|sd}|jd�}|dk	r6t|�||jf}nd}d|kr`|jdk	r`|jjr`|jj|d<|g}x�t|�D]�}|dkr~qp||}|dkr�djtj|��}d	}||j	�7}n2|dkr�djtj|��}d
}||j	�7}nt
|�}|jdj||��qpWt
jdj|�|d
�dS)aEDefault exception handler.

        This is called when an exception occurs and no exception
        handler is set, and can be called by a custom exception
        handler that wants to defer to the default behavior.

        This default handler logs the error message and other
        context-dependent information.  In debug mode, a truncated
        stack trace is also appended showing where the given object
        (e.g. a handle or future or task) was created, if any.

        The context parameter has the same meaning as in
        `call_exception_handler()`.
        r�z!Unhandled exception in event loopr�NFZsource_tracebackZhandle_tracebackr0z+Object created at (most recent call last):
z+Handle created at (most recent call last):
z{}: {}�
)r>r�r�)r{r>�
__traceback__r}r��sortedr��	traceback�format_list�rstriprr9r�r	r)	rX�contextr�r�rZ	log_linesr�value�tbrrr�default_exception_handler�s6


z'BaseEventLoop.default_exception_handlercCs�|jdkr>y|j|�Wq�tk
r:tjddd�Yq�Xnny|j||�Wn\tk
r�}z@y|jd||d��Wn"tk
r�tjddd�YnXWYdd}~XnXdS)aCall the current event loop's exception handler.

        The context argument is a dict containing the following keys:

        - 'message': Error message;
        - 'exception' (optional): Exception object;
        - 'future' (optional): Future instance;
        - 'handle' (optional): Handle instance;
        - 'protocol' (optional): Protocol instance;
        - 'transport' (optional): Transport instance;
        - 'socket' (optional): Socket instance;
        - 'asyncgen' (optional): Asynchronous generator that caused
                                 the exception.

        New keys maybe introduced in the future.

        Note: do not overload this method in an event loop subclass.
        For custom exception handling, use the
        `set_exception_handler()` method.
        Nz&Exception in default exception handlerT)rz$Unhandled error in exception handler)r�r�r.zeException in default exception handler while handling an unexpected error in custom exception handler)rtr1rOr	r)rXr.rRrrrr�s"
z$BaseEventLoop.call_exception_handlercCs|jr
dS|jj|�dS)z3Add a Handle to _scheduled (TimerHandle) or _ready.N)�
_cancelledrnr9)rXrrrr�
_add_callback9szBaseEventLoop._add_callbackcCs|j|�|j�dS)z6Like _add_callback() but called from a signal handler.N)r3r�)rXrrrr�_add_callback_signalsafeAs
z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)z3Notification that a TimerHandle has been cancelled.rN)rori)rXrrrr�_timer_handle_cancelledFsz%BaseEventLoop._timer_handle_cancelledcCs�t|j�}|tkrd|j|tkrdg}x&|jD]}|jr>d|_q,|j|�q,Wtj|�||_d|_n8x6|jr�|jdjr�|jd8_tj	|j�}d|_qfWd}|j
s�|jr�d}n*|jr�|jdj}t
td||j��t�}|jo�|dk�r�|j�}|jj|�}|j�|}|dk�rtj}	ntj}	t|�}
|dk�rLtj|	d|d|
�nD|
�rntj|	d|d|d|
�n"|dk�r�tj|	d	|d|d�n|jj|�}|j|�|j�|j}xD|j�r�|jd}|j|k�r�Ptj	|j�}d|_|j
j|��q�Wt|j
�}x�t|�D]|}
|j
j�}|j�r*�q|j�r�zD||_|j�}|j�|j�|}||jk�rttj d
t!|�|�Wdd|_Xn|j��qWd}dS)z�Run one full iteration of the event loop.

        This calls all currently ready callbacks, polls for I/O,
        schedules the resulting callbacks, and finally schedules
        'call_later' callbacks.
        FrrNg�?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)"r�ro�_MIN_SCHEDULED_TIMER_HANDLESri�%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr2r9r��heapify�heappoprnrkZ_when�min�maxrr�MAXIMUM_SELECT_TIMEOUTr�Z	_selectorZselect�logging�INFO�DEBUGr	�logr�rs�range�popleftr}Z_runr|rr)rXZsched_countZ
new_scheduledrZtimeoutr�r�r�r��levelZneventZend_timeZntodo�irrrr�Ks�











zBaseEventLoop._run_oncecCs�ytj}tj}Wntk
r$dSXt|�}|j|kr<dStj}|�}|rz|d|fkrjtj	d|t
�q�||�d|_n,|d|fkr�tj	d|t
�n|d�d|_dS)Nz[loop.set_debug(True): cannot set debug coroutine wrapper; another wrapper is already set %rTzWloop.set_debug(False): cannot unset debug coroutine wrapper; another wrapper was set %rF)rv�set_coroutine_wrapper�get_coroutine_wrapper�AttributeErrorrxrrZ
debug_wrapperr�r��RuntimeWarning)rX�enabledZset_wrapperZget_wrapper�wrapperZcurrent_wrapperrrrr��s.

z$BaseEventLoop._set_coroutine_wrappercCs|jS)N)r�)rXrrrr��szBaseEventLoop.get_debugcCs||_|j�r|j|�dS)N)r�r�r�)rXrIrrrru�szBaseEventLoop.set_debug)N)N)NNN)NN)NN)N)r)NN)F)NN)NN)Gr[rerfrYr\rDr�r�r�r�r�r�r�r�rr�r�r�r�r�r�r�r�r�rQr`r�rZPY34r�r�rrr�r�r�r�r�r�r�r�r�r�rFr�r�r�rrr r6Z
AI_PASSIVErrrrrrrr#r%r&r'r1r�r3r4r5r�r�r�rurrrrr
�s�!


		%	

u	`
12c!i�Q)2�__doc__rlZconcurrent.futuresr�r��inspectrr=ryr rr�rrr+rvr�r�r0rrrrrrr@r	�__all__r6r7�BrokenPipeError�ConnectionResetError�ConnectionAbortedErrorZ_FATAL_ERROR_IGNORErr8r<rrr&r+r-rAr)rKrMrSZAbstractServerrTZAbstractEventLoopr
rrrr�<module>sV
		;


/PK[P�\~zz,__pycache__/base_events.cpython-36.opt-2.pycnu�[���3


 \��@s�ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlmZddlmZddlmZddlmZddlmZddlmZdd	lmZd
gZdZdZeeefZe ed
�Z!d(Z"dd�Z#dd�Z$dd�Z%dd�Z&dd�Z'dd�Z(dej)ddd�dd�Z*e ed��rNd 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�
BaseEventLoop�dg�?�AF_INET6�icCs0|j}tt|dd�tj�r$t|j�St|�SdS)N�__self__)Z	_callback�
isinstance�getattrr�Task�reprr�str)�handle�cb�r�+/usr/lib64/python3.6/asyncio/base_events.py�_format_handle?s
rcCs(|tjkrdS|tjkrdSt|�SdS)Nz<pipe>z<stdout>)�
subprocess�PIPE�STDOUTr)�fdrrr�_format_pipeHs


rcCsLttd�std��n4y|jtjtjd�Wntk
rFtd��YnXdS)N�SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)�hasattr�socket�
ValueError�
setsockopt�
SOL_SOCKETr�OSError)�sockrrr�_set_reuseportQs

r&cCs&ttd�r|d@tjkS|tjkSdS)N�
SOCK_NONBLOCK�)rr �SOCK_STREAM)�	sock_typerrr�_is_stream_socket\s
r+cCs&ttd�r|d@tjkS|tjkSdS)Nr'r()rr �
SOCK_DGRAM)r*rrr�_is_dgram_sockeths
r-cCsvttd�sdS|dtjtjhks(|dkr,dSt|�r<tj}nt|�rLtj}ndS|dkr^d}nVt|t�rv|dkrvd}n>t|t�r�|dkr�d}n&yt	|�}Wnt
tfk
r�dSX|tjkr�tj
g}tr�|jtj�n|g}t|t�r�|jd�}d|k�rdSxp|D]h}yJtj||�t�r@|tjk�r@|||d||ddffS|||d||ffSWntk
�rjYnX�qWdS)N�	inet_ptonr��Zidna�%)rr �IPPROTO_TCPZIPPROTO_UDPr+r-r�bytesr�int�	TypeErrorr!�	AF_UNSPEC�AF_INET�	_HAS_IPv6�appendr�decoder.r$)�host�port�family�type�protoZafs�afrrr�_ipaddr_infopsL





rA)r=r>r?�flagsc
CsZ|dd�\}}t|||||�}|dk	r@|j�}	|	j|g�|	S|j||||||d�SdS)N�)r=r>r?rB)rA�
create_future�
set_result�getaddrinfo)
�addressr=r>r?rB�loopr;r<�info�futrrr�_ensure_resolved�srK�TCP_NODELAYcCs>|jtjtjhkr:t|j�r:|jtjkr:|jtjtj	d�dS)Nr)
r=r r7rr+r>r?r2r"rL)r%rrr�_set_nodelay�s
rMcCsdS)Nr)r%rrrrM�scCs.|j}t|t�r t|t�r dS|jj�dS)N)Z
_exceptionr�
BaseException�	Exception�_loop�stop)rJ�excrrr�_run_until_complete_cb�s

rSc@sHeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Ze	d
d��Z
dS)�ServercCs||_||_d|_g|_dS)Nr)rP�sockets�
_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�_attach�szServer._attachcCs.|jd8_|jdkr*|jdkr*|j�dS)Nrr)rVrU�_wakeup)rXrrr�_detach�szServer._detachcCsH|j}|dkrdSd|_x|D]}|jj|�qW|jdkrD|j�dS)Nr)rUrPZ
_stop_servingrVr^)rXrUr%rrr�close�s

zServer.closecCs0|j}d|_x|D]}|j�s|j|�qWdS)N)rW�donerE)rX�waiters�waiterrrrr^�s

zServer._wakeupccs<|jdks|jdkrdS|jj�}|jj|�|EdHdS)N)rUrWrPrDr9)rXrcrrr�wait_closed�s

zServer.wait_closedN)r[�
__module__�__qualname__rYr\r]r_r`r^rrdrrrrrT�s
rTc
@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd�d
d
d�dd�Z	d�dd
d
d
d�dd�Z
d�dd�Zd�dd�Zd�dd�Z
ed�dd��Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zed'd(��Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zej�r�d3d4�Zd5d6�Zd7d8�Zd9d:�Z d;d<�Z!d=d>�Z"d?d@�Z#dAdB�Z$dCdD�Z%dEdF�Z&dGdH�Z'dIdJ�Z(dKdL�Z)dMdMdMdMdN�dOdP�Z*d�dQdR�Z+ed�d
dMdMdMd
d
d
dS�dTdU��Z,ed�dVdW��Z-ed�dMdMdMd
d
d
d
dX�dYdZ��Z.ed[d\��Z/ed�e0j1e0j2d
d]d
d
d
d^�d_d`��Z3ed
da�dbdc��Z4eddde��Z5edfdg��Z6dhdi�Z7ee8j9e8j9e8j9ddjdMdk�dldm��Z:ee8j9e8j9e8j9dddMdk�dndo��Z;dpdq�Z<drds�Z=dtdu�Z>dvdw�Z?dxdy�Z@dzd{�ZAd|d}�ZBd~d�ZCd�d��ZDd�d��ZEd�d��ZFd
S)�r
cCs�d|_d|_d|_tj�|_g|_d|_d|_d|_	t
jd�j|_
d|_|jtjjodttjjd���d|_d|_d|_d|_ttd�r�tj�|_nd|_d|_dS)NrF�	monotonicZPYTHONASYNCIODEBUGg�������?�get_asyncgen_hooks) �_timer_cancelled_count�_closed�	_stopping�collections�deque�_ready�
_scheduled�_default_executorZ
_internal_fds�
_thread_id�timeZget_clock_infoZ
resolution�_clock_resolution�_exception_handler�	set_debug�sysrB�ignore_environment�bool�os�environ�get�slow_callback_duration�_current_handle�
_task_factory�_coroutine_wrapper_setr�weakref�WeakSet�
_asyncgens�_asyncgens_shutdown_called)rXrrrrY�s(

zBaseEventLoop.__init__cCs d|jj|j�|j�|j�fS)Nz"<%s running=%s closed=%s debug=%s>)rZr[�
is_running�	is_closed�	get_debug)rXrrrr\ szBaseEventLoop.__repr__cCstj|d�S)N)rH)rZFuture)rXrrrrD%szBaseEventLoop.create_futurecCs@|j�|jdkr0tj||d�}|jr<|jd=n|j||�}|S)N)rHr���)�
_check_closedr~rr�_source_traceback)rX�coroZtaskrrr�create_task)s

zBaseEventLoop.create_taskcCs$|dk	rt|�rtd��||_dS)Nz'task factory must be a callable or None)�callabler5r~)rX�factoryrrr�set_task_factory7s
zBaseEventLoop.set_task_factorycCs|jS)N)r~)rXrrr�get_task_factoryEszBaseEventLoop.get_task_factoryN)�extra�servercCst�dS)N)�NotImplementedError)rXr%�protocolrcr�r�rrr�_make_socket_transportIsz$BaseEventLoop._make_socket_transportF)�server_side�server_hostnamer�r�c	Cst�dS)N)r�)	rXZrawsockr��
sslcontextrcr�r�r�r�rrr�_make_ssl_transportNsz!BaseEventLoop._make_ssl_transportcCst�dS)N)r�)rXr%r�rGrcr�rrr�_make_datagram_transportTsz&BaseEventLoop._make_datagram_transportcCst�dS)N)r�)rX�piper�rcr�rrr�_make_read_pipe_transportYsz'BaseEventLoop._make_read_pipe_transportcCst�dS)N)r�)rXr�r�rcr�rrr�_make_write_pipe_transport^sz(BaseEventLoop._make_write_pipe_transportc	
Kst�dS)N)r�)
rXr��args�shell�stdin�stdout�stderr�bufsizer��kwargsrrr�_make_subprocess_transportcsz(BaseEventLoop._make_subprocess_transportcCst�dS)N)r�)rXrrr�_write_to_selfjszBaseEventLoop._write_to_selfcCst�dS)N)r�)rX�
event_listrrr�_process_eventssszBaseEventLoop._process_eventscCs|jrtd��dS)NzEvent loop is closed)rj�RuntimeError)rXrrrr�wszBaseEventLoop._check_closedcCs*|jj|�|j�s&|j|j|j��dS)N)r��discardr��call_soon_threadsafer��aclose)rX�agenrrr�_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)r��warnings�warn�format�ResourceWarningr��add)rXr�rrr�_asyncgen_firstiter_hook�s
z&BaseEventLoop._asyncgen_firstiter_hookccs�d|_|jdkst|j�r dSt|j�}|jj�tjdd�|D�d|d��}|EdH}x8t||�D]*\}}t|t	�rf|j
dj|�||d��qfWdS)NTcSsg|]}|j��qSr)r�)�.0Zagrrr�
<listcomp>�sz4BaseEventLoop.shutdown_asyncgens.<locals>.<listcomp>)Zreturn_exceptionsrHz?an error occurred during closing of asynchronous generator {!r})�message�	exceptionZasyncgen)r�r��len�list�clearr�gather�ziprrO�call_exception_handlerr�)rXZ
closing_agensZ
shutdown_coroZresults�resultr�rrr�shutdown_asyncgens�s"




z BaseEventLoop.shutdown_asyncgenscCs�|j�|j�rtd��tj�dk	r,td��|j|j�tj�|_	|j
dk	rftj�}tj
|j|jd�z$tj|�x|j�|jrtPqtWWdd|_d|_	tjd�|jd�|j
dk	r�tj
|�XdS)Nz"This event loop is already runningz7Cannot run the event loop while another loop is running)�	firstiter�	finalizerF)r�r�r�rZ_get_running_loop�_set_coroutine_wrapper�_debug�	threading�	get_identrqr�rvrh�set_asyncgen_hooksr�r�Z_set_running_loop�	_run_oncerk)rXZold_agen_hooksrrr�run_forever�s0







zBaseEventLoop.run_forevercCs�|j�tj|�}tj||d�}|r,d|_|jt�z>y|j�Wn,|rj|j	�rj|j
�rj|j��YnXWd|jt�X|j	�s�t
d��|j�S)N)rHFz+Event loop stopped before Future completed.)r�rZisfuturerZ
ensure_futureZ_log_destroy_pendingZadd_done_callbackrSr�raZ	cancelledr�Zremove_done_callbackr�r�)rXZfutureZnew_taskrrr�run_until_complete�s 
z BaseEventLoop.run_until_completecCs
d|_dS)NT)rk)rXrrrrQ�szBaseEventLoop.stopcCsj|j�rtd��|jrdS|jr,tjd|�d|_|jj�|jj�|j	}|dk	rfd|_	|j
dd�dS)Nz!Cannot close a running event loopzClose %rTF)�wait)r�r�rjr�r	�debugrnr�rorpZshutdown)rX�executorrrrr`�s

zBaseEventLoop.closecCs|jS)N)rj)rXrrrr�szBaseEventLoop.is_closedcCs0|j�s,tjd|t|d�|j�s,|j�dS)Nzunclosed event loop %r)r�)r�r�r�r�r�r`)rXrrr�__del__s
zBaseEventLoop.__del__cCs
|jdk	S)N)rq)rXrrrr�szBaseEventLoop.is_runningcCstj�S)N)rrrg)rXrrrrrszBaseEventLoop.timecGs,|j|j�||f|��}|jr(|jd=|S)Nrr�)�call_atrrr�)rXZdelay�callbackr��timerrrr�
call_later szBaseEventLoop.call_latercGsX|j�|jr"|j�|j|d�tj||||�}|jr@|jd=tj|j	|�d|_	|S)Nr�rTr�)
r�r��
_check_thread�_check_callbackrZTimerHandler��heapq�heappushro)rX�whenr�r�r�rrrr�5szBaseEventLoop.call_atcGs@|j�|jr"|j�|j|d�|j||�}|jr<|jd=|S)N�	call_soonrr�)r�r�r�r��
_call_soonr�)rXr�r�rrrrr�Es
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})rZiscoroutineZiscoroutinefunctionr5r�r�)rXr��methodrrrr�Xs

zBaseEventLoop._check_callbackcCs,tj|||�}|jr|jd=|jj|�|S)Nrr�)rZHandler�rnr9)rXr�r�rrrrr�cs
zBaseEventLoop._call_sooncCs,|jdkrdStj�}||jkr(td��dS)NzMNon-thread-safe operation invoked on an event loop other than the current one)rqr�r�r�)rXZ	thread_idrrrr�js	

zBaseEventLoop._check_threadcGs@|j�|jr|j|d�|j||�}|jr4|jd=|j�|S)Nr�rr�)r�r�r�r�r�r�)rXr�r�rrrrr�{sz"BaseEventLoop.call_soon_threadsafecGsZ|j�|jr|j|d�|dkr@|j}|dkr@tjj�}||_tj|j|f|��|d�S)N�run_in_executor)rH)	r�r�r�rp�
concurrentrZThreadPoolExecutorZwrap_futureZsubmit)rXr��funcr�rrrr��s
zBaseEventLoop.run_in_executorcCs
||_dS)N)rp)rXr�rrr�set_default_executor�sz"BaseEventLoop.set_default_executorcCs�d||fg}|r |jd|�|r2|jd|�|rD|jd|�|rV|jd|�dj|�}tjd|�|j�}tj||||||�}	|j�|}
d||
d	|	f}|
|jkr�tj|�n
tj|�|	S)
Nz%s:%rz	family=%rztype=%rzproto=%rzflags=%rz, zGet address info %sz(Getting address info %s took %.3f ms: %rg@�@)	r9�joinr	r�rrr rFr|rI)rXr;r<r=r>r?rB�msg�t0Zaddrinfo�dtrrr�_getaddrinfo_debug�s(


z BaseEventLoop._getaddrinfo_debugr)r=r>r?rBc	Cs>|jr |jd|j||||||�S|jdtj||||||�SdS)N)r�r�r�r rF)rXr;r<r=r>r?rBrrrrF�s


zBaseEventLoop.getaddrinfocCs|jdtj||�S)N)r�r �getnameinfo)rXZsockaddrrBrrrr��szBaseEventLoop.getnameinfo)�sslr=r?rBr%�
local_addrr�c#s|
dk	r|rtd��|
dkr2|r2|s.td��|}
|dk	sD|dk	�r�|dk	rTtd��t||f|tj|||d�}|g}|	dk	r�t|	|tj|||d�}
|j|
�nd}
tj||d�EdH|j�}|s�td��|
dk	r�|
j�}|s�td��g}�x�|D�]B\}}}}}y�tj|||d�}|j	d�|
dk	�r�x�|D]j\}}}}}y|j
|�PWnHtk
�r�}z*t|jd	j||j
j���}|j|�WYdd}~XnX�q.W|j�d}w�|j�r�tjd
||�|j||�EdHWn^tk
�r}z"|dk	�r�|j�|j|�WYdd}~Xq�|dk	�r,|j��Yq�XPq�Wt|�dk�rR|d�nJt|d��t�fd
d�|D���r~|d�tdjdjdd�|D�����n,|dk�r�td��t|j��s�tdj|���|j||||
�EdH\}}|j�r
|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)r�rR)�modelrr�	<genexpr>sz2BaseEventLoop.create_connection.<locals>.<genexpr>zMultiple exceptions: {}z, css|]}t|�VqdS)N)r)r�rRrrrr�#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)r9rr�r�r$�setblocking�bind�errnor��strerror�lowerr`r�r	r��sock_connectr�r�allr�r+r>�_create_connection_transport�get_extra_info)rX�protocol_factoryr;r<r�r=r?rBr%r�r��f1�fs�f2�infosZladdr_infos�
exceptionsr>ZcnamerG�_ZladdrrR�	transportr�r)r�r�create_connection�s�





"




zBaseEventLoop.create_connectionc
	cs�|jd�|�}|j�}|rFt|t�r*dn|}|j||||||d�}	n|j|||�}	y|EdHWn|	j��YnX|	|fS)NF)r�r�)r�rDrrxr�r�r`)
rXr%r�r�r�r�r�rcr�r�rrrr�=s
z*BaseEventLoop._create_connection_transport)r=r?rB�
reuse_address�
reuse_port�allow_broadcastr%c#s8|
dk	r�t|
j�s tdj|
����s@�s@|s@|s@|s@|s@|s@|	r~t��||||||	d�}djdd�|j�D��}tdj|���|
jd�d}
�n*�p��s�|dkr�td	��||fdff}n�tj	�}x�d�fd
�ffD]~\}}|dk	r�t
||tj|||d�EdH}|�st
d��xB|D]:\}}}}}||f}||k�r>ddg||<||||<�qWq�W��fd
d�|j�D�}|�sztd��g}|dk�r�tjdk�o�tjdk}�x|D�]\\}}\}}d}
d}
y�tj|tj|d�}
|�r�|
jtjtjd
�|�r�t|
�|	�r|
jtjtjd
�|
jd���r,|
j|���rH|j|
|�EdH|}
Wn^t
k
�r�}z"|
dk	�rp|
j�|j|�WYdd}~Xn"|
dk	�r�|
j��YnXP�q�W|d�|�}|j�}|j|
||
|�}|j�r
��r�tjd��||�ntj d�||�y|EdHWn|j��YnX||fS)Nz#A UDP Socket was expected, got {!r})r��remote_addrr=r?rBr�r�r�z, css"|]\}}|rdj||�VqdS)z{}={}N)r�)r��k�vrrrr�isz9BaseEventLoop.create_datagram_endpoint.<locals>.<genexpr>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||f�qS)rNrr)r��keyZ	addr_pair)r�r�rrr��sz:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address information�posix�cygwin)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!r��dictr��itemsr�rl�OrderedDictrKr r,r$ry�namerv�platformr"r#�SO_REUSEADDRr&ZSO_BROADCASTr�r�r`r9rDr�r�r	rIr�)rXr�r�r�r=r?rBr�r�r�r%ZoptsZproblemsZr_addrZaddr_pairs_infoZ
addr_infos�idxZaddrr�Zfamr�ZprorGrr�Z
local_addressZremote_addressrRr�rcr�r)r�r�r�create_datagram_endpointUs�








z&BaseEventLoop.create_datagram_endpointccs4t||f|tj||d�EdH}|s0tdj|���|S)N)r=r>rBrHz%getaddrinfo({!r}) returned empty list)rKr r)r$r�)rXr;r<r=rBr�rrr�_create_server_getaddrinfo�s
z(BaseEventLoop._create_server_getaddrinfor)r=rBr%�backlogr�r�r�c #s�t|t�rtd��|dk	s$�dk	�r|dk	r4td��|	dkrPtjdkoNtjdk}	g}|dkrddg}n$t|t�s|t|t	j
�r�|g}n|}����fdd�|D�}
tj|
d�i�EdH}t
tjj|��}d	}�z �x|D�]
}|\}}}}}ytj|||�}Wn6tjk
�r2�j�r,tjd
|||dd�w�YnX|j|�|	�rV|jtjtjd�|
�rdt|�t�r�|tjk�r�ttd
��r�|jtjtjd�y|j |�Wq�t!k
�r�}z t!|j"d||j#j$�f��WYdd}~Xq�Xq�Wd}Wd|�sx|D]}|j%��q�WXn2|dk�r"td��t&|j'��s<tdj(|���|g}t)�|�}x4|D],}|j*|�|j+d	��j,|||||��qRW�j�r�tj-d|�|S)Nz*ssl argument must be an SSLContext or Nonez8host/port and sock can not be specified at the same timerrr0csg|]}�j|���d��qS))r=rB)r)r�r;)r=rBr<rXrrr�sz/BaseEventLoop.create_server.<locals>.<listcomp>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!ryrrvrrrl�Iterablerr��set�	itertools�chain�
from_iterabler �errorr�r	�warningr9r"r#r	r&r8rrrZIPV6_V6ONLYr�r$r�r�r�r`r+r>r�rTZlistenr�Z_start_servingrI)rXr�r;r<r=rBr%r
r�r�r�rUZhostsr�r�Z	completed�resr@Zsocktyper?Z	canonnameZsa�errr�r)r=rBr<rXr�
create_server�s�


(





zBaseEventLoop.create_server)r�ccs^t|j�stdj|���|j|||ddd�EdH\}}|jrV|jd�}tjd|||�||fS)Nz&A Stream Socket was expected, got {!r}r0T)r�r z%r handled: (%r, %r))	r+r>r!r�r�r�r�r	r�)rXr�r%r�r�r�rrr�connect_accepted_socketAs


z%BaseEventLoop.connect_accepted_socketccsd|�}|j�}|j|||�}y|EdHWn|j��YnX|jr\tjd|j�||�||fS)Nz Read pipe %r connected: (%r, %r))rDr�r`r�r	r��fileno)rXr�r�r�rcr�rrr�connect_read_pipeXszBaseEventLoop.connect_read_pipeccsd|�}|j�}|j|||�}y|EdHWn|j��YnX|jr\tjd|j�||�||fS)Nz!Write pipe %r connected: (%r, %r))rDr�r`r�r	r�r)rXr�r�r�rcr�rrr�connect_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	r�r�)rXr�r�r�r�rIrrr�_log_subprocesszszBaseEventLoop._log_subprocessT)r�r�r��universal_newlinesr�r�c
ks�t|ttf�std��|r"td��|s.td��|dkr>td��|�}
d}|jrfd|}|j||||�|j|
|d||||f|	�EdH}|jr�|dk	r�tjd||�||
fS)	Nzcmd must be a stringz universal_newlines must be Falsezshell must be Truerzbufsize must be 0zrun shell command %rTz%s: %r)	rr3rr!r�rr�r	rI)
rXr��cmdr�r�r�r r�r�r�r��	debug_logr�rrr�subprocess_shell�s$zBaseEventLoop.subprocess_shellcos�|rtd��|rtd��|dkr(td��|f|	}x,|D]$}t|ttf�s8tdt|�j��q8W|�}
d}|jr�d|}|j||||�|j	|
|d||||f|
�EdH}|jr�|dk	r�t
jd||�||
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[r�rr�r	rI)rXr�Zprogramr�r�r�r r�r�r�r�Z
popen_args�argr�r"r�rrr�subprocess_exec�s,

zBaseEventLoop.subprocess_execcCs|jS)N)rt)rXrrr�get_exception_handler�sz#BaseEventLoop.get_exception_handlercCs*|dk	r t|�r tdj|���||_dS)Nz/A callable object or None is expected, got {!r})r�r5r�rt)rXZhandlerrrr�set_exception_handler�sz#BaseEventLoop.set_exception_handlerc	Cs|jd�}|sd}|jd�}|dk	r6t|�||jf}nd}d|kr`|jdk	r`|jjr`|jj|d<|g}x�t|�D]�}|d
kr~qp||}|dkr�djtj|��}d}||j	�7}n2|dkr�djtj|��}d	}||j	�7}nt
|�}|jd
j||��qpWt
jdj|�|d�dS)Nr�z!Unhandled exception in event loopr�FZsource_tracebackZhandle_tracebackr0z+Object created at (most recent call last):
z+Handle created at (most recent call last):
z{}: {}�
)r>r�r�)r{r>�
__traceback__r}r��sortedr��	traceback�format_list�rstriprr9r�r	r)	rX�contextr�r�rZ	log_linesr�value�tbrrr�default_exception_handler�s6


z'BaseEventLoop.default_exception_handlercCs�|jdkr>y|j|�Wq�tk
r:tjddd�Yq�Xnny|j||�Wn\tk
r�}z@y|jd||d��Wn"tk
r�tjddd�YnXWYdd}~XnXdS)Nz&Exception in default exception handlerT)rz$Unhandled error in exception handler)r�r�r.zeException in default exception handler while handling an unexpected error in custom exception handler)rtr1rOr	r)rXr.rRrrrr�s"
z$BaseEventLoop.call_exception_handlercCs|jr
dS|jj|�dS)N)�
_cancelledrnr9)rXrrrr�
_add_callback9szBaseEventLoop._add_callbackcCs|j|�|j�dS)N)r3r�)rXrrrr�_add_callback_signalsafeAs
z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)Nr)rori)rXrrrr�_timer_handle_cancelledFsz%BaseEventLoop._timer_handle_cancelledcCs�t|j�}|tkrd|j|tkrdg}x&|jD]}|jr>d|_q,|j|�q,Wtj|�||_d|_n8x6|jr�|jdjr�|jd8_tj	|j�}d|_qfWd}|j
s�|jr�d}n*|jr�|jdj}t
td||j��t�}|jo�|dk�r�|j�}|jj|�}|j�|}|dk�rtj}	ntj}	t|�}
|dk�rLtj|	d|d|
�nD|
�rntj|	d|d|d|
�n"|dk�r�tj|	d|d|d�n|jj|�}|j|�|j�|j}xD|j�r�|jd}|j|k�r�Ptj	|j�}d|_|j
j|��q�Wt|j
�}x�t|�D]|}
|j
j�}|j�r*�q|j�r�zD||_|j�}|j�|j�|}||jk�rttj d	t!|�|�Wdd|_Xn|j��qWd}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)"r�ro�_MIN_SCHEDULED_TIMER_HANDLESri�%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr2r9r��heapify�heappoprnrkZ_when�min�maxrr�MAXIMUM_SELECT_TIMEOUTr�Z	_selectorZselect�logging�INFO�DEBUGr	�logr�rs�range�popleftr}Z_runr|rr)rXZsched_countZ
new_scheduledrZtimeoutr�r�r�r��levelZneventZend_timeZntodo�irrrr�Ks�











zBaseEventLoop._run_oncecCs�ytj}tj}Wntk
r$dSXt|�}|j|kr<dStj}|�}|rz|d|fkrjtj	d|t
�q�||�d|_n,|d|fkr�tj	d|t
�n|d�d|_dS)Nz[loop.set_debug(True): cannot set debug coroutine wrapper; another wrapper is already set %rTzWloop.set_debug(False): cannot unset debug coroutine wrapper; another wrapper was set %rF)rv�set_coroutine_wrapper�get_coroutine_wrapper�AttributeErrorrxrrZ
debug_wrapperr�r��RuntimeWarning)rX�enabledZset_wrapperZget_wrapper�wrapperZcurrent_wrapperrrrr��s.

z$BaseEventLoop._set_coroutine_wrappercCs|jS)N)r�)rXrrrr��szBaseEventLoop.get_debugcCs||_|j�r|j|�dS)N)r�r�r�)rXrIrrrru�szBaseEventLoop.set_debug)N)N)NNN)NN)NN)N)r)NN)F)NN)NN)Gr[rerfrYr\rDr�r�r�r�r�r�r�r�rr�r�r�r�r�r�r�r�r�rQr`r�rZPY34r�r�rrr�r�r�r�r�r�r�r�r�r�rFr�r�r�rrr r6Z
AI_PASSIVErrrrrrrr#r%r&r'r1r�r3r4r5r�r�r�rurrrrr
�s�!


		%	

u	`
12c!i�Q)1rlZconcurrent.futuresr�r��inspectrr=ryr rr�rrr+rvr�r�r0rrrrrrr@r	�__all__r6r7�BrokenPipeError�ConnectionResetError�ConnectionAbortedErrorZ_FATAL_ERROR_IGNORErr8r<rrr&r+r-rAr)rKrMrSZAbstractServerrTZAbstractEventLoopr
rrrr�<module>sT
		;


/PK[�f��I�I&__pycache__/tasks.cpython-36.opt-1.pycnu�[���3


 \�a�
@s�dZddddddddd	d
ddd
g
ZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZddlmZddlm
Z
ddlmZGdd�de
j�ZeZyddlZWnek
r�YnXejZZej
jZej
jZej
jZedded�dd��Zdd�Zedd�dd��Zedd��Zddd �d!d�Zed/dd�d"d��Zdd�d#d$�Zee�d	<d	e_ [dd�d%d�Z!ed&d'��Z"Gd(d)�d)e
j�Z#dd*d+�d,d
�Z$dd�d-d�Z%d.d
�Z&dS)0z0Support for tasks, coroutines and the scheduler.�Task�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�wait�wait_for�as_completed�sleep�async�gather�shield�
ensure_future�run_coroutine_threadsafe�N�)�
base_tasks)�compat)�
coroutines)�events)�futures)�	coroutinecs�eZdZdZej�ZiZdZe	ddd��Z
e	ddd��Zdd��fd	d
�
Ze
jrXdd�Zd
d�Zdd�dd�Zddd�dd�Zdd�Zd�fdd�	Zdd�Z�ZS)rz A coroutine wrapped in a Future.TNcCs|dkrtj�}|jj|�S)z�Return the currently running task in an event loop or None.

        By default the current task for the current event loop is returned.

        None is returned when called not in the context of a Task.
        N)r�get_event_loop�_current_tasks�get)�cls�loop�r�%/usr/lib64/python3.6/asyncio/tasks.py�current_task.szTask.current_taskcs$�dkrtj���fdd�|jD�S)z|Return a set of all tasks for an event loop.

        By default all tasks for the current event loop are returned.
        Ncsh|]}|j�kr|�qSr)�_loop)�.0�t)rrr�	<setcomp>Bsz!Task.all_tasks.<locals>.<setcomp>)rr�
_all_tasks)rrr)rr�	all_tasks:szTask.all_tasks)rcsNt�j|d�|jr|jd=||_d|_d|_|jj|j�|j	j
j|�dS)N)rrF���)�super�__init__�_source_traceback�_coro�_fut_waiter�_must_cancelr�	call_soon�_step�	__class__r"�add)�self�coror)r-rrr&Dsz
Task.__init__cCsH|jtjkr8|jr8|dd�}|jr,|j|d<|jj|�tjj|�dS)Nz%Task was destroyed but it is pending!)�task�messageZsource_traceback)	Z_staterZ_PENDING�_log_destroy_pendingr'rZcall_exception_handler�Future�__del__)r/�contextrrrr5Ss
zTask.__del__cCs
tj|�S)N)rZ_task_repr_info)r/rrr�
_repr_info^szTask._repr_info)�limitcCstj||�S)a�Return the list of stack frames for this task's coroutine.

        If the coroutine is not done, this returns the stack where it is
        suspended.  If the coroutine has completed successfully or was
        cancelled, this returns an empty list.  If the coroutine was
        terminated by an exception, this returns the list of traceback
        frames.

        The frames are always ordered from oldest to newest.

        The optional limit gives the maximum number of frames to
        return; by default all available frames are returned.  Its
        meaning differs depending on whether a stack or a traceback is
        returned: the newest frames of a stack are returned, but the
        oldest frames of a traceback are returned.  (This matches the
        behavior of the traceback module.)

        For reasons beyond our control, only one stack frame is
        returned for a suspended coroutine.
        )rZ_task_get_stack)r/r8rrr�	get_stackaszTask.get_stack)r8�filecCstj|||�S)anPrint the stack or traceback for this task's coroutine.

        This produces output similar to that of the traceback module,
        for the frames retrieved by get_stack().  The limit argument
        is passed to get_stack().  The file argument is an I/O stream
        to which the output is written; by default output is written
        to sys.stderr.
        )rZ_task_print_stack)r/r8r:rrr�print_stackxs	zTask.print_stackcCs4d|_|j�rdS|jdk	r*|jj�r*dSd|_dS)a�Request that this task cancel itself.

        This arranges for a CancelledError to be thrown into the
        wrapped coroutine on the next cycle through the event loop.
        The coroutine then has a chance to clean up or even deny
        the request using try/except/finally.

        Unlike Future.cancel, this does not guarantee that the
        task will be cancelled: the exception might be caught and
        acted upon, delaying cancellation of the task or preventing
        cancellation completely.  The task may also return a value or
        raise a different exception.

        Immediately after this method is called, Task.cancelled() will
        not return True (unless the task was already cancelled).  A
        task will be marked as cancelled when the wrapped coroutine
        terminates with a CancelledError exception (even if cancel()
        was not called).
        FNT)Z_log_traceback�doner)�cancelr*)r/rrrr=�s

zTask.cancelcsf|jr t|tj�stj�}d|_|j}d|_||jj|j<�zy"|dkrT|j	d�}n
|j
|�}Wn�tk
r�}z.|jr�d|_|jtj��n|j
|j�WYdd}~X�n�tjk
r�t�j�Y�n|tk
r�}z|j|�WYdd}~X�nPtk
�r(}z|j|��WYdd}~X�n Xt|dd�}|dk	�r�|j|jk	�rl|jj|jtdj||���n||�r�||k�r�|jj|jtdj|���n2d|_|j|j�||_|j�r�|jj��r�d|_n|jj|jtdj||���n^|dk�r|jj|j�nDtj|��r.|jj|jtdj||���n|jj|jtdj|���Wd|jjj|j�d}XdS)NF�_asyncio_future_blockingz6Task {!r} got Future {!r} attached to a different loopz!Task cannot await on itself: {!r}z;yield was used instead of yield from in task {!r} with {!r}zIyield was used instead of yield from for generator in task {!r} with {!r}zTask got bad yield: {!r})r*�
isinstancer�CancelledErrorr(r)r-rr�send�throw�
StopIteration�
set_exception�
set_result�valuer%r=�	Exception�
BaseException�getattrr+r,�RuntimeError�formatr>�add_done_callback�_wakeup�inspectZisgenerator�pop)r/�excr0�resultZblocking)r-rrr,�s~



z
Task._stepcCsJy|j�Wn,tk
r8}z|j|�WYdd}~Xn
X|j�d}dS)N)rQrGr,)r/�futurerPrrrrM�szTask._wakeup)N)N)N)�__name__�
__module__�__qualname__�__doc__�weakref�WeakSetr"rr3�classmethodrr#r&rZPY34r5r7r9r;r=r,rM�
__classcell__rr)r-rrs"	!T)r�timeout�return_whenc#s�tj|�stj|�r&tdt|�j��|s2td��|tt	t
fkrNtdj|����dkr^tj
���fdd�t|�D�}t|||��EdHS)a�Wait for the Futures and coroutines given by fs to complete.

    The sequence futures must not be empty.

    Coroutines will be wrapped in Tasks.

    Returns two sets of Future: (done, pending).

    Usage:

        done, pending = yield from asyncio.wait(fs)

    Note: This does not raise TimeoutError! Futures that aren't done
    when the timeout occurs are returned in the second set.
    z expect a list of futures, not %sz#Set of coroutines/Futures is empty.zInvalid return_when value: {}Ncsh|]}t|�d��qS))r)r)r�f)rrrr!7szwait.<locals>.<setcomp>)r�isfuturer�iscoroutine�	TypeError�typerS�
ValueErrorrrrrKrr�set�_wait)�fsrr[r\r)rrrscGs|j�s|jd�dS)N)r<rE)�waiter�argsrrr�_release_waiter<srh)rccs�|dkrtj�}|dkr"|EdHS|j�}|j|t|�}tjt|�}t||d�}|j|�zhy|EdHWn*t	j
k
r�|j|�|j��YnX|j
�r�|j�S|j|�|j�t	j��Wd|j�XdS)a�Wait for the single Future or coroutine to complete, with timeout.

    Coroutine will be wrapped in Task.

    Returns result of the Future or coroutine.  When a timeout occurs,
    it cancels the task and raises TimeoutError.  To avoid the task
    cancellation, wrap it in shield().

    If the wait is cancelled, the task is also cancelled.

    This function is a coroutine.
    N)r)rr�
create_future�
call_laterrh�	functools�partialrrLrr@�remove_done_callbackr=r<rQ�TimeoutError)�futr[rrf�timeout_handle�cbrrrrAs,



c#s�|j��d�|dk	r"|j|t���t|������fdd�}x|D]}|j|�qBWz�EdHWd�dk	rt�j�Xt�t�}}x4|D],}|j|�|j�r�|j	|�q�|j	|�q�W||fS)zeInternal helper for wait() and wait_for().

    The fs argument must be a collection of Futures.
    Ncs\�d8��dks6�tks6�tkrX|j�rX|j�dk	rX�dk	rF�j��j�sX�jd�dS)Nrr)rr�	cancelled�	exceptionr=r<rE)r])�counterr\rprfrr�_on_completion|sz_wait.<locals>._on_completion)
rirjrh�lenrLr=rcrmr<r.)rer[r\rrur]r<�pendingr)rtr\rprfrrdos&



rd)rr[c#s�tj|�stj|�r&tdt|�j���dk	r2�ntj���fdd�t	|�D��ddl
m}|�d��d����fdd	�}���fd
d��t�fdd
��}x�D]}|j
��q�W�r�|dk	rʈj||��xtt���D]}|�Vq�WdS)amReturn an iterator whose values are coroutines.

    When waiting for the yielded coroutines you'll get the results (or
    exceptions!) of the original Futures (or coroutines), in the order
    in which and as soon as they complete.

    This differs from PEP 3148; the proper way to use this is:

        for f in as_completed(fs):
            result = yield from f  # The 'yield from' may raise.
            # Use result.

    If a timeout is specified, the 'yield from' will raise
    TimeoutError when the timeout occurs before all Futures are done.

    Note: The futures 'f' are not necessarily members of fs.
    z expect a list of futures, not %sNcsh|]}t|�d��qS))r)r)rr])rrrr!�szas_completed.<locals>.<setcomp>r)�Queue)rcs.x �D]}|j���jd�qW�j�dS)N)rm�
put_nowait�clear)r])rur<�todorr�_on_timeout�s

z!as_completed.<locals>._on_timeoutcs6�sdS�j|��j|��r2�dk	r2�j�dS)N)�removeryr=)r])r<rpr{rrru�s

z$as_completed.<locals>._on_completionc3s$�j�EdH}|dkrtj�|j�S)N)rrrnrQ)r])r<rr�
_wait_for_one�sz#as_completed.<locals>._wait_for_one)rr^rr_r`rarSrrrcZqueuesrxrrLrj�rangerv)rerr[rxr|r~r]�_r)rur<rrpr{rr�s 

c
csX|dkrdV|S|dkr"tj�}|j�}|jj|tj||�}z
|EdHS|j�XdS)z9Coroutine that completes after a given time (in seconds).rN)rrrirrjrZ_set_result_unless_cancelledr=)ZdelayrQrrR�hrrrr�s
cCstjdtdd�t||d�S)z�Wrap a coroutine in a future.

    If the argument is a Future, it is returned directly.

    This function is deprecated in 3.5. Use asyncio.ensure_future() instead.
    z;asyncio.async() function is deprecated, use ensure_future()�)�
stacklevel)r)�warnings�warn�DeprecationWarningr)�coro_or_futurerrrr�async_�sr�cCs�tj|�r(|dk	r$||jk	r$td��|Stj|�r^|dkrBtj�}|j|�}|j	rZ|j	d=|St
jr~tj
|�r~tt|�|d�Std��dS)zmWrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    Nz$loop argument must agree with Futurer)rz:An asyncio.Future, a coroutine or an awaitable is requiredr$)rr^rrbrr_rrZcreate_taskr'rZPY35rNZisawaitabler�_wrap_awaitabler`)r�rr1rrrr�s


ccs|j�EdHS)z�Helper for asyncio.ensure_future().

    Wraps awaitable (an object with __await__) into a coroutine
    that will later be wrapped in a Task by ensure_future().
    N)�	__await__)Z	awaitablerrrr�sr�cs.eZdZdZdd��fdd�
Zdd�Z�ZS)�_GatheringFuturez�Helper for gather().

    This overrides cancel() to cancel all the children and act more
    like Task.cancel(), which doesn't immediately mark itself as
    cancelled.
    N)rcst�j|d�||_d|_dS)N)rF)r%r&�	_children�_cancel_requested)r/�childrenr)r-rrr&$sz_GatheringFuture.__init__cCs:|j�rdSd}x|jD]}|j�rd}qW|r6d|_|S)NFT)r<r�r=r�)r/ZretZchildrrrr=)sz_GatheringFuture.cancel)rSrTrUrVr&r=rZrr)r-rr�sr�F)r�return_exceptionscs|s*|dkrtj�}|j���jg��Si�xjt|�D]^}tj|�sht||d�}|dkr`|j}d|_	n&|}|dkr||j}n|j|k	r�t
d��|�|<q8W�fdd�|D�}t|��t||d��d�dg�������fdd	�}x&t
|�D]\}}|jtj||��q�W�S)
a7Return a future aggregating results from the given coroutines
    or futures.

    Coroutines will be wrapped in a future and scheduled in the event
    loop. They will not necessarily be scheduled in the same order as
    passed in.

    All futures must share the same event loop.  If all the tasks are
    done successfully, the returned future's result is the list of
    results (in the order of the original sequence, not necessarily
    the order of results arrival).  If *return_exceptions* is True,
    exceptions in the tasks are treated the same as successful
    results, and gathered in the result list; otherwise, the first
    raised exception will be immediately propagated to the returned
    future.

    Cancellation: if the outer Future is cancelled, all children (that
    have not completed yet) are also cancelled.  If any child is
    cancelled, this is treated as if it raised CancelledError --
    the outer Future is *not* cancelled in this case.  (This is to
    prevent the cancellation of one child to cause other children to
    be cancelled.)
    N)rFz)futures are tied to different event loopscsg|]}�|�qSrr)r�arg)�
arg_to_futrr�
<listcomp>hszgather.<locals>.<listcomp>rcs��j�r|j�s|j�dS|j�r@tj�}�sl�j|�dSn,|jdk	rf|j�}�sl�j|�dSn|j}|�|<�d7���kr��jr��jtj��n
�j	��dS)Nr)
r<rrrsrr@rDZ
_exceptionZ_resultr�rE)�iro�res)�	nchildren�	nfinished�outer�resultsr�rr�_done_callbackns*


zgather.<locals>._done_callback)rrrirErcrr^rrr3rbrvr��	enumeraterLrkrl)rr�Zcoros_or_futuresr�ror�r�r�r)r�r�r�r�r�r�rr
8s8



cs@t||d�}|j�r|S|j}|j���fdd�}|j|��S)a=Wait for a future, shielding it from cancellation.

    The statement

        res = yield from shield(something())

    is exactly equivalent to the statement

        res = yield from something()

    *except* that if the coroutine containing it is cancelled, the
    task running in something() is not cancelled.  From the POV of
    something(), the cancellation did not happen.  But its caller is
    still cancelled, so the yield-from expression still raises
    CancelledError.  Note: If something() is cancelled by other means
    this will still cancel shield().

    If you want to completely ignore cancellation (not recommended)
    you can combine shield() with a try/except clause, as follows:

        try:
            res = yield from shield(something())
        except CancelledError:
            res = None
    )rcs\�j�r|j�s|j�dS|j�r.�j�n*|j�}|dk	rJ�j|�n�j|j��dS)N)rrrsr=rDrErQ)�innerrP)r�rrr��s
zshield.<locals>._done_callback)rr<rrirL)r�rr�r�r)r�rr�s
cs:tj��std��tjj�����fdd�}�j|��S)zsSubmit a coroutine object to a given event loop.

    Return a concurrent.futures.Future to access the result.
    zA coroutine object is requiredcsTytjt��d���Wn6tk
rN}z�j�r<�j|��WYdd}~XnXdS)N)r)rZ
_chain_futurerrGZset_running_or_notify_cancelrD)rP)r0rRrrr�callback�s
z*run_coroutine_threadsafe.<locals>.callback)rr_r`�
concurrentrr4Zcall_soon_threadsafe)r0rr�r)r0rRrrr
�s


)N)'rV�__all__Zconcurrent.futuresr�rkrNr�rW�rrrrrrr4rZ_PyTaskZ_asyncio�ImportErrorZ_CTaskrrrrrhrrdrrr��globalsrSrr�r�r
rr
rrrr�<module>sZ
s
--8

W5PK[�X��"�"&__pycache__/locks.cpython-36.opt-2.pycnu�[���3


 \�<�@s�dddddgZddlZddlmZdd	lmZdd
lmZddlmZGdd
�d
�ZGdd�d�Z	Gdd�de	�Z
Gdd�d�ZGdd�de	�ZGdd�de	�Z
Gdd�de
�ZdS)�Lock�Event�	Condition�	Semaphore�BoundedSemaphore�N�)�compat)�events)�futures)�	coroutinec@s$eZdZdd�Zdd�Zdd�ZdS)�_ContextManagercCs
||_dS)N)�_lock)�self�lock�r�%/usr/lib64/python3.6/asyncio/locks.py�__init__sz_ContextManager.__init__cCsdS)Nr)rrrr�	__enter__sz_ContextManager.__enter__cGsz|jj�Wdd|_XdS)N)r
�release)r�argsrrr�__exit__$sz_ContextManager.__exit__N)�__name__�
__module__�__qualname__rrrrrrrr
src@sNeZdZdd�Zdd�Zedd��ZejrJdd�Z	ed	d
��Z
edd��Zd
S)�_ContextManagerMixincCstd��dS)Nz9"yield from" should be used as context manager expression)�RuntimeError)rrrrr,sz_ContextManagerMixin.__enter__cGsdS)Nr)rrrrrr0sz_ContextManagerMixin.__exit__ccs|j�EdHt|�S)N)�acquirer)rrrr�__iter__5sz_ContextManagerMixin.__iter__ccs|j�EdHt|�S)N)rr)rrrr�	__await__Hsz_ContextManagerMixin.__await__ccs|j�EdHdS)N)r)rrrr�
__aenter__Msz_ContextManagerMixin.__aenter__cCs|j�dS)N)r)r�exc_type�exc�tbrrr�	__aexit__Tsz_ContextManagerMixin.__aexit__N)rrrrrrrrZPY35rrr#rrrrr+srcsNeZdZdd�dd�Z�fdd�Zdd�Zed	d
��Zdd�Zd
d�Z	�Z
S)rN)�loopcCs.tj�|_d|_|dk	r ||_n
tj�|_dS)NF)�collections�deque�_waiters�_locked�_loopr	�get_event_loop)rr$rrrr�s

z
Lock.__init__csDt�j�}|jrdnd}|jr0dj|t|j��}dj|dd�|�S)N�locked�unlockedz
{},waiters:{}z	<{} [{}]>r���)�super�__repr__r(r'�format�len)r�res�extra)�	__class__rrr/�s

z
Lock.__repr__cCs|jS)N)r()rrrrr+�szLock.lockedccs�|jr&tdd�|jD��r&d|_dS|jj�}|jj|�y"z|EdHWd|jj|�XWn&tjk
r�|js~|j	��YnXd|_dS)Ncss|]}|j�VqdS)N)�	cancelled)�.0�wrrr�	<genexpr>�szLock.acquire.<locals>.<genexpr>T)
r(�allr'r)�
create_future�append�remover
�CancelledError�_wake_up_first)r�futrrrr�s
zLock.acquirecCs"|jrd|_|j�ntd��dS)NFzLock is not acquired.)r(r>r)rrrrr�s
zLock.releasecCs>ytt|j��}Wntk
r&dSX|j�s:|jd�dS)NT)�next�iterr'�
StopIteration�done�
set_result)rr?rrrr>�szLock._wake_up_first)rrrrr/r+rrrr>�
__classcell__rr)r4rrYs6csNeZdZdd�dd�Z�fdd�Zdd�Zd	d
�Zdd�Zed
d��Z	�Z
S)rN)r$cCs.tj�|_d|_|dk	r ||_n
tj�|_dS)NF)r%r&r'�_valuer)r	r*)rr$rrrr�s

zEvent.__init__csDt�j�}|jrdnd}|jr0dj|t|j��}dj|dd�|�S)N�setZunsetz
{},waiters:{}z	<{} [{}]>rr-)r.r/rFr'r0r1)rr2r3)r4rrr/�s

zEvent.__repr__cCs|jS)N)rF)rrrr�is_set�szEvent.is_setcCs2|js.d|_x |jD]}|j�s|jd�qWdS)NT)rFr'rCrD)rr?rrrrG�s
z	Event.setcCs
d|_dS)NF)rF)rrrr�clearszEvent.clearccsB|jr
dS|jj�}|jj|�z|EdHdS|jj|�XdS)NT)rFr)r:r'r;r<)rr?rrr�wait
s

z
Event.wait)rrrrr/rHrGrIrrJrErr)r4rr�s	csVeZdZddd�dd�Z�fdd�Zedd��Zed	d
��Zddd
�Zdd�Z	�Z
S)rN)r$cCsp|dk	r||_n
tj�|_|dkr0t|jd�}n|j|jk	rDtd��||_|j|_|j|_|j|_t	j
�|_dS)N)r$z"loop argument must agree with lock)r)r	r*r�
ValueErrorr
r+rrr%r&r')rrr$rrrr+s
zCondition.__init__csFt�j�}|j�rdnd}|jr2dj|t|j��}dj|dd�|�S)Nr+r,z
{},waiters:{}z	<{} [{}]>rr-)r.r/r+r'r0r1)rr2r3)r4rrr/>s

zCondition.__repr__ccs�|j�std��|j�z8|jj�}|jj|�z|EdHdS|jj|�XWdd}x4y|j�EdHPWqXt	j
k
r�d}YqXXqXW|r�t	j
�XdS)Nzcannot wait on un-acquired lockTF)r+rrr)r:r'r;r<rr
r=)rr?r5rrrrJEs&

zCondition.waitccs(|�}x|s"|j�EdH|�}qW|S)N)rJ)rZ	predicate�resultrrr�wait_forks

zCondition.wait_forrcCsL|j�std��d}x2|jD](}||kr*P|j�s|d7}|jd�qWdS)Nz!cannot notify on un-acquired lockrrF)r+rr'rCrD)r�n�idxr?rrr�notifyyszCondition.notifycCs|jt|j��dS)N)rPr1r')rrrr�
notify_all�szCondition.notify_all)N)r)rrrrr/rrJrMrPrQrErr)r4rr!s
&
csPeZdZddd�dd�Z�fdd�Zdd	�Zd
d�Zedd
��Zdd�Z	�Z
S)rrN)r$cCs>|dkrtd��||_tj�|_|dk	r0||_n
tj�|_dS)Nrz$Semaphore initial value must be >= 0)rKrFr%r&r'r)r	r*)r�valuer$rrrr�s
zSemaphore.__init__csNt�j�}|j�rdn
dj|j�}|jr:dj|t|j��}dj|dd�|�S)Nr+zunlocked,value:{}z
{},waiters:{}z	<{} [{}]>rr-)r.r/r+r0rFr'r1)rr2r3)r4rrr/�s
zSemaphore.__repr__cCs0x*|jr*|jj�}|j�s|jd�dSqWdS)N)r'�popleftrCrD)rZwaiterrrr�
_wake_up_next�s


zSemaphore._wake_up_nextcCs
|jdkS)Nr)rF)rrrrr+�szSemaphore.lockedc	cszxf|jdkrf|jj�}|jj|�y|EdHWq|j�|jdkr\|j�r\|j��YqXqW|jd8_dS)NrrT)rFr)r:r'r;Zcancelr5rT)rr?rrrr�s

zSemaphore.acquirecCs|jd7_|j�dS)Nr)rFrT)rrrrr�szSemaphore.release)r)rrrrr/rTr+rrrrErr)r4rr�s
cs0eZdZddd��fdd�Z�fdd�Z�ZS)	rrN)r$cs||_t�j||d�dS)N)r$)�_bound_valuer.r)rrRr$)r4rrr�szBoundedSemaphore.__init__cs"|j|jkrtd��t�j�dS)Nz(BoundedSemaphore released too many times)rFrUrKr.r)r)r4rrr�szBoundedSemaphore.release)r)rrrrrrErr)r4rr�s)�__all__r%�rr	r
Z
coroutinesrrrrrrrrrrrr�<module>s.ByMPK[��o�5�5"__pycache__/futures.cpython-36.pycnu�[���3


 \>�@s
dZddddddgZddlZddlZddlZddlZd	d
lmZd	dlm	Z	d	dlm
Z
ejZejZej
Z
ejZejZejZejZejd	ZGd
d�d�ZGdd�d�ZeZdd�Zdd�Zdd�Zdd�Zdd�dd�ZyddlZWnek
r�YnXejZZdS)z.A Future class similar to the one in PEP 3148.�CancelledError�TimeoutError�InvalidStateError�Future�wrap_future�isfuture�N�)�base_futures)�compat)�eventsc@s4eZdZdZdZdd�Zdd	�Zd
d�Zdd
�ZdS)�_TracebackLoggera
Helper to log a traceback upon destruction if not cleared.

    This solves a nasty problem with Futures and Tasks that have an
    exception set: if nobody asks for the exception, the exception is
    never logged.  This violates the Zen of Python: 'Errors should
    never pass silently.  Unless explicitly silenced.'

    However, we don't want to log the exception as soon as
    set_exception() is called: if the calling code is written
    properly, it will get the exception and handle it properly.  But
    we *do* want to log it if result() or exception() was never called
    -- otherwise developers waste a lot of time wondering why their
    buggy code fails silently.

    An earlier attempt added a __del__() method to the Future class
    itself, but this backfired because the presence of __del__()
    prevents garbage collection from breaking cycles.  A way out of
    this catch-22 is to avoid having a __del__() method on the Future
    class itself, but instead to have a reference to a helper object
    with a __del__() method that logs the traceback, where we ensure
    that the helper object doesn't participate in cycles, and only the
    Future has a reference to it.

    The helper object is added when set_exception() is called.  When
    the Future is collected, and the helper is present, the helper
    object is also collected, and its __del__() method will log the
    traceback.  When the Future's result() or exception() method is
    called (and a helper object is present), it removes the helper
    object, after calling its clear() method to prevent it from
    logging.

    One downside is that we do a fair amount of work to extract the
    traceback from the exception, even when it is never logged.  It
    would seem cheaper to just store the exception object, but that
    references the traceback, which references stack frames, which may
    reference the Future, which references the _TracebackLogger, and
    then the _TracebackLogger would be included in a cycle, which is
    what we're trying to avoid!  As an optimization, we don't
    immediately format the exception; we only do the work when
    activate() is called, which call is delayed until after all the
    Future's callbacks have run.  Since usually a Future has at least
    one callback (typically set by 'yield from') and usually that
    callback extracts the callback, thereby removing the need to
    format the exception.

    PS. I don't claim credit for this solution.  I first heard of it
    in a discussion about closing files when they are collected.
    �loop�source_traceback�exc�tbcCs |j|_|j|_||_d|_dS)N)�_loopr
�_source_tracebackrrr)�self�futurer�r�'/usr/lib64/python3.6/asyncio/futures.py�__init__Rsz_TracebackLogger.__init__cCs,|j}|dk	r(d|_tj|j||j�|_dS)N)r�	traceback�format_exception�	__class__�
__traceback__r)rrrrr�activateXs

z_TracebackLogger.activatecCsd|_d|_dS)N)rr)rrrr�clear_sz_TracebackLogger.clearcCsb|jr^d}|jr:djtj|j��}|d7}|d|j�7}|dj|j�j�7}|jjd|i�dS)Nz*Future/Task exception was never retrieved
�z0Future/Task created at (most recent call last):
z%s
�message)rr�joinr�format_list�rstripr
�call_exception_handler)r�msg�srcrrr�__del__csz_TracebackLogger.__del__N)r
rrr)	�__name__�
__module__�__qualname__�__doc__�	__slots__rrrr&rrrrrs0rc@s�eZdZdZeZdZdZdZdZ	dZ
dZdd�dd�Ze
jZdd�ZejrRd	d
�Zdd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zejr�eZ dS)!ra,This class is *almost* compatible with concurrent.futures.Future.

    Differences:

    - This class is not thread-safe.

    - result() and exception() do not take a timeout argument and
      raise an exception when the future isn't done yet.

    - Callbacks registered with add_done_callback() are always called
      via the event loop's call_soon().

    - This class is not compatible with the wait() and as_completed()
      methods in the concurrent.futures package.

    (In Python 3.4 or later we may be able to unify the implementations.)
    NF)r
cCs@|dkrtj�|_n||_g|_|jj�r<tjtjd��|_dS)z�Initialize the future.

        The optional event_loop argument allows explicitly setting the event
        loop object used by the future. If it's not provided, the future uses
        the default event loop.
        Nr)	r�get_event_loopr�
_callbacksZ	get_debug�
extract_stack�sys�	_getframer)rr
rrrr�s
zFuture.__init__cCsd|jjdj|j��fS)Nz<%s %s>� )rr'r �
_repr_info)rrrr�__repr__�szFuture.__repr__cCsD|js
dS|j}d|jj||d�}|jr4|j|d<|jj|�dS)Nz %s exception was never retrieved)r�	exceptionrr)�_log_traceback�
_exceptionrr'rrr#)rr�contextrrrr&�s
zFuture.__del__cCs&d|_|jtkrdSt|_|j�dS)z�Cancel the future and schedule callbacks.

        If the future is already done or cancelled, return False.  Otherwise,
        change the future's state to cancelled, schedule the callbacks and
        return True.
        FT)r5�_state�_PENDING�
_CANCELLED�_schedule_callbacks)rrrr�cancel�s
z
Future.cancelcCsD|jdd�}|sdSg|jdd�<x|D]}|jj||�q*WdS)z�Internal: Ask the event loop to call all callbacks.

        The callbacks are scheduled to be called as soon as possible. Also
        clears the callback list.
        N)r-r�	call_soon)rZ	callbacks�callbackrrrr;�s
zFuture._schedule_callbackscCs
|jtkS)z(Return True if the future was cancelled.)r8r:)rrrr�	cancelled�szFuture.cancelledcCs
|jtkS)z�Return True if the future is done.

        Done means either that a result / exception are available, or that the
        future was cancelled.
        )r8r9)rrrr�done�szFuture.donecCs<|jtkrt�|jtkr td��d|_|jdk	r6|j�|jS)aReturn the result this future represents.

        If the future has been cancelled, raises CancelledError.  If the
        future's result isn't yet available, raises InvalidStateError.  If
        the future is done and has an exception set, this exception is raised.
        zResult is not ready.FN)r8r:r�	_FINISHEDrr5r6�_result)rrrr�result�s


z
Future.resultcCs,|jtkrt�|jtkr td��d|_|jS)a&Return the exception that was set on this future.

        The exception (or None if no exception was set) is returned only if
        the future is done.  If the future has been cancelled, raises
        CancelledError.  If the future isn't done yet, raises
        InvalidStateError.
        zException is not set.F)r8r:rrArr5r6)rrrrr4�s

zFuture.exceptioncCs*|jtkr|jj||�n|jj|�dS)z�Add a callback to be run when the future becomes done.

        The callback is called with a single argument - the future object. If
        the future is already done when this is called, the callback is
        scheduled with call_soon.
        N)r8r9rr=r-�append)r�fnrrr�add_done_callbacks
zFuture.add_done_callbackcs<�fdd�|jD�}t|j�t|�}|r8||jdd�<|S)z}Remove all instances of a callback from the "call when done" list.

        Returns the number of callbacks removed.
        csg|]}|�kr|�qSrr)�.0�f)rErr�
<listcomp>sz/Future.remove_done_callback.<locals>.<listcomp>N)r-�len)rrEZfiltered_callbacksZ
removed_countr)rEr�remove_done_callbacks
zFuture.remove_done_callbackcCs4|jtkrtdj|j|���||_t|_|j�dS)z�Mark the future done and set its result.

        If the future is already done when this method is called, raises
        InvalidStateError.
        z{}: {!r}N)r8r9r�formatrBrAr;)rrCrrr�
set_result s

zFuture.set_resultcCs�|jtkrtdj|j|���t|t�r,|�}t|�tkr@td��||_t	|_|j
�tjrbd|_
nt||�|_|jj|jj�dS)z�Mark the future done and set an exception.

        If the future is already done when this method is called, raises
        InvalidStateError.
        z{}: {!r}zPStopIteration interacts badly with generators and cannot be raised into a FutureTN)r8r9rrL�
isinstance�type�
StopIteration�	TypeErrorr6rAr;r
�PY34r5rZ
_tb_loggerrr=r)rr4rrr�
set_exception,s

zFuture.set_exceptionccs,|j�sd|_|V|j�s$td��|j�S)NTz"yield from wasn't used with future)r@�_asyncio_future_blocking�AssertionErrorrC)rrrr�__iter__Ds
zFuture.__iter__)!r'r(r)r*r9r8rBr6rrrTr5rr	Z_future_repr_infor2r3r
rRr&r<r;r?r@rCr4rFrKrMrSrVZPY35�	__await__rrrrrns4

cCs|j�rdS|j|�dS)z?Helper setting the result only if the future was not cancelled.N)r?rM)ZfutrCrrr�_set_result_unless_cancelledSsrXcCsZ|j�st�|j�r|j�|j�s(dS|j�}|dk	rD|j|�n|j�}|j|�dS)z8Copy state from a future to a concurrent.futures.Future.N)	r@rUr?r<Zset_running_or_notify_cancelr4rSrCrM)�
concurrent�sourcer4rCrrr�_set_concurrent_future_stateZsr[cCsj|j�st�|j�rdS|j�s&t�|j�r8|j�n.|j�}|dk	rT|j|�n|j�}|j|�dS)zqInternal helper to copy state from another Future.

    The other Future may be a concurrent.futures.Future.
    N)r@rUr?r<r4rSrCrM)rZ�destr4rCrrr�_copy_future_stateis
r]cs�t��r"t�tjj�r"td��t��rDt�tjj�rDtd��t��rR�jnd�t��rd�jnd�dd�����fdd�}����fdd	�}�j|��j|�dS)
aChain two futures so that when one completes, so does the other.

    The result (or exception) of source will be copied to destination.
    If destination is cancelled, source gets cancelled too.
    Compatible with both asyncio.Future and concurrent.futures.Future.
    z(A future is required for source argumentz-A future is required for destination argumentNcSs"t|�rt||�n
t||�dS)N)rr]r[)r�otherrrr�
_set_state�sz!_chain_future.<locals>._set_statecs2|j�r.�dks��kr"�j�n�j�j�dS)N)r?r<�call_soon_threadsafe)�destination)�	dest_looprZ�source_looprr�_call_check_cancel�s
z)_chain_future.<locals>._call_check_cancelcsJ�j�r�dk	r�j�rdS�dks,��kr8��|�n�j��|�dS)N)r?Z	is_closedr`)rZ)r_rbrarcrr�_call_set_state�sz&_chain_future.<locals>._call_set_state)rrNrY�futuresrrQrrF)rZrardrer)r_rbrarZrcr�
_chain_future}s	
rg)r
cCsNt|�r|St|tjj�s(tdj|���|dkr8tj�}|j	�}t
||�|S)z&Wrap concurrent.futures.Future object.z/concurrent.futures.Future is expected, got {!r}N)rrNrYrfrrUrLrr,Z
create_futurerg)rr
Z
new_futurerrrr�s
)r*�__all__Zconcurrent.futuresrYZloggingr/rrr	r
rrrrrr9r:rA�DEBUGZSTACK_DEBUGrrZ	_PyFuturerXr[r]rgrZ_asyncio�ImportErrorZ_CFuturerrrr�<module>s>

Pc*
PK[�%�O�S�S)__pycache__/windows_events.cpython-36.pycnu�[���3


 \�l�@s�dZddlZddlZddlZddlZddlZddlZddlmZddlm	Z	ddlm
Z
ddlmZddlmZdd	lm
Z
dd
lmZddlmZddlmZdd
lmZddddgZdZdZdZdZdZdZGdd�de
j�ZGdd�de
j�ZGdd�de�ZGdd�de�ZGdd �d e �Z!Gd!d"�d"ej"�Z#Gd#d�dej$�Z%Gd$d�d�Z&Gd%d&�d&e	j'�Z(e#Z)Gd'd(�d(ej*�Z+e+Z,dS))z.Selector and proactor event loops for Windows.�N�)�events)�base_subprocess)�futures)�proactor_events)�selector_events)�tasks)�
windows_utils)�_overlapped)�	coroutine)�logger�SelectorEventLoop�ProactorEventLoop�IocpProactor�DefaultEventLoopPolicyl��i�i�g����MbP?g�������?cs^eZdZdZdd��fdd�
Z�fdd�Zdd	�Z�fd
d�Z�fdd
�Z�fdd�Z	�Z
S)�_OverlappedFuturez�Subclass of Future which represents an overlapped operation.

    Cancelling it will immediately cancel the overlapped operation.
    N)�loopcs&t�j|d�|jr|jd=||_dS)N)rr���)�super�__init__�_source_traceback�_ov)�self�ovr)�	__class__��./usr/lib64/python3.6/asyncio/windows_events.pyr-sz_OverlappedFuture.__init__cs@t�j�}|jdk	r<|jjr dnd}|jdd||jjf�|S)N�pendingZ	completedrzoverlapped=<%s, %#x>)r�
_repr_inforr�insert�address)r�info�state)rrrr3s


z_OverlappedFuture._repr_infocCsr|jdkrdSy|jj�WnJtk
rf}z.d||d�}|jrJ|j|d<|jj|�WYdd}~XnXd|_dS)Nz&Cancelling an overlapped future failed)�message�	exception�future�source_traceback)r�cancel�OSErrorr�_loop�call_exception_handler)r�exc�contextrrr�_cancel_overlapped:s

z$_OverlappedFuture._cancel_overlappedcs|j�t�j�S)N)r-rr')r)rrrr'Jsz_OverlappedFuture.cancelcst�j|�|j�dS)N)r�
set_exceptionr-)rr$)rrrr.Nsz_OverlappedFuture.set_exceptioncst�j|�d|_dS)N)r�
set_resultr)r�result)rrrr/Rsz_OverlappedFuture.set_result)�__name__�
__module__�__qualname__�__doc__rrr-r'r.r/�
__classcell__rr)rrr'srcsneZdZdZdd��fdd�
Zdd�Z�fdd	�Zd
d�Zdd
�Z�fdd�Z	�fdd�Z
�fdd�Z�ZS)�_BaseWaitHandleFuturez2Subclass of Future which represents a wait handle.N)rcs8t�j|d�|jr|jd=||_||_||_d|_dS)N)rrTr)rrrr�_handle�_wait_handle�_registered)rr�handle�wait_handler)rrrrZsz_BaseWaitHandleFuture.__init__cCstj|jd�tjkS)Nr)�_winapiZWaitForSingleObjectr7Z
WAIT_OBJECT_0)rrrr�_pollhsz_BaseWaitHandleFuture._pollcs\t�j�}|jd|j�|jdk	r>|j�r0dnd}|j|�|jdk	rX|jd|j�|S)Nz
handle=%#xZsignaledZwaitingzwait_handle=%#x)rr�appendr7r=r8)rr!r")rrrrms



z _BaseWaitHandleFuture._repr_infocCs
d|_dS)N)r)r�futrrr�_unregister_wait_cbwsz)_BaseWaitHandleFuture._unregister_wait_cbcCs�|js
dSd|_|j}d|_ytj|�WnZtk
r�}z>|jtjkrtd||d�}|jrd|j|d<|jj	|�dSWYdd}~XnX|j
d�dS)NFz$Failed to unregister the wait handle)r#r$r%r&)r9r8r
ZUnregisterWaitr(�winerror�ERROR_IO_PENDINGrr)r*r@)rr;r+r,rrr�_unregister_wait|s"
z&_BaseWaitHandleFuture._unregister_waitcs|j�t�j�S)N)rCrr')r)rrrr'�sz_BaseWaitHandleFuture.cancelcs|j�t�j|�dS)N)rCrr.)rr$)rrrr.�sz#_BaseWaitHandleFuture.set_exceptioncs|j�t�j|�dS)N)rCrr/)rr0)rrrr/�sz _BaseWaitHandleFuture.set_result)
r1r2r3r4rr=rr@rCr'r.r/r5rr)rrr6Ws
r6csFeZdZdZdd��fdd�
Zdd�Z�fdd	�Z�fd
d�Z�ZS)�_WaitCancelFuturezoSubclass of Future which represents a wait for the cancellation of a
    _WaitHandleFuture using an event.
    N)rcst�j||||d�d|_dS)N)r)rr�_done_callback)rr�eventr;r)rrrr�sz_WaitCancelFuture.__init__cCstd��dS)Nz'_WaitCancelFuture must not be cancelled)�RuntimeError)rrrrr'�sz_WaitCancelFuture.cancelcs$t�j|�|jdk	r |j|�dS)N)rr/rE)rr0)rrrr/�s
z_WaitCancelFuture.set_resultcs$t�j|�|jdk	r |j|�dS)N)rr.rE)rr$)rrrr.�s
z_WaitCancelFuture.set_exception)	r1r2r3r4rr'r/r.r5rr)rrrD�s
rDcs6eZdZdd��fdd�
Z�fdd�Zdd�Z�ZS)	�_WaitHandleFutureN)rcs<t�j||||d�||_d|_tjdddd�|_d|_dS)N)rTF)rr�	_proactorZ_unregister_proactorr
ZCreateEvent�_event�
_event_fut)rrr:r;�proactorr)rrrr�s
z_WaitHandleFuture.__init__csF|jdk	r"tj|j�d|_d|_|jj|j�d|_t�j|�dS)N)	rJr<�CloseHandlerKrI�_unregisterrrr@)rr?)rrrr@�s
	z%_WaitHandleFuture._unregister_wait_cbcCs�|js
dSd|_|j}d|_ytj||j�WnZtk
r�}z>|jtjkrxd||d�}|jrh|j|d<|j	j
|�dSWYdd}~XnX|jj|j|j
�|_dS)NFz$Failed to unregister the wait handle)r#r$r%r&)r9r8r
ZUnregisterWaitExrJr(rArBrr)r*rI�_wait_cancelr@rK)rr;r+r,rrrrC�s$

z"_WaitHandleFuture._unregister_wait)r1r2r3rr@rCr5rr)rrrH�srHc@s<eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZeZ	dS)
�
PipeServerzXClass representing a pipe server.

    This is much like a bound, listening socket.
    cCs,||_tj�|_d|_d|_|jd�|_dS)NT)�_address�weakref�WeakSet�_free_instances�_pipe�_accept_pipe_future�_server_pipe_handle)rr rrrr�s

zPipeServer.__init__cCs|j|jd�}|_|S)NF)rUrW)r�tmprrr�_get_unconnected_pipe�sz PipeServer._get_unconnected_pipec	Csr|j�rdStjtjB}|r&|tjO}tj|j|tjtjBtj	Btj
tjtjtj
tj�}tj|�}|jj|�|S)N)�closedr<ZPIPE_ACCESS_DUPLEXZFILE_FLAG_OVERLAPPEDZFILE_FLAG_FIRST_PIPE_INSTANCEZCreateNamedPiperQZPIPE_TYPE_MESSAGEZPIPE_READMODE_MESSAGEZ	PIPE_WAITZPIPE_UNLIMITED_INSTANCESr	ZBUFSIZEZNMPWAIT_WAIT_FOREVER�NULL�
PipeHandlerT�add)r�first�flags�h�piperrrrWs


zPipeServer._server_pipe_handlecCs
|jdkS)N)rQ)rrrrrZszPipeServer.closedcCsV|jdk	r|jj�d|_|jdk	rRx|jD]}|j�q,Wd|_d|_|jj�dS)N)rVr'rQrT�closerU�clear)rrarrrrbs


zPipeServer.closeN)
r1r2r3r4rrYrWrZrb�__del__rrrrrP�s
rPc@seZdZdZdd�ZdS)�_WindowsSelectorEventLoopz'Windows version of selector event loop.cCstj�S)N)r	�
socketpair)rrrr�_socketpair+sz%_WindowsSelectorEventLoop._socketpairN)r1r2r3r4rgrrrrre(srecsPeZdZdZd
�fdd�	Zdd�Zedd��Zed	d
��Zeddd��Z	�Z
S)rz2Windows version of proactor event loop using IOCP.Ncs|dkrt�}t�j|�dS)N)rrr)rrL)rrrr2szProactorEventLoop.__init__cCstj�S)N)r	rf)rrrrrg7szProactorEventLoop._socketpairccs8|jj|�}|EdH}|�}|j||d|id�}||fS)N�addr)�extra)rI�connect_pipe�_make_duplex_pipe_transport)r�protocol_factoryr �fra�protocol�transrrr�create_pipe_connection:s
z(ProactorEventLoop.create_pipe_connectioncs.t���d�����fdd�	��j���gS)Ncsd}yj|rL|j�}�jj|��j�r2|j�dS��}�j||d�id��j�}|dkr`dS�jj|�}Wn�t	k
r�}zH|r�|j
�d	kr��jd||d��|j�n�jr�t
jd|dd�WYdd}~Xn2tjk
r�|r�|j�YnX|�_|j��dS)
Nrh)rirzPipe accept failed)r#r$razAccept pipe failed on pipe %rT)�exc_infor)r0rT�discardrZrbrkrYrI�accept_piper(�filenor*Z_debugrZwarningr�CancelledErrorrV�add_done_callback)rmrarnr+)r �loop_accept_piperlr�serverrrrwGs<

z>ProactorEventLoop.start_serving_pipe.<locals>.loop_accept_pipe)N)rPZ	call_soon)rrlr r)r rwrlrrxr�start_serving_pipeCs(
z$ProactorEventLoop.start_serving_pipec	ks�|j�}
t||||||||f|
|d�|	��}y|
EdHWn&tk
r`}z
|}
WYdd}~XnXd}
|
dk	r�|j�|j�EdH|
�|S)N)�waiterri)�
create_future�_WindowsSubprocessTransport�	ExceptionrbZ_wait)rrn�args�shell�stdin�stdout�stderr�bufsizeri�kwargsrzZtranspr+�errrrr�_make_subprocess_transportrs

z,ProactorEventLoop._make_subprocess_transport)N)N)r1r2r3r4rrgrrpryr�r5rr)rrr/s	/c@s�eZdZdZd1dd�Zdd�Zdd�Zd2d
d�Zdd
�Zd3dd�Z	d4dd�Z
dd�Zdd�Zdd�Z
edd��Zd5dd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd6d)d*�Zd+d,�Zd-d.�Zd/d0�Zd	S)7rz#Proactor implementation using IOCP.���cCsDd|_g|_tjtjtd|�|_i|_tj	�|_
g|_tj	�|_dS)Nr)
r)�_resultsr
�CreateIoCompletionPort�INVALID_HANDLE_VALUEr[�_iocp�_cacherRrSr9�
_unregistered�_stopped_serving)rZconcurrencyrrrr�s
zIocpProactor.__init__cCsd|jjt|j�t|j�fS)Nz<%s overlapped#=%s result#=%s>)rr1�lenr�r�)rrrr�__repr__�szIocpProactor.__repr__cCs
||_dS)N)r))rrrrr�set_loop�szIocpProactor.set_loopNcCs |js|j|�|j}g|_|S)N)r�r=)r�timeoutrXrrr�select�s

zIocpProactor.selectcCs|jj�}|j|�|S)N)r)r{r/)r�valuer?rrr�_result�s

zIocpProactor._resultrcCsz|j|�tjt�}y4t|tj�r6|j|j�||�n|j|j�|�Wnt	k
rb|j
d�SXdd�}|j|||�S)N�cSsJy|j�Stk
rD}z |jtjkr2t|j��n�WYdd}~XnXdS)N)�	getresultr(rAr
�ERROR_NETNAME_DELETED�ConnectionResetErrorr~)ro�keyrr+rrr�finish_recv�sz&IocpProactor.recv.<locals>.finish_recv)�_register_with_iocpr
�
Overlappedr[�
isinstance�socketZWSARecvrtZReadFile�BrokenPipeErrorr��	_register)r�conn�nbytesr_rr�rrr�recv�s

	zIocpProactor.recvcCsZ|j|�tjt�}t|tj�r4|j|j�||�n|j|j�|�dd�}|j	|||�S)NcSsJy|j�Stk
rD}z |jtjkr2t|j��n�WYdd}~XnXdS)N)r�r(rAr
r�r�r~)ror�rr+rrr�finish_send�sz&IocpProactor.send.<locals>.finish_send)
r�r
r�r[r�r�ZWSASendrtZ	WriteFiler�)rr��bufr_rr�rrr�send�s

	zIocpProactor.sendcsz|j��|j�j��tjt�}|j�j��j����fdd�}tdd��}|j	|�|�}||��}t
j||jd�|S)NcsD|j�tjd�j��}�jtjtj|��j	�j
����j�fS)Nz@P)r��structZpackrt�
setsockoptr��
SOL_SOCKETr
ZSO_UPDATE_ACCEPT_CONTEXT�
settimeoutZ
gettimeoutZgetpeername)ror�rr�)r��listenerrr�
finish_accept�s
z*IocpProactor.accept.<locals>.finish_acceptcss4y|EdHWn tjk
r.|j��YnXdS)N)rrurb)r%r�rrr�accept_coro�s
z(IocpProactor.accept.<locals>.accept_coro)r)
r��_get_accept_socket�familyr
r�r[ZAcceptExrtrr�rZ
ensure_futurer))rr�rr�r�r%�coror)r�r�r�accept�s

		
zIocpProactor.acceptcs�|j��ytj�j��j�WnBtk
rb}z&|jtjkr@��j	�ddkrR�WYdd}~XnXtj
t�}|j�j�|��fdd�}|j
|�|�S)Nrrcs|j��jtjtjd��S)Nr)r�r�r�r�r
ZSO_UPDATE_CONNECT_CONTEXT)ror�r)r�rr�finish_connects
z,IocpProactor.connect.<locals>.finish_connect)r�r
Z	BindLocalrtr�r(rA�errnoZ	WSAEINVALZgetsocknamer�r[Z	ConnectExr�)rr�r �err�r)r�r�connect�s

zIocpProactor.connectcsJ|j��tjt�}|j�j��}|r0|j��S�fdd�}|j|�|�S)Ncs|j��S)N)r�)ror�r)rarr�finish_accept_pipesz4IocpProactor.accept_pipe.<locals>.finish_accept_pipe)r�r
r�r[ZConnectNamedPipertr�r�)rrarZ	connectedr�r)rarrs
s


zIocpProactor.accept_pipeccszt}xjytj|�}PWn0tk
rF}z|jtjkr6�WYdd}~XnXt|dt�}tj	||j
d�EdHqWtj|�S)N�)r)
�CONNECT_PIPE_INIT_DELAYr
ZConnectPiper(rAZERROR_PIPE_BUSY�min�CONNECT_PIPE_MAX_DELAYrZsleepr)r	r\)rr Zdelayr:r+rrrrjs
zIocpProactor.connect_pipecCs|j||d�S)z�Wait for a handle.

        Return a Future object. The result of the future is True if the wait
        completed, or False if the wait did not complete (on timeout).
        F)�_wait_for_handle)rr:r�rrr�wait_for_handle/szIocpProactor.wait_for_handlecCs|j|dd�}||_|S)NT)r�rE)rrFZ
done_callbackr?rrrrO7szIocpProactor._wait_cancelcs�|dkrtj}ntj|d�}tjt�}tj||j|j	|�}|rTt
||||jd��nt|||||jd���j
rv�j
d=�fdd�}�|d|f|j|j	<�S)Ng@�@)rrcs�j�S)N)r=)ror�r)rmrr�finish_wait_for_handleRsz=IocpProactor._wait_for_handle.<locals>.finish_wait_for_handlerr)r<�INFINITE�math�ceilr
r�r[ZRegisterWaitWithQueuer�r rDr)rHrr�)rr:r�Z
_is_cancel�msrr;r�r)rmrr�>s


	zIocpProactor._wait_for_handlecCs0||jkr,|jj|�tj|j�|jdd�dS)Nr)r9r]r
r�rtr�)r�objrrrr�^s
z IocpProactor._register_with_iocpcCs�t||jd�}|jr|jd=|jsjy|dd|�}Wn,tk
r^}z|j|�WYdd}~XnX|j|�||||f|j|j<|S)N)rrr)	rr)rrr(r.r/r�r )rrr��callbackrmr�r�rrrr�hs

zIocpProactor._registercCs|jj|�dS)a
Unregister an overlapped object.

        Call this method when its future has been cancelled. The event can
        already be signalled (pending in the proactor event queue). It is also
        safe if the event is never signalled (because it was cancelled).
        N)r�r>)rrrrrrN�szIocpProactor._unregistercCstj|�}|jd�|S)Nr)r�r�)rr��srrrr��s

zIocpProactor._get_accept_socketcCs�|dkrt}n0|dkr td��ntj|d�}|tkr>td���xtj|j|�}|dkrZPd}|\}}}}y|jj|�\}}	}
}WnVt	k
r�|j
j�r�|j
jdd||||fd��|dtj
fkr�tj|�wBYnX|
|jkr�|j�qB|j�sBy||||	�}Wn:tk
�r@}
z|j|
�|jj|�WYdd}
~
XqBX|j|�|jj|�qBWx |jD]}	|jj|	jd��qdW|jj�dS)Nrznegative timeoutg@�@ztimeout too bigz8GetQueuedCompletionStatus() returned an unexpected eventz)err=%s transferred=%s key=%#x address=%#x)r#�status)r��
ValueErrorr�r�r
ZGetQueuedCompletionStatusr�r��pop�KeyErrorr)Z	get_debugr*r�r<rMr�r'�doner(r.r�r>r/r�r rc)rr�r�r�r�Ztransferredr�r rmrr�r�r�r�rrrr=�sJ






zIocpProactor._pollcCs|jj|�dS)N)r�r])rr�rrr�
_stop_serving�szIocpProactor._stop_servingcCs�x�t|jj��D]�\}\}}}}|j�r*qt|t�r6qy|j�Wqtk
r�}z8|jdk	r�d||d�}|j	rz|j	|d<|jj
|�WYdd}~XqXqWx|jr�|jd�s�tj
d�q�Wg|_|jdk	r�tj|j�d|_dS)NzCancelling a future failed)r#r$r%r&rz"taking long time to close proactor)�listr��itemsZ	cancelledr�rDr'r(r)rr*r=r�debugr�r�r<rM)rr r?rr�r�r+r,rrrrb�s, 


"

zIocpProactor.closecCs|j�dS)N)rb)rrrrrd�szIocpProactor.__del__)r�)N)r)r)N)N)r1r2r3r4rr�r�r�r�r�r�r�r�rsrrjr�rOr�r�r�rNr�r=r�rbrdrrrrr�s.





 
	
7 c@seZdZdd�ZdS)r|c
sPtj|f|||||d�|���_�fdd�}�jjjt�jj��}	|	j|�dS)N)rr�r�r�r�cs�jj�}�j|�dS)N)�_procZpollZ_process_exited)rm�
returncode)rrrr��s
z4_WindowsSubprocessTransport._start.<locals>.callback)	r	�Popenr�r)rIr��intr7rv)
rr~rr�r�r�r�r�r�rmr)rr�_start�sz"_WindowsSubprocessTransport._startN)r1r2r3r�rrrrr|�sr|c@seZdZeZdS)�_WindowsDefaultEventLoopPolicyN)r1r2r3r
Z
_loop_factoryrrrrr�sr�)-r4r<r�r�r�r�rR�rrrrrrr	r
Z
coroutinesr�logr�__all__r[r�ZERROR_CONNECTION_REFUSEDZERROR_CONNECTION_ABORTEDr�r�ZFuturerr6rDrH�objectrPZBaseSelectorEventLoopreZBaseProactorEventLooprrZBaseSubprocessTransportr|r
ZBaseDefaultEventLoopPolicyr�rrrrr�<module>sL0J4;]kPK[�H�O�O/__pycache__/windows_events.cpython-36.opt-2.pycnu�[���3


 \�l�@s�ddlZddlZddlZddlZddlZddlZddlmZddlmZddlm	Z	ddlm
Z
ddlmZddlmZdd	lm
Z
dd
lmZddlmZddlmZd
dddgZdZdZdZdZdZdZGdd�de	j�ZGdd�de	j�ZGdd�de�ZGdd�de�ZGdd�de�Z Gd d!�d!ej!�Z"Gd"d�de
j#�Z$Gd#d�d�Z%Gd$d%�d%ej&�Z'e"Z(Gd&d'�d'ej)�Z*e*Z+dS)(�N�)�events)�base_subprocess)�futures)�proactor_events)�selector_events)�tasks)�
windows_utils)�_overlapped)�	coroutine)�logger�SelectorEventLoop�ProactorEventLoop�IocpProactor�DefaultEventLoopPolicyl��i�i�g����MbP?g�������?csZeZdZdd��fdd�
Z�fdd�Zdd�Z�fd	d
�Z�fdd�Z�fd
d�Z�Z	S)�_OverlappedFutureN)�loopcs&t�j|d�|jr|jd=||_dS)N)rr���)�super�__init__�_source_traceback�_ov)�self�ovr)�	__class__��./usr/lib64/python3.6/asyncio/windows_events.pyr-sz_OverlappedFuture.__init__cs@t�j�}|jdk	r<|jjr dnd}|jdd||jjf�|S)N�pendingZ	completedrzoverlapped=<%s, %#x>)r�
_repr_inforr�insert�address)r�info�state)rrrr3s


z_OverlappedFuture._repr_infocCsr|jdkrdSy|jj�WnJtk
rf}z.d||d�}|jrJ|j|d<|jj|�WYdd}~XnXd|_dS)Nz&Cancelling an overlapped future failed)�message�	exception�future�source_traceback)r�cancel�OSErrorr�_loop�call_exception_handler)r�exc�contextrrr�_cancel_overlapped:s

z$_OverlappedFuture._cancel_overlappedcs|j�t�j�S)N)r-rr')r)rrrr'Jsz_OverlappedFuture.cancelcst�j|�|j�dS)N)r�
set_exceptionr-)rr$)rrrr.Nsz_OverlappedFuture.set_exceptioncst�j|�d|_dS)N)r�
set_resultr)r�result)rrrr/Rsz_OverlappedFuture.set_result)
�__name__�
__module__�__qualname__rrr-r'r.r/�
__classcell__rr)rrr'srcsjeZdZdd��fdd�
Zdd�Z�fdd�Zd	d
�Zdd�Z�fd
d�Z�fdd�Z	�fdd�Z
�ZS)�_BaseWaitHandleFutureN)rcs8t�j|d�|jr|jd=||_||_||_d|_dS)N)rrTr)rrrr�_handle�_wait_handle�_registered)rr�handle�wait_handler)rrrrZsz_BaseWaitHandleFuture.__init__cCstj|jd�tjkS)Nr)�_winapiZWaitForSingleObjectr6Z
WAIT_OBJECT_0)rrrr�_pollhsz_BaseWaitHandleFuture._pollcs\t�j�}|jd|j�|jdk	r>|j�r0dnd}|j|�|jdk	rX|jd|j�|S)Nz
handle=%#xZsignaledZwaitingzwait_handle=%#x)rr�appendr6r<r7)rr!r")rrrrms



z _BaseWaitHandleFuture._repr_infocCs
d|_dS)N)r)r�futrrr�_unregister_wait_cbwsz)_BaseWaitHandleFuture._unregister_wait_cbcCs�|js
dSd|_|j}d|_ytj|�WnZtk
r�}z>|jtjkrtd||d�}|jrd|j|d<|jj	|�dSWYdd}~XnX|j
d�dS)NFz$Failed to unregister the wait handle)r#r$r%r&)r8r7r
ZUnregisterWaitr(�winerror�ERROR_IO_PENDINGrr)r*r?)rr:r+r,rrr�_unregister_wait|s"
z&_BaseWaitHandleFuture._unregister_waitcs|j�t�j�S)N)rBrr')r)rrrr'�sz_BaseWaitHandleFuture.cancelcs|j�t�j|�dS)N)rBrr.)rr$)rrrr.�sz#_BaseWaitHandleFuture.set_exceptioncs|j�t�j|�dS)N)rBrr/)rr0)rrrr/�sz _BaseWaitHandleFuture.set_result)r1r2r3rr<rr?rBr'r.r/r4rr)rrr5Ws
r5csBeZdZdd��fdd�
Zdd�Z�fdd�Z�fd	d
�Z�ZS)�_WaitCancelFutureN)rcst�j||||d�d|_dS)N)r)rr�_done_callback)rr�eventr:r)rrrr�sz_WaitCancelFuture.__init__cCstd��dS)Nz'_WaitCancelFuture must not be cancelled)�RuntimeError)rrrrr'�sz_WaitCancelFuture.cancelcs$t�j|�|jdk	r |j|�dS)N)rr/rD)rr0)rrrr/�s
z_WaitCancelFuture.set_resultcs$t�j|�|jdk	r |j|�dS)N)rr.rD)rr$)rrrr.�s
z_WaitCancelFuture.set_exception)r1r2r3rr'r/r.r4rr)rrrC�srCcs6eZdZdd��fdd�
Z�fdd�Zdd�Z�ZS)	�_WaitHandleFutureN)rcs<t�j||||d�||_d|_tjdddd�|_d|_dS)N)rTF)rr�	_proactorZ_unregister_proactorr
ZCreateEvent�_event�
_event_fut)rrr9r:�proactorr)rrrr�s
z_WaitHandleFuture.__init__csF|jdk	r"tj|j�d|_d|_|jj|j�d|_t�j|�dS)N)	rIr;�CloseHandlerJrH�_unregisterrrr?)rr>)rrrr?�s
	z%_WaitHandleFuture._unregister_wait_cbcCs�|js
dSd|_|j}d|_ytj||j�WnZtk
r�}z>|jtjkrxd||d�}|jrh|j|d<|j	j
|�dSWYdd}~XnX|jj|j|j
�|_dS)NFz$Failed to unregister the wait handle)r#r$r%r&)r8r7r
ZUnregisterWaitExrIr(r@rArr)r*rH�_wait_cancelr?rJ)rr:r+r,rrrrB�s$

z"_WaitHandleFuture._unregister_wait)r1r2r3rr?rBr4rr)rrrG�srGc@s8eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZeZdS)�
PipeServercCs,||_tj�|_d|_d|_|jd�|_dS)NT)�_address�weakref�WeakSet�_free_instances�_pipe�_accept_pipe_future�_server_pipe_handle)rr rrrr�s

zPipeServer.__init__cCs|j|jd�}|_|S)NF)rTrV)r�tmprrr�_get_unconnected_pipe�sz PipeServer._get_unconnected_pipec	Csr|j�rdStjtjB}|r&|tjO}tj|j|tjtjBtj	Btj
tjtjtj
tj�}tj|�}|jj|�|S)N)�closedr;ZPIPE_ACCESS_DUPLEXZFILE_FLAG_OVERLAPPEDZFILE_FLAG_FIRST_PIPE_INSTANCEZCreateNamedPiperPZPIPE_TYPE_MESSAGEZPIPE_READMODE_MESSAGEZ	PIPE_WAITZPIPE_UNLIMITED_INSTANCESr	ZBUFSIZEZNMPWAIT_WAIT_FOREVER�NULL�
PipeHandlerS�add)r�first�flags�h�piperrrrVs


zPipeServer._server_pipe_handlecCs
|jdkS)N)rP)rrrrrYszPipeServer.closedcCsV|jdk	r|jj�d|_|jdk	rRx|jD]}|j�q,Wd|_d|_|jj�dS)N)rUr'rPrS�closerT�clear)rr`rrrras


zPipeServer.closeN)	r1r2r3rrXrVrYra�__del__rrrrrO�s
rOc@seZdZdd�ZdS)�_WindowsSelectorEventLoopcCstj�S)N)r	�
socketpair)rrrr�_socketpair+sz%_WindowsSelectorEventLoop._socketpairN)r1r2r3rfrrrrrd(srdcsLeZdZd�fdd�	Zdd�Zedd��Zedd	��Zed
d
d��Z�Z	S)rNcs|dkrt�}t�j|�dS)N)rrr)rrK)rrrr2szProactorEventLoop.__init__cCstj�S)N)r	re)rrrrrf7szProactorEventLoop._socketpairccs8|jj|�}|EdH}|�}|j||d|id�}||fS)N�addr)�extra)rH�connect_pipe�_make_duplex_pipe_transport)r�protocol_factoryr �fr`�protocol�transrrr�create_pipe_connection:s
z(ProactorEventLoop.create_pipe_connectioncs.t���d�����fdd�	��j���gS)Ncsd}yj|rL|j�}�jj|��j�r2|j�dS��}�j||d�id��j�}|dkr`dS�jj|�}Wn�t	k
r�}zH|r�|j
�d	kr��jd||d��|j�n�jr�t
jd|dd�WYdd}~Xn2tjk
r�|r�|j�YnX|�_|j��dS)
Nrg)rhrzPipe accept failed)r#r$r`zAccept pipe failed on pipe %rT)�exc_infor)r0rS�discardrYrarjrXrH�accept_piper(�filenor*Z_debugrZwarningr�CancelledErrorrU�add_done_callback)rlr`rmr+)r �loop_accept_piperkr�serverrrrvGs<

z>ProactorEventLoop.start_serving_pipe.<locals>.loop_accept_pipe)N)rOZ	call_soon)rrkr r)r rvrkrrwr�start_serving_pipeCs(
z$ProactorEventLoop.start_serving_pipec	ks�|j�}
t||||||||f|
|d�|	��}y|
EdHWn&tk
r`}z
|}
WYdd}~XnXd}
|
dk	r�|j�|j�EdH|
�|S)N)�waiterrh)�
create_future�_WindowsSubprocessTransport�	ExceptionraZ_wait)rrm�args�shell�stdin�stdout�stderr�bufsizerh�kwargsryZtranspr+�errrrr�_make_subprocess_transportrs

z,ProactorEventLoop._make_subprocess_transport)N)N)
r1r2r3rrfrrorxr�r4rr)rrr/s	/c@s�eZdZd0dd�Zdd�Zdd�Zd1d	d
�Zdd�Zd2dd�Zd3dd�Z	dd�Z
dd�Zdd�Ze
dd��Zd4dd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd5d(d)�Zd*d+�Zd,d-�Zd.d/�ZdS)6r���cCsDd|_g|_tjtjtd|�|_i|_tj	�|_
g|_tj	�|_dS)Nr)
r)�_resultsr
�CreateIoCompletionPort�INVALID_HANDLE_VALUErZ�_iocp�_cacherQrRr8�
_unregistered�_stopped_serving)rZconcurrencyrrrr�s
zIocpProactor.__init__cCsd|jjt|j�t|j�fS)Nz<%s overlapped#=%s result#=%s>)rr1�lenr�r�)rrrr�__repr__�szIocpProactor.__repr__cCs
||_dS)N)r))rrrrr�set_loop�szIocpProactor.set_loopNcCs |js|j|�|j}g|_|S)N)r�r<)r�timeoutrWrrr�select�s

zIocpProactor.selectcCs|jj�}|j|�|S)N)r)rzr/)r�valuer>rrr�_result�s

zIocpProactor._resultrcCsz|j|�tjt�}y4t|tj�r6|j|j�||�n|j|j�|�Wnt	k
rb|j
d�SXdd�}|j|||�S)N�cSsJy|j�Stk
rD}z |jtjkr2t|j��n�WYdd}~XnXdS)N)�	getresultr(r@r
�ERROR_NETNAME_DELETED�ConnectionResetErrorr})rn�keyrr+rrr�finish_recv�sz&IocpProactor.recv.<locals>.finish_recv)�_register_with_iocpr
�
OverlappedrZ�
isinstance�socketZWSARecvrsZReadFile�BrokenPipeErrorr��	_register)r�conn�nbytesr^rr�rrr�recv�s

	zIocpProactor.recvcCsZ|j|�tjt�}t|tj�r4|j|j�||�n|j|j�|�dd�}|j	|||�S)NcSsJy|j�Stk
rD}z |jtjkr2t|j��n�WYdd}~XnXdS)N)r�r(r@r
r�r�r})rnr�rr+rrr�finish_send�sz&IocpProactor.send.<locals>.finish_send)
r�r
r�rZr�r�ZWSASendrsZ	WriteFiler�)rr��bufr^rr�rrr�send�s

	zIocpProactor.sendcsz|j��|j�j��tjt�}|j�j��j����fdd�}tdd��}|j	|�|�}||��}t
j||jd�|S)NcsD|j�tjd�j��}�jtjtj|��j	�j
����j�fS)Nz@P)r��structZpackrs�
setsockoptr��
SOL_SOCKETr
ZSO_UPDATE_ACCEPT_CONTEXT�
settimeoutZ
gettimeoutZgetpeername)rnr�rr�)r��listenerrr�
finish_accept�s
z*IocpProactor.accept.<locals>.finish_acceptcss4y|EdHWn tjk
r.|j��YnXdS)N)rrtra)r%r�rrr�accept_coro�s
z(IocpProactor.accept.<locals>.accept_coro)r)
r��_get_accept_socket�familyr
r�rZZAcceptExrsrr�rZ
ensure_futurer))rr�rr�r�r%�coror)r�r�r�accept�s

		
zIocpProactor.acceptcs�|j��ytj�j��j�WnBtk
rb}z&|jtjkr@��j	�ddkrR�WYdd}~XnXtj
t�}|j�j�|��fdd�}|j
|�|�S)Nrrcs|j��jtjtjd��S)Nr)r�r�r�r�r
ZSO_UPDATE_CONNECT_CONTEXT)rnr�r)r�rr�finish_connects
z,IocpProactor.connect.<locals>.finish_connect)r�r
Z	BindLocalrsr�r(r@�errnoZ	WSAEINVALZgetsocknamer�rZZ	ConnectExr�)rr�r �err�r)r�r�connect�s

zIocpProactor.connectcsJ|j��tjt�}|j�j��}|r0|j��S�fdd�}|j|�|�S)Ncs|j��S)N)r�)rnr�r)r`rr�finish_accept_pipesz4IocpProactor.accept_pipe.<locals>.finish_accept_pipe)r�r
r�rZZConnectNamedPipersr�r�)rr`rZ	connectedr�r)r`rrr
s


zIocpProactor.accept_pipeccszt}xjytj|�}PWn0tk
rF}z|jtjkr6�WYdd}~XnXt|dt�}tj	||j
d�EdHqWtj|�S)N�)r)
�CONNECT_PIPE_INIT_DELAYr
ZConnectPiper(r@ZERROR_PIPE_BUSY�min�CONNECT_PIPE_MAX_DELAYrZsleepr)r	r[)rr Zdelayr9r+rrrris
zIocpProactor.connect_pipecCs|j||d�S)NF)�_wait_for_handle)rr9r�rrr�wait_for_handle/szIocpProactor.wait_for_handlecCs|j|dd�}||_|S)NT)r�rD)rrEZ
done_callbackr>rrrrN7szIocpProactor._wait_cancelcs�|dkrtj}ntj|d�}tjt�}tj||j|j	|�}|rTt
||||jd��nt|||||jd���j
rv�j
d=�fdd�}�|d|f|j|j	<�S)Ng@�@)rrcs�j�S)N)r<)rnr�r)rlrr�finish_wait_for_handleRsz=IocpProactor._wait_for_handle.<locals>.finish_wait_for_handlerr)r;�INFINITE�math�ceilr
r�rZZRegisterWaitWithQueuer�r rCr)rGrr�)rr9r�Z
_is_cancel�msrr:r�r)rlrr�>s


	zIocpProactor._wait_for_handlecCs0||jkr,|jj|�tj|j�|jdd�dS)Nr)r8r\r
r�rsr�)r�objrrrr�^s
z IocpProactor._register_with_iocpcCs�t||jd�}|jr|jd=|jsjy|dd|�}Wn,tk
r^}z|j|�WYdd}~XnX|j|�||||f|j|j<|S)N)rrr)	rr)rrr(r.r/r�r )rrr��callbackrlr�r�rrrr�hs

zIocpProactor._registercCs|jj|�dS)N)r�r=)rrrrrrM�szIocpProactor._unregistercCstj|�}|jd�|S)Nr)r�r�)rr��srrrr��s

zIocpProactor._get_accept_socketcCs�|dkrt}n0|dkr td��ntj|d�}|tkr>td���xtj|j|�}|dkrZPd}|\}}}}y|jj|�\}}	}
}WnVt	k
r�|j
j�r�|j
jdd||||fd��|dtj
fkr�tj|�wBYnX|
|jkr�|j�qB|j�sBy||||	�}Wn:tk
�r@}
z|j|
�|jj|�WYdd}
~
XqBX|j|�|jj|�qBWx |jD]}	|jj|	jd��qdW|jj�dS)Nrznegative timeoutg@�@ztimeout too bigz8GetQueuedCompletionStatus() returned an unexpected eventz)err=%s transferred=%s key=%#x address=%#x)r#�status)r��
ValueErrorr�r�r
ZGetQueuedCompletionStatusr�r��pop�KeyErrorr)Z	get_debugr*r�r;rLr�r'�doner(r.r�r=r/r�r rb)rr�r�r�r�Ztransferredr�r rlrr�r�r�r�rrrr<�sJ






zIocpProactor._pollcCs|jj|�dS)N)r�r\)rr�rrr�
_stop_serving�szIocpProactor._stop_servingcCs�x�t|jj��D]�\}\}}}}|j�r*qt|t�r6qy|j�Wqtk
r�}z8|jdk	r�d||d�}|j	rz|j	|d<|jj
|�WYdd}~XqXqWx|jr�|jd�s�tj
d�q�Wg|_|jdk	r�tj|j�d|_dS)NzCancelling a future failed)r#r$r%r&rz"taking long time to close proactor)�listr��itemsZ	cancelledr�rCr'r(r)rr*r<r�debugr�r�r;rL)rr r>rr�r�r+r,rrrra�s, 


"

zIocpProactor.closecCs|j�dS)N)ra)rrrrrc�szIocpProactor.__del__)r�)N)r)r)N)N)r1r2r3rr�r�r�r�r�r�r�r�rrrrir�rNr�r�r�rMr�r<r�rarcrrrrr�s,





 
	
7 c@seZdZdd�ZdS)r{c
sPtj|f|||||d�|���_�fdd�}�jjjt�jj��}	|	j|�dS)N)r~rr�r�r�cs�jj�}�j|�dS)N)�_procZpollZ_process_exited)rl�
returncode)rrrr��s
z4_WindowsSubprocessTransport._start.<locals>.callback)	r	�Popenr�r)rHr��intr6ru)
rr}r~rr�r�r�r�r�rlr)rr�_start�sz"_WindowsSubprocessTransport._startN)r1r2r3r�rrrrr{�sr{c@seZdZeZdS)�_WindowsDefaultEventLoopPolicyN)r1r2r3r
Z
_loop_factoryrrrrr�sr�),r;r�r�r�r�rQ�rrrrrrr	r
Z
coroutinesr�logr�__all__rZr�ZERROR_CONNECTION_REFUSEDZERROR_CONNECTION_ABORTEDr�r�ZFuturerr5rCrG�objectrOZBaseSelectorEventLooprdZBaseProactorEventLooprrZBaseSubprocessTransportr{r
ZBaseDefaultEventLoopPolicyr�rrrrr�<module>sJ0J4;]kPK[6����D�D'__pycache__/events.cpython-36.opt-2.pycnu�[���3


 \�[�@s|dddddddddd	d
ddd
gZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZdd�Z
dd�Zd2dd�Zdd�Zd3dd�ZGdd�d�ZGdd�de�ZGd d�d�ZGd!d�d�ZGd"d�d�ZGd#d$�d$e�Zdaej�ZGd%d&�d&ej�Ze�Zd'd
�Zd(d�Zd)d*�Z d+d�Z!d,d�Z"d-d�Z#d.d�Z$d/d	�Z%d0d
�Z&d1d�Z'dS)4�AbstractEventLoopPolicy�AbstractEventLoop�AbstractServer�Handle�TimerHandle�get_event_loop_policy�set_event_loop_policy�get_event_loop�set_event_loop�new_event_loop�get_child_watcher�set_child_watcher�_set_running_loop�_get_running_loop�N�)�compat)�	constantscCsttjrtj|�}nt|d�r"|j}tj|�r>|j}|j|j	fSt
|tj�rTt
|j�Stjrpt
|tj�rpt
|j�SdS)N�__wrapped__)rZPY34�inspectZunwrap�hasattrrZ
isfunction�__code__�co_filename�co_firstlineno�
isinstance�	functools�partial�_get_function_source�func�
partialmethod)r�code�r �&/usr/lib64/python3.6/asyncio/events.pyrs



rcCsJg}|r|jdd�|D��|r8|jdd�|j�D��ddj|�dS)Ncss|]}tj|�VqdS)N)�reprlib�repr)�.0�argr r r!�	<genexpr>1sz*_format_args_and_kwargs.<locals>.<genexpr>css$|]\}}dj|tj|��VqdS)z{}={}N)�formatr"r#)r$�k�vr r r!r&3s�(z, �))�extend�items�join)�args�kwargsr-r r r!�_format_args_and_kwargs)s
r1�cCs�t|tj�r.t||�|}t|j|j|j|�St|d�rF|j	rF|j	}n t|d�r^|j
r^|j
}nt|�}|t||�7}|r�||7}|S)N�__qualname__�__name__)rrrr1�_format_callbackrr/�keywordsrr3r4r#)rr/r0�suffix�	func_reprr r r!r58sr5cCs(t||d�}t|�}|r$|d|7}|S)Nz	 at %s:%s)r5r)rr/r8�sourcer r r!�_format_callback_sourceIs
r:cCsD|dkrtj�j}|dkr tj}tjjtj|�|dd�}|j	�|S)NF)�limit�lookup_lines)
�sys�	_getframe�f_backrZDEBUG_STACK_DEPTH�	traceback�StackSummary�extract�
walk_stack�reverse)�fr;�stackr r r!�
extract_stackQs
rGc@s8eZdZdZdd	�Zd
d�Zdd
�Zdd�Zdd�ZdS)r�	_callback�_args�
_cancelled�_loop�_source_traceback�_repr�__weakref__cCsD||_||_||_d|_d|_|jj�r:ttjd��|_	nd|_	dS)NFr)
rKrHrIrJrM�	get_debugrGr=r>rL)�self�callbackr/�loopr r r!�__init__hs
zHandle.__init__cCsf|jjg}|jr|jd�|jdk	r8|jt|j|j��|jrb|jd}|jd|d|df�|S)NZ	cancelledrzcreated at %s:%sr���)�	__class__r4rJ�appendrHr:rIrL)rP�info�framer r r!�
_repr_infoss



zHandle._repr_infocCs&|jdk	r|jS|j�}ddj|�S)Nz<%s>� )rMrYr.)rPrWr r r!�__repr__~s
zHandle.__repr__cCs0|js,d|_|jj�r t|�|_d|_d|_dS)NT)rJrKrOr#rMrHrI)rPr r r!�cancel�s

z
Handle.cancelcCs|y|j|j�Wnbtk
rr}zFt|j|j�}dj|�}|||d�}|jrV|j|d<|jj|�WYdd}~XnXd}dS)NzException in callback {})�messageZ	exception�handleZsource_traceback)rHrI�	Exceptionr:r'rLrK�call_exception_handler)rP�exc�cb�msg�contextr r r!�_run�s

zHandle._runN)rHrIrJrKrLrMrN)	r4�
__module__r3�	__slots__rSrYr[r\rer r r r!rbscsteZdZddgZ�fdd�Z�fdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Z�fdd�Z
�ZS)r�
_scheduled�_whencs.t�j|||�|jr|jd=||_d|_dS)NrFrT)�superrSrLrirh)rP�whenrQr/rR)rUr r!rS�s
zTimerHandle.__init__cs.t�j�}|jrdnd}|j|d|j�|S)N�rzwhen=%s)rjrYrJ�insertri)rPrW�pos)rUr r!rY�s
zTimerHandle._repr_infocCs
t|j�S)N)�hashri)rPr r r!�__hash__�szTimerHandle.__hash__cCs|j|jkS)N)ri)rP�otherr r r!�__lt__�szTimerHandle.__lt__cCs|j|jkrdS|j|�S)NT)ri�__eq__)rPrqr r r!�__le__�szTimerHandle.__le__cCs|j|jkS)N)ri)rPrqr r r!�__gt__�szTimerHandle.__gt__cCs|j|jkrdS|j|�S)NT)rirs)rPrqr r r!�__ge__�szTimerHandle.__ge__cCs>t|t�r:|j|jko8|j|jko8|j|jko8|j|jkStS)N)rrrirHrIrJ�NotImplemented)rPrqr r r!rs�s
zTimerHandle.__eq__cCs|j|�}|tkrtS|S)N)rsrw)rPrqZequalr r r!�__ne__�s
zTimerHandle.__ne__cs |js|jj|�t�j�dS)N)rJrK�_timer_handle_cancelledrjr\)rP)rUr r!r\�szTimerHandle.cancel)r4rfr3rgrSrYrprrrtrurvrsrxr\�
__classcell__r r )rUr!r�sc@seZdZdd�Zdd�ZdS)rcCstS)N)rw)rPr r r!�close�szAbstractServer.closecCstS)N)rw)rPr r r!�wait_closed�szAbstractServer.wait_closedN)r4rfr3r{r|r r r r!r�sc	@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d#d#d#d$�d%d&�Zdgd'd(�Zdhd)d#d#d#d)d)d)d*�d+d,�Zdiejejd)d-d)d)d)d.�d/d0�Zd)d)d)d1�d2d3�Zd)d-d)d4�d5d6�Zdjd#d#d#d)d)d)d)d7�d8d9�Zd:d;�Zd<d=�Ze j!e j!e j!d>�d?d@�Z"e j!e j!e j!d>�dAdB�Z#dCdD�Z$dEdF�Z%dGdH�Z&dIdJ�Z'dKdL�Z(dMdN�Z)dOdP�Z*dQdR�Z+dSdT�Z,dUdV�Z-dWdX�Z.dYdZ�Z/d[d\�Z0d]d^�Z1d_d`�Z2dadb�Z3dcdd�Z4dedf�Z5d)S)krcCst�dS)N)�NotImplementedError)rPr r r!�run_forever�szAbstractEventLoop.run_forevercCst�dS)N)r})rPZfuturer r r!�run_until_complete�sz$AbstractEventLoop.run_until_completecCst�dS)N)r})rPr r r!�stop�szAbstractEventLoop.stopcCst�dS)N)r})rPr r r!�
is_running�szAbstractEventLoop.is_runningcCst�dS)N)r})rPr r r!�	is_closedszAbstractEventLoop.is_closedcCst�dS)N)r})rPr r r!r{s	zAbstractEventLoop.closecCst�dS)N)r})rPr r r!�shutdown_asyncgenssz$AbstractEventLoop.shutdown_asyncgenscCst�dS)N)r})rPr^r r r!rysz)AbstractEventLoop._timer_handle_cancelledcGs|jd|f|��S)Nr)�
call_later)rPrQr/r r r!�	call_soonszAbstractEventLoop.call_sooncGst�dS)N)r})rPZdelayrQr/r r r!r�szAbstractEventLoop.call_latercGst�dS)N)r})rPrkrQr/r r r!�call_atszAbstractEventLoop.call_atcCst�dS)N)r})rPr r r!�time"szAbstractEventLoop.timecCst�dS)N)r})rPr r r!�
create_future%szAbstractEventLoop.create_futurecCst�dS)N)r})rP�coror r r!�create_task*szAbstractEventLoop.create_taskcGst�dS)N)r})rPrQr/r r r!�call_soon_threadsafe/sz&AbstractEventLoop.call_soon_threadsafecGst�dS)N)r})rP�executorrr/r r r!�run_in_executor2sz!AbstractEventLoop.run_in_executorcCst�dS)N)r})rPr�r r r!�set_default_executor5sz&AbstractEventLoop.set_default_executorr)�family�type�proto�flagscCst�dS)N)r})rP�host�portr�r�r�r�r r r!�getaddrinfo:szAbstractEventLoop.getaddrinfocCst�dS)N)r})rPZsockaddrr�r r r!�getnameinfo=szAbstractEventLoop.getnameinfoN)�sslr�r�r��sock�
local_addr�server_hostnamecCst�dS)N)r})rP�protocol_factoryr�r�r�r�r�r�r�r�r�r r r!�create_connection@sz#AbstractEventLoop.create_connection�d)r�r�r��backlogr��
reuse_address�
reuse_portcCst�dS)N)r})rPr�r�r�r�r�r�r�r�r�r�r r r!�
create_serverEs'zAbstractEventLoop.create_server)r�r�r�cCst�dS)N)r})rPr��pathr�r�r�r r r!�create_unix_connectionnsz(AbstractEventLoop.create_unix_connection)r�r�r�cCst�dS)N)r})rPr�r�r�r�r�r r r!�create_unix_serverssz$AbstractEventLoop.create_unix_server)r�r�r�r�r��allow_broadcastr�cCst�dS)N)r})rPr�r�Zremote_addrr�r�r�r�r�r�r�r r r!�create_datagram_endpoint�s!z*AbstractEventLoop.create_datagram_endpointcCst�dS)N)r})rPr��piper r r!�connect_read_pipe�sz#AbstractEventLoop.connect_read_pipecCst�dS)N)r})rPr�r�r r r!�connect_write_pipe�sz$AbstractEventLoop.connect_write_pipe)�stdin�stdout�stderrcKst�dS)N)r})rPr��cmdr�r�r�r0r r r!�subprocess_shell�sz"AbstractEventLoop.subprocess_shellcOst�dS)N)r})rPr�r�r�r�r/r0r r r!�subprocess_exec�sz!AbstractEventLoop.subprocess_execcGst�dS)N)r})rP�fdrQr/r r r!�
add_reader�szAbstractEventLoop.add_readercCst�dS)N)r})rPr�r r r!�
remove_reader�szAbstractEventLoop.remove_readercGst�dS)N)r})rPr�rQr/r r r!�
add_writer�szAbstractEventLoop.add_writercCst�dS)N)r})rPr�r r r!�
remove_writer�szAbstractEventLoop.remove_writercCst�dS)N)r})rPr��nbytesr r r!�	sock_recv�szAbstractEventLoop.sock_recvcCst�dS)N)r})rPr��datar r r!�sock_sendall�szAbstractEventLoop.sock_sendallcCst�dS)N)r})rPr�Zaddressr r r!�sock_connect�szAbstractEventLoop.sock_connectcCst�dS)N)r})rPr�r r r!�sock_accept�szAbstractEventLoop.sock_acceptcGst�dS)N)r})rP�sigrQr/r r r!�add_signal_handler�sz$AbstractEventLoop.add_signal_handlercCst�dS)N)r})rPr�r r r!�remove_signal_handler�sz'AbstractEventLoop.remove_signal_handlercCst�dS)N)r})rP�factoryr r r!�set_task_factory�sz"AbstractEventLoop.set_task_factorycCst�dS)N)r})rPr r r!�get_task_factory�sz"AbstractEventLoop.get_task_factorycCst�dS)N)r})rPr r r!�get_exception_handlersz'AbstractEventLoop.get_exception_handlercCst�dS)N)r})rPZhandlerr r r!�set_exception_handlersz'AbstractEventLoop.set_exception_handlercCst�dS)N)r})rPrdr r r!�default_exception_handlersz+AbstractEventLoop.default_exception_handlercCst�dS)N)r})rPrdr r r!r`sz(AbstractEventLoop.call_exception_handlercCst�dS)N)r})rPr r r!rOszAbstractEventLoop.get_debugcCst�dS)N)r})rPZenabledr r r!�	set_debugszAbstractEventLoop.set_debug)r)NN)NN)NN)6r4rfr3r~rr�r�r�r{r�ryr�r�r�r�r�r�r�r�r�r�r�r��socketZ	AF_UNSPECZ
AI_PASSIVEr�r�r�r�r�r��
subprocess�PIPEr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r`rOr�r r r r!r�sr

'!

	c@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)rcCst�dS)N)r})rPr r r!rsz&AbstractEventLoopPolicy.get_event_loopcCst�dS)N)r})rPrRr r r!r	$sz&AbstractEventLoopPolicy.set_event_loopcCst�dS)N)r})rPr r r!r
(sz&AbstractEventLoopPolicy.new_event_loopcCst�dS)N)r})rPr r r!r0sz)AbstractEventLoopPolicy.get_child_watchercCst�dS)N)r})rP�watcherr r r!r4sz)AbstractEventLoopPolicy.set_child_watcherN)r4rfr3rr	r
rrr r r r!rs

c@sBeZdZdZGdd�dej�Zdd�Zdd�Zdd	�Z	d
d�Z
dS)�BaseDefaultEventLoopPolicyNc@seZdZdZdZdS)z!BaseDefaultEventLoopPolicy._LocalNF)r4rfr3rK�_set_calledr r r r!�_LocalHsr�cCs|j�|_dS)N)r��_local)rPr r r!rSLsz#BaseDefaultEventLoopPolicy.__init__cCsZ|jjdkr4|jjr4ttj�tj�r4|j|j��|jjdkrRt	dtj�j
��|jjS)Nz,There is no current event loop in thread %r.)r�rKr�r�	threadingZcurrent_threadZ_MainThreadr	r
�RuntimeError�name)rPr r r!rOs
z)BaseDefaultEventLoopPolicy.get_event_loopcCsd|j_||j_dS)NT)r�r�rK)rPrRr r r!r	]sz)BaseDefaultEventLoopPolicy.set_event_loopcCs|j�S)N)�
_loop_factory)rPr r r!r
csz)BaseDefaultEventLoopPolicy.new_event_loop)r4rfr3r�r��localr�rSrr	r
r r r r!r�9s
r�c@seZdZdZdS)�_RunningLoopN)NN)r4rfr3�loop_pidr r r r!r�wsr�cCs&tj\}}|dk	r"|tj�kr"|SdS)N)�
_running_loopr��os�getpid)Zrunning_loop�pidr r r!r~s
cCs|tj�ft_dS)N)r�r�r�r�)rRr r r!r
�sc	Cs.t� tdkr ddlm}|�aWdQRXdS)Nr)�DefaultEventLoopPolicy)�_lock�_event_loop_policyr2r�)r�r r r!�_init_event_loop_policy�sr�cCstdkrt�tS)N)r�r�r r r r!r�scCs|adS)N)r�)Zpolicyr r r!r�scCst�}|dk	r|St�j�S)N)rrr)Zcurrent_loopr r r!r�s	cCst�j|�dS)N)rr	)rRr r r!r	�scCs
t�j�S)N)rr
r r r r!r
�scCs
t�j�S)N)rrr r r r!r�scCst�j|�S)N)rr)r�r r r!r�s)r2)NN)(�__all__rrr�r"r�r�r=r�r@r2rrrr1r5r:rGrrrrrr�r�ZLockr�r�r�r�rr
r�rrrr	r
rrr r r r!�<module>sX

>85"7		PK[�����'__pycache__/compat.cpython-36.opt-1.pycnu�[���3


 \�@s6dZddlZejd	kZejd
kZejdkZdd�ZdS)z8Compatibility helpers for the different Python versions.�N����cCstsdd�|D�}dj|�S)z-Concatenate a sequence of bytes-like objects.css$|]}t|t�rt|�n|VqdS)N)�
isinstance�
memoryview�bytes)�.0�data�r�&/usr/lib64/python3.6/asyncio/compat.py�	<genexpr>sz%flatten_list_bytes.<locals>.<genexpr>�)�PY34�join)Zlist_of_datarrr�flatten_list_bytes
sr)rr)rr)rrr)�__doc__�sys�version_inforZPY35ZPY352rrrrr�<module>s



PK[�a��Z<Z<&__pycache__/locks.cpython-36.opt-1.pycnu�[���3


 \�<�@s�dZdddddgZddlZdd	lmZdd
lmZddlmZddlmZGd
d�d�Z	Gdd�d�Z
Gdd�de
�ZGdd�d�ZGdd�de
�Z
Gdd�de
�ZGdd�de�ZdS)zSynchronization primitives.�Lock�Event�	Condition�	Semaphore�BoundedSemaphore�N�)�compat)�events)�futures)�	coroutinec@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_ContextManageraContext manager.

    This enables the following idiom for acquiring and releasing a
    lock around a block:

        with (yield from lock):
            <block>

    while failing loudly when accidentally using:

        with lock:
            <block>
    cCs
||_dS)N)�_lock)�self�lock�r�%/usr/lib64/python3.6/asyncio/locks.py�__init__sz_ContextManager.__init__cCsdS)Nr)rrrr�	__enter__sz_ContextManager.__enter__cGsz|jj�Wdd|_XdS)N)r
�release)r�argsrrr�__exit__$sz_ContextManager.__exit__N)�__name__�
__module__�__qualname__�__doc__rrrrrrrr
s
rc@sNeZdZdd�Zdd�Zedd��ZejrJdd�Z	ed	d
��Z
edd��Zd
S)�_ContextManagerMixincCstd��dS)Nz9"yield from" should be used as context manager expression)�RuntimeError)rrrrr,sz_ContextManagerMixin.__enter__cGsdS)Nr)rrrrrr0sz_ContextManagerMixin.__exit__ccs|j�EdHt|�S)N)�acquirer)rrrr�__iter__5sz_ContextManagerMixin.__iter__ccs|j�EdHt|�S)N)rr)rrrr�	__await__Hsz_ContextManagerMixin.__await__ccs|j�EdHdS)N)r)rrrr�
__aenter__Msz_ContextManagerMixin.__aenter__cCs|j�dS)N)r)r�exc_type�exc�tbrrr�	__aexit__Tsz_ContextManagerMixin.__aexit__N)rrrrrrrrZPY35rr r$rrrrr+srcsReZdZdZdd�dd�Z�fdd�Zdd	�Zed
d��Zdd
�Z	dd�Z
�ZS)ra�Primitive lock objects.

    A primitive lock is a synchronization primitive that is not owned
    by a particular coroutine when locked.  A primitive lock is in one
    of two states, 'locked' or 'unlocked'.

    It is created in the unlocked state.  It has two basic methods,
    acquire() and release().  When the state is unlocked, acquire()
    changes the state to locked and returns immediately.  When the
    state is locked, acquire() blocks until a call to release() in
    another coroutine changes it to unlocked, then the acquire() call
    resets it to locked and returns.  The release() method should only
    be called in the locked state; it changes the state to unlocked
    and returns immediately.  If an attempt is made to release an
    unlocked lock, a RuntimeError will be raised.

    When more than one coroutine is blocked in acquire() waiting for
    the state to turn to unlocked, only one coroutine proceeds when a
    release() call resets the state to unlocked; first coroutine which
    is blocked in acquire() is being processed.

    acquire() is a coroutine and should be called with 'yield from'.

    Locks also support the context management protocol.  '(yield from lock)'
    should be used as the context manager expression.

    Usage:

        lock = Lock()
        ...
        yield from lock
        try:
            ...
        finally:
            lock.release()

    Context manager usage:

        lock = Lock()
        ...
        with (yield from lock):
             ...

    Lock objects can be tested for locking state:

        if not lock.locked():
           yield from lock
        else:
           # lock is acquired
           ...

    N)�loopcCs.tj�|_d|_|dk	r ||_n
tj�|_dS)NF)�collections�deque�_waiters�_locked�_loopr	�get_event_loop)rr%rrrr�s

z
Lock.__init__csDt�j�}|jrdnd}|jr0dj|t|j��}dj|dd�|�S)N�locked�unlockedz
{},waiters:{}z	<{} [{}]>r���)�super�__repr__r)r(�format�len)r�res�extra)�	__class__rrr0�s

z
Lock.__repr__cCs|jS)z Return True if lock is acquired.)r))rrrrr,�szLock.lockedccs�|jr&tdd�|jD��r&d|_dS|jj�}|jj|�y"z|EdHWd|jj|�XWn&tjk
r�|js~|j	��YnXd|_dS)z�Acquire a lock.

        This method blocks until the lock is unlocked, then sets it to
        locked and returns True.
        css|]}|j�VqdS)N)�	cancelled)�.0�wrrr�	<genexpr>�szLock.acquire.<locals>.<genexpr>TN)
r)�allr(r*�
create_future�append�remover
�CancelledError�_wake_up_first)r�futrrrr�s
zLock.acquirecCs"|jrd|_|j�ntd��dS)aGRelease a lock.

        When the lock is locked, reset it to unlocked, and return.
        If any other coroutines are blocked waiting for the lock to become
        unlocked, allow exactly one of them to proceed.

        When invoked on an unlocked lock, a RuntimeError is raised.

        There is no return value.
        FzLock is not acquired.N)r)r?r)rrrrr�s
zLock.releasecCs>ytt|j��}Wntk
r&dSX|j�s:|jd�dS)z*Wake up the first waiter if it isn't done.NT)�next�iterr(�
StopIteration�done�
set_result)rr@rrrr?�szLock._wake_up_first)rrrrrr0r,rrrr?�
__classcell__rr)r5rrYs4csReZdZdZdd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Ze	dd��Z
�ZS)ra#Asynchronous equivalent to threading.Event.

    Class implementing event objects. An event manages a flag that can be set
    to true with the set() method and reset to false with the clear() method.
    The wait() method blocks until the flag is true. The flag is initially
    false.
    N)r%cCs.tj�|_d|_|dk	r ||_n
tj�|_dS)NF)r&r'r(�_valuer*r	r+)rr%rrrr�s

zEvent.__init__csDt�j�}|jrdnd}|jr0dj|t|j��}dj|dd�|�S)N�setZunsetz
{},waiters:{}z	<{} [{}]>rr.)r/r0rGr(r1r2)rr3r4)r5rrr0�s

zEvent.__repr__cCs|jS)z5Return True if and only if the internal flag is true.)rG)rrrr�is_set�szEvent.is_setcCs2|js.d|_x |jD]}|j�s|jd�qWdS)z�Set the internal flag to true. All coroutines waiting for it to
        become true are awakened. Coroutine that call wait() once the flag is
        true will not block at all.
        TN)rGr(rDrE)rr@rrrrH�s
z	Event.setcCs
d|_dS)z�Reset the internal flag to false. Subsequently, coroutines calling
        wait() will block until set() is called to set the internal flag
        to true again.FN)rG)rrrr�clearszEvent.clearccsB|jr
dS|jj�}|jj|�z|EdHdS|jj|�XdS)z�Block until the internal flag is true.

        If the internal flag is true on entry, return True
        immediately.  Otherwise, block until another coroutine calls
        set() to set the flag to true, then return True.
        TN)rGr*r;r(r<r=)rr@rrr�wait
s

z
Event.wait)rrrrrr0rIrHrJrrKrFrr)r5rr�scsZeZdZdZddd�dd�Z�fdd�Zedd	��Zed
d��Zdd
d�Z	dd�Z
�ZS)raAsynchronous equivalent to threading.Condition.

    This class implements condition variable objects. A condition variable
    allows one or more coroutines to wait until they are notified by another
    coroutine.

    A new Lock object is created and used as the underlying lock.
    N)r%cCsp|dk	r||_n
tj�|_|dkr0t|jd�}n|j|jk	rDtd��||_|j|_|j|_|j|_t	j
�|_dS)N)r%z"loop argument must agree with lock)r*r	r+r�
ValueErrorr
r,rrr&r'r()rrr%rrrr+s
zCondition.__init__csFt�j�}|j�rdnd}|jr2dj|t|j��}dj|dd�|�S)Nr,r-z
{},waiters:{}z	<{} [{}]>rr.)r/r0r,r(r1r2)rr3r4)r5rrr0>s

zCondition.__repr__ccs�|j�std��|j�z8|jj�}|jj|�z|EdHdS|jj|�XWdd}x4y|j�EdHPWqXt	j
k
r�d}YqXXqXW|r�t	j
�XdS)a�Wait until notified.

        If the calling coroutine has not acquired the lock when this
        method is called, a RuntimeError is raised.

        This method releases the underlying lock, and then blocks
        until it is awakened by a notify() or notify_all() call for
        the same condition variable in another coroutine.  Once
        awakened, it re-acquires the lock and returns True.
        zcannot wait on un-acquired lockNTF)r,rrr*r;r(r<r=rr
r>)rr@r6rrrrKEs&

zCondition.waitccs(|�}x|s"|j�EdH|�}qW|S)z�Wait until a predicate becomes true.

        The predicate should be a callable which result will be
        interpreted as a boolean value.  The final predicate value is
        the return value.
        N)rK)rZ	predicate�resultrrr�wait_forks

zCondition.wait_forrcCsL|j�std��d}x2|jD](}||kr*P|j�s|d7}|jd�qWdS)aBy default, wake up one coroutine waiting on this condition, if any.
        If the calling coroutine has not acquired the lock when this method
        is called, a RuntimeError is raised.

        This method wakes up at most n of the coroutines waiting for the
        condition variable; it is a no-op if no coroutines are waiting.

        Note: an awakened coroutine does not actually return from its
        wait() call until it can reacquire the lock. Since notify() does
        not release the lock, its caller should.
        z!cannot notify on un-acquired lockrrFN)r,rr(rDrE)r�n�idxr@rrr�notifyyszCondition.notifycCs|jt|j��dS)aWake up all threads waiting on this condition. This method acts
        like notify(), but wakes up all waiting threads instead of one. If the
        calling thread has not acquired the lock when this method is called,
        a RuntimeError is raised.
        N)rQr2r()rrrr�
notify_all�szCondition.notify_all)N)r)rrrrrr0rrKrNrQrRrFrr)r5rr!s&
csTeZdZdZddd�dd�Z�fdd�Zd	d
�Zdd�Zed
d��Z	dd�Z
�ZS)raA Semaphore implementation.

    A semaphore manages an internal counter which is decremented by each
    acquire() call and incremented by each release() call. The counter
    can never go below zero; when acquire() finds that it is zero, it blocks,
    waiting until some other thread calls release().

    Semaphores also support the context management protocol.

    The optional argument gives the initial value for the internal
    counter; it defaults to 1. If the value given is less than 0,
    ValueError is raised.
    rN)r%cCs>|dkrtd��||_tj�|_|dk	r0||_n
tj�|_dS)Nrz$Semaphore initial value must be >= 0)rLrGr&r'r(r*r	r+)r�valuer%rrrr�s
zSemaphore.__init__csNt�j�}|j�rdn
dj|j�}|jr:dj|t|j��}dj|dd�|�S)Nr,zunlocked,value:{}z
{},waiters:{}z	<{} [{}]>rr.)r/r0r,r1rGr(r2)rr3r4)r5rrr0�s
zSemaphore.__repr__cCs0x*|jr*|jj�}|j�s|jd�dSqWdS)N)r(�popleftrDrE)rZwaiterrrr�
_wake_up_next�s


zSemaphore._wake_up_nextcCs
|jdkS)z:Returns True if semaphore can not be acquired immediately.r)rG)rrrrr,�szSemaphore.lockedc	cszxf|jdkrf|jj�}|jj|�y|EdHWq|j�|jdkr\|j�r\|j��YqXqW|jd8_dS)a5Acquire a semaphore.

        If the internal counter is larger than zero on entry,
        decrement it by one and return True immediately.  If it is
        zero on entry, block, waiting until some other coroutine has
        called release() to make it larger than 0, and then return
        True.
        rNrT)rGr*r;r(r<Zcancelr6rU)rr@rrrr�s

zSemaphore.acquirecCs|jd7_|j�dS)z�Release a semaphore, incrementing the internal counter by one.
        When it was zero on entry and another coroutine is waiting for it to
        become larger than zero again, wake up that coroutine.
        rN)rGrU)rrrrr�szSemaphore.release)r)rrrrrr0rUr,rrrrFrr)r5rr�s

cs4eZdZdZd	dd��fdd�Z�fdd�Z�ZS)
rz�A bounded semaphore implementation.

    This raises ValueError in release() if it would increase the value
    above the initial value.
    rN)r%cs||_t�j||d�dS)N)r%)�_bound_valuer/r)rrSr%)r5rrr�szBoundedSemaphore.__init__cs"|j|jkrtd��t�j�dS)Nz(BoundedSemaphore released too many times)rGrVrLr/r)r)r5rrr�szBoundedSemaphore.release)r)rrrrrrrFrr)r5rr�s)r�__all__r&�rr	r
Z
coroutinesrrrrrrrrrrrr�<module>s.ByMPK[mʀ��L�L(__pycache__/streams.cpython-36.opt-1.pycnu�[���3


 \�_�@sLdZdddddddgZdd	lZeed
�r6ejddg�d
dlmZd
dlmZd
dlmZd
dlm	Z	d
dlm
Z
d
dlmZd"Z
Gdd�de�ZGdd�de�Ze
d#d	e
d�dd��Ze
d$d	e
d�dd��Zeed
��re
d%d	e
d�dd��Ze
d&d	e
d�dd��ZGdd�de	j�ZGdd�dee	j�ZGd d�d�ZGd!d�d�Zd	S)'zStream-related things.�StreamReader�StreamWriter�StreamReaderProtocol�open_connection�start_server�IncompleteReadError�LimitOverrunError�NZAF_UNIX�open_unix_connection�start_unix_server�)�
coroutines)�compat)�events)�	protocols)�	coroutine)�logger��cs(eZdZdZ�fdd�Zdd�Z�ZS)rz�
    Incomplete read error. Attributes:

    - partial: read bytes string before the end of stream was reached
    - expected: total number of expected bytes (or None if unknown)
    cs(t�jdt|�|f�||_||_dS)Nz-%d bytes read on a total of %r expected bytes)�super�__init__�len�partial�expected)�selfrr)�	__class__��'/usr/lib64/python3.6/asyncio/streams.pyr szIncompleteReadError.__init__cCst|�|j|jffS)N)�typerr)rrrr�
__reduce__&szIncompleteReadError.__reduce__)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__rr)rrrscs(eZdZdZ�fdd�Zdd�Z�ZS)rz�Reached the buffer limit while looking for a separator.

    Attributes:
    - consumed: total number of to be consumed bytes.
    cst�j|�||_dS)N)rr�consumed)r�messager$)rrrr0szLimitOverrunError.__init__cCst|�|jd|jffS)Nr)r�argsr$)rrrrr4szLimitOverrunError.__reduce__)rr r!r"rrr#rr)rrr*s)�loop�limitc	+sb|dkrtj�}t||d�}t||d��|j�fdd�||f|�EdH\}}t|�||�}||fS)a�A wrapper for create_connection() returning a (reader, writer) pair.

    The reader returned is a StreamReader instance; the writer is a
    StreamWriter instance.

    The arguments are all the usual arguments to create_connection()
    except protocol_factory; most common are positional host and port,
    with various optional keyword arguments following.

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    (If you want to customize the StreamReader and/or
    StreamReaderProtocol classes, just copy the code -- there's
    really nothing special here except some convenience.)
    N)r(r')r'cs�S)Nrr)�protocolrr�<lambda>Qsz!open_connection.<locals>.<lambda>)r�get_event_looprrZcreate_connectionr)	�host�portr'r(�kwds�reader�	transport�_�writerr)r)rr8s c+s8�dkrtj�����fdd�}�j|||f|�EdHS)a�Start a socket server, call back for each client connected.

    The first parameter, `client_connected_cb`, takes two parameters:
    client_reader, client_writer.  client_reader is a StreamReader
    object, while client_writer is a StreamWriter object.  This
    parameter can either be a plain callback function or a coroutine;
    if it is a coroutine, it will be automatically converted into a
    Task.

    The rest of the arguments are all the usual arguments to
    loop.create_server() except protocol_factory; most common are
    positional host and port, with various optional keyword arguments
    following.  The return value is the same as loop.create_server().

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    The return value is the same as loop.create_server(), i.e. a
    Server object which can be used to stop the service.
    Ncst��d�}t|��d�}|S)N)r(r')r')rr)r/r))�client_connected_cbr(r'rr�factoryqszstart_server.<locals>.factory)rr+Z
create_server)r3r,r-r'r(r.r4r)r3r(r'rrVsc+s`|dkrtj�}t||d�}t||d��|j�fdd�|f|�EdH\}}t|�||�}||fS)z@Similar to `open_connection` but works with UNIX Domain Sockets.N)r(r')r'cs�S)Nrr)r)rrr*�sz&open_unix_connection.<locals>.<lambda>)rr+rrZcreate_unix_connectionr)�pathr'r(r.r/r0r1r2r)r)rr	}sc+s6�dkrtj�����fdd�}�j||f|�EdHS)z=Similar to `start_server` but works with UNIX Domain Sockets.Ncst��d�}t|��d�}|S)N)r(r')r')rr)r/r))r3r(r'rrr4�sz"start_unix_server.<locals>.factory)rr+Zcreate_unix_server)r3r5r'r(r.r4r)r3r(r'rr
�sc@s>eZdZdZd
dd�Zdd�Zdd�Zd	d
�Zedd��Z	dS)�FlowControlMixina)Reusable flow control logic for StreamWriter.drain().

    This implements the protocol methods pause_writing(),
    resume_reading() and connection_lost().  If the subclass overrides
    these it must call the super methods.

    StreamWriter.drain() must wait for _drain_helper() coroutine.
    NcCs0|dkrtj�|_n||_d|_d|_d|_dS)NF)rr+�_loop�_paused�
_drain_waiter�_connection_lost)rr'rrrr�szFlowControlMixin.__init__cCs d|_|jj�rtjd|�dS)NTz%r pauses writing)r8r7�	get_debugr�debug)rrrr�
pause_writing�s
zFlowControlMixin.pause_writingcCsFd|_|jj�rtjd|�|j}|dk	rBd|_|j�sB|jd�dS)NFz%r resumes writing)r8r7r;rr<r9�done�
set_result)r�waiterrrr�resume_writing�s
zFlowControlMixin.resume_writingcCsVd|_|jsdS|j}|dkr"dSd|_|j�r4dS|dkrH|jd�n
|j|�dS)NT)r:r8r9r>r?�
set_exception)r�excr@rrr�connection_lost�sz FlowControlMixin.connection_lostccs<|jrtd��|jsdS|j}|jj�}||_|EdHdS)NzConnection lost)r:�ConnectionResetErrorr8r9r7�
create_future)rr@rrr�
_drain_helper�s
zFlowControlMixin._drain_helper)N)
rr r!r"rr=rArDrrGrrrrr6�s
	r6csFeZdZdZd
�fdd�	Zdd�Z�fdd�Zd	d
�Zdd�Z�Z	S)ra=Helper class to adapt between Protocol and StreamReader.

    (This is a helper class instead of making StreamReader itself a
    Protocol subclass, because the StreamReader has other potential
    uses, and to prevent the user of the StreamReader to accidentally
    call inappropriate methods of the protocol.)
    Ncs*t�j|d�||_d|_||_d|_dS)N)r'F)rr�_stream_reader�_stream_writer�_client_connected_cb�	_over_ssl)rZ
stream_readerr3r')rrrr�s
zStreamReaderProtocol.__init__cCsd|jj|�|jd�dk	|_|jdk	r`t|||j|j�|_|j|j|j�}tj	|�r`|jj
|�dS)NZ
sslcontext)rH�
set_transport�get_extra_inforKrJrr7rIrZiscoroutineZcreate_task)rr0�resrrr�connection_made�s


z$StreamReaderProtocol.connection_madecsF|jdk	r*|dkr|jj�n|jj|�t�j|�d|_d|_dS)N)rH�feed_eofrBrrDrI)rrC)rrrrD�s
z$StreamReaderProtocol.connection_lostcCs|jj|�dS)N)rH�	feed_data)r�datarrr�
data_receivedsz"StreamReaderProtocol.data_receivedcCs|jj�|jrdSdS)NFT)rHrPrK)rrrr�eof_receiveds
z!StreamReaderProtocol.eof_received)NN)
rr r!r"rrOrDrSrTr#rr)rrr�s
c@sjeZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zddd�Z
edd��ZdS)ra'Wraps a Transport.

    This exposes write(), writelines(), [can_]write_eof(),
    get_extra_info() and close().  It adds drain() which returns an
    optional Future on which you can wait for flow control.  It also
    adds a transport property which references the Transport
    directly.
    cCs||_||_||_||_dS)N)�
_transport�	_protocol�_readerr7)rr0r)r/r'rrrrszStreamWriter.__init__cCs:|jjd|jg}|jdk	r,|jd|j�ddj|�S)Nztransport=%rz	reader=%rz<%s>� )rrrUrW�append�join)r�inforrr�__repr__!s
zStreamWriter.__repr__cCs|jS)N)rU)rrrrr0'szStreamWriter.transportcCs|jj|�dS)N)rU�write)rrRrrrr]+szStreamWriter.writecCs|jj|�dS)N)rU�
writelines)rrRrrrr^.szStreamWriter.writelinescCs
|jj�S)N)rU�	write_eof)rrrrr_1szStreamWriter.write_eofcCs
|jj�S)N)rU�
can_write_eof)rrrrr`4szStreamWriter.can_write_eofcCs
|jj�S)N)rU�close)rrrrra7szStreamWriter.closeNcCs|jj||�S)N)rUrM)r�name�defaultrrrrM:szStreamWriter.get_extra_infoccsN|jdk	r |jj�}|dk	r |�|jdk	r:|jj�r:dV|jj�EdHdS)z~Flush the write buffer.

        The intended use is to write

          w.write(data)
          yield from w.drain()
        N)rW�	exceptionrUZ
is_closingrVrG)rrCrrr�drain=s	



zStreamWriter.drain)N)rr r!r"rr\�propertyr0r]r^r_r`rarMrrerrrrrs
c@s�eZdZedfdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
edd��Zedd��Zed'dd��Zed)dd��Zed d!��Zejr�ed"d#��Zed$d%��Zejr�d&d#�ZdS)*rNcCsZ|dkrtd��||_|dkr*tj�|_n||_t�|_d|_d|_d|_	d|_
d|_dS)NrzLimit cannot be <= 0F)�
ValueError�_limitrr+r7�	bytearray�_buffer�_eof�_waiter�
_exceptionrUr8)rr(r'rrrrXszStreamReader.__init__cCs�dg}|jr |jdt|j��|jr0|jd�|jtkrJ|jd|j�|jr`|jd|j�|jrv|jd|j�|jr�|jd|j�|j	r�|jd�d	d
j
|�S)Nrz%d bytes�eofzl=%dzw=%rze=%rzt=%rZpausedz<%s>rX)rjrYrrkrh�_DEFAULT_LIMITrlrmrUr8rZ)rr[rrrr\ks 


zStreamReader.__repr__cCs|jS)N)rm)rrrrrd}szStreamReader.exceptioncCs0||_|j}|dk	r,d|_|j�s,|j|�dS)N)rmrl�	cancelledrB)rrCr@rrrrB�szStreamReader.set_exceptioncCs*|j}|dk	r&d|_|j�s&|jd�dS)z1Wakeup read*() functions waiting for data or EOF.N)rlrpr?)rr@rrr�_wakeup_waiter�s
zStreamReader._wakeup_waitercCs
||_dS)N)rU)rr0rrrrL�szStreamReader.set_transportcCs*|jr&t|j�|jkr&d|_|jj�dS)NF)r8rrjrhrU�resume_reading)rrrr�_maybe_resume_transport�sz$StreamReader._maybe_resume_transportcCsd|_|j�dS)NT)rkrq)rrrrrP�szStreamReader.feed_eofcCs|jo|jS)z=Return True if the buffer is empty and 'feed_eof' was called.)rkrj)rrrr�at_eof�szStreamReader.at_eofcCsv|sdS|jj|�|j�|jdk	rr|jrrt|j�d|jkrry|jj�Wntk
rjd|_YnXd|_dS)NrT)	rj�extendrqrUr8rrhZ
pause_reading�NotImplementedError)rrRrrrrQ�s
zStreamReader.feed_dataccsV|jdk	rtd|��|jr,d|_|jj�|jj�|_z|jEdHWdd|_XdS)zpWait until feed_data() or feed_eof() is called.

        If stream was paused, automatically resume it.
        NzH%s() called while another coroutine is already waiting for incoming dataF)rl�RuntimeErrorr8rUrrr7rF)rZ	func_namerrr�_wait_for_data�s


zStreamReader._wait_for_dataccs�d}t|�}y|j|�EdH}Wn�tk
rB}z|jSd}~Xnftk
r�}zJ|jj||j�rv|jd|j|�=n
|jj�|j	�t
|jd��WYdd}~XnX|S)a�Read chunk of data from the stream until newline (b'
') is found.

        On success, return chunk that ends with newline. If only partial
        line can be read due to EOF, return incomplete line without
        terminating newline. When EOF was reached while no bytes read, empty
        bytes object is returned.

        If limit is reached, ValueError will be raised. In that case, if
        newline was found, complete line including newline will be removed
        from internal buffer. Else, internal buffer will be cleared. Limit is
        compared against part of the line without newline.

        If stream was paused, this function will automatically resume it if
        needed.
        �
Nr)r�	readuntilrrrrj�
startswithr$�clearrsrgr&)r�sep�seplen�line�errr�readline�s
 zStreamReader.readlineryccs�t|�}|dkrtd��|jdk	r(|j�d}x�t|j�}|||kr||jj||�}|dkr\P|d|}||jkr|td|��|jr�t|j�}|jj	�t
|d��|jd�EdHq.W||jkr�td|��|jd||�}|jd||�=|j�t|�S)	aVRead data from the stream until ``separator`` is found.

        On success, the data and separator will be removed from the
        internal buffer (consumed). Returned data will include the
        separator at the end.

        Configured stream limit is used to check result. Limit sets the
        maximal length of data that can be returned, not counting the
        separator.

        If an EOF occurs and the complete separator is still not found,
        an IncompleteReadError exception will be raised, and the internal
        buffer will be reset.  The IncompleteReadError.partial attribute
        may contain the separator partially.

        If the data cannot be read because of over limit, a
        LimitOverrunError exception  will be raised, and the data
        will be left in the internal buffer, so it can be read again.
        rz,Separator should be at least one-byte stringNrz2Separator is not found, and chunk exceed the limitrzz2Separator is found, but chunk is longer than limit���)
rrgrmrj�findrhrrk�bytesr|rrxrs)rZ	separatorr~�offsetZbuflenZisep�chunkrrrrz�s:






zStreamReader.readuntilrccs�|jdk	r|j�|dkrdS|dkrZg}x&|j|j�EdH}|sBP|j|�q*Wdj|�S|jrz|jrz|jd�EdHt|jd|��}|jd|�=|j	�|S)a�Read up to `n` bytes from the stream.

        If n is not provided, or set to -1, read until EOF and return all read
        bytes. If the EOF was received and the internal buffer is empty, return
        an empty bytes object.

        If n is zero, return empty bytes object immediately.

        If n is positive, this function try to read `n` bytes, and may return
        less or equal bytes than requested, but at least one byte. If EOF was
        received before any byte is read, this function returns empty byte
        object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        Nr��read)
rmr�rhrYrZrjrkrxr�rs)r�nZblocks�blockrRrrrr�Ps$

zStreamReader.readccs�|dkrtd��|jdk	r |j�|dkr,dSxFt|j�|krr|jr`t|j�}|jj�t||��|jd�EdHq.Wt|j�|kr�t|j�}|jj�nt|jd|��}|jd|�=|j	�|S)a�Read exactly `n` bytes.

        Raise an IncompleteReadError if EOF is reached before `n` bytes can be
        read. The IncompleteReadError.partial attribute of the exception will
        contain the partial read bytes.

        if n is zero, return empty bytes object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        rz*readexactly size can not be less than zeroNr��readexactly)
rgrmrrjrkr�r|rrxrs)rr�Z
incompleterRrrrr��s&




zStreamReader.readexactlycCs|S)Nr)rrrr�	__aiter__�szStreamReader.__aiter__ccs|j�EdH}|dkrt�|S)Nr�)r��StopAsyncIteration)r�valrrr�	__anext__�szStreamReader.__anext__cCs|S)Nr)rrrrr��s)ryr�)r�)rr r!rorr\rdrBrqrLrsrPrtrQrrxr�rzr�r�r
ZPY35r�r�ZPY352rrrrrVs,	 [2*i)NN)NN)N)N)r"�__all__Zsocket�hasattrru�rr
rrr�logrro�EOFErrorr�	Exceptionrrrr	r
ZProtocolr6rrrrrrr�<module>sB
"B3GPK[vԊ����&__pycache__/base_events.cpython-36.pycnu�[���3


 \��@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZdgZdZd
ZeeefZ e!e	d�Z"d)Z#dd�Z$dd�Z%dd�Z&dd�Z'dd�Z(dd�Z)de	j*ddd�dd�Z+e!e	d ��rRd!d"�Z,nd#d"�Z,d$d%�Z-Gd&d'�d'ej.�Z/Gd(d�dej0�Z1dS)*a�Base implementation of event loop.

The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.

Whenever a public API takes a callback, subsequent positional
arguments will be passed to the callback if/when it is called.  This
avoids the proliferation of trivial lambdas implementing closures.
Keyword arguments for the callback are not supported; this is a
conscious design decision, leaving the door open for keyword arguments
to modify the meaning of the API call itself.
�N�)�compat)�
coroutines)�events)�futures)�tasks)�	coroutine)�logger�
BaseEventLoop�dg�?�AF_INET6�icCs0|j}tt|dd�tj�r$t|j�St|�SdS)N�__self__)Z	_callback�
isinstance�getattrr�Task�reprr�str)�handle�cb�r�+/usr/lib64/python3.6/asyncio/base_events.py�_format_handle?s
rcCs(|tjkrdS|tjkrdSt|�SdS)Nz<pipe>z<stdout>)�
subprocess�PIPE�STDOUTr)�fdrrr�_format_pipeHs


rcCsLttd�std��n4y|jtjtjd�Wntk
rFtd��YnXdS)N�SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)�hasattr�socket�
ValueError�
setsockopt�
SOL_SOCKETr�OSError)�sockrrr�_set_reuseportQs

r&cCs&ttd�r|d@tjkS|tjkSdS)N�
SOCK_NONBLOCK�)rr �SOCK_STREAM)�	sock_typerrr�_is_stream_socket\s
r+cCs&ttd�r|d@tjkS|tjkSdS)Nr'r()rr �
SOCK_DGRAM)r*rrr�_is_dgram_sockeths
r-cCsvttd�sdS|dtjtjhks(|dkr,dSt|�r<tj}nt|�rLtj}ndS|dkr^d}nVt|t�rv|dkrvd}n>t|t�r�|dkr�d}n&yt	|�}Wnt
tfk
r�dSX|tjkr�tj
g}tr�|jtj�n|g}t|t�r�|jd�}d|k�rdSxp|D]h}yJtj||�t�r@|tjk�r@|||d||ddffS|||d||ffSWntk
�rjYnX�qWdS)N�	inet_ptonr��Zidna�%)rr �IPPROTO_TCPZIPPROTO_UDPr+r-r�bytesr�int�	TypeErrorr!�	AF_UNSPEC�AF_INET�	_HAS_IPv6�appendr�decoder.r$)�host�port�family�type�protoZafs�afrrr�_ipaddr_infopsL





rA)r=r>r?�flagsc
CsZ|dd�\}}t|||||�}|dk	r@|j�}	|	j|g�|	S|j||||||d�SdS)N�)r=r>r?rB)rA�
create_future�
set_result�getaddrinfo)
�addressr=r>r?rB�loopr;r<�info�futrrr�_ensure_resolved�srK�TCP_NODELAYcCs>|jtjtjhkr:t|j�r:|jtjkr:|jtjtj	d�dS)Nr)
r=r r7rr+r>r?r2r"rL)r%rrr�_set_nodelay�s
rMcCsdS)Nr)r%rrrrM�scCs.|j}t|t�r t|t�r dS|jj�dS)N)Z
_exceptionr�
BaseException�	Exception�_loop�stop)rJ�excrrr�_run_until_complete_cb�s

rSc@sHeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Ze	d
d��Z
dS)�ServercCs||_||_d|_g|_dS)Nr)rP�sockets�
_active_count�_waiters)�selfrHrUrrr�__init__�szServer.__init__cCsd|jj|jfS)Nz<%s sockets=%r>)�	__class__�__name__rU)rXrrr�__repr__�szServer.__repr__cCs |jdk	st�|jd7_dS)Nr)rU�AssertionErrorrV)rXrrr�_attach�szServer._attachcCs<|jdkst�|jd8_|jdkr8|jdkr8|j�dS)Nrr)rVr]rU�_wakeup)rXrrr�_detach�szServer._detachcCsH|j}|dkrdSd|_x|D]}|jj|�qW|jdkrD|j�dS)Nr)rUrPZ
_stop_servingrVr_)rXrUr%rrr�close�s

zServer.closecCs0|j}d|_x|D]}|j�s|j|�qWdS)N)rW�donerE)rX�waiters�waiterrrrr_�s

zServer._wakeupccs<|jdks|jdkrdS|jj�}|jj|�|EdHdS)N)rUrWrPrDr9)rXrdrrr�wait_closed�s

zServer.wait_closedN)r[�
__module__�__qualname__rYr\r^r`rar_rrerrrrrT�s
rTc
@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd�d
d
d�dd�Z	d�dd
d
d
d�dd�Z
d�dd�Zd�dd�Zd�dd�Z
ed�dd��Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zed'd(��Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zej�r�d3d4�Zd5d6�Zd7d8�Zd9d:�Z d;d<�Z!d=d>�Z"d?d@�Z#dAdB�Z$dCdD�Z%dEdF�Z&dGdH�Z'dIdJ�Z(dKdL�Z)dMdMdMdMdN�dOdP�Z*d�dQdR�Z+ed�d
dMdMdMd
d
d
dS�dTdU��Z,ed�dVdW��Z-ed�dMdMdMd
d
d
d
dX�dYdZ��Z.ed[d\��Z/ed�e0j1e0j2d
d]d
d
d
d^�d_d`��Z3ed
da�dbdc��Z4eddde��Z5edfdg��Z6dhdi�Z7ee8j9e8j9e8j9ddjdMdk�dldm��Z:ee8j9e8j9e8j9dddMdk�dndo��Z;dpdq�Z<drds�Z=dtdu�Z>dvdw�Z?dxdy�Z@dzd{�ZAd|d}�ZBd~d�ZCd�d��ZDd�d��ZEd�d��ZFd
S)�r
cCs�d|_d|_d|_tj�|_g|_d|_d|_d|_	t
jd�j|_
d|_|jtjjodttjjd���d|_d|_d|_d|_ttd�r�tj�|_nd|_d|_dS)NrF�	monotonicZPYTHONASYNCIODEBUGg�������?�get_asyncgen_hooks) �_timer_cancelled_count�_closed�	_stopping�collections�deque�_ready�
_scheduled�_default_executorZ
_internal_fds�
_thread_id�timeZget_clock_infoZ
resolution�_clock_resolution�_exception_handler�	set_debug�sysrB�ignore_environment�bool�os�environ�get�slow_callback_duration�_current_handle�
_task_factory�_coroutine_wrapper_setr�weakref�WeakSet�
_asyncgens�_asyncgens_shutdown_called)rXrrrrY�s(

zBaseEventLoop.__init__cCs d|jj|j�|j�|j�fS)Nz"<%s running=%s closed=%s debug=%s>)rZr[�
is_running�	is_closed�	get_debug)rXrrrr\ szBaseEventLoop.__repr__cCstj|d�S)z,Create a Future object attached to the loop.)rH)rZFuture)rXrrrrD%szBaseEventLoop.create_futurecCs@|j�|jdkr0tj||d�}|jr<|jd=n|j||�}|S)zDSchedule a coroutine object.

        Return a task object.
        N)rHr���)�
_check_closedrrr�_source_traceback)rX�coroZtaskrrr�create_task)s

zBaseEventLoop.create_taskcCs$|dk	rt|�rtd��||_dS)awSet a task factory that will be used by loop.create_task().

        If factory is None the default task factory will be set.

        If factory is a callable, it should have a signature matching
        '(loop, coro)', where 'loop' will be a reference to the active
        event loop, 'coro' will be a coroutine object.  The callable
        must return a Future.
        Nz'task factory must be a callable or None)�callabler5r)rX�factoryrrr�set_task_factory7s
zBaseEventLoop.set_task_factorycCs|jS)z<Return a task factory, or None if the default one is in use.)r)rXrrr�get_task_factoryEszBaseEventLoop.get_task_factoryN)�extra�servercCst�dS)zCreate socket transport.N)�NotImplementedError)rXr%�protocolrdr�r�rrr�_make_socket_transportIsz$BaseEventLoop._make_socket_transportF)�server_side�server_hostnamer�r�c	Cst�dS)zCreate SSL transport.N)r�)	rXZrawsockr��
sslcontextrdr�r�r�r�rrr�_make_ssl_transportNsz!BaseEventLoop._make_ssl_transportcCst�dS)zCreate datagram transport.N)r�)rXr%r�rGrdr�rrr�_make_datagram_transportTsz&BaseEventLoop._make_datagram_transportcCst�dS)zCreate read pipe transport.N)r�)rX�piper�rdr�rrr�_make_read_pipe_transportYsz'BaseEventLoop._make_read_pipe_transportcCst�dS)zCreate write pipe transport.N)r�)rXr�r�rdr�rrr�_make_write_pipe_transport^sz(BaseEventLoop._make_write_pipe_transportc	
Kst�dS)zCreate subprocess transport.N)r�)
rXr��args�shell�stdin�stdout�stderr�bufsizer��kwargsrrr�_make_subprocess_transportcsz(BaseEventLoop._make_subprocess_transportcCst�dS)z�Write a byte to self-pipe, to wake up the event loop.

        This may be called from a different thread.

        The subclass is responsible for implementing the self-pipe.
        N)r�)rXrrr�_write_to_selfjszBaseEventLoop._write_to_selfcCst�dS)zProcess selector events.N)r�)rX�
event_listrrr�_process_eventssszBaseEventLoop._process_eventscCs|jrtd��dS)NzEvent loop is closed)rk�RuntimeError)rXrrrr�wszBaseEventLoop._check_closedcCs*|jj|�|j�s&|j|j|j��dS)N)r��discardr��call_soon_threadsafer��aclose)rX�agenrrr�_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)r��warnings�warn�format�ResourceWarningr��add)rXr�rrr�_asyncgen_firstiter_hook�s
z&BaseEventLoop._asyncgen_firstiter_hookccs�d|_|jdkst|j�r dSt|j�}|jj�tjdd�|D�d|d��}|EdH}x8t||�D]*\}}t|t	�rf|j
dj|�||d��qfWdS)z,Shutdown all active asynchronous generators.TNcSsg|]}|j��qSr)r�)�.0Zagrrr�
<listcomp>�sz4BaseEventLoop.shutdown_asyncgens.<locals>.<listcomp>)Zreturn_exceptionsrHz?an error occurred during closing of asynchronous generator {!r})�message�	exceptionZasyncgen)r�r��len�list�clearr�gather�ziprrO�call_exception_handlerr�)rXZ
closing_agensZ
shutdown_coroZresults�resultr�rrr�shutdown_asyncgens�s"




z BaseEventLoop.shutdown_asyncgenscCs�|j�|j�rtd��tj�dk	r,td��|j|j�tj�|_	|j
dk	rftj�}tj
|j|jd�z$tj|�x|j�|jrtPqtWWdd|_d|_	tjd�|jd�|j
dk	r�tj
|�XdS)zRun until stop() is called.z"This event loop is already runningNz7Cannot run the event loop while another loop is running)�	firstiter�	finalizerF)r�r�r�rZ_get_running_loop�_set_coroutine_wrapper�_debug�	threading�	get_identrrr�rwri�set_asyncgen_hooksr�r�Z_set_running_loop�	_run_oncerl)rXZold_agen_hooksrrr�run_forever�s0







zBaseEventLoop.run_forevercCs�|j�tj|�}tj||d�}|r,d|_|jt�z>y|j�Wn,|rj|j	�rj|j
�rj|j��YnXWd|jt�X|j	�s�t
d��|j�S)a\Run until the Future is done.

        If the argument is a coroutine, it is wrapped in a Task.

        WARNING: It would be disastrous to call run_until_complete()
        with the same coroutine twice -- it would wrap it in two
        different Tasks and that can't be good.

        Return the Future's result, or raise its exception.
        )rHFNz+Event loop stopped before Future completed.)r�rZisfuturerZ
ensure_futureZ_log_destroy_pendingZadd_done_callbackrSr�rbZ	cancelledr�Zremove_done_callbackr�r�)rXZfutureZnew_taskrrr�run_until_complete�s 
z BaseEventLoop.run_until_completecCs
d|_dS)z�Stop running the event loop.

        Every callback already scheduled will still run.  This simply informs
        run_forever to stop looping after a complete iteration.
        TN)rl)rXrrrrQ�szBaseEventLoop.stopcCsj|j�rtd��|jrdS|jr,tjd|�d|_|jj�|jj�|j	}|dk	rfd|_	|j
dd�dS)z�Close the event loop.

        This clears the queues and shuts down the executor,
        but does not wait for the executor to finish.

        The event loop must not be running.
        z!Cannot close a running event loopNzClose %rTF)�wait)r�r�rkr�r	�debugror�rprqZshutdown)rX�executorrrrra�s

zBaseEventLoop.closecCs|jS)z*Returns True if the event loop was closed.)rk)rXrrrr�szBaseEventLoop.is_closedcCs0|j�s,tjd|t|d�|j�s,|j�dS)Nzunclosed event loop %r)r�)r�r�r�r�r�ra)rXrrr�__del__s
zBaseEventLoop.__del__cCs
|jdk	S)z*Returns True if the event loop is running.N)rr)rXrrrr�szBaseEventLoop.is_runningcCstj�S)z�Return the time according to the event loop's clock.

        This is a float expressed in seconds since an epoch, but the
        epoch, precision, accuracy and drift are unspecified and may
        differ per event loop.
        )rsrh)rXrrrrsszBaseEventLoop.timecGs,|j|j�||f|��}|jr(|jd=|S)a8Arrange for a callback to be called at a given time.

        Return a Handle: an opaque object with a cancel() method that
        can be used to cancel the call.

        The delay can be an int or float, expressed in seconds.  It is
        always relative to the current time.

        Each callback will be called exactly once.  If two callbacks
        are scheduled for exactly the same time, it undefined which
        will be called first.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        rr�)�call_atrsr�)rXZdelay�callbackr��timerrrr�
call_later szBaseEventLoop.call_latercGsX|j�|jr"|j�|j|d�tj||||�}|jr@|jd=tj|j	|�d|_	|S)z|Like call_later(), but uses an absolute time.

        Absolute time corresponds to the event loop's time() method.
        r�rTr�)
r�r��
_check_thread�_check_callbackr�TimerHandler��heapq�heappushrp)rX�whenr�r�r�rrrr�5szBaseEventLoop.call_atcGs@|j�|jr"|j�|j|d�|j||�}|jr<|jd=|S)aTArrange for a callback to be called as soon as possible.

        This operates as a FIFO queue: callbacks are called in the
        order in which they are registered.  Each callback will be
        called exactly once.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        �	call_soonrr�)r�r�r�r��
_call_soonr�)rXr�r�rrrrr�Es
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})rZiscoroutineZiscoroutinefunctionr5r�r�)rXr��methodrrrr�Xs

zBaseEventLoop._check_callbackcCs,tj|||�}|jr|jd=|jj|�|S)Nrr�)r�Handler�ror9)rXr�r�rrrrr�cs
zBaseEventLoop._call_sooncCs,|jdkrdStj�}||jkr(td��dS)aoCheck that the current thread is the thread running the event loop.

        Non-thread-safe methods of this class make this assumption and will
        likely behave incorrectly when the assumption is violated.

        Should only be called when (self._debug == True).  The caller is
        responsible for checking this condition for performance reasons.
        NzMNon-thread-safe operation invoked on an event loop other than the current one)rrr�r�r�)rXZ	thread_idrrrr�js	

zBaseEventLoop._check_threadcGs@|j�|jr|j|d�|j||�}|jr4|jd=|j�|S)z"Like call_soon(), but thread-safe.r�rr�)r�r�r�r�r�r�)rXr�r�rrrrr�{sz"BaseEventLoop.call_soon_threadsafecGsZ|j�|jr|j|d�|dkr@|j}|dkr@tjj�}||_tj|j|f|��|d�S)N�run_in_executor)rH)	r�r�r�rq�
concurrentrZThreadPoolExecutorZwrap_futureZsubmit)rXr��funcr�rrrr��s
zBaseEventLoop.run_in_executorcCs
||_dS)N)rq)rXr�rrr�set_default_executor�sz"BaseEventLoop.set_default_executorcCs�d||fg}|r |jd|�|r2|jd|�|rD|jd|�|rV|jd|�dj|�}tjd|�|j�}tj||||||�}	|j�|}
d||
d	|	f}|
|jkr�tj|�n
tj|�|	S)
Nz%s:%rz	family=%rztype=%rzproto=%rzflags=%rz, zGet address info %sz(Getting address info %s took %.3f ms: %rg@�@)	r9�joinr	r�rsr rFr}rI)rXr;r<r=r>r?rB�msg�t0Zaddrinfo�dtrrr�_getaddrinfo_debug�s(


z BaseEventLoop._getaddrinfo_debugr)r=r>r?rBc	Cs>|jr |jd|j||||||�S|jdtj||||||�SdS)N)r�r�r�r rF)rXr;r<r=r>r?rBrrrrF�s


zBaseEventLoop.getaddrinfocCs|jdtj||�S)N)r�r �getnameinfo)rXZsockaddrrBrrrr��szBaseEventLoop.getnameinfo)�sslr=r?rBr%�
local_addrr�c#s|
dk	r|rtd��|
dkr2|r2|s.td��|}
|dk	sD|dk	�r�|dk	rTtd��t||f|tj|||d�}|g}|	dk	r�t|	|tj|||d�}
|j|
�nd}
tj||d�EdH|j�}|s�td��|
dk	r�|
j�}|s�td��g}�x�|D�]B\}}}}}y�tj|||d�}|j	d	�|
dk	�r�x�|D]j\}}}}}y|j
|�PWnHtk
�r�}z*t|jd
j||j
j���}|j|�WYdd}~XnX�q.W|j�d}w�|j�r�tjd||�|j||�EdHWn^tk
�r}z"|dk	�r�|j�|j|�WYdd}~Xq�|dk	�r,|j��Yq�XPq�Wt|�dk�rR|d
�nJt|d
��t�fdd�|D���r~|d
�tdjdjdd�|D�����n,|dk�r�td��t|j��s�tdj|���|j||||
�EdH\}}|j�r
|jd�}tjd|||||�||fS)a�Connect to a TCP server.

        Create a streaming transport connection to a given Internet host and
        port: socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_STREAM. protocol_factory must be
        a callable returning a protocol instance.

        This method is a coroutine which will try to establish the connection
        in the background.  When successful, the coroutine returns a
        (transport, protocol) pair.
        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)r�rR)�modelrr�	<genexpr>sz2BaseEventLoop.create_connection.<locals>.<genexpr>zMultiple exceptions: {}z, css|]}t|�VqdS)N)r)r�rRrrrr�#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)r9rr�r�r$�setblocking�bind�errnor��strerror�lowerrar�r	r��sock_connectr�r�allr�r+r>�_create_connection_transport�get_extra_info)rX�protocol_factoryr;r<r�r=r?rBr%r�r��f1�fs�f2�infosZladdr_infos�
exceptionsr>ZcnamerG�_ZladdrrR�	transportr�r)r�r�create_connection�s�





"




zBaseEventLoop.create_connectionc
	cs�|jd�|�}|j�}|rFt|t�r*dn|}|j||||||d�}	n|j|||�}	y|EdHWn|	j��YnX|	|fS)NF)r�r�)r�rDrryr�r�ra)
rXr%r�r�r�r�r�rdr�r�rrrr�=s
z*BaseEventLoop._create_connection_transport)r=r?rB�
reuse_address�
reuse_port�allow_broadcastr%c#sZ|
dk	r�t|
j�s tdj|
����s@�s@|s@|s@|s@|s@|s@|	r~t��||||||	d�}djdd�|j�D��}tdj|���|
jd�d}
�nL�p��s�|d	kr�td
��||fdff}n�tj	�}x�d	�fd�ffD]�\}}|dk	r�t
|t��r�t|�dk�st
d
��t||tj|||d�EdH}|�s.td��xB|D]:\}}}}}||f}||k�r`ddg||<||||<�q4Wq�W��fdd�|j�D�}|�s�td��g}|dk�r�tjdk�o�tjdk}�x|D�]\\}}\}}d}
d}
y�tj|tj|d�}
|�r|
jtjtjd�|�rt|
�|	�r4|
jtjtjd�|
jd���rN|
j|���rj|j|
|�EdH|}
Wn^tk
�r�}z"|
dk	�r�|
j�|j|�WYdd}~Xn"|
dk	�r�|
j��YnXP�q�W|d	�|�}|j�}|j |
||
|�}|j!�r,��rt"j#d��||�nt"j$d�||�y|EdHWn|j��YnX||fS)zCreate datagram connection.Nz#A UDP Socket was expected, got {!r})r��remote_addrr=r?rBr�r�rz, css"|]\}}|rdj||�VqdS)z{}={}N)r�)r��k�vrrrr�isz9BaseEventLoop.create_datagram_endpoint.<locals>.<genexpr>zNsocket modifier keyword arguments can not be used when sock is specified. ({})Frzunexpected address familyrrCz2-tuple is expected)r=r>r?rBrHz!getaddrinfo() returned empty listcs8g|]0\}}�r|ddkp*�o*|ddks||f�qS)rNrr)r��keyZ	addr_pair)r�rrrr��sz:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address information�posix�cygwin)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!r��dictr��itemsr�rm�OrderedDictr�tupler�r]rKr r,r$rz�namerw�platformr"r#�SO_REUSEADDRr&ZSO_BROADCASTr�r�rar9rDr�r�r	rIr�)rXr�r�rr=r?rBr�r�rr%ZoptsZproblemsZr_addrZaddr_pairs_infoZ
addr_infos�idxZaddrr�Zfamr�ZprorGrr�Z
local_addressZremote_addressrRr�rdr�r)r�rr�create_datagram_endpointUs�








z&BaseEventLoop.create_datagram_endpointccs4t||f|tj||d�EdH}|s0tdj|���|S)N)r=r>rBrHz%getaddrinfo({!r}) returned empty list)rKr r)r$r�)rXr;r<r=rBr�rrr�_create_server_getaddrinfo�s
z(BaseEventLoop._create_server_getaddrinfor)r=rBr%�backlogr�r�r�c #s�t|t�rtd��|dk	s$�dk	�r|dk	r4td��|	dkrPtjdkoNtjdk}	g}|dkrddg}n$t|t�s|t|t	j
�r�|g}n|}����fdd�|D�}
tj|
d	�i�EdH}t
tjj|��}d
}�z �x|D�]
}|\}}}}}ytj|||�}Wn6tjk
�r2�j�r,tjd|||dd
�w�YnX|j|�|	�rV|jtjtjd�|
�rdt|�t�r�|tjk�r�ttd��r�|jtjtjd�y|j |�Wq�t!k
�r�}z t!|j"d||j#j$�f��WYdd}~Xq�Xq�Wd}Wd|�sx|D]}|j%��q�WXn2|dk�r"td��t&|j'��s<tdj(|���|g}t)�|�}x4|D],}|j*|�|j+d
��j,|||||��qRW�j�r�tj-d|�|S)a1Create a TCP server.

        The host parameter can be a string, in that case the TCP server is bound
        to host and port.

        The host parameter can also be a sequence of strings and in that case
        the TCP server is bound to all hosts of the sequence. If a host
        appears multiple times (possibly indirectly e.g. when hostnames
        resolve to the same IP address), the server is only bound once to that
        host.

        Return a Server object which can be used to stop the service.

        This method is a coroutine.
        z*ssl argument must be an SSLContext or NoneNz8host/port and sock can not be specified at the same timerrr0csg|]}�j|���d��qS))r=rB)r)r�r;)r=rBr<rXrrr�sz/BaseEventLoop.create_server.<locals>.<listcomp>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).rryr5r!rzrrwrrrm�Iterablerr��set�	itertools�chain�
from_iterabler �errorr�r	�warningr9r"r#r
r&r8rrrZIPV6_V6ONLYr�r$r�r�r�rar+r>r�rTZlistenr�Z_start_servingrI)rXr�r;r<r=rBr%rr�r�r�rUZhostsr�r�Z	completed�resr@Zsocktyper?Z	canonnameZsa�errr�r)r=rBr<rXr�
create_server�s�


(





zBaseEventLoop.create_server)r�ccs^t|j�stdj|���|j|||ddd�EdH\}}|jrV|jd�}tjd|||�||fS)aHandle an accepted connection.

        This is used by servers that accept connections outside of
        asyncio but that use asyncio to handle connections.

        This method is a coroutine.  When completed, the coroutine
        returns a (transport, protocol) pair.
        z&A Stream Socket was expected, got {!r}r0T)r�Nr z%r handled: (%r, %r))	r+r>r!r�r�r�r�r	r�)rXr�r%r�r�r�rrr�connect_accepted_socketAs


z%BaseEventLoop.connect_accepted_socketccsd|�}|j�}|j|||�}y|EdHWn|j��YnX|jr\tjd|j�||�||fS)Nz Read pipe %r connected: (%r, %r))rDr�rar�r	r��fileno)rXr�r�r�rdr�rrr�connect_read_pipeXszBaseEventLoop.connect_read_pipeccsd|�}|j�}|j|||�}y|EdHWn|j��YnX|jr\tjd|j�||�||fS)Nz!Write pipe %r connected: (%r, %r))rDr�rar�r	r�r)rXr�r�r�rdr�rrr�connect_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	r�r�)rXr�r�r�r�rIrrr�_log_subprocesszszBaseEventLoop._log_subprocessT)r�r�r��universal_newlinesr�r�c
ks�t|ttf�std��|r"td��|s.td��|dkr>td��|�}
d}|jrfd|}|j||||�|j|
|d||||f|	�EdH}|jr�|dk	r�tjd||�||
fS)	Nzcmd must be a stringz universal_newlines must be Falsezshell must be Truerzbufsize must be 0zrun shell command %rTz%s: %r)	rr3rr!r�r#r�r	rI)
rXr��cmdr�r�r�r$r�r�r�r��	debug_logr�rrr�subprocess_shell�s$zBaseEventLoop.subprocess_shellcos�|rtd��|rtd��|dkr(td��|f|	}x,|D]$}t|ttf�s8tdt|�j��q8W|�}
d}|jr�d|}|j||||�|j	|
|d||||f|
�EdH}|jr�|dk	r�t
jd||�||
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[r�r#r�r	rI)rXr�Zprogramr�r�r�r$r�r�r�r�Z
popen_args�argr�r&r�rrr�subprocess_exec�s,

zBaseEventLoop.subprocess_execcCs|jS)zKReturn an exception handler, or None if the default one is in use.
        )ru)rXrrr�get_exception_handler�sz#BaseEventLoop.get_exception_handlercCs*|dk	r t|�r tdj|���||_dS)a�Set handler as the new event loop exception handler.

        If handler is None, the default exception handler will
        be set.

        If handler is a callable object, it should have a
        signature matching '(loop, context)', where 'loop'
        will be a reference to the active event loop, 'context'
        will be a dict object (see `call_exception_handler()`
        documentation for details about context).
        Nz/A callable object or None is expected, got {!r})r�r5r�ru)rXZhandlerrrr�set_exception_handler�sz#BaseEventLoop.set_exception_handlerc	Cs|jd�}|sd}|jd�}|dk	r6t|�||jf}nd}d|kr`|jdk	r`|jjr`|jj|d<|g}x�t|�D]�}|dkr~qp||}|dkr�djtj|��}d	}||j	�7}n2|dkr�djtj|��}d
}||j	�7}nt
|�}|jdj||��qpWt
jdj|�|d
�dS)aEDefault exception handler.

        This is called when an exception occurs and no exception
        handler is set, and can be called by a custom exception
        handler that wants to defer to the default behavior.

        This default handler logs the error message and other
        context-dependent information.  In debug mode, a truncated
        stack trace is also appended showing where the given object
        (e.g. a handle or future or task) was created, if any.

        The context parameter has the same meaning as in
        `call_exception_handler()`.
        r�z!Unhandled exception in event loopr�NFZsource_tracebackZhandle_tracebackr0z+Object created at (most recent call last):
z+Handle created at (most recent call last):
z{}: {}�
)r>r�r�)r|r>�
__traceback__r~r��sortedr��	traceback�format_list�rstriprr9r�r	r)	rX�contextr�r�rZ	log_linesr�value�tbrrr�default_exception_handler�s6


z'BaseEventLoop.default_exception_handlercCs�|jdkr>y|j|�Wq�tk
r:tjddd�Yq�Xnny|j||�Wn\tk
r�}z@y|jd||d��Wn"tk
r�tjddd�YnXWYdd}~XnXdS)aCall the current event loop's exception handler.

        The context argument is a dict containing the following keys:

        - 'message': Error message;
        - 'exception' (optional): Exception object;
        - 'future' (optional): Future instance;
        - 'handle' (optional): Handle instance;
        - 'protocol' (optional): Protocol instance;
        - 'transport' (optional): Transport instance;
        - 'socket' (optional): Socket instance;
        - 'asyncgen' (optional): Asynchronous generator that caused
                                 the exception.

        New keys maybe introduced in the future.

        Note: do not overload this method in an event loop subclass.
        For custom exception handling, use the
        `set_exception_handler()` method.
        Nz&Exception in default exception handlerT)rz$Unhandled error in exception handler)r�r�r2zeException in default exception handler while handling an unexpected error in custom exception handler)rur5rOr	r)rXr2rRrrrr�s"
z$BaseEventLoop.call_exception_handlercCs@t|tj�std��|jrdSt|tj�s0t�|jj|�dS)z3Add a Handle to _scheduled (TimerHandle) or _ready.zA Handle is required hereN)rrr�r]�
_cancelledr�ror9)rXrrrr�
_add_callback9s
zBaseEventLoop._add_callbackcCs|j|�|j�dS)z6Like _add_callback() but called from a signal handler.N)r7r�)rXrrrr�_add_callback_signalsafeAs
z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)z3Notification that a TimerHandle has been cancelled.rN)rprj)rXrrrr�_timer_handle_cancelledFsz%BaseEventLoop._timer_handle_cancelledcCs�t|j�}|tkrd|j|tkrdg}x&|jD]}|jr>d|_q,|j|�q,Wtj|�||_d|_n8x6|jr�|jdjr�|jd8_tj	|j�}d|_qfWd}|j
s�|jr�d}n*|jr�|jdj}t
td||j��t�}|jo�|dk�r�|j�}|jj|�}|j�|}|dk�rtj}	ntj}	t|�}
|dk�rLtj|	d|d|
�nD|
�rntj|	d|d|d|
�n"|dk�r�tj|	d	|d|d�n|jj|�}|j|�|j�|j}xD|j�r�|jd}|j|k�r�Ptj	|j�}d|_|j
j|��q�Wt|j
�}x�t|�D]|}
|j
j�}|j�r*�q|j�r�zD||_|j�}|j�|j�|}||jk�rttj d
t!|�|�Wdd|_Xn|j��qWd}dS)z�Run one full iteration of the event loop.

        This calls all currently ready callbacks, polls for I/O,
        schedules the resulting callbacks, and finally schedules
        'call_later' callbacks.
        FrrNg�?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)"r�rp�_MIN_SCHEDULED_TIMER_HANDLESrj�%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr6r9r��heapify�heappoprorlZ_when�min�maxrs�MAXIMUM_SELECT_TIMEOUTr�Z	_selectorZselect�logging�INFO�DEBUGr	�logr�rt�range�popleftr~Z_runr}rr)rXZsched_countZ
new_scheduledrZtimeoutr�r�r�r��levelZneventZend_timeZntodo�irrrr�Ks�











zBaseEventLoop._run_oncecCs�ytj}tj}Wntk
r$dSXt|�}|j|kr<dStj}|�}|rz|d|fkrjtj	d|t
�q�||�d|_n,|d|fkr�tj	d|t
�n|d�d|_dS)Nz[loop.set_debug(True): cannot set debug coroutine wrapper; another wrapper is already set %rTzWloop.set_debug(False): cannot unset debug coroutine wrapper; another wrapper was set %rF)rw�set_coroutine_wrapper�get_coroutine_wrapper�AttributeErrorryr�rZ
debug_wrapperr�r��RuntimeWarning)rX�enabledZset_wrapperZget_wrapper�wrapperZcurrent_wrapperrrrr��s.

z$BaseEventLoop._set_coroutine_wrappercCs|jS)N)r�)rXrrrr��szBaseEventLoop.get_debugcCs||_|j�r|j|�dS)N)r�r�r�)rXrMrrrrv�szBaseEventLoop.set_debug)N)N)NNN)NN)NN)N)r)NN)F)NN)NN)Gr[rfrgrYr\rDr�r�r�r�r�r�r�r�rr�r�r�r�r�r�r�r�r�rQrar�rZPY34r�r�rsr�r�r�r�r�r�r�r�r�r�rFr�r�r�rrr r6Z
AI_PASSIVErrr r!r#rrr'r)r*r+r5r�r7r8r9r�r�r�rvrrrrr
�s�!


		%	

u	`
12c!i�Q)2�__doc__rmZconcurrent.futuresr�r��inspectrrArzr rr�rsr/rwr�r�r0rrrrrrrDr	�__all__r:r;�BrokenPipeError�ConnectionResetError�ConnectionAbortedErrorZ_FATAL_ERROR_IGNORErr8r@rrr&r+r-rAr)rKrMrSZAbstractServerrTZAbstractEventLoopr
rrrr�<module>sV
		;


/PK[�����$__pycache__/log.cpython-36.opt-1.pycnu�[���3


 \|�@sdZddlZeje�ZdS)zLogging configuration.�N)�__doc__ZloggingZ	getLogger�__package__Zlogger�rr�#/usr/lib64/python3.6/asyncio/log.py�<module>sPK[K�[[*__pycache__/protocols.cpython-36.opt-1.pycnu�[���3


 \��@sRdZddddgZGdd�d�ZGdd�de�ZGdd�de�ZGdd�de�Zd	S)
zAbstract Protocol class.�BaseProtocol�Protocol�DatagramProtocol�SubprocessProtocolc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)raCommon base class for protocol interfaces.

    Usually user implements protocols that derived from BaseProtocol
    like Protocol or ProcessProtocol.

    The only case when BaseProtocol should be implemented directly is
    write-only transport like write pipe
    cCsdS)z�Called when a connection is made.

        The argument is the transport representing the pipe connection.
        To receive data, wait for data_received() calls.
        When the connection is closed, connection_lost() is called.
        N�)�selfZ	transportrr�)/usr/lib64/python3.6/asyncio/protocols.py�connection_madeszBaseProtocol.connection_madecCsdS)z�Called when the connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        Nr)r�excrrr�connection_lostszBaseProtocol.connection_lostcCsdS)aCalled when the transport's buffer goes over the high-water mark.

        Pause and resume calls are paired -- pause_writing() is called
        once when the buffer goes strictly over the high-water mark
        (even if subsequent writes increases the buffer size even
        more), and eventually resume_writing() is called once when the
        buffer size reaches the low-water mark.

        Note that if the buffer size equals the high-water mark,
        pause_writing() is not called -- it must go strictly over.
        Conversely, resume_writing() is called when the buffer size is
        equal or lower than the low-water mark.  These end conditions
        are important to ensure that things go as expected when either
        mark is zero.

        NOTE: This is the only Protocol callback that is not called
        through EventLoop.call_soon() -- if it were, it would have no
        effect when it's most needed (when the app keeps writing
        without yielding until pause_writing() is called).
        Nr)rrrr�
pause_writing!szBaseProtocol.pause_writingcCsdS)zvCalled when the transport's buffer drains below the low-water mark.

        See pause_writing() for details.
        Nr)rrrr�resume_writing7szBaseProtocol.resume_writingN)�__name__�
__module__�__qualname__�__doc__rr
rrrrrrrs
c@s eZdZdZdd�Zdd�ZdS)ranInterface for stream protocol.

    The user should implement this interface.  They can inherit from
    this class but don't need to.  The implementations here do
    nothing (they don't raise exceptions).

    When the user wants to requests a transport, they pass a protocol
    factory to a utility function (e.g., EventLoop.create_connection()).

    When the connection is made successfully, connection_made() is
    called with a suitable transport object.  Then data_received()
    will be called 0 or more times with data (bytes) received from the
    transport; finally, connection_lost() will be called exactly once
    with either an exception object or None as an argument.

    State machine of calls:

      start -> CM [-> DR*] [-> ER?] -> CL -> end

    * CM: connection_made()
    * DR: data_received()
    * ER: eof_received()
    * CL: connection_lost()
    cCsdS)zTCalled when some data is received.

        The argument is a bytes object.
        Nr)r�datarrr�
data_receivedXszProtocol.data_receivedcCsdS)z�Called when the other end calls write_eof() or equivalent.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        Nr)rrrr�eof_received^szProtocol.eof_receivedN)r
rrrrrrrrrr>sc@s eZdZdZdd�Zdd�ZdS)rz Interface for datagram protocol.cCsdS)z&Called when some datagram is received.Nr)rrZaddrrrr�datagram_receivedjsz"DatagramProtocol.datagram_receivedcCsdS)z~Called when a send or receive operation raises an OSError.

        (Other than BlockingIOError or InterruptedError.)
        Nr)rr	rrr�error_receivedmszDatagramProtocol.error_receivedN)r
rrrrrrrrrrgsc@s(eZdZdZdd�Zdd�Zdd�ZdS)	rz,Interface for protocol for subprocess calls.cCsdS)z�Called when the subprocess writes data into stdout/stderr pipe.

        fd is int file descriptor.
        data is bytes object.
        Nr)r�fdrrrr�pipe_data_receivedwsz%SubprocessProtocol.pipe_data_receivedcCsdS)z�Called when a file descriptor associated with the child process is
        closed.

        fd is the int file descriptor that was closed.
        Nr)rrr	rrr�pipe_connection_lost~sz'SubprocessProtocol.pipe_connection_lostcCsdS)z"Called when subprocess has exited.Nr)rrrr�process_exited�sz!SubprocessProtocol.process_exitedN)r
rrrrrrrrrrrtsN)r�__all__rrrrrrrr�<module>s7)
PK["4���'__pycache__/queues.cpython-36.opt-2.pycnu�[���3


 \�@s�dddddgZddlZddlZddlmZdd	lmZdd
lmZddlmZGdd�de	�Z
Gd
d�de	�ZGdd�d�ZGdd�de�Z
Gdd�de�Zejs�eZejd�dS)�Queue�
PriorityQueue�	LifoQueue�	QueueFull�
QueueEmpty�N�)�compat)�events)�locks)�	coroutinec@seZdZdS)rN)�__name__�
__module__�__qualname__�rr�&/usr/lib64/python3.6/asyncio/queues.pyrsc@seZdZdS)rN)rr
rrrrrrsc@s�eZdZd(dd�dd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Zdd�Z	dd�Z
dd�Zedd��Z
dd�Zdd�Zedd��Zdd�Zed d!��Zd"d#�Zd$d%�Zed&d'��ZdS))rrN)�loopcCsb|dkrtj�|_n||_||_tj�|_tj�|_d|_t	j
|jd�|_|jj�|j
|�dS)Nr)r)r	Zget_event_loop�_loop�_maxsize�collections�deque�_getters�_putters�_unfinished_tasksr
ZEvent�	_finished�set�_init)�self�maxsizerrrr�__init__(s


zQueue.__init__cCstj�|_dS)N)rr�_queue)rrrrrr:szQueue._initcCs
|jj�S)N)r�popleft)rrrr�_get=sz
Queue._getcCs|jj|�dS)N)r�append)r�itemrrr�_put@sz
Queue._putcCs*x$|r$|j�}|j�s|jd�PqWdS)N)r �doneZ
set_result)r�waitersZwaiterrrr�_wakeup_nextEs

zQueue._wakeup_nextcCsdjt|�jt|�|j��S)Nz<{} at {:#x} {}>)�format�typer�id�_format)rrrr�__repr__MszQueue.__repr__cCsdjt|�j|j��S)Nz<{} {}>)r(r)rr+)rrrr�__str__Qsz
Queue.__str__cCszdj|j�}t|dd�r,|djt|j��7}|jrF|djt|j��7}|jr`|djt|j��7}|jrv|dj|j�7}|S)Nzmaxsize={!r}rz _queue={!r}z
 _getters[{}]z
 _putters[{}]z	 tasks={})	r(r�getattr�listrr�lenrr)r�resultrrrr+Tsz
Queue._formatcCs
t|j�S)N)r0r)rrrr�qsize`szQueue.qsizecCs|jS)N)r)rrrrrdsz
Queue.maxsizecCs|jS)N)r)rrrr�emptyiszQueue.emptycCs |jdkrdS|j�|jkSdS)NrF)rr2)rrrr�fullms
z
Queue.fullc	cstxh|j�rh|jj�}|jj|�y|EdHWq|j�|j�r^|j�r^|j|j��YqXqW|j|�S)N)	r4r�
create_futurerr"�cancel�	cancelledr'�
put_nowait)rr#Zputterrrr�putxs	

z	Queue.putcCs>|j�rt�|j|�|jd7_|jj�|j|j�dS)Nr)r4rr$rr�clearr'r)rr#rrrr8�s

zQueue.put_nowaitccs�x�|j�r�|jj�}|jj|�y|EdHWq|j�y|jj|�Wntk
rbYnX|j�r�|j�r�|j	|j��YqXqW|j
�S)N)r3rr5rr"r6�remove�
ValueErrorr7r'�
get_nowait)r�getterrrr�get�s

z	Queue.getcCs$|j�rt�|j�}|j|j�|S)N)r3rr!r'r)rr#rrrr=�s
zQueue.get_nowaitcCs8|jdkrtd��|jd8_|jdkr4|jj�dS)Nrz!task_done() called too many timesr)rr<rr)rrrr�	task_done�s


zQueue.task_doneccs|jdkr|jj�EdHdS)Nr)rr�wait)rrrr�join�s	
z
Queue.join)r)rr
rrrr!r$r'r,r-r+r2�propertyrr3r4rr9r8r?r=r@rBrrrrrs$c@s0eZdZdd�Zejfdd�Zejfdd�ZdS)rcCs
g|_dS)N)r)rrrrrr�szPriorityQueue._initcCs||j|�dS)N)r)rr#�heappushrrrr$�szPriorityQueue._putcCs
||j�S)N)r)r�heappoprrrr!�szPriorityQueue._getN)	rr
rr�heapqrDr$rEr!rrrrr�sc@s$eZdZdd�Zdd�Zdd�ZdS)rcCs
g|_dS)N)r)rrrrrr�szLifoQueue._initcCs|jj|�dS)N)rr")rr#rrrr$�szLifoQueue._putcCs
|jj�S)N)r�pop)rrrrr!�szLifoQueue._getN)rr
rrr$r!rrrrr�s�
JoinableQueue)�__all__rrF�rr	r
Z
coroutinesr�	ExceptionrrrrrZPY35rHr"rrrr�<module>sH
PK[��yOyO#__pycache__/sslproto.cpython-36.pycnu�[���3


 \�e�
@s�ddlZddlZyddlZWnek
r4dZYnXddlmZddlmZddlmZddlmZddl	m
Z
dd	�Zd
d�ZdZ
d
ZdZdZGdd�de�ZGdd�dejej�ZGdd�dej�ZdS)�N�)�base_events)�compat)�	protocols)�
transports)�loggercCsj|rtd��ttd�r*tj�}|sfd|_n<tjtj�}|jtjO_|jtj	O_|j
�tj|_|S)Nz(Server side SSL needs a valid SSLContext�create_default_contextF)
�
ValueError�hasattr�sslr�check_hostnameZ
SSLContextZPROTOCOL_SSLv23ZoptionsZOP_NO_SSLv2ZOP_NO_SSLv3Zset_default_verify_pathsZ
CERT_REQUIRED�verify_mode)�server_side�server_hostname�
sslcontext�r�(/usr/lib64/python3.6/asyncio/sslproto.py�_create_transport_contexts
rcCs
ttd�S)N�	MemoryBIO)r
rrrrr�_is_sslproto_available%srZ	UNWRAPPEDZDO_HANDSHAKEZWRAPPEDZSHUTDOWNc@s~eZdZdZdZddd�Zedd��Zed	d
��Zedd��Z	ed
d��Z
ddd�Zddd�Zdd�Z
ddd�Zd dd�ZdS)!�_SSLPipeaAn SSL "Pipe".

    An SSL pipe allows you to communicate with an SSL/TLS protocol instance
    through memory buffers. It can be used to implement a security layer for an
    existing connection where you don't have access to the connection's file
    descriptor, or for some reason you don't want to use it.

    An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
    data is passed through untransformed. In wrapped mode, application level
    data is encrypted to SSL record level data and vice versa. The SSL record
    level is the lowest level in the SSL protocol suite and is what travels
    as-is over the wire.

    An SslPipe initially is in "unwrapped" mode. To start SSL, call
    do_handshake(). To shutdown SSL again, call unwrap().
    �iNcCsH||_||_||_t|_tj�|_tj�|_d|_	d|_
d|_d|_dS)a�
        The *context* argument specifies the ssl.SSLContext to use.

        The *server_side* argument indicates whether this is a server side or
        client side transport.

        The optional *server_hostname* argument can be used to specify the
        hostname you are connecting to. You may only specify this parameter if
        the _ssl module supports Server Name Indication (SNI).
        NF)
�_context�_server_side�_server_hostname�
_UNWRAPPED�_staterr�	_incoming�	_outgoing�_sslobj�
_need_ssldata�
_handshake_cb�_shutdown_cb)�self�contextrrrrr�__init__Ds

z_SSLPipe.__init__cCs|jS)z*The SSL context passed to the constructor.)r)r#rrrr$Zsz_SSLPipe.contextcCs|jS)z^The internal ssl.SSLObject instance.

        Return None if the pipe is not wrapped.
        )r)r#rrr�
ssl_object_sz_SSLPipe.ssl_objectcCs|jS)zgWhether more record level data is needed to complete a handshake
        that is currently in progress.)r )r#rrr�need_ssldatagsz_SSLPipe.need_ssldatacCs
|jtkS)zj
        Whether a security layer is currently in effect.

        Return False during handshake.
        )r�_WRAPPED)r#rrr�wrappedmsz_SSLPipe.wrappedcCsb|jtkrtd��|jj|j|j|j|jd�|_	t
|_||_|jddd�\}}t
|�dks^t�|S)aLStart the SSL handshake.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the handshake is complete. The callback will be
        called with None if successful, else an exception instance.
        z"handshake in progress or completed)rr�T)�only_handshaker)rr�RuntimeErrorrZwrap_biorrrrr�
_DO_HANDSHAKEr!�feed_ssldata�len�AssertionError)r#�callback�ssldata�appdatarrr�do_handshakevs	
z_SSLPipe.do_handshakecCsj|jtkrtd��|jtkr$td��|jttfks6t�t|_||_|jd�\}}|gksf|dgksft�|S)a1Start the SSL shutdown sequence.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the shutdown is complete. The callback will be
        called without arguments.
        zno security layer presentzshutdown in progressr*)	rrr,�	_SHUTDOWNr(r-r0r"r.)r#r1r2r3rrr�shutdown�s	

z_SSLPipe.shutdowncCs2|jj�|jd�\}}|gks.|dgks.t�dS)z�Send a potentially "ragged" EOF.

        This method will raise an SSL_ERROR_EOF exception if the EOF is
        unexpected.
        r*N)rZ	write_eofr.r0)r#r2r3rrr�feed_eof�s
z_SSLPipe.feed_eofFcCs�|jtkr"|r|g}ng}g|fSd|_|r8|jj|�g}g}y�|jtkrx|jj�t|_|j	rl|j	d�|rx||fS|jtkr�xn|jj
|j�}|j|�|s�Pq�WnJ|jt
kr�|jj�d|_t|_|jr�|j�n|jtkr�|j|jj
��Wnxtjtjfk
�rl}zRt|dd�tjtjtjfk�rN|jtk�rL|j	�rL|j	|��|jtjk|_WYdd}~XnX|jj�r�|j|jj
��||fS)a�Feed SSL record level data into the pipe.

        The data must be a bytes instance. It is OK to send an empty bytes
        instance. This can be used to get ssldata for a handshake initiated by
        this endpoint.

        Return a (ssldata, appdata) tuple. The ssldata element is a list of
        buffers containing SSL data that needs to be sent to the remote SSL.

        The appdata element is a list of buffers containing plaintext data that
        needs to be forwarded to the application. The appdata list may contain
        an empty buffer indicating an SSL "close_notify" alert. This alert must
        be acknowledged by calling shutdown().
        FN�errno)rrr r�writer-rr4r(r!�read�max_size�appendr5Zunwrapr"r�SSLError�CertificateError�getattr�SSL_ERROR_WANT_READ�SSL_ERROR_WANT_WRITE�SSL_ERROR_SYSCALLr8r�pending)r#�datar+r3r2�chunk�excrrrr.�sV











 
z_SSLPipe.feed_ssldatarcCs,d|kot|�kns t�|jtkrV|t|�krF||d�g}ng}|t|�fSg}t|�}x�d|_y(|t|�kr�||jj||d��7}Wn\tj	k
r�}z>|j
dkr�tj|_|jtjtj
tjfkrЂ|jtjk|_WYdd}~XnX|jj�r
|j|jj��|t|�k�s|jrdPqdW||fS)aFeed plaintext data into the pipe.

        Return an (ssldata, offset) tuple. The ssldata element is a list of
        buffers containing record level data that needs to be sent to the
        remote SSL instance. The offset is the number of plaintext bytes that
        were processed, which may be less than the length of data.

        NOTE: In case of short writes, this call MUST be retried with the SAME
        buffer passed into the *data* argument (i.e. the id() must be the
        same). This is an OpenSSL requirement. A further particularity is that
        a short write will always have offset == 0, because the _ssl module
        does not enable partial writes. And even though the offset is zero,
        there will still be encrypted data in ssldata.
        rNFZPROTOCOL_IS_SHUTDOWN)r/r0rr�
memoryviewr rr9rr=�reasonr@r8rArBrrCr<r:)r#rD�offsetr2ZviewrFrrr�feed_appdata�s4 


 
z_SSLPipe.feed_appdatai)N)N)N)F)r)�__name__�
__module__�__qualname__�__doc__r;r%�propertyr$r&r'r)r4r6r7r.rJrrrrr0s
	



Jrc@s�eZdZdd�Zddd�Zdd�Zdd	�Zd
d�Zdd
�Ze	j
rHdd�Zdd�Zdd�Z
ddd�Zdd�Zdd�Zdd�Zdd�ZdS) �_SSLProtocolTransportcCs||_||_d|_dS)NF)�_loop�
_ssl_protocol�_closed)r#�loopZssl_protocolrrrr%)sz_SSLProtocolTransport.__init__NcCs|jj||�S)z#Get optional transport information.)rR�_get_extra_info)r#�name�defaultrrr�get_extra_info/sz$_SSLProtocolTransport.get_extra_infocCs||j_dS)N)rR�
_app_protocol)r#�protocolrrr�set_protocol3sz"_SSLProtocolTransport.set_protocolcCs|jjS)N)rRrY)r#rrr�get_protocol6sz"_SSLProtocolTransport.get_protocolcCs|jS)N)rS)r#rrr�
is_closing9sz _SSLProtocolTransport.is_closingcCsd|_|jj�dS)a
Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        TN)rSrR�_start_shutdown)r#rrr�close<sz_SSLProtocolTransport.closecCs&|js"tjd|t|d�|j�dS)Nzunclosed transport %r)�source)rS�warnings�warn�ResourceWarningr_)r#rrr�__del__Ksz_SSLProtocolTransport.__del__cCs|jjj�dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        N)rR�
_transport�
pause_reading)r#rrrrfQsz#_SSLProtocolTransport.pause_readingcCs|jjj�dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        N)rRre�resume_reading)r#rrrrgYsz$_SSLProtocolTransport.resume_readingcCs|jjj||�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        N)rRre�set_write_buffer_limits)r#ZhighZlowrrrrhasz-_SSLProtocolTransport.set_write_buffer_limitscCs|jjj�S)z,Return the current size of the write buffer.)rRre�get_write_buffer_size)r#rrrrivsz+_SSLProtocolTransport.get_write_buffer_sizecCs<t|tttf�s$tdjt|�j���|s,dS|jj	|�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        z/data: expecting a bytes-like instance, got {!r}N)
�
isinstance�bytes�	bytearrayrG�	TypeError�format�typerKrR�_write_appdata)r#rDrrrr9zsz_SSLProtocolTransport.writecCsdS)zAReturn True if this transport supports write_eof(), False if not.Fr)r#rrr�
can_write_eof�sz#_SSLProtocolTransport.can_write_eofcCs|jj�dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        N)rR�_abort)r#rrr�abort�sz_SSLProtocolTransport.abort)N)NN)rKrLrMr%rXr[r\r]r_rZPY34rdrfrgrhrir9rqrsrrrrrP&s


rPc@s�eZdZdZd(dd�Zd)dd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zd*dd�Zdd�Z
dd�Zdd�Zdd�Zdd �Zd+d"d#�Zd$d%�Zd&d'�ZdS),�SSLProtocolz�SSL protocol.

    Implementation of SSL on top of a socket using incoming and outgoing
    buffers which are ssl.MemoryBIO objects.
    FNTcCs�tdkrtd��|st||�}||_|r6|r6||_nd|_||_t|d�|_tj	�|_
d|_||_||_
||_t|j
|�|_d|_d|_d|_d|_d|_||_dS)Nzstdlib ssl module not available)rrF)rr,rrr�_sslcontext�dict�_extra�collections�deque�_write_backlog�_write_buffer_size�_waiterrQrYrP�_app_transport�_sslpipe�_session_established�
_in_handshake�_in_shutdownre�_call_connection_made)r#rTZapp_protocolrZwaiterrrZcall_connection_maderrrr%�s,


zSSLProtocol.__init__cCsD|jdkrdS|jj�s:|dk	r.|jj|�n|jjd�d|_dS)N)r|Z	cancelledZ
set_exceptionZ
set_result)r#rFrrr�_wakeup_waiter�s

zSSLProtocol._wakeup_waitercCs&||_t|j|j|j�|_|j�dS)zXCalled when the low-level connection is made.

        Start the SSL handshake.
        N)rerrurrr~�_start_handshake)r#�	transportrrr�connection_made�s

zSSLProtocol.connection_madecCs8|jrd|_|jj|jj|�d|_d|_|j|�dS)z�Called when the low-level connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        FN)rrQ�	call_soonrY�connection_lostrer}r�)r#rFrrrr��szSSLProtocol.connection_lostcCs|jj�dS)z\Called when the low-level transport's buffer goes over
        the high-water mark.
        N)rY�
pause_writing)r#rrrr��szSSLProtocol.pause_writingcCs|jj�dS)z^Called when the low-level transport's buffer drains below
        the low-water mark.
        N)rY�resume_writing)r#rrrr��szSSLProtocol.resume_writingcCs�|jdkrdSy|jj|�\}}WnHtjk
rj}z*|jj�rTtjd||j|j	�|j
�dSd}~XnXx|D]}|jj|�qrWx(|D] }|r�|j
j|�q�|j�Pq�WdS)zXCalled when some SSL data is received.

        The argument is a bytes object.
        Nz%r: SSL error %s (reason %s))r~r.rr=rQ�	get_debugr�warningr8rHrrrer9rY�
data_receivedr^)r#rDr2r3�erErrrr��s"



zSSLProtocol.data_receivedc
CsTzB|jj�rtjd|�|jt�|js@|jj�}|r@tj	d�Wd|j
j�XdS)aCalled when the other end of the low-level stream
        is half-closed.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        z%r received EOFz?returning true from eof_received() has no effect when using sslN)rQr�r�debugr��ConnectionResetErrorr�rY�eof_receivedr�rer_)r#Z	keep_openrrrr�s


zSSLProtocol.eof_receivedcCs4||jkr|j|S|jdk	r,|jj||�S|SdS)N)rwrerX)r#rVrWrrrrU!s



zSSLProtocol._get_extra_infocCs.|jr
dS|jr|j�nd|_|jd�dS)NTr*)r�r�rrrp)r#rrrr^)s
zSSLProtocol._start_shutdowncCs.|jj|df�|jt|�7_|j�dS)Nr)rzr<r{r/�_process_write_backlog)r#rDrrrrp2szSSLProtocol._write_appdatacCsH|jj�r$tjd|�|jj�|_nd|_d|_|jjd�|j	�dS)Nz%r starts SSL handshakeTr*r)r*r)
rQr�rr��time�_handshake_start_timer�rzr<r�)r#rrrr�7s
zSSLProtocol._start_handshakecCsTd|_|jj}yF|dk	r|�|j�}t|jd�sR|jrR|jjtj	krRtj
||j�Wn~tk
r�}zb|jj
�r�t|tj�r�tjd|dd�ntjd|dd�|jj�t|t�r�|j|�dS�WYdd}~XnX|jj
��r|jj�|j}tjd||d�|jj||j�|j�|d	�|j�r4|jj|j �|j�d|_!|jj"|j#�dS)
NFrz5%r: SSL handshake failed on verifying the certificateT)�exc_infoz%r: SSL handshake failedz%r: SSL handshake took %.1f msg@�@)�peercert�cipher�compressionr&)$r�r~r&Zgetpeercertr
rurr
rZ	CERT_NONEZmatch_hostname�
BaseExceptionrQr�rjr>rr�rer_�	Exceptionr�r�r�r�rw�updater�r�r�rYr�r}rr�r�)r#Z
handshake_excZsslobjr�rFZdtrrr�_on_handshake_completeCsD




z"SSLProtocol._on_handshake_completecCsJ|jdks|jdkrdSy�x�tt|j��D]�}|jd\}}|rT|jj||�\}}n*|rl|jj|j�}d}n|jj|j	�}d}x|D]}|jj
|�q�W|t|�kr�||f|jd<|jjs�t�|jj
r�|jj�P|jd=|jt|�8_q*WWnRtk
�rD}z4|j�r|j|�n|j|d�t|t��s4�WYdd}~XnXdS)NrrzFatal error on SSL transport)rer~�ranger/rzrJr4r�r6�	_finalizer9r'r0Z_pausedrgr{r�r��_fatal_errorrjr�)r#�irDrIr2rErFrrrr�ws:

z"SSLProtocol._process_write_backlog�Fatal error on transportcCsXt|tj�r*|jj�rBtjd||dd�n|jj|||j|d��|jrT|jj	|�dS)Nz%r: %sT)r�)�messageZ	exceptionr�rZ)
rjrZ_FATAL_ERROR_IGNORErQr�rr�Zcall_exception_handlerreZ_force_close)r#rFr�rrrr��s

zSSLProtocol._fatal_errorcCsd|_|jdk	r|jj�dS)N)r~rer_)r#rrrr��s
zSSLProtocol._finalizec
Cs(z|jdk	r|jj�Wd|j�XdS)N)rersr�)r#rrrrr�s
zSSLProtocol._abort)FNT)N)N)r�)rKrLrMrNr%r�r�r�r�r�r�r�rUr^rpr�r�r�r�r�rrrrrrrt�s&
"


	4,
rt)rxrar�ImportError�rrrr�logrrrrr-r(r5�objectrZ_FlowControlMixinZ	TransportrPZProtocolrtrrrr�<module>s*
wnPK[��ь��*__pycache__/constants.cpython-36.opt-1.pycnu�[���3


 \s�@sdZdZdZdZdS)z
Constants.���
N)�__doc__Z!LOG_THRESHOLD_FOR_CONNLOST_WRITESZACCEPT_RETRY_DELAYZDEBUG_STACK_DEPTH�rr�)/usr/lib64/python3.6/asyncio/constants.py�<module>sPK[Ea�#mm0__pycache__/selector_events.cpython-36.opt-2.pycnu�[���3


 \���
@s8dgZddlZddlZddlZddlZddlZddlZyddlZWnek
rZdZYnXddl	m
Z
ddl	mZddl	mZddl	m
Z
ddl	mZdd	l	mZdd
l	mZddl	mZddlmZdd
lmZdd�ZGdd�de
j�ZGdd�dejej�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)�BaseSelectorEventLoop�N�)�base_events)�compat)�	constants)�events)�futures)�	selectors)�
transports)�sslproto)�	coroutine)�loggercCs6y|j|�}Wntk
r"dSXt|j|@�SdS)NF)�get_key�KeyError�boolr)�selector�fdZevent�key�r�//usr/lib64/python3.6/asyncio/selector_events.py�_test_selector_event s
rcsneZdZdN�fdd�	ZdOddd�dd�ZdPddddd�d	d
�Zddddd�dd�ZdQd
d�Z�fdd�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdRdd�ZdSd d!�ZedTd"d#��Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Zd8d9�Zd:d;�Zd<d=�Zed>d?��Z d@dA�Z!dBdC�Z"dDdE�Z#dFdG�Z$dHdI�Z%dJdK�Z&dLdM�Z'�Z(S)UrNcsFt�j�|dkrtj�}tjd|jj�||_|j	�t
j�|_dS)NzUsing selector: %s)
�super�__init__r	ZDefaultSelectorr
�debug�	__class__�__name__�	_selector�_make_self_pipe�weakref�WeakValueDictionary�_transports)�selfr)rrrr1s
zBaseSelectorEventLoop.__init__)�extra�servercCst||||||�S)N)�_SelectorSocketTransport)r!�sock�protocol�waiterr"r#rrr�_make_socket_transport;s
z,BaseSelectorEventLoop._make_socket_transportF)�server_side�server_hostnamer"r#c

CsNtj�s"|j||||||||d�Stj||||||�}	t|||	||d�|	jS)N)r)r*r"r#)r"r#)rZ_is_sslproto_available�_make_legacy_ssl_transportZSSLProtocolr$Z_app_transport)
r!�rawsockr&�
sslcontextr'r)r*r"r#Zssl_protocolrrr�_make_ssl_transport@s

z)BaseSelectorEventLoop._make_ssl_transportc	
Cst|||||||||�	S)N)�_SelectorSslTransport)	r!r,r&r-r'r)r*r"r#rrrr+Os
z0BaseSelectorEventLoop._make_legacy_ssl_transportcCst||||||�S)N)�_SelectorDatagramTransport)r!r%r&�addressr'r"rrr�_make_datagram_transportYsz.BaseSelectorEventLoop._make_datagram_transportcsL|j�rtd��|j�rdS|j�t�j�|jdk	rH|jj�d|_dS)Nz!Cannot close a running event loop)Z
is_running�RuntimeError�	is_closed�_close_self_piper�closer)r!)rrrr6^s


zBaseSelectorEventLoop.closecCst�dS)N)�NotImplementedError)r!rrr�_socketpairisz!BaseSelectorEventLoop._socketpaircCsB|j|jj��|jj�d|_|jj�d|_|jd8_dS)Nr)�_remove_reader�_ssock�filenor6�_csock�
_internal_fds)r!rrrr5ls

z&BaseSelectorEventLoop._close_self_pipecCsN|j�\|_|_|jjd�|jjd�|jd7_|j|jj�|j�dS)NFr)r8r:r<�setblockingr=�_add_readerr;�_read_from_self)r!rrrrts
z%BaseSelectorEventLoop._make_self_pipecCsdS)Nr)r!�datarrr�_process_self_data|sz(BaseSelectorEventLoop._process_self_datacCsVxPy |jjd�}|sP|j|�Wqtk
r8wYqtk
rLPYqXqWdS)Ni)r:�recvrB�InterruptedError�BlockingIOError)r!rArrrr@sz%BaseSelectorEventLoop._read_from_selfcCsJ|j}|dk	rFy|jd�Wn(tk
rD|jr@tjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketT)�exc_info)r<�send�OSError�_debugr
r)r!Zcsockrrr�_write_to_self�sz$BaseSelectorEventLoop._write_to_self�dcCs |j|j�|j|||||�dS)N)r?r;�_accept_connection)r!�protocol_factoryr%r-r#�backlogrrr�_start_serving�sz$BaseSelectorEventLoop._start_servingcCs�x�t|�D]�}y0|j�\}}|jr2tjd|||�|jd�Wn�tttfk
rXdSt	k
r�}	z^|	j
t
jt
jt
j
t
jfkr�|jd|	|d��|j|j��|jtj|j|||||�n�WYdd}	~	Xq
Xd|i}
|j|||
||�}|j|�q
WdS)Nz#%r got a new connection from %r: %rFz&socket.accept() out of system resource)�message�	exception�socket�peername)�range�acceptrJr
rr>rErD�ConnectionAbortedErrorrI�errnoZEMFILEZENFILEZENOBUFSZENOMEM�call_exception_handlerr9r;Z
call_laterrZACCEPT_RETRY_DELAYrP�_accept_connection2Zcreate_task)r!rNr%r-r#rO�_�conn�addr�excr"rVrrrrM�s4


z(BaseSelectorEventLoop._accept_connectionccs�d}d}yj|�}|j�}|r6|j||||d||d�}n|j|||||d�}y|EdHWn|j��YnXWn\tk
r�}	z@|jr�d|	d�}
|dk	r�||
d<|dk	r�||
d<|j|
�WYdd}	~	XnXdS)NT)r'r)r"r#)r'r"r#z3Error on transport creation for incoming connection)rQrRr&�	transport)�
create_futurer.r(r6�	ExceptionrJrY)r!rNr\r"r-r#r&r_r'r^�contextrrrrZ�s4z)BaseSelectorEventLoop._accept_connection2cCs@y|j|}Wntk
r"YnX|j�s<tdj||���dS)Nz.File descriptor {!r} is used by transport {!r})r r�
is_closingr3�format)r!rr_rrr�_ensure_fd_no_transport�sz-BaseSelectorEventLoop._ensure_fd_no_transportc	
Gs�|j�tj|||�}y|jj|�}Wn*tk
rP|jj|tj|df�Yn>X|j|j	}\}}|jj
||tjB||f�|dk	r�|j�dS)N)�
_check_closedr�Handlerrr�registerr	�
EVENT_READrA�modify�cancel)	r!r�callback�args�handler�mask�reader�writerrrrr?�s
z!BaseSelectorEventLoop._add_readerc
Cs�|j�rdSy|jj|�}Wntk
r0dSX|j|j}\}}|tjM}|sb|jj|�n|jj	||d|f�|dk	r�|j
�dSdSdS)NFT)r4rrrrrAr	ri�
unregisterrjrk)r!rrrorprqrrrr9sz$BaseSelectorEventLoop._remove_readerc	
Gs�|j�tj|||�}y|jj|�}Wn*tk
rP|jj|tjd|f�Yn>X|j|j	}\}}|jj
||tjB||f�|dk	r�|j�dS)N)rfrrgrrrrhr	�EVENT_WRITErArjrk)	r!rrlrmrnrrorprqrrr�_add_writers
z!BaseSelectorEventLoop._add_writerc
Cs�|j�rdSy|jj|�}Wntk
r0dSX|j|j}\}}|tjM}|sb|jj|�n|jj	|||df�|dk	r�|j
�dSdSdS)NFT)r4rrrrrAr	rsrrrjrk)r!rrrorprqrrr�_remove_writer,sz$BaseSelectorEventLoop._remove_writercGs|j|�|j||f|��S)N)rer?)r!rrlrmrrr�
add_readerCs
z BaseSelectorEventLoop.add_readercCs|j|�|j|�S)N)rer9)r!rrrr�
remove_readerHs
z#BaseSelectorEventLoop.remove_readercGs|j|�|j||f|��S)N)rert)r!rrlrmrrr�
add_writerMs
z BaseSelectorEventLoop.add_writercCs|j|�|j|�S)N)reru)r!rrrr�
remove_writerRs
z#BaseSelectorEventLoop.remove_writercCs6|jr|j�dkrtd��|j�}|j|d||�|S)Nrzthe socket must be non-blocking)rJ�
gettimeout�
ValueErrorr`�
_sock_recv)r!r%�n�futrrr�	sock_recvWs
	zBaseSelectorEventLoop.sock_recvcCs�|dk	r|j|�|j�rdSy|j|�}Wn`ttfk
rb|j�}|j||j||||�Yn6tk
r�}z|j	|�WYdd}~XnX|j
|�dS)N)rw�	cancelledrCrErDr;rvr|ra�
set_exception�
set_result)r!r~�
registered_fdr%r}rArr^rrrr|fs
z BaseSelectorEventLoop._sock_recvcCsF|jr|j�dkrtd��|j�}|r8|j|d||�n
|jd�|S)Nrzthe socket must be non-blocking)rJrzr{r`�
_sock_sendallr�)r!r%rAr~rrr�sock_sendall{s
z"BaseSelectorEventLoop.sock_sendallcCs�|dk	r|j|�|j�rdSy|j|�}WnDttfk
rHd}Yn*tk
rp}z|j|�dSd}~XnX|t|�kr�|jd�n.|r�||d�}|j	�}|j
||j||||�dS)Nr)ryr�rHrErDrar��lenr�r;rxr�)r!r~r�r%rAr}r^rrrrr��s"

z#BaseSelectorEventLoop._sock_sendallccs�|jr|j�dkrtd��ttd�s2|jtjkrptj||j|j	|d�}|j
�sZ|EdH|j�d\}}}}}|j�}|j
|||�|EdHS)Nrzthe socket must be non-blocking�AF_UNIX)�family�proto�loop)rJrzr{�hasattrrSr�r�rZ_ensure_resolvedr��done�resultr`�
_sock_connect)r!r%r1Zresolvedr[r~rrr�sock_connect�s
z"BaseSelectorEventLoop.sock_connectcCs�|j�}y|j|�Wnjttfk
rV|jtj|j|��|j||j	|||�Yn6t
k
r�}z|j|�WYdd}~XnX|jd�dS)N)
r;ZconnectrErDZadd_done_callback�	functools�partial�_sock_connect_donerx�_sock_connect_cbrar�r�)r!r~r%r1rr^rrrr��sz#BaseSelectorEventLoop._sock_connectcCs|j|�dS)N)ry)r!rr~rrrr��sz(BaseSelectorEventLoop._sock_connect_donecCs�|j�rdSy,|jtjtj�}|dkr6t|d|f��WnBttfk
rPYn6tk
rz}z|j	|�WYdd}~XnX|j
d�dS)NrzConnect call failed %s)r�Z
getsockoptrSZ
SOL_SOCKETZSO_ERRORrIrErDrar�r�)r!r~r%r1�errr^rrrr��sz&BaseSelectorEventLoop._sock_connect_cbcCs4|jr|j�dkrtd��|j�}|j|d|�|S)Nrzthe socket must be non-blockingF)rJrzr{r`�_sock_accept)r!r%r~rrr�sock_accept�s

z!BaseSelectorEventLoop.sock_acceptcCs�|j�}|r|j|�|j�r"dSy|j�\}}|jd�WnVttfk
rh|j||j|d|�Yn:t	k
r�}z|j
|�WYdd}~XnX|j||f�dS)NFT)r;rwr�rVr>rErDrvr�rar�r�)r!r~Z
registeredr%rr\r1r^rrrr��s
z"BaseSelectorEventLoop._sock_acceptcCs�x~|D]v\}}|j|j}\}}|tj@rN|dk	rN|jrD|j|�n
|j|�|tj@r|dk	r|jrr|j|�q|j|�qWdS)N)	�fileobjrAr	riZ
_cancelledr9Z
_add_callbackrsru)r!Z
event_listrror�rprqrrr�_process_events�s
z%BaseSelectorEventLoop._process_eventscCs|j|j��|j�dS)N)r9r;r6)r!r%rrr�
_stop_servingsz#BaseSelectorEventLoop._stop_serving)N)N)N)NNN)NNrL)NNrL)NN))r�
__module__�__qualname__rr(r.r+r2r6r8r5rrBr@rKrPrMrrZrer?r9rtrurvrwrxryrr|r�r�r�r�r�r�r�r�r�r��
__classcell__rr)rrr+sR



(#cs�eZdZdZeZdZd �fdd�	Zdd�Zdd	�Z	d
d�Z
dd
�Zdd�Zdd�Z
ejr`dd�Zd!dd�Zdd�Zdd�Zdd�Zdd�Z�ZS)"�_SelectorTransport�iNcs�t�j||�||jd<|j�|jd<d|jkrdy|j�|jd<Wn tjk
rbd|jd<YnX||_|j�|_	||_
d|_||_|j
�|_d|_d|_|jdk	r�|jj�||j|j	<dS)NrSZsocknamerTTrF)rr�_extraZgetsocknameZgetpeernamerS�error�_sockr;�_sock_fd�	_protocol�_protocol_connected�_server�_buffer_factory�_buffer�
_conn_lost�_closingZ_attachr )r!r�r%r&r"r#)rrrrs&





z_SelectorTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�|jdk	r�|jj�r�t|jj	|jt
j�}|rz|jd�n
|jd�t|jj	|jt
j�}|r�d}nd}|j
�}|jd||f�d	d
j|�S)N�closed�closingzfd=%szread=pollingz	read=idle�pollingZidlezwrite=<%s, bufsize=%s>z<%s>� )rrr��appendr�r��_loopr4rrr	rirs�get_write_buffer_size�join)r!�infor��state�bufsizerrr�__repr__2s*



z_SelectorTransport.__repr__cCs|jd�dS)N)�_force_close)r!rrr�abortNsz_SelectorTransport.abortcCs
||_dS)N)r�)r!r&rrr�set_protocolQsz_SelectorTransport.set_protocolcCs|jS)N)r�)r!rrr�get_protocolTsz_SelectorTransport.get_protocolcCs|jS)N)r�)r!rrrrcWsz_SelectorTransport.is_closingcCsT|jr
dSd|_|jj|j�|jsP|jd7_|jj|j�|jj|jd�dS)NTr)	r�r�r9r�r�r�ru�	call_soon�_call_connection_lost)r!rrrr6Zsz_SelectorTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)�source)r��warnings�warn�ResourceWarningr6)r!rrr�__del__hs
z_SelectorTransport.__del__�Fatal error on transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)rG)rQrRr_r&)
�
isinstancerZ_FATAL_ERROR_IGNOREr��	get_debugr
rrYr�r�)r!r^rQrrr�_fatal_errorns
z_SelectorTransport._fatal_errorcCsd|jr
dS|jr(|jj�|jj|j�|jsBd|_|jj|j�|jd7_|jj|j	|�dS)NTr)
r�r��clearr�rur�r�r9r�r�)r!r^rrrr�|s
z_SelectorTransport._force_closecCsVz|jr|jj|�Wd|jj�d|_d|_d|_|j}|dk	rP|j�d|_XdS)N)r�r�Zconnection_lostr�r6r�r�Z_detach)r!r^r#rrrr��s
z(_SelectorTransport._call_connection_lostcCs
t|j�S)N)r�r�)r!rrrr��sz(_SelectorTransport.get_write_buffer_sizecGs"|jr
dS|jj||f|��dS)N)r�r�r?)r!rrlrmrrrr?�sz_SelectorTransport._add_readeri)NN)r�)rr�r��max_size�	bytearrayr�r�rr�r�r�r�rcr6rZPY34r�r�r�r�r�r?r�rr)rrr�s"

r�csVeZdZd�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
�ZS)r$Ncsrt�j|||||�d|_d|_tj|j�|jj|j	j
|�|jj|j|j|j
�|dk	rn|jjtj|d�dS)NF)rr�_eof�_pausedrZ_set_nodelayr�r�r�r��connection_mader?r��_read_readyr�_set_result_unless_cancelled)r!r�r%r&r'r"r#)rrrr�s

z!_SelectorSocketTransport.__init__cCs>|js|jrdSd|_|jj|j�|jj�r:tjd|�dS)NTz%r pauses reading)r�r�r�r9r�r�r
r)r!rrr�
pause_reading�s
z&_SelectorSocketTransport.pause_readingcCsB|js|jrdSd|_|j|j|j�|jj�r>tjd|�dS)NFz%r resumes reading)	r�r�r?r�r�r�r�r
r)r!rrr�resume_reading�s
z'_SelectorSocketTransport.resume_readingcCs�|jr
dSy|jj|j�}WnDttfk
r4Yn|tk
r`}z|j|d�WYdd}~XnPX|rt|jj	|�n<|j
j�r�tj
d|�|jj�}|r�|j
j|j�n|j�dS)Nz$Fatal read error on socket transportz%r received EOF)r�r�rCr�rErDrar�r��
data_receivedr�r�r
r�eof_receivedr9r�r6)r!rAr^�	keep_openrrrr��s 

z$_SelectorSocketTransport._read_readycCs�t|tttf�s"tdt|�j��|jr0td��|s8dS|j	rf|j	t
jkrTtj
d�|j	d7_	dS|js�y|jj|�}WnBttfk
r�Yn@tk
r�}z|j|d�dSd}~XnX||d�}|s�dS|jj|j|j�|jj|�|j�dS)Nz1data argument must be a bytes-like object, not %rz%Cannot call write() after write_eof()zsocket.send() raised exception.rz%Fatal write error on socket transport)r��bytesr��
memoryview�	TypeError�typerr�r3r�r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningr�r�rHrErDrar�r�rtr��_write_ready�extend�_maybe_pause_protocol)r!rAr}r^rrr�write�s4
z_SelectorSocketTransport.writecCs�|jr
dSy|jj|j�}Wn\ttfk
r4Yn�tk
rx}z*|jj|j	�|jj
�|j|d�WYdd}~XnTX|r�|jd|�=|j�|js�|jj|j	�|j
r�|jd�n|jr�|jjtj�dS)Nz%Fatal write error on socket transport)r�r�rHr�rErDrar�rur�r�r��_maybe_resume_protocolr�r�r��shutdownrS�SHUT_WR)r!r}r^rrrr�s&
z%_SelectorSocketTransport._write_readycCs.|js|jrdSd|_|js*|jjtj�dS)NT)r�r�r�r�r�rSr�)r!rrr�	write_eofs
z"_SelectorSocketTransport.write_eofcCsdS)NTr)r!rrr�
can_write_eof sz&_SelectorSocketTransport.can_write_eof)NNN)rr�r�rr�r�r�r�r�r�r�r�rr)rrr$�s#r$csdeZdZeZd�fdd�	Zddd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
�ZS)r/NFc

s�tdkrtd��|s tj||�}|dd�}
|r<|r<||
d<|j|f|
�}t�j|||||	�d|_||_||_	||_
d|_|jj
|d�|jj�r�tjd|�|jj�}nd}|j|�dS)Nzstdlib ssl module not availableF)r)Zdo_handshake_on_connectr*)r-z%r starts SSL handshake)�sslr3rZ_create_transport_contextZwrap_socketrrr��_server_hostname�_waiter�_sslcontextr�r��updater�r�r
r�time�
_on_handshake)
r!r�r,r&r-r'r)r*r"r#Zwrap_kwargsZsslsock�
start_time)rrrr(s*

z_SelectorSslTransport.__init__cCsD|jdkrdS|jj�s:|dk	r.|jj|�n|jjd�d|_dS)N)r�r�r�r�)r!r^rrr�_wakeup_waiterLs

z$_SelectorSslTransport._wakeup_waiterc"Cs$y|jj�Wn�tjk
r8|jj|j|j|�dStjk
r`|jj	|j|j|�dSt
k
r�}z`|jj�r�tj
d|dd�|jj|j�|jj|j�|jj�|j|�t|t�r�dS�WYdd}~XnX|jj|j�|jj|j�|jj�}t|jd��s�|j�r�|jjtjk�r�ytj||j�WnRtk
�r�}z4|jj��rjtj
d|dd�|jj�|j|�dSd}~XnX|jj||jj�|jj�|jd�d|_d|_ |jj|j|j!�d|_"|jj#|j$j%|�|jj#|j�|jj��r |jj&�|}tj'd||d	�dS)
Nz%r: SSL handshake failedT)rGZcheck_hostnamez1%r: SSL handshake failed on matching the hostname)�peercert�cipher�compressionZ
ssl_objectFz%r: SSL handshake took %.1f msg@�@)(r�Zdo_handshaker��SSLWantReadErrorr�r?r�r��SSLWantWriteErrorrt�
BaseExceptionr�r
r�r9rur6r�r�raZgetpeercertr�r�r�Zverify_modeZ	CERT_NONEZmatch_hostnamer�r�r�r��_read_wants_write�_write_wants_readr�r�r�r�r�r�r)r!r�r^r�Zdtrrrr�Vsb













z#_SelectorSslTransport._on_handshakecCsJ|jrtd��|jrtd��d|_|jj|j�|jj�rFtjd|�dS)Nz#Cannot pause_reading() when closingzAlready pausedTz%r pauses reading)	r�r3r�r�r9r�r�r
r)r!rrrr��s
z#_SelectorSslTransport.pause_readingcCsJ|jstd��d|_|jrdS|jj|j|j�|jj�rFtj	d|�dS)Nz
Not pausedFz%r resumes reading)
r�r3r�r�r?r�r�r�r
r)r!rrrr��s
z$_SelectorSslTransport.resume_readingcCs"|jr
dS|jr6d|_|j�|jr6|jj|j|j�y|jj|j	�}Wn�t
ttj
fk
rdYn�tjk
r�d|_|jj|j�|jj|j|j�Yn�tk
r�}z|j|d�WYdd}~XnTX|r�|jj|�n@z4|jj�r�tjd|�|jj�}|�rtjd�Wd|j�XdS)NFTz!Fatal read error on SSL transportz%r received EOFz?returning true from eof_received() has no effect when using ssl)r�r�r�r�r�rtr�r�rCr�rErDr�r�r�r�r9rar�r�r�r�r
rr�r�r6)r!rAr^r�rrrr��s4

z!_SelectorSslTransport._read_readycCs(|jr
dS|jr<d|_|j�|jp(|js<|jj|j|j�|jr�y|j	j
|j�}Wn�ttt
jfk
rtd}Ynpt
jk
r�d}|jj|j�d|_YnDtk
r�}z(|jj|j�|jj�|j|d�dSd}~XnX|r�|jd|�=|j�|j�s$|jj|j�|j�r$|jd�dS)NFrTz"Fatal write error on SSL transport)r�r�r�r�r�r�r?r�r�r�rHrErDr�r�r�rur�rar�r�r�r�)r!r}r^rrrr��s8

z"_SelectorSslTransport._write_readycCs�t|tttf�s"tdt|�j��|s*dS|jrX|jtj	krFt
jd�|jd7_dS|jsp|j
j|j|j�|jj|�|j�dS)Nz1data argument must be a bytes-like object, not %rzsocket.send() raised exception.r)r�r�r�r�r�r�rr�rr�r
r�r�r�rtr�r�r�r�)r!rArrrr��s
z_SelectorSslTransport.writecCsdS)NFr)r!rrrr�sz#_SelectorSslTransport.can_write_eof)NFNNN)N)rr�r�r�r�rr�r�r�r�r�r�r�r�r�rr)rrr/$s"

?
"#r/csFeZdZejZd�fdd�	Zdd�Zdd�Zd
dd	�Z	d
d�Z
�ZS)r0Ncs^t�j||||�||_|jj|jj|�|jj|j|j|j	�|dk	rZ|jjt
j|d�dS)N)rr�_addressr�r�r�r�r?r�r�rr�)r!r�r%r&r1r'r")rrrrs

z#_SelectorDatagramTransport.__init__cCstdd�|jD��S)Ncss|]\}}t|�VqdS)N)r�)�.0rAr[rrr�	<genexpr>szC_SelectorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr�)r!rrrr�sz0_SelectorDatagramTransport.get_write_buffer_sizecCs�|jr
dSy|jj|j�\}}Wnpttfk
r8Ynhtk
rd}z|jj|�WYdd}~Xn<t	k
r�}z|j
|d�WYdd}~XnX|jj||�dS)Nz&Fatal read error on datagram transport)r�r�Zrecvfromr�rErDrIr��error_receivedrar�Zdatagram_received)r!rAr]r^rrrr� sz&_SelectorDatagramTransport._read_readycCsTt|tttf�s"tdt|�j��|s*dS|jrN|d|jfkrNtd|jf��|j	r�|jr�|j	t
jkrptj
d�|j	d7_	dS|j�s4y&|jr�|jj|�n|jj||�dSttfk
r�|jj|j|j�YnZtk
�r}z|jj|�dSd}~Xn.tk
�r2}z|j|d�dSd}~XnX|jjt|�|f�|j�dS)Nz1data argument must be a bytes-like object, not %rz#Invalid address: must be None or %szsocket.send() raised exception.rz'Fatal write error on datagram transport)r�r�r�r�r�r�rr�r{r�rr�r
r�r�r�rH�sendtorErDr�rtr��
_sendto_readyrIr�r�rar�r�r�)r!rAr]r^rrrr�.s<
z!_SelectorDatagramTransport.sendtocCs�x�|jr�|jj�\}}y&|jr,|jj|�n|jj||�Wqttfk
rf|jj||f�PYqt	k
r�}z|j
j|�dSd}~Xqtk
r�}z|j
|d�dSd}~XqXqW|j�|js�|jj|j�|jr�|jd�dS)Nz'Fatal write error on datagram transport)r��popleftr�r�rHr�rErD�
appendleftrIr�r�rar�r�r�rur�r�r�)r!rAr]r^rrrr�Us*z(_SelectorDatagramTransport._sendto_ready)NNN)N)rr�r��collections�dequer�rr�r�r�r�r�rr)rrr0s
'r0)�__all__r�rXr�rSr�rr��ImportError�rrrrrr	r
rZ
coroutinesr�logr
rZ
BaseEventLooprZ_FlowControlMixinZ	Transportr�r$r/r0rrrr�<module>sB
iiPK[��ь��$__pycache__/constants.cpython-36.pycnu�[���3


 \s�@sdZdZdZdZdS)z
Constants.���
N)�__doc__Z!LOG_THRESHOLD_FOR_CONNLOST_WRITESZACCEPT_RETRY_DELAYZDEBUG_STACK_DEPTH�rr�)/usr/lib64/python3.6/asyncio/constants.py�<module>sPK[3'~��-__pycache__/base_futures.cpython-36.opt-2.pycnu�[���3


 \�@srgZddlZddlZddlmZejjjZejj	Z	ejj
Z
Gdd�de�ZdZdZ
dZd	d
�Zdd�Zd
d�ZdS)�N�)�eventsc@seZdZdS)�InvalidStateErrorN)�__name__�
__module__�__qualname__�rr�,/usr/lib64/python3.6/asyncio/base_futures.pyr
srZPENDINGZ	CANCELLEDZFINISHEDcCst|jd�o|jdk	S)N�_asyncio_future_blocking)�hasattr�	__class__r
)�objrrr	�isfuturesrcCs�t|�}|sd}dd�}|dkr.||d�}nP|dkrTdj||d�||d��}n*|dkr~dj||d�|d||d
��}d	|S)N�cSstj|f�S)N)rZ_format_callback_source)�callbackrrr	�	format_cb(sz$_format_callbacks.<locals>.format_cbrr�z{}, {}z{}, <{} more>, {}zcb=[%s]���)�len�format)�cb�sizerrrr	�_format_callbacks"srcCs�|jj�g}|jtkrP|jdk	r4|jdj|j��ntj|j�}|jdj|��|j	rf|jt
|j	��|jr�|jd}|jd|d|df�|S)Nzexception={!r}z	result={}rzcreated at %s:%srr)Z_state�lower�	_FINISHEDZ
_exception�appendr�reprlib�reprZ_resultZ
_callbacksrZ_source_traceback)Zfuture�info�result�framerrr	�_future_repr_info6s


r!)�__all__Zconcurrent.futures._baseZ
concurrentrrrZfuturesZ_base�ErrorZCancelledError�TimeoutErrorrZ_PENDINGZ
_CANCELLEDrrrr!rrrr	�<module>s
PK[Y����(__pycache__/futures.cpython-36.opt-2.pycnu�[���3


 \>�@sddddddgZddlZddlZddlZddlZdd	lmZdd
lmZddlm	Z	ej
Z
ejZejZej
Z
ejZejZejZejdZGdd
�d
�ZGdd�d�ZeZdd�Zdd�Zdd�Zdd�Zdd�dd�ZyddlZWnek
r�YnXejZZdS)�CancelledError�TimeoutError�InvalidStateError�Future�wrap_future�isfuture�N�)�base_futures)�compat)�eventsc@s0eZdZdZdd�Zdd�Zd	d
�Zdd�Zd
S)�_TracebackLogger�loop�source_traceback�exc�tbcCs |j|_|j|_||_d|_dS)N)�_loopr
�_source_tracebackrrr)�self�futurer�r�'/usr/lib64/python3.6/asyncio/futures.py�__init__Rsz_TracebackLogger.__init__cCs,|j}|dk	r(d|_tj|j||j�|_dS)N)r�	traceback�format_exception�	__class__�
__traceback__r)rrrrr�activateXs

z_TracebackLogger.activatecCsd|_d|_dS)N)rr)rrrr�clear_sz_TracebackLogger.clearcCsb|jr^d}|jr:djtj|j��}|d7}|d|j�7}|dj|j�j�7}|jjd|i�dS)Nz*Future/Task exception was never retrieved
�z0Future/Task created at (most recent call last):
z%s
�message)rr�joinr�format_list�rstripr
�call_exception_handler)r�msg�srcrrr�__del__csz_TracebackLogger.__del__N)r
rrr)�__name__�
__module__�__qualname__�	__slots__rrrr&rrrrrs
2rc@s�eZdZeZdZdZdZdZdZ	dZ
dd�dd�Zej
Zdd�ZejrNdd	�Zd
d�Zdd
�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zejr�eZdS) rNF)r
cCs@|dkrtj�|_n||_g|_|jj�r<tjtjd��|_dS)Nr)	r�get_event_loopr�
_callbacksZ	get_debug�
extract_stack�sys�	_getframer)rr
rrrr�s
zFuture.__init__cCsd|jjdj|j��fS)Nz<%s %s>� )rr'r �
_repr_info)rrrr�__repr__�szFuture.__repr__cCsD|js
dS|j}d|jj||d�}|jr4|j|d<|jj|�dS)Nz %s exception was never retrieved)r�	exceptionrr)�_log_traceback�
_exceptionrr'rrr#)rr�contextrrrr&�s
zFuture.__del__cCs&d|_|jtkrdSt|_|j�dS)NFT)r4�_state�_PENDING�
_CANCELLED�_schedule_callbacks)rrrr�cancel�s
z
Future.cancelcCsD|jdd�}|sdSg|jdd�<x|D]}|jj||�q*WdS)N)r,r�	call_soon)rZ	callbacks�callbackrrrr:�s
zFuture._schedule_callbackscCs
|jtkS)N)r7r9)rrrr�	cancelled�szFuture.cancelledcCs
|jtkS)N)r7r8)rrrr�done�szFuture.donecCs<|jtkrt�|jtkr td��d|_|jdk	r6|j�|jS)NzResult is not ready.F)r7r9r�	_FINISHEDrr4r5�_result)rrrr�result�s


z
Future.resultcCs,|jtkrt�|jtkr td��d|_|jS)NzException is not set.F)r7r9rr@rr4r5)rrrrr3�s

zFuture.exceptioncCs*|jtkr|jj||�n|jj|�dS)N)r7r8rr<r,�append)r�fnrrr�add_done_callbacks
zFuture.add_done_callbackcs<�fdd�|jD�}t|j�t|�}|r8||jdd�<|S)Ncsg|]}|�kr|�qSrr)�.0�f)rDrr�
<listcomp>sz/Future.remove_done_callback.<locals>.<listcomp>)r,�len)rrDZfiltered_callbacksZ
removed_countr)rDr�remove_done_callbacks
zFuture.remove_done_callbackcCs4|jtkrtdj|j|���||_t|_|j�dS)Nz{}: {!r})r7r8r�formatrAr@r:)rrBrrr�
set_result s

zFuture.set_resultcCs�|jtkrtdj|j|���t|t�r,|�}t|�tkr@td��||_t	|_|j
�tjrbd|_
nt||�|_|jj|jj�dS)Nz{}: {!r}zPStopIteration interacts badly with generators and cannot be raised into a FutureT)r7r8rrK�
isinstance�type�
StopIteration�	TypeErrorr5r@r:r
�PY34r4rZ
_tb_loggerrr<r)rr3rrr�
set_exception,s

zFuture.set_exceptionccs|j�sd|_|V|j�S)NT)r?�_asyncio_future_blockingrB)rrrr�__iter__DszFuture.__iter__) r'r(r)r8r7rAr5rrrSr4rr	Z_future_repr_infor1r2r
rQr&r;r:r>r?rBr3rErJrLrRrTZPY35�	__await__rrrrrns2

cCs|j�rdS|j|�dS)N)r>rL)ZfutrBrrr�_set_result_unless_cancelledSsrVcCsN|j�r|j�|j�sdS|j�}|dk	r8|j|�n|j�}|j|�dS)N)r>r;Zset_running_or_notify_cancelr3rRrBrL)�
concurrent�sourcer3rBrrr�_set_concurrent_future_stateZsrYcCsP|j�rdS|j�r|j�n.|j�}|dk	r:|j|�n|j�}|j|�dS)N)r>r;r3rRrBrL)rX�destr3rBrrr�_copy_future_stateis
r[cs�t��r"t�tjj�r"td��t��rDt�tjj�rDtd��t��rR�jnd�t��rd�jnd�dd�����fdd�}����fdd�}�j|��j|�dS)	Nz(A future is required for source argumentz-A future is required for destination argumentcSs"t|�rt||�n
t||�dS)N)rr[rY)r�otherrrr�
_set_state�sz!_chain_future.<locals>._set_statecs2|j�r.�dks��kr"�j�n�j�j�dS)N)r>r;�call_soon_threadsafe)�destination)�	dest_looprX�source_looprr�_call_check_cancel�s
z)_chain_future.<locals>._call_check_cancelcsJ�j�r�dk	r�j�rdS�dks,��kr8��|�n�j��|�dS)N)r>Z	is_closedr^)rX)r]r`r_rarr�_call_set_state�sz&_chain_future.<locals>._call_set_state)rrMrWZfuturesrrPrrE)rXr_rbrcr)r]r`r_rXrar�
_chain_future}s	
rd)r
cCs2t|�r|S|dkrtj�}|j�}t||�|S)N)rrr+Z
create_futurerd)rr
Z
new_futurerrrr�s
)�__all__Zconcurrent.futuresrWZloggingr.rrr	r
rrrrrr8r9r@�DEBUGZSTACK_DEBUGrrZ	_PyFuturerVrYr[rdrZ_asyncio�ImportErrorZ_CFuturerrrr�<module>s<

Pc*
PK[7�+��)__pycache__/__init__.cpython-36.opt-2.pycnu�[���3


 \��@s>ddlZyddlmZWnek
r4ddlZYnXejdkrnyddlmZWnek
rlddlZYnXddlTddlTddlTddl	Tddl
TddlTddlTddl
TddlTddlTddlTejejeje	je
jejeje
jejejejZejdk�r(ddlTeej7ZnddlTeej7ZdS)�N�)�	selectorsZwin32)�_overlapped)�*)�sys�r�ImportError�platformrZbase_eventsZ
coroutinesZeventsZfuturesZlocksZ	protocolsZqueuesZstreams�
subprocessZtasksZ
transports�__all__Zwindows_eventsZunix_events�rr�(/usr/lib64/python3.6/asyncio/__init__.py�<module>s6
:PK[D��o?o?0__pycache__/proactor_events.cpython-36.opt-2.pycnu�[���3


 \�O�@s�dgZddlZddlZddlmZddlmZddlmZddlmZddlmZdd	lm	Z	dd
l
mZGdd�de	je	j
�ZGd
d�dee	j�ZGdd�dee	j�ZGdd�de�ZGdd�deee	j�ZGdd�deee	j�ZGdd�dej�ZdS)�BaseProactorEventLoop�N�)�base_events)�compat)�	constants)�futures)�sslproto)�
transports)�loggercs~eZdZd�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jrTdd�Zddd�Z
dd�Zdd�Zdd�Z�ZS)�_ProactorBasePipeTransportNcs�t�j||�|j|�||_||_||_d|_d|_d|_d|_	d|_
d|_d|_|jdk	rh|jj
�|jj|jj|�|dk	r�|jjtj|d�dS)NrF)�super�__init__�
_set_extra�_sock�	_protocol�_server�_buffer�	_read_fut�
_write_fut�_pending_write�
_conn_lost�_closing�_eof_writtenZ_attach�_loop�	call_soonZconnection_maderZ_set_result_unless_cancelled)�self�loop�sock�protocol�waiter�extra�server)�	__class__��//usr/lib64/python3.6/asyncio/proactor_events.pyr
s$



z#_ProactorBasePipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jdk	rN|jd|jj��|jdk	rh|jd|j�|jdk	r�|jd|j�|jr�t	|j�}|jd|�|j
r�|jd�dd	j|�S)
N�closed�closingzfd=%szread=%szwrite=%rzwrite_bufsize=%szEOF writtenz<%s>� )r"�__name__r�appendr�filenorrr�lenr�join)r�info�bufsizer#r#r$�__repr__/s"







z#_ProactorBasePipeTransport.__repr__cCs||jd<dS)N�pipe)�_extra)rrr#r#r$rBsz%_ProactorBasePipeTransport._set_extracCs
||_dS)N)r)rrr#r#r$�set_protocolEsz'_ProactorBasePipeTransport.set_protocolcCs|jS)N)r)rr#r#r$�get_protocolHsz'_ProactorBasePipeTransport.get_protocolcCs|jS)N)r)rr#r#r$�
is_closingKsz%_ProactorBasePipeTransport.is_closingcCs^|jr
dSd|_|jd7_|jr@|jdkr@|jj|jd�|jdk	rZ|jj�d|_dS)NTr)	rrrrrr�_call_connection_lostr�cancel)rr#r#r$�closeNs

z _ProactorBasePipeTransport.closecCs*|jdk	r&tjd|t|d�|j�dS)Nzunclosed transport %r)�source)r�warnings�warn�ResourceWarningr7)rr#r#r$�__del__]s
z"_ProactorBasePipeTransport.__del__�Fatal error on pipe transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)�exc_info)�message�	exceptionZ	transportr)
�
isinstancerZ_FATAL_ERROR_IGNOREr�	get_debugr
�debug�call_exception_handlerr�_force_close)r�excr?r#r#r$�_fatal_errorcs
z'_ProactorBasePipeTransport._fatal_errorcCsj|jr
dSd|_|jd7_|jr4|jj�d|_|jrJ|jj�d|_d|_d|_|jj|j	|�dS)NTrr)
rrrr6rrrrrr5)rrFr#r#r$rEps

z'_ProactorBasePipeTransport._force_closecCs^z|jj|�Wdt|jd�r,|jjtj�|jj�d|_|j}|dk	rX|j	�d|_XdS)N�shutdown)
rZconnection_lost�hasattrrrH�socketZ	SHUT_RDWRr7rZ_detach)rrFr!r#r#r$r5s
z0_ProactorBasePipeTransport._call_connection_lostcCs"|j}|jdk	r|t|j�7}|S)N)rrr+)r�sizer#r#r$�get_write_buffer_size�s
z0_ProactorBasePipeTransport.get_write_buffer_size)NNN)r=)r(�
__module__�__qualname__r
r/rr2r3r4r7rZPY34r<rGrEr5rL�
__classcell__r#r#)r"r$rs

rcs8eZdZd
�fdd�	Zdd�Zdd�Zddd	�Z�ZS)�_ProactorReadPipeTransportNcs4t�j||||||�d|_d|_|jj|j�dS)NF)rr
�_paused�_reschedule_on_resumerr�
_loop_reading)rrrrrr r!)r"r#r$r
�sz#_ProactorReadPipeTransport.__init__cCs0|js|jrdSd|_|jj�r,tjd|�dS)NTz%r pauses reading)rrQrrBr
rC)rr#r#r$�
pause_reading�s

z(_ProactorReadPipeTransport.pause_readingcCsP|js|jrdSd|_|jr6|jj|j|j�d|_|jj�rLtj	d|�dS)NFz%r resumes reading)
rrQrRrrrSrrBr
rC)rr#r#r$�resume_reading�s
z)_ProactorReadPipeTransport.resume_readingcCs�|jrd|_dSd}�z"yH|dk	r0d|_|j�}|jr>d}dS|dkrJdS|jjj|jd�|_Wn�t	k
r�}z2|js�|j
|d�n|jj�r�tj
ddd�WYdd}~Xn�tk
r�}z|j|�WYdd}~Xn^tk
�r}z|j
|d�WYdd}~Xn0tjk
�r&|j�s"�YnX|jj|j�Wd|�rN|jj|�n:|dk	�r�|jj��rptj
d|�|jj�}|�s�|j�XdS)NT�iz"Fatal read error on pipe transportz*Read error on pipe transport while closing)r>z%r received EOF)rQrRr�resultrr�	_proactor�recvr�ConnectionAbortedErrorrGrBr
rC�ConnectionResetErrorrE�OSErrorr�CancelledError�add_done_callbackrSrZ
data_receivedZeof_receivedr7)r�fut�datarFZ	keep_openr#r#r$rS�sH


z(_ProactorReadPipeTransport._loop_reading)NNN)N)r(rMrNr
rTrUrSrOr#r#)r"r$rP�s

rPc@s6eZdZdd�Zddd�Zdd�Zdd	�Zd
d�ZdS)
�_ProactorBaseWritePipeTransportcCs�t|tttf�s&dt|�j}t|��|jr4td��|s<dS|j	rj|j	t
jkrXtj
d�|j	d7_	dS|jdkr�|jt|�d�n.|js�t|�|_|j�n|jj|�|j�dS)Nz3data argument must be a bytes-like object, not '%s'zwrite_eof() already calledzsocket.send() raised exception.r)r`)rA�bytes�	bytearray�
memoryview�typer(�	TypeErrorr�RuntimeErrorrrZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningr�
_loop_writingr�_maybe_pause_protocol�extend)rr`�msgr#r#r$�write�s(



z%_ProactorBaseWritePipeTransport.writeNcCsy�d|_d|_|r|j�|dkr.|j}d|_|sf|jrH|jj|jd�|jr\|j	j
tj�|j
�nN|jjj|j	|�|_|jj�s�t|�|_|jj|j�|j�n|jj|j�WnZtk
r�}z|j|�WYdd}~Xn0tk
�r}z|j|d�WYdd}~XnXdS)Nrz#Fatal write error on pipe transport)rrrWrrrrr5rrrHrJ�SHUT_WRZ_maybe_resume_protocolrX�send�doner+r^rirjr[rEr\rG)r�fr`rFr#r#r$ri
s0



z-_ProactorBaseWritePipeTransport._loop_writingcCsdS)NTr#)rr#r#r$�
can_write_eof0sz-_ProactorBaseWritePipeTransport.can_write_eofcCs|j�dS)N)r7)rr#r#r$�	write_eof3sz)_ProactorBaseWritePipeTransport.write_eofcCs|jd�dS)N)rE)rr#r#r$�abort6sz%_ProactorBaseWritePipeTransport.abort)NN)r(rMrNrmrirrrsrtr#r#r#r$ra�s
$
#racs$eZdZ�fdd�Zdd�Z�ZS)�_ProactorWritePipeTransportcs4t�j||�|jjj|jd�|_|jj|j�dS)N�)	rr
rrXrYrrr^�_pipe_closed)r�args�kw)r"r#r$r
;sz$_ProactorWritePipeTransport.__init__cCs@|j�rdS|jrdSd|_|jdk	r4|jt��n|j�dS)N)Z	cancelledrrrrE�BrokenPipeErrorr7)rr_r#r#r$rw@s
z(_ProactorWritePipeTransport._pipe_closed)r(rMrNr
rwrOr#r#)r"r$ru:sruc@seZdZdd�Zdd�ZdS)�_ProactorDuplexPipeTransportcCsdS)NFr#)rr#r#r$rrUsz*_ProactorDuplexPipeTransport.can_write_eofcCst�dS)N)�NotImplementedError)rr#r#r$rsXsz&_ProactorDuplexPipeTransport.write_eofN)r(rMrNrrrsr#r#r#r$r{Psr{cs6eZdZd
�fdd�	Zdd�Zdd�Zdd	�Z�ZS)�_ProactorSocketTransportNcs$t�j||||||�tj|�dS)N)rr
rZ_set_nodelay)rrrrrr r!)r"r#r$r
asz!_ProactorSocketTransport.__init__cCs�||jd<y|j�|jd<Wn4tjtfk
rP|jj�rLtjd|dd�YnXd|jkr�y|j	�|jd<Wn4tjtfk
r�|jj�r�tjd|dd�YnXdS)NrJZsocknamezgetsockname() failed on %rT)r>�peernamezgetpeername() failed on %r)
r1ZgetsocknamerJ�error�AttributeErrorrrBr
rhZgetpeername)rrr#r#r$rfs



z#_ProactorSocketTransport._set_extracCsdS)NTr#)rr#r#r$rrvsz&_ProactorSocketTransport.can_write_eofcCs2|js|jrdSd|_|jdkr.|jjtj�dS)NT)rrrrrHrJrn)rr#r#r$rsys

z"_ProactorSocketTransport.write_eof)NNN)r(rMrNr
rrrrsrOr#r#)r"r$r}\s
r}cs�eZdZ�fdd�Zd-dd�Zd.ddddd�dd	�Zd/d
d�Zd0dd
�Zd1dd�Z�fdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd2d d!�Zd"d#�Zd3d%d&�Zd'd(�Zd)d*�Zd+d,�Z�ZS)4rcsHt�j�tjd|jj�||_||_d|_i|_	|j
|�|j�dS)NzUsing proactor: %s)rr
r
rCr"r(rX�	_selector�_self_reading_future�_accept_futuresZset_loop�_make_self_pipe)rZproactor)r"r#r$r
�s

zBaseProactorEventLoop.__init__NcCst||||||�S)N)r})rrrrr r!r#r#r$�_make_socket_transport�s
z,BaseProactorEventLoop._make_socket_transportF)�server_side�server_hostnamer r!c
Cs<tj�std��tj||||||�}	t|||	||d�|	jS)NzOProactor event loop requires Python 3.5 or newer (ssl.MemoryBIO) to support SSL)r r!)rZ_is_sslproto_availabler|ZSSLProtocolr}Z_app_transport)
rZrawsockr�
sslcontextrr�r�r r!Zssl_protocolr#r#r$�_make_ssl_transport�s
z)BaseProactorEventLoop._make_ssl_transportcCst|||||�S)N)r{)rrrrr r#r#r$�_make_duplex_pipe_transport�sz1BaseProactorEventLoop._make_duplex_pipe_transportcCst|||||�S)N)rP)rrrrr r#r#r$�_make_read_pipe_transport�sz/BaseProactorEventLoop._make_read_pipe_transportcCst|||||�S)N)ru)rrrrr r#r#r$�_make_write_pipe_transport�sz0BaseProactorEventLoop._make_write_pipe_transportcsP|j�rtd��|j�rdS|j�|j�|jj�d|_d|_t�j�dS)Nz!Cannot close a running event loop)	Z
is_runningrg�	is_closed�_stop_accept_futures�_close_self_piperXr7r�r)r)r"r#r$r7�s
zBaseProactorEventLoop.closecCs|jj||�S)N)rXrY)rr�nr#r#r$�	sock_recv�szBaseProactorEventLoop.sock_recvcCs|jj||�S)N)rXro)rrr`r#r#r$�sock_sendall�sz"BaseProactorEventLoop.sock_sendallcCs|jj||�S)N)rXZconnect)rrZaddressr#r#r$�sock_connect�sz"BaseProactorEventLoop.sock_connectcCs|jj|�S)N)rX�accept)rrr#r#r$�sock_accept�sz!BaseProactorEventLoop.sock_acceptcCst�dS)N)r|)rr#r#r$�_socketpair�sz!BaseProactorEventLoop._socketpaircCsL|jdk	r|jj�d|_|jj�d|_|jj�d|_|jd8_dS)Nr)r�r6�_ssockr7�_csock�
_internal_fds)rr#r#r$r��s



z&BaseProactorEventLoop._close_self_pipecCsF|j�\|_|_|jjd�|jjd�|jd7_|j|j�dS)NFr)r�r�r�Zsetblockingr�r�_loop_self_reading)rr#r#r$r��s
z%BaseProactorEventLoop._make_self_pipecCs�y$|dk	r|j�|jj|jd�}WnHtjk
r:dStk
rl}z|jd||d��WYdd}~XnX||_|j	|j
�dS)Niz.Error on reading from the event loop self pipe)r?r@r)rWrXrYr�rr]�	ExceptionrDr�r^r�)rrqrFr#r#r$r��sz(BaseProactorEventLoop._loop_self_readingcCs|jjd�dS)N�)r�ro)rr#r#r$�_write_to_self�sz$BaseProactorEventLoop._write_to_self�dcs&d������fdd�	��j��dS)Ncs"y�|dk	rl|j�\}}�jr,tjd�||���}�dk	rV�j||�dd|i�d�n�j||d|i�d��j�rxdS�jj��}Wn~t	k
r�}zD�j
�dkr��jd|�d���j�n�jr�tjd	�dd
�WYdd}~Xn8t
jk
�r�j�YnX|�j�j
�<|j��dS)Nz#%r got a new connection from %r: %rTr~)r�r r!)r r!rzAccept failed on a socket)r?r@rJzAccept failed on socket %r)r>���)rWZ_debugr
rCr�r�r�rXr�r\r*rDr7rr]r�r^)rqZconnZaddrrrF)r�protocol_factoryrr!rr�r#r$r�s>


z2BaseProactorEventLoop._start_serving.<locals>.loop)N)r)rr�rr�r!Zbacklogr#)rr�rr!rr�r$�_start_serving�s$z$BaseProactorEventLoop._start_servingcCsdS)Nr#)rZ
event_listr#r#r$�_process_events sz%BaseProactorEventLoop._process_eventscCs*x|jj�D]}|j�qW|jj�dS)N)r��valuesr6�clear)rZfuturer#r#r$r�$sz*BaseProactorEventLoop._stop_accept_futurescCs |j�|jj|�|j�dS)N)r�rX�
_stop_servingr7)rrr#r#r$r�)sz#BaseProactorEventLoop._stop_serving)NNN)N)NN)NN)NN)N)NNr�)r(rMrNr
r�r�r�r�r�r7r�r�r�r�r�r�r�r�r�r�r�r�r�rOr#r#)r"r$r�s4







()�__all__rJr9�rrrrrr	�logr
Z_FlowControlMixinZ
BaseTransportrZ
ReadTransportrPZWriteTransportraruZ	Transportr{r}Z
BaseEventLooprr#r#r#r$�<module>s0MT
#PK[��)�#__pycache__/__init__.cpython-36.pycnu�[���3


 \��@sBdZddlZyddlmZWnek
r8ddlZYnXejdkrryddlmZWnek
rpddlZYnXddlTddlTddl	Tddl
TddlTddlTddl
TddlTddlTddlTddlTejeje	je
jejeje
jejejejejZejdk�r,ddlTeej7ZnddlTeej7ZdS)z'The asyncio package, tracking PEP 3156.�N�)�	selectorsZwin32)�_overlapped)�*)�__doc__�sys�r�ImportError�platformrZbase_eventsZ
coroutinesZeventsZfuturesZlocksZ	protocolsZqueuesZstreams�
subprocessZtasksZ
transports�__all__Zwindows_eventsZunix_events�r
r
�(/usr/lib64/python3.6/asyncio/__init__.py�<module>s8
:PK[P�f�#�#0__pycache__/base_subprocess.cpython-36.opt-1.pycnu�[���3


 \�#�@s�ddlZddlZddlZddlmZddlmZddlmZddlmZddl	m
Z
Gdd	�d	ej�ZGd
d�dej
�ZGdd
�d
eej�ZdS)�N�)�compat)�	protocols)�
transports)�	coroutine)�loggercs�eZdZd0�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jrTdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zed d!��Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zed*d+��Zd,d-�Zd.d/�Z�ZS)1�BaseSubprocessTransportNc
s&t�j|
�d|_||_||_d|_d|_d|_g|_t	j
�|_i|_d|_
|tjkr`d|jd<|tjkrtd|jd<|tjkr�d|jd<y"|jf||||||d�|��Wn|j��YnX|jj|_|j|jd<|jj��rt|ttf�r�|}n|d}tjd||j�|jj|j|	��dS)NFrr�)�args�shell�stdin�stdout�stderr�bufsize�
subprocesszprocess %r created: pid %s)�super�__init__�_closed�	_protocol�_loop�_proc�_pid�_returncode�
_exit_waiters�collections�deque�_pending_calls�_pipes�	_finishedr�PIPE�_start�close�pidZ_extra�	get_debug�
isinstance�bytes�strr�debugZcreate_task�_connect_pipes)
�self�loop�protocolr
rrr
rr�waiterZextra�kwargsZprogram)�	__class__��//usr/lib64/python3.6/asyncio/base_subprocess.pyrs@








z BaseSubprocessTransport.__init__cCs|jjg}|jr|jd�|jdk	r4|jd|j�|jdk	rP|jd|j�n |jdk	rf|jd�n
|jd�|jjd�}|dk	r�|jd|j�|jjd�}|jjd	�}|dk	r�||kr�|jd
|j�n0|dk	r�|jd|j�|dk	r�|jd|j�d
dj	|�S)N�closedzpid=%sz
returncode=%sZrunningznot startedrzstdin=%srr	zstdout=stderr=%sz	stdout=%sz	stderr=%sz<%s>� )
r.�__name__r�appendrrr�get�pipe�join)r)�inforr
rr/r/r0�__repr__9s,





z BaseSubprocessTransport.__repr__cKst�dS)N)�NotImplementedError)r)r
rrr
rrr-r/r/r0r VszBaseSubprocessTransport._startcCs
||_dS)N)r)r)r+r/r/r0�set_protocolYsz$BaseSubprocessTransport.set_protocolcCs|jS)N)r)r)r/r/r0�get_protocol\sz$BaseSubprocessTransport.get_protocolcCs|jS)N)r)r)r/r/r0�
is_closing_sz"BaseSubprocessTransport.is_closingcCs�|jr
dSd|_x&|jj�D]}|dkr*q|jj�qW|jdk	r�|jdkr�|jj�dkr�|jj	�rpt
jd|�y|jj�Wnt
k
r�YnXdS)NTz$Close running child process: kill %r)rr�valuesr6r!rrZpollrr#rZwarning�kill�ProcessLookupError)r)�protor/r/r0r!bs 


zBaseSubprocessTransport.closecCs&|js"tjd|t|d�|j�dS)Nzunclosed transport %r)�source)r�warnings�warn�ResourceWarningr!)r)r/r/r0�__del__�szBaseSubprocessTransport.__del__cCs|jS)N)r)r)r/r/r0�get_pid�szBaseSubprocessTransport.get_pidcCs|jS)N)r)r)r/r/r0�get_returncode�sz&BaseSubprocessTransport.get_returncodecCs||jkr|j|jSdSdS)N)rr6)r)�fdr/r/r0�get_pipe_transport�s
z*BaseSubprocessTransport.get_pipe_transportcCs|jdkrt��dS)N)rr@)r)r/r/r0�_check_proc�s
z#BaseSubprocessTransport._check_proccCs|j�|jj|�dS)N)rKr�send_signal)r)�signalr/r/r0rL�sz#BaseSubprocessTransport.send_signalcCs|j�|jj�dS)N)rKr�	terminate)r)r/r/r0rN�sz!BaseSubprocessTransport.terminatecCs|j�|jj�dS)N)rKrr?)r)r/r/r0r?�szBaseSubprocessTransport.killc	#sPy�j}�j}|jdk	rB|j�fdd�|j�EdH\}}|�jd<|jdk	rv|j�fdd�|j�EdH\}}|�jd<|jdk	r�|j�fdd�|j�EdH\}}|�jd<|j�j	j
��x"�jD]\}}|j|f|��q�Wd�_WnDtk
�r*}z&|dk	�r|j
��r|j|�WYdd}~Xn"X|dk	�rL|j
��rL|jd�dS)Ncs
t�d�S)Nr)�WriteSubprocessPipeProtor/)r)r/r0�<lambda>�sz8BaseSubprocessTransport._connect_pipes.<locals>.<lambda>rcs
t�d�S)Nr)�ReadSubprocessPipeProtor/)r)r/r0rP�srcs
t�d�S)Nr	)rQr/)r)r/r0rP�sr	)rrrZconnect_write_piperr
Zconnect_read_piper�	call_soonr�connection_mader�	Exception�	cancelledZ
set_exception�
set_result)	r)r,�procr*�_r6�callback�data�excr/)r)r0r(�s6









z&BaseSubprocessTransport._connect_pipescGs2|jdk	r|jj||f�n|jj|f|��dS)N)rr4rrR)r)�cbrZr/r/r0�_call�s
zBaseSubprocessTransport._callcCs|j|jj||�|j�dS)N)r]rZpipe_connection_lost�_try_finish)r)rIr[r/r/r0�_pipe_connection_lost�sz-BaseSubprocessTransport._pipe_connection_lostcCs|j|jj||�dS)N)r]rZpipe_data_received)r)rIrZr/r/r0�_pipe_data_received�sz+BaseSubprocessTransport._pipe_data_receivedcCst|jj�rtjd||�||_|jjdkr2||j_|j|jj	�|j
�x |jD]}|j�sP|j
|�qPWd|_dS)Nz%r exited with return code %r)rr#rr8rr�
returncoder]rZprocess_exitedr^rrUrV)r)rar,r/r/r0�_process_exited�s
z'BaseSubprocessTransport._process_exitedccs0|jdk	r|jS|jj�}|jj|�|EdHS)zdWait until the process exit and return the process return code.

        This method is a coroutine.N)rrZ
create_futurerr4)r)r,r/r/r0�_wait�s


zBaseSubprocessTransport._waitcCs>|jdkrdStdd�|jj�D��r:d|_|j|jd�dS)Ncss|]}|dk	o|jVqdS)N)�disconnected)�.0�pr/r/r0�	<genexpr>�sz6BaseSubprocessTransport._try_finish.<locals>.<genexpr>T)r�allrr>rr]�_call_connection_lost)r)r/r/r0r^�s
z#BaseSubprocessTransport._try_finishcCs*z|jj|�Wdd|_d|_d|_XdS)N)r�connection_lostrr)r)r[r/r/r0ri�s
z-BaseSubprocessTransport._call_connection_lost)NN)r3�
__module__�__qualname__rr9r r;r<r=r!rZPY34rFrGrHrJrKrLrNr?rr(r]r_r`rbrcr^ri�
__classcell__r/r/)r.r0rs0)%	rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rOcCs||_||_d|_d|_dS)NF)rWrIr6rd)r)rWrIr/r/r0rsz!WriteSubprocessPipeProto.__init__cCs
||_dS)N)r6)r)Z	transportr/r/r0rSsz(WriteSubprocessPipeProto.connection_madecCsd|jj|j|jfS)Nz<%s fd=%s pipe=%r>)r.r3rIr6)r)r/r/r0r9sz!WriteSubprocessPipeProto.__repr__cCs d|_|jj|j|�d|_dS)NT)rdrWr_rI)r)r[r/r/r0rjsz(WriteSubprocessPipeProto.connection_lostcCs|jjj�dS)N)rWr�
pause_writing)r)r/r/r0rnsz&WriteSubprocessPipeProto.pause_writingcCs|jjj�dS)N)rWr�resume_writing)r)r/r/r0rosz'WriteSubprocessPipeProto.resume_writingN)	r3rkrlrrSr9rjrnror/r/r/r0rOsrOc@seZdZdd�ZdS)rQcCs|jj|j|�dS)N)rWr`rI)r)rZr/r/r0�
data_received$sz%ReadSubprocessPipeProto.data_receivedN)r3rkrlrpr/r/r/r0rQ!srQ)rrrC�rrrZ
coroutinesr�logrZSubprocessTransportrZBaseProtocolrOZProtocolrQr/r/r/r0�<module>s{PK[VWX�EE%__pycache__/test_utils.cpython-36.pycnu�[���3


 \�:�
@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddl
mZddlmZddlmZmZyddlZWnek
r�dZYnXddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddl m!Z!ddl"m#Z#e	j$dk�rHddl%m&Z&nddlm&Z&dd�Z'e'd�Z(e'd�Z)dd�Z*dd�Z+dRdd�Z,dd�Z-Gdd �d e�Z.Gd!d"�d"e�Z/Gd#d$�d$�Z0Gd%d&�d&e0e/�Z1d'd(�d)d*�Z2e3ed+��rZGd,d-�d-ej4e�Z5Gd.d/�d/e5e�Z6Gd0d1�d1e6�Z7Gd2d3�d3e0e7�Z8d4d5�Z9ej:d6d7��Z;ej:d'd(�d8d9��Z<ej:d:dd'd;�d<d=��Z=d>d?�Z>Gd@dA�dAej?�Z@GdBdC�dCejA�ZBdDdE�ZCGdFdG�dGeD�ZEdHdI�ZFGdJdK�dKe
jG�ZGej:dLdM��ZHejIejJejKfdNdO�ZLdPdQ�ZMdS)SzUtilities shared by tests.�N)�mock)�
HTTPServer)�WSGIRequestHandler�
WSGIServer�)�base_events)�compat)�events)�futures)�	selectors)�tasks)�	coroutine)�logger)�supportZwin32)�
socketpaircCs`ttd�r*tjjtj|�}tjj|�r*|Stjjtjjtj�d|�}tjj|�rT|St	|��dS)N�
TEST_HOME_DIR�test)
�hasattrr�os�path�joinr�isfile�dirname�__file__�FileNotFoundError)�filename�fullname�r�*/usr/lib64/python3.6/asyncio/test_utils.py�	data_file-s
rzssl_cert.pemzssl_key.pemcCstdkrdStjtj�SdS)N)�ssl�
SSLContextZPROTOCOL_SSLv23rrrr�dummy_ssl_context<sr"c
Cs@tdd��}|�}|j|�}d|_z|j|�Wd|j�XdS)NcSsdS)Nrrrrr�onceDszrun_briefly.<locals>.onceF)r
Zcreate_taskZ_log_destroy_pending�run_until_complete�close)�loopr#�gen�trrr�run_brieflyCs
r)�cCsTtj�|}xB|�sN|dk	r8|tj�}|dkr8tj��|jtjd|d��qWdS)Nrg����MbP?)r&)�timer
�TimeoutErrorr$rZsleep)r&Zpred�timeoutZdeadlinerrr�	run_untilRsr.cCs|j|j�|j�dS)z�Legacy API to run once through the event loop.

    This is the recommended pattern for test code.  It will poll the
    selector once and run all callbacks scheduled in response to I/O
    events.
    N)Z	call_soon�stopZrun_forever)r&rrr�run_once\sr0c@seZdZdd�Zdd�ZdS)�SilentWSGIRequestHandlercCstj�S)N)�io�StringIO)�selfrrr�
get_stderrisz#SilentWSGIRequestHandler.get_stderrcGsdS)Nr)r4�format�argsrrr�log_messagelsz$SilentWSGIRequestHandler.log_messageN)�__name__�
__module__�__qualname__r5r8rrrrr1gsr1cs(eZdZdZ�fdd�Zdd�Z�ZS)�SilentWSGIServer�cs"t�j�\}}|j|j�||fS)N)�super�get_request�
settimeout�request_timeout)r4�request�client_addr)�	__class__rrr?tszSilentWSGIServer.get_requestcCsdS)Nr)r4rB�client_addressrrr�handle_erroryszSilentWSGIServer.handle_error)r9r:r;rAr?rF�
__classcell__rr)rDrr<psr<c@seZdZdd�ZdS)�SSLWSGIServerMixincCs^t}t}tj�}|j||�|j|dd�}y|j|||�|j�Wntk
rXYnXdS)NT)Zserver_side)	�ONLYKEY�ONLYCERTr r!Zload_cert_chainZwrap_socketZRequestHandlerClassr%�OSError)r4rBrEZkeyfileZcertfile�contextZssockrrr�finish_requestsz!SSLWSGIServerMixin.finish_requestN)r9r:r;rMrrrrrH}srHc@seZdZdS)�
SSLWSGIServerN)r9r:r;rrrrrN�srNF)�use_sslc
#svdd�}|r|n|}||t���j|��j�_tj�fdd�d�}|j�z
�VWd�j��j�|j	�XdS)NcSsd}dg}|||�dgS)Nz200 OK�Content-type�
text/plainsTest message)rPrQr)�environZstart_responseZstatusZheadersrrr�app�s
z_run_test_server.<locals>.appcs�jdd�S)Ng�������?)Z
poll_interval)Z
serve_foreverr)�httpdrr�<lambda>�sz"_run_test_server.<locals>.<lambda>)�target)
r1Zset_appZserver_address�address�	threadingZThread�start�shutdownZserver_closer)rWrO�
server_cls�server_ssl_clsrSZserver_classZ
server_threadr)rTr�_run_test_server�s


r]ZAF_UNIXc@seZdZdd�ZdS)�UnixHTTPServercCstjj|�d|_d|_dS)Nz	127.0.0.1�P)�socketserver�UnixStreamServer�server_bindZserver_nameZserver_port)r4rrrrb�szUnixHTTPServer.server_bindN)r9r:r;rbrrrrr^�sr^cs(eZdZdZdd�Z�fdd�Z�ZS)�UnixWSGIServerr=cCstj|�|j�dS)N)r^rbZ
setup_environ)r4rrrrb�s
zUnixWSGIServer.server_bindcs"t�j�\}}|j|j�|dfS)N�	127.0.0.1�)rdre)r>r?r@rA)r4rBrC)rDrrr?�szUnixWSGIServer.get_request)r9r:r;rArbr?rGrr)rDrrc�srcc@seZdZdd�ZdS)�SilentUnixWSGIServercCsdS)Nr)r4rBrErrrrF�sz!SilentUnixWSGIServer.handle_errorN)r9r:r;rFrrrrrf�srfc@seZdZdS)�UnixSSLWSGIServerN)r9r:r;rrrrrg�srgc	Cstj��}|jSQRXdS)N)�tempfileZNamedTemporaryFile�name)�filerrr�gen_unix_socket_path�s
rkccs<t�}z
|VWdytj|�Wntk
r4YnXXdS)N)rkr�unlinkrK)rrrr�unix_socket_path�s
rmc
cs,t��}t||ttd�EdHWdQRXdS)N)rWrOr[r\)rmr]rfrg)rOrrrr�run_test_unix_server�srnz	127.0.0.1)�host�portrOccst||f|ttd�EdHdS)N)rWrOr[r\)r]r<rN)rorprOrrr�run_test_server�s
rqcCsPi}x4t|�D](}|jd�r(|jd�r(qtdd�||<qWtd|f|j|��S)N�__)�return_valueZTestProtocol)�dir�
startswith�endswith�MockCallback�type�	__bases__)�baseZdctrirrr�make_test_protocol�sr{c@s6eZdZdd�Zddd�Zdd�Zdd	�Zd
d�ZdS)
�TestSelectorcCs
i|_dS)N)�keys)r4rrr�__init__szTestSelector.__init__NcCstj|d||�}||j|<|S)Nr)rZSelectorKeyr})r4�fileobjr	�data�keyrrr�registers
zTestSelector.registercCs|jj|�S)N)r}�pop)r4rrrr�
unregisterszTestSelector.unregistercCsgS)Nr)r4r-rrr�selectszTestSelector.selectcCs|jS)N)r})r4rrr�get_mapszTestSelector.get_map)N)r9r:r;r~r�r�r�r�rrrrr|s

r|cs�eZdZdZd-�fdd�	Zdd�Zdd�Z�fd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Z�fd%d&�Z�fd'd(�Zd)d*�Zd+d,�Z�ZS).�TestLoopa�Loop for unittests.

    It manages self time directly.
    If something scheduled to be executed later then
    on next loop iteration after all ready handlers done
    generator passed to __init__ is calling.

    Generator should be like this:

        def gen():
            ...
            when = yield ...
            ... = yield time_advance

    Value returned by yield is absolute time of next scheduled handler.
    Value passed to yield is time advance to move loop's time forward.
    Ncsvt�j�|dkr"dd�}d|_nd|_|�|_t|j�d|_d|_g|_t�|_	i|_
i|_|j�t
j�|_dS)Ncss
dVdS)Nrrrrrr',szTestLoop.__init__.<locals>.genFTrg��&�.>)r>r~�_check_on_close�_gen�next�_timeZ_clock_resolution�_timersr|Z	_selector�readers�writers�reset_counters�weakref�WeakValueDictionary�_transports)r4r')rDrrr~(s

zTestLoop.__init__cCs|jS)N)r�)r4rrrr+?sz
TestLoop.timecCs|r|j|7_dS)zMove test time forward.N)r�)r4�advancerrr�advance_timeBszTestLoop.advance_timecsBt�j�|jr>y|jjd�Wntk
r4Yn
Xtd��dS)NrzTime generator is not finished)r>r%r�r��send�
StopIteration�AssertionError)r4)rDrrr%Gs
zTestLoop.closecGstj|||�|j|<dS)N)r	�Handler�)r4�fd�callbackr7rrr�_add_readerQszTestLoop._add_readercCs0|j|d7<||jkr(|j|=dSdSdS)NrTF)�remove_reader_countr�)r4r�rrr�_remove_readerTs

zTestLoop._remove_readercGsh||jkrtd|�d���|j|}|j|krDtd|j�d|����|j|krdtd|j�d|����dS)Nzfd z is not registeredzunexpected callback: z != zunexpected callback args: )r�r��	_callback�_args)r4r�r�r7�handlerrr�
assert_reader\s



zTestLoop.assert_readercCs||jkrtd|�d���dS)Nzfd z is registered)r�r�)r4r�rrr�assert_no_readergs
zTestLoop.assert_no_readercGstj|||�|j|<dS)N)r	r�r�)r4r�r�r7rrr�_add_writerkszTestLoop._add_writercCs0|j|d7<||jkr(|j|=dSdSdS)NrTF)�remove_writer_countr�)r4r�rrr�_remove_writerns

zTestLoop._remove_writercGs^||jkstdj|���|j|}|j|ks>tdj|j|���|j|ksZtdj|j|���dS)Nzfd {} is not registeredz{!r} != {!r})r�r�r6r�r�)r4r�r�r7r�rrr�
assert_writervs
zTestLoop.assert_writercCs8y|j|}Wntk
r"YnXtdj||���dS)Nz.File descriptor {!r} is used by transport {!r})r��KeyError�RuntimeErrorr6)r4r�Z	transportrrr�_ensure_fd_no_transport~sz TestLoop._ensure_fd_no_transportcGs|j|�|j||f|��S)zAdd a reader callback.)r�r�)r4r�r�r7rrr�
add_reader�s
zTestLoop.add_readercCs|j|�|j|�S)zRemove a reader callback.)r�r�)r4r�rrr�
remove_reader�s
zTestLoop.remove_readercGs|j|�|j||f|��S)zAdd a writer callback..)r�r�)r4r�r�r7rrr�
add_writer�s
zTestLoop.add_writercCs|j|�|j|�S)zRemove a writer callback.)r�r�)r4r�rrr�
remove_writer�s
zTestLoop.remove_writercCstjt�|_tjt�|_dS)N)�collections�defaultdict�intr�r�)r4rrrr��szTestLoop.reset_counterscs:t�j�x$|jD]}|jj|�}|j|�qWg|_dS)N)r>�	_run_oncer�r�r�r�)r4�whenr�)rDrrr��s

zTestLoop._run_oncecs |jj|�t�j||f|��S)N)r��appendr>�call_at)r4r�r�r7)rDrrr��szTestLoop.call_atcCsdS)Nr)r4Z
event_listrrr�_process_events�szTestLoop._process_eventscCsdS)Nr)r4rrr�_write_to_self�szTestLoop._write_to_self)N)r9r:r;�__doc__r~r+r�r%r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rGrr)rDrr�s,

r�cKstjfddgi|��S)N�spec�__call__)rZMock)�kwargsrrrrw�srwc@seZdZdZdd�ZdS)�MockPatternz�A regex based str with a fuzzy __eq__.

    Use this helper with 'mock.assert_called_with', or anywhere
    where a regex comparison between strings is needed.

    For instance:
       mock_call.assert_called_with(MockPattern('spam.*ham'))
    cCsttjt|�|tj��S)N)�bool�re�search�str�S)r4�otherrrr�__eq__�szMockPattern.__eq__N)r9r:r;r�r�rrrrr��sr�cCs$tj|�}|dkr td|f��|S)Nzunable to get the source of %r)r	Z_get_function_source�
ValueError)�func�sourcerrr�get_function_source�s
r�c@sVeZdZedd��Zdd�dd�Zddd	�Zd
d�Zdd
�Zdd�Z	e
jsRdd�ZdS)�TestCasecCs&|j}|dk	r|jdd�|j�dS)NT)�wait)Z_default_executorrZr%)r&Zexecutorrrr�
close_loop�szTestCase.close_loopT)�cleanupcCs,|dk	st�tjd�|r(|j|j|�dS)N)r�r	�set_event_loopZ
addCleanupr�)r4r&r�rrrr��s
zTestCase.set_event_loopNcCst|�}|j|�|S)N)r�r�)r4r'r&rrr�
new_test_loop�s
zTestCase.new_test_loopcCs|jt_dS)N)�_get_running_loopr	)r4rrr�unpatch_get_running_loop�sz!TestCase.unpatch_get_running_loopcCs tj|_dd�t_tj�|_dS)NcSsdS)NrrrrrrU�sz TestCase.setUp.<locals>.<lambda>)r	r�rZthreading_setup�_thread_cleanup)r4rrr�setUp�s
zTestCase.setUpcCsB|j�tjd�|jtj�d�|j�tj|j	�tj
�dS)N)NNN)r�r	r�ZassertEqual�sys�exc_infoZ
doCleanupsrZthreading_cleanupr�Z
reap_children)r4rrr�tearDown�s
zTestCase.tearDowncOsGdd�d�}|�S)Nc@seZdZdd�Zdd�ZdS)z!TestCase.subTest.<locals>.EmptyCMcSsdS)Nr)r4rrr�	__enter__�sz+TestCase.subTest.<locals>.EmptyCM.__enter__cWsdS)Nr)r4�excrrr�__exit__�sz*TestCase.subTest.<locals>.EmptyCM.__exit__N)r9r:r;r�r�rrrr�EmptyCM�sr�r)r4r7r�r�rrr�subTest�szTestCase.subTest)N)
r9r:r;�staticmethodr�r�r�r�r�r�rZPY34r�rrrrr��s

r�ccs2tj}ztjtjd�dVWdtj|�XdS)zrContext manager to disable asyncio logger.

    For example, it can be used to ignore warnings in debug mode.
    rN)r�levelZsetLevel�loggingZCRITICAL)Z	old_levelrrr�disable_logger�s

r�cCs*tjtj�}||_||_||_d|j_|S)z'Create a mock of a non-blocking socket.g)rZ	MagicMock�socket�protorx�familyZ
gettimeoutrs)r�rxr�Zsockrrr�mock_nonblocking_socketsr�cCstjddd�S)Nz'asyncio.sslproto._is_sslproto_availableF)rs)rZpatchrrrr�force_legacy_ssl_supportsr�)r*)Nr�r��
contextlibr2r�rr�r�r`r�rhrXr+Zunittestr�rZhttp.serverrZwsgiref.simple_serverrrr �ImportErrorrerrr	r
rrZ
coroutinesr
�logrrr�platformZ
windows_utilsrrrJrIr"r)r.r0r1r<rHrNr]rrar^rcrfrgrk�contextmanagerrmrnrqr{ZBaseSelectorr|Z
BaseEventLoopr�rwr�r�r�r�r�ZIPPROTO_TCPZSOCK_STREAMZAF_INETr�r�rrrr�<module>s�


	


4
PK[�;�.4.4(__pycache__/streams.cpython-36.opt-2.pycnu�[���3


 \�_�@sHdddddddgZddlZeed	�r2ejd
dg�dd
lmZddlmZddlmZddlmZddlm	Z	ddl
mZd!ZGdd�de
�ZGdd�de�Ze	d"ded�dd��Ze	d#ded�dd��Zeed	��re	d$ded�dd
��Ze	d%ded�dd��ZGdd�dej�ZGdd�deej�ZGdd�d�ZGd d�d�ZdS)&�StreamReader�StreamWriter�StreamReaderProtocol�open_connection�start_server�IncompleteReadError�LimitOverrunError�NZAF_UNIX�open_unix_connection�start_unix_server�)�
coroutines)�compat)�events)�	protocols)�	coroutine)�logger��cs$eZdZ�fdd�Zdd�Z�ZS)rcs(t�jdt|�|f�||_||_dS)Nz-%d bytes read on a total of %r expected bytes)�super�__init__�len�partial�expected)�selfrr)�	__class__��'/usr/lib64/python3.6/asyncio/streams.pyr szIncompleteReadError.__init__cCst|�|j|jffS)N)�typerr)rrrr�
__reduce__&szIncompleteReadError.__reduce__)�__name__�
__module__�__qualname__rr�
__classcell__rr)rrrscs$eZdZ�fdd�Zdd�Z�ZS)rcst�j|�||_dS)N)rr�consumed)r�messager#)rrrr0szLimitOverrunError.__init__cCst|�|jd|jffS)Nr)r�argsr#)rrrrr4szLimitOverrunError.__reduce__)rr r!rrr"rr)rrr*s)�loop�limitc	+sb|dkrtj�}t||d�}t||d��|j�fdd�||f|�EdH\}}t|�||�}||fS)N)r'r&)r&cs�S)Nrr)�protocolrr�<lambda>Qsz!open_connection.<locals>.<lambda>)r�get_event_looprrZcreate_connectionr)	�host�portr&r'�kwds�reader�	transport�_�writerr)r(rr8s c+s8�dkrtj�����fdd�}�j|||f|�EdHS)Ncst��d�}t|��d�}|S)N)r'r&)r&)rr)r.r()�client_connected_cbr'r&rr�factoryqszstart_server.<locals>.factory)rr*Z
create_server)r2r+r,r&r'r-r3r)r2r'r&rrVsc+s`|dkrtj�}t||d�}t||d��|j�fdd�|f|�EdH\}}t|�||�}||fS)N)r'r&)r&cs�S)Nrr)r(rrr)�sz&open_unix_connection.<locals>.<lambda>)rr*rrZcreate_unix_connectionr)�pathr&r'r-r.r/r0r1r)r(rr	}sc+s6�dkrtj�����fdd�}�j||f|�EdHS)Ncst��d�}t|��d�}|S)N)r'r&)r&)rr)r.r()r2r'r&rrr3�sz"start_unix_server.<locals>.factory)rr*Zcreate_unix_server)r2r4r&r'r-r3r)r2r'r&rr
�sc@s:eZdZddd�Zdd�Zdd�Zdd	�Zed
d��ZdS)
�FlowControlMixinNcCs0|dkrtj�|_n||_d|_d|_d|_dS)NF)rr*�_loop�_paused�
_drain_waiter�_connection_lost)rr&rrrr�szFlowControlMixin.__init__cCs d|_|jj�rtjd|�dS)NTz%r pauses writing)r7r6�	get_debugr�debug)rrrr�
pause_writing�s
zFlowControlMixin.pause_writingcCsFd|_|jj�rtjd|�|j}|dk	rBd|_|j�sB|jd�dS)NFz%r resumes writing)r7r6r:rr;r8�done�
set_result)r�waiterrrr�resume_writing�s
zFlowControlMixin.resume_writingcCsVd|_|jsdS|j}|dkr"dSd|_|j�r4dS|dkrH|jd�n
|j|�dS)NT)r9r7r8r=r>�
set_exception)r�excr?rrr�connection_lost�sz FlowControlMixin.connection_lostccs<|jrtd��|jsdS|j}|jj�}||_|EdHdS)NzConnection lost)r9�ConnectionResetErrorr7r8r6�
create_future)rr?rrr�
_drain_helper�s
zFlowControlMixin._drain_helper)N)	rr r!rr<r@rCrrFrrrrr5�s


	r5csBeZdZd�fdd�	Zdd�Z�fdd�Zdd	�Zd
d�Z�ZS)
rNcs*t�j|d�||_d|_||_d|_dS)N)r&F)rr�_stream_reader�_stream_writer�_client_connected_cb�	_over_ssl)rZ
stream_readerr2r&)rrrr�s
zStreamReaderProtocol.__init__cCsd|jj|�|jd�dk	|_|jdk	r`t|||j|j�|_|j|j|j�}tj	|�r`|jj
|�dS)NZ
sslcontext)rG�
set_transport�get_extra_inforJrIrr6rHrZiscoroutineZcreate_task)rr/�resrrr�connection_made�s


z$StreamReaderProtocol.connection_madecsF|jdk	r*|dkr|jj�n|jj|�t�j|�d|_d|_dS)N)rG�feed_eofrArrCrH)rrB)rrrrC�s
z$StreamReaderProtocol.connection_lostcCs|jj|�dS)N)rG�	feed_data)r�datarrr�
data_receivedsz"StreamReaderProtocol.data_receivedcCs|jj�|jrdSdS)NFT)rGrOrJ)rrrr�eof_receiveds
z!StreamReaderProtocol.eof_received)NN)	rr r!rrNrCrRrSr"rr)rrr�s
	
c@sfeZdZdd�Zdd�Zedd��Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zddd�Ze
dd��ZdS)rcCs||_||_||_||_dS)N)�
_transport�	_protocol�_readerr6)rr/r(r.r&rrrrszStreamWriter.__init__cCs:|jjd|jg}|jdk	r,|jd|j�ddj|�S)Nztransport=%rz	reader=%rz<%s>� )rrrTrV�append�join)r�inforrr�__repr__!s
zStreamWriter.__repr__cCs|jS)N)rT)rrrrr/'szStreamWriter.transportcCs|jj|�dS)N)rT�write)rrQrrrr\+szStreamWriter.writecCs|jj|�dS)N)rT�
writelines)rrQrrrr].szStreamWriter.writelinescCs
|jj�S)N)rT�	write_eof)rrrrr^1szStreamWriter.write_eofcCs
|jj�S)N)rT�
can_write_eof)rrrrr_4szStreamWriter.can_write_eofcCs
|jj�S)N)rT�close)rrrrr`7szStreamWriter.closeNcCs|jj||�S)N)rTrL)r�name�defaultrrrrL:szStreamWriter.get_extra_infoccsN|jdk	r |jj�}|dk	r |�|jdk	r:|jj�r:dV|jj�EdHdS)N)rV�	exceptionrTZ
is_closingrUrF)rrBrrr�drain=s	



zStreamWriter.drain)N)rr r!rr[�propertyr/r\r]r^r_r`rLrrdrrrrrs

c@s�eZdZedfdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
edd��Zedd��Zed'dd��Zed)dd��Zed d!��Zejr�ed"d#��Zed$d%��Zejr�d&d#�ZdS)*rNcCsZ|dkrtd��||_|dkr*tj�|_n||_t�|_d|_d|_d|_	d|_
d|_dS)NrzLimit cannot be <= 0F)�
ValueError�_limitrr*r6�	bytearray�_buffer�_eof�_waiter�
_exceptionrTr7)rr'r&rrrrXszStreamReader.__init__cCs�dg}|jr |jdt|j��|jr0|jd�|jtkrJ|jd|j�|jr`|jd|j�|jrv|jd|j�|jr�|jd|j�|j	r�|jd�d	d
j
|�S)Nrz%d bytes�eofzl=%dzw=%rze=%rzt=%rZpausedz<%s>rW)rirXrrjrg�_DEFAULT_LIMITrkrlrTr7rY)rrZrrrr[ks 


zStreamReader.__repr__cCs|jS)N)rl)rrrrrc}szStreamReader.exceptioncCs0||_|j}|dk	r,d|_|j�s,|j|�dS)N)rlrk�	cancelledrA)rrBr?rrrrA�szStreamReader.set_exceptioncCs*|j}|dk	r&d|_|j�s&|jd�dS)N)rkror>)rr?rrr�_wakeup_waiter�s
zStreamReader._wakeup_waitercCs
||_dS)N)rT)rr/rrrrK�szStreamReader.set_transportcCs*|jr&t|j�|jkr&d|_|jj�dS)NF)r7rrirgrT�resume_reading)rrrr�_maybe_resume_transport�sz$StreamReader._maybe_resume_transportcCsd|_|j�dS)NT)rjrp)rrrrrO�szStreamReader.feed_eofcCs|jo|jS)N)rjri)rrrr�at_eof�szStreamReader.at_eofcCsv|sdS|jj|�|j�|jdk	rr|jrrt|j�d|jkrry|jj�Wntk
rjd|_YnXd|_dS)NrT)	ri�extendrprTr7rrgZ
pause_reading�NotImplementedError)rrQrrrrP�s
zStreamReader.feed_dataccsV|jdk	rtd|��|jr,d|_|jj�|jj�|_z|jEdHWdd|_XdS)NzH%s() called while another coroutine is already waiting for incoming dataF)rk�RuntimeErrorr7rTrqr6rE)rZ	func_namerrr�_wait_for_data�s


zStreamReader._wait_for_dataccs�d}t|�}y|j|�EdH}Wn�tk
rB}z|jSd}~Xnftk
r�}zJ|jj||j�rv|jd|j|�=n
|jj�|j	�t
|jd��WYdd}~XnX|S)N�
r)r�	readuntilrrrri�
startswithr#�clearrrrfr%)r�sep�seplen�line�errr�readline�s
 zStreamReader.readlinerxccs�t|�}|dkrtd��|jdk	r(|j�d}x�t|j�}|||kr||jj||�}|dkr\P|d|}||jkr|td|��|jr�t|j�}|jj	�t
|d��|jd�EdHq.W||jkr�td|��|jd||�}|jd||�=|j�t|�S)Nrz,Separator should be at least one-byte stringrz2Separator is not found, and chunk exceed the limitryz2Separator is found, but chunk is longer than limit���)
rrfrlri�findrgrrj�bytesr{rrwrr)rZ	separatorr}�offsetZbuflenZisep�chunkrrrry�s:






zStreamReader.readuntilrccs�|jdk	r|j�|dkrdS|dkrZg}x&|j|j�EdH}|sBP|j|�q*Wdj|�S|jrz|jrz|jd�EdHt|jd|��}|jd|�=|j	�|S)Nr��read)
rlr�rgrXrYrirjrwr�rr)r�nZblocks�blockrQrrrr�Ps$

zStreamReader.readccs�|dkrtd��|jdk	r |j�|dkr,dSxFt|j�|krr|jr`t|j�}|jj�t||��|jd�EdHq.Wt|j�|kr�t|j�}|jj�nt|jd|��}|jd|�=|j	�|S)Nrz*readexactly size can not be less than zeror��readexactly)
rfrlrrirjr�r{rrwrr)rr�Z
incompleterQrrrr��s&




zStreamReader.readexactlycCs|S)Nr)rrrr�	__aiter__�szStreamReader.__aiter__ccs|j�EdH}|dkrt�|S)Nr�)r��StopAsyncIteration)r�valrrr�	__anext__�szStreamReader.__anext__cCs|S)Nr)rrrrr��s)rxr�)r�)rr r!rnrr[rcrArprKrrrOrsrPrrwr�ryr�r�r
ZPY35r�r�ZPY352rrrrrVs,	 [2*i)NN)NN)N)N)�__all__Zsocket�hasattrrt�rr
rrr�logrrn�EOFErrorr�	Exceptionrrrr	r
ZProtocolr5rrrrrrr�<module>s@
"B3GPK[�`���*__pycache__/protocols.cpython-36.opt-2.pycnu�[���3


 \��@sNddddgZGdd�d�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)	�BaseProtocol�Protocol�DatagramProtocol�SubprocessProtocolc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
rcCsdS)N�)�selfZ	transportrr�)/usr/lib64/python3.6/asyncio/protocols.py�connection_madeszBaseProtocol.connection_madecCsdS)Nr)r�excrrr�connection_lostszBaseProtocol.connection_lostcCsdS)Nr)rrrr�
pause_writing!szBaseProtocol.pause_writingcCsdS)Nr)rrrr�resume_writing7szBaseProtocol.resume_writingN)�__name__�
__module__�__qualname__rr
rrrrrrrs
c@seZdZdd�Zdd�ZdS)rcCsdS)Nr)r�datarrr�
data_receivedXszProtocol.data_receivedcCsdS)Nr)rrrr�eof_received^szProtocol.eof_receivedN)r
rrrrrrrrr>sc@seZdZdd�Zdd�ZdS)rcCsdS)Nr)rrZaddrrrr�datagram_receivedjsz"DatagramProtocol.datagram_receivedcCsdS)Nr)rr	rrr�error_receivedmszDatagramProtocol.error_receivedN)r
rrrrrrrrrgsc@s$eZdZdd�Zdd�Zdd�ZdS)rcCsdS)Nr)r�fdrrrr�pipe_data_receivedwsz%SubprocessProtocol.pipe_data_receivedcCsdS)Nr)rrr	rrr�pipe_connection_lost~sz'SubprocessProtocol.pipe_connection_lostcCsdS)Nr)rrrr�process_exited�sz!SubprocessProtocol.process_exitedN)r
rrrrrrrrrrtsN)�__all__rrrrrrrr�<module>s
7)
PK[��t�GsGs0__pycache__/selector_events.cpython-36.opt-1.pycnu�[���3


 \���
@s<dZdgZddlZddlZddlZddlZddlZddlZyddlZWne	k
r^dZYnXddl
mZddl
mZddl
m
Z
ddl
mZdd	l
mZdd
l
mZddl
mZddl
mZdd
lmZddlmZdd�ZGdd�dej�ZGdd�dejej�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)z�Event loop using a selector and related classes.

A selector is a "notify-when-ready" multiplexer.  For a subclass which
also includes support for signal handling, see the unix_events sub-module.
�BaseSelectorEventLoop�N�)�base_events)�compat)�	constants)�events)�futures)�	selectors)�
transports)�sslproto)�	coroutine)�loggercCs6y|j|�}Wntk
r"dSXt|j|@�SdS)NF)�get_key�KeyError�boolr)�selector�fdZevent�key�r�//usr/lib64/python3.6/asyncio/selector_events.py�_test_selector_event s
rcsreZdZdZdO�fdd�	ZdPddd�dd�ZdQddddd	�d
d�Zddddd	�dd
�ZdRdd�Z�fdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�ZdSdd �ZdTd!d"�ZedUd#d$��Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd9d:�Zd;d<�Zd=d>�Z ed?d@��Z!dAdB�Z"dCdD�Z#dEdF�Z$dGdH�Z%dIdJ�Z&dKdL�Z'dMdN�Z(�Z)S)VrzJSelector event loop.

    See events.EventLoop for API specification.
    NcsFt�j�|dkrtj�}tjd|jj�||_|j	�t
j�|_dS)NzUsing selector: %s)
�super�__init__r	ZDefaultSelectorr
�debug�	__class__�__name__�	_selector�_make_self_pipe�weakref�WeakValueDictionary�_transports)�selfr)rrrr1s
zBaseSelectorEventLoop.__init__)�extra�servercCst||||||�S)N)�_SelectorSocketTransport)r!�sock�protocol�waiterr"r#rrr�_make_socket_transport;s
z,BaseSelectorEventLoop._make_socket_transportF)�server_side�server_hostnamer"r#c

CsNtj�s"|j||||||||d�Stj||||||�}	t|||	||d�|	jS)N)r)r*r"r#)r"r#)rZ_is_sslproto_available�_make_legacy_ssl_transportZSSLProtocolr$Z_app_transport)
r!�rawsockr&�
sslcontextr'r)r*r"r#Zssl_protocolrrr�_make_ssl_transport@s

z)BaseSelectorEventLoop._make_ssl_transportc	
Cst|||||||||�	S)N)�_SelectorSslTransport)	r!r,r&r-r'r)r*r"r#rrrr+Os
z0BaseSelectorEventLoop._make_legacy_ssl_transportcCst||||||�S)N)�_SelectorDatagramTransport)r!r%r&�addressr'r"rrr�_make_datagram_transportYsz.BaseSelectorEventLoop._make_datagram_transportcsL|j�rtd��|j�rdS|j�t�j�|jdk	rH|jj�d|_dS)Nz!Cannot close a running event loop)Z
is_running�RuntimeError�	is_closed�_close_self_piper�closer)r!)rrrr6^s


zBaseSelectorEventLoop.closecCst�dS)N)�NotImplementedError)r!rrr�_socketpairisz!BaseSelectorEventLoop._socketpaircCsB|j|jj��|jj�d|_|jj�d|_|jd8_dS)Nr)�_remove_reader�_ssock�filenor6�_csock�
_internal_fds)r!rrrr5ls

z&BaseSelectorEventLoop._close_self_pipecCsN|j�\|_|_|jjd�|jjd�|jd7_|j|jj�|j�dS)NFr)r8r:r<�setblockingr=�_add_readerr;�_read_from_self)r!rrrrts
z%BaseSelectorEventLoop._make_self_pipecCsdS)Nr)r!�datarrr�_process_self_data|sz(BaseSelectorEventLoop._process_self_datacCsVxPy |jjd�}|sP|j|�Wqtk
r8wYqtk
rLPYqXqWdS)Ni)r:�recvrB�InterruptedError�BlockingIOError)r!rArrrr@sz%BaseSelectorEventLoop._read_from_selfcCsJ|j}|dk	rFy|jd�Wn(tk
rD|jr@tjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketT)�exc_info)r<�send�OSError�_debugr
r)r!Zcsockrrr�_write_to_self�sz$BaseSelectorEventLoop._write_to_self�dcCs |j|j�|j|||||�dS)N)r?r;�_accept_connection)r!�protocol_factoryr%r-r#�backlogrrr�_start_serving�sz$BaseSelectorEventLoop._start_servingcCs�x�t|�D]�}y0|j�\}}|jr2tjd|||�|jd�Wn�tttfk
rXdSt	k
r�}	z^|	j
t
jt
jt
j
t
jfkr�|jd|	|d��|j|j��|jtj|j|||||�n�WYdd}	~	Xq
Xd|i}
|j|||
||�}|j|�q
WdS)Nz#%r got a new connection from %r: %rFz&socket.accept() out of system resource)�message�	exception�socket�peername)�range�acceptrJr
rr>rErD�ConnectionAbortedErrorrI�errnoZEMFILEZENFILEZENOBUFSZENOMEM�call_exception_handlerr9r;Z
call_laterrZACCEPT_RETRY_DELAYrP�_accept_connection2Zcreate_task)r!rNr%r-r#rO�_�conn�addr�excr"rVrrrrM�s4


z(BaseSelectorEventLoop._accept_connectionccs�d}d}yj|�}|j�}|r6|j||||d||d�}n|j|||||d�}y|EdHWn|j��YnXWn\tk
r�}	z@|jr�d|	d�}
|dk	r�||
d<|dk	r�||
d<|j|
�WYdd}	~	XnXdS)NT)r'r)r"r#)r'r"r#z3Error on transport creation for incoming connection)rQrRr&�	transport)�
create_futurer.r(r6�	ExceptionrJrY)r!rNr\r"r-r#r&r_r'r^�contextrrrrZ�s4z)BaseSelectorEventLoop._accept_connection2cCs@y|j|}Wntk
r"YnX|j�s<tdj||���dS)Nz.File descriptor {!r} is used by transport {!r})r r�
is_closingr3�format)r!rr_rrr�_ensure_fd_no_transport�sz-BaseSelectorEventLoop._ensure_fd_no_transportc	
Gs�|j�tj|||�}y|jj|�}Wn*tk
rP|jj|tj|df�Yn>X|j|j	}\}}|jj
||tjB||f�|dk	r�|j�dS)N)�
_check_closedr�Handlerrr�registerr	�
EVENT_READrA�modify�cancel)	r!r�callback�args�handler�mask�reader�writerrrrr?�s
z!BaseSelectorEventLoop._add_readerc
Cs�|j�rdSy|jj|�}Wntk
r0dSX|j|j}\}}|tjM}|sb|jj|�n|jj	||d|f�|dk	r�|j
�dSdSdS)NFT)r4rrrrrAr	ri�
unregisterrjrk)r!rrrorprqrrrr9sz$BaseSelectorEventLoop._remove_readerc	
Gs�|j�tj|||�}y|jj|�}Wn*tk
rP|jj|tjd|f�Yn>X|j|j	}\}}|jj
||tjB||f�|dk	r�|j�dS)N)rfrrgrrrrhr	�EVENT_WRITErArjrk)	r!rrlrmrnrrorprqrrr�_add_writers
z!BaseSelectorEventLoop._add_writerc
Cs�|j�rdSy|jj|�}Wntk
r0dSX|j|j}\}}|tjM}|sb|jj|�n|jj	|||df�|dk	r�|j
�dSdSdS)zRemove a writer callback.FNT)r4rrrrrAr	rsrrrjrk)r!rrrorprqrrr�_remove_writer,sz$BaseSelectorEventLoop._remove_writercGs|j|�|j||f|��S)zAdd a reader callback.)rer?)r!rrlrmrrr�
add_readerCs
z BaseSelectorEventLoop.add_readercCs|j|�|j|�S)zRemove a reader callback.)rer9)r!rrrr�
remove_readerHs
z#BaseSelectorEventLoop.remove_readercGs|j|�|j||f|��S)zAdd a writer callback..)rert)r!rrlrmrrr�
add_writerMs
z BaseSelectorEventLoop.add_writercCs|j|�|j|�S)zRemove a writer callback.)reru)r!rrrr�
remove_writerRs
z#BaseSelectorEventLoop.remove_writercCs6|jr|j�dkrtd��|j�}|j|d||�|S)z�Receive data from the socket.

        The return value is a bytes object representing the data received.
        The maximum amount of data to be received at once is specified by
        nbytes.

        This method is a coroutine.
        rzthe socket must be non-blockingN)rJ�
gettimeout�
ValueErrorr`�
_sock_recv)r!r%�n�futrrr�	sock_recvWs
	zBaseSelectorEventLoop.sock_recvcCs�|dk	r|j|�|j�rdSy|j|�}Wn`ttfk
rb|j�}|j||j||||�Yn6tk
r�}z|j	|�WYdd}~XnX|j
|�dS)N)rw�	cancelledrCrErDr;rvr|ra�
set_exception�
set_result)r!r~�
registered_fdr%r}rArr^rrrr|fs
z BaseSelectorEventLoop._sock_recvcCsF|jr|j�dkrtd��|j�}|r8|j|d||�n
|jd�|S)a�Send data to the socket.

        The socket must be connected to a remote socket. This method continues
        to send data from data until either all data has been sent or an
        error occurs. None is returned on success. On error, an exception is
        raised, and there is no way to determine how much data, if any, was
        successfully processed by the receiving end of the connection.

        This method is a coroutine.
        rzthe socket must be non-blockingN)rJrzr{r`�
_sock_sendallr�)r!r%rAr~rrr�sock_sendall{s
z"BaseSelectorEventLoop.sock_sendallcCs�|dk	r|j|�|j�rdSy|j|�}WnDttfk
rHd}Yn*tk
rp}z|j|�dSd}~XnX|t|�kr�|jd�n.|r�||d�}|j	�}|j
||j||||�dS)Nr)ryr�rHrErDrar��lenr�r;rxr�)r!r~r�r%rAr}r^rrrrr��s"

z#BaseSelectorEventLoop._sock_sendallccs�|jr|j�dkrtd��ttd�s2|jtjkrptj||j|j	|d�}|j
�sZ|EdH|j�d\}}}}}|j�}|j
|||�|EdHS)zTConnect to a remote socket at address.

        This method is a coroutine.
        rzthe socket must be non-blocking�AF_UNIX)�family�proto�loopN)rJrzr{�hasattrrSr�r�rZ_ensure_resolvedr��done�resultr`�
_sock_connect)r!r%r1Zresolvedr[r~rrr�sock_connect�s
z"BaseSelectorEventLoop.sock_connectcCs�|j�}y|j|�Wnjttfk
rV|jtj|j|��|j||j	|||�Yn6t
k
r�}z|j|�WYdd}~XnX|jd�dS)N)
r;ZconnectrErDZadd_done_callback�	functools�partial�_sock_connect_donerx�_sock_connect_cbrar�r�)r!r~r%r1rr^rrrr��sz#BaseSelectorEventLoop._sock_connectcCs|j|�dS)N)ry)r!rr~rrrr��sz(BaseSelectorEventLoop._sock_connect_donecCs�|j�rdSy,|jtjtj�}|dkr6t|d|f��WnBttfk
rPYn6tk
rz}z|j	|�WYdd}~XnX|j
d�dS)NrzConnect call failed %s)r�Z
getsockoptrSZ
SOL_SOCKETZSO_ERRORrIrErDrar�r�)r!r~r%r1�errr^rrrr��sz&BaseSelectorEventLoop._sock_connect_cbcCs4|jr|j�dkrtd��|j�}|j|d|�|S)a|Accept a connection.

        The socket must be bound to an address and listening for connections.
        The return value is a pair (conn, address) where conn is a new socket
        object usable to send and receive data on the connection, and address
        is the address bound to the socket on the other end of the connection.

        This method is a coroutine.
        rzthe socket must be non-blockingF)rJrzr{r`�_sock_accept)r!r%r~rrr�sock_accept�s

z!BaseSelectorEventLoop.sock_acceptcCs�|j�}|r|j|�|j�r"dSy|j�\}}|jd�WnVttfk
rh|j||j|d|�Yn:t	k
r�}z|j
|�WYdd}~XnX|j||f�dS)NFT)r;rwr�rVr>rErDrvr�rar�r�)r!r~Z
registeredr%rr\r1r^rrrr��s
z"BaseSelectorEventLoop._sock_acceptcCs�x~|D]v\}}|j|j}\}}|tj@rN|dk	rN|jrD|j|�n
|j|�|tj@r|dk	r|jrr|j|�q|j|�qWdS)N)	�fileobjrAr	riZ
_cancelledr9Z
_add_callbackrsru)r!Z
event_listrror�rprqrrr�_process_events�s
z%BaseSelectorEventLoop._process_eventscCs|j|j��|j�dS)N)r9r;r6)r!r%rrr�
_stop_servingsz#BaseSelectorEventLoop._stop_serving)N)N)N)NNN)NNrL)NNrL)NN)*r�
__module__�__qualname__�__doc__rr(r.r+r2r6r8r5rrBr@rKrPrMrrZrer?r9rtrurvrwrxryrr|r�r�r�r�r�r�r�r�r�r��
__classcell__rr)rrr+sT



(#cs�eZdZdZeZdZd �fdd�	Zdd�Zdd	�Z	d
d�Z
dd
�Zdd�Zdd�Z
ejr`dd�Zd!dd�Zdd�Zdd�Zdd�Zdd�Z�ZS)"�_SelectorTransport�iNcs�t�j||�||jd<|j�|jd<d|jkrdy|j�|jd<Wn tjk
rbd|jd<YnX||_|j�|_	||_
d|_||_|j
�|_d|_d|_|jdk	r�|jj�||j|j	<dS)NrSZsocknamerTTrF)rr�_extraZgetsocknameZgetpeernamerS�error�_sockr;�_sock_fd�	_protocol�_protocol_connected�_server�_buffer_factory�_buffer�
_conn_lost�_closingZ_attachr )r!r�r%r&r"r#)rrrrs&





z_SelectorTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�|jdk	r�|jj�r�t|jj	|jt
j�}|rz|jd�n
|jd�t|jj	|jt
j�}|r�d}nd}|j
�}|jd||f�d	d
j|�S)N�closed�closingzfd=%szread=pollingz	read=idle�pollingZidlezwrite=<%s, bufsize=%s>z<%s>� )rrr��appendr�r��_loopr4rrr	rirs�get_write_buffer_size�join)r!�infor��state�bufsizerrr�__repr__2s*



z_SelectorTransport.__repr__cCs|jd�dS)N)�_force_close)r!rrr�abortNsz_SelectorTransport.abortcCs
||_dS)N)r�)r!r&rrr�set_protocolQsz_SelectorTransport.set_protocolcCs|jS)N)r�)r!rrr�get_protocolTsz_SelectorTransport.get_protocolcCs|jS)N)r�)r!rrrrcWsz_SelectorTransport.is_closingcCsT|jr
dSd|_|jj|j�|jsP|jd7_|jj|j�|jj|jd�dS)NTr)	r�r�r9r�r�r�ru�	call_soon�_call_connection_lost)r!rrrr6Zsz_SelectorTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)�source)r��warnings�warn�ResourceWarningr6)r!rrr�__del__hs
z_SelectorTransport.__del__�Fatal error on transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)rG)rQrRr_r&)
�
isinstancerZ_FATAL_ERROR_IGNOREr��	get_debugr
rrYr�r�)r!r^rQrrr�_fatal_errorns
z_SelectorTransport._fatal_errorcCsd|jr
dS|jr(|jj�|jj|j�|jsBd|_|jj|j�|jd7_|jj|j	|�dS)NTr)
r�r��clearr�rur�r�r9r�r�)r!r^rrrr�|s
z_SelectorTransport._force_closecCsVz|jr|jj|�Wd|jj�d|_d|_d|_|j}|dk	rP|j�d|_XdS)N)r�r�Zconnection_lostr�r6r�r�Z_detach)r!r^r#rrrr��s
z(_SelectorTransport._call_connection_lostcCs
t|j�S)N)r�r�)r!rrrr��sz(_SelectorTransport.get_write_buffer_sizecGs"|jr
dS|jj||f|��dS)N)r�r�r?)r!rrlrmrrrr?�sz_SelectorTransport._add_readeri)NN)r�)rr�r��max_size�	bytearrayr�r�rr�r�r�r�rcr6rZPY34r�r�r�r�r�r?r�rr)rrr�s"

r�csVeZdZd�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
�ZS)r$Ncsrt�j|||||�d|_d|_tj|j�|jj|j	j
|�|jj|j|j|j
�|dk	rn|jjtj|d�dS)NF)rr�_eof�_pausedrZ_set_nodelayr�r�r�r��connection_mader?r��_read_readyr�_set_result_unless_cancelled)r!r�r%r&r'r"r#)rrrr�s

z!_SelectorSocketTransport.__init__cCs>|js|jrdSd|_|jj|j�|jj�r:tjd|�dS)NTz%r pauses reading)r�r�r�r9r�r�r
r)r!rrr�
pause_reading�s
z&_SelectorSocketTransport.pause_readingcCsB|js|jrdSd|_|j|j|j�|jj�r>tjd|�dS)NFz%r resumes reading)	r�r�r?r�r�r�r�r
r)r!rrr�resume_reading�s
z'_SelectorSocketTransport.resume_readingcCs�|jr
dSy|jj|j�}WnDttfk
r4Yn|tk
r`}z|j|d�WYdd}~XnPX|rt|jj	|�n<|j
j�r�tj
d|�|jj�}|r�|j
j|j�n|j�dS)Nz$Fatal read error on socket transportz%r received EOF)r�r�rCr�rErDrar�r��
data_receivedr�r�r
r�eof_receivedr9r�r6)r!rAr^�	keep_openrrrr��s 

z$_SelectorSocketTransport._read_readycCs�t|tttf�s"tdt|�j��|jr0td��|s8dS|j	rf|j	t
jkrTtj
d�|j	d7_	dS|js�y|jj|�}WnBttfk
r�Yn@tk
r�}z|j|d�dSd}~XnX||d�}|s�dS|jj|j|j�|jj|�|j�dS)Nz1data argument must be a bytes-like object, not %rz%Cannot call write() after write_eof()zsocket.send() raised exception.rz%Fatal write error on socket transport)r��bytesr��
memoryview�	TypeError�typerr�r3r�r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningr�r�rHrErDrar�r�rtr��_write_ready�extend�_maybe_pause_protocol)r!rAr}r^rrr�write�s4
z_SelectorSocketTransport.writecCs�|jr
dSy|jj|j�}Wn\ttfk
r4Yn�tk
rx}z*|jj|j	�|jj
�|j|d�WYdd}~XnTX|r�|jd|�=|j�|js�|jj|j	�|j
r�|jd�n|jr�|jjtj�dS)Nz%Fatal write error on socket transport)r�r�rHr�rErDrar�rur�r�r��_maybe_resume_protocolr�r�r��shutdownrS�SHUT_WR)r!r}r^rrrr�s&
z%_SelectorSocketTransport._write_readycCs.|js|jrdSd|_|js*|jjtj�dS)NT)r�r�r�r�r�rSr�)r!rrr�	write_eofs
z"_SelectorSocketTransport.write_eofcCsdS)NTr)r!rrr�
can_write_eof sz&_SelectorSocketTransport.can_write_eof)NNN)rr�r�rr�r�r�r�r�r�r�r�rr)rrr$�s#r$csdeZdZeZd�fdd�	Zddd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
�ZS)r/NFc

s�tdkrtd��|s tj||�}|dd�}
|r<|r<||
d<|j|f|
�}t�j|||||	�d|_||_||_	||_
d|_|jj
|d�|jj�r�tjd|�|jj�}nd}|j|�dS)Nzstdlib ssl module not availableF)r)Zdo_handshake_on_connectr*)r-z%r starts SSL handshake)�sslr3rZ_create_transport_contextZwrap_socketrrr��_server_hostname�_waiter�_sslcontextr�r��updater�r�r
r�time�
_on_handshake)
r!r�r,r&r-r'r)r*r"r#Zwrap_kwargsZsslsock�
start_time)rrrr(s*

z_SelectorSslTransport.__init__cCsD|jdkrdS|jj�s:|dk	r.|jj|�n|jjd�d|_dS)N)r�r�r�r�)r!r^rrr�_wakeup_waiterLs

z$_SelectorSslTransport._wakeup_waiterc"Cs$y|jj�Wn�tjk
r8|jj|j|j|�dStjk
r`|jj	|j|j|�dSt
k
r�}z`|jj�r�tj
d|dd�|jj|j�|jj|j�|jj�|j|�t|t�r�dS�WYdd}~XnX|jj|j�|jj|j�|jj�}t|jd��s�|j�r�|jjtjk�r�ytj||j�WnRtk
�r�}z4|jj��rjtj
d|dd�|jj�|j|�dSd}~XnX|jj||jj�|jj�|jd�d|_d|_ |jj|j|j!�d|_"|jj#|j$j%|�|jj#|j�|jj��r |jj&�|}tj'd||d	�dS)
Nz%r: SSL handshake failedT)rGZcheck_hostnamez1%r: SSL handshake failed on matching the hostname)�peercert�cipher�compressionZ
ssl_objectFz%r: SSL handshake took %.1f msg@�@)(r�Zdo_handshaker��SSLWantReadErrorr�r?r�r��SSLWantWriteErrorrt�
BaseExceptionr�r
r�r9rur6r�r�raZgetpeercertr�r�r�Zverify_modeZ	CERT_NONEZmatch_hostnamer�r�r�r��_read_wants_write�_write_wants_readr�r�r�r�r�r�r)r!r�r^r�Zdtrrrr�Vsb













z#_SelectorSslTransport._on_handshakecCsJ|jrtd��|jrtd��d|_|jj|j�|jj�rFtjd|�dS)Nz#Cannot pause_reading() when closingzAlready pausedTz%r pauses reading)	r�r3r�r�r9r�r�r
r)r!rrrr��s
z#_SelectorSslTransport.pause_readingcCsJ|jstd��d|_|jrdS|jj|j|j�|jj�rFtj	d|�dS)Nz
Not pausedFz%r resumes reading)
r�r3r�r�r?r�r�r�r
r)r!rrrr��s
z$_SelectorSslTransport.resume_readingcCs"|jr
dS|jr6d|_|j�|jr6|jj|j|j�y|jj|j	�}Wn�t
ttj
fk
rdYn�tjk
r�d|_|jj|j�|jj|j|j�Yn�tk
r�}z|j|d�WYdd}~XnTX|r�|jj|�n@z4|jj�r�tjd|�|jj�}|�rtjd�Wd|j�XdS)NFTz!Fatal read error on SSL transportz%r received EOFz?returning true from eof_received() has no effect when using ssl)r�r�r�r�r�rtr�r�rCr�rErDr�r�r�r�r9rar�r�r�r�r
rr�r�r6)r!rAr^r�rrrr��s4

z!_SelectorSslTransport._read_readycCs(|jr
dS|jr<d|_|j�|jp(|js<|jj|j|j�|jr�y|j	j
|j�}Wn�ttt
jfk
rtd}Ynpt
jk
r�d}|jj|j�d|_YnDtk
r�}z(|jj|j�|jj�|j|d�dSd}~XnX|r�|jd|�=|j�|j�s$|jj|j�|j�r$|jd�dS)NFrTz"Fatal write error on SSL transport)r�r�r�r�r�r�r?r�r�r�rHrErDr�r�r�rur�rar�r�r�r�)r!r}r^rrrr��s8

z"_SelectorSslTransport._write_readycCs�t|tttf�s"tdt|�j��|s*dS|jrX|jtj	krFt
jd�|jd7_dS|jsp|j
j|j|j�|jj|�|j�dS)Nz1data argument must be a bytes-like object, not %rzsocket.send() raised exception.r)r�r�r�r�r�r�rr�rr�r
r�r�r�rtr�r�r�r�)r!rArrrr��s
z_SelectorSslTransport.writecCsdS)NFr)r!rrrr�sz#_SelectorSslTransport.can_write_eof)NFNNN)N)rr�r�r�r�rr�r�r�r�r�r�r�r�r�rr)rrr/$s"

?
"#r/csFeZdZejZd�fdd�	Zdd�Zdd�Zd
dd	�Z	d
d�Z
�ZS)r0Ncs^t�j||||�||_|jj|jj|�|jj|j|j|j	�|dk	rZ|jjt
j|d�dS)N)rr�_addressr�r�r�r�r?r�r�rr�)r!r�r%r&r1r'r")rrrrs

z#_SelectorDatagramTransport.__init__cCstdd�|jD��S)Ncss|]\}}t|�VqdS)N)r�)�.0rAr[rrr�	<genexpr>szC_SelectorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr�)r!rrrr�sz0_SelectorDatagramTransport.get_write_buffer_sizecCs�|jr
dSy|jj|j�\}}Wnpttfk
r8Ynhtk
rd}z|jj|�WYdd}~Xn<t	k
r�}z|j
|d�WYdd}~XnX|jj||�dS)Nz&Fatal read error on datagram transport)r�r�Zrecvfromr�rErDrIr��error_receivedrar�Zdatagram_received)r!rAr]r^rrrr� sz&_SelectorDatagramTransport._read_readycCsTt|tttf�s"tdt|�j��|s*dS|jrN|d|jfkrNtd|jf��|j	r�|jr�|j	t
jkrptj
d�|j	d7_	dS|j�s4y&|jr�|jj|�n|jj||�dSttfk
r�|jj|j|j�YnZtk
�r}z|jj|�dSd}~Xn.tk
�r2}z|j|d�dSd}~XnX|jjt|�|f�|j�dS)Nz1data argument must be a bytes-like object, not %rz#Invalid address: must be None or %szsocket.send() raised exception.rz'Fatal write error on datagram transport)r�r�r�r�r�r�rr�r{r�rr�r
r�r�r�rH�sendtorErDr�rtr��
_sendto_readyrIr�r�rar�r�r�)r!rAr]r^rrrr�.s<
z!_SelectorDatagramTransport.sendtocCs�x�|jr�|jj�\}}y&|jr,|jj|�n|jj||�Wqttfk
rf|jj||f�PYqt	k
r�}z|j
j|�dSd}~Xqtk
r�}z|j
|d�dSd}~XqXqW|j�|js�|jj|j�|jr�|jd�dS)Nz'Fatal write error on datagram transport)r��popleftr�r�rHr�rErD�
appendleftrIr�r�rar�r�r�rur�r�r�)r!rAr]r^rrrr�Us*z(_SelectorDatagramTransport._sendto_ready)NNN)N)rr�r��collections�dequer�rr�r�r�r�r�rr)rrr0s
'r0) r��__all__r�rXr�rSr�rr��ImportError�rrrrrr	r
rZ
coroutinesr�logr
rZ
BaseEventLooprZ_FlowControlMixinZ	Transportr�r$r/r0rrrr�<module>sD
iiPK[����j#j#0__pycache__/base_subprocess.cpython-36.opt-2.pycnu�[���3


 \�#�@s�ddlZddlZddlZddlmZddlmZddlmZddlmZddl	m
Z
Gdd	�d	ej�ZGd
d�dej
�ZGdd
�d
eej�ZdS)�N�)�compat)�	protocols)�
transports)�	coroutine)�loggercs�eZdZd0�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jrTdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zed d!��Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zed*d+��Zd,d-�Zd.d/�Z�ZS)1�BaseSubprocessTransportNc
s&t�j|
�d|_||_||_d|_d|_d|_g|_t	j
�|_i|_d|_
|tjkr`d|jd<|tjkrtd|jd<|tjkr�d|jd<y"|jf||||||d�|��Wn|j��YnX|jj|_|j|jd<|jj��rt|ttf�r�|}n|d}tjd||j�|jj|j|	��dS)NFrr�)�args�shell�stdin�stdout�stderr�bufsize�
subprocesszprocess %r created: pid %s)�super�__init__�_closed�	_protocol�_loop�_proc�_pid�_returncode�
_exit_waiters�collections�deque�_pending_calls�_pipes�	_finishedr�PIPE�_start�close�pidZ_extra�	get_debug�
isinstance�bytes�strr�debugZcreate_task�_connect_pipes)
�self�loop�protocolr
rrr
rr�waiterZextra�kwargsZprogram)�	__class__��//usr/lib64/python3.6/asyncio/base_subprocess.pyrs@








z BaseSubprocessTransport.__init__cCs|jjg}|jr|jd�|jdk	r4|jd|j�|jdk	rP|jd|j�n |jdk	rf|jd�n
|jd�|jjd�}|dk	r�|jd|j�|jjd�}|jjd	�}|dk	r�||kr�|jd
|j�n0|dk	r�|jd|j�|dk	r�|jd|j�d
dj	|�S)N�closedzpid=%sz
returncode=%sZrunningznot startedrzstdin=%srr	zstdout=stderr=%sz	stdout=%sz	stderr=%sz<%s>� )
r.�__name__r�appendrrr�get�pipe�join)r)�inforr
rr/r/r0�__repr__9s,





z BaseSubprocessTransport.__repr__cKst�dS)N)�NotImplementedError)r)r
rrr
rrr-r/r/r0r VszBaseSubprocessTransport._startcCs
||_dS)N)r)r)r+r/r/r0�set_protocolYsz$BaseSubprocessTransport.set_protocolcCs|jS)N)r)r)r/r/r0�get_protocol\sz$BaseSubprocessTransport.get_protocolcCs|jS)N)r)r)r/r/r0�
is_closing_sz"BaseSubprocessTransport.is_closingcCs�|jr
dSd|_x&|jj�D]}|dkr*q|jj�qW|jdk	r�|jdkr�|jj�dkr�|jj	�rpt
jd|�y|jj�Wnt
k
r�YnXdS)NTz$Close running child process: kill %r)rr�valuesr6r!rrZpollrr#rZwarning�kill�ProcessLookupError)r)�protor/r/r0r!bs 


zBaseSubprocessTransport.closecCs&|js"tjd|t|d�|j�dS)Nzunclosed transport %r)�source)r�warnings�warn�ResourceWarningr!)r)r/r/r0�__del__�szBaseSubprocessTransport.__del__cCs|jS)N)r)r)r/r/r0�get_pid�szBaseSubprocessTransport.get_pidcCs|jS)N)r)r)r/r/r0�get_returncode�sz&BaseSubprocessTransport.get_returncodecCs||jkr|j|jSdSdS)N)rr6)r)�fdr/r/r0�get_pipe_transport�s
z*BaseSubprocessTransport.get_pipe_transportcCs|jdkrt��dS)N)rr@)r)r/r/r0�_check_proc�s
z#BaseSubprocessTransport._check_proccCs|j�|jj|�dS)N)rKr�send_signal)r)�signalr/r/r0rL�sz#BaseSubprocessTransport.send_signalcCs|j�|jj�dS)N)rKr�	terminate)r)r/r/r0rN�sz!BaseSubprocessTransport.terminatecCs|j�|jj�dS)N)rKrr?)r)r/r/r0r?�szBaseSubprocessTransport.killc	#sPy�j}�j}|jdk	rB|j�fdd�|j�EdH\}}|�jd<|jdk	rv|j�fdd�|j�EdH\}}|�jd<|jdk	r�|j�fdd�|j�EdH\}}|�jd<|j�j	j
��x"�jD]\}}|j|f|��q�Wd�_WnDtk
�r*}z&|dk	�r|j
��r|j|�WYdd}~Xn"X|dk	�rL|j
��rL|jd�dS)Ncs
t�d�S)Nr)�WriteSubprocessPipeProtor/)r)r/r0�<lambda>�sz8BaseSubprocessTransport._connect_pipes.<locals>.<lambda>rcs
t�d�S)Nr)�ReadSubprocessPipeProtor/)r)r/r0rP�srcs
t�d�S)Nr	)rQr/)r)r/r0rP�sr	)rrrZconnect_write_piperr
Zconnect_read_piper�	call_soonr�connection_mader�	Exception�	cancelledZ
set_exception�
set_result)	r)r,�procr*�_r6�callback�data�excr/)r)r0r(�s6









z&BaseSubprocessTransport._connect_pipescGs2|jdk	r|jj||f�n|jj|f|��dS)N)rr4rrR)r)�cbrZr/r/r0�_call�s
zBaseSubprocessTransport._callcCs|j|jj||�|j�dS)N)r]rZpipe_connection_lost�_try_finish)r)rIr[r/r/r0�_pipe_connection_lost�sz-BaseSubprocessTransport._pipe_connection_lostcCs|j|jj||�dS)N)r]rZpipe_data_received)r)rIrZr/r/r0�_pipe_data_received�sz+BaseSubprocessTransport._pipe_data_receivedcCst|jj�rtjd||�||_|jjdkr2||j_|j|jj	�|j
�x |jD]}|j�sP|j
|�qPWd|_dS)Nz%r exited with return code %r)rr#rr8rr�
returncoder]rZprocess_exitedr^rrUrV)r)rar,r/r/r0�_process_exited�s
z'BaseSubprocessTransport._process_exitedccs0|jdk	r|jS|jj�}|jj|�|EdHS)N)rrZ
create_futurerr4)r)r,r/r/r0�_wait�s


zBaseSubprocessTransport._waitcCs>|jdkrdStdd�|jj�D��r:d|_|j|jd�dS)Ncss|]}|dk	o|jVqdS)N)�disconnected)�.0�pr/r/r0�	<genexpr>�sz6BaseSubprocessTransport._try_finish.<locals>.<genexpr>T)r�allrr>rr]�_call_connection_lost)r)r/r/r0r^�s
z#BaseSubprocessTransport._try_finishcCs*z|jj|�Wdd|_d|_d|_XdS)N)r�connection_lostrr)r)r[r/r/r0ri�s
z-BaseSubprocessTransport._call_connection_lost)NN)r3�
__module__�__qualname__rr9r r;r<r=r!rZPY34rFrGrHrJrKrLrNr?rr(r]r_r`rbrcr^ri�
__classcell__r/r/)r.r0rs0)%	rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rOcCs||_||_d|_d|_dS)NF)rWrIr6rd)r)rWrIr/r/r0rsz!WriteSubprocessPipeProto.__init__cCs
||_dS)N)r6)r)Z	transportr/r/r0rSsz(WriteSubprocessPipeProto.connection_madecCsd|jj|j|jfS)Nz<%s fd=%s pipe=%r>)r.r3rIr6)r)r/r/r0r9sz!WriteSubprocessPipeProto.__repr__cCs d|_|jj|j|�d|_dS)NT)rdrWr_rI)r)r[r/r/r0rjsz(WriteSubprocessPipeProto.connection_lostcCs|jjj�dS)N)rWr�
pause_writing)r)r/r/r0rnsz&WriteSubprocessPipeProto.pause_writingcCs|jjj�dS)N)rWr�resume_writing)r)r/r/r0rosz'WriteSubprocessPipeProto.resume_writingN)	r3rkrlrrSr9rjrnror/r/r/r0rOsrOc@seZdZdd�ZdS)rQcCs|jj|j|�dS)N)rWr`rI)r)rZr/r/r0�
data_received$sz%ReadSubprocessPipeProto.data_receivedN)r3rkrlrpr/r/r/r0rQ!srQ)rrrC�rrrZ
coroutinesr�logrZSubprocessTransportrZBaseProtocolrOZProtocolrQr/r/r/r0�<module>s{PK[�#�~� � !__pycache__/queues.cpython-36.pycnu�[���3


 \�@s�dZdddddgZddlZddlZdd	lmZdd
lmZddlmZddlm	Z	Gd
d�de
�ZGdd�de
�ZGdd�d�Z
Gdd�de
�ZGdd�de
�Zejs�e
Zejd�dS)ZQueues�Queue�
PriorityQueue�	LifoQueue�	QueueFull�
QueueEmpty�N�)�compat)�events)�locks)�	coroutinec@seZdZdZdS)rz]Exception raised when Queue.get_nowait() is called on a Queue object
    which is empty.
    N)�__name__�
__module__�__qualname__�__doc__�rr�&/usr/lib64/python3.6/asyncio/queues.pyrsc@seZdZdZdS)rzgException raised when the Queue.put_nowait() method is called on a Queue
    object which is full.
    N)rr
rrrrrrrsc@s�eZdZdZd)dd�dd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Ze
dd��Zdd�Zdd�Zedd��Zdd �Zed!d"��Zd#d$�Zd%d&�Zed'd(��ZdS)*raA queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "yield from put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded asyncio application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    rN)�loopcCsb|dkrtj�|_n||_||_tj�|_tj�|_d|_t	j
|jd�|_|jj�|j
|�dS)Nr)r)r	Zget_event_loop�_loop�_maxsize�collections�deque�_getters�_putters�_unfinished_tasksr
ZEvent�	_finished�set�_init)�self�maxsizerrrr�__init__(s


zQueue.__init__cCstj�|_dS)N)rr�_queue)rrrrrr:szQueue._initcCs
|jj�S)N)r �popleft)rrrr�_get=sz
Queue._getcCs|jj|�dS)N)r �append)r�itemrrr�_put@sz
Queue._putcCs*x$|r$|j�}|j�s|jd�PqWdS)N)r!�doneZ
set_result)r�waitersZwaiterrrr�_wakeup_nextEs

zQueue._wakeup_nextcCsdjt|�jt|�|j��S)Nz<{} at {:#x} {}>)�format�typer�id�_format)rrrr�__repr__MszQueue.__repr__cCsdjt|�j|j��S)Nz<{} {}>)r)r*rr,)rrrr�__str__Qsz
Queue.__str__cCszdj|j�}t|dd�r,|djt|j��7}|jrF|djt|j��7}|jr`|djt|j��7}|jrv|dj|j�7}|S)Nzmaxsize={!r}r z _queue={!r}z
 _getters[{}]z
 _putters[{}]z	 tasks={})	r)r�getattr�listr r�lenrr)r�resultrrrr,Tsz
Queue._formatcCs
t|j�S)zNumber of items in the queue.)r1r )rrrr�qsize`szQueue.qsizecCs|jS)z%Number of items allowed in the queue.)r)rrrrrdsz
Queue.maxsizecCs|jS)z3Return True if the queue is empty, False otherwise.)r )rrrr�emptyiszQueue.emptycCs |jdkrdS|j�|jkSdS)z�Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        rFN)rr3)rrrr�fullms
z
Queue.fullc	cstxh|j�rh|jj�}|jj|�y|EdHWq|j�|j�r^|j�r^|j|j��YqXqW|j|�S)z�Put an item into the queue.

        Put an item into the queue. If the queue is full, wait until a free
        slot is available before adding item.

        This method is a coroutine.
        N)	r5r�
create_futurerr#�cancel�	cancelledr(�
put_nowait)rr$Zputterrrr�putxs	

z	Queue.putcCs>|j�rt�|j|�|jd7_|jj�|j|j�dS)zyPut an item into the queue without blocking.

        If no free slot is immediately available, raise QueueFull.
        rN)r5rr%rr�clearr(r)rr$rrrr9�s

zQueue.put_nowaitccs�x�|j�r�|jj�}|jj|�y|EdHWq|j�y|jj|�Wntk
rbYnX|j�r�|j�r�|j	|j��YqXqW|j
�S)z�Remove and return an item from the queue.

        If queue is empty, wait until an item is available.

        This method is a coroutine.
        N)r4rr6rr#r7�remove�
ValueErrorr8r(�
get_nowait)r�getterrrr�get�s

z	Queue.getcCs$|j�rt�|j�}|j|j�|S)z�Remove and return an item from the queue.

        Return an item if one is immediately available, else raise QueueEmpty.
        )r4rr"r(r)rr$rrrr>�s
zQueue.get_nowaitcCs8|jdkrtd��|jd8_|jdkr4|jj�dS)a$Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).

        Raises ValueError if called more times than there were items placed in
        the queue.
        rz!task_done() called too many timesrN)rr=rr)rrrr�	task_done�s


zQueue.task_doneccs|jdkr|jj�EdHdS)aBlock until all items in the queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer calls task_done() to
        indicate that the item was retrieved and all work on it is complete.
        When the count of unfinished tasks drops to zero, join() unblocks.
        rN)rr�wait)rrrr�join�s	
z
Queue.join)r)rr
rrrrr"r%r(r-r.r,r3�propertyrr4r5rr:r9r@r>rArCrrrrrs&
c@s4eZdZdZdd�Zejfdd�Zejfdd�Z	dS)	rz�A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    cCs
g|_dS)N)r )rrrrrr�szPriorityQueue._initcCs||j|�dS)N)r )rr$�heappushrrrr%�szPriorityQueue._putcCs
||j�S)N)r )r�heappoprrrr"�szPriorityQueue._getN)
rr
rrr�heapqrEr%rFr"rrrrr�sc@s(eZdZdZdd�Zdd�Zdd�ZdS)	rzEA subclass of Queue that retrieves most recently added entries first.cCs
g|_dS)N)r )rrrrrr�szLifoQueue._initcCs|jj|�dS)N)r r#)rr$rrrr%�szLifoQueue._putcCs
|jj�S)N)r �pop)rrrrr"�szLifoQueue._getN)rr
rrrr%r"rrrrr�s�
JoinableQueue)r�__all__rrG�rr	r
Z
coroutinesr�	ExceptionrrrrrZPY35rIr#rrrr�<module>s H
PK[1<���J�J __pycache__/tasks.cpython-36.pycnu�[���3


 \�a�
@s�dZddddddddd	d
ddd
g
ZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZddlmZddlm
Z
ddlmZGdd�de
j�ZeZyddlZWnek
r�YnXejZZej
jZej
jZej
jZedded�dd��Zdd�Zedd�dd��Zedd��Zddd �d!d�Zed/dd�d"d��Zdd�d#d$�Zee�d	<d	e_ [dd�d%d�Z!ed&d'��Z"Gd(d)�d)e
j�Z#dd*d+�d,d
�Z$dd�d-d�Z%d.d
�Z&dS)0z0Support for tasks, coroutines and the scheduler.�Task�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�wait�wait_for�as_completed�sleep�async�gather�shield�
ensure_future�run_coroutine_threadsafe�N�)�
base_tasks)�compat)�
coroutines)�events)�futures)�	coroutinecs�eZdZdZej�ZiZdZe	ddd��Z
e	ddd��Zdd��fd	d
�
Ze
jrXdd�Zd
d�Zdd�dd�Zddd�dd�Zdd�Zd�fdd�	Zdd�Z�ZS)rz A coroutine wrapped in a Future.TNcCs|dkrtj�}|jj|�S)z�Return the currently running task in an event loop or None.

        By default the current task for the current event loop is returned.

        None is returned when called not in the context of a Task.
        N)r�get_event_loop�_current_tasks�get)�cls�loop�r�%/usr/lib64/python3.6/asyncio/tasks.py�current_task.szTask.current_taskcs$�dkrtj���fdd�|jD�S)z|Return a set of all tasks for an event loop.

        By default all tasks for the current event loop are returned.
        Ncsh|]}|j�kr|�qSr)�_loop)�.0�t)rrr�	<setcomp>Bsz!Task.all_tasks.<locals>.<setcomp>)rr�
_all_tasks)rrr)rr�	all_tasks:szTask.all_tasks)rcsdtj|�stt|���t�j|d�|jr2|jd=||_d|_d|_	|j
j|j�|j
jj|�dS)N)rrF���)r�iscoroutine�AssertionError�repr�super�__init__�_source_traceback�_coro�_fut_waiter�_must_cancelr�	call_soon�_step�	__class__r"�add)�self�coror)r0rrr)Dsz
Task.__init__cCsH|jtjkr8|jr8|dd�}|jr,|j|d<|jj|�tjj|�dS)Nz%Task was destroyed but it is pending!)�task�messageZsource_traceback)	Z_staterZ_PENDING�_log_destroy_pendingr*rZcall_exception_handler�Future�__del__)r2�contextrrrr8Ss
zTask.__del__cCs
tj|�S)N)rZ_task_repr_info)r2rrr�
_repr_info^szTask._repr_info)�limitcCstj||�S)a�Return the list of stack frames for this task's coroutine.

        If the coroutine is not done, this returns the stack where it is
        suspended.  If the coroutine has completed successfully or was
        cancelled, this returns an empty list.  If the coroutine was
        terminated by an exception, this returns the list of traceback
        frames.

        The frames are always ordered from oldest to newest.

        The optional limit gives the maximum number of frames to
        return; by default all available frames are returned.  Its
        meaning differs depending on whether a stack or a traceback is
        returned: the newest frames of a stack are returned, but the
        oldest frames of a traceback are returned.  (This matches the
        behavior of the traceback module.)

        For reasons beyond our control, only one stack frame is
        returned for a suspended coroutine.
        )rZ_task_get_stack)r2r;rrr�	get_stackaszTask.get_stack)r;�filecCstj|||�S)anPrint the stack or traceback for this task's coroutine.

        This produces output similar to that of the traceback module,
        for the frames retrieved by get_stack().  The limit argument
        is passed to get_stack().  The file argument is an I/O stream
        to which the output is written; by default output is written
        to sys.stderr.
        )rZ_task_print_stack)r2r;r=rrr�print_stackxs	zTask.print_stackcCs4d|_|j�rdS|jdk	r*|jj�r*dSd|_dS)a�Request that this task cancel itself.

        This arranges for a CancelledError to be thrown into the
        wrapped coroutine on the next cycle through the event loop.
        The coroutine then has a chance to clean up or even deny
        the request using try/except/finally.

        Unlike Future.cancel, this does not guarantee that the
        task will be cancelled: the exception might be caught and
        acted upon, delaying cancellation of the task or preventing
        cancellation completely.  The task may also return a value or
        raise a different exception.

        Immediately after this method is called, Task.cancelled() will
        not return True (unless the task was already cancelled).  A
        task will be marked as cancelled when the wrapped coroutine
        terminates with a CancelledError exception (even if cancel()
        was not called).
        FNT)Z_log_traceback�doner,�cancelr-)r2rrrr@�s

zTask.cancelcs�|j�stdj||���|jr:t|tj�s4tj�}d|_|j}d|_||j	j
|j<�zy"|dkrn|jd�}n
|j
|�}Wn�tk
r�}z.|jr�d|_|jtj��n|j|j�WYdd}~X�n�tjk
r�t�j�Y�n~tk
�r}z|j|�WYdd}~X�nPtk
�rD}z|j|��WYdd}~X�n Xt|dd�}|dk	�r|j|jk	�r�|jj|jtdj||���n||�r�||k�r�|jj|jtdj|���n2d|_|j|j�||_|j�r|jj��rd|_n|jj|jtdj||���n^|dk�r |jj|j�nDtj|��rJ|jj|jtdj||���n|jj|jtdj|���Wd|j	j
j|j�d}XdS)	Nz!_step(): already done: {!r}, {!r}F�_asyncio_future_blockingz6Task {!r} got Future {!r} attached to a different loopz!Task cannot await on itself: {!r}z;yield was used instead of yield from in task {!r} with {!r}zIyield was used instead of yield from for generator in task {!r} with {!r}zTask got bad yield: {!r}) r?r&�formatr-�
isinstancer�CancelledErrorr+r,r0rr�send�throw�
StopIteration�
set_exception�
set_result�valuer(r@�	Exception�
BaseException�getattrr.r/�RuntimeErrorrA�add_done_callback�_wakeup�inspectZisgenerator�pop)r2�excr3�resultZblocking)r0rrr/�s�



z
Task._stepcCsJy|j�Wn,tk
r8}z|j|�WYdd}~Xn
X|j�d}dS)N)rTrKr/)r2�futurerSrrrrP�szTask._wakeup)N)N)N)�__name__�
__module__�__qualname__�__doc__�weakref�WeakSetr"rr6�classmethodrr#r)rZPY34r8r:r<r>r@r/rP�
__classcell__rr)r0rrs"	!T)r�timeout�return_whenc#s�tj|�stj|�r&tdt|�j��|s2td��|tt	t
fkrNtdj|����dkr^tj
���fdd�t|�D�}t|||��EdHS)a�Wait for the Futures and coroutines given by fs to complete.

    The sequence futures must not be empty.

    Coroutines will be wrapped in Tasks.

    Returns two sets of Future: (done, pending).

    Usage:

        done, pending = yield from asyncio.wait(fs)

    Note: This does not raise TimeoutError! Futures that aren't done
    when the timeout occurs are returned in the second set.
    z expect a list of futures, not %sz#Set of coroutines/Futures is empty.zInvalid return_when value: {}Ncsh|]}t|�d��qS))r)r)r�f)rrrr!7szwait.<locals>.<setcomp>)r�isfuturerr%�	TypeError�typerV�
ValueErrorrrrrBrr�set�_wait)�fsrr^r_r)rrrscGs|j�s|jd�dS)N)r?rI)�waiter�argsrrr�_release_waiter<srj)rccs�|dkrtj�}|dkr"|EdHS|j�}|j|t|�}tjt|�}t||d�}|j|�zhy|EdHWn*t	j
k
r�|j|�|j��YnX|j
�r�|j�S|j|�|j�t	j��Wd|j�XdS)a�Wait for the single Future or coroutine to complete, with timeout.

    Coroutine will be wrapped in Task.

    Returns result of the Future or coroutine.  When a timeout occurs,
    it cancels the task and raises TimeoutError.  To avoid the task
    cancellation, wrap it in shield().

    If the wait is cancelled, the task is also cancelled.

    This function is a coroutine.
    N)r)rr�
create_future�
call_laterrj�	functools�partialrrOrrD�remove_done_callbackr@r?rT�TimeoutError)�futr^rrh�timeout_handle�cbrrrrAs,



c#s�|std��|j��d�|dk	r.|j|t���t|������fdd�}x|D]}|j|�qNWz�EdHWd�dk	r��j�Xt�t�}}x4|D],}|j|�|j	�r�|j
|�q�|j
|�q�W||fS)zeInternal helper for wait() and wait_for().

    The fs argument must be a collection of Futures.
    zSet of Futures is empty.Ncs\�d8��dks6�tks6�tkrX|j�rX|j�dk	rX�dk	rF�j��j�sX�jd�dS)Nrr)rr�	cancelled�	exceptionr@r?rI)r`)�counterr_rrrhrr�_on_completion|sz_wait.<locals>._on_completion)r&rkrlrj�lenrOr@reror?r1)rgr^r_rrwr`r?�pendingr)rvr_rrrhrrfos(



rf)rr^c#s�tj|�stj|�r&tdt|�j���dk	r2�ntj���fdd�t	|�D��ddl
m}|�d��d����fdd	�}���fd
d��t�fdd
��}x�D]}|j
��q�W�r�|dk	rʈj||��xtt���D]}|�Vq�WdS)amReturn an iterator whose values are coroutines.

    When waiting for the yielded coroutines you'll get the results (or
    exceptions!) of the original Futures (or coroutines), in the order
    in which and as soon as they complete.

    This differs from PEP 3148; the proper way to use this is:

        for f in as_completed(fs):
            result = yield from f  # The 'yield from' may raise.
            # Use result.

    If a timeout is specified, the 'yield from' will raise
    TimeoutError when the timeout occurs before all Futures are done.

    Note: The futures 'f' are not necessarily members of fs.
    z expect a list of futures, not %sNcsh|]}t|�d��qS))r)r)rr`)rrrr!�szas_completed.<locals>.<setcomp>r)�Queue)rcs.x �D]}|j���jd�qW�j�dS)N)ro�
put_nowait�clear)r`)rwr?�todorr�_on_timeout�s

z!as_completed.<locals>._on_timeoutcs6�sdS�j|��j|��r2�dk	r2�j�dS)N)�remover{r@)r`)r?rrr}rrrw�s

z$as_completed.<locals>._on_completionc3s$�j�EdH}|dkrtj�|j�S)N)rrrprT)r`)r?rr�
_wait_for_one�sz#as_completed.<locals>._wait_for_one)rrarr%rbrcrVrrreZqueuesrzrrOrl�rangerx)rgrr^rzr~r�r`�_r)rwr?rrrr}rr�s 

c
csX|dkrdV|S|dkr"tj�}|j�}|jj|tj||�}z
|EdHS|j�XdS)z9Coroutine that completes after a given time (in seconds).rN)rrrkrrlrZ_set_result_unless_cancelledr@)ZdelayrTrrU�hrrrr�s
cCstjdtdd�t||d�S)z�Wrap a coroutine in a future.

    If the argument is a Future, it is returned directly.

    This function is deprecated in 3.5. Use asyncio.ensure_future() instead.
    z;asyncio.async() function is deprecated, use ensure_future()�)�
stacklevel)r)�warnings�warn�DeprecationWarningr)�coro_or_futurerrrr�async_�sr�cCs�tj|�r(|dk	r$||jk	r$td��|Stj|�r^|dkrBtj�}|j|�}|j	rZ|j	d=|St
jr~tj
|�r~tt|�|d�Std��dS)zmWrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    Nz$loop argument must agree with Futurer)rz:An asyncio.Future, a coroutine or an awaitable is requiredr$)rrarrdrr%rrZcreate_taskr*rZPY35rQZisawaitabler�_wrap_awaitablerb)r�rr4rrrr�s


ccs|j�EdHS)z�Helper for asyncio.ensure_future().

    Wraps awaitable (an object with __await__) into a coroutine
    that will later be wrapped in a Task by ensure_future().
    N)�	__await__)Z	awaitablerrrr�sr�cs.eZdZdZdd��fdd�
Zdd�Z�ZS)�_GatheringFuturez�Helper for gather().

    This overrides cancel() to cancel all the children and act more
    like Task.cancel(), which doesn't immediately mark itself as
    cancelled.
    N)rcst�j|d�||_d|_dS)N)rF)r(r)�	_children�_cancel_requested)r2�childrenr)r0rrr)$sz_GatheringFuture.__init__cCs:|j�rdSd}x|jD]}|j�rd}qW|r6d|_|S)NFT)r?r�r@r�)r2ZretZchildrrrr@)sz_GatheringFuture.cancel)rVrWrXrYr)r@r]rr)r0rr�sr�F)r�return_exceptionscs|s*|dkrtj�}|j���jg��Si�xjt|�D]^}tj|�sht||d�}|dkr`|j}d|_	n&|}|dkr||j}n|j|k	r�t
d��|�|<q8W�fdd�|D�}t|��t||d��d�dg�������fdd	�}x&t
|�D]\}}|jtj||��q�W�S)
a7Return a future aggregating results from the given coroutines
    or futures.

    Coroutines will be wrapped in a future and scheduled in the event
    loop. They will not necessarily be scheduled in the same order as
    passed in.

    All futures must share the same event loop.  If all the tasks are
    done successfully, the returned future's result is the list of
    results (in the order of the original sequence, not necessarily
    the order of results arrival).  If *return_exceptions* is True,
    exceptions in the tasks are treated the same as successful
    results, and gathered in the result list; otherwise, the first
    raised exception will be immediately propagated to the returned
    future.

    Cancellation: if the outer Future is cancelled, all children (that
    have not completed yet) are also cancelled.  If any child is
    cancelled, this is treated as if it raised CancelledError --
    the outer Future is *not* cancelled in this case.  (This is to
    prevent the cancellation of one child to cause other children to
    be cancelled.)
    N)rFz)futures are tied to different event loopscsg|]}�|�qSrr)r�arg)�
arg_to_futrr�
<listcomp>hszgather.<locals>.<listcomp>rcs��j�r|j�s|j�dS|j�r@tj�}�sl�j|�dSn,|jdk	rf|j�}�sl�j|�dSn|j}|�|<�d7���kr��jr��jtj��n
�j	��dS)Nr)
r?rtrurrDrHZ
_exceptionZ_resultr�rI)�irq�res)�	nchildren�	nfinished�outer�resultsr�rr�_done_callbackns*


zgather.<locals>._done_callback)rrrkrIrerrarrr6rdrxr��	enumeraterOrmrn)rr�Zcoros_or_futuresr�rqr�r�r�r)r�r�r�r�r�r�rr
8s8



cs@t||d�}|j�r|S|j}|j���fdd�}|j|��S)a=Wait for a future, shielding it from cancellation.

    The statement

        res = yield from shield(something())

    is exactly equivalent to the statement

        res = yield from something()

    *except* that if the coroutine containing it is cancelled, the
    task running in something() is not cancelled.  From the POV of
    something(), the cancellation did not happen.  But its caller is
    still cancelled, so the yield-from expression still raises
    CancelledError.  Note: If something() is cancelled by other means
    this will still cancel shield().

    If you want to completely ignore cancellation (not recommended)
    you can combine shield() with a try/except clause, as follows:

        try:
            res = yield from shield(something())
        except CancelledError:
            res = None
    )rcs\�j�r|j�s|j�dS|j�r.�j�n*|j�}|dk	rJ�j|�n�j|j��dS)N)rtrur@rHrIrT)�innerrS)r�rrr��s
zshield.<locals>._done_callback)rr?rrkrO)r�rr�r�r)r�rr�s
cs:tj��std��tjj�����fdd�}�j|��S)zsSubmit a coroutine object to a given event loop.

    Return a concurrent.futures.Future to access the result.
    zA coroutine object is requiredcsTytjt��d���Wn6tk
rN}z�j�r<�j|��WYdd}~XnXdS)N)r)rZ
_chain_futurerrKZset_running_or_notify_cancelrH)rS)r3rUrrr�callback�s
z*run_coroutine_threadsafe.<locals>.callback)rr%rb�
concurrentrr7Zcall_soon_threadsafe)r3rr�r)r3rUrrr
�s


)N)'rY�__all__Zconcurrent.futuresr�rmrQr�rZ�rrrrrrr7rZ_PyTaskZ_asyncio�ImportErrorZ_CTaskrrrrrjrrfrrr��globalsrVrr�r�r
rr
rrrr�<module>sZ
s
--8

W5PK[ϤУ'__pycache__/base_futures.cpython-36.pycnu�[���3


 \�@srgZddlZddlZddlmZejjjZejj	Z	ejj
Z
Gdd�de�ZdZdZ
dZd	d
�Zdd�Zd
d�ZdS)�N�)�eventsc@seZdZdZdS)�InvalidStateErrorz+The operation is not allowed in this state.N)�__name__�
__module__�__qualname__�__doc__�r	r	�,/usr/lib64/python3.6/asyncio/base_futures.pyr
srZPENDINGZ	CANCELLEDZFINISHEDcCst|jd�o|jdk	S)z�Check for a Future.

    This returns True when obj is a Future instance or is advertising
    itself as duck-type compatible by setting _asyncio_future_blocking.
    See comment in Future for more details.
    �_asyncio_future_blockingN)�hasattr�	__class__r)�objr	r	r
�isfuturesrcCs�t|�}|sd}dd�}|dkr.||d�}nP|dkrTdj||d�||d��}n*|dkr~dj||d�|d||d
��}d	|S)z#helper function for Future.__repr__�cSstj|f�S)N)rZ_format_callback_source)�callbackr	r	r
�	format_cb(sz$_format_callbacks.<locals>.format_cbrr�z{}, {}z{}, <{} more>, {}zcb=[%s]���)�len�format)�cb�sizerr	r	r
�_format_callbacks"srcCs�|jj�g}|jtkrP|jdk	r4|jdj|j��ntj|j�}|jdj|��|j	rf|jt
|j	��|jr�|jd}|jd|d|df�|S)z#helper function for Future.__repr__Nzexception={!r}z	result={}rzcreated at %s:%srr)Z_state�lower�	_FINISHEDZ
_exception�appendr�reprlib�reprZ_resultZ
_callbacksrZ_source_traceback)Zfuture�info�result�framer	r	r
�_future_repr_info6s


r")�__all__Zconcurrent.futures._baseZ
concurrentrrrZfuturesZ_base�ErrorZCancelledError�TimeoutErrorrZ_PENDINGZ
_CANCELLEDrrrr"r	r	r	r
�<module>s
PK[�pä�b�b!__pycache__/events.cpython-36.pycnu�[���3


 \�[�@s�dZddddddddd	d
ddd
dgZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddlm
Z
dd�Zdd�Zd3dd�Zdd�Zd4dd�ZGdd�d�ZGd d�de�ZGd!d�d�ZGd"d�d�ZGd#d�d�ZGd$d%�d%e�Zdae	j�ZGd&d'�d'e	j�Ze�Zd(d�Zd)d
�Z d*d+�Z!d,d�Z"d-d�Z#d.d�Z$d/d	�Z%d0d
�Z&d1d�Z'd2d�Z(dS)5z!Event loop and event loop policy.�AbstractEventLoopPolicy�AbstractEventLoop�AbstractServer�Handle�TimerHandle�get_event_loop_policy�set_event_loop_policy�get_event_loop�set_event_loop�new_event_loop�get_child_watcher�set_child_watcher�_set_running_loop�_get_running_loop�N�)�compat)�	constantscCsttjrtj|�}nt|d�r"|j}tj|�r>|j}|j|j	fSt
|tj�rTt
|j�Stjrpt
|tj�rpt
|j�SdS)N�__wrapped__)rZPY34�inspectZunwrap�hasattrrZ
isfunction�__code__�co_filename�co_firstlineno�
isinstance�	functools�partial�_get_function_source�func�
partialmethod)r�code�r �&/usr/lib64/python3.6/asyncio/events.pyrs



rcCsJg}|r|jdd�|D��|r8|jdd�|j�D��ddj|�dS)z�Format function arguments and keyword arguments.

    Special case for a single parameter: ('hello',) is formatted as ('hello').
    css|]}tj|�VqdS)N)�reprlib�repr)�.0�argr r r!�	<genexpr>1sz*_format_args_and_kwargs.<locals>.<genexpr>css$|]\}}dj|tj|��VqdS)z{}={}N)�formatr"r#)r$�k�vr r r!r&3s�(z, �))�extend�items�join)�args�kwargsr-r r r!�_format_args_and_kwargs)s
r1�cCs�t|tj�r.t||�|}t|j|j|j|�St|d�rF|j	rF|j	}n t|d�r^|j
r^|j
}nt|�}|t||�7}|r�||7}|S)N�__qualname__�__name__)rrrr1�_format_callbackrr/�keywordsrr3r4r#)rr/r0�suffix�	func_reprr r r!r58sr5cCs(t||d�}t|�}|r$|d|7}|S)Nz	 at %s:%s)r5r)rr/r8�sourcer r r!�_format_callback_sourceIs
r:cCsD|dkrtj�j}|dkr tj}tjjtj|�|dd�}|j	�|S)zlReplacement for traceback.extract_stack() that only does the
    necessary work for asyncio debug mode.
    NF)�limit�lookup_lines)
�sys�	_getframe�f_backrZDEBUG_STACK_DEPTH�	traceback�StackSummary�extract�
walk_stack�reverse)�fr;�stackr r r!�
extract_stackQs
rGc@s<eZdZdZdZd	d
�Zdd�Zd
d�Zdd�Zdd�Z	dS)rz1Object returned by callback registration methods.�	_callback�_args�
_cancelled�_loop�_source_traceback�_repr�__weakref__cCsD||_||_||_d|_d|_|jj�r:ttjd��|_	nd|_	dS)NFr)
rKrHrIrJrM�	get_debugrGr=r>rL)�self�callbackr/�loopr r r!�__init__hs
zHandle.__init__cCsf|jjg}|jr|jd�|jdk	r8|jt|j|j��|jrb|jd}|jd|d|df�|S)NZ	cancelledrzcreated at %s:%sr���)�	__class__r4rJ�appendrHr:rIrL)rP�info�framer r r!�
_repr_infoss



zHandle._repr_infocCs&|jdk	r|jS|j�}ddj|�S)Nz<%s>� )rMrYr.)rPrWr r r!�__repr__~s
zHandle.__repr__cCs0|js,d|_|jj�r t|�|_d|_d|_dS)NT)rJrKrOr#rMrHrI)rPr r r!�cancel�s

z
Handle.cancelcCs|y|j|j�Wnbtk
rr}zFt|j|j�}dj|�}|||d�}|jrV|j|d<|jj|�WYdd}~XnXd}dS)NzException in callback {})�messageZ	exception�handleZsource_traceback)rHrI�	Exceptionr:r'rLrK�call_exception_handler)rP�exc�cb�msg�contextr r r!�_run�s

zHandle._runN)rHrIrJrKrLrMrN)
r4�
__module__r3�__doc__�	__slots__rSrYr[r\rer r r r!rbscsxeZdZdZddgZ�fdd�Z�fdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
�fdd�Z�ZS)rz7Object returned by timed callback registration methods.�
_scheduled�_whencs:|dk	st�t�j|||�|jr*|jd=||_d|_dS)NrFrT)�AssertionError�superrSrLrjri)rP�whenrQr/rR)rUr r!rS�szTimerHandle.__init__cs.t�j�}|jrdnd}|j|d|j�|S)N�rzwhen=%s)rlrYrJ�insertrj)rPrW�pos)rUr r!rY�s
zTimerHandle._repr_infocCs
t|j�S)N)�hashrj)rPr r r!�__hash__�szTimerHandle.__hash__cCs|j|jkS)N)rj)rP�otherr r r!�__lt__�szTimerHandle.__lt__cCs|j|jkrdS|j|�S)NT)rj�__eq__)rPrsr r r!�__le__�szTimerHandle.__le__cCs|j|jkS)N)rj)rPrsr r r!�__gt__�szTimerHandle.__gt__cCs|j|jkrdS|j|�S)NT)rjru)rPrsr r r!�__ge__�szTimerHandle.__ge__cCs>t|t�r:|j|jko8|j|jko8|j|jko8|j|jkStS)N)rrrjrHrIrJ�NotImplemented)rPrsr r r!ru�s
zTimerHandle.__eq__cCs|j|�}|tkrtS|S)N)rury)rPrsZequalr r r!�__ne__�s
zTimerHandle.__ne__cs |js|jj|�t�j�dS)N)rJrK�_timer_handle_cancelledrlr\)rP)rUr r!r\�szTimerHandle.cancel)r4rfr3rgrhrSrYrrrtrvrwrxrurzr\�
__classcell__r r )rUr!r�sc@s eZdZdZdd�Zdd�ZdS)rz,Abstract server returned by create_server().cCstS)z5Stop serving.  This leaves existing connections open.)ry)rPr r r!�close�szAbstractServer.closecCstS)z*Coroutine to wait until service is closed.)ry)rPr r r!�wait_closed�szAbstractServer.wait_closedN)r4rfr3rgr}r~r r r r!r�sc	@seZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d$d$d$d%�d&d'�Zdhd(d)�Zdid*d$d$d$d*d*d*d+�d,d-�Zdjejejd*d.d*d*d*d/�d0d1�Zd*d*d*d2�d3d4�Zd*d.d*d5�d6d7�Zdkd$d$d$d*d*d*d*d8�d9d:�Zd;d<�Zd=d>�Z e!j"e!j"e!j"d?�d@dA�Z#e!j"e!j"e!j"d?�dBdC�Z$dDdE�Z%dFdG�Z&dHdI�Z'dJdK�Z(dLdM�Z)dNdO�Z*dPdQ�Z+dRdS�Z,dTdU�Z-dVdW�Z.dXdY�Z/dZd[�Z0d\d]�Z1d^d_�Z2d`da�Z3dbdc�Z4ddde�Z5dfdg�Z6d*S)lrzAbstract event loop.cCst�dS)z*Run the event loop until stop() is called.N)�NotImplementedError)rPr r r!�run_forever�szAbstractEventLoop.run_forevercCst�dS)zpRun the event loop until a Future is done.

        Return the Future's result, or raise its exception.
        N)r)rPZfuturer r r!�run_until_complete�sz$AbstractEventLoop.run_until_completecCst�dS)z�Stop the event loop as soon as reasonable.

        Exactly how soon that is may depend on the implementation, but
        no more I/O callbacks should be scheduled.
        N)r)rPr r r!�stop�szAbstractEventLoop.stopcCst�dS)z3Return whether the event loop is currently running.N)r)rPr r r!�
is_running�szAbstractEventLoop.is_runningcCst�dS)z*Returns True if the event loop was closed.N)r)rPr r r!�	is_closedszAbstractEventLoop.is_closedcCst�dS)z�Close the loop.

        The loop should not be running.

        This is idempotent and irreversible.

        No other methods should be called after this one.
        N)r)rPr r r!r}s	zAbstractEventLoop.closecCst�dS)z,Shutdown all active asynchronous generators.N)r)rPr r r!�shutdown_asyncgenssz$AbstractEventLoop.shutdown_asyncgenscCst�dS)z3Notification that a TimerHandle has been cancelled.N)r)rPr^r r r!r{sz)AbstractEventLoop._timer_handle_cancelledcGs|jd|f|��S)Nr)�
call_later)rPrQr/r r r!�	call_soonszAbstractEventLoop.call_sooncGst�dS)N)r)rPZdelayrQr/r r r!r�szAbstractEventLoop.call_latercGst�dS)N)r)rPrmrQr/r r r!�call_atszAbstractEventLoop.call_atcCst�dS)N)r)rPr r r!�time"szAbstractEventLoop.timecCst�dS)N)r)rPr r r!�
create_future%szAbstractEventLoop.create_futurecCst�dS)N)r)rP�coror r r!�create_task*szAbstractEventLoop.create_taskcGst�dS)N)r)rPrQr/r r r!�call_soon_threadsafe/sz&AbstractEventLoop.call_soon_threadsafecGst�dS)N)r)rP�executorrr/r r r!�run_in_executor2sz!AbstractEventLoop.run_in_executorcCst�dS)N)r)rPr�r r r!�set_default_executor5sz&AbstractEventLoop.set_default_executorr)�family�type�proto�flagscCst�dS)N)r)rP�host�portr�r�r�r�r r r!�getaddrinfo:szAbstractEventLoop.getaddrinfocCst�dS)N)r)rPZsockaddrr�r r r!�getnameinfo=szAbstractEventLoop.getnameinfoN)�sslr�r�r��sock�
local_addr�server_hostnamecCst�dS)N)r)rP�protocol_factoryr�r�r�r�r�r�r�r�r�r r r!�create_connection@sz#AbstractEventLoop.create_connection�d)r�r�r��backlogr��
reuse_address�
reuse_portcCst�dS)a�A coroutine which creates a TCP server bound to host and port.

        The return value is a Server object which can be used to stop
        the service.

        If host is an empty string or None all interfaces are assumed
        and a list of multiple sockets will be returned (most likely
        one for IPv4 and another one for IPv6). The host parameter can also be a
        sequence (e.g. list) of hosts to bind to.

        family can be set to either AF_INET or AF_INET6 to force the
        socket to use IPv4 or IPv6. If not set it will be determined
        from host (defaults to AF_UNSPEC).

        flags is a bitmask for getaddrinfo().

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows.
        N)r)rPr�r�r�r�r�r�r�r�r�r�r r r!�
create_serverEs'zAbstractEventLoop.create_server)r�r�r�cCst�dS)N)r)rPr��pathr�r�r�r r r!�create_unix_connectionnsz(AbstractEventLoop.create_unix_connection)r�r�r�cCst�dS)a#A coroutine which creates a UNIX Domain Socket server.

        The return value is a Server object, which can be used to stop
        the service.

        path is a str, representing a file systsem path to bind the
        server socket to.

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.
        N)r)rPr�r�r�r�r�r r r!�create_unix_serverssz$AbstractEventLoop.create_unix_server)r�r�r�r�r��allow_broadcastr�cCst�dS)a�A coroutine which creates a datagram endpoint.

        This method will try to establish the endpoint in the background.
        When successful, the coroutine returns a (transport, protocol) pair.

        protocol_factory must be a callable returning a protocol instance.

        socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_DGRAM.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified it will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows and some UNIX's. If the
        :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
        capability is unsupported.

        allow_broadcast tells the kernel to allow this endpoint to send
        messages to the broadcast address.

        sock can optionally be specified in order to use a preexisting
        socket object.
        N)r)rPr�r�Zremote_addrr�r�r�r�r�r�r�r r r!�create_datagram_endpoint�s!z*AbstractEventLoop.create_datagram_endpointcCst�dS)aRegister read pipe in event loop. Set the pipe to non-blocking mode.

        protocol_factory should instantiate object with Protocol interface.
        pipe is a file-like object.
        Return pair (transport, protocol), where transport supports the
        ReadTransport interface.N)r)rPr��piper r r!�connect_read_pipe�sz#AbstractEventLoop.connect_read_pipecCst�dS)aRegister write pipe in event loop.

        protocol_factory should instantiate object with BaseProtocol interface.
        Pipe is file-like object already switched to nonblocking.
        Return pair (transport, protocol), where transport support
        WriteTransport interface.N)r)rPr�r�r r r!�connect_write_pipe�sz$AbstractEventLoop.connect_write_pipe)�stdin�stdout�stderrcKst�dS)N)r)rPr��cmdr�r�r�r0r r r!�subprocess_shell�sz"AbstractEventLoop.subprocess_shellcOst�dS)N)r)rPr�r�r�r�r/r0r r r!�subprocess_exec�sz!AbstractEventLoop.subprocess_execcGst�dS)N)r)rP�fdrQr/r r r!�
add_reader�szAbstractEventLoop.add_readercCst�dS)N)r)rPr�r r r!�
remove_reader�szAbstractEventLoop.remove_readercGst�dS)N)r)rPr�rQr/r r r!�
add_writer�szAbstractEventLoop.add_writercCst�dS)N)r)rPr�r r r!�
remove_writer�szAbstractEventLoop.remove_writercCst�dS)N)r)rPr��nbytesr r r!�	sock_recv�szAbstractEventLoop.sock_recvcCst�dS)N)r)rPr��datar r r!�sock_sendall�szAbstractEventLoop.sock_sendallcCst�dS)N)r)rPr�Zaddressr r r!�sock_connect�szAbstractEventLoop.sock_connectcCst�dS)N)r)rPr�r r r!�sock_accept�szAbstractEventLoop.sock_acceptcGst�dS)N)r)rP�sigrQr/r r r!�add_signal_handler�sz$AbstractEventLoop.add_signal_handlercCst�dS)N)r)rPr�r r r!�remove_signal_handler�sz'AbstractEventLoop.remove_signal_handlercCst�dS)N)r)rP�factoryr r r!�set_task_factory�sz"AbstractEventLoop.set_task_factorycCst�dS)N)r)rPr r r!�get_task_factory�sz"AbstractEventLoop.get_task_factorycCst�dS)N)r)rPr r r!�get_exception_handlersz'AbstractEventLoop.get_exception_handlercCst�dS)N)r)rPZhandlerr r r!�set_exception_handlersz'AbstractEventLoop.set_exception_handlercCst�dS)N)r)rPrdr r r!�default_exception_handlersz+AbstractEventLoop.default_exception_handlercCst�dS)N)r)rPrdr r r!r`sz(AbstractEventLoop.call_exception_handlercCst�dS)N)r)rPr r r!rOszAbstractEventLoop.get_debugcCst�dS)N)r)rPZenabledr r r!�	set_debugszAbstractEventLoop.set_debug)r)NN)NN)NN)7r4rfr3rgr�r�r�r�r�r}r�r{r�r�r�r�r�r�r�r�r�r�r�r��socketZ	AF_UNSPECZ
AI_PASSIVEr�r�r�r�r�r��
subprocess�PIPEr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r`rOr�r r r r!r�st

'!

	c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
rz-Abstract policy for accessing the event loop.cCst�dS)a:Get the event loop for the current context.

        Returns an event loop object implementing the BaseEventLoop interface,
        or raises an exception in case no event loop has been set for the
        current context and the current policy does not specify to create one.

        It should never return None.N)r)rPr r r!rsz&AbstractEventLoopPolicy.get_event_loopcCst�dS)z3Set the event loop for the current context to loop.N)r)rPrRr r r!r	$sz&AbstractEventLoopPolicy.set_event_loopcCst�dS)z�Create and return a new event loop object according to this
        policy's rules. If there's need to set this loop as the event loop for
        the current context, set_event_loop must be called explicitly.N)r)rPr r r!r
(sz&AbstractEventLoopPolicy.new_event_loopcCst�dS)z$Get the watcher for child processes.N)r)rPr r r!r0sz)AbstractEventLoopPolicy.get_child_watchercCst�dS)z$Set the watcher for child processes.N)r)rP�watcherr r r!r4sz)AbstractEventLoopPolicy.set_child_watcherN)	r4rfr3rgrr	r
rrr r r r!rs
c@sFeZdZdZdZGdd�dej�Zdd�Zdd�Z	d	d
�Z
dd�ZdS)
�BaseDefaultEventLoopPolicya�Default policy implementation for accessing the event loop.

    In this policy, each thread has its own event loop.  However, we
    only automatically create an event loop by default for the main
    thread; other threads by default have no event loop.

    Other policies may have different rules (e.g. a single global
    event loop, or automatically creating an event loop per thread, or
    using some other notion of context to which an event loop is
    associated).
    Nc@seZdZdZdZdS)z!BaseDefaultEventLoopPolicy._LocalNF)r4rfr3rK�_set_calledr r r r!�_LocalHsr�cCs|j�|_dS)N)r��_local)rPr r r!rSLsz#BaseDefaultEventLoopPolicy.__init__cCsZ|jjdkr4|jjr4ttj�tj�r4|j|j��|jjdkrRt	dtj�j
��|jjS)zSGet the event loop.

        This may be None or an instance of EventLoop.
        Nz,There is no current event loop in thread %r.)r�rKr�r�	threadingZcurrent_threadZ_MainThreadr	r
�RuntimeError�name)rPr r r!rOs
z)BaseDefaultEventLoopPolicy.get_event_loopcCs*d|j_|dkst|t�st�||j_dS)zSet the event loop.TN)r�r�rrrkrK)rPrRr r r!r	]sz)BaseDefaultEventLoopPolicy.set_event_loopcCs|j�S)zvCreate a new event loop.

        You must call set_event_loop() to make this the current event
        loop.
        )�
_loop_factory)rPr r r!r
csz)BaseDefaultEventLoopPolicy.new_event_loop)r4rfr3rgr�r��localr�rSrr	r
r r r r!r�9sr�c@seZdZdZdS)�_RunningLoopN)NN)r4rfr3�loop_pidr r r r!r�wsr�cCs&tj\}}|dk	r"|tj�kr"|SdS)z�Return the running event loop or None.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)�
_running_loopr��os�getpid)Zrunning_loop�pidr r r!r~s
cCs|tj�ft_dS)z�Set the running event loop.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)r�r�r�r�)rRr r r!r
�sc	Cs.t� tdkr ddlm}|�aWdQRXdS)Nr)�DefaultEventLoopPolicy)�_lock�_event_loop_policyr2r�)r�r r r!�_init_event_loop_policy�sr�cCstdkrt�tS)z"Get the current event loop policy.N)r�r�r r r r!r�scCs|dkst|t�st�|adS)zZSet the current event loop policy.

    If policy is None, the default policy is restored.N)rrrkr�)Zpolicyr r r!r�scCst�}|dk	r|St�j�S)aGReturn an asyncio event loop.

    When called from a coroutine or a callback (e.g. scheduled with call_soon
    or similar API), this function will always return the running event loop.

    If there is no running event loop set, the function will return
    the result of `get_event_loop_policy().get_event_loop()` call.
    N)rrr)Zcurrent_loopr r r!r�s	cCst�j|�dS)zCEquivalent to calling get_event_loop_policy().set_event_loop(loop).N)rr	)rRr r r!r	�scCs
t�j�S)z?Equivalent to calling get_event_loop_policy().new_event_loop().)rr
r r r r!r
�scCs
t�j�S)zBEquivalent to calling get_event_loop_policy().get_child_watcher().)rrr r r r!r�scCst�j|�S)zMEquivalent to calling
    get_event_loop_policy().set_child_watcher(watcher).)rr)r�r r r!r�s)r2)NN))rg�__all__rrr�r"r�r�r=r�r@r2rrrr1r5r:rGrrrrrr�r�ZLockr�r�r�r�rr
r�rrrr	r
rrr r r r!�<module>sZ

>85"7		PK[�ny�0$0$*__pycache__/base_subprocess.cpython-36.pycnu�[���3


 \�#�@s�ddlZddlZddlZddlmZddlmZddlmZddlmZddl	m
Z
Gdd	�d	ej�ZGd
d�dej
�ZGdd
�d
eej�ZdS)�N�)�compat)�	protocols)�
transports)�	coroutine)�loggercs�eZdZd0�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jrTdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zed d!��Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zed*d+��Zd,d-�Zd.d/�Z�ZS)1�BaseSubprocessTransportNc
s&t�j|
�d|_||_||_d|_d|_d|_g|_t	j
�|_i|_d|_
|tjkr`d|jd<|tjkrtd|jd<|tjkr�d|jd<y"|jf||||||d�|��Wn|j��YnX|jj|_|j|jd<|jj��rt|ttf�r�|}n|d}tjd||j�|jj|j|	��dS)NFrr�)�args�shell�stdin�stdout�stderr�bufsize�
subprocesszprocess %r created: pid %s)�super�__init__�_closed�	_protocol�_loop�_proc�_pid�_returncode�
_exit_waiters�collections�deque�_pending_calls�_pipes�	_finishedr�PIPE�_start�close�pidZ_extra�	get_debug�
isinstance�bytes�strr�debugZcreate_task�_connect_pipes)
�self�loop�protocolr
rrr
rr�waiterZextra�kwargsZprogram)�	__class__��//usr/lib64/python3.6/asyncio/base_subprocess.pyrs@








z BaseSubprocessTransport.__init__cCs|jjg}|jr|jd�|jdk	r4|jd|j�|jdk	rP|jd|j�n |jdk	rf|jd�n
|jd�|jjd�}|dk	r�|jd|j�|jjd�}|jjd	�}|dk	r�||kr�|jd
|j�n0|dk	r�|jd|j�|dk	r�|jd|j�d
dj	|�S)N�closedzpid=%sz
returncode=%sZrunningznot startedrzstdin=%srr	zstdout=stderr=%sz	stdout=%sz	stderr=%sz<%s>� )
r.�__name__r�appendrrr�get�pipe�join)r)�inforr
rr/r/r0�__repr__9s,





z BaseSubprocessTransport.__repr__cKst�dS)N)�NotImplementedError)r)r
rrr
rrr-r/r/r0r VszBaseSubprocessTransport._startcCs
||_dS)N)r)r)r+r/r/r0�set_protocolYsz$BaseSubprocessTransport.set_protocolcCs|jS)N)r)r)r/r/r0�get_protocol\sz$BaseSubprocessTransport.get_protocolcCs|jS)N)r)r)r/r/r0�
is_closing_sz"BaseSubprocessTransport.is_closingcCs�|jr
dSd|_x&|jj�D]}|dkr*q|jj�qW|jdk	r�|jdkr�|jj�dkr�|jj	�rpt
jd|�y|jj�Wnt
k
r�YnXdS)NTz$Close running child process: kill %r)rr�valuesr6r!rrZpollrr#rZwarning�kill�ProcessLookupError)r)�protor/r/r0r!bs 


zBaseSubprocessTransport.closecCs&|js"tjd|t|d�|j�dS)Nzunclosed transport %r)�source)r�warnings�warn�ResourceWarningr!)r)r/r/r0�__del__�szBaseSubprocessTransport.__del__cCs|jS)N)r)r)r/r/r0�get_pid�szBaseSubprocessTransport.get_pidcCs|jS)N)r)r)r/r/r0�get_returncode�sz&BaseSubprocessTransport.get_returncodecCs||jkr|j|jSdSdS)N)rr6)r)�fdr/r/r0�get_pipe_transport�s
z*BaseSubprocessTransport.get_pipe_transportcCs|jdkrt��dS)N)rr@)r)r/r/r0�_check_proc�s
z#BaseSubprocessTransport._check_proccCs|j�|jj|�dS)N)rKr�send_signal)r)�signalr/r/r0rL�sz#BaseSubprocessTransport.send_signalcCs|j�|jj�dS)N)rKr�	terminate)r)r/r/r0rN�sz!BaseSubprocessTransport.terminatecCs|j�|jj�dS)N)rKrr?)r)r/r/r0r?�szBaseSubprocessTransport.killc	#s^y�j}�j}|jdk	rB|j�fdd�|j�EdH\}}|�jd<|jdk	rv|j�fdd�|j�EdH\}}|�jd<|jdk	r�|j�fdd�|j�EdH\}}|�jd<�jdk	s�t	�|j
�jj��x"�jD]\}}|j
|f|��q�Wd�_WnDt
k
�r8}z&|dk	�r(|j��r(|j|�WYdd}~Xn"X|dk	�rZ|j��rZ|jd�dS)Ncs
t�d�S)Nr)�WriteSubprocessPipeProtor/)r)r/r0�<lambda>�sz8BaseSubprocessTransport._connect_pipes.<locals>.<lambda>rcs
t�d�S)Nr)�ReadSubprocessPipeProtor/)r)r/r0rP�srcs
t�d�S)Nr	)rQr/)r)r/r0rP�sr	)rrrZconnect_write_piperr
Zconnect_read_piperr�AssertionError�	call_soonr�connection_made�	Exception�	cancelledZ
set_exception�
set_result)	r)r,�procr*�_r6�callback�data�excr/)r)r0r(�s8









z&BaseSubprocessTransport._connect_pipescGs2|jdk	r|jj||f�n|jj|f|��dS)N)rr4rrS)r)�cbr[r/r/r0�_call�s
zBaseSubprocessTransport._callcCs|j|jj||�|j�dS)N)r^rZpipe_connection_lost�_try_finish)r)rIr\r/r/r0�_pipe_connection_lost�sz-BaseSubprocessTransport._pipe_connection_lostcCs|j|jj||�dS)N)r^rZpipe_data_received)r)rIr[r/r/r0�_pipe_data_received�sz+BaseSubprocessTransport._pipe_data_receivedcCs�|dk	st|��|jdks$t|j��|jj�r<tjd||�||_|jjdkrV||j_|j|j	j
�|j�x |jD]}|j
�st|j|�qtWd|_dS)Nz%r exited with return code %r)rRrrr#rr8r�
returncoder^rZprocess_exitedr_rrVrW)r)rbr,r/r/r0�_process_exited�s
z'BaseSubprocessTransport._process_exitedccs0|jdk	r|jS|jj�}|jj|�|EdHS)zdWait until the process exit and return the process return code.

        This method is a coroutine.N)rrZ
create_futurerr4)r)r,r/r/r0�_wait�s


zBaseSubprocessTransport._waitcCsJ|jst�|jdkrdStdd�|jj�D��rFd|_|j|jd�dS)Ncss|]}|dk	o|jVqdS)N)�disconnected)�.0�pr/r/r0�	<genexpr>�sz6BaseSubprocessTransport._try_finish.<locals>.<genexpr>T)rrRr�allrr>r^�_call_connection_lost)r)r/r/r0r_�s
z#BaseSubprocessTransport._try_finishcCs*z|jj|�Wdd|_d|_d|_XdS)N)r�connection_lostrr)r)r\r/r/r0rj�s
z-BaseSubprocessTransport._call_connection_lost)NN)r3�
__module__�__qualname__rr9r r;r<r=r!rZPY34rFrGrHrJrKrLrNr?rr(r^r`rarcrdr_rj�
__classcell__r/r/)r.r0rs0)%	rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rOcCs||_||_d|_d|_dS)NF)rXrIr6re)r)rXrIr/r/r0rsz!WriteSubprocessPipeProto.__init__cCs
||_dS)N)r6)r)Z	transportr/r/r0rTsz(WriteSubprocessPipeProto.connection_madecCsd|jj|j|jfS)Nz<%s fd=%s pipe=%r>)r.r3rIr6)r)r/r/r0r9sz!WriteSubprocessPipeProto.__repr__cCs d|_|jj|j|�d|_dS)NT)rerXr`rI)r)r\r/r/r0rksz(WriteSubprocessPipeProto.connection_lostcCs|jjj�dS)N)rXr�
pause_writing)r)r/r/r0rosz&WriteSubprocessPipeProto.pause_writingcCs|jjj�dS)N)rXr�resume_writing)r)r/r/r0rpsz'WriteSubprocessPipeProto.resume_writingN)	r3rlrmrrTr9rkrorpr/r/r/r0rOsrOc@seZdZdd�ZdS)rQcCs|jj|j|�dS)N)rXrarI)r)r[r/r/r0�
data_received$sz%ReadSubprocessPipeProto.data_receivedN)r3rlrmrqr/r/r/r0rQ!srQ)rrrC�rrrZ
coroutinesr�logrZSubprocessTransportrZBaseProtocolrOZProtocolrQr/r/r/r0�<module>s{PK[h8�"��.__pycache__/windows_utils.cpython-36.opt-1.pycnu�[���3


 \��@s�dZddlZejdkred��ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddddd	gZd
Z
e	jZe	jZej�Zeed�r�ejZnejejdfdd�Zdde
d�dd�ZGdd	�d	�ZGdd�de	j�ZdS)z*
Various Windows specific bits and pieces
�NZwin32z
win32 only�
socketpair�pipe�Popen�PIPE�
PipeHandlei c
Cs|tjkrd}n|tjkr d}ntd��|tjkr:td��|dkrJtd��tj|||�}z�|j|df�|jd�|j�dd	�\}}tj|||�}yP|jd
�y|j	||f�Wnt
tfk
r�YnX|jd�|j�\}}	Wn|j
��YnXWd|j
�X||fS)z�A socket pair usable as a self-pipe, for Windows.

        Origin: https://gist.github.com/4325783, by Geert Jansen.
        Public domain.
        z	127.0.0.1z::1z?Only AF_INET and AF_INET6 socket address families are supportedz)Only SOCK_STREAM socket type is supportedrzOnly protocol zero is supported�N�FT)�socket�AF_INETZAF_INET6�
ValueError�SOCK_STREAMZbindZlistenZgetsocknameZsetblockingZconnect�BlockingIOError�InterruptedErrorZaccept�close)
Zfamily�type�proto�hostZlsockZaddrZportZcsockZssock�_�r�-/usr/lib64/python3.6/asyncio/windows_utils.pyr%s8






FT)�duplex�
overlapped�bufsizecCs"tjdtj�tt�fd�}|r>tj}tjtj	B}||}}ntj
}tj	}d|}}|tjO}|drp|tjO}|dr�tj}nd}d}	}
yZtj
||tjd||tjtj�}	tj||dtjtj|tj�}
tj|	dd�}|jd�|	|
fS|	dk	�rtj|	�|
dk	�rtj|
��YnXdS)zELike os.pipe() but with overlapped support and using handles not fds.z\\.\pipe\python-pipe-%d-%d-)�prefixrrNT)r)�tempfileZmktemp�os�getpid�next�
_mmap_counter�_winapiZPIPE_ACCESS_DUPLEXZGENERIC_READZ
GENERIC_WRITEZPIPE_ACCESS_INBOUNDZFILE_FLAG_FIRST_PIPE_INSTANCEZFILE_FLAG_OVERLAPPEDZCreateNamedPipeZ	PIPE_WAITZNMPWAIT_WAIT_FOREVERZNULLZ
CreateFileZ
OPEN_EXISTINGZConnectNamedPipeZGetOverlappedResult�CloseHandle)rrrZaddressZopenmode�accessZobsizeZibsizeZflags_and_attribsZh1Zh2ZovrrrrSs@








c@s\eZdZdZdd�Zdd�Zedd��Zdd	�Ze	j
d
�dd�Zd
d�Zdd�Z
dd�ZdS)rz�Wrapper for an overlapped pipe handle which is vaguely file-object like.

    The IOCP event loop can use these instead of socket objects.
    cCs
||_dS)N)�_handle)�self�handlerrr�__init__�szPipeHandle.__init__cCs*|jdk	rd|j}nd}d|jj|fS)Nz	handle=%r�closedz<%s %s>)r"�	__class__�__name__)r#r$rrr�__repr__�s
zPipeHandle.__repr__cCs|jS)N)r")r#rrrr$�szPipeHandle.handlecCs|jdkrtd��|jS)NzI/O operatioon on closed pipe)r"r)r#rrr�fileno�s
zPipeHandle.fileno)r cCs|jdk	r||j�d|_dS)N)r")r#r rrrr�s

zPipeHandle.closecCs*|jdk	r&tjd|t|d�|j�dS)Nzunclosed %r)�source)r"�warnings�warn�ResourceWarningr)r#rrr�__del__�s
zPipeHandle.__del__cCs|S)Nr)r#rrr�	__enter__�szPipeHandle.__enter__cCs|j�dS)N)r)r#�t�v�tbrrr�__exit__�szPipeHandle.__exit__N)r(�
__module__�__qualname__�__doc__r%r)�propertyr$r*rr rr/r0r4rrrrr�scs"eZdZdZd�fdd�	Z�ZS)rz�Replacement for subprocess.Popen using overlapped pipe handles.

    The stdin, stdout, stderr are None or instances of PipeHandle.
    Ncs|d}}}d}	}
}|tkr@tddd�\}}	tj|tj�}n|}|tkrhtdd�\}
}
tj|
d�}n|}|tkr�td	d�\}}tj|d�}n|tkr�|}n|}z�y t�j|f|||d�|��Wn4x$|	|
|fD]}|dk	r�t	j
|�q�W�Yn>X|	dk	�rt|	�|_|
dk	�r"t|
�|_
|dk	�r6t|�|_Wd|tk�rNtj|�|tk�rbtj|�|tk�rvtj|�XdS)
NFT)rr)rr)�stdin�stdout�stderr)FT)TF)TF)rr�msvcrtZopen_osfhandler�O_RDONLY�STDOUT�superr%rr rr9r:r;r)r#�argsr9r:r;�kwdsZ	stdin_rfdZ
stdout_wfdZ
stderr_wfdZstdin_whZ	stdout_rhZ	stderr_rhZstdin_rhZ	stdout_whZ	stderr_wh�h)r'rrr%�sH









zPopen.__init__)NNN)r(r5r6r7r%�
__classcell__rr)r'rr�s)TT)r7�sys�platform�ImportErrorr�	itertoolsr<rr	�
subprocessrr,�__all__ZBUFSIZErr>�countr�hasattrrr
rrrrrrrr�<module>s,

.0-PK[4]�j!j!%__pycache__/coroutines.cpython-36.pycnu�[���3


 \+�@s�dddgZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZdd	lmZdd
l
mZejdZejjo�eejjd��ZyejZejZWnek
r�dZdZYnXy
ejZWnek
r�d
d�ZYnXyddlmZ m!Z"Wne#k
�r*dZ Z"YnXdd�Z$e$�Z%[$dd�Z&Gdd�d�Z'dd�Ze(�Z)dd�Zej*e'fZ+e dk	�r�e+e f7Z+edk	�r�efe+Z+dd�Z,dd�Z-dS)�	coroutine�iscoroutinefunction�iscoroutine�N�)�compat)�	constants)�events)�base_futures)�loggerZ
YIELD_FROMZPYTHONASYNCIODEBUGcCsdS)NF�)�funcrr�*/usr/lib64/python3.6/asyncio/coroutines.py�<lambda>/sr)�	Coroutine�	AwaitablecCsFGdd�d�}dd�}d}|�}||�}t|�|j|�|j|fkS)	Nc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
z!has_yield_from_bug.<locals>.MyGencSs
d|_dS)N)�	send_args)�selfrrr
�__init__;sz*has_yield_from_bug.<locals>.MyGen.__init__cSs|S)Nr)rrrr
�__iter__=sz*has_yield_from_bug.<locals>.MyGen.__iter__cSsdS)N�*r)rrrr
�__next__?sz*has_yield_from_bug.<locals>.MyGen.__next__cWs
||_dS)N)r)rZwhatrrr
�sendAsz&has_yield_from_bug.<locals>.MyGen.sendN)�__name__�
__module__�__qualname__rrrrrrrr
�MyGen:srcss|EdHdS)Nr)�genrrr
�yield_from_genDsz*has_yield_from_bug.<locals>.yield_from_genr��)rrr)�nextrr)rr�valuer�cororrr
�has_yield_from_bug9s

r#cCs
t|d�S)N)�CoroWrapper)rrrr
�
debug_wrapperPsr%c@s�eZdZd%dd�Zdd�Zdd�Zdd	�Zer8d
d�Zndd�Zd&d
d�Z	dd�Z
edd��Zedd��Z
edd��Zejr�dd�Zedd��Zedd��Zedd��Zedd ��Zed!d"��Zd#d$�ZdS)'r$NcCsZtj|�stj|�st|��||_||_tjtj	d��|_
t|dd�|_t|dd�|_
dS)Nrrr)�inspect�isgeneratorr�AssertionErrorrrr�
extract_stack�sys�	_getframe�_source_traceback�getattrrr)rrrrrr
r[szCoroWrapper.__init__cCs@t|�}|jr0|jd}|d|d|df7}d|jj|fS)Nrz, created at %s:%srz<%s %s>���)�_format_coroutiner,�	__class__r)r�	coro_repr�framerrr
�__repr__cs

zCoroWrapper.__repr__cCs|S)Nr)rrrr
rjszCoroWrapper.__iter__cCs|jjd�S)N)rr)rrrr
rmszCoroWrapper.__next__cGsBtj�}|j}|jdkst�|jj|jtkr6|d}|jj	|�S)Nr)
r*r+�f_back�f_lastir(�f_code�co_code�_YIELD_FROMrr)rr!r2Zcallerrrr
ruszCoroWrapper.sendcCs|jj|�S)N)rr)rr!rrr
r}scCs|jj|||�S)N)r�throw)r�typer!�	tracebackrrr
r9�szCoroWrapper.throwcCs
|jj�S)N)r�close)rrrr
r<�szCoroWrapper.closecCs|jjS)N)r�gi_frame)rrrr
r=�szCoroWrapper.gi_framecCs|jjS)N)r�
gi_running)rrrr
r>�szCoroWrapper.gi_runningcCs|jjS)N)r�gi_code)rrrr
r?�szCoroWrapper.gi_codecCs,t|jdd�}|dk	r(tdj|j|���|S)N�cr_awaitz;Cannot await on coroutine {!r} while it's awaiting for {!r})r-r�RuntimeError�format)rr@rrr
�	__await__�szCoroWrapper.__await__cCs|jjS)N)r�gi_yieldfrom)rrrr
rD�szCoroWrapper.gi_yieldfromcCs|jjS)N)rr@)rrrr
r@�szCoroWrapper.cr_awaitcCs|jjS)N)r�
cr_running)rrrr
rE�szCoroWrapper.cr_runningcCs|jjS)N)r�cr_code)rrrr
rF�szCoroWrapper.cr_codecCs|jjS)N)r�cr_frame)rrrr
rG�szCoroWrapper.cr_framecCs�t|dd�}t|dd�}|dkr,t|dd�}|dk	r�|jd
kr�d|}t|df�}|r�djtj|��}|dtj�d	�7}||j�7}tj	|�dS)Nrr=rGrz%r was never yielded fromr,�zB
Coroutine object created at (most recent call last, truncated to z last lines):
r.)
r-r5�joinr;�format_listrZDEBUG_STACK_DEPTH�rstripr
�error)rrr2�msg�tbrrr
�__del__�szCoroWrapper.__del__)N)NN)rrrrr3rr�_YIELD_FROM_BUGrr9r<�propertyr=r>r?rZPY35rCrDr@rErFrGrOrrrr
r$Xs(


r$cspt��r�Stj��r��ntj���fdd���tsNtdkrD�}qft��}ntj����fdd��}t|_|S)z�Decorator to mark coroutines.

    If the coroutine is not yielded from before it is destroyed,
    an error message is logged.
    c?sv�||�}tj|�s(tj|�s(t|t�r4|EdH}n>tdk	rry
|j}Wntk
rZYnXt|t�rr|�EdH}|S)N)	r	Zisfuturer&r'�
isinstancer$�
_AwaitableABCrC�AttributeError)�args�kw�resZ
await_meth)rrr
r"�s



zcoroutine.<locals>.coroNcs@t�||��d�}|jr |jd=t�dd�|_t�dd�|_|S)N)rrrrr.)r$r,r-rr)rU�kwds�w)r"rrr
�wrapper�szcoroutine.<locals>.wrapper)�_inspect_iscoroutinefunctionr&�isgeneratorfunction�	functools�wraps�_DEBUG�_types_coroutine�
_is_coroutine)rrZr)r"rr
r�s


cCst|dd�tkpt|�S)z6Return True if func is a decorated coroutine function.raN)r-rar[)rrrr
r�scCs
t|t�S)z)Return True if obj is a coroutine object.)rR�_COROUTINE_TYPES)�objrrr
rsc
Cs&t|�st�t|d�r�t|d�r�t|dt|dt|�j��}dj|�}d}y
|j}Wn4tk
r�y
|j	}Wntk
r�YnXYnX|r�dj|�S|Sd}t
|t�r�|j}|j
}|dk	r�dj|�}n|}|dkr�tj|fi�}d}t|d�o�|j�r|j}nt|d��r|j�r|j}d}t|d��r>|j�r>|j}nt|d	��rX|j�rX|j}d
}|�rp|j�rp|j}d}|}t
|t��r�tj|j��r�|jdk	�r�tj|j�}	|	dk	�r�|	\}}|dk�r�d|||f}nd
|||f}n:|dk	�r|j}d|||f}n|�r"|j}d|||f}|S)NrFr?rrz{}()Fz
{} runningrGr=z<empty co_filename>rz%s done, defined at %s:%sz%s running, defined at %s:%sz%s running at %s:%s)rr(�hasattrr-r:rrBrErTr>rRr$rrrZ_format_callbackrFr?rGr=�co_filenamer&r\Z_get_function_source�f_lineno�co_firstlineno)
r"Z	coro_nameZrunningrZ	coro_codeZ
coro_frame�filename�linenor1�sourcerrr
r/sz







r/).�__all__r]r&Zopcode�osr*r;�typesrHrrrr	�logr
Zopmapr8�flags�ignore_environment�bool�environ�getr_rr`�
CoroutineTypeZ_types_CoroutineTyperTrr[�collections.abcrZ
_CoroutineABCrrS�ImportErrorr#rPr%r$�objectra�
GeneratorTyperbrr/rrrr
�<module>sZ




j:




PK[{fU���*__pycache__/constants.cpython-36.opt-2.pycnu�[���3


 \s�@sdZdZdZdS)���
N)Z!LOG_THRESHOLD_FOR_CONNLOST_WRITESZACCEPT_RETRY_DELAYZDEBUG_STACK_DEPTH�rr�)/usr/lib64/python3.6/asyncio/constants.py�<module>sPK[�>B�+__pycache__/transports.cpython-36.opt-2.pycnu�[���3


 \R'�@s�ddlmZddddddgZGdd�d�ZGd	d�de�ZGd
d�de�ZGdd�dee�ZGdd�de�ZGd
d�de�ZGdd�de�Z	dS)�)�compat�
BaseTransport�
ReadTransport�WriteTransport�	Transport�DatagramTransport�SubprocessTransportc@s@eZdZddd�Zddd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)rNcCs|dkri}||_dS)N)�_extra)�self�extra�r�*/usr/lib64/python3.6/asyncio/transports.py�__init__
szBaseTransport.__init__cCs|jj||�S)N)r	�get)r
�name�defaultrrr
�get_extra_infoszBaseTransport.get_extra_infocCst�dS)N)�NotImplementedError)r
rrr
�
is_closingszBaseTransport.is_closingcCst�dS)N)r)r
rrr
�closeszBaseTransport.closecCst�dS)N)r)r
�protocolrrr
�set_protocol$szBaseTransport.set_protocolcCst�dS)N)r)r
rrr
�get_protocol(szBaseTransport.get_protocol)N)N)	�__name__�
__module__�__qualname__rrrrrrrrrr
r
s


c@seZdZdd�Zdd�ZdS)rcCst�dS)N)r)r
rrr
�
pause_reading0szReadTransport.pause_readingcCst�dS)N)r)r
rrr
�resume_reading8szReadTransport.resume_readingN)rrrrrrrrr
r-sc@sFeZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dS)rNcCst�dS)N)r)r
�high�lowrrr
�set_write_buffer_limitsDsz&WriteTransport.set_write_buffer_limitscCst�dS)N)r)r
rrr
�get_write_buffer_sizeYsz$WriteTransport.get_write_buffer_sizecCst�dS)N)r)r
�datarrr
�write]szWriteTransport.writecCstj|�}|j|�dS)N)rZflatten_list_bytesr#)r
Zlist_of_datar"rrr
�
writelineses
zWriteTransport.writelinescCst�dS)N)r)r
rrr
�	write_eofnszWriteTransport.write_eofcCst�dS)N)r)r
rrr
�
can_write_eofwszWriteTransport.can_write_eofcCst�dS)N)r)r
rrr
�abort{szWriteTransport.abort)NN)
rrrr r!r#r$r%r&r'rrrr
rAs
		c@seZdZdS)rN)rrrrrrr
r�sc@seZdZddd�Zdd�ZdS)rNcCst�dS)N)r)r
r"Zaddrrrr
�sendto�szDatagramTransport.sendtocCst�dS)N)r)r
rrr
r'�szDatagramTransport.abort)N)rrrr(r'rrrr
r�s

c@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rcCst�dS)N)r)r
rrr
�get_pid�szSubprocessTransport.get_pidcCst�dS)N)r)r
rrr
�get_returncode�sz"SubprocessTransport.get_returncodecCst�dS)N)r)r
�fdrrr
�get_pipe_transport�sz&SubprocessTransport.get_pipe_transportcCst�dS)N)r)r
�signalrrr
�send_signal�szSubprocessTransport.send_signalcCst�dS)N)r)r
rrr
�	terminate�szSubprocessTransport.terminatecCst�dS)N)r)r
rrr
�kill�s	zSubprocessTransport.killN)	rrrr)r*r,r.r/r0rrrr
r�scsReZdZd�fdd�	Zdd�Zdd�Zdd	�Zdd
d�Zddd
�Zdd�Z	�Z
S)�_FlowControlMixinNcs$t�j|�||_d|_|j�dS)NF)�superr�_loop�_protocol_paused�_set_write_buffer_limits)r
rZloop)�	__class__rr
r�sz_FlowControlMixin.__init__cCsp|j�}||jkrdS|jsld|_y|jj�Wn:tk
rj}z|jjd|||jd��WYdd}~XnXdS)NTzprotocol.pause_writing() failed)�message�	exception�	transportr)r!�_high_waterr4�	_protocolZ
pause_writing�	Exceptionr3�call_exception_handler)r
�size�excrrr
�_maybe_pause_protocol�s
z'_FlowControlMixin._maybe_pause_protocolcCsh|jrd|j�|jkrdd|_y|jj�Wn:tk
rb}z|jjd|||jd��WYdd}~XnXdS)NFz protocol.resume_writing() failed)r7r8r9r)r4r!�
_low_waterr;Zresume_writingr<r3r=)r
r?rrr
�_maybe_resume_protocolsz(_FlowControlMixin._maybe_resume_protocolcCs|j|jfS)N)rAr:)r
rrr
�get_write_buffer_limitssz)_FlowControlMixin.get_write_buffer_limitscCsf|dkr|dkrd}nd|}|dkr.|d}||ko@dknsVtd||f��||_||_dS)N�@i�rz*high (%r) must be >= low (%r) must be >= 0i)�
ValueErrorr:rA)r
rrrrr
r5sz*_FlowControlMixin._set_write_buffer_limitscCs|j||d�|j�dS)N)rr)r5r@)r
rrrrr
r -sz)_FlowControlMixin.set_write_buffer_limitscCst�dS)N)r)r
rrr
r!1sz'_FlowControlMixin.get_write_buffer_size)NN)NN)NN)rrrrr@rBrCr5r r!�
__classcell__rr)r6r
r1�s

r1N)
Zasyncior�__all__rrrrrrr1rrrr
�<module>s
#D4PK[�����!__pycache__/compat.cpython-36.pycnu�[���3


 \�@s6dZddlZejd	kZejd
kZejdkZdd�ZdS)z8Compatibility helpers for the different Python versions.�N����cCstsdd�|D�}dj|�S)z-Concatenate a sequence of bytes-like objects.css$|]}t|t�rt|�n|VqdS)N)�
isinstance�
memoryview�bytes)�.0�data�r�&/usr/lib64/python3.6/asyncio/compat.py�	<genexpr>sz%flatten_list_bytes.<locals>.<genexpr>�)�PY34�join)Zlist_of_datarrr�flatten_list_bytes
sr)rr)rr)rrr)�__doc__�sys�version_inforZPY35ZPY352rrrrr�<module>s



PK[C�s//+__pycache__/transports.cpython-36.opt-1.pycnu�[���3


 \R'�@s�dZddlmZddddddgZGd	d�d�ZGd
d�de�ZGdd�de�ZGdd�dee�ZGd
d�de�ZGdd�de�Z	Gdd�de�Z
dS)zAbstract Transport class.�)�compat�
BaseTransport�
ReadTransport�WriteTransport�	Transport�DatagramTransport�SubprocessTransportc@sDeZdZdZddd�Zddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)rzBase class for transports.NcCs|dkri}||_dS)N)�_extra)�self�extra�r�*/usr/lib64/python3.6/asyncio/transports.py�__init__
szBaseTransport.__init__cCs|jj||�S)z#Get optional transport information.)r	�get)r
�name�defaultrrr
�get_extra_infoszBaseTransport.get_extra_infocCst�dS)z2Return True if the transport is closing or closed.N)�NotImplementedError)r
rrr
�
is_closingszBaseTransport.is_closingcCst�dS)a
Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        N)r)r
rrr
�closeszBaseTransport.closecCst�dS)zSet a new protocol.N)r)r
�protocolrrr
�set_protocol$szBaseTransport.set_protocolcCst�dS)zReturn the current protocol.N)r)r
rrr
�get_protocol(szBaseTransport.get_protocol)N)N)
�__name__�
__module__�__qualname__�__doc__rrrrrrrrrr
r
s


c@s eZdZdZdd�Zdd�ZdS)rz#Interface for read-only transports.cCst�dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        N)r)r
rrr
�
pause_reading0szReadTransport.pause_readingcCst�dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        N)r)r
rrr
�resume_reading8szReadTransport.resume_readingN)rrrrrrrrrr
r-sc@sJeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dS)rz$Interface for write-only transports.NcCst�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        N)r)r
�high�lowrrr
�set_write_buffer_limitsDsz&WriteTransport.set_write_buffer_limitscCst�dS)z,Return the current size of the write buffer.N)r)r
rrr
�get_write_buffer_sizeYsz$WriteTransport.get_write_buffer_sizecCst�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        N)r)r
�datarrr
�write]szWriteTransport.writecCstj|�}|j|�dS)z�Write a list (or any iterable) of data bytes to the transport.

        The default implementation concatenates the arguments and
        calls write() on the result.
        N)rZflatten_list_bytesr$)r
Zlist_of_datar#rrr
�
writelineses
zWriteTransport.writelinescCst�dS)z�Close the write end after flushing buffered data.

        (This is like typing ^D into a UNIX program reading from stdin.)

        Data may still be received.
        N)r)r
rrr
�	write_eofnszWriteTransport.write_eofcCst�dS)zAReturn True if this transport supports write_eof(), False if not.N)r)r
rrr
�
can_write_eofwszWriteTransport.can_write_eofcCst�dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        N)r)r
rrr
�abort{szWriteTransport.abort)NN)rrrrr!r"r$r%r&r'r(rrrr
rAs
		c@seZdZdZdS)raSInterface representing a bidirectional transport.

    There may be several implementations, but typically, the user does
    not implement new transports; rather, the platform provides some
    useful transports that are implemented using the platform's best
    practices.

    The user never instantiates a transport directly; they call a
    utility function, passing it a protocol factory and other
    information necessary to create the transport and protocol.  (E.g.
    EventLoop.create_connection() or EventLoop.create_server().)

    The utility function will asynchronously create a transport and a
    protocol and hook them up by calling the protocol's
    connection_made() method, passing it the transport.

    The implementation here raises NotImplemented for every method
    except writelines(), which calls write() in a loop.
    N)rrrrrrrr
r�sc@s"eZdZdZddd�Zdd�ZdS)rz(Interface for datagram (UDP) transports.NcCst�dS)aSend data to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        addr is target socket address.
        If addr is None use target address pointed on transport creation.
        N)r)r
r#Zaddrrrr
�sendto�szDatagramTransport.sendtocCst�dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        N)r)r
rrr
r(�szDatagramTransport.abort)N)rrrrr)r(rrrr
r�s

c@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rcCst�dS)zGet subprocess id.N)r)r
rrr
�get_pid�szSubprocessTransport.get_pidcCst�dS)z�Get subprocess returncode.

        See also
        http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
        N)r)r
rrr
�get_returncode�sz"SubprocessTransport.get_returncodecCst�dS)z&Get transport for pipe with number fd.N)r)r
�fdrrr
�get_pipe_transport�sz&SubprocessTransport.get_pipe_transportcCst�dS)z�Send signal to subprocess.

        See also:
        docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
        N)r)r
�signalrrr
�send_signal�szSubprocessTransport.send_signalcCst�dS)aLStop the subprocess.

        Alias for close() method.

        On Posix OSs the method sends SIGTERM to the subprocess.
        On Windows the Win32 API function TerminateProcess()
         is called to stop the subprocess.

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
        N)r)r
rrr
�	terminate�szSubprocessTransport.terminatecCst�dS)z�Kill the subprocess.

        On Posix OSs the function sends SIGKILL to the subprocess.
        On Windows kill() is an alias for terminate().

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
        N)r)r
rrr
�kill�s	zSubprocessTransport.killN)	rrrr*r+r-r/r0r1rrrr
r�scsVeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zddd�Zdd
d�Z	dd�Z
�ZS)�_FlowControlMixinavAll the logic for (write) flow control in a mix-in base class.

    The subclass must implement get_write_buffer_size().  It must call
    _maybe_pause_protocol() whenever the write buffer size increases,
    and _maybe_resume_protocol() whenever it decreases.  It may also
    override set_write_buffer_limits() (e.g. to specify different
    defaults).

    The subclass constructor must call super().__init__(extra).  This
    will call set_write_buffer_limits().

    The user may call set_write_buffer_limits() and
    get_write_buffer_size(), and their protocol's pause_writing() and
    resume_writing() may be called.
    Ncs$t�j|�||_d|_|j�dS)NF)�superr�_loop�_protocol_paused�_set_write_buffer_limits)r
rZloop)�	__class__rr
r�sz_FlowControlMixin.__init__cCsp|j�}||jkrdS|jsld|_y|jj�Wn:tk
rj}z|jjd|||jd��WYdd}~XnXdS)NTzprotocol.pause_writing() failed)�message�	exception�	transportr)r"�_high_waterr5�	_protocolZ
pause_writing�	Exceptionr4�call_exception_handler)r
�size�excrrr
�_maybe_pause_protocol�s
z'_FlowControlMixin._maybe_pause_protocolcCsh|jrd|j�|jkrdd|_y|jj�Wn:tk
rb}z|jjd|||jd��WYdd}~XnXdS)NFz protocol.resume_writing() failed)r8r9r:r)r5r"�
_low_waterr<Zresume_writingr=r4r>)r
r@rrr
�_maybe_resume_protocolsz(_FlowControlMixin._maybe_resume_protocolcCs|j|jfS)N)rBr;)r
rrr
�get_write_buffer_limitssz)_FlowControlMixin.get_write_buffer_limitscCsf|dkr|dkrd}nd|}|dkr.|d}||ko@dknsVtd||f��||_||_dS)N�@i�rz*high (%r) must be >= low (%r) must be >= 0i)�
ValueErrorr;rB)r
rr rrr
r6sz*_FlowControlMixin._set_write_buffer_limitscCs|j||d�|j�dS)N)rr )r6rA)r
rr rrr
r!-sz)_FlowControlMixin.set_write_buffer_limitscCst�dS)N)r)r
rrr
r"1sz'_FlowControlMixin.get_write_buffer_size)NN)NN)NN)rrrrrrArCrDr6r!r"�
__classcell__rr)r7r
r2�s

r2N)rZasyncior�__all__rrrrrrr2rrrr
�<module>s
#D4PK[G��4GG%__pycache__/base_tasks.cpython-36.pycnu�[���3


 \��@sDddlZddlZddlmZddlmZdd�Zdd�Zd	d
�ZdS)�N�)�base_futures)�
coroutinescCsTtj|�}|jrd|d<tj|j�}|jdd|�|jdk	rP|jdd|j�|S)NZ
cancellingrrz	coro=<%s>�zwait_for=%r)rZ_future_repr_infoZ_must_cancelrZ_format_coroutine�_coro�insertZ_fut_waiter)�task�info�coro�r�*/usr/lib64/python3.6/asyncio/base_tasks.py�_task_repr_infos

r
cCs�g}y|jj}Wntk
r,|jj}YnX|dk	rxx6|dk	rl|dk	rZ|dkrRP|d8}|j|�|j}q8W|j�nL|jdk	r�|jj}x8|dk	r�|dk	r�|dkr�P|d8}|j|j	�|j
}q�W|S)Nrr)r�cr_frame�AttributeError�gi_frame�append�f_back�reverse�
_exception�
__traceback__�tb_frame�tb_next)r�limitZframes�f�tbrrr�_task_get_stacks0






rcCs�g}t�}xj|j|d�D]Z}|j}|j}|j}|j}	||krP|j|�tj|�tj	|||j
�}
|j|||	|
f�qW|j}|s�t
d||d�n*|dk	r�t
d||d�nt
d||d�tj||d�|dk	r�x$tj|j|�D]}
t
|
|dd�q�WdS)N)rzNo stack for %r)�filez)Traceback for %r (most recent call last):z%Stack for %r (most recent call last):�)r�end)�setZ	get_stack�f_lineno�f_code�co_filename�co_name�add�	linecache�
checkcache�getline�	f_globalsrr�print�	traceback�
print_list�format_exception_only�	__class__)rrr�extracted_listZcheckedr�lineno�co�filename�name�line�excrrr�_task_print_stack3s0


r5)r%r*rrrr
rr5rrrr�<module>sPK[ϤУ-__pycache__/base_futures.cpython-36.opt-1.pycnu�[���3


 \�@srgZddlZddlZddlmZejjjZejj	Z	ejj
Z
Gdd�de�ZdZdZ
dZd	d
�Zdd�Zd
d�ZdS)�N�)�eventsc@seZdZdZdS)�InvalidStateErrorz+The operation is not allowed in this state.N)�__name__�
__module__�__qualname__�__doc__�r	r	�,/usr/lib64/python3.6/asyncio/base_futures.pyr
srZPENDINGZ	CANCELLEDZFINISHEDcCst|jd�o|jdk	S)z�Check for a Future.

    This returns True when obj is a Future instance or is advertising
    itself as duck-type compatible by setting _asyncio_future_blocking.
    See comment in Future for more details.
    �_asyncio_future_blockingN)�hasattr�	__class__r)�objr	r	r
�isfuturesrcCs�t|�}|sd}dd�}|dkr.||d�}nP|dkrTdj||d�||d��}n*|dkr~dj||d�|d||d
��}d	|S)z#helper function for Future.__repr__�cSstj|f�S)N)rZ_format_callback_source)�callbackr	r	r
�	format_cb(sz$_format_callbacks.<locals>.format_cbrr�z{}, {}z{}, <{} more>, {}zcb=[%s]���)�len�format)�cb�sizerr	r	r
�_format_callbacks"srcCs�|jj�g}|jtkrP|jdk	r4|jdj|j��ntj|j�}|jdj|��|j	rf|jt
|j	��|jr�|jd}|jd|d|df�|S)z#helper function for Future.__repr__Nzexception={!r}z	result={}rzcreated at %s:%srr)Z_state�lower�	_FINISHEDZ
_exception�appendr�reprlib�reprZ_resultZ
_callbacksrZ_source_traceback)Zfuture�info�result�framer	r	r
�_future_repr_info6s


r")�__all__Zconcurrent.futures._baseZ
concurrentrrrZfuturesZ_base�ErrorZCancelledError�TimeoutErrorrZ_PENDINGZ
_CANCELLEDrrrr"r	r	r	r
�<module>s
PK[/F\:(__pycache__/windows_utils.cpython-36.pycnu�[���3


 \��@s�dZddlZejdkred��ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddddd	gZd
Z
e	jZe	jZej�Zeed�r�ejZnejejdfdd�Zdde
d�dd�ZGdd	�d	�ZGdd�de	j�ZdS)z*
Various Windows specific bits and pieces
�NZwin32z
win32 only�
socketpair�pipe�Popen�PIPE�
PipeHandlei c
Cs|tjkrd}n|tjkr d}ntd��|tjkr:td��|dkrJtd��tj|||�}z�|j|df�|jd�|j�dd	�\}}tj|||�}yP|jd
�y|j	||f�Wnt
tfk
r�YnX|jd�|j�\}}	Wn|j
��YnXWd|j
�X||fS)z�A socket pair usable as a self-pipe, for Windows.

        Origin: https://gist.github.com/4325783, by Geert Jansen.
        Public domain.
        z	127.0.0.1z::1z?Only AF_INET and AF_INET6 socket address families are supportedz)Only SOCK_STREAM socket type is supportedrzOnly protocol zero is supported�N�FT)�socket�AF_INETZAF_INET6�
ValueError�SOCK_STREAMZbindZlistenZgetsocknameZsetblockingZconnect�BlockingIOError�InterruptedErrorZaccept�close)
Zfamily�type�proto�hostZlsockZaddrZportZcsockZssock�_�r�-/usr/lib64/python3.6/asyncio/windows_utils.pyr%s8






FT)�duplex�
overlapped�bufsizecCs"tjdtj�tt�fd�}|r>tj}tjtj	B}||}}ntj
}tj	}d|}}|tjO}|drp|tjO}|dr�tj}nd}d}	}
yZtj
||tjd||tjtj�}	tj||dtjtj|tj�}
tj|	dd�}|jd�|	|
fS|	dk	�rtj|	�|
dk	�rtj|
��YnXdS)zELike os.pipe() but with overlapped support and using handles not fds.z\\.\pipe\python-pipe-%d-%d-)�prefixrrNT)r)�tempfileZmktemp�os�getpid�next�
_mmap_counter�_winapiZPIPE_ACCESS_DUPLEXZGENERIC_READZ
GENERIC_WRITEZPIPE_ACCESS_INBOUNDZFILE_FLAG_FIRST_PIPE_INSTANCEZFILE_FLAG_OVERLAPPEDZCreateNamedPipeZ	PIPE_WAITZNMPWAIT_WAIT_FOREVERZNULLZ
CreateFileZ
OPEN_EXISTINGZConnectNamedPipeZGetOverlappedResult�CloseHandle)rrrZaddressZopenmode�accessZobsizeZibsizeZflags_and_attribsZh1Zh2ZovrrrrSs@








c@s\eZdZdZdd�Zdd�Zedd��Zdd	�Ze	j
d
�dd�Zd
d�Zdd�Z
dd�ZdS)rz�Wrapper for an overlapped pipe handle which is vaguely file-object like.

    The IOCP event loop can use these instead of socket objects.
    cCs
||_dS)N)�_handle)�self�handlerrr�__init__�szPipeHandle.__init__cCs*|jdk	rd|j}nd}d|jj|fS)Nz	handle=%r�closedz<%s %s>)r"�	__class__�__name__)r#r$rrr�__repr__�s
zPipeHandle.__repr__cCs|jS)N)r")r#rrrr$�szPipeHandle.handlecCs|jdkrtd��|jS)NzI/O operatioon on closed pipe)r"r)r#rrr�fileno�s
zPipeHandle.fileno)r cCs|jdk	r||j�d|_dS)N)r")r#r rrrr�s

zPipeHandle.closecCs*|jdk	r&tjd|t|d�|j�dS)Nzunclosed %r)�source)r"�warnings�warn�ResourceWarningr)r#rrr�__del__�s
zPipeHandle.__del__cCs|S)Nr)r#rrr�	__enter__�szPipeHandle.__enter__cCs|j�dS)N)r)r#�t�v�tbrrr�__exit__�szPipeHandle.__exit__N)r(�
__module__�__qualname__�__doc__r%r)�propertyr$r*rr rr/r0r4rrrrr�scs"eZdZdZd�fdd�	Z�ZS)rz�Replacement for subprocess.Popen using overlapped pipe handles.

    The stdin, stdout, stderr are None or instances of PipeHandle.
    Ncs�|jd�st�|jdd�dks$t�d}}}d}	}
}|tkrdtd	dd�\}}	tj|tj�}n|}|tkr�td
d�\}
}
tj|
d�}n|}|tkr�tdd�\}}tj|d�}n|tkr�|}n|}z�y t	�j
|f|||d�|��Wn8x(|	|
|fD]}|dk	�r�tj|��q�W�Yn>X|	dk	�r6t
|	�|_|
dk	�rJt
|
�|_|dk	�r^t
|�|_Wd|tk�rvtj|�|tk�r�tj|�|tk�r�tj|�XdS)NZuniversal_newlinesrrFT)rr)r)�stdin�stdout�stderr)FT)TF)TF)�get�AssertionErrorrr�msvcrtZopen_osfhandler�O_RDONLY�STDOUT�superr%rr rr9r:r;r)r#�argsr9r:r;�kwdsZ	stdin_rfdZ
stdout_wfdZ
stderr_wfdZstdin_whZ	stdout_rhZ	stderr_rhZstdin_rhZ	stdout_whZ	stderr_wh�h)r'rrr%�sL










zPopen.__init__)NNN)r(r5r6r7r%�
__classcell__rr)r'rr�s)TT)r7�sys�platform�ImportErrorr�	itertoolsr>rr	�
subprocessrr,�__all__ZBUFSIZErr@�countr�hasattrrr
rrrrrrrr�<module>s,

.0-PK[��z�4�4(__pycache__/futures.cpython-36.opt-1.pycnu�[���3


 \>�@s
dZddddddgZddlZddlZddlZddlZd	d
lmZd	dlm	Z	d	dlm
Z
ejZejZej
Z
ejZejZejZejZejd	ZGd
d�d�ZGdd�d�ZeZdd�Zdd�Zdd�Zdd�Zdd�dd�ZyddlZWnek
r�YnXejZZdS)z.A Future class similar to the one in PEP 3148.�CancelledError�TimeoutError�InvalidStateError�Future�wrap_future�isfuture�N�)�base_futures)�compat)�eventsc@s4eZdZdZdZdd�Zdd	�Zd
d�Zdd
�ZdS)�_TracebackLoggera
Helper to log a traceback upon destruction if not cleared.

    This solves a nasty problem with Futures and Tasks that have an
    exception set: if nobody asks for the exception, the exception is
    never logged.  This violates the Zen of Python: 'Errors should
    never pass silently.  Unless explicitly silenced.'

    However, we don't want to log the exception as soon as
    set_exception() is called: if the calling code is written
    properly, it will get the exception and handle it properly.  But
    we *do* want to log it if result() or exception() was never called
    -- otherwise developers waste a lot of time wondering why their
    buggy code fails silently.

    An earlier attempt added a __del__() method to the Future class
    itself, but this backfired because the presence of __del__()
    prevents garbage collection from breaking cycles.  A way out of
    this catch-22 is to avoid having a __del__() method on the Future
    class itself, but instead to have a reference to a helper object
    with a __del__() method that logs the traceback, where we ensure
    that the helper object doesn't participate in cycles, and only the
    Future has a reference to it.

    The helper object is added when set_exception() is called.  When
    the Future is collected, and the helper is present, the helper
    object is also collected, and its __del__() method will log the
    traceback.  When the Future's result() or exception() method is
    called (and a helper object is present), it removes the helper
    object, after calling its clear() method to prevent it from
    logging.

    One downside is that we do a fair amount of work to extract the
    traceback from the exception, even when it is never logged.  It
    would seem cheaper to just store the exception object, but that
    references the traceback, which references stack frames, which may
    reference the Future, which references the _TracebackLogger, and
    then the _TracebackLogger would be included in a cycle, which is
    what we're trying to avoid!  As an optimization, we don't
    immediately format the exception; we only do the work when
    activate() is called, which call is delayed until after all the
    Future's callbacks have run.  Since usually a Future has at least
    one callback (typically set by 'yield from') and usually that
    callback extracts the callback, thereby removing the need to
    format the exception.

    PS. I don't claim credit for this solution.  I first heard of it
    in a discussion about closing files when they are collected.
    �loop�source_traceback�exc�tbcCs |j|_|j|_||_d|_dS)N)�_loopr
�_source_tracebackrrr)�self�futurer�r�'/usr/lib64/python3.6/asyncio/futures.py�__init__Rsz_TracebackLogger.__init__cCs,|j}|dk	r(d|_tj|j||j�|_dS)N)r�	traceback�format_exception�	__class__�
__traceback__r)rrrrr�activateXs

z_TracebackLogger.activatecCsd|_d|_dS)N)rr)rrrr�clear_sz_TracebackLogger.clearcCsb|jr^d}|jr:djtj|j��}|d7}|d|j�7}|dj|j�j�7}|jjd|i�dS)Nz*Future/Task exception was never retrieved
�z0Future/Task created at (most recent call last):
z%s
�message)rr�joinr�format_list�rstripr
�call_exception_handler)r�msg�srcrrr�__del__csz_TracebackLogger.__del__N)r
rrr)	�__name__�
__module__�__qualname__�__doc__�	__slots__rrrr&rrrrrs0rc@s�eZdZdZeZdZdZdZdZ	dZ
dZdd�dd�Ze
jZdd�ZejrRd	d
�Zdd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zejr�eZ dS)!ra,This class is *almost* compatible with concurrent.futures.Future.

    Differences:

    - This class is not thread-safe.

    - result() and exception() do not take a timeout argument and
      raise an exception when the future isn't done yet.

    - Callbacks registered with add_done_callback() are always called
      via the event loop's call_soon().

    - This class is not compatible with the wait() and as_completed()
      methods in the concurrent.futures package.

    (In Python 3.4 or later we may be able to unify the implementations.)
    NF)r
cCs@|dkrtj�|_n||_g|_|jj�r<tjtjd��|_dS)z�Initialize the future.

        The optional event_loop argument allows explicitly setting the event
        loop object used by the future. If it's not provided, the future uses
        the default event loop.
        Nr)	r�get_event_loopr�
_callbacksZ	get_debug�
extract_stack�sys�	_getframer)rr
rrrr�s
zFuture.__init__cCsd|jjdj|j��fS)Nz<%s %s>� )rr'r �
_repr_info)rrrr�__repr__�szFuture.__repr__cCsD|js
dS|j}d|jj||d�}|jr4|j|d<|jj|�dS)Nz %s exception was never retrieved)r�	exceptionrr)�_log_traceback�
_exceptionrr'rrr#)rr�contextrrrr&�s
zFuture.__del__cCs&d|_|jtkrdSt|_|j�dS)z�Cancel the future and schedule callbacks.

        If the future is already done or cancelled, return False.  Otherwise,
        change the future's state to cancelled, schedule the callbacks and
        return True.
        FT)r5�_state�_PENDING�
_CANCELLED�_schedule_callbacks)rrrr�cancel�s
z
Future.cancelcCsD|jdd�}|sdSg|jdd�<x|D]}|jj||�q*WdS)z�Internal: Ask the event loop to call all callbacks.

        The callbacks are scheduled to be called as soon as possible. Also
        clears the callback list.
        N)r-r�	call_soon)rZ	callbacks�callbackrrrr;�s
zFuture._schedule_callbackscCs
|jtkS)z(Return True if the future was cancelled.)r8r:)rrrr�	cancelled�szFuture.cancelledcCs
|jtkS)z�Return True if the future is done.

        Done means either that a result / exception are available, or that the
        future was cancelled.
        )r8r9)rrrr�done�szFuture.donecCs<|jtkrt�|jtkr td��d|_|jdk	r6|j�|jS)aReturn the result this future represents.

        If the future has been cancelled, raises CancelledError.  If the
        future's result isn't yet available, raises InvalidStateError.  If
        the future is done and has an exception set, this exception is raised.
        zResult is not ready.FN)r8r:r�	_FINISHEDrr5r6�_result)rrrr�result�s


z
Future.resultcCs,|jtkrt�|jtkr td��d|_|jS)a&Return the exception that was set on this future.

        The exception (or None if no exception was set) is returned only if
        the future is done.  If the future has been cancelled, raises
        CancelledError.  If the future isn't done yet, raises
        InvalidStateError.
        zException is not set.F)r8r:rrArr5r6)rrrrr4�s

zFuture.exceptioncCs*|jtkr|jj||�n|jj|�dS)z�Add a callback to be run when the future becomes done.

        The callback is called with a single argument - the future object. If
        the future is already done when this is called, the callback is
        scheduled with call_soon.
        N)r8r9rr=r-�append)r�fnrrr�add_done_callbacks
zFuture.add_done_callbackcs<�fdd�|jD�}t|j�t|�}|r8||jdd�<|S)z}Remove all instances of a callback from the "call when done" list.

        Returns the number of callbacks removed.
        csg|]}|�kr|�qSrr)�.0�f)rErr�
<listcomp>sz/Future.remove_done_callback.<locals>.<listcomp>N)r-�len)rrEZfiltered_callbacksZ
removed_countr)rEr�remove_done_callbacks
zFuture.remove_done_callbackcCs4|jtkrtdj|j|���||_t|_|j�dS)z�Mark the future done and set its result.

        If the future is already done when this method is called, raises
        InvalidStateError.
        z{}: {!r}N)r8r9r�formatrBrAr;)rrCrrr�
set_result s

zFuture.set_resultcCs�|jtkrtdj|j|���t|t�r,|�}t|�tkr@td��||_t	|_|j
�tjrbd|_
nt||�|_|jj|jj�dS)z�Mark the future done and set an exception.

        If the future is already done when this method is called, raises
        InvalidStateError.
        z{}: {!r}zPStopIteration interacts badly with generators and cannot be raised into a FutureTN)r8r9rrL�
isinstance�type�
StopIteration�	TypeErrorr6rAr;r
�PY34r5rZ
_tb_loggerrr=r)rr4rrr�
set_exception,s

zFuture.set_exceptionccs|j�sd|_|V|j�S)NT)r@�_asyncio_future_blockingrC)rrrr�__iter__DszFuture.__iter__)!r'r(r)r*r9r8rBr6rrrTr5rr	Z_future_repr_infor2r3r
rRr&r<r;r?r@rCr4rFrKrMrSrUZPY35�	__await__rrrrrns4

cCs|j�rdS|j|�dS)z?Helper setting the result only if the future was not cancelled.N)r?rM)ZfutrCrrr�_set_result_unless_cancelledSsrWcCsN|j�r|j�|j�sdS|j�}|dk	r8|j|�n|j�}|j|�dS)z8Copy state from a future to a concurrent.futures.Future.N)r?r<Zset_running_or_notify_cancelr4rSrCrM)�
concurrent�sourcer4rCrrr�_set_concurrent_future_stateZsrZcCsP|j�rdS|j�r|j�n.|j�}|dk	r:|j|�n|j�}|j|�dS)zqInternal helper to copy state from another Future.

    The other Future may be a concurrent.futures.Future.
    N)r?r<r4rSrCrM)rY�destr4rCrrr�_copy_future_stateis
r\cs�t��r"t�tjj�r"td��t��rDt�tjj�rDtd��t��rR�jnd�t��rd�jnd�dd�����fdd�}����fdd	�}�j|��j|�dS)
aChain two futures so that when one completes, so does the other.

    The result (or exception) of source will be copied to destination.
    If destination is cancelled, source gets cancelled too.
    Compatible with both asyncio.Future and concurrent.futures.Future.
    z(A future is required for source argumentz-A future is required for destination argumentNcSs"t|�rt||�n
t||�dS)N)rr\rZ)r�otherrrr�
_set_state�sz!_chain_future.<locals>._set_statecs2|j�r.�dks��kr"�j�n�j�j�dS)N)r?r<�call_soon_threadsafe)�destination)�	dest_looprY�source_looprr�_call_check_cancel�s
z)_chain_future.<locals>._call_check_cancelcsJ�j�r�dk	r�j�rdS�dks,��kr8��|�n�j��|�dS)N)r?Z	is_closedr_)rY)r^rar`rbrr�_call_set_state�sz&_chain_future.<locals>._call_set_state)rrNrXZfuturesrrQrrF)rYr`rcrdr)r^rar`rYrbr�
_chain_future}s	
re)r
cCs2t|�r|S|dkrtj�}|j�}t||�|S)z&Wrap concurrent.futures.Future object.N)rrr,Z
create_futurere)rr
Z
new_futurerrrr�s
)r*�__all__Zconcurrent.futuresrXZloggingr/rrr	r
rrrrrr9r:rA�DEBUGZSTACK_DEBUGrrZ	_PyFuturerWrZr\rerZ_asyncio�ImportErrorZ_CFuturerrrr�<module>s>

Pc*
PK[��� � +__pycache__/coroutines.cpython-36.opt-1.pycnu�[���3


 \+�@s�dddgZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZdd	lmZdd
l
mZejdZejjo�eejjd��ZyejZejZWnek
r�dZdZYnXy
ejZWnek
r�d
d�ZYnXyddlmZ m!Z"Wne#k
�r*dZ Z"YnXdd�Z$e$�Z%[$dd�Z&Gdd�d�Z'dd�Ze(�Z)dd�Zej*e'fZ+e dk	�r�e+e f7Z+edk	�r�efe+Z+dd�Z,dd�Z-dS)�	coroutine�iscoroutinefunction�iscoroutine�N�)�compat)�	constants)�events)�base_futures)�loggerZ
YIELD_FROMZPYTHONASYNCIODEBUGcCsdS)NF�)�funcrr�*/usr/lib64/python3.6/asyncio/coroutines.py�<lambda>/sr)�	Coroutine�	AwaitablecCsFGdd�d�}dd�}d}|�}||�}t|�|j|�|j|fkS)	Nc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
z!has_yield_from_bug.<locals>.MyGencSs
d|_dS)N)�	send_args)�selfrrr
�__init__;sz*has_yield_from_bug.<locals>.MyGen.__init__cSs|S)Nr)rrrr
�__iter__=sz*has_yield_from_bug.<locals>.MyGen.__iter__cSsdS)N�*r)rrrr
�__next__?sz*has_yield_from_bug.<locals>.MyGen.__next__cWs
||_dS)N)r)rZwhatrrr
�sendAsz&has_yield_from_bug.<locals>.MyGen.sendN)�__name__�
__module__�__qualname__rrrrrrrr
�MyGen:srcss|EdHdS)Nr)�genrrr
�yield_from_genDsz*has_yield_from_bug.<locals>.yield_from_genr��)rrr)�nextrr)rr�valuer�cororrr
�has_yield_from_bug9s

r#cCs
t|d�S)N)�CoroWrapper)rrrr
�
debug_wrapperPsr%c@s�eZdZd%dd�Zdd�Zdd�Zdd	�Zer8d
d�Zndd�Zd&d
d�Z	dd�Z
edd��Zedd��Z
edd��Zejr�dd�Zedd��Zedd��Zedd��Zedd ��Zed!d"��Zd#d$�ZdS)'r$NcCs>||_||_tjtjd��|_t|dd�|_t|dd�|_	dS)Nrrr)
rrr�
extract_stack�sys�	_getframe�_source_traceback�getattrrr)rrrrrr
r[s
zCoroWrapper.__init__cCs@t|�}|jr0|jd}|d|d|df7}d|jj|fS)Nrz, created at %s:%srz<%s %s>���)�_format_coroutiner)�	__class__r)r�	coro_repr�framerrr
�__repr__cs

zCoroWrapper.__repr__cCs|S)Nr)rrrr
rjszCoroWrapper.__iter__cCs|jjd�S)N)rr)rrrr
rmszCoroWrapper.__next__cGs4tj�}|j}|jj|jtkr(|d}|jj|�S)Nr)	r'r(�f_back�f_code�co_code�f_lasti�_YIELD_FROMrr)rr!r/Zcallerrrr
rus
zCoroWrapper.sendcCs|jj|�S)N)rr)rr!rrr
r}scCs|jj|||�S)N)r�throw)r�typer!�	tracebackrrr
r6�szCoroWrapper.throwcCs
|jj�S)N)r�close)rrrr
r9�szCoroWrapper.closecCs|jjS)N)r�gi_frame)rrrr
r:�szCoroWrapper.gi_framecCs|jjS)N)r�
gi_running)rrrr
r;�szCoroWrapper.gi_runningcCs|jjS)N)r�gi_code)rrrr
r<�szCoroWrapper.gi_codecCs,t|jdd�}|dk	r(tdj|j|���|S)N�cr_awaitz;Cannot await on coroutine {!r} while it's awaiting for {!r})r*r�RuntimeError�format)rr=rrr
�	__await__�szCoroWrapper.__await__cCs|jjS)N)r�gi_yieldfrom)rrrr
rA�szCoroWrapper.gi_yieldfromcCs|jjS)N)rr=)rrrr
r=�szCoroWrapper.cr_awaitcCs|jjS)N)r�
cr_running)rrrr
rB�szCoroWrapper.cr_runningcCs|jjS)N)r�cr_code)rrrr
rC�szCoroWrapper.cr_codecCs|jjS)N)r�cr_frame)rrrr
rD�szCoroWrapper.cr_framecCs�t|dd�}t|dd�}|dkr,t|dd�}|dk	r�|jd
kr�d|}t|df�}|r�djtj|��}|dtj�d	�7}||j�7}tj	|�dS)Nrr:rDrz%r was never yielded fromr)�zB
Coroutine object created at (most recent call last, truncated to z last lines):
r+)
r*r4�joinr8�format_listrZDEBUG_STACK_DEPTH�rstripr
�error)rrr/�msg�tbrrr
�__del__�szCoroWrapper.__del__)N)NN)rrrrr0rr�_YIELD_FROM_BUGrr6r9�propertyr:r;r<rZPY35r@rAr=rBrCrDrLrrrr
r$Xs(


r$cspt��r�Stj��r��ntj���fdd���tsNtdkrD�}qft��}ntj����fdd��}t|_|S)z�Decorator to mark coroutines.

    If the coroutine is not yielded from before it is destroyed,
    an error message is logged.
    c?sv�||�}tj|�s(tj|�s(t|t�r4|EdH}n>tdk	rry
|j}Wntk
rZYnXt|t�rr|�EdH}|S)N)	r	Zisfuture�inspectZisgenerator�
isinstancer$�
_AwaitableABCr@�AttributeError)�args�kw�resZ
await_meth)rrr
r"�s



zcoroutine.<locals>.coroNcs@t�||��d�}|jr |jd=t�dd�|_t�dd�|_|S)N)rrrrr+)r$r)r*rr)rS�kwds�w)r"rrr
�wrapper�szcoroutine.<locals>.wrapper)�_inspect_iscoroutinefunctionrO�isgeneratorfunction�	functools�wraps�_DEBUG�_types_coroutine�
_is_coroutine)rrXr)r"rr
r�s


cCst|dd�tkpt|�S)z6Return True if func is a decorated coroutine function.r_N)r*r_rY)rrrr
r�scCs
t|t�S)z)Return True if obj is a coroutine object.)rP�_COROUTINE_TYPES)�objrrr
rsc
Cst|d�r�t|d�r�t|dt|dt|�j��}dj|�}d}y
|j}Wn4tk
r~y
|j}Wntk
rxYnXYnX|r�dj|�S|Sd}t|t	�r�|j
}|j}|dk	r�dj|�}n|}|dkr�tj
|fi�}d}t|d�r�|jr�|j}nt|d��r|j�r|j}d}t|d��r0|j�r0|j}nt|d	��rJ|j�rJ|j}d
}|�rb|j�rb|j}d}|}t|t	��r�tj|j
��r�|j
dk	�r�tj|j
�}	|	dk	�r�|	\}}|dk�r�d|||f}nd
|||f}n:|dk	�r�|j}d|||f}n|�r|j}d|||f}|S)NrCr<rrz{}()Fz
{} runningrDr:z<empty co_filename>rz%s done, defined at %s:%sz%s running, defined at %s:%sz%s running at %s:%s)�hasattrr*r7rr?rBrRr;rPr$rrrZ_format_callbackrCr<rDr:�co_filenamerOrZZ_get_function_source�f_lineno�co_firstlineno)
r"Z	coro_nameZrunningrZ	coro_codeZ
coro_frame�filename�linenor.�sourcerrr
r,sx







r,).�__all__r[rOZopcode�osr'r8�typesrErrrr	�logr
Zopmapr5�flags�ignore_environment�bool�environ�getr]rr^�
CoroutineTypeZ_types_CoroutineTyperRrrY�collections.abcrZ
_CoroutineABCrrQ�ImportErrorr#rMr%r$�objectr_�
GeneratorTyper`rr,rrrr
�<module>sZ




j:




PK[5�h�@�@0__pycache__/proactor_events.cpython-36.opt-1.pycnu�[���3


 \�O�@s�dZdgZddlZddlZddlmZddlmZddlmZddlmZdd	lm	Z	dd
lm
Z
ddlmZGdd
�d
e
j
e
j�ZGdd�dee
j�ZGdd�dee
j�ZGdd�de�ZGdd�deee
j�ZGdd�deee
j�ZGdd�dej�ZdS)z�Event loop using a proactor and related classes.

A proactor is a "notify-on-completion" multiplexer.  Currently a
proactor is only implemented on Windows with IOCP.
�BaseProactorEventLoop�N�)�base_events)�compat)�	constants)�futures)�sslproto)�
transports)�loggercs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
ejrXdd�Z
ddd�Zdd�Zdd�Zdd�Z�ZS)�_ProactorBasePipeTransportz*Base class for pipe and socket transports.Ncs�t�j||�|j|�||_||_||_d|_d|_d|_d|_	d|_
d|_d|_|jdk	rh|jj
�|jj|jj|�|dk	r�|jjtj|d�dS)NrF)�super�__init__�
_set_extra�_sock�	_protocol�_server�_buffer�	_read_fut�
_write_fut�_pending_write�
_conn_lost�_closing�_eof_writtenZ_attach�_loop�	call_soonZconnection_maderZ_set_result_unless_cancelled)�self�loop�sock�protocol�waiter�extra�server)�	__class__��//usr/lib64/python3.6/asyncio/proactor_events.pyr
s$



z#_ProactorBasePipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jdk	rN|jd|jj��|jdk	rh|jd|j�|jdk	r�|jd|j�|jr�t	|j�}|jd|�|j
r�|jd�dd	j|�S)
N�closed�closingzfd=%szread=%szwrite=%rzwrite_bufsize=%szEOF writtenz<%s>� )r"�__name__r�appendr�filenorrr�lenr�join)r�info�bufsizer#r#r$�__repr__/s"







z#_ProactorBasePipeTransport.__repr__cCs||jd<dS)N�pipe)�_extra)rrr#r#r$rBsz%_ProactorBasePipeTransport._set_extracCs
||_dS)N)r)rrr#r#r$�set_protocolEsz'_ProactorBasePipeTransport.set_protocolcCs|jS)N)r)rr#r#r$�get_protocolHsz'_ProactorBasePipeTransport.get_protocolcCs|jS)N)r)rr#r#r$�
is_closingKsz%_ProactorBasePipeTransport.is_closingcCs^|jr
dSd|_|jd7_|jr@|jdkr@|jj|jd�|jdk	rZ|jj�d|_dS)NTr)	rrrrrr�_call_connection_lostr�cancel)rr#r#r$�closeNs

z _ProactorBasePipeTransport.closecCs*|jdk	r&tjd|t|d�|j�dS)Nzunclosed transport %r)�source)r�warnings�warn�ResourceWarningr7)rr#r#r$�__del__]s
z"_ProactorBasePipeTransport.__del__�Fatal error on pipe transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)�exc_info)�message�	exceptionZ	transportr)
�
isinstancerZ_FATAL_ERROR_IGNOREr�	get_debugr
�debug�call_exception_handlerr�_force_close)r�excr?r#r#r$�_fatal_errorcs
z'_ProactorBasePipeTransport._fatal_errorcCsj|jr
dSd|_|jd7_|jr4|jj�d|_|jrJ|jj�d|_d|_d|_|jj|j	|�dS)NTrr)
rrrr6rrrrrr5)rrFr#r#r$rEps

z'_ProactorBasePipeTransport._force_closecCs^z|jj|�Wdt|jd�r,|jjtj�|jj�d|_|j}|dk	rX|j	�d|_XdS)N�shutdown)
rZconnection_lost�hasattrrrH�socketZ	SHUT_RDWRr7rZ_detach)rrFr!r#r#r$r5s
z0_ProactorBasePipeTransport._call_connection_lostcCs"|j}|jdk	r|t|j�7}|S)N)rrr+)r�sizer#r#r$�get_write_buffer_size�s
z0_ProactorBasePipeTransport.get_write_buffer_size)NNN)r=)r(�
__module__�__qualname__�__doc__r
r/rr2r3r4r7rZPY34r<rGrEr5rL�
__classcell__r#r#)r"r$rs

rcs<eZdZdZd�fdd�	Zdd�Zdd�Zdd	d
�Z�ZS)
�_ProactorReadPipeTransportzTransport for read pipes.Ncs4t�j||||||�d|_d|_|jj|j�dS)NF)rr
�_paused�_reschedule_on_resumerr�
_loop_reading)rrrrrr r!)r"r#r$r
�sz#_ProactorReadPipeTransport.__init__cCs0|js|jrdSd|_|jj�r,tjd|�dS)NTz%r pauses reading)rrRrrBr
rC)rr#r#r$�
pause_reading�s

z(_ProactorReadPipeTransport.pause_readingcCsP|js|jrdSd|_|jr6|jj|j|j�d|_|jj�rLtj	d|�dS)NFz%r resumes reading)
rrRrSrrrTrrBr
rC)rr#r#r$�resume_reading�s
z)_ProactorReadPipeTransport.resume_readingcCs�|jrd|_dSd}�z"yH|dk	r0d|_|j�}|jr>d}dS|dkrJdS|jjj|jd�|_Wn�t	k
r�}z2|js�|j
|d�n|jj�r�tj
ddd�WYdd}~Xn�tk
r�}z|j|�WYdd}~Xn^tk
�r}z|j
|d�WYdd}~Xn0tjk
�r&|j�s"�YnX|jj|j�Wd|�rN|jj|�n:|dk	�r�|jj��rptj
d|�|jj�}|�s�|j�XdS)NT�iz"Fatal read error on pipe transportz*Read error on pipe transport while closing)r>z%r received EOF)rRrSr�resultrr�	_proactor�recvr�ConnectionAbortedErrorrGrBr
rC�ConnectionResetErrorrE�OSErrorr�CancelledError�add_done_callbackrTrZ
data_receivedZeof_receivedr7)r�fut�datarFZ	keep_openr#r#r$rT�sH


z(_ProactorReadPipeTransport._loop_reading)NNN)N)	r(rMrNrOr
rUrVrTrPr#r#)r"r$rQ�s
rQc@s:eZdZdZdd�Zd
dd�Zdd�Zd	d
�Zdd�ZdS)�_ProactorBaseWritePipeTransportzTransport for write pipes.cCs�t|tttf�s&dt|�j}t|��|jr4td��|s<dS|j	rj|j	t
jkrXtj
d�|j	d7_	dS|jdkr�|jt|�d�n.|js�t|�|_|j�n|jj|�|j�dS)Nz3data argument must be a bytes-like object, not '%s'zwrite_eof() already calledzsocket.send() raised exception.r)ra)rA�bytes�	bytearray�
memoryview�typer(�	TypeErrorr�RuntimeErrorrrZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningr�
_loop_writingr�_maybe_pause_protocol�extend)rra�msgr#r#r$�write�s(



z%_ProactorBaseWritePipeTransport.writeNcCsy�d|_d|_|r|j�|dkr.|j}d|_|sf|jrH|jj|jd�|jr\|j	j
tj�|j
�nN|jjj|j	|�|_|jj�s�t|�|_|jj|j�|j�n|jj|j�WnZtk
r�}z|j|�WYdd}~Xn0tk
�r}z|j|d�WYdd}~XnXdS)Nrz#Fatal write error on pipe transport)rrrXrrrrr5rrrHrJ�SHUT_WRZ_maybe_resume_protocolrY�send�doner+r_rjrkr\rEr]rG)r�frarFr#r#r$rj
s0



z-_ProactorBaseWritePipeTransport._loop_writingcCsdS)NTr#)rr#r#r$�
can_write_eof0sz-_ProactorBaseWritePipeTransport.can_write_eofcCs|j�dS)N)r7)rr#r#r$�	write_eof3sz)_ProactorBaseWritePipeTransport.write_eofcCs|jd�dS)N)rE)rr#r#r$�abort6sz%_ProactorBaseWritePipeTransport.abort)NN)	r(rMrNrOrnrjrsrtrur#r#r#r$rb�s$
#rbcs$eZdZ�fdd�Zdd�Z�ZS)�_ProactorWritePipeTransportcs4t�j||�|jjj|jd�|_|jj|j�dS)N�)	rr
rrYrZrrr_�_pipe_closed)r�args�kw)r"r#r$r
;sz$_ProactorWritePipeTransport.__init__cCs@|j�rdS|jrdSd|_|jdk	r4|jt��n|j�dS)N)Z	cancelledrrrrE�BrokenPipeErrorr7)rr`r#r#r$rx@s
z(_ProactorWritePipeTransport._pipe_closed)r(rMrNr
rxrPr#r#)r"r$rv:srvc@s eZdZdZdd�Zdd�ZdS)�_ProactorDuplexPipeTransportzTransport for duplex pipes.cCsdS)NFr#)rr#r#r$rsUsz*_ProactorDuplexPipeTransport.can_write_eofcCst�dS)N)�NotImplementedError)rr#r#r$rtXsz&_ProactorDuplexPipeTransport.write_eofN)r(rMrNrOrsrtr#r#r#r$r|Psr|cs:eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Z�ZS)�_ProactorSocketTransportz Transport for connected sockets.Ncs$t�j||||||�tj|�dS)N)rr
rZ_set_nodelay)rrrrrr r!)r"r#r$r
asz!_ProactorSocketTransport.__init__cCs�||jd<y|j�|jd<Wn4tjtfk
rP|jj�rLtjd|dd�YnXd|jkr�y|j	�|jd<Wn4tjtfk
r�|jj�r�tjd|dd�YnXdS)NrJZsocknamezgetsockname() failed on %rT)r>�peernamezgetpeername() failed on %r)
r1ZgetsocknamerJ�error�AttributeErrorrrBr
riZgetpeername)rrr#r#r$rfs



z#_ProactorSocketTransport._set_extracCsdS)NTr#)rr#r#r$rsvsz&_ProactorSocketTransport.can_write_eofcCs2|js|jrdSd|_|jdkr.|jjtj�dS)NT)rrrrrHrJro)rr#r#r$rtys

z"_ProactorSocketTransport.write_eof)NNN)	r(rMrNrOr
rrsrtrPr#r#)r"r$r~\sr~cs�eZdZ�fdd�Zd-dd�Zd.ddddd�dd	�Zd/d
d�Zd0dd
�Zd1dd�Z�fdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd2d d!�Zd"d#�Zd3d%d&�Zd'd(�Zd)d*�Zd+d,�Z�ZS)4rcsHt�j�tjd|jj�||_||_d|_i|_	|j
|�|j�dS)NzUsing proactor: %s)rr
r
rCr"r(rY�	_selector�_self_reading_future�_accept_futuresZset_loop�_make_self_pipe)rZproactor)r"r#r$r
�s

zBaseProactorEventLoop.__init__NcCst||||||�S)N)r~)rrrrr r!r#r#r$�_make_socket_transport�s
z,BaseProactorEventLoop._make_socket_transportF)�server_side�server_hostnamer r!c
Cs<tj�std��tj||||||�}	t|||	||d�|	jS)NzOProactor event loop requires Python 3.5 or newer (ssl.MemoryBIO) to support SSL)r r!)rZ_is_sslproto_availabler}ZSSLProtocolr~Z_app_transport)
rZrawsockr�
sslcontextrr�r�r r!Zssl_protocolr#r#r$�_make_ssl_transport�s
z)BaseProactorEventLoop._make_ssl_transportcCst|||||�S)N)r|)rrrrr r#r#r$�_make_duplex_pipe_transport�sz1BaseProactorEventLoop._make_duplex_pipe_transportcCst|||||�S)N)rQ)rrrrr r#r#r$�_make_read_pipe_transport�sz/BaseProactorEventLoop._make_read_pipe_transportcCst|||||�S)N)rv)rrrrr r#r#r$�_make_write_pipe_transport�sz0BaseProactorEventLoop._make_write_pipe_transportcsP|j�rtd��|j�rdS|j�|j�|jj�d|_d|_t�j�dS)Nz!Cannot close a running event loop)	Z
is_runningrh�	is_closed�_stop_accept_futures�_close_self_piperYr7r�r)r)r"r#r$r7�s
zBaseProactorEventLoop.closecCs|jj||�S)N)rYrZ)rr�nr#r#r$�	sock_recv�szBaseProactorEventLoop.sock_recvcCs|jj||�S)N)rYrp)rrrar#r#r$�sock_sendall�sz"BaseProactorEventLoop.sock_sendallcCs|jj||�S)N)rYZconnect)rrZaddressr#r#r$�sock_connect�sz"BaseProactorEventLoop.sock_connectcCs|jj|�S)N)rY�accept)rrr#r#r$�sock_accept�sz!BaseProactorEventLoop.sock_acceptcCst�dS)N)r})rr#r#r$�_socketpair�sz!BaseProactorEventLoop._socketpaircCsL|jdk	r|jj�d|_|jj�d|_|jj�d|_|jd8_dS)Nr)r�r6�_ssockr7�_csock�
_internal_fds)rr#r#r$r��s



z&BaseProactorEventLoop._close_self_pipecCsF|j�\|_|_|jjd�|jjd�|jd7_|j|j�dS)NFr)r�r�r�Zsetblockingr�r�_loop_self_reading)rr#r#r$r��s
z%BaseProactorEventLoop._make_self_pipecCs�y$|dk	r|j�|jj|jd�}WnHtjk
r:dStk
rl}z|jd||d��WYdd}~XnX||_|j	|j
�dS)Niz.Error on reading from the event loop self pipe)r?r@r)rXrYrZr�rr^�	ExceptionrDr�r_r�)rrrrFr#r#r$r��sz(BaseProactorEventLoop._loop_self_readingcCs|jjd�dS)N�)r�rp)rr#r#r$�_write_to_self�sz$BaseProactorEventLoop._write_to_self�dcs&d������fdd�	��j��dS)Ncs"y�|dk	rl|j�\}}�jr,tjd�||���}�dk	rV�j||�dd|i�d�n�j||d|i�d��j�rxdS�jj��}Wn~t	k
r�}zD�j
�dkr��jd|�d���j�n�jr�tjd	�dd
�WYdd}~Xn8t
jk
�r�j�YnX|�j�j
�<|j��dS)Nz#%r got a new connection from %r: %rTr)r�r r!)r r!rzAccept failed on a socket)r?r@rJzAccept failed on socket %r)r>���)rXZ_debugr
rCr�r�r�rYr�r]r*rDr7rr^r�r_)rrZconnZaddrrrF)r�protocol_factoryrr!rr�r#r$r�s>


z2BaseProactorEventLoop._start_serving.<locals>.loop)N)r)rr�rr�r!Zbacklogr#)rr�rr!rr�r$�_start_serving�s$z$BaseProactorEventLoop._start_servingcCsdS)Nr#)rZ
event_listr#r#r$�_process_events sz%BaseProactorEventLoop._process_eventscCs*x|jj�D]}|j�qW|jj�dS)N)r��valuesr6�clear)rZfuturer#r#r$r�$sz*BaseProactorEventLoop._stop_accept_futurescCs |j�|jj|�|j�dS)N)r�rY�
_stop_servingr7)rrr#r#r$r�)sz#BaseProactorEventLoop._stop_serving)NNN)N)NN)NN)NN)N)NNr�)r(rMrNr
r�r�r�r�r�r7r�r�r�r�r�r�r�r�r�r�r�r�r�rPr#r#)r"r$r�s4







()rO�__all__rJr9�rrrrrr	�logr
Z_FlowControlMixinZ
BaseTransportrZ
ReadTransportrQZWriteTransportrbrvZ	Transportr|r~Z
BaseEventLooprr#r#r#r$�<module>s2MT
#PK[����$__pycache__/log.cpython-36.opt-2.pycnu�[���3


 \|�@sddlZeje�ZdS)�N)ZloggingZ	getLogger�__package__Zlogger�rr�#/usr/lib64/python3.6/asyncio/log.py�<module>sPK[�%�O�S�S/__pycache__/windows_events.cpython-36.opt-1.pycnu�[���3


 \�l�@s�dZddlZddlZddlZddlZddlZddlZddlmZddlm	Z	ddlm
Z
ddlmZddlmZdd	lm
Z
dd
lmZddlmZddlmZdd
lmZddddgZdZdZdZdZdZdZGdd�de
j�ZGdd�de
j�ZGdd�de�ZGdd�de�ZGdd �d e �Z!Gd!d"�d"ej"�Z#Gd#d�dej$�Z%Gd$d�d�Z&Gd%d&�d&e	j'�Z(e#Z)Gd'd(�d(ej*�Z+e+Z,dS))z.Selector and proactor event loops for Windows.�N�)�events)�base_subprocess)�futures)�proactor_events)�selector_events)�tasks)�
windows_utils)�_overlapped)�	coroutine)�logger�SelectorEventLoop�ProactorEventLoop�IocpProactor�DefaultEventLoopPolicyl��i�i�g����MbP?g�������?cs^eZdZdZdd��fdd�
Z�fdd�Zdd	�Z�fd
d�Z�fdd
�Z�fdd�Z	�Z
S)�_OverlappedFuturez�Subclass of Future which represents an overlapped operation.

    Cancelling it will immediately cancel the overlapped operation.
    N)�loopcs&t�j|d�|jr|jd=||_dS)N)rr���)�super�__init__�_source_traceback�_ov)�self�ovr)�	__class__��./usr/lib64/python3.6/asyncio/windows_events.pyr-sz_OverlappedFuture.__init__cs@t�j�}|jdk	r<|jjr dnd}|jdd||jjf�|S)N�pendingZ	completedrzoverlapped=<%s, %#x>)r�
_repr_inforr�insert�address)r�info�state)rrrr3s


z_OverlappedFuture._repr_infocCsr|jdkrdSy|jj�WnJtk
rf}z.d||d�}|jrJ|j|d<|jj|�WYdd}~XnXd|_dS)Nz&Cancelling an overlapped future failed)�message�	exception�future�source_traceback)r�cancel�OSErrorr�_loop�call_exception_handler)r�exc�contextrrr�_cancel_overlapped:s

z$_OverlappedFuture._cancel_overlappedcs|j�t�j�S)N)r-rr')r)rrrr'Jsz_OverlappedFuture.cancelcst�j|�|j�dS)N)r�
set_exceptionr-)rr$)rrrr.Nsz_OverlappedFuture.set_exceptioncst�j|�d|_dS)N)r�
set_resultr)r�result)rrrr/Rsz_OverlappedFuture.set_result)�__name__�
__module__�__qualname__�__doc__rrr-r'r.r/�
__classcell__rr)rrr'srcsneZdZdZdd��fdd�
Zdd�Z�fdd	�Zd
d�Zdd
�Z�fdd�Z	�fdd�Z
�fdd�Z�ZS)�_BaseWaitHandleFuturez2Subclass of Future which represents a wait handle.N)rcs8t�j|d�|jr|jd=||_||_||_d|_dS)N)rrTr)rrrr�_handle�_wait_handle�_registered)rr�handle�wait_handler)rrrrZsz_BaseWaitHandleFuture.__init__cCstj|jd�tjkS)Nr)�_winapiZWaitForSingleObjectr7Z
WAIT_OBJECT_0)rrrr�_pollhsz_BaseWaitHandleFuture._pollcs\t�j�}|jd|j�|jdk	r>|j�r0dnd}|j|�|jdk	rX|jd|j�|S)Nz
handle=%#xZsignaledZwaitingzwait_handle=%#x)rr�appendr7r=r8)rr!r")rrrrms



z _BaseWaitHandleFuture._repr_infocCs
d|_dS)N)r)r�futrrr�_unregister_wait_cbwsz)_BaseWaitHandleFuture._unregister_wait_cbcCs�|js
dSd|_|j}d|_ytj|�WnZtk
r�}z>|jtjkrtd||d�}|jrd|j|d<|jj	|�dSWYdd}~XnX|j
d�dS)NFz$Failed to unregister the wait handle)r#r$r%r&)r9r8r
ZUnregisterWaitr(�winerror�ERROR_IO_PENDINGrr)r*r@)rr;r+r,rrr�_unregister_wait|s"
z&_BaseWaitHandleFuture._unregister_waitcs|j�t�j�S)N)rCrr')r)rrrr'�sz_BaseWaitHandleFuture.cancelcs|j�t�j|�dS)N)rCrr.)rr$)rrrr.�sz#_BaseWaitHandleFuture.set_exceptioncs|j�t�j|�dS)N)rCrr/)rr0)rrrr/�sz _BaseWaitHandleFuture.set_result)
r1r2r3r4rr=rr@rCr'r.r/r5rr)rrr6Ws
r6csFeZdZdZdd��fdd�
Zdd�Z�fdd	�Z�fd
d�Z�ZS)�_WaitCancelFuturezoSubclass of Future which represents a wait for the cancellation of a
    _WaitHandleFuture using an event.
    N)rcst�j||||d�d|_dS)N)r)rr�_done_callback)rr�eventr;r)rrrr�sz_WaitCancelFuture.__init__cCstd��dS)Nz'_WaitCancelFuture must not be cancelled)�RuntimeError)rrrrr'�sz_WaitCancelFuture.cancelcs$t�j|�|jdk	r |j|�dS)N)rr/rE)rr0)rrrr/�s
z_WaitCancelFuture.set_resultcs$t�j|�|jdk	r |j|�dS)N)rr.rE)rr$)rrrr.�s
z_WaitCancelFuture.set_exception)	r1r2r3r4rr'r/r.r5rr)rrrD�s
rDcs6eZdZdd��fdd�
Z�fdd�Zdd�Z�ZS)	�_WaitHandleFutureN)rcs<t�j||||d�||_d|_tjdddd�|_d|_dS)N)rTF)rr�	_proactorZ_unregister_proactorr
ZCreateEvent�_event�
_event_fut)rrr:r;�proactorr)rrrr�s
z_WaitHandleFuture.__init__csF|jdk	r"tj|j�d|_d|_|jj|j�d|_t�j|�dS)N)	rJr<�CloseHandlerKrI�_unregisterrrr@)rr?)rrrr@�s
	z%_WaitHandleFuture._unregister_wait_cbcCs�|js
dSd|_|j}d|_ytj||j�WnZtk
r�}z>|jtjkrxd||d�}|jrh|j|d<|j	j
|�dSWYdd}~XnX|jj|j|j
�|_dS)NFz$Failed to unregister the wait handle)r#r$r%r&)r9r8r
ZUnregisterWaitExrJr(rArBrr)r*rI�_wait_cancelr@rK)rr;r+r,rrrrC�s$

z"_WaitHandleFuture._unregister_wait)r1r2r3rr@rCr5rr)rrrH�srHc@s<eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZeZ	dS)
�
PipeServerzXClass representing a pipe server.

    This is much like a bound, listening socket.
    cCs,||_tj�|_d|_d|_|jd�|_dS)NT)�_address�weakref�WeakSet�_free_instances�_pipe�_accept_pipe_future�_server_pipe_handle)rr rrrr�s

zPipeServer.__init__cCs|j|jd�}|_|S)NF)rUrW)r�tmprrr�_get_unconnected_pipe�sz PipeServer._get_unconnected_pipec	Csr|j�rdStjtjB}|r&|tjO}tj|j|tjtjBtj	Btj
tjtjtj
tj�}tj|�}|jj|�|S)N)�closedr<ZPIPE_ACCESS_DUPLEXZFILE_FLAG_OVERLAPPEDZFILE_FLAG_FIRST_PIPE_INSTANCEZCreateNamedPiperQZPIPE_TYPE_MESSAGEZPIPE_READMODE_MESSAGEZ	PIPE_WAITZPIPE_UNLIMITED_INSTANCESr	ZBUFSIZEZNMPWAIT_WAIT_FOREVER�NULL�
PipeHandlerT�add)r�first�flags�h�piperrrrWs


zPipeServer._server_pipe_handlecCs
|jdkS)N)rQ)rrrrrZszPipeServer.closedcCsV|jdk	r|jj�d|_|jdk	rRx|jD]}|j�q,Wd|_d|_|jj�dS)N)rVr'rQrT�closerU�clear)rrarrrrbs


zPipeServer.closeN)
r1r2r3r4rrYrWrZrb�__del__rrrrrP�s
rPc@seZdZdZdd�ZdS)�_WindowsSelectorEventLoopz'Windows version of selector event loop.cCstj�S)N)r	�
socketpair)rrrr�_socketpair+sz%_WindowsSelectorEventLoop._socketpairN)r1r2r3r4rgrrrrre(srecsPeZdZdZd
�fdd�	Zdd�Zedd��Zed	d
��Zeddd��Z	�Z
S)rz2Windows version of proactor event loop using IOCP.Ncs|dkrt�}t�j|�dS)N)rrr)rrL)rrrr2szProactorEventLoop.__init__cCstj�S)N)r	rf)rrrrrg7szProactorEventLoop._socketpairccs8|jj|�}|EdH}|�}|j||d|id�}||fS)N�addr)�extra)rI�connect_pipe�_make_duplex_pipe_transport)r�protocol_factoryr �fra�protocol�transrrr�create_pipe_connection:s
z(ProactorEventLoop.create_pipe_connectioncs.t���d�����fdd�	��j���gS)Ncsd}yj|rL|j�}�jj|��j�r2|j�dS��}�j||d�id��j�}|dkr`dS�jj|�}Wn�t	k
r�}zH|r�|j
�d	kr��jd||d��|j�n�jr�t
jd|dd�WYdd}~Xn2tjk
r�|r�|j�YnX|�_|j��dS)
Nrh)rirzPipe accept failed)r#r$razAccept pipe failed on pipe %rT)�exc_infor)r0rT�discardrZrbrkrYrI�accept_piper(�filenor*Z_debugrZwarningr�CancelledErrorrV�add_done_callback)rmrarnr+)r �loop_accept_piperlr�serverrrrwGs<

z>ProactorEventLoop.start_serving_pipe.<locals>.loop_accept_pipe)N)rPZ	call_soon)rrlr r)r rwrlrrxr�start_serving_pipeCs(
z$ProactorEventLoop.start_serving_pipec	ks�|j�}
t||||||||f|
|d�|	��}y|
EdHWn&tk
r`}z
|}
WYdd}~XnXd}
|
dk	r�|j�|j�EdH|
�|S)N)�waiterri)�
create_future�_WindowsSubprocessTransport�	ExceptionrbZ_wait)rrn�args�shell�stdin�stdout�stderr�bufsizeri�kwargsrzZtranspr+�errrrr�_make_subprocess_transportrs

z,ProactorEventLoop._make_subprocess_transport)N)N)r1r2r3r4rrgrrpryr�r5rr)rrr/s	/c@s�eZdZdZd1dd�Zdd�Zdd�Zd2d
d�Zdd
�Zd3dd�Z	d4dd�Z
dd�Zdd�Zdd�Z
edd��Zd5dd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd6d)d*�Zd+d,�Zd-d.�Zd/d0�Zd	S)7rz#Proactor implementation using IOCP.���cCsDd|_g|_tjtjtd|�|_i|_tj	�|_
g|_tj	�|_dS)Nr)
r)�_resultsr
�CreateIoCompletionPort�INVALID_HANDLE_VALUEr[�_iocp�_cacherRrSr9�
_unregistered�_stopped_serving)rZconcurrencyrrrr�s
zIocpProactor.__init__cCsd|jjt|j�t|j�fS)Nz<%s overlapped#=%s result#=%s>)rr1�lenr�r�)rrrr�__repr__�szIocpProactor.__repr__cCs
||_dS)N)r))rrrrr�set_loop�szIocpProactor.set_loopNcCs |js|j|�|j}g|_|S)N)r�r=)r�timeoutrXrrr�select�s

zIocpProactor.selectcCs|jj�}|j|�|S)N)r)r{r/)r�valuer?rrr�_result�s

zIocpProactor._resultrcCsz|j|�tjt�}y4t|tj�r6|j|j�||�n|j|j�|�Wnt	k
rb|j
d�SXdd�}|j|||�S)N�cSsJy|j�Stk
rD}z |jtjkr2t|j��n�WYdd}~XnXdS)N)�	getresultr(rAr
�ERROR_NETNAME_DELETED�ConnectionResetErrorr~)ro�keyrr+rrr�finish_recv�sz&IocpProactor.recv.<locals>.finish_recv)�_register_with_iocpr
�
Overlappedr[�
isinstance�socketZWSARecvrtZReadFile�BrokenPipeErrorr��	_register)r�conn�nbytesr_rr�rrr�recv�s

	zIocpProactor.recvcCsZ|j|�tjt�}t|tj�r4|j|j�||�n|j|j�|�dd�}|j	|||�S)NcSsJy|j�Stk
rD}z |jtjkr2t|j��n�WYdd}~XnXdS)N)r�r(rAr
r�r�r~)ror�rr+rrr�finish_send�sz&IocpProactor.send.<locals>.finish_send)
r�r
r�r[r�r�ZWSASendrtZ	WriteFiler�)rr��bufr_rr�rrr�send�s

	zIocpProactor.sendcsz|j��|j�j��tjt�}|j�j��j����fdd�}tdd��}|j	|�|�}||��}t
j||jd�|S)NcsD|j�tjd�j��}�jtjtj|��j	�j
����j�fS)Nz@P)r��structZpackrt�
setsockoptr��
SOL_SOCKETr
ZSO_UPDATE_ACCEPT_CONTEXT�
settimeoutZ
gettimeoutZgetpeername)ror�rr�)r��listenerrr�
finish_accept�s
z*IocpProactor.accept.<locals>.finish_acceptcss4y|EdHWn tjk
r.|j��YnXdS)N)rrurb)r%r�rrr�accept_coro�s
z(IocpProactor.accept.<locals>.accept_coro)r)
r��_get_accept_socket�familyr
r�r[ZAcceptExrtrr�rZ
ensure_futurer))rr�rr�r�r%�coror)r�r�r�accept�s

		
zIocpProactor.acceptcs�|j��ytj�j��j�WnBtk
rb}z&|jtjkr@��j	�ddkrR�WYdd}~XnXtj
t�}|j�j�|��fdd�}|j
|�|�S)Nrrcs|j��jtjtjd��S)Nr)r�r�r�r�r
ZSO_UPDATE_CONNECT_CONTEXT)ror�r)r�rr�finish_connects
z,IocpProactor.connect.<locals>.finish_connect)r�r
Z	BindLocalrtr�r(rA�errnoZ	WSAEINVALZgetsocknamer�r[Z	ConnectExr�)rr�r �err�r)r�r�connect�s

zIocpProactor.connectcsJ|j��tjt�}|j�j��}|r0|j��S�fdd�}|j|�|�S)Ncs|j��S)N)r�)ror�r)rarr�finish_accept_pipesz4IocpProactor.accept_pipe.<locals>.finish_accept_pipe)r�r
r�r[ZConnectNamedPipertr�r�)rrarZ	connectedr�r)rarrs
s


zIocpProactor.accept_pipeccszt}xjytj|�}PWn0tk
rF}z|jtjkr6�WYdd}~XnXt|dt�}tj	||j
d�EdHqWtj|�S)N�)r)
�CONNECT_PIPE_INIT_DELAYr
ZConnectPiper(rAZERROR_PIPE_BUSY�min�CONNECT_PIPE_MAX_DELAYrZsleepr)r	r\)rr Zdelayr:r+rrrrjs
zIocpProactor.connect_pipecCs|j||d�S)z�Wait for a handle.

        Return a Future object. The result of the future is True if the wait
        completed, or False if the wait did not complete (on timeout).
        F)�_wait_for_handle)rr:r�rrr�wait_for_handle/szIocpProactor.wait_for_handlecCs|j|dd�}||_|S)NT)r�rE)rrFZ
done_callbackr?rrrrO7szIocpProactor._wait_cancelcs�|dkrtj}ntj|d�}tjt�}tj||j|j	|�}|rTt
||||jd��nt|||||jd���j
rv�j
d=�fdd�}�|d|f|j|j	<�S)Ng@�@)rrcs�j�S)N)r=)ror�r)rmrr�finish_wait_for_handleRsz=IocpProactor._wait_for_handle.<locals>.finish_wait_for_handlerr)r<�INFINITE�math�ceilr
r�r[ZRegisterWaitWithQueuer�r rDr)rHrr�)rr:r�Z
_is_cancel�msrr;r�r)rmrr�>s


	zIocpProactor._wait_for_handlecCs0||jkr,|jj|�tj|j�|jdd�dS)Nr)r9r]r
r�rtr�)r�objrrrr�^s
z IocpProactor._register_with_iocpcCs�t||jd�}|jr|jd=|jsjy|dd|�}Wn,tk
r^}z|j|�WYdd}~XnX|j|�||||f|j|j<|S)N)rrr)	rr)rrr(r.r/r�r )rrr��callbackrmr�r�rrrr�hs

zIocpProactor._registercCs|jj|�dS)a
Unregister an overlapped object.

        Call this method when its future has been cancelled. The event can
        already be signalled (pending in the proactor event queue). It is also
        safe if the event is never signalled (because it was cancelled).
        N)r�r>)rrrrrrN�szIocpProactor._unregistercCstj|�}|jd�|S)Nr)r�r�)rr��srrrr��s

zIocpProactor._get_accept_socketcCs�|dkrt}n0|dkr td��ntj|d�}|tkr>td���xtj|j|�}|dkrZPd}|\}}}}y|jj|�\}}	}
}WnVt	k
r�|j
j�r�|j
jdd||||fd��|dtj
fkr�tj|�wBYnX|
|jkr�|j�qB|j�sBy||||	�}Wn:tk
�r@}
z|j|
�|jj|�WYdd}
~
XqBX|j|�|jj|�qBWx |jD]}	|jj|	jd��qdW|jj�dS)Nrznegative timeoutg@�@ztimeout too bigz8GetQueuedCompletionStatus() returned an unexpected eventz)err=%s transferred=%s key=%#x address=%#x)r#�status)r��
ValueErrorr�r�r
ZGetQueuedCompletionStatusr�r��pop�KeyErrorr)Z	get_debugr*r�r<rMr�r'�doner(r.r�r>r/r�r rc)rr�r�r�r�Ztransferredr�r rmrr�r�r�r�rrrr=�sJ






zIocpProactor._pollcCs|jj|�dS)N)r�r])rr�rrr�
_stop_serving�szIocpProactor._stop_servingcCs�x�t|jj��D]�\}\}}}}|j�r*qt|t�r6qy|j�Wqtk
r�}z8|jdk	r�d||d�}|j	rz|j	|d<|jj
|�WYdd}~XqXqWx|jr�|jd�s�tj
d�q�Wg|_|jdk	r�tj|j�d|_dS)NzCancelling a future failed)r#r$r%r&rz"taking long time to close proactor)�listr��itemsZ	cancelledr�rDr'r(r)rr*r=r�debugr�r�r<rM)rr r?rr�r�r+r,rrrrb�s, 


"

zIocpProactor.closecCs|j�dS)N)rb)rrrrrd�szIocpProactor.__del__)r�)N)r)r)N)N)r1r2r3r4rr�r�r�r�r�r�r�r�rsrrjr�rOr�r�r�rNr�r=r�rbrdrrrrr�s.





 
	
7 c@seZdZdd�ZdS)r|c
sPtj|f|||||d�|���_�fdd�}�jjjt�jj��}	|	j|�dS)N)rr�r�r�r�cs�jj�}�j|�dS)N)�_procZpollZ_process_exited)rm�
returncode)rrrr��s
z4_WindowsSubprocessTransport._start.<locals>.callback)	r	�Popenr�r)rIr��intr7rv)
rr~rr�r�r�r�r�r�rmr)rr�_start�sz"_WindowsSubprocessTransport._startN)r1r2r3r�rrrrr|�sr|c@seZdZeZdS)�_WindowsDefaultEventLoopPolicyN)r1r2r3r
Z
_loop_factoryrrrrr�sr�)-r4r<r�r�r�r�rR�rrrrrrr	r
Z
coroutinesr�logr�__all__r[r�ZERROR_CONNECTION_REFUSEDZERROR_CONNECTION_ABORTEDr�r�ZFuturerr6rDrH�objectrPZBaseSelectorEventLoopreZBaseProactorEventLooprrZBaseSubprocessTransportr|r
ZBaseDefaultEventLoopPolicyr�rrrrr�<module>sL0J4;]kPK[�gғg�g,__pycache__/unix_events.cpython-36.opt-2.pycnu�[���3


 \���
@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
ddl	mZddl	mZddl	m
Z
ddl	mZddl	mZdd	l	mZdd
l	mZddl	mZddl	mZdd
lmZddlmZdddddgZejdkr�ed��dd�Zy
ejZWnek
�r(dd�ZYnXGdd�dej�Ze ed��rRdd�Z!nddl"Z"dd�Z!Gd d!�d!ej#�Z$Gd"d#�d#ej%ej&�Z'e ed$��r�ej(Z)nddl"Z"d%d&�Z)Gd'd(�d(ej*�Z+Gd)d�d�Z,Gd*d+�d+e,�Z-Gd,d�de-�Z.Gd-d�de-�Z/Gd.d/�d/ej0�Z1eZ2e1Z3dS)0�N�)�base_events)�base_subprocess)�compat)�	constants)�
coroutines)�events)�futures)�selector_events)�	selectors)�
transports)�	coroutine)�logger�SelectorEventLoop�AbstractChildWatcher�SafeChildWatcher�FastChildWatcher�DefaultEventLoopPolicyZwin32z+Signals are not really supported on WindowscCsdS)N�)�signum�framerr�+/usr/lib64/python3.6/asyncio/unix_events.py�_sighandler_noop%srcCs|S)Nr)�pathrrr�<lambda>.srcs�eZdZd!�fdd�	Zdd�Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
d"dd�Zd#dd�Ze
d$dd��Zdd�Ze
dddd�dd��Ze
d%dddd�dd ��Z�ZS)&�_UnixSelectorEventLoopNcst�j|�i|_dS)N)�super�__init__�_signal_handlers)�self�selector)�	__class__rrr7sz_UnixSelectorEventLoop.__init__cCstj�S)N)�socketZ
socketpair)rrrr�_socketpair;sz"_UnixSelectorEventLoop._socketpaircs^t�j�tj�s2xFt|j�D]}|j|�qWn(|jrZtjd|�d�t	|d�|jj
�dS)NzClosing the loop z@ on interpreter shutdown stage, skipping signal handlers removal)�source)r�close�sys�
is_finalizing�listr�remove_signal_handler�warnings�warn�ResourceWarning�clear)r�sig)r!rrr%>s
z_UnixSelectorEventLoop.closecCs"x|D]}|sq|j|�qWdS)N)�_handle_signal)r�datarrrr�_process_self_dataLs
z)_UnixSelectorEventLoop._process_self_datac+GsHtj|�stj|�rtd��|j|�|j�ytj|jj	��Wn2t
tfk
rt}ztt
|���WYdd}~XnXtj|||�}||j|<ytj|t�tj|d�Wn�tk
�rB}zz|j|=|j�sytjd�Wn4t
tfk
�r}ztjd|�WYdd}~XnX|jtjk�r0tdj|���n�WYdd}~XnXdS)Nz3coroutines cannot be used with add_signal_handler()Frzset_wakeup_fd(-1) failed: %szsig {} cannot be caught���)rZiscoroutineZiscoroutinefunction�	TypeError�
_check_signalZ
_check_closed�signal�
set_wakeup_fdZ_csock�fileno�
ValueError�OSError�RuntimeError�strrZHandlerr�siginterruptr�info�errno�EINVAL�format)rr.�callback�args�exc�handleZnexcrrr�add_signal_handlerSs0



z)_UnixSelectorEventLoop.add_signal_handlercCs8|jj|�}|dkrdS|jr*|j|�n
|j|�dS)N)r�getZ
_cancelledr)Z_add_callback_signalsafe)rr.rDrrrr/�sz%_UnixSelectorEventLoop._handle_signalc&Cs�|j|�y|j|=Wntk
r*dSX|tjkr>tj}ntj}ytj||�Wn@tk
r�}z$|jtj	kr�t
dj|���n�WYdd}~XnX|js�ytjd�Wn2t
tfk
r�}ztjd|�WYdd}~XnXdS)NFzsig {} cannot be caughtrzset_wakeup_fd(-1) failed: %sTr2)r4r�KeyErrorr5�SIGINT�default_int_handler�SIG_DFLr9r>r?r:r@r6r8rr=)rr.ZhandlerrCrrrr)�s(

z,_UnixSelectorEventLoop.remove_signal_handlercCsHt|t�stdj|���d|ko,tjknsDtdj|tj���dS)Nzsig must be an int, not {!r}rzsig {} out of range(1, {}))�
isinstance�intr3r@r5�NSIGr8)rr.rrrr4�s

z$_UnixSelectorEventLoop._check_signalcCst|||||�S)N)�_UnixReadPipeTransport)r�pipe�protocol�waiter�extrarrr�_make_read_pipe_transport�sz0_UnixSelectorEventLoop._make_read_pipe_transportcCst|||||�S)N)�_UnixWritePipeTransport)rrOrPrQrRrrr�_make_write_pipe_transport�sz1_UnixSelectorEventLoop._make_write_pipe_transportc	ks�tj���}
|j�}t||||||||f||d�|	��}|
j|j�|j|�y|EdHWn&tk
r~}
z
|
}WYdd}
~
XnXd}|dk	r�|j�|j	�EdH|�WdQRX|S)N)rQrR)
r�get_child_watcherZ
create_future�_UnixSubprocessTransport�add_child_handlerZget_pid�_child_watcher_callback�	Exceptionr%Z_wait)rrPrB�shell�stdin�stdout�stderr�bufsizerR�kwargs�watcherrQ�transprC�errrrr�_make_subprocess_transport�s$




z1_UnixSelectorEventLoop._make_subprocess_transportcCs|j|j|�dS)N)Zcall_soon_threadsafeZ_process_exited)r�pid�
returncoderbrrrrY�sz._UnixSelectorEventLoop._child_watcher_callback)�ssl�sock�server_hostnameccs�|r|dkr&td��n|dk	r&td��|dk	r�|dk	r>td��tjtjtjd�}y |jd�|j||�EdHWq�|j��Yq�XnB|dkr�td��|jtjks�tj	|j
�r�tdj|���|jd�|j||||�EdH\}}||fS)Nz/you have to pass server_hostname when using sslz+server_hostname is only meaningful with sslz3path and sock can not be specified at the same timerFzno path and sock were specifiedz2A UNIX Domain Stream Socket was expected, got {!r})
r8r"�AF_UNIX�SOCK_STREAM�setblockingZsock_connectr%�familyr�_is_stream_socket�typer@Z_create_connection_transport)r�protocol_factoryrrgrhri�	transportrPrrr�create_unix_connection�s8


z-_UnixSelectorEventLoop.create_unix_connection�d)rh�backlogrgc
!Cs�t|t�rtd��|dk	�r0|dk	r,td��t|�}tjtjtj�}|dd
kr�y tj	t
j|�j�rnt
j|�WnBt
k
r�Yn0tk
r�}ztjd||�WYdd}~XnXy|j|�Wnjtk
�r}z8|j�|jtjk�rdj|�}ttj|�d�n�WYdd}~Xn|j��YnXn>|dk�rBtd��|jtjk�s`tj|j��rntdj|���tj||g�}	|j|�|jd	�|j||||	�|	S)Nz*ssl argument must be an SSLContext or Nonez3path and sock can not be specified at the same timer�z2Unable to check or remove stale UNIX socket %r: %rzAddress {!r} is already in usez-path was not specified, and no sock specifiedz2A UNIX Domain Stream Socket was expected, got {!r}F)rru)rK�boolr3r8�_fspathr"rjrk�stat�S_ISSOCK�os�st_mode�remove�FileNotFoundErrorr9r�errorZbindr%r>Z
EADDRINUSEr@rmrrnroZServerZlistenrlZ_start_serving)
rrprrhrtrgrcrC�msgZserverrrr�create_unix_serversP

 




z)_UnixSelectorEventLoop.create_unix_server)N)NN)NN)N)N)�__name__�
__module__�__qualname__rr#r%r1rEr/r)r4rSrUr
rdrYrrr��
__classcell__rr)r!rr1s*-
 


%r�set_blockingcCstj|d�dS)NF)rzr�)�fdrrr�_set_nonblockingBsr�cCs,tj|tj�}|tjB}tj|tj|�dS)N)�fcntlZF_GETFLrz�
O_NONBLOCKZF_SETFL)r��flagsrrrr�Gs
cs�eZdZdZd �fdd�	Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Ze
jrhdd�Zd!dd�Zdd�Zdd�Z�ZS)"rN�iNcs�t�j|�||jd<||_||_|j�|_||_d|_t	j
|j�j}tj
|�pbtj|�pbtj|�s~d|_d|_d|_td��t|j�|jj|jj|�|jj|jj|j|j�|dk	r�|jjtj|d�dS)NrOFz)Pipe transport is for pipes/sockets only.)rr�_extra�_loop�_piper7�_fileno�	_protocol�_closingrz�fstatr{rx�S_ISFIFOry�S_ISCHRr8r��	call_soon�connection_made�_add_reader�_read_readyr	�_set_result_unless_cancelled)r�looprOrPrQrR�mode)r!rrrQs,






z_UnixReadPipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�t|jdd�}|jdk	r�|dk	r�tj	||jt
j�}|r�|jd�q�|jd�n |jdk	r�|jd�n
|jd�dd	j|�S)
N�closed�closingzfd=%s�	_selector�polling�idle�openz<%s>� )
r!r�r��appendr�r��getattrr�r
�_test_selector_eventrZ
EVENT_READ�join)rr=r r�rrr�__repr__ns$




z_UnixReadPipeTransport.__repr__cCs�ytj|j|j�}WnDttfk
r,Yn�tk
rX}z|j|d�WYdd}~Xn^X|rl|jj	|�nJ|j
j�r�tj
d|�d|_|j
j|j�|j
j|jj�|j
j|jd�dS)Nz"Fatal read error on pipe transportz%r was closed by peerT)rz�readr��max_size�BlockingIOError�InterruptedErrorr9�_fatal_errorr�Z
data_receivedr��	get_debugrr=r��_remove_readerr�Zeof_received�_call_connection_lost)rr0rCrrrr��s
z"_UnixReadPipeTransport._read_readycCs|jj|j�dS)N)r�r�r�)rrrr�
pause_reading�sz$_UnixReadPipeTransport.pause_readingcCs|jj|j|j�dS)N)r�r�r�r�)rrrr�resume_reading�sz%_UnixReadPipeTransport.resume_readingcCs
||_dS)N)r�)rrPrrr�set_protocol�sz#_UnixReadPipeTransport.set_protocolcCs|jS)N)r�)rrrr�get_protocol�sz#_UnixReadPipeTransport.get_protocolcCs|jS)N)r�)rrrr�
is_closing�sz!_UnixReadPipeTransport.is_closingcCs|js|jd�dS)N)r��_close)rrrrr%�sz_UnixReadPipeTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)r$)r�r*r+r,r%)rrrr�__del__�s
z_UnixReadPipeTransport.__del__�Fatal error on pipe transportcCsZt|t�r4|jtjkr4|jj�rLtjd||dd�n|jj||||j	d��|j
|�dS)Nz%r: %sT)�exc_info)�message�	exceptionrqrP)rKr9r>ZEIOr�r�r�debug�call_exception_handlerr�r�)rrCr�rrrr��s
z#_UnixReadPipeTransport._fatal_errorcCs(d|_|jj|j�|jj|j|�dS)NT)r�r�r�r�r�r�)rrCrrrr��sz_UnixReadPipeTransport._closecCs4z|jj|�Wd|jj�d|_d|_d|_XdS)N)r��connection_lostr�r%r�)rrCrrrr��s
z,_UnixReadPipeTransport._call_connection_losti)NN)r�)r�r�r�r�rr�r�r�r�r�r�r�r%r�PY34r�r�r�r�r�rr)r!rrNMs
rNcs�eZdZd%�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zejr|dd�Zdd�Zd&dd �Zd'd!d"�Zd#d$�Z�ZS)(rTNc
s�t�j||�||jd<||_|j�|_||_t�|_d|_	d|_
tj|j�j
}tj|�}tj|�}tj|�}	|px|px|	s�d|_d|_d|_td��t|j�|jj|jj|�|	s�|r�tjjd�r�|jj|jj|j|j�|dk	r�|jjtj|d�dS)NrOrFz?Pipe transport is only for pipes, sockets and character devices�aix)rrr�r�r7r�r��	bytearray�_buffer�
_conn_lostr�rzr�r{rxr�r�ryr8r�r�r�r�r&�platform�
startswithr�r�r	r�)
rr�rOrPrQrRr�Zis_charZis_fifoZ	is_socket)r!rrr�s2






z _UnixWritePipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�t|jdd�}|jdk	r�|dk	r�tj	||jt
j�}|r�|jd�n
|jd�|j�}|jd|�n |jdk	r�|jd�n
|jd�d	d
j
|�S)Nr�r�zfd=%sr�r�r�z
bufsize=%sr�z<%s>r�)r!r�r�r�r�r�r�r�r
r�rZEVENT_WRITE�get_write_buffer_sizer�)rr=r r�r_rrrr��s(





z _UnixWritePipeTransport.__repr__cCs
t|j�S)N)�lenr�)rrrrr�sz-_UnixWritePipeTransport.get_write_buffer_sizecCs6|jj�rtjd|�|jr*|jt��n|j�dS)Nz%r was closed by peer)r�r�rr=r�r��BrokenPipeError)rrrrr�s

z#_UnixWritePipeTransport._read_readycCst|t�rt|�}|sdS|js&|jrN|jtjkr<tjd�|jd7_dS|j	�s�yt
j|j|�}WnTt
tfk
r�d}Yn:tk
r�}z|jd7_|j|d�dSd}~XnX|t|�kr�dS|dkr�t|�|d�}|jj|j|j�|j	|7_	|j�dS)Nz=pipe closed by peer or os.write(pipe, data) raised exception.rrz#Fatal write error on pipe transport)rKr��
memoryviewr�r�rZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr�warningr�rz�writer�r�r�rZr�r�r�Z_add_writer�_write_readyZ_maybe_pause_protocol)rr0�nrCrrrr�s2

z_UnixWritePipeTransport.writecCs�ytj|j|j�}Wnjttfk
r,Yn�tk
r~}z8|jj�|jd7_|j	j
|j�|j|d�WYdd}~XnfX|t|j�kr�|jj�|j	j
|j�|j
�|jr�|j	j|j�|jd�dS|dkr�|jd|�=dS)Nrz#Fatal write error on pipe transportr)rzr�r�r�r�r�rZr-r�r��_remove_writerr�r�Z_maybe_resume_protocolr�r�r�)rr�rCrrrr�>s&


z$_UnixWritePipeTransport._write_readycCsdS)NTr)rrrr�
can_write_eofXsz%_UnixWritePipeTransport.can_write_eofcCs8|jr
dSd|_|js4|jj|j�|jj|jd�dS)NT)r�r�r�r�r�r�r�)rrrr�	write_eof[sz!_UnixWritePipeTransport.write_eofcCs
||_dS)N)r�)rrPrrrr�dsz$_UnixWritePipeTransport.set_protocolcCs|jS)N)r�)rrrrr�gsz$_UnixWritePipeTransport.get_protocolcCs|jS)N)r�)rrrrr�jsz"_UnixWritePipeTransport.is_closingcCs|jdk	r|jr|j�dS)N)r�r�r�)rrrrr%msz_UnixWritePipeTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)r$)r�r*r+r,r%)rrrrr�vs
z_UnixWritePipeTransport.__del__cCs|jd�dS)N)r�)rrrr�abort|sz_UnixWritePipeTransport.abort�Fatal error on pipe transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)r�)r�r�rqrP)
rKrZ_FATAL_ERROR_IGNOREr�r�rr�r�r�r�)rrCr�rrrr�s
z$_UnixWritePipeTransport._fatal_errorcCsFd|_|jr|jj|j�|jj�|jj|j�|jj|j|�dS)NT)	r�r�r�r�r�r-r�r�r�)rrCrrrr��s
z_UnixWritePipeTransport._closecCs4z|jj|�Wd|jj�d|_d|_d|_XdS)N)r�r�r�r%r�)rrCrrrr��s
z-_UnixWritePipeTransport._call_connection_lost)NN)r�)N)r�r�r�rr�r�r�r�r�r�r�r�r�r�r%rr�r�r�r�r�r�r�rr)r!rrT�s$%	!	

rT�set_inheritablecCsNttdd�}tj|tj�}|s4tj|tj||B�ntj|tj||@�dS)NZ
FD_CLOEXECr)r�r�ZF_GETFDZF_SETFD)r�ZinheritableZcloexec_flag�oldrrr�_set_inheritable�s
r�c@seZdZdd�ZdS)rWc		Ksvd}|tjkr*|jj�\}}t|j�d�tj|f||||d|d�|��|_|dk	rr|j�t	|j
�d|d�|j_dS)NF)r[r\r]r^Zuniversal_newlinesr_�wb)�	buffering)�
subprocess�PIPEr�r#r�r7�Popen�_procr%r��detachr\)	rrBr[r\r]r^r_r`Zstdin_wrrr�_start�s
z_UnixSubprocessTransport._startN)r�r�r�r�rrrrrW�srWc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rcGs
t��dS)N)�NotImplementedError)rrerArBrrrrX�s	z&AbstractChildWatcher.add_child_handlercCs
t��dS)N)r�)rrerrr�remove_child_handler�sz)AbstractChildWatcher.remove_child_handlercCs
t��dS)N)r�)rr�rrr�attach_loop�sz AbstractChildWatcher.attach_loopcCs
t��dS)N)r�)rrrrr%�szAbstractChildWatcher.closecCs
t��dS)N)r�)rrrr�	__enter__szAbstractChildWatcher.__enter__cCs
t��dS)N)r�)r�a�b�crrr�__exit__	szAbstractChildWatcher.__exit__N)	r�r�r�rXr�r�r%r�r�rrrrr�s
c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�BaseChildWatchercCsd|_i|_dS)N)r��
_callbacks)rrrrrszBaseChildWatcher.__init__cCs|jd�dS)N)r�)rrrrr%szBaseChildWatcher.closecCs
t��dS)N)r�)r�expected_pidrrr�_do_waitpidszBaseChildWatcher._do_waitpidcCs
t��dS)N)r�)rrrr�_do_waitpid_allsz BaseChildWatcher._do_waitpid_allcCsf|jdk	r$|dkr$|jr$tjdt�|jdk	r<|jjtj�||_|dk	rb|jtj|j	�|j
�dS)NzCA loop is being detached from a child watcher with pending handlers)r�r�r*r+�RuntimeWarningr)r5�SIGCHLDrE�	_sig_chldr�)rr�rrrr�s
zBaseChildWatcher.attach_loopcCsFy|j�Wn4tk
r@}z|jjd|d��WYdd}~XnXdS)Nz$Unknown exception in SIGCHLD handler)r�r�)r�rZr�r�)rrCrrrr�1szBaseChildWatcher._sig_chldcCs2tj|�rtj|�Stj|�r*tj|�S|SdS)N)rz�WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS)r�statusrrr�_compute_returncode=s



z$BaseChildWatcher._compute_returncodeN)
r�r�r�rr%r�r�r�r�r�rrrrr�sr�csLeZdZ�fdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	�Z
S)rcs|jj�t�j�dS)N)r�r-rr%)r)r!rrr%Vs
zSafeChildWatcher.closecCs|S)Nr)rrrrr�ZszSafeChildWatcher.__enter__cCsdS)Nr)rr�r�r�rrrr�]szSafeChildWatcher.__exit__cGs.|jdkrtd��||f|j|<|j|�dS)NzICannot add child handler, the child watcher does not have a loop attached)r�r:r�r�)rrerArBrrrrX`s

z"SafeChildWatcher.add_child_handlercCs&y|j|=dStk
r dSXdS)NTF)r�rG)rrerrrr�ks
z%SafeChildWatcher.remove_child_handlercCs"xt|j�D]}|j|�qWdS)N)r(r�r�)rrerrrr�rsz SafeChildWatcher._do_waitpid_allcCs�ytj|tj�\}}Wn(tk
r>|}d}tjd|�Yn0X|dkrLdS|j|�}|jj�rntj	d||�y|j
j|�\}}Wn.tk
r�|jj�r�tjd|dd�YnX|||f|��dS)N�z8Unknown child process pid %d, will report returncode 255rz$process %s exited with returncode %sz'Child watcher got an unexpected pid: %rT)r�)
rz�waitpid�WNOHANG�ChildProcessErrorrr�r�r�r�r�r��poprG)rr�rer�rfrArBrrrr�ws*


zSafeChildWatcher._do_waitpid)r�r�r�r%r�r�rXr�r�r�r�rr)r!rrKscsPeZdZ�fdd�Z�fdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	�Z
S)rcs$t�j�tj�|_i|_d|_dS)Nr)rr�	threadingZLock�_lock�_zombies�_forks)r)r!rrr�s

zFastChildWatcher.__init__cs"|jj�|jj�t�j�dS)N)r�r-r�rr%)r)r!rrr%�s

zFastChildWatcher.closec
Cs$|j�|jd7_|SQRXdS)Nr)r�r�)rrrrr��szFastChildWatcher.__enter__c
CsV|j�:|jd8_|js$|jr(dSt|j�}|jj�WdQRXtjd|�dS)Nrz5Caught subprocesses termination from unknown pids: %s)r�r�r�r;r-rr�)rr�r�r�Zcollateral_victimsrrrr��s
zFastChildWatcher.__exit__cGsl|jdkrtd��|j�:y|jj|�}Wn"tk
rL||f|j|<dSXWdQRX|||f|��dS)NzICannot add child handler, the child watcher does not have a loop attached)r�r:r�r�r�rGr�)rrerArBrfrrrrX�s
z"FastChildWatcher.add_child_handlercCs&y|j|=dStk
r dSXdS)NTF)r�rG)rrerrrr��s
z%FastChildWatcher.remove_child_handlercCs�x�ytjdtj�\}}Wntk
r,dSX|dkr:dS|j|�}|j�vy|jj|�\}}WnBtk
r�|j	r�||j
|<|jj�r�t
jd||�wd}YnX|jj�r�t
jd||�WdQRX|dkr�t
jd||�q|||f|��qWdS)Nrrz,unknown process %s exited with returncode %sz$process %s exited with returncode %sz8Caught subprocess termination from unknown pid: %d -> %dr2)rzr�r�r�r�r�r�r�rGr�r�r�r�rr�r�)rrer�rfrArBrrrr��s6





z FastChildWatcher._do_waitpid_all)r�r�r�rr%r�r�rXr�r�r�rr)r!rr�s
csDeZdZeZ�fdd�Zdd�Z�fdd�Zdd�Zd	d
�Z	�Z
S)�_UnixDefaultEventLoopPolicycst�j�d|_dS)N)rr�_watcher)r)r!rrrs
z$_UnixDefaultEventLoopPolicy.__init__c
CsHtj�8|jdkr:t�|_ttj�tj�r:|jj|j	j
�WdQRXdS)N)rr�r�rrKr��current_thread�_MainThreadr��_localr�)rrrr�
_init_watchers
z)_UnixDefaultEventLoopPolicy._init_watchercs6t�j|�|jdk	r2ttj�tj�r2|jj|�dS)N)r�set_event_loopr�rKr�r�r�r�)rr�)r!rrrs
z*_UnixDefaultEventLoopPolicy.set_event_loopcCs|jdkr|j�|jS)N)r�r)rrrrrV&s
z-_UnixDefaultEventLoopPolicy.get_child_watchercCs|jdk	r|jj�||_dS)N)r�r%)rrarrr�set_child_watcher0s

z-_UnixDefaultEventLoopPolicy.set_child_watcher)r�r�r�rZ
_loop_factoryrrrrVrr�rr)r!rr�s
r�)4r>rzr5r"rxr�r&r�r*�rrrrrrr	r
rrr
�logr�__all__r��ImportErrorr�fspathrw�AttributeErrorZBaseSelectorEventLoopr�hasattrr�r�Z
ReadTransportrNZ_FlowControlMixinZWriteTransportrTr�r�ZBaseSubprocessTransportrWrr�rrZBaseDefaultEventLoopPolicyr�rrrrrr�<module>sl


O
F=On2PK[����M�M"__pycache__/streams.cpython-36.pycnu�[���3


 \�_�@sLdZdddddddgZdd	lZeed
�r6ejddg�d
dlmZd
dlmZd
dlmZd
dlm	Z	d
dlm
Z
d
dlmZd"Z
Gdd�de�ZGdd�de�Ze
d#d	e
d�dd��Ze
d$d	e
d�dd��Zeed
��re
d%d	e
d�dd��Ze
d&d	e
d�dd��ZGdd�de	j�ZGdd�dee	j�ZGd d�d�ZGd!d�d�Zd	S)'zStream-related things.�StreamReader�StreamWriter�StreamReaderProtocol�open_connection�start_server�IncompleteReadError�LimitOverrunError�NZAF_UNIX�open_unix_connection�start_unix_server�)�
coroutines)�compat)�events)�	protocols)�	coroutine)�logger��cs(eZdZdZ�fdd�Zdd�Z�ZS)rz�
    Incomplete read error. Attributes:

    - partial: read bytes string before the end of stream was reached
    - expected: total number of expected bytes (or None if unknown)
    cs(t�jdt|�|f�||_||_dS)Nz-%d bytes read on a total of %r expected bytes)�super�__init__�len�partial�expected)�selfrr)�	__class__��'/usr/lib64/python3.6/asyncio/streams.pyr szIncompleteReadError.__init__cCst|�|j|jffS)N)�typerr)rrrr�
__reduce__&szIncompleteReadError.__reduce__)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__rr)rrrscs(eZdZdZ�fdd�Zdd�Z�ZS)rz�Reached the buffer limit while looking for a separator.

    Attributes:
    - consumed: total number of to be consumed bytes.
    cst�j|�||_dS)N)rr�consumed)r�messager$)rrrr0szLimitOverrunError.__init__cCst|�|jd|jffS)Nr)r�argsr$)rrrrr4szLimitOverrunError.__reduce__)rr r!r"rrr#rr)rrr*s)�loop�limitc	+sb|dkrtj�}t||d�}t||d��|j�fdd�||f|�EdH\}}t|�||�}||fS)a�A wrapper for create_connection() returning a (reader, writer) pair.

    The reader returned is a StreamReader instance; the writer is a
    StreamWriter instance.

    The arguments are all the usual arguments to create_connection()
    except protocol_factory; most common are positional host and port,
    with various optional keyword arguments following.

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    (If you want to customize the StreamReader and/or
    StreamReaderProtocol classes, just copy the code -- there's
    really nothing special here except some convenience.)
    N)r(r')r'cs�S)Nrr)�protocolrr�<lambda>Qsz!open_connection.<locals>.<lambda>)r�get_event_looprrZcreate_connectionr)	�host�portr'r(�kwds�reader�	transport�_�writerr)r)rr8s c+s8�dkrtj�����fdd�}�j|||f|�EdHS)a�Start a socket server, call back for each client connected.

    The first parameter, `client_connected_cb`, takes two parameters:
    client_reader, client_writer.  client_reader is a StreamReader
    object, while client_writer is a StreamWriter object.  This
    parameter can either be a plain callback function or a coroutine;
    if it is a coroutine, it will be automatically converted into a
    Task.

    The rest of the arguments are all the usual arguments to
    loop.create_server() except protocol_factory; most common are
    positional host and port, with various optional keyword arguments
    following.  The return value is the same as loop.create_server().

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    The return value is the same as loop.create_server(), i.e. a
    Server object which can be used to stop the service.
    Ncst��d�}t|��d�}|S)N)r(r')r')rr)r/r))�client_connected_cbr(r'rr�factoryqszstart_server.<locals>.factory)rr+Z
create_server)r3r,r-r'r(r.r4r)r3r(r'rrVsc+s`|dkrtj�}t||d�}t||d��|j�fdd�|f|�EdH\}}t|�||�}||fS)z@Similar to `open_connection` but works with UNIX Domain Sockets.N)r(r')r'cs�S)Nrr)r)rrr*�sz&open_unix_connection.<locals>.<lambda>)rr+rrZcreate_unix_connectionr)�pathr'r(r.r/r0r1r2r)r)rr	}sc+s6�dkrtj�����fdd�}�j||f|�EdHS)z=Similar to `start_server` but works with UNIX Domain Sockets.Ncst��d�}t|��d�}|S)N)r(r')r')rr)r/r))r3r(r'rrr4�sz"start_unix_server.<locals>.factory)rr+Zcreate_unix_server)r3r5r'r(r.r4r)r3r(r'rr
�sc@s>eZdZdZd
dd�Zdd�Zdd�Zd	d
�Zedd��Z	dS)�FlowControlMixina)Reusable flow control logic for StreamWriter.drain().

    This implements the protocol methods pause_writing(),
    resume_reading() and connection_lost().  If the subclass overrides
    these it must call the super methods.

    StreamWriter.drain() must wait for _drain_helper() coroutine.
    NcCs0|dkrtj�|_n||_d|_d|_d|_dS)NF)rr+�_loop�_paused�
_drain_waiter�_connection_lost)rr'rrrr�szFlowControlMixin.__init__cCs,|jst�d|_|jj�r(tjd|�dS)NTz%r pauses writing)r8�AssertionErrorr7�	get_debugr�debug)rrrr�
pause_writing�s
zFlowControlMixin.pause_writingcCsP|js
t�d|_|jj�r&tjd|�|j}|dk	rLd|_|j�sL|jd�dS)NFz%r resumes writing)	r8r;r7r<rr=r9�done�
set_result)r�waiterrrr�resume_writing�s

zFlowControlMixin.resume_writingcCsVd|_|jsdS|j}|dkr"dSd|_|j�r4dS|dkrH|jd�n
|j|�dS)NT)r:r8r9r?r@�
set_exception)r�excrArrr�connection_lost�sz FlowControlMixin.connection_lostccsP|jrtd��|jsdS|j}|dks2|j�s2t�|jj�}||_|EdHdS)NzConnection lost)r:�ConnectionResetErrorr8r9�	cancelledr;r7�
create_future)rrArrr�
_drain_helper�s
zFlowControlMixin._drain_helper)N)
rr r!r"rr>rBrErrIrrrrr6�s
	r6csFeZdZdZd
�fdd�	Zdd�Z�fdd�Zd	d
�Zdd�Z�Z	S)ra=Helper class to adapt between Protocol and StreamReader.

    (This is a helper class instead of making StreamReader itself a
    Protocol subclass, because the StreamReader has other potential
    uses, and to prevent the user of the StreamReader to accidentally
    call inappropriate methods of the protocol.)
    Ncs*t�j|d�||_d|_||_d|_dS)N)r'F)rr�_stream_reader�_stream_writer�_client_connected_cb�	_over_ssl)rZ
stream_readerr3r')rrrr�s
zStreamReaderProtocol.__init__cCsd|jj|�|jd�dk	|_|jdk	r`t|||j|j�|_|j|j|j�}tj	|�r`|jj
|�dS)NZ
sslcontext)rJ�
set_transport�get_extra_inforMrLrr7rKrZiscoroutineZcreate_task)rr0�resrrr�connection_made�s


z$StreamReaderProtocol.connection_madecsF|jdk	r*|dkr|jj�n|jj|�t�j|�d|_d|_dS)N)rJ�feed_eofrCrrErK)rrD)rrrrE�s
z$StreamReaderProtocol.connection_lostcCs|jj|�dS)N)rJ�	feed_data)r�datarrr�
data_receivedsz"StreamReaderProtocol.data_receivedcCs|jj�|jrdSdS)NFT)rJrRrM)rrrr�eof_receiveds
z!StreamReaderProtocol.eof_received)NN)
rr r!r"rrQrErUrVr#rr)rrr�s
c@sjeZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zddd�Z
edd��ZdS)ra'Wraps a Transport.

    This exposes write(), writelines(), [can_]write_eof(),
    get_extra_info() and close().  It adds drain() which returns an
    optional Future on which you can wait for flow control.  It also
    adds a transport property which references the Transport
    directly.
    cCs2||_||_|dks"t|t�s"t�||_||_dS)N)�
_transport�	_protocol�
isinstancerr;�_readerr7)rr0r)r/r'rrrrs
zStreamWriter.__init__cCs:|jjd|jg}|jdk	r,|jd|j�ddj|�S)Nztransport=%rz	reader=%rz<%s>� )rrrWrZ�append�join)r�inforrr�__repr__!s
zStreamWriter.__repr__cCs|jS)N)rW)rrrrr0'szStreamWriter.transportcCs|jj|�dS)N)rW�write)rrTrrrr`+szStreamWriter.writecCs|jj|�dS)N)rW�
writelines)rrTrrrra.szStreamWriter.writelinescCs
|jj�S)N)rW�	write_eof)rrrrrb1szStreamWriter.write_eofcCs
|jj�S)N)rW�
can_write_eof)rrrrrc4szStreamWriter.can_write_eofcCs
|jj�S)N)rW�close)rrrrrd7szStreamWriter.closeNcCs|jj||�S)N)rWrO)r�name�defaultrrrrO:szStreamWriter.get_extra_infoccsN|jdk	r |jj�}|dk	r |�|jdk	r:|jj�r:dV|jj�EdHdS)z~Flush the write buffer.

        The intended use is to write

          w.write(data)
          yield from w.drain()
        N)rZ�	exceptionrWZ
is_closingrXrI)rrDrrr�drain=s	



zStreamWriter.drain)N)rr r!r"rr_�propertyr0r`rarbrcrdrOrrhrrrrrs
c@s�eZdZedfdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
edd��Zedd��Zed'dd��Zed)dd��Zed d!��Zejr�ed"d#��Zed$d%��Zejr�d&d#�ZdS)*rNcCsZ|dkrtd��||_|dkr*tj�|_n||_t�|_d|_d|_d|_	d|_
d|_dS)NrzLimit cannot be <= 0F)�
ValueError�_limitrr+r7�	bytearray�_buffer�_eof�_waiter�
_exceptionrWr8)rr(r'rrrrXszStreamReader.__init__cCs�dg}|jr |jdt|j��|jr0|jd�|jtkrJ|jd|j�|jr`|jd|j�|jrv|jd|j�|jr�|jd|j�|j	r�|jd�d	d
j
|�S)Nrz%d bytes�eofzl=%dzw=%rze=%rzt=%rZpausedz<%s>r[)rmr\rrnrk�_DEFAULT_LIMITrorprWr8r])rr^rrrr_ks 


zStreamReader.__repr__cCs|jS)N)rp)rrrrrg}szStreamReader.exceptioncCs0||_|j}|dk	r,d|_|j�s,|j|�dS)N)rprorGrC)rrDrArrrrC�szStreamReader.set_exceptioncCs*|j}|dk	r&d|_|j�s&|jd�dS)z1Wakeup read*() functions waiting for data or EOF.N)rorGr@)rrArrr�_wakeup_waiter�s
zStreamReader._wakeup_waitercCs|jdkstd��||_dS)NzTransport already set)rWr;)rr0rrrrN�szStreamReader.set_transportcCs*|jr&t|j�|jkr&d|_|jj�dS)NF)r8rrmrkrW�resume_reading)rrrr�_maybe_resume_transport�sz$StreamReader._maybe_resume_transportcCsd|_|j�dS)NT)rnrs)rrrrrR�szStreamReader.feed_eofcCs|jo|jS)z=Return True if the buffer is empty and 'feed_eof' was called.)rnrm)rrrr�at_eof�szStreamReader.at_eofcCs�|jstd��|sdS|jj|�|j�|jdk	r�|jr�t|j�d|jkr�y|jj	�Wnt
k
rzd|_YnXd|_dS)Nzfeed_data after feed_eofrT)rnr;rm�extendrsrWr8rrkZ
pause_reading�NotImplementedError)rrTrrrrS�s
zStreamReader.feed_dataccsf|jdk	rtd|��|js&td��|jr<d|_|jj�|jj�|_z|jEdHWdd|_XdS)zpWait until feed_data() or feed_eof() is called.

        If stream was paused, automatically resume it.
        NzH%s() called while another coroutine is already waiting for incoming dataz_wait_for_data after EOFF)	ro�RuntimeErrorrnr;r8rWrtr7rH)rZ	func_namerrr�_wait_for_data�s


zStreamReader._wait_for_dataccs�d}t|�}y|j|�EdH}Wn�tk
rB}z|jSd}~Xnftk
r�}zJ|jj||j�rv|jd|j|�=n
|jj�|j	�t
|jd��WYdd}~XnX|S)a�Read chunk of data from the stream until newline (b'
') is found.

        On success, return chunk that ends with newline. If only partial
        line can be read due to EOF, return incomplete line without
        terminating newline. When EOF was reached while no bytes read, empty
        bytes object is returned.

        If limit is reached, ValueError will be raised. In that case, if
        newline was found, complete line including newline will be removed
        from internal buffer. Else, internal buffer will be cleared. Limit is
        compared against part of the line without newline.

        If stream was paused, this function will automatically resume it if
        needed.
        �
Nr)r�	readuntilrrrrm�
startswithr$�clearrurjr&)r�sep�seplen�line�errr�readline�s
 zStreamReader.readliner{ccs�t|�}|dkrtd��|jdk	r(|j�d}x�t|j�}|||kr||jj||�}|dkr\P|d|}||jkr|td|��|jr�t|j�}|jj	�t
|d��|jd�EdHq.W||jkr�td|��|jd||�}|jd||�=|j�t|�S)	aVRead data from the stream until ``separator`` is found.

        On success, the data and separator will be removed from the
        internal buffer (consumed). Returned data will include the
        separator at the end.

        Configured stream limit is used to check result. Limit sets the
        maximal length of data that can be returned, not counting the
        separator.

        If an EOF occurs and the complete separator is still not found,
        an IncompleteReadError exception will be raised, and the internal
        buffer will be reset.  The IncompleteReadError.partial attribute
        may contain the separator partially.

        If the data cannot be read because of over limit, a
        LimitOverrunError exception  will be raised, and the data
        will be left in the internal buffer, so it can be read again.
        rz,Separator should be at least one-byte stringNrz2Separator is not found, and chunk exceed the limitr|z2Separator is found, but chunk is longer than limit���)
rrjrprm�findrkrrn�bytesr~rrzru)rZ	separatorr��offsetZbuflenZisep�chunkrrrr|�s:






zStreamReader.readuntilrccs�|jdk	r|j�|dkrdS|dkrZg}x&|j|j�EdH}|sBP|j|�q*Wdj|�S|jrz|jrz|jd�EdHt|jd|��}|jd|�=|j	�|S)a�Read up to `n` bytes from the stream.

        If n is not provided, or set to -1, read until EOF and return all read
        bytes. If the EOF was received and the internal buffer is empty, return
        an empty bytes object.

        If n is zero, return empty bytes object immediately.

        If n is positive, this function try to read `n` bytes, and may return
        less or equal bytes than requested, but at least one byte. If EOF was
        received before any byte is read, this function returns empty byte
        object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        Nr��read)
rpr�rkr\r]rmrnrzr�ru)r�nZblocks�blockrTrrrr�Ps$

zStreamReader.readccs�|dkrtd��|jdk	r |j�|dkr,dSxFt|j�|krr|jr`t|j�}|jj�t||��|jd�EdHq.Wt|j�|kr�t|j�}|jj�nt|jd|��}|jd|�=|j	�|S)a�Read exactly `n` bytes.

        Raise an IncompleteReadError if EOF is reached before `n` bytes can be
        read. The IncompleteReadError.partial attribute of the exception will
        contain the partial read bytes.

        if n is zero, return empty bytes object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        rz*readexactly size can not be less than zeroNr��readexactly)
rjrprrmrnr�r~rrzru)rr�Z
incompleterTrrrr��s&




zStreamReader.readexactlycCs|S)Nr)rrrr�	__aiter__�szStreamReader.__aiter__ccs|j�EdH}|dkrt�|S)Nr�)r��StopAsyncIteration)r�valrrr�	__anext__�szStreamReader.__anext__cCs|S)Nr)rrrrr��s)r{r�)r�)rr r!rrrr_rgrCrsrNrurRrvrSrrzr�r|r�r�r
ZPY35r�r�ZPY352rrrrrVs,	 [2*i)NN)NN)N)N)r"�__all__Zsocket�hasattrrw�rr
rrr�logrrr�EOFErrorr�	Exceptionrrrr	r
ZProtocolr6rrrrrrr�<module>sB
"B3GPK[G��4GG+__pycache__/base_tasks.cpython-36.opt-1.pycnu�[���3


 \��@sDddlZddlZddlmZddlmZdd�Zdd�Zd	d
�ZdS)�N�)�base_futures)�
coroutinescCsTtj|�}|jrd|d<tj|j�}|jdd|�|jdk	rP|jdd|j�|S)NZ
cancellingrrz	coro=<%s>�zwait_for=%r)rZ_future_repr_infoZ_must_cancelrZ_format_coroutine�_coro�insertZ_fut_waiter)�task�info�coro�r�*/usr/lib64/python3.6/asyncio/base_tasks.py�_task_repr_infos

r
cCs�g}y|jj}Wntk
r,|jj}YnX|dk	rxx6|dk	rl|dk	rZ|dkrRP|d8}|j|�|j}q8W|j�nL|jdk	r�|jj}x8|dk	r�|dk	r�|dkr�P|d8}|j|j	�|j
}q�W|S)Nrr)r�cr_frame�AttributeError�gi_frame�append�f_back�reverse�
_exception�
__traceback__�tb_frame�tb_next)r�limitZframes�f�tbrrr�_task_get_stacks0






rcCs�g}t�}xj|j|d�D]Z}|j}|j}|j}|j}	||krP|j|�tj|�tj	|||j
�}
|j|||	|
f�qW|j}|s�t
d||d�n*|dk	r�t
d||d�nt
d||d�tj||d�|dk	r�x$tj|j|�D]}
t
|
|dd�q�WdS)N)rzNo stack for %r)�filez)Traceback for %r (most recent call last):z%Stack for %r (most recent call last):�)r�end)�setZ	get_stack�f_lineno�f_code�co_filename�co_name�add�	linecache�
checkcache�getline�	f_globalsrr�print�	traceback�
print_list�format_exception_only�	__class__)rrr�extracted_listZcheckedr�lineno�co�filename�name�line�excrrr�_task_print_stack3s0


r5)r%r*rrrr
rr5rrrr�<module>sPK[�a��Z<Z< __pycache__/locks.cpython-36.pycnu�[���3


 \�<�@s�dZdddddgZddlZdd	lmZdd
lmZddlmZddlmZGd
d�d�Z	Gdd�d�Z
Gdd�de
�ZGdd�d�ZGdd�de
�Z
Gdd�de
�ZGdd�de�ZdS)zSynchronization primitives.�Lock�Event�	Condition�	Semaphore�BoundedSemaphore�N�)�compat)�events)�futures)�	coroutinec@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_ContextManageraContext manager.

    This enables the following idiom for acquiring and releasing a
    lock around a block:

        with (yield from lock):
            <block>

    while failing loudly when accidentally using:

        with lock:
            <block>
    cCs
||_dS)N)�_lock)�self�lock�r�%/usr/lib64/python3.6/asyncio/locks.py�__init__sz_ContextManager.__init__cCsdS)Nr)rrrr�	__enter__sz_ContextManager.__enter__cGsz|jj�Wdd|_XdS)N)r
�release)r�argsrrr�__exit__$sz_ContextManager.__exit__N)�__name__�
__module__�__qualname__�__doc__rrrrrrrr
s
rc@sNeZdZdd�Zdd�Zedd��ZejrJdd�Z	ed	d
��Z
edd��Zd
S)�_ContextManagerMixincCstd��dS)Nz9"yield from" should be used as context manager expression)�RuntimeError)rrrrr,sz_ContextManagerMixin.__enter__cGsdS)Nr)rrrrrr0sz_ContextManagerMixin.__exit__ccs|j�EdHt|�S)N)�acquirer)rrrr�__iter__5sz_ContextManagerMixin.__iter__ccs|j�EdHt|�S)N)rr)rrrr�	__await__Hsz_ContextManagerMixin.__await__ccs|j�EdHdS)N)r)rrrr�
__aenter__Msz_ContextManagerMixin.__aenter__cCs|j�dS)N)r)r�exc_type�exc�tbrrr�	__aexit__Tsz_ContextManagerMixin.__aexit__N)rrrrrrrrZPY35rr r$rrrrr+srcsReZdZdZdd�dd�Z�fdd�Zdd	�Zed
d��Zdd
�Z	dd�Z
�ZS)ra�Primitive lock objects.

    A primitive lock is a synchronization primitive that is not owned
    by a particular coroutine when locked.  A primitive lock is in one
    of two states, 'locked' or 'unlocked'.

    It is created in the unlocked state.  It has two basic methods,
    acquire() and release().  When the state is unlocked, acquire()
    changes the state to locked and returns immediately.  When the
    state is locked, acquire() blocks until a call to release() in
    another coroutine changes it to unlocked, then the acquire() call
    resets it to locked and returns.  The release() method should only
    be called in the locked state; it changes the state to unlocked
    and returns immediately.  If an attempt is made to release an
    unlocked lock, a RuntimeError will be raised.

    When more than one coroutine is blocked in acquire() waiting for
    the state to turn to unlocked, only one coroutine proceeds when a
    release() call resets the state to unlocked; first coroutine which
    is blocked in acquire() is being processed.

    acquire() is a coroutine and should be called with 'yield from'.

    Locks also support the context management protocol.  '(yield from lock)'
    should be used as the context manager expression.

    Usage:

        lock = Lock()
        ...
        yield from lock
        try:
            ...
        finally:
            lock.release()

    Context manager usage:

        lock = Lock()
        ...
        with (yield from lock):
             ...

    Lock objects can be tested for locking state:

        if not lock.locked():
           yield from lock
        else:
           # lock is acquired
           ...

    N)�loopcCs.tj�|_d|_|dk	r ||_n
tj�|_dS)NF)�collections�deque�_waiters�_locked�_loopr	�get_event_loop)rr%rrrr�s

z
Lock.__init__csDt�j�}|jrdnd}|jr0dj|t|j��}dj|dd�|�S)N�locked�unlockedz
{},waiters:{}z	<{} [{}]>r���)�super�__repr__r)r(�format�len)r�res�extra)�	__class__rrr0�s

z
Lock.__repr__cCs|jS)z Return True if lock is acquired.)r))rrrrr,�szLock.lockedccs�|jr&tdd�|jD��r&d|_dS|jj�}|jj|�y"z|EdHWd|jj|�XWn&tjk
r�|js~|j	��YnXd|_dS)z�Acquire a lock.

        This method blocks until the lock is unlocked, then sets it to
        locked and returns True.
        css|]}|j�VqdS)N)�	cancelled)�.0�wrrr�	<genexpr>�szLock.acquire.<locals>.<genexpr>TN)
r)�allr(r*�
create_future�append�remover
�CancelledError�_wake_up_first)r�futrrrr�s
zLock.acquirecCs"|jrd|_|j�ntd��dS)aGRelease a lock.

        When the lock is locked, reset it to unlocked, and return.
        If any other coroutines are blocked waiting for the lock to become
        unlocked, allow exactly one of them to proceed.

        When invoked on an unlocked lock, a RuntimeError is raised.

        There is no return value.
        FzLock is not acquired.N)r)r?r)rrrrr�s
zLock.releasecCs>ytt|j��}Wntk
r&dSX|j�s:|jd�dS)z*Wake up the first waiter if it isn't done.NT)�next�iterr(�
StopIteration�done�
set_result)rr@rrrr?�szLock._wake_up_first)rrrrrr0r,rrrr?�
__classcell__rr)r5rrYs4csReZdZdZdd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Ze	dd��Z
�ZS)ra#Asynchronous equivalent to threading.Event.

    Class implementing event objects. An event manages a flag that can be set
    to true with the set() method and reset to false with the clear() method.
    The wait() method blocks until the flag is true. The flag is initially
    false.
    N)r%cCs.tj�|_d|_|dk	r ||_n
tj�|_dS)NF)r&r'r(�_valuer*r	r+)rr%rrrr�s

zEvent.__init__csDt�j�}|jrdnd}|jr0dj|t|j��}dj|dd�|�S)N�setZunsetz
{},waiters:{}z	<{} [{}]>rr.)r/r0rGr(r1r2)rr3r4)r5rrr0�s

zEvent.__repr__cCs|jS)z5Return True if and only if the internal flag is true.)rG)rrrr�is_set�szEvent.is_setcCs2|js.d|_x |jD]}|j�s|jd�qWdS)z�Set the internal flag to true. All coroutines waiting for it to
        become true are awakened. Coroutine that call wait() once the flag is
        true will not block at all.
        TN)rGr(rDrE)rr@rrrrH�s
z	Event.setcCs
d|_dS)z�Reset the internal flag to false. Subsequently, coroutines calling
        wait() will block until set() is called to set the internal flag
        to true again.FN)rG)rrrr�clearszEvent.clearccsB|jr
dS|jj�}|jj|�z|EdHdS|jj|�XdS)z�Block until the internal flag is true.

        If the internal flag is true on entry, return True
        immediately.  Otherwise, block until another coroutine calls
        set() to set the flag to true, then return True.
        TN)rGr*r;r(r<r=)rr@rrr�wait
s

z
Event.wait)rrrrrr0rIrHrJrrKrFrr)r5rr�scsZeZdZdZddd�dd�Z�fdd�Zedd	��Zed
d��Zdd
d�Z	dd�Z
�ZS)raAsynchronous equivalent to threading.Condition.

    This class implements condition variable objects. A condition variable
    allows one or more coroutines to wait until they are notified by another
    coroutine.

    A new Lock object is created and used as the underlying lock.
    N)r%cCsp|dk	r||_n
tj�|_|dkr0t|jd�}n|j|jk	rDtd��||_|j|_|j|_|j|_t	j
�|_dS)N)r%z"loop argument must agree with lock)r*r	r+r�
ValueErrorr
r,rrr&r'r()rrr%rrrr+s
zCondition.__init__csFt�j�}|j�rdnd}|jr2dj|t|j��}dj|dd�|�S)Nr,r-z
{},waiters:{}z	<{} [{}]>rr.)r/r0r,r(r1r2)rr3r4)r5rrr0>s

zCondition.__repr__ccs�|j�std��|j�z8|jj�}|jj|�z|EdHdS|jj|�XWdd}x4y|j�EdHPWqXt	j
k
r�d}YqXXqXW|r�t	j
�XdS)a�Wait until notified.

        If the calling coroutine has not acquired the lock when this
        method is called, a RuntimeError is raised.

        This method releases the underlying lock, and then blocks
        until it is awakened by a notify() or notify_all() call for
        the same condition variable in another coroutine.  Once
        awakened, it re-acquires the lock and returns True.
        zcannot wait on un-acquired lockNTF)r,rrr*r;r(r<r=rr
r>)rr@r6rrrrKEs&

zCondition.waitccs(|�}x|s"|j�EdH|�}qW|S)z�Wait until a predicate becomes true.

        The predicate should be a callable which result will be
        interpreted as a boolean value.  The final predicate value is
        the return value.
        N)rK)rZ	predicate�resultrrr�wait_forks

zCondition.wait_forrcCsL|j�std��d}x2|jD](}||kr*P|j�s|d7}|jd�qWdS)aBy default, wake up one coroutine waiting on this condition, if any.
        If the calling coroutine has not acquired the lock when this method
        is called, a RuntimeError is raised.

        This method wakes up at most n of the coroutines waiting for the
        condition variable; it is a no-op if no coroutines are waiting.

        Note: an awakened coroutine does not actually return from its
        wait() call until it can reacquire the lock. Since notify() does
        not release the lock, its caller should.
        z!cannot notify on un-acquired lockrrFN)r,rr(rDrE)r�n�idxr@rrr�notifyyszCondition.notifycCs|jt|j��dS)aWake up all threads waiting on this condition. This method acts
        like notify(), but wakes up all waiting threads instead of one. If the
        calling thread has not acquired the lock when this method is called,
        a RuntimeError is raised.
        N)rQr2r()rrrr�
notify_all�szCondition.notify_all)N)r)rrrrrr0rrKrNrQrRrFrr)r5rr!s&
csTeZdZdZddd�dd�Z�fdd�Zd	d
�Zdd�Zed
d��Z	dd�Z
�ZS)raA Semaphore implementation.

    A semaphore manages an internal counter which is decremented by each
    acquire() call and incremented by each release() call. The counter
    can never go below zero; when acquire() finds that it is zero, it blocks,
    waiting until some other thread calls release().

    Semaphores also support the context management protocol.

    The optional argument gives the initial value for the internal
    counter; it defaults to 1. If the value given is less than 0,
    ValueError is raised.
    rN)r%cCs>|dkrtd��||_tj�|_|dk	r0||_n
tj�|_dS)Nrz$Semaphore initial value must be >= 0)rLrGr&r'r(r*r	r+)r�valuer%rrrr�s
zSemaphore.__init__csNt�j�}|j�rdn
dj|j�}|jr:dj|t|j��}dj|dd�|�S)Nr,zunlocked,value:{}z
{},waiters:{}z	<{} [{}]>rr.)r/r0r,r1rGr(r2)rr3r4)r5rrr0�s
zSemaphore.__repr__cCs0x*|jr*|jj�}|j�s|jd�dSqWdS)N)r(�popleftrDrE)rZwaiterrrr�
_wake_up_next�s


zSemaphore._wake_up_nextcCs
|jdkS)z:Returns True if semaphore can not be acquired immediately.r)rG)rrrrr,�szSemaphore.lockedc	cszxf|jdkrf|jj�}|jj|�y|EdHWq|j�|jdkr\|j�r\|j��YqXqW|jd8_dS)a5Acquire a semaphore.

        If the internal counter is larger than zero on entry,
        decrement it by one and return True immediately.  If it is
        zero on entry, block, waiting until some other coroutine has
        called release() to make it larger than 0, and then return
        True.
        rNrT)rGr*r;r(r<Zcancelr6rU)rr@rrrr�s

zSemaphore.acquirecCs|jd7_|j�dS)z�Release a semaphore, incrementing the internal counter by one.
        When it was zero on entry and another coroutine is waiting for it to
        become larger than zero again, wake up that coroutine.
        rN)rGrU)rrrrr�szSemaphore.release)r)rrrrrr0rUr,rrrrFrr)r5rr�s

cs4eZdZdZd	dd��fdd�Z�fdd�Z�ZS)
rz�A bounded semaphore implementation.

    This raises ValueError in release() if it would increase the value
    above the initial value.
    rN)r%cs||_t�j||d�dS)N)r%)�_bound_valuer/r)rrSr%)r5rrr�szBoundedSemaphore.__init__cs"|j|jkrtd��t�j�dS)Nz(BoundedSemaphore released too many times)rGrVrLr/r)r)r5rrr�szBoundedSemaphore.release)r)rrrrrrrFrr)r5rr�s)r�__all__r&�rr	r
Z
coroutinesrrrrrrrrrrrr�<module>s.ByMPK[�x�mDmD+__pycache__/test_utils.cpython-36.opt-1.pycnu�[���3


 \�:�
@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddl
mZddlmZddlmZmZyddlZWnek
r�dZYnXddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddl m!Z!ddl"m#Z#e	j$dk�rHddl%m&Z&nddlm&Z&dd�Z'e'd�Z(e'd�Z)dd�Z*dd�Z+dRdd�Z,dd�Z-Gdd �d e�Z.Gd!d"�d"e�Z/Gd#d$�d$�Z0Gd%d&�d&e0e/�Z1d'd(�d)d*�Z2e3ed+��rZGd,d-�d-ej4e�Z5Gd.d/�d/e5e�Z6Gd0d1�d1e6�Z7Gd2d3�d3e0e7�Z8d4d5�Z9ej:d6d7��Z;ej:d'd(�d8d9��Z<ej:d:dd'd;�d<d=��Z=d>d?�Z>Gd@dA�dAej?�Z@GdBdC�dCejA�ZBdDdE�ZCGdFdG�dGeD�ZEdHdI�ZFGdJdK�dKe
jG�ZGej:dLdM��ZHejIejJejKfdNdO�ZLdPdQ�ZMdS)SzUtilities shared by tests.�N)�mock)�
HTTPServer)�WSGIRequestHandler�
WSGIServer�)�base_events)�compat)�events)�futures)�	selectors)�tasks)�	coroutine)�logger)�supportZwin32)�
socketpaircCs`ttd�r*tjjtj|�}tjj|�r*|Stjjtjjtj�d|�}tjj|�rT|St	|��dS)N�
TEST_HOME_DIR�test)
�hasattrr�os�path�joinr�isfile�dirname�__file__�FileNotFoundError)�filename�fullname�r�*/usr/lib64/python3.6/asyncio/test_utils.py�	data_file-s
rzssl_cert.pemzssl_key.pemcCstdkrdStjtj�SdS)N)�ssl�
SSLContextZPROTOCOL_SSLv23rrrr�dummy_ssl_context<sr"c
Cs@tdd��}|�}|j|�}d|_z|j|�Wd|j�XdS)NcSsdS)Nrrrrr�onceDszrun_briefly.<locals>.onceF)r
Zcreate_taskZ_log_destroy_pending�run_until_complete�close)�loopr#�gen�trrr�run_brieflyCs
r)�cCsTtj�|}xB|�sN|dk	r8|tj�}|dkr8tj��|jtjd|d��qWdS)Nrg����MbP?)r&)�timer
�TimeoutErrorr$rZsleep)r&Zpred�timeoutZdeadlinerrr�	run_untilRsr.cCs|j|j�|j�dS)z�Legacy API to run once through the event loop.

    This is the recommended pattern for test code.  It will poll the
    selector once and run all callbacks scheduled in response to I/O
    events.
    N)Z	call_soon�stopZrun_forever)r&rrr�run_once\sr0c@seZdZdd�Zdd�ZdS)�SilentWSGIRequestHandlercCstj�S)N)�io�StringIO)�selfrrr�
get_stderrisz#SilentWSGIRequestHandler.get_stderrcGsdS)Nr)r4�format�argsrrr�log_messagelsz$SilentWSGIRequestHandler.log_messageN)�__name__�
__module__�__qualname__r5r8rrrrr1gsr1cs(eZdZdZ�fdd�Zdd�Z�ZS)�SilentWSGIServer�cs"t�j�\}}|j|j�||fS)N)�super�get_request�
settimeout�request_timeout)r4�request�client_addr)�	__class__rrr?tszSilentWSGIServer.get_requestcCsdS)Nr)r4rB�client_addressrrr�handle_erroryszSilentWSGIServer.handle_error)r9r:r;rAr?rF�
__classcell__rr)rDrr<psr<c@seZdZdd�ZdS)�SSLWSGIServerMixincCs^t}t}tj�}|j||�|j|dd�}y|j|||�|j�Wntk
rXYnXdS)NT)Zserver_side)	�ONLYKEY�ONLYCERTr r!Zload_cert_chainZwrap_socketZRequestHandlerClassr%�OSError)r4rBrEZkeyfileZcertfile�contextZssockrrr�finish_requestsz!SSLWSGIServerMixin.finish_requestN)r9r:r;rMrrrrrH}srHc@seZdZdS)�
SSLWSGIServerN)r9r:r;rrrrrN�srNF)�use_sslc
#svdd�}|r|n|}||t���j|��j�_tj�fdd�d�}|j�z
�VWd�j��j�|j	�XdS)NcSsd}dg}|||�dgS)Nz200 OK�Content-type�
text/plainsTest message)rPrQr)�environZstart_responseZstatusZheadersrrr�app�s
z_run_test_server.<locals>.appcs�jdd�S)Ng�������?)Z
poll_interval)Z
serve_foreverr)�httpdrr�<lambda>�sz"_run_test_server.<locals>.<lambda>)�target)
r1Zset_appZserver_address�address�	threadingZThread�start�shutdownZserver_closer)rWrO�
server_cls�server_ssl_clsrSZserver_classZ
server_threadr)rTr�_run_test_server�s


r]ZAF_UNIXc@seZdZdd�ZdS)�UnixHTTPServercCstjj|�d|_d|_dS)Nz	127.0.0.1�P)�socketserver�UnixStreamServer�server_bindZserver_nameZserver_port)r4rrrrb�szUnixHTTPServer.server_bindN)r9r:r;rbrrrrr^�sr^cs(eZdZdZdd�Z�fdd�Z�ZS)�UnixWSGIServerr=cCstj|�|j�dS)N)r^rbZ
setup_environ)r4rrrrb�s
zUnixWSGIServer.server_bindcs"t�j�\}}|j|j�|dfS)N�	127.0.0.1�)rdre)r>r?r@rA)r4rBrC)rDrrr?�szUnixWSGIServer.get_request)r9r:r;rArbr?rGrr)rDrrc�srcc@seZdZdd�ZdS)�SilentUnixWSGIServercCsdS)Nr)r4rBrErrrrF�sz!SilentUnixWSGIServer.handle_errorN)r9r:r;rFrrrrrf�srfc@seZdZdS)�UnixSSLWSGIServerN)r9r:r;rrrrrg�srgc	Cstj��}|jSQRXdS)N)�tempfileZNamedTemporaryFile�name)�filerrr�gen_unix_socket_path�s
rkccs<t�}z
|VWdytj|�Wntk
r4YnXXdS)N)rkr�unlinkrK)rrrr�unix_socket_path�s
rmc
cs,t��}t||ttd�EdHWdQRXdS)N)rWrOr[r\)rmr]rfrg)rOrrrr�run_test_unix_server�srnz	127.0.0.1)�host�portrOccst||f|ttd�EdHdS)N)rWrOr[r\)r]r<rN)rorprOrrr�run_test_server�s
rqcCsPi}x4t|�D](}|jd�r(|jd�r(qtdd�||<qWtd|f|j|��S)N�__)�return_valueZTestProtocol)�dir�
startswith�endswith�MockCallback�type�	__bases__)�baseZdctrirrr�make_test_protocol�sr{c@s6eZdZdd�Zddd�Zdd�Zdd	�Zd
d�ZdS)
�TestSelectorcCs
i|_dS)N)�keys)r4rrr�__init__szTestSelector.__init__NcCstj|d||�}||j|<|S)Nr)rZSelectorKeyr})r4�fileobjr	�data�keyrrr�registers
zTestSelector.registercCs|jj|�S)N)r}�pop)r4rrrr�
unregisterszTestSelector.unregistercCsgS)Nr)r4r-rrr�selectszTestSelector.selectcCs|jS)N)r})r4rrr�get_mapszTestSelector.get_map)N)r9r:r;r~r�r�r�r�rrrrr|s

r|cs�eZdZdZd-�fdd�	Zdd�Zdd�Z�fd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Z�fd%d&�Z�fd'd(�Zd)d*�Zd+d,�Z�ZS).�TestLoopa�Loop for unittests.

    It manages self time directly.
    If something scheduled to be executed later then
    on next loop iteration after all ready handlers done
    generator passed to __init__ is calling.

    Generator should be like this:

        def gen():
            ...
            when = yield ...
            ... = yield time_advance

    Value returned by yield is absolute time of next scheduled handler.
    Value passed to yield is time advance to move loop's time forward.
    Ncsvt�j�|dkr"dd�}d|_nd|_|�|_t|j�d|_d|_g|_t�|_	i|_
i|_|j�t
j�|_dS)Ncss
dVdS)Nrrrrrr',szTestLoop.__init__.<locals>.genFTrg��&�.>)r>r~�_check_on_close�_gen�next�_timeZ_clock_resolution�_timersr|Z	_selector�readers�writers�reset_counters�weakref�WeakValueDictionary�_transports)r4r')rDrrr~(s

zTestLoop.__init__cCs|jS)N)r�)r4rrrr+?sz
TestLoop.timecCs|r|j|7_dS)zMove test time forward.N)r�)r4�advancerrr�advance_timeBszTestLoop.advance_timecsBt�j�|jr>y|jjd�Wntk
r4Yn
Xtd��dS)NrzTime generator is not finished)r>r%r�r��send�
StopIteration�AssertionError)r4)rDrrr%Gs
zTestLoop.closecGstj|||�|j|<dS)N)r	�Handler�)r4�fd�callbackr7rrr�_add_readerQszTestLoop._add_readercCs0|j|d7<||jkr(|j|=dSdSdS)NrTF)�remove_reader_countr�)r4r�rrr�_remove_readerTs

zTestLoop._remove_readercGsh||jkrtd|�d���|j|}|j|krDtd|j�d|����|j|krdtd|j�d|����dS)Nzfd z is not registeredzunexpected callback: z != zunexpected callback args: )r�r�Z	_callbackZ_args)r4r�r�r7�handlerrr�
assert_reader\s



zTestLoop.assert_readercCs||jkrtd|�d���dS)Nzfd z is registered)r�r�)r4r�rrr�assert_no_readergs
zTestLoop.assert_no_readercGstj|||�|j|<dS)N)r	r�r�)r4r�r�r7rrr�_add_writerkszTestLoop._add_writercCs0|j|d7<||jkr(|j|=dSdSdS)NrTF)�remove_writer_countr�)r4r�rrr�_remove_writerns

zTestLoop._remove_writercGs|j|}dS)N)r�)r4r�r�r7r�rrr�
assert_writervs
zTestLoop.assert_writercCs8y|j|}Wntk
r"YnXtdj||���dS)Nz.File descriptor {!r} is used by transport {!r})r��KeyError�RuntimeErrorr6)r4r�Z	transportrrr�_ensure_fd_no_transport~sz TestLoop._ensure_fd_no_transportcGs|j|�|j||f|��S)zAdd a reader callback.)r�r�)r4r�r�r7rrr�
add_reader�s
zTestLoop.add_readercCs|j|�|j|�S)zRemove a reader callback.)r�r�)r4r�rrr�
remove_reader�s
zTestLoop.remove_readercGs|j|�|j||f|��S)zAdd a writer callback..)r�r�)r4r�r�r7rrr�
add_writer�s
zTestLoop.add_writercCs|j|�|j|�S)zRemove a writer callback.)r�r�)r4r�rrr�
remove_writer�s
zTestLoop.remove_writercCstjt�|_tjt�|_dS)N)�collections�defaultdict�intr�r�)r4rrrr��szTestLoop.reset_counterscs:t�j�x$|jD]}|jj|�}|j|�qWg|_dS)N)r>�	_run_oncer�r�r�r�)r4�whenr�)rDrrr��s

zTestLoop._run_oncecs |jj|�t�j||f|��S)N)r��appendr>�call_at)r4r�r�r7)rDrrr��szTestLoop.call_atcCsdS)Nr)r4Z
event_listrrr�_process_events�szTestLoop._process_eventscCsdS)Nr)r4rrr�_write_to_self�szTestLoop._write_to_self)N)r9r:r;�__doc__r~r+r�r%r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rGrr)rDrr�s,

r�cKstjfddgi|��S)N�spec�__call__)rZMock)�kwargsrrrrw�srwc@seZdZdZdd�ZdS)�MockPatternz�A regex based str with a fuzzy __eq__.

    Use this helper with 'mock.assert_called_with', or anywhere
    where a regex comparison between strings is needed.

    For instance:
       mock_call.assert_called_with(MockPattern('spam.*ham'))
    cCsttjt|�|tj��S)N)�bool�re�search�str�S)r4�otherrrr�__eq__�szMockPattern.__eq__N)r9r:r;r�r�rrrrr��sr�cCs$tj|�}|dkr td|f��|S)Nzunable to get the source of %r)r	Z_get_function_source�
ValueError)�func�sourcerrr�get_function_source�s
r�c@sVeZdZedd��Zdd�dd�Zddd	�Zd
d�Zdd
�Zdd�Z	e
jsRdd�ZdS)�TestCasecCs&|j}|dk	r|jdd�|j�dS)NT)�wait)Z_default_executorrZr%)r&Zexecutorrrr�
close_loop�szTestCase.close_loopT)�cleanupcCs tjd�|r|j|j|�dS)N)r	�set_event_loopZ
addCleanupr�)r4r&r�rrrr��s
zTestCase.set_event_loopNcCst|�}|j|�|S)N)r�r�)r4r'r&rrr�
new_test_loop�s
zTestCase.new_test_loopcCs|jt_dS)N)�_get_running_loopr	)r4rrr�unpatch_get_running_loop�sz!TestCase.unpatch_get_running_loopcCs tj|_dd�t_tj�|_dS)NcSsdS)NrrrrrrU�sz TestCase.setUp.<locals>.<lambda>)r	r�rZthreading_setup�_thread_cleanup)r4rrr�setUp�s
zTestCase.setUpcCsB|j�tjd�|jtj�d�|j�tj|j	�tj
�dS)N)NNN)r�r	r�ZassertEqual�sys�exc_infoZ
doCleanupsrZthreading_cleanupr�Z
reap_children)r4rrr�tearDown�s
zTestCase.tearDowncOsGdd�d�}|�S)Nc@seZdZdd�Zdd�ZdS)z!TestCase.subTest.<locals>.EmptyCMcSsdS)Nr)r4rrr�	__enter__�sz+TestCase.subTest.<locals>.EmptyCM.__enter__cWsdS)Nr)r4�excrrr�__exit__�sz*TestCase.subTest.<locals>.EmptyCM.__exit__N)r9r:r;r�r�rrrr�EmptyCM�sr�r)r4r7r�r�rrr�subTest�szTestCase.subTest)N)
r9r:r;�staticmethodr�r�r�r�r�r�rZPY34r�rrrrr��s

r�ccs2tj}ztjtjd�dVWdtj|�XdS)zrContext manager to disable asyncio logger.

    For example, it can be used to ignore warnings in debug mode.
    rN)r�levelZsetLevel�loggingZCRITICAL)Z	old_levelrrr�disable_logger�s

r�cCs*tjtj�}||_||_||_d|j_|S)z'Create a mock of a non-blocking socket.g)rZ	MagicMock�socket�protorx�familyZ
gettimeoutrs)r�rxr�Zsockrrr�mock_nonblocking_socketsr�cCstjddd�S)Nz'asyncio.sslproto._is_sslproto_availableF)rs)rZpatchrrrr�force_legacy_ssl_supportsr�)r*)Nr�r��
contextlibr2r�rr�r�r`r�rhrXr+Zunittestr�rZhttp.serverrZwsgiref.simple_serverrrr �ImportErrorrerrr	r
rrZ
coroutinesr
�logrrr�platformZ
windows_utilsrrrJrIr"r)r.r0r1r<rHrNr]rrar^rcrfrgrk�contextmanagerrmrnrqr{ZBaseSelectorr|Z
BaseEventLoopr�rwr�r�r�r�r�ZIPPROTO_TCPZSOCK_STREAMZAF_INETr�r�rrrr�<module>s�


	


4
PK[�E(�gg'__pycache__/compat.cpython-36.opt-2.pycnu�[���3


 \�@s2ddlZejdkZejd	kZejd
kZdd�ZdS)�N����cCstsdd�|D�}dj|�S)Ncss$|]}t|t�rt|�n|VqdS)N)�
isinstance�
memoryview�bytes)�.0�data�r�&/usr/lib64/python3.6/asyncio/compat.py�	<genexpr>sz%flatten_list_bytes.<locals>.<genexpr>�)�PY34�join)Zlist_of_datarrr�flatten_list_bytes
sr)rr)rr)rrr)�sys�version_inforZPY35ZPY352rrrrr�<module>s


PK[#���]w]w&__pycache__/unix_events.cpython-36.pycnu�[���3


 \���
@s dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddl
mZdd
l
mZddlmZddlmZdddddgZejdkr�ed��dd�Zy
ejZWnek
�r,dd�ZYnXGdd�dej�Z e!ed��rVdd�Z"nddl#Z#d d�Z"Gd!d"�d"ej$�Z%Gd#d$�d$ej&ej'�Z(e!ed%��r�ej)Z*nddl#Z#d&d'�Z*Gd(d)�d)ej+�Z,Gd*d�d�Z-Gd+d,�d,e-�Z.Gd-d�de.�Z/Gd.d�de.�Z0Gd/d0�d0ej1�Z2e Z3e2Z4dS)1z2Selector event loop for Unix with signal handling.�N�)�base_events)�base_subprocess)�compat)�	constants)�
coroutines)�events)�futures)�selector_events)�	selectors)�
transports)�	coroutine)�logger�SelectorEventLoop�AbstractChildWatcher�SafeChildWatcher�FastChildWatcher�DefaultEventLoopPolicyZwin32z+Signals are not really supported on WindowscCsdS)zDummy signal handler.N�)�signum�framerr�+/usr/lib64/python3.6/asyncio/unix_events.py�_sighandler_noop%srcCs|S)Nr)�pathrrr�<lambda>.srcs�eZdZdZd"�fdd�	Zdd�Z�fdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zd#dd�Zd$dd�Z
ed%dd��Zdd�Zedddd�dd��Zed&dddd�d d!��Z�ZS)'�_UnixSelectorEventLoopzdUnix event loop.

    Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
    Ncst�j|�i|_dS)N)�super�__init__�_signal_handlers)�self�selector)�	__class__rrr7sz_UnixSelectorEventLoop.__init__cCstj�S)N)�socketZ
socketpair)rrrr�_socketpair;sz"_UnixSelectorEventLoop._socketpaircs^t�j�tj�s2xFt|j�D]}|j|�qWn(|jrZtjd|�d�t	|d�|jj
�dS)NzClosing the loop z@ on interpreter shutdown stage, skipping signal handlers removal)�source)r�close�sys�
is_finalizing�listr�remove_signal_handler�warnings�warn�ResourceWarning�clear)r�sig)r!rrr%>s
z_UnixSelectorEventLoop.closecCs"x|D]}|sq|j|�qWdS)N)�_handle_signal)r�datarrrr�_process_self_dataLs
z)_UnixSelectorEventLoop._process_self_datac+GsHtj|�stj|�rtd��|j|�|j�ytj|jj	��Wn2t
tfk
rt}ztt
|���WYdd}~XnXtj|||�}||j|<ytj|t�tj|d�Wn�tk
�rB}zz|j|=|j�sytjd�Wn4t
tfk
�r}ztjd|�WYdd}~XnX|jtjk�r0tdj|���n�WYdd}~XnXdS)z�Add a handler for a signal.  UNIX only.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        z3coroutines cannot be used with add_signal_handler()NFrzset_wakeup_fd(-1) failed: %szsig {} cannot be caught���)rZiscoroutineZiscoroutinefunction�	TypeError�
_check_signalZ
_check_closed�signal�
set_wakeup_fdZ_csock�fileno�
ValueError�OSError�RuntimeError�strrZHandlerr�siginterruptr�info�errno�EINVAL�format)rr.�callback�args�exc�handleZnexcrrr�add_signal_handlerSs0



z)_UnixSelectorEventLoop.add_signal_handlercCs8|jj|�}|dkrdS|jr*|j|�n
|j|�dS)z2Internal helper that is the actual signal handler.N)r�getZ
_cancelledr)Z_add_callback_signalsafe)rr.rDrrrr/�sz%_UnixSelectorEventLoop._handle_signalc&Cs�|j|�y|j|=Wntk
r*dSX|tjkr>tj}ntj}ytj||�Wn@tk
r�}z$|jtj	kr�t
dj|���n�WYdd}~XnX|js�ytjd�Wn2t
tfk
r�}ztjd|�WYdd}~XnXdS)zwRemove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        Fzsig {} cannot be caughtNrzset_wakeup_fd(-1) failed: %sTr2)r4r�KeyErrorr5�SIGINT�default_int_handler�SIG_DFLr9r>r?r:r@r6r8rr=)rr.ZhandlerrCrrrr)�s(

z,_UnixSelectorEventLoop.remove_signal_handlercCsHt|t�stdj|���d|ko,tjknsDtdj|tj���dS)z�Internal helper to validate a signal.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        zsig must be an int, not {!r}rzsig {} out of range(1, {})N)�
isinstance�intr3r@r5�NSIGr8)rr.rrrr4�s

z$_UnixSelectorEventLoop._check_signalcCst|||||�S)N)�_UnixReadPipeTransport)r�pipe�protocol�waiter�extrarrr�_make_read_pipe_transport�sz0_UnixSelectorEventLoop._make_read_pipe_transportcCst|||||�S)N)�_UnixWritePipeTransport)rrOrPrQrRrrr�_make_write_pipe_transport�sz1_UnixSelectorEventLoop._make_write_pipe_transportc	ks�tj���}
|j�}t||||||||f||d�|	��}|
j|j�|j|�y|EdHWn&tk
r~}
z
|
}WYdd}
~
XnXd}|dk	r�|j�|j	�EdH|�WdQRX|S)N)rQrR)
r�get_child_watcherZ
create_future�_UnixSubprocessTransport�add_child_handlerZget_pid�_child_watcher_callback�	Exceptionr%Z_wait)rrPrB�shell�stdin�stdout�stderr�bufsizerR�kwargs�watcherrQ�transprC�errrrr�_make_subprocess_transport�s$




z1_UnixSelectorEventLoop._make_subprocess_transportcCs|j|j|�dS)N)Zcall_soon_threadsafeZ_process_exited)r�pid�
returncoderbrrrrY�sz._UnixSelectorEventLoop._child_watcher_callback)�ssl�sock�server_hostnameccs|dkst|t�st�|r,|dkr<td��n|dk	r<td��|dk	r�|dk	rTtd��tjtjtjd�}y |jd�|j||�EdHWq�|j	��Yq�XnB|dkr�td��|j
tjks�tj|j
�r�tdj|���|jd�|j||||�EdH\}}||fS)Nz/you have to pass server_hostname when using sslz+server_hostname is only meaningful with sslz3path and sock can not be specified at the same timerFzno path and sock were specifiedz2A UNIX Domain Stream Socket was expected, got {!r})rKr;�AssertionErrorr8r"�AF_UNIX�SOCK_STREAM�setblockingZsock_connectr%�familyr�_is_stream_socket�typer@Z_create_connection_transport)r�protocol_factoryrrgrhri�	transportrPrrr�create_unix_connection�s:


z-_UnixSelectorEventLoop.create_unix_connection�d)rh�backlogrgc
!Cs�t|t�rtd��|dk	�r0|dk	r,td��t|�}tjtjtj�}|dd
kr�y tj	t
j|�j�rnt
j|�WnBt
k
r�Yn0tk
r�}ztjd||�WYdd}~XnXy|j|�Wnjtk
�r}z8|j�|jtjk�rdj|�}ttj|�d�n�WYdd}~Xn|j��YnXn>|dk�rBtd��|jtjk�s`tj|j��rntdj|���tj||g�}	|j|�|jd	�|j||||	�|	S)Nz*ssl argument must be an SSLContext or Nonez3path and sock can not be specified at the same timer�z2Unable to check or remove stale UNIX socket %r: %rzAddress {!r} is already in usez-path was not specified, and no sock specifiedz2A UNIX Domain Stream Socket was expected, got {!r}F)rrv)rK�boolr3r8�_fspathr"rkrl�stat�S_ISSOCK�os�st_mode�remove�FileNotFoundErrorr9r�errorZbindr%r>Z
EADDRINUSEr@rnrrorpZServerZlistenrmZ_start_serving)
rrqrrhrurgrcrC�msgZserverrrr�create_unix_serversP

 




z)_UnixSelectorEventLoop.create_unix_server)N)NN)NN)N)N)�__name__�
__module__�__qualname__�__doc__rr#r%r1rEr/r)r4rSrUr
rdrYrsr��
__classcell__rr)r!rr1s,-
 


%r�set_blockingcCstj|d�dS)NF)r{r�)�fdrrr�_set_nonblockingBsr�cCs,tj|tj�}|tjB}tj|tj|�dS)N)�fcntlZF_GETFLr{�
O_NONBLOCKZF_SETFL)r��flagsrrrr�Gs
cs�eZdZdZd �fdd�	Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Ze
jrhdd�Zd!dd�Zdd�Zdd�Z�ZS)"rN�iNcs�t�j|�||jd<||_||_|j�|_||_d|_t	j
|j�j}tj
|�pbtj|�pbtj|�s~d|_d|_d|_td��t|j�|jj|jj|�|jj|jj|j|j�|dk	r�|jjtj|d�dS)NrOFz)Pipe transport is for pipes/sockets only.)rr�_extra�_loop�_piper7�_fileno�	_protocol�_closingr{�fstatr|ry�S_ISFIFOrz�S_ISCHRr8r��	call_soon�connection_made�_add_reader�_read_readyr	�_set_result_unless_cancelled)r�looprOrPrQrR�mode)r!rrrQs,






z_UnixReadPipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�t|jdd�}|jdk	r�|dk	r�tj	||jt
j�}|r�|jd�q�|jd�n |jdk	r�|jd�n
|jd�dd	j|�S)
N�closed�closingzfd=%s�	_selector�polling�idle�openz<%s>� )
r!r�r��appendr�r��getattrr�r
�_test_selector_eventrZ
EVENT_READ�join)rr=r r�rrr�__repr__ns$




z_UnixReadPipeTransport.__repr__cCs�ytj|j|j�}WnDttfk
r,Yn�tk
rX}z|j|d�WYdd}~Xn^X|rl|jj	|�nJ|j
j�r�tj
d|�d|_|j
j|j�|j
j|jj�|j
j|jd�dS)Nz"Fatal read error on pipe transportz%r was closed by peerT)r{�readr��max_size�BlockingIOError�InterruptedErrorr9�_fatal_errorr�Z
data_receivedr��	get_debugrr=r��_remove_readerr�Zeof_received�_call_connection_lost)rr0rCrrrr��s
z"_UnixReadPipeTransport._read_readycCs|jj|j�dS)N)r�r�r�)rrrr�
pause_reading�sz$_UnixReadPipeTransport.pause_readingcCs|jj|j|j�dS)N)r�r�r�r�)rrrr�resume_reading�sz%_UnixReadPipeTransport.resume_readingcCs
||_dS)N)r�)rrPrrr�set_protocol�sz#_UnixReadPipeTransport.set_protocolcCs|jS)N)r�)rrrr�get_protocol�sz#_UnixReadPipeTransport.get_protocolcCs|jS)N)r�)rrrr�
is_closing�sz!_UnixReadPipeTransport.is_closingcCs|js|jd�dS)N)r��_close)rrrrr%�sz_UnixReadPipeTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)r$)r�r*r+r,r%)rrrr�__del__�s
z_UnixReadPipeTransport.__del__�Fatal error on pipe transportcCsZt|t�r4|jtjkr4|jj�rLtjd||dd�n|jj||||j	d��|j
|�dS)Nz%r: %sT)�exc_info)�message�	exceptionrrrP)rKr9r>ZEIOr�r�r�debug�call_exception_handlerr�r�)rrCr�rrrr��s
z#_UnixReadPipeTransport._fatal_errorcCs(d|_|jj|j�|jj|j|�dS)NT)r�r�r�r�r�r�)rrCrrrr��sz_UnixReadPipeTransport._closecCs4z|jj|�Wd|jj�d|_d|_d|_XdS)N)r��connection_lostr�r%r�)rrCrrrr��s
z,_UnixReadPipeTransport._call_connection_losti)NN)r�)r�r�r�r�rr�r�r�r�r�r�r�r%r�PY34r�r�r�r�r�rr)r!rrNMs
rNcs�eZdZd%�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zejr|dd�Zdd�Zd&dd �Zd'd!d"�Zd#d$�Z�ZS)(rTNc
s�t�j||�||jd<||_|j�|_||_t�|_d|_	d|_
tj|j�j
}tj|�}tj|�}tj|�}	|px|px|	s�d|_d|_d|_td��t|j�|jj|jj|�|	s�|r�tjjd�r�|jj|jj|j|j�|dk	r�|jjtj|d�dS)NrOrFz?Pipe transport is only for pipes, sockets and character devices�aix)rrr�r�r7r�r��	bytearray�_buffer�
_conn_lostr�r{r�r|ryr�r�rzr8r�r�r�r�r&�platform�
startswithr�r�r	r�)
rr�rOrPrQrRr�Zis_charZis_fifoZ	is_socket)r!rrr�s2






z _UnixWritePipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�t|jdd�}|jdk	r�|dk	r�tj	||jt
j�}|r�|jd�n
|jd�|j�}|jd|�n |jdk	r�|jd�n
|jd�d	d
j
|�S)Nr�r�zfd=%sr�r�r�z
bufsize=%sr�z<%s>r�)r!r�r�r�r�r�r�r�r
r�rZEVENT_WRITE�get_write_buffer_sizer�)rr=r r�r_rrrr��s(





z _UnixWritePipeTransport.__repr__cCs
t|j�S)N)�lenr�)rrrrr�sz-_UnixWritePipeTransport.get_write_buffer_sizecCs6|jj�rtjd|�|jr*|jt��n|j�dS)Nz%r was closed by peer)r�r�rr=r�r��BrokenPipeError)rrrrr�s

z#_UnixWritePipeTransport._read_readycCs0t|tttf�stt|���t|t�r.t|�}|s6dS|jsB|jrj|jtj	krXt
jd�|jd7_dS|j�syt
j|j|�}WnTttfk
r�d}Yn:tk
r�}z|jd7_|j|d�dSd}~XnX|t|�kr�dS|dk�rt|�|d�}|jj|j|j�|j|7_|j�dS)Nz=pipe closed by peer or os.write(pipe, data) raised exception.rrz#Fatal write error on pipe transport)rK�bytesr��
memoryviewrj�reprr�r�rZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr�warningr�r{�writer�r�r�rZr�r�r�Z_add_writer�_write_readyZ_maybe_pause_protocol)rr0�nrCrrrr�s4


z_UnixWritePipeTransport.writecCs�|jstd��ytj|j|j�}Wnjttfk
r:Yn�tk
r�}z8|jj�|j	d7_	|j
j|j�|j|d�WYdd}~XnfX|t
|j�kr�|jj�|j
j|j�|j�|jr�|j
j|j�|jd�dS|dkr�|jd|�=dS)NzData should not be emptyrz#Fatal write error on pipe transportr)r�rjr{r�r�r�r�rZr-r�r��_remove_writerr�r�Z_maybe_resume_protocolr�r�r�)rr�rCrrrr�>s(


z$_UnixWritePipeTransport._write_readycCsdS)NTr)rrrr�
can_write_eofXsz%_UnixWritePipeTransport.can_write_eofcCsB|jr
dS|jst�d|_|js>|jj|j�|jj|jd�dS)NT)	r�r�rjr�r�r�r�r�r�)rrrr�	write_eof[s
z!_UnixWritePipeTransport.write_eofcCs
||_dS)N)r�)rrPrrrr�dsz$_UnixWritePipeTransport.set_protocolcCs|jS)N)r�)rrrrr�gsz$_UnixWritePipeTransport.get_protocolcCs|jS)N)r�)rrrrr�jsz"_UnixWritePipeTransport.is_closingcCs|jdk	r|jr|j�dS)N)r�r�r�)rrrrr%msz_UnixWritePipeTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)r$)r�r*r+r,r%)rrrrr�vs
z_UnixWritePipeTransport.__del__cCs|jd�dS)N)r�)rrrr�abort|sz_UnixWritePipeTransport.abort�Fatal error on pipe transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)r�)r�r�rrrP)
rKrZ_FATAL_ERROR_IGNOREr�r�rr�r�r�r�)rrCr�rrrr�s
z$_UnixWritePipeTransport._fatal_errorcCsFd|_|jr|jj|j�|jj�|jj|j�|jj|j|�dS)NT)	r�r�r�r�r�r-r�r�r�)rrCrrrr��s
z_UnixWritePipeTransport._closecCs4z|jj|�Wd|jj�d|_d|_d|_XdS)N)r�r�r�r%r�)rrCrrrr��s
z-_UnixWritePipeTransport._call_connection_lost)NN)r�)N)r�r�r�rr�r�r�r�r�r�r�r�r�r�r%rr�r�r�r�r�r�r�rr)r!rrT�s$%	!	

rT�set_inheritablecCsNttdd�}tj|tj�}|s4tj|tj||B�ntj|tj||@�dS)NZ
FD_CLOEXECr)r�r�ZF_GETFDZF_SETFD)r�ZinheritableZcloexec_flag�oldrrr�_set_inheritable�s
r�c@seZdZdd�ZdS)rWc		Ksvd}|tjkr*|jj�\}}t|j�d�tj|f||||d|d�|��|_|dk	rr|j�t	|j
�d|d�|j_dS)NF)r[r\r]r^Zuniversal_newlinesr_�wb)�	buffering)�
subprocess�PIPEr�r#r�r7�Popen�_procr%r��detachr\)	rrBr[r\r]r^r_r`Zstdin_wrrr�_start�s
z_UnixSubprocessTransport._startN)r�r�r�r�rrrrrW�srWc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)raHAbstract base class for monitoring child processes.

    Objects derived from this class monitor a collection of subprocesses and
    report their termination or interruption by a signal.

    New callbacks are registered with .add_child_handler(). Starting a new
    process must be done within a 'with' block to allow the watcher to suspend
    its activity until the new process if fully registered (this is needed to
    prevent a race condition in some implementations).

    Example:
        with watcher:
            proc = subprocess.Popen("sleep 1")
            watcher.add_child_handler(proc.pid, callback)

    Notes:
        Implementations of this class must be thread-safe.

        Since child watcher objects may catch the SIGCHLD signal and call
        waitpid(-1), there should be only one active object per process.
    cGs
t��dS)aRegister a new child handler.

        Arrange for callback(pid, returncode, *args) to be called when
        process 'pid' terminates. Specifying another callback for the same
        process replaces the previous handler.

        Note: callback() must be thread-safe.
        N)�NotImplementedError)rrerArBrrrrX�s	z&AbstractChildWatcher.add_child_handlercCs
t��dS)z�Removes the handler for process 'pid'.

        The function returns True if the handler was successfully removed,
        False if there was nothing to remove.N)r�)rrerrr�remove_child_handler�sz)AbstractChildWatcher.remove_child_handlercCs
t��dS)z�Attach the watcher to an event loop.

        If the watcher was previously attached to an event loop, then it is
        first detached before attaching to the new loop.

        Note: loop may be None.
        N)r�)rr�rrr�attach_loop�sz AbstractChildWatcher.attach_loopcCs
t��dS)zlClose the watcher.

        This must be called to make sure that any underlying resource is freed.
        N)r�)rrrrr%�szAbstractChildWatcher.closecCs
t��dS)zdEnter the watcher's context and allow starting new processes

        This function must return selfN)r�)rrrr�	__enter__szAbstractChildWatcher.__enter__cCs
t��dS)zExit the watcher's contextN)r�)r�a�b�crrr�__exit__	szAbstractChildWatcher.__exit__N)
r�r�r�r�rXr�r�r%r�r�rrrrr�s
c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�BaseChildWatchercCsd|_i|_dS)N)r��
_callbacks)rrrrrszBaseChildWatcher.__init__cCs|jd�dS)N)r�)rrrrr%szBaseChildWatcher.closecCs
t��dS)N)r�)r�expected_pidrrr�_do_waitpidszBaseChildWatcher._do_waitpidcCs
t��dS)N)r�)rrrr�_do_waitpid_allsz BaseChildWatcher._do_waitpid_allcCs~|dkst|tj�st�|jdk	r<|dkr<|jr<tjdt�|jdk	rT|jj	t
j�||_|dk	rz|jt
j|j
�|j�dS)NzCA loop is being detached from a child watcher with pending handlers)rKrZAbstractEventLooprjr�r�r*r+�RuntimeWarningr)r5�SIGCHLDrE�	_sig_chldr�)rr�rrrr�s
zBaseChildWatcher.attach_loopcCsFy|j�Wn4tk
r@}z|jjd|d��WYdd}~XnXdS)Nz$Unknown exception in SIGCHLD handler)r�r�)r�rZr�r�)rrCrrrr�1szBaseChildWatcher._sig_chldcCs2tj|�rtj|�Stj|�r*tj|�S|SdS)N)r{�WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS)r�statusrrr�_compute_returncode=s



z$BaseChildWatcher._compute_returncodeN)
r�r�r�rr%r�r�r�r�r�rrrrr�sr�csPeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)rad'Safe' child watcher implementation.

    This implementation avoids disrupting other code spawning processes by
    polling explicitly each process in the SIGCHLD handler instead of calling
    os.waitpid(-1).

    This is a safe solution but it has a significant overhead when handling a
    big number of children (O(n) each time SIGCHLD is raised)
    cs|jj�t�j�dS)N)r�r-rr%)r)r!rrr%Vs
zSafeChildWatcher.closecCs|S)Nr)rrrrr�ZszSafeChildWatcher.__enter__cCsdS)Nr)rr�r�r�rrrr�]szSafeChildWatcher.__exit__cGs.|jdkrtd��||f|j|<|j|�dS)NzICannot add child handler, the child watcher does not have a loop attached)r�r:r�r�)rrerArBrrrrX`s

z"SafeChildWatcher.add_child_handlercCs&y|j|=dStk
r dSXdS)NTF)r�rG)rrerrrr�ks
z%SafeChildWatcher.remove_child_handlercCs"xt|j�D]}|j|�qWdS)N)r(r�r�)rrerrrr�rsz SafeChildWatcher._do_waitpid_allcCs�|dkst�ytj|tj�\}}Wn(tk
rJ|}d}tjd|�Yn0X|dkrXdS|j|�}|jj	�rztj
d||�y|jj|�\}}Wn.t
k
r�|jj	�r�tjd|dd�YnX|||f|��dS)Nr�z8Unknown child process pid %d, will report returncode 255z$process %s exited with returncode %sz'Child watcher got an unexpected pid: %rT)r�)rjr{�waitpid�WNOHANG�ChildProcessErrorrr�r�r�r�r�r��poprG)rr�rer�rfrArBrrrr�ws,


zSafeChildWatcher._do_waitpid)r�r�r�r�r%r�r�rXr�r�r�r�rr)r!rrKs	csTeZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)raW'Fast' child watcher implementation.

    This implementation reaps every terminated processes by calling
    os.waitpid(-1) directly, possibly breaking other code spawning processes
    and waiting for their termination.

    There is no noticeable overhead when handling a big number of children
    (O(1) each time a child terminates).
    cs$t�j�tj�|_i|_d|_dS)Nr)rr�	threadingZLock�_lock�_zombies�_forks)r)r!rrr�s

zFastChildWatcher.__init__cs"|jj�|jj�t�j�dS)N)r�r-r�rr%)r)r!rrr%�s

zFastChildWatcher.closec
Cs$|j�|jd7_|SQRXdS)Nr)r�r�)rrrrr��szFastChildWatcher.__enter__c
CsV|j�:|jd8_|js$|jr(dSt|j�}|jj�WdQRXtjd|�dS)Nrz5Caught subprocesses termination from unknown pids: %s)r�r�r�r;r-rr�)rr�r�r�Zcollateral_victimsrrrr��s
zFastChildWatcher.__exit__cGsz|jstd��|jdkr td��|j�:y|jj|�}Wn"tk
rZ||f|j|<dSXWdQRX|||f|��dS)NzMust use the context managerzICannot add child handler, the child watcher does not have a loop attached)	r�rjr�r:r�r�r�rGr�)rrerArBrfrrrrX�s
z"FastChildWatcher.add_child_handlercCs&y|j|=dStk
r dSXdS)NTF)r�rG)rrerrrr��s
z%FastChildWatcher.remove_child_handlercCs�x�ytjdtj�\}}Wntk
r,dSX|dkr:dS|j|�}|j�vy|jj|�\}}WnBtk
r�|j	r�||j
|<|jj�r�t
jd||�wd}YnX|jj�r�t
jd||�WdQRX|dkr�t
jd||�q|||f|��qWdS)Nrrz,unknown process %s exited with returncode %sz$process %s exited with returncode %sz8Caught subprocess termination from unknown pid: %d -> %dr2)r{r�r�r�r�r�r�r�rGr�r�r�r�rr�r�)rrer�rfrArBrrrr��s6





z FastChildWatcher._do_waitpid_all)r�r�r�r�rr%r�r�rXr�r�r�rr)r!rr�s	csHeZdZdZeZ�fdd�Zdd�Z�fdd�Zdd	�Z	d
d�Z
�ZS)�_UnixDefaultEventLoopPolicyz:UNIX event loop policy with a watcher for child processes.cst�j�d|_dS)N)rr�_watcher)r)r!rrrs
z$_UnixDefaultEventLoopPolicy.__init__c
CsHtj�8|jdkr:t�|_ttj�tj�r:|jj|j	j
�WdQRXdS)N)rr�rrrKr��current_thread�_MainThreadr��_localr�)rrrr�
_init_watchers
z)_UnixDefaultEventLoopPolicy._init_watchercs6t�j|�|jdk	r2ttj�tj�r2|jj|�dS)z�Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        N)r�set_event_looprrKr�rrr�)rr�)r!rrrs
z*_UnixDefaultEventLoopPolicy.set_event_loopcCs|jdkr|j�|jS)zzGet the watcher for child processes.

        If not yet set, a SafeChildWatcher object is automatically created.
        N)rr)rrrrrV&s
z-_UnixDefaultEventLoopPolicy.get_child_watchercCs4|dkst|t�st�|jdk	r*|jj�||_dS)z$Set the watcher for child processes.N)rKrrjrr%)rrarrr�set_child_watcher0s

z-_UnixDefaultEventLoopPolicy.set_child_watcher)r�r�r�r�rZ
_loop_factoryrrrrVrr�rr)r!rrs
r)5r�r>r{r5r"ryr�r&r�r*�rrrrrrr	r
rrr
�logr�__all__r��ImportErrorr�fspathrx�AttributeErrorZBaseSelectorEventLoopr�hasattrr�r�Z
ReadTransportrNZ_FlowControlMixinZWriteTransportrTr�r�ZBaseSubprocessTransportrWrr�rrZBaseDefaultEventLoopPolicyrrrrrrr�<module>sn


O
F=On2PK[ U��44)__pycache__/sslproto.cpython-36.opt-2.pycnu�[���3


 \�e�
@s�ddlZddlZyddlZWnek
r4dZYnXddlmZddlmZddlmZddlmZddl	m
Z
dd	�Zd
d�ZdZ
d
ZdZdZGdd�de�ZGdd�dejej�ZGdd�dej�ZdS)�N�)�base_events)�compat)�	protocols)�
transports)�loggercCsj|rtd��ttd�r*tj�}|sfd|_n<tjtj�}|jtjO_|jtj	O_|j
�tj|_|S)Nz(Server side SSL needs a valid SSLContext�create_default_contextF)
�
ValueError�hasattr�sslr�check_hostnameZ
SSLContextZPROTOCOL_SSLv23ZoptionsZOP_NO_SSLv2ZOP_NO_SSLv3Zset_default_verify_pathsZ
CERT_REQUIRED�verify_mode)�server_side�server_hostname�
sslcontext�r�(/usr/lib64/python3.6/asyncio/sslproto.py�_create_transport_contexts
rcCs
ttd�S)N�	MemoryBIO)r
rrrrr�_is_sslproto_available%srZ	UNWRAPPEDZDO_HANDSHAKEZWRAPPEDZSHUTDOWNc@szeZdZdZddd�Zedd��Zedd	��Zed
d��Zedd
��Z	ddd�Z
ddd�Zdd�Zddd�Z
ddd�ZdS) �_SSLPipe�iNcCsH||_||_||_t|_tj�|_tj�|_d|_	d|_
d|_d|_dS)NF)
�_context�_server_side�_server_hostname�
_UNWRAPPED�_staterr�	_incoming�	_outgoing�_sslobj�
_need_ssldata�
_handshake_cb�_shutdown_cb)�self�contextrrrrr�__init__Ds

z_SSLPipe.__init__cCs|jS)N)r)r#rrrr$Zsz_SSLPipe.contextcCs|jS)N)r)r#rrr�
ssl_object_sz_SSLPipe.ssl_objectcCs|jS)N)r )r#rrr�need_ssldatagsz_SSLPipe.need_ssldatacCs
|jtkS)N)r�_WRAPPED)r#rrr�wrappedmsz_SSLPipe.wrappedcCsR|jtkrtd��|jj|j|j|j|jd�|_	t
|_||_|jddd�\}}|S)Nz"handshake in progress or completed)rr�T)�only_handshake)
rr�RuntimeErrorrZwrap_biorrrrr�
_DO_HANDSHAKEr!�feed_ssldata)r#�callback�ssldata�appdatarrr�do_handshakevs	
z_SSLPipe.do_handshakecCsB|jtkrtd��|jtkr$td��t|_||_|jd�\}}|S)Nzno security layer presentzshutdown in progressr*)rrr,�	_SHUTDOWNr"r.)r#r/r0r1rrr�shutdown�s	

z_SSLPipe.shutdowncCs|jj�|jd�\}}dS)Nr*)rZ	write_eofr.)r#r0r1rrr�feed_eof�s
z_SSLPipe.feed_eofFcCs�|jtkr"|r|g}ng}g|fSd|_|r8|jj|�g}g}y�|jtkrx|jj�t|_|j	rl|j	d�|rx||fS|jtkr�xn|jj
|j�}|j|�|s�Pq�WnJ|jt
kr�|jj�d|_t|_|jr�|j�n|jtkr�|j|jj
��Wnxtjtjfk
�rl}zRt|dd�tjtjtjfk�rN|jtk�rL|j	�rL|j	|��|jtjk|_WYdd}~XnX|jj�r�|j|jj
��||fS)NF�errno)rrr r�writer-rr2r(r!�read�max_size�appendr3Zunwrapr"r�SSLError�CertificateError�getattr�SSL_ERROR_WANT_READ�SSL_ERROR_WANT_WRITE�SSL_ERROR_SYSCALLr6r�pending)r#�datar+r1r0�chunk�excrrrr.�sV











 
z_SSLPipe.feed_ssldatarcCs|jtkr6|t|�kr&||d�g}ng}|t|�fSg}t|�}x�d|_y(|t|�krp||jj||d��7}Wn\tjk
r�}z>|j	dkr�tj
|_|jtj
tjtj
fkr��|jtj
k|_WYdd}~XnX|jjr�|j|jj��|t|�ks�|jrDPqDW||fS)NFZPROTOCOL_IS_SHUTDOWN)rr�len�
memoryviewr rr7rr;�reasonr>r6r?r@rrAr:r8)r#rB�offsetr0ZviewrDrrr�feed_appdata�s2


 z_SSLPipe.feed_appdatai)N)N)N)F)r)�__name__�
__module__�__qualname__r9r%�propertyr$r&r'r)r2r4r5r.rIrrrrr0s
	



Jrc@s�eZdZdd�Zddd�Zdd�Zdd	�Zd
d�Zdd
�Ze	j
rHdd�Zdd�Zdd�Z
ddd�Zdd�Zdd�Zdd�Zdd�ZdS) �_SSLProtocolTransportcCs||_||_d|_dS)NF)�_loop�
_ssl_protocol�_closed)r#�loopZssl_protocolrrrr%)sz_SSLProtocolTransport.__init__NcCs|jj||�S)N)rP�_get_extra_info)r#�name�defaultrrr�get_extra_info/sz$_SSLProtocolTransport.get_extra_infocCs||j_dS)N)rP�
_app_protocol)r#�protocolrrr�set_protocol3sz"_SSLProtocolTransport.set_protocolcCs|jjS)N)rPrW)r#rrr�get_protocol6sz"_SSLProtocolTransport.get_protocolcCs|jS)N)rQ)r#rrr�
is_closing9sz _SSLProtocolTransport.is_closingcCsd|_|jj�dS)NT)rQrP�_start_shutdown)r#rrr�close<sz_SSLProtocolTransport.closecCs&|js"tjd|t|d�|j�dS)Nzunclosed transport %r)�source)rQ�warnings�warn�ResourceWarningr])r#rrr�__del__Ksz_SSLProtocolTransport.__del__cCs|jjj�dS)N)rP�
_transport�
pause_reading)r#rrrrdQsz#_SSLProtocolTransport.pause_readingcCs|jjj�dS)N)rPrc�resume_reading)r#rrrreYsz$_SSLProtocolTransport.resume_readingcCs|jjj||�dS)N)rPrc�set_write_buffer_limits)r#ZhighZlowrrrrfasz-_SSLProtocolTransport.set_write_buffer_limitscCs|jjj�S)N)rPrc�get_write_buffer_size)r#rrrrgvsz+_SSLProtocolTransport.get_write_buffer_sizecCs<t|tttf�s$tdjt|�j���|s,dS|jj	|�dS)Nz/data: expecting a bytes-like instance, got {!r})
�
isinstance�bytes�	bytearrayrF�	TypeError�format�typerJrP�_write_appdata)r#rBrrrr7zsz_SSLProtocolTransport.writecCsdS)NFr)r#rrr�
can_write_eof�sz#_SSLProtocolTransport.can_write_eofcCs|jj�dS)N)rP�_abort)r#rrr�abort�sz_SSLProtocolTransport.abort)N)NN)rJrKrLr%rVrYrZr[r]rZPY34rbrdrerfrgr7rorqrrrrrN&s


rNc@s�eZdZd'dd�Zd(dd�Zdd	�Zd
d�Zdd
�Zdd�Zdd�Z	dd�Z
d)dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd*d!d"�Zd#d$�Zd%d&�ZdS)+�SSLProtocolFNTcCs�tdkrtd��|st||�}||_|r6|r6||_nd|_||_t|d�|_tj	�|_
d|_||_||_
||_t|j
|�|_d|_d|_d|_d|_d|_||_dS)Nzstdlib ssl module not available)rrF)rr,rrr�_sslcontext�dict�_extra�collections�deque�_write_backlog�_write_buffer_size�_waiterrOrWrN�_app_transport�_sslpipe�_session_established�
_in_handshake�_in_shutdownrc�_call_connection_made)r#rRZapp_protocolrZwaiterrrZcall_connection_maderrrr%�s,


zSSLProtocol.__init__cCsD|jdkrdS|jj�s:|dk	r.|jj|�n|jjd�d|_dS)N)rzZ	cancelledZ
set_exceptionZ
set_result)r#rDrrr�_wakeup_waiter�s

zSSLProtocol._wakeup_waitercCs&||_t|j|j|j�|_|j�dS)N)rcrrsrrr|�_start_handshake)r#�	transportrrr�connection_made�s

zSSLProtocol.connection_madecCs8|jrd|_|jj|jj|�d|_d|_|j|�dS)NF)r}rO�	call_soonrW�connection_lostrcr{r�)r#rDrrrr��szSSLProtocol.connection_lostcCs|jj�dS)N)rW�
pause_writing)r#rrrr��szSSLProtocol.pause_writingcCs|jj�dS)N)rW�resume_writing)r#rrrr��szSSLProtocol.resume_writingcCs�|jdkrdSy|jj|�\}}WnHtjk
rj}z*|jj�rTtjd||j|j	�|j
�dSd}~XnXx|D]}|jj|�qrWx(|D] }|r�|j
j|�q�|j�Pq�WdS)Nz%r: SSL error %s (reason %s))r|r.rr;rO�	get_debugr�warningr6rGrprcr7rW�
data_receivedr\)r#rBr0r1�erCrrrr��s"



zSSLProtocol.data_receivedc
CsTzB|jj�rtjd|�|jt�|js@|jj�}|r@tj	d�Wd|j
j�XdS)Nz%r received EOFz?returning true from eof_received() has no effect when using ssl)rOr�r�debugr��ConnectionResetErrorr~rW�eof_receivedr�rcr])r#Z	keep_openrrrr�s


zSSLProtocol.eof_receivedcCs4||jkr|j|S|jdk	r,|jj||�S|SdS)N)rurcrV)r#rTrUrrrrS!s



zSSLProtocol._get_extra_infocCs.|jr
dS|jr|j�nd|_|jd�dS)NTr*)rr~rprn)r#rrrr\)s
zSSLProtocol._start_shutdowncCs.|jj|df�|jt|�7_|j�dS)Nr)rxr:ryrE�_process_write_backlog)r#rBrrrrn2szSSLProtocol._write_appdatacCsH|jj�r$tjd|�|jj�|_nd|_d|_|jjd�|j	�dS)Nz%r starts SSL handshakeTr*r)r*r)
rOr�rr��time�_handshake_start_timer~rxr:r�)r#rrrr�7s
zSSLProtocol._start_handshakecCsTd|_|jj}yF|dk	r|�|j�}t|jd�sR|jrR|jjtj	krRtj
||j�Wn~tk
r�}zb|jj
�r�t|tj�r�tjd|dd�ntjd|dd�|jj�t|t�r�|j|�dS�WYdd}~XnX|jj
��r|jj�|j}tjd||d�|jj||j�|j�|d	�|j�r4|jj|j �|j�d|_!|jj"|j#�dS)
NFrz5%r: SSL handshake failed on verifying the certificateT)�exc_infoz%r: SSL handshake failedz%r: SSL handshake took %.1f msg@�@)�peercert�cipher�compressionr&)$r~r|r&Zgetpeercertr
rsrr
rZ	CERT_NONEZmatch_hostname�
BaseExceptionrOr�rhr<rr�rcr]�	Exceptionr�r�r�r�ru�updater�r�r�rWr�r{r}r�r�)r#Z
handshake_excZsslobjr�rDZdtrrr�_on_handshake_completeCsD




z"SSLProtocol._on_handshake_completecCs>|jdks|jdkrdSy�x�tt|j��D]�}|jd\}}|rT|jj||�\}}n*|rl|jj|j�}d}n|jj|j	�}d}x|D]}|jj
|�q�W|t|�kr�||f|jd<|jjr�|jj�P|jd=|j
t|�8_
q*WWnRtk
�r8}z4|j�r|j|�n|j|d�t|t��s(�WYdd}~XnXdS)NrrzFatal error on SSL transport)rcr|�rangerErxrIr2r�r4�	_finalizer7Z_pausedreryr�r~�_fatal_errorrhr�)r#�irBrHr0rCrDrrrr�ws8

z"SSLProtocol._process_write_backlog�Fatal error on transportcCsXt|tj�r*|jj�rBtjd||dd�n|jj|||j|d��|jrT|jj	|�dS)Nz%r: %sT)r�)�messageZ	exceptionr�rX)
rhrZ_FATAL_ERROR_IGNORErOr�rr�Zcall_exception_handlerrcZ_force_close)r#rDr�rrrr��s

zSSLProtocol._fatal_errorcCsd|_|jdk	r|jj�dS)N)r|rcr])r#rrrr��s
zSSLProtocol._finalizec
Cs(z|jdk	r|jj�Wd|j�XdS)N)rcrqr�)r#rrrrp�s
zSSLProtocol._abort)FNT)N)N)r�)rJrKrLr%r�r�r�r�r�r�r�rSr\rnr�r�r�r�r�rprrrrrr�s$
"


	4,
rr)rvr_r�ImportError�rrrr�logrrrrr-r(r3�objectrZ_FlowControlMixinZ	TransportrNZProtocolrrrrrr�<module>s*
wnPK[��ېb�b'__pycache__/events.cpython-36.opt-1.pycnu�[���3


 \�[�@s�dZddddddddd	d
ddd
dgZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddlm
Z
dd�Zdd�Zd3dd�Zdd�Zd4dd�ZGdd�d�ZGd d�de�ZGd!d�d�ZGd"d�d�ZGd#d�d�ZGd$d%�d%e�Zdae	j�ZGd&d'�d'e	j�Ze�Zd(d�Zd)d
�Z d*d+�Z!d,d�Z"d-d�Z#d.d�Z$d/d	�Z%d0d
�Z&d1d�Z'd2d�Z(dS)5z!Event loop and event loop policy.�AbstractEventLoopPolicy�AbstractEventLoop�AbstractServer�Handle�TimerHandle�get_event_loop_policy�set_event_loop_policy�get_event_loop�set_event_loop�new_event_loop�get_child_watcher�set_child_watcher�_set_running_loop�_get_running_loop�N�)�compat)�	constantscCsttjrtj|�}nt|d�r"|j}tj|�r>|j}|j|j	fSt
|tj�rTt
|j�Stjrpt
|tj�rpt
|j�SdS)N�__wrapped__)rZPY34�inspectZunwrap�hasattrrZ
isfunction�__code__�co_filename�co_firstlineno�
isinstance�	functools�partial�_get_function_source�func�
partialmethod)r�code�r �&/usr/lib64/python3.6/asyncio/events.pyrs



rcCsJg}|r|jdd�|D��|r8|jdd�|j�D��ddj|�dS)z�Format function arguments and keyword arguments.

    Special case for a single parameter: ('hello',) is formatted as ('hello').
    css|]}tj|�VqdS)N)�reprlib�repr)�.0�argr r r!�	<genexpr>1sz*_format_args_and_kwargs.<locals>.<genexpr>css$|]\}}dj|tj|��VqdS)z{}={}N)�formatr"r#)r$�k�vr r r!r&3s�(z, �))�extend�items�join)�args�kwargsr-r r r!�_format_args_and_kwargs)s
r1�cCs�t|tj�r.t||�|}t|j|j|j|�St|d�rF|j	rF|j	}n t|d�r^|j
r^|j
}nt|�}|t||�7}|r�||7}|S)N�__qualname__�__name__)rrrr1�_format_callbackrr/�keywordsrr3r4r#)rr/r0�suffix�	func_reprr r r!r58sr5cCs(t||d�}t|�}|r$|d|7}|S)Nz	 at %s:%s)r5r)rr/r8�sourcer r r!�_format_callback_sourceIs
r:cCsD|dkrtj�j}|dkr tj}tjjtj|�|dd�}|j	�|S)zlReplacement for traceback.extract_stack() that only does the
    necessary work for asyncio debug mode.
    NF)�limit�lookup_lines)
�sys�	_getframe�f_backrZDEBUG_STACK_DEPTH�	traceback�StackSummary�extract�
walk_stack�reverse)�fr;�stackr r r!�
extract_stackQs
rGc@s<eZdZdZdZd	d
�Zdd�Zd
d�Zdd�Zdd�Z	dS)rz1Object returned by callback registration methods.�	_callback�_args�
_cancelled�_loop�_source_traceback�_repr�__weakref__cCsD||_||_||_d|_d|_|jj�r:ttjd��|_	nd|_	dS)NFr)
rKrHrIrJrM�	get_debugrGr=r>rL)�self�callbackr/�loopr r r!�__init__hs
zHandle.__init__cCsf|jjg}|jr|jd�|jdk	r8|jt|j|j��|jrb|jd}|jd|d|df�|S)NZ	cancelledrzcreated at %s:%sr���)�	__class__r4rJ�appendrHr:rIrL)rP�info�framer r r!�
_repr_infoss



zHandle._repr_infocCs&|jdk	r|jS|j�}ddj|�S)Nz<%s>� )rMrYr.)rPrWr r r!�__repr__~s
zHandle.__repr__cCs0|js,d|_|jj�r t|�|_d|_d|_dS)NT)rJrKrOr#rMrHrI)rPr r r!�cancel�s

z
Handle.cancelcCs|y|j|j�Wnbtk
rr}zFt|j|j�}dj|�}|||d�}|jrV|j|d<|jj|�WYdd}~XnXd}dS)NzException in callback {})�messageZ	exception�handleZsource_traceback)rHrI�	Exceptionr:r'rLrK�call_exception_handler)rP�exc�cb�msg�contextr r r!�_run�s

zHandle._runN)rHrIrJrKrLrMrN)
r4�
__module__r3�__doc__�	__slots__rSrYr[r\rer r r r!rbscsxeZdZdZddgZ�fdd�Z�fdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
�fdd�Z�ZS)rz7Object returned by timed callback registration methods.�
_scheduled�_whencs.t�j|||�|jr|jd=||_d|_dS)NrFrT)�superrSrLrjri)rP�whenrQr/rR)rUr r!rS�s
zTimerHandle.__init__cs.t�j�}|jrdnd}|j|d|j�|S)N�rzwhen=%s)rkrYrJ�insertrj)rPrW�pos)rUr r!rY�s
zTimerHandle._repr_infocCs
t|j�S)N)�hashrj)rPr r r!�__hash__�szTimerHandle.__hash__cCs|j|jkS)N)rj)rP�otherr r r!�__lt__�szTimerHandle.__lt__cCs|j|jkrdS|j|�S)NT)rj�__eq__)rPrrr r r!�__le__�szTimerHandle.__le__cCs|j|jkS)N)rj)rPrrr r r!�__gt__�szTimerHandle.__gt__cCs|j|jkrdS|j|�S)NT)rjrt)rPrrr r r!�__ge__�szTimerHandle.__ge__cCs>t|t�r:|j|jko8|j|jko8|j|jko8|j|jkStS)N)rrrjrHrIrJ�NotImplemented)rPrrr r r!rt�s
zTimerHandle.__eq__cCs|j|�}|tkrtS|S)N)rtrx)rPrrZequalr r r!�__ne__�s
zTimerHandle.__ne__cs |js|jj|�t�j�dS)N)rJrK�_timer_handle_cancelledrkr\)rP)rUr r!r\�szTimerHandle.cancel)r4rfr3rgrhrSrYrqrsrurvrwrtryr\�
__classcell__r r )rUr!r�sc@s eZdZdZdd�Zdd�ZdS)rz,Abstract server returned by create_server().cCstS)z5Stop serving.  This leaves existing connections open.)rx)rPr r r!�close�szAbstractServer.closecCstS)z*Coroutine to wait until service is closed.)rx)rPr r r!�wait_closed�szAbstractServer.wait_closedN)r4rfr3rgr|r}r r r r!r�sc	@seZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d$d$d$d%�d&d'�Zdhd(d)�Zdid*d$d$d$d*d*d*d+�d,d-�Zdjejejd*d.d*d*d*d/�d0d1�Zd*d*d*d2�d3d4�Zd*d.d*d5�d6d7�Zdkd$d$d$d*d*d*d*d8�d9d:�Zd;d<�Zd=d>�Z e!j"e!j"e!j"d?�d@dA�Z#e!j"e!j"e!j"d?�dBdC�Z$dDdE�Z%dFdG�Z&dHdI�Z'dJdK�Z(dLdM�Z)dNdO�Z*dPdQ�Z+dRdS�Z,dTdU�Z-dVdW�Z.dXdY�Z/dZd[�Z0d\d]�Z1d^d_�Z2d`da�Z3dbdc�Z4ddde�Z5dfdg�Z6d*S)lrzAbstract event loop.cCst�dS)z*Run the event loop until stop() is called.N)�NotImplementedError)rPr r r!�run_forever�szAbstractEventLoop.run_forevercCst�dS)zpRun the event loop until a Future is done.

        Return the Future's result, or raise its exception.
        N)r~)rPZfuturer r r!�run_until_complete�sz$AbstractEventLoop.run_until_completecCst�dS)z�Stop the event loop as soon as reasonable.

        Exactly how soon that is may depend on the implementation, but
        no more I/O callbacks should be scheduled.
        N)r~)rPr r r!�stop�szAbstractEventLoop.stopcCst�dS)z3Return whether the event loop is currently running.N)r~)rPr r r!�
is_running�szAbstractEventLoop.is_runningcCst�dS)z*Returns True if the event loop was closed.N)r~)rPr r r!�	is_closedszAbstractEventLoop.is_closedcCst�dS)z�Close the loop.

        The loop should not be running.

        This is idempotent and irreversible.

        No other methods should be called after this one.
        N)r~)rPr r r!r|s	zAbstractEventLoop.closecCst�dS)z,Shutdown all active asynchronous generators.N)r~)rPr r r!�shutdown_asyncgenssz$AbstractEventLoop.shutdown_asyncgenscCst�dS)z3Notification that a TimerHandle has been cancelled.N)r~)rPr^r r r!rzsz)AbstractEventLoop._timer_handle_cancelledcGs|jd|f|��S)Nr)�
call_later)rPrQr/r r r!�	call_soonszAbstractEventLoop.call_sooncGst�dS)N)r~)rPZdelayrQr/r r r!r�szAbstractEventLoop.call_latercGst�dS)N)r~)rPrlrQr/r r r!�call_atszAbstractEventLoop.call_atcCst�dS)N)r~)rPr r r!�time"szAbstractEventLoop.timecCst�dS)N)r~)rPr r r!�
create_future%szAbstractEventLoop.create_futurecCst�dS)N)r~)rP�coror r r!�create_task*szAbstractEventLoop.create_taskcGst�dS)N)r~)rPrQr/r r r!�call_soon_threadsafe/sz&AbstractEventLoop.call_soon_threadsafecGst�dS)N)r~)rP�executorrr/r r r!�run_in_executor2sz!AbstractEventLoop.run_in_executorcCst�dS)N)r~)rPr�r r r!�set_default_executor5sz&AbstractEventLoop.set_default_executorr)�family�type�proto�flagscCst�dS)N)r~)rP�host�portr�r�r�r�r r r!�getaddrinfo:szAbstractEventLoop.getaddrinfocCst�dS)N)r~)rPZsockaddrr�r r r!�getnameinfo=szAbstractEventLoop.getnameinfoN)�sslr�r�r��sock�
local_addr�server_hostnamecCst�dS)N)r~)rP�protocol_factoryr�r�r�r�r�r�r�r�r�r r r!�create_connection@sz#AbstractEventLoop.create_connection�d)r�r�r��backlogr��
reuse_address�
reuse_portcCst�dS)a�A coroutine which creates a TCP server bound to host and port.

        The return value is a Server object which can be used to stop
        the service.

        If host is an empty string or None all interfaces are assumed
        and a list of multiple sockets will be returned (most likely
        one for IPv4 and another one for IPv6). The host parameter can also be a
        sequence (e.g. list) of hosts to bind to.

        family can be set to either AF_INET or AF_INET6 to force the
        socket to use IPv4 or IPv6. If not set it will be determined
        from host (defaults to AF_UNSPEC).

        flags is a bitmask for getaddrinfo().

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows.
        N)r~)rPr�r�r�r�r�r�r�r�r�r�r r r!�
create_serverEs'zAbstractEventLoop.create_server)r�r�r�cCst�dS)N)r~)rPr��pathr�r�r�r r r!�create_unix_connectionnsz(AbstractEventLoop.create_unix_connection)r�r�r�cCst�dS)a#A coroutine which creates a UNIX Domain Socket server.

        The return value is a Server object, which can be used to stop
        the service.

        path is a str, representing a file systsem path to bind the
        server socket to.

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.
        N)r~)rPr�r�r�r�r�r r r!�create_unix_serverssz$AbstractEventLoop.create_unix_server)r�r�r�r�r��allow_broadcastr�cCst�dS)a�A coroutine which creates a datagram endpoint.

        This method will try to establish the endpoint in the background.
        When successful, the coroutine returns a (transport, protocol) pair.

        protocol_factory must be a callable returning a protocol instance.

        socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_DGRAM.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified it will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows and some UNIX's. If the
        :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
        capability is unsupported.

        allow_broadcast tells the kernel to allow this endpoint to send
        messages to the broadcast address.

        sock can optionally be specified in order to use a preexisting
        socket object.
        N)r~)rPr�r�Zremote_addrr�r�r�r�r�r�r�r r r!�create_datagram_endpoint�s!z*AbstractEventLoop.create_datagram_endpointcCst�dS)aRegister read pipe in event loop. Set the pipe to non-blocking mode.

        protocol_factory should instantiate object with Protocol interface.
        pipe is a file-like object.
        Return pair (transport, protocol), where transport supports the
        ReadTransport interface.N)r~)rPr��piper r r!�connect_read_pipe�sz#AbstractEventLoop.connect_read_pipecCst�dS)aRegister write pipe in event loop.

        protocol_factory should instantiate object with BaseProtocol interface.
        Pipe is file-like object already switched to nonblocking.
        Return pair (transport, protocol), where transport support
        WriteTransport interface.N)r~)rPr�r�r r r!�connect_write_pipe�sz$AbstractEventLoop.connect_write_pipe)�stdin�stdout�stderrcKst�dS)N)r~)rPr��cmdr�r�r�r0r r r!�subprocess_shell�sz"AbstractEventLoop.subprocess_shellcOst�dS)N)r~)rPr�r�r�r�r/r0r r r!�subprocess_exec�sz!AbstractEventLoop.subprocess_execcGst�dS)N)r~)rP�fdrQr/r r r!�
add_reader�szAbstractEventLoop.add_readercCst�dS)N)r~)rPr�r r r!�
remove_reader�szAbstractEventLoop.remove_readercGst�dS)N)r~)rPr�rQr/r r r!�
add_writer�szAbstractEventLoop.add_writercCst�dS)N)r~)rPr�r r r!�
remove_writer�szAbstractEventLoop.remove_writercCst�dS)N)r~)rPr��nbytesr r r!�	sock_recv�szAbstractEventLoop.sock_recvcCst�dS)N)r~)rPr��datar r r!�sock_sendall�szAbstractEventLoop.sock_sendallcCst�dS)N)r~)rPr�Zaddressr r r!�sock_connect�szAbstractEventLoop.sock_connectcCst�dS)N)r~)rPr�r r r!�sock_accept�szAbstractEventLoop.sock_acceptcGst�dS)N)r~)rP�sigrQr/r r r!�add_signal_handler�sz$AbstractEventLoop.add_signal_handlercCst�dS)N)r~)rPr�r r r!�remove_signal_handler�sz'AbstractEventLoop.remove_signal_handlercCst�dS)N)r~)rP�factoryr r r!�set_task_factory�sz"AbstractEventLoop.set_task_factorycCst�dS)N)r~)rPr r r!�get_task_factory�sz"AbstractEventLoop.get_task_factorycCst�dS)N)r~)rPr r r!�get_exception_handlersz'AbstractEventLoop.get_exception_handlercCst�dS)N)r~)rPZhandlerr r r!�set_exception_handlersz'AbstractEventLoop.set_exception_handlercCst�dS)N)r~)rPrdr r r!�default_exception_handlersz+AbstractEventLoop.default_exception_handlercCst�dS)N)r~)rPrdr r r!r`sz(AbstractEventLoop.call_exception_handlercCst�dS)N)r~)rPr r r!rOszAbstractEventLoop.get_debugcCst�dS)N)r~)rPZenabledr r r!�	set_debugszAbstractEventLoop.set_debug)r)NN)NN)NN)7r4rfr3rgrr�r�r�r�r|r�rzr�r�r�r�r�r�r�r�r�r�r�r��socketZ	AF_UNSPECZ
AI_PASSIVEr�r�r�r�r�r��
subprocess�PIPEr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r`rOr�r r r r!r�st

'!

	c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
rz-Abstract policy for accessing the event loop.cCst�dS)a:Get the event loop for the current context.

        Returns an event loop object implementing the BaseEventLoop interface,
        or raises an exception in case no event loop has been set for the
        current context and the current policy does not specify to create one.

        It should never return None.N)r~)rPr r r!rsz&AbstractEventLoopPolicy.get_event_loopcCst�dS)z3Set the event loop for the current context to loop.N)r~)rPrRr r r!r	$sz&AbstractEventLoopPolicy.set_event_loopcCst�dS)z�Create and return a new event loop object according to this
        policy's rules. If there's need to set this loop as the event loop for
        the current context, set_event_loop must be called explicitly.N)r~)rPr r r!r
(sz&AbstractEventLoopPolicy.new_event_loopcCst�dS)z$Get the watcher for child processes.N)r~)rPr r r!r0sz)AbstractEventLoopPolicy.get_child_watchercCst�dS)z$Set the watcher for child processes.N)r~)rP�watcherr r r!r4sz)AbstractEventLoopPolicy.set_child_watcherN)	r4rfr3rgrr	r
rrr r r r!rs
c@sFeZdZdZdZGdd�dej�Zdd�Zdd�Z	d	d
�Z
dd�ZdS)
�BaseDefaultEventLoopPolicya�Default policy implementation for accessing the event loop.

    In this policy, each thread has its own event loop.  However, we
    only automatically create an event loop by default for the main
    thread; other threads by default have no event loop.

    Other policies may have different rules (e.g. a single global
    event loop, or automatically creating an event loop per thread, or
    using some other notion of context to which an event loop is
    associated).
    Nc@seZdZdZdZdS)z!BaseDefaultEventLoopPolicy._LocalNF)r4rfr3rK�_set_calledr r r r!�_LocalHsr�cCs|j�|_dS)N)r��_local)rPr r r!rSLsz#BaseDefaultEventLoopPolicy.__init__cCsZ|jjdkr4|jjr4ttj�tj�r4|j|j��|jjdkrRt	dtj�j
��|jjS)zSGet the event loop.

        This may be None or an instance of EventLoop.
        Nz,There is no current event loop in thread %r.)r�rKr�r�	threadingZcurrent_threadZ_MainThreadr	r
�RuntimeError�name)rPr r r!rOs
z)BaseDefaultEventLoopPolicy.get_event_loopcCsd|j_||j_dS)zSet the event loop.TN)r�r�rK)rPrRr r r!r	]sz)BaseDefaultEventLoopPolicy.set_event_loopcCs|j�S)zvCreate a new event loop.

        You must call set_event_loop() to make this the current event
        loop.
        )�
_loop_factory)rPr r r!r
csz)BaseDefaultEventLoopPolicy.new_event_loop)r4rfr3rgr�r��localr�rSrr	r
r r r r!r�9sr�c@seZdZdZdS)�_RunningLoopN)NN)r4rfr3�loop_pidr r r r!r�wsr�cCs&tj\}}|dk	r"|tj�kr"|SdS)z�Return the running event loop or None.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)�
_running_loopr��os�getpid)Zrunning_loop�pidr r r!r~s
cCs|tj�ft_dS)z�Set the running event loop.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)r�r�r�r�)rRr r r!r
�sc	Cs.t� tdkr ddlm}|�aWdQRXdS)Nr)�DefaultEventLoopPolicy)�_lock�_event_loop_policyr2r�)r�r r r!�_init_event_loop_policy�sr�cCstdkrt�tS)z"Get the current event loop policy.N)r�r�r r r r!r�scCs|adS)zZSet the current event loop policy.

    If policy is None, the default policy is restored.N)r�)Zpolicyr r r!r�scCst�}|dk	r|St�j�S)aGReturn an asyncio event loop.

    When called from a coroutine or a callback (e.g. scheduled with call_soon
    or similar API), this function will always return the running event loop.

    If there is no running event loop set, the function will return
    the result of `get_event_loop_policy().get_event_loop()` call.
    N)rrr)Zcurrent_loopr r r!r�s	cCst�j|�dS)zCEquivalent to calling get_event_loop_policy().set_event_loop(loop).N)rr	)rRr r r!r	�scCs
t�j�S)z?Equivalent to calling get_event_loop_policy().new_event_loop().)rr
r r r r!r
�scCs
t�j�S)zBEquivalent to calling get_event_loop_policy().get_child_watcher().)rrr r r r!r�scCst�j|�S)zMEquivalent to calling
    get_event_loop_policy().set_child_watcher(watcher).)rr)r�r r r!r�s)r2)NN))rg�__all__rrr�r"r�r�r=r�r@r2rrrr1r5r:rGrrrrrr�r�ZLockr�r�r�r�rr
r�rrrr	r
rrr r r r!�<module>sZ

>85"7		PK[�#�~� � '__pycache__/queues.cpython-36.opt-1.pycnu�[���3


 \�@s�dZdddddgZddlZddlZdd	lmZdd
lmZddlmZddlm	Z	Gd
d�de
�ZGdd�de
�ZGdd�d�Z
Gdd�de
�ZGdd�de
�Zejs�e
Zejd�dS)ZQueues�Queue�
PriorityQueue�	LifoQueue�	QueueFull�
QueueEmpty�N�)�compat)�events)�locks)�	coroutinec@seZdZdZdS)rz]Exception raised when Queue.get_nowait() is called on a Queue object
    which is empty.
    N)�__name__�
__module__�__qualname__�__doc__�rr�&/usr/lib64/python3.6/asyncio/queues.pyrsc@seZdZdZdS)rzgException raised when the Queue.put_nowait() method is called on a Queue
    object which is full.
    N)rr
rrrrrrrsc@s�eZdZdZd)dd�dd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Ze
dd��Zdd�Zdd�Zedd��Zdd �Zed!d"��Zd#d$�Zd%d&�Zed'd(��ZdS)*raA queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "yield from put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded asyncio application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    rN)�loopcCsb|dkrtj�|_n||_||_tj�|_tj�|_d|_t	j
|jd�|_|jj�|j
|�dS)Nr)r)r	Zget_event_loop�_loop�_maxsize�collections�deque�_getters�_putters�_unfinished_tasksr
ZEvent�	_finished�set�_init)�self�maxsizerrrr�__init__(s


zQueue.__init__cCstj�|_dS)N)rr�_queue)rrrrrr:szQueue._initcCs
|jj�S)N)r �popleft)rrrr�_get=sz
Queue._getcCs|jj|�dS)N)r �append)r�itemrrr�_put@sz
Queue._putcCs*x$|r$|j�}|j�s|jd�PqWdS)N)r!�doneZ
set_result)r�waitersZwaiterrrr�_wakeup_nextEs

zQueue._wakeup_nextcCsdjt|�jt|�|j��S)Nz<{} at {:#x} {}>)�format�typer�id�_format)rrrr�__repr__MszQueue.__repr__cCsdjt|�j|j��S)Nz<{} {}>)r)r*rr,)rrrr�__str__Qsz
Queue.__str__cCszdj|j�}t|dd�r,|djt|j��7}|jrF|djt|j��7}|jr`|djt|j��7}|jrv|dj|j�7}|S)Nzmaxsize={!r}r z _queue={!r}z
 _getters[{}]z
 _putters[{}]z	 tasks={})	r)r�getattr�listr r�lenrr)r�resultrrrr,Tsz
Queue._formatcCs
t|j�S)zNumber of items in the queue.)r1r )rrrr�qsize`szQueue.qsizecCs|jS)z%Number of items allowed in the queue.)r)rrrrrdsz
Queue.maxsizecCs|jS)z3Return True if the queue is empty, False otherwise.)r )rrrr�emptyiszQueue.emptycCs |jdkrdS|j�|jkSdS)z�Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        rFN)rr3)rrrr�fullms
z
Queue.fullc	cstxh|j�rh|jj�}|jj|�y|EdHWq|j�|j�r^|j�r^|j|j��YqXqW|j|�S)z�Put an item into the queue.

        Put an item into the queue. If the queue is full, wait until a free
        slot is available before adding item.

        This method is a coroutine.
        N)	r5r�
create_futurerr#�cancel�	cancelledr(�
put_nowait)rr$Zputterrrr�putxs	

z	Queue.putcCs>|j�rt�|j|�|jd7_|jj�|j|j�dS)zyPut an item into the queue without blocking.

        If no free slot is immediately available, raise QueueFull.
        rN)r5rr%rr�clearr(r)rr$rrrr9�s

zQueue.put_nowaitccs�x�|j�r�|jj�}|jj|�y|EdHWq|j�y|jj|�Wntk
rbYnX|j�r�|j�r�|j	|j��YqXqW|j
�S)z�Remove and return an item from the queue.

        If queue is empty, wait until an item is available.

        This method is a coroutine.
        N)r4rr6rr#r7�remove�
ValueErrorr8r(�
get_nowait)r�getterrrr�get�s

z	Queue.getcCs$|j�rt�|j�}|j|j�|S)z�Remove and return an item from the queue.

        Return an item if one is immediately available, else raise QueueEmpty.
        )r4rr"r(r)rr$rrrr>�s
zQueue.get_nowaitcCs8|jdkrtd��|jd8_|jdkr4|jj�dS)a$Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).

        Raises ValueError if called more times than there were items placed in
        the queue.
        rz!task_done() called too many timesrN)rr=rr)rrrr�	task_done�s


zQueue.task_doneccs|jdkr|jj�EdHdS)aBlock until all items in the queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer calls task_done() to
        indicate that the item was retrieved and all work on it is complete.
        When the count of unfinished tasks drops to zero, join() unblocks.
        rN)rr�wait)rrrr�join�s	
z
Queue.join)r)rr
rrrrr"r%r(r-r.r,r3�propertyrr4r5rr:r9r@r>rArCrrrrrs&
c@s4eZdZdZdd�Zejfdd�Zejfdd�Z	dS)	rz�A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    cCs
g|_dS)N)r )rrrrrr�szPriorityQueue._initcCs||j|�dS)N)r )rr$�heappushrrrr%�szPriorityQueue._putcCs
||j�S)N)r )r�heappoprrrr"�szPriorityQueue._getN)
rr
rrr�heapqrEr%rFr"rrrrr�sc@s(eZdZdZdd�Zdd�Zdd�ZdS)	rzEA subclass of Queue that retrieves most recently added entries first.cCs
g|_dS)N)r )rrrrrr�szLifoQueue._initcCs|jj|�dS)N)r r#)rr$rrrr%�szLifoQueue._putcCs
|jj�S)N)r �pop)rrrrr"�szLifoQueue._getN)rr
rrrr%r"rrrrr�s�
JoinableQueue)r�__all__rrG�rr	r
Z
coroutinesr�	ExceptionrrrrrZPY35rIr#rrrr�<module>s H
PK[����N�N)__pycache__/sslproto.cpython-36.opt-1.pycnu�[���3


 \�e�
@s�ddlZddlZyddlZWnek
r4dZYnXddlmZddlmZddlmZddlmZddl	m
Z
dd	�Zd
d�ZdZ
d
ZdZdZGdd�de�ZGdd�dejej�ZGdd�dej�ZdS)�N�)�base_events)�compat)�	protocols)�
transports)�loggercCsj|rtd��ttd�r*tj�}|sfd|_n<tjtj�}|jtjO_|jtj	O_|j
�tj|_|S)Nz(Server side SSL needs a valid SSLContext�create_default_contextF)
�
ValueError�hasattr�sslr�check_hostnameZ
SSLContextZPROTOCOL_SSLv23ZoptionsZOP_NO_SSLv2ZOP_NO_SSLv3Zset_default_verify_pathsZ
CERT_REQUIRED�verify_mode)�server_side�server_hostname�
sslcontext�r�(/usr/lib64/python3.6/asyncio/sslproto.py�_create_transport_contexts
rcCs
ttd�S)N�	MemoryBIO)r
rrrrr�_is_sslproto_available%srZ	UNWRAPPEDZDO_HANDSHAKEZWRAPPEDZSHUTDOWNc@s~eZdZdZdZddd�Zedd��Zed	d
��Zedd��Z	ed
d��Z
ddd�Zddd�Zdd�Z
ddd�Zd dd�ZdS)!�_SSLPipeaAn SSL "Pipe".

    An SSL pipe allows you to communicate with an SSL/TLS protocol instance
    through memory buffers. It can be used to implement a security layer for an
    existing connection where you don't have access to the connection's file
    descriptor, or for some reason you don't want to use it.

    An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
    data is passed through untransformed. In wrapped mode, application level
    data is encrypted to SSL record level data and vice versa. The SSL record
    level is the lowest level in the SSL protocol suite and is what travels
    as-is over the wire.

    An SslPipe initially is in "unwrapped" mode. To start SSL, call
    do_handshake(). To shutdown SSL again, call unwrap().
    �iNcCsH||_||_||_t|_tj�|_tj�|_d|_	d|_
d|_d|_dS)a�
        The *context* argument specifies the ssl.SSLContext to use.

        The *server_side* argument indicates whether this is a server side or
        client side transport.

        The optional *server_hostname* argument can be used to specify the
        hostname you are connecting to. You may only specify this parameter if
        the _ssl module supports Server Name Indication (SNI).
        NF)
�_context�_server_side�_server_hostname�
_UNWRAPPED�_staterr�	_incoming�	_outgoing�_sslobj�
_need_ssldata�
_handshake_cb�_shutdown_cb)�self�contextrrrrr�__init__Ds

z_SSLPipe.__init__cCs|jS)z*The SSL context passed to the constructor.)r)r#rrrr$Zsz_SSLPipe.contextcCs|jS)z^The internal ssl.SSLObject instance.

        Return None if the pipe is not wrapped.
        )r)r#rrr�
ssl_object_sz_SSLPipe.ssl_objectcCs|jS)zgWhether more record level data is needed to complete a handshake
        that is currently in progress.)r )r#rrr�need_ssldatagsz_SSLPipe.need_ssldatacCs
|jtkS)zj
        Whether a security layer is currently in effect.

        Return False during handshake.
        )r�_WRAPPED)r#rrr�wrappedmsz_SSLPipe.wrappedcCsR|jtkrtd��|jj|j|j|j|jd�|_	t
|_||_|jddd�\}}|S)aLStart the SSL handshake.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the handshake is complete. The callback will be
        called with None if successful, else an exception instance.
        z"handshake in progress or completed)rr�T)�only_handshake)
rr�RuntimeErrorrZwrap_biorrrrr�
_DO_HANDSHAKEr!�feed_ssldata)r#�callback�ssldata�appdatarrr�do_handshakevs	
z_SSLPipe.do_handshakecCsB|jtkrtd��|jtkr$td��t|_||_|jd�\}}|S)a1Start the SSL shutdown sequence.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the shutdown is complete. The callback will be
        called without arguments.
        zno security layer presentzshutdown in progressr*)rrr,�	_SHUTDOWNr"r.)r#r/r0r1rrr�shutdown�s	

z_SSLPipe.shutdowncCs|jj�|jd�\}}dS)z�Send a potentially "ragged" EOF.

        This method will raise an SSL_ERROR_EOF exception if the EOF is
        unexpected.
        r*N)rZ	write_eofr.)r#r0r1rrr�feed_eof�s
z_SSLPipe.feed_eofFcCs�|jtkr"|r|g}ng}g|fSd|_|r8|jj|�g}g}y�|jtkrx|jj�t|_|j	rl|j	d�|rx||fS|jtkr�xn|jj
|j�}|j|�|s�Pq�WnJ|jt
kr�|jj�d|_t|_|jr�|j�n|jtkr�|j|jj
��Wnxtjtjfk
�rl}zRt|dd�tjtjtjfk�rN|jtk�rL|j	�rL|j	|��|jtjk|_WYdd}~XnX|jj�r�|j|jj
��||fS)a�Feed SSL record level data into the pipe.

        The data must be a bytes instance. It is OK to send an empty bytes
        instance. This can be used to get ssldata for a handshake initiated by
        this endpoint.

        Return a (ssldata, appdata) tuple. The ssldata element is a list of
        buffers containing SSL data that needs to be sent to the remote SSL.

        The appdata element is a list of buffers containing plaintext data that
        needs to be forwarded to the application. The appdata list may contain
        an empty buffer indicating an SSL "close_notify" alert. This alert must
        be acknowledged by calling shutdown().
        FN�errno)rrr r�writer-rr2r(r!�read�max_size�appendr3Zunwrapr"r�SSLError�CertificateError�getattr�SSL_ERROR_WANT_READ�SSL_ERROR_WANT_WRITE�SSL_ERROR_SYSCALLr6r�pending)r#�datar+r1r0�chunk�excrrrr.�sV











 
z_SSLPipe.feed_ssldatarcCs|jtkr6|t|�kr&||d�g}ng}|t|�fSg}t|�}x�d|_y(|t|�krp||jj||d��7}Wn\tjk
r�}z>|j	dkr�tj
|_|jtj
tjtj
fkr��|jtj
k|_WYdd}~XnX|jjr�|j|jj��|t|�ks�|jrDPqDW||fS)aFeed plaintext data into the pipe.

        Return an (ssldata, offset) tuple. The ssldata element is a list of
        buffers containing record level data that needs to be sent to the
        remote SSL instance. The offset is the number of plaintext bytes that
        were processed, which may be less than the length of data.

        NOTE: In case of short writes, this call MUST be retried with the SAME
        buffer passed into the *data* argument (i.e. the id() must be the
        same). This is an OpenSSL requirement. A further particularity is that
        a short write will always have offset == 0, because the _ssl module
        does not enable partial writes. And even though the offset is zero,
        there will still be encrypted data in ssldata.
        NFZPROTOCOL_IS_SHUTDOWN)rr�len�
memoryviewr rr7rr;�reasonr>r6r?r@rrAr:r8)r#rB�offsetr0ZviewrDrrr�feed_appdata�s2


 z_SSLPipe.feed_appdatai)N)N)N)F)r)�__name__�
__module__�__qualname__�__doc__r9r%�propertyr$r&r'r)r2r4r5r.rIrrrrr0s
	



Jrc@s�eZdZdd�Zddd�Zdd�Zdd	�Zd
d�Zdd
�Ze	j
rHdd�Zdd�Zdd�Z
ddd�Zdd�Zdd�Zdd�Zdd�ZdS) �_SSLProtocolTransportcCs||_||_d|_dS)NF)�_loop�
_ssl_protocol�_closed)r#�loopZssl_protocolrrrr%)sz_SSLProtocolTransport.__init__NcCs|jj||�S)z#Get optional transport information.)rQ�_get_extra_info)r#�name�defaultrrr�get_extra_info/sz$_SSLProtocolTransport.get_extra_infocCs||j_dS)N)rQ�
_app_protocol)r#�protocolrrr�set_protocol3sz"_SSLProtocolTransport.set_protocolcCs|jjS)N)rQrX)r#rrr�get_protocol6sz"_SSLProtocolTransport.get_protocolcCs|jS)N)rR)r#rrr�
is_closing9sz _SSLProtocolTransport.is_closingcCsd|_|jj�dS)a
Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        TN)rRrQ�_start_shutdown)r#rrr�close<sz_SSLProtocolTransport.closecCs&|js"tjd|t|d�|j�dS)Nzunclosed transport %r)�source)rR�warnings�warn�ResourceWarningr^)r#rrr�__del__Ksz_SSLProtocolTransport.__del__cCs|jjj�dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        N)rQ�
_transport�
pause_reading)r#rrrreQsz#_SSLProtocolTransport.pause_readingcCs|jjj�dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        N)rQrd�resume_reading)r#rrrrfYsz$_SSLProtocolTransport.resume_readingcCs|jjj||�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        N)rQrd�set_write_buffer_limits)r#ZhighZlowrrrrgasz-_SSLProtocolTransport.set_write_buffer_limitscCs|jjj�S)z,Return the current size of the write buffer.)rQrd�get_write_buffer_size)r#rrrrhvsz+_SSLProtocolTransport.get_write_buffer_sizecCs<t|tttf�s$tdjt|�j���|s,dS|jj	|�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        z/data: expecting a bytes-like instance, got {!r}N)
�
isinstance�bytes�	bytearrayrF�	TypeError�format�typerJrQ�_write_appdata)r#rBrrrr7zsz_SSLProtocolTransport.writecCsdS)zAReturn True if this transport supports write_eof(), False if not.Fr)r#rrr�
can_write_eof�sz#_SSLProtocolTransport.can_write_eofcCs|jj�dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        N)rQ�_abort)r#rrr�abort�sz_SSLProtocolTransport.abort)N)NN)rJrKrLr%rWrZr[r\r^rZPY34rcrerfrgrhr7rprrrrrrrO&s


rOc@s�eZdZdZd(dd�Zd)dd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zd*dd�Zdd�Z
dd�Zdd�Zdd�Zdd �Zd+d"d#�Zd$d%�Zd&d'�ZdS),�SSLProtocolz�SSL protocol.

    Implementation of SSL on top of a socket using incoming and outgoing
    buffers which are ssl.MemoryBIO objects.
    FNTcCs�tdkrtd��|st||�}||_|r6|r6||_nd|_||_t|d�|_tj	�|_
d|_||_||_
||_t|j
|�|_d|_d|_d|_d|_d|_||_dS)Nzstdlib ssl module not available)rrF)rr,rrr�_sslcontext�dict�_extra�collections�deque�_write_backlog�_write_buffer_size�_waiterrPrXrO�_app_transport�_sslpipe�_session_established�
_in_handshake�_in_shutdownrd�_call_connection_made)r#rSZapp_protocolrZwaiterrrZcall_connection_maderrrr%�s,


zSSLProtocol.__init__cCsD|jdkrdS|jj�s:|dk	r.|jj|�n|jjd�d|_dS)N)r{Z	cancelledZ
set_exceptionZ
set_result)r#rDrrr�_wakeup_waiter�s

zSSLProtocol._wakeup_waitercCs&||_t|j|j|j�|_|j�dS)zXCalled when the low-level connection is made.

        Start the SSL handshake.
        N)rdrrtrrr}�_start_handshake)r#�	transportrrr�connection_made�s

zSSLProtocol.connection_madecCs8|jrd|_|jj|jj|�d|_d|_|j|�dS)z�Called when the low-level connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        FN)r~rP�	call_soonrX�connection_lostrdr|r�)r#rDrrrr��szSSLProtocol.connection_lostcCs|jj�dS)z\Called when the low-level transport's buffer goes over
        the high-water mark.
        N)rX�
pause_writing)r#rrrr��szSSLProtocol.pause_writingcCs|jj�dS)z^Called when the low-level transport's buffer drains below
        the low-water mark.
        N)rX�resume_writing)r#rrrr��szSSLProtocol.resume_writingcCs�|jdkrdSy|jj|�\}}WnHtjk
rj}z*|jj�rTtjd||j|j	�|j
�dSd}~XnXx|D]}|jj|�qrWx(|D] }|r�|j
j|�q�|j�Pq�WdS)zXCalled when some SSL data is received.

        The argument is a bytes object.
        Nz%r: SSL error %s (reason %s))r}r.rr;rP�	get_debugr�warningr6rGrqrdr7rX�
data_receivedr])r#rBr0r1�erCrrrr��s"



zSSLProtocol.data_receivedc
CsTzB|jj�rtjd|�|jt�|js@|jj�}|r@tj	d�Wd|j
j�XdS)aCalled when the other end of the low-level stream
        is half-closed.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        z%r received EOFz?returning true from eof_received() has no effect when using sslN)rPr�r�debugr��ConnectionResetErrorrrX�eof_receivedr�rdr^)r#Z	keep_openrrrr�s


zSSLProtocol.eof_receivedcCs4||jkr|j|S|jdk	r,|jj||�S|SdS)N)rvrdrW)r#rUrVrrrrT!s



zSSLProtocol._get_extra_infocCs.|jr
dS|jr|j�nd|_|jd�dS)NTr*)r�rrqro)r#rrrr])s
zSSLProtocol._start_shutdowncCs.|jj|df�|jt|�7_|j�dS)Nr)ryr:rzrE�_process_write_backlog)r#rBrrrro2szSSLProtocol._write_appdatacCsH|jj�r$tjd|�|jj�|_nd|_d|_|jjd�|j	�dS)Nz%r starts SSL handshakeTr*r)r*r)
rPr�rr��time�_handshake_start_timerryr:r�)r#rrrr�7s
zSSLProtocol._start_handshakecCsTd|_|jj}yF|dk	r|�|j�}t|jd�sR|jrR|jjtj	krRtj
||j�Wn~tk
r�}zb|jj
�r�t|tj�r�tjd|dd�ntjd|dd�|jj�t|t�r�|j|�dS�WYdd}~XnX|jj
��r|jj�|j}tjd||d�|jj||j�|j�|d	�|j�r4|jj|j �|j�d|_!|jj"|j#�dS)
NFrz5%r: SSL handshake failed on verifying the certificateT)�exc_infoz%r: SSL handshake failedz%r: SSL handshake took %.1f msg@�@)�peercert�cipher�compressionr&)$rr}r&Zgetpeercertr
rtrr
rZ	CERT_NONEZmatch_hostname�
BaseExceptionrPr�rir<rr�rdr^�	Exceptionr�r�r�r�rv�updater�r�r�rXr�r|r~r�r�)r#Z
handshake_excZsslobjr�rDZdtrrr�_on_handshake_completeCsD




z"SSLProtocol._on_handshake_completecCs>|jdks|jdkrdSy�x�tt|j��D]�}|jd\}}|rT|jj||�\}}n*|rl|jj|j�}d}n|jj|j	�}d}x|D]}|jj
|�q�W|t|�kr�||f|jd<|jjr�|jj�P|jd=|j
t|�8_
q*WWnRtk
�r8}z4|j�r|j|�n|j|d�t|t��s(�WYdd}~XnXdS)NrrzFatal error on SSL transport)rdr}�rangerEryrIr2r�r4�	_finalizer7Z_pausedrfrzr�r�_fatal_errorrir�)r#�irBrHr0rCrDrrrr�ws8

z"SSLProtocol._process_write_backlog�Fatal error on transportcCsXt|tj�r*|jj�rBtjd||dd�n|jj|||j|d��|jrT|jj	|�dS)Nz%r: %sT)r�)�messageZ	exceptionr�rY)
rirZ_FATAL_ERROR_IGNORErPr�rr�Zcall_exception_handlerrdZ_force_close)r#rDr�rrrr��s

zSSLProtocol._fatal_errorcCsd|_|jdk	r|jj�dS)N)r}rdr^)r#rrrr��s
zSSLProtocol._finalizec
Cs(z|jdk	r|jj�Wd|j�XdS)N)rdrrr�)r#rrrrq�s
zSSLProtocol._abort)FNT)N)N)r�)rJrKrLrMr%r�r�r�r�r�r�r�rTr]ror�r�r�r�r�rqrrrrrs�s&
"


	4,
rs)rwr`r�ImportError�rrrr�logrrrrr-r(r3�objectrZ_FlowControlMixinZ	TransportrOZProtocolrsrrrr�<module>s*
wnPK[�R�ӸA�A*__pycache__/proactor_events.cpython-36.pycnu�[���3


 \�O�@s�dZdgZddlZddlZddlmZddlmZddlmZddlmZdd	lm	Z	dd
lm
Z
ddlmZGdd
�d
e
j
e
j�ZGdd�dee
j�ZGdd�dee
j�ZGdd�de�ZGdd�deee
j�ZGdd�deee
j�ZGdd�dej�ZdS)z�Event loop using a proactor and related classes.

A proactor is a "notify-on-completion" multiplexer.  Currently a
proactor is only implemented on Windows with IOCP.
�BaseProactorEventLoop�N�)�base_events)�compat)�	constants)�futures)�sslproto)�
transports)�loggercs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
ejrXdd�Z
ddd�Zdd�Zdd�Zdd�Z�ZS)�_ProactorBasePipeTransportz*Base class for pipe and socket transports.Ncs�t�j||�|j|�||_||_||_d|_d|_d|_d|_	d|_
d|_d|_|jdk	rh|jj
�|jj|jj|�|dk	r�|jjtj|d�dS)NrF)�super�__init__�
_set_extra�_sock�	_protocol�_server�_buffer�	_read_fut�
_write_fut�_pending_write�
_conn_lost�_closing�_eof_writtenZ_attach�_loop�	call_soonZconnection_maderZ_set_result_unless_cancelled)�self�loop�sock�protocol�waiter�extra�server)�	__class__��//usr/lib64/python3.6/asyncio/proactor_events.pyr
s$



z#_ProactorBasePipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jdk	rN|jd|jj��|jdk	rh|jd|j�|jdk	r�|jd|j�|jr�t	|j�}|jd|�|j
r�|jd�dd	j|�S)
N�closed�closingzfd=%szread=%szwrite=%rzwrite_bufsize=%szEOF writtenz<%s>� )r"�__name__r�appendr�filenorrr�lenr�join)r�info�bufsizer#r#r$�__repr__/s"







z#_ProactorBasePipeTransport.__repr__cCs||jd<dS)N�pipe)�_extra)rrr#r#r$rBsz%_ProactorBasePipeTransport._set_extracCs
||_dS)N)r)rrr#r#r$�set_protocolEsz'_ProactorBasePipeTransport.set_protocolcCs|jS)N)r)rr#r#r$�get_protocolHsz'_ProactorBasePipeTransport.get_protocolcCs|jS)N)r)rr#r#r$�
is_closingKsz%_ProactorBasePipeTransport.is_closingcCs^|jr
dSd|_|jd7_|jr@|jdkr@|jj|jd�|jdk	rZ|jj�d|_dS)NTr)	rrrrrr�_call_connection_lostr�cancel)rr#r#r$�closeNs

z _ProactorBasePipeTransport.closecCs*|jdk	r&tjd|t|d�|j�dS)Nzunclosed transport %r)�source)r�warnings�warn�ResourceWarningr7)rr#r#r$�__del__]s
z"_ProactorBasePipeTransport.__del__�Fatal error on pipe transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)�exc_info)�message�	exceptionZ	transportr)
�
isinstancerZ_FATAL_ERROR_IGNOREr�	get_debugr
�debug�call_exception_handlerr�_force_close)r�excr?r#r#r$�_fatal_errorcs
z'_ProactorBasePipeTransport._fatal_errorcCsj|jr
dSd|_|jd7_|jr4|jj�d|_|jrJ|jj�d|_d|_d|_|jj|j	|�dS)NTrr)
rrrr6rrrrrr5)rrFr#r#r$rEps

z'_ProactorBasePipeTransport._force_closecCs^z|jj|�Wdt|jd�r,|jjtj�|jj�d|_|j}|dk	rX|j	�d|_XdS)N�shutdown)
rZconnection_lost�hasattrrrH�socketZ	SHUT_RDWRr7rZ_detach)rrFr!r#r#r$r5s
z0_ProactorBasePipeTransport._call_connection_lostcCs"|j}|jdk	r|t|j�7}|S)N)rrr+)r�sizer#r#r$�get_write_buffer_size�s
z0_ProactorBasePipeTransport.get_write_buffer_size)NNN)r=)r(�
__module__�__qualname__�__doc__r
r/rr2r3r4r7rZPY34r<rGrEr5rL�
__classcell__r#r#)r"r$rs

rcs<eZdZdZd�fdd�	Zdd�Zdd�Zdd	d
�Z�ZS)
�_ProactorReadPipeTransportzTransport for read pipes.Ncs4t�j||||||�d|_d|_|jj|j�dS)NF)rr
�_paused�_reschedule_on_resumerr�
_loop_reading)rrrrrr r!)r"r#r$r
�sz#_ProactorReadPipeTransport.__init__cCs0|js|jrdSd|_|jj�r,tjd|�dS)NTz%r pauses reading)rrRrrBr
rC)rr#r#r$�
pause_reading�s

z(_ProactorReadPipeTransport.pause_readingcCsP|js|jrdSd|_|jr6|jj|j|j�d|_|jj�rLtj	d|�dS)NFz%r resumes reading)
rrRrSrrrTrrBr
rC)rr#r#r$�resume_reading�s
z)_ProactorReadPipeTransport.resume_readingcCs�|jrd|_dSd}�z@yf|dk	rN|j|ks@|jdkr<|js@t�d|_|j�}|jr\d}dS|dkrhdS|jjj|j	d�|_Wn�t
k
r�}z2|js�|j|d�n|jj�r�t
jddd�WYdd}~Xn�tk
r�}z|j|�WYdd}~Xn^tk
�r$}z|j|d�WYdd}~Xn0tjk
�rD|j�s@�YnX|jj|j�Wd|�rl|jj|�n:|dk	�r�|jj��r�t
jd|�|jj�}|�s�|j�XdS)NT�iz"Fatal read error on pipe transportz*Read error on pipe transport while closing)r>z%r received EOF)rRrSrr�AssertionError�resultr�	_proactor�recvr�ConnectionAbortedErrorrGrBr
rC�ConnectionResetErrorrE�OSErrorr�CancelledError�add_done_callbackrTrZ
data_receivedZeof_receivedr7)r�fut�datarFZ	keep_openr#r#r$rT�sL



z(_ProactorReadPipeTransport._loop_reading)NNN)N)	r(rMrNrOr
rUrVrTrPr#r#)r"r$rQ�s
rQc@s:eZdZdZdd�Zd
dd�Zdd�Zd	d
�Zdd�ZdS)�_ProactorBaseWritePipeTransportzTransport for write pipes.cCs�t|tttf�s&dt|�j}t|��|jr4td��|s<dS|j	rj|j	t
jkrXtj
d�|j	d7_	dS|jdkr�|jdks�t�|jt|�d�n.|js�t|�|_|j�n|jj|�|j�dS)Nz3data argument must be a bytes-like object, not '%s'zwrite_eof() already calledzsocket.send() raised exception.r)rb)rA�bytes�	bytearray�
memoryview�typer(�	TypeErrorr�RuntimeErrorrrZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningrrrX�
_loop_writing�_maybe_pause_protocol�extend)rrb�msgr#r#r$�write�s*



z%_ProactorBaseWritePipeTransport.writeNcCs4y�||jkst�d|_d|_|r(|j�|dkr<|j}d|_|st|jrV|jj|jd�|j	rj|j
jtj
�|j�n\|jjj|j
|�|_|jj�s�|jdks�t�t|�|_|jj|j�|j�n|jj|j�Wn\tk
�r}z|j|�WYdd}~Xn0tk
�r.}z|j|d�WYdd}~XnXdS)Nrz#Fatal write error on pipe transport)rrXrrYrrrrr5rrrHrJ�SHUT_WRZ_maybe_resume_protocolrZ�send�doner+r`rkrlr]rEr^rG)r�frbrFr#r#r$rk
s4



z-_ProactorBaseWritePipeTransport._loop_writingcCsdS)NTr#)rr#r#r$�
can_write_eof0sz-_ProactorBaseWritePipeTransport.can_write_eofcCs|j�dS)N)r7)rr#r#r$�	write_eof3sz)_ProactorBaseWritePipeTransport.write_eofcCs|jd�dS)N)rE)rr#r#r$�abort6sz%_ProactorBaseWritePipeTransport.abort)NN)	r(rMrNrOrorkrtrurvr#r#r#r$rc�s$
#rccs$eZdZ�fdd�Zdd�Z�ZS)�_ProactorWritePipeTransportcs4t�j||�|jjj|jd�|_|jj|j�dS)N�)	rr
rrZr[rrr`�_pipe_closed)r�args�kw)r"r#r$r
;sz$_ProactorWritePipeTransport.__init__cCsv|j�rdS|j�dkst�|jr4|jdks0t�dS||jksLt||jf��d|_|jdk	rj|jt��n|j�dS)NrW)	Z	cancelledrYrXrrrrE�BrokenPipeErrorr7)rrar#r#r$ry@s
z(_ProactorWritePipeTransport._pipe_closed)r(rMrNr
ryrPr#r#)r"r$rw:srwc@s eZdZdZdd�Zdd�ZdS)�_ProactorDuplexPipeTransportzTransport for duplex pipes.cCsdS)NFr#)rr#r#r$rtUsz*_ProactorDuplexPipeTransport.can_write_eofcCst�dS)N)�NotImplementedError)rr#r#r$ruXsz&_ProactorDuplexPipeTransport.write_eofN)r(rMrNrOrtrur#r#r#r$r}Psr}cs:eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Z�ZS)�_ProactorSocketTransportz Transport for connected sockets.Ncs$t�j||||||�tj|�dS)N)rr
rZ_set_nodelay)rrrrrr r!)r"r#r$r
asz!_ProactorSocketTransport.__init__cCs�||jd<y|j�|jd<Wn4tjtfk
rP|jj�rLtjd|dd�YnXd|jkr�y|j	�|jd<Wn4tjtfk
r�|jj�r�tjd|dd�YnXdS)NrJZsocknamezgetsockname() failed on %rT)r>�peernamezgetpeername() failed on %r)
r1ZgetsocknamerJ�error�AttributeErrorrrBr
rjZgetpeername)rrr#r#r$rfs



z#_ProactorSocketTransport._set_extracCsdS)NTr#)rr#r#r$rtvsz&_ProactorSocketTransport.can_write_eofcCs2|js|jrdSd|_|jdkr.|jjtj�dS)NT)rrrrrHrJrp)rr#r#r$ruys

z"_ProactorSocketTransport.write_eof)NNN)	r(rMrNrOr
rrtrurPr#r#)r"r$r\srcs�eZdZ�fdd�Zd-dd�Zd.ddddd�dd	�Zd/d
d�Zd0dd
�Zd1dd�Z�fdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd2d d!�Zd"d#�Zd3d%d&�Zd'd(�Zd)d*�Zd+d,�Z�ZS)4rcsHt�j�tjd|jj�||_||_d|_i|_	|j
|�|j�dS)NzUsing proactor: %s)rr
r
rCr"r(rZ�	_selector�_self_reading_future�_accept_futuresZset_loop�_make_self_pipe)rZproactor)r"r#r$r
�s

zBaseProactorEventLoop.__init__NcCst||||||�S)N)r)rrrrr r!r#r#r$�_make_socket_transport�s
z,BaseProactorEventLoop._make_socket_transportF)�server_side�server_hostnamer r!c
Cs<tj�std��tj||||||�}	t|||	||d�|	jS)NzOProactor event loop requires Python 3.5 or newer (ssl.MemoryBIO) to support SSL)r r!)rZ_is_sslproto_availabler~ZSSLProtocolrZ_app_transport)
rZrawsockr�
sslcontextrr�r�r r!Zssl_protocolr#r#r$�_make_ssl_transport�s
z)BaseProactorEventLoop._make_ssl_transportcCst|||||�S)N)r})rrrrr r#r#r$�_make_duplex_pipe_transport�sz1BaseProactorEventLoop._make_duplex_pipe_transportcCst|||||�S)N)rQ)rrrrr r#r#r$�_make_read_pipe_transport�sz/BaseProactorEventLoop._make_read_pipe_transportcCst|||||�S)N)rw)rrrrr r#r#r$�_make_write_pipe_transport�sz0BaseProactorEventLoop._make_write_pipe_transportcsP|j�rtd��|j�rdS|j�|j�|jj�d|_d|_t�j�dS)Nz!Cannot close a running event loop)	Z
is_runningri�	is_closed�_stop_accept_futures�_close_self_piperZr7r�r)r)r"r#r$r7�s
zBaseProactorEventLoop.closecCs|jj||�S)N)rZr[)rr�nr#r#r$�	sock_recv�szBaseProactorEventLoop.sock_recvcCs|jj||�S)N)rZrq)rrrbr#r#r$�sock_sendall�sz"BaseProactorEventLoop.sock_sendallcCs|jj||�S)N)rZZconnect)rrZaddressr#r#r$�sock_connect�sz"BaseProactorEventLoop.sock_connectcCs|jj|�S)N)rZ�accept)rrr#r#r$�sock_accept�sz!BaseProactorEventLoop.sock_acceptcCst�dS)N)r~)rr#r#r$�_socketpair�sz!BaseProactorEventLoop._socketpaircCsL|jdk	r|jj�d|_|jj�d|_|jj�d|_|jd8_dS)Nr)r�r6�_ssockr7�_csock�
_internal_fds)rr#r#r$r��s



z&BaseProactorEventLoop._close_self_pipecCsF|j�\|_|_|jjd�|jjd�|jd7_|j|j�dS)NFr)r�r�r�Zsetblockingr�r�_loop_self_reading)rr#r#r$r��s
z%BaseProactorEventLoop._make_self_pipecCs�y$|dk	r|j�|jj|jd�}WnHtjk
r:dStk
rl}z|jd||d��WYdd}~XnX||_|j	|j
�dS)Niz.Error on reading from the event loop self pipe)r?r@r)rYrZr[r�rr_�	ExceptionrDr�r`r�)rrsrFr#r#r$r��sz(BaseProactorEventLoop._loop_self_readingcCs|jjd�dS)N�)r�rq)rr#r#r$�_write_to_self�sz$BaseProactorEventLoop._write_to_self�dcs&d������fdd�	��j��dS)Ncs"y�|dk	rl|j�\}}�jr,tjd�||���}�dk	rV�j||�dd|i�d�n�j||d|i�d��j�rxdS�jj��}Wn~t	k
r�}zD�j
�dkr��jd|�d���j�n�jr�tjd	�dd
�WYdd}~Xn8t
jk
�r�j�YnX|�j�j
�<|j��dS)Nz#%r got a new connection from %r: %rTr�)r�r r!)r r!rzAccept failed on a socket)r?r@rJzAccept failed on socket %r)r>���)rYZ_debugr
rCr�r�r�rZr�r^r*rDr7rr_r�r`)rsZconnZaddrrrF)r�protocol_factoryrr!rr�r#r$r�s>


z2BaseProactorEventLoop._start_serving.<locals>.loop)N)r)rr�rr�r!Zbacklogr#)rr�rr!rr�r$�_start_serving�s$z$BaseProactorEventLoop._start_servingcCsdS)Nr#)rZ
event_listr#r#r$�_process_events sz%BaseProactorEventLoop._process_eventscCs*x|jj�D]}|j�qW|jj�dS)N)r��valuesr6�clear)rZfuturer#r#r$r�$sz*BaseProactorEventLoop._stop_accept_futurescCs |j�|jj|�|j�dS)N)r�rZ�
_stop_servingr7)rrr#r#r$r�)sz#BaseProactorEventLoop._stop_serving)NNN)N)NN)NN)NN)N)NNr�)r(rMrNr
r�r�r�r�r�r7r�r�r�r�r�r�r�r�r�r�r�r�r�rPr#r#)r"r$r�s4







()rO�__all__rJr9�rrrrrr	�logr
Z_FlowControlMixinZ
BaseTransportrZ
ReadTransportrQZWriteTransportrcrwZ	Transportr}rZ
BaseEventLooprr#r#r#r$�<module>s2MT
#PK[$��dvv,__pycache__/unix_events.cpython-36.opt-1.pycnu�[���3


 \���
@s dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddl
mZdd
l
mZddlmZddlmZdddddgZejdkr�ed��dd�Zy
ejZWnek
�r,dd�ZYnXGdd�dej�Z e!ed��rVdd�Z"nddl#Z#d d�Z"Gd!d"�d"ej$�Z%Gd#d$�d$ej&ej'�Z(e!ed%��r�ej)Z*nddl#Z#d&d'�Z*Gd(d)�d)ej+�Z,Gd*d�d�Z-Gd+d,�d,e-�Z.Gd-d�de.�Z/Gd.d�de.�Z0Gd/d0�d0ej1�Z2e Z3e2Z4dS)1z2Selector event loop for Unix with signal handling.�N�)�base_events)�base_subprocess)�compat)�	constants)�
coroutines)�events)�futures)�selector_events)�	selectors)�
transports)�	coroutine)�logger�SelectorEventLoop�AbstractChildWatcher�SafeChildWatcher�FastChildWatcher�DefaultEventLoopPolicyZwin32z+Signals are not really supported on WindowscCsdS)zDummy signal handler.N�)�signum�framerr�+/usr/lib64/python3.6/asyncio/unix_events.py�_sighandler_noop%srcCs|S)Nr)�pathrrr�<lambda>.srcs�eZdZdZd"�fdd�	Zdd�Z�fdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zd#dd�Zd$dd�Z
ed%dd��Zdd�Zedddd�dd��Zed&dddd�d d!��Z�ZS)'�_UnixSelectorEventLoopzdUnix event loop.

    Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
    Ncst�j|�i|_dS)N)�super�__init__�_signal_handlers)�self�selector)�	__class__rrr7sz_UnixSelectorEventLoop.__init__cCstj�S)N)�socketZ
socketpair)rrrr�_socketpair;sz"_UnixSelectorEventLoop._socketpaircs^t�j�tj�s2xFt|j�D]}|j|�qWn(|jrZtjd|�d�t	|d�|jj
�dS)NzClosing the loop z@ on interpreter shutdown stage, skipping signal handlers removal)�source)r�close�sys�
is_finalizing�listr�remove_signal_handler�warnings�warn�ResourceWarning�clear)r�sig)r!rrr%>s
z_UnixSelectorEventLoop.closecCs"x|D]}|sq|j|�qWdS)N)�_handle_signal)r�datarrrr�_process_self_dataLs
z)_UnixSelectorEventLoop._process_self_datac+GsHtj|�stj|�rtd��|j|�|j�ytj|jj	��Wn2t
tfk
rt}ztt
|���WYdd}~XnXtj|||�}||j|<ytj|t�tj|d�Wn�tk
�rB}zz|j|=|j�sytjd�Wn4t
tfk
�r}ztjd|�WYdd}~XnX|jtjk�r0tdj|���n�WYdd}~XnXdS)z�Add a handler for a signal.  UNIX only.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        z3coroutines cannot be used with add_signal_handler()NFrzset_wakeup_fd(-1) failed: %szsig {} cannot be caught���)rZiscoroutineZiscoroutinefunction�	TypeError�
_check_signalZ
_check_closed�signal�
set_wakeup_fdZ_csock�fileno�
ValueError�OSError�RuntimeError�strrZHandlerr�siginterruptr�info�errno�EINVAL�format)rr.�callback�args�exc�handleZnexcrrr�add_signal_handlerSs0



z)_UnixSelectorEventLoop.add_signal_handlercCs8|jj|�}|dkrdS|jr*|j|�n
|j|�dS)z2Internal helper that is the actual signal handler.N)r�getZ
_cancelledr)Z_add_callback_signalsafe)rr.rDrrrr/�sz%_UnixSelectorEventLoop._handle_signalc&Cs�|j|�y|j|=Wntk
r*dSX|tjkr>tj}ntj}ytj||�Wn@tk
r�}z$|jtj	kr�t
dj|���n�WYdd}~XnX|js�ytjd�Wn2t
tfk
r�}ztjd|�WYdd}~XnXdS)zwRemove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        Fzsig {} cannot be caughtNrzset_wakeup_fd(-1) failed: %sTr2)r4r�KeyErrorr5�SIGINT�default_int_handler�SIG_DFLr9r>r?r:r@r6r8rr=)rr.ZhandlerrCrrrr)�s(

z,_UnixSelectorEventLoop.remove_signal_handlercCsHt|t�stdj|���d|ko,tjknsDtdj|tj���dS)z�Internal helper to validate a signal.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        zsig must be an int, not {!r}rzsig {} out of range(1, {})N)�
isinstance�intr3r@r5�NSIGr8)rr.rrrr4�s

z$_UnixSelectorEventLoop._check_signalcCst|||||�S)N)�_UnixReadPipeTransport)r�pipe�protocol�waiter�extrarrr�_make_read_pipe_transport�sz0_UnixSelectorEventLoop._make_read_pipe_transportcCst|||||�S)N)�_UnixWritePipeTransport)rrOrPrQrRrrr�_make_write_pipe_transport�sz1_UnixSelectorEventLoop._make_write_pipe_transportc	ks�tj���}
|j�}t||||||||f||d�|	��}|
j|j�|j|�y|EdHWn&tk
r~}
z
|
}WYdd}
~
XnXd}|dk	r�|j�|j	�EdH|�WdQRX|S)N)rQrR)
r�get_child_watcherZ
create_future�_UnixSubprocessTransport�add_child_handlerZget_pid�_child_watcher_callback�	Exceptionr%Z_wait)rrPrB�shell�stdin�stdout�stderr�bufsizerR�kwargs�watcherrQ�transprC�errrrr�_make_subprocess_transport�s$




z1_UnixSelectorEventLoop._make_subprocess_transportcCs|j|j|�dS)N)Zcall_soon_threadsafeZ_process_exited)r�pid�
returncoderbrrrrY�sz._UnixSelectorEventLoop._child_watcher_callback)�ssl�sock�server_hostnameccs�|r|dkr&td��n|dk	r&td��|dk	r�|dk	r>td��tjtjtjd�}y |jd�|j||�EdHWq�|j��Yq�XnB|dkr�td��|jtjks�tj	|j
�r�tdj|���|jd�|j||||�EdH\}}||fS)Nz/you have to pass server_hostname when using sslz+server_hostname is only meaningful with sslz3path and sock can not be specified at the same timerFzno path and sock were specifiedz2A UNIX Domain Stream Socket was expected, got {!r})
r8r"�AF_UNIX�SOCK_STREAM�setblockingZsock_connectr%�familyr�_is_stream_socket�typer@Z_create_connection_transport)r�protocol_factoryrrgrhri�	transportrPrrr�create_unix_connection�s8


z-_UnixSelectorEventLoop.create_unix_connection�d)rh�backlogrgc
!Cs�t|t�rtd��|dk	�r0|dk	r,td��t|�}tjtjtj�}|dd
kr�y tj	t
j|�j�rnt
j|�WnBt
k
r�Yn0tk
r�}ztjd||�WYdd}~XnXy|j|�Wnjtk
�r}z8|j�|jtjk�rdj|�}ttj|�d�n�WYdd}~Xn|j��YnXn>|dk�rBtd��|jtjk�s`tj|j��rntdj|���tj||g�}	|j|�|jd	�|j||||	�|	S)Nz*ssl argument must be an SSLContext or Nonez3path and sock can not be specified at the same timer�z2Unable to check or remove stale UNIX socket %r: %rzAddress {!r} is already in usez-path was not specified, and no sock specifiedz2A UNIX Domain Stream Socket was expected, got {!r}F)rru)rK�boolr3r8�_fspathr"rjrk�stat�S_ISSOCK�os�st_mode�remove�FileNotFoundErrorr9r�errorZbindr%r>Z
EADDRINUSEr@rmrrnroZServerZlistenrlZ_start_serving)
rrprrhrtrgrcrC�msgZserverrrr�create_unix_serversP

 




z)_UnixSelectorEventLoop.create_unix_server)N)NN)NN)N)N)�__name__�
__module__�__qualname__�__doc__rr#r%r1rEr/r)r4rSrUr
rdrYrrr��
__classcell__rr)r!rr1s,-
 


%r�set_blockingcCstj|d�dS)NF)rzr�)�fdrrr�_set_nonblockingBsr�cCs,tj|tj�}|tjB}tj|tj|�dS)N)�fcntlZF_GETFLrz�
O_NONBLOCKZF_SETFL)r��flagsrrrr�Gs
cs�eZdZdZd �fdd�	Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Ze
jrhdd�Zd!dd�Zdd�Zdd�Z�ZS)"rN�iNcs�t�j|�||jd<||_||_|j�|_||_d|_t	j
|j�j}tj
|�pbtj|�pbtj|�s~d|_d|_d|_td��t|j�|jj|jj|�|jj|jj|j|j�|dk	r�|jjtj|d�dS)NrOFz)Pipe transport is for pipes/sockets only.)rr�_extra�_loop�_piper7�_fileno�	_protocol�_closingrz�fstatr{rx�S_ISFIFOry�S_ISCHRr8r��	call_soon�connection_made�_add_reader�_read_readyr	�_set_result_unless_cancelled)r�looprOrPrQrR�mode)r!rrrQs,






z_UnixReadPipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�t|jdd�}|jdk	r�|dk	r�tj	||jt
j�}|r�|jd�q�|jd�n |jdk	r�|jd�n
|jd�dd	j|�S)
N�closed�closingzfd=%s�	_selector�polling�idle�openz<%s>� )
r!r�r��appendr�r��getattrr�r
�_test_selector_eventrZ
EVENT_READ�join)rr=r r�rrr�__repr__ns$




z_UnixReadPipeTransport.__repr__cCs�ytj|j|j�}WnDttfk
r,Yn�tk
rX}z|j|d�WYdd}~Xn^X|rl|jj	|�nJ|j
j�r�tj
d|�d|_|j
j|j�|j
j|jj�|j
j|jd�dS)Nz"Fatal read error on pipe transportz%r was closed by peerT)rz�readr��max_size�BlockingIOError�InterruptedErrorr9�_fatal_errorr�Z
data_receivedr��	get_debugrr=r��_remove_readerr�Zeof_received�_call_connection_lost)rr0rCrrrr��s
z"_UnixReadPipeTransport._read_readycCs|jj|j�dS)N)r�r�r�)rrrr�
pause_reading�sz$_UnixReadPipeTransport.pause_readingcCs|jj|j|j�dS)N)r�r�r�r�)rrrr�resume_reading�sz%_UnixReadPipeTransport.resume_readingcCs
||_dS)N)r�)rrPrrr�set_protocol�sz#_UnixReadPipeTransport.set_protocolcCs|jS)N)r�)rrrr�get_protocol�sz#_UnixReadPipeTransport.get_protocolcCs|jS)N)r�)rrrr�
is_closing�sz!_UnixReadPipeTransport.is_closingcCs|js|jd�dS)N)r��_close)rrrrr%�sz_UnixReadPipeTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)r$)r�r*r+r,r%)rrrr�__del__�s
z_UnixReadPipeTransport.__del__�Fatal error on pipe transportcCsZt|t�r4|jtjkr4|jj�rLtjd||dd�n|jj||||j	d��|j
|�dS)Nz%r: %sT)�exc_info)�message�	exceptionrqrP)rKr9r>ZEIOr�r�r�debug�call_exception_handlerr�r�)rrCr�rrrr��s
z#_UnixReadPipeTransport._fatal_errorcCs(d|_|jj|j�|jj|j|�dS)NT)r�r�r�r�r�r�)rrCrrrr��sz_UnixReadPipeTransport._closecCs4z|jj|�Wd|jj�d|_d|_d|_XdS)N)r��connection_lostr�r%r�)rrCrrrr��s
z,_UnixReadPipeTransport._call_connection_losti)NN)r�)r�r�r�r�rr�r�r�r�r�r�r�r%r�PY34r�r�r�r�r�rr)r!rrNMs
rNcs�eZdZd%�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zejr|dd�Zdd�Zd&dd �Zd'd!d"�Zd#d$�Z�ZS)(rTNc
s�t�j||�||jd<||_|j�|_||_t�|_d|_	d|_
tj|j�j
}tj|�}tj|�}tj|�}	|px|px|	s�d|_d|_d|_td��t|j�|jj|jj|�|	s�|r�tjjd�r�|jj|jj|j|j�|dk	r�|jjtj|d�dS)NrOrFz?Pipe transport is only for pipes, sockets and character devices�aix)rrr�r�r7r�r��	bytearray�_buffer�
_conn_lostr�rzr�r{rxr�r�ryr8r�r�r�r�r&�platform�
startswithr�r�r	r�)
rr�rOrPrQrRr�Zis_charZis_fifoZ	is_socket)r!rrr�s2






z _UnixWritePipeTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�t|jdd�}|jdk	r�|dk	r�tj	||jt
j�}|r�|jd�n
|jd�|j�}|jd|�n |jdk	r�|jd�n
|jd�d	d
j
|�S)Nr�r�zfd=%sr�r�r�z
bufsize=%sr�z<%s>r�)r!r�r�r�r�r�r�r�r
r�rZEVENT_WRITE�get_write_buffer_sizer�)rr=r r�r_rrrr��s(





z _UnixWritePipeTransport.__repr__cCs
t|j�S)N)�lenr�)rrrrr�sz-_UnixWritePipeTransport.get_write_buffer_sizecCs6|jj�rtjd|�|jr*|jt��n|j�dS)Nz%r was closed by peer)r�r�rr=r�r��BrokenPipeError)rrrrr�s

z#_UnixWritePipeTransport._read_readycCst|t�rt|�}|sdS|js&|jrN|jtjkr<tjd�|jd7_dS|j	�s�yt
j|j|�}WnTt
tfk
r�d}Yn:tk
r�}z|jd7_|j|d�dSd}~XnX|t|�kr�dS|dkr�t|�|d�}|jj|j|j�|j	|7_	|j�dS)Nz=pipe closed by peer or os.write(pipe, data) raised exception.rrz#Fatal write error on pipe transport)rKr��
memoryviewr�r�rZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr�warningr�rz�writer�r�r�rZr�r�r�Z_add_writer�_write_readyZ_maybe_pause_protocol)rr0�nrCrrrr�s2

z_UnixWritePipeTransport.writecCs�ytj|j|j�}Wnjttfk
r,Yn�tk
r~}z8|jj�|jd7_|j	j
|j�|j|d�WYdd}~XnfX|t|j�kr�|jj�|j	j
|j�|j
�|jr�|j	j|j�|jd�dS|dkr�|jd|�=dS)Nrz#Fatal write error on pipe transportr)rzr�r�r�r�r�rZr-r�r��_remove_writerr�r�Z_maybe_resume_protocolr�r�r�)rr�rCrrrr�>s&


z$_UnixWritePipeTransport._write_readycCsdS)NTr)rrrr�
can_write_eofXsz%_UnixWritePipeTransport.can_write_eofcCs8|jr
dSd|_|js4|jj|j�|jj|jd�dS)NT)r�r�r�r�r�r�r�)rrrr�	write_eof[sz!_UnixWritePipeTransport.write_eofcCs
||_dS)N)r�)rrPrrrr�dsz$_UnixWritePipeTransport.set_protocolcCs|jS)N)r�)rrrrr�gsz$_UnixWritePipeTransport.get_protocolcCs|jS)N)r�)rrrrr�jsz"_UnixWritePipeTransport.is_closingcCs|jdk	r|jr|j�dS)N)r�r�r�)rrrrr%msz_UnixWritePipeTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)r$)r�r*r+r,r%)rrrrr�vs
z_UnixWritePipeTransport.__del__cCs|jd�dS)N)r�)rrrr�abort|sz_UnixWritePipeTransport.abort�Fatal error on pipe transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)r�)r�r�rqrP)
rKrZ_FATAL_ERROR_IGNOREr�r�rr�r�r�r�)rrCr�rrrr�s
z$_UnixWritePipeTransport._fatal_errorcCsFd|_|jr|jj|j�|jj�|jj|j�|jj|j|�dS)NT)	r�r�r�r�r�r-r�r�r�)rrCrrrr��s
z_UnixWritePipeTransport._closecCs4z|jj|�Wd|jj�d|_d|_d|_XdS)N)r�r�r�r%r�)rrCrrrr��s
z-_UnixWritePipeTransport._call_connection_lost)NN)r�)N)r�r�r�rr�r�r�r�r�r�r�r�r�r�r%rr�r�r�r�r�r�r�rr)r!rrT�s$%	!	

rT�set_inheritablecCsNttdd�}tj|tj�}|s4tj|tj||B�ntj|tj||@�dS)NZ
FD_CLOEXECr)r�r�ZF_GETFDZF_SETFD)r�ZinheritableZcloexec_flag�oldrrr�_set_inheritable�s
r�c@seZdZdd�ZdS)rWc		Ksvd}|tjkr*|jj�\}}t|j�d�tj|f||||d|d�|��|_|dk	rr|j�t	|j
�d|d�|j_dS)NF)r[r\r]r^Zuniversal_newlinesr_�wb)�	buffering)�
subprocess�PIPEr�r#r�r7�Popen�_procr%r��detachr\)	rrBr[r\r]r^r_r`Zstdin_wrrr�_start�s
z_UnixSubprocessTransport._startN)r�r�r�r�rrrrrW�srWc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)raHAbstract base class for monitoring child processes.

    Objects derived from this class monitor a collection of subprocesses and
    report their termination or interruption by a signal.

    New callbacks are registered with .add_child_handler(). Starting a new
    process must be done within a 'with' block to allow the watcher to suspend
    its activity until the new process if fully registered (this is needed to
    prevent a race condition in some implementations).

    Example:
        with watcher:
            proc = subprocess.Popen("sleep 1")
            watcher.add_child_handler(proc.pid, callback)

    Notes:
        Implementations of this class must be thread-safe.

        Since child watcher objects may catch the SIGCHLD signal and call
        waitpid(-1), there should be only one active object per process.
    cGs
t��dS)aRegister a new child handler.

        Arrange for callback(pid, returncode, *args) to be called when
        process 'pid' terminates. Specifying another callback for the same
        process replaces the previous handler.

        Note: callback() must be thread-safe.
        N)�NotImplementedError)rrerArBrrrrX�s	z&AbstractChildWatcher.add_child_handlercCs
t��dS)z�Removes the handler for process 'pid'.

        The function returns True if the handler was successfully removed,
        False if there was nothing to remove.N)r�)rrerrr�remove_child_handler�sz)AbstractChildWatcher.remove_child_handlercCs
t��dS)z�Attach the watcher to an event loop.

        If the watcher was previously attached to an event loop, then it is
        first detached before attaching to the new loop.

        Note: loop may be None.
        N)r�)rr�rrr�attach_loop�sz AbstractChildWatcher.attach_loopcCs
t��dS)zlClose the watcher.

        This must be called to make sure that any underlying resource is freed.
        N)r�)rrrrr%�szAbstractChildWatcher.closecCs
t��dS)zdEnter the watcher's context and allow starting new processes

        This function must return selfN)r�)rrrr�	__enter__szAbstractChildWatcher.__enter__cCs
t��dS)zExit the watcher's contextN)r�)r�a�b�crrr�__exit__	szAbstractChildWatcher.__exit__N)
r�r�r�r�rXr�r�r%r�r�rrrrr�s
c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�BaseChildWatchercCsd|_i|_dS)N)r��
_callbacks)rrrrrszBaseChildWatcher.__init__cCs|jd�dS)N)r�)rrrrr%szBaseChildWatcher.closecCs
t��dS)N)r�)r�expected_pidrrr�_do_waitpidszBaseChildWatcher._do_waitpidcCs
t��dS)N)r�)rrrr�_do_waitpid_allsz BaseChildWatcher._do_waitpid_allcCsf|jdk	r$|dkr$|jr$tjdt�|jdk	r<|jjtj�||_|dk	rb|jtj|j	�|j
�dS)NzCA loop is being detached from a child watcher with pending handlers)r�r�r*r+�RuntimeWarningr)r5�SIGCHLDrE�	_sig_chldr�)rr�rrrr�s
zBaseChildWatcher.attach_loopcCsFy|j�Wn4tk
r@}z|jjd|d��WYdd}~XnXdS)Nz$Unknown exception in SIGCHLD handler)r�r�)r�rZr�r�)rrCrrrr�1szBaseChildWatcher._sig_chldcCs2tj|�rtj|�Stj|�r*tj|�S|SdS)N)rz�WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS)r�statusrrr�_compute_returncode=s



z$BaseChildWatcher._compute_returncodeN)
r�r�r�rr%r�r�r�r�r�rrrrr�sr�csPeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)rad'Safe' child watcher implementation.

    This implementation avoids disrupting other code spawning processes by
    polling explicitly each process in the SIGCHLD handler instead of calling
    os.waitpid(-1).

    This is a safe solution but it has a significant overhead when handling a
    big number of children (O(n) each time SIGCHLD is raised)
    cs|jj�t�j�dS)N)r�r-rr%)r)r!rrr%Vs
zSafeChildWatcher.closecCs|S)Nr)rrrrr�ZszSafeChildWatcher.__enter__cCsdS)Nr)rr�r�r�rrrr�]szSafeChildWatcher.__exit__cGs.|jdkrtd��||f|j|<|j|�dS)NzICannot add child handler, the child watcher does not have a loop attached)r�r:r�r�)rrerArBrrrrX`s

z"SafeChildWatcher.add_child_handlercCs&y|j|=dStk
r dSXdS)NTF)r�rG)rrerrrr�ks
z%SafeChildWatcher.remove_child_handlercCs"xt|j�D]}|j|�qWdS)N)r(r�r�)rrerrrr�rsz SafeChildWatcher._do_waitpid_allcCs�ytj|tj�\}}Wn(tk
r>|}d}tjd|�Yn0X|dkrLdS|j|�}|jj�rntj	d||�y|j
j|�\}}Wn.tk
r�|jj�r�tjd|dd�YnX|||f|��dS)N�z8Unknown child process pid %d, will report returncode 255rz$process %s exited with returncode %sz'Child watcher got an unexpected pid: %rT)r�)
rz�waitpid�WNOHANG�ChildProcessErrorrr�r�r�r�r�r��poprG)rr�rer�rfrArBrrrr�ws*


zSafeChildWatcher._do_waitpid)r�r�r�r�r%r�r�rXr�r�r�r�rr)r!rrKs	csTeZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)raW'Fast' child watcher implementation.

    This implementation reaps every terminated processes by calling
    os.waitpid(-1) directly, possibly breaking other code spawning processes
    and waiting for their termination.

    There is no noticeable overhead when handling a big number of children
    (O(1) each time a child terminates).
    cs$t�j�tj�|_i|_d|_dS)Nr)rr�	threadingZLock�_lock�_zombies�_forks)r)r!rrr�s

zFastChildWatcher.__init__cs"|jj�|jj�t�j�dS)N)r�r-r�rr%)r)r!rrr%�s

zFastChildWatcher.closec
Cs$|j�|jd7_|SQRXdS)Nr)r�r�)rrrrr��szFastChildWatcher.__enter__c
CsV|j�:|jd8_|js$|jr(dSt|j�}|jj�WdQRXtjd|�dS)Nrz5Caught subprocesses termination from unknown pids: %s)r�r�r�r;r-rr�)rr�r�r�Zcollateral_victimsrrrr��s
zFastChildWatcher.__exit__cGsl|jdkrtd��|j�:y|jj|�}Wn"tk
rL||f|j|<dSXWdQRX|||f|��dS)NzICannot add child handler, the child watcher does not have a loop attached)r�r:r�r�r�rGr�)rrerArBrfrrrrX�s
z"FastChildWatcher.add_child_handlercCs&y|j|=dStk
r dSXdS)NTF)r�rG)rrerrrr��s
z%FastChildWatcher.remove_child_handlercCs�x�ytjdtj�\}}Wntk
r,dSX|dkr:dS|j|�}|j�vy|jj|�\}}WnBtk
r�|j	r�||j
|<|jj�r�t
jd||�wd}YnX|jj�r�t
jd||�WdQRX|dkr�t
jd||�q|||f|��qWdS)Nrrz,unknown process %s exited with returncode %sz$process %s exited with returncode %sz8Caught subprocess termination from unknown pid: %d -> %dr2)rzr�r�r�r�r�r�r�rGr�r�r�r�rr�r�)rrer�rfrArBrrrr��s6





z FastChildWatcher._do_waitpid_all)r�r�r�r�rr%r�r�rXr�r�r�rr)r!rr�s	csHeZdZdZeZ�fdd�Zdd�Z�fdd�Zdd	�Z	d
d�Z
�ZS)�_UnixDefaultEventLoopPolicyz:UNIX event loop policy with a watcher for child processes.cst�j�d|_dS)N)rr�_watcher)r)r!rrrs
z$_UnixDefaultEventLoopPolicy.__init__c
CsHtj�8|jdkr:t�|_ttj�tj�r:|jj|j	j
�WdQRXdS)N)rr�r�rrKr��current_thread�_MainThreadr��_localr�)rrrr�
_init_watchers
z)_UnixDefaultEventLoopPolicy._init_watchercs6t�j|�|jdk	r2ttj�tj�r2|jj|�dS)z�Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        N)r�set_event_loopr�rKr�r�rr�)rr�)r!rrrs
z*_UnixDefaultEventLoopPolicy.set_event_loopcCs|jdkr|j�|jS)zzGet the watcher for child processes.

        If not yet set, a SafeChildWatcher object is automatically created.
        N)r�r)rrrrrV&s
z-_UnixDefaultEventLoopPolicy.get_child_watchercCs|jdk	r|jj�||_dS)z$Set the watcher for child processes.N)r�r%)rrarrr�set_child_watcher0s

z-_UnixDefaultEventLoopPolicy.set_child_watcher)r�r�r�r�rZ
_loop_factoryrrrrVrr�rr)r!rr�s
r�)5r�r>rzr5r"rxr�r&r�r*�rrrrrrr	r
rrr
�logr�__all__r��ImportErrorr�fspathrw�AttributeErrorZBaseSelectorEventLoopr�hasattrr�r�Z
ReadTransportrNZ_FlowControlMixinZWriteTransportrTr�r�ZBaseSubprocessTransportrWrr�rrZBaseDefaultEventLoopPolicyr�rrrrrr�<module>sn


O
F=On2PK[�»��+__pycache__/subprocess.cpython-36.opt-1.pycnu�[���3


 \��@s�ddgZddlZddlmZddlmZddlmZddlmZdd	lmZdd
l	m
Z
ejZejZej
Z
Gdd�dejej�ZGd
d�d�Zeddddejfdd��Zeddddejd�dd��ZdS)�create_subprocess_exec�create_subprocess_shell�N�)�events)�	protocols)�streams)�tasks)�	coroutine)�loggercsPeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)�SubprocessStreamProtocolz0Like StreamReaderProtocol, but for a subprocess.cs<t�j|d�||_d|_|_|_d|_d|_g|_dS)N)�loopF)	�super�__init__�_limit�stdin�stdout�stderr�
_transport�_process_exited�	_pipe_fds)�self�limitr)�	__class__��*/usr/lib64/python3.6/asyncio/subprocess.pyrsz!SubprocessStreamProtocol.__init__cCsf|jjg}|jdk	r$|jd|j�|jdk	r>|jd|j�|jdk	rX|jd|j�ddj|�S)Nzstdin=%rz	stdout=%rz	stderr=%rz<%s>� )r�__name__r�appendrr�join)r�inforrr�__repr__s



z!SubprocessStreamProtocol.__repr__cCs�||_|jd�}|dk	rDtj|j|jd�|_|jj|�|jj	d�|jd�}|dk	r�tj|j|jd�|_
|j
j|�|jj	d�|jd�}|dk	r�tj||d|jd�|_dS)Nr)rr�r)�protocol�readerr)
r�get_pipe_transportr�StreamReaderr�_looprZ
set_transportrrr�StreamWriterr)r�	transportZstdout_transportZstderr_transportZstdin_transportrrr�connection_made(s&


z(SubprocessStreamProtocol.connection_madecCs:|dkr|j}n|dkr |j}nd}|dk	r6|j|�dS)Nrr!)rrZ	feed_data)r�fd�datar#rrr�pipe_data_received@sz+SubprocessStreamProtocol.pipe_data_receivedcCs�|dkr,|j}|dk	r|j�|j|�dS|dkr<|j}n|dkrL|j}nd}|dkrt|dkrj|j�n
|j|�||jkr�|jj|�|j	�dS)Nrrr!)
r�closeZconnection_lostrrZfeed_eofZ
set_exceptionr�remove�_maybe_close_transport)rr*�exc�piper#rrr�pipe_connection_lostJs$



z-SubprocessStreamProtocol.pipe_connection_lostcCsd|_|j�dS)NT)rr/)rrrr�process_exitedasz'SubprocessStreamProtocol.process_exitedcCs(t|j�dkr$|jr$|jj�d|_dS)Nr)�lenrrrr-)rrrrr/es
z/SubprocessStreamProtocol._maybe_close_transport)r�
__module__�__qualname__�__doc__rr r)r,r2r3r/�
__classcell__rr)rrrs

rc@s~eZdZdd�Zdd�Zedd��Zedd��Zd	d
�Z	dd�Z
d
d�Zedd��Zedd��Z
edd��Zeddd��ZdS)�ProcesscCs8||_||_||_|j|_|j|_|j|_|j�|_dS)N)rZ	_protocolr&rrrZget_pid�pid)rr(r"rrrrrlszProcess.__init__cCsd|jj|jfS)Nz<%s %s>)rrr:)rrrrr uszProcess.__repr__cCs
|jj�S)N)rZget_returncode)rrrr�
returncodexszProcess.returncodeccs|jj�EdHS)zdWait until the process exit and return the process return code.

        This method is a coroutine.N)rZ_wait)rrrr�wait|szProcess.waitcCs|jj|�dS)N)r�send_signal)r�signalrrrr=�szProcess.send_signalcCs|jj�dS)N)r�	terminate)rrrrr?�szProcess.terminatecCs|jj�dS)N)r�kill)rrrrr@�szProcess.killccs�|jj�}|jj|�|r,tjd|t|��y|jj�EdHWn8tt	fk
rx}z|rhtjd||�WYdd}~XnX|r�tjd|�|jj
�dS)Nz%%r communicate: feed stdin (%s bytes)z%r communicate: stdin got %rz%r communicate: close stdin)r&�	get_debugr�writer
�debugr4Zdrain�BrokenPipeError�ConnectionResetErrorr-)r�inputrCr0rrr�_feed_stdin�s
 zProcess._feed_stdincCsdS)Nr)rrrr�_noop�sz
Process._noopccs�|jj|�}|dkr|j}n|j}|jj�rJ|dkr8dnd}tjd||�|j�EdH}|jj�r�|dkrndnd}tjd||�|j	�|S)Nr!rrrz%r communicate: read %sz%r communicate: close %s)
rr$rrr&rAr
rC�readr-)rr*r(�stream�name�outputrrr�_read_stream�s

zProcess._read_streamNccs�|dk	r|j|�}n|j�}|jdk	r2|jd�}n|j�}|jdk	rP|jd�}n|j�}tj||||jd�EdH\}}}|j�EdH||fS)Nrr!)r)	rGrHrrMrrZgatherr&r<)rrFrrrrrr�communicate�s


zProcess.communicate)N)rr5r6rr �propertyr;r	r<r=r?r@rGrHrMrNrrrrr9ks	r9c
+sP�dkrtj����fdd�}�j||f|||d�|��EdH\}}	t||	��S)Ncst��d�S)N)rr)rr)rrrr�<lambda>�sz)create_subprocess_shell.<locals>.<lambda>)rrr)r�get_event_loopZsubprocess_shellr9)
�cmdrrrrr�kwds�protocol_factoryr(r"r)rrrr�s)rrrrrc/sT�dkrtj����fdd�}�j||f|�|||d�|��EdH\}	}
t|	|
��S)Ncst��d�S)N)rr)rr)rrrrrP�sz(create_subprocess_exec.<locals>.<lambda>)rrr)rrQZsubprocess_execr9)Zprogramrrrrr�argsrSrTr(r"r)rrrr�s)�__all__�
subprocess�rrrrZ
coroutinesr	�logr
�PIPEZSTDOUTZDEVNULLZFlowControlMixinZSubprocessProtocolrr9Z_DEFAULT_LIMITrrrrrr�<module>s(X]PK[	��[?[?+__pycache__/test_utils.cpython-36.opt-2.pycnu�[���3


 \�:�
@s�ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlmZddlmZddlmZmZyddlZWnek
r�dZYnXddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lm Z ddl!m"Z"ej#dk�rDddl$m%Z%nddlm%Z%dd�Z&e&d�Z'e&d�Z(dd�Z)dd�Z*dQdd�Z+dd�Z,Gdd�de�Z-Gd d!�d!e�Z.Gd"d#�d#�Z/Gd$d%�d%e/e.�Z0d&d'�d(d)�Z1e2ed*��rVGd+d,�d,ej3e�Z4Gd-d.�d.e4e�Z5Gd/d0�d0e5�Z6Gd1d2�d2e/e6�Z7d3d4�Z8ej9d5d6��Z:ej9d&d'�d7d8��Z;ej9d9dd&d:�d;d<��Z<d=d>�Z=Gd?d@�d@ej>�Z?GdAdB�dBej@�ZAdCdD�ZBGdEdF�dFeC�ZDdGdH�ZEGdIdJ�dJejF�ZFej9dKdL��ZGejHejIejJfdMdN�ZKdOdP�ZLdS)R�N)�mock)�
HTTPServer)�WSGIRequestHandler�
WSGIServer�)�base_events)�compat)�events)�futures)�	selectors)�tasks)�	coroutine)�logger)�supportZwin32)�
socketpaircCs`ttd�r*tjjtj|�}tjj|�r*|Stjjtjjtj�d|�}tjj|�rT|St	|��dS)N�
TEST_HOME_DIR�test)
�hasattrr�os�path�joinr�isfile�dirname�__file__�FileNotFoundError)�filename�fullname�r�*/usr/lib64/python3.6/asyncio/test_utils.py�	data_file-s
rzssl_cert.pemzssl_key.pemcCstdkrdStjtj�SdS)N)�ssl�
SSLContextZPROTOCOL_SSLv23rrrr�dummy_ssl_context<sr"c
Cs@tdd��}|�}|j|�}d|_z|j|�Wd|j�XdS)NcSsdS)Nrrrrr�onceDszrun_briefly.<locals>.onceF)r
Zcreate_taskZ_log_destroy_pending�run_until_complete�close)�loopr#�gen�trrr�run_brieflyCs
r)�cCsTtj�|}xB|�sN|dk	r8|tj�}|dkr8tj��|jtjd|d��qWdS)Nrg����MbP?)r&)�timer
�TimeoutErrorr$rZsleep)r&Zpred�timeoutZdeadlinerrr�	run_untilRsr.cCs|j|j�|j�dS)N)Z	call_soon�stopZrun_forever)r&rrr�run_once\sr0c@seZdZdd�Zdd�ZdS)�SilentWSGIRequestHandlercCstj�S)N)�io�StringIO)�selfrrr�
get_stderrisz#SilentWSGIRequestHandler.get_stderrcGsdS)Nr)r4�format�argsrrr�log_messagelsz$SilentWSGIRequestHandler.log_messageN)�__name__�
__module__�__qualname__r5r8rrrrr1gsr1cs(eZdZdZ�fdd�Zdd�Z�ZS)�SilentWSGIServer�cs"t�j�\}}|j|j�||fS)N)�super�get_request�
settimeout�request_timeout)r4�request�client_addr)�	__class__rrr?tszSilentWSGIServer.get_requestcCsdS)Nr)r4rB�client_addressrrr�handle_erroryszSilentWSGIServer.handle_error)r9r:r;rAr?rF�
__classcell__rr)rDrr<psr<c@seZdZdd�ZdS)�SSLWSGIServerMixincCs^t}t}tj�}|j||�|j|dd�}y|j|||�|j�Wntk
rXYnXdS)NT)Zserver_side)	�ONLYKEY�ONLYCERTr r!Zload_cert_chainZwrap_socketZRequestHandlerClassr%�OSError)r4rBrEZkeyfileZcertfile�contextZssockrrr�finish_requestsz!SSLWSGIServerMixin.finish_requestN)r9r:r;rMrrrrrH}srHc@seZdZdS)�
SSLWSGIServerN)r9r:r;rrrrrN�srNF)�use_sslc
#svdd�}|r|n|}||t���j|��j�_tj�fdd�d�}|j�z
�VWd�j��j�|j	�XdS)NcSsd}dg}|||�dgS)Nz200 OK�Content-type�
text/plainsTest message)rPrQr)�environZstart_responseZstatusZheadersrrr�app�s
z_run_test_server.<locals>.appcs�jdd�S)Ng�������?)Z
poll_interval)Z
serve_foreverr)�httpdrr�<lambda>�sz"_run_test_server.<locals>.<lambda>)�target)
r1Zset_appZserver_address�address�	threadingZThread�start�shutdownZserver_closer)rWrO�
server_cls�server_ssl_clsrSZserver_classZ
server_threadr)rTr�_run_test_server�s


r]ZAF_UNIXc@seZdZdd�ZdS)�UnixHTTPServercCstjj|�d|_d|_dS)Nz	127.0.0.1�P)�socketserver�UnixStreamServer�server_bindZserver_nameZserver_port)r4rrrrb�szUnixHTTPServer.server_bindN)r9r:r;rbrrrrr^�sr^cs(eZdZdZdd�Z�fdd�Z�ZS)�UnixWSGIServerr=cCstj|�|j�dS)N)r^rbZ
setup_environ)r4rrrrb�s
zUnixWSGIServer.server_bindcs"t�j�\}}|j|j�|dfS)N�	127.0.0.1�)rdre)r>r?r@rA)r4rBrC)rDrrr?�szUnixWSGIServer.get_request)r9r:r;rArbr?rGrr)rDrrc�srcc@seZdZdd�ZdS)�SilentUnixWSGIServercCsdS)Nr)r4rBrErrrrF�sz!SilentUnixWSGIServer.handle_errorN)r9r:r;rFrrrrrf�srfc@seZdZdS)�UnixSSLWSGIServerN)r9r:r;rrrrrg�srgc	Cstj��}|jSQRXdS)N)�tempfileZNamedTemporaryFile�name)�filerrr�gen_unix_socket_path�s
rkccs<t�}z
|VWdytj|�Wntk
r4YnXXdS)N)rkr�unlinkrK)rrrr�unix_socket_path�s
rmc
cs,t��}t||ttd�EdHWdQRXdS)N)rWrOr[r\)rmr]rfrg)rOrrrr�run_test_unix_server�srnz	127.0.0.1)�host�portrOccst||f|ttd�EdHdS)N)rWrOr[r\)r]r<rN)rorprOrrr�run_test_server�s
rqcCsPi}x4t|�D](}|jd�r(|jd�r(qtdd�||<qWtd|f|j|��S)N�__)�return_valueZTestProtocol)�dir�
startswith�endswith�MockCallback�type�	__bases__)�baseZdctrirrr�make_test_protocol�sr{c@s6eZdZdd�Zddd�Zdd�Zdd	�Zd
d�ZdS)
�TestSelectorcCs
i|_dS)N)�keys)r4rrr�__init__szTestSelector.__init__NcCstj|d||�}||j|<|S)Nr)rZSelectorKeyr})r4�fileobjr	�data�keyrrr�registers
zTestSelector.registercCs|jj|�S)N)r}�pop)r4rrrr�
unregisterszTestSelector.unregistercCsgS)Nr)r4r-rrr�selectszTestSelector.selectcCs|jS)N)r})r4rrr�get_mapszTestSelector.get_map)N)r9r:r;r~r�r�r�r�rrrrr|s

r|cs�eZdZd,�fdd�	Zdd�Zdd�Z�fdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Z�fd$d%�Z�fd&d'�Zd(d)�Zd*d+�Z�ZS)-�TestLoopNcsvt�j�|dkr"dd�}d|_nd|_|�|_t|j�d|_d|_g|_t�|_	i|_
i|_|j�t
j�|_dS)Ncss
dVdS)Nrrrrrr',szTestLoop.__init__.<locals>.genFTrg��&�.>)r>r~�_check_on_close�_gen�next�_timeZ_clock_resolution�_timersr|Z	_selector�readers�writers�reset_counters�weakref�WeakValueDictionary�_transports)r4r')rDrrr~(s

zTestLoop.__init__cCs|jS)N)r�)r4rrrr+?sz
TestLoop.timecCs|r|j|7_dS)N)r�)r4�advancerrr�advance_timeBszTestLoop.advance_timecsBt�j�|jr>y|jjd�Wntk
r4Yn
Xtd��dS)NrzTime generator is not finished)r>r%r�r��send�
StopIteration�AssertionError)r4)rDrrr%Gs
zTestLoop.closecGstj|||�|j|<dS)N)r	�Handler�)r4�fd�callbackr7rrr�_add_readerQszTestLoop._add_readercCs0|j|d7<||jkr(|j|=dSdSdS)NrTF)�remove_reader_countr�)r4r�rrr�_remove_readerTs

zTestLoop._remove_readercGsh||jkrtd|�d���|j|}|j|krDtd|j�d|����|j|krdtd|j�d|����dS)Nzfd z is not registeredzunexpected callback: z != zunexpected callback args: )r�r�Z	_callbackZ_args)r4r�r�r7�handlerrr�
assert_reader\s



zTestLoop.assert_readercCs||jkrtd|�d���dS)Nzfd z is registered)r�r�)r4r�rrr�assert_no_readergs
zTestLoop.assert_no_readercGstj|||�|j|<dS)N)r	r�r�)r4r�r�r7rrr�_add_writerkszTestLoop._add_writercCs0|j|d7<||jkr(|j|=dSdSdS)NrTF)�remove_writer_countr�)r4r�rrr�_remove_writerns

zTestLoop._remove_writercGs|j|}dS)N)r�)r4r�r�r7r�rrr�
assert_writervs
zTestLoop.assert_writercCs8y|j|}Wntk
r"YnXtdj||���dS)Nz.File descriptor {!r} is used by transport {!r})r��KeyError�RuntimeErrorr6)r4r�Z	transportrrr�_ensure_fd_no_transport~sz TestLoop._ensure_fd_no_transportcGs|j|�|j||f|��S)N)r�r�)r4r�r�r7rrr�
add_reader�s
zTestLoop.add_readercCs|j|�|j|�S)N)r�r�)r4r�rrr�
remove_reader�s
zTestLoop.remove_readercGs|j|�|j||f|��S)N)r�r�)r4r�r�r7rrr�
add_writer�s
zTestLoop.add_writercCs|j|�|j|�S)N)r�r�)r4r�rrr�
remove_writer�s
zTestLoop.remove_writercCstjt�|_tjt�|_dS)N)�collections�defaultdict�intr�r�)r4rrrr��szTestLoop.reset_counterscs:t�j�x$|jD]}|jj|�}|j|�qWg|_dS)N)r>�	_run_oncer�r�r�r�)r4�whenr�)rDrrr��s

zTestLoop._run_oncecs |jj|�t�j||f|��S)N)r��appendr>�call_at)r4r�r�r7)rDrrr��szTestLoop.call_atcCsdS)Nr)r4Z
event_listrrr�_process_events�szTestLoop._process_eventscCsdS)Nr)r4rrr�_write_to_self�szTestLoop._write_to_self)N)r9r:r;r~r+r�r%r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rGrr)rDrr�s*

r�cKstjfddgi|��S)N�spec�__call__)rZMock)�kwargsrrrrw�srwc@seZdZdd�ZdS)�MockPatterncCsttjt|�|tj��S)N)�bool�re�search�str�S)r4�otherrrr�__eq__�szMockPattern.__eq__N)r9r:r;r�rrrrr��s	r�cCs$tj|�}|dkr td|f��|S)Nzunable to get the source of %r)r	Z_get_function_source�
ValueError)�func�sourcerrr�get_function_source�s
r�c@sVeZdZedd��Zdd�dd�Zddd	�Zd
d�Zdd
�Zdd�Z	e
jsRdd�ZdS)�TestCasecCs&|j}|dk	r|jdd�|j�dS)NT)�wait)Z_default_executorrZr%)r&Zexecutorrrr�
close_loop�szTestCase.close_loopT)�cleanupcCs tjd�|r|j|j|�dS)N)r	�set_event_loopZ
addCleanupr�)r4r&r�rrrr��s
zTestCase.set_event_loopNcCst|�}|j|�|S)N)r�r�)r4r'r&rrr�
new_test_loop�s
zTestCase.new_test_loopcCs|jt_dS)N)�_get_running_loopr	)r4rrr�unpatch_get_running_loop�sz!TestCase.unpatch_get_running_loopcCs tj|_dd�t_tj�|_dS)NcSsdS)NrrrrrrU�sz TestCase.setUp.<locals>.<lambda>)r	r�rZthreading_setup�_thread_cleanup)r4rrr�setUp�s
zTestCase.setUpcCsB|j�tjd�|jtj�d�|j�tj|j	�tj
�dS)N)NNN)r�r	r�ZassertEqual�sys�exc_infoZ
doCleanupsrZthreading_cleanupr�Z
reap_children)r4rrr�tearDown�s
zTestCase.tearDowncOsGdd�d�}|�S)Nc@seZdZdd�Zdd�ZdS)z!TestCase.subTest.<locals>.EmptyCMcSsdS)Nr)r4rrr�	__enter__�sz+TestCase.subTest.<locals>.EmptyCM.__enter__cWsdS)Nr)r4�excrrr�__exit__�sz*TestCase.subTest.<locals>.EmptyCM.__exit__N)r9r:r;r�r�rrrr�EmptyCM�sr�r)r4r7r�r�rrr�subTest�szTestCase.subTest)N)
r9r:r;�staticmethodr�r�r�r�r�r�rZPY34r�rrrrr��s

r�ccs2tj}ztjtjd�dVWdtj|�XdS)Nr)r�levelZsetLevel�loggingZCRITICAL)Z	old_levelrrr�disable_logger�s

r�cCs*tjtj�}||_||_||_d|j_|S)Ng)rZ	MagicMock�socket�protorx�familyZ
gettimeoutrs)r�rxr�Zsockrrr�mock_nonblocking_socketsr�cCstjddd�S)Nz'asyncio.sslproto._is_sslproto_availableF)rs)rZpatchrrrr�force_legacy_ssl_supportsr�)r*)Mr��
contextlibr2r�rr�r�r`r�rhrXr+Zunittestr�rZhttp.serverrZwsgiref.simple_serverrrr �ImportErrorrerrr	r
rrZ
coroutinesr
�logrrr�platformZ
windows_utilsrrrJrIr"r)r.r0r1r<rHrNr]rrar^rcrfrgrk�contextmanagerrmrnrqr{ZBaseSelectorr|Z
BaseEventLoopr�rwr�r�r�r�r�ZIPPROTO_TCPZSOCK_STREAMZAF_INETr�r�rrrr�<module>s�


	


4
PK[�����__pycache__/log.cpython-36.pycnu�[���3


 \|�@sdZddlZeje�ZdS)zLogging configuration.�N)�__doc__ZloggingZ	getLogger�__package__Zlogger�rr�#/usr/lib64/python3.6/asyncio/log.py�<module>sPK[G��4GG+__pycache__/base_tasks.cpython-36.opt-2.pycnu�[���3


 \��@sDddlZddlZddlmZddlmZdd�Zdd�Zd	d
�ZdS)�N�)�base_futures)�
coroutinescCsTtj|�}|jrd|d<tj|j�}|jdd|�|jdk	rP|jdd|j�|S)NZ
cancellingrrz	coro=<%s>�zwait_for=%r)rZ_future_repr_infoZ_must_cancelrZ_format_coroutine�_coro�insertZ_fut_waiter)�task�info�coro�r�*/usr/lib64/python3.6/asyncio/base_tasks.py�_task_repr_infos

r
cCs�g}y|jj}Wntk
r,|jj}YnX|dk	rxx6|dk	rl|dk	rZ|dkrRP|d8}|j|�|j}q8W|j�nL|jdk	r�|jj}x8|dk	r�|dk	r�|dkr�P|d8}|j|j	�|j
}q�W|S)Nrr)r�cr_frame�AttributeError�gi_frame�append�f_back�reverse�
_exception�
__traceback__�tb_frame�tb_next)r�limitZframes�f�tbrrr�_task_get_stacks0






rcCs�g}t�}xj|j|d�D]Z}|j}|j}|j}|j}	||krP|j|�tj|�tj	|||j
�}
|j|||	|
f�qW|j}|s�t
d||d�n*|dk	r�t
d||d�nt
d||d�tj||d�|dk	r�x$tj|j|�D]}
t
|
|dd�q�WdS)N)rzNo stack for %r)�filez)Traceback for %r (most recent call last):z%Stack for %r (most recent call last):�)r�end)�setZ	get_stack�f_lineno�f_code�co_filename�co_name�add�	linecache�
checkcache�getline�	f_globalsrr�print�	traceback�
print_list�format_exception_only�	__class__)rrr�extracted_listZcheckedr�lineno�co�filename�name�line�excrrr�_task_print_stack3s0


r5)r%r*rrrr
rr5rrrr�<module>sPK[s�58�s�s*__pycache__/selector_events.cpython-36.pycnu�[���3


 \���
@s<dZdgZddlZddlZddlZddlZddlZddlZyddlZWne	k
r^dZYnXddl
mZddl
mZddl
m
Z
ddl
mZdd	l
mZdd
l
mZddl
mZddl
mZdd
lmZddlmZdd�ZGdd�dej�ZGdd�dejej�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)z�Event loop using a selector and related classes.

A selector is a "notify-when-ready" multiplexer.  For a subclass which
also includes support for signal handling, see the unix_events sub-module.
�BaseSelectorEventLoop�N�)�base_events)�compat)�	constants)�events)�futures)�	selectors)�
transports)�sslproto)�	coroutine)�loggercCs6y|j|�}Wntk
r"dSXt|j|@�SdS)NF)�get_key�KeyError�boolr)�selector�fdZevent�key�r�//usr/lib64/python3.6/asyncio/selector_events.py�_test_selector_event s
rcsreZdZdZdO�fdd�	ZdPddd�dd�ZdQddddd	�d
d�Zddddd	�dd
�ZdRdd�Z�fdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�ZdSdd �ZdTd!d"�ZedUd#d$��Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd9d:�Zd;d<�Zd=d>�Z ed?d@��Z!dAdB�Z"dCdD�Z#dEdF�Z$dGdH�Z%dIdJ�Z&dKdL�Z'dMdN�Z(�Z)S)VrzJSelector event loop.

    See events.EventLoop for API specification.
    NcsFt�j�|dkrtj�}tjd|jj�||_|j	�t
j�|_dS)NzUsing selector: %s)
�super�__init__r	ZDefaultSelectorr
�debug�	__class__�__name__�	_selector�_make_self_pipe�weakref�WeakValueDictionary�_transports)�selfr)rrrr1s
zBaseSelectorEventLoop.__init__)�extra�servercCst||||||�S)N)�_SelectorSocketTransport)r!�sock�protocol�waiterr"r#rrr�_make_socket_transport;s
z,BaseSelectorEventLoop._make_socket_transportF)�server_side�server_hostnamer"r#c

CsNtj�s"|j||||||||d�Stj||||||�}	t|||	||d�|	jS)N)r)r*r"r#)r"r#)rZ_is_sslproto_available�_make_legacy_ssl_transportZSSLProtocolr$Z_app_transport)
r!�rawsockr&�
sslcontextr'r)r*r"r#Zssl_protocolrrr�_make_ssl_transport@s

z)BaseSelectorEventLoop._make_ssl_transportc	
Cst|||||||||�	S)N)�_SelectorSslTransport)	r!r,r&r-r'r)r*r"r#rrrr+Os
z0BaseSelectorEventLoop._make_legacy_ssl_transportcCst||||||�S)N)�_SelectorDatagramTransport)r!r%r&�addressr'r"rrr�_make_datagram_transportYsz.BaseSelectorEventLoop._make_datagram_transportcsL|j�rtd��|j�rdS|j�t�j�|jdk	rH|jj�d|_dS)Nz!Cannot close a running event loop)Z
is_running�RuntimeError�	is_closed�_close_self_piper�closer)r!)rrrr6^s


zBaseSelectorEventLoop.closecCst�dS)N)�NotImplementedError)r!rrr�_socketpairisz!BaseSelectorEventLoop._socketpaircCsB|j|jj��|jj�d|_|jj�d|_|jd8_dS)Nr)�_remove_reader�_ssock�filenor6�_csock�
_internal_fds)r!rrrr5ls

z&BaseSelectorEventLoop._close_self_pipecCsN|j�\|_|_|jjd�|jjd�|jd7_|j|jj�|j�dS)NFr)r8r:r<�setblockingr=�_add_readerr;�_read_from_self)r!rrrrts
z%BaseSelectorEventLoop._make_self_pipecCsdS)Nr)r!�datarrr�_process_self_data|sz(BaseSelectorEventLoop._process_self_datacCsVxPy |jjd�}|sP|j|�Wqtk
r8wYqtk
rLPYqXqWdS)Ni)r:�recvrB�InterruptedError�BlockingIOError)r!rArrrr@sz%BaseSelectorEventLoop._read_from_selfcCsJ|j}|dk	rFy|jd�Wn(tk
rD|jr@tjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketT)�exc_info)r<�send�OSError�_debugr
r)r!Zcsockrrr�_write_to_self�sz$BaseSelectorEventLoop._write_to_self�dcCs |j|j�|j|||||�dS)N)r?r;�_accept_connection)r!�protocol_factoryr%r-r#�backlogrrr�_start_serving�sz$BaseSelectorEventLoop._start_servingcCs�x�t|�D]�}y0|j�\}}|jr2tjd|||�|jd�Wn�tttfk
rXdSt	k
r�}	z^|	j
t
jt
jt
j
t
jfkr�|jd|	|d��|j|j��|jtj|j|||||�n�WYdd}	~	Xq
Xd|i}
|j|||
||�}|j|�q
WdS)Nz#%r got a new connection from %r: %rFz&socket.accept() out of system resource)�message�	exception�socket�peername)�range�acceptrJr
rr>rErD�ConnectionAbortedErrorrI�errnoZEMFILEZENFILEZENOBUFSZENOMEM�call_exception_handlerr9r;Z
call_laterrZACCEPT_RETRY_DELAYrP�_accept_connection2Zcreate_task)r!rNr%r-r#rO�_�conn�addr�excr"rVrrrrM�s4


z(BaseSelectorEventLoop._accept_connectionccs�d}d}yj|�}|j�}|r6|j||||d||d�}n|j|||||d�}y|EdHWn|j��YnXWn\tk
r�}	z@|jr�d|	d�}
|dk	r�||
d<|dk	r�||
d<|j|
�WYdd}	~	XnXdS)NT)r'r)r"r#)r'r"r#z3Error on transport creation for incoming connection)rQrRr&�	transport)�
create_futurer.r(r6�	ExceptionrJrY)r!rNr\r"r-r#r&r_r'r^�contextrrrrZ�s4z)BaseSelectorEventLoop._accept_connection2cCs@y|j|}Wntk
r"YnX|j�s<tdj||���dS)Nz.File descriptor {!r} is used by transport {!r})r r�
is_closingr3�format)r!rr_rrr�_ensure_fd_no_transport�sz-BaseSelectorEventLoop._ensure_fd_no_transportc	
Gs�|j�tj|||�}y|jj|�}Wn*tk
rP|jj|tj|df�Yn>X|j|j	}\}}|jj
||tjB||f�|dk	r�|j�dS)N)�
_check_closedr�Handlerrr�registerr	�
EVENT_READrA�modify�cancel)	r!r�callback�args�handler�mask�reader�writerrrrr?�s
z!BaseSelectorEventLoop._add_readerc
Cs�|j�rdSy|jj|�}Wntk
r0dSX|j|j}\}}|tjM}|sb|jj|�n|jj	||d|f�|dk	r�|j
�dSdSdS)NFT)r4rrrrrAr	ri�
unregisterrjrk)r!rrrorprqrrrr9sz$BaseSelectorEventLoop._remove_readerc	
Gs�|j�tj|||�}y|jj|�}Wn*tk
rP|jj|tjd|f�Yn>X|j|j	}\}}|jj
||tjB||f�|dk	r�|j�dS)N)rfrrgrrrrhr	�EVENT_WRITErArjrk)	r!rrlrmrnrrorprqrrr�_add_writers
z!BaseSelectorEventLoop._add_writerc
Cs�|j�rdSy|jj|�}Wntk
r0dSX|j|j}\}}|tjM}|sb|jj|�n|jj	|||df�|dk	r�|j
�dSdSdS)zRemove a writer callback.FNT)r4rrrrrAr	rsrrrjrk)r!rrrorprqrrr�_remove_writer,sz$BaseSelectorEventLoop._remove_writercGs|j|�|j||f|��S)zAdd a reader callback.)rer?)r!rrlrmrrr�
add_readerCs
z BaseSelectorEventLoop.add_readercCs|j|�|j|�S)zRemove a reader callback.)rer9)r!rrrr�
remove_readerHs
z#BaseSelectorEventLoop.remove_readercGs|j|�|j||f|��S)zAdd a writer callback..)rert)r!rrlrmrrr�
add_writerMs
z BaseSelectorEventLoop.add_writercCs|j|�|j|�S)zRemove a writer callback.)reru)r!rrrr�
remove_writerRs
z#BaseSelectorEventLoop.remove_writercCs6|jr|j�dkrtd��|j�}|j|d||�|S)z�Receive data from the socket.

        The return value is a bytes object representing the data received.
        The maximum amount of data to be received at once is specified by
        nbytes.

        This method is a coroutine.
        rzthe socket must be non-blockingN)rJ�
gettimeout�
ValueErrorr`�
_sock_recv)r!r%�n�futrrr�	sock_recvWs
	zBaseSelectorEventLoop.sock_recvcCs�|dk	r|j|�|j�rdSy|j|�}Wn`ttfk
rb|j�}|j||j||||�Yn6tk
r�}z|j	|�WYdd}~XnX|j
|�dS)N)rw�	cancelledrCrErDr;rvr|ra�
set_exception�
set_result)r!r~�
registered_fdr%r}rArr^rrrr|fs
z BaseSelectorEventLoop._sock_recvcCsF|jr|j�dkrtd��|j�}|r8|j|d||�n
|jd�|S)a�Send data to the socket.

        The socket must be connected to a remote socket. This method continues
        to send data from data until either all data has been sent or an
        error occurs. None is returned on success. On error, an exception is
        raised, and there is no way to determine how much data, if any, was
        successfully processed by the receiving end of the connection.

        This method is a coroutine.
        rzthe socket must be non-blockingN)rJrzr{r`�
_sock_sendallr�)r!r%rAr~rrr�sock_sendall{s
z"BaseSelectorEventLoop.sock_sendallcCs�|dk	r|j|�|j�rdSy|j|�}WnDttfk
rHd}Yn*tk
rp}z|j|�dSd}~XnX|t|�kr�|jd�n.|r�||d�}|j	�}|j
||j||||�dS)Nr)ryr�rHrErDrar��lenr�r;rxr�)r!r~r�r%rAr}r^rrrrr��s"

z#BaseSelectorEventLoop._sock_sendallccs�|jr|j�dkrtd��ttd�s2|jtjkrptj||j|j	|d�}|j
�sZ|EdH|j�d\}}}}}|j�}|j
|||�|EdHS)zTConnect to a remote socket at address.

        This method is a coroutine.
        rzthe socket must be non-blocking�AF_UNIX)�family�proto�loopN)rJrzr{�hasattrrSr�r�rZ_ensure_resolvedr��done�resultr`�
_sock_connect)r!r%r1Zresolvedr[r~rrr�sock_connect�s
z"BaseSelectorEventLoop.sock_connectcCs�|j�}y|j|�Wnjttfk
rV|jtj|j|��|j||j	|||�Yn6t
k
r�}z|j|�WYdd}~XnX|jd�dS)N)
r;ZconnectrErDZadd_done_callback�	functools�partial�_sock_connect_donerx�_sock_connect_cbrar�r�)r!r~r%r1rr^rrrr��sz#BaseSelectorEventLoop._sock_connectcCs|j|�dS)N)ry)r!rr~rrrr��sz(BaseSelectorEventLoop._sock_connect_donecCs�|j�rdSy,|jtjtj�}|dkr6t|d|f��WnBttfk
rPYn6tk
rz}z|j	|�WYdd}~XnX|j
d�dS)NrzConnect call failed %s)r�Z
getsockoptrSZ
SOL_SOCKETZSO_ERRORrIrErDrar�r�)r!r~r%r1�errr^rrrr��sz&BaseSelectorEventLoop._sock_connect_cbcCs4|jr|j�dkrtd��|j�}|j|d|�|S)a|Accept a connection.

        The socket must be bound to an address and listening for connections.
        The return value is a pair (conn, address) where conn is a new socket
        object usable to send and receive data on the connection, and address
        is the address bound to the socket on the other end of the connection.

        This method is a coroutine.
        rzthe socket must be non-blockingF)rJrzr{r`�_sock_accept)r!r%r~rrr�sock_accept�s

z!BaseSelectorEventLoop.sock_acceptcCs�|j�}|r|j|�|j�r"dSy|j�\}}|jd�WnVttfk
rh|j||j|d|�Yn:t	k
r�}z|j
|�WYdd}~XnX|j||f�dS)NFT)r;rwr�rVr>rErDrvr�rar�r�)r!r~Z
registeredr%rr\r1r^rrrr��s
z"BaseSelectorEventLoop._sock_acceptcCs�x~|D]v\}}|j|j}\}}|tj@rN|dk	rN|jrD|j|�n
|j|�|tj@r|dk	r|jrr|j|�q|j|�qWdS)N)	�fileobjrAr	riZ
_cancelledr9Z
_add_callbackrsru)r!Z
event_listrror�rprqrrr�_process_events�s
z%BaseSelectorEventLoop._process_eventscCs|j|j��|j�dS)N)r9r;r6)r!r%rrr�
_stop_servingsz#BaseSelectorEventLoop._stop_serving)N)N)N)NNN)NNrL)NNrL)NN)*r�
__module__�__qualname__�__doc__rr(r.r+r2r6r8r5rrBr@rKrPrMrrZrer?r9rtrurvrwrxryrr|r�r�r�r�r�r�r�r�r�r��
__classcell__rr)rrr+sT



(#cs�eZdZdZeZdZd �fdd�	Zdd�Zdd	�Z	d
d�Z
dd
�Zdd�Zdd�Z
ejr`dd�Zd!dd�Zdd�Zdd�Zdd�Zdd�Z�ZS)"�_SelectorTransport�iNcs�t�j||�||jd<|j�|jd<d|jkrdy|j�|jd<Wn tjk
rbd|jd<YnX||_|j�|_	||_
d|_||_|j
�|_d|_d|_|jdk	r�|jj�||j|j	<dS)NrSZsocknamerTTrF)rr�_extraZgetsocknameZgetpeernamerS�error�_sockr;�_sock_fd�	_protocol�_protocol_connected�_server�_buffer_factory�_buffer�
_conn_lost�_closingZ_attachr )r!r�r%r&r"r#)rrrrs&





z_SelectorTransport.__init__cCs�|jjg}|jdkr |jd�n|jr0|jd�|jd|j�|jdk	r�|jj�r�t|jj	|jt
j�}|rz|jd�n
|jd�t|jj	|jt
j�}|r�d}nd}|j
�}|jd||f�d	d
j|�S)N�closed�closingzfd=%szread=pollingz	read=idle�pollingZidlezwrite=<%s, bufsize=%s>z<%s>� )rrr��appendr�r��_loopr4rrr	rirs�get_write_buffer_size�join)r!�infor��state�bufsizerrr�__repr__2s*



z_SelectorTransport.__repr__cCs|jd�dS)N)�_force_close)r!rrr�abortNsz_SelectorTransport.abortcCs
||_dS)N)r�)r!r&rrr�set_protocolQsz_SelectorTransport.set_protocolcCs|jS)N)r�)r!rrr�get_protocolTsz_SelectorTransport.get_protocolcCs|jS)N)r�)r!rrrrcWsz_SelectorTransport.is_closingcCsT|jr
dSd|_|jj|j�|jsP|jd7_|jj|j�|jj|jd�dS)NTr)	r�r�r9r�r�r�ru�	call_soon�_call_connection_lost)r!rrrr6Zsz_SelectorTransport.closecCs,|jdk	r(tjd|t|d�|jj�dS)Nzunclosed transport %r)�source)r��warnings�warn�ResourceWarningr6)r!rrr�__del__hs
z_SelectorTransport.__del__�Fatal error on transportcCsPt|tj�r*|jj�rBtjd||dd�n|jj||||jd��|j	|�dS)Nz%r: %sT)rG)rQrRr_r&)
�
isinstancerZ_FATAL_ERROR_IGNOREr��	get_debugr
rrYr�r�)r!r^rQrrr�_fatal_errorns
z_SelectorTransport._fatal_errorcCsd|jr
dS|jr(|jj�|jj|j�|jsBd|_|jj|j�|jd7_|jj|j	|�dS)NTr)
r�r��clearr�rur�r�r9r�r�)r!r^rrrr�|s
z_SelectorTransport._force_closecCsVz|jr|jj|�Wd|jj�d|_d|_d|_|j}|dk	rP|j�d|_XdS)N)r�r�Zconnection_lostr�r6r�r�Z_detach)r!r^r#rrrr��s
z(_SelectorTransport._call_connection_lostcCs
t|j�S)N)r�r�)r!rrrr��sz(_SelectorTransport.get_write_buffer_sizecGs"|jr
dS|jj||f|��dS)N)r�r�r?)r!rrlrmrrrr?�sz_SelectorTransport._add_readeri)NN)r�)rr�r��max_size�	bytearrayr�r�rr�r�r�r�rcr6rZPY34r�r�r�r�r�r?r�rr)rrr�s"

r�csVeZdZd�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
�ZS)r$Ncsrt�j|||||�d|_d|_tj|j�|jj|j	j
|�|jj|j|j|j
�|dk	rn|jjtj|d�dS)NF)rr�_eof�_pausedrZ_set_nodelayr�r�r�r��connection_mader?r��_read_readyr�_set_result_unless_cancelled)r!r�r%r&r'r"r#)rrrr�s

z!_SelectorSocketTransport.__init__cCs>|js|jrdSd|_|jj|j�|jj�r:tjd|�dS)NTz%r pauses reading)r�r�r�r9r�r�r
r)r!rrr�
pause_reading�s
z&_SelectorSocketTransport.pause_readingcCsB|js|jrdSd|_|j|j|j�|jj�r>tjd|�dS)NFz%r resumes reading)	r�r�r?r�r�r�r�r
r)r!rrr�resume_reading�s
z'_SelectorSocketTransport.resume_readingcCs�|jr
dSy|jj|j�}WnDttfk
r4Yn|tk
r`}z|j|d�WYdd}~XnPX|rt|jj	|�n<|j
j�r�tj
d|�|jj�}|r�|j
j|j�n|j�dS)Nz$Fatal read error on socket transportz%r received EOF)r�r�rCr�rErDrar�r��
data_receivedr�r�r
r�eof_receivedr9r�r6)r!rAr^�	keep_openrrrr��s 

z$_SelectorSocketTransport._read_readycCs�t|tttf�s"tdt|�j��|jr0td��|s8dS|j	rf|j	t
jkrTtj
d�|j	d7_	dS|js�y|jj|�}WnBttfk
r�Yn@tk
r�}z|j|d�dSd}~XnX||d�}|s�dS|jj|j|j�|jj|�|j�dS)Nz1data argument must be a bytes-like object, not %rz%Cannot call write() after write_eof()zsocket.send() raised exception.rz%Fatal write error on socket transport)r��bytesr��
memoryview�	TypeError�typerr�r3r�r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningr�r�rHrErDrar�r�rtr��_write_ready�extend�_maybe_pause_protocol)r!rAr}r^rrr�write�s4
z_SelectorSocketTransport.writecCs�|jstd��|jrdSy|jj|j�}Wn\ttfk
rBYn�tk
r�}z*|jj	|j
�|jj�|j|d�WYdd}~XnTX|r�|jd|�=|j
�|js�|jj	|j
�|jr�|jd�n|jr�|jjtj�dS)NzData should not be emptyz%Fatal write error on socket transport)r��AssertionErrorr�r�rHrErDrar�rur�r�r��_maybe_resume_protocolr�r�r��shutdownrS�SHUT_WR)r!r}r^rrrr�s(
z%_SelectorSocketTransport._write_readycCs.|js|jrdSd|_|js*|jjtj�dS)NT)r�r�r�r�r�rSr�)r!rrr�	write_eofs
z"_SelectorSocketTransport.write_eofcCsdS)NTr)r!rrr�
can_write_eof sz&_SelectorSocketTransport.can_write_eof)NNN)rr�r�rr�r�r�r�r�r�r�r�rr)rrr$�s#r$csdeZdZeZd�fdd�	Zddd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
�ZS)r/NFc

s�tdkrtd��|s tj||�}|dd�}
|r<|r<||
d<|j|f|
�}t�j|||||	�d|_||_||_	||_
d|_|jj
|d�|jj�r�tjd|�|jj�}nd}|j|�dS)Nzstdlib ssl module not availableF)r)Zdo_handshake_on_connectr*)r-z%r starts SSL handshake)�sslr3rZ_create_transport_contextZwrap_socketrrr��_server_hostname�_waiter�_sslcontextr�r��updater�r�r
r�time�
_on_handshake)
r!r�r,r&r-r'r)r*r"r#Zwrap_kwargsZsslsock�
start_time)rrrr(s*

z_SelectorSslTransport.__init__cCsD|jdkrdS|jj�s:|dk	r.|jj|�n|jjd�d|_dS)N)r�r�r�r�)r!r^rrr�_wakeup_waiterLs

z$_SelectorSslTransport._wakeup_waiterc"Cs$y|jj�Wn�tjk
r8|jj|j|j|�dStjk
r`|jj	|j|j|�dSt
k
r�}z`|jj�r�tj
d|dd�|jj|j�|jj|j�|jj�|j|�t|t�r�dS�WYdd}~XnX|jj|j�|jj|j�|jj�}t|jd��s�|j�r�|jjtjk�r�ytj||j�WnRtk
�r�}z4|jj��rjtj
d|dd�|jj�|j|�dSd}~XnX|jj||jj�|jj�|jd�d|_d|_ |jj|j|j!�d|_"|jj#|j$j%|�|jj#|j�|jj��r |jj&�|}tj'd||d	�dS)
Nz%r: SSL handshake failedT)rGZcheck_hostnamez1%r: SSL handshake failed on matching the hostname)�peercert�cipher�compressionZ
ssl_objectFz%r: SSL handshake took %.1f msg@�@)(r�Zdo_handshaker��SSLWantReadErrorr�r?r�r��SSLWantWriteErrorrt�
BaseExceptionr�r
r�r9rur6r�r�raZgetpeercertr�r�r�Zverify_modeZ	CERT_NONEZmatch_hostnamer�r�r�r��_read_wants_write�_write_wants_readr�r�r�r�r�r�r)r!r�r^r�Zdtrrrr�Vsb













z#_SelectorSslTransport._on_handshakecCsJ|jrtd��|jrtd��d|_|jj|j�|jj�rFtjd|�dS)Nz#Cannot pause_reading() when closingzAlready pausedTz%r pauses reading)	r�r3r�r�r9r�r�r
r)r!rrrr��s
z#_SelectorSslTransport.pause_readingcCsJ|jstd��d|_|jrdS|jj|j|j�|jj�rFtj	d|�dS)Nz
Not pausedFz%r resumes reading)
r�r3r�r�r?r�r�r�r
r)r!rrrr��s
z$_SelectorSslTransport.resume_readingcCs"|jr
dS|jr6d|_|j�|jr6|jj|j|j�y|jj|j	�}Wn�t
ttj
fk
rdYn�tjk
r�d|_|jj|j�|jj|j|j�Yn�tk
r�}z|j|d�WYdd}~XnTX|r�|jj|�n@z4|jj�r�tjd|�|jj�}|�rtjd�Wd|j�XdS)NFTz!Fatal read error on SSL transportz%r received EOFz?returning true from eof_received() has no effect when using ssl)r�r�r�r�r�rtr�r�rCr�rErDr�r�r�r�r9rar�r�r�r�r
rr�r�r6)r!rAr^r�rrrr��s4

z!_SelectorSslTransport._read_readycCs(|jr
dS|jr<d|_|j�|jp(|js<|jj|j|j�|jr�y|j	j
|j�}Wn�ttt
jfk
rtd}Ynpt
jk
r�d}|jj|j�d|_YnDtk
r�}z(|jj|j�|jj�|j|d�dSd}~XnX|r�|jd|�=|j�|j�s$|jj|j�|j�r$|jd�dS)NFrTz"Fatal write error on SSL transport)r�r�r�r�r�r�r?r�r�r�rHrErDr�r�r�rur�rar�r�r�r�)r!r}r^rrrr��s8

z"_SelectorSslTransport._write_readycCs�t|tttf�s"tdt|�j��|s*dS|jrX|jtj	krFt
jd�|jd7_dS|jsp|j
j|j|j�|jj|�|j�dS)Nz1data argument must be a bytes-like object, not %rzsocket.send() raised exception.r)r�r�r�r�r�r�rr�rr�r
r�r�r�rtr�r�r�r�)r!rArrrr��s
z_SelectorSslTransport.writecCsdS)NFr)r!rrrr�sz#_SelectorSslTransport.can_write_eof)NFNNN)N)rr�r�r�r�rr�r�r�r�r�r�r�r�r�rr)rrr/$s"

?
"#r/csFeZdZejZd�fdd�	Zdd�Zdd�Zd
dd	�Z	d
d�Z
�ZS)r0Ncs^t�j||||�||_|jj|jj|�|jj|j|j|j	�|dk	rZ|jjt
j|d�dS)N)rr�_addressr�r�r�r�r?r�r�rr�)r!r�r%r&r1r'r")rrrrs

z#_SelectorDatagramTransport.__init__cCstdd�|jD��S)Ncss|]\}}t|�VqdS)N)r�)�.0rAr[rrr�	<genexpr>szC_SelectorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr�)r!rrrr�sz0_SelectorDatagramTransport.get_write_buffer_sizecCs�|jr
dSy|jj|j�\}}Wnpttfk
r8Ynhtk
rd}z|jj|�WYdd}~Xn<t	k
r�}z|j
|d�WYdd}~XnX|jj||�dS)Nz&Fatal read error on datagram transport)r�r�Zrecvfromr�rErDrIr��error_receivedrar�Zdatagram_received)r!rAr]r^rrrr� sz&_SelectorDatagramTransport._read_readycCsTt|tttf�s"tdt|�j��|s*dS|jrN|d|jfkrNtd|jf��|j	r�|jr�|j	t
jkrptj
d�|j	d7_	dS|j�s4y&|jr�|jj|�n|jj||�dSttfk
r�|jj|j|j�YnZtk
�r}z|jj|�dSd}~Xn.tk
�r2}z|j|d�dSd}~XnX|jjt|�|f�|j�dS)Nz1data argument must be a bytes-like object, not %rz#Invalid address: must be None or %szsocket.send() raised exception.rz'Fatal write error on datagram transport)r�r�r�r�r�r�rr�r{r�rr�r
r�r�r�rH�sendtorErDr�rtr��
_sendto_readyrIr�r�rar�r�r�)r!rAr]r^rrrr�.s<
z!_SelectorDatagramTransport.sendtocCs�x�|jr�|jj�\}}y&|jr,|jj|�n|jj||�Wqttfk
rf|jj||f�PYqt	k
r�}z|j
j|�dSd}~Xqtk
r�}z|j
|d�dSd}~XqXqW|j�|js�|jj|j�|jr�|jd�dS)Nz'Fatal write error on datagram transport)r��popleftr�r�rHr�rErD�
appendleftrIr�r�rar�r�r�rur�r�r�)r!rAr]r^rrrr�Us*z(_SelectorDatagramTransport._sendto_ready)NNN)N)rr�r��collections�dequer�rr�r�r�r�r�rr)rrr0s
'r0) r��__all__r�rXr�rSr�rr��ImportError�rrrrrr	r
rZ
coroutinesr�logr
rZ
BaseEventLooprZ_FlowControlMixinZ	Transportr�r$r/r0rrrr�<module>sD
iiPK[K�[[$__pycache__/protocols.cpython-36.pycnu�[���3


 \��@sRdZddddgZGdd�d�ZGdd�de�ZGdd�de�ZGdd�de�Zd	S)
zAbstract Protocol class.�BaseProtocol�Protocol�DatagramProtocol�SubprocessProtocolc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)raCommon base class for protocol interfaces.

    Usually user implements protocols that derived from BaseProtocol
    like Protocol or ProcessProtocol.

    The only case when BaseProtocol should be implemented directly is
    write-only transport like write pipe
    cCsdS)z�Called when a connection is made.

        The argument is the transport representing the pipe connection.
        To receive data, wait for data_received() calls.
        When the connection is closed, connection_lost() is called.
        N�)�selfZ	transportrr�)/usr/lib64/python3.6/asyncio/protocols.py�connection_madeszBaseProtocol.connection_madecCsdS)z�Called when the connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        Nr)r�excrrr�connection_lostszBaseProtocol.connection_lostcCsdS)aCalled when the transport's buffer goes over the high-water mark.

        Pause and resume calls are paired -- pause_writing() is called
        once when the buffer goes strictly over the high-water mark
        (even if subsequent writes increases the buffer size even
        more), and eventually resume_writing() is called once when the
        buffer size reaches the low-water mark.

        Note that if the buffer size equals the high-water mark,
        pause_writing() is not called -- it must go strictly over.
        Conversely, resume_writing() is called when the buffer size is
        equal or lower than the low-water mark.  These end conditions
        are important to ensure that things go as expected when either
        mark is zero.

        NOTE: This is the only Protocol callback that is not called
        through EventLoop.call_soon() -- if it were, it would have no
        effect when it's most needed (when the app keeps writing
        without yielding until pause_writing() is called).
        Nr)rrrr�
pause_writing!szBaseProtocol.pause_writingcCsdS)zvCalled when the transport's buffer drains below the low-water mark.

        See pause_writing() for details.
        Nr)rrrr�resume_writing7szBaseProtocol.resume_writingN)�__name__�
__module__�__qualname__�__doc__rr
rrrrrrrs
c@s eZdZdZdd�Zdd�ZdS)ranInterface for stream protocol.

    The user should implement this interface.  They can inherit from
    this class but don't need to.  The implementations here do
    nothing (they don't raise exceptions).

    When the user wants to requests a transport, they pass a protocol
    factory to a utility function (e.g., EventLoop.create_connection()).

    When the connection is made successfully, connection_made() is
    called with a suitable transport object.  Then data_received()
    will be called 0 or more times with data (bytes) received from the
    transport; finally, connection_lost() will be called exactly once
    with either an exception object or None as an argument.

    State machine of calls:

      start -> CM [-> DR*] [-> ER?] -> CL -> end

    * CM: connection_made()
    * DR: data_received()
    * ER: eof_received()
    * CL: connection_lost()
    cCsdS)zTCalled when some data is received.

        The argument is a bytes object.
        Nr)r�datarrr�
data_receivedXszProtocol.data_receivedcCsdS)z�Called when the other end calls write_eof() or equivalent.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        Nr)rrrr�eof_received^szProtocol.eof_receivedN)r
rrrrrrrrrr>sc@s eZdZdZdd�Zdd�ZdS)rz Interface for datagram protocol.cCsdS)z&Called when some datagram is received.Nr)rrZaddrrrr�datagram_receivedjsz"DatagramProtocol.datagram_receivedcCsdS)z~Called when a send or receive operation raises an OSError.

        (Other than BlockingIOError or InterruptedError.)
        Nr)rr	rrr�error_receivedmszDatagramProtocol.error_receivedN)r
rrrrrrrrrrgsc@s(eZdZdZdd�Zdd�Zdd�ZdS)	rz,Interface for protocol for subprocess calls.cCsdS)z�Called when the subprocess writes data into stdout/stderr pipe.

        fd is int file descriptor.
        data is bytes object.
        Nr)r�fdrrrr�pipe_data_receivedwsz%SubprocessProtocol.pipe_data_receivedcCsdS)z�Called when a file descriptor associated with the child process is
        closed.

        fd is the int file descriptor that was closed.
        Nr)rrr	rrr�pipe_connection_lost~sz'SubprocessProtocol.pipe_connection_lostcCsdS)z"Called when subprocess has exited.Nr)rrrr�process_exited�sz!SubprocessProtocol.process_exitedN)r
rrrrrrrrrrrtsN)r�__all__rrrrrrrr�<module>s7)
PK[i|MZ�.�.&__pycache__/tasks.cpython-36.opt-2.pycnu�[���3


 \�a�
@s�dddddddddd	d
ddg
Zd
dlZd
dlZd
dlZd
dlZd
dlZddlmZddlm	Z	ddlm
Z
ddlmZddlmZddl
m
Z
Gdd�dej�ZeZyd
dlZWnek
r�YnXejZZejjZejjZejjZe
dded�dd��Zdd�Ze
dd�dd��Ze
dd��Zddd�d d�Ze
d.dd�d!d��Zdd�d"d#�Zee�d<de_[dd�d$d�Z e
d%d&��Z!Gd'd(�d(ej�Z"dd)d*�d+d	�Z#dd�d,d
�Z$d-d�Z%dS)/�Task�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�wait�wait_for�as_completed�sleep�async�gather�shield�
ensure_future�run_coroutine_threadsafe�N�)�
base_tasks)�compat)�
coroutines)�events)�futures)�	coroutinecs�eZdZej�ZiZdZeddd��Z	eddd��Z
dd��fdd	�
Zej
rTd
d�Zdd
�Zdd�dd�Zddd�dd�Zdd�Zd�fdd�	Zdd�Z�ZS)rTNcCs|dkrtj�}|jj|�S)N)r�get_event_loop�_current_tasks�get)�cls�loop�r�%/usr/lib64/python3.6/asyncio/tasks.py�current_task.szTask.current_taskcs$�dkrtj���fdd�|jD�S)Ncsh|]}|j�kr|�qSr)�_loop)�.0�t)rrr�	<setcomp>Bsz!Task.all_tasks.<locals>.<setcomp>)rr�
_all_tasks)rrr)rr�	all_tasks:szTask.all_tasks)rcsNt�j|d�|jr|jd=||_d|_d|_|jj|j�|j	j
j|�dS)N)rrF���)�super�__init__�_source_traceback�_coro�_fut_waiter�_must_cancelr�	call_soon�_step�	__class__r"�add)�self�coror)r-rrr&Dsz
Task.__init__cCsH|jtjkr8|jr8|dd�}|jr,|j|d<|jj|�tjj|�dS)Nz%Task was destroyed but it is pending!)�task�messageZsource_traceback)	Z_staterZ_PENDING�_log_destroy_pendingr'rZcall_exception_handler�Future�__del__)r/�contextrrrr5Ss
zTask.__del__cCs
tj|�S)N)rZ_task_repr_info)r/rrr�
_repr_info^szTask._repr_info)�limitcCstj||�S)N)rZ_task_get_stack)r/r8rrr�	get_stackaszTask.get_stack)r8�filecCstj|||�S)N)rZ_task_print_stack)r/r8r:rrr�print_stackxs	zTask.print_stackcCs4d|_|j�rdS|jdk	r*|jj�r*dSd|_dS)NFT)Z_log_traceback�doner)�cancelr*)r/rrrr=�s

zTask.cancelcsf|jr t|tj�stj�}d|_|j}d|_||jj|j<�zy"|dkrT|j	d�}n
|j
|�}Wn�tk
r�}z.|jr�d|_|jtj��n|j
|j�WYdd}~X�n�tjk
r�t�j�Y�n|tk
r�}z|j|�WYdd}~X�nPtk
�r(}z|j|��WYdd}~X�n Xt|dd�}|dk	�r�|j|jk	�rl|jj|jtdj||���n||�r�||k�r�|jj|jtdj|���n2d|_|j|j�||_|j�r�|jj��r�d|_n|jj|jtdj||���n^|dk�r|jj|j�nDtj|��r.|jj|jtdj||���n|jj|jtdj|���Wd|jjj|j�d}XdS)NF�_asyncio_future_blockingz6Task {!r} got Future {!r} attached to a different loopz!Task cannot await on itself: {!r}z;yield was used instead of yield from in task {!r} with {!r}zIyield was used instead of yield from for generator in task {!r} with {!r}zTask got bad yield: {!r})r*�
isinstancer�CancelledErrorr(r)r-rr�send�throw�
StopIteration�
set_exception�
set_result�valuer%r=�	Exception�
BaseException�getattrr+r,�RuntimeError�formatr>�add_done_callback�_wakeup�inspectZisgenerator�pop)r/�excr0�resultZblocking)r-rrr,�s~



z
Task._stepcCsJy|j�Wn,tk
r8}z|j|�WYdd}~Xn
X|j�d}dS)N)rQrGr,)r/�futurerPrrrrM�szTask._wakeup)N)N)N)�__name__�
__module__�__qualname__�weakref�WeakSetr"rr3�classmethodrr#r&rZPY34r5r7r9r;r=r,rM�
__classcell__rr)r-rrs 
	!T)r�timeout�return_whenc#s�tj|�stj|�r&tdt|�j��|s2td��|tt	t
fkrNtdj|����dkr^tj
���fdd�t|�D�}t|||��EdHS)Nz expect a list of futures, not %sz#Set of coroutines/Futures is empty.zInvalid return_when value: {}csh|]}t|�d��qS))r)r)r�f)rrrr!7szwait.<locals>.<setcomp>)r�isfuturer�iscoroutine�	TypeError�typerS�
ValueErrorrrrrKrr�set�_wait)�fsrrZr[r)rrrscGs|j�s|jd�dS)N)r<rE)�waiter�argsrrr�_release_waiter<srg)rccs�|dkrtj�}|dkr"|EdHS|j�}|j|t|�}tjt|�}t||d�}|j|�zhy|EdHWn*t	j
k
r�|j|�|j��YnX|j
�r�|j�S|j|�|j�t	j��Wd|j�XdS)N)r)rr�
create_future�
call_laterrg�	functools�partialrrLrr@�remove_done_callbackr=r<rQ�TimeoutError)�futrZrre�timeout_handle�cbrrrrAs,



c#s�|j��d�|dk	r"|j|t���t|������fdd�}x|D]}|j|�qBWz�EdHWd�dk	rt�j�Xt�t�}}x4|D],}|j|�|j�r�|j	|�q�|j	|�q�W||fS)Ncs\�d8��dks6�tks6�tkrX|j�rX|j�dk	rX�dk	rF�j��j�sX�jd�dS)Nrr)rr�	cancelled�	exceptionr=r<rE)r\)�counterr[rorerr�_on_completion|sz_wait.<locals>._on_completion)
rhrirg�lenrLr=rbrlr<r.)rdrZr[rrtr\r<�pendingr)rsr[rorerrcos&



rc)rrZc#s�tj|�stj|�r&tdt|�j���dk	r2�ntj���fdd�t	|�D��ddl
m}|�d��d����fdd�}���fd	d
��t�fdd��}x�D]}|j
��q�W�r�|dk	rʈj||��xtt���D]}|�Vq�WdS)
Nz expect a list of futures, not %scsh|]}t|�d��qS))r)r)rr\)rrrr!�szas_completed.<locals>.<setcomp>r)�Queue)rcs.x �D]}|j���jd�qW�j�dS)N)rl�
put_nowait�clear)r\)rtr<�todorr�_on_timeout�s

z!as_completed.<locals>._on_timeoutcs6�sdS�j|��j|��r2�dk	r2�j�dS)N)�removerxr=)r\)r<rorzrrrt�s

z$as_completed.<locals>._on_completionc3s$�j�EdH}|dkrtj�|j�S)N)rrrmrQ)r\)r<rr�
_wait_for_one�sz#as_completed.<locals>._wait_for_one)rr]rr^r_r`rSrrrbZqueuesrwrrLri�rangeru)rdrrZrwr{r}r\�_r)rtr<rrorzrr�s 

c
csX|dkrdV|S|dkr"tj�}|j�}|jj|tj||�}z
|EdHS|j�XdS)Nr)rrrhrrirZ_set_result_unless_cancelledr=)ZdelayrQrrR�hrrrr�s
cCstjdtdd�t||d�S)Nz;asyncio.async() function is deprecated, use ensure_future()�)�
stacklevel)r)�warnings�warn�DeprecationWarningr)�coro_or_futurerrrr�async_�sr�cCs�tj|�r(|dk	r$||jk	r$td��|Stj|�r^|dkrBtj�}|j|�}|j	rZ|j	d=|St
jr~tj
|�r~tt|�|d�Std��dS)Nz$loop argument must agree with Futurer)rz:An asyncio.Future, a coroutine or an awaitable is requiredr$)rr]rrarr^rrZcreate_taskr'rZPY35rNZisawaitabler�_wrap_awaitabler_)r�rr1rrrr�s


ccs|j�EdHS)N)�	__await__)Z	awaitablerrrr�sr�cs*eZdZdd��fdd�
Zdd�Z�ZS)�_GatheringFutureN)rcst�j|d�||_d|_dS)N)rF)r%r&�	_children�_cancel_requested)r/�childrenr)r-rrr&$sz_GatheringFuture.__init__cCs:|j�rdSd}x|jD]}|j�rd}qW|r6d|_|S)NFT)r<r�r=r�)r/ZretZchildrrrr=)sz_GatheringFuture.cancel)rSrTrUr&r=rYrr)r-rr�sr�F)r�return_exceptionscs|s*|dkrtj�}|j���jg��Si�xjt|�D]^}tj|�sht||d�}|dkr`|j}d|_	n&|}|dkr||j}n|j|k	r�t
d��|�|<q8W�fdd�|D�}t|��t||d��d�dg�������fdd�}x&t
|�D]\}}|jtj||��q�W�S)	N)rFz)futures are tied to different event loopscsg|]}�|�qSrr)r�arg)�
arg_to_futrr�
<listcomp>hszgather.<locals>.<listcomp>rcs��j�r|j�s|j�dS|j�r@tj�}�sl�j|�dSn,|jdk	rf|j�}�sl�j|�dSn|j}|�|<�d7���kr��jr��jtj��n
�j	��dS)Nr)
r<rqrrrr@rDZ
_exceptionZ_resultr�rE)�irn�res)�	nchildren�	nfinished�outer�resultsr�rr�_done_callbackns*


zgather.<locals>._done_callback)rrrhrErbrr]rrr3rarur��	enumeraterLrjrk)rr�Zcoros_or_futuresr�rnr�r�r�r)r�r�r�r�r�r�rr
8s8



cs@t||d�}|j�r|S|j}|j���fdd�}|j|��S)N)rcs\�j�r|j�s|j�dS|j�r.�j�n*|j�}|dk	rJ�j|�n�j|j��dS)N)rqrrr=rDrErQ)�innerrP)r�rrr��s
zshield.<locals>._done_callback)rr<rrhrL)r�rr�r�r)r�rr�s
cs:tj��std��tjj�����fdd�}�j|��S)NzA coroutine object is requiredcsTytjt��d���Wn6tk
rN}z�j�r<�j|��WYdd}~XnXdS)N)r)rZ
_chain_futurerrGZset_running_or_notify_cancelrD)rP)r0rRrrr�callback�s
z*run_coroutine_threadsafe.<locals>.callback)rr^r_�
concurrentrr4Zcall_soon_threadsafe)r0rr�r)r0rRrrr
�s


)N)&�__all__Zconcurrent.futuresr�rjrNr�rV�rrrrrrr4rZ_PyTaskZ_asyncio�ImportErrorZ_CTaskrrrrrgrrcrrr��globalsrSrr�r�r
rr
rrrr�<module>sX
s
--8

W5PK[H�V1  +__pycache__/coroutines.cpython-36.opt-2.pycnu�[���3


 \+�@s�dddgZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZdd	lmZdd
l
mZejdZejjo�eejjd��ZyejZejZWnek
r�dZdZYnXy
ejZWnek
r�d
d�ZYnXyddlmZ m!Z"Wne#k
�r*dZ Z"YnXdd�Z$e$�Z%[$dd�Z&Gdd�d�Z'dd�Ze(�Z)dd�Zej*e'fZ+e dk	�r�e+e f7Z+edk	�r�efe+Z+dd�Z,dd�Z-dS)�	coroutine�iscoroutinefunction�iscoroutine�N�)�compat)�	constants)�events)�base_futures)�loggerZ
YIELD_FROMZPYTHONASYNCIODEBUGcCsdS)NF�)�funcrr�*/usr/lib64/python3.6/asyncio/coroutines.py�<lambda>/sr)�	Coroutine�	AwaitablecCsFGdd�d�}dd�}d}|�}||�}t|�|j|�|j|fkS)	Nc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
z!has_yield_from_bug.<locals>.MyGencSs
d|_dS)N)�	send_args)�selfrrr
�__init__;sz*has_yield_from_bug.<locals>.MyGen.__init__cSs|S)Nr)rrrr
�__iter__=sz*has_yield_from_bug.<locals>.MyGen.__iter__cSsdS)N�*r)rrrr
�__next__?sz*has_yield_from_bug.<locals>.MyGen.__next__cWs
||_dS)N)r)rZwhatrrr
�sendAsz&has_yield_from_bug.<locals>.MyGen.sendN)�__name__�
__module__�__qualname__rrrrrrrr
�MyGen:srcss|EdHdS)Nr)�genrrr
�yield_from_genDsz*has_yield_from_bug.<locals>.yield_from_genr��)rrr)�nextrr)rr�valuer�cororrr
�has_yield_from_bug9s

r#cCs
t|d�S)N)�CoroWrapper)rrrr
�
debug_wrapperPsr%c@s�eZdZd%dd�Zdd�Zdd�Zdd	�Zer8d
d�Zndd�Zd&d
d�Z	dd�Z
edd��Zedd��Z
edd��Zejr�dd�Zedd��Zedd��Zedd��Zedd ��Zed!d"��Zd#d$�ZdS)'r$NcCs>||_||_tjtjd��|_t|dd�|_t|dd�|_	dS)Nrrr)
rrr�
extract_stack�sys�	_getframe�_source_traceback�getattrrr)rrrrrr
r[s
zCoroWrapper.__init__cCs@t|�}|jr0|jd}|d|d|df7}d|jj|fS)Nrz, created at %s:%srz<%s %s>���)�_format_coroutiner)�	__class__r)r�	coro_repr�framerrr
�__repr__cs

zCoroWrapper.__repr__cCs|S)Nr)rrrr
rjszCoroWrapper.__iter__cCs|jjd�S)N)rr)rrrr
rmszCoroWrapper.__next__cGs4tj�}|j}|jj|jtkr(|d}|jj|�S)Nr)	r'r(�f_back�f_code�co_code�f_lasti�_YIELD_FROMrr)rr!r/Zcallerrrr
rus
zCoroWrapper.sendcCs|jj|�S)N)rr)rr!rrr
r}scCs|jj|||�S)N)r�throw)r�typer!�	tracebackrrr
r6�szCoroWrapper.throwcCs
|jj�S)N)r�close)rrrr
r9�szCoroWrapper.closecCs|jjS)N)r�gi_frame)rrrr
r:�szCoroWrapper.gi_framecCs|jjS)N)r�
gi_running)rrrr
r;�szCoroWrapper.gi_runningcCs|jjS)N)r�gi_code)rrrr
r<�szCoroWrapper.gi_codecCs,t|jdd�}|dk	r(tdj|j|���|S)N�cr_awaitz;Cannot await on coroutine {!r} while it's awaiting for {!r})r*r�RuntimeError�format)rr=rrr
�	__await__�szCoroWrapper.__await__cCs|jjS)N)r�gi_yieldfrom)rrrr
rA�szCoroWrapper.gi_yieldfromcCs|jjS)N)rr=)rrrr
r=�szCoroWrapper.cr_awaitcCs|jjS)N)r�
cr_running)rrrr
rB�szCoroWrapper.cr_runningcCs|jjS)N)r�cr_code)rrrr
rC�szCoroWrapper.cr_codecCs|jjS)N)r�cr_frame)rrrr
rD�szCoroWrapper.cr_framecCs�t|dd�}t|dd�}|dkr,t|dd�}|dk	r�|jd
kr�d|}t|df�}|r�djtj|��}|dtj�d	�7}||j�7}tj	|�dS)Nrr:rDrz%r was never yielded fromr)�zB
Coroutine object created at (most recent call last, truncated to z last lines):
r+)
r*r4�joinr8�format_listrZDEBUG_STACK_DEPTH�rstripr
�error)rrr/�msg�tbrrr
�__del__�szCoroWrapper.__del__)N)NN)rrrrr0rr�_YIELD_FROM_BUGrr6r9�propertyr:r;r<rZPY35r@rAr=rBrCrDrLrrrr
r$Xs(


r$cspt��r�Stj��r��ntj���fdd���tsNtdkrD�}qft��}ntj����fdd��}t|_|S)Nc?sv�||�}tj|�s(tj|�s(t|t�r4|EdH}n>tdk	rry
|j}Wntk
rZYnXt|t�rr|�EdH}|S)N)	r	Zisfuture�inspectZisgenerator�
isinstancer$�
_AwaitableABCr@�AttributeError)�args�kw�resZ
await_meth)rrr
r"�s



zcoroutine.<locals>.corocs@t�||��d�}|jr |jd=t�dd�|_t�dd�|_|S)N)rrrrr+)r$r)r*rr)rS�kwds�w)r"rrr
�wrapper�szcoroutine.<locals>.wrapper)�_inspect_iscoroutinefunctionrO�isgeneratorfunction�	functools�wraps�_DEBUG�_types_coroutine�
_is_coroutine)rrXr)r"rr
r�s


cCst|dd�tkpt|�S)Nr_)r*r_rY)rrrr
r�scCs
t|t�S)N)rP�_COROUTINE_TYPES)�objrrr
rsc
Cst|d�r�t|d�r�t|dt|dt|�j��}dj|�}d}y
|j}Wn4tk
r~y
|j}Wntk
rxYnXYnX|r�dj|�S|Sd}t|t	�r�|j
}|j}|dk	r�dj|�}n|}|dkr�tj
|fi�}d}t|d�r�|jr�|j}nt|d��r|j�r|j}d}t|d��r0|j�r0|j}nt|d	��rJ|j�rJ|j}d
}|�rb|j�rb|j}d}|}t|t	��r�tj|j
��r�|j
dk	�r�tj|j
�}	|	dk	�r�|	\}}|dk�r�d|||f}nd
|||f}n:|dk	�r�|j}d|||f}n|�r|j}d|||f}|S)NrCr<rrz{}()Fz
{} runningrDr:z<empty co_filename>rz%s done, defined at %s:%sz%s running, defined at %s:%sz%s running at %s:%s)�hasattrr*r7rr?rBrRr;rPr$rrrZ_format_callbackrCr<rDr:�co_filenamerOrZZ_get_function_source�f_lineno�co_firstlineno)
r"Z	coro_nameZrunningrZ	coro_codeZ
coro_frame�filename�linenor.�sourcerrr
r,sx







r,).�__all__r[rOZopcode�osr'r8�typesrErrrr	�logr
Zopmapr5�flags�ignore_environment�bool�environ�getr]rr^�
CoroutineTypeZ_types_CoroutineTyperRrrY�collections.abcrZ
_CoroutineABCrrQ�ImportErrorr#rMr%r$�objectr_�
GeneratorTyper`rr,rrrr
�<module>sZ




j:




PK[���ee.__pycache__/windows_utils.cpython-36.opt-2.pycnu�[���3


 \��@s�ddlZejdkred��ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
dddddgZd	Zej
Z
ejZej�Zeed�r�ejZnejejdfd
d�Zdded
�dd�ZGdd�d�ZGdd�dej�ZdS)�NZwin32z
win32 only�
socketpair�pipe�Popen�PIPE�
PipeHandlei c
Cs|tjkrd}n|tjkr d}ntd��|tjkr:td��|dkrJtd��tj|||�}z�|j|df�|jd�|j�dd�\}}tj|||�}yP|jd	�y|j	||f�Wnt
tfk
r�YnX|jd
�|j�\}}	Wn|j
��YnXWd|j
�X||fS)Nz	127.0.0.1z::1z?Only AF_INET and AF_INET6 socket address families are supportedz)Only SOCK_STREAM socket type is supportedrzOnly protocol zero is supported��FT)�socket�AF_INETZAF_INET6�
ValueError�SOCK_STREAMZbindZlistenZgetsocknameZsetblockingZconnect�BlockingIOError�InterruptedErrorZaccept�close)
Zfamily�type�proto�hostZlsockZaddrZportZcsockZssock�_�r�-/usr/lib64/python3.6/asyncio/windows_utils.pyr%s8






FT)�duplex�
overlapped�bufsizecCs"tjdtj�tt�fd�}|r>tj}tjtj	B}||}}ntj
}tj	}d|}}|tjO}|drp|tjO}|dr�tj}nd}d}	}
yZtj
||tjd||tjtj�}	tj||dtjtj|tj�}
tj|	dd�}|jd�|	|
fS|	dk	�rtj|	�|
dk	�rtj|
��YnXdS)Nz\\.\pipe\python-pipe-%d-%d-)�prefixrrT)r)�tempfileZmktemp�os�getpid�next�
_mmap_counter�_winapiZPIPE_ACCESS_DUPLEXZGENERIC_READZ
GENERIC_WRITEZPIPE_ACCESS_INBOUNDZFILE_FLAG_FIRST_PIPE_INSTANCEZFILE_FLAG_OVERLAPPEDZCreateNamedPipeZ	PIPE_WAITZNMPWAIT_WAIT_FOREVERZNULLZ
CreateFileZ
OPEN_EXISTINGZConnectNamedPipeZGetOverlappedResult�CloseHandle)rrrZaddressZopenmode�accessZobsizeZibsizeZflags_and_attribsZh1Zh2ZovrrrrSs@








c@sXeZdZdd�Zdd�Zedd��Zdd�Zej	d	�d
d�Z
dd
�Zdd�Zdd�Z
dS)rcCs
||_dS)N)�_handle)�self�handlerrr�__init__�szPipeHandle.__init__cCs*|jdk	rd|j}nd}d|jj|fS)Nz	handle=%r�closedz<%s %s>)r"�	__class__�__name__)r#r$rrr�__repr__�s
zPipeHandle.__repr__cCs|jS)N)r")r#rrrr$�szPipeHandle.handlecCs|jdkrtd��|jS)NzI/O operatioon on closed pipe)r"r)r#rrr�fileno�s
zPipeHandle.fileno)r cCs|jdk	r||j�d|_dS)N)r")r#r rrrr�s

zPipeHandle.closecCs*|jdk	r&tjd|t|d�|j�dS)Nzunclosed %r)�source)r"�warnings�warn�ResourceWarningr)r#rrr�__del__�s
zPipeHandle.__del__cCs|S)Nr)r#rrr�	__enter__�szPipeHandle.__enter__cCs|j�dS)N)r)r#�t�v�tbrrr�__exit__�szPipeHandle.__exit__N)r(�
__module__�__qualname__r%r)�propertyr$r*rr rr/r0r4rrrrr�scseZdZd�fdd�	Z�ZS)rNcs|d}}}d}	}
}|tkr@tddd�\}}	tj|tj�}n|}|tkrhtdd�\}
}
tj|
d�}n|}|tkr�td	d�\}}tj|d�}n|tkr�|}n|}z�y t�j|f|||d�|��Wn4x$|	|
|fD]}|dk	r�t	j
|�q�W�Yn>X|	dk	�rt|	�|_|
dk	�r"t|
�|_
|dk	�r6t|�|_Wd|tk�rNtj|�|tk�rbtj|�|tk�rvtj|�XdS)
NFT)rr)rr)�stdin�stdout�stderr)FT)TF)TF)rr�msvcrtZopen_osfhandler�O_RDONLY�STDOUT�superr%rr rr8r9r:r)r#�argsr8r9r:�kwdsZ	stdin_rfdZ
stdout_wfdZ
stderr_wfdZstdin_whZ	stdout_rhZ	stderr_rhZstdin_rhZ	stdout_whZ	stderr_wh�h)r'rrr%�sH









zPopen.__init__)NNN)r(r5r6r%�
__classcell__rr)r'rr�s)TT)�sys�platform�ImportErrorr�	itertoolsr;rr	�
subprocessrr,�__all__ZBUFSIZErr=�countr�hasattrrr
rrrrrrrr�<module>s*

.0-PK[������+__pycache__/subprocess.cpython-36.opt-2.pycnu�[���3


 \��@s�ddgZddlZddlmZddlmZddlmZddlmZdd	lmZdd
l	m
Z
ejZejZej
Z
Gdd�dejej�ZGd
d�d�Zeddddejfdd��Zeddddejd�dd��ZdS)�create_subprocess_exec�create_subprocess_shell�N�)�events)�	protocols)�streams)�tasks)�	coroutine)�loggercsLeZdZ�fdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	�Z
S)�SubprocessStreamProtocolcs<t�j|d�||_d|_|_|_d|_d|_g|_dS)N)�loopF)	�super�__init__�_limit�stdin�stdout�stderr�
_transport�_process_exited�	_pipe_fds)�self�limitr)�	__class__��*/usr/lib64/python3.6/asyncio/subprocess.pyrsz!SubprocessStreamProtocol.__init__cCsf|jjg}|jdk	r$|jd|j�|jdk	r>|jd|j�|jdk	rX|jd|j�ddj|�S)Nzstdin=%rz	stdout=%rz	stderr=%rz<%s>� )r�__name__r�appendrr�join)r�inforrr�__repr__s



z!SubprocessStreamProtocol.__repr__cCs�||_|jd�}|dk	rDtj|j|jd�|_|jj|�|jj	d�|jd�}|dk	r�tj|j|jd�|_
|j
j|�|jj	d�|jd�}|dk	r�tj||d|jd�|_dS)Nr)rr�r)�protocol�readerr)
r�get_pipe_transportr�StreamReaderr�_looprZ
set_transportrrr�StreamWriterr)r�	transportZstdout_transportZstderr_transportZstdin_transportrrr�connection_made(s&


z(SubprocessStreamProtocol.connection_madecCs:|dkr|j}n|dkr |j}nd}|dk	r6|j|�dS)Nrr!)rrZ	feed_data)r�fd�datar#rrr�pipe_data_received@sz+SubprocessStreamProtocol.pipe_data_receivedcCs�|dkr,|j}|dk	r|j�|j|�dS|dkr<|j}n|dkrL|j}nd}|dkrt|dkrj|j�n
|j|�||jkr�|jj|�|j	�dS)Nrrr!)
r�closeZconnection_lostrrZfeed_eofZ
set_exceptionr�remove�_maybe_close_transport)rr*�exc�piper#rrr�pipe_connection_lostJs$



z-SubprocessStreamProtocol.pipe_connection_lostcCsd|_|j�dS)NT)rr/)rrrr�process_exitedasz'SubprocessStreamProtocol.process_exitedcCs(t|j�dkr$|jr$|jj�d|_dS)Nr)�lenrrrr-)rrrrr/es
z/SubprocessStreamProtocol._maybe_close_transport)r�
__module__�__qualname__rr r)r,r2r3r/�
__classcell__rr)rrrs

rc@s~eZdZdd�Zdd�Zedd��Zedd��Zd	d
�Z	dd�Z
d
d�Zedd��Zedd��Z
edd��Zeddd��ZdS)�ProcesscCs8||_||_||_|j|_|j|_|j|_|j�|_dS)N)rZ	_protocolr&rrrZget_pid�pid)rr(r"rrrrrlszProcess.__init__cCsd|jj|jfS)Nz<%s %s>)rrr9)rrrrr uszProcess.__repr__cCs
|jj�S)N)rZget_returncode)rrrr�
returncodexszProcess.returncodeccs|jj�EdHS)N)rZ_wait)rrrr�wait|szProcess.waitcCs|jj|�dS)N)r�send_signal)r�signalrrrr<�szProcess.send_signalcCs|jj�dS)N)r�	terminate)rrrrr>�szProcess.terminatecCs|jj�dS)N)r�kill)rrrrr?�szProcess.killccs�|jj�}|jj|�|r,tjd|t|��y|jj�EdHWn8tt	fk
rx}z|rhtjd||�WYdd}~XnX|r�tjd|�|jj
�dS)Nz%%r communicate: feed stdin (%s bytes)z%r communicate: stdin got %rz%r communicate: close stdin)r&�	get_debugr�writer
�debugr4Zdrain�BrokenPipeError�ConnectionResetErrorr-)r�inputrBr0rrr�_feed_stdin�s
 zProcess._feed_stdincCsdS)Nr)rrrr�_noop�sz
Process._noopccs�|jj|�}|dkr|j}n|j}|jj�rJ|dkr8dnd}tjd||�|j�EdH}|jj�r�|dkrndnd}tjd||�|j	�|S)Nr!rrrz%r communicate: read %sz%r communicate: close %s)
rr$rrr&r@r
rB�readr-)rr*r(�stream�name�outputrrr�_read_stream�s

zProcess._read_streamNccs�|dk	r|j|�}n|j�}|jdk	r2|jd�}n|j�}|jdk	rP|jd�}n|j�}tj||||jd�EdH\}}}|j�EdH||fS)Nrr!)r)	rFrGrrLrrZgatherr&r;)rrErrrrrr�communicate�s


zProcess.communicate)N)rr5r6rr �propertyr:r	r;r<r>r?rFrGrLrMrrrrr8ks	r8c
+sP�dkrtj����fdd�}�j||f|||d�|��EdH\}}	t||	��S)Ncst��d�S)N)rr)rr)rrrr�<lambda>�sz)create_subprocess_shell.<locals>.<lambda>)rrr)r�get_event_loopZsubprocess_shellr8)
�cmdrrrrr�kwds�protocol_factoryr(r"r)rrrr�s)rrrrrc/sT�dkrtj����fdd�}�j||f|�|||d�|��EdH\}	}
t|	|
��S)Ncst��d�S)N)rr)rr)rrrrrO�sz(create_subprocess_exec.<locals>.<lambda>)rrr)rrPZsubprocess_execr8)Zprogramrrrrr�argsrRrSr(r"r)rrrr�s)�__all__�
subprocess�rrrrZ
coroutinesr	�logr
�PIPEZSTDOUTZDEVNULLZFlowControlMixinZSubprocessProtocolrr8Z_DEFAULT_LIMITrrrrrr�<module>s(X]PK[Q*_//%__pycache__/transports.cpython-36.pycnu�[���3


 \R'�@s�dZddlmZddddddgZGd	d�d�ZGd
d�de�ZGdd�de�ZGdd�dee�ZGd
d�de�ZGdd�de�Z	Gdd�de�Z
dS)zAbstract Transport class.�)�compat�
BaseTransport�
ReadTransport�WriteTransport�	Transport�DatagramTransport�SubprocessTransportc@sDeZdZdZddd�Zddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)rzBase class for transports.NcCs|dkri}||_dS)N)�_extra)�self�extra�r�*/usr/lib64/python3.6/asyncio/transports.py�__init__
szBaseTransport.__init__cCs|jj||�S)z#Get optional transport information.)r	�get)r
�name�defaultrrr
�get_extra_infoszBaseTransport.get_extra_infocCst�dS)z2Return True if the transport is closing or closed.N)�NotImplementedError)r
rrr
�
is_closingszBaseTransport.is_closingcCst�dS)a
Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        N)r)r
rrr
�closeszBaseTransport.closecCst�dS)zSet a new protocol.N)r)r
�protocolrrr
�set_protocol$szBaseTransport.set_protocolcCst�dS)zReturn the current protocol.N)r)r
rrr
�get_protocol(szBaseTransport.get_protocol)N)N)
�__name__�
__module__�__qualname__�__doc__rrrrrrrrrr
r
s


c@s eZdZdZdd�Zdd�ZdS)rz#Interface for read-only transports.cCst�dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        N)r)r
rrr
�
pause_reading0szReadTransport.pause_readingcCst�dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        N)r)r
rrr
�resume_reading8szReadTransport.resume_readingN)rrrrrrrrrr
r-sc@sJeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dS)rz$Interface for write-only transports.NcCst�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        N)r)r
�high�lowrrr
�set_write_buffer_limitsDsz&WriteTransport.set_write_buffer_limitscCst�dS)z,Return the current size of the write buffer.N)r)r
rrr
�get_write_buffer_sizeYsz$WriteTransport.get_write_buffer_sizecCst�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        N)r)r
�datarrr
�write]szWriteTransport.writecCstj|�}|j|�dS)z�Write a list (or any iterable) of data bytes to the transport.

        The default implementation concatenates the arguments and
        calls write() on the result.
        N)rZflatten_list_bytesr$)r
Zlist_of_datar#rrr
�
writelineses
zWriteTransport.writelinescCst�dS)z�Close the write end after flushing buffered data.

        (This is like typing ^D into a UNIX program reading from stdin.)

        Data may still be received.
        N)r)r
rrr
�	write_eofnszWriteTransport.write_eofcCst�dS)zAReturn True if this transport supports write_eof(), False if not.N)r)r
rrr
�
can_write_eofwszWriteTransport.can_write_eofcCst�dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        N)r)r
rrr
�abort{szWriteTransport.abort)NN)rrrrr!r"r$r%r&r'r(rrrr
rAs
		c@seZdZdZdS)raSInterface representing a bidirectional transport.

    There may be several implementations, but typically, the user does
    not implement new transports; rather, the platform provides some
    useful transports that are implemented using the platform's best
    practices.

    The user never instantiates a transport directly; they call a
    utility function, passing it a protocol factory and other
    information necessary to create the transport and protocol.  (E.g.
    EventLoop.create_connection() or EventLoop.create_server().)

    The utility function will asynchronously create a transport and a
    protocol and hook them up by calling the protocol's
    connection_made() method, passing it the transport.

    The implementation here raises NotImplemented for every method
    except writelines(), which calls write() in a loop.
    N)rrrrrrrr
r�sc@s"eZdZdZddd�Zdd�ZdS)rz(Interface for datagram (UDP) transports.NcCst�dS)aSend data to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        addr is target socket address.
        If addr is None use target address pointed on transport creation.
        N)r)r
r#Zaddrrrr
�sendto�szDatagramTransport.sendtocCst�dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        N)r)r
rrr
r(�szDatagramTransport.abort)N)rrrrr)r(rrrr
r�s

c@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rcCst�dS)zGet subprocess id.N)r)r
rrr
�get_pid�szSubprocessTransport.get_pidcCst�dS)z�Get subprocess returncode.

        See also
        http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
        N)r)r
rrr
�get_returncode�sz"SubprocessTransport.get_returncodecCst�dS)z&Get transport for pipe with number fd.N)r)r
�fdrrr
�get_pipe_transport�sz&SubprocessTransport.get_pipe_transportcCst�dS)z�Send signal to subprocess.

        See also:
        docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
        N)r)r
�signalrrr
�send_signal�szSubprocessTransport.send_signalcCst�dS)aLStop the subprocess.

        Alias for close() method.

        On Posix OSs the method sends SIGTERM to the subprocess.
        On Windows the Win32 API function TerminateProcess()
         is called to stop the subprocess.

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
        N)r)r
rrr
�	terminate�szSubprocessTransport.terminatecCst�dS)z�Kill the subprocess.

        On Posix OSs the function sends SIGKILL to the subprocess.
        On Windows kill() is an alias for terminate().

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
        N)r)r
rrr
�kill�s	zSubprocessTransport.killN)	rrrr*r+r-r/r0r1rrrr
r�scsVeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zddd�Zdd
d�Z	dd�Z
�ZS)�_FlowControlMixinavAll the logic for (write) flow control in a mix-in base class.

    The subclass must implement get_write_buffer_size().  It must call
    _maybe_pause_protocol() whenever the write buffer size increases,
    and _maybe_resume_protocol() whenever it decreases.  It may also
    override set_write_buffer_limits() (e.g. to specify different
    defaults).

    The subclass constructor must call super().__init__(extra).  This
    will call set_write_buffer_limits().

    The user may call set_write_buffer_limits() and
    get_write_buffer_size(), and their protocol's pause_writing() and
    resume_writing() may be called.
    Ncs0t�j|�|dk	st�||_d|_|j�dS)NF)�superr�AssertionError�_loop�_protocol_paused�_set_write_buffer_limits)r
rZloop)�	__class__rr
r�s
z_FlowControlMixin.__init__cCsp|j�}||jkrdS|jsld|_y|jj�Wn:tk
rj}z|jjd|||jd��WYdd}~XnXdS)NTzprotocol.pause_writing() failed)�message�	exception�	transportr)r"�_high_waterr6�	_protocolZ
pause_writing�	Exceptionr5�call_exception_handler)r
�size�excrrr
�_maybe_pause_protocol�s
z'_FlowControlMixin._maybe_pause_protocolcCsh|jrd|j�|jkrdd|_y|jj�Wn:tk
rb}z|jjd|||jd��WYdd}~XnXdS)NFz protocol.resume_writing() failed)r9r:r;r)r6r"�
_low_waterr=Zresume_writingr>r5r?)r
rArrr
�_maybe_resume_protocolsz(_FlowControlMixin._maybe_resume_protocolcCs|j|jfS)N)rCr<)r
rrr
�get_write_buffer_limitssz)_FlowControlMixin.get_write_buffer_limitscCsf|dkr|dkrd}nd|}|dkr.|d}||ko@dknsVtd||f��||_||_dS)N�@i�rz*high (%r) must be >= low (%r) must be >= 0i)�
ValueErrorr<rC)r
rr rrr
r7sz*_FlowControlMixin._set_write_buffer_limitscCs|j||d�|j�dS)N)rr )r7rB)r
rr rrr
r!-sz)_FlowControlMixin.set_write_buffer_limitscCst�dS)N)r)r
rrr
r"1sz'_FlowControlMixin.get_write_buffer_size)NN)NN)NN)rrrrrrBrDrEr7r!r"�
__classcell__rr)r8r
r2�s

r2N)rZasyncior�__all__rrrrrrr2rrrr
�<module>s
#D4PK[̡��b3b3
futures.pynu�[���"""A Future class similar to the one in PEP 3148."""

__all__ = (
    'Future', 'wrap_future', 'isfuture',
)

import concurrent.futures
import contextvars
import logging
import sys

from . import base_futures
from . import events
from . import exceptions
from . import format_helpers


isfuture = base_futures.isfuture


_PENDING = base_futures._PENDING
_CANCELLED = base_futures._CANCELLED
_FINISHED = base_futures._FINISHED


STACK_DEBUG = logging.DEBUG - 1  # heavy-duty debugging


class Future:
    """This class is *almost* compatible with concurrent.futures.Future.

    Differences:

    - This class is not thread-safe.

    - result() and exception() do not take a timeout argument and
      raise an exception when the future isn't done yet.

    - Callbacks registered with add_done_callback() are always called
      via the event loop's call_soon().

    - This class is not compatible with the wait() and as_completed()
      methods in the concurrent.futures package.

    (In Python 3.4 or later we may be able to unify the implementations.)
    """

    # Class variables serving as defaults for instance variables.
    _state = _PENDING
    _result = None
    _exception = None
    _loop = None
    _source_traceback = None

    # This field is used for a dual purpose:
    # - Its presence is a marker to declare that a class implements
    #   the Future protocol (i.e. is intended to be duck-type compatible).
    #   The value must also be not-None, to enable a subclass to declare
    #   that it is not compatible by setting this to None.
    # - It is set by __iter__() below so that Task._step() can tell
    #   the difference between
    #   `await Future()` or`yield from Future()` (correct) vs.
    #   `yield Future()` (incorrect).
    _asyncio_future_blocking = False

    __log_traceback = False

    def __init__(self, *, loop=None):
        """Initialize the future.

        The optional event_loop argument allows explicitly setting the event
        loop object used by the future. If it's not provided, the future uses
        the default event loop.
        """
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
        self._callbacks = []
        if self._loop.get_debug():
            self._source_traceback = format_helpers.extract_stack(
                sys._getframe(1))

    _repr_info = base_futures._future_repr_info

    def __repr__(self):
        return '<{} {}>'.format(self.__class__.__name__,
                                ' '.join(self._repr_info()))

    def __del__(self):
        if not self.__log_traceback:
            # set_exception() was not called, or result() or exception()
            # has consumed the exception
            return
        exc = self._exception
        context = {
            'message':
                f'{self.__class__.__name__} exception was never retrieved',
            'exception': exc,
            'future': self,
        }
        if self._source_traceback:
            context['source_traceback'] = self._source_traceback
        self._loop.call_exception_handler(context)

    @property
    def _log_traceback(self):
        return self.__log_traceback

    @_log_traceback.setter
    def _log_traceback(self, val):
        if bool(val):
            raise ValueError('_log_traceback can only be set to False')
        self.__log_traceback = False

    def get_loop(self):
        """Return the event loop the Future is bound to."""
        loop = self._loop
        if loop is None:
            raise RuntimeError("Future object is not initialized.")
        return loop

    def cancel(self):
        """Cancel the future and schedule callbacks.

        If the future is already done or cancelled, return False.  Otherwise,
        change the future's state to cancelled, schedule the callbacks and
        return True.
        """
        self.__log_traceback = False
        if self._state != _PENDING:
            return False
        self._state = _CANCELLED
        self.__schedule_callbacks()
        return True

    def __schedule_callbacks(self):
        """Internal: Ask the event loop to call all callbacks.

        The callbacks are scheduled to be called as soon as possible. Also
        clears the callback list.
        """
        callbacks = self._callbacks[:]
        if not callbacks:
            return

        self._callbacks[:] = []
        for callback, ctx in callbacks:
            self._loop.call_soon(callback, self, context=ctx)

    def cancelled(self):
        """Return True if the future was cancelled."""
        return self._state == _CANCELLED

    # Don't implement running(); see http://bugs.python.org/issue18699

    def done(self):
        """Return True if the future is done.

        Done means either that a result / exception are available, or that the
        future was cancelled.
        """
        return self._state != _PENDING

    def result(self):
        """Return the result this future represents.

        If the future has been cancelled, raises CancelledError.  If the
        future's result isn't yet available, raises InvalidStateError.  If
        the future is done and has an exception set, this exception is raised.
        """
        if self._state == _CANCELLED:
            raise exceptions.CancelledError
        if self._state != _FINISHED:
            raise exceptions.InvalidStateError('Result is not ready.')
        self.__log_traceback = False
        if self._exception is not None:
            raise self._exception
        return self._result

    def exception(self):
        """Return the exception that was set on this future.

        The exception (or None if no exception was set) is returned only if
        the future is done.  If the future has been cancelled, raises
        CancelledError.  If the future isn't done yet, raises
        InvalidStateError.
        """
        if self._state == _CANCELLED:
            raise exceptions.CancelledError
        if self._state != _FINISHED:
            raise exceptions.InvalidStateError('Exception is not set.')
        self.__log_traceback = False
        return self._exception

    def add_done_callback(self, fn, *, context=None):
        """Add a callback to be run when the future becomes done.

        The callback is called with a single argument - the future object. If
        the future is already done when this is called, the callback is
        scheduled with call_soon.
        """
        if self._state != _PENDING:
            self._loop.call_soon(fn, self, context=context)
        else:
            if context is None:
                context = contextvars.copy_context()
            self._callbacks.append((fn, context))

    # New method not in PEP 3148.

    def remove_done_callback(self, fn):
        """Remove all instances of a callback from the "call when done" list.

        Returns the number of callbacks removed.
        """
        filtered_callbacks = [(f, ctx)
                              for (f, ctx) in self._callbacks
                              if f != fn]
        removed_count = len(self._callbacks) - len(filtered_callbacks)
        if removed_count:
            self._callbacks[:] = filtered_callbacks
        return removed_count

    # So-called internal methods (note: no set_running_or_notify_cancel()).

    def set_result(self, result):
        """Mark the future done and set its result.

        If the future is already done when this method is called, raises
        InvalidStateError.
        """
        if self._state != _PENDING:
            raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
        self._result = result
        self._state = _FINISHED
        self.__schedule_callbacks()

    def set_exception(self, exception):
        """Mark the future done and set an exception.

        If the future is already done when this method is called, raises
        InvalidStateError.
        """
        if self._state != _PENDING:
            raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
        if isinstance(exception, type):
            exception = exception()
        if type(exception) is StopIteration:
            raise TypeError("StopIteration interacts badly with generators "
                            "and cannot be raised into a Future")
        self._exception = exception
        self._state = _FINISHED
        self.__schedule_callbacks()
        self.__log_traceback = True

    def __await__(self):
        if not self.done():
            self._asyncio_future_blocking = True
            yield self  # This tells Task to wait for completion.
        if not self.done():
            raise RuntimeError("await wasn't used with future")
        return self.result()  # May raise too.

    __iter__ = __await__  # make compatible with 'yield from'.


# Needed for testing purposes.
_PyFuture = Future


def _get_loop(fut):
    # Tries to call Future.get_loop() if it's available.
    # Otherwise fallbacks to using the old '_loop' property.
    try:
        get_loop = fut.get_loop
    except AttributeError:
        pass
    else:
        return get_loop()
    return fut._loop


def _set_result_unless_cancelled(fut, result):
    """Helper setting the result only if the future was not cancelled."""
    if fut.cancelled():
        return
    fut.set_result(result)


def _convert_future_exc(exc):
    exc_class = type(exc)
    if exc_class is concurrent.futures.CancelledError:
        return exceptions.CancelledError(*exc.args)
    elif exc_class is concurrent.futures.TimeoutError:
        return exceptions.TimeoutError(*exc.args)
    elif exc_class is concurrent.futures.InvalidStateError:
        return exceptions.InvalidStateError(*exc.args)
    else:
        return exc


def _set_concurrent_future_state(concurrent, source):
    """Copy state from a future to a concurrent.futures.Future."""
    assert source.done()
    if source.cancelled():
        concurrent.cancel()
    if not concurrent.set_running_or_notify_cancel():
        return
    exception = source.exception()
    if exception is not None:
        concurrent.set_exception(_convert_future_exc(exception))
    else:
        result = source.result()
        concurrent.set_result(result)


def _copy_future_state(source, dest):
    """Internal helper to copy state from another Future.

    The other Future may be a concurrent.futures.Future.
    """
    assert source.done()
    if dest.cancelled():
        return
    assert not dest.done()
    if source.cancelled():
        dest.cancel()
    else:
        exception = source.exception()
        if exception is not None:
            dest.set_exception(_convert_future_exc(exception))
        else:
            result = source.result()
            dest.set_result(result)


def _chain_future(source, destination):
    """Chain two futures so that when one completes, so does the other.

    The result (or exception) of source will be copied to destination.
    If destination is cancelled, source gets cancelled too.
    Compatible with both asyncio.Future and concurrent.futures.Future.
    """
    if not isfuture(source) and not isinstance(source,
                                               concurrent.futures.Future):
        raise TypeError('A future is required for source argument')
    if not isfuture(destination) and not isinstance(destination,
                                                    concurrent.futures.Future):
        raise TypeError('A future is required for destination argument')
    source_loop = _get_loop(source) if isfuture(source) else None
    dest_loop = _get_loop(destination) if isfuture(destination) else None

    def _set_state(future, other):
        if isfuture(future):
            _copy_future_state(other, future)
        else:
            _set_concurrent_future_state(future, other)

    def _call_check_cancel(destination):
        if destination.cancelled():
            if source_loop is None or source_loop is dest_loop:
                source.cancel()
            else:
                source_loop.call_soon_threadsafe(source.cancel)

    def _call_set_state(source):
        if (destination.cancelled() and
                dest_loop is not None and dest_loop.is_closed()):
            return
        if dest_loop is None or dest_loop is source_loop:
            _set_state(destination, source)
        else:
            dest_loop.call_soon_threadsafe(_set_state, destination, source)

    destination.add_done_callback(_call_check_cancel)
    source.add_done_callback(_call_set_state)


def wrap_future(future, *, loop=None):
    """Wrap concurrent.futures.Future object."""
    if isfuture(future):
        return future
    assert isinstance(future, concurrent.futures.Future), \
        f'concurrent.futures.Future is expected, got {future!r}'
    if loop is None:
        loop = events.get_event_loop()
    new_future = loop.create_future()
    _chain_future(future, new_future)
    return new_future


try:
    import _asyncio
except ImportError:
    pass
else:
    # _CFuture is needed for tests.
    Future = _CFuture = _asyncio.Future
PK[a��ۿۿunix_events.pynu�[���"""Selector event loop for Unix with signal handling."""

import errno
import io
import itertools
import os
import selectors
import signal
import socket
import stat
import subprocess
import sys
import threading
import warnings

from . import base_events
from . import base_subprocess
from . import constants
from . import coroutines
from . import events
from . import exceptions
from . import futures
from . import selector_events
from . import tasks
from . import transports
from .log import logger


__all__ = (
    'SelectorEventLoop',
    'AbstractChildWatcher', 'SafeChildWatcher',
    'FastChildWatcher',
    'MultiLoopChildWatcher', 'ThreadedChildWatcher',
    'DefaultEventLoopPolicy',
)


if sys.platform == 'win32':  # pragma: no cover
    raise ImportError('Signals are not really supported on Windows')


def _sighandler_noop(signum, frame):
    """Dummy signal handler."""
    pass


class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
    """Unix event loop.

    Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
    """

    def __init__(self, selector=None):
        super().__init__(selector)
        self._signal_handlers = {}

    def close(self):
        super().close()
        if not sys.is_finalizing():
            for sig in list(self._signal_handlers):
                self.remove_signal_handler(sig)
        else:
            if self._signal_handlers:
                warnings.warn(f"Closing the loop {self!r} "
                              f"on interpreter shutdown "
                              f"stage, skipping signal handlers removal",
                              ResourceWarning,
                              source=self)
                self._signal_handlers.clear()

    def _process_self_data(self, data):
        for signum in data:
            if not signum:
                # ignore null bytes written by _write_to_self()
                continue
            self._handle_signal(signum)

    def add_signal_handler(self, sig, callback, *args):
        """Add a handler for a signal.  UNIX only.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        """
        if (coroutines.iscoroutine(callback) or
                coroutines.iscoroutinefunction(callback)):
            raise TypeError("coroutines cannot be used "
                            "with add_signal_handler()")
        self._check_signal(sig)
        self._check_closed()
        try:
            # set_wakeup_fd() raises ValueError if this is not the
            # main thread.  By calling it early we ensure that an
            # event loop running in another thread cannot add a signal
            # handler.
            signal.set_wakeup_fd(self._csock.fileno())
        except (ValueError, OSError) as exc:
            raise RuntimeError(str(exc))

        handle = events.Handle(callback, args, self, None)
        self._signal_handlers[sig] = handle

        try:
            # Register a dummy signal handler to ask Python to write the signal
            # number in the wakeup file descriptor. _process_self_data() will
            # read signal numbers from this file descriptor to handle signals.
            signal.signal(sig, _sighandler_noop)

            # Set SA_RESTART to limit EINTR occurrences.
            signal.siginterrupt(sig, False)
        except OSError as exc:
            del self._signal_handlers[sig]
            if not self._signal_handlers:
                try:
                    signal.set_wakeup_fd(-1)
                except (ValueError, OSError) as nexc:
                    logger.info('set_wakeup_fd(-1) failed: %s', nexc)

            if exc.errno == errno.EINVAL:
                raise RuntimeError(f'sig {sig} cannot be caught')
            else:
                raise

    def _handle_signal(self, sig):
        """Internal helper that is the actual signal handler."""
        handle = self._signal_handlers.get(sig)
        if handle is None:
            return  # Assume it's some race condition.
        if handle._cancelled:
            self.remove_signal_handler(sig)  # Remove it properly.
        else:
            self._add_callback_signalsafe(handle)

    def remove_signal_handler(self, sig):
        """Remove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        """
        self._check_signal(sig)
        try:
            del self._signal_handlers[sig]
        except KeyError:
            return False

        if sig == signal.SIGINT:
            handler = signal.default_int_handler
        else:
            handler = signal.SIG_DFL

        try:
            signal.signal(sig, handler)
        except OSError as exc:
            if exc.errno == errno.EINVAL:
                raise RuntimeError(f'sig {sig} cannot be caught')
            else:
                raise

        if not self._signal_handlers:
            try:
                signal.set_wakeup_fd(-1)
            except (ValueError, OSError) as exc:
                logger.info('set_wakeup_fd(-1) failed: %s', exc)

        return True

    def _check_signal(self, sig):
        """Internal helper to validate a signal.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        """
        if not isinstance(sig, int):
            raise TypeError(f'sig must be an int, not {sig!r}')

        if sig not in signal.valid_signals():
            raise ValueError(f'invalid signal number {sig}')

    def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
                                  extra=None):
        return _UnixReadPipeTransport(self, pipe, protocol, waiter, extra)

    def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
                                   extra=None):
        return _UnixWritePipeTransport(self, pipe, protocol, waiter, extra)

    async def _make_subprocess_transport(self, protocol, args, shell,
                                         stdin, stdout, stderr, bufsize,
                                         extra=None, **kwargs):
        with events.get_child_watcher() as watcher:
            if not watcher.is_active():
                # Check early.
                # Raising exception before process creation
                # prevents subprocess execution if the watcher
                # is not ready to handle it.
                raise RuntimeError("asyncio.get_child_watcher() is not activated, "
                                   "subprocess support is not installed.")
            waiter = self.create_future()
            transp = _UnixSubprocessTransport(self, protocol, args, shell,
                                              stdin, stdout, stderr, bufsize,
                                              waiter=waiter, extra=extra,
                                              **kwargs)

            watcher.add_child_handler(transp.get_pid(),
                                      self._child_watcher_callback, transp)
            try:
                await waiter
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException:
                transp.close()
                await transp._wait()
                raise

        return transp

    def _child_watcher_callback(self, pid, returncode, transp):
        self.call_soon_threadsafe(transp._process_exited, returncode)

    async def create_unix_connection(
            self, protocol_factory, path=None, *,
            ssl=None, sock=None,
            server_hostname=None,
            ssl_handshake_timeout=None):
        assert server_hostname is None or isinstance(server_hostname, str)
        if ssl:
            if server_hostname is None:
                raise ValueError(
                    'you have to pass server_hostname when using ssl')
        else:
            if server_hostname is not None:
                raise ValueError('server_hostname is only meaningful with ssl')
            if ssl_handshake_timeout is not None:
                raise ValueError(
                    'ssl_handshake_timeout is only meaningful with ssl')

        if path is not None:
            if sock is not None:
                raise ValueError(
                    'path and sock can not be specified at the same time')

            path = os.fspath(path)
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
            try:
                sock.setblocking(False)
                await self.sock_connect(sock, path)
            except:
                sock.close()
                raise

        else:
            if sock is None:
                raise ValueError('no path and sock were specified')
            if (sock.family != socket.AF_UNIX or
                    sock.type != socket.SOCK_STREAM):
                raise ValueError(
                    f'A UNIX Domain Stream Socket was expected, got {sock!r}')
            sock.setblocking(False)

        transport, protocol = await self._create_connection_transport(
            sock, protocol_factory, ssl, server_hostname,
            ssl_handshake_timeout=ssl_handshake_timeout)
        return transport, protocol

    async def create_unix_server(
            self, protocol_factory, path=None, *,
            sock=None, backlog=100, ssl=None,
            ssl_handshake_timeout=None,
            start_serving=True):
        if isinstance(ssl, bool):
            raise TypeError('ssl argument must be an SSLContext or None')

        if ssl_handshake_timeout is not None and not ssl:
            raise ValueError(
                'ssl_handshake_timeout is only meaningful with ssl')

        if path is not None:
            if sock is not None:
                raise ValueError(
                    'path and sock can not be specified at the same time')

            path = os.fspath(path)
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

            # Check for abstract socket. `str` and `bytes` paths are supported.
            if path[0] not in (0, '\x00'):
                try:
                    if stat.S_ISSOCK(os.stat(path).st_mode):
                        os.remove(path)
                except FileNotFoundError:
                    pass
                except OSError as err:
                    # Directory may have permissions only to create socket.
                    logger.error('Unable to check or remove stale UNIX socket '
                                 '%r: %r', path, err)

            try:
                sock.bind(path)
            except OSError as exc:
                sock.close()
                if exc.errno == errno.EADDRINUSE:
                    # Let's improve the error message by adding
                    # with what exact address it occurs.
                    msg = f'Address {path!r} is already in use'
                    raise OSError(errno.EADDRINUSE, msg) from None
                else:
                    raise
            except:
                sock.close()
                raise
        else:
            if sock is None:
                raise ValueError(
                    'path was not specified, and no sock specified')

            if (sock.family != socket.AF_UNIX or
                    sock.type != socket.SOCK_STREAM):
                raise ValueError(
                    f'A UNIX Domain Stream Socket was expected, got {sock!r}')

        sock.setblocking(False)
        server = base_events.Server(self, [sock], protocol_factory,
                                    ssl, backlog, ssl_handshake_timeout)
        if start_serving:
            server._start_serving()
            # Skip one loop iteration so that all 'loop.add_reader'
            # go through.
            await tasks.sleep(0, loop=self)

        return server

    async def _sock_sendfile_native(self, sock, file, offset, count):
        try:
            os.sendfile
        except AttributeError as exc:
            raise exceptions.SendfileNotAvailableError(
                "os.sendfile() is not available")
        try:
            fileno = file.fileno()
        except (AttributeError, io.UnsupportedOperation) as err:
            raise exceptions.SendfileNotAvailableError("not a regular file")
        try:
            fsize = os.fstat(fileno).st_size
        except OSError as err:
            raise exceptions.SendfileNotAvailableError("not a regular file")
        blocksize = count if count else fsize
        if not blocksize:
            return 0  # empty file

        fut = self.create_future()
        self._sock_sendfile_native_impl(fut, None, sock, fileno,
                                        offset, count, blocksize, 0)
        return await fut

    def _sock_sendfile_native_impl(self, fut, registered_fd, sock, fileno,
                                   offset, count, blocksize, total_sent):
        fd = sock.fileno()
        if registered_fd is not None:
            # Remove the callback early.  It should be rare that the
            # selector says the fd is ready but the call still returns
            # EAGAIN, and I am willing to take a hit in that case in
            # order to simplify the common case.
            self.remove_writer(registered_fd)
        if fut.cancelled():
            self._sock_sendfile_update_filepos(fileno, offset, total_sent)
            return
        if count:
            blocksize = count - total_sent
            if blocksize <= 0:
                self._sock_sendfile_update_filepos(fileno, offset, total_sent)
                fut.set_result(total_sent)
                return

        try:
            sent = os.sendfile(fd, fileno, offset, blocksize)
        except (BlockingIOError, InterruptedError):
            if registered_fd is None:
                self._sock_add_cancellation_callback(fut, sock)
            self.add_writer(fd, self._sock_sendfile_native_impl, fut,
                            fd, sock, fileno,
                            offset, count, blocksize, total_sent)
        except OSError as exc:
            if (registered_fd is not None and
                    exc.errno == errno.ENOTCONN and
                    type(exc) is not ConnectionError):
                # If we have an ENOTCONN and this isn't a first call to
                # sendfile(), i.e. the connection was closed in the middle
                # of the operation, normalize the error to ConnectionError
                # to make it consistent across all Posix systems.
                new_exc = ConnectionError(
                    "socket is not connected", errno.ENOTCONN)
                new_exc.__cause__ = exc
                exc = new_exc
            if total_sent == 0:
                # We can get here for different reasons, the main
                # one being 'file' is not a regular mmap(2)-like
                # file, in which case we'll fall back on using
                # plain send().
                err = exceptions.SendfileNotAvailableError(
                    "os.sendfile call failed")
                self._sock_sendfile_update_filepos(fileno, offset, total_sent)
                fut.set_exception(err)
            else:
                self._sock_sendfile_update_filepos(fileno, offset, total_sent)
                fut.set_exception(exc)
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._sock_sendfile_update_filepos(fileno, offset, total_sent)
            fut.set_exception(exc)
        else:
            if sent == 0:
                # EOF
                self._sock_sendfile_update_filepos(fileno, offset, total_sent)
                fut.set_result(total_sent)
            else:
                offset += sent
                total_sent += sent
                if registered_fd is None:
                    self._sock_add_cancellation_callback(fut, sock)
                self.add_writer(fd, self._sock_sendfile_native_impl, fut,
                                fd, sock, fileno,
                                offset, count, blocksize, total_sent)

    def _sock_sendfile_update_filepos(self, fileno, offset, total_sent):
        if total_sent > 0:
            os.lseek(fileno, offset, os.SEEK_SET)

    def _sock_add_cancellation_callback(self, fut, sock):
        def cb(fut):
            if fut.cancelled():
                fd = sock.fileno()
                if fd != -1:
                    self.remove_writer(fd)
        fut.add_done_callback(cb)


class _UnixReadPipeTransport(transports.ReadTransport):

    max_size = 256 * 1024  # max bytes we read in one event loop iteration

    def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
        super().__init__(extra)
        self._extra['pipe'] = pipe
        self._loop = loop
        self._pipe = pipe
        self._fileno = pipe.fileno()
        self._protocol = protocol
        self._closing = False
        self._paused = False

        mode = os.fstat(self._fileno).st_mode
        if not (stat.S_ISFIFO(mode) or
                stat.S_ISSOCK(mode) or
                stat.S_ISCHR(mode)):
            self._pipe = None
            self._fileno = None
            self._protocol = None
            raise ValueError("Pipe transport is for pipes/sockets only.")

        os.set_blocking(self._fileno, False)

        self._loop.call_soon(self._protocol.connection_made, self)
        # only start reading when connection_made() has been called
        self._loop.call_soon(self._loop._add_reader,
                             self._fileno, self._read_ready)
        if waiter is not None:
            # only wake up the waiter when connection_made() has been called
            self._loop.call_soon(futures._set_result_unless_cancelled,
                                 waiter, None)

    def __repr__(self):
        info = [self.__class__.__name__]
        if self._pipe is None:
            info.append('closed')
        elif self._closing:
            info.append('closing')
        info.append(f'fd={self._fileno}')
        selector = getattr(self._loop, '_selector', None)
        if self._pipe is not None and selector is not None:
            polling = selector_events._test_selector_event(
                selector, self._fileno, selectors.EVENT_READ)
            if polling:
                info.append('polling')
            else:
                info.append('idle')
        elif self._pipe is not None:
            info.append('open')
        else:
            info.append('closed')
        return '<{}>'.format(' '.join(info))

    def _read_ready(self):
        try:
            data = os.read(self._fileno, self.max_size)
        except (BlockingIOError, InterruptedError):
            pass
        except OSError as exc:
            self._fatal_error(exc, 'Fatal read error on pipe transport')
        else:
            if data:
                self._protocol.data_received(data)
            else:
                if self._loop.get_debug():
                    logger.info("%r was closed by peer", self)
                self._closing = True
                self._loop._remove_reader(self._fileno)
                self._loop.call_soon(self._protocol.eof_received)
                self._loop.call_soon(self._call_connection_lost, None)

    def pause_reading(self):
        if self._closing or self._paused:
            return
        self._paused = True
        self._loop._remove_reader(self._fileno)
        if self._loop.get_debug():
            logger.debug("%r pauses reading", self)

    def resume_reading(self):
        if self._closing or not self._paused:
            return
        self._paused = False
        self._loop._add_reader(self._fileno, self._read_ready)
        if self._loop.get_debug():
            logger.debug("%r resumes reading", self)

    def set_protocol(self, protocol):
        self._protocol = protocol

    def get_protocol(self):
        return self._protocol

    def is_closing(self):
        return self._closing

    def close(self):
        if not self._closing:
            self._close(None)

    def __del__(self, _warn=warnings.warn):
        if self._pipe is not None:
            _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
            self._pipe.close()

    def _fatal_error(self, exc, message='Fatal error on pipe transport'):
        # should be called by exception handler only
        if (isinstance(exc, OSError) and exc.errno == errno.EIO):
            if self._loop.get_debug():
                logger.debug("%r: %s", self, message, exc_info=True)
        else:
            self._loop.call_exception_handler({
                'message': message,
                'exception': exc,
                'transport': self,
                'protocol': self._protocol,
            })
        self._close(exc)

    def _close(self, exc):
        self._closing = True
        self._loop._remove_reader(self._fileno)
        self._loop.call_soon(self._call_connection_lost, exc)

    def _call_connection_lost(self, exc):
        try:
            self._protocol.connection_lost(exc)
        finally:
            self._pipe.close()
            self._pipe = None
            self._protocol = None
            self._loop = None


class _UnixWritePipeTransport(transports._FlowControlMixin,
                              transports.WriteTransport):

    def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
        super().__init__(extra, loop)
        self._extra['pipe'] = pipe
        self._pipe = pipe
        self._fileno = pipe.fileno()
        self._protocol = protocol
        self._buffer = bytearray()
        self._conn_lost = 0
        self._closing = False  # Set when close() or write_eof() called.

        mode = os.fstat(self._fileno).st_mode
        is_char = stat.S_ISCHR(mode)
        is_fifo = stat.S_ISFIFO(mode)
        is_socket = stat.S_ISSOCK(mode)
        if not (is_char or is_fifo or is_socket):
            self._pipe = None
            self._fileno = None
            self._protocol = None
            raise ValueError("Pipe transport is only for "
                             "pipes, sockets and character devices")

        os.set_blocking(self._fileno, False)
        self._loop.call_soon(self._protocol.connection_made, self)

        # On AIX, the reader trick (to be notified when the read end of the
        # socket is closed) only works for sockets. On other platforms it
        # works for pipes and sockets. (Exception: OS X 10.4?  Issue #19294.)
        if is_socket or (is_fifo and not sys.platform.startswith("aix")):
            # only start reading when connection_made() has been called
            self._loop.call_soon(self._loop._add_reader,
                                 self._fileno, self._read_ready)

        if waiter is not None:
            # only wake up the waiter when connection_made() has been called
            self._loop.call_soon(futures._set_result_unless_cancelled,
                                 waiter, None)

    def __repr__(self):
        info = [self.__class__.__name__]
        if self._pipe is None:
            info.append('closed')
        elif self._closing:
            info.append('closing')
        info.append(f'fd={self._fileno}')
        selector = getattr(self._loop, '_selector', None)
        if self._pipe is not None and selector is not None:
            polling = selector_events._test_selector_event(
                selector, self._fileno, selectors.EVENT_WRITE)
            if polling:
                info.append('polling')
            else:
                info.append('idle')

            bufsize = self.get_write_buffer_size()
            info.append(f'bufsize={bufsize}')
        elif self._pipe is not None:
            info.append('open')
        else:
            info.append('closed')
        return '<{}>'.format(' '.join(info))

    def get_write_buffer_size(self):
        return len(self._buffer)

    def _read_ready(self):
        # Pipe was closed by peer.
        if self._loop.get_debug():
            logger.info("%r was closed by peer", self)
        if self._buffer:
            self._close(BrokenPipeError())
        else:
            self._close()

    def write(self, data):
        assert isinstance(data, (bytes, bytearray, memoryview)), repr(data)
        if isinstance(data, bytearray):
            data = memoryview(data)
        if not data:
            return

        if self._conn_lost or self._closing:
            if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
                logger.warning('pipe closed by peer or '
                               'os.write(pipe, data) raised exception.')
            self._conn_lost += 1
            return

        if not self._buffer:
            # Attempt to send it right away first.
            try:
                n = os.write(self._fileno, data)
            except (BlockingIOError, InterruptedError):
                n = 0
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException as exc:
                self._conn_lost += 1
                self._fatal_error(exc, 'Fatal write error on pipe transport')
                return
            if n == len(data):
                return
            elif n > 0:
                data = memoryview(data)[n:]
            self._loop._add_writer(self._fileno, self._write_ready)

        self._buffer += data
        self._maybe_pause_protocol()

    def _write_ready(self):
        assert self._buffer, 'Data should not be empty'

        try:
            n = os.write(self._fileno, self._buffer)
        except (BlockingIOError, InterruptedError):
            pass
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._buffer.clear()
            self._conn_lost += 1
            # Remove writer here, _fatal_error() doesn't it
            # because _buffer is empty.
            self._loop._remove_writer(self._fileno)
            self._fatal_error(exc, 'Fatal write error on pipe transport')
        else:
            if n == len(self._buffer):
                self._buffer.clear()
                self._loop._remove_writer(self._fileno)
                self._maybe_resume_protocol()  # May append to buffer.
                if self._closing:
                    self._loop._remove_reader(self._fileno)
                    self._call_connection_lost(None)
                return
            elif n > 0:
                del self._buffer[:n]

    def can_write_eof(self):
        return True

    def write_eof(self):
        if self._closing:
            return
        assert self._pipe
        self._closing = True
        if not self._buffer:
            self._loop._remove_reader(self._fileno)
            self._loop.call_soon(self._call_connection_lost, None)

    def set_protocol(self, protocol):
        self._protocol = protocol

    def get_protocol(self):
        return self._protocol

    def is_closing(self):
        return self._closing

    def close(self):
        if self._pipe is not None and not self._closing:
            # write_eof is all what we needed to close the write pipe
            self.write_eof()

    def __del__(self, _warn=warnings.warn):
        if self._pipe is not None:
            _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
            self._pipe.close()

    def abort(self):
        self._close(None)

    def _fatal_error(self, exc, message='Fatal error on pipe transport'):
        # should be called by exception handler only
        if isinstance(exc, OSError):
            if self._loop.get_debug():
                logger.debug("%r: %s", self, message, exc_info=True)
        else:
            self._loop.call_exception_handler({
                'message': message,
                'exception': exc,
                'transport': self,
                'protocol': self._protocol,
            })
        self._close(exc)

    def _close(self, exc=None):
        self._closing = True
        if self._buffer:
            self._loop._remove_writer(self._fileno)
        self._buffer.clear()
        self._loop._remove_reader(self._fileno)
        self._loop.call_soon(self._call_connection_lost, exc)

    def _call_connection_lost(self, exc):
        try:
            self._protocol.connection_lost(exc)
        finally:
            self._pipe.close()
            self._pipe = None
            self._protocol = None
            self._loop = None


class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport):

    def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
        stdin_w = None
        if stdin == subprocess.PIPE:
            # Use a socket pair for stdin, since not all platforms
            # support selecting read events on the write end of a
            # socket (which we use in order to detect closing of the
            # other end).  Notably this is needed on AIX, and works
            # just fine on other platforms.
            stdin, stdin_w = socket.socketpair()
        try:
            self._proc = subprocess.Popen(
                args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
                universal_newlines=False, bufsize=bufsize, **kwargs)
            if stdin_w is not None:
                stdin.close()
                self._proc.stdin = open(stdin_w.detach(), 'wb', buffering=bufsize)
                stdin_w = None
        finally:
            if stdin_w is not None:
                stdin.close()
                stdin_w.close()


class AbstractChildWatcher:
    """Abstract base class for monitoring child processes.

    Objects derived from this class monitor a collection of subprocesses and
    report their termination or interruption by a signal.

    New callbacks are registered with .add_child_handler(). Starting a new
    process must be done within a 'with' block to allow the watcher to suspend
    its activity until the new process if fully registered (this is needed to
    prevent a race condition in some implementations).

    Example:
        with watcher:
            proc = subprocess.Popen("sleep 1")
            watcher.add_child_handler(proc.pid, callback)

    Notes:
        Implementations of this class must be thread-safe.

        Since child watcher objects may catch the SIGCHLD signal and call
        waitpid(-1), there should be only one active object per process.
    """

    def add_child_handler(self, pid, callback, *args):
        """Register a new child handler.

        Arrange for callback(pid, returncode, *args) to be called when
        process 'pid' terminates. Specifying another callback for the same
        process replaces the previous handler.

        Note: callback() must be thread-safe.
        """
        raise NotImplementedError()

    def remove_child_handler(self, pid):
        """Removes the handler for process 'pid'.

        The function returns True if the handler was successfully removed,
        False if there was nothing to remove."""

        raise NotImplementedError()

    def attach_loop(self, loop):
        """Attach the watcher to an event loop.

        If the watcher was previously attached to an event loop, then it is
        first detached before attaching to the new loop.

        Note: loop may be None.
        """
        raise NotImplementedError()

    def close(self):
        """Close the watcher.

        This must be called to make sure that any underlying resource is freed.
        """
        raise NotImplementedError()

    def is_active(self):
        """Return ``True`` if the watcher is active and is used by the event loop.

        Return True if the watcher is installed and ready to handle process exit
        notifications.

        """
        raise NotImplementedError()

    def __enter__(self):
        """Enter the watcher's context and allow starting new processes

        This function must return self"""
        raise NotImplementedError()

    def __exit__(self, a, b, c):
        """Exit the watcher's context"""
        raise NotImplementedError()


def _compute_returncode(status):
    if os.WIFSIGNALED(status):
        # The child process died because of a signal.
        return -os.WTERMSIG(status)
    elif os.WIFEXITED(status):
        # The child process exited (e.g sys.exit()).
        return os.WEXITSTATUS(status)
    else:
        # The child exited, but we don't understand its status.
        # This shouldn't happen, but if it does, let's just
        # return that status; perhaps that helps debug it.
        return status


class BaseChildWatcher(AbstractChildWatcher):

    def __init__(self):
        self._loop = None
        self._callbacks = {}

    def close(self):
        self.attach_loop(None)

    def is_active(self):
        return self._loop is not None and self._loop.is_running()

    def _do_waitpid(self, expected_pid):
        raise NotImplementedError()

    def _do_waitpid_all(self):
        raise NotImplementedError()

    def attach_loop(self, loop):
        assert loop is None or isinstance(loop, events.AbstractEventLoop)

        if self._loop is not None and loop is None and self._callbacks:
            warnings.warn(
                'A loop is being detached '
                'from a child watcher with pending handlers',
                RuntimeWarning)

        if self._loop is not None:
            self._loop.remove_signal_handler(signal.SIGCHLD)

        self._loop = loop
        if loop is not None:
            loop.add_signal_handler(signal.SIGCHLD, self._sig_chld)

            # Prevent a race condition in case a child terminated
            # during the switch.
            self._do_waitpid_all()

    def _sig_chld(self):
        try:
            self._do_waitpid_all()
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            # self._loop should always be available here
            # as '_sig_chld' is added as a signal handler
            # in 'attach_loop'
            self._loop.call_exception_handler({
                'message': 'Unknown exception in SIGCHLD handler',
                'exception': exc,
            })


class SafeChildWatcher(BaseChildWatcher):
    """'Safe' child watcher implementation.

    This implementation avoids disrupting other code spawning processes by
    polling explicitly each process in the SIGCHLD handler instead of calling
    os.waitpid(-1).

    This is a safe solution but it has a significant overhead when handling a
    big number of children (O(n) each time SIGCHLD is raised)
    """

    def close(self):
        self._callbacks.clear()
        super().close()

    def __enter__(self):
        return self

    def __exit__(self, a, b, c):
        pass

    def add_child_handler(self, pid, callback, *args):
        self._callbacks[pid] = (callback, args)

        # Prevent a race condition in case the child is already terminated.
        self._do_waitpid(pid)

    def remove_child_handler(self, pid):
        try:
            del self._callbacks[pid]
            return True
        except KeyError:
            return False

    def _do_waitpid_all(self):

        for pid in list(self._callbacks):
            self._do_waitpid(pid)

    def _do_waitpid(self, expected_pid):
        assert expected_pid > 0

        try:
            pid, status = os.waitpid(expected_pid, os.WNOHANG)
        except ChildProcessError:
            # The child process is already reaped
            # (may happen if waitpid() is called elsewhere).
            pid = expected_pid
            returncode = 255
            logger.warning(
                "Unknown child process pid %d, will report returncode 255",
                pid)
        else:
            if pid == 0:
                # The child process is still alive.
                return

            returncode = _compute_returncode(status)
            if self._loop.get_debug():
                logger.debug('process %s exited with returncode %s',
                             expected_pid, returncode)

        try:
            callback, args = self._callbacks.pop(pid)
        except KeyError:  # pragma: no cover
            # May happen if .remove_child_handler() is called
            # after os.waitpid() returns.
            if self._loop.get_debug():
                logger.warning("Child watcher got an unexpected pid: %r",
                               pid, exc_info=True)
        else:
            callback(pid, returncode, *args)


class FastChildWatcher(BaseChildWatcher):
    """'Fast' child watcher implementation.

    This implementation reaps every terminated processes by calling
    os.waitpid(-1) directly, possibly breaking other code spawning processes
    and waiting for their termination.

    There is no noticeable overhead when handling a big number of children
    (O(1) each time a child terminates).
    """
    def __init__(self):
        super().__init__()
        self._lock = threading.Lock()
        self._zombies = {}
        self._forks = 0

    def close(self):
        self._callbacks.clear()
        self._zombies.clear()
        super().close()

    def __enter__(self):
        with self._lock:
            self._forks += 1

            return self

    def __exit__(self, a, b, c):
        with self._lock:
            self._forks -= 1

            if self._forks or not self._zombies:
                return

            collateral_victims = str(self._zombies)
            self._zombies.clear()

        logger.warning(
            "Caught subprocesses termination from unknown pids: %s",
            collateral_victims)

    def add_child_handler(self, pid, callback, *args):
        assert self._forks, "Must use the context manager"

        with self._lock:
            try:
                returncode = self._zombies.pop(pid)
            except KeyError:
                # The child is running.
                self._callbacks[pid] = callback, args
                return

        # The child is dead already. We can fire the callback.
        callback(pid, returncode, *args)

    def remove_child_handler(self, pid):
        try:
            del self._callbacks[pid]
            return True
        except KeyError:
            return False

    def _do_waitpid_all(self):
        # Because of signal coalescing, we must keep calling waitpid() as
        # long as we're able to reap a child.
        while True:
            try:
                pid, status = os.waitpid(-1, os.WNOHANG)
            except ChildProcessError:
                # No more child processes exist.
                return
            else:
                if pid == 0:
                    # A child process is still alive.
                    return

                returncode = _compute_returncode(status)

            with self._lock:
                try:
                    callback, args = self._callbacks.pop(pid)
                except KeyError:
                    # unknown child
                    if self._forks:
                        # It may not be registered yet.
                        self._zombies[pid] = returncode
                        if self._loop.get_debug():
                            logger.debug('unknown process %s exited '
                                         'with returncode %s',
                                         pid, returncode)
                        continue
                    callback = None
                else:
                    if self._loop.get_debug():
                        logger.debug('process %s exited with returncode %s',
                                     pid, returncode)

            if callback is None:
                logger.warning(
                    "Caught subprocess termination from unknown pid: "
                    "%d -> %d", pid, returncode)
            else:
                callback(pid, returncode, *args)


class MultiLoopChildWatcher(AbstractChildWatcher):
    """A watcher that doesn't require running loop in the main thread.

    This implementation registers a SIGCHLD signal handler on
    instantiation (which may conflict with other code that
    install own handler for this signal).

    The solution is safe but it has a significant overhead when
    handling a big number of processes (*O(n)* each time a
    SIGCHLD is received).
    """

    # Implementation note:
    # The class keeps compatibility with AbstractChildWatcher ABC
    # To achieve this it has empty attach_loop() method
    # and doesn't accept explicit loop argument
    # for add_child_handler()/remove_child_handler()
    # but retrieves the current loop by get_running_loop()

    def __init__(self):
        self._callbacks = {}
        self._saved_sighandler = None

    def is_active(self):
        return self._saved_sighandler is not None

    def close(self):
        self._callbacks.clear()
        if self._saved_sighandler is None:
            return

        handler = signal.getsignal(signal.SIGCHLD)
        if handler != self._sig_chld:
            logger.warning("SIGCHLD handler was changed by outside code")
        else:
            signal.signal(signal.SIGCHLD, self._saved_sighandler)
        self._saved_sighandler = None

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    def add_child_handler(self, pid, callback, *args):
        loop = events.get_running_loop()
        self._callbacks[pid] = (loop, callback, args)

        # Prevent a race condition in case the child is already terminated.
        self._do_waitpid(pid)

    def remove_child_handler(self, pid):
        try:
            del self._callbacks[pid]
            return True
        except KeyError:
            return False

    def attach_loop(self, loop):
        # Don't save the loop but initialize itself if called first time
        # The reason to do it here is that attach_loop() is called from
        # unix policy only for the main thread.
        # Main thread is required for subscription on SIGCHLD signal
        if self._saved_sighandler is not None:
            return

        self._saved_sighandler = signal.signal(signal.SIGCHLD, self._sig_chld)
        if self._saved_sighandler is None:
            logger.warning("Previous SIGCHLD handler was set by non-Python code, "
                           "restore to default handler on watcher close.")
            self._saved_sighandler = signal.SIG_DFL

        # Set SA_RESTART to limit EINTR occurrences.
        signal.siginterrupt(signal.SIGCHLD, False)

    def _do_waitpid_all(self):
        for pid in list(self._callbacks):
            self._do_waitpid(pid)

    def _do_waitpid(self, expected_pid):
        assert expected_pid > 0

        try:
            pid, status = os.waitpid(expected_pid, os.WNOHANG)
        except ChildProcessError:
            # The child process is already reaped
            # (may happen if waitpid() is called elsewhere).
            pid = expected_pid
            returncode = 255
            logger.warning(
                "Unknown child process pid %d, will report returncode 255",
                pid)
            debug_log = False
        else:
            if pid == 0:
                # The child process is still alive.
                return

            returncode = _compute_returncode(status)
            debug_log = True
        try:
            loop, callback, args = self._callbacks.pop(pid)
        except KeyError:  # pragma: no cover
            # May happen if .remove_child_handler() is called
            # after os.waitpid() returns.
            logger.warning("Child watcher got an unexpected pid: %r",
                           pid, exc_info=True)
        else:
            if loop.is_closed():
                logger.warning("Loop %r that handles pid %r is closed", loop, pid)
            else:
                if debug_log and loop.get_debug():
                    logger.debug('process %s exited with returncode %s',
                                 expected_pid, returncode)
                loop.call_soon_threadsafe(callback, pid, returncode, *args)

    def _sig_chld(self, signum, frame):
        try:
            self._do_waitpid_all()
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException:
            logger.warning('Unknown exception in SIGCHLD handler', exc_info=True)


class ThreadedChildWatcher(AbstractChildWatcher):
    """Threaded child watcher implementation.

    The watcher uses a thread per process
    for waiting for the process finish.

    It doesn't require subscription on POSIX signal
    but a thread creation is not free.

    The watcher has O(1) complexity, its performance doesn't depend
    on amount of spawn processes.
    """

    def __init__(self):
        self._pid_counter = itertools.count(0)
        self._threads = {}

    def is_active(self):
        return True

    def close(self):
        self._join_threads()

    def _join_threads(self):
        """Internal: Join all non-daemon threads"""
        threads = [thread for thread in list(self._threads.values())
                   if thread.is_alive() and not thread.daemon]
        for thread in threads:
            thread.join()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    def __del__(self, _warn=warnings.warn):
        threads = [thread for thread in list(self._threads.values())
                   if thread.is_alive()]
        if threads:
            _warn(f"{self.__class__} has registered but not finished child processes",
                  ResourceWarning,
                  source=self)

    def add_child_handler(self, pid, callback, *args):
        loop = events.get_running_loop()
        thread = threading.Thread(target=self._do_waitpid,
                                  name=f"waitpid-{next(self._pid_counter)}",
                                  args=(loop, pid, callback, args),
                                  daemon=True)
        self._threads[pid] = thread
        thread.start()

    def remove_child_handler(self, pid):
        # asyncio never calls remove_child_handler() !!!
        # The method is no-op but is implemented because
        # abstract base classe requires it
        return True

    def attach_loop(self, loop):
        pass

    def _do_waitpid(self, loop, expected_pid, callback, args):
        assert expected_pid > 0

        try:
            pid, status = os.waitpid(expected_pid, 0)
        except ChildProcessError:
            # The child process is already reaped
            # (may happen if waitpid() is called elsewhere).
            pid = expected_pid
            returncode = 255
            logger.warning(
                "Unknown child process pid %d, will report returncode 255",
                pid)
        else:
            returncode = _compute_returncode(status)
            if loop.get_debug():
                logger.debug('process %s exited with returncode %s',
                             expected_pid, returncode)

        if loop.is_closed():
            logger.warning("Loop %r that handles pid %r is closed", loop, pid)
        else:
            loop.call_soon_threadsafe(callback, pid, returncode, *args)

        self._threads.pop(expected_pid)


class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
    """UNIX event loop policy with a watcher for child processes."""
    _loop_factory = _UnixSelectorEventLoop

    def __init__(self):
        super().__init__()
        self._watcher = None

    def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = ThreadedChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop)

    def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if (self._watcher is not None and
                isinstance(threading.current_thread(), threading._MainThread)):
            self._watcher.attach_loop(loop)

    def get_child_watcher(self):
        """Get the watcher for child processes.

        If not yet set, a ThreadedChildWatcher object is automatically created.
        """
        if self._watcher is None:
            self._init_watcher()

        return self._watcher

    def set_child_watcher(self, watcher):
        """Set the watcher for child processes."""

        assert watcher is None or isinstance(watcher, AbstractChildWatcher)

        if self._watcher is not None:
            self._watcher.close()

        self._watcher = watcher


SelectorEventLoop = _UnixSelectorEventLoop
DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy
PK[����

base_futures.pynu�[���__all__ = ()

import reprlib
from _thread import get_ident

from . import format_helpers

# States for Future.
_PENDING = 'PENDING'
_CANCELLED = 'CANCELLED'
_FINISHED = 'FINISHED'


def isfuture(obj):
    """Check for a Future.

    This returns True when obj is a Future instance or is advertising
    itself as duck-type compatible by setting _asyncio_future_blocking.
    See comment in Future for more details.
    """
    return (hasattr(obj.__class__, '_asyncio_future_blocking') and
            obj._asyncio_future_blocking is not None)


def _format_callbacks(cb):
    """helper function for Future.__repr__"""
    size = len(cb)
    if not size:
        cb = ''

    def format_cb(callback):
        return format_helpers._format_callback_source(callback, ())

    if size == 1:
        cb = format_cb(cb[0][0])
    elif size == 2:
        cb = '{}, {}'.format(format_cb(cb[0][0]), format_cb(cb[1][0]))
    elif size > 2:
        cb = '{}, <{} more>, {}'.format(format_cb(cb[0][0]),
                                        size - 2,
                                        format_cb(cb[-1][0]))
    return f'cb=[{cb}]'


# bpo-42183: _repr_running is needed for repr protection
# when a Future or Task result contains itself directly or indirectly.
# The logic is borrowed from @reprlib.recursive_repr decorator.
# Unfortunately, the direct decorator usage is impossible because of
# AttributeError: '_asyncio.Task' object has no attribute '__module__' error.
#
# After fixing this thing we can return to the decorator based approach.
_repr_running = set()


def _future_repr_info(future):
    # (Future) -> str
    """helper function for Future.__repr__"""
    info = [future._state.lower()]
    if future._state == _FINISHED:
        if future._exception is not None:
            info.append(f'exception={future._exception!r}')
        else:
            key = id(future), get_ident()
            if key in _repr_running:
                result = '...'
            else:
                _repr_running.add(key)
                try:
                    # use reprlib to limit the length of the output, especially
                    # for very long strings
                    result = reprlib.repr(future._result)
                finally:
                    _repr_running.discard(key)
            info.append(f'result={result}')
    if future._callbacks:
        info.append(_format_callbacks(future._callbacks))
    if future._source_traceback:
        frame = future._source_traceback[-1]
        info.append(f'created at {frame[0]}:{frame[1]}')
    return info
PK[E{C�||log.pynu�[���"""Logging configuration."""

import logging


# Name the logger after the package.
logger = logging.getLogger(__package__)
PK[��n�	�	
base_tasks.pynu�[���import linecache
import traceback

from . import base_futures
from . import coroutines


def _task_repr_info(task):
    info = base_futures._future_repr_info(task)

    if task._must_cancel:
        # replace status
        info[0] = 'cancelling'

    info.insert(1, 'name=%r' % task.get_name())

    coro = coroutines._format_coroutine(task._coro)
    info.insert(2, f'coro=<{coro}>')

    if task._fut_waiter is not None:
        info.insert(3, f'wait_for={task._fut_waiter!r}')
    return info


def _task_get_stack(task, limit):
    frames = []
    if hasattr(task._coro, 'cr_frame'):
        # case 1: 'async def' coroutines
        f = task._coro.cr_frame
    elif hasattr(task._coro, 'gi_frame'):
        # case 2: legacy coroutines
        f = task._coro.gi_frame
    elif hasattr(task._coro, 'ag_frame'):
        # case 3: async generators
        f = task._coro.ag_frame
    else:
        # case 4: unknown objects
        f = None
    if f is not None:
        while f is not None:
            if limit is not None:
                if limit <= 0:
                    break
                limit -= 1
            frames.append(f)
            f = f.f_back
        frames.reverse()
    elif task._exception is not None:
        tb = task._exception.__traceback__
        while tb is not None:
            if limit is not None:
                if limit <= 0:
                    break
                limit -= 1
            frames.append(tb.tb_frame)
            tb = tb.tb_next
    return frames


def _task_print_stack(task, limit, file):
    extracted_list = []
    checked = set()
    for f in task.get_stack(limit=limit):
        lineno = f.f_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        if filename not in checked:
            checked.add(filename)
            linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        extracted_list.append((filename, lineno, name, line))

    exc = task._exception
    if not extracted_list:
        print(f'No stack for {task!r}', file=file)
    elif exc is not None:
        print(f'Traceback for {task!r} (most recent call last):', file=file)
    else:
        print(f'Stack for {task!r} (most recent call last):', file=file)

    traceback.print_list(extracted_list, file=file)
    if exc is not None:
        for line in traceback.format_exception_only(exc.__class__, exc):
            print(line, file=file, end='')
PK['J��i�i�windows_events.pynu�[���"""Selector and proactor event loops for Windows."""

import _overlapped
import _winapi
import errno
import math
import msvcrt
import socket
import struct
import time
import weakref

from . import events
from . import base_subprocess
from . import futures
from . import exceptions
from . import proactor_events
from . import selector_events
from . import tasks
from . import windows_utils
from .log import logger


__all__ = (
    'SelectorEventLoop', 'ProactorEventLoop', 'IocpProactor',
    'DefaultEventLoopPolicy', 'WindowsSelectorEventLoopPolicy',
    'WindowsProactorEventLoopPolicy',
)


NULL = 0
INFINITE = 0xffffffff
ERROR_CONNECTION_REFUSED = 1225
ERROR_CONNECTION_ABORTED = 1236

# Initial delay in seconds for connect_pipe() before retrying to connect
CONNECT_PIPE_INIT_DELAY = 0.001

# Maximum delay in seconds for connect_pipe() before retrying to connect
CONNECT_PIPE_MAX_DELAY = 0.100


class _OverlappedFuture(futures.Future):
    """Subclass of Future which represents an overlapped operation.

    Cancelling it will immediately cancel the overlapped operation.
    """

    def __init__(self, ov, *, loop=None):
        super().__init__(loop=loop)
        if self._source_traceback:
            del self._source_traceback[-1]
        self._ov = ov

    def _repr_info(self):
        info = super()._repr_info()
        if self._ov is not None:
            state = 'pending' if self._ov.pending else 'completed'
            info.insert(1, f'overlapped=<{state}, {self._ov.address:#x}>')
        return info

    def _cancel_overlapped(self):
        if self._ov is None:
            return
        try:
            self._ov.cancel()
        except OSError as exc:
            context = {
                'message': 'Cancelling an overlapped future failed',
                'exception': exc,
                'future': self,
            }
            if self._source_traceback:
                context['source_traceback'] = self._source_traceback
            self._loop.call_exception_handler(context)
        self._ov = None

    def cancel(self):
        self._cancel_overlapped()
        return super().cancel()

    def set_exception(self, exception):
        super().set_exception(exception)
        self._cancel_overlapped()

    def set_result(self, result):
        super().set_result(result)
        self._ov = None


class _BaseWaitHandleFuture(futures.Future):
    """Subclass of Future which represents a wait handle."""

    def __init__(self, ov, handle, wait_handle, *, loop=None):
        super().__init__(loop=loop)
        if self._source_traceback:
            del self._source_traceback[-1]
        # Keep a reference to the Overlapped object to keep it alive until the
        # wait is unregistered
        self._ov = ov
        self._handle = handle
        self._wait_handle = wait_handle

        # Should we call UnregisterWaitEx() if the wait completes
        # or is cancelled?
        self._registered = True

    def _poll(self):
        # non-blocking wait: use a timeout of 0 millisecond
        return (_winapi.WaitForSingleObject(self._handle, 0) ==
                _winapi.WAIT_OBJECT_0)

    def _repr_info(self):
        info = super()._repr_info()
        info.append(f'handle={self._handle:#x}')
        if self._handle is not None:
            state = 'signaled' if self._poll() else 'waiting'
            info.append(state)
        if self._wait_handle is not None:
            info.append(f'wait_handle={self._wait_handle:#x}')
        return info

    def _unregister_wait_cb(self, fut):
        # The wait was unregistered: it's not safe to destroy the Overlapped
        # object
        self._ov = None

    def _unregister_wait(self):
        if not self._registered:
            return
        self._registered = False

        wait_handle = self._wait_handle
        self._wait_handle = None
        try:
            _overlapped.UnregisterWait(wait_handle)
        except OSError as exc:
            if exc.winerror != _overlapped.ERROR_IO_PENDING:
                context = {
                    'message': 'Failed to unregister the wait handle',
                    'exception': exc,
                    'future': self,
                }
                if self._source_traceback:
                    context['source_traceback'] = self._source_traceback
                self._loop.call_exception_handler(context)
                return
            # ERROR_IO_PENDING means that the unregister is pending

        self._unregister_wait_cb(None)

    def cancel(self):
        self._unregister_wait()
        return super().cancel()

    def set_exception(self, exception):
        self._unregister_wait()
        super().set_exception(exception)

    def set_result(self, result):
        self._unregister_wait()
        super().set_result(result)


class _WaitCancelFuture(_BaseWaitHandleFuture):
    """Subclass of Future which represents a wait for the cancellation of a
    _WaitHandleFuture using an event.
    """

    def __init__(self, ov, event, wait_handle, *, loop=None):
        super().__init__(ov, event, wait_handle, loop=loop)

        self._done_callback = None

    def cancel(self):
        raise RuntimeError("_WaitCancelFuture must not be cancelled")

    def set_result(self, result):
        super().set_result(result)
        if self._done_callback is not None:
            self._done_callback(self)

    def set_exception(self, exception):
        super().set_exception(exception)
        if self._done_callback is not None:
            self._done_callback(self)


class _WaitHandleFuture(_BaseWaitHandleFuture):
    def __init__(self, ov, handle, wait_handle, proactor, *, loop=None):
        super().__init__(ov, handle, wait_handle, loop=loop)
        self._proactor = proactor
        self._unregister_proactor = True
        self._event = _overlapped.CreateEvent(None, True, False, None)
        self._event_fut = None

    def _unregister_wait_cb(self, fut):
        if self._event is not None:
            _winapi.CloseHandle(self._event)
            self._event = None
            self._event_fut = None

        # If the wait was cancelled, the wait may never be signalled, so
        # it's required to unregister it. Otherwise, IocpProactor.close() will
        # wait forever for an event which will never come.
        #
        # If the IocpProactor already received the event, it's safe to call
        # _unregister() because we kept a reference to the Overlapped object
        # which is used as a unique key.
        self._proactor._unregister(self._ov)
        self._proactor = None

        super()._unregister_wait_cb(fut)

    def _unregister_wait(self):
        if not self._registered:
            return
        self._registered = False

        wait_handle = self._wait_handle
        self._wait_handle = None
        try:
            _overlapped.UnregisterWaitEx(wait_handle, self._event)
        except OSError as exc:
            if exc.winerror != _overlapped.ERROR_IO_PENDING:
                context = {
                    'message': 'Failed to unregister the wait handle',
                    'exception': exc,
                    'future': self,
                }
                if self._source_traceback:
                    context['source_traceback'] = self._source_traceback
                self._loop.call_exception_handler(context)
                return
            # ERROR_IO_PENDING is not an error, the wait was unregistered

        self._event_fut = self._proactor._wait_cancel(self._event,
                                                      self._unregister_wait_cb)


class PipeServer(object):
    """Class representing a pipe server.

    This is much like a bound, listening socket.
    """
    def __init__(self, address):
        self._address = address
        self._free_instances = weakref.WeakSet()
        # initialize the pipe attribute before calling _server_pipe_handle()
        # because this function can raise an exception and the destructor calls
        # the close() method
        self._pipe = None
        self._accept_pipe_future = None
        self._pipe = self._server_pipe_handle(True)

    def _get_unconnected_pipe(self):
        # Create new instance and return previous one.  This ensures
        # that (until the server is closed) there is always at least
        # one pipe handle for address.  Therefore if a client attempt
        # to connect it will not fail with FileNotFoundError.
        tmp, self._pipe = self._pipe, self._server_pipe_handle(False)
        return tmp

    def _server_pipe_handle(self, first):
        # Return a wrapper for a new pipe handle.
        if self.closed():
            return None
        flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
        if first:
            flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
        h = _winapi.CreateNamedPipe(
            self._address, flags,
            _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
            _winapi.PIPE_WAIT,
            _winapi.PIPE_UNLIMITED_INSTANCES,
            windows_utils.BUFSIZE, windows_utils.BUFSIZE,
            _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
        pipe = windows_utils.PipeHandle(h)
        self._free_instances.add(pipe)
        return pipe

    def closed(self):
        return (self._address is None)

    def close(self):
        if self._accept_pipe_future is not None:
            self._accept_pipe_future.cancel()
            self._accept_pipe_future = None
        # Close all instances which have not been connected to by a client.
        if self._address is not None:
            for pipe in self._free_instances:
                pipe.close()
            self._pipe = None
            self._address = None
            self._free_instances.clear()

    __del__ = close


class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop):
    """Windows version of selector event loop."""


class ProactorEventLoop(proactor_events.BaseProactorEventLoop):
    """Windows version of proactor event loop using IOCP."""

    def __init__(self, proactor=None):
        if proactor is None:
            proactor = IocpProactor()
        super().__init__(proactor)

    def run_forever(self):
        try:
            assert self._self_reading_future is None
            self.call_soon(self._loop_self_reading)
            super().run_forever()
        finally:
            if self._self_reading_future is not None:
                ov = self._self_reading_future._ov
                self._self_reading_future.cancel()
                # self_reading_future was just cancelled so if it hasn't been
                # finished yet, it never will be (it's possible that it has
                # already finished and its callback is waiting in the queue,
                # where it could still happen if the event loop is restarted).
                # Unregister it otherwise IocpProactor.close will wait for it
                # forever
                if ov is not None:
                    self._proactor._unregister(ov)
                self._self_reading_future = None

    async def create_pipe_connection(self, protocol_factory, address):
        f = self._proactor.connect_pipe(address)
        pipe = await f
        protocol = protocol_factory()
        trans = self._make_duplex_pipe_transport(pipe, protocol,
                                                 extra={'addr': address})
        return trans, protocol

    async def start_serving_pipe(self, protocol_factory, address):
        server = PipeServer(address)

        def loop_accept_pipe(f=None):
            pipe = None
            try:
                if f:
                    pipe = f.result()
                    server._free_instances.discard(pipe)

                    if server.closed():
                        # A client connected before the server was closed:
                        # drop the client (close the pipe) and exit
                        pipe.close()
                        return

                    protocol = protocol_factory()
                    self._make_duplex_pipe_transport(
                        pipe, protocol, extra={'addr': address})

                pipe = server._get_unconnected_pipe()
                if pipe is None:
                    return

                f = self._proactor.accept_pipe(pipe)
            except OSError as exc:
                if pipe and pipe.fileno() != -1:
                    self.call_exception_handler({
                        'message': 'Pipe accept failed',
                        'exception': exc,
                        'pipe': pipe,
                    })
                    pipe.close()
                elif self._debug:
                    logger.warning("Accept pipe failed on pipe %r",
                                   pipe, exc_info=True)
            except exceptions.CancelledError:
                if pipe:
                    pipe.close()
            else:
                server._accept_pipe_future = f
                f.add_done_callback(loop_accept_pipe)

        self.call_soon(loop_accept_pipe)
        return [server]

    async def _make_subprocess_transport(self, protocol, args, shell,
                                         stdin, stdout, stderr, bufsize,
                                         extra=None, **kwargs):
        waiter = self.create_future()
        transp = _WindowsSubprocessTransport(self, protocol, args, shell,
                                             stdin, stdout, stderr, bufsize,
                                             waiter=waiter, extra=extra,
                                             **kwargs)
        try:
            await waiter
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException:
            transp.close()
            await transp._wait()
            raise

        return transp


class IocpProactor:
    """Proactor implementation using IOCP."""

    def __init__(self, concurrency=0xffffffff):
        self._loop = None
        self._results = []
        self._iocp = _overlapped.CreateIoCompletionPort(
            _overlapped.INVALID_HANDLE_VALUE, NULL, 0, concurrency)
        self._cache = {}
        self._registered = weakref.WeakSet()
        self._unregistered = []
        self._stopped_serving = weakref.WeakSet()

    def _check_closed(self):
        if self._iocp is None:
            raise RuntimeError('IocpProactor is closed')

    def __repr__(self):
        info = ['overlapped#=%s' % len(self._cache),
                'result#=%s' % len(self._results)]
        if self._iocp is None:
            info.append('closed')
        return '<%s %s>' % (self.__class__.__name__, " ".join(info))

    def set_loop(self, loop):
        self._loop = loop

    def select(self, timeout=None):
        if not self._results:
            self._poll(timeout)
        tmp = self._results
        self._results = []
        return tmp

    def _result(self, value):
        fut = self._loop.create_future()
        fut.set_result(value)
        return fut

    def recv(self, conn, nbytes, flags=0):
        self._register_with_iocp(conn)
        ov = _overlapped.Overlapped(NULL)
        try:
            if isinstance(conn, socket.socket):
                ov.WSARecv(conn.fileno(), nbytes, flags)
            else:
                ov.ReadFile(conn.fileno(), nbytes)
        except BrokenPipeError:
            return self._result(b'')

        def finish_recv(trans, key, ov):
            try:
                return ov.getresult()
            except OSError as exc:
                if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
                                    _overlapped.ERROR_OPERATION_ABORTED):
                    raise ConnectionResetError(*exc.args)
                else:
                    raise

        return self._register(ov, conn, finish_recv)

    def recv_into(self, conn, buf, flags=0):
        self._register_with_iocp(conn)
        ov = _overlapped.Overlapped(NULL)
        try:
            if isinstance(conn, socket.socket):
                ov.WSARecvInto(conn.fileno(), buf, flags)
            else:
                ov.ReadFileInto(conn.fileno(), buf)
        except BrokenPipeError:
            return self._result(0)

        def finish_recv(trans, key, ov):
            try:
                return ov.getresult()
            except OSError as exc:
                if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
                                    _overlapped.ERROR_OPERATION_ABORTED):
                    raise ConnectionResetError(*exc.args)
                else:
                    raise

        return self._register(ov, conn, finish_recv)

    def recvfrom(self, conn, nbytes, flags=0):
        self._register_with_iocp(conn)
        ov = _overlapped.Overlapped(NULL)
        try:
            ov.WSARecvFrom(conn.fileno(), nbytes, flags)
        except BrokenPipeError:
            return self._result((b'', None))

        def finish_recv(trans, key, ov):
            try:
                return ov.getresult()
            except OSError as exc:
                if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
                                    _overlapped.ERROR_OPERATION_ABORTED):
                    raise ConnectionResetError(*exc.args)
                else:
                    raise

        return self._register(ov, conn, finish_recv)

    def sendto(self, conn, buf, flags=0, addr=None):
        self._register_with_iocp(conn)
        ov = _overlapped.Overlapped(NULL)

        ov.WSASendTo(conn.fileno(), buf, flags, addr)

        def finish_send(trans, key, ov):
            try:
                return ov.getresult()
            except OSError as exc:
                if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
                                    _overlapped.ERROR_OPERATION_ABORTED):
                    raise ConnectionResetError(*exc.args)
                else:
                    raise

        return self._register(ov, conn, finish_send)

    def send(self, conn, buf, flags=0):
        self._register_with_iocp(conn)
        ov = _overlapped.Overlapped(NULL)
        if isinstance(conn, socket.socket):
            ov.WSASend(conn.fileno(), buf, flags)
        else:
            ov.WriteFile(conn.fileno(), buf)

        def finish_send(trans, key, ov):
            try:
                return ov.getresult()
            except OSError as exc:
                if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
                                    _overlapped.ERROR_OPERATION_ABORTED):
                    raise ConnectionResetError(*exc.args)
                else:
                    raise

        return self._register(ov, conn, finish_send)

    def accept(self, listener):
        self._register_with_iocp(listener)
        conn = self._get_accept_socket(listener.family)
        ov = _overlapped.Overlapped(NULL)
        ov.AcceptEx(listener.fileno(), conn.fileno())

        def finish_accept(trans, key, ov):
            ov.getresult()
            # Use SO_UPDATE_ACCEPT_CONTEXT so getsockname() etc work.
            buf = struct.pack('@P', listener.fileno())
            conn.setsockopt(socket.SOL_SOCKET,
                            _overlapped.SO_UPDATE_ACCEPT_CONTEXT, buf)
            conn.settimeout(listener.gettimeout())
            return conn, conn.getpeername()

        async def accept_coro(future, conn):
            # Coroutine closing the accept socket if the future is cancelled
            try:
                await future
            except exceptions.CancelledError:
                conn.close()
                raise

        future = self._register(ov, listener, finish_accept)
        coro = accept_coro(future, conn)
        tasks.ensure_future(coro, loop=self._loop)
        return future

    def connect(self, conn, address):
        if conn.type == socket.SOCK_DGRAM:
            # WSAConnect will complete immediately for UDP sockets so we don't
            # need to register any IOCP operation
            _overlapped.WSAConnect(conn.fileno(), address)
            fut = self._loop.create_future()
            fut.set_result(None)
            return fut

        self._register_with_iocp(conn)
        # The socket needs to be locally bound before we call ConnectEx().
        try:
            _overlapped.BindLocal(conn.fileno(), conn.family)
        except OSError as e:
            if e.winerror != errno.WSAEINVAL:
                raise
            # Probably already locally bound; check using getsockname().
            if conn.getsockname()[1] == 0:
                raise
        ov = _overlapped.Overlapped(NULL)
        ov.ConnectEx(conn.fileno(), address)

        def finish_connect(trans, key, ov):
            ov.getresult()
            # Use SO_UPDATE_CONNECT_CONTEXT so getsockname() etc work.
            conn.setsockopt(socket.SOL_SOCKET,
                            _overlapped.SO_UPDATE_CONNECT_CONTEXT, 0)
            return conn

        return self._register(ov, conn, finish_connect)

    def sendfile(self, sock, file, offset, count):
        self._register_with_iocp(sock)
        ov = _overlapped.Overlapped(NULL)
        offset_low = offset & 0xffff_ffff
        offset_high = (offset >> 32) & 0xffff_ffff
        ov.TransmitFile(sock.fileno(),
                        msvcrt.get_osfhandle(file.fileno()),
                        offset_low, offset_high,
                        count, 0, 0)

        def finish_sendfile(trans, key, ov):
            try:
                return ov.getresult()
            except OSError as exc:
                if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
                                    _overlapped.ERROR_OPERATION_ABORTED):
                    raise ConnectionResetError(*exc.args)
                else:
                    raise
        return self._register(ov, sock, finish_sendfile)

    def accept_pipe(self, pipe):
        self._register_with_iocp(pipe)
        ov = _overlapped.Overlapped(NULL)
        connected = ov.ConnectNamedPipe(pipe.fileno())

        if connected:
            # ConnectNamePipe() failed with ERROR_PIPE_CONNECTED which means
            # that the pipe is connected. There is no need to wait for the
            # completion of the connection.
            return self._result(pipe)

        def finish_accept_pipe(trans, key, ov):
            ov.getresult()
            return pipe

        return self._register(ov, pipe, finish_accept_pipe)

    async def connect_pipe(self, address):
        delay = CONNECT_PIPE_INIT_DELAY
        while True:
            # Unfortunately there is no way to do an overlapped connect to
            # a pipe.  Call CreateFile() in a loop until it doesn't fail with
            # ERROR_PIPE_BUSY.
            try:
                handle = _overlapped.ConnectPipe(address)
                break
            except OSError as exc:
                if exc.winerror != _overlapped.ERROR_PIPE_BUSY:
                    raise

            # ConnectPipe() failed with ERROR_PIPE_BUSY: retry later
            delay = min(delay * 2, CONNECT_PIPE_MAX_DELAY)
            await tasks.sleep(delay)

        return windows_utils.PipeHandle(handle)

    def wait_for_handle(self, handle, timeout=None):
        """Wait for a handle.

        Return a Future object. The result of the future is True if the wait
        completed, or False if the wait did not complete (on timeout).
        """
        return self._wait_for_handle(handle, timeout, False)

    def _wait_cancel(self, event, done_callback):
        fut = self._wait_for_handle(event, None, True)
        # add_done_callback() cannot be used because the wait may only complete
        # in IocpProactor.close(), while the event loop is not running.
        fut._done_callback = done_callback
        return fut

    def _wait_for_handle(self, handle, timeout, _is_cancel):
        self._check_closed()

        if timeout is None:
            ms = _winapi.INFINITE
        else:
            # RegisterWaitForSingleObject() has a resolution of 1 millisecond,
            # round away from zero to wait *at least* timeout seconds.
            ms = math.ceil(timeout * 1e3)

        # We only create ov so we can use ov.address as a key for the cache.
        ov = _overlapped.Overlapped(NULL)
        wait_handle = _overlapped.RegisterWaitWithQueue(
            handle, self._iocp, ov.address, ms)
        if _is_cancel:
            f = _WaitCancelFuture(ov, handle, wait_handle, loop=self._loop)
        else:
            f = _WaitHandleFuture(ov, handle, wait_handle, self,
                                  loop=self._loop)
        if f._source_traceback:
            del f._source_traceback[-1]

        def finish_wait_for_handle(trans, key, ov):
            # Note that this second wait means that we should only use
            # this with handles types where a successful wait has no
            # effect.  So events or processes are all right, but locks
            # or semaphores are not.  Also note if the handle is
            # signalled and then quickly reset, then we may return
            # False even though we have not timed out.
            return f._poll()

        self._cache[ov.address] = (f, ov, 0, finish_wait_for_handle)
        return f

    def _register_with_iocp(self, obj):
        # To get notifications of finished ops on this objects sent to the
        # completion port, were must register the handle.
        if obj not in self._registered:
            self._registered.add(obj)
            _overlapped.CreateIoCompletionPort(obj.fileno(), self._iocp, 0, 0)
            # XXX We could also use SetFileCompletionNotificationModes()
            # to avoid sending notifications to completion port of ops
            # that succeed immediately.

    def _register(self, ov, obj, callback):
        self._check_closed()

        # Return a future which will be set with the result of the
        # operation when it completes.  The future's value is actually
        # the value returned by callback().
        f = _OverlappedFuture(ov, loop=self._loop)
        if f._source_traceback:
            del f._source_traceback[-1]
        if not ov.pending:
            # The operation has completed, so no need to postpone the
            # work.  We cannot take this short cut if we need the
            # NumberOfBytes, CompletionKey values returned by
            # PostQueuedCompletionStatus().
            try:
                value = callback(None, None, ov)
            except OSError as e:
                f.set_exception(e)
            else:
                f.set_result(value)
            # Even if GetOverlappedResult() was called, we have to wait for the
            # notification of the completion in GetQueuedCompletionStatus().
            # Register the overlapped operation to keep a reference to the
            # OVERLAPPED object, otherwise the memory is freed and Windows may
            # read uninitialized memory.

        # Register the overlapped operation for later.  Note that
        # we only store obj to prevent it from being garbage
        # collected too early.
        self._cache[ov.address] = (f, ov, obj, callback)
        return f

    def _unregister(self, ov):
        """Unregister an overlapped object.

        Call this method when its future has been cancelled. The event can
        already be signalled (pending in the proactor event queue). It is also
        safe if the event is never signalled (because it was cancelled).
        """
        self._check_closed()
        self._unregistered.append(ov)

    def _get_accept_socket(self, family):
        s = socket.socket(family)
        s.settimeout(0)
        return s

    def _poll(self, timeout=None):
        if timeout is None:
            ms = INFINITE
        elif timeout < 0:
            raise ValueError("negative timeout")
        else:
            # GetQueuedCompletionStatus() has a resolution of 1 millisecond,
            # round away from zero to wait *at least* timeout seconds.
            ms = math.ceil(timeout * 1e3)
            if ms >= INFINITE:
                raise ValueError("timeout too big")

        while True:
            status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
            if status is None:
                break
            ms = 0

            err, transferred, key, address = status
            try:
                f, ov, obj, callback = self._cache.pop(address)
            except KeyError:
                if self._loop.get_debug():
                    self._loop.call_exception_handler({
                        'message': ('GetQueuedCompletionStatus() returned an '
                                    'unexpected event'),
                        'status': ('err=%s transferred=%s key=%#x address=%#x'
                                   % (err, transferred, key, address)),
                    })

                # key is either zero, or it is used to return a pipe
                # handle which should be closed to avoid a leak.
                if key not in (0, _overlapped.INVALID_HANDLE_VALUE):
                    _winapi.CloseHandle(key)
                continue

            if obj in self._stopped_serving:
                f.cancel()
            # Don't call the callback if _register() already read the result or
            # if the overlapped has been cancelled
            elif not f.done():
                try:
                    value = callback(transferred, key, ov)
                except OSError as e:
                    f.set_exception(e)
                    self._results.append(f)
                else:
                    f.set_result(value)
                    self._results.append(f)

        # Remove unregistered futures
        for ov in self._unregistered:
            self._cache.pop(ov.address, None)
        self._unregistered.clear()

    def _stop_serving(self, obj):
        # obj is a socket or pipe handle.  It will be closed in
        # BaseProactorEventLoop._stop_serving() which will make any
        # pending operations fail quickly.
        self._stopped_serving.add(obj)

    def close(self):
        if self._iocp is None:
            # already closed
            return

        # Cancel remaining registered operations.
        for address, (fut, ov, obj, callback) in list(self._cache.items()):
            if fut.cancelled():
                # Nothing to do with cancelled futures
                pass
            elif isinstance(fut, _WaitCancelFuture):
                # _WaitCancelFuture must not be cancelled
                pass
            else:
                try:
                    fut.cancel()
                except OSError as exc:
                    if self._loop is not None:
                        context = {
                            'message': 'Cancelling a future failed',
                            'exception': exc,
                            'future': fut,
                        }
                        if fut._source_traceback:
                            context['source_traceback'] = fut._source_traceback
                        self._loop.call_exception_handler(context)

        # Wait until all cancelled overlapped complete: don't exit with running
        # overlapped to prevent a crash. Display progress every second if the
        # loop is still running.
        msg_update = 1.0
        start_time = time.monotonic()
        next_msg = start_time + msg_update
        while self._cache:
            if next_msg <= time.monotonic():
                logger.debug('%r is running after closing for %.1f seconds',
                             self, time.monotonic() - start_time)
                next_msg = time.monotonic() + msg_update

            # handle a few events, or timeout
            self._poll(msg_update)

        self._results = []

        _winapi.CloseHandle(self._iocp)
        self._iocp = None

    def __del__(self):
        self.close()


class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):

    def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
        self._proc = windows_utils.Popen(
            args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
            bufsize=bufsize, **kwargs)

        def callback(f):
            returncode = self._proc.poll()
            self._process_exited(returncode)

        f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
        f.add_done_callback(callback)


SelectorEventLoop = _WindowsSelectorEventLoop


class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
    _loop_factory = SelectorEventLoop


class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
    _loop_factory = ProactorEventLoop


DefaultEventLoopPolicy = WindowsProactorEventLoopPolicy
PK[������__init__.pynu�[���"""The asyncio package, tracking PEP 3156."""

# flake8: noqa

import sys

# This relies on each of the submodules having an __all__ variable.
from .base_events import *
from .coroutines import *
from .events import *
from .exceptions import *
from .futures import *
from .locks import *
from .protocols import *
from .runners import *
from .queues import *
from .streams import *
from .subprocess import *
from .tasks import *
from .transports import *

# Exposed for _asynciomodule.c to implement now deprecated
# Task.all_tasks() method.  This function will be removed in 3.9.
from .tasks import _all_tasks_compat  # NoQA

__all__ = (base_events.__all__ +
           coroutines.__all__ +
           events.__all__ +
           exceptions.__all__ +
           futures.__all__ +
           locks.__all__ +
           protocols.__all__ +
           runners.__all__ +
           queues.__all__ +
           streams.__all__ +
           subprocess.__all__ +
           tasks.__all__ +
           transports.__all__)

if sys.platform == 'win32':  # pragma: no cover
    from .windows_events import *
    __all__ += windows_events.__all__
else:
    from .unix_events import *  # pragma: no cover
    __all__ += unix_events.__all__
PK[0��  	queues.pynu�[���__all__ = ('Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty')

import collections
import heapq
import warnings

from . import events
from . import locks


class QueueEmpty(Exception):
    """Raised when Queue.get_nowait() is called on an empty Queue."""
    pass


class QueueFull(Exception):
    """Raised when the Queue.put_nowait() method is called on a full Queue."""
    pass


class Queue:
    """A queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "await put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded asyncio application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    """

    def __init__(self, maxsize=0, *, loop=None):
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)
        self._maxsize = maxsize

        # Futures.
        self._getters = collections.deque()
        # Futures.
        self._putters = collections.deque()
        self._unfinished_tasks = 0
        self._finished = locks.Event(loop=loop)
        self._finished.set()
        self._init(maxsize)

    # These three are overridable in subclasses.

    def _init(self, maxsize):
        self._queue = collections.deque()

    def _get(self):
        return self._queue.popleft()

    def _put(self, item):
        self._queue.append(item)

    # End of the overridable methods.

    def _wakeup_next(self, waiters):
        # Wake up the next waiter (if any) that isn't cancelled.
        while waiters:
            waiter = waiters.popleft()
            if not waiter.done():
                waiter.set_result(None)
                break

    def __repr__(self):
        return f'<{type(self).__name__} at {id(self):#x} {self._format()}>'

    def __str__(self):
        return f'<{type(self).__name__} {self._format()}>'

    def _format(self):
        result = f'maxsize={self._maxsize!r}'
        if getattr(self, '_queue', None):
            result += f' _queue={list(self._queue)!r}'
        if self._getters:
            result += f' _getters[{len(self._getters)}]'
        if self._putters:
            result += f' _putters[{len(self._putters)}]'
        if self._unfinished_tasks:
            result += f' tasks={self._unfinished_tasks}'
        return result

    def qsize(self):
        """Number of items in the queue."""
        return len(self._queue)

    @property
    def maxsize(self):
        """Number of items allowed in the queue."""
        return self._maxsize

    def empty(self):
        """Return True if the queue is empty, False otherwise."""
        return not self._queue

    def full(self):
        """Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        """
        if self._maxsize <= 0:
            return False
        else:
            return self.qsize() >= self._maxsize

    async def put(self, item):
        """Put an item into the queue.

        Put an item into the queue. If the queue is full, wait until a free
        slot is available before adding item.
        """
        while self.full():
            putter = self._loop.create_future()
            self._putters.append(putter)
            try:
                await putter
            except:
                putter.cancel()  # Just in case putter is not done yet.
                try:
                    # Clean self._putters from canceled putters.
                    self._putters.remove(putter)
                except ValueError:
                    # The putter could be removed from self._putters by a
                    # previous get_nowait call.
                    pass
                if not self.full() and not putter.cancelled():
                    # We were woken up by get_nowait(), but can't take
                    # the call.  Wake up the next in line.
                    self._wakeup_next(self._putters)
                raise
        return self.put_nowait(item)

    def put_nowait(self, item):
        """Put an item into the queue without blocking.

        If no free slot is immediately available, raise QueueFull.
        """
        if self.full():
            raise QueueFull
        self._put(item)
        self._unfinished_tasks += 1
        self._finished.clear()
        self._wakeup_next(self._getters)

    async def get(self):
        """Remove and return an item from the queue.

        If queue is empty, wait until an item is available.
        """
        while self.empty():
            getter = self._loop.create_future()
            self._getters.append(getter)
            try:
                await getter
            except:
                getter.cancel()  # Just in case getter is not done yet.
                try:
                    # Clean self._getters from canceled getters.
                    self._getters.remove(getter)
                except ValueError:
                    # The getter could be removed from self._getters by a
                    # previous put_nowait call.
                    pass
                if not self.empty() and not getter.cancelled():
                    # We were woken up by put_nowait(), but can't take
                    # the call.  Wake up the next in line.
                    self._wakeup_next(self._getters)
                raise
        return self.get_nowait()

    def get_nowait(self):
        """Remove and return an item from the queue.

        Return an item if one is immediately available, else raise QueueEmpty.
        """
        if self.empty():
            raise QueueEmpty
        item = self._get()
        self._wakeup_next(self._putters)
        return item

    def task_done(self):
        """Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).

        Raises ValueError if called more times than there were items placed in
        the queue.
        """
        if self._unfinished_tasks <= 0:
            raise ValueError('task_done() called too many times')
        self._unfinished_tasks -= 1
        if self._unfinished_tasks == 0:
            self._finished.set()

    async def join(self):
        """Block until all items in the queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer calls task_done() to
        indicate that the item was retrieved and all work on it is complete.
        When the count of unfinished tasks drops to zero, join() unblocks.
        """
        if self._unfinished_tasks > 0:
            await self._finished.wait()


class PriorityQueue(Queue):
    """A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    """

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item, heappush=heapq.heappush):
        heappush(self._queue, item)

    def _get(self, heappop=heapq.heappop):
        return heappop(self._queue)


class LifoQueue(Queue):
    """A subclass of Queue that retrieves most recently added entries first."""

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item):
        self._queue.append(item)

    def _get(self):
        return self._queue.pop()
PK[VW�<}<}proactor_events.pynu�[���"""Event loop using a proactor and related classes.

A proactor is a "notify-on-completion" multiplexer.  Currently a
proactor is only implemented on Windows with IOCP.
"""

__all__ = 'BaseProactorEventLoop',

import io
import os
import socket
import warnings
import signal
import threading
import collections

from . import base_events
from . import constants
from . import futures
from . import exceptions
from . import protocols
from . import sslproto
from . import transports
from . import trsock
from .log import logger


def _set_socket_extra(transport, sock):
    transport._extra['socket'] = trsock.TransportSocket(sock)

    try:
        transport._extra['sockname'] = sock.getsockname()
    except socket.error:
        if transport._loop.get_debug():
            logger.warning(
                "getsockname() failed on %r", sock, exc_info=True)

    if 'peername' not in transport._extra:
        try:
            transport._extra['peername'] = sock.getpeername()
        except socket.error:
            # UDP sockets may not have a peer name
            transport._extra['peername'] = None


class _ProactorBasePipeTransport(transports._FlowControlMixin,
                                 transports.BaseTransport):
    """Base class for pipe and socket transports."""

    def __init__(self, loop, sock, protocol, waiter=None,
                 extra=None, server=None):
        super().__init__(extra, loop)
        self._set_extra(sock)
        self._sock = sock
        self.set_protocol(protocol)
        self._server = server
        self._buffer = None  # None or bytearray.
        self._read_fut = None
        self._write_fut = None
        self._pending_write = 0
        self._conn_lost = 0
        self._closing = False  # Set when close() called.
        self._eof_written = False
        if self._server is not None:
            self._server._attach()
        self._loop.call_soon(self._protocol.connection_made, self)
        if waiter is not None:
            # only wake up the waiter when connection_made() has been called
            self._loop.call_soon(futures._set_result_unless_cancelled,
                                 waiter, None)

    def __repr__(self):
        info = [self.__class__.__name__]
        if self._sock is None:
            info.append('closed')
        elif self._closing:
            info.append('closing')
        if self._sock is not None:
            info.append(f'fd={self._sock.fileno()}')
        if self._read_fut is not None:
            info.append(f'read={self._read_fut!r}')
        if self._write_fut is not None:
            info.append(f'write={self._write_fut!r}')
        if self._buffer:
            info.append(f'write_bufsize={len(self._buffer)}')
        if self._eof_written:
            info.append('EOF written')
        return '<{}>'.format(' '.join(info))

    def _set_extra(self, sock):
        self._extra['pipe'] = sock

    def set_protocol(self, protocol):
        self._protocol = protocol

    def get_protocol(self):
        return self._protocol

    def is_closing(self):
        return self._closing

    def close(self):
        if self._closing:
            return
        self._closing = True
        self._conn_lost += 1
        if not self._buffer and self._write_fut is None:
            self._loop.call_soon(self._call_connection_lost, None)
        if self._read_fut is not None:
            self._read_fut.cancel()
            self._read_fut = None

    def __del__(self, _warn=warnings.warn):
        if self._sock is not None:
            _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
            self.close()

    def _fatal_error(self, exc, message='Fatal error on pipe transport'):
        try:
            if isinstance(exc, OSError):
                if self._loop.get_debug():
                    logger.debug("%r: %s", self, message, exc_info=True)
            else:
                self._loop.call_exception_handler({
                    'message': message,
                    'exception': exc,
                    'transport': self,
                    'protocol': self._protocol,
                })
        finally:
            self._force_close(exc)

    def _force_close(self, exc):
        if self._empty_waiter is not None and not self._empty_waiter.done():
            if exc is None:
                self._empty_waiter.set_result(None)
            else:
                self._empty_waiter.set_exception(exc)
        if self._closing:
            return
        self._closing = True
        self._conn_lost += 1
        if self._write_fut:
            self._write_fut.cancel()
            self._write_fut = None
        if self._read_fut:
            self._read_fut.cancel()
            self._read_fut = None
        self._pending_write = 0
        self._buffer = None
        self._loop.call_soon(self._call_connection_lost, exc)

    def _call_connection_lost(self, exc):
        try:
            self._protocol.connection_lost(exc)
        finally:
            # XXX If there is a pending overlapped read on the other
            # end then it may fail with ERROR_NETNAME_DELETED if we
            # just close our end.  First calling shutdown() seems to
            # cure it, but maybe using DisconnectEx() would be better.
            if hasattr(self._sock, 'shutdown'):
                self._sock.shutdown(socket.SHUT_RDWR)
            self._sock.close()
            self._sock = None
            server = self._server
            if server is not None:
                server._detach()
                self._server = None

    def get_write_buffer_size(self):
        size = self._pending_write
        if self._buffer is not None:
            size += len(self._buffer)
        return size


class _ProactorReadPipeTransport(_ProactorBasePipeTransport,
                                 transports.ReadTransport):
    """Transport for read pipes."""

    def __init__(self, loop, sock, protocol, waiter=None,
                 extra=None, server=None):
        self._pending_data = None
        self._paused = True
        super().__init__(loop, sock, protocol, waiter, extra, server)

        self._loop.call_soon(self._loop_reading)
        self._paused = False

    def is_reading(self):
        return not self._paused and not self._closing

    def pause_reading(self):
        if self._closing or self._paused:
            return
        self._paused = True

        # bpo-33694: Don't cancel self._read_fut because cancelling an
        # overlapped WSASend() loss silently data with the current proactor
        # implementation.
        #
        # If CancelIoEx() fails with ERROR_NOT_FOUND, it means that WSASend()
        # completed (even if HasOverlappedIoCompleted() returns 0), but
        # Overlapped.cancel() currently silently ignores the ERROR_NOT_FOUND
        # error. Once the overlapped is ignored, the IOCP loop will ignores the
        # completion I/O event and so not read the result of the overlapped
        # WSARecv().

        if self._loop.get_debug():
            logger.debug("%r pauses reading", self)

    def resume_reading(self):
        if self._closing or not self._paused:
            return

        self._paused = False
        if self._read_fut is None:
            self._loop.call_soon(self._loop_reading, None)

        data = self._pending_data
        self._pending_data = None
        if data is not None:
            # Call the protocol methode after calling _loop_reading(),
            # since the protocol can decide to pause reading again.
            self._loop.call_soon(self._data_received, data)

        if self._loop.get_debug():
            logger.debug("%r resumes reading", self)

    def _eof_received(self):
        if self._loop.get_debug():
            logger.debug("%r received EOF", self)

        try:
            keep_open = self._protocol.eof_received()
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self._fatal_error(
                exc, 'Fatal error: protocol.eof_received() call failed.')
            return

        if not keep_open:
            self.close()

    def _data_received(self, data):
        if self._paused:
            # Don't call any protocol method while reading is paused.
            # The protocol will be called on resume_reading().
            assert self._pending_data is None
            self._pending_data = data
            return

        if not data:
            self._eof_received()
            return

        if isinstance(self._protocol, protocols.BufferedProtocol):
            try:
                protocols._feed_data_to_buffered_proto(self._protocol, data)
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException as exc:
                self._fatal_error(exc,
                                  'Fatal error: protocol.buffer_updated() '
                                  'call failed.')
                return
        else:
            self._protocol.data_received(data)

    def _loop_reading(self, fut=None):
        data = None
        try:
            if fut is not None:
                assert self._read_fut is fut or (self._read_fut is None and
                                                 self._closing)
                self._read_fut = None
                if fut.done():
                    # deliver data later in "finally" clause
                    data = fut.result()
                else:
                    # the future will be replaced by next proactor.recv call
                    fut.cancel()

            if self._closing:
                # since close() has been called we ignore any read data
                data = None
                return

            if data == b'':
                # we got end-of-file so no need to reschedule a new read
                return

            # bpo-33694: buffer_updated() has currently no fast path because of
            # a data loss issue caused by overlapped WSASend() cancellation.

            if not self._paused:
                # reschedule a new read
                self._read_fut = self._loop._proactor.recv(self._sock, 32768)
        except ConnectionAbortedError as exc:
            if not self._closing:
                self._fatal_error(exc, 'Fatal read error on pipe transport')
            elif self._loop.get_debug():
                logger.debug("Read error on pipe transport while closing",
                             exc_info=True)
        except ConnectionResetError as exc:
            self._force_close(exc)
        except OSError as exc:
            self._fatal_error(exc, 'Fatal read error on pipe transport')
        except exceptions.CancelledError:
            if not self._closing:
                raise
        else:
            if not self._paused:
                self._read_fut.add_done_callback(self._loop_reading)
        finally:
            if data is not None:
                self._data_received(data)


class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport,
                                      transports.WriteTransport):
    """Transport for write pipes."""

    _start_tls_compatible = True

    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        self._empty_waiter = None

    def write(self, data):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError(
                f"data argument must be a bytes-like object, "
                f"not {type(data).__name__}")
        if self._eof_written:
            raise RuntimeError('write_eof() already called')
        if self._empty_waiter is not None:
            raise RuntimeError('unable to write; sendfile is in progress')

        if not data:
            return

        if self._conn_lost:
            if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
                logger.warning('socket.send() raised exception.')
            self._conn_lost += 1
            return

        # Observable states:
        # 1. IDLE: _write_fut and _buffer both None
        # 2. WRITING: _write_fut set; _buffer None
        # 3. BACKED UP: _write_fut set; _buffer a bytearray
        # We always copy the data, so the caller can't modify it
        # while we're still waiting for the I/O to happen.
        if self._write_fut is None:  # IDLE -> WRITING
            assert self._buffer is None
            # Pass a copy, except if it's already immutable.
            self._loop_writing(data=bytes(data))
        elif not self._buffer:  # WRITING -> BACKED UP
            # Make a mutable copy which we can extend.
            self._buffer = bytearray(data)
            self._maybe_pause_protocol()
        else:  # BACKED UP
            # Append to buffer (also copies).
            self._buffer.extend(data)
            self._maybe_pause_protocol()

    def _loop_writing(self, f=None, data=None):
        try:
            if f is not None and self._write_fut is None and self._closing:
                # XXX most likely self._force_close() has been called, and
                # it has set self._write_fut to None.
                return
            assert f is self._write_fut
            self._write_fut = None
            self._pending_write = 0
            if f:
                f.result()
            if data is None:
                data = self._buffer
                self._buffer = None
            if not data:
                if self._closing:
                    self._loop.call_soon(self._call_connection_lost, None)
                if self._eof_written:
                    self._sock.shutdown(socket.SHUT_WR)
                # Now that we've reduced the buffer size, tell the
                # protocol to resume writing if it was paused.  Note that
                # we do this last since the callback is called immediately
                # and it may add more data to the buffer (even causing the
                # protocol to be paused again).
                self._maybe_resume_protocol()
            else:
                self._write_fut = self._loop._proactor.send(self._sock, data)
                if not self._write_fut.done():
                    assert self._pending_write == 0
                    self._pending_write = len(data)
                    self._write_fut.add_done_callback(self._loop_writing)
                    self._maybe_pause_protocol()
                else:
                    self._write_fut.add_done_callback(self._loop_writing)
            if self._empty_waiter is not None and self._write_fut is None:
                self._empty_waiter.set_result(None)
        except ConnectionResetError as exc:
            self._force_close(exc)
        except OSError as exc:
            self._fatal_error(exc, 'Fatal write error on pipe transport')

    def can_write_eof(self):
        return True

    def write_eof(self):
        self.close()

    def abort(self):
        self._force_close(None)

    def _make_empty_waiter(self):
        if self._empty_waiter is not None:
            raise RuntimeError("Empty waiter is already set")
        self._empty_waiter = self._loop.create_future()
        if self._write_fut is None:
            self._empty_waiter.set_result(None)
        return self._empty_waiter

    def _reset_empty_waiter(self):
        self._empty_waiter = None


class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport):
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        self._read_fut = self._loop._proactor.recv(self._sock, 16)
        self._read_fut.add_done_callback(self._pipe_closed)

    def _pipe_closed(self, fut):
        if fut.cancelled():
            # the transport has been closed
            return
        assert fut.result() == b''
        if self._closing:
            assert self._read_fut is None
            return
        assert fut is self._read_fut, (fut, self._read_fut)
        self._read_fut = None
        if self._write_fut is not None:
            self._force_close(BrokenPipeError())
        else:
            self.close()


class _ProactorDatagramTransport(_ProactorBasePipeTransport):
    max_size = 256 * 1024
    def __init__(self, loop, sock, protocol, address=None,
                 waiter=None, extra=None):
        self._address = address
        self._empty_waiter = None
        # We don't need to call _protocol.connection_made() since our base
        # constructor does it for us.
        super().__init__(loop, sock, protocol, waiter=waiter, extra=extra)

        # The base constructor sets _buffer = None, so we set it here
        self._buffer = collections.deque()
        self._loop.call_soon(self._loop_reading)

    def _set_extra(self, sock):
        _set_socket_extra(self, sock)

    def get_write_buffer_size(self):
        return sum(len(data) for data, _ in self._buffer)

    def abort(self):
        self._force_close(None)

    def sendto(self, data, addr=None):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError('data argument must be bytes-like object (%r)',
                            type(data))

        if not data:
            return

        if self._address is not None and addr not in (None, self._address):
            raise ValueError(
                f'Invalid address: must be None or {self._address}')

        if self._conn_lost and self._address:
            if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
                logger.warning('socket.sendto() raised exception.')
            self._conn_lost += 1
            return

        # Ensure that what we buffer is immutable.
        self._buffer.append((bytes(data), addr))

        if self._write_fut is None:
            # No current write operations are active, kick one off
            self._loop_writing()
        # else: A write operation is already kicked off

        self._maybe_pause_protocol()

    def _loop_writing(self, fut=None):
        try:
            if self._conn_lost:
                return

            assert fut is self._write_fut
            self._write_fut = None
            if fut:
                # We are in a _loop_writing() done callback, get the result
                fut.result()

            if not self._buffer or (self._conn_lost and self._address):
                # The connection has been closed
                if self._closing:
                    self._loop.call_soon(self._call_connection_lost, None)
                return

            data, addr = self._buffer.popleft()
            if self._address is not None:
                self._write_fut = self._loop._proactor.send(self._sock,
                                                            data)
            else:
                self._write_fut = self._loop._proactor.sendto(self._sock,
                                                              data,
                                                              addr=addr)
        except OSError as exc:
            self._protocol.error_received(exc)
        except Exception as exc:
            self._fatal_error(exc, 'Fatal write error on datagram transport')
        else:
            self._write_fut.add_done_callback(self._loop_writing)
            self._maybe_resume_protocol()

    def _loop_reading(self, fut=None):
        data = None
        try:
            if self._conn_lost:
                return

            assert self._read_fut is fut or (self._read_fut is None and
                                             self._closing)

            self._read_fut = None
            if fut is not None:
                res = fut.result()

                if self._closing:
                    # since close() has been called we ignore any read data
                    data = None
                    return

                if self._address is not None:
                    data, addr = res, self._address
                else:
                    data, addr = res

            if self._conn_lost:
                return
            if self._address is not None:
                self._read_fut = self._loop._proactor.recv(self._sock,
                                                           self.max_size)
            else:
                self._read_fut = self._loop._proactor.recvfrom(self._sock,
                                                               self.max_size)
        except OSError as exc:
            self._protocol.error_received(exc)
        except exceptions.CancelledError:
            if not self._closing:
                raise
        else:
            if self._read_fut is not None:
                self._read_fut.add_done_callback(self._loop_reading)
        finally:
            if data:
                self._protocol.datagram_received(data, addr)


class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport,
                                   _ProactorBaseWritePipeTransport,
                                   transports.Transport):
    """Transport for duplex pipes."""

    def can_write_eof(self):
        return False

    def write_eof(self):
        raise NotImplementedError


class _ProactorSocketTransport(_ProactorReadPipeTransport,
                               _ProactorBaseWritePipeTransport,
                               transports.Transport):
    """Transport for connected sockets."""

    _sendfile_compatible = constants._SendfileMode.TRY_NATIVE

    def __init__(self, loop, sock, protocol, waiter=None,
                 extra=None, server=None):
        super().__init__(loop, sock, protocol, waiter, extra, server)
        base_events._set_nodelay(sock)

    def _set_extra(self, sock):
        _set_socket_extra(self, sock)

    def can_write_eof(self):
        return True

    def write_eof(self):
        if self._closing or self._eof_written:
            return
        self._eof_written = True
        if self._write_fut is None:
            self._sock.shutdown(socket.SHUT_WR)


class BaseProactorEventLoop(base_events.BaseEventLoop):

    def __init__(self, proactor):
        super().__init__()
        logger.debug('Using proactor: %s', proactor.__class__.__name__)
        self._proactor = proactor
        self._selector = proactor   # convenient alias
        self._self_reading_future = None
        self._accept_futures = {}   # socket file descriptor => Future
        proactor.set_loop(self)
        self._make_self_pipe()
        if threading.current_thread() is threading.main_thread():
            # wakeup fd can only be installed to a file descriptor from the main thread
            signal.set_wakeup_fd(self._csock.fileno())

    def _make_socket_transport(self, sock, protocol, waiter=None,
                               extra=None, server=None):
        return _ProactorSocketTransport(self, sock, protocol, waiter,
                                        extra, server)

    def _make_ssl_transport(
            self, rawsock, protocol, sslcontext, waiter=None,
            *, server_side=False, server_hostname=None,
            extra=None, server=None,
            ssl_handshake_timeout=None):
        ssl_protocol = sslproto.SSLProtocol(
                self, protocol, sslcontext, waiter,
                server_side, server_hostname,
                ssl_handshake_timeout=ssl_handshake_timeout)
        _ProactorSocketTransport(self, rawsock, ssl_protocol,
                                 extra=extra, server=server)
        return ssl_protocol._app_transport

    def _make_datagram_transport(self, sock, protocol,
                                 address=None, waiter=None, extra=None):
        return _ProactorDatagramTransport(self, sock, protocol, address,
                                          waiter, extra)

    def _make_duplex_pipe_transport(self, sock, protocol, waiter=None,
                                    extra=None):
        return _ProactorDuplexPipeTransport(self,
                                            sock, protocol, waiter, extra)

    def _make_read_pipe_transport(self, sock, protocol, waiter=None,
                                  extra=None):
        return _ProactorReadPipeTransport(self, sock, protocol, waiter, extra)

    def _make_write_pipe_transport(self, sock, protocol, waiter=None,
                                   extra=None):
        # We want connection_lost() to be called when other end closes
        return _ProactorWritePipeTransport(self,
                                           sock, protocol, waiter, extra)

    def close(self):
        if self.is_running():
            raise RuntimeError("Cannot close a running event loop")
        if self.is_closed():
            return

        if threading.current_thread() is threading.main_thread():
            signal.set_wakeup_fd(-1)
        # Call these methods before closing the event loop (before calling
        # BaseEventLoop.close), because they can schedule callbacks with
        # call_soon(), which is forbidden when the event loop is closed.
        self._stop_accept_futures()
        self._close_self_pipe()
        self._proactor.close()
        self._proactor = None
        self._selector = None

        # Close the event loop
        super().close()

    async def sock_recv(self, sock, n):
        return await self._proactor.recv(sock, n)

    async def sock_recv_into(self, sock, buf):
        return await self._proactor.recv_into(sock, buf)

    async def sock_sendall(self, sock, data):
        return await self._proactor.send(sock, data)

    async def sock_connect(self, sock, address):
        return await self._proactor.connect(sock, address)

    async def sock_accept(self, sock):
        return await self._proactor.accept(sock)

    async def _sock_sendfile_native(self, sock, file, offset, count):
        try:
            fileno = file.fileno()
        except (AttributeError, io.UnsupportedOperation) as err:
            raise exceptions.SendfileNotAvailableError("not a regular file")
        try:
            fsize = os.fstat(fileno).st_size
        except OSError as err:
            raise exceptions.SendfileNotAvailableError("not a regular file")
        blocksize = count if count else fsize
        if not blocksize:
            return 0  # empty file

        blocksize = min(blocksize, 0xffff_ffff)
        end_pos = min(offset + count, fsize) if count else fsize
        offset = min(offset, fsize)
        total_sent = 0
        try:
            while True:
                blocksize = min(end_pos - offset, blocksize)
                if blocksize <= 0:
                    return total_sent
                await self._proactor.sendfile(sock, file, offset, blocksize)
                offset += blocksize
                total_sent += blocksize
        finally:
            if total_sent > 0:
                file.seek(offset)

    async def _sendfile_native(self, transp, file, offset, count):
        resume_reading = transp.is_reading()
        transp.pause_reading()
        await transp._make_empty_waiter()
        try:
            return await self.sock_sendfile(transp._sock, file, offset, count,
                                            fallback=False)
        finally:
            transp._reset_empty_waiter()
            if resume_reading:
                transp.resume_reading()

    def _close_self_pipe(self):
        if self._self_reading_future is not None:
            self._self_reading_future.cancel()
            self._self_reading_future = None
        self._ssock.close()
        self._ssock = None
        self._csock.close()
        self._csock = None
        self._internal_fds -= 1

    def _make_self_pipe(self):
        # A self-socket, really. :-)
        self._ssock, self._csock = socket.socketpair()
        self._ssock.setblocking(False)
        self._csock.setblocking(False)
        self._internal_fds += 1

    def _loop_self_reading(self, f=None):
        try:
            if f is not None:
                f.result()  # may raise
            if self._self_reading_future is not f:
                # When we scheduled this Future, we assigned it to
                # _self_reading_future. If it's not there now, something has
                # tried to cancel the loop while this callback was still in the
                # queue (see windows_events.ProactorEventLoop.run_forever). In
                # that case stop here instead of continuing to schedule a new
                # iteration.
                return
            f = self._proactor.recv(self._ssock, 4096)
        except exceptions.CancelledError:
            # _close_self_pipe() has been called, stop waiting for data
            return
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as exc:
            self.call_exception_handler({
                'message': 'Error on reading from the event loop self pipe',
                'exception': exc,
                'loop': self,
            })
        else:
            self._self_reading_future = f
            f.add_done_callback(self._loop_self_reading)

    def _write_to_self(self):
        # This may be called from a different thread, possibly after
        # _close_self_pipe() has been called or even while it is
        # running.  Guard for self._csock being None or closed.  When
        # a socket is closed, send() raises OSError (with errno set to
        # EBADF, but let's not rely on the exact error code).
        csock = self._csock
        if csock is None:
            return

        try:
            csock.send(b'\0')
        except OSError:
            if self._debug:
                logger.debug("Fail to write a null byte into the "
                             "self-pipe socket",
                             exc_info=True)

    def _start_serving(self, protocol_factory, sock,
                       sslcontext=None, server=None, backlog=100,
                       ssl_handshake_timeout=None):

        def loop(f=None):
            try:
                if f is not None:
                    conn, addr = f.result()
                    if self._debug:
                        logger.debug("%r got a new connection from %r: %r",
                                     server, addr, conn)
                    protocol = protocol_factory()
                    if sslcontext is not None:
                        self._make_ssl_transport(
                            conn, protocol, sslcontext, server_side=True,
                            extra={'peername': addr}, server=server,
                            ssl_handshake_timeout=ssl_handshake_timeout)
                    else:
                        self._make_socket_transport(
                            conn, protocol,
                            extra={'peername': addr}, server=server)
                if self.is_closed():
                    return
                f = self._proactor.accept(sock)
            except OSError as exc:
                if sock.fileno() != -1:
                    self.call_exception_handler({
                        'message': 'Accept failed on a socket',
                        'exception': exc,
                        'socket': trsock.TransportSocket(sock),
                    })
                    sock.close()
                elif self._debug:
                    logger.debug("Accept failed on socket %r",
                                 sock, exc_info=True)
            except exceptions.CancelledError:
                sock.close()
            else:
                self._accept_futures[sock.fileno()] = f
                f.add_done_callback(loop)

        self.call_soon(loop)

    def _process_events(self, event_list):
        # Events are processed in the IocpProactor._poll() method
        pass

    def _stop_accept_futures(self):
        for future in self._accept_futures.values():
            future.cancel()
        self._accept_futures.clear()

    def _stop_serving(self, sock):
        future = self._accept_futures.pop(sock.fileno(), None)
        if future:
            future.cancel()
        self._proactor._stop_serving(sock)
        sock.close()
PK[�H����base_events.pynu�[���"""Base implementation of event loop.

The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.

Whenever a public API takes a callback, subsequent positional
arguments will be passed to the callback if/when it is called.  This
avoids the proliferation of trivial lambdas implementing closures.
Keyword arguments for the callback are not supported; this is a
conscious design decision, leaving the door open for keyword arguments
to modify the meaning of the API call itself.
"""

import collections
import collections.abc
import concurrent.futures
import functools
import heapq
import itertools
import os
import socket
import stat
import subprocess
import threading
import time
import traceback
import sys
import warnings
import weakref

try:
    import ssl
except ImportError:  # pragma: no cover
    ssl = None

from . import constants
from . import coroutines
from . import events
from . import exceptions
from . import futures
from . import protocols
from . import sslproto
from . import staggered
from . import tasks
from . import transports
from . import trsock
from .log import logger


__all__ = 'BaseEventLoop',


# Minimum number of _scheduled timer handles before cleanup of
# cancelled handles is performed.
_MIN_SCHEDULED_TIMER_HANDLES = 100

# Minimum fraction of _scheduled timer handles that are cancelled
# before cleanup of cancelled handles is performed.
_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5


_HAS_IPv6 = hasattr(socket, 'AF_INET6')

# Maximum timeout passed to select to avoid OS limitations
MAXIMUM_SELECT_TIMEOUT = 24 * 3600

# Used for deprecation and removal of `loop.create_datagram_endpoint()`'s
# *reuse_address* parameter
_unset = object()


def _format_handle(handle):
    cb = handle._callback
    if isinstance(getattr(cb, '__self__', None), tasks.Task):
        # format the task
        return repr(cb.__self__)
    else:
        return str(handle)


def _format_pipe(fd):
    if fd == subprocess.PIPE:
        return '<pipe>'
    elif fd == subprocess.STDOUT:
        return '<stdout>'
    else:
        return repr(fd)


def _set_reuseport(sock):
    if not hasattr(socket, 'SO_REUSEPORT'):
        raise ValueError('reuse_port not supported by socket module')
    else:
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except OSError:
            raise ValueError('reuse_port not supported by socket module, '
                             'SO_REUSEPORT defined but not implemented.')


def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
    # Try to skip getaddrinfo if "host" is already an IP. Users might have
    # handled name resolution in their own code and pass in resolved IPs.
    if not hasattr(socket, 'inet_pton'):
        return

    if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
            host is None:
        return None

    if type == socket.SOCK_STREAM:
        proto = socket.IPPROTO_TCP
    elif type == socket.SOCK_DGRAM:
        proto = socket.IPPROTO_UDP
    else:
        return None

    if port is None:
        port = 0
    elif isinstance(port, bytes) and port == b'':
        port = 0
    elif isinstance(port, str) and port == '':
        port = 0
    else:
        # If port's a service name like "http", don't skip getaddrinfo.
        try:
            port = int(port)
        except (TypeError, ValueError):
            return None

    if family == socket.AF_UNSPEC:
        afs = [socket.AF_INET]
        if _HAS_IPv6:
            afs.append(socket.AF_INET6)
    else:
        afs = [family]

    if isinstance(host, bytes):
        host = host.decode('idna')
    if '%' in host:
        # Linux's inet_pton doesn't accept an IPv6 zone index after host,
        # like '::1%lo0'.
        return None

    for af in afs:
        try:
            socket.inet_pton(af, host)
            # The host has already been resolved.
            if _HAS_IPv6 and af == socket.AF_INET6:
                return af, type, proto, '', (host, port, flowinfo, scopeid)
            else:
                return af, type, proto, '', (host, port)
        except OSError:
            pass

    # "host" is not an IP address.
    return None


def _interleave_addrinfos(addrinfos, first_address_family_count=1):
    """Interleave list of addrinfo tuples by family."""
    # Group addresses by family
    addrinfos_by_family = collections.OrderedDict()
    for addr in addrinfos:
        family = addr[0]
        if family not in addrinfos_by_family:
            addrinfos_by_family[family] = []
        addrinfos_by_family[family].append(addr)
    addrinfos_lists = list(addrinfos_by_family.values())

    reordered = []
    if first_address_family_count > 1:
        reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
        del addrinfos_lists[0][:first_address_family_count - 1]
    reordered.extend(
        a for a in itertools.chain.from_iterable(
            itertools.zip_longest(*addrinfos_lists)
        ) if a is not None)
    return reordered


def _run_until_complete_cb(fut):
    if not fut.cancelled():
        exc = fut.exception()
        if isinstance(exc, (SystemExit, KeyboardInterrupt)):
            # Issue #22429: run_forever() already finished, no need to
            # stop it.
            return
    futures._get_loop(fut).stop()


if hasattr(socket, 'TCP_NODELAY'):
    def _set_nodelay(sock):
        if (sock.family in {socket.AF_INET, socket.AF_INET6} and
                sock.type == socket.SOCK_STREAM and
                sock.proto == socket.IPPROTO_TCP):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
else:
    def _set_nodelay(sock):
        pass


class _SendfileFallbackProtocol(protocols.Protocol):
    def __init__(self, transp):
        if not isinstance(transp, transports._FlowControlMixin):
            raise TypeError("transport should be _FlowControlMixin instance")
        self._transport = transp
        self._proto = transp.get_protocol()
        self._should_resume_reading = transp.is_reading()
        self._should_resume_writing = transp._protocol_paused
        transp.pause_reading()
        transp.set_protocol(self)
        if self._should_resume_writing:
            self._write_ready_fut = self._transport._loop.create_future()
        else:
            self._write_ready_fut = None

    async def drain(self):
        if self._transport.is_closing():
            raise ConnectionError("Connection closed by peer")
        fut = self._write_ready_fut
        if fut is None:
            return
        await fut

    def connection_made(self, transport):
        raise RuntimeError("Invalid state: "
                           "connection should have been established already.")

    def connection_lost(self, exc):
        if self._write_ready_fut is not None:
            # Never happens if peer disconnects after sending the whole content
            # Thus disconnection is always an exception from user perspective
            if exc is None:
                self._write_ready_fut.set_exception(
                    ConnectionError("Connection is closed by peer"))
            else:
                self._write_ready_fut.set_exception(exc)
        self._proto.connection_lost(exc)

    def pause_writing(self):
        if self._write_ready_fut is not None:
            return
        self._write_ready_fut = self._transport._loop.create_future()

    def resume_writing(self):
        if self._write_ready_fut is None:
            return
        self._write_ready_fut.set_result(False)
        self._write_ready_fut = None

    def data_received(self, data):
        raise RuntimeError("Invalid state: reading should be paused")

    def eof_received(self):
        raise RuntimeError("Invalid state: reading should be paused")

    async def restore(self):
        self._transport.set_protocol(self._proto)
        if self._should_resume_reading:
            self._transport.resume_reading()
        if self._write_ready_fut is not None:
            # Cancel the future.
            # Basically it has no effect because protocol is switched back,
            # no code should wait for it anymore.
            self._write_ready_fut.cancel()
        if self._should_resume_writing:
            self._proto.resume_writing()


class Server(events.AbstractServer):

    def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
                 ssl_handshake_timeout):
        self._loop = loop
        self._sockets = sockets
        self._active_count = 0
        self._waiters = []
        self._protocol_factory = protocol_factory
        self._backlog = backlog
        self._ssl_context = ssl_context
        self._ssl_handshake_timeout = ssl_handshake_timeout
        self._serving = False
        self._serving_forever_fut = None

    def __repr__(self):
        return f'<{self.__class__.__name__} sockets={self.sockets!r}>'

    def _attach(self):
        assert self._sockets is not None
        self._active_count += 1

    def _detach(self):
        assert self._active_count > 0
        self._active_count -= 1
        if self._active_count == 0 and self._sockets is None:
            self._wakeup()

    def _wakeup(self):
        waiters = self._waiters
        self._waiters = None
        for waiter in waiters:
            if not waiter.done():
                waiter.set_result(waiter)

    def _start_serving(self):
        if self._serving:
            return
        self._serving = True
        for sock in self._sockets:
            sock.listen(self._backlog)
            self._loop._start_serving(
                self._protocol_factory, sock, self._ssl_context,
                self, self._backlog, self._ssl_handshake_timeout)

    def get_loop(self):
        return self._loop

    def is_serving(self):
        return self._serving

    @property
    def sockets(self):
        if self._sockets is None:
            return ()
        return tuple(trsock.TransportSocket(s) for s in self._sockets)

    def close(self):
        sockets = self._sockets
        if sockets is None:
            return
        self._sockets = None

        for sock in sockets:
            self._loop._stop_serving(sock)

        self._serving = False

        if (self._serving_forever_fut is not None and
                not self._serving_forever_fut.done()):
            self._serving_forever_fut.cancel()
            self._serving_forever_fut = None

        if self._active_count == 0:
            self._wakeup()

    async def start_serving(self):
        self._start_serving()
        # Skip one loop iteration so that all 'loop.add_reader'
        # go through.
        await tasks.sleep(0, loop=self._loop)

    async def serve_forever(self):
        if self._serving_forever_fut is not None:
            raise RuntimeError(
                f'server {self!r} is already being awaited on serve_forever()')
        if self._sockets is None:
            raise RuntimeError(f'server {self!r} is closed')

        self._start_serving()
        self._serving_forever_fut = self._loop.create_future()

        try:
            await self._serving_forever_fut
        except exceptions.CancelledError:
            try:
                self.close()
                await self.wait_closed()
            finally:
                raise
        finally:
            self._serving_forever_fut = None

    async def wait_closed(self):
        if self._sockets is None or self._waiters is None:
            return
        waiter = self._loop.create_future()
        self._waiters.append(waiter)
        await waiter


class BaseEventLoop(events.AbstractEventLoop):

    def __init__(self):
        self._timer_cancelled_count = 0
        self._closed = False
        self._stopping = False
        self._ready = collections.deque()
        self._scheduled = []
        self._default_executor = None
        self._internal_fds = 0
        # Identifier of the thread running the event loop, or None if the
        # event loop is not running
        self._thread_id = None
        self._clock_resolution = time.get_clock_info('monotonic').resolution
        self._exception_handler = None
        self.set_debug(coroutines._is_debug_mode())
        # In debug mode, if the execution of a callback or a step of a task
        # exceed this duration in seconds, the slow callback/task is logged.
        self.slow_callback_duration = 0.1
        self._current_handle = None
        self._task_factory = None
        self._coroutine_origin_tracking_enabled = False
        self._coroutine_origin_tracking_saved_depth = None

        # A weak set of all asynchronous generators that are
        # being iterated by the loop.
        self._asyncgens = weakref.WeakSet()
        # Set to True when `loop.shutdown_asyncgens` is called.
        self._asyncgens_shutdown_called = False

    def __repr__(self):
        return (
            f'<{self.__class__.__name__} running={self.is_running()} '
            f'closed={self.is_closed()} debug={self.get_debug()}>'
        )

    def create_future(self):
        """Create a Future object attached to the loop."""
        return futures.Future(loop=self)

    def create_task(self, coro, *, name=None):
        """Schedule a coroutine object.

        Return a task object.
        """
        self._check_closed()
        if self._task_factory is None:
            task = tasks.Task(coro, loop=self, name=name)
            if task._source_traceback:
                del task._source_traceback[-1]
        else:
            task = self._task_factory(self, coro)
            tasks._set_task_name(task, name)

        return task

    def set_task_factory(self, factory):
        """Set a task factory that will be used by loop.create_task().

        If factory is None the default task factory will be set.

        If factory is a callable, it should have a signature matching
        '(loop, coro)', where 'loop' will be a reference to the active
        event loop, 'coro' will be a coroutine object.  The callable
        must return a Future.
        """
        if factory is not None and not callable(factory):
            raise TypeError('task factory must be a callable or None')
        self._task_factory = factory

    def get_task_factory(self):
        """Return a task factory, or None if the default one is in use."""
        return self._task_factory

    def _make_socket_transport(self, sock, protocol, waiter=None, *,
                               extra=None, server=None):
        """Create socket transport."""
        raise NotImplementedError

    def _make_ssl_transport(
            self, rawsock, protocol, sslcontext, waiter=None,
            *, server_side=False, server_hostname=None,
            extra=None, server=None,
            ssl_handshake_timeout=None,
            call_connection_made=True):
        """Create SSL transport."""
        raise NotImplementedError

    def _make_datagram_transport(self, sock, protocol,
                                 address=None, waiter=None, extra=None):
        """Create datagram transport."""
        raise NotImplementedError

    def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
                                  extra=None):
        """Create read pipe transport."""
        raise NotImplementedError

    def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
                                   extra=None):
        """Create write pipe transport."""
        raise NotImplementedError

    async def _make_subprocess_transport(self, protocol, args, shell,
                                         stdin, stdout, stderr, bufsize,
                                         extra=None, **kwargs):
        """Create subprocess transport."""
        raise NotImplementedError

    def _write_to_self(self):
        """Write a byte to self-pipe, to wake up the event loop.

        This may be called from a different thread.

        The subclass is responsible for implementing the self-pipe.
        """
        raise NotImplementedError

    def _process_events(self, event_list):
        """Process selector events."""
        raise NotImplementedError

    def _check_closed(self):
        if self._closed:
            raise RuntimeError('Event loop is closed')

    def _asyncgen_finalizer_hook(self, agen):
        self._asyncgens.discard(agen)
        if not self.is_closed():
            self.call_soon_threadsafe(self.create_task, agen.aclose())

    def _asyncgen_firstiter_hook(self, agen):
        if self._asyncgens_shutdown_called:
            warnings.warn(
                f"asynchronous generator {agen!r} was scheduled after "
                f"loop.shutdown_asyncgens() call",
                ResourceWarning, source=self)

        self._asyncgens.add(agen)

    async def shutdown_asyncgens(self):
        """Shutdown all active asynchronous generators."""
        self._asyncgens_shutdown_called = True

        if not len(self._asyncgens):
            # If Python version is <3.6 or we don't have any asynchronous
            # generators alive.
            return

        closing_agens = list(self._asyncgens)
        self._asyncgens.clear()

        results = await tasks.gather(
            *[ag.aclose() for ag in closing_agens],
            return_exceptions=True,
            loop=self)

        for result, agen in zip(results, closing_agens):
            if isinstance(result, Exception):
                self.call_exception_handler({
                    'message': f'an error occurred during closing of '
                               f'asynchronous generator {agen!r}',
                    'exception': result,
                    'asyncgen': agen
                })

    def _check_running(self):
        if self.is_running():
            raise RuntimeError('This event loop is already running')
        if events._get_running_loop() is not None:
            raise RuntimeError(
                'Cannot run the event loop while another loop is running')

    def run_forever(self):
        """Run until stop() is called."""
        self._check_closed()
        self._check_running()
        self._set_coroutine_origin_tracking(self._debug)
        self._thread_id = threading.get_ident()

        old_agen_hooks = sys.get_asyncgen_hooks()
        sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
                               finalizer=self._asyncgen_finalizer_hook)
        try:
            events._set_running_loop(self)
            while True:
                self._run_once()
                if self._stopping:
                    break
        finally:
            self._stopping = False
            self._thread_id = None
            events._set_running_loop(None)
            self._set_coroutine_origin_tracking(False)
            sys.set_asyncgen_hooks(*old_agen_hooks)

    def run_until_complete(self, future):
        """Run until the Future is done.

        If the argument is a coroutine, it is wrapped in a Task.

        WARNING: It would be disastrous to call run_until_complete()
        with the same coroutine twice -- it would wrap it in two
        different Tasks and that can't be good.

        Return the Future's result, or raise its exception.
        """
        self._check_closed()
        self._check_running()

        new_task = not futures.isfuture(future)
        future = tasks.ensure_future(future, loop=self)
        if new_task:
            # An exception is raised if the future didn't complete, so there
            # is no need to log the "destroy pending task" message
            future._log_destroy_pending = False

        future.add_done_callback(_run_until_complete_cb)
        try:
            self.run_forever()
        except:
            if new_task and future.done() and not future.cancelled():
                # The coroutine raised a BaseException. Consume the exception
                # to not log a warning, the caller doesn't have access to the
                # local task.
                future.exception()
            raise
        finally:
            future.remove_done_callback(_run_until_complete_cb)
        if not future.done():
            raise RuntimeError('Event loop stopped before Future completed.')

        return future.result()

    def stop(self):
        """Stop running the event loop.

        Every callback already scheduled will still run.  This simply informs
        run_forever to stop looping after a complete iteration.
        """
        self._stopping = True

    def close(self):
        """Close the event loop.

        This clears the queues and shuts down the executor,
        but does not wait for the executor to finish.

        The event loop must not be running.
        """
        if self.is_running():
            raise RuntimeError("Cannot close a running event loop")
        if self._closed:
            return
        if self._debug:
            logger.debug("Close %r", self)
        self._closed = True
        self._ready.clear()
        self._scheduled.clear()
        executor = self._default_executor
        if executor is not None:
            self._default_executor = None
            executor.shutdown(wait=False)

    def is_closed(self):
        """Returns True if the event loop was closed."""
        return self._closed

    def __del__(self, _warn=warnings.warn):
        if not self.is_closed():
            _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
            if not self.is_running():
                self.close()

    def is_running(self):
        """Returns True if the event loop is running."""
        return (self._thread_id is not None)

    def time(self):
        """Return the time according to the event loop's clock.

        This is a float expressed in seconds since an epoch, but the
        epoch, precision, accuracy and drift are unspecified and may
        differ per event loop.
        """
        return time.monotonic()

    def call_later(self, delay, callback, *args, context=None):
        """Arrange for a callback to be called at a given time.

        Return a Handle: an opaque object with a cancel() method that
        can be used to cancel the call.

        The delay can be an int or float, expressed in seconds.  It is
        always relative to the current time.

        Each callback will be called exactly once.  If two callbacks
        are scheduled for exactly the same time, it undefined which
        will be called first.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        """
        timer = self.call_at(self.time() + delay, callback, *args,
                             context=context)
        if timer._source_traceback:
            del timer._source_traceback[-1]
        return timer

    def call_at(self, when, callback, *args, context=None):
        """Like call_later(), but uses an absolute time.

        Absolute time corresponds to the event loop's time() method.
        """
        self._check_closed()
        if self._debug:
            self._check_thread()
            self._check_callback(callback, 'call_at')
        timer = events.TimerHandle(when, callback, args, self, context)
        if timer._source_traceback:
            del timer._source_traceback[-1]
        heapq.heappush(self._scheduled, timer)
        timer._scheduled = True
        return timer

    def call_soon(self, callback, *args, context=None):
        """Arrange for a callback to be called as soon as possible.

        This operates as a FIFO queue: callbacks are called in the
        order in which they are registered.  Each callback will be
        called exactly once.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        """
        self._check_closed()
        if self._debug:
            self._check_thread()
            self._check_callback(callback, 'call_soon')
        handle = self._call_soon(callback, args, context)
        if handle._source_traceback:
            del handle._source_traceback[-1]
        return handle

    def _check_callback(self, callback, method):
        if (coroutines.iscoroutine(callback) or
                coroutines.iscoroutinefunction(callback)):
            raise TypeError(
                f"coroutines cannot be used with {method}()")
        if not callable(callback):
            raise TypeError(
                f'a callable object was expected by {method}(), '
                f'got {callback!r}')

    def _call_soon(self, callback, args, context):
        handle = events.Handle(callback, args, self, context)
        if handle._source_traceback:
            del handle._source_traceback[-1]
        self._ready.append(handle)
        return handle

    def _check_thread(self):
        """Check that the current thread is the thread running the event loop.

        Non-thread-safe methods of this class make this assumption and will
        likely behave incorrectly when the assumption is violated.

        Should only be called when (self._debug == True).  The caller is
        responsible for checking this condition for performance reasons.
        """
        if self._thread_id is None:
            return
        thread_id = threading.get_ident()
        if thread_id != self._thread_id:
            raise RuntimeError(
                "Non-thread-safe operation invoked on an event loop other "
                "than the current one")

    def call_soon_threadsafe(self, callback, *args, context=None):
        """Like call_soon(), but thread-safe."""
        self._check_closed()
        if self._debug:
            self._check_callback(callback, 'call_soon_threadsafe')
        handle = self._call_soon(callback, args, context)
        if handle._source_traceback:
            del handle._source_traceback[-1]
        self._write_to_self()
        return handle

    def run_in_executor(self, executor, func, *args):
        self._check_closed()
        if self._debug:
            self._check_callback(func, 'run_in_executor')
        if executor is None:
            executor = self._default_executor
            if executor is None:
                executor = concurrent.futures.ThreadPoolExecutor()
                self._default_executor = executor
        return futures.wrap_future(
            executor.submit(func, *args), loop=self)

    def set_default_executor(self, executor):
        if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
            warnings.warn(
                'Using the default executor that is not an instance of '
                'ThreadPoolExecutor is deprecated and will be prohibited '
                'in Python 3.9',
                DeprecationWarning, 2)
        self._default_executor = executor

    def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
        msg = [f"{host}:{port!r}"]
        if family:
            msg.append(f'family={family!r}')
        if type:
            msg.append(f'type={type!r}')
        if proto:
            msg.append(f'proto={proto!r}')
        if flags:
            msg.append(f'flags={flags!r}')
        msg = ', '.join(msg)
        logger.debug('Get address info %s', msg)

        t0 = self.time()
        addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
        dt = self.time() - t0

        msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
        if dt >= self.slow_callback_duration:
            logger.info(msg)
        else:
            logger.debug(msg)
        return addrinfo

    async def getaddrinfo(self, host, port, *,
                          family=0, type=0, proto=0, flags=0):
        if self._debug:
            getaddr_func = self._getaddrinfo_debug
        else:
            getaddr_func = socket.getaddrinfo

        return await self.run_in_executor(
            None, getaddr_func, host, port, family, type, proto, flags)

    async def getnameinfo(self, sockaddr, flags=0):
        return await self.run_in_executor(
            None, socket.getnameinfo, sockaddr, flags)

    async def sock_sendfile(self, sock, file, offset=0, count=None,
                            *, fallback=True):
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")
        self._check_sendfile_params(sock, file, offset, count)
        try:
            return await self._sock_sendfile_native(sock, file,
                                                    offset, count)
        except exceptions.SendfileNotAvailableError as exc:
            if not fallback:
                raise
        return await self._sock_sendfile_fallback(sock, file,
                                                  offset, count)

    async def _sock_sendfile_native(self, sock, file, offset, count):
        # NB: sendfile syscall is not supported for SSL sockets and
        # non-mmap files even if sendfile is supported by OS
        raise exceptions.SendfileNotAvailableError(
            f"syscall sendfile is not available for socket {sock!r} "
            "and file {file!r} combination")

    async def _sock_sendfile_fallback(self, sock, file, offset, count):
        if offset:
            file.seek(offset)
        blocksize = (
            min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
            if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
        )
        buf = bytearray(blocksize)
        total_sent = 0
        try:
            while True:
                if count:
                    blocksize = min(count - total_sent, blocksize)
                    if blocksize <= 0:
                        break
                view = memoryview(buf)[:blocksize]
                read = await self.run_in_executor(None, file.readinto, view)
                if not read:
                    break  # EOF
                await self.sock_sendall(sock, view[:read])
                total_sent += read
            return total_sent
        finally:
            if total_sent > 0 and hasattr(file, 'seek'):
                file.seek(offset + total_sent)

    def _check_sendfile_params(self, sock, file, offset, count):
        if 'b' not in getattr(file, 'mode', 'b'):
            raise ValueError("file should be opened in binary mode")
        if not sock.type == socket.SOCK_STREAM:
            raise ValueError("only SOCK_STREAM type sockets are supported")
        if count is not None:
            if not isinstance(count, int):
                raise TypeError(
                    "count must be a positive integer (got {!r})".format(count))
            if count <= 0:
                raise ValueError(
                    "count must be a positive integer (got {!r})".format(count))
        if not isinstance(offset, int):
            raise TypeError(
                "offset must be a non-negative integer (got {!r})".format(
                    offset))
        if offset < 0:
            raise ValueError(
                "offset must be a non-negative integer (got {!r})".format(
                    offset))

    async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
        """Create, bind and connect one socket."""
        my_exceptions = []
        exceptions.append(my_exceptions)
        family, type_, proto, _, address = addr_info
        sock = None
        try:
            sock = socket.socket(family=family, type=type_, proto=proto)
            sock.setblocking(False)
            if local_addr_infos is not None:
                for _, _, _, _, laddr in local_addr_infos:
                    try:
                        sock.bind(laddr)
                        break
                    except OSError as exc:
                        msg = (
                            f'error while attempting to bind on '
                            f'address {laddr!r}: '
                            f'{exc.strerror.lower()}'
                        )
                        exc = OSError(exc.errno, msg)
                        my_exceptions.append(exc)
                else:  # all bind attempts failed
                    raise my_exceptions.pop()
            await self.sock_connect(sock, address)
            return sock
        except OSError as exc:
            my_exceptions.append(exc)
            if sock is not None:
                sock.close()
            raise
        except:
            if sock is not None:
                sock.close()
            raise

    async def create_connection(
            self, protocol_factory, host=None, port=None,
            *, ssl=None, family=0,
            proto=0, flags=0, sock=None,
            local_addr=None, server_hostname=None,
            ssl_handshake_timeout=None,
            happy_eyeballs_delay=None, interleave=None):
        """Connect to a TCP server.

        Create a streaming transport connection to a given Internet host and
        port: socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_STREAM. protocol_factory must be
        a callable returning a protocol instance.

        This method is a coroutine which will try to establish the connection
        in the background.  When successful, the coroutine returns a
        (transport, protocol) pair.
        """
        if server_hostname is not None and not ssl:
            raise ValueError('server_hostname is only meaningful with ssl')

        if server_hostname is None and ssl:
            # Use host as default for server_hostname.  It is an error
            # if host is empty or not set, e.g. when an
            # already-connected socket was passed or when only a port
            # is given.  To avoid this error, you can pass
            # server_hostname='' -- this will bypass the hostname
            # check.  (This also means that if host is a numeric
            # IP/IPv6 address, we will attempt to verify that exact
            # address; this will probably fail, but it is possible to
            # create a certificate for a specific IP address, so we
            # don't judge it here.)
            if not host:
                raise ValueError('You must set server_hostname '
                                 'when using ssl without a host')
            server_hostname = host

        if ssl_handshake_timeout is not None and not ssl:
            raise ValueError(
                'ssl_handshake_timeout is only meaningful with ssl')

        if happy_eyeballs_delay is not None and interleave is None:
            # If using happy eyeballs, default to interleave addresses by family
            interleave = 1

        if host is not None or port is not None:
            if sock is not None:
                raise ValueError(
                    'host/port and sock can not be specified at the same time')

            infos = await self._ensure_resolved(
                (host, port), family=family,
                type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
            if not infos:
                raise OSError('getaddrinfo() returned empty list')

            if local_addr is not None:
                laddr_infos = await self._ensure_resolved(
                    local_addr, family=family,
                    type=socket.SOCK_STREAM, proto=proto,
                    flags=flags, loop=self)
                if not laddr_infos:
                    raise OSError('getaddrinfo() returned empty list')
            else:
                laddr_infos = None

            if interleave:
                infos = _interleave_addrinfos(infos, interleave)

            exceptions = []
            if happy_eyeballs_delay is None:
                # not using happy eyeballs
                for addrinfo in infos:
                    try:
                        sock = await self._connect_sock(
                            exceptions, addrinfo, laddr_infos)
                        break
                    except OSError:
                        continue
            else:  # using happy eyeballs
                sock, _, _ = await staggered.staggered_race(
                    (functools.partial(self._connect_sock,
                                       exceptions, addrinfo, laddr_infos)
                     for addrinfo in infos),
                    happy_eyeballs_delay, loop=self)

            if sock is None:
                exceptions = [exc for sub in exceptions for exc in sub]
                if len(exceptions) == 1:
                    raise exceptions[0]
                else:
                    # If they all have the same str(), raise one.
                    model = str(exceptions[0])
                    if all(str(exc) == model for exc in exceptions):
                        raise exceptions[0]
                    # Raise a combined exception so the user can see all
                    # the various error messages.
                    raise OSError('Multiple exceptions: {}'.format(
                        ', '.join(str(exc) for exc in exceptions)))

        else:
            if sock is None:
                raise ValueError(
                    'host and port was not specified and no sock specified')
            if sock.type != socket.SOCK_STREAM:
                # We allow AF_INET, AF_INET6, AF_UNIX as long as they
                # are SOCK_STREAM.
                # We support passing AF_UNIX sockets even though we have
                # a dedicated API for that: create_unix_connection.
                # Disallowing AF_UNIX in this method, breaks backwards
                # compatibility.
                raise ValueError(
                    f'A Stream Socket was expected, got {sock!r}')

        transport, protocol = await self._create_connection_transport(
            sock, protocol_factory, ssl, server_hostname,
            ssl_handshake_timeout=ssl_handshake_timeout)
        if self._debug:
            # Get the socket from the transport because SSL transport closes
            # the old socket and creates a new SSL socket
            sock = transport.get_extra_info('socket')
            logger.debug("%r connected to %s:%r: (%r, %r)",
                         sock, host, port, transport, protocol)
        return transport, protocol

    async def _create_connection_transport(
            self, sock, protocol_factory, ssl,
            server_hostname, server_side=False,
            ssl_handshake_timeout=None):

        sock.setblocking(False)

        protocol = protocol_factory()
        waiter = self.create_future()
        if ssl:
            sslcontext = None if isinstance(ssl, bool) else ssl
            transport = self._make_ssl_transport(
                sock, protocol, sslcontext, waiter,
                server_side=server_side, server_hostname=server_hostname,
                ssl_handshake_timeout=ssl_handshake_timeout)
        else:
            transport = self._make_socket_transport(sock, protocol, waiter)

        try:
            await waiter
        except:
            transport.close()
            raise

        return transport, protocol

    async def sendfile(self, transport, file, offset=0, count=None,
                       *, fallback=True):
        """Send a file to transport.

        Return the total number of bytes which were sent.

        The method uses high-performance os.sendfile if available.

        file must be a regular file object opened in binary mode.

        offset tells from where to start reading the file. If specified,
        count is the total number of bytes to transmit as opposed to
        sending the file until EOF is reached. File position is updated on
        return or also in case of error in which case file.tell()
        can be used to figure out the number of bytes
        which were sent.

        fallback set to True makes asyncio to manually read and send
        the file when the platform does not support the sendfile syscall
        (e.g. Windows or SSL socket on Unix).

        Raise SendfileNotAvailableError if the system does not support
        sendfile syscall and fallback is False.
        """
        if transport.is_closing():
            raise RuntimeError("Transport is closing")
        mode = getattr(transport, '_sendfile_compatible',
                       constants._SendfileMode.UNSUPPORTED)
        if mode is constants._SendfileMode.UNSUPPORTED:
            raise RuntimeError(
                f"sendfile is not supported for transport {transport!r}")
        if mode is constants._SendfileMode.TRY_NATIVE:
            try:
                return await self._sendfile_native(transport, file,
                                                   offset, count)
            except exceptions.SendfileNotAvailableError as exc:
                if not fallback:
                    raise

        if not fallback:
            raise RuntimeError(
                f"fallback is disabled and native sendfile is not "
                f"supported for transport {transport!r}")

        return await self._sendfile_fallback(transport, file,
                                             offset, count)

    async def _sendfile_native(self, transp, file, offset, count):
        raise exceptions.SendfileNotAvailableError(
            "sendfile syscall is not supported")

    async def _sendfile_fallback(self, transp, file, offset, count):
        if offset:
            file.seek(offset)
        blocksize = min(count, 16384) if count else 16384
        buf = bytearray(blocksize)
        total_sent = 0
        proto = _SendfileFallbackProtocol(transp)
        try:
            while True:
                if count:
                    blocksize = min(count - total_sent, blocksize)
                    if blocksize <= 0:
                        return total_sent
                view = memoryview(buf)[:blocksize]
                read = await self.run_in_executor(None, file.readinto, view)
                if not read:
                    return total_sent  # EOF
                await proto.drain()
                transp.write(view[:read])
                total_sent += read
        finally:
            if total_sent > 0 and hasattr(file, 'seek'):
                file.seek(offset + total_sent)
            await proto.restore()

    async def start_tls(self, transport, protocol, sslcontext, *,
                        server_side=False,
                        server_hostname=None,
                        ssl_handshake_timeout=None):
        """Upgrade transport to TLS.

        Return a new transport that *protocol* should start using
        immediately.
        """
        if ssl is None:
            raise RuntimeError('Python ssl module is not available')

        if not isinstance(sslcontext, ssl.SSLContext):
            raise TypeError(
                f'sslcontext is expected to be an instance of ssl.SSLContext, '
                f'got {sslcontext!r}')

        if not getattr(transport, '_start_tls_compatible', False):
            raise TypeError(
                f'transport {transport!r} is not supported by start_tls()')

        waiter = self.create_future()
        ssl_protocol = sslproto.SSLProtocol(
            self, protocol, sslcontext, waiter,
            server_side, server_hostname,
            ssl_handshake_timeout=ssl_handshake_timeout,
            call_connection_made=False)

        # Pause early so that "ssl_protocol.data_received()" doesn't
        # have a chance to get called before "ssl_protocol.connection_made()".
        transport.pause_reading()

        transport.set_protocol(ssl_protocol)
        conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
        resume_cb = self.call_soon(transport.resume_reading)

        try:
            await waiter
        except BaseException:
            transport.close()
            conmade_cb.cancel()
            resume_cb.cancel()
            raise

        return ssl_protocol._app_transport

    async def create_datagram_endpoint(self, protocol_factory,
                                       local_addr=None, remote_addr=None, *,
                                       family=0, proto=0, flags=0,
                                       reuse_address=_unset, reuse_port=None,
                                       allow_broadcast=None, sock=None):
        """Create datagram connection."""
        if sock is not None:
            if sock.type != socket.SOCK_DGRAM:
                raise ValueError(
                    f'A UDP Socket was expected, got {sock!r}')
            if (local_addr or remote_addr or
                    family or proto or flags or
                    reuse_port or allow_broadcast):
                # show the problematic kwargs in exception msg
                opts = dict(local_addr=local_addr, remote_addr=remote_addr,
                            family=family, proto=proto, flags=flags,
                            reuse_address=reuse_address, reuse_port=reuse_port,
                            allow_broadcast=allow_broadcast)
                problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
                raise ValueError(
                    f'socket modifier keyword arguments can not be used '
                    f'when sock is specified. ({problems})')
            sock.setblocking(False)
            r_addr = None
        else:
            if not (local_addr or remote_addr):
                if family == 0:
                    raise ValueError('unexpected address family')
                addr_pairs_info = (((family, proto), (None, None)),)
            elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
                for addr in (local_addr, remote_addr):
                    if addr is not None and not isinstance(addr, str):
                        raise TypeError('string is expected')

                if local_addr and local_addr[0] not in (0, '\x00'):
                    try:
                        if stat.S_ISSOCK(os.stat(local_addr).st_mode):
                            os.remove(local_addr)
                    except FileNotFoundError:
                        pass
                    except OSError as err:
                        # Directory may have permissions only to create socket.
                        logger.error('Unable to check or remove stale UNIX '
                                     'socket %r: %r',
                                     local_addr, err)

                addr_pairs_info = (((family, proto),
                                    (local_addr, remote_addr)), )
            else:
                # join address by (family, protocol)
                addr_infos = {}  # Using order preserving dict
                for idx, addr in ((0, local_addr), (1, remote_addr)):
                    if addr is not None:
                        assert isinstance(addr, tuple) and len(addr) == 2, (
                            '2-tuple is expected')

                        infos = await self._ensure_resolved(
                            addr, family=family, type=socket.SOCK_DGRAM,
                            proto=proto, flags=flags, loop=self)
                        if not infos:
                            raise OSError('getaddrinfo() returned empty list')

                        for fam, _, pro, _, address in infos:
                            key = (fam, pro)
                            if key not in addr_infos:
                                addr_infos[key] = [None, None]
                            addr_infos[key][idx] = address

                # each addr has to have info for each (family, proto) pair
                addr_pairs_info = [
                    (key, addr_pair) for key, addr_pair in addr_infos.items()
                    if not ((local_addr and addr_pair[0] is None) or
                            (remote_addr and addr_pair[1] is None))]

                if not addr_pairs_info:
                    raise ValueError('can not get address information')

            exceptions = []

            # bpo-37228
            if reuse_address is not _unset:
                if reuse_address:
                    raise ValueError("Passing `reuse_address=True` is no "
                                     "longer supported, as the usage of "
                                     "SO_REUSEPORT in UDP poses a significant "
                                     "security concern.")
                else:
                    warnings.warn("The *reuse_address* parameter has been "
                                  "deprecated as of 3.5.10 and is scheduled "
                                  "for removal in 3.11.", DeprecationWarning,
                                  stacklevel=2)

            for ((family, proto),
                 (local_address, remote_address)) in addr_pairs_info:
                sock = None
                r_addr = None
                try:
                    sock = socket.socket(
                        family=family, type=socket.SOCK_DGRAM, proto=proto)
                    if reuse_port:
                        _set_reuseport(sock)
                    if allow_broadcast:
                        sock.setsockopt(
                            socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
                    sock.setblocking(False)

                    if local_addr:
                        sock.bind(local_address)
                    if remote_addr:
                        if not allow_broadcast:
                            await self.sock_connect(sock, remote_address)
                        r_addr = remote_address
                except OSError as exc:
                    if sock is not None:
                        sock.close()
                    exceptions.append(exc)
                except:
                    if sock is not None:
                        sock.close()
                    raise
                else:
                    break
            else:
                raise exceptions[0]

        protocol = protocol_factory()
        waiter = self.create_future()
        transport = self._make_datagram_transport(
            sock, protocol, r_addr, waiter)
        if self._debug:
            if local_addr:
                logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
                            "created: (%r, %r)",
                            local_addr, remote_addr, transport, protocol)
            else:
                logger.debug("Datagram endpoint remote_addr=%r created: "
                             "(%r, %r)",
                             remote_addr, transport, protocol)

        try:
            await waiter
        except:
            transport.close()
            raise

        return transport, protocol

    async def _ensure_resolved(self, address, *,
                               family=0, type=socket.SOCK_STREAM,
                               proto=0, flags=0, loop):
        host, port = address[:2]
        info = _ipaddr_info(host, port, family, type, proto, *address[2:])
        if info is not None:
            # "host" is already a resolved IP.
            return [info]
        else:
            return await loop.getaddrinfo(host, port, family=family, type=type,
                                          proto=proto, flags=flags)

    async def _create_server_getaddrinfo(self, host, port, family, flags):
        infos = await self._ensure_resolved((host, port), family=family,
                                            type=socket.SOCK_STREAM,
                                            flags=flags, loop=self)
        if not infos:
            raise OSError(f'getaddrinfo({host!r}) returned empty list')
        return infos

    async def create_server(
            self, protocol_factory, host=None, port=None,
            *,
            family=socket.AF_UNSPEC,
            flags=socket.AI_PASSIVE,
            sock=None,
            backlog=100,
            ssl=None,
            reuse_address=None,
            reuse_port=None,
            ssl_handshake_timeout=None,
            start_serving=True):
        """Create a TCP server.

        The host parameter can be a string, in that case the TCP server is
        bound to host and port.

        The host parameter can also be a sequence of strings and in that case
        the TCP server is bound to all hosts of the sequence. If a host
        appears multiple times (possibly indirectly e.g. when hostnames
        resolve to the same IP address), the server is only bound once to that
        host.

        Return a Server object which can be used to stop the service.

        This method is a coroutine.
        """
        if isinstance(ssl, bool):
            raise TypeError('ssl argument must be an SSLContext or None')

        if ssl_handshake_timeout is not None and ssl is None:
            raise ValueError(
                'ssl_handshake_timeout is only meaningful with ssl')

        if host is not None or port is not None:
            if sock is not None:
                raise ValueError(
                    'host/port and sock can not be specified at the same time')

            if reuse_address is None:
                reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
            sockets = []
            if host == '':
                hosts = [None]
            elif (isinstance(host, str) or
                  not isinstance(host, collections.abc.Iterable)):
                hosts = [host]
            else:
                hosts = host

            fs = [self._create_server_getaddrinfo(host, port, family=family,
                                                  flags=flags)
                  for host in hosts]
            infos = await tasks.gather(*fs, loop=self)
            infos = set(itertools.chain.from_iterable(infos))

            completed = False
            try:
                for res in infos:
                    af, socktype, proto, canonname, sa = res
                    try:
                        sock = socket.socket(af, socktype, proto)
                    except socket.error:
                        # Assume it's a bad family/type/protocol combination.
                        if self._debug:
                            logger.warning('create_server() failed to create '
                                           'socket.socket(%r, %r, %r)',
                                           af, socktype, proto, exc_info=True)
                        continue
                    sockets.append(sock)
                    if reuse_address:
                        sock.setsockopt(
                            socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
                    if reuse_port:
                        _set_reuseport(sock)
                    # Disable IPv4/IPv6 dual stack support (enabled by
                    # default on Linux) which makes a single socket
                    # listen on both address families.
                    if (_HAS_IPv6 and
                            af == socket.AF_INET6 and
                            hasattr(socket, 'IPPROTO_IPV6')):
                        sock.setsockopt(socket.IPPROTO_IPV6,
                                        socket.IPV6_V6ONLY,
                                        True)
                    try:
                        sock.bind(sa)
                    except OSError as err:
                        raise OSError(err.errno, 'error while attempting '
                                      'to bind on address %r: %s'
                                      % (sa, err.strerror.lower())) from None
                completed = True
            finally:
                if not completed:
                    for sock in sockets:
                        sock.close()
        else:
            if sock is None:
                raise ValueError('Neither host/port nor sock were specified')
            if sock.type != socket.SOCK_STREAM:
                raise ValueError(f'A Stream Socket was expected, got {sock!r}')
            sockets = [sock]

        for sock in sockets:
            sock.setblocking(False)

        server = Server(self, sockets, protocol_factory,
                        ssl, backlog, ssl_handshake_timeout)
        if start_serving:
            server._start_serving()
            # Skip one loop iteration so that all 'loop.add_reader'
            # go through.
            await tasks.sleep(0, loop=self)

        if self._debug:
            logger.info("%r is serving", server)
        return server

    async def connect_accepted_socket(
            self, protocol_factory, sock,
            *, ssl=None,
            ssl_handshake_timeout=None):
        """Handle an accepted connection.

        This is used by servers that accept connections outside of
        asyncio but that use asyncio to handle connections.

        This method is a coroutine.  When completed, the coroutine
        returns a (transport, protocol) pair.
        """
        if sock.type != socket.SOCK_STREAM:
            raise ValueError(f'A Stream Socket was expected, got {sock!r}')

        if ssl_handshake_timeout is not None and not ssl:
            raise ValueError(
                'ssl_handshake_timeout is only meaningful with ssl')

        transport, protocol = await self._create_connection_transport(
            sock, protocol_factory, ssl, '', server_side=True,
            ssl_handshake_timeout=ssl_handshake_timeout)
        if self._debug:
            # Get the socket from the transport because SSL transport closes
            # the old socket and creates a new SSL socket
            sock = transport.get_extra_info('socket')
            logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
        return transport, protocol

    async def connect_read_pipe(self, protocol_factory, pipe):
        protocol = protocol_factory()
        waiter = self.create_future()
        transport = self._make_read_pipe_transport(pipe, protocol, waiter)

        try:
            await waiter
        except:
            transport.close()
            raise

        if self._debug:
            logger.debug('Read pipe %r connected: (%r, %r)',
                         pipe.fileno(), transport, protocol)
        return transport, protocol

    async def connect_write_pipe(self, protocol_factory, pipe):
        protocol = protocol_factory()
        waiter = self.create_future()
        transport = self._make_write_pipe_transport(pipe, protocol, waiter)

        try:
            await waiter
        except:
            transport.close()
            raise

        if self._debug:
            logger.debug('Write pipe %r connected: (%r, %r)',
                         pipe.fileno(), transport, protocol)
        return transport, protocol

    def _log_subprocess(self, msg, stdin, stdout, stderr):
        info = [msg]
        if stdin is not None:
            info.append(f'stdin={_format_pipe(stdin)}')
        if stdout is not None and stderr == subprocess.STDOUT:
            info.append(f'stdout=stderr={_format_pipe(stdout)}')
        else:
            if stdout is not None:
                info.append(f'stdout={_format_pipe(stdout)}')
            if stderr is not None:
                info.append(f'stderr={_format_pipe(stderr)}')
        logger.debug(' '.join(info))

    async def subprocess_shell(self, protocol_factory, cmd, *,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               universal_newlines=False,
                               shell=True, bufsize=0,
                               encoding=None, errors=None, text=None,
                               **kwargs):
        if not isinstance(cmd, (bytes, str)):
            raise ValueError("cmd must be a string")
        if universal_newlines:
            raise ValueError("universal_newlines must be False")
        if not shell:
            raise ValueError("shell must be True")
        if bufsize != 0:
            raise ValueError("bufsize must be 0")
        if text:
            raise ValueError("text must be False")
        if encoding is not None:
            raise ValueError("encoding must be None")
        if errors is not None:
            raise ValueError("errors must be None")

        protocol = protocol_factory()
        debug_log = None
        if self._debug:
            # don't log parameters: they may contain sensitive information
            # (password) and may be too long
            debug_log = 'run shell command %r' % cmd
            self._log_subprocess(debug_log, stdin, stdout, stderr)
        transport = await self._make_subprocess_transport(
            protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
        if self._debug and debug_log is not None:
            logger.info('%s: %r', debug_log, transport)
        return transport, protocol

    async def subprocess_exec(self, protocol_factory, program, *args,
                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE, universal_newlines=False,
                              shell=False, bufsize=0,
                              encoding=None, errors=None, text=None,
                              **kwargs):
        if universal_newlines:
            raise ValueError("universal_newlines must be False")
        if shell:
            raise ValueError("shell must be False")
        if bufsize != 0:
            raise ValueError("bufsize must be 0")
        if text:
            raise ValueError("text must be False")
        if encoding is not None:
            raise ValueError("encoding must be None")
        if errors is not None:
            raise ValueError("errors must be None")

        popen_args = (program,) + args
        protocol = protocol_factory()
        debug_log = None
        if self._debug:
            # don't log parameters: they may contain sensitive information
            # (password) and may be too long
            debug_log = f'execute program {program!r}'
            self._log_subprocess(debug_log, stdin, stdout, stderr)
        transport = await self._make_subprocess_transport(
            protocol, popen_args, False, stdin, stdout, stderr,
            bufsize, **kwargs)
        if self._debug and debug_log is not None:
            logger.info('%s: %r', debug_log, transport)
        return transport, protocol

    def get_exception_handler(self):
        """Return an exception handler, or None if the default one is in use.
        """
        return self._exception_handler

    def set_exception_handler(self, handler):
        """Set handler as the new event loop exception handler.

        If handler is None, the default exception handler will
        be set.

        If handler is a callable object, it should have a
        signature matching '(loop, context)', where 'loop'
        will be a reference to the active event loop, 'context'
        will be a dict object (see `call_exception_handler()`
        documentation for details about context).
        """
        if handler is not None and not callable(handler):
            raise TypeError(f'A callable object or None is expected, '
                            f'got {handler!r}')
        self._exception_handler = handler

    def default_exception_handler(self, context):
        """Default exception handler.

        This is called when an exception occurs and no exception
        handler is set, and can be called by a custom exception
        handler that wants to defer to the default behavior.

        This default handler logs the error message and other
        context-dependent information.  In debug mode, a truncated
        stack trace is also appended showing where the given object
        (e.g. a handle or future or task) was created, if any.

        The context parameter has the same meaning as in
        `call_exception_handler()`.
        """
        message = context.get('message')
        if not message:
            message = 'Unhandled exception in event loop'

        exception = context.get('exception')
        if exception is not None:
            exc_info = (type(exception), exception, exception.__traceback__)
        else:
            exc_info = False

        if ('source_traceback' not in context and
                self._current_handle is not None and
                self._current_handle._source_traceback):
            context['handle_traceback'] = \
                self._current_handle._source_traceback

        log_lines = [message]
        for key in sorted(context):
            if key in {'message', 'exception'}:
                continue
            value = context[key]
            if key == 'source_traceback':
                tb = ''.join(traceback.format_list(value))
                value = 'Object created at (most recent call last):\n'
                value += tb.rstrip()
            elif key == 'handle_traceback':
                tb = ''.join(traceback.format_list(value))
                value = 'Handle created at (most recent call last):\n'
                value += tb.rstrip()
            else:
                value = repr(value)
            log_lines.append(f'{key}: {value}')

        logger.error('\n'.join(log_lines), exc_info=exc_info)

    def call_exception_handler(self, context):
        """Call the current event loop's exception handler.

        The context argument is a dict containing the following keys:

        - 'message': Error message;
        - 'exception' (optional): Exception object;
        - 'future' (optional): Future instance;
        - 'task' (optional): Task instance;
        - 'handle' (optional): Handle instance;
        - 'protocol' (optional): Protocol instance;
        - 'transport' (optional): Transport instance;
        - 'socket' (optional): Socket instance;
        - 'asyncgen' (optional): Asynchronous generator that caused
                                 the exception.

        New keys maybe introduced in the future.

        Note: do not overload this method in an event loop subclass.
        For custom exception handling, use the
        `set_exception_handler()` method.
        """
        if self._exception_handler is None:
            try:
                self.default_exception_handler(context)
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException:
                # Second protection layer for unexpected errors
                # in the default implementation, as well as for subclassed
                # event loops with overloaded "default_exception_handler".
                logger.error('Exception in default exception handler',
                             exc_info=True)
        else:
            try:
                self._exception_handler(self, context)
            except (SystemExit, KeyboardInterrupt):
                raise
            except BaseException as exc:
                # Exception in the user set custom exception handler.
                try:
                    # Let's try default handler.
                    self.default_exception_handler({
                        'message': 'Unhandled error in exception handler',
                        'exception': exc,
                        'context': context,
                    })
                except (SystemExit, KeyboardInterrupt):
                    raise
                except BaseException:
                    # Guard 'default_exception_handler' in case it is
                    # overloaded.
                    logger.error('Exception in default exception handler '
                                 'while handling an unexpected error '
                                 'in custom exception handler',
                                 exc_info=True)

    def _add_callback(self, handle):
        """Add a Handle to _scheduled (TimerHandle) or _ready."""
        assert isinstance(handle, events.Handle), 'A Handle is required here'
        if handle._cancelled:
            return
        assert not isinstance(handle, events.TimerHandle)
        self._ready.append(handle)

    def _add_callback_signalsafe(self, handle):
        """Like _add_callback() but called from a signal handler."""
        self._add_callback(handle)
        self._write_to_self()

    def _timer_handle_cancelled(self, handle):
        """Notification that a TimerHandle has been cancelled."""
        if handle._scheduled:
            self._timer_cancelled_count += 1

    def _run_once(self):
        """Run one full iteration of the event loop.

        This calls all currently ready callbacks, polls for I/O,
        schedules the resulting callbacks, and finally schedules
        'call_later' callbacks.
        """

        sched_count = len(self._scheduled)
        if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
            self._timer_cancelled_count / sched_count >
                _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
            # Remove delayed calls that were cancelled if their number
            # is too high
            new_scheduled = []
            for handle in self._scheduled:
                if handle._cancelled:
                    handle._scheduled = False
                else:
                    new_scheduled.append(handle)

            heapq.heapify(new_scheduled)
            self._scheduled = new_scheduled
            self._timer_cancelled_count = 0
        else:
            # Remove delayed calls that were cancelled from head of queue.
            while self._scheduled and self._scheduled[0]._cancelled:
                self._timer_cancelled_count -= 1
                handle = heapq.heappop(self._scheduled)
                handle._scheduled = False

        timeout = None
        if self._ready or self._stopping:
            timeout = 0
        elif self._scheduled:
            # Compute the desired timeout.
            when = self._scheduled[0]._when
            timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)

        event_list = self._selector.select(timeout)
        self._process_events(event_list)

        # Handle 'later' callbacks that are ready.
        end_time = self.time() + self._clock_resolution
        while self._scheduled:
            handle = self._scheduled[0]
            if handle._when >= end_time:
                break
            handle = heapq.heappop(self._scheduled)
            handle._scheduled = False
            self._ready.append(handle)

        # This is the only place where callbacks are actually *called*.
        # All other places just add them to ready.
        # Note: We run all currently scheduled callbacks, but not any
        # callbacks scheduled by callbacks run this time around --
        # they will be run the next time (after another I/O poll).
        # Use an idiom that is thread-safe without using locks.
        ntodo = len(self._ready)
        for i in range(ntodo):
            handle = self._ready.popleft()
            if handle._cancelled:
                continue
            if self._debug:
                try:
                    self._current_handle = handle
                    t0 = self.time()
                    handle._run()
                    dt = self.time() - t0
                    if dt >= self.slow_callback_duration:
                        logger.warning('Executing %s took %.3f seconds',
                                       _format_handle(handle), dt)
                finally:
                    self._current_handle = None
            else:
                handle._run()
        handle = None  # Needed to break cycles when an exception occurs.

    def _set_coroutine_origin_tracking(self, enabled):
        if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
            return

        if enabled:
            self._coroutine_origin_tracking_saved_depth = (
                sys.get_coroutine_origin_tracking_depth())
            sys.set_coroutine_origin_tracking_depth(
                constants.DEBUG_STACK_DEPTH)
        else:
            sys.set_coroutine_origin_tracking_depth(
                self._coroutine_origin_tracking_saved_depth)

        self._coroutine_origin_tracking_enabled = enabled

    def get_debug(self):
        return self._debug

    def set_debug(self, enabled):
        self._debug = enabled

        if self.is_running():
            self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)
PK[���]"]"
coroutines.pynu�[���__all__ = 'coroutine', 'iscoroutinefunction', 'iscoroutine'

import collections.abc
import functools
import inspect
import os
import sys
import traceback
import types
import warnings

from . import base_futures
from . import constants
from . import format_helpers
from .log import logger


def _is_debug_mode():
    # If you set _DEBUG to true, @coroutine will wrap the resulting
    # generator objects in a CoroWrapper instance (defined below).  That
    # instance will log a message when the generator is never iterated
    # over, which may happen when you forget to use "await" or "yield from"
    # with a coroutine call.
    # Note that the value of the _DEBUG flag is taken
    # when the decorator is used, so to be of any use it must be set
    # before you define your coroutines.  A downside of using this feature
    # is that tracebacks show entries for the CoroWrapper.__next__ method
    # when _DEBUG is true.
    return sys.flags.dev_mode or (not sys.flags.ignore_environment and
                                  bool(os.environ.get('PYTHONASYNCIODEBUG')))


_DEBUG = _is_debug_mode()


class CoroWrapper:
    # Wrapper for coroutine object in _DEBUG mode.

    def __init__(self, gen, func=None):
        assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
        self.gen = gen
        self.func = func  # Used to unwrap @coroutine decorator
        self._source_traceback = format_helpers.extract_stack(sys._getframe(1))
        self.__name__ = getattr(gen, '__name__', None)
        self.__qualname__ = getattr(gen, '__qualname__', None)

    def __repr__(self):
        coro_repr = _format_coroutine(self)
        if self._source_traceback:
            frame = self._source_traceback[-1]
            coro_repr += f', created at {frame[0]}:{frame[1]}'

        return f'<{self.__class__.__name__} {coro_repr}>'

    def __iter__(self):
        return self

    def __next__(self):
        return self.gen.send(None)

    def send(self, value):
        return self.gen.send(value)

    def throw(self, type, value=None, traceback=None):
        return self.gen.throw(type, value, traceback)

    def close(self):
        return self.gen.close()

    @property
    def gi_frame(self):
        return self.gen.gi_frame

    @property
    def gi_running(self):
        return self.gen.gi_running

    @property
    def gi_code(self):
        return self.gen.gi_code

    def __await__(self):
        return self

    @property
    def gi_yieldfrom(self):
        return self.gen.gi_yieldfrom

    def __del__(self):
        # Be careful accessing self.gen.frame -- self.gen might not exist.
        gen = getattr(self, 'gen', None)
        frame = getattr(gen, 'gi_frame', None)
        if frame is not None and frame.f_lasti == -1:
            msg = f'{self!r} was never yielded from'
            tb = getattr(self, '_source_traceback', ())
            if tb:
                tb = ''.join(traceback.format_list(tb))
                msg += (f'\nCoroutine object created at '
                        f'(most recent call last, truncated to '
                        f'{constants.DEBUG_STACK_DEPTH} last lines):\n')
                msg += tb.rstrip()
            logger.error(msg)


def coroutine(func):
    """Decorator to mark coroutines.

    If the coroutine is not yielded from before it is destroyed,
    an error message is logged.
    """
    warnings.warn('"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead',
                  DeprecationWarning,
                  stacklevel=2)
    if inspect.iscoroutinefunction(func):
        # In Python 3.5 that's all we need to do for coroutines
        # defined with "async def".
        return func

    if inspect.isgeneratorfunction(func):
        coro = func
    else:
        @functools.wraps(func)
        def coro(*args, **kw):
            res = func(*args, **kw)
            if (base_futures.isfuture(res) or inspect.isgenerator(res) or
                    isinstance(res, CoroWrapper)):
                res = yield from res
            else:
                # If 'res' is an awaitable, run it.
                try:
                    await_meth = res.__await__
                except AttributeError:
                    pass
                else:
                    if isinstance(res, collections.abc.Awaitable):
                        res = yield from await_meth()
            return res

    coro = types.coroutine(coro)
    if not _DEBUG:
        wrapper = coro
    else:
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            w = CoroWrapper(coro(*args, **kwds), func=func)
            if w._source_traceback:
                del w._source_traceback[-1]
            # Python < 3.5 does not implement __qualname__
            # on generator objects, so we set it manually.
            # We use getattr as some callables (such as
            # functools.partial may lack __qualname__).
            w.__name__ = getattr(func, '__name__', None)
            w.__qualname__ = getattr(func, '__qualname__', None)
            return w

    wrapper._is_coroutine = _is_coroutine  # For iscoroutinefunction().
    return wrapper


# A marker for iscoroutinefunction.
_is_coroutine = object()


def iscoroutinefunction(func):
    """Return True if func is a decorated coroutine function."""
    return (inspect.iscoroutinefunction(func) or
            getattr(func, '_is_coroutine', None) is _is_coroutine)


# Prioritize native coroutine check to speed-up
# asyncio.iscoroutine.
_COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
                    collections.abc.Coroutine, CoroWrapper)
_iscoroutine_typecache = set()


def iscoroutine(obj):
    """Return True if obj is a coroutine object."""
    if type(obj) in _iscoroutine_typecache:
        return True

    if isinstance(obj, _COROUTINE_TYPES):
        # Just in case we don't want to cache more than 100
        # positive types.  That shouldn't ever happen, unless
        # someone stressing the system on purpose.
        if len(_iscoroutine_typecache) < 100:
            _iscoroutine_typecache.add(type(obj))
        return True
    else:
        return False


def _format_coroutine(coro):
    assert iscoroutine(coro)

    is_corowrapper = isinstance(coro, CoroWrapper)

    def get_name(coro):
        # Coroutines compiled with Cython sometimes don't have
        # proper __qualname__ or __name__.  While that is a bug
        # in Cython, asyncio shouldn't crash with an AttributeError
        # in its __repr__ functions.
        if is_corowrapper:
            return format_helpers._format_callback(coro.func, (), {})

        if hasattr(coro, '__qualname__') and coro.__qualname__:
            coro_name = coro.__qualname__
        elif hasattr(coro, '__name__') and coro.__name__:
            coro_name = coro.__name__
        else:
            # Stop masking Cython bugs, expose them in a friendly way.
            coro_name = f'<{type(coro).__name__} without __name__>'
        return f'{coro_name}()'

    def is_running(coro):
        try:
            return coro.cr_running
        except AttributeError:
            try:
                return coro.gi_running
            except AttributeError:
                return False

    coro_code = None
    if hasattr(coro, 'cr_code') and coro.cr_code:
        coro_code = coro.cr_code
    elif hasattr(coro, 'gi_code') and coro.gi_code:
        coro_code = coro.gi_code

    coro_name = get_name(coro)

    if not coro_code:
        # Built-in types might not have __qualname__ or __name__.
        if is_running(coro):
            return f'{coro_name} running'
        else:
            return coro_name

    coro_frame = None
    if hasattr(coro, 'gi_frame') and coro.gi_frame:
        coro_frame = coro.gi_frame
    elif hasattr(coro, 'cr_frame') and coro.cr_frame:
        coro_frame = coro.cr_frame

    # If Cython's coroutine has a fake code object without proper
    # co_filename -- expose that.
    filename = coro_code.co_filename or '<empty co_filename>'

    lineno = 0
    if (is_corowrapper and
            coro.func is not None and
            not inspect.isgeneratorfunction(coro.func)):
        source = format_helpers._get_function_source(coro.func)
        if source is not None:
            filename, lineno = source
        if coro_frame is None:
            coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
        else:
            coro_repr = f'{coro_name} running, defined at {filename}:{lineno}'

    elif coro_frame is not None:
        lineno = coro_frame.f_lineno
        coro_repr = f'{coro_name} running at {filename}:{lineno}'

    else:
        lineno = coro_code.co_firstlineno
        coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'

    return coro_repr
PK[|�q���protocols.pynu�[���"""Abstract Protocol base classes."""

__all__ = (
    'BaseProtocol', 'Protocol', 'DatagramProtocol',
    'SubprocessProtocol', 'BufferedProtocol',
)


class BaseProtocol:
    """Common base class for protocol interfaces.

    Usually user implements protocols that derived from BaseProtocol
    like Protocol or ProcessProtocol.

    The only case when BaseProtocol should be implemented directly is
    write-only transport like write pipe
    """

    __slots__ = ()

    def connection_made(self, transport):
        """Called when a connection is made.

        The argument is the transport representing the pipe connection.
        To receive data, wait for data_received() calls.
        When the connection is closed, connection_lost() is called.
        """

    def connection_lost(self, exc):
        """Called when the connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        """

    def pause_writing(self):
        """Called when the transport's buffer goes over the high-water mark.

        Pause and resume calls are paired -- pause_writing() is called
        once when the buffer goes strictly over the high-water mark
        (even if subsequent writes increases the buffer size even
        more), and eventually resume_writing() is called once when the
        buffer size reaches the low-water mark.

        Note that if the buffer size equals the high-water mark,
        pause_writing() is not called -- it must go strictly over.
        Conversely, resume_writing() is called when the buffer size is
        equal or lower than the low-water mark.  These end conditions
        are important to ensure that things go as expected when either
        mark is zero.

        NOTE: This is the only Protocol callback that is not called
        through EventLoop.call_soon() -- if it were, it would have no
        effect when it's most needed (when the app keeps writing
        without yielding until pause_writing() is called).
        """

    def resume_writing(self):
        """Called when the transport's buffer drains below the low-water mark.

        See pause_writing() for details.
        """


class Protocol(BaseProtocol):
    """Interface for stream protocol.

    The user should implement this interface.  They can inherit from
    this class but don't need to.  The implementations here do
    nothing (they don't raise exceptions).

    When the user wants to requests a transport, they pass a protocol
    factory to a utility function (e.g., EventLoop.create_connection()).

    When the connection is made successfully, connection_made() is
    called with a suitable transport object.  Then data_received()
    will be called 0 or more times with data (bytes) received from the
    transport; finally, connection_lost() will be called exactly once
    with either an exception object or None as an argument.

    State machine of calls:

      start -> CM [-> DR*] [-> ER?] -> CL -> end

    * CM: connection_made()
    * DR: data_received()
    * ER: eof_received()
    * CL: connection_lost()
    """

    __slots__ = ()

    def data_received(self, data):
        """Called when some data is received.

        The argument is a bytes object.
        """

    def eof_received(self):
        """Called when the other end calls write_eof() or equivalent.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        """


class BufferedProtocol(BaseProtocol):
    """Interface for stream protocol with manual buffer control.

    Important: this has been added to asyncio in Python 3.7
    *on a provisional basis*!  Consider it as an experimental API that
    might be changed or removed in Python 3.8.

    Event methods, such as `create_server` and `create_connection`,
    accept factories that return protocols that implement this interface.

    The idea of BufferedProtocol is that it allows to manually allocate
    and control the receive buffer.  Event loops can then use the buffer
    provided by the protocol to avoid unnecessary data copies.  This
    can result in noticeable performance improvement for protocols that
    receive big amounts of data.  Sophisticated protocols can allocate
    the buffer only once at creation time.

    State machine of calls:

      start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end

    * CM: connection_made()
    * GB: get_buffer()
    * BU: buffer_updated()
    * ER: eof_received()
    * CL: connection_lost()
    """

    __slots__ = ()

    def get_buffer(self, sizehint):
        """Called to allocate a new receive buffer.

        *sizehint* is a recommended minimal size for the returned
        buffer.  When set to -1, the buffer size can be arbitrary.

        Must return an object that implements the
        :ref:`buffer protocol <bufferobjects>`.
        It is an error to return a zero-sized buffer.
        """

    def buffer_updated(self, nbytes):
        """Called when the buffer was updated with the received data.

        *nbytes* is the total number of bytes that were written to
        the buffer.
        """

    def eof_received(self):
        """Called when the other end calls write_eof() or equivalent.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        """


class DatagramProtocol(BaseProtocol):
    """Interface for datagram protocol."""

    __slots__ = ()

    def datagram_received(self, data, addr):
        """Called when some datagram is received."""

    def error_received(self, exc):
        """Called when a send or receive operation raises an OSError.

        (Other than BlockingIOError or InterruptedError.)
        """


class SubprocessProtocol(BaseProtocol):
    """Interface for protocol for subprocess calls."""

    __slots__ = ()

    def pipe_data_received(self, fd, data):
        """Called when the subprocess writes data into stdout/stderr pipe.

        fd is int file descriptor.
        data is bytes object.
        """

    def pipe_connection_lost(self, fd, exc):
        """Called when a file descriptor associated with the child process is
        closed.

        fd is the int file descriptor that was closed.
        """

    def process_exited(self):
        """Called when subprocess has exited."""


def _feed_data_to_buffered_proto(proto, data):
    data_len = len(data)
    while data_len:
        buf = proto.get_buffer(data_len)
        buf_len = len(buf)
        if not buf_len:
            raise RuntimeError('get_buffer() returned an empty buffer')

        if buf_len >= data_len:
            buf[:data_len] = data
            proto.buffer_updated(data_len)
            return
        else:
            buf[:buf_len] = data[:buf_len]
            proto.buffer_updated(buf_len)
            data = data[buf_len:]
            data_len = len(data)
PK [��Zd	d	format_helpers.pynu�[���import functools
import inspect
import reprlib
import sys
import traceback

from . import constants


def _get_function_source(func):
    func = inspect.unwrap(func)
    if inspect.isfunction(func):
        code = func.__code__
        return (code.co_filename, code.co_firstlineno)
    if isinstance(func, functools.partial):
        return _get_function_source(func.func)
    if isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None


def _format_callback_source(func, args):
    func_repr = _format_callback(func, args, None)
    source = _get_function_source(func)
    if source:
        func_repr += f' at {source[0]}:{source[1]}'
    return func_repr


def _format_args_and_kwargs(args, kwargs):
    """Format function arguments and keyword arguments.

    Special case for a single parameter: ('hello',) is formatted as ('hello').
    """
    # use reprlib to limit the length of the output
    items = []
    if args:
        items.extend(reprlib.repr(arg) for arg in args)
    if kwargs:
        items.extend(f'{k}={reprlib.repr(v)}' for k, v in kwargs.items())
    return '({})'.format(', '.join(items))


def _format_callback(func, args, kwargs, suffix=''):
    if isinstance(func, functools.partial):
        suffix = _format_args_and_kwargs(args, kwargs) + suffix
        return _format_callback(func.func, func.args, func.keywords, suffix)

    if hasattr(func, '__qualname__') and func.__qualname__:
        func_repr = func.__qualname__
    elif hasattr(func, '__name__') and func.__name__:
        func_repr = func.__name__
    else:
        func_repr = repr(func)

    func_repr += _format_args_and_kwargs(args, kwargs)
    if suffix:
        func_repr += suffix
    return func_repr


def extract_stack(f=None, limit=None):
    """Replacement for traceback.extract_stack() that only does the
    necessary work for asyncio debug mode.
    """
    if f is None:
        f = sys._getframe().f_back
    if limit is None:
        # Limit the amount of work to a reasonable amount, as extract_stack()
        # can be called for each coroutine and future in debug mode.
        limit = constants.DEBUG_STACK_DEPTH
    stack = traceback.StackSummary.extract(traceback.walk_stack(f),
                                           limit=limit,
                                           lookup_lines=False)
    stack.reverse()
    return stack
PK [z/%:
runners.pynu�[���__all__ = 'run',

from . import coroutines
from . import events
from . import tasks


def run(main, *, debug=None):
    """Execute the coroutine and return the result.

    This function runs the passed coroutine, taking care of
    managing the asyncio event loop and finalizing asynchronous
    generators.

    This function cannot be called when another asyncio event loop is
    running in the same thread.

    If debug is True, the event loop will be run in debug mode.

    This function always creates a new event loop and closes it at the end.
    It should be used as a main entry point for asyncio programs, and should
    ideally only be called once.

    Example:

        async def main():
            await asyncio.sleep(1)
            print('hello')

        asyncio.run(main())
    """
    if events._get_running_loop() is not None:
        raise RuntimeError(
            "asyncio.run() cannot be called from a running event loop")

    if not coroutines.iscoroutine(main):
        raise ValueError("a coroutine was expected, got {!r}".format(main))

    loop = events.new_event_loop()
    try:
        events.set_event_loop(loop)
        if debug is not None:
            loop.set_debug(debug)
        return loop.run_until_complete(main)
    finally:
        try:
            _cancel_all_tasks(loop)
            loop.run_until_complete(loop.shutdown_asyncgens())
        finally:
            events.set_event_loop(None)
            loop.close()


def _cancel_all_tasks(loop):
    to_cancel = tasks.all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(
        tasks.gather(*to_cancel, loop=loop, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                'message': 'unhandled exception during asyncio.run() shutdown',
                'exception': task.exception(),
                'task': task,
            })
PK [yPaa
exceptions.pynu�[���"""asyncio exceptions."""


__all__ = ('CancelledError', 'InvalidStateError', 'TimeoutError',
           'IncompleteReadError', 'LimitOverrunError',
           'SendfileNotAvailableError')


class CancelledError(BaseException):
    """The Future or Task was cancelled."""


class TimeoutError(Exception):
    """The operation exceeded the given deadline."""


class InvalidStateError(Exception):
    """The operation is not allowed in this state."""


class SendfileNotAvailableError(RuntimeError):
    """Sendfile syscall is not available.

    Raised if OS does not support sendfile syscall for given socket or
    file type.
    """


class IncompleteReadError(EOFError):
    """
    Incomplete read error. Attributes:

    - partial: read bytes string before the end of stream was reached
    - expected: total number of expected bytes (or None if unknown)
    """
    def __init__(self, partial, expected):
        r_expected = 'undefined' if expected is None else repr(expected)
        super().__init__(f'{len(partial)} bytes read on a total of '
                         f'{r_expected} expected bytes')
        self.partial = partial
        self.expected = expected

    def __reduce__(self):
        return type(self), (self.partial, self.expected)


class LimitOverrunError(Exception):
    """Reached the buffer limit while looking for a separator.

    Attributes:
    - consumed: total number of to be consumed bytes.
    """
    def __init__(self, message, consumed):
        super().__init__(message)
        self.consumed = consumed

    def __reduce__(self):
        return type(self), (self.args[0], self.consumed)
PK [��M%!%!'__pycache__/trsock.cpython-38.opt-1.pycnu�[���U

e5d��@s"ddlZddlZGdd�d�ZdS)�Nc@s�eZdZdZdZejd�dd�Zdd�Zedd	��Z	ed
d��Z
edd
��Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Z d8d9�Z!d:d;�Z"d<d=�Z#d>d?�Z$d@dA�Z%dBdC�Z&dDdE�Z'dFdG�Z(dHdI�Z)dJdK�Z*dLdM�Z+dNdO�Z,dPdQ�Z-dRdS�Z.dTdU�Z/dVdW�Z0dXdY�Z1dZd[�Z2d\S)]�TransportSocketz�A socket-like wrapper for exposing real transport sockets.

    These objects can be safely returned by APIs like
    `transport.get_extra_info('socket')`.  All potentially disruptive
    operations (like "socket.close()") are banned.
    ��_sock)�sockcCs
||_dS�Nr)�selfr�r�&/usr/lib64/python3.8/asyncio/trsock.py�__init__szTransportSocket.__init__cCstjd|�d�t|d�dS)NzUsing z� on sockets returned from get_extra_info('socket') will be prohibited in asyncio 3.9. Please report your use case to bugs.python.org.)�source)�warnings�warn�DeprecationWarning)rZwhatrrr	�_nas

�zTransportSocket._nacCs|jjSr)r�family�rrrr	rszTransportSocket.familycCs|jjSr)r�typerrrr	rszTransportSocket.typecCs|jjSr)r�protorrrr	r"szTransportSocket.protocCs�d|���d|j�d|j�d|j��}|��dkr�z|��}|rN|�d|��}Wntjk
rfYnXz|��}|r�|�d|��}Wntjk
r�YnX|�d�S)	Nz<asyncio.TransportSocket fd=z	, family=z, type=z, proto=���z, laddr=z, raddr=�>)�filenorrr�getsockname�socket�error�getpeername)r�sZladdrZraddrrrr	�__repr__&s $�zTransportSocket.__repr__cCstd��dS)Nz/Cannot serialize asyncio.TransportSocket object)�	TypeErrorrrrr	�__getstate__=szTransportSocket.__getstate__cCs
|j��Sr)rrrrrr	r@szTransportSocket.filenocCs
|j��Sr)r�duprrrr	rCszTransportSocket.dupcCs
|j��Sr)r�get_inheritablerrrr	r FszTransportSocket.get_inheritablecCs|j�|�dSr)r�shutdown)rZhowrrr	r!IszTransportSocket.shutdowncOs|jj||�Sr)r�
getsockopt�r�args�kwargsrrr	r"NszTransportSocket.getsockoptcOs|jj||�dSr)r�
setsockoptr#rrr	r&QszTransportSocket.setsockoptcCs
|j��Sr)rrrrrr	rTszTransportSocket.getpeernamecCs
|j��Sr)rrrrrr	rWszTransportSocket.getsocknamecCs
|j��Sr)r�
getsockbynamerrrr	r'ZszTransportSocket.getsockbynamecCs|�d�|j��S)Nzaccept() method)rr�acceptrrrr	r(]s
zTransportSocket.acceptcOs|�d�|jj||�S)Nzconnect() method)rr�connectr#rrr	r)as
zTransportSocket.connectcOs|�d�|jj||�S)Nzconnect_ex() method)rr�
connect_exr#rrr	r*es
zTransportSocket.connect_excOs|�d�|jj||�S)Nz
bind() method)rr�bindr#rrr	r+is
zTransportSocket.bindcOs|�d�|jj||�S)Nzioctl() method)rr�ioctlr#rrr	r,ms
zTransportSocket.ioctlcOs|�d�|jj||�S)Nzlisten() method)rr�listenr#rrr	r-qs
zTransportSocket.listencCs|�d�|j��S)Nzmakefile() method)rr�makefilerrrr	r.us
zTransportSocket.makefilecOs|�d�|jj||�S)Nzsendfile() method)rr�sendfiler#rrr	r/ys
zTransportSocket.sendfilecCs|�d�|j��S)Nzclose() method)rr�closerrrr	r0}s
zTransportSocket.closecCs|�d�|j��S)Nzdetach() method)rr�detachrrrr	r1�s
zTransportSocket.detachcOs|�d�|jj||�S)Nzsendmsg_afalg() method)rr�
sendmsg_afalgr#rrr	r2�s
zTransportSocket.sendmsg_afalgcOs|�d�|jj||�S)Nzsendmsg() method)rr�sendmsgr#rrr	r3�s
zTransportSocket.sendmsgcOs|�d�|jj||�S)Nzsendto() method)rr�sendtor#rrr	r4�s
zTransportSocket.sendtocOs|�d�|jj||�S)Nz
send() method)rr�sendr#rrr	r5�s
zTransportSocket.sendcOs|�d�|jj||�S)Nzsendall() method)rr�sendallr#rrr	r6�s
zTransportSocket.sendallcOs|�d�|jj||�S)Nzset_inheritable() method)rr�set_inheritabler#rrr	r7�s
zTransportSocket.set_inheritablecCs|�d�|j�|�S)Nzshare() method)rr�share)rZ
process_idrrr	r8�s
zTransportSocket.sharecOs|�d�|jj||�S)Nzrecv_into() method)rr�	recv_intor#rrr	r9�s
zTransportSocket.recv_intocOs|�d�|jj||�S)Nzrecvfrom_into() method)rr�
recvfrom_intor#rrr	r:�s
zTransportSocket.recvfrom_intocOs|�d�|jj||�S)Nzrecvmsg_into() method)rr�recvmsg_intor#rrr	r;�s
zTransportSocket.recvmsg_intocOs|�d�|jj||�S)Nzrecvmsg() method)rr�recvmsgr#rrr	r<�s
zTransportSocket.recvmsgcOs|�d�|jj||�S)Nzrecvfrom() method)rr�recvfromr#rrr	r=�s
zTransportSocket.recvfromcOs|�d�|jj||�S)Nz
recv() method)rr�recvr#rrr	r>�s
zTransportSocket.recvcCs|dkrdStd��dS)Nrz<settimeout(): only 0 timeout is allowed on transport sockets��
ValueError)r�valuerrr	�
settimeout�s
�zTransportSocket.settimeoutcCsdS)Nrrrrrr	�
gettimeout�szTransportSocket.gettimeoutcCs|sdStd��dS)Nz3setblocking(): transport sockets cannot be blockingr?)r�flagrrr	�setblocking�s
�zTransportSocket.setblockingcCs|�d�|j��S�Nzcontext manager protocol)rr�	__enter__rrrr	rG�s
zTransportSocket.__enter__cGs|�d�|jj|�SrF)rr�__exit__)r�errrrr	rH�s
zTransportSocket.__exit__N)3�__name__�
__module__�__qualname__�__doc__�	__slots__rr
r�propertyrrrrrrrr r!r"r&rrr'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>rBrCrErGrHrrrr	rsb


r)rrrrrrr	�<module>sPK [ߋ�ѢP�P"__pycache__/streams.cpython-38.pycnu�[���U

e5d h�@s&dZddlZddlZddlZddlZeed�r6ed7ZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlm
Z
ddlmZd
Zdded�dd�Zd ded�dd�Zeed�r�d!ded�dd�Zd"ded�dd�ZGdd�dej�ZGdd�deej�ZGdd�d�ZGdd�d�ZdS)#)�StreamReader�StreamWriter�StreamReaderProtocol�open_connection�start_server�NZAF_UNIX)�open_unix_connection�start_unix_server�)�
coroutines)�events)�
exceptions)�format_helpers)�	protocols)�logger)�sleepi)�loop�limitc	�st|dkrt��}ntjdtdd�t||d�}t||d��|j�fdd�||f|�IdH\}}t|�||�}||fS)	a�A wrapper for create_connection() returning a (reader, writer) pair.

    The reader returned is a StreamReader instance; the writer is a
    StreamWriter instance.

    The arguments are all the usual arguments to create_connection()
    except protocol_factory; most common are positional host and port,
    with various optional keyword arguments following.

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    (If you want to customize the StreamReader and/or
    StreamReaderProtocol classes, just copy the code -- there's
    really nothing special here except some convenience.)
    N�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.���
stacklevel�rr�rcs�S�N�r��protocolr�'/usr/lib64/python3.8/asyncio/streams.py�<lambda>5�z!open_connection.<locals>.<lambda>)	r�get_event_loop�warnings�warn�DeprecationWarningrrZcreate_connectionr)	�host�portrr�kwds�reader�	transport�_�writerrrrrs"
�
��rc�sJ�dkrt���ntjdtdd����fdd�}�j|||f|�IdHS)a�Start a socket server, call back for each client connected.

    The first parameter, `client_connected_cb`, takes two parameters:
    client_reader, client_writer.  client_reader is a StreamReader
    object, while client_writer is a StreamWriter object.  This
    parameter can either be a plain callback function or a coroutine;
    if it is a coroutine, it will be automatically converted into a
    Task.

    The rest of the arguments are all the usual arguments to
    loop.create_server() except protocol_factory; most common are
    positional host and port, with various optional keyword arguments
    following.  The return value is the same as loop.create_server().

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    The return value is the same as loop.create_server(), i.e. a
    Server object which can be used to stop the service.
    Nrrrcst��d�}t|��d�}|S�Nrr�rr�r'r��client_connected_cbrrrr�factoryXs
�zstart_server.<locals>.factory)rr r!r"r#Z
create_server)r/r$r%rrr&r0rr.rr:s
�rc�sr|dkrt��}ntjdtdd�t||d�}t||d��|j�fdd�|f|�IdH\}}t|�||�}||fS)	z@Similar to `open_connection` but works with UNIX Domain Sockets.Nrrrrrcs�Srrrrrrrprz&open_unix_connection.<locals>.<lambda>)	rr r!r"r#rrZcreate_unix_connectionr)�pathrrr&r'r(r)r*rrrrds 
�
��rc�sH�dkrt���ntjdtdd����fdd�}�j||f|�IdHS)z=Similar to `start_server` but works with UNIX Domain Sockets.Nrrrcst��d�}t|��d�}|Sr+r,r-r.rrr0~s
�z"start_unix_server.<locals>.factory)rr r!r"r#Zcreate_unix_server)r/r1rrr&r0rr.rrts
�rc@sBeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�FlowControlMixina)Reusable flow control logic for StreamWriter.drain().

    This implements the protocol methods pause_writing(),
    resume_writing() and connection_lost().  If the subclass overrides
    these it must call the super methods.

    StreamWriter.drain() must wait for _drain_helper() coroutine.
    NcCs0|dkrt��|_n||_d|_d|_d|_dS�NF)rr �_loop�_paused�
_drain_waiter�_connection_lost)�selfrrrr�__init__�szFlowControlMixin.__init__cCs*|jr
t�d|_|j��r&t�d|�dS)NTz%r pauses writing)r5�AssertionErrorr4�	get_debugr�debug�r8rrr�
pause_writing�s

zFlowControlMixin.pause_writingcCsP|js
t�d|_|j��r&t�d|�|j}|dk	rLd|_|��sL|�d�dS)NFz%r resumes writing)	r5r:r4r;rr<r6�done�
set_result�r8�waiterrrr�resume_writing�s

zFlowControlMixin.resume_writingcCsVd|_|jsdS|j}|dkr"dSd|_|��r4dS|dkrH|�d�n
|�|�dS�NT)r7r5r6r?r@�
set_exception�r8�excrBrrr�connection_lost�sz FlowControlMixin.connection_lostc�sP|jrtd��|jsdS|j}|dks2|��s2t�|j��}||_|IdHdS)NzConnection lost)r7�ConnectionResetErrorr5r6�	cancelledr:r4�
create_futurerArrr�
_drain_helper�s
zFlowControlMixin._drain_helpercCst�dSr)�NotImplementedError�r8�streamrrr�_get_close_waiter�sz"FlowControlMixin._get_close_waiter)N)
�__name__�
__module__�__qualname__�__doc__r9r>rCrHrLrPrrrrr2�s	
	r2csfeZdZdZdZd�fdd�	Zedd��Zdd�Z�fd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
�ZS)ra=Helper class to adapt between Protocol and StreamReader.

    (This is a helper class instead of making StreamReader itself a
    Protocol subclass, because the StreamReader has other potential
    uses, and to prevent the user of the StreamReader to accidentally
    call inappropriate methods of the protocol.)
    Ncsnt�j|d�|dk	r,t�|�|_|j|_nd|_|dk	r@||_d|_d|_d|_	||_
d|_|j�
�|_dS)NrF)�superr9�weakref�ref�_stream_reader_wr�_source_traceback�_strong_reader�_reject_connection�_stream_writer�
_transport�_client_connected_cb�	_over_sslr4rK�_closed)r8Z
stream_readerr/r��	__class__rrr9�s
zStreamReaderProtocol.__init__cCs|jdkrdS|��Sr)rXr=rrr�_stream_reader�s
z#StreamReaderProtocol._stream_readercCs�|jr6ddi}|jr|j|d<|j�|�|��dS||_|j}|dk	rT|�|�|�d�dk	|_	|j
dk	r�t||||j�|_|�
||j�}t
�|�r�|j�|�d|_dS)N�messagezpAn open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.Zsource_tracebackZ
sslcontext)r[rYr4Zcall_exception_handler�abortr]rc�
set_transport�get_extra_infor_r^rr\r
ZiscoroutineZcreate_taskrZ)r8r(�contextr'�resrrr�connection_made�s2�


��
z$StreamReaderProtocol.connection_madecsx|j}|dk	r*|dkr |��n
|�|�|j��sV|dkrJ|j�d�n|j�|�t��|�d|_d|_	d|_
dSr)rc�feed_eofrEr`r?r@rUrHrXr\r])r8rGr'rarrrH
s


z$StreamReaderProtocol.connection_lostcCs|j}|dk	r|�|�dSr)rc�	feed_data)r8�datar'rrr�
data_receivedsz"StreamReaderProtocol.data_receivedcCs$|j}|dk	r|��|jr dSdS)NFT)rcrkr_)r8r'rrr�eof_received sz!StreamReaderProtocol.eof_receivedcCs|jSr)r`rNrrrrP+sz&StreamReaderProtocol._get_close_waitercCs"|j}|��r|��s|��dSr)r`r?rJ�	exception)r8�closedrrr�__del__.szStreamReaderProtocol.__del__)NN)rQrRrSrTrYr9�propertyrcrjrHrnrorPrr�
__classcell__rrrarr�s
rc@sveZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zddd�Zdd�ZdS)ra'Wraps a Transport.

    This exposes write(), writelines(), [can_]write_eof(),
    get_extra_info() and close().  It adds drain() which returns an
    optional Future on which you can wait for flow control.  It also
    adds a transport property which references the Transport
    directly.
    cCsJ||_||_|dks"t|t�s"t�||_||_|j��|_|j�	d�dSr)
r]�	_protocol�
isinstancerr:�_readerr4rKZ
_complete_futr@)r8r(rr'rrrrr9@szStreamWriter.__init__cCs@|jjd|j��g}|jdk	r0|�d|j���d�d�|��S)N�
transport=zreader=�<{}>� )rbrQr]rw�append�format�join�r8�inforrr�__repr__Js
zStreamWriter.__repr__cCs|jSr)r]r=rrrr(PszStreamWriter.transportcCs|j�|�dSr)r]�write�r8rmrrrr�TszStreamWriter.writecCs|j�|�dSr)r]�
writelinesr�rrrr�WszStreamWriter.writelinescCs
|j��Sr)r]�	write_eofr=rrrr�ZszStreamWriter.write_eofcCs
|j��Sr)r]�
can_write_eofr=rrrr�]szStreamWriter.can_write_eofcCs
|j��Sr)r]�closer=rrrr�`szStreamWriter.closecCs
|j��Sr)r]�
is_closingr=rrrr�cszStreamWriter.is_closingc�s|j�|�IdHdSr)rurPr=rrr�wait_closedfszStreamWriter.wait_closedNcCs|j�||�Sr)r]rg)r8�name�defaultrrrrgiszStreamWriter.get_extra_infoc�sL|jdk	r |j��}|dk	r |�|j��r8td�IdH|j��IdHdS)zyFlush the write buffer.

        The intended use is to write

          w.write(data)
          await w.drain()
        Nr)rwrpr]r�rrurL)r8rGrrr�drainls



zStreamWriter.drain)N)rQrRrSrTr9r�rsr(r�r�r�r�r�r�r�rgr�rrrrr6s	


rc@s�eZdZdZedfdd�Zdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd&dd�Zd'dd�Zd d!�Zd"d#�Zd$d%�ZdS)(rNcCsv|dkrtd��||_|dkr*t��|_n||_t�|_d|_d|_d|_	d|_
d|_|j��rrt
�t�d��|_dS)NrzLimit cannot be <= 0Fr	)�
ValueError�_limitrr r4�	bytearray�_buffer�_eof�_waiter�
_exceptionr]r5r;r
�
extract_stack�sys�	_getframerY)r8rrrrrr9�s 
�zStreamReader.__init__cCs�dg}|jr"|�t|j��d��|jr2|�d�|jtkrN|�d|j���|jrf|�d|j���|jr~|�d|j���|jr�|�d|j���|j	r�|�d�d	�
d
�|��S)Nrz bytes�eofzlimit=zwaiter=z
exception=rxZpausedryrz)r�r{�lenr�r��_DEFAULT_LIMITr�r�r]r5r|r}r~rrrr��s 


zStreamReader.__repr__cCs|jSr)r�r=rrrrp�szStreamReader.exceptioncCs0||_|j}|dk	r,d|_|��s,|�|�dSr)r�r�rJrErFrrrrE�szStreamReader.set_exceptioncCs*|j}|dk	r&d|_|��s&|�d�dS)z1Wakeup read*() functions waiting for data or EOF.N)r�rJr@rArrr�_wakeup_waiter�s
zStreamReader._wakeup_waitercCs|jdkstd��||_dS)NzTransport already set)r]r:)r8r(rrrrf�szStreamReader.set_transportcCs*|jr&t|j�|jkr&d|_|j��dSr3)r5r�r�r�r]�resume_readingr=rrr�_maybe_resume_transport�sz$StreamReader._maybe_resume_transportcCsd|_|��dSrD)r�r�r=rrrrk�szStreamReader.feed_eofcCs|jo|jS)z=Return True if the buffer is empty and 'feed_eof' was called.)r�r�r=rrr�at_eof�szStreamReader.at_eofcCs�|jrtd��|sdS|j�|�|��|jdk	r~|js~t|j�d|jkr~z|j�	�Wnt
k
rvd|_YnXd|_dS)Nzfeed_data after feed_eofrT)r�r:r��extendr�r]r5r�r�Z
pause_readingrMr�rrrrl�s
��zStreamReader.feed_datac�sf|jdk	rt|�d���|jr&td��|jr<d|_|j��|j��|_z|jIdHW5d|_XdS)zpWait until feed_data() or feed_eof() is called.

        If stream was paused, automatically resume it.
        NzF() called while another coroutine is already waiting for incoming dataz_wait_for_data after EOFF)	r��RuntimeErrorr�r:r5r]r�r4rK)r8Z	func_namerrr�_wait_for_data�s	
�
zStreamReader._wait_for_datac
�s�d}t|�}z|�|�IdH}Wn�tjk
rN}z|jWY�Sd}~XYnhtjk
r�}zH|j�||j�r�|jd|j|�=n
|j�	�|�
�t|jd��W5d}~XYnX|S)a�Read chunk of data from the stream until newline (b'
') is found.

        On success, return chunk that ends with newline. If only partial
        line can be read due to EOF, return incomplete line without
        terminating newline. When EOF was reached while no bytes read, empty
        bytes object is returned.

        If limit is reached, ValueError will be raised. In that case, if
        newline was found, complete line including newline will be removed
        from internal buffer. Else, internal buffer will be cleared. Limit is
        compared against part of the line without newline.

        If stream was paused, this function will automatically resume it if
        needed.
        �
Nr)
r��	readuntilr�IncompleteReadError�partial�LimitOverrunErrorr��
startswith�consumed�clearr�r��args)r8�sep�seplen�line�errr�readline	s
 zStreamReader.readliner�c�s�t|�}|dkrtd��|jdk	r(|j�d}t|j�}|||kr||j�||�}|dkrZq�|d|}||jkr|t�d|��|jr�t	|j�}|j�
�t�|d��|�d�IdHq,||jkr�t�d|��|jd||�}|jd||�=|�
�t	|�S)	aVRead data from the stream until ``separator`` is found.

        On success, the data and separator will be removed from the
        internal buffer (consumed). Returned data will include the
        separator at the end.

        Configured stream limit is used to check result. Limit sets the
        maximal length of data that can be returned, not counting the
        separator.

        If an EOF occurs and the complete separator is still not found,
        an IncompleteReadError exception will be raised, and the internal
        buffer will be reset.  The IncompleteReadError.partial attribute
        may contain the separator partially.

        If the data cannot be read because of over limit, a
        LimitOverrunError exception  will be raised, and the data
        will be left in the internal buffer, so it can be read again.
        rz,Separator should be at least one-byte stringN���r	z2Separator is not found, and chunk exceed the limitr�z2Separator is found, but chunk is longer than limit)r�r�r�r��findr�rr�r��bytesr�r�r�r�)r8Z	separatorr��offsetZbuflenZisep�chunkrrrr�(s>


�


�zStreamReader.readuntilr�c�s�|jdk	r|j�|dkrdS|dkrVg}|�|j�IdH}|s@qL|�|�q(d�|�S|jsr|jsr|�d�IdHt|jd|��}|jd|�=|�	�|S)a�Read up to `n` bytes from the stream.

        If n is not provided, or set to -1, read until EOF and return all read
        bytes. If the EOF was received and the internal buffer is empty, return
        an empty bytes object.

        If n is zero, return empty bytes object immediately.

        If n is positive, this function try to read `n` bytes, and may return
        less or equal bytes than requested, but at least one byte. If EOF was
        received before any byte is read, this function returns empty byte
        object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        Nrr�read)
r�r�r�r{r}r�r�r�r�r�)r8�nZblocks�blockrmrrrr��s"

zStreamReader.readc�s�|dkrtd��|jdk	r |j�|dkr,dSt|j�|krr|jr`t|j�}|j��t�||��|�	d�IdHq,t|j�|kr�t|j�}|j��nt|jd|��}|jd|�=|�
�|S)a�Read exactly `n` bytes.

        Raise an IncompleteReadError if EOF is reached before `n` bytes can be
        read. The IncompleteReadError.partial attribute of the exception will
        contain the partial read bytes.

        if n is zero, return empty bytes object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        rz*readexactly size can not be less than zeroNr�readexactly)r�r�r�r�r�r�r�rr�r�r�)r8r�Z
incompletermrrrr��s&



zStreamReader.readexactlycCs|Srrr=rrr�	__aiter__�szStreamReader.__aiter__c�s|��IdH}|dkrt�|S)Nr)r��StopAsyncIteration)r8�valrrr�	__anext__�szStreamReader.__anext__)r�)r�)rQrRrSrYr�r9r�rprEr�rfr�rkr�rlr�r�r�r�r�r�r�rrrrr�s$	
[
2)r)NN)NN)N)N)�__all__Zsocketr�r!rV�hasattr�r
rrr
r�logrZtasksrr�rrrrZProtocolr2rrrrrrr�<module>sF
�!�'
��DkPPK [[k�AA&__pycache__/tasks.cpython-38.opt-2.pycnu�[���U

e5d���@srdZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddl
mZddl
mZdd	lmZe�d�jZdAd
d�ZdBdd
�ZdCdd�Zdd�ZGdd�dej�ZeZzddlZWnek
r�YnXejZZdd�dd�ZejjZejj Z ejj!Z!dde!d�dd�Z"dd�Z#dd�dd�Z$dd �Z%d!d"�Z&ddd#�d$d%�Z'ej(d&d'��Z)dDdd�d(d)�Z*dd�d*d+�Z+ej(d,d-��Z,ee,_Gd.d/�d/ej-�Z.dd0d1�d2d3�Z/dd�d4d5�Z0d6d7�Z1e	�2�Z3iZ4d8d9�Z5d:d;�Z6d<d=�Z7d>d?�Z8e5Z9e8Z:e6Z;e7Z<z$dd@lm5Z5m8Z8m6Z6m7Z7m3Z3m4Z4Wnek
�r\YnXe5Z=e8Z>e6Z?e7Z@dS)E)�Task�create_task�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�wait�wait_for�as_completed�sleep�gather�shield�
ensure_future�run_coroutine_threadsafe�current_task�	all_tasks�_register_task�_unregister_task�_enter_task�_leave_task�N�)�
base_tasks)�
coroutines)�events)�
exceptions)�futures)�
_is_coroutinecCs|dkrt��}t�|�S�N)r�get_running_loop�_current_tasks�get��loop�r"�%/usr/lib64/python3.8/asyncio/tasks.pyr"srcs^�dkrt���d}ztt�}WqLtk
rF|d7}|dkrB�YqXqLq�fdd�|D�S)Nrr��cs&h|]}t�|��kr|��s|�qSr")r�	_get_loop�done��.0�tr r"r#�	<setcomp><s�zall_tasks.<locals>.<setcomp>)rr�list�
_all_tasks�RuntimeError�r!�iZtasksr"r r#r)srcs^�dkrt���d}ztt�}WqLtk
rF|d7}|dkrB�YqXqLq�fdd�|D�S)Nrrr$csh|]}t�|��kr|�qSr")rr%r'r r"r#r*Usz$_all_tasks_compat.<locals>.<setcomp>)r�get_event_loopr+r,r-r.r"r r#�_all_tasks_compat@sr1cCs4|dk	r0z
|j}Wntk
r&Yn
X||�dSr)�set_name�AttributeError)�task�namer2r"r"r#�_set_task_nameXs
r6cs�eZdZdZed$dd��Zed%dd��Zddd��fdd	�
Z�fd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�dd�Zddd�dd�Zdd�Zd&�fd d!�	Zd"d#�Z�ZS)'rTNcCs(tjdtdd�|dkr t��}t|�S)NzVTask.current_task() is deprecated since Python 3.7, use asyncio.current_task() instead���
stacklevel)�warnings�warn�DeprecationWarningrr0r��clsr!r"r"r#rts�zTask.current_taskcCstjdtdd�t|�S)NzPTask.all_tasks() is deprecated since Python 3.7, use asyncio.all_tasks() insteadr7r8)r:r;r<r1r=r"r"r#r�s
�zTask.all_tasks)r!r5cs�t�j|d�|jr|jd=t�|�s:d|_td|����|dkrRdt���|_n
t	|�|_d|_
d|_||_t
��|_|jj|j|jd�t|�dS)Nr ���Fza coroutine was expected, got zTask-��context)�super�__init__�_source_tracebackr�iscoroutine�_log_destroy_pending�	TypeError�_task_name_counter�_name�str�_must_cancel�_fut_waiter�_coro�contextvarsZcopy_context�_context�_loop�	call_soon�_Task__stepr)�self�coror!r5��	__class__r"r#rC�s


z
Task.__init__csF|jtjkr8|jr8|dd�}|jr,|j|d<|j�|�t���dS)Nz%Task was destroyed but it is pending!)r4�messageZsource_traceback)	Z_staterZ_PENDINGrFrDrPZcall_exception_handlerrB�__del__)rSrArUr"r#rX�s�
zTask.__del__cCs
t�|�Sr)rZ_task_repr_info�rSr"r"r#�
_repr_info�szTask._repr_infocCs|jSr)rMrYr"r"r#�get_coro�sz
Task.get_corocCs|jSr)rIrYr"r"r#�get_name�sz
Task.get_namecCst|�|_dSr)rJrI)rS�valuer"r"r#r2�sz
Task.set_namecCstd��dS)Nz*Task does not support set_result operation�r-)rS�resultr"r"r#�
set_result�szTask.set_resultcCstd��dS)Nz-Task does not support set_exception operationr^)rS�	exceptionr"r"r#�
set_exception�szTask.set_exception)�limitcCst�||�Sr)rZ_task_get_stack)rSrcr"r"r#�	get_stack�szTask.get_stack)rc�filecCst�|||�Sr)rZ_task_print_stack)rSrcrer"r"r#�print_stack�s	zTask.print_stackcCs4d|_|��rdS|jdk	r*|j��r*dSd|_dS�NFT)Z_log_tracebackr&rL�cancelrKrYr"r"r#rh�s

zTask.cancelc
s�|��rt�d|�d|����|jr>t|tj�s8t��}d|_|j}d|_t|j	|��zfz"|dkrp|�d�}n
|�|�}Wn�t
k
r�}z*|jr�d|_t���nt��|j�W5d}~XY�n�tjk
r�t���Y�n�ttfk
�r}zt��|��W5d}~XY�n�tk
�rL}zt��|�W5d}~XY�npXt|dd�}|dk	�r@t�|�|j	k	�r�td|�d|�d��}|j	j|j||jd�n�|�r||k�r�td	|���}|j	j|j||jd�n8d|_|j|j|jd�||_|j�r>|j���r>d|_n*td
|�d|���}|j	j|j||jd�n||dk�r`|j	j|j|jd�n\t �!|��r�td|�d|���}|j	j|j||jd�n$td
|���}|j	j|j||jd�W5t
|j	|�d}XdS)Nz_step(): already done: z, F�_asyncio_future_blockingzTask z got Future z attached to a different loopr@zTask cannot await on itself: z-yield was used instead of yield from in task z with z;yield was used instead of yield from for generator in task zTask got bad yield: )"r&rZInvalidStateErrorrK�
isinstance�CancelledErrorrMrLrrPr�send�throw�
StopIterationrBrhr`r]�KeyboardInterrupt�
SystemExitrb�
BaseException�getattrrr%r-rQrRrOri�add_done_callback�
_Task__wakeup�inspectZisgenerator)rS�excrTr_Zblocking�new_excrUr"r#Z__steps��  
��
�����
���
zTask.__stepc
CsJz|��Wn,tk
r8}z|�|�W5d}~XYn
X|��d}dSr)r_rqrR)rS�futurervr"r"r#Z__wakeup[sz
Task.__wakeup)N)N)N)�__name__�
__module__�__qualname__rF�classmethodrrrCrXrZr[r\r2r`rbrdrfrhrRrt�
__classcell__r"r"rUr#rbs$!Tr)r5cCs t��}|�|�}t||�|Sr)rrrr6)rTr5r!r4r"r"r#rxs

r)r!�timeout�return_whenc�s�t�|�st�|�r(tdt|�j����|s4td��|tt	t
fkrPtd|�����dkrbt���nt
jdtdd��fdd�t|�D�}t|||��IdHS)	Nzexpect a list of futures, not z#Set of coroutines/Futures is empty.zInvalid return_when value: �[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r7r8csh|]}t|�d��qS�r �r�r(�fr r"r#r*�szwait.<locals>.<setcomp>)r�isfuturerrErG�typery�
ValueErrorrrrrrr:r;r<�set�_wait)�fsr!r~rr"r r#r�s
�rcGs|��s|�d�dSr)r&r`)�waiter�argsr"r"r#�_release_waiter�sr�r c
�s�|dkrt��}ntjdtdd�|dkr4|IdHS|dkr�t||d�}|��rX|��St||d�IdHz|��Wn.t	j
k
r�}zt	��|�W5d}~XYn
Xt	���|��}|�
|t|�}t�t|�}t||d�}|�|�z�z|IdHWnPt	j
k
�rF|���r$|��YW�dS|�|�t||d�IdH�YnX|���r^|��W�*S|�|�t||d�IdHt	���W5|��XdS)Nr�r7r8rr )rrr:r;r<rr&r_�_cancel_and_waitrrk�TimeoutError�
create_future�
call_laterr��	functools�partialrsrh�remove_done_callback)�futr~r!rvr��timeout_handle�cbr"r"r#r�sL

�





rc
�s�|���d�|dk	r"|�|t���t|������fdd�}|D]}|�|�q@z�IdHW5�dk	rp���|D]}|�|�qtXt�t�}}|D]"}|��r�|�	|�q�|�	|�q�||fS)NcsZ�d8��dks4�tks4�tkrV|��sV|��dk	rV�dk	rD������sV��d�dS)Nrr)rr�	cancelledrarhr&r`�r��Zcounterrr�r�r"r#�_on_completions���
�z_wait.<locals>._on_completion)
r�r�r��lenrsrhr�r�r&�add)r�r~rr!r�r�r&Zpendingr"r�r#r��s(r�c	�sF|��}t�t|�}|�|�z|��|IdHW5|�|�XdSr)r�r�r�r�rsr�rh)r�r!r�r�r"r"r#r�&s
r�)r!r~c#s�t�|�st�|�r(tdt|�j����ddlm}|�d���dkrPt	�
��ntjdt
dd��fdd	�t|�D��d����fd
d�}���fdd
���fdd�}�D]}|���q��r�|dk	r҈�||��tt���D]}|�Vq�dS)Nz#expect an iterable of futures, not r)�Queuer r�r7r8csh|]}t|�d��qSr�r�r�r r"r#r*Uszas_completed.<locals>.<setcomp>cs*�D]}|�����d�q���dSr)r��
put_nowait�clearr�)r�r&�todor"r#�_on_timeoutXs
z!as_completed.<locals>._on_timeoutcs4�sdS��|���|��s0�dk	r0���dSr)�remover�rhr�)r&r�r�r"r#r�^s

z$as_completed.<locals>._on_completionc�s$���IdH}|dkrtj�|��Sr)rrr�r_r�)r&r"r#�
_wait_for_onefsz#as_completed.<locals>._wait_for_one)rr�rrErGr�ryZqueuesr�rr0r:r;r<r�rsr��ranger�)r�r!r~r�r�r�r��_r")r�r&r!r�r�r#r7s*

�rccs
dVdSrr"r"r"r"r#�__sleep0us	r�c�sr|dkrt�IdH|S|dkr*t��}ntjdtdd�|��}|�|tj	||�}z|IdHW�S|�
�XdS)Nrr�r7r8)r�rrr:r;r<r�r�rZ_set_result_unless_cancelledrh)Zdelayr_r!rx�hr"r"r#r	�s$
��r	cCs�t�|�r6|dkrt��}|�|�}|jr2|jd=|St�|�rb|dk	r^|t�|�k	r^t	d��|St
�|�r|tt
|�|d�Std��dS)Nr?zRThe future belongs to a different loop than the one specified as the loop argumentr z:An asyncio.Future, a coroutine or an awaitable is required)rrErr0rrDrr�r%r�ruZisawaitabler�_wrap_awaitablerG)Zcoro_or_futurer!r4r"r"r#r�s



rccs|��EdHSr)�	__await__)Z	awaitabler"r"r#r��sr�cs*eZdZdd��fdd�
Zdd�Z�ZS)�_GatheringFutureNr cst�j|d�||_d|_dS)Nr F)rBrC�	_children�_cancel_requested)rS�childrenr!rUr"r#rC�sz_GatheringFuture.__init__cCs6|��rdSd}|jD]}|��rd}q|r2d|_|Srg)r&r�rhr�)rSZretZchildr"r"r#rh�s
z_GatheringFuture.cancel)ryrzr{rCrhr}r"r"rUr#r��sr�F)r!�return_exceptionscs�|s<|dkrt��}ntjdtdd�|�����g��S�����fdd�}i}g�d�d�|D]f}||kr�t||d�}|dkr�t�	|�}||k	r�d|_
�d	7�|||<|�|�n||}��|�qdt
�|d���S)
Nr�r7r8cs��d7����r$|��s |��dS�sd|��rFt��}��|�dS|��}|dk	rd��|�dS��kr�g}�D]8}|��r�t��}n|��}|dkr�|��}|�|�qt�jrĈ�t���n
��	|�dS)Nr)
r&r�rarrkrbr_�appendr�r`)r�rvZresults�res�r�Z	nfinishedZnfuts�outerr�r"r#�_done_callbacks4


zgather.<locals>._done_callbackrr Fr)rr0r:r;r<r�r`rrr%rFrsr�r�)r!r�Zcoros_or_futuresr�Z
arg_to_fut�argr�r"r�r#r
�s:
�
1
r
cst|dk	rtjdtdd�t||d�����r0�St���}|����fdd����fdd�}������|��S)	Nr�r7r8r cs\���r|��s|��dS|��r.���n*|��}|dk	rJ��|�n��|���dSr)r�rarhrbr`r_)�innerrv�r�r"r#�_inner_done_callbackus
z$shield.<locals>._inner_done_callbackcs���s����dSr)r&r�r�)r�r�r"r#�_outer_done_callback�sz$shield.<locals>._outer_done_callback)	r:r;r<rr&rr%r�rs)r�r!r�r")r�r�r�r#rPs�


rcs:t���std��tj������fdd�}��|��S)NzA coroutine object is requiredc
slzt�t��d���WnNttfk
r2�Yn6tk
rf}z���rT��|��W5d}~XYnXdS)Nr )rZ
_chain_futurerrprorqZset_running_or_notify_cancelrb)rv�rTrxr!r"r#�callback�s
z*run_coroutine_threadsafe.<locals>.callback)rrErG�
concurrentr�FutureZcall_soon_threadsafe)rTr!r�r"r�r#r
�s



r
cCst�|�dSr)r,r��r4r"r"r#r�srcCs4t�|�}|dk	r(td|�d|�d���|t|<dS)NzCannot enter into task z while another task z is being executed.�rrr-�r!r4rr"r"r#r�s
rcCs2t�|�}||k	r(td|�d|�d���t|=dS)Nz
Leaving task z! does not match the current task �.r�r�r"r"r#r�s
rcCst�|�dSr)r,�discardr�r"r"r#r�sr)rrrrr,r)N)N)N)N)A�__all__Zconcurrent.futuresr�rNr�ru�	itertools�typesr:�weakref�rrrrrr�count�__next__rHrrr1r6Z	_PyFuturerZ_PyTaskZ_asyncio�ImportErrorZ_CTaskrrrrrr�rr�r�r�	coroutiner�r	rr�r�r�r
rr
ZWeakSetr,rrrrrZ_py_register_taskZ_py_unregister_taskZ_py_enter_taskZ_py_leave_taskZ_c_register_taskZ_c_unregister_taskZ
_c_enter_taskZ
_c_leave_taskr"r"r"r#�<module>s�	





#H,>

x?$PK [�\@��/�/+__pycache__/transports.cpython-38.opt-1.pycnu�[���U

e5d�(�@s|dZdZGdd�d�ZGdd�de�ZGdd�de�ZGdd	�d	ee�ZGd
d�de�ZGdd
�d
e�ZGdd�de�ZdS)zAbstract Transport class.)�
BaseTransport�
ReadTransport�WriteTransport�	Transport�DatagramTransport�SubprocessTransportc@sHeZdZdZdZddd�Zddd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)rzBase class for transports.��_extraNcCs|dkri}||_dS�Nr)�self�extra�r�*/usr/lib64/python3.8/asyncio/transports.py�__init__szBaseTransport.__init__cCs|j�||�S)z#Get optional transport information.)r�get)r
�name�defaultrrr
�get_extra_infoszBaseTransport.get_extra_infocCst�dS)z2Return True if the transport is closing or closed.N��NotImplementedError�r
rrr
�
is_closingszBaseTransport.is_closingcCst�dS)aClose the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        Nrrrrr
�closeszBaseTransport.closecCst�dS)zSet a new protocol.Nr)r
�protocolrrr
�set_protocol%szBaseTransport.set_protocolcCst�dS)zReturn the current protocol.Nrrrrr
�get_protocol)szBaseTransport.get_protocol)N)N)�__name__�
__module__�__qualname__�__doc__�	__slots__rrrrrrrrrr
r	s


rc@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
rz#Interface for read-only transports.rcCst�dS)z*Return True if the transport is receiving.Nrrrrr
�
is_reading3szReadTransport.is_readingcCst�dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        Nrrrrr
�
pause_reading7szReadTransport.pause_readingcCst�dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        Nrrrrr
�resume_reading?szReadTransport.resume_readingN)rrrrrr r!r"rrrr
r.s
rc@sNeZdZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)rz$Interface for write-only transports.rNcCst�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        Nr�r
�high�lowrrr
�set_write_buffer_limitsMsz&WriteTransport.set_write_buffer_limitscCst�dS)z,Return the current size of the write buffer.Nrrrrr
�get_write_buffer_sizebsz$WriteTransport.get_write_buffer_sizecCst�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        Nr)r
�datarrr
�writefszWriteTransport.writecCsd�|�}|�|�dS)z�Write a list (or any iterable) of data bytes to the transport.

        The default implementation concatenates the arguments and
        calls write() on the result.
        �N)�joinr))r
Zlist_of_datar(rrr
�
writelinesns
zWriteTransport.writelinescCst�dS)z�Close the write end after flushing buffered data.

        (This is like typing ^D into a UNIX program reading from stdin.)

        Data may still be received.
        Nrrrrr
�	write_eofwszWriteTransport.write_eofcCst�dS)zAReturn True if this transport supports write_eof(), False if not.Nrrrrr
�
can_write_eof�szWriteTransport.can_write_eofcCst�dS�z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        Nrrrrr
�abort�szWriteTransport.abort)NN)rrrrrr&r'r)r,r-r.r0rrrr
rHs
		rc@seZdZdZdZdS)raSInterface representing a bidirectional transport.

    There may be several implementations, but typically, the user does
    not implement new transports; rather, the platform provides some
    useful transports that are implemented using the platform's best
    practices.

    The user never instantiates a transport directly; they call a
    utility function, passing it a protocol factory and other
    information necessary to create the transport and protocol.  (E.g.
    EventLoop.create_connection() or EventLoop.create_server().)

    The utility function will asynchronously create a transport and a
    protocol and hook them up by calling the protocol's
    connection_made() method, passing it the transport.

    The implementation here raises NotImplemented for every method
    except writelines(), which calls write() in a loop.
    rN)rrrrrrrrr
r�src@s&eZdZdZdZddd�Zdd�ZdS)	rz(Interface for datagram (UDP) transports.rNcCst�dS)aSend data to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        addr is target socket address.
        If addr is None use target address pointed on transport creation.
        Nr)r
r(Zaddrrrr
�sendto�szDatagramTransport.sendtocCst�dSr/rrrrr
r0�szDatagramTransport.abort)N)rrrrrr1r0rrrr
r�s

rc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)rrcCst�dS)zGet subprocess id.Nrrrrr
�get_pid�szSubprocessTransport.get_pidcCst�dS)z�Get subprocess returncode.

        See also
        http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
        Nrrrrr
�get_returncode�sz"SubprocessTransport.get_returncodecCst�dS)z&Get transport for pipe with number fd.Nr)r
�fdrrr
�get_pipe_transport�sz&SubprocessTransport.get_pipe_transportcCst�dS)z�Send signal to subprocess.

        See also:
        docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
        Nr)r
�signalrrr
�send_signal�szSubprocessTransport.send_signalcCst�dS)aLStop the subprocess.

        Alias for close() method.

        On Posix OSs the method sends SIGTERM to the subprocess.
        On Windows the Win32 API function TerminateProcess()
         is called to stop the subprocess.

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
        Nrrrrr
�	terminate�szSubprocessTransport.terminatecCst�dS)z�Kill the subprocess.

        On Posix OSs the function sends SIGKILL to the subprocess.
        On Windows kill() is an alias for terminate().

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
        Nrrrrr
�kill�s	zSubprocessTransport.killN)
rrrrr2r3r5r7r8r9rrrr
r�srcsZeZdZdZdZd�fdd�	Zdd�Zdd	�Zd
d�Zddd
�Z	ddd�Z
dd�Z�ZS)�_FlowControlMixinavAll the logic for (write) flow control in a mix-in base class.

    The subclass must implement get_write_buffer_size().  It must call
    _maybe_pause_protocol() whenever the write buffer size increases,
    and _maybe_resume_protocol() whenever it decreases.  It may also
    override set_write_buffer_limits() (e.g. to specify different
    defaults).

    The subclass constructor must call super().__init__(extra).  This
    will call set_write_buffer_limits().

    The user may call set_write_buffer_limits() and
    get_write_buffer_size(), and their protocol's pause_writing() and
    resume_writing() may be called.
    )�_loop�_protocol_paused�_high_water�
_low_waterNcs$t��|�||_d|_|��dS)NF)�superrr;r<�_set_write_buffer_limits)r
rZloop��	__class__rr
rsz_FlowControlMixin.__init__c
Cs�|��}||jkrdS|js�d|_z|j��WnRttfk
rJ�Yn:tk
r�}z|j�	d|||jd��W5d}~XYnXdS)NTzprotocol.pause_writing() failed��messageZ	exceptionZ	transportr)
r'r=r<�	_protocolZ
pause_writing�
SystemExit�KeyboardInterrupt�
BaseExceptionr;�call_exception_handler)r
�size�excrrr
�_maybe_pause_protocols 
�z'_FlowControlMixin._maybe_pause_protocolc
Cs�|jr||��|jkr|d|_z|j��WnRttfk
rB�Yn:tk
rz}z|j�	d|||jd��W5d}~XYnXdS)NFz protocol.resume_writing() failedrC)
r<r'r>rEZresume_writingrFrGrHr;rI)r
rKrrr
�_maybe_resume_protocol!s��z(_FlowControlMixin._maybe_resume_protocolcCs|j|jfSr	)r>r=rrrr
�get_write_buffer_limits1sz)_FlowControlMixin.get_write_buffer_limitscCsj|dkr|dkrd}nd|}|dkr.|d}||krBdksZntd|�d|�d���||_||_dS)Ni��zhigh (z) must be >= low (z) must be >= 0)�
ValueErrorr=r>r#rrr
r@4s�z*_FlowControlMixin._set_write_buffer_limitscCs|j||d�|��dS)N)r$r%)r@rLr#rrr
r&Dsz)_FlowControlMixin.set_write_buffer_limitscCst�dSr	rrrrr
r'Hsz'_FlowControlMixin.get_write_buffer_size)NN)NN)NN)
rrrrrrrLrMrNr@r&r'�
__classcell__rrrAr
r:�s

r:N)	r�__all__rrrrrrr:rrrr
�<module>s%F6PK [�x��**/__pycache__/format_helpers.cpython-38.opt-2.pycnu�[���U

e5dd	�@sdddlZddlZddlZddlZddlZddlmZdd�Zdd�Zdd	�Z	ddd�Z
dd
d�ZdS)�N�)�	constantscCsVt�|�}t�|�r&|j}|j|jfSt|tj�r<t	|j
�St|tj�rRt	|j
�SdS�N)�inspectZunwrapZ
isfunction�__code__�co_filename�co_firstlineno�
isinstance�	functools�partial�_get_function_source�func�
partialmethod)r
�code�r�./usr/lib64/python3.8/asyncio/format_helpers.pyr
s



rcCs8t||d�}t|�}|r4|d|d�d|d��7}|S)Nz at r�:r)�_format_callbackr)r
�args�	func_repr�sourcerrr�_format_callback_sources
rcCsHg}|r|�dd�|D��|r8|�dd�|��D��d�d�|��S)Ncss|]}t�|�VqdSr��reprlib�repr)�.0�argrrr�	<genexpr>&sz*_format_args_and_kwargs.<locals>.<genexpr>css&|]\}}|�dt�|���VqdS)�=Nr)r�k�vrrrr(sz({})z, )�extend�items�format�join)r�kwargsr"rrr�_format_args_and_kwargssr&�cCs�t|tj�r.t||�|}t|j|j|j|�St|d�rF|j	rF|j	}n t|d�r^|j
r^|j
}nt|�}|t||�7}|r�||7}|S)N�__qualname__�__name__)r	r
rr&rr
r�keywords�hasattrr(r)r)r
rr%�suffixrrrrr,srcCsD|dkrt��j}|dkr tj}tjjt�|�|dd�}|�	�|S)NF)�limit�lookup_lines)
�sys�	_getframe�f_backrZDEBUG_STACK_DEPTH�	traceback�StackSummary�extract�
walk_stack�reverse)�fr-�stackrrr�
extract_stack>s
�r9)r')NN)r
rrr/r2r'rrrr&rr9rrrr�<module>s
PK [�ar�$�$*__pycache__/base_subprocess.cpython-38.pycnu�[���U

e5d�"�@sxddlZddlZddlZddlmZddlmZddlmZGdd�dej�Z	Gdd	�d	ej
�ZGd
d�deej�Z
dS)�N�)�	protocols)�
transports)�loggercs�eZdZd0�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jfdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Z�ZS)1�BaseSubprocessTransportNc
	s&t��|
�d|_||_||_d|_d|_d|_g|_t	�
�|_i|_d|_
|tjkr`d|jd<|tjkrtd|jd<|tjkr�d|jd<z"|jf||||||d�|��Wn|���YnX|jj|_|j|jd<|j���rt|ttf�r�|}n|d}t�d||j�|j�|�|	��dS)NFrr�)�args�shell�stdin�stdout�stderr�bufsize�
subprocesszprocess %r created: pid %s)�super�__init__�_closed�	_protocol�_loop�_proc�_pid�_returncode�
_exit_waiters�collections�deque�_pending_calls�_pipes�	_finishedr�PIPE�_start�close�pidZ_extra�	get_debug�
isinstance�bytes�strr�debugZcreate_task�_connect_pipes)
�self�loop�protocolrr	r
rrr
�waiterZextra�kwargsZprogram��	__class__��//usr/lib64/python3.8/asyncio/base_subprocess.pyrsL






��

�z BaseSubprocessTransport.__init__cCs|jjg}|jr|�d�|jdk	r6|�d|j���|jdk	rT|�d|j���n |jdk	rj|�d�n
|�d�|j�d�}|dk	r�|�d|j���|j�d�}|j�d	�}|dk	r�||kr�|�d
|j���n6|dk	r�|�d|j���|dk	�r|�d|j���d
�	d�
|��S)N�closedzpid=zreturncode=Zrunningznot startedrzstdin=rrzstdout=stderr=zstdout=zstderr=z<{}>� )r-�__name__r�appendrrr�get�pipe�format�join)r'�infor
rrr.r.r/�__repr__7s,






z BaseSubprocessTransport.__repr__cKst�dS�N)�NotImplementedError)r'rr	r
rrr
r+r.r.r/rTszBaseSubprocessTransport._startcCs
||_dSr:�r)r'r)r.r.r/�set_protocolWsz$BaseSubprocessTransport.set_protocolcCs|jSr:r<�r'r.r.r/�get_protocolZsz$BaseSubprocessTransport.get_protocolcCs|jSr:)rr>r.r.r/�
is_closing]sz"BaseSubprocessTransport.is_closingcCs�|jr
dSd|_|j��D]}|dkr(q|j��q|jdk	r�|jdkr�|j��dkr�|j�	�rlt
�d|�z|j��Wnt
k
r�YnXdS)NTz$Close running child process: kill %r)rr�valuesr5rrrZpollrr!rZwarning�kill�ProcessLookupError)r'�protor.r.r/r`s$
��
zBaseSubprocessTransport.closecCs&|js"|d|��t|d�|��dS)Nzunclosed transport )�source)r�ResourceWarningr)r'Z_warnr.r.r/�__del__{szBaseSubprocessTransport.__del__cCs|jSr:)rr>r.r.r/�get_pid�szBaseSubprocessTransport.get_pidcCs|jSr:)rr>r.r.r/�get_returncode�sz&BaseSubprocessTransport.get_returncodecCs||jkr|j|jSdSdSr:)rr5)r'�fdr.r.r/�get_pipe_transport�s
z*BaseSubprocessTransport.get_pipe_transportcCs|jdkrt��dSr:)rrCr>r.r.r/�_check_proc�s
z#BaseSubprocessTransport._check_proccCs|��|j�|�dSr:)rLr�send_signal)r'�signalr.r.r/rM�sz#BaseSubprocessTransport.send_signalcCs|��|j��dSr:)rLr�	terminater>r.r.r/rO�sz!BaseSubprocessTransport.terminatecCs|��|j��dSr:)rLrrBr>r.r.r/rB�szBaseSubprocessTransport.killc	
�spz�j}�j}|jdk	rB|��fdd�|j�IdH\}}|�jd<|jdk	rv|��fdd�|j�IdH\}}|�jd<|jdk	r�|��fdd�|j�IdH\}}|�jd<�jdk	s�t	�|�
�jj���jD]\}}|j
|f|��q�d�_Wn\t
tfk
�r�Yn`tk
�rL}z"|dk	�r<|���s<|�|�W5d}~XYn X|dk	�rl|���sl|�d�dS)Ncs
t�d�S)Nr)�WriteSubprocessPipeProtor.r>r.r/�<lambda>��z8BaseSubprocessTransport._connect_pipes.<locals>.<lambda>rcs
t�d�S)Nr��ReadSubprocessPipeProtor.r>r.r/rQ�rRrcs
t�d�S)NrrSr.r>r.r/rQ�rRr)rrr
Zconnect_write_piperrZconnect_read_piperr�AssertionError�	call_soonr�connection_made�
SystemExit�KeyboardInterrupt�
BaseException�	cancelledZ
set_exception�
set_result)	r'r*�procr(�_r5�callback�data�excr.r>r/r&�sB

�


�


�

z&BaseSubprocessTransport._connect_pipescGs2|jdk	r|j�||f�n|jj|f|��dSr:)rr3rrV)r'�cbr`r.r.r/�_call�s
zBaseSubprocessTransport._callcCs|�|jj||�|��dSr:)rcrZpipe_connection_lost�_try_finish)r'rJrar.r.r/�_pipe_connection_lost�sz-BaseSubprocessTransport._pipe_connection_lostcCs|�|jj||�dSr:)rcrZpipe_data_received)r'rJr`r.r.r/�_pipe_data_received�sz+BaseSubprocessTransport._pipe_data_receivedcCs�|dk	st|��|jdks$t|j��|j��r<t�d||�||_|jjdkrV||j_|�|j	j
�|��|jD]}|�
�sr|�|�qrd|_dS)Nz%r exited with return code %r)rUrrr!rr8r�
returncodercrZprocess_exitedrdrr[r\)r'rgr*r.r.r/�_process_exited�s

z'BaseSubprocessTransport._process_exitedc�s0|jdk	r|jS|j��}|j�|�|IdHS)zdWait until the process exit and return the process return code.

        This method is a coroutine.N)rrZ
create_futurerr3)r'r*r.r.r/�_wait�s


zBaseSubprocessTransport._waitcCsH|jr
t�|jdkrdStdd�|j��D��rDd|_|�|jd�dS)Ncss|]}|dk	o|jVqdSr:)�disconnected)�.0�pr.r.r/�	<genexpr>�s�z6BaseSubprocessTransport._try_finish.<locals>.<genexpr>T)rrUr�allrrArc�_call_connection_lostr>r.r.r/rd�s

�z#BaseSubprocessTransport._try_finishcCs*z|j�|�W5d|_d|_d|_XdSr:)rrr�connection_lost�r'rar.r.r/ro�s
z-BaseSubprocessTransport._call_connection_lost)NN)r2�
__module__�__qualname__rr9rr=r?r@r�warnings�warnrGrHrIrKrLrMrOrBr&rcrerfrhrirdro�
__classcell__r.r.r,r/r
s2�+&	rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rPcCs||_||_d|_d|_dS)NF)r]rJr5rj)r'r]rJr.r.r/rsz!WriteSubprocessPipeProto.__init__cCs
||_dSr:)r5)r'Z	transportr.r.r/rWsz(WriteSubprocessPipeProto.connection_madecCs d|jj�d|j�d|j�d�S)N�<z fd=z pipe=�>)r-r2rJr5r>r.r.r/r9
sz!WriteSubprocessPipeProto.__repr__cCs d|_|j�|j|�d|_dS)NT)rjr]rerJrqr.r.r/rp
sz(WriteSubprocessPipeProto.connection_lostcCs|jj��dSr:)r]r�
pause_writingr>r.r.r/rysz&WriteSubprocessPipeProto.pause_writingcCs|jj��dSr:)r]r�resume_writingr>r.r.r/rzsz'WriteSubprocessPipeProto.resume_writingN)	r2rrrsrrWr9rpryrzr.r.r.r/rP�srPc@seZdZdd�ZdS)rTcCs|j�|j|�dSr:)r]rfrJ)r'r`r.r.r/�
data_receivedsz%ReadSubprocessPipeProto.data_receivedN)r2rrrsr{r.r.r.r/rTsrT)rrrt�rr�logrZSubprocessTransportrZBaseProtocolrPZProtocolrTr.r.r.r/�<module>sv�PK [���/$$0__pycache__/base_subprocess.cpython-38.opt-2.pycnu�[���U

e5d�"�@sxddlZddlZddlZddlmZddlmZddlmZGdd�dej�Z	Gdd	�d	ej
�ZGd
d�deej�Z
dS)�N�)�	protocols)�
transports)�loggercs�eZdZd0�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jfdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Z�ZS)1�BaseSubprocessTransportNc
	s&t��|
�d|_||_||_d|_d|_d|_g|_t	�
�|_i|_d|_
|tjkr`d|jd<|tjkrtd|jd<|tjkr�d|jd<z"|jf||||||d�|��Wn|���YnX|jj|_|j|jd<|j���rt|ttf�r�|}n|d}t�d||j�|j�|�|	��dS)NFrr�)�args�shell�stdin�stdout�stderr�bufsize�
subprocesszprocess %r created: pid %s)�super�__init__�_closed�	_protocol�_loop�_proc�_pid�_returncode�
_exit_waiters�collections�deque�_pending_calls�_pipes�	_finishedr�PIPE�_start�close�pidZ_extra�	get_debug�
isinstance�bytes�strr�debugZcreate_task�_connect_pipes)
�self�loop�protocolrr	r
rrr
�waiterZextra�kwargsZprogram��	__class__��//usr/lib64/python3.8/asyncio/base_subprocess.pyrsL






��

�z BaseSubprocessTransport.__init__cCs|jjg}|jr|�d�|jdk	r6|�d|j���|jdk	rT|�d|j���n |jdk	rj|�d�n
|�d�|j�d�}|dk	r�|�d|j���|j�d�}|j�d	�}|dk	r�||kr�|�d
|j���n6|dk	r�|�d|j���|dk	�r|�d|j���d
�	d�
|��S)N�closedzpid=zreturncode=Zrunningznot startedrzstdin=rrzstdout=stderr=zstdout=zstderr=z<{}>� )r-�__name__r�appendrrr�get�pipe�format�join)r'�infor
rrr.r.r/�__repr__7s,






z BaseSubprocessTransport.__repr__cKst�dS�N)�NotImplementedError)r'rr	r
rrr
r+r.r.r/rTszBaseSubprocessTransport._startcCs
||_dSr:�r)r'r)r.r.r/�set_protocolWsz$BaseSubprocessTransport.set_protocolcCs|jSr:r<�r'r.r.r/�get_protocolZsz$BaseSubprocessTransport.get_protocolcCs|jSr:)rr>r.r.r/�
is_closing]sz"BaseSubprocessTransport.is_closingcCs�|jr
dSd|_|j��D]}|dkr(q|j��q|jdk	r�|jdkr�|j��dkr�|j�	�rlt
�d|�z|j��Wnt
k
r�YnXdS)NTz$Close running child process: kill %r)rr�valuesr5rrrZpollrr!rZwarning�kill�ProcessLookupError)r'�protor.r.r/r`s$
��
zBaseSubprocessTransport.closecCs&|js"|d|��t|d�|��dS)Nzunclosed transport )�source)r�ResourceWarningr)r'Z_warnr.r.r/�__del__{szBaseSubprocessTransport.__del__cCs|jSr:)rr>r.r.r/�get_pid�szBaseSubprocessTransport.get_pidcCs|jSr:)rr>r.r.r/�get_returncode�sz&BaseSubprocessTransport.get_returncodecCs||jkr|j|jSdSdSr:)rr5)r'�fdr.r.r/�get_pipe_transport�s
z*BaseSubprocessTransport.get_pipe_transportcCs|jdkrt��dSr:)rrCr>r.r.r/�_check_proc�s
z#BaseSubprocessTransport._check_proccCs|��|j�|�dSr:)rLr�send_signal)r'�signalr.r.r/rM�sz#BaseSubprocessTransport.send_signalcCs|��|j��dSr:)rLr�	terminater>r.r.r/rO�sz!BaseSubprocessTransport.terminatecCs|��|j��dSr:)rLrrBr>r.r.r/rB�szBaseSubprocessTransport.killc	
�s`z�j}�j}|jdk	rB|��fdd�|j�IdH\}}|�jd<|jdk	rv|��fdd�|j�IdH\}}|�jd<|jdk	r�|��fdd�|j�IdH\}}|�jd<|��j	j
���jD]\}}|j|f|��q�d�_WnZtt
fk
r��Yn`tk
�r<}z"|dk	�r,|���s,|�|�W5d}~XYn X|dk	�r\|���s\|�d�dS)Ncs
t�d�S)Nr)�WriteSubprocessPipeProtor.r>r.r/�<lambda>��z8BaseSubprocessTransport._connect_pipes.<locals>.<lambda>rcs
t�d�S)Nr��ReadSubprocessPipeProtor.r>r.r/rQ�rRrcs
t�d�S)NrrSr.r>r.r/rQ�rRr)rrr
Zconnect_write_piperrZconnect_read_piper�	call_soonr�connection_mader�
SystemExit�KeyboardInterrupt�
BaseException�	cancelledZ
set_exception�
set_result)	r'r*�procr(�_r5�callback�data�excr.r>r/r&�s@

�


�


�

z&BaseSubprocessTransport._connect_pipescGs2|jdk	r|j�||f�n|jj|f|��dSr:)rr3rrU)r'�cbr_r.r.r/�_call�s
zBaseSubprocessTransport._callcCs|�|jj||�|��dSr:)rbrZpipe_connection_lost�_try_finish)r'rJr`r.r.r/�_pipe_connection_lost�sz-BaseSubprocessTransport._pipe_connection_lostcCs|�|jj||�dSr:)rbrZpipe_data_received)r'rJr_r.r.r/�_pipe_data_received�sz+BaseSubprocessTransport._pipe_data_receivedcCsp|j��rt�d||�||_|jjdkr2||j_|�|jj	�|�
�|jD]}|��sN|�
|�qNd|_dS)Nz%r exited with return code %r)rr!rr8rr�
returncoderbrZprocess_exitedrcrrZr[)r'rfr*r.r.r/�_process_exited�s

z'BaseSubprocessTransport._process_exitedc�s0|jdk	r|jS|j��}|j�|�|IdHSr:)rrZ
create_futurerr3)r'r*r.r.r/�_wait�s


zBaseSubprocessTransport._waitcCs>|jdkrdStdd�|j��D��r:d|_|�|jd�dS)Ncss|]}|dk	o|jVqdSr:)�disconnected)�.0�pr.r.r/�	<genexpr>�s�z6BaseSubprocessTransport._try_finish.<locals>.<genexpr>T)r�allrrArrb�_call_connection_lostr>r.r.r/rc�s
�z#BaseSubprocessTransport._try_finishcCs*z|j�|�W5d|_d|_d|_XdSr:)rrr�connection_lost�r'r`r.r.r/rn�s
z-BaseSubprocessTransport._call_connection_lost)NN)r2�
__module__�__qualname__rr9rr=r?r@r�warnings�warnrGrHrIrKrLrMrOrBr&rbrdrergrhrcrn�
__classcell__r.r.r,r/r
s2�+&	rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rPcCs||_||_d|_d|_dS)NF)r\rJr5ri)r'r\rJr.r.r/rsz!WriteSubprocessPipeProto.__init__cCs
||_dSr:)r5)r'Z	transportr.r.r/rVsz(WriteSubprocessPipeProto.connection_madecCs d|jj�d|j�d|j�d�S)N�<z fd=z pipe=�>)r-r2rJr5r>r.r.r/r9
sz!WriteSubprocessPipeProto.__repr__cCs d|_|j�|j|�d|_dS)NT)rir\rdrJrpr.r.r/ro
sz(WriteSubprocessPipeProto.connection_lostcCs|jj��dSr:)r\r�
pause_writingr>r.r.r/rxsz&WriteSubprocessPipeProto.pause_writingcCs|jj��dSr:)r\r�resume_writingr>r.r.r/rysz'WriteSubprocessPipeProto.resume_writingN)	r2rqrrrrVr9rorxryr.r.r.r/rP�srPc@seZdZdd�ZdS)rTcCs|j�|j|�dSr:)r\rerJ)r'r_r.r.r/�
data_receivedsz%ReadSubprocessPipeProto.data_receivedN)r2rqrrrzr.r.r.r/rTsrT)rrrs�rr�logrZSubprocessTransportrZBaseProtocolrPZProtocolrTr.r.r.r/�<module>sv�PK [�H��m�m!__pycache__/events.cpython-38.pycnu�[���U

e5d4f�@s|dZdZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
Gdd�d�ZGd	d
�d
e�ZGdd�d�Z
Gd
d�d�ZGdd�d�ZGdd�de�Zdae��ZGdd�dej�Ze�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Z d)d*�Z!eZ"eZ#eZ$eZ%zdd+l&mZmZmZmZWne'k
�rfYnXeZ(eZ)eZ*eZ+dS),z!Event loop and event loop policy.)�AbstractEventLoopPolicy�AbstractEventLoop�AbstractServer�Handle�TimerHandle�get_event_loop_policy�set_event_loop_policy�get_event_loop�set_event_loop�new_event_loop�get_child_watcher�set_child_watcher�_set_running_loop�get_running_loop�_get_running_loop�N�)�format_helpers)�
exceptionsc@sFeZdZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)rz1Object returned by callback registration methods.)�	_callback�_args�
_cancelled�_loop�_source_traceback�_repr�__weakref__�_contextNcCs\|dkrt��}||_||_||_||_d|_d|_|j��rRt	�
t�d��|_
nd|_
dS)NFr)�contextvarsZcopy_contextrrrrrr�	get_debugr�
extract_stack�sys�	_getframer)�self�callback�args�loop�context�r&�&/usr/lib64/python3.8/asyncio/events.py�__init__ s
�zHandle.__init__cCsl|jjg}|jr|�d�|jdk	r:|�t�|j|j��|jrh|jd}|�d|d�d|d���|S)N�	cancelled���zcreated at r�:r)	�	__class__�__name__r�appendrr�_format_callback_sourcerr)r!�info�framer&r&r'�
_repr_info/s


�
zHandle._repr_infocCs(|jdk	r|jS|��}d�d�|��S)Nz<{}>� )rr2�format�join)r!r0r&r&r'�__repr__;s
zHandle.__repr__cCs0|js,d|_|j��r t|�|_d|_d|_dS�NT)rrr�reprrrr�r!r&r&r'�cancelAs

z
Handle.cancelcCs|jS�N)rr9r&r&r'r)LszHandle.cancelledc
Cs�z|jj|jf|j��Wn|ttfk
r4�Yndtk
r�}zFt�|j|j�}d|��}|||d�}|j	rz|j	|d<|j
�|�W5d}~XYnXd}dS)NzException in callback )�messageZ	exception�handleZsource_traceback)r�runrr�
SystemExit�KeyboardInterrupt�
BaseExceptionrr/rr�call_exception_handler)r!�exc�cb�msgr%r&r&r'�_runOs$�
�
zHandle._run)N)r-�
__module__�__qualname__�__doc__�	__slots__r(r2r6r:r)rFr&r&r&r'rs
rcs�eZdZdZddgZd�fdd�	Z�fdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
�fdd�Zdd�Z�ZS)rz7Object returned by timed callback registration methods.�
_scheduled�_whenNcs<|dk	st�t��||||�|jr,|jd=||_d|_dS)Nr*F)�AssertionError�superr(rrLrK)r!�whenr"r#r$r%�r,r&r'r(hszTimerHandle.__init__cs0t���}|jrdnd}|�|d|j���|S)N�rzwhen=)rNr2r�insertrL)r!r0�posrPr&r'r2ps
zTimerHandle._repr_infocCs
t|j�Sr;)�hashrLr9r&r&r'�__hash__vszTimerHandle.__hash__cCs|j|jkSr;�rL�r!�otherr&r&r'�__lt__yszTimerHandle.__lt__cCs|j|jkrdS|�|�Sr7�rL�__eq__rWr&r&r'�__le__|szTimerHandle.__le__cCs|j|jkSr;rVrWr&r&r'�__gt__�szTimerHandle.__gt__cCs|j|jkrdS|�|�Sr7rZrWr&r&r'�__ge__�szTimerHandle.__ge__cCs>t|t�r:|j|jko8|j|jko8|j|jko8|j|jkStSr;)�
isinstancerrLrrr�NotImplementedrWr&r&r'r[�s

�
�
�zTimerHandle.__eq__cCs|�|�}|tkrtS|Sr;)r[r`)r!rXZequalr&r&r'�__ne__�s
zTimerHandle.__ne__cs |js|j�|�t���dSr;)rr�_timer_handle_cancelledrNr:r9rPr&r'r:�szTimerHandle.cancelcCs|jS)z�Return a scheduled callback time.

        The time is an absolute timestamp, using the same time
        reference as loop.time().
        rVr9r&r&r'rO�szTimerHandle.when)N)r-rGrHrIrJr(r2rUrYr\r]r^r[rar:rO�
__classcell__r&r&rPr'rcsrc@sPeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)rz,Abstract server returned by create_server().cCst�dS)z5Stop serving.  This leaves existing connections open.N��NotImplementedErrorr9r&r&r'�close�szAbstractServer.closecCst�dS)z4Get the event loop the Server object is attached to.Nrdr9r&r&r'�get_loop�szAbstractServer.get_loopcCst�dS)z3Return True if the server is accepting connections.Nrdr9r&r&r'�
is_serving�szAbstractServer.is_servingc�st�dS)z�Start accepting connections.

        This method is idempotent, so it can be called when
        the server is already being serving.
        Nrdr9r&r&r'�
start_serving�szAbstractServer.start_servingc�st�dS)z�Start accepting connections until the coroutine is cancelled.

        The server is closed when the coroutine is cancelled.
        Nrdr9r&r&r'�
serve_forever�szAbstractServer.serve_foreverc�st�dS)z*Coroutine to wait until service is closed.Nrdr9r&r&r'�wait_closed�szAbstractServer.wait_closedc�s|Sr;r&r9r&r&r'�
__aenter__�szAbstractServer.__aenter__c�s|��|��IdHdSr;)rfrk)r!rCr&r&r'�	__aexit__�szAbstractServer.__aexit__N)r-rGrHrIrfrgrhrirjrkrlrmr&r&r&r'r�src@sVeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�dd�Zd d!�Zd"d#�Zd$d%�Zd&d&d&d&d'�d(d)�Zdud*d+�Zdvdd&d&d&ddddddd,�
d-d.�Zdwejejdd/ddddd0d1�	d2d3�Zdxd0d4�d5d6�Zd7ddd8�d9d:�Zdyddddd;�d<d=�Zdzdd/ddd0d>�d?d@�Zd{d&d&d&dddddA�dBdC�Z dDdE�Z!dFdG�Z"e#j$e#j$e#j$dH�dIdJ�Z%e#j$e#j$e#j$dH�dKdL�Z&dMdN�Z'dOdP�Z(dQdR�Z)dSdT�Z*dUdV�Z+dWdX�Z,dYdZ�Z-d[d\�Z.d]d^�Z/d|dd4�d_d`�Z0dadb�Z1dcdd�Z2dedf�Z3dgdh�Z4didj�Z5dkdl�Z6dmdn�Z7dodp�Z8dqdr�Z9dsdt�Z:dS)}rzAbstract event loop.cCst�dS)z*Run the event loop until stop() is called.Nrdr9r&r&r'�run_forever�szAbstractEventLoop.run_forevercCst�dS)zpRun the event loop until a Future is done.

        Return the Future's result, or raise its exception.
        Nrd)r!Zfuturer&r&r'�run_until_complete�sz$AbstractEventLoop.run_until_completecCst�dS)z�Stop the event loop as soon as reasonable.

        Exactly how soon that is may depend on the implementation, but
        no more I/O callbacks should be scheduled.
        Nrdr9r&r&r'�stop�szAbstractEventLoop.stopcCst�dS)z3Return whether the event loop is currently running.Nrdr9r&r&r'�
is_running�szAbstractEventLoop.is_runningcCst�dS)z*Returns True if the event loop was closed.Nrdr9r&r&r'�	is_closed�szAbstractEventLoop.is_closedcCst�dS)z�Close the loop.

        The loop should not be running.

        This is idempotent and irreversible.

        No other methods should be called after this one.
        Nrdr9r&r&r'rf�s	zAbstractEventLoop.closec�st�dS)z,Shutdown all active asynchronous generators.Nrdr9r&r&r'�shutdown_asyncgens�sz$AbstractEventLoop.shutdown_asyncgenscCst�dS)z3Notification that a TimerHandle has been cancelled.Nrd)r!r=r&r&r'rb�sz)AbstractEventLoop._timer_handle_cancelledcGs|jd|f|��S)Nr)�
call_later�r!r"r#r&r&r'�	call_soonszAbstractEventLoop.call_sooncGst�dSr;rd)r!Zdelayr"r#r&r&r'rtszAbstractEventLoop.call_latercGst�dSr;rd)r!rOr"r#r&r&r'�call_atszAbstractEventLoop.call_atcCst�dSr;rdr9r&r&r'�timeszAbstractEventLoop.timecCst�dSr;rdr9r&r&r'�
create_futureszAbstractEventLoop.create_futureN)�namecCst�dSr;rd)r!�cororzr&r&r'�create_taskszAbstractEventLoop.create_taskcGst�dSr;rdrur&r&r'�call_soon_threadsafesz&AbstractEventLoop.call_soon_threadsafecGst�dSr;rd)r!�executor�funcr#r&r&r'�run_in_executorsz!AbstractEventLoop.run_in_executorcCst�dSr;rd)r!r~r&r&r'�set_default_executorsz&AbstractEventLoop.set_default_executorr)�family�type�proto�flagsc�st�dSr;rd)r!�host�portr�r�r�r�r&r&r'�getaddrinfo#szAbstractEventLoop.getaddrinfoc�st�dSr;rd)r!Zsockaddrr�r&r&r'�getnameinfo'szAbstractEventLoop.getnameinfo)
�sslr�r�r��sock�
local_addr�server_hostname�ssl_handshake_timeout�happy_eyeballs_delay�
interleavec
�st�dSr;rd)r!�protocol_factoryr�r�r�r�r�r�r�r�r�r�r�r�r&r&r'�create_connection*sz#AbstractEventLoop.create_connection�dT)	r�r�r��backlogr��
reuse_address�
reuse_portr�ric	
�st�dS)adA coroutine which creates a TCP server bound to host and port.

        The return value is a Server object which can be used to stop
        the service.

        If host is an empty string or None all interfaces are assumed
        and a list of multiple sockets will be returned (most likely
        one for IPv4 and another one for IPv6). The host parameter can also be
        a sequence (e.g. list) of hosts to bind to.

        family can be set to either AF_INET or AF_INET6 to force the
        socket to use IPv4 or IPv6. If not set it will be determined
        from host (defaults to AF_UNSPEC).

        flags is a bitmask for getaddrinfo().

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows.

        ssl_handshake_timeout is the time in seconds that an SSL server
        will wait for completion of the SSL handshake before aborting the
        connection. Default is 60s.

        start_serving set to True (default) causes the created server
        to start accepting connections immediately.  When set to False,
        the user should await Server.start_serving() or Server.serve_forever()
        to make the server to start accepting connections.
        Nrd)
r!r�r�r�r�r�r�r�r�r�r�r�rir&r&r'�
create_server3s3zAbstractEventLoop.create_server)�fallbackc�st�dS)zRSend a file through a transport.

        Return an amount of sent bytes.
        Nrd)r!�	transport�file�offset�countr�r&r&r'�sendfilehszAbstractEventLoop.sendfileF)�server_sider�r�c�st�dS)z|Upgrade a transport to TLS.

        Return a new transport that *protocol* should start using
        immediately.
        Nrd)r!r�ZprotocolZ
sslcontextr�r�r�r&r&r'�	start_tlsps	zAbstractEventLoop.start_tls)r�r�r�r�c�st�dSr;rd)r!r��pathr�r�r�r�r&r&r'�create_unix_connection{sz(AbstractEventLoop.create_unix_connection)r�r�r�r�ric�st�dS)a�A coroutine which creates a UNIX Domain Socket server.

        The return value is a Server object, which can be used to stop
        the service.

        path is a str, representing a file systsem path to bind the
        server socket to.

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        ssl_handshake_timeout is the time in seconds that an SSL server
        will wait for the SSL handshake to complete (defaults to 60s).

        start_serving set to True (default) causes the created server
        to start accepting connections immediately.  When set to False,
        the user should await Server.start_serving() or Server.serve_forever()
        to make the server to start accepting connections.
        Nrd)r!r�r�r�r�r�r�rir&r&r'�create_unix_server�sz$AbstractEventLoop.create_unix_server)r�r�r�r�r��allow_broadcastr�c�st�dS)a�A coroutine which creates a datagram endpoint.

        This method will try to establish the endpoint in the background.
        When successful, the coroutine returns a (transport, protocol) pair.

        protocol_factory must be a callable returning a protocol instance.

        socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
        host (or family if specified), socket type SOCK_DGRAM.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified it will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows and some UNIX's. If the
        :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
        capability is unsupported.

        allow_broadcast tells the kernel to allow this endpoint to send
        messages to the broadcast address.

        sock can optionally be specified in order to use a preexisting
        socket object.
        Nrd)r!r�r�Zremote_addrr�r�r�r�r�r�r�r&r&r'�create_datagram_endpoint�s!z*AbstractEventLoop.create_datagram_endpointc�st�dS)aRegister read pipe in event loop. Set the pipe to non-blocking mode.

        protocol_factory should instantiate object with Protocol interface.
        pipe is a file-like object.
        Return pair (transport, protocol), where transport supports the
        ReadTransport interface.Nrd�r!r��piper&r&r'�connect_read_pipe�sz#AbstractEventLoop.connect_read_pipec�st�dS)aRegister write pipe in event loop.

        protocol_factory should instantiate object with BaseProtocol interface.
        Pipe is file-like object already switched to nonblocking.
        Return pair (transport, protocol), where transport support
        WriteTransport interface.Nrdr�r&r&r'�connect_write_pipe�sz$AbstractEventLoop.connect_write_pipe)�stdin�stdout�stderrc�st�dSr;rd)r!r��cmdr�r�r��kwargsr&r&r'�subprocess_shell�sz"AbstractEventLoop.subprocess_shellc�st�dSr;rd)r!r�r�r�r�r#r�r&r&r'�subprocess_exec�sz!AbstractEventLoop.subprocess_execcGst�dSr;rd�r!�fdr"r#r&r&r'�
add_reader�szAbstractEventLoop.add_readercCst�dSr;rd�r!r�r&r&r'�
remove_reader�szAbstractEventLoop.remove_readercGst�dSr;rdr�r&r&r'�
add_writer�szAbstractEventLoop.add_writercCst�dSr;rdr�r&r&r'�
remove_writer�szAbstractEventLoop.remove_writerc�st�dSr;rd)r!r��nbytesr&r&r'�	sock_recvszAbstractEventLoop.sock_recvc�st�dSr;rd)r!r�Zbufr&r&r'�sock_recv_intosz AbstractEventLoop.sock_recv_intoc�st�dSr;rd)r!r��datar&r&r'�sock_sendallszAbstractEventLoop.sock_sendallc�st�dSr;rd)r!r�Zaddressr&r&r'�sock_connectszAbstractEventLoop.sock_connectc�st�dSr;rd)r!r�r&r&r'�sock_acceptszAbstractEventLoop.sock_acceptc�st�dSr;rd)r!r�r�r�r�r�r&r&r'�
sock_sendfileszAbstractEventLoop.sock_sendfilecGst�dSr;rd)r!�sigr"r#r&r&r'�add_signal_handlersz$AbstractEventLoop.add_signal_handlercCst�dSr;rd)r!r�r&r&r'�remove_signal_handlersz'AbstractEventLoop.remove_signal_handlercCst�dSr;rd)r!�factoryr&r&r'�set_task_factorysz"AbstractEventLoop.set_task_factorycCst�dSr;rdr9r&r&r'�get_task_factory"sz"AbstractEventLoop.get_task_factorycCst�dSr;rdr9r&r&r'�get_exception_handler'sz'AbstractEventLoop.get_exception_handlercCst�dSr;rd)r!Zhandlerr&r&r'�set_exception_handler*sz'AbstractEventLoop.set_exception_handlercCst�dSr;rd�r!r%r&r&r'�default_exception_handler-sz+AbstractEventLoop.default_exception_handlercCst�dSr;rdr�r&r&r'rB0sz(AbstractEventLoop.call_exception_handlercCst�dSr;rdr9r&r&r'r5szAbstractEventLoop.get_debugcCst�dSr;rd)r!Zenabledr&r&r'�	set_debug8szAbstractEventLoop.set_debug)r)NN)NN)rN)N)N)NN)rN);r-rGrHrIrnrorprqrrrfrsrbrvrtrwrxryr|r}r�r�r�r�r��socketZ	AF_UNSPECZ
AI_PASSIVEr�r�r�r�r�r�r�r��
subprocess�PIPEr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rBrr�r&r&r&r'r�s��
��
��5�	�����!��%
���rc@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
rz-Abstract policy for accessing the event loop.cCst�dS)a:Get the event loop for the current context.

        Returns an event loop object implementing the BaseEventLoop interface,
        or raises an exception in case no event loop has been set for the
        current context and the current policy does not specify to create one.

        It should never return None.Nrdr9r&r&r'r?sz&AbstractEventLoopPolicy.get_event_loopcCst�dS)z3Set the event loop for the current context to loop.Nrd�r!r$r&r&r'r	Isz&AbstractEventLoopPolicy.set_event_loopcCst�dS)z�Create and return a new event loop object according to this
        policy's rules. If there's need to set this loop as the event loop for
        the current context, set_event_loop must be called explicitly.Nrdr9r&r&r'r
Msz&AbstractEventLoopPolicy.new_event_loopcCst�dS)z$Get the watcher for child processes.Nrdr9r&r&r'rUsz)AbstractEventLoopPolicy.get_child_watchercCst�dS)z$Set the watcher for child processes.Nrd)r!�watcherr&r&r'rYsz)AbstractEventLoopPolicy.set_child_watcherN)	r-rGrHrIrr	r
rrr&r&r&r'r<s
rc@sFeZdZdZdZGdd�dej�Zdd�Zdd�Z	d	d
�Z
dd�ZdS)
�BaseDefaultEventLoopPolicya�Default policy implementation for accessing the event loop.

    In this policy, each thread has its own event loop.  However, we
    only automatically create an event loop by default for the main
    thread; other threads by default have no event loop.

    Other policies may have different rules (e.g. a single global
    event loop, or automatically creating an event loop per thread, or
    using some other notion of context to which an event loop is
    associated).
    Nc@seZdZdZdZdS)z!BaseDefaultEventLoopPolicy._LocalNF)r-rGrHr�_set_calledr&r&r&r'�_Localmsr�cCs|��|_dSr;)r��_localr9r&r&r'r(qsz#BaseDefaultEventLoopPolicy.__init__cCsX|jjdkr2|jjs2tt��tj�r2|�|���|jjdkrPt	dt��j
��|jjS)zvGet the event loop for the current context.

        Returns an instance of EventLoop or raises an exception.
        Nz,There is no current event loop in thread %r.)r�rr�r_�	threadingZcurrent_threadZ_MainThreadr	r
�RuntimeErrorrzr9r&r&r'rts���z)BaseDefaultEventLoopPolicy.get_event_loopcCs*d|j_|dkst|t�st�||j_dS)zSet the event loop.TN)r�r�r_rrMrr�r&r&r'r	�sz)BaseDefaultEventLoopPolicy.set_event_loopcCs|��S)zvCreate a new event loop.

        You must call set_event_loop() to make this the current event
        loop.
        )�
_loop_factoryr9r&r&r'r
�sz)BaseDefaultEventLoopPolicy.new_event_loop)r-rGrHrIr�r��localr�r(rr	r
r&r&r&r'r�^sr�c@seZdZdZdS)�_RunningLoop)NNN)r-rGrH�loop_pidr&r&r&r'r��sr�cCst�}|dkrtd��|S)zrReturn the running event loop.  Raise a RuntimeError if there is none.

    This function is thread-specific.
    Nzno running event loop)rr��r$r&r&r'r�srcCs&tj\}}|dk	r"|t��kr"|SdS)z�Return the running event loop or None.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)�
_running_loopr��os�getpid)Zrunning_loop�pidr&r&r'r�s
rcCs|t��ft_dS)z�Set the running event loop.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)r�r�r�r�r�r&r&r'r
�sr
c	Cs.t� tdkr ddlm}|�aW5QRXdS)Nr��DefaultEventLoopPolicy)�_lock�_event_loop_policy�r�r�r&r&r'�_init_event_loop_policy�sr�cCstdkrt�tS)z"Get the current event loop policy.N)r�r�r&r&r&r'r�srcCs|dkst|t�st�|adS)zZSet the current event loop policy.

    If policy is None, the default policy is restored.N)r_rrMr�)Zpolicyr&r&r'r�srcCst�}|dk	r|St���S)aGReturn an asyncio event loop.

    When called from a coroutine or a callback (e.g. scheduled with call_soon
    or similar API), this function will always return the running event loop.

    If there is no running event loop set, the function will return
    the result of `get_event_loop_policy().get_event_loop()` call.
    N)rrr)Zcurrent_loopr&r&r'r�s
rcCst��|�dS)zCEquivalent to calling get_event_loop_policy().set_event_loop(loop).N)rr	r�r&r&r'r	�sr	cCs
t���S)z?Equivalent to calling get_event_loop_policy().new_event_loop().)rr
r&r&r&r'r
�sr
cCs
t���S)zBEquivalent to calling get_event_loop_policy().get_child_watcher().)rrr&r&r&r'r�srcCst��|�S)zMEquivalent to calling
    get_event_loop_policy().set_child_watcher(watcher).)rr)r�r&r&r'r�sr)rr
rr),rI�__all__rr�r�r�rr�r�rrrrrrrr�r�ZLockr�r�r�r�rrr
r�rrrr	r
rrZ_py__get_running_loopZ_py__set_running_loopZ_py_get_running_loopZ_py_get_event_loopZ_asyncio�ImportErrorZ_c__get_running_loopZ_c__set_running_loopZ_c_get_running_loopZ_c_get_event_loopr&r&r&r'�<module>sXJ@*q"9
	PK [�h���(__pycache__/runners.cpython-38.opt-1.pycnu�[���U

e5d�@sBdZddlmZddlmZddlmZdd�dd�Zd	d
�ZdS))�run�)�
coroutines)�events)�tasksN)�debugcCs�t��dk	rtd��t�|�s,td�|���t��}z*t�|�|dk	rR|�
|�|�|�W�Szt
|�|�|���W5t�d�|�	�XXdS)a�Execute the coroutine and return the result.

    This function runs the passed coroutine, taking care of
    managing the asyncio event loop and finalizing asynchronous
    generators.

    This function cannot be called when another asyncio event loop is
    running in the same thread.

    If debug is True, the event loop will be run in debug mode.

    This function always creates a new event loop and closes it at the end.
    It should be used as a main entry point for asyncio programs, and should
    ideally only be called once.

    Example:

        async def main():
            await asyncio.sleep(1)
            print('hello')

        asyncio.run(main())
    Nz8asyncio.run() cannot be called from a running event loopz"a coroutine was expected, got {!r})rZ_get_running_loop�RuntimeErrorrZiscoroutine�
ValueError�formatZnew_event_loopZset_event_loop�close�_cancel_all_tasks�run_until_completeZshutdown_asyncgensZ	set_debug)�mainr�loop�r�'/usr/lib64/python3.8/asyncio/runners.pyrs"�



rcCsvt�|�}|sdS|D]}|��q|�tj||dd���|D]0}|��rNq@|��dk	r@|�d|��|d��q@dS)NT)rZreturn_exceptionsz1unhandled exception during asyncio.run() shutdown)�message�	exception�task)rZ	all_tasksZcancelrZgatherZ	cancelledrZcall_exception_handler)rZ	to_cancelrrrrr6s"

��r)�__all__�rrrrrrrrr�<module>s
.PK [i�.CHH'__pycache__/queues.cpython-38.opt-2.pycnu�[���U

e5d �@s�dZddlZddlZddlZddlmZddlmZGdd�de�ZGdd	�d	e�Z	Gd
d�d�Z
Gdd
�d
e
�ZGdd�de
�ZdS))�Queue�
PriorityQueue�	LifoQueue�	QueueFull�
QueueEmpty�N�)�events)�locksc@seZdZdS)rN��__name__�
__module__�__qualname__�rr�&/usr/lib64/python3.8/asyncio/queues.pyrsrc@seZdZdS)rNr
rrrrrsrc@s�eZdZd(dd�dd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Zdd�Z	dd�Z
dd�Zedd��Z
dd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�ZdS))rrN��loopcCsp|dkrt��|_n||_tjdtdd�||_t��|_	t��|_
d|_tj
|d�|_|j��|�|�dS)Nz[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.�)�
stacklevelrr)rZget_event_loop�_loop�warnings�warn�DeprecationWarning�_maxsize�collections�deque�_getters�_putters�_unfinished_tasksr	ZEvent�	_finished�set�_init)�self�maxsizerrrr�__init__!s�


zQueue.__init__cCst��|_dS�N)rr�_queue�r!r"rrrr 6szQueue._initcCs
|j��Sr$)r%�popleft�r!rrr�_get9sz
Queue._getcCs|j�|�dSr$�r%�append�r!�itemrrr�_put<sz
Queue._putcCs&|r"|��}|��s|�d�q"qdSr$)r'ZdoneZ
set_result)r!�waitersZwaiterrrr�_wakeup_nextAs

zQueue._wakeup_nextcCs(dt|�j�dt|�d�d|���d�S)N�<z at z#x� �>)�typer�id�_formatr(rrr�__repr__IszQueue.__repr__cCsdt|�j�d|���d�S)Nr1r2r3)r4rr6r(rrr�__str__Lsz
Queue.__str__cCs~d|j��}t|dd�r,|dt|j���7}|jrH|dt|j��d�7}|jrd|dt|j��d�7}|jrz|d|j��7}|S)Nzmaxsize=r%z _queue=z
 _getters[�]z
 _putters[z tasks=)r�getattr�listr%r�lenrr)r!�resultrrrr6Osz
Queue._formatcCs
t|j�Sr$)r<r%r(rrr�qsize[szQueue.qsizecCs|jSr$)rr(rrrr"_sz
Queue.maxsizecCs|jSr$�r%r(rrr�emptydszQueue.emptycCs |jdkrdS|��|jkSdS)NrF)rr>r(rrr�fullhs
z
Queue.fullc�s�|��r�|j��}|j�|�z|IdHWq|��z|j�|�Wntk
r`YnX|��s~|��s~|�	|j��YqXq|�
|�Sr$)rAr�
create_futurerr+�cancel�remove�
ValueError�	cancelledr0�
put_nowait)r!r-Zputterrrr�putss

z	Queue.putcCs>|��rt�|�|�|jd7_|j��|�|j�dS)Nr)rArr.rr�clearr0rr,rrrrG�s

zQueue.put_nowaitc�s�|��r�|j��}|j�|�z|IdHWq|��z|j�|�Wntk
r`YnX|��s~|��s~|�	|j��YqXq|�
�Sr$)r@rrBrr+rCrDrErFr0�
get_nowait)r!�getterrrr�get�s

z	Queue.getcCs$|��rt�|��}|�|j�|Sr$)r@rr)r0rr,rrrrJ�s
zQueue.get_nowaitcCs8|jdkrtd��|jd8_|jdkr4|j��dS)Nrz!task_done() called too many timesr)rrErrr(rrr�	task_done�s


zQueue.task_donec�s|jdkr|j��IdHdS)Nr)rr�waitr(rrr�join�s
z
Queue.join)r)rrr
r#r r)r.r0r7r8r6r>�propertyr"r@rArHrGrLrJrMrOrrrrrs&
rc@s0eZdZdd�Zejfdd�Zejfdd�ZdS)rcCs
g|_dSr$r?r&rrrr �szPriorityQueue._initcCs||j|�dSr$r?)r!r-�heappushrrrr.�szPriorityQueue._putcCs
||j�Sr$r?)r!�heappoprrrr)�szPriorityQueue._getN)	rrr
r �heapqrQr.rRr)rrrrr�src@s$eZdZdd�Zdd�Zdd�ZdS)rcCs
g|_dSr$r?r&rrrr �szLifoQueue._initcCs|j�|�dSr$r*r,rrrr.�szLifoQueue._putcCs
|j��Sr$)r%�popr(rrrr)�szLifoQueue._getN)rrr
r r.r)rrrrr�sr)
�__all__rrSr�rr	�	Exceptionrrrrrrrrr�<module>sKPK [6�8+��)__pycache__/__init__.cpython-38.opt-2.pycnu�[���U

e5d��@s�ddlZddlTddlTddlTddlTddlTddlTddlTddlTddl	Tddl
TddlTddlTddl
TddlmZejejejejejejejeje	je
jejeje
jZejdkr�ddlTeej7ZnddlTeej7ZdS)�N�)�*)�_all_tasks_compatZwin32)�sysZbase_eventsZ
coroutinesZevents�
exceptionsZfuturesZlocksZ	protocolsZrunnersZqueuesZstreams�
subprocessZtasksZ
transportsr�__all__�platformZwindows_eventsZunix_events�r
r
�(/usr/lib64/python3.8/asyncio/__init__.py�<module>sX��������	�
���
PK [wI<wss+__pycache__/exceptions.cpython-38.opt-2.pycnu�[���U

e5da�@shdZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGd	d
�d
e�Z	Gdd�de�Z
d
S))�CancelledError�InvalidStateError�TimeoutError�IncompleteReadError�LimitOverrunError�SendfileNotAvailableErrorc@seZdZdS)rN��__name__�
__module__�__qualname__�rr�*/usr/lib64/python3.8/asyncio/exceptions.pyr	src@seZdZdS)rNrrrrrr
src@seZdZdS)rNrrrrrrsrc@seZdZdS)rNrrrrrrsrcs$eZdZ�fdd�Zdd�Z�ZS)rcs@|dkrdnt|�}t��t|��d|�d��||_||_dS)NZ	undefinedz bytes read on a total of z expected bytes)�repr�super�__init__�len�partial�expected)�selfrrZ
r_expected��	__class__rrr$szIncompleteReadError.__init__cCst|�|j|jffS�N)�typerr�rrrr�
__reduce__+szIncompleteReadError.__reduce__�rr	r
rr�
__classcell__rrrrrsrcs$eZdZ�fdd�Zdd�Z�ZS)rcst��|�||_dSr)rr�consumed)r�messagerrrrr5szLimitOverrunError.__init__cCst|�|jd|jffS)N�)r�argsrrrrrr9szLimitOverrunError.__reduce__rrrrrr/srN)�__all__�
BaseExceptionr�	Exceptionrr�RuntimeErrorr�EOFErrorrrrrrr�<module>sPK [?��O�O(__pycache__/streams.cpython-38.opt-1.pycnu�[���U

e5d h�@s&dZddlZddlZddlZddlZeed�r6ed7ZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlm
Z
ddlmZd
Zdded�dd�Zd ded�dd�Zeed�r�d!ded�dd�Zd"ded�dd�ZGdd�dej�ZGdd�deej�ZGdd�d�ZGdd�d�ZdS)#)�StreamReader�StreamWriter�StreamReaderProtocol�open_connection�start_server�NZAF_UNIX)�open_unix_connection�start_unix_server�)�
coroutines)�events)�
exceptions)�format_helpers)�	protocols)�logger)�sleepi)�loop�limitc	�st|dkrt��}ntjdtdd�t||d�}t||d��|j�fdd�||f|�IdH\}}t|�||�}||fS)	a�A wrapper for create_connection() returning a (reader, writer) pair.

    The reader returned is a StreamReader instance; the writer is a
    StreamWriter instance.

    The arguments are all the usual arguments to create_connection()
    except protocol_factory; most common are positional host and port,
    with various optional keyword arguments following.

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    (If you want to customize the StreamReader and/or
    StreamReaderProtocol classes, just copy the code -- there's
    really nothing special here except some convenience.)
    N�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.���
stacklevel�rr�rcs�S�N�r��protocolr�'/usr/lib64/python3.8/asyncio/streams.py�<lambda>5�z!open_connection.<locals>.<lambda>)	r�get_event_loop�warnings�warn�DeprecationWarningrrZcreate_connectionr)	�host�portrr�kwds�reader�	transport�_�writerrrrrs"
�
��rc�sJ�dkrt���ntjdtdd����fdd�}�j|||f|�IdHS)a�Start a socket server, call back for each client connected.

    The first parameter, `client_connected_cb`, takes two parameters:
    client_reader, client_writer.  client_reader is a StreamReader
    object, while client_writer is a StreamWriter object.  This
    parameter can either be a plain callback function or a coroutine;
    if it is a coroutine, it will be automatically converted into a
    Task.

    The rest of the arguments are all the usual arguments to
    loop.create_server() except protocol_factory; most common are
    positional host and port, with various optional keyword arguments
    following.  The return value is the same as loop.create_server().

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    The return value is the same as loop.create_server(), i.e. a
    Server object which can be used to stop the service.
    Nrrrcst��d�}t|��d�}|S�Nrr�rr�r'r��client_connected_cbrrrr�factoryXs
�zstart_server.<locals>.factory)rr r!r"r#Z
create_server)r/r$r%rrr&r0rr.rr:s
�rc�sr|dkrt��}ntjdtdd�t||d�}t||d��|j�fdd�|f|�IdH\}}t|�||�}||fS)	z@Similar to `open_connection` but works with UNIX Domain Sockets.Nrrrrrcs�Srrrrrrrprz&open_unix_connection.<locals>.<lambda>)	rr r!r"r#rrZcreate_unix_connectionr)�pathrrr&r'r(r)r*rrrrds 
�
��rc�sH�dkrt���ntjdtdd����fdd�}�j||f|�IdHS)z=Similar to `start_server` but works with UNIX Domain Sockets.Nrrrcst��d�}t|��d�}|Sr+r,r-r.rrr0~s
�z"start_unix_server.<locals>.factory)rr r!r"r#Zcreate_unix_server)r/r1rrr&r0rr.rrts
�rc@sBeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�FlowControlMixina)Reusable flow control logic for StreamWriter.drain().

    This implements the protocol methods pause_writing(),
    resume_writing() and connection_lost().  If the subclass overrides
    these it must call the super methods.

    StreamWriter.drain() must wait for _drain_helper() coroutine.
    NcCs0|dkrt��|_n||_d|_d|_d|_dS�NF)rr �_loop�_paused�
_drain_waiter�_connection_lost)�selfrrrr�__init__�szFlowControlMixin.__init__cCs d|_|j��rt�d|�dS)NTz%r pauses writing)r5r4�	get_debugr�debug�r8rrr�
pause_writing�s
zFlowControlMixin.pause_writingcCsFd|_|j��rt�d|�|j}|dk	rBd|_|��sB|�d�dS)NFz%r resumes writing)r5r4r:rr;r6�done�
set_result�r8�waiterrrr�resume_writing�s
zFlowControlMixin.resume_writingcCsVd|_|jsdS|j}|dkr"dSd|_|��r4dS|dkrH|�d�n
|�|�dS�NT)r7r5r6r>r?�
set_exception�r8�excrArrr�connection_lost�sz FlowControlMixin.connection_lostc�s<|jrtd��|jsdS|j}|j��}||_|IdHdS)NzConnection lost)r7�ConnectionResetErrorr5r6r4�
create_futurer@rrr�
_drain_helper�s
zFlowControlMixin._drain_helpercCst�dSr)�NotImplementedError�r8�streamrrr�_get_close_waiter�sz"FlowControlMixin._get_close_waiter)N)
�__name__�
__module__�__qualname__�__doc__r9r=rBrGrJrNrrrrr2�s	
	r2csfeZdZdZdZd�fdd�	Zedd��Zdd�Z�fd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
�ZS)ra=Helper class to adapt between Protocol and StreamReader.

    (This is a helper class instead of making StreamReader itself a
    Protocol subclass, because the StreamReader has other potential
    uses, and to prevent the user of the StreamReader to accidentally
    call inappropriate methods of the protocol.)
    Ncsnt�j|d�|dk	r,t�|�|_|j|_nd|_|dk	r@||_d|_d|_d|_	||_
d|_|j�
�|_dS)NrF)�superr9�weakref�ref�_stream_reader_wr�_source_traceback�_strong_reader�_reject_connection�_stream_writer�
_transport�_client_connected_cb�	_over_sslr4rI�_closed)r8Z
stream_readerr/r��	__class__rrr9�s
zStreamReaderProtocol.__init__cCs|jdkrdS|��Sr)rVr<rrr�_stream_reader�s
z#StreamReaderProtocol._stream_readercCs�|jr6ddi}|jr|j|d<|j�|�|��dS||_|j}|dk	rT|�|�|�d�dk	|_	|j
dk	r�t||||j�|_|�
||j�}t
�|�r�|j�|�d|_dS)N�messagezpAn open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.Zsource_tracebackZ
sslcontext)rYrWr4Zcall_exception_handler�abortr[ra�
set_transport�get_extra_infor]r\rrZr
ZiscoroutineZcreate_taskrX)r8r(�contextr'�resrrr�connection_made�s2�


��
z$StreamReaderProtocol.connection_madecsx|j}|dk	r*|dkr |��n
|�|�|j��sV|dkrJ|j�d�n|j�|�t��|�d|_d|_	d|_
dSr)ra�feed_eofrDr^r>r?rSrGrVrZr[)r8rFr'r_rrrG
s


z$StreamReaderProtocol.connection_lostcCs|j}|dk	r|�|�dSr)ra�	feed_data)r8�datar'rrr�
data_receivedsz"StreamReaderProtocol.data_receivedcCs$|j}|dk	r|��|jr dSdS)NFT)rarir])r8r'rrr�eof_received sz!StreamReaderProtocol.eof_receivedcCs|jSr)r^rLrrrrN+sz&StreamReaderProtocol._get_close_waitercCs"|j}|��r|��s|��dSr)r^r>�	cancelled�	exception)r8�closedrrr�__del__.szStreamReaderProtocol.__del__)NN)rOrPrQrRrWr9�propertyrarhrGrlrmrNrq�
__classcell__rrr_rr�s
rc@sveZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zddd�Zdd�ZdS)ra'Wraps a Transport.

    This exposes write(), writelines(), [can_]write_eof(),
    get_extra_info() and close().  It adds drain() which returns an
    optional Future on which you can wait for flow control.  It also
    adds a transport property which references the Transport
    directly.
    cCs4||_||_||_||_|j��|_|j�d�dSr)r[�	_protocol�_readerr4rIZ
_complete_futr?)r8r(rr'rrrrr9@szStreamWriter.__init__cCs@|jjd|j��g}|jdk	r0|�d|j���d�d�|��S)N�
transport=zreader=�<{}>� )r`rOr[ru�append�format�join�r8�inforrr�__repr__Js
zStreamWriter.__repr__cCs|jSr�r[r<rrrr(PszStreamWriter.transportcCs|j�|�dSr)r[�write�r8rkrrrr�TszStreamWriter.writecCs|j�|�dSr)r[�
writelinesr�rrrr�WszStreamWriter.writelinescCs
|j��Sr)r[�	write_eofr<rrrr�ZszStreamWriter.write_eofcCs
|j��Sr)r[�
can_write_eofr<rrrr�]szStreamWriter.can_write_eofcCs
|j��Sr)r[�closer<rrrr�`szStreamWriter.closecCs
|j��Sr)r[�
is_closingr<rrrr�cszStreamWriter.is_closingc�s|j�|�IdHdSr)rtrNr<rrr�wait_closedfszStreamWriter.wait_closedNcCs|j�||�Sr)r[re)r8�name�defaultrrrreiszStreamWriter.get_extra_infoc�sL|jdk	r |j��}|dk	r |�|j��r8td�IdH|j��IdHdS)zyFlush the write buffer.

        The intended use is to write

          w.write(data)
          await w.drain()
        Nr)ruror[r�rrtrJ)r8rFrrr�drainls



zStreamWriter.drain)N)rOrPrQrRr9r~rrr(r�r�r�r�r�r�r�rer�rrrrr6s	


rc@s�eZdZdZedfdd�Zdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd&dd�Zd'dd�Zd d!�Zd"d#�Zd$d%�ZdS)(rNcCsv|dkrtd��||_|dkr*t��|_n||_t�|_d|_d|_d|_	d|_
d|_|j��rrt
�t�d��|_dS)NrzLimit cannot be <= 0Fr	)�
ValueError�_limitrr r4�	bytearray�_buffer�_eof�_waiter�
_exceptionr[r5r:r
�
extract_stack�sys�	_getframerW)r8rrrrrr9�s 
�zStreamReader.__init__cCs�dg}|jr"|�t|j��d��|jr2|�d�|jtkrN|�d|j���|jrf|�d|j���|jr~|�d|j���|jr�|�d|j���|j	r�|�d�d	�
d
�|��S)Nrz bytes�eofzlimit=zwaiter=z
exception=rvZpausedrwrx)r�ry�lenr�r��_DEFAULT_LIMITr�r�r[r5rzr{r|rrrr~�s 


zStreamReader.__repr__cCs|jSr)r�r<rrrro�szStreamReader.exceptioncCs0||_|j}|dk	r,d|_|��s,|�|�dSr)r�r�rnrDrErrrrD�szStreamReader.set_exceptioncCs*|j}|dk	r&d|_|��s&|�d�dS)z1Wakeup read*() functions waiting for data or EOF.N)r�rnr?r@rrr�_wakeup_waiter�s
zStreamReader._wakeup_waitercCs
||_dSrr)r8r(rrrrd�szStreamReader.set_transportcCs*|jr&t|j�|jkr&d|_|j��dSr3)r5r�r�r�r[�resume_readingr<rrr�_maybe_resume_transport�sz$StreamReader._maybe_resume_transportcCsd|_|��dSrC)r�r�r<rrrri�szStreamReader.feed_eofcCs|jo|jS)z=Return True if the buffer is empty and 'feed_eof' was called.)r�r�r<rrr�at_eof�szStreamReader.at_eofcCst|sdS|j�|�|��|jdk	rp|jspt|j�d|jkrpz|j��Wntk
rhd|_YnXd|_dS)NrT)	r��extendr�r[r5r�r�Z
pause_readingrKr�rrrrj�s
��zStreamReader.feed_datac�sX|jdk	rt|�d���|jr.d|_|j��|j��|_z|jIdHW5d|_XdS)zpWait until feed_data() or feed_eof() is called.

        If stream was paused, automatically resume it.
        NzF() called while another coroutine is already waiting for incoming dataF)r��RuntimeErrorr5r[r�r4rI)r8Z	func_namerrr�_wait_for_data�s	
�
zStreamReader._wait_for_datac
�s�d}t|�}z|�|�IdH}Wn�tjk
rN}z|jWY�Sd}~XYnhtjk
r�}zH|j�||j�r�|jd|j|�=n
|j�	�|�
�t|jd��W5d}~XYnX|S)a�Read chunk of data from the stream until newline (b'
') is found.

        On success, return chunk that ends with newline. If only partial
        line can be read due to EOF, return incomplete line without
        terminating newline. When EOF was reached while no bytes read, empty
        bytes object is returned.

        If limit is reached, ValueError will be raised. In that case, if
        newline was found, complete line including newline will be removed
        from internal buffer. Else, internal buffer will be cleared. Limit is
        compared against part of the line without newline.

        If stream was paused, this function will automatically resume it if
        needed.
        �
Nr)
r��	readuntilr�IncompleteReadError�partial�LimitOverrunErrorr��
startswith�consumed�clearr�r��args)r8�sep�seplen�line�errr�readline	s
 zStreamReader.readliner�c�s�t|�}|dkrtd��|jdk	r(|j�d}t|j�}|||kr||j�||�}|dkrZq�|d|}||jkr|t�d|��|jr�t	|j�}|j�
�t�|d��|�d�IdHq,||jkr�t�d|��|jd||�}|jd||�=|�
�t	|�S)	aVRead data from the stream until ``separator`` is found.

        On success, the data and separator will be removed from the
        internal buffer (consumed). Returned data will include the
        separator at the end.

        Configured stream limit is used to check result. Limit sets the
        maximal length of data that can be returned, not counting the
        separator.

        If an EOF occurs and the complete separator is still not found,
        an IncompleteReadError exception will be raised, and the internal
        buffer will be reset.  The IncompleteReadError.partial attribute
        may contain the separator partially.

        If the data cannot be read because of over limit, a
        LimitOverrunError exception  will be raised, and the data
        will be left in the internal buffer, so it can be read again.
        rz,Separator should be at least one-byte stringN���r	z2Separator is not found, and chunk exceed the limitr�z2Separator is found, but chunk is longer than limit)r�r�r�r��findr�rr�r��bytesr�r�r�r�)r8Z	separatorr��offsetZbuflenZisep�chunkrrrr�(s>


�


�zStreamReader.readuntilr�c�s�|jdk	r|j�|dkrdS|dkrVg}|�|j�IdH}|s@qL|�|�q(d�|�S|jsr|jsr|�d�IdHt|jd|��}|jd|�=|�	�|S)a�Read up to `n` bytes from the stream.

        If n is not provided, or set to -1, read until EOF and return all read
        bytes. If the EOF was received and the internal buffer is empty, return
        an empty bytes object.

        If n is zero, return empty bytes object immediately.

        If n is positive, this function try to read `n` bytes, and may return
        less or equal bytes than requested, but at least one byte. If EOF was
        received before any byte is read, this function returns empty byte
        object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        Nrr�read)
r�r�r�ryr{r�r�r�r�r�)r8�nZblocks�blockrkrrrr��s"

zStreamReader.readc�s�|dkrtd��|jdk	r |j�|dkr,dSt|j�|krr|jr`t|j�}|j��t�||��|�	d�IdHq,t|j�|kr�t|j�}|j��nt|jd|��}|jd|�=|�
�|S)a�Read exactly `n` bytes.

        Raise an IncompleteReadError if EOF is reached before `n` bytes can be
        read. The IncompleteReadError.partial attribute of the exception will
        contain the partial read bytes.

        if n is zero, return empty bytes object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        rz*readexactly size can not be less than zeroNr�readexactly)r�r�r�r�r�r�r�rr�r�r�)r8r�Z
incompleterkrrrr��s&



zStreamReader.readexactlycCs|Srrr<rrr�	__aiter__�szStreamReader.__aiter__c�s|��IdH}|dkrt�|S)Nr)r��StopAsyncIteration)r8�valrrr�	__anext__�szStreamReader.__anext__)r�)r�)rOrPrQrWr�r9r~rorDr�rdr�rir�rjr�r�r�r�r�r�r�rrrrr�s$	
[
2)r)NN)NN)N)N)�__all__Zsocketr�r!rT�hasattr�r
rrr
r�logrZtasksrr�rrrrZProtocolr2rrrrrrr�<module>sF
�!�'
��DkPPK [���1N�N�&__pycache__/base_events.cpython-38.pycnu�[���U

e5d��@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZzddlZWnek
r�dZYnXddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddl m!Z!dZ"dZ#dZ$e%e	d�Z&dZ'e(�Z)dd�Z*dd�Z+dd�Z,d+dd�Z-d,dd�Z.dd �Z/e%e	d!��r�d"d#�Z0nd$d#�Z0Gd%d&�d&ej1�Z2Gd'd(�d(ej3�Z4Gd)d*�d*ej5�Z6dS)-a�Base implementation of event loop.

The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.

Whenever a public API takes a callback, subsequent positional
arguments will be passed to the callback if/when it is called.  This
avoids the proliferation of trivial lambdas implementing closures.
Keyword arguments for the callback are not supported; this is a
conscious design decision, leaving the door open for keyword arguments
to modify the meaning of the API call itself.
�N�)�	constants)�
coroutines)�events)�
exceptions)�futures)�	protocols)�sslproto)�	staggered)�tasks)�
transports)�trsock)�logger)�
BaseEventLoop�dg�?�AF_INET6i�QcCs0|j}tt|dd�tj�r$t|j�St|�SdS)N�__self__)Z	_callback�
isinstance�getattrr�Task�reprr�str)�handle�cb�r�+/usr/lib64/python3.8/asyncio/base_events.py�_format_handleJs
rcCs(|tjkrdS|tjkrdSt|�SdS)Nz<pipe>z<stdout>)�
subprocess�PIPE�STDOUTr)�fdrrr�_format_pipeSs


r!cCsLttd�std��n4z|�tjtjd�Wntk
rFtd��YnXdS)N�SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)�hasattr�socket�
ValueError�
setsockopt�
SOL_SOCKETr"�OSError��sockrrr�_set_reuseport\s

r+c		Cs�ttd�sdS|dtjtjhks(|dkr,dS|tjkr>tj}n|tjkrPtj}ndS|dkrbd}nXt|t�rz|dkrzd}n@t|t�r�|dkr�d}n(zt	|�}Wnt
tfk
r�YdSX|tjkr�tj
g}tr�|�tj�n|g}t|t�r�|�d�}d|k�rdS|D]t}zVt�||�t�rJ|tjk�rJ|||d||||ffWS|||d||ffWSWntk
�rzYnX�q
dS)N�	inet_ptonr��Zidna�%)r#r$�IPPROTO_TCPZIPPROTO_UDP�SOCK_STREAM�
SOCK_DGRAMr�bytesr�int�	TypeErrorr%�	AF_UNSPEC�AF_INET�	_HAS_IPv6�appendr�decoder,r()	�host�port�family�type�protoZflowinfoZscopeidZafs�afrrr�_ipaddr_infogsN
�






rAcCs�t��}|D]*}|d}||kr(g||<||�|�qt|���}g}|dkr||�|dd|d��|dd|d�=|�dd�tj�tj	|��D��|S)z-Interleave list of addrinfo tuples by family.rrNcss|]}|dk	r|VqdS�Nr)�.0�arrr�	<genexpr>�s�z(_interleave_addrinfos.<locals>.<genexpr>)
�collections�OrderedDictr9�list�values�extend�	itertools�chain�
from_iterable�zip_longest)Z	addrinfosZfirst_address_family_countZaddrinfos_by_family�addrr=Zaddrinfos_listsZ	reorderedrrr�_interleave_addrinfos�s"
��rPcCs4|��s"|��}t|ttf�r"dSt�|���dSrB)�	cancelled�	exceptionr�
SystemExit�KeyboardInterruptrZ	_get_loop�stop)�fut�excrrr�_run_until_complete_cb�s
rX�TCP_NODELAYcCs@|jtjtjhkr<|jtjkr<|jtjkr<|�tjtj	d�dS�Nr)
r=r$r7rr>r1r?r0r&rYr)rrr�_set_nodelay�s
�
�r[cCsdSrBrr)rrrr[�sc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)�_SendfileFallbackProtocolcCsht|tj�std��||_|��|_|��|_|j	|_
|��|�|�|j
r^|jj
��|_nd|_dS)Nz.transport should be _FlowControlMixin instance)rrZ_FlowControlMixinr5�
_transportZget_protocol�_protoZ
is_reading�_should_resume_readingZ_protocol_paused�_should_resume_writing�
pause_reading�set_protocol�_loop�
create_future�_write_ready_fut)�self�transprrr�__init__�s


z"_SendfileFallbackProtocol.__init__c�s2|j��rtd��|j}|dkr$dS|IdHdS)NzConnection closed by peer)r]�
is_closing�ConnectionErrorre)rfrVrrr�drain�s
z_SendfileFallbackProtocol.draincCstd��dS)Nz?Invalid state: connection should have been established already.��RuntimeError)rf�	transportrrr�connection_made�sz)_SendfileFallbackProtocol.connection_madecCs@|jdk	r0|dkr$|j�td��n|j�|�|j�|�dS)NzConnection is closed by peer)reZ
set_exceptionrjr^�connection_lost)rfrWrrrrp�s
�z)_SendfileFallbackProtocol.connection_lostcCs |jdk	rdS|jj��|_dSrB)rer]rcrd�rfrrr�
pause_writing�s
z'_SendfileFallbackProtocol.pause_writingcCs$|jdkrdS|j�d�d|_dS)NF)re�
set_resultrqrrr�resume_writing�s
z(_SendfileFallbackProtocol.resume_writingcCstd��dS�Nz'Invalid state: reading should be pausedrl)rf�datarrr�
data_received�sz'_SendfileFallbackProtocol.data_receivedcCstd��dSrurlrqrrr�eof_receivedsz&_SendfileFallbackProtocol.eof_receivedc�sF|j�|j�|jr|j��|jdk	r2|j��|jrB|j��dSrB)	r]rbr^r_�resume_readingre�cancelr`rtrqrrr�restores


z!_SendfileFallbackProtocol.restoreN)�__name__�
__module__�__qualname__rhrkrorprrrtrwrxr{rrrrr\�sr\c@sxeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
edd��Zdd�Z
dd�Zdd�Zdd�ZdS)�ServercCs@||_||_d|_g|_||_||_||_||_d|_d|_	dS)NrF)
rc�_sockets�
_active_count�_waiters�_protocol_factory�_backlog�_ssl_context�_ssl_handshake_timeout�_serving�_serving_forever_fut)rf�loop�sockets�protocol_factoryZssl_context�backlog�ssl_handshake_timeoutrrrrhszServer.__init__cCsd|jj�d|j�d�S)N�<z	 sockets=�>)�	__class__r|r�rqrrr�__repr__ szServer.__repr__cCs |jdk	st�|jd7_dSrZ)r��AssertionErrorr�rqrrr�_attach#szServer._attachcCs<|jdkst�|jd8_|jdkr8|jdkr8|��dS)Nrr)r�r�r��_wakeuprqrrr�_detach'szServer._detachcCs,|j}d|_|D]}|��s|�|�qdSrB)r��doners)rf�waiters�waiterrrrr�-s
zServer._wakeupc	CsJ|jr
dSd|_|jD].}|�|j�|j�|j||j||j|j�qdS)NT)	r�r�Zlistenr�rc�_start_servingr�r�r�)rfr*rrrr�4s
�zServer._start_servingcCs|jSrB)rcrqrrr�get_loop>szServer.get_loopcCs|jSrB)r�rqrrr�
is_servingAszServer.is_servingcCs"|jdkrdStdd�|jD��S)Nrcss|]}t�|�VqdSrB)r
ZTransportSocket)rC�srrrrEHsz!Server.sockets.<locals>.<genexpr>)r��tuplerqrrrr�Ds
zServer.socketscCsn|j}|dkrdSd|_|D]}|j�|�qd|_|jdk	rX|j��sX|j��d|_|jdkrj|��dS)NFr)	r�rcZ
_stop_servingr�r�r�rzr�r�)rfr�r*rrr�closeJs
�

zServer.closec�s"|��tjd|jd�IdHdS)Nr�r�)r�r�sleeprcrqrrr�
start_serving]szServer.start_servingc	�s�|jdk	rtd|�d���|jdkr4td|�d���|��|j��|_zLz|jIdHWn6tjk
r�z|��|�	�IdHW5�XYnXW5d|_XdS)Nzserver z, is already being awaited on serve_forever()z
 is closed)
r�rmr�r�rcrdrZCancelledErrorr��wait_closedrqrrr�
serve_forevercs 

�
zServer.serve_foreverc�s<|jdks|jdkrdS|j��}|j�|�|IdHdSrB)r�r�rcrdr9)rfr�rrrr�xs

zServer.wait_closedN)r|r}r~rhr�r�r�r�r�r�r��propertyr�r�r�r�r�rrrrrs


rc@sPeZdZdd�Zdd�Zdd�Zdd�d	d
�Zdd�Zd
d�Zd�ddd�dd�Z	d�ddddddd�dd�Z
d�dd�Zd�dd�Zd�dd�Z
d�dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zejfd7d8�Zd9d:�Zd;d<�Zdd=�d>d?�Z dd=�d@dA�Z!dd=�dBdC�Z"dDdE�Z#dFdG�Z$dHdI�Z%dd=�dJdK�Z&dLdM�Z'dNdO�Z(dPdQ�Z)dRdRdRdRdS�dTdU�Z*d�dVdW�Z+d�ddX�dYdZ�Z,d[d\�Z-d]d^�Z.d_d`�Z/d�dadb�Z0d�ddRdRdRdddddddc�
ddde�Z1d�dfdg�Z2d�ddX�dhdi�Z3djdk�Z4dldm�Z5ddddn�dodp�Z6d�dRdRdRe7ddddq�drds�Z8dRe9j:dRdRdS�dtdu�Z;dvdw�Z<d�e9j=e9j>ddxddddddy�	dzd{�Z?ddd|�d}d~�Z@dd��ZAd�d��ZBd�d��ZCeDjEeDjEeDjEdddRdddd��	d�d��ZFeDjEeDjEeDjEdddRdddd��	d�d��ZGd�d��ZHd�d��ZId�d��ZJd�d��ZKd�d��ZLd�d��ZMd�d��ZNd�d��ZOd�d��ZPd�d��ZQd�d��ZRdS)�rcCs�d|_d|_d|_t��|_g|_d|_d|_d|_	t
�d�j|_
d|_|�t���d|_d|_d|_d|_d|_t��|_d|_dS)NrF�	monotonicg�������?)�_timer_cancelled_count�_closed�	_stoppingrF�deque�_ready�
_scheduled�_default_executorZ
_internal_fds�
_thread_id�time�get_clock_infoZ
resolution�_clock_resolution�_exception_handler�	set_debugrZ_is_debug_mode�slow_callback_duration�_current_handle�
_task_factory�"_coroutine_origin_tracking_enabled�&_coroutine_origin_tracking_saved_depth�weakrefZWeakSet�
_asyncgens�_asyncgens_shutdown_calledrqrrrrh�s$

zBaseEventLoop.__init__c	Cs.d|jj�d|���d|���d|���d�	S)Nr�z	 running=z closed=z debug=r�)r�r|�
is_running�	is_closed�	get_debugrqrrrr��s,�zBaseEventLoop.__repr__cCstj|d�S)z,Create a Future object attached to the loop.r�)rZFuturerqrrrrd�szBaseEventLoop.create_futureN)�namecCsN|��|jdkr2tj|||d�}|jrJ|jd=n|�||�}t�||�|S)zDSchedule a coroutine object.

        Return a task object.
        N)r�r����)�
_check_closedr�rr�_source_tracebackZ_set_task_name)rf�coror�Ztaskrrr�create_task�s

zBaseEventLoop.create_taskcCs"|dk	rt|�std��||_dS)awSet a task factory that will be used by loop.create_task().

        If factory is None the default task factory will be set.

        If factory is a callable, it should have a signature matching
        '(loop, coro)', where 'loop' will be a reference to the active
        event loop, 'coro' will be a coroutine object.  The callable
        must return a Future.
        Nz'task factory must be a callable or None)�callabler5r�)rf�factoryrrr�set_task_factory�s
zBaseEventLoop.set_task_factorycCs|jS)z<Return a task factory, or None if the default one is in use.)r�rqrrr�get_task_factory�szBaseEventLoop.get_task_factory)�extra�servercCst�dS)zCreate socket transport.N��NotImplementedError)rfr*�protocolr�r�r�rrr�_make_socket_transport�sz$BaseEventLoop._make_socket_transportFT)�server_side�server_hostnamer�r�r��call_connection_madecCst�dS)zCreate SSL transport.Nr�)rfZrawsockr��
sslcontextr�r�r�r�r�r�r�rrr�_make_ssl_transport�sz!BaseEventLoop._make_ssl_transportcCst�dS)zCreate datagram transport.Nr�)rfr*r��addressr�r�rrr�_make_datagram_transport�sz&BaseEventLoop._make_datagram_transportcCst�dS)zCreate read pipe transport.Nr��rf�piper�r�r�rrr�_make_read_pipe_transport�sz'BaseEventLoop._make_read_pipe_transportcCst�dS)zCreate write pipe transport.Nr�r�rrr�_make_write_pipe_transport�sz(BaseEventLoop._make_write_pipe_transportc	
�st�dS)zCreate subprocess transport.Nr�)
rfr��args�shell�stdin�stdout�stderr�bufsizer��kwargsrrr�_make_subprocess_transport�sz(BaseEventLoop._make_subprocess_transportcCst�dS)z�Write a byte to self-pipe, to wake up the event loop.

        This may be called from a different thread.

        The subclass is responsible for implementing the self-pipe.
        Nr�rqrrr�_write_to_self�szBaseEventLoop._write_to_selfcCst�dS)zProcess selector events.Nr�)rf�
event_listrrr�_process_events�szBaseEventLoop._process_eventscCs|jrtd��dS)NzEvent loop is closed)r�rmrqrrrr��szBaseEventLoop._check_closedcCs*|j�|�|��s&|�|j|���dSrB)r��discardr��call_soon_threadsafer��aclose�rf�agenrrr�_asyncgen_finalizer_hook�sz&BaseEventLoop._asyncgen_finalizer_hookcCs.|jrtjd|�d�t|d�|j�|�dS)Nzasynchronous generator z3 was scheduled after loop.shutdown_asyncgens() call��source)r��warnings�warn�ResourceWarningr��addr�rrr�_asyncgen_firstiter_hooks
�z&BaseEventLoop._asyncgen_firstiter_hookc�s�d|_t|j�sdSt|j�}|j��tjdd�|D�d|d��IdH}t||�D]*\}}t|t	�rT|�
d|��||d��qTdS)z,Shutdown all active asynchronous generators.TNcSsg|]}|���qSr)r�)rCZagrrr�
<listcomp>sz4BaseEventLoop.shutdown_asyncgens.<locals>.<listcomp>)Zreturn_exceptionsr�z;an error occurred during closing of asynchronous generator )�messagerRZasyncgen)r��lenr�rH�clearr�gather�zipr�	Exception�call_exception_handler)rfZ
closing_agensZresults�resultr�rrr�shutdown_asyncgenss"


�
�z BaseEventLoop.shutdown_asyncgenscCs(|��rtd��t��dk	r$td��dS)Nz"This event loop is already runningz7Cannot run the event loop while another loop is running)r�rmrZ_get_running_looprqrrr�_check_running&s�zBaseEventLoop._check_runningc	Cs�|��|��|�|j�t��|_t��}tj	|j
|jd�z t
�|�|��|jrLq^qLW5d|_d|_t
�d�|�d�tj	|�XdS)zRun until stop() is called.)�	firstiter�	finalizerFN)r�r��_set_coroutine_origin_tracking�_debug�	threading�	get_identr��sys�get_asyncgen_hooks�set_asyncgen_hooksr�r�r�rZ_set_running_loop�	_run_once)rfZold_agen_hooksrrr�run_forever-s$
�


zBaseEventLoop.run_foreverc	Cs�|��|��t�|�}tj||d�}|r4d|_|�t�z<z|�
�Wn*|rp|��rp|��sp|�
��YnXW5|�	t�X|��s�td��|��S)a\Run until the Future is done.

        If the argument is a coroutine, it is wrapped in a Task.

        WARNING: It would be disastrous to call run_until_complete()
        with the same coroutine twice -- it would wrap it in two
        different Tasks and that can't be good.

        Return the Future's result, or raise its exception.
        r�Fz+Event loop stopped before Future completed.)r�r�rZisfuturerZ
ensure_futureZ_log_destroy_pendingZadd_done_callbackrXZremove_done_callbackrr�rQrRrmr�)rfZfutureZnew_taskrrr�run_until_completeDs"
z BaseEventLoop.run_until_completecCs
d|_dS)z�Stop running the event loop.

        Every callback already scheduled will still run.  This simply informs
        run_forever to stop looping after a complete iteration.
        TN)r�rqrrrrUjszBaseEventLoop.stopcCsj|��rtd��|jrdS|jr,t�d|�d|_|j��|j��|j	}|dk	rfd|_	|j
dd�dS)z�Close the event loop.

        This clears the queues and shuts down the executor,
        but does not wait for the executor to finish.

        The event loop must not be running.
        z!Cannot close a running event loopNzClose %rTF)�wait)r�rmr�r�r�debugr�r�r�r�Zshutdown�rf�executorrrrr�rs

zBaseEventLoop.closecCs|jS)z*Returns True if the event loop was closed.)r�rqrrrr��szBaseEventLoop.is_closedcCs0|��s,|d|��t|d�|��s,|��dS)Nzunclosed event loop r�)r�r�r�r�)rfZ_warnrrr�__del__�szBaseEventLoop.__del__cCs
|jdk	S)z*Returns True if the event loop is running.N)r�rqrrrr��szBaseEventLoop.is_runningcCst��S)z�Return the time according to the event loop's clock.

        This is a float expressed in seconds since an epoch, but the
        epoch, precision, accuracy and drift are unspecified and may
        differ per event loop.
        )r�r�rqrrrr��szBaseEventLoop.time)�contextcGs2|j|��||f|�d|i�}|jr.|jd=|S)a8Arrange for a callback to be called at a given time.

        Return a Handle: an opaque object with a cancel() method that
        can be used to cancel the call.

        The delay can be an int or float, expressed in seconds.  It is
        always relative to the current time.

        Each callback will be called exactly once.  If two callbacks
        are scheduled for exactly the same time, it undefined which
        will be called first.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        r
r�)�call_atr�r�)rfZdelay�callbackr
r��timerrrr�
call_later�s�zBaseEventLoop.call_latercGsZ|��|jr"|��|�|d�t�|||||�}|jrB|jd=t�|j	|�d|_	|S)z|Like call_later(), but uses an absolute time.

        Absolute time corresponds to the event loop's time() method.
        rr�T)
r�r��
_check_thread�_check_callbackr�TimerHandler��heapq�heappushr�)rf�whenrr
r�rrrrr�szBaseEventLoop.call_atcGsB|��|jr"|��|�|d�|�|||�}|jr>|jd=|S)aTArrange for a callback to be called as soon as possible.

        This operates as a FIFO queue: callbacks are called in the
        order in which they are registered.  Each callback will be
        called exactly once.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        �	call_soonr�)r�r�rr�
_call_soonr��rfrr
r�rrrrr�s
zBaseEventLoop.call_sooncCsDt�|�st�|�r$td|�d���t|�s@td|�d|����dS)Nzcoroutines cannot be used with z()z"a callable object was expected by z(), got )rZiscoroutineZiscoroutinefunctionr5r�)rfr�methodrrrr�s
�
��zBaseEventLoop._check_callbackcCs.t�||||�}|jr|jd=|j�|�|S)Nr�)r�Handler�r�r9)rfrr�r
rrrrr�s
zBaseEventLoop._call_sooncCs,|jdkrdSt��}||jkr(td��dS)aoCheck that the current thread is the thread running the event loop.

        Non-thread-safe methods of this class make this assumption and will
        likely behave incorrectly when the assumption is violated.

        Should only be called when (self._debug == True).  The caller is
        responsible for checking this condition for performance reasons.
        NzMNon-thread-safe operation invoked on an event loop other than the current one)r�rrrm)rfZ	thread_idrrrr�s	

�zBaseEventLoop._check_threadcGsB|��|jr|�|d�|�|||�}|jr6|jd=|��|S)z"Like call_soon(), but thread-safe.r�r�)r�r�rrr�r�rrrrr��sz"BaseEventLoop.call_soon_threadsafecGsZ|��|jr|�|d�|dkr@|j}|dkr@tj��}||_tj|j|f|��|d�S)N�run_in_executorr�)	r�r�rr��
concurrentr�ThreadPoolExecutorZwrap_futureZsubmit)rfr�funcr�rrrrs
�zBaseEventLoop.run_in_executorcCs&t|tjj�st�dtd�||_dS)Nz{Using the default executor that is not an instance of ThreadPoolExecutor is deprecated and will be prohibited in Python 3.9�)rrrrr�r��DeprecationWarningr�r
rrr�set_default_executors�z"BaseEventLoop.set_default_executorcCs�|�d|��g}|r$|�d|���|r8|�d|���|rL|�d|���|r`|�d|���d�|�}t�d|�|��}t�||||||�}	|��|}
d|�d	|
d
d�d|	��}|
|jkr�t�|�n
t�|�|	S)
N�:zfamily=ztype=zproto=zflags=�, zGet address info %szGetting address info z took g@�@z.3fzms: )	r9�joinrr	r�r$�getaddrinfor��info)rfr;r<r=r>r?�flags�msg�t0�addrinfo�dtrrr�_getaddrinfo_debugs&


z BaseEventLoop._getaddrinfo_debugr�r=r>r?r)c
�s2|jr|j}ntj}|�d|||||||�IdHSrB)r�r.r$r'r)rfr;r<r=r>r?r)Zgetaddr_funcrrrr'2s�zBaseEventLoop.getaddrinfoc�s|�dtj||�IdHSrB)rr$�getnameinfo)rfZsockaddrr)rrrr0<s�zBaseEventLoop.getnameinfo)�fallbackc
�s�|jr|��dkrtd��|�||||�z|�||||�IdHWStjk
rl}z
|s\�W5d}~XYnX|�||||�IdHS)Nrzthe socket must be non-blocking)r�Z
gettimeoutr%�_check_sendfile_params�_sock_sendfile_nativer�SendfileNotAvailableError�_sock_sendfile_fallback)rfr*�file�offset�countr1rWrrr�
sock_sendfile@s��zBaseEventLoop.sock_sendfilec�st�d|�d���dS)Nz-syscall sendfile is not available for socket z and file {file!r} combination�rr4�rfr*r6r7r8rrrr3Ns
�z#BaseEventLoop._sock_sendfile_nativec

�s�|r|�|�|rt|tj�ntj}t|�}d}zt|rNt|||�}|dkrNq�t|�d|�}|�d|j|�IdH}	|	szq�|�	||d|	��IdH||	7}q2|W�S|dkr�t|d�r�|�||�XdS)Nr�seek)
r<�minrZ!SENDFILE_FALLBACK_READBUFFER_SIZE�	bytearrayr#�
memoryviewr�readintoZsock_sendall)
rfr*r6r7r8�	blocksize�buf�
total_sent�view�readrrrr5Us,
��
z%BaseEventLoop._sock_sendfile_fallbackcCs�dt|dd�krtd��|jtjks,td��|dk	rbt|t�sLtd�|���|dkrbtd�|���t|t�sztd�|���|dkr�td�|���dS)N�b�modez$file should be opened in binary modez+only SOCK_STREAM type sockets are supportedz+count must be a positive integer (got {!r})rz0offset must be a non-negative integer (got {!r}))	rr%r>r$r1rr4r5�formatr;rrrr2os2
��
����z$BaseEventLoop._check_sendfile_paramsc�s@g}|�|�|\}}}}}	d}
z�tj|||d�}
|
�d�|dk	r�|D]r\}}}}}z|
�|�Wq�WqHtk
r�}z0d|�d|j����}
t|j|
�}|�|�W5d}~XYqHXqH|���|�	|
|	�IdH|
WStk
�r}z"|�|�|
dk	�r
|
�
��W5d}~XYn |
dk	�r4|
�
��YnXdS)z$Create, bind and connect one socket.N�r=r>r?Fz*error while attempting to bind on address �: )r9r$�setblocking�bindr(�strerror�lower�errno�pop�sock_connectr�)rfrZ	addr_infoZlocal_addr_infosZ
my_exceptionsr=Ztype_r?�_r�r*ZladdrrWr*rrr�
_connect_sock�s:



�


zBaseEventLoop._connect_sock)
�sslr=r?r)r*�
local_addrr�r��happy_eyeballs_delay�
interleavec
	�sl|
dk	r|std��|
dkr0|r0|s,td��|}
|dk	rD|sDtd��|dk	rX|
dkrXd}
|dk	sj|dk	�r�|dk	rztd���j||f|tj||�d�IdH}|s�td��|	dk	r܈j|	|tj||�d�IdH��s�td��nd�|
r�t||
�}g�|dk�rH|D]D}z ���|��IdH}W�qvWntk
�r@Y�qYnX�qn.tj���fd	d
�|D�|�d�IdH\}}}|dk�r dd
��D��t	��dk�r��d�nJt
�d��t�fdd
��D���r҈d�td�d�
dd
��D�����n.|dk�rtd��|jtjk�r td|�����j||||
|d�IdH\}}�j�rd|�d�}t�d|||||�||fS)a�Connect to a TCP server.

        Create a streaming transport connection to a given Internet host and
        port: socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_STREAM. protocol_factory must be
        a callable returning a protocol instance.

        This method is a coroutine which will try to establish the connection
        in the background.  When successful, the coroutine returns a
        (transport, protocol) pair.
        Nz+server_hostname is only meaningful with sslz:You must set server_hostname when using ssl without a host�1ssl_handshake_timeout is only meaningful with sslr�8host/port and sock can not be specified at the same time�r=r>r?r)r��!getaddrinfo() returned empty listc3s |]}t��j�|��VqdSrB)�	functools�partialrS)rCr,)r�laddr_infosrfrrrE�s��z2BaseEventLoop.create_connection.<locals>.<genexpr>r�cSsg|]}|D]}|�qqSrr)rC�subrWrrrr��sz3BaseEventLoop.create_connection.<locals>.<listcomp>rc3s|]}t|��kVqdSrB�r�rCrW)�modelrrrEszMultiple exceptions: {}r%css|]}t|�VqdSrBr`rarrrrE
sz5host and port was not specified and no sock specified�"A Stream Socket was expected, got )r�r$z%r connected to %s:%r: (%r, %r))r%�_ensure_resolvedr$r1r(rPrSr
Zstaggered_racer�r�allrHr&r>�_create_connection_transportr��get_extra_inforr	)rfr�r;r<rTr=r?r)r*rUr�r�rVrW�infosr,rRrnr�r)rr^rbrfr�create_connection�s�����


�
��

�
���
�zBaseEventLoop.create_connectionc	�s�|�d�|�}|��}|rHt|t�r*dn|}	|j|||	||||d�}
n|�|||�}
z|IdHWn|
���YnX|
|fS)NF�r�r�r�)rKrdr�boolr�r�r�)rfr*r�rTr�r�r�r�r�r�rnrrrrf%s*
�z*BaseEventLoop._create_connection_transportc
�s�|��rtd��t|dtjj�}|tjjkr:td|����|tjjkr�z|�||||�IdHWStj	k
r�}z
|sx�W5d}~XYnX|s�td|����|�
||||�IdHS)a�Send a file to transport.

        Return the total number of bytes which were sent.

        The method uses high-performance os.sendfile if available.

        file must be a regular file object opened in binary mode.

        offset tells from where to start reading the file. If specified,
        count is the total number of bytes to transmit as opposed to
        sending the file until EOF is reached. File position is updated on
        return or also in case of error in which case file.tell()
        can be used to figure out the number of bytes
        which were sent.

        fallback set to True makes asyncio to manually read and send
        the file when the platform does not support the sendfile syscall
        (e.g. Windows or SSL socket on Unix).

        Raise SendfileNotAvailableError if the system does not support
        sendfile syscall and fallback is False.
        zTransport is closingZ_sendfile_compatiblez(sendfile is not supported for transport NzHfallback is disabled and native sendfile is not supported for transport )rirmrrZ
_SendfileModeZUNSUPPORTEDZ
TRY_NATIVE�_sendfile_nativerr4�_sendfile_fallback)rfrnr6r7r8r1rGrWrrr�sendfile?s4�����zBaseEventLoop.sendfilec�st�d��dS)Nz!sendfile syscall is not supportedr:)rfrgr6r7r8rrrrlns�zBaseEventLoop._sendfile_nativec
�s�|r|�|�|rt|d�nd}t|�}d}t|�}z�|rXt|||�}|dkrX|W�bSt|�d|�}	|�d|j|	�IdH}
|
s�|W�0S|�	�IdH|�
|	d|
��||
7}q6W5|dkr�t|d�r�|�||�|��IdHXdS)Ni@rr<)r<r=r>r\r#r{r?rr@rk�write)rfrgr6r7r8rArBrCr?rDrErrrrmrs*
z BaseEventLoop._sendfile_fallbackrjc
�s�tdkrtd��t|tj�s*td|����t|dd�sFtd|�d���|��}tj|||||||dd�}|�	�|�
|�|�|j|�}	|�|j
�}
z|IdHWn.tk
r�|��|	��|
���YnX|jS)	zzUpgrade transport to TLS.

        Return a new transport that *protocol* should start using
        immediately.
        Nz"Python ssl module is not availablez@sslcontext is expected to be an instance of ssl.SSLContext, got Z_start_tls_compatibleFz
transport z  is not supported by start_tls())r�r�)rTrmrZ
SSLContextr5rrdr	ZSSLProtocolrarbrrory�
BaseExceptionr�rzZ_app_transport)rfrnr�r�r�r�r�r�Zssl_protocolZ
conmade_cbZ	resume_cbrrr�	start_tls�sB	�
��
zBaseEventLoop.start_tls)r=r?r)�
reuse_address�
reuse_port�allow_broadcastr*c �s|
dk	r�|
jtjkr"td|
�����s>�s>|s>|s>|s>|s>|	r~t��||||||	d�}d�dd�|��D��}td|�d���|
�d	�d}
�n�s��s�|d
kr�td��||fdff}�n�ttd
��r�|tj	k�r���fD]}|dk	r�t
|t�s�td��qڈ�rx�d
dk�rxz"t
�t�
��j��r.t���WnFtk
�rFYn2tk
�rv}zt�d�|�W5d}~XYnX||f��fff}n�i}d
�fd�ffD]�\}}|dk	�r�t
|t��r�t|�dk�s�td��|j||tj|||d�IdH}|�std��|D]:\}}}}}||f}||k�r0ddg||<||||<�q�q���fdd�|��D�}|�sjtd��g}|tk	�r�|�r�td��ntjdtdd�|D]�\\}}\}}d}
d}
zxtj|tj|d�}
|�r�t|
�|	�r�|
�tj tj!d�|
�d	���r|
�"|���r*|	�s&|�#|
|�IdH|}
Wn^tk
�rl}z |
dk	�rR|
�$�|�%|�W5d}~XYn&|
dk	�r�|
�$��YnX�q��q�|d
�|�}|�&�}|�'|
||
|�}|j(�r��r�t�)d��||�nt�*d�||�z|IdHWn|�$��YnX||fS)zCreate datagram connection.NzA UDP Socket was expected, got )rU�remote_addrr=r?r)rrrsrtr%css$|]\}}|r|�d|��VqdS)�=Nr)rC�k�vrrrrE�sz9BaseEventLoop.create_datagram_endpoint.<locals>.<genexpr>zKsocket modifier keyword arguments can not be used when sock is specified. (�)Frzunexpected address family)NN�AF_UNIXzstring is expected)r�z2Unable to check or remove stale UNIX socket %r: %rrr!z2-tuple is expectedrZr[cs8g|]0\}}�r|ddks�r,|ddks||f�qS)rNrr)rC�keyZ	addr_pair�rUrurrr��s�z:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address informationz~Passing `reuse_address=True` is no longer supported, as the usage of SO_REUSEPORT in UDP poses a significant security concern.zdThe *reuse_address* parameter has been deprecated as of 3.5.10 and is scheduled for removal in 3.11.)�
stacklevelrIz@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))+r>r$r2r%�dictr&�itemsrKr#rzrrr5�stat�S_ISSOCK�os�st_mode�remove�FileNotFoundErrorr(r�errorr�r�r�rd�_unsetr�r�r"r+r&r'ZSO_BROADCASTrLrQr�r9rdr�r�r(r	) rfr�rUrur=r?r)rrrsrtr*ZoptsZproblemsZr_addrZaddr_pairs_inforO�errZ
addr_infos�idxrhZfamrRZpror�r|rZ
local_addressZremote_addressrWr�r�rnrr}r�create_datagram_endpoint�s*�������
�

��
��
�

����




���z&BaseEventLoop.create_datagram_endpointc
�s\|dd�\}}t|||||f|dd���}	|	dk	r<|	gS|j||||||d�IdHSdS)Nr!r/)rAr')
rfr�r=r>r?r)r�r;r<r(rrrrdLs�zBaseEventLoop._ensure_resolvedc�s8|j||f|tj||d�IdH}|s4td|�d���|S)N)r=r>r)r�zgetaddrinfo(z) returned empty list)rdr$r1r()rfr;r<r=r)rhrrr�_create_server_getaddrinfoXs�z(BaseEventLoop._create_server_getaddrinfor)	r=r)r*r�rTrrrsr�r�c	�s�t|t�rtd��|dk	r*|dkr*td��|dk	s<�dk	�r"|dk	rLtd��|	dkrhtjdkoftjdk}	g}
|dkr|dg}n$t|t�s�t|t	j
j�s�|g}n|}����fdd	�|D�}tj
|d
�i�IdH}ttj�|��}d}�z|D�]}|\}}}}}zt�|||�}Wn8tjk
�rH�j�r@tjd|||d
d�Yq�YnX|
�|�|	�rl|�tjtjd
�|
�rzt|�t�r�|tjk�r�ttd��r�|�tj tj!d
�z|�"|�Wq�t#k
�r�}z t#|j$d||j%�&�f�d�W5d}~XYq�Xq�d
}W5|�s|
D]}|���qXn4|dk�r4td��|j'tj(k�rPtd|����|g}
|
D]}|�)d��qZt*�|
||||�}|�r�|�+�tj,d�d�IdH�j�r�t�-d|�|S)a1Create a TCP server.

        The host parameter can be a string, in that case the TCP server is
        bound to host and port.

        The host parameter can also be a sequence of strings and in that case
        the TCP server is bound to all hosts of the sequence. If a host
        appears multiple times (possibly indirectly e.g. when hostnames
        resolve to the same IP address), the server is only bound once to that
        host.

        Return a Server object which can be used to stop the service.

        This method is a coroutine.
        z*ssl argument must be an SSLContext or NoneNrXrY�posix�cygwinr.csg|]}�j|���d��qS))r=r))r�)rCr;�r=r)r<rfrrr��s�
�z/BaseEventLoop.create_server.<locals>.<listcomp>r�Fz: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 specifiedrcrr�z
%r is serving).rrkr5r%r�r�r�platformrrF�abc�Iterablerr��setrKrLrMr�r$r�r�r�warningr9r&r'ZSO_REUSEADDRr+r8rr#r�ZIPV6_V6ONLYrLr(rOrMrNr>r1rKrr�r�r()rfr�r;r<r=r)r*r�rTrrrsr�r�r�ZhostsZfsrhZ	completed�resr@Zsocktyper?Z	canonnameZsar�r�rr�r�
create_server`s�
��
��
�

������
�zBaseEventLoop.create_server)rTr�c�sv|jtjkrtd|����|dk	r.|s.td��|j|||dd|d�IdH\}}|jrn|�d�}t�d|||�||fS)	aHandle an accepted connection.

        This is used by servers that accept connections outside of
        asyncio but that use asyncio to handle connections.

        This method is a coroutine.  When completed, the coroutine
        returns a (transport, protocol) pair.
        rcNrXr.T)r�r�r$z%r handled: (%r, %r))	r>r$r1r%rfr�rgrr	)rfr�r*rTr�rnr�rrr�connect_accepted_socket�s$��
z%BaseEventLoop.connect_accepted_socketc�sd|�}|��}|�|||�}z|IdHWn|���YnX|jr\t�d|��||�||fS)Nz Read pipe %r connected: (%r, %r))rdr�r�r�rr	�fileno�rfr�r�r�r�rnrrr�connect_read_pipe�s�zBaseEventLoop.connect_read_pipec�sd|�}|��}|�|||�}z|IdHWn|���YnX|jr\t�d|��||�||fS)Nz!Write pipe %r connected: (%r, %r))rdr�r�r�rr	r�r�rrr�connect_write_pipes�z BaseEventLoop.connect_write_pipecCs�|g}|dk	r"|�dt|����|dk	rJ|tjkrJ|�dt|����n8|dk	rf|�dt|����|dk	r�|�dt|����t�d�|��dS)Nzstdin=zstdout=stderr=zstdout=zstderr=� )r9r!rrrr	r&)rfr*r�r�r�r(rrr�_log_subprocessszBaseEventLoop._log_subprocess)	r�r�r��universal_newlinesr�r��encoding�errors�textc	�s�t|ttf�std��|r"td��|s.td��|dkr>td��|rJtd��|	dk	rZtd��|
dk	rjtd��|�}
d}|jr�d	|}|�||||�|j|
|d
||||f|�IdH}|jr�|dk	r�t�d||�||
fS)Nzcmd must be a string� universal_newlines must be Falsezshell must be Truer�bufsize must be 0�text must be False�encoding must be None�errors must be Nonezrun shell command %rT�%s: %r)	rr3rr%r�r�r�rr()rfr��cmdr�r�r�r�r�r�r�r�r�r�r��	debug_logrnrrr�subprocess_shellsB��
zBaseEventLoop.subprocess_shellc	�s�|rtd��|rtd��|dkr(td��|r4td��|	dk	rDtd��|
dk	rTtd��|f|}|�}d}|jr�d|��}|�||||�|j||d	||||f|
�IdH}|jr�|dk	r�t�d
||�||fS)Nr�zshell must be Falserr�r�r�r�zexecute program Fr�)r%r�r�r�rr()rfr�Zprogramr�r�r�r�r�r�r�r�r�r�r�Z
popen_argsr�r�rnrrr�subprocess_execCs@

��
zBaseEventLoop.subprocess_execcCs|jS)zKReturn an exception handler, or None if the default one is in use.
        )r�rqrrr�get_exception_handleresz#BaseEventLoop.get_exception_handlercCs(|dk	rt|�std|����||_dS)a�Set handler as the new event loop exception handler.

        If handler is None, the default exception handler will
        be set.

        If handler is a callable object, it should have a
        signature matching '(loop, context)', where 'loop'
        will be a reference to the active event loop, 'context'
        will be a dict object (see `call_exception_handler()`
        documentation for details about context).
        Nz+A callable object or None is expected, got )r�r5r�)rfZhandlerrrr�set_exception_handlerjsz#BaseEventLoop.set_exception_handlerc	Cs|�d�}|sd}|�d�}|dk	r6t|�||jf}nd}d|kr`|jdk	r`|jjr`|jj|d<|g}t|�D]�}|dkr|qn||}|dkr�d	�t�|��}d
}||�	�7}n2|dkr�d	�t�|��}d}||�	�7}nt
|�}|�|�d|���qntj
d
�|�|d�dS)aEDefault exception handler.

        This is called when an exception occurs and no exception
        handler is set, and can be called by a custom exception
        handler that wants to defer to the default behavior.

        This default handler logs the error message and other
        context-dependent information.  In debug mode, a truncated
        stack trace is also appended showing where the given object
        (e.g. a handle or future or task) was created, if any.

        The context parameter has the same meaning as in
        `call_exception_handler()`.
        r�z!Unhandled exception in event looprRNFZsource_tracebackZhandle_traceback>r�rRr.z+Object created at (most recent call last):
z+Handle created at (most recent call last):
rJ�
r�)�getr>�
__traceback__r�r��sortedr&�	traceback�format_list�rstriprr9rr�)	rfr
r�rRr�Z	log_linesr|�value�tbrrr�default_exception_handler{s<

���z'BaseEventLoop.default_exception_handlercCs�|jdkrVz|�|�Wq�ttfk
r2�Yq�tk
rRtjddd�Yq�Xn�z|�||�Wn�ttfk
r��Ynttk
r�}zVz|�d||d��Wn:ttfk
r��Yn"tk
r�tjddd�YnXW5d}~XYnXdS)aDCall the current event loop's exception handler.

        The context argument is a dict containing the following keys:

        - 'message': Error message;
        - 'exception' (optional): Exception object;
        - 'future' (optional): Future instance;
        - 'task' (optional): Task instance;
        - 'handle' (optional): Handle instance;
        - 'protocol' (optional): Protocol instance;
        - 'transport' (optional): Transport instance;
        - 'socket' (optional): Socket instance;
        - 'asyncgen' (optional): Asynchronous generator that caused
                                 the exception.

        New keys maybe introduced in the future.

        Note: do not overload this method in an event loop subclass.
        For custom exception handling, use the
        `set_exception_handler()` method.
        Nz&Exception in default exception handlerTr�z$Unhandled error in exception handler)r�rRr
zeException in default exception handler while handling an unexpected error in custom exception handler)r�r�rSrTrprr�)rfr
rWrrrr��s4
���z$BaseEventLoop.call_exception_handlercCs>t|tj�std��|jrdSt|tj�r.t�|j�|�dS)z3Add a Handle to _scheduled (TimerHandle) or _ready.zA Handle is required hereN)rrrr��
_cancelledrr�r9�rfrrrr�
_add_callback�s
zBaseEventLoop._add_callbackcCs|�|�|��dS)z6Like _add_callback() but called from a signal handler.N)r�r�r�rrr�_add_callback_signalsafe�s
z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)z3Notification that a TimerHandle has been cancelled.rN)r�r�r�rrr�_timer_handle_cancelled�sz%BaseEventLoop._timer_handle_cancelledc	Cs�t|j�}|tkr`|j|tkr`g}|jD]}|jr<d|_q*|�|�q*t�|�||_d|_n4|jr�|jdjr�|jd8_t�	|j�}d|_q`d}|j
s�|jr�d}n*|jr�|jdj}t
td||���t�}|j�|�}|�|�|��|j}|j�r:|jd}|j|k�r�q:t�	|j�}d|_|j
�|�q�t|j
�}t|�D]|}	|j
��}|j�rf�qL|j�r�zD||_|��}
|��|��|
}||jk�r�t�dt|�|�W5d|_Xn|���qLd}dS)z�Run one full iteration of the event loop.

        This calls all currently ready callbacks, polls for I/O,
        schedules the resulting callbacks, and finally schedules
        'call_later' callbacks.
        FrrNzExecuting %s took %.3f seconds)r�r��_MIN_SCHEDULED_TIMER_HANDLESr��%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr�r9r�heapify�heappopr�r�Z_whenr=�maxr��MAXIMUM_SELECT_TIMEOUTZ	_selectorZselectr�r��range�popleftr�r�Z_runr�rr�r)rfZsched_countZ
new_scheduledrZtimeoutrr�Zend_timeZntodo�ir+r-rrrr�sj
��





�
zBaseEventLoop._run_oncecCsHt|�t|j�krdS|r2t��|_t�tj�nt�|j�||_dSrB)rkr�r�#get_coroutine_origin_tracking_depthr��#set_coroutine_origin_tracking_depthrZDEBUG_STACK_DEPTH�rfZenabledrrrr�Fs���z,BaseEventLoop._set_coroutine_origin_trackingcCs|jSrB)r�rqrrrr�UszBaseEventLoop.get_debugcCs ||_|��r|�|j|�dSrB)r�r�r�r�r�rrrr�XszBaseEventLoop.set_debug)N)N)NNN)NN)NN)N)r)rN)N)NN)FN)rN)NN)NN)Sr|r}r~rhr�rdr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrUr�r�r�r�rr�r�rrrrrrr�rr#r.r'r0r9r3r5r2rSrirfrnrlrmrqr�r�r$r1rdr�r6Z
AI_PASSIVEr�r�r�r�r�rrr�r�r�r�r�r�r�r�r�rr�r�r�rrrrr�sF���
�
�
�
�
		&	
	�

�
%���
�/�/���	��w��%�"29Nr)rr)r)7�__doc__rFZcollections.abcZconcurrent.futuresrr\rrKr�r$r�rrr�r�rr�r�rT�ImportErrorr.rrrrrrr	r
rrr
�logr�__all__r�r�r#r8r��objectr�rr!r+rArPrXr[ZProtocolr\ZAbstractServerrZAbstractEventLooprrrrr�<module>sd

		
;


DoPK [7�!�!$__pycache__/protocols.cpython-38.pycnu�[���U

e5d��@sbdZdZGdd�d�ZGdd�de�ZGdd�de�ZGdd	�d	e�ZGd
d�de�Zdd
�ZdS)zAbstract Protocol base classes.)�BaseProtocol�Protocol�DatagramProtocol�SubprocessProtocol�BufferedProtocolc@s4eZdZdZdZdd�Zdd�Zdd�Zd	d
�ZdS)raCommon base class for protocol interfaces.

    Usually user implements protocols that derived from BaseProtocol
    like Protocol or ProcessProtocol.

    The only case when BaseProtocol should be implemented directly is
    write-only transport like write pipe
    �cCsdS)z�Called when a connection is made.

        The argument is the transport representing the pipe connection.
        To receive data, wait for data_received() calls.
        When the connection is closed, connection_lost() is called.
        Nr)�selfZ	transportrr�)/usr/lib64/python3.8/asyncio/protocols.py�connection_madeszBaseProtocol.connection_madecCsdS)z�Called when the connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        Nr�r�excrrr�connection_lostszBaseProtocol.connection_lostcCsdS)aCalled when the transport's buffer goes over the high-water mark.

        Pause and resume calls are paired -- pause_writing() is called
        once when the buffer goes strictly over the high-water mark
        (even if subsequent writes increases the buffer size even
        more), and eventually resume_writing() is called once when the
        buffer size reaches the low-water mark.

        Note that if the buffer size equals the high-water mark,
        pause_writing() is not called -- it must go strictly over.
        Conversely, resume_writing() is called when the buffer size is
        equal or lower than the low-water mark.  These end conditions
        are important to ensure that things go as expected when either
        mark is zero.

        NOTE: This is the only Protocol callback that is not called
        through EventLoop.call_soon() -- if it were, it would have no
        effect when it's most needed (when the app keeps writing
        without yielding until pause_writing() is called).
        Nr�rrrr�
pause_writing%szBaseProtocol.pause_writingcCsdS)zvCalled when the transport's buffer drains below the low-water mark.

        See pause_writing() for details.
        Nrr
rrr�resume_writing;szBaseProtocol.resume_writingN)	�__name__�
__module__�__qualname__�__doc__�	__slots__r	rrrrrrrr	s	rc@s$eZdZdZdZdd�Zdd�ZdS)ranInterface for stream protocol.

    The user should implement this interface.  They can inherit from
    this class but don't need to.  The implementations here do
    nothing (they don't raise exceptions).

    When the user wants to requests a transport, they pass a protocol
    factory to a utility function (e.g., EventLoop.create_connection()).

    When the connection is made successfully, connection_made() is
    called with a suitable transport object.  Then data_received()
    will be called 0 or more times with data (bytes) received from the
    transport; finally, connection_lost() will be called exactly once
    with either an exception object or None as an argument.

    State machine of calls:

      start -> CM [-> DR*] [-> ER?] -> CL -> end

    * CM: connection_made()
    * DR: data_received()
    * ER: eof_received()
    * CL: connection_lost()
    rcCsdS)zTCalled when some data is received.

        The argument is a bytes object.
        Nr)r�datarrr�
data_received^szProtocol.data_receivedcCsdS�z�Called when the other end calls write_eof() or equivalent.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        Nrr
rrr�eof_receiveddszProtocol.eof_receivedN)rrrrrrrrrrrrBsrc@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
ra�Interface for stream protocol with manual buffer control.

    Important: this has been added to asyncio in Python 3.7
    *on a provisional basis*!  Consider it as an experimental API that
    might be changed or removed in Python 3.8.

    Event methods, such as `create_server` and `create_connection`,
    accept factories that return protocols that implement this interface.

    The idea of BufferedProtocol is that it allows to manually allocate
    and control the receive buffer.  Event loops can then use the buffer
    provided by the protocol to avoid unnecessary data copies.  This
    can result in noticeable performance improvement for protocols that
    receive big amounts of data.  Sophisticated protocols can allocate
    the buffer only once at creation time.

    State machine of calls:

      start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end

    * CM: connection_made()
    * GB: get_buffer()
    * BU: buffer_updated()
    * ER: eof_received()
    * CL: connection_lost()
    rcCsdS)aPCalled to allocate a new receive buffer.

        *sizehint* is a recommended minimal size for the returned
        buffer.  When set to -1, the buffer size can be arbitrary.

        Must return an object that implements the
        :ref:`buffer protocol <bufferobjects>`.
        It is an error to return a zero-sized buffer.
        Nr)r�sizehintrrr�
get_buffer�szBufferedProtocol.get_buffercCsdS)z�Called when the buffer was updated with the received data.

        *nbytes* is the total number of bytes that were written to
        the buffer.
        Nr)r�nbytesrrr�buffer_updated�szBufferedProtocol.buffer_updatedcCsdSrrr
rrrr�szBufferedProtocol.eof_receivedN)rrrrrrrrrrrrrms
rc@s$eZdZdZdZdd�Zdd�ZdS)rz Interface for datagram protocol.rcCsdS)z&Called when some datagram is received.Nr)rrZaddrrrr�datagram_received�sz"DatagramProtocol.datagram_receivedcCsdS)z~Called when a send or receive operation raises an OSError.

        (Other than BlockingIOError or InterruptedError.)
        Nrr
rrr�error_received�szDatagramProtocol.error_receivedN)rrrrrrrrrrrr�src@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
rz,Interface for protocol for subprocess calls.rcCsdS)z�Called when the subprocess writes data into stdout/stderr pipe.

        fd is int file descriptor.
        data is bytes object.
        Nr)r�fdrrrr�pipe_data_received�sz%SubprocessProtocol.pipe_data_receivedcCsdS)z�Called when a file descriptor associated with the child process is
        closed.

        fd is the int file descriptor that was closed.
        Nr)rrrrrr�pipe_connection_lost�sz'SubprocessProtocol.pipe_connection_lostcCsdS)z"Called when subprocess has exited.Nrr
rrr�process_exited�sz!SubprocessProtocol.process_exitedN)rrrrrr r!r"rrrrr�s
rcCs�t|�}|r�|�|�}t|�}|s*td��||krL||d|�<|�|�dS|d|�|d|�<|�|�||d�}t|�}qdS)Nz%get_buffer() returned an empty buffer)�lenr�RuntimeErrorr)�protorZdata_lenZbufZbuf_lenrrr�_feed_data_to_buffered_proto�s


r&N)r�__all__rrrrrr&rrrr�<module>s9+9PK [�ۤ�YmYm0__pycache__/selector_events.cpython-38.opt-2.pycnu�[���U

e5dT��@s*dZddlZddlZddlZddlZddlZddlZddlZzddlZWne	k
r`dZYnXddl
mZddl
mZddl
m
Z
ddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddlmZd
d�Zdd�ZGdd�dej�ZGdd�dejej�ZGdd�de�ZGdd�de�ZdS))�BaseSelectorEventLoop�N�)�base_events)�	constants)�events)�futures)�	protocols)�sslproto)�
transports)�trsock)�loggercCs8z|�|�}Wntk
r$YdSXt|j|@�SdS�NF)�get_key�KeyError�boolr)�selector�fdZevent�key�r�//usr/lib64/python3.8/asyncio/selector_events.py�_test_selector_event s
rcCs tdk	rt|tj�rtd��dS)Nz"Socket cannot be of type SSLSocket)�ssl�
isinstanceZ	SSLSocket�	TypeError)�sockrrr�_check_ssl_socket+srcs�eZdZdR�fdd�	ZdSddd�dd�ZdTddddejd�d	d
�ZdUdd�Z�fd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdddejfdd�Zdddejfdd�Zddejfdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Zd8d9�Zd:d;�Zd<d=�Z d>d?�Z!d@dA�Z"dBdC�Z#dDdE�Z$dFdG�Z%dHdI�Z&dJdK�Z'dLdM�Z(dNdO�Z)dPdQ�Z*�Z+S)VrNcsFt���|dkrt��}t�d|jj�||_|�	�t
��|_dS)NzUsing selector: %s)
�super�__init__�	selectorsZDefaultSelectorr�debug�	__class__�__name__�	_selector�_make_self_pipe�weakrefZWeakValueDictionary�_transports)�selfr�r rrr6s
zBaseSelectorEventLoop.__init__��extra�servercCst||||||�S�N)�_SelectorSocketTransport)r&r�protocol�waiterr)r*rrr�_make_socket_transport@s
�z,BaseSelectorEventLoop._make_socket_transportF)�server_side�server_hostnamer)r*�ssl_handshake_timeoutc	Cs0tj|||||||	d�}
t|||
||d�|
jS)N)r2r()r	ZSSLProtocolr,Z_app_transport)r&Zrawsockr-�
sslcontextr.r0r1r)r*r2Zssl_protocolrrr�_make_ssl_transportEs��z)BaseSelectorEventLoop._make_ssl_transportcCst||||||�Sr+)�_SelectorDatagramTransport)r&rr-�addressr.r)rrr�_make_datagram_transportRs
�z.BaseSelectorEventLoop._make_datagram_transportcsL|��rtd��|��rdS|��t���|jdk	rH|j��d|_dS)Nz!Cannot close a running event loop)Z
is_running�RuntimeError�	is_closed�_close_self_piper�closer"�r&r'rrr;Ws


zBaseSelectorEventLoop.closecCsB|�|j���|j��d|_|j��d|_|jd8_dS)Nr)�_remove_reader�_ssock�filenor;�_csock�
_internal_fdsr<rrrr:bs

z&BaseSelectorEventLoop._close_self_pipecCsNt��\|_|_|j�d�|j�d�|jd7_|�|j��|j�dS)NFr)	�socketZ
socketpairr>r@�setblockingrA�_add_readerr?�_read_from_selfr<rrrr#js
z%BaseSelectorEventLoop._make_self_pipecCsdSr+r�r&�datarrr�_process_self_datarsz(BaseSelectorEventLoop._process_self_datacCsXz"|j�d�}|sWqT|�|�Wqtk
r:YqYqtk
rPYqTYqXqdS)Ni)r>�recvrH�InterruptedError�BlockingIOErrorrFrrrrEusz%BaseSelectorEventLoop._read_from_selfcCsN|j}|dkrdSz|�d�Wn(tk
rH|jrDtjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketT��exc_info)r@�send�OSError�_debugrr)r&Zcsockrrr�_write_to_self�s�z$BaseSelectorEventLoop._write_to_self�dc
Cs"|�|��|j||||||�dSr+)rDr?�_accept_connection)r&�protocol_factoryrr3r*�backlogr2rrr�_start_serving�s�z$BaseSelectorEventLoop._start_servingc
Cst|�D]�}z0|��\}}	|jr0t�d||	|�|�d�Wn�tttfk
rZYdSt	k
r�}
zd|
j
t
jt
jt
j
t
jfkr�|�d|
t�|�d��|�|���|�tj|j||||||�n�W5d}
~
XYqXd|	i}|�||||||�}|�|�qdS)Nz#%r got a new connection from %r: %rFz&socket.accept() out of system resource)�message�	exceptionrB�peername)�range�acceptrQrrrCrKrJ�ConnectionAbortedErrorrP�errnoZEMFILEZENFILEZENOBUFSZENOMEM�call_exception_handlerr�TransportSocketr=r?Z
call_laterrZACCEPT_RETRY_DELAYrW�_accept_connection2Zcreate_task)
r&rUrr3r*rVr2�_�conn�addr�excr)r\rrrrT�sV�����z(BaseSelectorEventLoop._accept_connectionc
�s�d}d}zt|�}|��}	|r8|j||||	d|||d�}n|j|||	||d�}z|	IdHWntk
rx|���YnXWntttfk
r��Yn\tk
r�}
z>|jr�d|
d�}|dk	r�||d<|dk	r�||d<|�|�W5d}
~
XYnXdS)NT)r.r0r)r*r2)r.r)r*z3Error on transport creation for incoming connection)rXrYr-�	transport)	�
create_futurer4r/�
BaseExceptionr;�
SystemExit�KeyboardInterruptrQr_)r&rUrcr)r3r*r2r-rfr.re�contextrrrra�sP���z)BaseSelectorEventLoop._accept_connection2c
Cs�|}t|t�sJzt|���}Wn*tttfk
rHtd|���d�YnXz|j|}Wntk
rlYnX|��s�t	d|�d|����dS)NzInvalid file object: zFile descriptor z is used by transport )
r�intr?�AttributeErrorr�
ValueErrorr%r�
is_closingr8)r&rr?rfrrr�_ensure_fd_no_transport�s
�z-BaseSelectorEventLoop._ensure_fd_no_transportc		Gs�|��t�|||d�}z|j�|�}Wn*tk
rR|j�|tj|df�Yn>X|j|j	}\}}|j�
||tjB||f�|dk	r�|��dSr+)�
_check_closedr�Handler"rr�registerr�
EVENT_READrG�modify�cancel�	r&r�callback�argsZhandler�mask�reader�writerrrrrDs�
�z!BaseSelectorEventLoop._add_readercCs�|��rdSz|j�|�}Wntk
r2YdSX|j|j}\}}|tjM}|sd|j�|�n|j�	||d|f�|dk	r�|�
�dSdSdS�NFT)r9r"rrrrGrrt�
unregisterrurv�r&rrrzr{r|rrrr=sz$BaseSelectorEventLoop._remove_readerc		Gs�|��t�|||d�}z|j�|�}Wn*tk
rR|j�|tjd|f�Yn>X|j|j	}\}}|j�
||tjB||f�|dk	r�|��dSr+)rqrrrr"rrrsr�EVENT_WRITErGrurvrwrrr�_add_writer%s�
�z!BaseSelectorEventLoop._add_writercCs�|��rdSz|j�|�}Wntk
r2YdSX|j|j}\}}|tjM}|sd|j�|�n|j�	|||df�|dk	r�|�
�dSdSdSr})r9r"rrrrGrr�r~rurvrrrr�_remove_writer4sz$BaseSelectorEventLoop._remove_writercGs|�|�|j||f|��Sr+)rprD�r&rrxryrrr�
add_readerKs
z BaseSelectorEventLoop.add_readercCs|�|�|�|�Sr+)rpr=�r&rrrr�
remove_readerPs
z#BaseSelectorEventLoop.remove_readercGs|�|�|j||f|��Sr+)rpr�r�rrr�
add_writerUs
z BaseSelectorEventLoop.add_writercCs|�|�|�|�Sr+)rpr�r�rrr�
remove_writerZs
z#BaseSelectorEventLoop.remove_writerc	�s�t|�|jr"|��dkr"td��z|�|�WSttfk
rFYnX|��}|��}|�	||j
|||�|�t�
|j|��|IdHS�Nr�the socket must be non-blocking)rrQ�
gettimeoutrnrIrKrJrgr?r��
_sock_recv�add_done_callback�	functools�partial�_sock_read_done)r&r�n�futrrrr�	sock_recv_s�zBaseSelectorEventLoop.sock_recvcCs|�|�dSr+)r��r&rr�rrrr�tsz%BaseSelectorEventLoop._sock_read_donec
Cs�|��rdSz|�|�}Wn\ttfk
r4YdSttfk
rL�Yn6tk
rv}z|�|�W5d}~XYnX|�|�dSr+)	�donerIrKrJrirjrh�
set_exception�
set_result)r&r�rr�rGrerrrr�wsz BaseSelectorEventLoop._sock_recvc	�s�t|�|jr"|��dkr"td��z|�|�WSttfk
rFYnX|��}|��}|�	||j
|||�|�t�
|j|��|IdHSr�)rrQr�rn�	recv_intorKrJrgr?r��_sock_recv_intor�r�r�r�)r&r�bufr�rrrr�sock_recv_into�s�z$BaseSelectorEventLoop.sock_recv_intoc
Cs�|��rdSz|�|�}Wn\ttfk
r4YdSttfk
rL�Yn6tk
rv}z|�|�W5d}~XYnX|�|�dSr+)	r�r�rKrJrirjrhr�r�)r&r�rr��nbytesrerrrr��sz%BaseSelectorEventLoop._sock_recv_intoc	�s�t|�|jr"|��dkr"td��z|�|�}Wnttfk
rLd}YnX|t|�kr^dS|��}|�	�}|�
t�|j
|��|�||j||t|�|g�|IdHSr�)rrQr�rnrOrKrJ�lenrgr?r�r�r��_sock_write_doner��
_sock_sendall�
memoryview)r&rrGr�r�rrrr�sock_sendall�s&	
��z"BaseSelectorEventLoop.sock_sendallc
Cs�|��rdS|d}z|�||d��}Wnbttfk
rDYdSttfk
r\�Yn2tk
r�}z|�|�WY�dSd}~XYnX||7}|t|�kr�|�	d�n||d<dS)Nr)
r�rOrKrJrirjrhr�r�r�)r&r�rZview�pos�startr�rerrrr��s 
z#BaseSelectorEventLoop._sock_sendallc�s�t|�|jr"|��dkr"td��ttd�r8|jtjkrf|j||j|j	|d�IdH}|d\}}}}}|�
�}|�|||�|IdHS)Nrr��AF_UNIX)�family�proto�loop)rrQr�rn�hasattrrBr�r�Z_ensure_resolvedr�rg�
_sock_connect)r&rr6Zresolvedrbr�rrr�sock_connect�s�z"BaseSelectorEventLoop.sock_connectc
Cs�|��}z|�|�Wn�ttfk
rV|�t�|j|��|�||j	|||�YnNt
tfk
rn�Yn6tk
r�}z|�
|�W5d}~XYnX|�d�dSr+)r?ZconnectrKrJr�r�r�r�r��_sock_connect_cbrirjrhr�r�)r&r�rr6rrerrrr��s�z#BaseSelectorEventLoop._sock_connectcCs|�|�dSr+)r�r�rrrr�sz&BaseSelectorEventLoop._sock_write_donec
Cs�|��rdSz,|�tjtj�}|dkr6t|d|����WnZttfk
rPYnNtt	fk
rh�Yn6t
k
r�}z|�|�W5d}~XYnX|�d�dS)NrzConnect call failed )
r�Z
getsockoptrBZ
SOL_SOCKETZSO_ERRORrPrKrJrirjrhr�r�)r&r�rr6�errrerrrr�sz&BaseSelectorEventLoop._sock_connect_cbc�sBt|�|jr"|��dkr"td��|��}|�|d|�|IdHS)Nrr�F)rrQr�rnrg�_sock_accept)r&rr�rrr�sock_acceptsz!BaseSelectorEventLoop.sock_acceptc
Cs�|��}|r|�|�|��r"dSz|��\}}|�d�Wnnttfk
rh|�||j|d|�YnRt	t
fk
r��Yn:tk
r�}z|�|�W5d}~XYnX|�
||f�dSr})r?r�r�r\rCrKrJr�r�rirjrhr�r�)r&r�Z
registeredrrrcr6rerrrr�*s
z"BaseSelectorEventLoop._sock_acceptc	�sp|j|j=|��}|��|��IdHz |j|j|||dd�IdHW�S|��|r^|��||j|j<XdS)NF)Zfallback)	r%�_sock_fd�
is_reading�
pause_reading�_make_empty_waiter�_reset_empty_waiter�resume_readingZ
sock_sendfile�_sock)r&Ztransp�file�offset�countr�rrr�_sendfile_native<s
�z&BaseSelectorEventLoop._sendfile_nativecCs�|D]v\}}|j|j}\}}|tj@rL|dk	rL|jrB|�|�n
|�|�|tj@r|dk	r|jrp|�|�q|�|�qdSr+)	�fileobjrGrrtZ
_cancelledr=Z
_add_callbackr�r�)r&Z
event_listrrzr�r{r|rrr�_process_eventsJs
z%BaseSelectorEventLoop._process_eventscCs|�|���|��dSr+)r=r?r;)r&rrrr�
_stop_servingXsz#BaseSelectorEventLoop._stop_serving)N)N)N)NNN),r!�
__module__�__qualname__rr/rZSSL_HANDSHAKE_TIMEOUTr4r7r;r:r#rHrErRrWrTrarprDr=r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��
__classcell__rrr'rr0s|
����
�
	�
.�
)rcs�eZdZdZeZdZd�fdd�	Zdd�Zdd�Z	d	d
�Z
dd�Zd
d�Zdd�Z
ejfdd�Zddd�Zdd�Zdd�Zdd�Zdd�Z�ZS) �_SelectorTransportiNcs�t��||�t�|�|jd<z|��|jd<Wntk
rNd|jd<YnXd|jkr�z|��|jd<Wn tj	k
r�d|jd<YnX||_
|��|_d|_
|�|�||_|��|_d|_d|_|jdk	r�|j��||j|j<dS)NrBZsocknamerZFr)rrrr`�_extraZgetsocknamerPZgetpeernamerB�errorr�r?r��_protocol_connected�set_protocol�_server�_buffer_factory�_buffer�
_conn_lost�_closingZ_attachr%)r&r�rr-r)r*r'rrris,





z_SelectorTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���|jdk	r�|j��s�t|jj	|jt
j�}|rz|�d�n
|�d�t|jj	|jt
j�}|r�d}nd}|�
�}|�d|�d	|�d
��d�d�|��S)
N�closed�closingzfd=zread=pollingz	read=idle�pollingZidlezwrite=<z
, bufsize=�>z<{}>� )r r!r��appendr�r��_loopr9rr"rrtr��get_write_buffer_size�format�join)r&�infor��state�bufsizerrr�__repr__�s0


�
�z_SelectorTransport.__repr__cCs|�d�dSr+)�_force_closer<rrr�abort�sz_SelectorTransport.abortcCs||_d|_dS�NT)�	_protocolr��r&r-rrrr��sz_SelectorTransport.set_protocolcCs|jSr+)r�r<rrr�get_protocol�sz_SelectorTransport.get_protocolcCs|jSr+)r�r<rrrro�sz_SelectorTransport.is_closingcCsT|jr
dSd|_|j�|j�|jsP|jd7_|j�|j�|j�|jd�dS�NTr)	r�r�r=r�r�r�r��	call_soon�_call_connection_lostr<rrrr;�sz_SelectorTransport.closecCs,|jdk	r(|d|��t|d�|j��dS)Nzunclosed transport )�source)r��ResourceWarningr;)r&Z_warnrrr�__del__�s
z_SelectorTransport.__del__�Fatal error on transportcCsNt|t�r(|j��r@tjd||dd�n|j�||||jd��|�|�dS)Nz%r: %sTrM)rXrYrfr-)	rrPr��	get_debugrrr_r�r�)r&rerXrrr�_fatal_error�s

�z_SelectorTransport._fatal_errorcCsd|jr
dS|jr(|j��|j�|j�|jsBd|_|j�|j�|jd7_|j�|j	|�dSr�)
r�r��clearr�r�r�r�r=r�r��r&rerrrr��s
z_SelectorTransport._force_closecCsVz|jr|j�|�W5|j��d|_d|_d|_|j}|dk	rP|��d|_XdSr+)r�r;r�r�r�Z_detachr�Zconnection_lost)r&rer*rrrr��s
z(_SelectorTransport._call_connection_lostcCs
t|j�Sr+)r�r�r<rrrr��sz(_SelectorTransport.get_write_buffer_sizecGs"|jr
dS|jj||f|��dSr+)r�r�rDr�rrrrD�sz_SelectorTransport._add_reader)NN)r�)r!r�r��max_size�	bytearrayr�r�rr�r�r�r�ror;�warnings�warnr�r�r�r�r�rDr�rrr'rr�]s 

r�cs�eZdZdZejjZd#�fdd�	Z�fdd�Z	dd�Z
d	d
�Zdd�Zd
d�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Z�fdd�Zdd �Zd!d"�Z�ZS)$r,TNcs~d|_t��|||||�d|_d|_d|_t�|j�|j	�
|jj|�|j	�
|j
|j|j�|dk	rz|j	�
tj|d�dSr
)�_read_ready_cbrr�_eof�_paused�
_empty_waiterrZ_set_nodelayr�r�r�r��connection_maderDr��_read_readyr�_set_result_unless_cancelled)r&r�rr-r.r)r*r'rrr�s 
�
�z!_SelectorSocketTransport.__init__cs.t|tj�r|j|_n|j|_t��|�dSr+)rrZBufferedProtocol�_read_ready__get_bufferr��_read_ready__data_receivedrr�r�r'rrr�	s
z%_SelectorSocketTransport.set_protocolcCs|jo|jSr+)r�r�r<rrrr�sz#_SelectorSocketTransport.is_readingcCs>|js|jrdSd|_|j�|j�|j��r:t�d|�dS)NTz%r pauses reading)r�r�r�r=r�r�rrr<rrrr�s
z&_SelectorSocketTransport.pause_readingcCs@|js|jsdSd|_|�|j|j�|j��r<t�d|�dS)NFz%r resumes reading)	r�r�rDr�r�r�r�rrr<rrrr�s
z'_SelectorSocketTransport.resume_readingcCs|��dSr+)r�r<rrrr�$sz$_SelectorSocketTransport._read_readyc
Cs`|jr
dSz |j�d�}t|�s(td��WnLttfk
rD�Yn4tk
rv}z|�|d�WY�dSd}~XYnXz|j	�
|�}Wndttfk
r�YdSttfk
r��Yn4tk
r�}z|�|d�WY�dSd}~XYnX|�s|�
�dSz|j�|�WnJttfk
�r,�Yn0tk
�rZ}z|�|d�W5d}~XYnXdS)N���z%get_buffer() returned an empty bufferz/Fatal error: protocol.get_buffer() call failed.�$Fatal read error on socket transportz3Fatal error: protocol.buffer_updated() call failed.)r�r�Z
get_bufferr�r8rirjrhr�r�r�rKrJ�_read_ready__on_eofZbuffer_updated)r&r�rer�rrrr�'sF��z0_SelectorSocketTransport._read_ready__get_bufferc
Cs�|jr
dSz|j�|j�}Wndttfk
r6YdSttfk
rN�Yn4tk
r�}z|�	|d�WY�dSd}~XYnX|s�|�
�dSz|j�|�WnFttfk
r��Yn.tk
r�}z|�	|d�W5d}~XYnXdS)Nr�z2Fatal error: protocol.data_received() call failed.)
r�r�rIr�rKrJrirjrhr�r�r�Z
data_received)r&rGrerrrr�Ls.�z3_SelectorSocketTransport._read_ready__data_receivedc
Cs�|j��rt�d|�z|j��}WnLttfk
r>�Yn4tk
rp}z|�	|d�WY�dSd}~XYnX|r�|j�
|j�n|��dS)Nz%r received EOFz1Fatal error: protocol.eof_received() call failed.)
r�r�rrr�Zeof_receivedrirjrhr�r=r�r;)r&Z	keep_openrerrrr�es
�z,_SelectorSocketTransport._read_ready__on_eofc
Cs6t|tttf�s$tdt|�j����|jr2td��|j	dk	rDtd��|sLdS|j
rz|j
tjkrht
�d�|j
d7_
dS|j�sz|j�|�}Wnbttfk
r�Ynbttfk
r��YnJtk
r�}z|�|d�WY�dSd}~XYnX||d�}|�sdS|j�|j|j�|j�|�|��dS)N�/data argument must be a bytes-like object, not z%Cannot call write() after write_eof()z(unable to write; sendfile is in progress�socket.send() raised exception.r�%Fatal write error on socket transport)r�bytesr�r�r�typer!r�r8r�r�r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESr�warningr�r�rOrKrJrirjrhr�r�r�r��_write_ready�extend�_maybe_pause_protocol)r&rGr�rerrr�writezs:

z_SelectorSocketTransport.writec
Cs|jr
dSz|j�|j�}Wn�ttfk
r4Yn�ttfk
rL�Yn�tk
r�}z>|j	�
|j�|j��|�
|d�|jdk	r�|j�|�W5d}~XYnnX|r�|jd|�=|��|j�s|j	�
|j�|jdk	r�|j�d�|jr�|�d�n|j�r|j�tj�dS)Nr�)r�r�rOr�rKrJrirjrhr�r�r�r�r�r�r��_maybe_resume_protocolr�r�r�r��shutdownrB�SHUT_WR)r&r�rerrrr�s2


z%_SelectorSocketTransport._write_readycCs.|js|jrdSd|_|js*|j�tj�dSr�)r�r�r�r�rrBrr<rrr�	write_eof�s
z"_SelectorSocketTransport.write_eofcCsdSr�rr<rrr�
can_write_eof�sz&_SelectorSocketTransport.can_write_eofcs*t��|�|jdk	r&|j�td��dS)NzConnection is closed by peer)rr�r�r��ConnectionErrorr�r'rrr��s

�z._SelectorSocketTransport._call_connection_lostcCs6|jdk	rtd��|j��|_|js0|j�d�|jS)NzEmpty waiter is already set)r�r8r�rgr�r�r<rrrr��s
z+_SelectorSocketTransport._make_empty_waitercCs
d|_dSr+)r�r<rrrr��sz,_SelectorSocketTransport._reset_empty_waiter)NNN)r!r�r�Z_start_tls_compatiblerZ
_SendfileModeZ
TRY_NATIVEZ_sendfile_compatiblerr�r�r�r�r�r�r�r�rrrrr�r�r�r�rrr'rr,�s*�%'r,csFeZdZejZd�fdd�	Zdd�Zdd�Zd
dd	�Z	d
d�Z
�ZS)r5Ncs^t��||||�||_|j�|jj|�|j�|j|j|j	�|dk	rZ|j�t
j|d�dSr+)rr�_addressr�r�r�r�rDr�r�rr�)r&r�rr-r6r.r)r'rrr�s
�
�z#_SelectorDatagramTransport.__init__cCstdd�|jD��S)Ncss|]\}}t|�VqdSr+)r�)�.0rGrbrrr�	<genexpr>�szC_SelectorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr�r<rrrr��sz0_SelectorDatagramTransport.get_write_buffer_sizec
Cs�|jr
dSz|j�|j�\}}Wn�ttfk
r8Yn�tk
rd}z|j�|�W5d}~XYnTt	t
fk
r|�Yn<tk
r�}z|�|d�W5d}~XYnX|j�
||�dS)Nz&Fatal read error on datagram transport)r�r�Zrecvfromr�rKrJrPr��error_receivedrirjrhr�Zdatagram_received�r&rGrdrerrrr��sz&_SelectorDatagramTransport._read_readyc
Cs�t|tttf�s$tdt|�j����|s,dS|jrV|d|jfkrPtd|j����|j}|j	r�|jr�|j	t
jkrxt�
d�|j	d7_	dS|j�slz,|jdr�|j�|�n|j�||�WdSttfk
r�|j�|j|j�Yn�tk
�r}z|j�|�WY�dSd}~XYnPttfk
�r6�Yn6tk
�rj}z|�|d�WY�dSd}~XYnX|j� t|�|f�|�!�dS)Nr�z!Invalid address: must be None or r�rrZ�'Fatal write error on datagram transport)"rr�r�r�rr�r!r
rnr�rr�rr�r�r�r�rO�sendtorKrJr�r�r��
_sendto_readyrPr�rrirjrhr�r�rrrrrr�sH
�

�z!_SelectorDatagramTransport.sendtoc
Cs|jr�|j��\}}z*|jdr.|j�|�n|j�||�Wqttfk
rj|j�||f�Yq�Yqt	k
r�}z|j
�|�WY�dSd}~XYqtt
fk
r��Yqtk
r�}z|�|d�WY�dSd}~XYqXq|��|j�s|j�|j�|j�r|�d�dS)NrZr)r��popleftr�r�rOrrKrJ�
appendleftrPr�rrirjrhr�rr�r�r�r�r�rrrrr*s2
�z(_SelectorDatagramTransport._sendto_ready)NNN)N)r!r�r��collections�dequer�rr�r�rrr�rrr'rr5�s�

+r5)�__all__rr^r�rrBr�r$r�ImportError�rrrrrr	r
r�logrrrZ
BaseEventLooprZ_FlowControlMixinZ	Transportr�r,r5rrrr�<module>sD
1�oPK [��?�?&__pycache__/locks.cpython-38.opt-1.pycnu�[���U

e5d|C�@s�dZdZddlZddlZddlZddlmZddlmZddlmZddlm	Z	Gd	d
�d
�Z
Gdd�d�ZGd
d�de�ZGdd�d�Z
Gdd�de�ZGdd�de�ZGdd�de�ZdS)zSynchronization primitives.)�Lock�Event�	Condition�	Semaphore�BoundedSemaphore�N�)�events)�futures)�
exceptions)�
coroutinesc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_ContextManagera\Context manager.

    This enables the following idiom for acquiring and releasing a
    lock around a block:

        with (yield from lock):
            <block>

    while failing loudly when accidentally using:

        with lock:
            <block>

    Deprecated, use 'async with' statement:
        async with lock:
            <block>
    cCs
||_dS�N)�_lock)�self�lock�r�%/usr/lib64/python3.8/asyncio/locks.py�__init__"sz_ContextManager.__init__cCsdSr
r�rrrr�	__enter__%sz_ContextManager.__enter__cGsz|j��W5d|_XdSr
)r�release�r�argsrrr�__exit__*sz_ContextManager.__exit__N)�__name__�
__module__�__qualname__�__doc__rrrrrrrrsrc@sReZdZdd�Zdd�Zejdd��Zej	e_	dd�Z
d	d
�Zdd�Zd
d�Z
dS)�_ContextManagerMixincCstd��dS)Nz9"yield from" should be used as context manager expression)�RuntimeErrorrrrrr2s�z_ContextManagerMixin.__enter__cGsdSr
rrrrrr6sz_ContextManagerMixin.__exit__ccs&tjdtdd�|��EdHt|�S)NzD'with (yield from lock)' is deprecated use 'async with lock' instead���
stacklevel)�warnings�warn�DeprecationWarning�acquirerrrrr�__iter__;s�z_ContextManagerMixin.__iter__c�s|��IdHt|�Sr
)r&rrrrrZ
__acquire_ctxUsz"_ContextManagerMixin.__acquire_ctxcCstjdtdd�|����S)Nz='with await lock' is deprecated use 'async with lock' insteadr r!)r#r$r%�!_ContextManagerMixin__acquire_ctx�	__await__rrrrr)Ys
�z_ContextManagerMixin.__await__c�s|��IdHdSr
)r&rrrr�
__aenter__`sz_ContextManagerMixin.__aenter__c�s|��dSr
)r)r�exc_type�exc�tbrrr�	__aexit__fsz_ContextManagerMixin.__aexit__N)rrrrr�types�	coroutiner'rZ
_is_coroutiner(r)r*r.rrrrr1s
rcsNeZdZdZdd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z	�Z
S)ra�Primitive lock objects.

    A primitive lock is a synchronization primitive that is not owned
    by a particular coroutine when locked.  A primitive lock is in one
    of two states, 'locked' or 'unlocked'.

    It is created in the unlocked state.  It has two basic methods,
    acquire() and release().  When the state is unlocked, acquire()
    changes the state to locked and returns immediately.  When the
    state is locked, acquire() blocks until a call to release() in
    another coroutine changes it to unlocked, then the acquire() call
    resets it to locked and returns.  The release() method should only
    be called in the locked state; it changes the state to unlocked
    and returns immediately.  If an attempt is made to release an
    unlocked lock, a RuntimeError will be raised.

    When more than one coroutine is blocked in acquire() waiting for
    the state to turn to unlocked, only one coroutine proceeds when a
    release() call resets the state to unlocked; first coroutine which
    is blocked in acquire() is being processed.

    acquire() is a coroutine and should be called with 'await'.

    Locks also support the asynchronous context management protocol.
    'async with lock' statement should be used.

    Usage:

        lock = Lock()
        ...
        await lock.acquire()
        try:
            ...
        finally:
            lock.release()

    Context manager usage:

        lock = Lock()
        ...
        async with lock:
             ...

    Lock objects can be tested for locking state:

        if not lock.locked():
           await lock.acquire()
        else:
           # lock is acquired
           ...

    N��loopcCs:d|_d|_|dkr t��|_n||_tjdtdd�dS�NF�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r r!)�_waiters�_lockedr�get_event_loop�_loopr#r$r%�rr2rrrr�s�z
Lock.__init__csLt���}|jrdnd}|jr2|�dt|j���}d|dd��d|�d�S�	N�lockedZunlocked�
, waiters:�<r���� [�]>)�super�__repr__r6r5�len�r�resZextra��	__class__rrrB�s

z
Lock.__repr__cCs|jS)z Return True if lock is acquired.)r6rrrrr;�szLock.lockedc	�s�|js.|jdks$tdd�|jD��r.d|_dS|jdkrBt��|_|j��}|j�|�z"z|IdHW5|j�|�XWn&t	j
k
r�|js�|���YnXd|_dS)z�Acquire a lock.

        This method blocks until the lock is unlocked, then sets it to
        locked and returns True.
        Ncss|]}|��VqdSr
)�	cancelled)�.0�wrrr�	<genexpr>�szLock.acquire.<locals>.<genexpr>T)r6r5�all�collections�dequer8�
create_future�append�remover
�CancelledError�_wake_up_first�r�futrrrr&�s&�


zLock.acquirecCs"|jrd|_|��ntd��dS)aGRelease a lock.

        When the lock is locked, reset it to unlocked, and return.
        If any other coroutines are blocked waiting for the lock to become
        unlocked, allow exactly one of them to proceed.

        When invoked on an unlocked lock, a RuntimeError is raised.

        There is no return value.
        FzLock is not acquired.N)r6rSrrrrrr�s
zLock.releasecCsJ|js
dSztt|j��}Wntk
r2YdSX|��sF|�d�dS)z*Wake up the first waiter if it isn't done.NT)r5�next�iter�
StopIteration�done�
set_resultrTrrrrS�szLock._wake_up_first)rrrrrrBr;r&rrS�
__classcell__rrrFrrjs5 rcsNeZdZdZdd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z	�Z
S)ra#Asynchronous equivalent to threading.Event.

    Class implementing event objects. An event manages a flag that can be set
    to true with the set() method and reset to false with the clear() method.
    The wait() method blocks until the flag is true. The flag is initially
    false.
    Nr1cCs>t��|_d|_|dkr$t��|_n||_tjdt	dd�dSr3)
rMrNr5�_valuerr7r8r#r$r%r9rrrrs
�zEvent.__init__csLt���}|jrdnd}|jr2|�dt|j���}d|dd��d|�d�S)	N�setZunsetr<r=rr>r?r@)rArBr\r5rCrDrFrrrBs

zEvent.__repr__cCs|jS)z5Return True if and only if the internal flag is true.�r\rrrr�is_setszEvent.is_setcCs.|js*d|_|jD]}|��s|�d�qdS)z�Set the internal flag to true. All coroutines waiting for it to
        become true are awakened. Coroutine that call wait() once the flag is
        true will not block at all.
        TN)r\r5rYrZrTrrrr]s

z	Event.setcCs
d|_dS)z�Reset the internal flag to false. Subsequently, coroutines calling
        wait() will block until set() is called to set the internal flag
        to true again.FNr^rrrr�clear"szEvent.clearc	�sF|jr
dS|j��}|j�|�z|IdHW�dS|j�|�XdS)z�Block until the internal flag is true.

        If the internal flag is true on entry, return True
        immediately.  Otherwise, block until another coroutine calls
        set() to set the flag to true, then return True.
        TN)r\r8rOr5rPrQrTrrr�wait(s

z
Event.wait)rrrrrrBr_r]r`rar[rrrFrr�srcsReZdZdZddd�dd�Z�fdd�Zdd	�Zd
d�Zdd
d�Zdd�Z	�Z
S)raAsynchronous equivalent to threading.Condition.

    This class implements condition variable objects. A condition variable
    allows one or more coroutines to wait until they are notified by another
    coroutine.

    A new Lock object is created and used as the underlying lock.
    Nr1cCs~|dkrt��|_n||_tjdtdd�|dkr>t|d�}n|j|jk	rRtd��||_|j	|_	|j
|_
|j|_t�
�|_dS)Nr4r r!r1z"loop argument must agree with lock)rr7r8r#r$r%r�
ValueErrorrr;r&rrMrNr5)rrr2rrrrEs �zCondition.__init__csNt���}|��rdnd}|jr4|�dt|j���}d|dd��d|�d�Sr:)rArBr;r5rCrDrFrrrB[s

zCondition.__repr__c�s�|��std��|��z@|j��}|j�	|�z|IdHW�W�dS|j�
|�XW5d}z|��IdHWq�Wq^tjk
r�d}Yq^Xq^|r�tj�XdS)a�Wait until notified.

        If the calling coroutine has not acquired the lock when this
        method is called, a RuntimeError is raised.

        This method releases the underlying lock, and then blocks
        until it is awakened by a notify() or notify_all() call for
        the same condition variable in another coroutine.  Once
        awakened, it re-acquires the lock and returns True.
        zcannot wait on un-acquired lockFNT)r;rrr&r
rRr8rOr5rPrQ)rrHrUrrrrabs$

zCondition.waitc�s$|�}|s |��IdH|�}q|S)z�Wait until a predicate becomes true.

        The predicate should be a callable which result will be
        interpreted as a boolean value.  The final predicate value is
        the return value.
        N)ra)rZ	predicate�resultrrr�wait_for�s
zCondition.wait_forrcCsJ|��std��d}|jD]*}||kr*qF|��s|d7}|�d�qdS)aBy default, wake up one coroutine waiting on this condition, if any.
        If the calling coroutine has not acquired the lock when this method
        is called, a RuntimeError is raised.

        This method wakes up at most n of the coroutines waiting for the
        condition variable; it is a no-op if no coroutines are waiting.

        Note: an awakened coroutine does not actually return from its
        wait() call until it can reacquire the lock. Since notify() does
        not release the lock, its caller should.
        z!cannot notify on un-acquired lockrrFN)r;rr5rYrZ)r�n�idxrUrrr�notify�s
zCondition.notifycCs|�t|j��dS)aWake up all threads waiting on this condition. This method acts
        like notify(), but wakes up all waiting threads instead of one. If the
        calling thread has not acquired the lock when this method is called,
        a RuntimeError is raised.
        N)rgrCr5rrrr�
notify_all�szCondition.notify_all)N)r)rrrrrrBrardrgrhr[rrrFrr;s	%
rcsPeZdZdZddd�dd�Z�fdd�Zd	d
�Zdd�Zd
d�Zdd�Z	�Z
S)raA Semaphore implementation.

    A semaphore manages an internal counter which is decremented by each
    acquire() call and incremented by each release() call. The counter
    can never go below zero; when acquire() finds that it is zero, it blocks,
    waiting until some other thread calls release().

    Semaphores also support the context management protocol.

    The optional argument gives the initial value for the internal
    counter; it defaults to 1. If the value given is less than 0,
    ValueError is raised.
    rNr1cCsN|dkrtd��||_t��|_|dkr4t��|_n||_tj	dt
dd�dS)Nrz$Semaphore initial value must be >= 0r4r r!)rbr\rMrNr5rr7r8r#r$r%�r�valuer2rrrr�s
�zSemaphore.__init__csVt���}|��rdn
d|j��}|jr<|�dt|j���}d|dd��d|�d�S)	Nr;zunlocked, value:r<r=rr>r?r@)rArBr;r\r5rCrDrFrrrB�s

zSemaphore.__repr__cCs,|jr(|j��}|��s|�d�dSqdSr
)r5�popleftrYrZ)rZwaiterrrr�
_wake_up_next�s


zSemaphore._wake_up_nextcCs
|jdkS)z:Returns True if semaphore can not be acquired immediately.rr^rrrrr;�szSemaphore.lockedc�st|jdkrb|j��}|j�|�z|IdHWq|��|jdkrX|��sX|���YqXq|jd8_dS)a5Acquire a semaphore.

        If the internal counter is larger than zero on entry,
        decrement it by one and return True immediately.  If it is
        zero on entry, block, waiting until some other coroutine has
        called release() to make it larger than 0, and then return
        True.
        rNrT)r\r8rOr5rPZcancelrHrlrTrrrr&�s	


zSemaphore.acquirecCs|jd7_|��dS)z�Release a semaphore, incrementing the internal counter by one.
        When it was zero on entry and another coroutine is waiting for it to
        become larger than zero again, wake up that coroutine.
        rN)r\rlrrrrr�szSemaphore.release)r)rrrrrrBrlr;r&rr[rrrFrr�s
rcs4eZdZdZd	dd��fdd�Z�fdd�Z�ZS)
rz�A bounded semaphore implementation.

    This raises ValueError in release() if it would increase the value
    above the initial value.
    rNr1cs.|rtjdtdd�||_t�j||d�dS)Nr4r r!r1)r#r$r%�_bound_valuerArrirFrrr
s�zBoundedSemaphore.__init__cs"|j|jkrtd��t���dS)Nz(BoundedSemaphore released too many times)r\rmrbrArrrFrrrszBoundedSemaphore.release)r)rrrrrrr[rrrFrrs	r)r�__all__rMr/r#�rr	r
rrrrrrrrrrrr�<module>s "9DzNPK [�5BB)__pycache__/__main__.cpython-38.opt-2.pycnu�[���U

e5d
�@sJddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZGdd�dej�Z
Gdd�dej�Zedk�rFe��Ze�e�d	eiZd
D]Ze�eee<q�e
ee�ZdadazddlZWnek
r�YnXe�Zde_e��ze��Wn6e k
�r>t�r6t�!��s6t�"�daYq�Yq�X�qFq�dS)
�N�)�futurescs$eZdZ�fdd�Zdd�Z�ZS)�AsyncIOInteractiveConsolecs*t��|�|jjjtjO_||_dS)N)�super�__init__�compileZcompiler�flags�astZPyCF_ALLOW_TOP_LEVEL_AWAIT�loop)�self�localsr
��	__class__��(/usr/lib64/python3.8/asyncio/__main__.pyrsz"AsyncIOInteractiveConsole.__init__csttj������fdd�}t�|�z
���WStk
rD�Yn,tk
rntrb��	d�n��
�YnXdS)Nc
sdadat���j�}z
|�}Wnztk
r6�Ynftk
rj}zda��|�WY�dSd}~XYn2tk
r�}z��|�WY�dSd}~XYnXt	�
|�s���|�dSz�j�
|�at�t��Wn.tk
�r�}z��|�W5d}~XYnXdS)NFT)�repl_future�repl_future_interrupted�types�FunctionTyper�
SystemExit�KeyboardInterruptZ
set_exception�
BaseException�inspectZiscoroutineZ
set_resultr
Zcreate_taskrZ
_chain_future)�func�coroZex�exc��codeZfuturerrr�callbacks,




z3AsyncIOInteractiveConsole.runcode.<locals>.callbackz
KeyboardInterrupt
)�
concurrentrZFuturer
�call_soon_threadsafe�resultrrr�writeZ
showtraceback)rrrrrr�runcodes


z!AsyncIOInteractiveConsole.runcode)�__name__�
__module__�__qualname__rr#�
__classcell__rrr
rrsrc@seZdZdd�ZdS)�
REPLThreadcCsZz6dtj�dtj�dt	tdd��d	�}t
j|d
d�W5tjddtd�t�tj�XdS)N�ignorez ^coroutine .* was never awaited$)�message�categoryz
asyncio REPL z on zy
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
Zps1z>>> zimport asynciozexiting asyncio REPL...)�bannerZexitmsg)�warnings�filterwarnings�RuntimeWarningr
r �stop�sys�version�platform�getattr�consoleZinteract)rr,rrr�runFs"��
�zREPLThread.runN)r$r%r&r6rrrrr(Dsr(�__main__�asyncio>�__builtins__�__spec__r$�__file__�
__loader__�__package__FT)#r	r8rZconcurrent.futuresrrr1Z	threadingrr-�rZInteractiveConsolerZThreadr(r$Znew_event_loopr
Zset_event_loopZrepl_locals�keyrr5rr�readline�ImportErrorZrepl_threadZdaemon�startZrun_foreverrZdoneZcancelrrrr�<module>sF6



PK [���kk*__pycache__/staggered.cpython-38.opt-1.pycnu�[���U

e5dh�
@s�dZdZddlZddlZddlmZddlmZddlmZddlm	Z	dd	�ej
ejgejfej
eejejejej
eejej
efd
�dd�ZdS)
zFSupport for running coroutines in parallel with staggered start times.)�staggered_race�N�)�events)�
exceptions)�locks)�tasks)�loop)�coro_fns�delayr�returnc	�s��p
t���t|��d�d�g�g�tjtjdd���������fdd�����d��}��|�z<d}|t
��kr�t���IdH\}}t
|�}ql���fW�S�D]}|�	�q�XdS)a�Run coroutines with staggered start times and take the first to finish.

    This method takes an iterable of coroutine functions. The first one is
    started immediately. From then on, whenever the immediately preceding one
    fails (raises an exception), or when *delay* seconds has passed, the next
    coroutine is started. This continues until one of the coroutines complete
    successfully, in which case all others are cancelled, or until all
    coroutines fail.

    The coroutines provided should be well-behaved in the following way:

    * They should only ``return`` if completed successfully.

    * They should always raise an exception if they did not complete
      successfully. In particular, if they handle cancellation, they should
      probably reraise, like this::

        try:
            # do work
        except asyncio.CancelledError:
            # undo partially completed work
            raise

    Args:
        coro_fns: an iterable of coroutine functions, i.e. callables that
            return a coroutine object when called. Use ``functools.partial`` or
            lambdas to pass arguments.

        delay: amount of time, in seconds, between starting coroutines. If
            ``None``, the coroutines will run sequentially.

        loop: the event loop to use.

    Returns:
        tuple *(winner_result, winner_index, exceptions)* where

        - *winner_result*: the result of the winning coroutine, or ``None``
          if no coroutines won.

        - *winner_index*: the index of the winning coroutine in
          ``coro_fns``, or ``None`` if no coroutines won. If the winning
          coroutine may return None on success, *winner_index* can be used
          to definitively determine whether any coroutine won.

        - *exceptions*: list of exceptions returned by the coroutines.
          ``len(exceptions)`` is equal to the number of coroutines actually
          started, and the order is the same as in ``coro_fns``. The winning
          coroutine's entry is ``None``.

    N)�previous_failedrc	
�s|dk	r6t�tj��t�|����IdHW5QRXzt��\}}Wntk
r\YdSXt	�
�}���|��}��|���d�z|�IdH}WnJt
tfk
r��Yn\tk
r�}z|�|<|��W5d}~XYn,X|�|�t��D]\}}||kr�|��q�dS)N)�
contextlib�suppress�exceptions_mod�TimeoutErrorrZwait_for�wait�next�
StopIterationr�Event�create_task�append�
SystemExit�KeyboardInterrupt�
BaseException�set�	enumerate�cancel)	rZ
this_indexZcoro_fnZthis_failedZ	next_task�result�e�i�t�r
Z
enum_coro_fnsrr�run_one_coroZ
running_tasksZwinner_indexZ
winner_result��)/usr/lib64/python3.8/asyncio/staggered.pyr"Rs. 

z$staggered_race.<locals>.run_one_coror)
rZget_running_loopr�typing�Optionalrrrrr�lenrr)r	r
rZ
first_taskr Z
done_countZdone�_r#r!r$rs(=
�0
r)�__doc__�__all__r
r%�rrrrr�Iterable�Callable�	Awaitabler&�floatZAbstractEventLoopZTupleZAny�intZList�	Exceptionrr#r#r#r$�<module>s&����PK [��,�*__pycache__/staggered.cpython-38.opt-2.pycnu�[���U

e5dh�
@s�dZddlZddlZddlmZddlmZddlmZddlmZdd�ej	ej
gejfeje
ejejejejeejejefd	�d
d�ZdS))�staggered_race�N�)�events)�
exceptions)�locks)�tasks)�loop)�coro_fns�delayr�returnc	�s��p
t���t|��d�d�g�g�tjtjdd���������fdd�����d��}��|�z<d}|t
��kr�t���IdH\}}t
|�}ql���fW�S�D]}|�	�q�XdS)N)�previous_failedrc	
�s|dk	r6t�tj��t�|����IdHW5QRXzt��\}}Wntk
r\YdSXt	�
�}���|��}��|���d�z|�IdH}WnJt
tfk
r��Yn\tk
r�}z|�|<|��W5d}~XYn,X|�|�t��D]\}}||kr�|��q�dS)N)�
contextlib�suppress�exceptions_mod�TimeoutErrorrZwait_for�wait�next�
StopIterationr�Event�create_task�append�
SystemExit�KeyboardInterrupt�
BaseException�set�	enumerate�cancel)	rZ
this_indexZcoro_fnZthis_failedZ	next_task�result�e�i�t�r
Z
enum_coro_fnsrr�run_one_coroZ
running_tasksZwinner_indexZ
winner_result��)/usr/lib64/python3.8/asyncio/staggered.pyr"Rs. 

z$staggered_race.<locals>.run_one_coror)
rZget_running_loopr�typing�Optionalrrrrr�lenrr)r	r
rZ
first_taskr Z
done_countZdone�_r#r!r$rs(=
�0
r)�__all__r
r%�rrrrr�Iterable�Callable�	Awaitabler&�floatZAbstractEventLoopZTupleZAny�intZList�	Exceptionrr#r#r#r$�<module>s$����PK [�N&%__pycache__/coroutines.cpython-38.pycnu�[���U

e5d]"�@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddlmZdd	�Ze�ZGd
d�d�Zdd
�Ze�Zdd�ZejejejjefZe�Zdd�Zdd�ZdS))�	coroutine�iscoroutinefunction�iscoroutine�N�)�base_futures)�	constants)�format_helpers)�loggercCs"tjjp tjjo ttj�d��S)NZPYTHONASYNCIODEBUG)�sys�flags�dev_mode�ignore_environment�bool�os�environ�get�rr�*/usr/lib64/python3.8/asyncio/coroutines.py�_is_debug_modes�rc@s�eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zddd
�Zdd�Z	e
dd��Ze
dd��Ze
dd��Z
dd�Ze
dd��Zdd�ZdS)�CoroWrapperNcCsZt�|�st�|�st|��||_||_t�t�	d��|_
t|dd�|_t|dd�|_
dS)Nr�__name__�__qualname__)�inspect�isgeneratorr�AssertionError�gen�funcr�
extract_stackr
�	_getframe�_source_traceback�getattrrr)�selfrrrrr�__init__'szCoroWrapper.__init__cCsJt|�}|jr4|jd}|d|d�d|d��7}d|jj�d|�d�S)	N���z
, created at r�:r�<� �>)�_format_coroutiner�	__class__r)r!�	coro_repr�framerrr�__repr__/s

zCoroWrapper.__repr__cCs|S�Nr�r!rrr�__iter__7szCoroWrapper.__iter__cCs|j�d�Sr-�r�sendr.rrr�__next__:szCoroWrapper.__next__cCs|j�|�Sr-r0)r!�valuerrrr1=szCoroWrapper.sendcCs|j�|||�Sr-)r�throw)r!�typer3�	tracebackrrrr4@szCoroWrapper.throwcCs
|j��Sr-)r�closer.rrrr7CszCoroWrapper.closecCs|jjSr-)r�gi_framer.rrrr8FszCoroWrapper.gi_framecCs|jjSr-)r�
gi_runningr.rrrr9JszCoroWrapper.gi_runningcCs|jjSr-)r�gi_coder.rrrr:NszCoroWrapper.gi_codecCs|Sr-rr.rrr�	__await__RszCoroWrapper.__await__cCs|jjSr-)r�gi_yieldfromr.rrrr<UszCoroWrapper.gi_yieldfromcCs�t|dd�}t|dd�}|dk	r||jdkr||�d�}t|dd�}|rrd�t�|��}|dtj�d	�7}||��7}t�	|�dS)
Nrr8r#z was never yielded fromrr�zB
Coroutine object created at (most recent call last, truncated to z last lines):
)
r �f_lasti�joinr6�format_listrZDEBUG_STACK_DEPTH�rstripr	�error)r!rr+�msg�tbrrr�__del__Ys
zCoroWrapper.__del__)N)NN)r�
__module__rr"r,r/r2r1r4r7�propertyr8r9r:r;r<rErrrrr$s"





rcsztjdtdd�t���r�St���r.��nt����fdd���t�	���t
sX�}nt�����fdd��}t|_|S)z�Decorator to mark coroutines.

    If the coroutine is not yielded from before it is destroyed,
    an error message is logged.
    zN"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead�)�
stacklevelc?sr�||�}t�|�s(t�|�s(t|t�r4|EdH}n:z
|j}Wntk
rRYnXt|tj	j
�rn|�EdH}|Sr-)rZisfuturerr�
isinstancerr;�AttributeError�collections�abc�	Awaitable)�args�kw�resZ
await_meth�rrr�corozs
�
zcoroutine.<locals>.corocs@t�||��d�}|jr |jd=t�dd�|_t�dd�|_|S)NrRr#rr)rrr rr)rO�kwds�w�rSrrr�wrapper�szcoroutine.<locals>.wrapper)�warnings�warn�DeprecationWarningrr�isgeneratorfunction�	functools�wraps�typesr�_DEBUG�
_is_coroutine)rrWrrVrris"�


rcCst�|�pt|dd�tkS)z6Return True if func is a decorated coroutine function.r`N)rrr r`rRrrrr�s
�rcCs@t|�tkrdSt|t�r8tt�dkr4t�t|��dSdSdS)z)Return True if obj is a coroutine object.T�dFN)r5�_iscoroutine_typecacherJ�_COROUTINE_TYPES�len�add)�objrrrr�s
rc
stt|�st�t|t���fdd�}dd�}d}t|d�rF|jrF|j}nt|d�r\|jr\|j}||�}|s~||�rz|�d�S|Sd}t|d�r�|jr�|j}nt|d	�r�|jr�|j}|j	p�d
}d}��r0|j
dk	�r0t�|j
��s0t
�|j
�}|dk	r�|\}}|dk�r|�d|�d
|��}	n|�d|�d
|��}	n@|dk	�rV|j}|�d|�d
|��}	n|j}|�d|�d
|��}	|	S)Ncs`�rt�|jdi�St|d�r,|jr,|j}n*t|d�rD|jrD|j}ndt|�j�d�}|�d�S)Nrrrr%z without __name__>z())rZ_format_callbackr�hasattrrrr5)rS�	coro_name�Zis_corowrapperrr�get_name�sz#_format_coroutine.<locals>.get_namecSsHz|jWStk
rBz|jWYStk
r<YYdSXYnXdS)NF)�
cr_runningrKr9)rSrrr�
is_running�sz%_format_coroutine.<locals>.is_running�cr_coder:z runningr8�cr_framez<empty co_filename>rz done, defined at r$z running, defined at z running at )rrrJrrgrmr:r8rn�co_filenamerrr[rZ_get_function_source�f_lineno�co_firstlineno)
rSrjrlZ	coro_coderhZ
coro_frame�filename�lineno�sourcer*rrirr(�sL
	

�
�

r() �__all__Zcollections.abcrLr\rrr
r6r^rXr=rrr�logr	rr_rr�objectr`r�
CoroutineType�
GeneratorTyperM�	Coroutinerc�setrbrr(rrrr�<module>s2E8�PK [˼��-�-�,__pycache__/unix_events.cpython-38.opt-1.pycnu�[���U

e5dۿ�@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
mZddl
mZddl
mZddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddl
mZdd
l
mZddlmZdZe
jdkr�ed��dd�ZGdd�dej�ZGdd�dej �Z!Gdd�dej"ej#�Z$Gdd�dej%�Z&Gdd�d�Z'dd�Z(Gd d!�d!e'�Z)Gd"d#�d#e)�Z*Gd$d%�d%e)�Z+Gd&d'�d'e'�Z,Gd(d)�d)e'�Z-Gd*d+�d+ej.�Z/eZ0e/Z1dS),z2Selector event loop for Unix with signal handling.�N�)�base_events)�base_subprocess)�	constants)�
coroutines)�events)�
exceptions)�futures)�selector_events)�tasks)�
transports)�logger)�SelectorEventLoop�AbstractChildWatcher�SafeChildWatcher�FastChildWatcher�MultiLoopChildWatcher�ThreadedChildWatcher�DefaultEventLoopPolicyZwin32z+Signals are not really supported on WindowscCsdS)zDummy signal handler.N�)�signum�framerr�+/usr/lib64/python3.8/asyncio/unix_events.py�_sighandler_noop*srcs�eZdZdZd)�fdd�	Z�fdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
d*dd�Zd+dd�Zd,dd�Z
dd�Zd-ddddd�dd�Zd.dddddd�dd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Z�ZS)/�_UnixSelectorEventLoopzdUnix event loop.

    Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
    Ncst��|�i|_dS�N)�super�__init__�_signal_handlers)�self�selector��	__class__rrr5sz_UnixSelectorEventLoop.__init__csZt���t��s.t|j�D]}|�|�qn(|jrVtjd|�d�t	|d�|j�
�dS)NzClosing the loop z@ on interpreter shutdown stage, skipping signal handlers removal��source)r�close�sys�
is_finalizing�listr�remove_signal_handler�warnings�warn�ResourceWarning�clear�r�sigr!rrr%9s
�z_UnixSelectorEventLoop.closecCs|D]}|sq|�|�qdSr)�_handle_signal)r�datarrrr�_process_self_dataGsz)_UnixSelectorEventLoop._process_self_datac
GsLt�|�st�|�rtd��|�|�|��zt�|j�	��Wn2t
tfk
rt}ztt
|���W5d}~XYnXt�|||d�}||j|<zt�|t�t�|d�Wn�tk
�rF}zz|j|=|j�szt�d�Wn4t
tfk
�r}zt�d|�W5d}~XYnX|jtjk�r4td|�d���n�W5d}~XYnXdS)z�Add a handler for a signal.  UNIX only.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        z3coroutines cannot be used with add_signal_handler()NF����set_wakeup_fd(-1) failed: %s�sig � cannot be caught)rZiscoroutineZiscoroutinefunction�	TypeError�
_check_signalZ
_check_closed�signal�
set_wakeup_fdZ_csock�fileno�
ValueError�OSError�RuntimeError�strrZHandlerr�siginterruptr
�info�errno�EINVAL)rr/�callback�args�exc�handleZnexcrrr�add_signal_handlerNs2
�

z)_UnixSelectorEventLoop.add_signal_handlercCs8|j�|�}|dkrdS|jr*|�|�n
|�|�dS)z2Internal helper that is the actual signal handler.N)r�getZ
_cancelledr)Z_add_callback_signalsafe)rr/rGrrrr0{sz%_UnixSelectorEventLoop._handle_signalc
Cs�|�|�z|j|=Wntk
r,YdSX|tjkr@tj}ntj}zt�||�WnBtk
r�}z$|jtj	kr�t
d|�d���n�W5d}~XYnX|js�zt�d�Wn2ttfk
r�}zt
�d|�W5d}~XYnXdS)zwRemove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        Fr5r6Nr3r4T)r8r�KeyErrorr9�SIGINT�default_int_handler�SIG_DFLr=rBrCr>r:r<r
rA)rr/�handlerrFrrrr)�s(

z,_UnixSelectorEventLoop.remove_signal_handlercCs6t|t�std|����|t��kr2td|����dS)z�Internal helper to validate a signal.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        zsig must be an int, not zinvalid signal number N)�
isinstance�intr7r9�
valid_signalsr<r.rrrr8�s
z$_UnixSelectorEventLoop._check_signalcCst|||||�Sr)�_UnixReadPipeTransport�r�pipe�protocol�waiter�extrarrr�_make_read_pipe_transport�sz0_UnixSelectorEventLoop._make_read_pipe_transportcCst|||||�Sr)�_UnixWritePipeTransportrSrrr�_make_write_pipe_transport�sz1_UnixSelectorEventLoop._make_write_pipe_transportc	

�s�t����}
|
��std��|��}t||||||||f||d�|	��}|
�|��|j|�z|IdHWnDt	t
fk
r��Yn,tk
r�|��|�
�IdH�YnXW5QRX|S)NzRasyncio.get_child_watcher() is not activated, subprocess support is not installed.)rVrW)r�get_child_watcher�	is_activer>�
create_future�_UnixSubprocessTransport�add_child_handlerZget_pid�_child_watcher_callback�
SystemExit�KeyboardInterrupt�
BaseExceptionr%Z_wait)
rrUrE�shell�stdin�stdout�stderr�bufsizerW�kwargs�watcherrV�transprrr�_make_subprocess_transport�s8

���
�z1_UnixSelectorEventLoop._make_subprocess_transportcCs|�|j|�dSr)�call_soon_threadsafeZ_process_exited)r�pid�
returncoderkrrrr`�sz._UnixSelectorEventLoop._child_watcher_callback)�ssl�sock�server_hostname�ssl_handshake_timeoutc	�s
|r|dkr6td��n |dk	r&td��|dk	r6td��|dk	r�|dk	rNtd��t�|�}t�tjtjd�}z |�d�|�||�IdHWq�|���Yq�Xn@|dkr�td��|j	tjks�|j
tjkr�td|����|�d�|j|||||d	�IdH\}}||fS)
Nz/you have to pass server_hostname when using sslz+server_hostname is only meaningful with ssl�1ssl_handshake_timeout is only meaningful with ssl�3path and sock can not be specified at the same timerFzno path and sock were specified�.A UNIX Domain Stream Socket was expected, got )rs)r<�os�fspath�socket�AF_UNIX�SOCK_STREAM�setblockingZsock_connectr%�family�typeZ_create_connection_transport)	r�protocol_factory�pathrprqrrrs�	transportrUrrr�create_unix_connection�sR���



��
�z-_UnixSelectorEventLoop.create_unix_connection�dT)rq�backlogrprs�
start_servingc
�s�t|t�rtd��|dk	r&|s&td��|dk	�rH|dk	r@td��t�|�}t�tjtj�}|ddkr�z t	�
t�	|�j�r�t�|�WnBt
k
r�Yn0tk
r�}zt�d||�W5d}~XYnXz|�|�Wnltk
�r0}	z8|��|	jtjk�rd|�d�}
ttj|
�d�n�W5d}	~	XYn|���YnXn<|dk�rZtd	��|jtjk�sv|jtjk�r�td
|����|�d�t�||g||||�}|�r�|��tjd|d�IdH|S)
Nz*ssl argument must be an SSLContext or Nonertrur)r�z2Unable to check or remove stale UNIX socket %r: %rzAddress z is already in usez-path was not specified, and no sock specifiedrvF)�loop)rO�boolr7r<rwrxryrzr{�stat�S_ISSOCK�st_mode�remove�FileNotFoundErrorr=r
�errorZbindr%rBZ
EADDRINUSEr}r~r|rZServerZ_start_servingr�sleep)rrr�rqr�rprsr��errrF�msgZserverrrr�create_unix_serversn
�
�
�

�
��
�z)_UnixSelectorEventLoop.create_unix_serverc
�s�z
tjWn,tk
r6}zt�d��W5d}~XYnXz|��}Wn2ttjfk
rv}zt�d��W5d}~XYnXzt�|�j	}Wn,t
k
r�}zt�d��W5d}~XYnX|r�|n|}	|	s�dS|��}
|�|
d|||||	d�|
IdHS)Nzos.sendfile() is not availableznot a regular filer)
rw�sendfile�AttributeErrorr�SendfileNotAvailableErrorr;�io�UnsupportedOperation�fstat�st_sizer=r]�_sock_sendfile_native_impl)rrq�file�offset�countrFr;r�Zfsize�	blocksize�futrrr�_sock_sendfile_nativeJs2
��z,_UnixSelectorEventLoop._sock_sendfile_nativec	Cs,|��}	|dk	r|�|�|��r4|�|||�dS|rd||}|dkrd|�|||�|�|�dSzt�|	|||�}
W�nDttfk
r�|dkr�|�	||�|�
|	|j||	||||||�
Y�nbtk
�rj}z�|dk	�r|j
t
jk�rt|�tk	�rtdt
j�}||_|}|dk�rBt�d�}
|�|||�|�|
�n|�|||�|�|�W5d}~XYn�ttfk
�r��Yn�tk
�r�}z|�|||�|�|�W5d}~XYnjX|
dk�r�|�|||�|�|�nD||
7}||
7}|dk�r
|�	||�|�
|	|j||	||||||�
dS)Nrzsocket is not connectedzos.sendfile call failed)r;�
remove_writer�	cancelled�_sock_sendfile_update_fileposZ
set_resultrwr��BlockingIOError�InterruptedError�_sock_add_cancellation_callbackZ
add_writerr�r=rBZENOTCONNr~�ConnectionError�	__cause__rr�Z
set_exceptionrarbrc)rr�Z
registered_fdrqr;r�r�r��
total_sent�fdZsentrF�new_excr�rrrr�as�

�


�
��
�

�z1_UnixSelectorEventLoop._sock_sendfile_native_implcCs|dkrt�||tj�dS�Nr)rw�lseek�SEEK_SET)rr;r�r�rrrr��sz4_UnixSelectorEventLoop._sock_sendfile_update_fileposcs��fdd�}|�|�dS)Ncs&|��r"���}|dkr"��|�dS)Nr3)r�r;r�)r�r��rrqrr�cb�szB_UnixSelectorEventLoop._sock_add_cancellation_callback.<locals>.cb)Zadd_done_callback)rr�rqr�rr�rr��sz6_UnixSelectorEventLoop._sock_add_cancellation_callback)N)NN)NN)N)N)N)�__name__�
__module__�__qualname__�__doc__rr%r2rHr0r)r8rXrZrlr`r�r�r�r�r�r��
__classcell__rrr!rr/sH-
 �
�
�
��.��CFrcs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Ze
jfdd�Zddd�Zdd�Zdd�Z�ZS) rRiNcs�t��|�||jd<||_||_|��|_||_d|_d|_	t
�|j�j}t
�|�s�t
�|�s�t
�|�s�d|_d|_d|_td��t
�|jd�|j�|jj|�|j�|jj|j|j�|dk	r�|j�tj|d�dS)NrTFz)Pipe transport is for pipes/sockets only.)rr�_extra�_loop�_piper;�_fileno�	_protocol�_closing�_pausedrwr�r�r��S_ISFIFOr��S_ISCHRr<�set_blocking�	call_soon�connection_made�_add_reader�_read_readyr	�_set_result_unless_cancelled)rr�rTrUrVrW�moder!rrr�s:


���
�z_UnixReadPipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���t|jdd�}|jdk	r�|dk	r�t�	||jt
j�}|r�|�d�q�|�d�n |jdk	r�|�d�n
|�d�d�d	�
|��S)
N�closed�closing�fd=�	_selector�polling�idle�open�<{}>� )r"r�r��appendr�r��getattrr�r
�_test_selector_event�	selectorsZ
EVENT_READ�format�join)rrAr r�rrr�__repr__�s(


�

z_UnixReadPipeTransport.__repr__c
Cs�zt�|j|j�}WnDttfk
r,Yn�tk
rX}z|�|d�W5d}~XYn^X|rl|j�	|�nJ|j
��r�t�
d|�d|_|j
�|j�|j
�|jj�|j
�|jd�dS)Nz"Fatal read error on pipe transport�%r was closed by peerT)rw�readr��max_sizer�r�r=�_fatal_errorr�Z
data_receivedr��	get_debugr
rAr��_remove_readerr�Zeof_received�_call_connection_lost)rr1rFrrrr��s
z"_UnixReadPipeTransport._read_readycCs>|js|jrdSd|_|j�|j�|j��r:t�d|�dS)NTz%r pauses reading)r�r�r�r�r�r�r
�debug�rrrr�
pause_reading�s
z$_UnixReadPipeTransport.pause_readingcCsB|js|jsdSd|_|j�|j|j�|j��r>t�d|�dS)NFz%r resumes reading)	r�r�r�r�r�r�r�r
r�r�rrr�resume_readings
z%_UnixReadPipeTransport.resume_readingcCs
||_dSr�r��rrUrrr�set_protocol
sz#_UnixReadPipeTransport.set_protocolcCs|jSrr�r�rrr�get_protocolsz#_UnixReadPipeTransport.get_protocolcCs|jSr�r�r�rrr�
is_closingsz!_UnixReadPipeTransport.is_closingcCs|js|�d�dSr)r��_closer�rrrr%sz_UnixReadPipeTransport.closecCs,|jdk	r(|d|��t|d�|j��dS�Nzunclosed transport r#�r�r,r%�r�_warnrrr�__del__s
z_UnixReadPipeTransport.__del__�Fatal error on pipe transportcCsZt|t�r4|jtjkr4|j��rLtjd||dd�n|j�||||j	d��|�
|�dS�Nz%r: %sT��exc_info)�message�	exceptionr�rU)rOr=rBZEIOr�r�r
r��call_exception_handlerr�r��rrFr�rrrr�s
�z#_UnixReadPipeTransport._fatal_errorcCs(d|_|j�|j�|j�|j|�dS�NT)r�r�r�r�r�r��rrFrrrr�-sz_UnixReadPipeTransport._closecCs4z|j�|�W5|j��d|_d|_d|_XdSr�r�r%r�r�Zconnection_lostr�rrrr�2s
z,_UnixReadPipeTransport._call_connection_lost)NN)r�)r�r�r�r�rr�r�r�r�r�r�r�r%r*r+r�r�r�r�r�rrr!rrR�s
rRcs�eZdZd%�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zejfdd�Zdd�Zd&dd �Zd'd!d"�Zd#d$�Z�ZS)(rYNc
s�t��||�||jd<||_|��|_||_t�|_d|_	d|_
t�|j�j
}t�|�}t�|�}t�|�}	|s�|s�|	s�d|_d|_d|_td��t�|jd�|j�|jj|�|	s�|r�tj�d�s�|j�|jj|j|j�|dk	r�|j�tj|d�dS)NrTrFz?Pipe transport is only for pipes, sockets and character devicesZaix)rrr�r�r;r�r��	bytearray�_buffer�
_conn_lostr�rwr�r�r�r�r�r�r<r�r�r�r�r&�platform�
startswithr�r�r	r�)
rr�rTrUrVrWr�Zis_charZis_fifoZ	is_socketr!rrr?s:




�
�z _UnixWritePipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���t|jdd�}|jdk	r�|dk	r�t�	||jt
j�}|r�|�d�n
|�d�|��}|�d|���n |jdk	r�|�d�n
|�d�d	�
d
�|��S)Nr�r�r�r�r�r�zbufsize=r�r�r�)r"r�r�r�r�r�r�r�r
r�r�ZEVENT_WRITE�get_write_buffer_sizer�r�)rrAr r�rhrrrr�ds,


�


z _UnixWritePipeTransport.__repr__cCs
t|j�Sr)�lenr�r�rrrr�|sz-_UnixWritePipeTransport.get_write_buffer_sizecCs6|j��rt�d|�|jr*|�t��n|��dS)Nr�)r�r�r
rAr�r��BrokenPipeErrorr�rrrr�s

z#_UnixWritePipeTransport._read_readyc
Cs4t|t�rt|�}|sdS|js&|jrN|jtjkr<t�d�|jd7_dS|j	�szt
�|j|�}Wntt
tfk
r�d}YnZttfk
r��YnBtk
r�}z$|jd7_|�|d�WY�dSd}~XYnX|t|�kr�dS|dk�rt|�|d�}|j�|j|j�|j	|7_	|��dS)Nz=pipe closed by peer or os.write(pipe, data) raised exception.rr�#Fatal write error on pipe transport)rOr��
memoryviewr�r�rZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningr�rw�writer�r�r�rarbrcr�r�r�Z_add_writer�_write_readyZ_maybe_pause_protocol)rr1�nrFrrrr�s6


z_UnixWritePipeTransport.writec
Cszt�|j|j�}Wn�ttfk
r,Yn�ttfk
rD�Yn�tk
r�}z6|j�	�|j
d7_
|j�|j�|�
|d�W5d}~XYnfX|t|j�kr�|j�	�|j�|j�|��|jr�|j�|j�|�d�dS|dkr�|jd|�=dS)Nrrr)rwrr�r�r�r�rarbrcr-r�r��_remove_writerr�r�Z_maybe_resume_protocolr�r�r�)rrrFrrrr�s*


z$_UnixWritePipeTransport._write_readycCsdSr�rr�rrr�
can_write_eof�sz%_UnixWritePipeTransport.can_write_eofcCs8|jr
dSd|_|js4|j�|j�|j�|jd�dSr�)r�r�r�r�r�r�r�r�rrr�	write_eof�sz!_UnixWritePipeTransport.write_eofcCs
||_dSrr�r�rrrr��sz$_UnixWritePipeTransport.set_protocolcCs|jSrr�r�rrrr��sz$_UnixWritePipeTransport.get_protocolcCs|jSrr�r�rrrr��sz"_UnixWritePipeTransport.is_closingcCs|jdk	r|js|��dSr)r�r�rr�rrrr%�sz_UnixWritePipeTransport.closecCs,|jdk	r(|d|��t|d�|j��dSr�r�r�rrrr��s
z_UnixWritePipeTransport.__del__cCs|�d�dSr)r�r�rrr�abort�sz_UnixWritePipeTransport.abortr�cCsNt|t�r(|j��r@tjd||dd�n|j�||||jd��|�|�dSr�)	rOr=r�r�r
r�r�r�r�r�rrrr��s

�z$_UnixWritePipeTransport._fatal_errorcCsFd|_|jr|j�|j�|j��|j�|j�|j�|j|�dSr�)	r�r�r�rr�r-r�r�r�r�rrrr��s
z_UnixWritePipeTransport._closecCs4z|j�|�W5|j��d|_d|_d|_XdSrr�r�rrrr��s
z-_UnixWritePipeTransport._call_connection_lost)NN)r�)N)r�r�r�rr�r�r�rrrrr�r�r�r%r*r+r�r	r�r�r�r�rrr!rrY<s"%	#	

rYc@seZdZdd�ZdS)r^c		Ks�d}|tjkrt��\}}zPtj|f||||d|d�|��|_|dk	rh|��t|��d|d�|j_	d}W5|dk	r�|��|��XdS)NF)rdrerfrgZuniversal_newlinesrh�wb)�	buffering)
�
subprocess�PIPEryZ
socketpairr%�Popen�_procr��detachre)	rrErdrerfrgrhriZstdin_wrrr�_starts.
���z_UnixSubprocessTransport._startN)r�r�r�rrrrrr^	sr^c@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)raHAbstract base class for monitoring child processes.

    Objects derived from this class monitor a collection of subprocesses and
    report their termination or interruption by a signal.

    New callbacks are registered with .add_child_handler(). Starting a new
    process must be done within a 'with' block to allow the watcher to suspend
    its activity until the new process if fully registered (this is needed to
    prevent a race condition in some implementations).

    Example:
        with watcher:
            proc = subprocess.Popen("sleep 1")
            watcher.add_child_handler(proc.pid, callback)

    Notes:
        Implementations of this class must be thread-safe.

        Since child watcher objects may catch the SIGCHLD signal and call
        waitpid(-1), there should be only one active object per process.
    cGs
t��dS)aRegister a new child handler.

        Arrange for callback(pid, returncode, *args) to be called when
        process 'pid' terminates. Specifying another callback for the same
        process replaces the previous handler.

        Note: callback() must be thread-safe.
        N��NotImplementedError�rrnrDrErrrr_9s	z&AbstractChildWatcher.add_child_handlercCs
t��dS)z�Removes the handler for process 'pid'.

        The function returns True if the handler was successfully removed,
        False if there was nothing to remove.Nr�rrnrrr�remove_child_handlerDsz)AbstractChildWatcher.remove_child_handlercCs
t��dS)z�Attach the watcher to an event loop.

        If the watcher was previously attached to an event loop, then it is
        first detached before attaching to the new loop.

        Note: loop may be None.
        Nr�rr�rrr�attach_loopLsz AbstractChildWatcher.attach_loopcCs
t��dS)zlClose the watcher.

        This must be called to make sure that any underlying resource is freed.
        Nrr�rrrr%VszAbstractChildWatcher.closecCs
t��dS)z�Return ``True`` if the watcher is active and is used by the event loop.

        Return True if the watcher is installed and ready to handle process exit
        notifications.

        Nrr�rrrr\]szAbstractChildWatcher.is_activecCs
t��dS)zdEnter the watcher's context and allow starting new processes

        This function must return selfNrr�rrr�	__enter__fszAbstractChildWatcher.__enter__cCs
t��dS)zExit the watcher's contextNr�r�a�b�crrr�__exit__lszAbstractChildWatcher.__exit__N)r�r�r�r�r_rrr%r\rrrrrrr"s
	rcCs2t�|�rt�|�St�|�r*t�|�S|SdSr)rw�WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS)�statusrrr�_compute_returncodeqs



r$c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�BaseChildWatchercCsd|_i|_dSr)r��
_callbacksr�rrrr�szBaseChildWatcher.__init__cCs|�d�dSr)rr�rrrr%�szBaseChildWatcher.closecCs|jdk	o|j��Sr)r�Z
is_runningr�rrrr\�szBaseChildWatcher.is_activecCs
t��dSrr)r�expected_pidrrr�_do_waitpid�szBaseChildWatcher._do_waitpidcCs
t��dSrrr�rrr�_do_waitpid_all�sz BaseChildWatcher._do_waitpid_allcCsf|jdk	r$|dkr$|jr$t�dt�|jdk	r<|j�tj�||_|dk	rb|�tj|j	�|�
�dS)NzCA loop is being detached from a child watcher with pending handlers)r�r&r*r+�RuntimeWarningr)r9�SIGCHLDrH�	_sig_chldr)rrrrr�s�
zBaseChildWatcher.attach_loopc
Cs^z|��WnLttfk
r&�Yn4tk
rX}z|j�d|d��W5d}~XYnXdS)N�$Unknown exception in SIGCHLD handler)r�r�)r)rarbrcr�r�r�rrrr,�s�zBaseChildWatcher._sig_chldN)
r�r�r�rr%r\r(r)rr,rrrrr%sr%csPeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)rad'Safe' child watcher implementation.

    This implementation avoids disrupting other code spawning processes by
    polling explicitly each process in the SIGCHLD handler instead of calling
    os.waitpid(-1).

    This is a safe solution but it has a significant overhead when handling a
    big number of children (O(n) each time SIGCHLD is raised)
    cs|j��t���dSr)r&r-rr%r�r!rrr%�s
zSafeChildWatcher.closecCs|Srrr�rrrr�szSafeChildWatcher.__enter__cCsdSrrrrrrr�szSafeChildWatcher.__exit__cGs||f|j|<|�|�dSr)r&r(rrrrr_�sz"SafeChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdS�NTF�r&rJrrrrr�s
z%SafeChildWatcher.remove_child_handlercCst|j�D]}|�|�q
dSr�r(r&r(rrrrr)�sz SafeChildWatcher._do_waitpid_allcCs�zt�|tj�\}}Wn(tk
r>|}d}t�d|�Yn.X|dkrLdSt|�}|j��rlt�	d||�z|j
�|�\}}Wn.tk
r�|j��r�tjd|dd�YnX|||f|��dS)N��8Unknown child process pid %d, will report returncode 255r�$process %s exited with returncode %s�'Child watcher got an unexpected pid: %rTr�)
rw�waitpid�WNOHANG�ChildProcessErrorr
rr$r�r�r�r&�poprJ)rr'rnr#rorDrErrrr(�s4�

�
�zSafeChildWatcher._do_waitpid)r�r�r�r�r%rrr_rr)r(r�rrr!rr�s
rcsTeZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)raW'Fast' child watcher implementation.

    This implementation reaps every terminated processes by calling
    os.waitpid(-1) directly, possibly breaking other code spawning processes
    and waiting for their termination.

    There is no noticeable overhead when handling a big number of children
    (O(1) each time a child terminates).
    cs$t���t��|_i|_d|_dSr�)rr�	threadingZLock�_lock�_zombies�_forksr�r!rrrs

zFastChildWatcher.__init__cs"|j��|j��t���dSr)r&r-r;rr%r�r!rrr%s

zFastChildWatcher.closec
Cs0|j� |jd7_|W5QR�SQRXdS)Nr)r:r<r�rrrrszFastChildWatcher.__enter__c	Cs^|j�B|jd8_|js"|js0W5QR�dSt|j�}|j��W5QRXt�d|�dS)Nrz5Caught subprocesses termination from unknown pids: %s)r:r<r;r?r-r
r)rrrrZcollateral_victimsrrrrs
�zFastChildWatcher.__exit__c	Gsf|j�Fz|j�|�}Wn.tk
rF||f|j|<YW5QR�dSXW5QRX|||f|��dSr)r:r;r8rJr&)rrnrDrErorrrr_'sz"FastChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdSr.r/rrrrr5s
z%FastChildWatcher.remove_child_handlerc	Cs�zt�dtj�\}}Wntk
r,YdSX|dkr:dSt|�}|j��z|j�|�\}}WnNtk
r�|j	r�||j
|<|j��r�t
�d||�YW5QR�qd}YnX|j��r�t
�d||�W5QRX|dkr�t
�d||�q|||f|��qdS)Nr3rz,unknown process %s exited with returncode %sr3z8Caught subprocess termination from unknown pid: %d -> %d)rwr5r6r7r$r:r&r8rJr<r;r�r�r
r�r)rrnr#rorDrErrrr)<s@

�

��z FastChildWatcher._do_waitpid_all)r�r�r�r�rr%rrr_rr)r�rrr!rr�s	rc@sheZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)ra~A watcher that doesn't require running loop in the main thread.

    This implementation registers a SIGCHLD signal handler on
    instantiation (which may conflict with other code that
    install own handler for this signal).

    The solution is safe but it has a significant overhead when
    handling a big number of processes (*O(n)* each time a
    SIGCHLD is received).
    cCsi|_d|_dSr)r&�_saved_sighandlerr�rrrrzszMultiLoopChildWatcher.__init__cCs
|jdk	Sr)r=r�rrrr\~szMultiLoopChildWatcher.is_activecCsT|j��|jdkrdSt�tj�}||jkr:t�d�nt�tj|j�d|_dS)Nz+SIGCHLD handler was changed by outside code)	r&r-r=r9�	getsignalr+r,r
r)rrNrrrr%�s


zMultiLoopChildWatcher.closecCs|Srrr�rrrr�szMultiLoopChildWatcher.__enter__cCsdSrr�r�exc_typeZexc_valZexc_tbrrrr�szMultiLoopChildWatcher.__exit__cGs&t��}|||f|j|<|�|�dSr)r�get_running_loopr&r()rrnrDrEr�rrrr_�sz'MultiLoopChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdSr.r/rrrrr�s
z*MultiLoopChildWatcher.remove_child_handlercCsN|jdk	rdSt�tj|j�|_|jdkr<t�d�tj|_t�tjd�dS)NzaPrevious SIGCHLD handler was set by non-Python code, restore to default handler on watcher close.F)r=r9r+r,r
rrMr@rrrrr�s


z!MultiLoopChildWatcher.attach_loopcCst|j�D]}|�|�q
dSrr0rrrrr)�sz%MultiLoopChildWatcher._do_waitpid_allc	Cs�zt�|tj�\}}Wn,tk
rB|}d}t�d|�d}YnX|dkrPdSt|�}d}z|j�|�\}}}Wn$t	k
r�tjd|dd�YnHX|�
�r�t�d||�n.|r�|��r�t�d	||�|j
|||f|��dS)
Nr1r2FrTr4r��%Loop %r that handles pid %r is closedr3)rwr5r6r7r
rr$r&r8rJ�	is_closedr�r�rm)	rr'rnr#roZ	debug_logr�rDrErrrr(�s:�
��z!MultiLoopChildWatcher._do_waitpidc	CsLz|��Wn:ttfk
r&�Yn"tk
rFtjddd�YnXdS)Nr-Tr�)r)rarbrcr
r)rrrrrrr,�szMultiLoopChildWatcher._sig_chldN)r�r�r�r�rr\r%rrr_rrr)r(r,rrrrrgs%rc@sneZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	e
jfdd�Zdd�Z
dd�Zdd�Zdd�ZdS)raAThreaded child watcher implementation.

    The watcher uses a thread per process
    for waiting for the process finish.

    It doesn't require subscription on POSIX signal
    but a thread creation is not free.

    The watcher has O(1) complexity, its performance doesn't depend
    on amount of spawn processes.
    cCst�d�|_i|_dSr�)�	itertoolsr��_pid_counter�_threadsr�rrrr�szThreadedChildWatcher.__init__cCsdSr�rr�rrrr\�szThreadedChildWatcher.is_activecCs|��dSr)�
_join_threadsr�rrrr%�szThreadedChildWatcher.closecCs.dd�t|j���D�}|D]}|��qdS)z%Internal: Join all non-daemon threadscSsg|]}|��r|js|�qSr)�is_alive�daemon��.0�threadrrr�
<listcomp>�s�z6ThreadedChildWatcher._join_threads.<locals>.<listcomp>N)r(rF�valuesr�)r�threadsrLrrrrG�sz"ThreadedChildWatcher._join_threadscCs|Srrr�rrrrszThreadedChildWatcher.__enter__cCsdSrrr?rrrrszThreadedChildWatcher.__exit__cCs6dd�t|j���D�}|r2||j�d�t|d�dS)NcSsg|]}|��r|�qSr)rHrJrrrrM	s�z0ThreadedChildWatcher.__del__.<locals>.<listcomp>z0 has registered but not finished child processesr#)r(rFrNr"r,)rr�rOrrrr�s�zThreadedChildWatcher.__del__cGsFt��}tj|jdt|j���||||fdd�}||j|<|��dS)Nzwaitpid-T)�target�namerErI)	rrAr9ZThreadr(�nextrErF�start)rrnrDrEr�rLrrrr_s
�
z&ThreadedChildWatcher.add_child_handlercCsdSr�rrrrrrsz)ThreadedChildWatcher.remove_child_handlercCsdSrrrrrrrsz ThreadedChildWatcher.attach_loopcCs�zt�|d�\}}Wn(tk
r<|}d}t�d|�Yn Xt|�}|��r\t�d||�|��rtt�d||�n|j	|||f|��|j
�|�dS)Nrr1r2r3rB)rwr5r7r
rr$r�r�rCrmrFr8)rr�r'rDrErnr#rorrrr("s&�
�z ThreadedChildWatcher._do_waitpidN)r�r�r�r�rr\r%rGrrr*r+r�r_rrr(rrrrr�s	rcsHeZdZdZeZ�fdd�Zdd�Z�fdd�Zdd	�Z	d
d�Z
�ZS)�_UnixDefaultEventLoopPolicyz:UNIX event loop policy with a watcher for child processes.cst���d|_dSr)rr�_watcherr�r!rrrAs
z$_UnixDefaultEventLoopPolicy.__init__c	CsHtj�8|jdkr:t�|_tt��tj�r:|j�|j	j
�W5QRXdSr)rr:rUrrOr9�current_thread�_MainThreadr�_localr�r�rrr�
_init_watcherEs
�z)_UnixDefaultEventLoopPolicy._init_watchercs6t��|�|jdk	r2tt��tj�r2|j�|�dS)z�Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        N)r�set_event_looprUrOr9rVrWrrr!rrrZMs

�z*_UnixDefaultEventLoopPolicy.set_event_loopcCs|jdkr|��|jS)z~Get the watcher for child processes.

        If not yet set, a ThreadedChildWatcher object is automatically created.
        N)rUrYr�rrrr[[s
z-_UnixDefaultEventLoopPolicy.get_child_watchercCs|jdk	r|j��||_dS)z$Set the watcher for child processes.N)rUr%)rrjrrr�set_child_watcheres

z-_UnixDefaultEventLoopPolicy.set_child_watcher)r�r�r�r�rZ
_loop_factoryrrYrZr[r[r�rrr!rrT=s
rT)2r�rBr�rDrwr�r9ryr�rr&r9r*�rrrrrrr	r
rr�logr
�__all__r��ImportErrorrZBaseSelectorEventLooprZ
ReadTransportrRZ_FlowControlMixinZWriteTransportrYZBaseSubprocessTransportr^rr$r%rrrrZBaseDefaultEventLoopPolicyrTrrrrrr�<module>s`	
	�NO5Ji}Y3PK [��?�? __pycache__/locks.cpython-38.pycnu�[���U

e5d|C�@s�dZdZddlZddlZddlZddlmZddlmZddlmZddlm	Z	Gd	d
�d
�Z
Gdd�d�ZGd
d�de�ZGdd�d�Z
Gdd�de�ZGdd�de�ZGdd�de�ZdS)zSynchronization primitives.)�Lock�Event�	Condition�	Semaphore�BoundedSemaphore�N�)�events)�futures)�
exceptions)�
coroutinesc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_ContextManagera\Context manager.

    This enables the following idiom for acquiring and releasing a
    lock around a block:

        with (yield from lock):
            <block>

    while failing loudly when accidentally using:

        with lock:
            <block>

    Deprecated, use 'async with' statement:
        async with lock:
            <block>
    cCs
||_dS�N)�_lock)�self�lock�r�%/usr/lib64/python3.8/asyncio/locks.py�__init__"sz_ContextManager.__init__cCsdSr
r�rrrr�	__enter__%sz_ContextManager.__enter__cGsz|j��W5d|_XdSr
)r�release�r�argsrrr�__exit__*sz_ContextManager.__exit__N)�__name__�
__module__�__qualname__�__doc__rrrrrrrrsrc@sReZdZdd�Zdd�Zejdd��Zej	e_	dd�Z
d	d
�Zdd�Zd
d�Z
dS)�_ContextManagerMixincCstd��dS)Nz9"yield from" should be used as context manager expression)�RuntimeErrorrrrrr2s�z_ContextManagerMixin.__enter__cGsdSr
rrrrrr6sz_ContextManagerMixin.__exit__ccs&tjdtdd�|��EdHt|�S)NzD'with (yield from lock)' is deprecated use 'async with lock' instead���
stacklevel)�warnings�warn�DeprecationWarning�acquirerrrrr�__iter__;s�z_ContextManagerMixin.__iter__c�s|��IdHt|�Sr
)r&rrrrrZ
__acquire_ctxUsz"_ContextManagerMixin.__acquire_ctxcCstjdtdd�|����S)Nz='with await lock' is deprecated use 'async with lock' insteadr r!)r#r$r%�!_ContextManagerMixin__acquire_ctx�	__await__rrrrr)Ys
�z_ContextManagerMixin.__await__c�s|��IdHdSr
)r&rrrr�
__aenter__`sz_ContextManagerMixin.__aenter__c�s|��dSr
)r)r�exc_type�exc�tbrrr�	__aexit__fsz_ContextManagerMixin.__aexit__N)rrrrr�types�	coroutiner'rZ
_is_coroutiner(r)r*r.rrrrr1s
rcsNeZdZdZdd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z	�Z
S)ra�Primitive lock objects.

    A primitive lock is a synchronization primitive that is not owned
    by a particular coroutine when locked.  A primitive lock is in one
    of two states, 'locked' or 'unlocked'.

    It is created in the unlocked state.  It has two basic methods,
    acquire() and release().  When the state is unlocked, acquire()
    changes the state to locked and returns immediately.  When the
    state is locked, acquire() blocks until a call to release() in
    another coroutine changes it to unlocked, then the acquire() call
    resets it to locked and returns.  The release() method should only
    be called in the locked state; it changes the state to unlocked
    and returns immediately.  If an attempt is made to release an
    unlocked lock, a RuntimeError will be raised.

    When more than one coroutine is blocked in acquire() waiting for
    the state to turn to unlocked, only one coroutine proceeds when a
    release() call resets the state to unlocked; first coroutine which
    is blocked in acquire() is being processed.

    acquire() is a coroutine and should be called with 'await'.

    Locks also support the asynchronous context management protocol.
    'async with lock' statement should be used.

    Usage:

        lock = Lock()
        ...
        await lock.acquire()
        try:
            ...
        finally:
            lock.release()

    Context manager usage:

        lock = Lock()
        ...
        async with lock:
             ...

    Lock objects can be tested for locking state:

        if not lock.locked():
           await lock.acquire()
        else:
           # lock is acquired
           ...

    N��loopcCs:d|_d|_|dkr t��|_n||_tjdtdd�dS�NF�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r r!)�_waiters�_lockedr�get_event_loop�_loopr#r$r%�rr2rrrr�s�z
Lock.__init__csLt���}|jrdnd}|jr2|�dt|j���}d|dd��d|�d�S�	N�lockedZunlocked�
, waiters:�<r���� [�]>)�super�__repr__r6r5�len�r�resZextra��	__class__rrrB�s

z
Lock.__repr__cCs|jS)z Return True if lock is acquired.)r6rrrrr;�szLock.lockedc	�s�|js.|jdks$tdd�|jD��r.d|_dS|jdkrBt��|_|j��}|j�|�z"z|IdHW5|j�|�XWn&t	j
k
r�|js�|���YnXd|_dS)z�Acquire a lock.

        This method blocks until the lock is unlocked, then sets it to
        locked and returns True.
        Ncss|]}|��VqdSr
)�	cancelled)�.0�wrrr�	<genexpr>�szLock.acquire.<locals>.<genexpr>T)r6r5�all�collections�dequer8�
create_future�append�remover
�CancelledError�_wake_up_first�r�futrrrr&�s&�


zLock.acquirecCs"|jrd|_|��ntd��dS)aGRelease a lock.

        When the lock is locked, reset it to unlocked, and return.
        If any other coroutines are blocked waiting for the lock to become
        unlocked, allow exactly one of them to proceed.

        When invoked on an unlocked lock, a RuntimeError is raised.

        There is no return value.
        FzLock is not acquired.N)r6rSrrrrrr�s
zLock.releasecCsJ|js
dSztt|j��}Wntk
r2YdSX|��sF|�d�dS)z*Wake up the first waiter if it isn't done.NT)r5�next�iter�
StopIteration�done�
set_resultrTrrrrS�szLock._wake_up_first)rrrrrrBr;r&rrS�
__classcell__rrrFrrjs5 rcsNeZdZdZdd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z	�Z
S)ra#Asynchronous equivalent to threading.Event.

    Class implementing event objects. An event manages a flag that can be set
    to true with the set() method and reset to false with the clear() method.
    The wait() method blocks until the flag is true. The flag is initially
    false.
    Nr1cCs>t��|_d|_|dkr$t��|_n||_tjdt	dd�dSr3)
rMrNr5�_valuerr7r8r#r$r%r9rrrrs
�zEvent.__init__csLt���}|jrdnd}|jr2|�dt|j���}d|dd��d|�d�S)	N�setZunsetr<r=rr>r?r@)rArBr\r5rCrDrFrrrBs

zEvent.__repr__cCs|jS)z5Return True if and only if the internal flag is true.�r\rrrr�is_setszEvent.is_setcCs.|js*d|_|jD]}|��s|�d�qdS)z�Set the internal flag to true. All coroutines waiting for it to
        become true are awakened. Coroutine that call wait() once the flag is
        true will not block at all.
        TN)r\r5rYrZrTrrrr]s

z	Event.setcCs
d|_dS)z�Reset the internal flag to false. Subsequently, coroutines calling
        wait() will block until set() is called to set the internal flag
        to true again.FNr^rrrr�clear"szEvent.clearc	�sF|jr
dS|j��}|j�|�z|IdHW�dS|j�|�XdS)z�Block until the internal flag is true.

        If the internal flag is true on entry, return True
        immediately.  Otherwise, block until another coroutine calls
        set() to set the flag to true, then return True.
        TN)r\r8rOr5rPrQrTrrr�wait(s

z
Event.wait)rrrrrrBr_r]r`rar[rrrFrr�srcsReZdZdZddd�dd�Z�fdd�Zdd	�Zd
d�Zdd
d�Zdd�Z	�Z
S)raAsynchronous equivalent to threading.Condition.

    This class implements condition variable objects. A condition variable
    allows one or more coroutines to wait until they are notified by another
    coroutine.

    A new Lock object is created and used as the underlying lock.
    Nr1cCs~|dkrt��|_n||_tjdtdd�|dkr>t|d�}n|j|jk	rRtd��||_|j	|_	|j
|_
|j|_t�
�|_dS)Nr4r r!r1z"loop argument must agree with lock)rr7r8r#r$r%r�
ValueErrorrr;r&rrMrNr5)rrr2rrrrEs �zCondition.__init__csNt���}|��rdnd}|jr4|�dt|j���}d|dd��d|�d�Sr:)rArBr;r5rCrDrFrrrB[s

zCondition.__repr__c�s�|��std��|��z@|j��}|j�	|�z|IdHW�W�dS|j�
|�XW5d}z|��IdHWq�Wq^tjk
r�d}Yq^Xq^|r�tj�XdS)a�Wait until notified.

        If the calling coroutine has not acquired the lock when this
        method is called, a RuntimeError is raised.

        This method releases the underlying lock, and then blocks
        until it is awakened by a notify() or notify_all() call for
        the same condition variable in another coroutine.  Once
        awakened, it re-acquires the lock and returns True.
        zcannot wait on un-acquired lockFNT)r;rrr&r
rRr8rOr5rPrQ)rrHrUrrrrabs$

zCondition.waitc�s$|�}|s |��IdH|�}q|S)z�Wait until a predicate becomes true.

        The predicate should be a callable which result will be
        interpreted as a boolean value.  The final predicate value is
        the return value.
        N)ra)rZ	predicate�resultrrr�wait_for�s
zCondition.wait_forrcCsJ|��std��d}|jD]*}||kr*qF|��s|d7}|�d�qdS)aBy default, wake up one coroutine waiting on this condition, if any.
        If the calling coroutine has not acquired the lock when this method
        is called, a RuntimeError is raised.

        This method wakes up at most n of the coroutines waiting for the
        condition variable; it is a no-op if no coroutines are waiting.

        Note: an awakened coroutine does not actually return from its
        wait() call until it can reacquire the lock. Since notify() does
        not release the lock, its caller should.
        z!cannot notify on un-acquired lockrrFN)r;rr5rYrZ)r�n�idxrUrrr�notify�s
zCondition.notifycCs|�t|j��dS)aWake up all threads waiting on this condition. This method acts
        like notify(), but wakes up all waiting threads instead of one. If the
        calling thread has not acquired the lock when this method is called,
        a RuntimeError is raised.
        N)rgrCr5rrrr�
notify_all�szCondition.notify_all)N)r)rrrrrrBrardrgrhr[rrrFrr;s	%
rcsPeZdZdZddd�dd�Z�fdd�Zd	d
�Zdd�Zd
d�Zdd�Z	�Z
S)raA Semaphore implementation.

    A semaphore manages an internal counter which is decremented by each
    acquire() call and incremented by each release() call. The counter
    can never go below zero; when acquire() finds that it is zero, it blocks,
    waiting until some other thread calls release().

    Semaphores also support the context management protocol.

    The optional argument gives the initial value for the internal
    counter; it defaults to 1. If the value given is less than 0,
    ValueError is raised.
    rNr1cCsN|dkrtd��||_t��|_|dkr4t��|_n||_tj	dt
dd�dS)Nrz$Semaphore initial value must be >= 0r4r r!)rbr\rMrNr5rr7r8r#r$r%�r�valuer2rrrr�s
�zSemaphore.__init__csVt���}|��rdn
d|j��}|jr<|�dt|j���}d|dd��d|�d�S)	Nr;zunlocked, value:r<r=rr>r?r@)rArBr;r\r5rCrDrFrrrB�s

zSemaphore.__repr__cCs,|jr(|j��}|��s|�d�dSqdSr
)r5�popleftrYrZ)rZwaiterrrr�
_wake_up_next�s


zSemaphore._wake_up_nextcCs
|jdkS)z:Returns True if semaphore can not be acquired immediately.rr^rrrrr;�szSemaphore.lockedc�st|jdkrb|j��}|j�|�z|IdHWq|��|jdkrX|��sX|���YqXq|jd8_dS)a5Acquire a semaphore.

        If the internal counter is larger than zero on entry,
        decrement it by one and return True immediately.  If it is
        zero on entry, block, waiting until some other coroutine has
        called release() to make it larger than 0, and then return
        True.
        rNrT)r\r8rOr5rPZcancelrHrlrTrrrr&�s	


zSemaphore.acquirecCs|jd7_|��dS)z�Release a semaphore, incrementing the internal counter by one.
        When it was zero on entry and another coroutine is waiting for it to
        become larger than zero again, wake up that coroutine.
        rN)r\rlrrrrr�szSemaphore.release)r)rrrrrrBrlr;r&rr[rrrFrr�s
rcs4eZdZdZd	dd��fdd�Z�fdd�Z�ZS)
rz�A bounded semaphore implementation.

    This raises ValueError in release() if it would increase the value
    above the initial value.
    rNr1cs.|rtjdtdd�||_t�j||d�dS)Nr4r r!r1)r#r$r%�_bound_valuerArrirFrrr
s�zBoundedSemaphore.__init__cs"|j|jkrtd��t���dS)Nz(BoundedSemaphore released too many times)r\rmrbrArrrFrrrszBoundedSemaphore.release)r)rrrrrrr[rrrFrrs	r)r�__all__rMr/r#�rr	r
rrrrrrrrrrrr�<module>s "9DzNPK [���+�+"__pycache__/futures.cpython-38.pycnu�[���U

e5db3�@s�dZdZddlZddlZddlZddlZddlmZddlm	Z	ddlm
Z
ddlmZejZej
Z
ejZejZejdZGd	d
�d
�ZeZdd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�dd�ZzddlZWnek
r�YnXejZZdS)z.A Future class similar to the one in PEP 3148.)�Future�wrap_future�isfuture�N�)�base_futures)�events)�
exceptions)�format_helpersc@s�eZdZdZeZdZdZdZdZ	dZ
dZdd�dd�Ze
jZdd�Zd	d
�Zedd��Zejd
d��Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Z e Z!dS)'ra,This class is *almost* compatible with concurrent.futures.Future.

    Differences:

    - This class is not thread-safe.

    - result() and exception() do not take a timeout argument and
      raise an exception when the future isn't done yet.

    - Callbacks registered with add_done_callback() are always called
      via the event loop's call_soon().

    - This class is not compatible with the wait() and as_completed()
      methods in the concurrent.futures package.

    (In Python 3.4 or later we may be able to unify the implementations.)
    NF��loopcCs@|dkrt��|_n||_g|_|j��r<t�t�d��|_	dS)z�Initialize the future.

        The optional event_loop argument allows explicitly setting the event
        loop object used by the future. If it's not provided, the future uses
        the default event loop.
        Nr)
r�get_event_loop�_loop�
_callbacksZ	get_debugr	�
extract_stack�sys�	_getframe�_source_traceback��selfr�r�'/usr/lib64/python3.8/asyncio/futures.py�__init__Ds
�zFuture.__init__cCsd�|jjd�|����S)Nz<{} {}>� )�format�	__class__�__name__�join�
_repr_info�rrrr�__repr__Vs
�zFuture.__repr__cCsF|js
dS|j}|jj�d�||d�}|jr6|j|d<|j�|�dS)Nz exception was never retrieved)�message�	exception�futureZsource_traceback)�_Future__log_traceback�
_exceptionrrrr
Zcall_exception_handler)r�exc�contextrrr�__del__Zs�
zFuture.__del__cCs|jS�N)r#rrrr�_log_tracebackjszFuture._log_tracebackcCst|�rtd��d|_dS)Nz'_log_traceback can only be set to FalseF)�bool�
ValueErrorr#)r�valrrrr)nscCs|j}|dkrtd��|S)z-Return the event loop the Future is bound to.Nz!Future object is not initialized.)r
�RuntimeErrorrrrr�get_looptszFuture.get_loopcCs&d|_|jtkrdSt|_|��dS)z�Cancel the future and schedule callbacks.

        If the future is already done or cancelled, return False.  Otherwise,
        change the future's state to cancelled, schedule the callbacks and
        return True.
        FT)r#�_state�_PENDING�
_CANCELLED�_Future__schedule_callbacksrrrr�cancel{s
z
Future.cancelcCsH|jdd�}|sdSg|jdd�<|D]\}}|jj|||d�q(dS)z�Internal: Ask the event loop to call all callbacks.

        The callbacks are scheduled to be called as soon as possible. Also
        clears the callback list.
        N�r&)rr
�	call_soon)rZ	callbacks�callback�ctxrrrZ__schedule_callbacks�szFuture.__schedule_callbackscCs
|jtkS)z(Return True if the future was cancelled.)r/r1rrrr�	cancelled�szFuture.cancelledcCs
|jtkS)z�Return True if the future is done.

        Done means either that a result / exception are available, or that the
        future was cancelled.
        )r/r0rrrr�done�szFuture.donecCs@|jtkrtj�|jtkr$t�d��d|_|jdk	r:|j�|jS)aReturn the result this future represents.

        If the future has been cancelled, raises CancelledError.  If the
        future's result isn't yet available, raises InvalidStateError.  If
        the future is done and has an exception set, this exception is raised.
        zResult is not ready.FN)	r/r1r�CancelledError�	_FINISHED�InvalidStateErrorr#r$�_resultrrrr�result�s



z
Future.resultcCs0|jtkrtj�|jtkr$t�d��d|_|jS)a&Return the exception that was set on this future.

        The exception (or None if no exception was set) is returned only if
        the future is done.  If the future has been cancelled, raises
        CancelledError.  If the future isn't done yet, raises
        InvalidStateError.
        zException is not set.F)r/r1rr:r;r<r#r$rrrrr!�s


zFuture.exceptionr4cCsB|jtkr|jj|||d�n |dkr.t��}|j�||f�dS)z�Add a callback to be run when the future becomes done.

        The callback is called with a single argument - the future object. If
        the future is already done when this is called, the callback is
        scheduled with call_soon.
        r4N)r/r0r
r5�contextvarsZcopy_contextr�append)r�fnr&rrr�add_done_callback�s

zFuture.add_done_callbackcs<�fdd�|jD�}t|j�t|�}|r8||jdd�<|S)z}Remove all instances of a callback from the "call when done" list.

        Returns the number of callbacks removed.
        cs g|]\}}|�kr||f�qSrr)�.0�fr7�rArr�
<listcomp>�s�z/Future.remove_done_callback.<locals>.<listcomp>N)r�len)rrAZfiltered_callbacksZ
removed_countrrEr�remove_done_callback�s
�zFuture.remove_done_callbackcCs8|jtkr t�|j�d|����||_t|_|��dS)z�Mark the future done and set its result.

        If the future is already done when this method is called, raises
        InvalidStateError.
        �: N)r/r0rr<r=r;r2)rr>rrr�
set_result�s

zFuture.set_resultcCsb|jtkr t�|j�d|����t|t�r0|�}t|�tkrDtd��||_t	|_|�
�d|_dS)z�Mark the future done and set an exception.

        If the future is already done when this method is called, raises
        InvalidStateError.
        rIzPStopIteration interacts badly with generators and cannot be raised into a FutureTN)r/r0rr<�
isinstance�type�
StopIteration�	TypeErrorr$r;r2r#)rr!rrr�
set_exception�s

zFuture.set_exceptionccs,|��sd|_|V|��s$td��|��S)NTzawait wasn't used with future)r9�_asyncio_future_blockingr-r>rrrr�	__await__szFuture.__await__)"r�
__module__�__qualname__�__doc__r0r/r=r$r
rrPr#rrZ_future_repr_inforrr'�propertyr)�setterr.r3r2r8r9r>r!rBrHrJrOrQ�__iter__rrrrrs:

rcCs,z
|j}Wntk
rYnX|�S|jSr()r.�AttributeErrorr
)�futr.rrr�	_get_loops
rZcCs|��rdS|�|�dS)z?Helper setting the result only if the future was not cancelled.N)r8rJ)rYr>rrr�_set_result_unless_cancelledsr[cCsXt|�}|tjjkr tj|j�S|tjjkr8tj|j�S|tjjkrPtj|j�S|SdSr()rL�
concurrent�futuresr:r�args�TimeoutErrorr<)r%Z	exc_classrrr�_convert_future_exc#sr`cCs^|��st�|��r|��|��s(dS|��}|dk	rH|�t|��n|��}|�	|�dS)z8Copy state from a future to a concurrent.futures.Future.N)
r9�AssertionErrorr8r3Zset_running_or_notify_cancelr!rOr`r>rJ)r\�sourcer!r>rrr�_set_concurrent_future_state/srccCsl|��st�|��rdS|��r$t�|��r6|��n2|��}|dk	rV|�t|��n|��}|�|�dS)zqInternal helper to copy state from another Future.

    The other Future may be a concurrent.futures.Future.
    N)	r9rar8r3r!rOr`r>rJ)rb�destr!r>rrr�_copy_future_state>s
recs�t��st�tjj�std��t��s<t�tjj�s<td��t��rLt��nd�t��r`t��nd�dd�����fdd�}����fdd	�}��|���|�dS)
aChain two futures so that when one completes, so does the other.

    The result (or exception) of source will be copied to destination.
    If destination is cancelled, source gets cancelled too.
    Compatible with both asyncio.Future and concurrent.futures.Future.
    z(A future is required for source argumentz-A future is required for destination argumentNcSs"t|�rt||�n
t||�dSr()rrerc)r"�otherrrr�
_set_statebsz!_chain_future.<locals>._set_statecs2|��r.�dks��kr"���n���j�dSr()r8r3�call_soon_threadsafe)�destination)�	dest_looprb�source_looprr�_call_check_cancelhs
z)_chain_future.<locals>._call_check_cancelcsJ���r�dk	r���rdS�dks,��kr8��|�n����|�dSr()r8Z	is_closedrh)rb)rgrjrirkrr�_call_set_stateos��z&_chain_future.<locals>._call_set_state)rrKr\r]rrNrZrB)rbrirlrmr)rgrjrirbrkr�
_chain_futureRs��	
rnr
cCsNt|�r|St|tjj�s(td|����|dkr8t��}|��}t	||�|S)z&Wrap concurrent.futures.Future object.z+concurrent.futures.Future is expected, got N)
rrKr\r]rrarrZ
create_futurern)r"rZ
new_futurerrrr|s�
r)rT�__all__Zconcurrent.futuresr\r?Zloggingr�rrrr	rr0r1r;�DEBUGZSTACK_DEBUGrZ	_PyFuturerZr[r`rcrernrZ_asyncio�ImportErrorZ_CFuturerrrr�<module>s:
q*
PK [�?�`��(__pycache__/runners.cpython-38.opt-2.pycnu�[���U

e5d�@sBdZddlmZddlmZddlmZdd�dd�Zd	d
�ZdS))�run�)�
coroutines)�events)�tasksN)�debugcCs�t��dk	rtd��t�|�s,td�|���t��}z*t�|�|dk	rR|�
|�|�|�W�Szt
|�|�|���W5t�d�|�	�XXdS)Nz8asyncio.run() cannot be called from a running event loopz"a coroutine was expected, got {!r})rZ_get_running_loop�RuntimeErrorrZiscoroutine�
ValueError�formatZnew_event_loopZset_event_loop�close�_cancel_all_tasks�run_until_completeZshutdown_asyncgensZ	set_debug)�mainr�loop�r�'/usr/lib64/python3.8/asyncio/runners.pyrs"�



rcCsvt�|�}|sdS|D]}|��q|�tj||dd���|D]0}|��rNq@|��dk	r@|�d|��|d��q@dS)NT)rZreturn_exceptionsz1unhandled exception during asyncio.run() shutdown)�message�	exception�task)rZ	all_tasksZcancelrZgatherZ	cancelledrZcall_exception_handler)rZ	to_cancelrrrrr6s"

��r)�__all__�rrrrrrrrr�<module>s
.PK [���I�I'__pycache__/events.cpython-38.opt-2.pycnu�[���U

e5d4f�@sxdZddlZddlZddlZddlZddlZddlZddlmZddlm	Z	Gdd�d�Z
Gdd	�d	e
�ZGd
d�d�ZGdd
�d
�Z
Gdd�d�ZGdd�de�Zdae��ZGdd�dej�Ze�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Z eZ!eZ"eZ#eZ$zdd*l%mZmZmZmZWne&k
�rbYnXeZ'eZ(eZ)eZ*dS)+)�AbstractEventLoopPolicy�AbstractEventLoop�AbstractServer�Handle�TimerHandle�get_event_loop_policy�set_event_loop_policy�get_event_loop�set_event_loop�new_event_loop�get_child_watcher�set_child_watcher�_set_running_loop�get_running_loop�_get_running_loop�N�)�format_helpers)�
exceptionsc@sBeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)r)�	_callback�_args�
_cancelled�_loop�_source_traceback�_repr�__weakref__�_contextNcCs\|dkrt��}||_||_||_||_d|_d|_|j��rRt	�
t�d��|_
nd|_
dS)NFr)�contextvarsZcopy_contextrrrrrr�	get_debugr�
extract_stack�sys�	_getframer)�self�callback�args�loop�context�r&�&/usr/lib64/python3.8/asyncio/events.py�__init__ s
�zHandle.__init__cCsl|jjg}|jr|�d�|jdk	r:|�t�|j|j��|jrh|jd}|�d|d�d|d���|S)N�	cancelled���zcreated at r�:r)	�	__class__�__name__r�appendrr�_format_callback_sourcerr)r!�info�framer&r&r'�
_repr_info/s


�
zHandle._repr_infocCs(|jdk	r|jS|��}d�d�|��S)Nz<{}>� )rr2�format�join)r!r0r&r&r'�__repr__;s
zHandle.__repr__cCs0|js,d|_|j��r t|�|_d|_d|_dS�NT)rrr�reprrrr�r!r&r&r'�cancelAs

z
Handle.cancelcCs|jS�N)rr9r&r&r'r)LszHandle.cancelledc
Cs�z|jj|jf|j��Wn|ttfk
r4�Yndtk
r�}zFt�|j|j�}d|��}|||d�}|j	rz|j	|d<|j
�|�W5d}~XYnXd}dS)NzException in callback )�messageZ	exception�handleZsource_traceback)r�runrr�
SystemExit�KeyboardInterrupt�
BaseExceptionrr/rr�call_exception_handler)r!�exc�cb�msgr%r&r&r'�_runOs$�
�
zHandle._run)N)
r-�
__module__�__qualname__�	__slots__r(r2r6r:r)rFr&r&r&r'rs
rcs~eZdZddgZd�fdd�	Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Z�fdd�Z
dd�Z�ZS)r�
_scheduled�_whenNcs0t��||||�|jr |jd=||_d|_dS)Nr*F)�superr(rrKrJ)r!�whenr"r#r$r%�r,r&r'r(hs
zTimerHandle.__init__cs0t���}|jrdnd}|�|d|j���|S)N�rzwhen=)rLr2r�insertrK)r!r0�posrNr&r'r2ps
zTimerHandle._repr_infocCs
t|j�Sr;)�hashrKr9r&r&r'�__hash__vszTimerHandle.__hash__cCs|j|jkSr;�rK�r!�otherr&r&r'�__lt__yszTimerHandle.__lt__cCs|j|jkrdS|�|�Sr7�rK�__eq__rUr&r&r'�__le__|szTimerHandle.__le__cCs|j|jkSr;rTrUr&r&r'�__gt__�szTimerHandle.__gt__cCs|j|jkrdS|�|�Sr7rXrUr&r&r'�__ge__�szTimerHandle.__ge__cCs>t|t�r:|j|jko8|j|jko8|j|jko8|j|jkStSr;)�
isinstancerrKrrr�NotImplementedrUr&r&r'rY�s

�
�
�zTimerHandle.__eq__cCs|�|�}|tkrtS|Sr;)rYr^)r!rVZequalr&r&r'�__ne__�s
zTimerHandle.__ne__cs |js|j�|�t���dSr;)rr�_timer_handle_cancelledrLr:r9rNr&r'r:�szTimerHandle.cancelcCs|jSr;rTr9r&r&r'rM�szTimerHandle.when)N)r-rGrHrIr(r2rSrWrZr[r\rYr_r:rM�
__classcell__r&r&rNr'rcsrc@sLeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dS)rcCst�dSr;��NotImplementedErrorr9r&r&r'�close�szAbstractServer.closecCst�dSr;rbr9r&r&r'�get_loop�szAbstractServer.get_loopcCst�dSr;rbr9r&r&r'�
is_serving�szAbstractServer.is_servingc�st�dSr;rbr9r&r&r'�
start_serving�szAbstractServer.start_servingc�st�dSr;rbr9r&r&r'�
serve_forever�szAbstractServer.serve_foreverc�st�dSr;rbr9r&r&r'�wait_closed�szAbstractServer.wait_closedc�s|Sr;r&r9r&r&r'�
__aenter__�szAbstractServer.__aenter__c�s|��|��IdHdSr;)rdri)r!rCr&r&r'�	__aexit__�szAbstractServer.__aexit__N)r-rGrHrdrerfrgrhrirjrkr&r&r&r'r�src@sReZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�dd�Zdd �Zd!d"�Zd#d$�Zd%d%d%d%d&�d'd(�Zdtd)d*�Zdudd%d%d%ddddddd+�
d,d-�Zdvejejdd.ddddd/d0�	d1d2�Zdwd/d3�d4d5�Zd6ddd7�d8d9�Zdxddddd:�d;d<�Zdydd.ddd/d=�d>d?�Zdzd%d%d%ddddd@�dAdB�ZdCdD�Z dEdF�Z!e"j#e"j#e"j#dG�dHdI�Z$e"j#e"j#e"j#dG�dJdK�Z%dLdM�Z&dNdO�Z'dPdQ�Z(dRdS�Z)dTdU�Z*dVdW�Z+dXdY�Z,dZd[�Z-d\d]�Z.d{dd3�d^d_�Z/d`da�Z0dbdc�Z1ddde�Z2dfdg�Z3dhdi�Z4djdk�Z5dldm�Z6dndo�Z7dpdq�Z8drds�Z9dS)|rcCst�dSr;rbr9r&r&r'�run_forever�szAbstractEventLoop.run_forevercCst�dSr;rb)r!Zfuturer&r&r'�run_until_complete�sz$AbstractEventLoop.run_until_completecCst�dSr;rbr9r&r&r'�stop�szAbstractEventLoop.stopcCst�dSr;rbr9r&r&r'�
is_running�szAbstractEventLoop.is_runningcCst�dSr;rbr9r&r&r'�	is_closed�szAbstractEventLoop.is_closedcCst�dSr;rbr9r&r&r'rd�s	zAbstractEventLoop.closec�st�dSr;rbr9r&r&r'�shutdown_asyncgens�sz$AbstractEventLoop.shutdown_asyncgenscCst�dSr;rb)r!r=r&r&r'r`�sz)AbstractEventLoop._timer_handle_cancelledcGs|jd|f|��S)Nr)�
call_later�r!r"r#r&r&r'�	call_soonszAbstractEventLoop.call_sooncGst�dSr;rb)r!Zdelayr"r#r&r&r'rrszAbstractEventLoop.call_latercGst�dSr;rb)r!rMr"r#r&r&r'�call_atszAbstractEventLoop.call_atcCst�dSr;rbr9r&r&r'�timeszAbstractEventLoop.timecCst�dSr;rbr9r&r&r'�
create_futureszAbstractEventLoop.create_futureN)�namecCst�dSr;rb)r!�cororxr&r&r'�create_taskszAbstractEventLoop.create_taskcGst�dSr;rbrsr&r&r'�call_soon_threadsafesz&AbstractEventLoop.call_soon_threadsafecGst�dSr;rb)r!�executor�funcr#r&r&r'�run_in_executorsz!AbstractEventLoop.run_in_executorcCst�dSr;rb)r!r|r&r&r'�set_default_executorsz&AbstractEventLoop.set_default_executorr)�family�type�proto�flagsc�st�dSr;rb)r!�host�portr�r�r�r�r&r&r'�getaddrinfo#szAbstractEventLoop.getaddrinfoc�st�dSr;rb)r!Zsockaddrr�r&r&r'�getnameinfo'szAbstractEventLoop.getnameinfo)
�sslr�r�r��sock�
local_addr�server_hostname�ssl_handshake_timeout�happy_eyeballs_delay�
interleavec
�st�dSr;rb)r!�protocol_factoryr�r�r�r�r�r�r�r�r�r�r�r�r&r&r'�create_connection*sz#AbstractEventLoop.create_connection�dT)	r�r�r��backlogr��
reuse_address�
reuse_portr�rgc	
�st�dSr;rb)
r!r�r�r�r�r�r�r�r�r�r�r�rgr&r&r'�
create_server3s3zAbstractEventLoop.create_server)�fallbackc�st�dSr;rb)r!�	transport�file�offset�countr�r&r&r'�sendfilehszAbstractEventLoop.sendfileF)�server_sider�r�c�st�dSr;rb)r!r�ZprotocolZ
sslcontextr�r�r�r&r&r'�	start_tlsps	zAbstractEventLoop.start_tls)r�r�r�r�c�st�dSr;rb)r!r��pathr�r�r�r�r&r&r'�create_unix_connection{sz(AbstractEventLoop.create_unix_connection)r�r�r�r�rgc�st�dSr;rb)r!r�r�r�r�r�r�rgr&r&r'�create_unix_server�sz$AbstractEventLoop.create_unix_server)r�r�r�r�r��allow_broadcastr�c�st�dSr;rb)r!r�r�Zremote_addrr�r�r�r�r�r�r�r&r&r'�create_datagram_endpoint�s!z*AbstractEventLoop.create_datagram_endpointc�st�dSr;rb�r!r��piper&r&r'�connect_read_pipe�sz#AbstractEventLoop.connect_read_pipec�st�dSr;rbr�r&r&r'�connect_write_pipe�sz$AbstractEventLoop.connect_write_pipe)�stdin�stdout�stderrc�st�dSr;rb)r!r��cmdr�r�r��kwargsr&r&r'�subprocess_shell�sz"AbstractEventLoop.subprocess_shellc�st�dSr;rb)r!r�r�r�r�r#r�r&r&r'�subprocess_exec�sz!AbstractEventLoop.subprocess_execcGst�dSr;rb�r!�fdr"r#r&r&r'�
add_reader�szAbstractEventLoop.add_readercCst�dSr;rb�r!r�r&r&r'�
remove_reader�szAbstractEventLoop.remove_readercGst�dSr;rbr�r&r&r'�
add_writer�szAbstractEventLoop.add_writercCst�dSr;rbr�r&r&r'�
remove_writer�szAbstractEventLoop.remove_writerc�st�dSr;rb)r!r��nbytesr&r&r'�	sock_recvszAbstractEventLoop.sock_recvc�st�dSr;rb)r!r�Zbufr&r&r'�sock_recv_intosz AbstractEventLoop.sock_recv_intoc�st�dSr;rb)r!r��datar&r&r'�sock_sendallszAbstractEventLoop.sock_sendallc�st�dSr;rb)r!r�Zaddressr&r&r'�sock_connectszAbstractEventLoop.sock_connectc�st�dSr;rb)r!r�r&r&r'�sock_acceptszAbstractEventLoop.sock_acceptc�st�dSr;rb)r!r�r�r�r�r�r&r&r'�
sock_sendfileszAbstractEventLoop.sock_sendfilecGst�dSr;rb)r!�sigr"r#r&r&r'�add_signal_handlersz$AbstractEventLoop.add_signal_handlercCst�dSr;rb)r!r�r&r&r'�remove_signal_handlersz'AbstractEventLoop.remove_signal_handlercCst�dSr;rb)r!�factoryr&r&r'�set_task_factorysz"AbstractEventLoop.set_task_factorycCst�dSr;rbr9r&r&r'�get_task_factory"sz"AbstractEventLoop.get_task_factorycCst�dSr;rbr9r&r&r'�get_exception_handler'sz'AbstractEventLoop.get_exception_handlercCst�dSr;rb)r!Zhandlerr&r&r'�set_exception_handler*sz'AbstractEventLoop.set_exception_handlercCst�dSr;rb�r!r%r&r&r'�default_exception_handler-sz+AbstractEventLoop.default_exception_handlercCst�dSr;rbr�r&r&r'rB0sz(AbstractEventLoop.call_exception_handlercCst�dSr;rbr9r&r&r'r5szAbstractEventLoop.get_debugcCst�dSr;rb)r!Zenabledr&r&r'�	set_debug8szAbstractEventLoop.set_debug)r)NN)NN)rN)N)N)NN)rN):r-rGrHrlrmrnrorprdrqr`rtrrrurvrwrzr{r~rr�r�r��socketZ	AF_UNSPECZ
AI_PASSIVEr�r�r�r�r�r�r�r��
subprocess�PIPEr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rBrr�r&r&r&r'r�s��
��
��5�	�����!��%
���rc@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)rcCst�dSr;rbr9r&r&r'r?sz&AbstractEventLoopPolicy.get_event_loopcCst�dSr;rb�r!r$r&r&r'r	Isz&AbstractEventLoopPolicy.set_event_loopcCst�dSr;rbr9r&r&r'r
Msz&AbstractEventLoopPolicy.new_event_loopcCst�dSr;rbr9r&r&r'rUsz)AbstractEventLoopPolicy.get_child_watchercCst�dSr;rb)r!�watcherr&r&r'rYsz)AbstractEventLoopPolicy.set_child_watcherN)r-rGrHrr	r
rrr&r&r&r'r<s

rc@sBeZdZdZGdd�dej�Zdd�Zdd�Zdd	�Z	d
d�Z
dS)�BaseDefaultEventLoopPolicyNc@seZdZdZdZdS)z!BaseDefaultEventLoopPolicy._LocalNF)r-rGrHr�_set_calledr&r&r&r'�_Localmsr�cCs|��|_dSr;)r��_localr9r&r&r'r(qsz#BaseDefaultEventLoopPolicy.__init__cCsX|jjdkr2|jjs2tt��tj�r2|�|���|jjdkrPt	dt��j
��|jjS)Nz,There is no current event loop in thread %r.)r�rr�r]�	threadingZcurrent_threadZ_MainThreadr	r
�RuntimeErrorrxr9r&r&r'rts���z)BaseDefaultEventLoopPolicy.get_event_loopcCsd|j_||j_dSr7)r�r�rr�r&r&r'r	�sz)BaseDefaultEventLoopPolicy.set_event_loopcCs|��Sr;)�
_loop_factoryr9r&r&r'r
�sz)BaseDefaultEventLoopPolicy.new_event_loop)r-rGrHr�r��localr�r(rr	r
r&r&r&r'r�^s
r�c@seZdZdZdS)�_RunningLoop)NNN)r-rGrH�loop_pidr&r&r&r'r��sr�cCst�}|dkrtd��|S)Nzno running event loop)rr��r$r&r&r'r�srcCs&tj\}}|dk	r"|t��kr"|SdSr;)�
_running_loopr��os�getpid)Zrunning_loop�pidr&r&r'r�s
rcCs|t��ft_dSr;)r�r�r�r�r�r&r&r'r
�sr
c	Cs.t� tdkr ddlm}|�aW5QRXdS)Nr��DefaultEventLoopPolicy)�_lock�_event_loop_policy�r�r�r&r&r'�_init_event_loop_policy�sr�cCstdkrt�tSr;)r�r�r&r&r&r'r�srcCs|adSr;)r�)Zpolicyr&r&r'r�srcCst�}|dk	r|St���Sr;)rrr)Zcurrent_loopr&r&r'r�s
rcCst��|�dSr;)rr	r�r&r&r'r	�sr	cCs
t���Sr;)rr
r&r&r&r'r
�sr
cCs
t���Sr;)rrr&r&r&r'r�srcCst��|�Sr;)rr)r�r&r&r'r�sr)rr
rr)+�__all__rr�r�r�rr�r�rrrrrrrr�r�ZLockr�r�r�r�rrr
r�rrrr	r
rrZ_py__get_running_loopZ_py__set_running_loopZ_py_get_running_loopZ_py_get_event_loopZ_asyncio�ImportErrorZ_c__get_running_loopZ_c__set_running_loopZ_c_get_running_loopZ_c_get_event_loopr&r&r&r'�<module>sVJ@*q"9
	PK [\dkss.__pycache__/windows_utils.cpython-38.opt-2.pycnu�[���U

e5d��@s�ddlZejdkred��ddlZddlZddlZddlZddlZddlZddl	Z	dZ
dZejZej
Z
e��Zdded�d	d
�ZGdd�d�ZGd
d�dej�ZdS)�NZwin32z
win32 only)�pipe�Popen�PIPE�
PipeHandlei F)TT)�duplex�
overlapped�bufsizec
Cs$tjd�t��tt��d�}|r>tj}tj	tj
B}||}}ntj}tj
}d|}}|tjO}|drp|tj
O}|dr�tj
}nd}d}	}
z\t�||tjd||tjtj�}	t�||dtjtj|tj�}
tj|	dd�}|�d�|	|
fWS|	dk	�rt�|	�|
dk	�rt�|
��YnXdS)Nz\\.\pipe\python-pipe-{:d}-{:d}-)�prefixr�T�r)�tempfileZmktemp�format�os�getpid�next�
_mmap_counter�_winapiZPIPE_ACCESS_DUPLEXZGENERIC_READZ
GENERIC_WRITEZPIPE_ACCESS_INBOUNDZFILE_FLAG_FIRST_PIPE_INSTANCEZFILE_FLAG_OVERLAPPEDZCreateNamedPipeZ	PIPE_WAITZNMPWAIT_WAIT_FOREVERZNULLZ
CreateFileZ
OPEN_EXISTINGZConnectNamedPipeZGetOverlappedResult�CloseHandle)rrrZaddressZopenmode�accessZobsizeZibsizeZflags_and_attribsZh1Zh2Zov�r�-/usr/lib64/python3.8/asyncio/windows_utils.pyr sb��


��





rc@s^eZdZdd�Zdd�Zedd��Zdd�Zej	d	�d
d�Z
ejfdd
�Z
dd�Zdd�ZdS)rcCs
||_dS�N��_handle��self�handlerrr�__init__VszPipeHandle.__init__cCs2|jdk	rd|j��}nd}d|jj�d|�d�S)Nzhandle=�closed�<� �>)r�	__class__�__name__rrrr�__repr__Ys
zPipeHandle.__repr__cCs|jSrr�rrrrr`szPipeHandle.handlecCs|jdkrtd��|jS)NzI/O operation on closed pipe)r�
ValueErrorr%rrr�filenods
zPipeHandle.fileno)rcCs|jdk	r||j�d|_dSrr)rrrrr�closeis

zPipeHandle.closecCs*|jdk	r&|d|��t|d�|��dS)Nz	unclosed )�source)r�ResourceWarningr()rZ_warnrrr�__del__ns
zPipeHandle.__del__cCs|Srrr%rrr�	__enter__sszPipeHandle.__enter__cCs|��dSr)r()r�t�v�tbrrr�__exit__vszPipeHandle.__exit__N)r#�
__module__�__qualname__rr$�propertyrr'rrr(�warnings�warnr+r,r0rrrrrQs
rcseZdZd�fdd�	Z�ZS)rNc	sxd}}}d}	}
}|tkr@tddd�\}}	t�|tj�}n|}|tkrhtdd�\}
}
t�|
d�}n|}|tkr�tdd�\}}t�|d�}n|tkr�|}n|}z�z t�j	|f|||d�|��Wn0|	|
|fD]}|dk	r�t
�|�qւYn>X|	dk	�r
t|	�|_
|
dk	�rt|
�|_|dk	�r2t|�|_W5|tk�rJt�|�|tk�r^t�|�|tk�rrt�|�XdS)N)FTT)rr)TFrr)�stdin�stdout�stderr)rr�msvcrtZopen_osfhandler�O_RDONLY�STDOUTr(�superrrrrr6r7r8)r�argsr6r7r8�kwdsZ	stdin_rfdZ
stdout_wfdZ
stderr_wfdZstdin_whZ	stdout_rhZ	stderr_rhZstdin_rhZ	stdout_whZ	stderr_wh�h�r"rrr�sN��










zPopen.__init__)NNN)r#r1r2r�
__classcell__rrr@rr}sr)�sys�platform�ImportErrorr�	itertoolsr9r�
subprocessrr4�__all__ZBUFSIZErr;�countrrrrrrrr�<module>s"
1,PK [��q�ll-__pycache__/base_futures.cpython-38.opt-1.pycnu�[���U

e5d
�@sRdZddlZddlmZddlmZdZdZdZd	d
�Z	dd�Z
e�Zd
d�Z
dS)��N)�	get_ident�)�format_helpersZPENDINGZ	CANCELLEDZFINISHEDcCst|jd�o|jdk	S)z�Check for a Future.

    This returns True when obj is a Future instance or is advertising
    itself as duck-type compatible by setting _asyncio_future_blocking.
    See comment in Future for more details.
    �_asyncio_future_blockingN)�hasattr�	__class__r)�objrr�,/usr/lib64/python3.8/asyncio/base_futures.py�isfutures�rcCs�t|�}|sd}dd�}|dkr2||dd�}n`|dkr`d�||dd�||dd��}n2|dkr�d�||dd�|d||d	d��}d
|�d�S)�#helper function for Future.__repr__�cSst�|d�S)Nr)rZ_format_callback_source)�callbackrrr
�	format_cbsz$_format_callbacks.<locals>.format_cbrr�z{}, {}z{}, <{} more>, {}���zcb=[�])�len�format)�cb�sizerrrr
�_format_callbackss&�rc	Cs�|j��g}|jtkr�|jdk	r4|�d|j���nTt|�t�f}|tkrPd}n(t�|�zt
�|j�}W5t�	|�X|�d|���|j
r�|�t|j
��|jr�|jd}|�d|d�d|d	���|S)
rNz
exception=z...zresult=rzcreated at r�:r)Z_state�lower�	_FINISHEDZ
_exception�append�idr�
_repr_running�add�discard�reprlib�reprZ_resultZ
_callbacksrZ_source_traceback)Zfuture�info�key�result�framerrr
�_future_repr_info7s$



r&)�__all__r �_threadrr
rZ_PENDINGZ
_CANCELLEDrrr�setrr&rrrr
�<module>sPK [	�?�/m/m'__pycache__/events.cpython-38.opt-1.pycnu�[���U

e5d4f�@s|dZdZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
Gdd�d�ZGd	d
�d
e�ZGdd�d�Z
Gd
d�d�ZGdd�d�ZGdd�de�Zdae��ZGdd�dej�Ze�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Z d)d*�Z!eZ"eZ#eZ$eZ%zdd+l&mZmZmZmZWne'k
�rfYnXeZ(eZ)eZ*eZ+dS),z!Event loop and event loop policy.)�AbstractEventLoopPolicy�AbstractEventLoop�AbstractServer�Handle�TimerHandle�get_event_loop_policy�set_event_loop_policy�get_event_loop�set_event_loop�new_event_loop�get_child_watcher�set_child_watcher�_set_running_loop�get_running_loop�_get_running_loop�N�)�format_helpers)�
exceptionsc@sFeZdZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)rz1Object returned by callback registration methods.)�	_callback�_args�
_cancelled�_loop�_source_traceback�_repr�__weakref__�_contextNcCs\|dkrt��}||_||_||_||_d|_d|_|j��rRt	�
t�d��|_
nd|_
dS)NFr)�contextvarsZcopy_contextrrrrrr�	get_debugr�
extract_stack�sys�	_getframer)�self�callback�args�loop�context�r&�&/usr/lib64/python3.8/asyncio/events.py�__init__ s
�zHandle.__init__cCsl|jjg}|jr|�d�|jdk	r:|�t�|j|j��|jrh|jd}|�d|d�d|d���|S)N�	cancelled���zcreated at r�:r)	�	__class__�__name__r�appendrr�_format_callback_sourcerr)r!�info�framer&r&r'�
_repr_info/s


�
zHandle._repr_infocCs(|jdk	r|jS|��}d�d�|��S)Nz<{}>� )rr2�format�join)r!r0r&r&r'�__repr__;s
zHandle.__repr__cCs0|js,d|_|j��r t|�|_d|_d|_dS�NT)rrr�reprrrr�r!r&r&r'�cancelAs

z
Handle.cancelcCs|jS�N)rr9r&r&r'r)LszHandle.cancelledc
Cs�z|jj|jf|j��Wn|ttfk
r4�Yndtk
r�}zFt�|j|j�}d|��}|||d�}|j	rz|j	|d<|j
�|�W5d}~XYnXd}dS)NzException in callback )�messageZ	exception�handleZsource_traceback)r�runrr�
SystemExit�KeyboardInterrupt�
BaseExceptionrr/rr�call_exception_handler)r!�exc�cb�msgr%r&r&r'�_runOs$�
�
zHandle._run)N)r-�
__module__�__qualname__�__doc__�	__slots__r(r2r6r:r)rFr&r&r&r'rs
rcs�eZdZdZddgZd�fdd�	Z�fdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
�fdd�Zdd�Z�ZS)rz7Object returned by timed callback registration methods.�
_scheduled�_whenNcs0t��||||�|jr |jd=||_d|_dS)Nr*F)�superr(rrLrK)r!�whenr"r#r$r%�r,r&r'r(hs
zTimerHandle.__init__cs0t���}|jrdnd}|�|d|j���|S)N�rzwhen=)rMr2r�insertrL)r!r0�posrOr&r'r2ps
zTimerHandle._repr_infocCs
t|j�Sr;)�hashrLr9r&r&r'�__hash__vszTimerHandle.__hash__cCs|j|jkSr;�rL�r!�otherr&r&r'�__lt__yszTimerHandle.__lt__cCs|j|jkrdS|�|�Sr7�rL�__eq__rVr&r&r'�__le__|szTimerHandle.__le__cCs|j|jkSr;rUrVr&r&r'�__gt__�szTimerHandle.__gt__cCs|j|jkrdS|�|�Sr7rYrVr&r&r'�__ge__�szTimerHandle.__ge__cCs>t|t�r:|j|jko8|j|jko8|j|jko8|j|jkStSr;)�
isinstancerrLrrr�NotImplementedrVr&r&r'rZ�s

�
�
�zTimerHandle.__eq__cCs|�|�}|tkrtS|Sr;)rZr_)r!rWZequalr&r&r'�__ne__�s
zTimerHandle.__ne__cs |js|j�|�t���dSr;)rr�_timer_handle_cancelledrMr:r9rOr&r'r:�szTimerHandle.cancelcCs|jS)z�Return a scheduled callback time.

        The time is an absolute timestamp, using the same time
        reference as loop.time().
        rUr9r&r&r'rN�szTimerHandle.when)N)r-rGrHrIrJr(r2rTrXr[r\r]rZr`r:rN�
__classcell__r&r&rOr'rcsrc@sPeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)rz,Abstract server returned by create_server().cCst�dS)z5Stop serving.  This leaves existing connections open.N��NotImplementedErrorr9r&r&r'�close�szAbstractServer.closecCst�dS)z4Get the event loop the Server object is attached to.Nrcr9r&r&r'�get_loop�szAbstractServer.get_loopcCst�dS)z3Return True if the server is accepting connections.Nrcr9r&r&r'�
is_serving�szAbstractServer.is_servingc�st�dS)z�Start accepting connections.

        This method is idempotent, so it can be called when
        the server is already being serving.
        Nrcr9r&r&r'�
start_serving�szAbstractServer.start_servingc�st�dS)z�Start accepting connections until the coroutine is cancelled.

        The server is closed when the coroutine is cancelled.
        Nrcr9r&r&r'�
serve_forever�szAbstractServer.serve_foreverc�st�dS)z*Coroutine to wait until service is closed.Nrcr9r&r&r'�wait_closed�szAbstractServer.wait_closedc�s|Sr;r&r9r&r&r'�
__aenter__�szAbstractServer.__aenter__c�s|��|��IdHdSr;)rerj)r!rCr&r&r'�	__aexit__�szAbstractServer.__aexit__N)r-rGrHrIrerfrgrhrirjrkrlr&r&r&r'r�src@sVeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�dd�Zd d!�Zd"d#�Zd$d%�Zd&d&d&d&d'�d(d)�Zdud*d+�Zdvdd&d&d&ddddddd,�
d-d.�Zdwejejdd/ddddd0d1�	d2d3�Zdxd0d4�d5d6�Zd7ddd8�d9d:�Zdyddddd;�d<d=�Zdzdd/ddd0d>�d?d@�Zd{d&d&d&dddddA�dBdC�Z dDdE�Z!dFdG�Z"e#j$e#j$e#j$dH�dIdJ�Z%e#j$e#j$e#j$dH�dKdL�Z&dMdN�Z'dOdP�Z(dQdR�Z)dSdT�Z*dUdV�Z+dWdX�Z,dYdZ�Z-d[d\�Z.d]d^�Z/d|dd4�d_d`�Z0dadb�Z1dcdd�Z2dedf�Z3dgdh�Z4didj�Z5dkdl�Z6dmdn�Z7dodp�Z8dqdr�Z9dsdt�Z:dS)}rzAbstract event loop.cCst�dS)z*Run the event loop until stop() is called.Nrcr9r&r&r'�run_forever�szAbstractEventLoop.run_forevercCst�dS)zpRun the event loop until a Future is done.

        Return the Future's result, or raise its exception.
        Nrc)r!Zfuturer&r&r'�run_until_complete�sz$AbstractEventLoop.run_until_completecCst�dS)z�Stop the event loop as soon as reasonable.

        Exactly how soon that is may depend on the implementation, but
        no more I/O callbacks should be scheduled.
        Nrcr9r&r&r'�stop�szAbstractEventLoop.stopcCst�dS)z3Return whether the event loop is currently running.Nrcr9r&r&r'�
is_running�szAbstractEventLoop.is_runningcCst�dS)z*Returns True if the event loop was closed.Nrcr9r&r&r'�	is_closed�szAbstractEventLoop.is_closedcCst�dS)z�Close the loop.

        The loop should not be running.

        This is idempotent and irreversible.

        No other methods should be called after this one.
        Nrcr9r&r&r're�s	zAbstractEventLoop.closec�st�dS)z,Shutdown all active asynchronous generators.Nrcr9r&r&r'�shutdown_asyncgens�sz$AbstractEventLoop.shutdown_asyncgenscCst�dS)z3Notification that a TimerHandle has been cancelled.Nrc)r!r=r&r&r'ra�sz)AbstractEventLoop._timer_handle_cancelledcGs|jd|f|��S)Nr)�
call_later�r!r"r#r&r&r'�	call_soonszAbstractEventLoop.call_sooncGst�dSr;rc)r!Zdelayr"r#r&r&r'rsszAbstractEventLoop.call_latercGst�dSr;rc)r!rNr"r#r&r&r'�call_atszAbstractEventLoop.call_atcCst�dSr;rcr9r&r&r'�timeszAbstractEventLoop.timecCst�dSr;rcr9r&r&r'�
create_futureszAbstractEventLoop.create_futureN)�namecCst�dSr;rc)r!�cororyr&r&r'�create_taskszAbstractEventLoop.create_taskcGst�dSr;rcrtr&r&r'�call_soon_threadsafesz&AbstractEventLoop.call_soon_threadsafecGst�dSr;rc)r!�executor�funcr#r&r&r'�run_in_executorsz!AbstractEventLoop.run_in_executorcCst�dSr;rc)r!r}r&r&r'�set_default_executorsz&AbstractEventLoop.set_default_executorr)�family�type�proto�flagsc�st�dSr;rc)r!�host�portr�r�r�r�r&r&r'�getaddrinfo#szAbstractEventLoop.getaddrinfoc�st�dSr;rc)r!Zsockaddrr�r&r&r'�getnameinfo'szAbstractEventLoop.getnameinfo)
�sslr�r�r��sock�
local_addr�server_hostname�ssl_handshake_timeout�happy_eyeballs_delay�
interleavec
�st�dSr;rc)r!�protocol_factoryr�r�r�r�r�r�r�r�r�r�r�r�r&r&r'�create_connection*sz#AbstractEventLoop.create_connection�dT)	r�r�r��backlogr��
reuse_address�
reuse_portr�rhc	
�st�dS)adA coroutine which creates a TCP server bound to host and port.

        The return value is a Server object which can be used to stop
        the service.

        If host is an empty string or None all interfaces are assumed
        and a list of multiple sockets will be returned (most likely
        one for IPv4 and another one for IPv6). The host parameter can also be
        a sequence (e.g. list) of hosts to bind to.

        family can be set to either AF_INET or AF_INET6 to force the
        socket to use IPv4 or IPv6. If not set it will be determined
        from host (defaults to AF_UNSPEC).

        flags is a bitmask for getaddrinfo().

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows.

        ssl_handshake_timeout is the time in seconds that an SSL server
        will wait for completion of the SSL handshake before aborting the
        connection. Default is 60s.

        start_serving set to True (default) causes the created server
        to start accepting connections immediately.  When set to False,
        the user should await Server.start_serving() or Server.serve_forever()
        to make the server to start accepting connections.
        Nrc)
r!r�r�r�r�r�r�r�r�r�r�r�rhr&r&r'�
create_server3s3zAbstractEventLoop.create_server)�fallbackc�st�dS)zRSend a file through a transport.

        Return an amount of sent bytes.
        Nrc)r!�	transport�file�offset�countr�r&r&r'�sendfilehszAbstractEventLoop.sendfileF)�server_sider�r�c�st�dS)z|Upgrade a transport to TLS.

        Return a new transport that *protocol* should start using
        immediately.
        Nrc)r!r�ZprotocolZ
sslcontextr�r�r�r&r&r'�	start_tlsps	zAbstractEventLoop.start_tls)r�r�r�r�c�st�dSr;rc)r!r��pathr�r�r�r�r&r&r'�create_unix_connection{sz(AbstractEventLoop.create_unix_connection)r�r�r�r�rhc�st�dS)a�A coroutine which creates a UNIX Domain Socket server.

        The return value is a Server object, which can be used to stop
        the service.

        path is a str, representing a file systsem path to bind the
        server socket to.

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        ssl_handshake_timeout is the time in seconds that an SSL server
        will wait for the SSL handshake to complete (defaults to 60s).

        start_serving set to True (default) causes the created server
        to start accepting connections immediately.  When set to False,
        the user should await Server.start_serving() or Server.serve_forever()
        to make the server to start accepting connections.
        Nrc)r!r�r�r�r�r�r�rhr&r&r'�create_unix_server�sz$AbstractEventLoop.create_unix_server)r�r�r�r�r��allow_broadcastr�c�st�dS)a�A coroutine which creates a datagram endpoint.

        This method will try to establish the endpoint in the background.
        When successful, the coroutine returns a (transport, protocol) pair.

        protocol_factory must be a callable returning a protocol instance.

        socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
        host (or family if specified), socket type SOCK_DGRAM.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified it will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows and some UNIX's. If the
        :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
        capability is unsupported.

        allow_broadcast tells the kernel to allow this endpoint to send
        messages to the broadcast address.

        sock can optionally be specified in order to use a preexisting
        socket object.
        Nrc)r!r�r�Zremote_addrr�r�r�r�r�r�r�r&r&r'�create_datagram_endpoint�s!z*AbstractEventLoop.create_datagram_endpointc�st�dS)aRegister read pipe in event loop. Set the pipe to non-blocking mode.

        protocol_factory should instantiate object with Protocol interface.
        pipe is a file-like object.
        Return pair (transport, protocol), where transport supports the
        ReadTransport interface.Nrc�r!r��piper&r&r'�connect_read_pipe�sz#AbstractEventLoop.connect_read_pipec�st�dS)aRegister write pipe in event loop.

        protocol_factory should instantiate object with BaseProtocol interface.
        Pipe is file-like object already switched to nonblocking.
        Return pair (transport, protocol), where transport support
        WriteTransport interface.Nrcr�r&r&r'�connect_write_pipe�sz$AbstractEventLoop.connect_write_pipe)�stdin�stdout�stderrc�st�dSr;rc)r!r��cmdr�r�r��kwargsr&r&r'�subprocess_shell�sz"AbstractEventLoop.subprocess_shellc�st�dSr;rc)r!r�r�r�r�r#r�r&r&r'�subprocess_exec�sz!AbstractEventLoop.subprocess_execcGst�dSr;rc�r!�fdr"r#r&r&r'�
add_reader�szAbstractEventLoop.add_readercCst�dSr;rc�r!r�r&r&r'�
remove_reader�szAbstractEventLoop.remove_readercGst�dSr;rcr�r&r&r'�
add_writer�szAbstractEventLoop.add_writercCst�dSr;rcr�r&r&r'�
remove_writer�szAbstractEventLoop.remove_writerc�st�dSr;rc)r!r��nbytesr&r&r'�	sock_recvszAbstractEventLoop.sock_recvc�st�dSr;rc)r!r�Zbufr&r&r'�sock_recv_intosz AbstractEventLoop.sock_recv_intoc�st�dSr;rc)r!r��datar&r&r'�sock_sendallszAbstractEventLoop.sock_sendallc�st�dSr;rc)r!r�Zaddressr&r&r'�sock_connectszAbstractEventLoop.sock_connectc�st�dSr;rc)r!r�r&r&r'�sock_acceptszAbstractEventLoop.sock_acceptc�st�dSr;rc)r!r�r�r�r�r�r&r&r'�
sock_sendfileszAbstractEventLoop.sock_sendfilecGst�dSr;rc)r!�sigr"r#r&r&r'�add_signal_handlersz$AbstractEventLoop.add_signal_handlercCst�dSr;rc)r!r�r&r&r'�remove_signal_handlersz'AbstractEventLoop.remove_signal_handlercCst�dSr;rc)r!�factoryr&r&r'�set_task_factorysz"AbstractEventLoop.set_task_factorycCst�dSr;rcr9r&r&r'�get_task_factory"sz"AbstractEventLoop.get_task_factorycCst�dSr;rcr9r&r&r'�get_exception_handler'sz'AbstractEventLoop.get_exception_handlercCst�dSr;rc)r!Zhandlerr&r&r'�set_exception_handler*sz'AbstractEventLoop.set_exception_handlercCst�dSr;rc�r!r%r&r&r'�default_exception_handler-sz+AbstractEventLoop.default_exception_handlercCst�dSr;rcr�r&r&r'rB0sz(AbstractEventLoop.call_exception_handlercCst�dSr;rcr9r&r&r'r5szAbstractEventLoop.get_debugcCst�dSr;rc)r!Zenabledr&r&r'�	set_debug8szAbstractEventLoop.set_debug)r)NN)NN)rN)N)N)NN)rN);r-rGrHrIrmrnrorprqrerrrarursrvrwrxr{r|rr�r�r�r��socketZ	AF_UNSPECZ
AI_PASSIVEr�r�r�r�r�r�r�r��
subprocess�PIPEr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rBrr�r&r&r&r'r�s��
��
��5�	�����!��%
���rc@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
rz-Abstract policy for accessing the event loop.cCst�dS)a:Get the event loop for the current context.

        Returns an event loop object implementing the BaseEventLoop interface,
        or raises an exception in case no event loop has been set for the
        current context and the current policy does not specify to create one.

        It should never return None.Nrcr9r&r&r'r?sz&AbstractEventLoopPolicy.get_event_loopcCst�dS)z3Set the event loop for the current context to loop.Nrc�r!r$r&r&r'r	Isz&AbstractEventLoopPolicy.set_event_loopcCst�dS)z�Create and return a new event loop object according to this
        policy's rules. If there's need to set this loop as the event loop for
        the current context, set_event_loop must be called explicitly.Nrcr9r&r&r'r
Msz&AbstractEventLoopPolicy.new_event_loopcCst�dS)z$Get the watcher for child processes.Nrcr9r&r&r'rUsz)AbstractEventLoopPolicy.get_child_watchercCst�dS)z$Set the watcher for child processes.Nrc)r!�watcherr&r&r'rYsz)AbstractEventLoopPolicy.set_child_watcherN)	r-rGrHrIrr	r
rrr&r&r&r'r<s
rc@sFeZdZdZdZGdd�dej�Zdd�Zdd�Z	d	d
�Z
dd�ZdS)
�BaseDefaultEventLoopPolicya�Default policy implementation for accessing the event loop.

    In this policy, each thread has its own event loop.  However, we
    only automatically create an event loop by default for the main
    thread; other threads by default have no event loop.

    Other policies may have different rules (e.g. a single global
    event loop, or automatically creating an event loop per thread, or
    using some other notion of context to which an event loop is
    associated).
    Nc@seZdZdZdZdS)z!BaseDefaultEventLoopPolicy._LocalNF)r-rGrHr�_set_calledr&r&r&r'�_Localmsr�cCs|��|_dSr;)r��_localr9r&r&r'r(qsz#BaseDefaultEventLoopPolicy.__init__cCsX|jjdkr2|jjs2tt��tj�r2|�|���|jjdkrPt	dt��j
��|jjS)zvGet the event loop for the current context.

        Returns an instance of EventLoop or raises an exception.
        Nz,There is no current event loop in thread %r.)r�rr�r^�	threadingZcurrent_threadZ_MainThreadr	r
�RuntimeErrorryr9r&r&r'rts���z)BaseDefaultEventLoopPolicy.get_event_loopcCsd|j_||j_dS)zSet the event loop.TN)r�r�rr�r&r&r'r	�sz)BaseDefaultEventLoopPolicy.set_event_loopcCs|��S)zvCreate a new event loop.

        You must call set_event_loop() to make this the current event
        loop.
        )�
_loop_factoryr9r&r&r'r
�sz)BaseDefaultEventLoopPolicy.new_event_loop)r-rGrHrIr�r��localr�r(rr	r
r&r&r&r'r�^sr�c@seZdZdZdS)�_RunningLoop)NNN)r-rGrH�loop_pidr&r&r&r'r��sr�cCst�}|dkrtd��|S)zrReturn the running event loop.  Raise a RuntimeError if there is none.

    This function is thread-specific.
    Nzno running event loop)rr��r$r&r&r'r�srcCs&tj\}}|dk	r"|t��kr"|SdS)z�Return the running event loop or None.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)�
_running_loopr��os�getpid)Zrunning_loop�pidr&r&r'r�s
rcCs|t��ft_dS)z�Set the running event loop.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)r�r�r�r�r�r&r&r'r
�sr
c	Cs.t� tdkr ddlm}|�aW5QRXdS)Nr��DefaultEventLoopPolicy)�_lock�_event_loop_policy�r�r�r&r&r'�_init_event_loop_policy�sr�cCstdkrt�tS)z"Get the current event loop policy.N)r�r�r&r&r&r'r�srcCs|adS)zZSet the current event loop policy.

    If policy is None, the default policy is restored.N)r�)Zpolicyr&r&r'r�srcCst�}|dk	r|St���S)aGReturn an asyncio event loop.

    When called from a coroutine or a callback (e.g. scheduled with call_soon
    or similar API), this function will always return the running event loop.

    If there is no running event loop set, the function will return
    the result of `get_event_loop_policy().get_event_loop()` call.
    N)rrr)Zcurrent_loopr&r&r'r�s
rcCst��|�dS)zCEquivalent to calling get_event_loop_policy().set_event_loop(loop).N)rr	r�r&r&r'r	�sr	cCs
t���S)z?Equivalent to calling get_event_loop_policy().new_event_loop().)rr
r&r&r&r'r
�sr
cCs
t���S)zBEquivalent to calling get_event_loop_policy().get_child_watcher().)rrr&r&r&r'r�srcCst��|�S)zMEquivalent to calling
    get_event_loop_policy().set_child_watcher(watcher).)rr)r�r&r&r'r�sr)rr
rr),rI�__all__rr�r�r�rr�r�rrrrrrrr�r�ZLockr�r�r�r�rrr
r�rrrr	r
rrZ_py__get_running_loopZ_py__set_running_loopZ_py_get_running_loopZ_py_get_event_loopZ_asyncio�ImportErrorZ_c__get_running_loopZ_c__set_running_loopZ_c_get_running_loopZ_c_get_event_loopr&r&r&r'�<module>sXJ@*q"9
	PK [C��ktTtT#__pycache__/sslproto.cpython-38.pycnu�[���U

e5dJj�@s�ddlZddlZzddlZWnek
r4dZYnXddlmZddlmZddlmZddlmZddl	m
Z
dd	�Zd
ZdZ
dZd
ZGdd�de�ZGdd�dejej�ZGdd�dej�ZdS)�N�)�base_events)�	constants)�	protocols)�
transports)�loggercCs"|rtd��t��}|sd|_|S)Nz(Server side SSL needs a valid SSLContextF)�
ValueError�sslZcreate_default_contextZcheck_hostname)�server_side�server_hostname�
sslcontext�r
�(/usr/lib64/python3.8/asyncio/sslproto.py�_create_transport_contextsrZ	UNWRAPPEDZDO_HANDSHAKEZWRAPPEDZSHUTDOWNc@s~eZdZdZdZddd�Zedd��Zedd	��Zed
d��Z	edd
��Z
ddd�Zddd�Zdd�Z
ddd�Zddd�ZdS)�_SSLPipeaAn SSL "Pipe".

    An SSL pipe allows you to communicate with an SSL/TLS protocol instance
    through memory buffers. It can be used to implement a security layer for an
    existing connection where you don't have access to the connection's file
    descriptor, or for some reason you don't want to use it.

    An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
    data is passed through untransformed. In wrapped mode, application level
    data is encrypted to SSL record level data and vice versa. The SSL record
    level is the lowest level in the SSL protocol suite and is what travels
    as-is over the wire.

    An SslPipe initially is in "unwrapped" mode. To start SSL, call
    do_handshake(). To shutdown SSL again, call unwrap().
    iNcCsH||_||_||_t|_t��|_t��|_d|_	d|_
d|_d|_dS)a�
        The *context* argument specifies the ssl.SSLContext to use.

        The *server_side* argument indicates whether this is a server side or
        client side transport.

        The optional *server_hostname* argument can be used to specify the
        hostname you are connecting to. You may only specify this parameter if
        the _ssl module supports Server Name Indication (SNI).
        NF)
�_context�_server_side�_server_hostname�
_UNWRAPPED�_stater	Z	MemoryBIO�	_incoming�	_outgoing�_sslobj�
_need_ssldata�
_handshake_cb�_shutdown_cb)�self�contextr
rr
r
r�__init__8s

z_SSLPipe.__init__cCs|jS)z*The SSL context passed to the constructor.)r�rr
r
rrNsz_SSLPipe.contextcCs|jS)z^The internal ssl.SSLObject instance.

        Return None if the pipe is not wrapped.
        )rrr
r
r�
ssl_objectSsz_SSLPipe.ssl_objectcCs|jS)zgWhether more record level data is needed to complete a handshake
        that is currently in progress.)rrr
r
r�need_ssldata[sz_SSLPipe.need_ssldatacCs
|jtkS)zj
        Whether a security layer is currently in effect.

        Return False during handshake.
        )r�_WRAPPEDrr
r
r�wrappedasz_SSLPipe.wrappedcCsb|jtkrtd��|jj|j|j|j|jd�|_	t
|_||_|jddd�\}}t
|�dks^t�|S)aLStart the SSL handshake.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the handshake is complete. The callback will be
        called with None if successful, else an exception instance.
        z"handshake in progress or completed)r
r�T)�only_handshaker)rr�RuntimeErrorrZwrap_biorrrrr�
_DO_HANDSHAKEr�feed_ssldata�len�AssertionError�r�callback�ssldata�appdatar
r
r�do_handshakejs	
�z_SSLPipe.do_handshakecCsj|jtkrtd��|jtkr$td��|jttfks6t�t|_||_|�d�\}}|gksf|dgksft�|S)a1Start the SSL shutdown sequence.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the shutdown is complete. The callback will be
        called without arguments.
        zno security layer presentzshutdown in progressr$)	rrr&�	_SHUTDOWNr"r'r*rr(r+r
r
r�shutdowns	

z_SSLPipe.shutdowncCs2|j��|�d�\}}|gks.|dgks.t�dS)z�Send a potentially "ragged" EOF.

        This method will raise an SSL_ERROR_EOF exception if the EOF is
        unexpected.
        r$N)rZ	write_eofr(r*)rr-r.r
r
r�feed_eof�s
z_SSLPipe.feed_eofFc
Cs�|jtkr"|r|g}ng}g|fSd|_|r8|j�|�g}g}z�|jtkrz|j��t|_|j	rl|�	d�|rz||fWS|jtkr�|j�
|j�}|�|�|s�q�q�nJ|jt
kr�|j��d|_t|_|jr�|��n|jtkr�|�|j�
��Wnztjtjfk
�rl}zRt|dd�}|tjtjtjfk�rP|jtk�rN|j	�rN|�	|��|tjk|_W5d}~XYnX|jj�r�|�|j�
��||fS)a�Feed SSL record level data into the pipe.

        The data must be a bytes instance. It is OK to send an empty bytes
        instance. This can be used to get ssldata for a handshake initiated by
        this endpoint.

        Return a (ssldata, appdata) tuple. The ssldata element is a list of
        buffers containing SSL data that needs to be sent to the remote SSL.

        The appdata element is a list of buffers containing plaintext data that
        needs to be forwarded to the application. The appdata list may contain
        an empty buffer indicating an SSL "close_notify" alert. This alert must
        be acknowledged by calling shutdown().
        FN�errno)rrrr�writer'rr/r"r�read�max_size�appendr0Zunwraprr	�SSLError�CertificateError�getattr�SSL_ERROR_WANT_READ�SSL_ERROR_WANT_WRITE�SSL_ERROR_SYSCALLr�pending)r�datar%r.r-�chunk�exc�	exc_errnor
r
rr(�sZ










�

z_SSLPipe.feed_ssldatarc
Cs4d|krt|�ksnt�|jtkrT|t|�krD||d�g}ng}|t|�fSg}t|�}d|_z(|t|�kr�||j�||d��7}Wnhtj	k
r�}zHt
|dd�}|jdkr�tj}|_
|tjtjtjfkrڂ|tjk|_W5d}~XYnX|jj�r|�|j���|t|�k�s,|jr`�q,q`||fS)aFeed plaintext data into the pipe.

        Return an (ssldata, offset) tuple. The ssldata element is a list of
        buffers containing record level data that needs to be sent to the
        remote SSL instance. The offset is the number of plaintext bytes that
        were processed, which may be less than the length of data.

        NOTE: In case of short writes, this call MUST be retried with the SAME
        buffer passed into the *data* argument (i.e. the id() must be the
        same). This is an OpenSSL requirement. A further particularity is that
        a short write will always have offset == 0, because the _ssl module
        does not enable partial writes. And even though the offset is zero,
        there will still be encrypted data in ssldata.
        rNFr3ZPROTOCOL_IS_SHUTDOWN)r)r*rr�
memoryviewrrr4r	r8r:�reasonr;r3r<r=rr>r7r5)rr?�offsetr-ZviewrArBr
r
r�feed_appdata�s6

�
z_SSLPipe.feed_appdata)N)N)N)F)r)�__name__�
__module__�__qualname__�__doc__r6r�propertyrr r!r#r/r1r2r(rFr
r
r
rr$s 








Krc@s�eZdZejjZdd�Zd"dd�Zdd�Z	dd	�Z
d
d�Zdd
�Ze
jfdd�Zdd�Zdd�Zdd�Zd#dd�Zdd�Zedd��Zdd�Zdd�Zd d!�ZdS)$�_SSLProtocolTransportcCs||_||_d|_dS)NF)�_loop�
_ssl_protocol�_closed)r�loopZssl_protocolr
r
rr!sz_SSLProtocolTransport.__init__NcCs|j�||�S)z#Get optional transport information.)rN�_get_extra_info�r�name�defaultr
r
r�get_extra_info'sz$_SSLProtocolTransport.get_extra_infocCs|j�|�dS�N)rN�_set_app_protocol)r�protocolr
r
r�set_protocol+sz"_SSLProtocolTransport.set_protocolcCs|jjSrV)rN�
_app_protocolrr
r
r�get_protocol.sz"_SSLProtocolTransport.get_protocolcCs|jSrV)rOrr
r
r�
is_closing1sz _SSLProtocolTransport.is_closingcCsd|_|j��dS)a
Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        TN)rOrN�_start_shutdownrr
r
r�close4sz_SSLProtocolTransport.closecCs&|js"|d|��t|d�|��dS)Nzunclosed transport )�source)rO�ResourceWarningr^)rZ_warnr
r
r�__del__?sz_SSLProtocolTransport.__del__cCs |jj}|dkrtd��|��S)Nz*SSL transport has not been initialized yet)rN�
_transportr&�
is_reading)rZtrr
r
rrcDsz _SSLProtocolTransport.is_readingcCs|jj��dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        N)rNrb�
pause_readingrr
r
rrdJsz#_SSLProtocolTransport.pause_readingcCs|jj��dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        N)rNrb�resume_readingrr
r
rreRsz$_SSLProtocolTransport.resume_readingcCs|jj�||�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        N)rNrb�set_write_buffer_limits)rZhighZlowr
r
rrfZsz-_SSLProtocolTransport.set_write_buffer_limitscCs|jj��S)z,Return the current size of the write buffer.)rNrb�get_write_buffer_sizerr
r
rrgosz+_SSLProtocolTransport.get_write_buffer_sizecCs
|jjjSrV)rNrb�_protocol_pausedrr
r
rrhssz&_SSLProtocolTransport._protocol_pausedcCs<t|tttf�s$tdt|�j����|s,dS|j�|�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        z+data: expecting a bytes-like instance, got N)	�
isinstance�bytes�	bytearrayrC�	TypeError�typerGrN�_write_appdata�rr?r
r
rr4xs
z_SSLProtocolTransport.writecCsdS)zAReturn True if this transport supports write_eof(), False if not.Fr
rr
r
r�
can_write_eof�sz#_SSLProtocolTransport.can_write_eofcCs|j��d|_dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        TN)rN�_abortrOrr
r
r�abort�s
z_SSLProtocolTransport.abort)N)NN)rGrHrIrZ
_SendfileModeZFALLBACKZ_sendfile_compatiblerrUrYr[r\r^�warnings�warnrarcrdrerfrgrKrhr4rprrr
r
r
rrLs$



rLc@s�eZdZdZd,dd�Zdd�Zd-d	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Zd.dd�Z
dd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd/d&d'�Zd(d)�Zd*d+�ZdS)0�SSLProtocolz�SSL protocol.

    Implementation of SSL on top of a socket using incoming and outgoing
    buffers which are ssl.MemoryBIO objects.
    FNTc		Cs�tdkrtd��|dkr tj}n|dkr6td|����|sDt||�}||_|rZ|sZ||_nd|_||_t	|d�|_
t��|_
d|_||_||_|�|�t|j|�|_d|_d|_d|_d|_d|_||_||_dS)Nzstdlib ssl module not availablerz7ssl_handshake_timeout should be a positive number, got )rF)r	r&rZSSL_HANDSHAKE_TIMEOUTrrrr�_sslcontext�dict�_extra�collections�deque�_write_backlog�_write_buffer_size�_waiterrMrWrL�_app_transport�_sslpipe�_session_established�
_in_handshake�_in_shutdownrb�_call_connection_made�_ssl_handshake_timeout)	rrP�app_protocolrZwaiterr
rZcall_connection_madeZssl_handshake_timeoutr
r
rr�s@��

zSSLProtocol.__init__cCs||_t|tj�|_dSrV)rZrirZBufferedProtocol�_app_protocol_is_buffer)rr�r
r
rrW�s
�zSSLProtocol._set_app_protocolcCsD|jdkrdS|j��s:|dk	r.|j�|�n|j�d�d|_dSrV)r}Z	cancelledZ
set_exceptionZ
set_result�rrAr
r
r�_wakeup_waiter�s

zSSLProtocol._wakeup_waitercCs&||_t|j|j|j�|_|��dS)zXCalled when the low-level connection is made.

        Start the SSL handshake.
        N)rbrrvrrr�_start_handshake)r�	transportr
r
r�connection_made�s�zSSLProtocol.connection_madecCsn|jr d|_|j�|jj|�n|jdk	r2d|j_d|_d|_t|dd�rT|j	�
�|�|�d|_d|_dS)z�Called when the low-level connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        FNT�_handshake_timeout_handle)
r�rM�	call_soonrZ�connection_lostr~rOrbr:r��cancelr�rr�r
r
rr��s


zSSLProtocol.connection_lostcCs|j��dS)z\Called when the low-level transport's buffer goes over
        the high-water mark.
        N)rZ�
pause_writingrr
r
rr��szSSLProtocol.pause_writingcCs|j��dS)z^Called when the low-level transport's buffer drains below
        the low-water mark.
        N)rZ�resume_writingrr
r
rr�szSSLProtocol.resume_writingcCs"|jdkrdSz|j�|�\}}WnLttfk
r<�Yn4tk
rn}z|�|d�WY�dSd}~XYnX|D]}|j�|�qt|D]�}|�rz&|jr�t	�
|j|�n|j�|�WnPttfk
r��Yn8tk
�r
}z|�|d�WY�dSd}~XYnXq�|�
��qq�dS)zXCalled when some SSL data is received.

        The argument is a bytes object.
        NzSSL error in data receivedz/application protocol failed to receive SSL data)rr(�
SystemExit�KeyboardInterrupt�
BaseException�_fatal_errorrbr4r�rZ_feed_data_to_buffered_protorZ�
data_receivedr])rr?r-r.�er@Zexr
r
rr�s<
��zSSLProtocol.data_receivedcCsTzB|j��rt�d|�|�t�|js@|j	�
�}|r@t�d�W5|j��XdS)aCalled when the other end of the low-level stream
        is half-closed.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        z%r received EOFz?returning true from eof_received() has no effect when using sslN)rbr^rM�	get_debugr�debugr��ConnectionResetErrorr�rZ�eof_receivedZwarning)rZ	keep_openr
r
rr�-s


zSSLProtocol.eof_receivedcCs4||jkr|j|S|jdk	r,|j�||�S|SdSrV)rxrbrUrRr
r
rrQCs



zSSLProtocol._get_extra_infocCs.|jr
dS|jr|��nd|_|�d�dS)NTr$)r�r�rqrnrr
r
rr]Ks
zSSLProtocol._start_shutdowncCs.|j�|df�|jt|�7_|��dS)Nr)r{r7r|r)�_process_write_backlogror
r
rrnTszSSLProtocol._write_appdatacCs\|j��r$t�d|�|j��|_nd|_d|_|j�d�|j�	|j
|j�|_|�
�dS)Nz%r starts SSL handshakeT)r$r)rMr�rr��time�_handshake_start_timer�r{r7Z
call_laterr��_check_handshake_timeoutr�r�rr
r
rr�Ys

��zSSLProtocol._start_handshakecCs*|jdkr&d|j�d�}|�t|��dS)NTz$SSL handshake is taking longer than z! seconds: aborting the connection)r�r�r��ConnectionAbortedError)r�msgr
r
rr�hs
�z$SSLProtocol._check_handshake_timeoutc
Csd|_|j��|jj}z|dk	r&|�|��}Wnbttfk
rJ�YnJtk
r�}z,t	|t
j�rld}nd}|�||�WY�dSd}~XYnX|j
��r�|j
��|j}t�d||d�|jj||��|��|d�|jr�|j�|j�|��d|_|j
�|j�dS)NFz1SSL handshake failed on verifying the certificatezSSL handshake failedz%r: SSL handshake took %.1f msg@�@)�peercert�cipher�compressionr T)r�r�r�rr Zgetpeercertr�r�r�rir	r9r�rMr�r�r�rr�rx�updater�r�r�rZr�r~r�r�r�r�)rZ
handshake_excZsslobjr�rAr�Zdtr
r
r�_on_handshake_completeqs8

�z"SSLProtocol._on_handshake_completec
CsP|jdks|jdkrdSz�tt|j��D]�}|jd\}}|rR|j�||�\}}n*|rj|j�|j�}d}n|j�|j	�}d}|D]}|j�
|�q�|t|�kr�||f|jd<|jjs�t�|jj
r�|j��q�|jd=|jt|�8_q(Wn^ttfk
�r�YnDtk
�rJ}z$|j�r.|�|�n|�|d�W5d}~XYnXdS)NrrzFatal error on SSL transport)rbr�ranger)r{rFr/r�r1�	_finalizer4r!r*Z_pausedrer|r�r�r�r�r�)r�ir?rEr-r@rAr
r
rr��s<�
z"SSLProtocol._process_write_backlog�Fatal error on transportcCsVt|t�r(|j��r@tjd||dd�n|j�|||j|d��|jrR|j�|�dS)Nz%r: %sT)�exc_info)�messageZ	exceptionr�rX)	ri�OSErrorrMr�rr�Zcall_exception_handlerrbZ_force_close)rrAr�r
r
rr��s

�zSSLProtocol._fatal_errorcCsd|_|jdk	r|j��dSrV)rrbr^rr
r
rr��s
zSSLProtocol._finalizecCs(z|jdk	r|j��W5|��XdSrV)r�rbrrrr
r
rrq�s
zSSLProtocol._abort)FNTN)N)N)r�)rGrHrIrJrrWr�r�r�r�r�r�r�rQr]rnr�r�r�r�r�r�rqr
r
r
rru�s0�
.

&
		)+
ru)ryrsr	�ImportError�rrrr�logrrrr'r"r0�objectrZ_FlowControlMixinZ	TransportrLZProtocolrur
r
r
r�<module>s*
y�xPK [$��'��+__pycache__/base_tasks.cpython-38.opt-2.pycnu�[���U

e5d�	�@sDddlZddlZddlmZddlmZdd�Zdd�Zd	d
�ZdS)�N�)�base_futures)�
coroutinescCsnt�|�}|jrd|d<|�dd|���t�|j�}|�dd|�d��|jdk	rj|�dd	|j���|S)
NZ
cancellingrrzname=%r�zcoro=<�>�z	wait_for=)	rZ_future_repr_infoZ_must_cancel�insertZget_namerZ_format_coroutine�_coroZ_fut_waiter)�task�info�coro�r
�*/usr/lib64/python3.8/asyncio/base_tasks.py�_task_repr_infos

rcCs�g}t|jd�r|jj}n0t|jd�r0|jj}nt|jd�rF|jj}nd}|dk	r�|dk	r�|dk	rt|dkrlq�|d8}|�|�|j}qR|��nH|jdk	r�|jj	}|dk	r�|dk	r�|dkr�q�|d8}|�|j
�|j}q�|S)N�cr_frame�gi_frame�ag_framerr)�hasattrr	rrr�append�f_back�reverse�
_exception�
__traceback__�tb_frame�tb_next)r
�limitZframes�f�tbr
r
r�_task_get_stacks6





rcCs�g}t�}|j|d�D]Z}|j}|j}|j}|j}	||krN|�|�t�|�t�	|||j
�}
|�|||	|
f�q|j}|s�t
d|��|d�n2|dk	r�t
d|�d�|d�nt
d|�d�|d�tj||d�|dk	r�t�|j|�D]}
t
|
|dd�q�dS)	N)rz
No stack for )�filezTraceback for z (most recent call last):z
Stack for �)r�end)�setZ	get_stack�f_lineno�f_code�co_filename�co_name�add�	linecache�
checkcache�getline�	f_globalsrr�print�	traceback�
print_list�format_exception_only�	__class__)r
rr�extracted_list�checkedr�lineno�co�filename�name�line�excr
r
r�_task_print_stack<s,

r9)r(r-r rrrrr9r
r
r
r�<module>s#PK [��q�ll'__pycache__/base_futures.cpython-38.pycnu�[���U

e5d
�@sRdZddlZddlmZddlmZdZdZdZd	d
�Z	dd�Z
e�Zd
d�Z
dS)��N)�	get_ident�)�format_helpersZPENDINGZ	CANCELLEDZFINISHEDcCst|jd�o|jdk	S)z�Check for a Future.

    This returns True when obj is a Future instance or is advertising
    itself as duck-type compatible by setting _asyncio_future_blocking.
    See comment in Future for more details.
    �_asyncio_future_blockingN)�hasattr�	__class__r)�objrr�,/usr/lib64/python3.8/asyncio/base_futures.py�isfutures�rcCs�t|�}|sd}dd�}|dkr2||dd�}n`|dkr`d�||dd�||dd��}n2|dkr�d�||dd�|d||d	d��}d
|�d�S)�#helper function for Future.__repr__�cSst�|d�S)Nr)rZ_format_callback_source)�callbackrrr
�	format_cbsz$_format_callbacks.<locals>.format_cbrr�z{}, {}z{}, <{} more>, {}���zcb=[�])�len�format)�cb�sizerrrr
�_format_callbackss&�rc	Cs�|j��g}|jtkr�|jdk	r4|�d|j���nTt|�t�f}|tkrPd}n(t�|�zt
�|j�}W5t�	|�X|�d|���|j
r�|�t|j
��|jr�|jd}|�d|d�d|d	���|S)
rNz
exception=z...zresult=rzcreated at r�:r)Z_state�lower�	_FINISHEDZ
_exception�append�idr�
_repr_running�add�discard�reprlib�reprZ_resultZ
_callbacksrZ_source_traceback)Zfuture�info�key�result�framerrr
�_future_repr_info7s$



r&)�__all__r �_threadrr
rZ_PENDINGZ
_CANCELLEDrrr�setrr&rrrr
�<module>sPK [r׉nn-__pycache__/base_futures.cpython-38.opt-2.pycnu�[���U

e5d
�@sRdZddlZddlmZddlmZdZdZdZd	d
�Z	dd�Z
e�Zd
d�Z
dS)��N)�	get_ident�)�format_helpersZPENDINGZ	CANCELLEDZFINISHEDcCst|jd�o|jdk	S)N�_asyncio_future_blocking)�hasattr�	__class__r)�objrr�,/usr/lib64/python3.8/asyncio/base_futures.py�isfutures�rcCs�t|�}|sd}dd�}|dkr2||dd�}n`|dkr`d�||dd�||dd��}n2|dkr�d�||dd�|d||d	d��}d
|�d�S)N�cSst�|d�S)Nr)rZ_format_callback_source)�callbackrrr
�	format_cbsz$_format_callbacks.<locals>.format_cbrr�z{}, {}z{}, <{} more>, {}���zcb=[�])�len�format)�cb�sizerrrr
�_format_callbackss&�rc	Cs�|j��g}|jtkr�|jdk	r4|�d|j���nTt|�t�f}|tkrPd}n(t�|�zt
�|j�}W5t�	|�X|�d|���|j
r�|�t|j
��|jr�|jd}|�d|d�d|d���|S)	Nz
exception=z...zresult=rzcreated at r�:r)Z_state�lower�	_FINISHEDZ
_exception�append�idr�
_repr_running�add�discard�reprlib�reprZ_resultZ
_callbacksrZ_source_traceback)Zfuture�info�key�result�framerrr
�_future_repr_info7s$



r%)�__all__r�_threadrrrZ_PENDINGZ
_CANCELLEDrrr�setrr%rrrr
�<module>sPK [��+�[�[0__pycache__/proactor_events.cpython-38.opt-2.pycnu�[���U

e5d<}�@sPdZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZddlmZddlm
Z
dd	lmZdd
lmZddlmZddlmZd
d�ZGdd�dejej�ZGdd�deej�ZGdd�deej�ZGdd�de�ZGdd�de�ZGdd�deeej�ZGdd�deeej�ZGdd�de	j �Z!dS))�BaseProactorEventLoop�N�)�base_events)�	constants)�futures)�
exceptions)�	protocols)�sslproto)�
transports)�trsock)�loggercCs�t�|�|jd<z|��|jd<Wn0tjk
rR|j��rNtj	d|dd�YnXd|jkr�z|�
�|jd<Wn tjk
r�d|jd<YnXdS)N�socketZsocknamezgetsockname() failed on %rT��exc_info�peername)r�TransportSocket�_extraZgetsocknamer
�error�_loop�	get_debugr�warningZgetpeername)�	transport�sock�r�//usr/lib64/python3.8/asyncio/proactor_events.py�_set_socket_extras
�
rcs~eZdZd�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jfdd�Zddd�Z
dd�Zdd�Zdd�Z�ZS)�_ProactorBasePipeTransportNcs�t��||�|�|�||_|�|�||_d|_d|_d|_d|_	d|_
d|_d|_|jdk	rl|j�
�|j�|jj|�|dk	r�|j�tj|d�dS)NrF)�super�__init__�
_set_extra�_sock�set_protocol�_server�_buffer�	_read_fut�
_write_fut�_pending_write�
_conn_lost�_closing�_eof_writtenZ_attachr�	call_soon�	_protocolZconnection_maderZ_set_result_unless_cancelled��self�loopr�protocol�waiter�extra�server��	__class__rrr2s(




�z#_ProactorBasePipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|jdk	rP|�d|j�����|jdk	rl|�d|j���|jdk	r�|�d|j���|jr�|�dt	|j����|j
r�|�d�d�d	�|��S)
N�closed�closingzfd=zread=zwrite=zwrite_bufsize=zEOF writtenz<{}>� )
r4�__name__r �appendr(�filenor$r%r#�lenr)�format�join)r-�inforrr�__repr__Hs 






z#_ProactorBasePipeTransport.__repr__cCs||jd<dS)N�pipe)r�r-rrrrrZsz%_ProactorBasePipeTransport._set_extracCs
||_dS�N�r+)r-r/rrrr!]sz'_ProactorBasePipeTransport.set_protocolcCs|jSrBrC�r-rrr�get_protocol`sz'_ProactorBasePipeTransport.get_protocolcCs|jSrB)r(rDrrr�
is_closingcsz%_ProactorBasePipeTransport.is_closingcCs\|jr
dSd|_|jd7_|js>|jdkr>|j�|jd�|jdk	rX|j��d|_dS)NTr)	r(r'r#r%rr*�_call_connection_lostr$�cancelrDrrr�closefs

z _ProactorBasePipeTransport.closecCs*|jdk	r&|d|��t|d�|��dS)Nzunclosed transport )�source)r �ResourceWarningrI)r-Z_warnrrr�__del__qs
z"_ProactorBasePipeTransport.__del__�Fatal error on pipe transportc	CsVzDt|t�r*|j��rBtjd||dd�n|j�||||jd��W5|�|�XdS)Nz%r: %sTr)�message�	exceptionrr/)	�_force_close�
isinstance�OSErrorrrr�debug�call_exception_handlerr+)r-�excrNrrr�_fatal_errorvs

�z'_ProactorBasePipeTransport._fatal_errorcCs�|jdk	r6|j��s6|dkr*|j�d�n|j�|�|jr@dSd|_|jd7_|jrj|j��d|_|jr�|j��d|_d|_	d|_
|j�|j
|�dS)NTrr)�
_empty_waiter�done�
set_resultZ
set_exceptionr(r'r%rHr$r&r#rr*rG)r-rUrrrrP�s"

z'_ProactorBasePipeTransport._force_closec	Cs^z|j�	|�W5t|jd�r,|j�tj�|j��d|_|j}|dk	rX|��d|_XdS)N�shutdown)
�hasattrr rZr
Z	SHUT_RDWRrIr"Z_detachr+Zconnection_lost)r-rUr2rrrrG�s
z0_ProactorBasePipeTransport._call_connection_lostcCs"|j}|jdk	r|t|j�7}|SrB)r&r#r;)r-�sizerrr�get_write_buffer_size�s
z0_ProactorBasePipeTransport.get_write_buffer_size)NNN)rM)r8�
__module__�__qualname__rr?rr!rErFrI�warnings�warnrLrVrPrGr]�
__classcell__rrr3rr.s�
rcsPeZdZd�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zddd�Z	�Z
S)�_ProactorReadPipeTransportNcs:d|_d|_t��||||||�|j�|j�d|_dS)NTF)�
_pending_data�_pausedrrrr*�
_loop_readingr,r3rrr�s
z#_ProactorReadPipeTransport.__init__cCs|jo|jSrB)rer(rDrrr�
is_reading�sz%_ProactorReadPipeTransport.is_readingcCs0|js|jrdSd|_|j��r,t�d|�dS)NTz%r pauses reading)r(rerrrrSrDrrr�
pause_reading�s

z(_ProactorReadPipeTransport.pause_readingcCsn|js|jsdSd|_|jdkr0|j�|jd�|j}d|_|dk	rT|j�|j|�|j��rjt	�
d|�dS)NFz%r resumes reading)r(rer$rr*rfrd�_data_receivedrrrS�r-�datarrr�resume_reading�s

z)_ProactorReadPipeTransport.resume_readingc
Cs�|j��rt�d|�z|j��}WnLttfk
r>�Yn4tk
rp}z|�	|d�WY�dSd}~XYnX|s~|�
�dS)Nz%r received EOFz1Fatal error: protocol.eof_received() call failed.)rrrrSr+Zeof_received�
SystemExit�KeyboardInterrupt�
BaseExceptionrVrI)r-Z	keep_openrUrrr�
_eof_received�s
�z(_ProactorReadPipeTransport._eof_receivedc
Cs�|jr||_dS|s |��dSt|jtj�r�zt�|j|�Wq�tt	fk
rZ�Yq�t
k
r�}z|�|d�WY�dSd}~XYq�Xn|j�|�dS)Nz3Fatal error: protocol.buffer_updated() call failed.)
rerdrprQr+rZBufferedProtocolZ_feed_data_to_buffered_protormrnrorVZ
data_received)r-rkrUrrrri�s"�z)_ProactorReadPipeTransport._data_receivedc
Cstd}�zRzp|dk	r2d|_|��r*|��}n|��|jrHd}WW��dS|dkr\WW��dS|jsv|jj�	|j
d�|_Wn�tk
r�}z0|js�|�|d�n|j�
�r�tjddd�W5d}~XYn�tk
r�}z|�|�W5d}~XYnftk
�r}z|�|d�W5d}~XYn8tjk
�r>|j�s:�YnX|j�sV|j�|j�W5|dk	�rn|�|�XdS)N�i�z"Fatal read error on pipe transportz*Read error on pipe transport while closingTr)rir$rX�resultrHr(rer�	_proactor�recvr �ConnectionAbortedErrorrVrrrS�ConnectionResetErrorrPrRr�CancelledError�add_done_callbackrf)r-�futrkrUrrrrfs@

�
z(_ProactorReadPipeTransport._loop_reading)NNN)N)r8r^r_rrgrhrlrprirfrbrrr3rrc�s�	rccsZeZdZdZ�fdd�Zdd�Zddd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Z�ZS)�_ProactorBaseWritePipeTransportTcst�j||�d|_dSrB)rrrW�r-�args�kwr3rrrGsz(_ProactorBaseWritePipeTransport.__init__cCs�t|tttf�s$tdt|�j����|jr2td��|j	dk	rDtd��|sLdS|j
rz|j
tjkrht
�d�|j
d7_
dS|jdkr�|jt|�d�n.|js�t|�|_|��n|j�|�|��dS)Nz/data argument must be a bytes-like object, not zwrite_eof() already calledz(unable to write; sendfile is in progresszsocket.send() raised exception.r)rk)rQ�bytes�	bytearray�
memoryview�	TypeError�typer8r)�RuntimeErrorrWr'r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESrrr%�
_loop_writingr#�_maybe_pause_protocol�extendrjrrr�writeKs,�




z%_ProactorBaseWritePipeTransport.writeNc
CsVz�|dk	r |jdkr |jr WdSd|_d|_|r8|��|dkrL|j}d|_|s�|jrf|j�|jd�|jrz|j	�
tj�|�
�nN|jj�|j	|�|_|j��s�t|�|_|j�|j�|��n|j�|j�|jdk	r�|jdkr�|j�d�Wn\tk
�r"}z|�|�W5d}~XYn0tk
�rP}z|�|d�W5d}~XYnXdS)Nrz#Fatal write error on pipe transport)r%r(r&rrr#rr*rGr)r rZr
�SHUT_WR�_maybe_resume_protocolrs�sendrXr;rxr�r�rWrYrvrPrRrV)r-�frkrUrrrr�qs8



z-_ProactorBaseWritePipeTransport._loop_writingcCsdS�NTrrDrrr�
can_write_eof�sz-_ProactorBaseWritePipeTransport.can_write_eofcCs|��dSrB)rIrDrrr�	write_eof�sz)_ProactorBaseWritePipeTransport.write_eofcCs|�d�dSrB�rPrDrrr�abort�sz%_ProactorBaseWritePipeTransport.abortcCs:|jdk	rtd��|j��|_|jdkr4|j�d�|jS)NzEmpty waiter is already set)rWr�rZ
create_futurer%rYrDrrr�_make_empty_waiter�s

z2_ProactorBaseWritePipeTransport._make_empty_waitercCs
d|_dSrB)rWrDrrr�_reset_empty_waiter�sz3_ProactorBaseWritePipeTransport._reset_empty_waiter)NN)
r8r^r_Z_start_tls_compatiblerr�r�r�r�r�r�r�rbrrr3rrzAs&
)rzcs$eZdZ�fdd�Zdd�Z�ZS)�_ProactorWritePipeTransportcs4t�j||�|jj�|jd�|_|j�|j�dS)N�)	rrrrsrtr r$rx�_pipe_closedr{r3rrr�sz$_ProactorWritePipeTransport.__init__cCs@|��rdS|jrdSd|_|jdk	r4|�t��n|��dSrB)Z	cancelledr(r$r%rP�BrokenPipeErrorrI)r-ryrrrr��s
z(_ProactorWritePipeTransport._pipe_closed)r8r^r_rr�rbrrr3rr��sr�csXeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zddd�Zdd
d�Z	ddd�Z
�ZS)�_ProactorDatagramTransportiNcs>||_d|_t�j|||||d�t��|_|j�|j	�dS)N)r0r1)
�_addressrWrr�collections�dequer#rr*rf)r-r.rr/�addressr0r1r3rrr�s

z#_ProactorDatagramTransport.__init__cCst||�dSrB�rrArrrr�sz%_ProactorDatagramTransport._set_extracCstdd�|jD��S)Ncss|]\}}t|�VqdSrB)r;)�.0rk�_rrr�	<genexpr>�szC_ProactorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr#rDrrrr]�sz0_ProactorDatagramTransport.get_write_buffer_sizecCs|�d�dSrBr�rDrrrr��sz _ProactorDatagramTransport.abortcCs�t|tttf�stdt|���|s&dS|jdk	rN|d|jfkrNtd|j����|jr�|jr�|jt	j
krpt�d�|jd7_dS|j
�t|�|f�|jdkr�|��|��dS)Nz,data argument must be bytes-like object (%r)z!Invalid address: must be None or z!socket.sendto() raised exception.r)rQr~rr�r�r�r��
ValueErrorr'rr�rrr#r9r%r�r�)r-rk�addrrrr�sendto�s&�
�

z!_ProactorDatagramTransport.sendtoc
Csz�|jrWdSd|_|r |��|jr2|jrN|jrN|jrH|j�|jd�WdS|j�	�\}}|jdk	r||jj
�|j|�|_n|jj
j
|j||d�|_WnZtk
r�}z|j�|�W5d}~XYnDtk
r�}z|�|d�W5d}~XYnX|j�|j�|��dS)N)r�z'Fatal write error on datagram transport)r'r%rrr#r�r(rr*rG�popleftrsr�r r�rRr+�error_received�	ExceptionrVrxr�r�)r-ryrkr�rUrrrr��s2
��z(_ProactorDatagramTransport._loop_writingc
Cs4d}�zz�|jrWW��dSd|_|dk	rf|��}|jrFd}WW��dS|jdk	r^||j}}n|\}}|jrvWW��dS|jdk	r�|jj�	|j
|j�|_n|jj�|j
|j�|_WnJt
k
r�}z|j�|�W5d}~XYn8tjk
r�|js��YnX|jdk	�r|j�|j�W5|�r.|j�||�XdSrB)r+Zdatagram_receivedr'r$rrr(r�rrsrtr �max_sizeZrecvfromrRr�rrwrxrf)r-ryrkr��resrUrrrrfs>



��
z(_ProactorDatagramTransport._loop_reading)NNN)N)N)N)r8r^r_r�rrr]r�r�r�rfrbrrr3rr��s�

!r�c@seZdZdd�Zdd�ZdS)�_ProactorDuplexPipeTransportcCsdS)NFrrDrrrr�Jsz*_ProactorDuplexPipeTransport.can_write_eofcCst�dSrB)�NotImplementedErrorrDrrrr�Msz&_ProactorDuplexPipeTransport.write_eofN)r8r^r_r�r�rrrrr�Esr�cs>eZdZejjZd
�fdd�	Zdd�Zdd�Z	dd	�Z
�ZS)�_ProactorSocketTransportNcs$t��||||||�t�|�dSrB)rrrZ_set_nodelayr,r3rrrXsz!_ProactorSocketTransport.__init__cCst||�dSrBr�rArrrr]sz#_ProactorSocketTransport._set_extracCsdSr�rrDrrrr�`sz&_ProactorSocketTransport.can_write_eofcCs2|js|jrdSd|_|jdkr.|j�tj�dSr�)r(r)r%r rZr
r�rDrrrr�cs

z"_ProactorSocketTransport.write_eof)NNN)r8r^r_rZ
_SendfileModeZ
TRY_NATIVEZ_sendfile_compatiblerrr�r�rbrrr3rr�Qs�r�cs�eZdZ�fdd�Zd3dd�Zd4dddddd�dd	�Zd5d
d�Zd6dd
�Zd7dd�Zd8dd�Z	�fdd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd9d&d'�Zd(d)�Zd:d+d,�Zd-d.�Zd/d0�Zd1d2�Z�ZS);rcsht���t�d|jj�||_||_d|_i|_	|�
|�|��t�
�t��krdt�|j���dS)NzUsing proactor: %s)rrrrSr4r8rs�	_selector�_self_reading_future�_accept_futuresZset_loop�_make_self_pipe�	threading�current_thread�main_thread�signal�
set_wakeup_fd�_csockr:)r-Zproactorr3rrrms

zBaseProactorEventLoop.__init__NcCst||||||�SrB)r�)r-rr/r0r1r2rrr�_make_socket_transportzs
�z,BaseProactorEventLoop._make_socket_transportF)�server_side�server_hostnamer1r2�ssl_handshake_timeoutc	Cs0tj|||||||	d�}
t|||
||d�|
jS)N)r��r1r2)r	ZSSLProtocolr�Z_app_transport)r-Zrawsockr/�
sslcontextr0r�r�r1r2r�Zssl_protocolrrr�_make_ssl_transports��z)BaseProactorEventLoop._make_ssl_transportcCst||||||�SrB)r�)r-rr/r�r0r1rrr�_make_datagram_transport�s
�z.BaseProactorEventLoop._make_datagram_transportcCst|||||�SrB)r��r-rr/r0r1rrr�_make_duplex_pipe_transport�s�z1BaseProactorEventLoop._make_duplex_pipe_transportcCst|||||�SrB)rcr�rrr�_make_read_pipe_transport�sz/BaseProactorEventLoop._make_read_pipe_transportcCst|||||�SrB)r�r�rrr�_make_write_pipe_transport�s�z0BaseProactorEventLoop._make_write_pipe_transportcsj|��rtd��|��rdSt��t��kr6t�d�|��|�	�|j
��d|_
d|_t
���dS)Nz!Cannot close a running event loop���)Z
is_runningr��	is_closedr�r�r�r�r��_stop_accept_futures�_close_self_pipersrIr�rrDr3rrrI�s

zBaseProactorEventLoop.closec�s|j�||�IdHSrB)rsrt)r-r�nrrr�	sock_recv�szBaseProactorEventLoop.sock_recvc�s|j�||�IdHSrB)rsZ	recv_into)r-rZbufrrr�sock_recv_into�sz$BaseProactorEventLoop.sock_recv_intoc�s|j�||�IdHSrB)rsr�)r-rrkrrr�sock_sendall�sz"BaseProactorEventLoop.sock_sendallc�s|j�||�IdHSrB)rsZconnect)r-rr�rrr�sock_connect�sz"BaseProactorEventLoop.sock_connectc�s|j�|�IdHSrB)rs�acceptrArrr�sock_accept�sz!BaseProactorEventLoop.sock_acceptc
�s(z|��}Wn2ttjfk
r>}zt�d��W5d}~XYnXzt�|�j}Wn,t	k
r|}zt�d��W5d}~XYnX|r�|n|}|s�dSt
|d�}|r�t
|||�n|}	t
||�}d}
zLt
|	||�}|dkr�|
W�0S|j�
||||�IdH||7}|
|7}
q�W5|
dk�r"|�|�XdS)Nznot a regular filerl��)r:�AttributeError�io�UnsupportedOperationrZSendfileNotAvailableError�os�fstat�st_sizerR�min�seekrs�sendfile)r-r�file�offset�countr:�errZfsizeZ	blocksizeZend_posZ
total_sentrrr�_sock_sendfile_native�s0


z+BaseProactorEventLoop._sock_sendfile_nativec�sZ|��}|��|��IdHz |j|j|||dd�IdHW�S|��|rT|��XdS)NF)Zfallback)rgrhr�r�rlZ
sock_sendfiler )r-Ztranspr�r�r�rlrrr�_sendfile_native�s�z&BaseProactorEventLoop._sendfile_nativecCsL|jdk	r|j��d|_|j��d|_|j��d|_|jd8_dS)Nr)r�rH�_ssockrIr��
_internal_fdsrDrrrr��s



z&BaseProactorEventLoop._close_self_pipecCs:t��\|_|_|j�d�|j�d�|jd7_dS)NFr)r
Z
socketpairr�r�Zsetblockingr�rDrrrr��sz%BaseProactorEventLoop._make_self_pipec
Cs�z4|dk	r|��|j|k	r"WdS|j�|jd�}Wnbtjk
rLYdSttfk
rd�YnFt	k
r�}z|�
d||d��W5d}~XYnX||_|�|j�dS)Niz.Error on reading from the event loop self pipe)rNrOr.)
rrr�rsrtr�rrwrmrnrorTrx�_loop_self_reading)r-r�rUrrrr��s$
�z(BaseProactorEventLoop._loop_self_readingcCsN|j}|dkrdSz|�d�Wn(tk
rH|jrDtjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketTr)r�r�rR�_debugrrS)r-Zcsockrrr�_write_to_selfs�z$BaseProactorEventLoop._write_to_self�dcs(d�������fdd�	�����dS)Nc
s,z�|dk	rn|��\}}�jr,t�d�||���}�dk	rX�j||�dd|i��d�n�j||d|i�d����r|WdS�j���}Wn�t	k
r�}zH��
�dkrʈ�d|t�
��d�����n�jr�tjd	�dd
�W5d}~XYn8tjk
�r���YnX|�j��
�<|���dS)Nz#%r got a new connection from %r: %rTr)r�r1r2r�r�r�zAccept failed on a socket)rNrOr
zAccept failed on socket %rr)rrr�rrSr�r�r�rsr�rRr:rTrrrIrrwr�rx)r�Zconnr�r/rU�r.�protocol_factoryr-r2rr�r�rrr./s\����
�z2BaseProactorEventLoop._start_serving.<locals>.loop)N)r*)r-r�rr�r2Zbacklogr�rr�r�_start_serving+s%z$BaseProactorEventLoop._start_servingcCsdSrBr)r-Z
event_listrrr�_process_eventsVsz%BaseProactorEventLoop._process_eventscCs&|j��D]}|��q
|j��dSrB)r��valuesrH�clear)r-�futurerrrr�Zs
z*BaseProactorEventLoop._stop_accept_futurescCs6|j�|��d�}|r|��|j�|�|��dSrB)r��popr:rHrs�
_stop_servingrI)r-rr�rrrr�_s
z#BaseProactorEventLoop._stop_serving)NNN)N)NNN)NN)NN)NN)N)NNr�N)r8r^r_rr�r�r�r�r�r�rIr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rbrrr3rrks\
�
���
�
�
�


�
+r)"�__all__r�r�r
r`r�r�r��rrrrrr	r
r�logrrZ_FlowControlMixinZ
BaseTransportrZ
ReadTransportrcZWriteTransportrzr�r�Z	Transportr�r�Z
BaseEventLooprrrrr�<module>sP���n��PK [7�!�!*__pycache__/protocols.cpython-38.opt-1.pycnu�[���U

e5d��@sbdZdZGdd�d�ZGdd�de�ZGdd�de�ZGdd	�d	e�ZGd
d�de�Zdd
�ZdS)zAbstract Protocol base classes.)�BaseProtocol�Protocol�DatagramProtocol�SubprocessProtocol�BufferedProtocolc@s4eZdZdZdZdd�Zdd�Zdd�Zd	d
�ZdS)raCommon base class for protocol interfaces.

    Usually user implements protocols that derived from BaseProtocol
    like Protocol or ProcessProtocol.

    The only case when BaseProtocol should be implemented directly is
    write-only transport like write pipe
    �cCsdS)z�Called when a connection is made.

        The argument is the transport representing the pipe connection.
        To receive data, wait for data_received() calls.
        When the connection is closed, connection_lost() is called.
        Nr)�selfZ	transportrr�)/usr/lib64/python3.8/asyncio/protocols.py�connection_madeszBaseProtocol.connection_madecCsdS)z�Called when the connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        Nr�r�excrrr�connection_lostszBaseProtocol.connection_lostcCsdS)aCalled when the transport's buffer goes over the high-water mark.

        Pause and resume calls are paired -- pause_writing() is called
        once when the buffer goes strictly over the high-water mark
        (even if subsequent writes increases the buffer size even
        more), and eventually resume_writing() is called once when the
        buffer size reaches the low-water mark.

        Note that if the buffer size equals the high-water mark,
        pause_writing() is not called -- it must go strictly over.
        Conversely, resume_writing() is called when the buffer size is
        equal or lower than the low-water mark.  These end conditions
        are important to ensure that things go as expected when either
        mark is zero.

        NOTE: This is the only Protocol callback that is not called
        through EventLoop.call_soon() -- if it were, it would have no
        effect when it's most needed (when the app keeps writing
        without yielding until pause_writing() is called).
        Nr�rrrr�
pause_writing%szBaseProtocol.pause_writingcCsdS)zvCalled when the transport's buffer drains below the low-water mark.

        See pause_writing() for details.
        Nrr
rrr�resume_writing;szBaseProtocol.resume_writingN)	�__name__�
__module__�__qualname__�__doc__�	__slots__r	rrrrrrrr	s	rc@s$eZdZdZdZdd�Zdd�ZdS)ranInterface for stream protocol.

    The user should implement this interface.  They can inherit from
    this class but don't need to.  The implementations here do
    nothing (they don't raise exceptions).

    When the user wants to requests a transport, they pass a protocol
    factory to a utility function (e.g., EventLoop.create_connection()).

    When the connection is made successfully, connection_made() is
    called with a suitable transport object.  Then data_received()
    will be called 0 or more times with data (bytes) received from the
    transport; finally, connection_lost() will be called exactly once
    with either an exception object or None as an argument.

    State machine of calls:

      start -> CM [-> DR*] [-> ER?] -> CL -> end

    * CM: connection_made()
    * DR: data_received()
    * ER: eof_received()
    * CL: connection_lost()
    rcCsdS)zTCalled when some data is received.

        The argument is a bytes object.
        Nr)r�datarrr�
data_received^szProtocol.data_receivedcCsdS�z�Called when the other end calls write_eof() or equivalent.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        Nrr
rrr�eof_receiveddszProtocol.eof_receivedN)rrrrrrrrrrrrBsrc@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
ra�Interface for stream protocol with manual buffer control.

    Important: this has been added to asyncio in Python 3.7
    *on a provisional basis*!  Consider it as an experimental API that
    might be changed or removed in Python 3.8.

    Event methods, such as `create_server` and `create_connection`,
    accept factories that return protocols that implement this interface.

    The idea of BufferedProtocol is that it allows to manually allocate
    and control the receive buffer.  Event loops can then use the buffer
    provided by the protocol to avoid unnecessary data copies.  This
    can result in noticeable performance improvement for protocols that
    receive big amounts of data.  Sophisticated protocols can allocate
    the buffer only once at creation time.

    State machine of calls:

      start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end

    * CM: connection_made()
    * GB: get_buffer()
    * BU: buffer_updated()
    * ER: eof_received()
    * CL: connection_lost()
    rcCsdS)aPCalled to allocate a new receive buffer.

        *sizehint* is a recommended minimal size for the returned
        buffer.  When set to -1, the buffer size can be arbitrary.

        Must return an object that implements the
        :ref:`buffer protocol <bufferobjects>`.
        It is an error to return a zero-sized buffer.
        Nr)r�sizehintrrr�
get_buffer�szBufferedProtocol.get_buffercCsdS)z�Called when the buffer was updated with the received data.

        *nbytes* is the total number of bytes that were written to
        the buffer.
        Nr)r�nbytesrrr�buffer_updated�szBufferedProtocol.buffer_updatedcCsdSrrr
rrrr�szBufferedProtocol.eof_receivedN)rrrrrrrrrrrrrms
rc@s$eZdZdZdZdd�Zdd�ZdS)rz Interface for datagram protocol.rcCsdS)z&Called when some datagram is received.Nr)rrZaddrrrr�datagram_received�sz"DatagramProtocol.datagram_receivedcCsdS)z~Called when a send or receive operation raises an OSError.

        (Other than BlockingIOError or InterruptedError.)
        Nrr
rrr�error_received�szDatagramProtocol.error_receivedN)rrrrrrrrrrrr�src@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
rz,Interface for protocol for subprocess calls.rcCsdS)z�Called when the subprocess writes data into stdout/stderr pipe.

        fd is int file descriptor.
        data is bytes object.
        Nr)r�fdrrrr�pipe_data_received�sz%SubprocessProtocol.pipe_data_receivedcCsdS)z�Called when a file descriptor associated with the child process is
        closed.

        fd is the int file descriptor that was closed.
        Nr)rrrrrr�pipe_connection_lost�sz'SubprocessProtocol.pipe_connection_lostcCsdS)z"Called when subprocess has exited.Nrr
rrr�process_exited�sz!SubprocessProtocol.process_exitedN)rrrrrr r!r"rrrrr�s
rcCs�t|�}|r�|�|�}t|�}|s*td��||krL||d|�<|�|�dS|d|�|d|�<|�|�||d�}t|�}qdS)Nz%get_buffer() returned an empty buffer)�lenr�RuntimeErrorr)�protorZdata_lenZbufZbuf_lenrrr�_feed_data_to_buffered_proto�s


r&N)r�__all__rrrrrr&rrrr�<module>s9+9PK [�	�j$j$0__pycache__/base_subprocess.cpython-38.opt-1.pycnu�[���U

e5d�"�@sxddlZddlZddlZddlmZddlmZddlmZGdd�dej�Z	Gdd	�d	ej
�ZGd
d�deej�Z
dS)�N�)�	protocols)�
transports)�loggercs�eZdZd0�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jfdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Z�ZS)1�BaseSubprocessTransportNc
	s&t��|
�d|_||_||_d|_d|_d|_g|_t	�
�|_i|_d|_
|tjkr`d|jd<|tjkrtd|jd<|tjkr�d|jd<z"|jf||||||d�|��Wn|���YnX|jj|_|j|jd<|j���rt|ttf�r�|}n|d}t�d||j�|j�|�|	��dS)NFrr�)�args�shell�stdin�stdout�stderr�bufsize�
subprocesszprocess %r created: pid %s)�super�__init__�_closed�	_protocol�_loop�_proc�_pid�_returncode�
_exit_waiters�collections�deque�_pending_calls�_pipes�	_finishedr�PIPE�_start�close�pidZ_extra�	get_debug�
isinstance�bytes�strr�debugZcreate_task�_connect_pipes)
�self�loop�protocolrr	r
rrr
�waiterZextra�kwargsZprogram��	__class__��//usr/lib64/python3.8/asyncio/base_subprocess.pyrsL






��

�z BaseSubprocessTransport.__init__cCs|jjg}|jr|�d�|jdk	r6|�d|j���|jdk	rT|�d|j���n |jdk	rj|�d�n
|�d�|j�d�}|dk	r�|�d|j���|j�d�}|j�d	�}|dk	r�||kr�|�d
|j���n6|dk	r�|�d|j���|dk	�r|�d|j���d
�	d�
|��S)N�closedzpid=zreturncode=Zrunningznot startedrzstdin=rrzstdout=stderr=zstdout=zstderr=z<{}>� )r-�__name__r�appendrrr�get�pipe�format�join)r'�infor
rrr.r.r/�__repr__7s,






z BaseSubprocessTransport.__repr__cKst�dS�N)�NotImplementedError)r'rr	r
rrr
r+r.r.r/rTszBaseSubprocessTransport._startcCs
||_dSr:�r)r'r)r.r.r/�set_protocolWsz$BaseSubprocessTransport.set_protocolcCs|jSr:r<�r'r.r.r/�get_protocolZsz$BaseSubprocessTransport.get_protocolcCs|jSr:)rr>r.r.r/�
is_closing]sz"BaseSubprocessTransport.is_closingcCs�|jr
dSd|_|j��D]}|dkr(q|j��q|jdk	r�|jdkr�|j��dkr�|j�	�rlt
�d|�z|j��Wnt
k
r�YnXdS)NTz$Close running child process: kill %r)rr�valuesr5rrrZpollrr!rZwarning�kill�ProcessLookupError)r'�protor.r.r/r`s$
��
zBaseSubprocessTransport.closecCs&|js"|d|��t|d�|��dS)Nzunclosed transport )�source)r�ResourceWarningr)r'Z_warnr.r.r/�__del__{szBaseSubprocessTransport.__del__cCs|jSr:)rr>r.r.r/�get_pid�szBaseSubprocessTransport.get_pidcCs|jSr:)rr>r.r.r/�get_returncode�sz&BaseSubprocessTransport.get_returncodecCs||jkr|j|jSdSdSr:)rr5)r'�fdr.r.r/�get_pipe_transport�s
z*BaseSubprocessTransport.get_pipe_transportcCs|jdkrt��dSr:)rrCr>r.r.r/�_check_proc�s
z#BaseSubprocessTransport._check_proccCs|��|j�|�dSr:)rLr�send_signal)r'�signalr.r.r/rM�sz#BaseSubprocessTransport.send_signalcCs|��|j��dSr:)rLr�	terminater>r.r.r/rO�sz!BaseSubprocessTransport.terminatecCs|��|j��dSr:)rLrrBr>r.r.r/rB�szBaseSubprocessTransport.killc	
�s`z�j}�j}|jdk	rB|��fdd�|j�IdH\}}|�jd<|jdk	rv|��fdd�|j�IdH\}}|�jd<|jdk	r�|��fdd�|j�IdH\}}|�jd<|��j	j
���jD]\}}|j|f|��q�d�_WnZtt
fk
r��Yn`tk
�r<}z"|dk	�r,|���s,|�|�W5d}~XYn X|dk	�r\|���s\|�d�dS)Ncs
t�d�S)Nr)�WriteSubprocessPipeProtor.r>r.r/�<lambda>��z8BaseSubprocessTransport._connect_pipes.<locals>.<lambda>rcs
t�d�S)Nr��ReadSubprocessPipeProtor.r>r.r/rQ�rRrcs
t�d�S)NrrSr.r>r.r/rQ�rRr)rrr
Zconnect_write_piperrZconnect_read_piper�	call_soonr�connection_mader�
SystemExit�KeyboardInterrupt�
BaseException�	cancelledZ
set_exception�
set_result)	r'r*�procr(�_r5�callback�data�excr.r>r/r&�s@

�


�


�

z&BaseSubprocessTransport._connect_pipescGs2|jdk	r|j�||f�n|jj|f|��dSr:)rr3rrU)r'�cbr_r.r.r/�_call�s
zBaseSubprocessTransport._callcCs|�|jj||�|��dSr:)rbrZpipe_connection_lost�_try_finish)r'rJr`r.r.r/�_pipe_connection_lost�sz-BaseSubprocessTransport._pipe_connection_lostcCs|�|jj||�dSr:)rbrZpipe_data_received)r'rJr_r.r.r/�_pipe_data_received�sz+BaseSubprocessTransport._pipe_data_receivedcCsp|j��rt�d||�||_|jjdkr2||j_|�|jj	�|�
�|jD]}|��sN|�
|�qNd|_dS)Nz%r exited with return code %r)rr!rr8rr�
returncoderbrZprocess_exitedrcrrZr[)r'rfr*r.r.r/�_process_exited�s

z'BaseSubprocessTransport._process_exitedc�s0|jdk	r|jS|j��}|j�|�|IdHS)zdWait until the process exit and return the process return code.

        This method is a coroutine.N)rrZ
create_futurerr3)r'r*r.r.r/�_wait�s


zBaseSubprocessTransport._waitcCs>|jdkrdStdd�|j��D��r:d|_|�|jd�dS)Ncss|]}|dk	o|jVqdSr:)�disconnected)�.0�pr.r.r/�	<genexpr>�s�z6BaseSubprocessTransport._try_finish.<locals>.<genexpr>T)r�allrrArrb�_call_connection_lostr>r.r.r/rc�s
�z#BaseSubprocessTransport._try_finishcCs*z|j�|�W5d|_d|_d|_XdSr:)rrr�connection_lost�r'r`r.r.r/rn�s
z-BaseSubprocessTransport._call_connection_lost)NN)r2�
__module__�__qualname__rr9rr=r?r@r�warnings�warnrGrHrIrKrLrMrOrBr&rbrdrergrhrcrn�
__classcell__r.r.r,r/r
s2�+&	rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rPcCs||_||_d|_d|_dS)NF)r\rJr5ri)r'r\rJr.r.r/rsz!WriteSubprocessPipeProto.__init__cCs
||_dSr:)r5)r'Z	transportr.r.r/rVsz(WriteSubprocessPipeProto.connection_madecCs d|jj�d|j�d|j�d�S)N�<z fd=z pipe=�>)r-r2rJr5r>r.r.r/r9
sz!WriteSubprocessPipeProto.__repr__cCs d|_|j�|j|�d|_dS)NT)rir\rdrJrpr.r.r/ro
sz(WriteSubprocessPipeProto.connection_lostcCs|jj��dSr:)r\r�
pause_writingr>r.r.r/rxsz&WriteSubprocessPipeProto.pause_writingcCs|jj��dSr:)r\r�resume_writingr>r.r.r/rysz'WriteSubprocessPipeProto.resume_writingN)	r2rqrrrrVr9rorxryr.r.r.r/rP�srPc@seZdZdd�ZdS)rTcCs|j�|j|�dSr:)r\rerJ)r'r_r.r.r/�
data_receivedsz%ReadSubprocessPipeProto.data_receivedN)r2rqrrrzr.r.r.r/rTsrT)rrrs�rr�logrZSubprocessTransportrZBaseProtocolrPZProtocolrTr.r.r.r/�<module>sv�PK [�Ŀ � '__pycache__/queues.cpython-38.opt-1.pycnu�[���U

e5d �@s�dZddlZddlZddlZddlmZddlmZGdd�de�ZGdd	�d	e�Z	Gd
d�d�Z
Gdd
�d
e
�ZGdd�de
�ZdS))�Queue�
PriorityQueue�	LifoQueue�	QueueFull�
QueueEmpty�N�)�events)�locksc@seZdZdZdS)rz;Raised when Queue.get_nowait() is called on an empty Queue.N��__name__�
__module__�__qualname__�__doc__�rr�&/usr/lib64/python3.8/asyncio/queues.pyrsrc@seZdZdZdS)rzDRaised when the Queue.put_nowait() method is called on a full Queue.Nr
rrrrrsrc@s�eZdZdZd)dd�dd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Ze
dd��Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�ZdS)*raA queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "await put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded asyncio application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    rN��loopcCsp|dkrt��|_n||_tjdtdd�||_t��|_	t��|_
d|_tj
|d�|_|j��|�|�dS)Nz[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.�)�
stacklevelrr)rZget_event_loop�_loop�warnings�warn�DeprecationWarning�_maxsize�collections�deque�_getters�_putters�_unfinished_tasksr	ZEvent�	_finished�set�_init)�self�maxsizerrrr�__init__!s�


zQueue.__init__cCst��|_dS�N)rr�_queue�r"r#rrrr!6szQueue._initcCs
|j��Sr%)r&�popleft�r"rrr�_get9sz
Queue._getcCs|j�|�dSr%�r&�append�r"�itemrrr�_put<sz
Queue._putcCs&|r"|��}|��s|�d�q"qdSr%)r(ZdoneZ
set_result)r"�waitersZwaiterrrr�_wakeup_nextAs

zQueue._wakeup_nextcCs(dt|�j�dt|�d�d|���d�S)N�<z at z#x� �>)�typer�id�_formatr)rrr�__repr__IszQueue.__repr__cCsdt|�j�d|���d�S)Nr2r3r4)r5rr7r)rrr�__str__Lsz
Queue.__str__cCs~d|j��}t|dd�r,|dt|j���7}|jrH|dt|j��d�7}|jrd|dt|j��d�7}|jrz|d|j��7}|S)Nzmaxsize=r&z _queue=z
 _getters[�]z
 _putters[z tasks=)r�getattr�listr&r�lenrr)r"�resultrrrr7Osz
Queue._formatcCs
t|j�S)zNumber of items in the queue.)r=r&r)rrr�qsize[szQueue.qsizecCs|jS)z%Number of items allowed in the queue.)rr)rrrr#_sz
Queue.maxsizecCs|jS)z3Return True if the queue is empty, False otherwise.�r&r)rrr�emptydszQueue.emptycCs |jdkrdS|��|jkSdS)z�Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        rFN)rr?r)rrr�fullhs
z
Queue.fullc�s�|��r�|j��}|j�|�z|IdHWq|��z|j�|�Wntk
r`YnX|��s~|��s~|�	|j��YqXq|�
|�S)z�Put an item into the queue.

        Put an item into the queue. If the queue is full, wait until a free
        slot is available before adding item.
        N)rBr�
create_futurerr,�cancel�remove�
ValueError�	cancelledr1�
put_nowait)r"r.Zputterrrr�putss

z	Queue.putcCs>|��rt�|�|�|jd7_|j��|�|j�dS)zyPut an item into the queue without blocking.

        If no free slot is immediately available, raise QueueFull.
        rN)rBrr/rr�clearr1rr-rrrrH�s

zQueue.put_nowaitc�s�|��r�|j��}|j�|�z|IdHWq|��z|j�|�Wntk
r`YnX|��s~|��s~|�	|j��YqXq|�
�S)zoRemove and return an item from the queue.

        If queue is empty, wait until an item is available.
        N)rArrCrr,rDrErFrGr1�
get_nowait)r"�getterrrr�get�s

z	Queue.getcCs$|��rt�|��}|�|j�|S)z�Remove and return an item from the queue.

        Return an item if one is immediately available, else raise QueueEmpty.
        )rArr*r1rr-rrrrK�s
zQueue.get_nowaitcCs8|jdkrtd��|jd8_|jdkr4|j��dS)a$Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).

        Raises ValueError if called more times than there were items placed in
        the queue.
        rz!task_done() called too many timesrN)rrFrr r)rrr�	task_done�s


zQueue.task_donec�s|jdkr|j��IdHdS)aBlock until all items in the queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer calls task_done() to
        indicate that the item was retrieved and all work on it is complete.
        When the count of unfinished tasks drops to zero, join() unblocks.
        rN)rr�waitr)rrr�join�s
z
Queue.join)r)rrr
rr$r!r*r/r1r8r9r7r?�propertyr#rArBrIrHrMrKrNrPrrrrrs(
rc@s4eZdZdZdd�Zejfdd�Zejfdd�Z	dS)	rz�A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    cCs
g|_dSr%r@r'rrrr!�szPriorityQueue._initcCs||j|�dSr%r@)r"r.�heappushrrrr/�szPriorityQueue._putcCs
||j�Sr%r@)r"�heappoprrrr*�szPriorityQueue._getN)
rrr
rr!�heapqrRr/rSr*rrrrr�src@s(eZdZdZdd�Zdd�Zdd�ZdS)	rzEA subclass of Queue that retrieves most recently added entries first.cCs
g|_dSr%r@r'rrrr!�szLifoQueue._initcCs|j�|�dSr%r+r-rrrr/�szLifoQueue._putcCs
|j��Sr%)r&�popr)rrrr*�szLifoQueue._getN)rrr
rr!r/r*rrrrr�sr)
�__all__rrTr�rr	�	Exceptionrrrrrrrrr�<module>sKPK [�T
��$__pycache__/log.cpython-38.opt-1.pycnu�[���U

e5d|�@sdZddlZe�e�ZdS)zLogging configuration.�N)�__doc__ZloggingZ	getLogger�__package__Zlogger�rr�#/usr/lib64/python3.8/asyncio/log.py�<module>sPK [$��'��+__pycache__/base_tasks.cpython-38.opt-1.pycnu�[���U

e5d�	�@sDddlZddlZddlmZddlmZdd�Zdd�Zd	d
�ZdS)�N�)�base_futures)�
coroutinescCsnt�|�}|jrd|d<|�dd|���t�|j�}|�dd|�d��|jdk	rj|�dd	|j���|S)
NZ
cancellingrrzname=%r�zcoro=<�>�z	wait_for=)	rZ_future_repr_infoZ_must_cancel�insertZget_namerZ_format_coroutine�_coroZ_fut_waiter)�task�info�coro�r
�*/usr/lib64/python3.8/asyncio/base_tasks.py�_task_repr_infos

rcCs�g}t|jd�r|jj}n0t|jd�r0|jj}nt|jd�rF|jj}nd}|dk	r�|dk	r�|dk	rt|dkrlq�|d8}|�|�|j}qR|��nH|jdk	r�|jj	}|dk	r�|dk	r�|dkr�q�|d8}|�|j
�|j}q�|S)N�cr_frame�gi_frame�ag_framerr)�hasattrr	rrr�append�f_back�reverse�
_exception�
__traceback__�tb_frame�tb_next)r
�limitZframes�f�tbr
r
r�_task_get_stacks6





rcCs�g}t�}|j|d�D]Z}|j}|j}|j}|j}	||krN|�|�t�|�t�	|||j
�}
|�|||	|
f�q|j}|s�t
d|��|d�n2|dk	r�t
d|�d�|d�nt
d|�d�|d�tj||d�|dk	r�t�|j|�D]}
t
|
|dd�q�dS)	N)rz
No stack for )�filezTraceback for z (most recent call last):z
Stack for �)r�end)�setZ	get_stack�f_lineno�f_code�co_filename�co_name�add�	linecache�
checkcache�getline�	f_globalsrr�print�	traceback�
print_list�format_exception_only�	__class__)r
rr�extracted_list�checkedr�lineno�co�filename�name�line�excr
r
r�_task_print_stack<s,

r9)r(r-r rrrrr9r
r
r
r�<module>s#PK [���  (__pycache__/futures.cpython-38.opt-2.pycnu�[���U

e5db3�@s�dZddlZddlZddlZddlZddlmZddlmZddlm	Z	ddlm
Z
ejZejZej
Z
ejZejdZGdd	�d	�ZeZd
d�Zdd
�Zdd�Zdd�Zdd�Zdd�Zdd�dd�ZzddlZWnek
r�YnXejZZdS))�Future�wrap_future�isfuture�N�)�base_futures)�events)�
exceptions)�format_helpersc@s�eZdZeZdZdZdZdZdZ	dZ
dd�dd�Zej
Zdd�Zdd	�Zed
d��Zejdd��Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�dd�Zdd�Zd d!�Zd"d#�Zd$d%�ZeZ dS)&rNF��loopcCs@|dkrt��|_n||_g|_|j��r<t�t�d��|_	dS)Nr)
r�get_event_loop�_loop�
_callbacksZ	get_debugr	�
extract_stack�sys�	_getframe�_source_traceback��selfr�r�'/usr/lib64/python3.8/asyncio/futures.py�__init__Ds
�zFuture.__init__cCsd�|jjd�|����S)Nz<{} {}>� )�format�	__class__�__name__�join�
_repr_info�rrrr�__repr__Vs
�zFuture.__repr__cCsF|js
dS|j}|jj�d�||d�}|jr6|j|d<|j�|�dS)Nz exception was never retrieved)�message�	exception�futureZsource_traceback)�_Future__log_traceback�
_exceptionrrrr
Zcall_exception_handler)r�exc�contextrrr�__del__Zs�
zFuture.__del__cCs|jS�N)r#rrrr�_log_tracebackjszFuture._log_tracebackcCst|�rtd��d|_dS)Nz'_log_traceback can only be set to FalseF)�bool�
ValueErrorr#)r�valrrrr)nscCs|j}|dkrtd��|S)Nz!Future object is not initialized.)r
�RuntimeErrorrrrr�get_looptszFuture.get_loopcCs&d|_|jtkrdSt|_|��dS)NFT)r#�_state�_PENDING�
_CANCELLED�_Future__schedule_callbacksrrrr�cancel{s
z
Future.cancelcCsH|jdd�}|sdSg|jdd�<|D]\}}|jj|||d�q(dS�N�r&)rr
�	call_soon)rZ	callbacks�callback�ctxrrrZ__schedule_callbacks�szFuture.__schedule_callbackscCs
|jtkSr()r/r1rrrr�	cancelled�szFuture.cancelledcCs
|jtkSr()r/r0rrrr�done�szFuture.donecCs@|jtkrtj�|jtkr$t�d��d|_|jdk	r:|j�|jS)NzResult is not ready.F)	r/r1r�CancelledError�	_FINISHED�InvalidStateErrorr#r$�_resultrrrr�result�s



z
Future.resultcCs0|jtkrtj�|jtkr$t�d��d|_|jS)NzException is not set.F)r/r1rr;r<r=r#r$rrrrr!�s


zFuture.exceptionr5cCsB|jtkr|jj|||d�n |dkr.t��}|j�||f�dSr4)r/r0r
r6�contextvarsZcopy_contextr�append)r�fnr&rrr�add_done_callback�s

zFuture.add_done_callbackcs<�fdd�|jD�}t|j�t|�}|r8||jdd�<|S)Ncs g|]\}}|�kr||f�qSrr)�.0�fr8�rBrr�
<listcomp>�s�z/Future.remove_done_callback.<locals>.<listcomp>)r�len)rrBZfiltered_callbacksZ
removed_countrrFr�remove_done_callback�s
�zFuture.remove_done_callbackcCs8|jtkr t�|j�d|����||_t|_|��dS)N�: )r/r0rr=r>r<r2)rr?rrr�
set_result�s

zFuture.set_resultcCsb|jtkr t�|j�d|����t|t�r0|�}t|�tkrDtd��||_t	|_|�
�d|_dS)NrJzPStopIteration interacts badly with generators and cannot be raised into a FutureT)r/r0rr=�
isinstance�type�
StopIteration�	TypeErrorr$r<r2r#)rr!rrr�
set_exception�s

zFuture.set_exceptionccs,|��sd|_|V|��s$td��|��S)NTzawait wasn't used with future)r:�_asyncio_future_blockingr-r?rrrr�	__await__szFuture.__await__)!r�
__module__�__qualname__r0r/r>r$r
rrQr#rrZ_future_repr_inforrr'�propertyr)�setterr.r3r2r9r:r?r!rCrIrKrPrR�__iter__rrrrrs8

rcCs,z
|j}Wntk
rYnX|�S|jSr()r.�AttributeErrorr
)�futr.rrr�	_get_loops
rZcCs|��rdS|�|�dSr()r9rK)rYr?rrr�_set_result_unless_cancelledsr[cCsXt|�}|tjjkr tj|j�S|tjjkr8tj|j�S|tjjkrPtj|j�S|SdSr()rM�
concurrent�futuresr;r�args�TimeoutErrorr=)r%Z	exc_classrrr�_convert_future_exc#sr`cCsR|��r|��|��sdS|��}|dk	r<|�t|��n|��}|�|�dSr()r9r3Zset_running_or_notify_cancelr!rPr`r?rK)r\�sourcer!r?rrr�_set_concurrent_future_state/srbcCsT|��rdS|��r|��n2|��}|dk	r>|�t|��n|��}|�|�dSr()r9r3r!rPr`r?rK)ra�destr!r?rrr�_copy_future_state>s
rdcs�t��st�tjj�std��t��s<t�tjj�s<td��t��rLt��nd�t��r`t��nd�dd�����fdd�}����fdd�}��|���|�dS)	Nz(A future is required for source argumentz-A future is required for destination argumentcSs"t|�rt||�n
t||�dSr()rrdrb)r"�otherrrr�
_set_statebsz!_chain_future.<locals>._set_statecs2|��r.�dks��kr"���n���j�dSr()r9r3�call_soon_threadsafe)�destination)�	dest_loopra�source_looprr�_call_check_cancelhs
z)_chain_future.<locals>._call_check_cancelcsJ���r�dk	r���rdS�dks,��kr8��|�n����|�dSr()r9Z	is_closedrg)ra)rfrirhrjrr�_call_set_stateos��z&_chain_future.<locals>._call_set_state)rrLr\r]rrOrZrC)rarhrkrlr)rfrirhrarjr�
_chain_futureRs��	
rmr
cCs2t|�r|S|dkrt��}|��}t||�|Sr()rrrZ
create_futurerm)r"rZ
new_futurerrrr|s
r)�__all__Zconcurrent.futuresr\r@Zloggingr�rrrr	rr0r1r<�DEBUGZSTACK_DEBUGrZ	_PyFuturerZr[r`rbrdrmrZ_asyncio�ImportErrorZ_CFuturerrrr�<module>s8
q*
PK [�	u�

*__pycache__/protocols.cpython-38.opt-2.pycnu�[���U

e5d��@s^dZGdd�d�ZGdd�de�ZGdd�de�ZGdd�de�ZGd	d
�d
e�Zdd�Zd
S))�BaseProtocol�Protocol�DatagramProtocol�SubprocessProtocol�BufferedProtocolc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)r�cCsdS�Nr)�selfZ	transportrr�)/usr/lib64/python3.8/asyncio/protocols.py�connection_madeszBaseProtocol.connection_madecCsdSrr�r�excrrr	�connection_lostszBaseProtocol.connection_lostcCsdSrr�rrrr	�
pause_writing%szBaseProtocol.pause_writingcCsdSrrrrrr	�resume_writing;szBaseProtocol.resume_writingN)�__name__�
__module__�__qualname__�	__slots__r
r
rrrrrr	r	s

rc@s eZdZdZdd�Zdd�ZdS)rrcCsdSrr)r�datarrr	�
data_received^szProtocol.data_receivedcCsdSrrrrrr	�eof_receiveddszProtocol.eof_receivedN)rrrrrrrrrr	rBsrc@s(eZdZdZdd�Zdd�Zdd�ZdS)	rrcCsdSrr)r�sizehintrrr	�
get_buffer�szBufferedProtocol.get_buffercCsdSrr)r�nbytesrrr	�buffer_updated�szBufferedProtocol.buffer_updatedcCsdSrrrrrr	r�szBufferedProtocol.eof_receivedN)rrrrrrrrrrr	rmsrc@s eZdZdZdd�Zdd�ZdS)rrcCsdSrr)rrZaddrrrr	�datagram_received�sz"DatagramProtocol.datagram_receivedcCsdSrrrrrr	�error_received�szDatagramProtocol.error_receivedN)rrrrrrrrrr	r�src@s(eZdZdZdd�Zdd�Zdd�ZdS)	rrcCsdSrr)r�fdrrrr	�pipe_data_received�sz%SubprocessProtocol.pipe_data_receivedcCsdSrr)rrrrrr	�pipe_connection_lost�sz'SubprocessProtocol.pipe_connection_lostcCsdSrrrrrr	�process_exited�sz!SubprocessProtocol.process_exitedN)rrrrrr r!rrrr	r�srcCs�t|�}|r�|�|�}t|�}|s*td��||krL||d|�<|�|�dS|d|�|d|�<|�|�||d�}t|�}qdS)Nz%get_buffer() returned an empty buffer)�lenr�RuntimeErrorr)�protorZdata_lenZbufZbuf_lenrrr	�_feed_data_to_buffered_proto�s


r%N)�__all__rrrrrr%rrrr	�<module>s9+9PK [-w/��)__pycache__/__init__.cpython-38.opt-1.pycnu�[���U

e5d��@sdZddlZddlTddlTddlTddlTddlTddlTddlTddl	Tddl
TddlTddlTddl
TddlTddl
mZejejejejejejeje	je
jejeje
jejZejdkr�ddlTeej7ZnddlTeej7ZdS)z'The asyncio package, tracking PEP 3156.�N�)�*)�_all_tasks_compatZwin32)�__doc__�sysZbase_eventsZ
coroutinesZevents�
exceptionsZfuturesZlocksZ	protocolsZrunnersZqueuesZstreams�
subprocessZtasksZ
transportsr�__all__�platformZwindows_eventsZunix_events�rr�(/usr/lib64/python3.8/asyncio/__init__.py�<module>sZ��������	�
���
PK [���
		/__pycache__/format_helpers.cpython-38.opt-1.pycnu�[���U

e5dd	�@sdddlZddlZddlZddlZddlZddlmZdd�Zdd�Zdd	�Z	ddd�Z
dd
d�ZdS)�N�)�	constantscCsVt�|�}t�|�r&|j}|j|jfSt|tj�r<t	|j
�St|tj�rRt	|j
�SdS�N)�inspectZunwrapZ
isfunction�__code__�co_filename�co_firstlineno�
isinstance�	functools�partial�_get_function_source�func�
partialmethod)r
�code�r�./usr/lib64/python3.8/asyncio/format_helpers.pyr
s



rcCs8t||d�}t|�}|r4|d|d�d|d��7}|S)Nz at r�:r)�_format_callbackr)r
�args�	func_repr�sourcerrr�_format_callback_sources
rcCsHg}|r|�dd�|D��|r8|�dd�|��D��d�d�|��S)z�Format function arguments and keyword arguments.

    Special case for a single parameter: ('hello',) is formatted as ('hello').
    css|]}t�|�VqdSr��reprlib�repr)�.0�argrrr�	<genexpr>&sz*_format_args_and_kwargs.<locals>.<genexpr>css&|]\}}|�dt�|���VqdS)�=Nr)r�k�vrrrr(sz({})z, )�extend�items�format�join)r�kwargsr"rrr�_format_args_and_kwargssr&�cCs�t|tj�r.t||�|}t|j|j|j|�St|d�rF|j	rF|j	}n t|d�r^|j
r^|j
}nt|�}|t||�7}|r�||7}|S)N�__qualname__�__name__)r	r
rr&rr
r�keywords�hasattrr(r)r)r
rr%�suffixrrrrr,srcCsD|dkrt��j}|dkr tj}tjjt�|�|dd�}|�	�|S)zlReplacement for traceback.extract_stack() that only does the
    necessary work for asyncio debug mode.
    NF)�limit�lookup_lines)
�sys�	_getframe�f_backrZDEBUG_STACK_DEPTH�	traceback�StackSummary�extract�
walk_stack�reverse)�fr-�stackrrr�
extract_stack>s
�r9)r')NN)r
rrr/r2r'rrrr&rr9rrrr�<module>s
PK [�����+__pycache__/coroutines.cpython-38.opt-2.pycnu�[���U

e5d]"�@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddlmZdd	�Ze�ZGd
d�d�Zdd
�Ze�Zdd�ZejejejjefZe�Zdd�Zdd�ZdS))�	coroutine�iscoroutinefunction�iscoroutine�N�)�base_futures)�	constants)�format_helpers)�loggercCs"tjjp tjjo ttj�d��S)NZPYTHONASYNCIODEBUG)�sys�flags�dev_mode�ignore_environment�bool�os�environ�get�rr�*/usr/lib64/python3.8/asyncio/coroutines.py�_is_debug_modes�rc@s�eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zddd
�Zdd�Z	e
dd��Ze
dd��Ze
dd��Z
dd�Ze
dd��Zdd�ZdS)�CoroWrapperNcCs>||_||_t�t�d��|_t|dd�|_t|dd�|_	dS)Nr�__name__�__qualname__)
�gen�funcr�
extract_stackr
�	_getframe�_source_traceback�getattrrr)�selfrrrrr�__init__'s
zCoroWrapper.__init__cCsJt|�}|jr4|jd}|d|d�d|d��7}d|jj�d|�d�S)	N���z
, created at r�:r�<� �>)�_format_coroutiner�	__class__r)r�	coro_repr�framerrr�__repr__/s

zCoroWrapper.__repr__cCs|S�Nr�rrrr�__iter__7szCoroWrapper.__iter__cCs|j�d�Sr*�r�sendr+rrr�__next__:szCoroWrapper.__next__cCs|j�|�Sr*r-)r�valuerrrr.=szCoroWrapper.sendcCs|j�|||�Sr*)r�throw)r�typer0�	tracebackrrrr1@szCoroWrapper.throwcCs
|j��Sr*)r�closer+rrrr4CszCoroWrapper.closecCs|jjSr*)r�gi_framer+rrrr5FszCoroWrapper.gi_framecCs|jjSr*)r�
gi_runningr+rrrr6JszCoroWrapper.gi_runningcCs|jjSr*)r�gi_coder+rrrr7NszCoroWrapper.gi_codecCs|Sr*rr+rrr�	__await__RszCoroWrapper.__await__cCs|jjSr*)r�gi_yieldfromr+rrrr9UszCoroWrapper.gi_yieldfromcCs�t|dd�}t|dd�}|dk	r||jdkr||�d�}t|dd�}|rrd�t�|��}|dtj�d	�7}||��7}t�	|�dS)
Nrr5r z was never yielded fromrr�zB
Coroutine object created at (most recent call last, truncated to z last lines):
)
r�f_lasti�joinr3�format_listrZDEBUG_STACK_DEPTH�rstripr	�error)rrr(�msg�tbrrr�__del__Ys
zCoroWrapper.__del__)N)NN)r�
__module__rrr)r,r/r.r1r4�propertyr5r6r7r8r9rBrrrrr$s"





rcsztjdtdd�t���r�St���r.��nt����fdd���t�	���t
sX�}nt�����fdd��}t|_|S)NzN"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead�)�
stacklevelc?sr�||�}t�|�s(t�|�s(t|t�r4|EdH}n:z
|j}Wntk
rRYnXt|tj	j
�rn|�EdH}|Sr*)rZisfuture�inspectZisgenerator�
isinstancerr8�AttributeError�collections�abc�	Awaitable)�args�kw�resZ
await_meth�rrr�corozs
�
zcoroutine.<locals>.corocs@t�||��d�}|jr |jd=t�dd�|_t�dd�|_|S)NrPr rr)rrrrr)rM�kwds�w�rQrrr�wrapper�szcoroutine.<locals>.wrapper)�warnings�warn�DeprecationWarningrGr�isgeneratorfunction�	functools�wraps�typesr�_DEBUG�
_is_coroutine)rrUrrTrris"�


rcCst�|�pt|dd�tkS)Nr^)rGrrr^rPrrrr�s
�rcCs@t|�tkrdSt|t�r8tt�dkr4t�t|��dSdSdS)NT�dF)r2�_iscoroutine_typecacherH�_COROUTINE_TYPES�len�add)�objrrrr�s
rc
sht|t���fdd�}dd�}d}t|d�r:|jr:|j}nt|d�rP|jrP|j}||�}|sr||�rn|�d�S|Sd}t|d�r�|jr�|j}nt|d	�r�|jr�|j}|jp�d
}d}��r$|jdk	�r$t	�
|j��s$t�|j�}|dk	r�|\}}|dk�r|�d|�d
|��}	n|�d|�d
|��}	n@|dk	�rJ|j
}|�d|�d
|��}	n|j}|�d|�d
|��}	|	S)Ncs`�rt�|jdi�St|d�r,|jr,|j}n*t|d�rD|jrD|j}ndt|�j�d�}|�d�S)Nrrrr"z without __name__>z())rZ_format_callbackr�hasattrrrr2)rQ�	coro_name�Zis_corowrapperrr�get_name�sz#_format_coroutine.<locals>.get_namecSsHz|jWStk
rBz|jWYStk
r<YYdSXYnXdS)NF)�
cr_runningrIr6)rQrrr�
is_running�sz%_format_coroutine.<locals>.is_running�cr_coder7z runningr5�cr_framez<empty co_filename>rz done, defined at r!z running, defined at z running at )rHrrerkr7r5rl�co_filenamerrGrYrZ_get_function_source�f_lineno�co_firstlineno)
rQrhrjZ	coro_coderfZ
coro_frame�filename�lineno�sourcer'rrgrr%�sJ
	

�
�

r%) �__all__Zcollections.abcrJrZrGrr
r3r\rVr:rrr�logr	rr]rr�objectr^r�
CoroutineType�
GeneratorTyperK�	Coroutinera�setr`rr%rrrr�<module>s2E8�PK [�с�^�^&__pycache__/tasks.cpython-38.opt-1.pycnu�[���U

e5d���@svdZdZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddlm
Z
ddlmZddlmZdd	lmZdd
l
mZe�d�jZdBdd�ZdCd
d�ZdDdd�Zdd�ZGdd�dej�ZeZzddlZWnek
r�YnXejZZdd�dd�Zejj Z ejj!Z!ejj"Z"dde"d�dd�Z#dd�Z$dd�dd�Z%d d!�Z&d"d#�Z'ddd$�d%d&�Z(ej)d'd(��Z*dEdd�d)d*�Z+dd�d+d,�Z,ej)d-d.��Z-ee-_Gd/d0�d0ej.�Z/dd1d2�d3d4�Z0dd�d5d6�Z1d7d8�Z2e
�3�Z4iZ5d9d:�Z6d;d<�Z7d=d>�Z8d?d@�Z9e6Z:e9Z;e7Z<e8Z=z$ddAlm6Z6m9Z9m7Z7m8Z8m4Z4m5Z5Wnek
�r`YnXe6Z>e9Z?e7Z@e8ZAdS)Fz0Support for tasks, coroutines and the scheduler.)�Task�create_task�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�wait�wait_for�as_completed�sleep�gather�shield�
ensure_future�run_coroutine_threadsafe�current_task�	all_tasks�_register_task�_unregister_task�_enter_task�_leave_task�N�)�
base_tasks)�
coroutines)�events)�
exceptions)�futures)�
_is_coroutinecCs|dkrt��}t�|�S)z!Return a currently executed task.N)r�get_running_loop�_current_tasks�get��loop�r!�%/usr/lib64/python3.8/asyncio/tasks.pyr"srcs^�dkrt���d}ztt�}WqLtk
rF|d7}|dkrB�YqXqLq�fdd�|D�S)z'Return a set of all tasks for the loop.Nrr��cs&h|]}t�|��kr|��s|�qSr!)r�	_get_loop�done��.0�trr!r"�	<setcomp><s�zall_tasks.<locals>.<setcomp>)rr�list�
_all_tasks�RuntimeError�r �iZtasksr!rr"r)srcs^�dkrt���d}ztt�}WqLtk
rF|d7}|dkrB�YqXqLq�fdd�|D�S)Nrrr#csh|]}t�|��kr|�qSr!)rr$r&rr!r"r)Usz$_all_tasks_compat.<locals>.<setcomp>)r�get_event_loopr*r+r,r-r!rr"�_all_tasks_compat@sr0cCs4|dk	r0z
|j}Wntk
r&Yn
X||�dS�N)�set_name�AttributeError)�task�namer2r!r!r"�_set_task_nameXs
r6cs�eZdZdZdZed%dd��Zed&dd��Zddd��fd	d
�
Z�fdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�dd�Zddd�dd�Zdd �Zd'�fd!d"�	Zd#d$�Z�ZS)(rz A coroutine wrapped in a Future.TNcCs(tjdtdd�|dkr t��}t|�S)z�Return the currently running task in an event loop or None.

        By default the current task for the current event loop is returned.

        None is returned when called not in the context of a Task.
        zVTask.current_task() is deprecated since Python 3.7, use asyncio.current_task() instead���
stacklevelN)�warnings�warn�DeprecationWarningrr/r��clsr r!r!r"rts�zTask.current_taskcCstjdtdd�t|�S)z|Return a set of all tasks for an event loop.

        By default all tasks for the current event loop are returned.
        zPTask.all_tasks() is deprecated since Python 3.7, use asyncio.all_tasks() insteadr7r8)r:r;r<r0r=r!r!r"r�s
�zTask.all_tasks)r r5cs�t�j|d�|jr|jd=t�|�s:d|_td|����|dkrRdt���|_n
t	|�|_d|_
d|_||_t
��|_|jj|j|jd�t|�dS)Nr���Fza coroutine was expected, got zTask-��context)�super�__init__�_source_tracebackr�iscoroutine�_log_destroy_pending�	TypeError�_task_name_counter�_name�str�_must_cancel�_fut_waiter�_coro�contextvarsZcopy_context�_context�_loop�	call_soon�_Task__stepr)�self�coror r5��	__class__r!r"rC�s


z
Task.__init__csF|jtjkr8|jr8|dd�}|jr,|j|d<|j�|�t���dS)Nz%Task was destroyed but it is pending!)r4�messageZsource_traceback)	Z_staterZ_PENDINGrFrDrPZcall_exception_handlerrB�__del__)rSrArUr!r"rX�s�
zTask.__del__cCs
t�|�Sr1)rZ_task_repr_info�rSr!r!r"�
_repr_info�szTask._repr_infocCs|jSr1)rMrYr!r!r"�get_coro�sz
Task.get_corocCs|jSr1)rIrYr!r!r"�get_name�sz
Task.get_namecCst|�|_dSr1)rJrI)rS�valuer!r!r"r2�sz
Task.set_namecCstd��dS)Nz*Task does not support set_result operation�r,)rS�resultr!r!r"�
set_result�szTask.set_resultcCstd��dS)Nz-Task does not support set_exception operationr^)rS�	exceptionr!r!r"�
set_exception�szTask.set_exception)�limitcCst�||�S)a�Return the list of stack frames for this task's coroutine.

        If the coroutine is not done, this returns the stack where it is
        suspended.  If the coroutine has completed successfully or was
        cancelled, this returns an empty list.  If the coroutine was
        terminated by an exception, this returns the list of traceback
        frames.

        The frames are always ordered from oldest to newest.

        The optional limit gives the maximum number of frames to
        return; by default all available frames are returned.  Its
        meaning differs depending on whether a stack or a traceback is
        returned: the newest frames of a stack are returned, but the
        oldest frames of a traceback are returned.  (This matches the
        behavior of the traceback module.)

        For reasons beyond our control, only one stack frame is
        returned for a suspended coroutine.
        )rZ_task_get_stack)rSrcr!r!r"�	get_stack�szTask.get_stack)rc�filecCst�|||�S)anPrint the stack or traceback for this task's coroutine.

        This produces output similar to that of the traceback module,
        for the frames retrieved by get_stack().  The limit argument
        is passed to get_stack().  The file argument is an I/O stream
        to which the output is written; by default output is written
        to sys.stderr.
        )rZ_task_print_stack)rSrcrer!r!r"�print_stack�s	zTask.print_stackcCs4d|_|��rdS|jdk	r*|j��r*dSd|_dS)a�Request that this task cancel itself.

        This arranges for a CancelledError to be thrown into the
        wrapped coroutine on the next cycle through the event loop.
        The coroutine then has a chance to clean up or even deny
        the request using try/except/finally.

        Unlike Future.cancel, this does not guarantee that the
        task will be cancelled: the exception might be caught and
        acted upon, delaying cancellation of the task or preventing
        cancellation completely.  The task may also return a value or
        raise a different exception.

        Immediately after this method is called, Task.cancelled() will
        not return True (unless the task was already cancelled).  A
        task will be marked as cancelled when the wrapped coroutine
        terminates with a CancelledError exception (even if cancel()
        was not called).
        FNT)Z_log_tracebackr%rL�cancelrKrYr!r!r"rg�s

zTask.cancelc
s�|��rt�d|�d|����|jr>t|tj�s8t��}d|_|j}d|_t|j	|��zfz"|dkrp|�d�}n
|�|�}Wn�t
k
r�}z*|jr�d|_t���nt��|j�W5d}~XY�n�tjk
r�t���Y�n�ttfk
�r}zt��|��W5d}~XY�n�tk
�rL}zt��|�W5d}~XY�npXt|dd�}|dk	�r@t�|�|j	k	�r�td|�d|�d��}|j	j|j||jd�n�|�r||k�r�td	|���}|j	j|j||jd�n8d|_|j|j|jd�||_|j�r>|j���r>d|_n*td
|�d|���}|j	j|j||jd�n||dk�r`|j	j|j|jd�n\t �!|��r�td|�d|���}|j	j|j||jd�n$td
|���}|j	j|j||jd�W5t
|j	|�d}XdS)Nz_step(): already done: z, F�_asyncio_future_blockingzTask z got Future z attached to a different loopr@zTask cannot await on itself: z-yield was used instead of yield from in task z with z;yield was used instead of yield from for generator in task zTask got bad yield: )"r%rZInvalidStateErrorrK�
isinstance�CancelledErrorrMrLrrPr�send�throw�
StopIterationrBrgr`r]�KeyboardInterrupt�
SystemExitrb�
BaseException�getattrrr$r,rQrRrOrh�add_done_callback�
_Task__wakeup�inspectZisgenerator)rS�excrTr_Zblocking�new_excrUr!r"Z__steps��  
��
�����
���
zTask.__stepc
CsJz|��Wn,tk
r8}z|�|�W5d}~XYn
X|��d}dSr1)r_rprR)rS�futurerur!r!r"Z__wakeup[sz
Task.__wakeup)N)N)N)�__name__�
__module__�__qualname__�__doc__rF�classmethodrrrCrXrZr[r\r2r`rbrdrfrgrRrs�
__classcell__r!r!rUr"rbs&
!Tr)r5cCs t��}|�|�}t||�|S)z]Schedule the execution of a coroutine object in a spawn task.

    Return a Task object.
    )rrrr6)rTr5r r4r!r!r"rxs

r)r �timeout�return_whenc�s�t�|�st�|�r(tdt|�j����|s4td��|tt	t
fkrPtd|�����dkrbt���nt
jdtdd��fdd	�t|�D�}t|||��IdHS)
a�Wait for the Futures and coroutines given by fs to complete.

    The fs iterable must not be empty.

    Coroutines will be wrapped in Tasks.

    Returns two sets of Future: (done, pending).

    Usage:

        done, pending = await asyncio.wait(fs)

    Note: This does not raise TimeoutError! Futures that aren't done
    when the timeout occurs are returned in the second set.
    zexpect a list of futures, not z#Set of coroutines/Futures is empty.zInvalid return_when value: N�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r7r8csh|]}t|�d��qS�r�r�r'�frr!r"r)�szwait.<locals>.<setcomp>)r�isfuturerrErG�typerx�
ValueErrorrrrrrr:r;r<�set�_wait)�fsr r~rr!rr"r�s
�rcGs|��s|�d�dSr1)r%r`)�waiter�argsr!r!r"�_release_waiter�sr�rc
�s�|dkrt��}ntjdtdd�|dkr4|IdHS|dkr�t||d�}|��rX|��St||d�IdHz|��Wn.t	j
k
r�}zt	��|�W5d}~XYn
Xt	���|��}|�
|t|�}t�t|�}t||d�}|�|�z�z|IdHWnPt	j
k
�rF|���r$|��YW�dS|�|�t||d�IdH�YnX|���r^|��W�*S|�|�t||d�IdHt	���W5|��XdS)a�Wait for the single Future or coroutine to complete, with timeout.

    Coroutine will be wrapped in Task.

    Returns result of the Future or coroutine.  When a timeout occurs,
    it cancels the task and raises TimeoutError.  To avoid the task
    cancellation, wrap it in shield().

    If the wait is cancelled, the task is also cancelled.

    This function is a coroutine.
    Nr�r7r8rr)rrr:r;r<rr%r_�_cancel_and_waitrrj�TimeoutError�
create_future�
call_laterr��	functools�partialrrrg�remove_done_callback)�futr~r rur��timeout_handle�cbr!r!r"r�sL

�





rc
�s�|���d�|dk	r"|�|t���t|������fdd�}|D]}|�|�q@z�IdHW5�dk	rp���|D]}|�|�qtXt�t�}}|D]"}|��r�|�	|�q�|�	|�q�||fS)zVInternal helper for wait().

    The fs argument must be a collection of Futures.
    NcsZ�d8��dks4�tks4�tkrV|��sV|��dk	rV�dk	rD������sV��d�dS)Nrr)rr�	cancelledrargr%r`�r��Zcounterrr�r�r!r"�_on_completions���
�z_wait.<locals>._on_completion)
r�r�r��lenrrrgr�r�r%�add)r�r~rr r�r�r%Zpendingr!r�r"r��s(r�c	�sF|��}t�t|�}|�|�z|��|IdHW5|�|�XdS)z<Cancel the *fut* future or task and wait until it completes.N)r�r�r�r�rrr�rg)r�r r�r�r!r!r"r�&s
r�)r r~c#s�t�|�st�|�r(tdt|�j����ddlm}|�d���dkrPt	�
��ntjdt
dd��fd	d
�t|�D��d����fdd�}���fd
d���fdd�}�D]}|���q��r�|dk	r҈�||��tt���D]}|�Vq�dS)a^Return an iterator whose values are coroutines.

    When waiting for the yielded coroutines you'll get the results (or
    exceptions!) of the original Futures (or coroutines), in the order
    in which and as soon as they complete.

    This differs from PEP 3148; the proper way to use this is:

        for f in as_completed(fs):
            result = await f  # The 'await' may raise.
            # Use result.

    If a timeout is specified, the 'await' will raise
    TimeoutError when the timeout occurs before all Futures are done.

    Note: The futures 'f' are not necessarily members of fs.
    z#expect an iterable of futures, not r)�QueuerNr�r7r8csh|]}t|�d��qSr�r�r�rr!r"r)Uszas_completed.<locals>.<setcomp>cs*�D]}|�����d�q���dSr1)r��
put_nowait�clearr�)r�r%�todor!r"�_on_timeoutXs
z!as_completed.<locals>._on_timeoutcs4�sdS��|���|��s0�dk	r0���dSr1)�remover�rgr�)r%r�r�r!r"r�^s

z$as_completed.<locals>._on_completionc�s$���IdH}|dkrtj�|��Sr1)rrr�r_r�)r%r!r"�
_wait_for_onefsz#as_completed.<locals>._wait_for_one)rr�rrErGr�rxZqueuesr�rr/r:r;r<r�rrr��ranger�)r�r r~r�r�r�r��_r!)r�r%r r�r�r"r7s*

�rccs
dVdS)z�Skip one event loop run cycle.

    This is a private helper for 'asyncio.sleep()', used
    when the 'delay' is set to 0.  It uses a bare 'yield'
    expression (which Task.__step knows how to handle)
    instead of creating a Future object.
    Nr!r!r!r!r"�__sleep0us	r�c�sr|dkrt�IdH|S|dkr*t��}ntjdtdd�|��}|�|tj	||�}z|IdHW�S|�
�XdS)z9Coroutine that completes after a given time (in seconds).rNr�r7r8)r�rrr:r;r<r�r�rZ_set_result_unless_cancelledrg)Zdelayr_r rw�hr!r!r"r	�s$
��r	cCs�t�|�r6|dkrt��}|�|�}|jr2|jd=|St�|�rb|dk	r^|t�|�k	r^t	d��|St
�|�r|tt
|�|d�Std��dS)zmWrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    Nr?zRThe future belongs to a different loop than the one specified as the loop argumentrz:An asyncio.Future, a coroutine or an awaitable is required)rrErr/rrDrr�r$r�rtZisawaitabler�_wrap_awaitablerG)Zcoro_or_futurer r4r!r!r"r�s



rccs|��EdHS)z�Helper for asyncio.ensure_future().

    Wraps awaitable (an object with __await__) into a coroutine
    that will later be wrapped in a Task by ensure_future().
    N)�	__await__)Z	awaitabler!r!r"r��sr�cs.eZdZdZdd��fdd�
Zdd�Z�ZS)�_GatheringFuturez�Helper for gather().

    This overrides cancel() to cancel all the children and act more
    like Task.cancel(), which doesn't immediately mark itself as
    cancelled.
    Nrcst�j|d�||_d|_dS)NrF)rBrC�	_children�_cancel_requested)rS�childrenr rUr!r"rC�sz_GatheringFuture.__init__cCs6|��rdSd}|jD]}|��rd}q|r2d|_|S)NFT)r%r�rgr�)rSZretZchildr!r!r"rg�s
z_GatheringFuture.cancel)rxryrzr{rCrgr}r!r!rUr"r��sr�F)r �return_exceptionscs�|s<|dkrt��}ntjdtdd�|�����g��S�����fdd�}i}g�d�d�|D]f}||kr�t||d�}|dkr�t�	|�}||k	r�d	|_
�d
7�|||<|�|�n||}��|�qdt
�|d���S)a�Return a future aggregating results from the given coroutines/futures.

    Coroutines will be wrapped in a future and scheduled in the event
    loop. They will not necessarily be scheduled in the same order as
    passed in.

    All futures must share the same event loop.  If all the tasks are
    done successfully, the returned future's result is the list of
    results (in the order of the original sequence, not necessarily
    the order of results arrival).  If *return_exceptions* is True,
    exceptions in the tasks are treated the same as successful
    results, and gathered in the result list; otherwise, the first
    raised exception will be immediately propagated to the returned
    future.

    Cancellation: if the outer Future is cancelled, all children (that
    have not completed yet) are also cancelled.  If any child is
    cancelled, this is treated as if it raised CancelledError --
    the outer Future is *not* cancelled in this case.  (This is to
    prevent the cancellation of one child to cause other children to
    be cancelled.)

    If *return_exceptions* is False, cancelling gather() after it
    has been marked done won't cancel any submitted awaitables.
    For instance, gather can be marked done after propagating an
    exception to the caller, therefore, calling ``gather.cancel()``
    after catching an exception (raised by one of the awaitables) from
    gather won't cancel any other awaitables.
    Nr�r7r8cs��d7����r$|��s |��dS�sd|��rFt��}��|�dS|��}|dk	rd��|�dS��kr�g}�D]8}|��r�t��}n|��}|dkr�|��}|�|�qt�jrĈ�t���n
��	|�dS)Nr)
r%r�rarrjrbr_�appendr�r`)r�ruZresults�res�r�Z	nfinishedZnfuts�outerr�r!r"�_done_callbacks4


zgather.<locals>._done_callbackrrFr)rr/r:r;r<r�r`rrr$rFrrr�r�)r r�Zcoros_or_futuresr�Z
arg_to_fut�argr�r!r�r"r
�s:
�
1
r
cst|dk	rtjdtdd�t||d�����r0�St���}|����fdd����fdd	�}������|��S)
a.Wait for a future, shielding it from cancellation.

    The statement

        res = await shield(something())

    is exactly equivalent to the statement

        res = await something()

    *except* that if the coroutine containing it is cancelled, the
    task running in something() is not cancelled.  From the POV of
    something(), the cancellation did not happen.  But its caller is
    still cancelled, so the yield-from expression still raises
    CancelledError.  Note: If something() is cancelled by other means
    this will still cancel shield().

    If you want to completely ignore cancellation (not recommended)
    you can combine shield() with a try/except clause, as follows:

        try:
            res = await shield(something())
        except CancelledError:
            res = None
    Nr�r7r8rcs\���r|��s|��dS|��r.���n*|��}|dk	rJ��|�n��|���dSr1)r�rargrbr`r_)�innerru�r�r!r"�_inner_done_callbackus
z$shield.<locals>._inner_done_callbackcs���s����dSr1)r%r�r�)r�r�r!r"�_outer_done_callback�sz$shield.<locals>._outer_done_callback)	r:r;r<rr%rr$r�rr)r�r r�r!)r�r�r�r"rPs�


rcs:t���std��tj������fdd�}��|��S)zsSubmit a coroutine object to a given event loop.

    Return a concurrent.futures.Future to access the result.
    zA coroutine object is requiredc
slzt�t��d���WnNttfk
r2�Yn6tk
rf}z���rT��|��W5d}~XYnXdS)Nr)rZ
_chain_futurerrornrpZset_running_or_notify_cancelrb)ru�rTrwr r!r"�callback�s
z*run_coroutine_threadsafe.<locals>.callback)rrErG�
concurrentr�FutureZcall_soon_threadsafe)rTr r�r!r�r"r
�s



r
cCst�|�dS)z3Register a new task in asyncio as executed by loop.N)r+r��r4r!r!r"r�srcCs4t�|�}|dk	r(td|�d|�d���|t|<dS)NzCannot enter into task z while another task z is being executed.�rrr,�r r4rr!r!r"r�s
rcCs2t�|�}||k	r(td|�d|�d���t|=dS)Nz
Leaving task z! does not match the current task �.r�r�r!r!r"r�s
rcCst�|�dS)zUnregister a task.N)r+�discardr�r!r!r"r�sr)rrrrr+r)N)N)N)N)Br{�__all__Zconcurrent.futuresr�rNr�rt�	itertools�typesr:�weakref�rrrrrr�count�__next__rHrrr0r6Z	_PyFuturerZ_PyTaskZ_asyncio�ImportErrorZ_CTaskrrrrrr�rr�r�r�	coroutiner�r	rr�r�r�r
rr
ZWeakSetr+rrrrrZ_py_register_taskZ_py_unregister_taskZ_py_enter_taskZ_py_leave_taskZ_c_register_taskZ_c_unregister_taskZ
_c_enter_taskZ
_c_leave_taskr!r!r!r"�<module>s�	





#H,>

x?$PK [2�
��+__pycache__/transports.cpython-38.opt-2.pycnu�[���U

e5d�(�@sxdZGdd�d�ZGdd�de�ZGdd�de�ZGdd�dee�ZGd	d
�d
e�ZGdd�de�ZGd
d�de�ZdS))�
BaseTransport�
ReadTransport�WriteTransport�	Transport�DatagramTransport�SubprocessTransportc@sDeZdZdZddd�Zddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)r��_extraNcCs|dkri}||_dS�Nr)�self�extra�r�*/usr/lib64/python3.8/asyncio/transports.py�__init__szBaseTransport.__init__cCs|j�||�Sr	)r�get)r
�name�defaultrrr
�get_extra_infoszBaseTransport.get_extra_infocCst�dSr	��NotImplementedError�r
rrr
�
is_closingszBaseTransport.is_closingcCst�dSr	rrrrr
�closeszBaseTransport.closecCst�dSr	r)r
�protocolrrr
�set_protocol%szBaseTransport.set_protocolcCst�dSr	rrrrr
�get_protocol)szBaseTransport.get_protocol)N)N)
�__name__�
__module__�__qualname__�	__slots__rrrrrrrrrr
r	s


rc@s(eZdZdZdd�Zdd�Zdd�ZdS)	rrcCst�dSr	rrrrr
�
is_reading3szReadTransport.is_readingcCst�dSr	rrrrr
�
pause_reading7szReadTransport.pause_readingcCst�dSr	rrrrr
�resume_reading?szReadTransport.resume_readingN)rrrrrr r!rrrr
r.src@sJeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dS)rrNcCst�dSr	r�r
�high�lowrrr
�set_write_buffer_limitsMsz&WriteTransport.set_write_buffer_limitscCst�dSr	rrrrr
�get_write_buffer_sizebsz$WriteTransport.get_write_buffer_sizecCst�dSr	r)r
�datarrr
�writefszWriteTransport.writecCsd�|�}|�|�dS)N�)�joinr()r
Zlist_of_datar'rrr
�
writelinesns
zWriteTransport.writelinescCst�dSr	rrrrr
�	write_eofwszWriteTransport.write_eofcCst�dSr	rrrrr
�
can_write_eof�szWriteTransport.can_write_eofcCst�dSr	rrrrr
�abort�szWriteTransport.abort)NN)rrrrr%r&r(r+r,r-r.rrrr
rHs
		rc@seZdZdZdS)rrN)rrrrrrrr
r�src@s"eZdZdZddd�Zdd�ZdS)rrNcCst�dSr	r)r
r'Zaddrrrr
�sendto�szDatagramTransport.sendtocCst�dSr	rrrrr
r.�szDatagramTransport.abort)N)rrrrr/r.rrrr
r�s

rc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)rrcCst�dSr	rrrrr
�get_pid�szSubprocessTransport.get_pidcCst�dSr	rrrrr
�get_returncode�sz"SubprocessTransport.get_returncodecCst�dSr	r)r
�fdrrr
�get_pipe_transport�sz&SubprocessTransport.get_pipe_transportcCst�dSr	r)r
�signalrrr
�send_signal�szSubprocessTransport.send_signalcCst�dSr	rrrrr
�	terminate�szSubprocessTransport.terminatecCst�dSr	rrrrr
�kill�s	zSubprocessTransport.killN)
rrrrr0r1r3r5r6r7rrrr
r�srcsVeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zddd�Zdd
d�Z	dd�Z
�ZS)�_FlowControlMixin)�_loop�_protocol_paused�_high_water�
_low_waterNcs$t��|�||_d|_|��dS)NF)�superrr9r:�_set_write_buffer_limits)r
rZloop��	__class__rr
rsz_FlowControlMixin.__init__c
Cs�|��}||jkrdS|js�d|_z|j��WnRttfk
rJ�Yn:tk
r�}z|j�	d|||jd��W5d}~XYnXdS)NTzprotocol.pause_writing() failed��messageZ	exceptionZ	transportr)
r&r;r:�	_protocolZ
pause_writing�
SystemExit�KeyboardInterrupt�
BaseExceptionr9�call_exception_handler)r
�size�excrrr
�_maybe_pause_protocols 
�z'_FlowControlMixin._maybe_pause_protocolc
Cs�|jr||��|jkr|d|_z|j��WnRttfk
rB�Yn:tk
rz}z|j�	d|||jd��W5d}~XYnXdS)NFz protocol.resume_writing() failedrA)
r:r&r<rCZresume_writingrDrErFr9rG)r
rIrrr
�_maybe_resume_protocol!s��z(_FlowControlMixin._maybe_resume_protocolcCs|j|jfSr	)r<r;rrrr
�get_write_buffer_limits1sz)_FlowControlMixin.get_write_buffer_limitscCsj|dkr|dkrd}nd|}|dkr.|d}||krBdksZntd|�d|�d���||_||_dS)Ni��zhigh (z) must be >= low (z) must be >= 0)�
ValueErrorr;r<r"rrr
r>4s�z*_FlowControlMixin._set_write_buffer_limitscCs|j||d�|��dS)N)r#r$)r>rJr"rrr
r%Dsz)_FlowControlMixin.set_write_buffer_limitscCst�dSr	rrrrr
r&Hsz'_FlowControlMixin.get_write_buffer_size)NN)NN)NN)rrrrrrJrKrLr>r%r&�
__classcell__rrr?r
r8�s

r8N)�__all__rrrrrrr8rrrr
�<module>s%F6PK [�O�=]=]0__pycache__/proactor_events.cpython-38.opt-1.pycnu�[���U

e5d<}�@sTdZdZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
ddl	mZddl	mZddl	m
Z
dd	l	mZdd
l	mZddl	mZddl	mZdd
lmZdd�ZGdd�dejej�ZGdd�deej�ZGdd�deej�ZGdd�de�ZGdd�de�ZGdd�deeej�ZGdd�deeej�Z Gdd�de
j!�Z"dS) z�Event loop using a proactor and related classes.

A proactor is a "notify-on-completion" multiplexer.  Currently a
proactor is only implemented on Windows with IOCP.
)�BaseProactorEventLoop�N�)�base_events)�	constants)�futures)�
exceptions)�	protocols)�sslproto)�
transports)�trsock)�loggercCs�t�|�|jd<z|��|jd<Wn0tjk
rR|j��rNtj	d|dd�YnXd|jkr�z|�
�|jd<Wn tjk
r�d|jd<YnXdS)N�socketZsocknamezgetsockname() failed on %rT��exc_info�peername)r�TransportSocket�_extraZgetsocknamer
�error�_loop�	get_debugr�warningZgetpeername)�	transport�sock�r�//usr/lib64/python3.8/asyncio/proactor_events.py�_set_socket_extras
�
rcs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
ejfdd�Z
ddd�Zdd�Zdd�Zdd�Z�ZS)�_ProactorBasePipeTransportz*Base class for pipe and socket transports.Ncs�t��||�|�|�||_|�|�||_d|_d|_d|_d|_	d|_
d|_d|_|jdk	rl|j�
�|j�|jj|�|dk	r�|j�tj|d�dS)NrF)�super�__init__�
_set_extra�_sock�set_protocol�_server�_buffer�	_read_fut�
_write_fut�_pending_write�
_conn_lost�_closing�_eof_writtenZ_attachr�	call_soon�	_protocolZconnection_maderZ_set_result_unless_cancelled��self�loopr�protocol�waiter�extra�server��	__class__rrr2s(




�z#_ProactorBasePipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|jdk	rP|�d|j�����|jdk	rl|�d|j���|jdk	r�|�d|j���|jr�|�dt	|j����|j
r�|�d�d�d	�|��S)
N�closed�closingzfd=zread=zwrite=zwrite_bufsize=zEOF writtenz<{}>� )
r4�__name__r �appendr(�filenor$r%r#�lenr)�format�join)r-�inforrr�__repr__Hs 






z#_ProactorBasePipeTransport.__repr__cCs||jd<dS)N�pipe)r�r-rrrrrZsz%_ProactorBasePipeTransport._set_extracCs
||_dS�N�r+)r-r/rrrr!]sz'_ProactorBasePipeTransport.set_protocolcCs|jSrBrC�r-rrr�get_protocol`sz'_ProactorBasePipeTransport.get_protocolcCs|jSrB)r(rDrrr�
is_closingcsz%_ProactorBasePipeTransport.is_closingcCs\|jr
dSd|_|jd7_|js>|jdkr>|j�|jd�|jdk	rX|j��d|_dS)NTr)	r(r'r#r%rr*�_call_connection_lostr$�cancelrDrrr�closefs

z _ProactorBasePipeTransport.closecCs*|jdk	r&|d|��t|d�|��dS)Nzunclosed transport )�source)r �ResourceWarningrI)r-Z_warnrrr�__del__qs
z"_ProactorBasePipeTransport.__del__�Fatal error on pipe transportc	CsVzDt|t�r*|j��rBtjd||dd�n|j�||||jd��W5|�|�XdS)Nz%r: %sTr)�message�	exceptionrr/)	�_force_close�
isinstance�OSErrorrrr�debug�call_exception_handlerr+)r-�excrNrrr�_fatal_errorvs

�z'_ProactorBasePipeTransport._fatal_errorcCs�|jdk	r6|j��s6|dkr*|j�d�n|j�|�|jr@dSd|_|jd7_|jrj|j��d|_|jr�|j��d|_d|_	d|_
|j�|j
|�dS)NTrr)�
_empty_waiter�done�
set_resultZ
set_exceptionr(r'r%rHr$r&r#rr*rG)r-rUrrrrP�s"

z'_ProactorBasePipeTransport._force_closec	Cs^z|j�	|�W5t|jd�r,|j�tj�|j��d|_|j}|dk	rX|��d|_XdS)N�shutdown)
�hasattrr rZr
Z	SHUT_RDWRrIr"Z_detachr+Zconnection_lost)r-rUr2rrrrG�s
z0_ProactorBasePipeTransport._call_connection_lostcCs"|j}|jdk	r|t|j�7}|SrB)r&r#r;)r-�sizerrr�get_write_buffer_size�s
z0_ProactorBasePipeTransport.get_write_buffer_size)NNN)rM)r8�
__module__�__qualname__�__doc__rr?rr!rErFrI�warnings�warnrLrVrPrGr]�
__classcell__rrr3rr.s �
rcsTeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	ddd�Z
�ZS)�_ProactorReadPipeTransportzTransport for read pipes.Ncs:d|_d|_t��||||||�|j�|j�d|_dS)NTF)�
_pending_data�_pausedrrrr*�
_loop_readingr,r3rrr�s
z#_ProactorReadPipeTransport.__init__cCs|jo|jSrB)rfr(rDrrr�
is_reading�sz%_ProactorReadPipeTransport.is_readingcCs0|js|jrdSd|_|j��r,t�d|�dS)NTz%r pauses reading)r(rfrrrrSrDrrr�
pause_reading�s

z(_ProactorReadPipeTransport.pause_readingcCsn|js|jsdSd|_|jdkr0|j�|jd�|j}d|_|dk	rT|j�|j|�|j��rjt	�
d|�dS)NFz%r resumes reading)r(rfr$rr*rgre�_data_receivedrrrS�r-�datarrr�resume_reading�s

z)_ProactorReadPipeTransport.resume_readingc
Cs�|j��rt�d|�z|j��}WnLttfk
r>�Yn4tk
rp}z|�	|d�WY�dSd}~XYnX|s~|�
�dS)Nz%r received EOFz1Fatal error: protocol.eof_received() call failed.)rrrrSr+Zeof_received�
SystemExit�KeyboardInterrupt�
BaseExceptionrVrI)r-Z	keep_openrUrrr�
_eof_received�s
�z(_ProactorReadPipeTransport._eof_receivedc
Cs�|jr||_dS|s |��dSt|jtj�r�zt�|j|�Wq�tt	fk
rZ�Yq�t
k
r�}z|�|d�WY�dSd}~XYq�Xn|j�|�dS)Nz3Fatal error: protocol.buffer_updated() call failed.)
rfrerqrQr+rZBufferedProtocolZ_feed_data_to_buffered_protornrorprVZ
data_received)r-rlrUrrrrj�s"�z)_ProactorReadPipeTransport._data_receivedc
Cstd}�zRzp|dk	r2d|_|��r*|��}n|��|jrHd}WW��dS|dkr\WW��dS|jsv|jj�	|j
d�|_Wn�tk
r�}z0|js�|�|d�n|j�
�r�tjddd�W5d}~XYn�tk
r�}z|�|�W5d}~XYnftk
�r}z|�|d�W5d}~XYn8tjk
�r>|j�s:�YnX|j�sV|j�|j�W5|dk	�rn|�|�XdS)N�i�z"Fatal read error on pipe transportz*Read error on pipe transport while closingTr)rjr$rX�resultrHr(rfr�	_proactor�recvr �ConnectionAbortedErrorrVrrrS�ConnectionResetErrorrPrRr�CancelledError�add_done_callbackrg)r-�futrlrUrrrrgs@

�
z(_ProactorReadPipeTransport._loop_reading)NNN)N)r8r^r_r`rrhrirmrqrjrgrcrrr3rrd�s�	rdcs^eZdZdZdZ�fdd�Zdd�Zddd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Z�Z
S)�_ProactorBaseWritePipeTransportzTransport for write pipes.Tcst�j||�d|_dSrB)rrrW�r-�args�kwr3rrrGsz(_ProactorBaseWritePipeTransport.__init__cCs�t|tttf�s$tdt|�j����|jr2td��|j	dk	rDtd��|sLdS|j
rz|j
tjkrht
�d�|j
d7_
dS|jdkr�|jt|�d�n.|js�t|�|_|��n|j�|�|��dS)Nz/data argument must be a bytes-like object, not zwrite_eof() already calledz(unable to write; sendfile is in progresszsocket.send() raised exception.r)rl)rQ�bytes�	bytearray�
memoryview�	TypeError�typer8r)�RuntimeErrorrWr'r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESrrr%�
_loop_writingr#�_maybe_pause_protocol�extendrkrrr�writeKs,�




z%_ProactorBaseWritePipeTransport.writeNc
CsVz�|dk	r |jdkr |jr WdSd|_d|_|r8|��|dkrL|j}d|_|s�|jrf|j�|jd�|jrz|j	�
tj�|�
�nN|jj�|j	|�|_|j��s�t|�|_|j�|j�|��n|j�|j�|jdk	r�|jdkr�|j�d�Wn\tk
�r"}z|�|�W5d}~XYn0tk
�rP}z|�|d�W5d}~XYnXdS)Nrz#Fatal write error on pipe transport)r%r(r&rsr#rr*rGr)r rZr
�SHUT_WR�_maybe_resume_protocolrt�sendrXr;ryr�r�rWrYrwrPrRrV)r-�frlrUrrrr�qs8



z-_ProactorBaseWritePipeTransport._loop_writingcCsdS�NTrrDrrr�
can_write_eof�sz-_ProactorBaseWritePipeTransport.can_write_eofcCs|��dSrB)rIrDrrr�	write_eof�sz)_ProactorBaseWritePipeTransport.write_eofcCs|�d�dSrB�rPrDrrr�abort�sz%_ProactorBaseWritePipeTransport.abortcCs:|jdk	rtd��|j��|_|jdkr4|j�d�|jS)NzEmpty waiter is already set)rWr�rZ
create_futurer%rYrDrrr�_make_empty_waiter�s

z2_ProactorBaseWritePipeTransport._make_empty_waitercCs
d|_dSrB)rWrDrrr�_reset_empty_waiter�sz3_ProactorBaseWritePipeTransport._reset_empty_waiter)NN)r8r^r_r`Z_start_tls_compatiblerr�r�r�r�r�r�r�rcrrr3rr{As&
)r{cs$eZdZ�fdd�Zdd�Z�ZS)�_ProactorWritePipeTransportcs4t�j||�|jj�|jd�|_|j�|j�dS)N�)	rrrrtrur r$ry�_pipe_closedr|r3rrr�sz$_ProactorWritePipeTransport.__init__cCs@|��rdS|jrdSd|_|jdk	r4|�t��n|��dSrB)Z	cancelledr(r$r%rP�BrokenPipeErrorrI)r-rzrrrr��s
z(_ProactorWritePipeTransport._pipe_closed)r8r^r_rr�rcrrr3rr��sr�csXeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zddd�Zdd
d�Z	ddd�Z
�ZS)�_ProactorDatagramTransportiNcs>||_d|_t�j|||||d�t��|_|j�|j	�dS)N)r0r1)
�_addressrWrr�collections�dequer#rr*rg)r-r.rr/�addressr0r1r3rrr�s

z#_ProactorDatagramTransport.__init__cCst||�dSrB�rrArrrr�sz%_ProactorDatagramTransport._set_extracCstdd�|jD��S)Ncss|]\}}t|�VqdSrB)r;)�.0rl�_rrr�	<genexpr>�szC_ProactorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr#rDrrrr]�sz0_ProactorDatagramTransport.get_write_buffer_sizecCs|�d�dSrBr�rDrrrr��sz _ProactorDatagramTransport.abortcCs�t|tttf�stdt|���|s&dS|jdk	rN|d|jfkrNtd|j����|jr�|jr�|jt	j
krpt�d�|jd7_dS|j
�t|�|f�|jdkr�|��|��dS)Nz,data argument must be bytes-like object (%r)z!Invalid address: must be None or z!socket.sendto() raised exception.r)rQrr�r�r�r�r��
ValueErrorr'rr�rrr#r9r%r�r�)r-rl�addrrrr�sendto�s&�
�

z!_ProactorDatagramTransport.sendtoc
Csz�|jrWdSd|_|r |��|jr2|jrN|jrN|jrH|j�|jd�WdS|j�	�\}}|jdk	r||jj
�|j|�|_n|jj
j
|j||d�|_WnZtk
r�}z|j�|�W5d}~XYnDtk
r�}z|�|d�W5d}~XYnX|j�|j�|��dS)N)r�z'Fatal write error on datagram transport)r'r%rsr#r�r(rr*rG�popleftrtr�r r�rRr+�error_received�	ExceptionrVryr�r�)r-rzrlr�rUrrrr��s2
��z(_ProactorDatagramTransport._loop_writingc
Cs4d}�zz�|jrWW��dSd|_|dk	rf|��}|jrFd}WW��dS|jdk	r^||j}}n|\}}|jrvWW��dS|jdk	r�|jj�	|j
|j�|_n|jj�|j
|j�|_WnJt
k
r�}z|j�|�W5d}~XYn8tjk
r�|js��YnX|jdk	�r|j�|j�W5|�r.|j�||�XdSrB)r+Zdatagram_receivedr'r$rsr(r�rrtrur �max_sizeZrecvfromrRr�rrxryrg)r-rzrlr��resrUrrrrgs>



��
z(_ProactorDatagramTransport._loop_reading)NNN)N)N)N)r8r^r_r�rrr]r�r�r�rgrcrrr3rr��s�

!r�c@s eZdZdZdd�Zdd�ZdS)�_ProactorDuplexPipeTransportzTransport for duplex pipes.cCsdS)NFrrDrrrr�Jsz*_ProactorDuplexPipeTransport.can_write_eofcCst�dSrB)�NotImplementedErrorrDrrrr�Msz&_ProactorDuplexPipeTransport.write_eofN)r8r^r_r`r�r�rrrrr�Esr�csBeZdZdZejjZd�fdd�	Zdd�Z	dd�Z
d	d
�Z�ZS)�_ProactorSocketTransportz Transport for connected sockets.Ncs$t��||||||�t�|�dSrB)rrrZ_set_nodelayr,r3rrrXsz!_ProactorSocketTransport.__init__cCst||�dSrBr�rArrrr]sz#_ProactorSocketTransport._set_extracCsdSr�rrDrrrr�`sz&_ProactorSocketTransport.can_write_eofcCs2|js|jrdSd|_|jdkr.|j�tj�dSr�)r(r)r%r rZr
r�rDrrrr�cs

z"_ProactorSocketTransport.write_eof)NNN)
r8r^r_r`rZ
_SendfileModeZ
TRY_NATIVEZ_sendfile_compatiblerrr�r�rcrrr3rr�Qs�r�cs�eZdZ�fdd�Zd3dd�Zd4dddddd�dd	�Zd5d
d�Zd6dd
�Zd7dd�Zd8dd�Z	�fdd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd9d&d'�Zd(d)�Zd:d+d,�Zd-d.�Zd/d0�Zd1d2�Z�ZS);rcsht���t�d|jj�||_||_d|_i|_	|�
|�|��t�
�t��krdt�|j���dS)NzUsing proactor: %s)rrrrSr4r8rt�	_selector�_self_reading_future�_accept_futuresZset_loop�_make_self_pipe�	threading�current_thread�main_thread�signal�
set_wakeup_fd�_csockr:)r-Zproactorr3rrrms

zBaseProactorEventLoop.__init__NcCst||||||�SrB)r�)r-rr/r0r1r2rrr�_make_socket_transportzs
�z,BaseProactorEventLoop._make_socket_transportF)�server_side�server_hostnamer1r2�ssl_handshake_timeoutc	Cs0tj|||||||	d�}
t|||
||d�|
jS)N)r��r1r2)r	ZSSLProtocolr�Z_app_transport)r-Zrawsockr/�
sslcontextr0r�r�r1r2r�Zssl_protocolrrr�_make_ssl_transports��z)BaseProactorEventLoop._make_ssl_transportcCst||||||�SrB)r�)r-rr/r�r0r1rrr�_make_datagram_transport�s
�z.BaseProactorEventLoop._make_datagram_transportcCst|||||�SrB)r��r-rr/r0r1rrr�_make_duplex_pipe_transport�s�z1BaseProactorEventLoop._make_duplex_pipe_transportcCst|||||�SrB)rdr�rrr�_make_read_pipe_transport�sz/BaseProactorEventLoop._make_read_pipe_transportcCst|||||�SrB)r�r�rrr�_make_write_pipe_transport�s�z0BaseProactorEventLoop._make_write_pipe_transportcsj|��rtd��|��rdSt��t��kr6t�d�|��|�	�|j
��d|_
d|_t
���dS)Nz!Cannot close a running event loop���)Z
is_runningr��	is_closedr�r�r�r�r��_stop_accept_futures�_close_self_pipertrIr�rrDr3rrrI�s

zBaseProactorEventLoop.closec�s|j�||�IdHSrB)rtru)r-r�nrrr�	sock_recv�szBaseProactorEventLoop.sock_recvc�s|j�||�IdHSrB)rtZ	recv_into)r-rZbufrrr�sock_recv_into�sz$BaseProactorEventLoop.sock_recv_intoc�s|j�||�IdHSrB)rtr�)r-rrlrrr�sock_sendall�sz"BaseProactorEventLoop.sock_sendallc�s|j�||�IdHSrB)rtZconnect)r-rr�rrr�sock_connect�sz"BaseProactorEventLoop.sock_connectc�s|j�|�IdHSrB)rt�acceptrArrr�sock_accept�sz!BaseProactorEventLoop.sock_acceptc
�s(z|��}Wn2ttjfk
r>}zt�d��W5d}~XYnXzt�|�j}Wn,t	k
r|}zt�d��W5d}~XYnX|r�|n|}|s�dSt
|d�}|r�t
|||�n|}	t
||�}d}
zLt
|	||�}|dkr�|
W�0S|j�
||||�IdH||7}|
|7}
q�W5|
dk�r"|�|�XdS)Nznot a regular filerl��)r:�AttributeError�io�UnsupportedOperationrZSendfileNotAvailableError�os�fstat�st_sizerR�min�seekrt�sendfile)r-r�file�offset�countr:�errZfsizeZ	blocksizeZend_posZ
total_sentrrr�_sock_sendfile_native�s0


z+BaseProactorEventLoop._sock_sendfile_nativec�sZ|��}|��|��IdHz |j|j|||dd�IdHW�S|��|rT|��XdS)NF)Zfallback)rhrir�r�rmZ
sock_sendfiler )r-Ztranspr�r�r�rmrrr�_sendfile_native�s�z&BaseProactorEventLoop._sendfile_nativecCsL|jdk	r|j��d|_|j��d|_|j��d|_|jd8_dS)Nr)r�rH�_ssockrIr��
_internal_fdsrDrrrr��s



z&BaseProactorEventLoop._close_self_pipecCs:t��\|_|_|j�d�|j�d�|jd7_dS)NFr)r
Z
socketpairr�r�Zsetblockingr�rDrrrr��sz%BaseProactorEventLoop._make_self_pipec
Cs�z4|dk	r|��|j|k	r"WdS|j�|jd�}Wnbtjk
rLYdSttfk
rd�YnFt	k
r�}z|�
d||d��W5d}~XYnX||_|�|j�dS)Niz.Error on reading from the event loop self pipe)rNrOr.)
rsr�rtrur�rrxrnrorprTry�_loop_self_reading)r-r�rUrrrr��s$
�z(BaseProactorEventLoop._loop_self_readingcCsN|j}|dkrdSz|�d�Wn(tk
rH|jrDtjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketTr)r�r�rR�_debugrrS)r-Zcsockrrr�_write_to_selfs�z$BaseProactorEventLoop._write_to_self�dcs(d�������fdd�	�����dS)Nc
s,z�|dk	rn|��\}}�jr,t�d�||���}�dk	rX�j||�dd|i��d�n�j||d|i�d����r|WdS�j���}Wn�t	k
r�}zH��
�dkrʈ�d|t�
��d�����n�jr�tjd	�dd
�W5d}~XYn8tjk
�r���YnX|�j��
�<|���dS)Nz#%r got a new connection from %r: %rTr)r�r1r2r�r�r�zAccept failed on a socket)rNrOr
zAccept failed on socket %rr)rsr�rrSr�r�r�rtr�rRr:rTrrrIrrxr�ry)r�Zconnr�r/rU�r.�protocol_factoryr-r2rr�r�rrr./s\����
�z2BaseProactorEventLoop._start_serving.<locals>.loop)N)r*)r-r�rr�r2Zbacklogr�rr�r�_start_serving+s%z$BaseProactorEventLoop._start_servingcCsdSrBr)r-Z
event_listrrr�_process_eventsVsz%BaseProactorEventLoop._process_eventscCs&|j��D]}|��q
|j��dSrB)r��valuesrH�clear)r-�futurerrrr�Zs
z*BaseProactorEventLoop._stop_accept_futurescCs6|j�|��d�}|r|��|j�|�|��dSrB)r��popr:rHrt�
_stop_servingrI)r-rr�rrrr�_s
z#BaseProactorEventLoop._stop_serving)NNN)N)NNN)NN)NN)NN)N)NNr�N)r8r^r_rr�r�r�r�r�r�rIr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rcrrr3rrks\
�
���
�
�
�


�
+r)#r`�__all__r�r�r
rar�r�r��rrrrrr	r
r�logrrZ_FlowControlMixinZ
BaseTransportrZ
ReadTransportrdZWriteTransportr{r�r�Z	Transportr�r�Z
BaseEventLooprrrrr�<module>sR���n��PK [-w/��#__pycache__/__init__.cpython-38.pycnu�[���U

e5d��@sdZddlZddlTddlTddlTddlTddlTddlTddlTddl	Tddl
TddlTddlTddl
TddlTddl
mZejejejejejejeje	je
jejeje
jejZejdkr�ddlTeej7ZnddlTeej7ZdS)z'The asyncio package, tracking PEP 3156.�N�)�*)�_all_tasks_compatZwin32)�__doc__�sysZbase_eventsZ
coroutinesZevents�
exceptionsZfuturesZlocksZ	protocolsZrunnersZqueuesZstreams�
subprocessZtasksZ
transportsr�__all__�platformZwindows_eventsZunix_events�rr�(/usr/lib64/python3.8/asyncio/__init__.py�<module>sZ��������	�
���
PK [��gF��,__pycache__/unix_events.cpython-38.opt-2.pycnu�[���U

e5dۿ�@s�ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlm
Z
ddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZdZe	jdkr�ed��dd�ZGdd�dej�ZGdd�dej�Z Gdd�dej!ej"�Z#Gdd�dej$�Z%Gdd�d�Z&dd�Z'Gdd �d e&�Z(Gd!d"�d"e(�Z)Gd#d$�d$e(�Z*Gd%d&�d&e&�Z+Gd'd(�d(e&�Z,Gd)d*�d*ej-�Z.eZ/e.Z0dS)+�N�)�base_events)�base_subprocess)�	constants)�
coroutines)�events)�
exceptions)�futures)�selector_events)�tasks)�
transports)�logger)�SelectorEventLoop�AbstractChildWatcher�SafeChildWatcher�FastChildWatcher�MultiLoopChildWatcher�ThreadedChildWatcher�DefaultEventLoopPolicyZwin32z+Signals are not really supported on WindowscCsdS�N�)�signum�framerr�+/usr/lib64/python3.8/asyncio/unix_events.py�_sighandler_noop*srcs�eZdZd(�fdd�	Z�fdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	d)dd�Z
d*dd�Zd+dd�Zdd�Z
d,ddddd�dd�Zd-dddddd�dd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Z�ZS).�_UnixSelectorEventLoopNcst��|�i|_dSr)�super�__init__�_signal_handlers)�self�selector��	__class__rrr5sz_UnixSelectorEventLoop.__init__csZt���t��s.t|j�D]}|�|�qn(|jrVtjd|�d�t	|d�|j�
�dS)NzClosing the loop z@ on interpreter shutdown stage, skipping signal handlers removal��source)r�close�sys�
is_finalizing�listr�remove_signal_handler�warnings�warn�ResourceWarning�clear�r�sigr!rrr%9s
�z_UnixSelectorEventLoop.closecCs|D]}|sq|�|�qdSr)�_handle_signal)r�datarrrr�_process_self_dataGsz)_UnixSelectorEventLoop._process_self_datac
GsLt�|�st�|�rtd��|�|�|��zt�|j�	��Wn2t
tfk
rt}ztt
|���W5d}~XYnXt�|||d�}||j|<zt�|t�t�|d�Wn�tk
�rF}zz|j|=|j�szt�d�Wn4t
tfk
�r}zt�d|�W5d}~XYnX|jtjk�r4td|�d���n�W5d}~XYnXdS)Nz3coroutines cannot be used with add_signal_handler()F����set_wakeup_fd(-1) failed: %s�sig � cannot be caught)rZiscoroutineZiscoroutinefunction�	TypeError�
_check_signalZ
_check_closed�signal�
set_wakeup_fdZ_csock�fileno�
ValueError�OSError�RuntimeError�strrZHandlerr�siginterruptr
�info�errno�EINVAL)rr/�callback�args�exc�handleZnexcrrr�add_signal_handlerNs2
�

z)_UnixSelectorEventLoop.add_signal_handlercCs8|j�|�}|dkrdS|jr*|�|�n
|�|�dSr)r�getZ
_cancelledr)Z_add_callback_signalsafe)rr/rGrrrr0{sz%_UnixSelectorEventLoop._handle_signalc
Cs�|�|�z|j|=Wntk
r,YdSX|tjkr@tj}ntj}zt�||�WnBtk
r�}z$|jtj	kr�t
d|�d���n�W5d}~XYnX|js�zt�d�Wn2ttfk
r�}zt
�d|�W5d}~XYnXdS)NFr5r6r3r4T)r8r�KeyErrorr9�SIGINT�default_int_handler�SIG_DFLr=rBrCr>r:r<r
rA)rr/�handlerrFrrrr)�s(

z,_UnixSelectorEventLoop.remove_signal_handlercCs6t|t�std|����|t��kr2td|����dS)Nzsig must be an int, not zinvalid signal number )�
isinstance�intr7r9�
valid_signalsr<r.rrrr8�s
z$_UnixSelectorEventLoop._check_signalcCst|||||�Sr)�_UnixReadPipeTransport�r�pipe�protocol�waiter�extrarrr�_make_read_pipe_transport�sz0_UnixSelectorEventLoop._make_read_pipe_transportcCst|||||�Sr)�_UnixWritePipeTransportrSrrr�_make_write_pipe_transport�sz1_UnixSelectorEventLoop._make_write_pipe_transportc	

�s�t����}
|
��std��|��}t||||||||f||d�|	��}|
�|��|j|�z|IdHWnDt	t
fk
r��Yn,tk
r�|��|�
�IdH�YnXW5QRX|S)NzRasyncio.get_child_watcher() is not activated, subprocess support is not installed.)rVrW)r�get_child_watcher�	is_activer>�
create_future�_UnixSubprocessTransport�add_child_handlerZget_pid�_child_watcher_callback�
SystemExit�KeyboardInterrupt�
BaseExceptionr%Z_wait)
rrUrE�shell�stdin�stdout�stderr�bufsizerW�kwargs�watcherrV�transprrr�_make_subprocess_transport�s8

���
�z1_UnixSelectorEventLoop._make_subprocess_transportcCs|�|j|�dSr)�call_soon_threadsafeZ_process_exited)r�pid�
returncoderkrrrr`�sz._UnixSelectorEventLoop._child_watcher_callback)�ssl�sock�server_hostname�ssl_handshake_timeoutc	�s
|r|dkr6td��n |dk	r&td��|dk	r6td��|dk	r�|dk	rNtd��t�|�}t�tjtjd�}z |�d�|�||�IdHWq�|���Yq�Xn@|dkr�td��|j	tjks�|j
tjkr�td|����|�d�|j|||||d	�IdH\}}||fS)
Nz/you have to pass server_hostname when using sslz+server_hostname is only meaningful with ssl�1ssl_handshake_timeout is only meaningful with ssl�3path and sock can not be specified at the same timerFzno path and sock were specified�.A UNIX Domain Stream Socket was expected, got )rs)r<�os�fspath�socket�AF_UNIX�SOCK_STREAM�setblockingZsock_connectr%�family�typeZ_create_connection_transport)	r�protocol_factory�pathrprqrrrs�	transportrUrrr�create_unix_connection�sR���



��
�z-_UnixSelectorEventLoop.create_unix_connection�dT)rq�backlogrprs�
start_servingc
�s�t|t�rtd��|dk	r&|s&td��|dk	�rH|dk	r@td��t�|�}t�tjtj�}|ddkr�z t	�
t�	|�j�r�t�|�WnBt
k
r�Yn0tk
r�}zt�d||�W5d}~XYnXz|�|�Wnltk
�r0}	z8|��|	jtjk�rd|�d�}
ttj|
�d�n�W5d}	~	XYn|���YnXn<|dk�rZtd	��|jtjk�sv|jtjk�r�td
|����|�d�t�||g||||�}|�r�|��tjd|d�IdH|S)
Nz*ssl argument must be an SSLContext or Nonertrur)r�z2Unable to check or remove stale UNIX socket %r: %rzAddress z is already in usez-path was not specified, and no sock specifiedrvF)�loop)rO�boolr7r<rwrxryrzr{�stat�S_ISSOCK�st_mode�remove�FileNotFoundErrorr=r
�errorZbindr%rBZ
EADDRINUSEr}r~r|rZServerZ_start_servingr�sleep)rrr�rqr�rprsr��errrF�msgZserverrrr�create_unix_serversn
�
�
�

�
��
�z)_UnixSelectorEventLoop.create_unix_serverc
�s�z
tjWn,tk
r6}zt�d��W5d}~XYnXz|��}Wn2ttjfk
rv}zt�d��W5d}~XYnXzt�|�j	}Wn,t
k
r�}zt�d��W5d}~XYnX|r�|n|}	|	s�dS|��}
|�|
d|||||	d�|
IdHS)Nzos.sendfile() is not availableznot a regular filer)
rw�sendfile�AttributeErrorr�SendfileNotAvailableErrorr;�io�UnsupportedOperation�fstat�st_sizer=r]�_sock_sendfile_native_impl)rrq�file�offset�countrFr;r�Zfsize�	blocksize�futrrr�_sock_sendfile_nativeJs2
��z,_UnixSelectorEventLoop._sock_sendfile_nativec	Cs,|��}	|dk	r|�|�|��r4|�|||�dS|rd||}|dkrd|�|||�|�|�dSzt�|	|||�}
W�nDttfk
r�|dkr�|�	||�|�
|	|j||	||||||�
Y�nbtk
�rj}z�|dk	�r|j
t
jk�rt|�tk	�rtdt
j�}||_|}|dk�rBt�d�}
|�|||�|�|
�n|�|||�|�|�W5d}~XYn�ttfk
�r��Yn�tk
�r�}z|�|||�|�|�W5d}~XYnjX|
dk�r�|�|||�|�|�nD||
7}||
7}|dk�r
|�	||�|�
|	|j||	||||||�
dS)Nrzsocket is not connectedzos.sendfile call failed)r;�
remove_writer�	cancelled�_sock_sendfile_update_fileposZ
set_resultrwr��BlockingIOError�InterruptedError�_sock_add_cancellation_callbackZ
add_writerr�r=rBZENOTCONNr~�ConnectionError�	__cause__rr�Z
set_exceptionrarbrc)rr�Z
registered_fdrqr;r�r�r��
total_sent�fdZsentrF�new_excr�rrrr�as�

�


�
��
�

�z1_UnixSelectorEventLoop._sock_sendfile_native_implcCs|dkrt�||tj�dS�Nr)rw�lseek�SEEK_SET)rr;r�r�rrrr��sz4_UnixSelectorEventLoop._sock_sendfile_update_fileposcs��fdd�}|�|�dS)Ncs&|��r"���}|dkr"��|�dS)Nr3)r�r;r�)r�r��rrqrr�cb�szB_UnixSelectorEventLoop._sock_add_cancellation_callback.<locals>.cb)Zadd_done_callback)rr�rqr�rr�rr��sz6_UnixSelectorEventLoop._sock_add_cancellation_callback)N)NN)NN)N)N)N)�__name__�
__module__�__qualname__rr%r2rHr0r)r8rXrZrlr`r�r�r�r�r�r��
__classcell__rrr!rr/sF-
 �
�
�
��.��CFrcs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Ze
jfdd�Zddd�Zdd�Zdd�Z�ZS) rRiNcs�t��|�||jd<||_||_|��|_||_d|_d|_	t
�|j�j}t
�|�s�t
�|�s�t
�|�s�d|_d|_d|_td��t
�|jd�|j�|jj|�|j�|jj|j|j�|dk	r�|j�tj|d�dS)NrTFz)Pipe transport is for pipes/sockets only.)rr�_extra�_loop�_piper;�_fileno�	_protocol�_closing�_pausedrwr�r�r��S_ISFIFOr��S_ISCHRr<�set_blocking�	call_soon�connection_made�_add_reader�_read_readyr	�_set_result_unless_cancelled)rr�rTrUrVrW�moder!rrr�s:


���
�z_UnixReadPipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���t|jdd�}|jdk	r�|dk	r�t�	||jt
j�}|r�|�d�q�|�d�n |jdk	r�|�d�n
|�d�d�d	�
|��S)
N�closed�closing�fd=�	_selector�polling�idle�open�<{}>� )r"r�r��appendr�r��getattrr�r
�_test_selector_event�	selectorsZ
EVENT_READ�format�join)rrAr r�rrr�__repr__�s(


�

z_UnixReadPipeTransport.__repr__c
Cs�zt�|j|j�}WnDttfk
r,Yn�tk
rX}z|�|d�W5d}~XYn^X|rl|j�	|�nJ|j
��r�t�
d|�d|_|j
�|j�|j
�|jj�|j
�|jd�dS)Nz"Fatal read error on pipe transport�%r was closed by peerT)rw�readr��max_sizer�r�r=�_fatal_errorr�Z
data_receivedr��	get_debugr
rAr��_remove_readerr�Zeof_received�_call_connection_lost)rr1rFrrrr��s
z"_UnixReadPipeTransport._read_readycCs>|js|jrdSd|_|j�|j�|j��r:t�d|�dS)NTz%r pauses reading)r�r�r�r�r�r�r
�debug�rrrr�
pause_reading�s
z$_UnixReadPipeTransport.pause_readingcCsB|js|jsdSd|_|j�|j|j�|j��r>t�d|�dS)NFz%r resumes reading)	r�r�r�r�r�r�r�r
r�r�rrr�resume_readings
z%_UnixReadPipeTransport.resume_readingcCs
||_dSr�r��rrUrrr�set_protocol
sz#_UnixReadPipeTransport.set_protocolcCs|jSrr�r�rrr�get_protocolsz#_UnixReadPipeTransport.get_protocolcCs|jSr�r�r�rrr�
is_closingsz!_UnixReadPipeTransport.is_closingcCs|js|�d�dSr)r��_closer�rrrr%sz_UnixReadPipeTransport.closecCs,|jdk	r(|d|��t|d�|j��dS�Nzunclosed transport r#�r�r,r%�r�_warnrrr�__del__s
z_UnixReadPipeTransport.__del__�Fatal error on pipe transportcCsZt|t�r4|jtjkr4|j��rLtjd||dd�n|j�||||j	d��|�
|�dS�Nz%r: %sT��exc_info)�message�	exceptionr�rU)rOr=rBZEIOr�r�r
r��call_exception_handlerr�r��rrFr�rrrr�s
�z#_UnixReadPipeTransport._fatal_errorcCs(d|_|j�|j�|j�|j|�dS�NT)r�r�r�r�r�r��rrFrrrr�-sz_UnixReadPipeTransport._closecCs4z|j�|�W5|j��d|_d|_d|_XdSr�r�r%r�r�Zconnection_lostr�rrrr�2s
z,_UnixReadPipeTransport._call_connection_lost)NN)r�)r�r�r�r�rr�r�r�r�r�r�r�r%r*r+r�r�r�r�r�rrr!rrR�s
rRcs�eZdZd%�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zejfdd�Zdd�Zd&dd �Zd'd!d"�Zd#d$�Z�ZS)(rYNc
s�t��||�||jd<||_|��|_||_t�|_d|_	d|_
t�|j�j
}t�|�}t�|�}t�|�}	|s�|s�|	s�d|_d|_d|_td��t�|jd�|j�|jj|�|	s�|r�tj�d�s�|j�|jj|j|j�|dk	r�|j�tj|d�dS)NrTrFz?Pipe transport is only for pipes, sockets and character devicesZaix)rrr�r�r;r�r��	bytearray�_buffer�
_conn_lostr�rwr�r�r�r�r�r�r<r�r�r�r�r&�platform�
startswithr�r�r	r�)
rr�rTrUrVrWr�Zis_charZis_fifoZ	is_socketr!rrr?s:




�
�z _UnixWritePipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���t|jdd�}|jdk	r�|dk	r�t�	||jt
j�}|r�|�d�n
|�d�|��}|�d|���n |jdk	r�|�d�n
|�d�d	�
d
�|��S)Nr�r�r�r�r�r�zbufsize=r�r�r�)r"r�r�r�r�r�r�r�r
r�r�ZEVENT_WRITE�get_write_buffer_sizer�r�)rrAr r�rhrrrr�ds,


�


z _UnixWritePipeTransport.__repr__cCs
t|j�Sr)�lenr�r�rrrr�|sz-_UnixWritePipeTransport.get_write_buffer_sizecCs6|j��rt�d|�|jr*|�t��n|��dS)Nr�)r�r�r
rAr�r��BrokenPipeErrorr�rrrr�s

z#_UnixWritePipeTransport._read_readyc
Cs4t|t�rt|�}|sdS|js&|jrN|jtjkr<t�d�|jd7_dS|j	�szt
�|j|�}Wntt
tfk
r�d}YnZttfk
r��YnBtk
r�}z$|jd7_|�|d�WY�dSd}~XYnX|t|�kr�dS|dk�rt|�|d�}|j�|j|j�|j	|7_	|��dS)Nz=pipe closed by peer or os.write(pipe, data) raised exception.rr�#Fatal write error on pipe transport)rOr��
memoryviewr�r�rZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningr�rw�writer�r�r�rarbrcr�r�r�Z_add_writer�_write_readyZ_maybe_pause_protocol)rr1�nrFrrrr�s6


z_UnixWritePipeTransport.writec
Cszt�|j|j�}Wn�ttfk
r,Yn�ttfk
rD�Yn�tk
r�}z6|j�	�|j
d7_
|j�|j�|�
|d�W5d}~XYnfX|t|j�kr�|j�	�|j�|j�|��|jr�|j�|j�|�d�dS|dkr�|jd|�=dS)Nrr�r)rwrr�r�r�r�rarbrcr-r�r��_remove_writerr�r�Z_maybe_resume_protocolr�r�r�)rrrFrrrr�s*


z$_UnixWritePipeTransport._write_readycCsdSr�rr�rrr�
can_write_eof�sz%_UnixWritePipeTransport.can_write_eofcCs8|jr
dSd|_|js4|j�|j�|j�|jd�dSr�)r�r�r�r�r�r�r�r�rrr�	write_eof�sz!_UnixWritePipeTransport.write_eofcCs
||_dSrr�r�rrrr��sz$_UnixWritePipeTransport.set_protocolcCs|jSrr�r�rrrr��sz$_UnixWritePipeTransport.get_protocolcCs|jSrr�r�rrrr��sz"_UnixWritePipeTransport.is_closingcCs|jdk	r|js|��dSr)r�r�rr�rrrr%�sz_UnixWritePipeTransport.closecCs,|jdk	r(|d|��t|d�|j��dSr�r�r�rrrr��s
z_UnixWritePipeTransport.__del__cCs|�d�dSr)r�r�rrr�abort�sz_UnixWritePipeTransport.abortr�cCsNt|t�r(|j��r@tjd||dd�n|j�||||jd��|�|�dSr�)	rOr=r�r�r
r�r�r�r�r�rrrr��s

�z$_UnixWritePipeTransport._fatal_errorcCsFd|_|jr|j�|j�|j��|j�|j�|j�|j|�dSr�)	r�r�r�rr�r-r�r�r�r�rrrr��s
z_UnixWritePipeTransport._closecCs4z|j�|�W5|j��d|_d|_d|_XdSrr�r�rrrr��s
z-_UnixWritePipeTransport._call_connection_lost)NN)r�)N)r�r�r�rr�r�r�rrrrr�r�r�r%r*r+r�rr�r�r�r�rrr!rrY<s"%	#	

rYc@seZdZdd�ZdS)r^c		Ks�d}|tjkrt��\}}zPtj|f||||d|d�|��|_|dk	rh|��t|��d|d�|j_	d}W5|dk	r�|��|��XdS)NF)rdrerfrgZuniversal_newlinesrh�wb)�	buffering)
�
subprocess�PIPEryZ
socketpairr%�Popen�_procr��detachre)	rrErdrerfrgrhriZstdin_wrrr�_starts.
���z_UnixSubprocessTransport._startN)r�r�r�rrrrrr^	sr^c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)rcGs
t��dSr��NotImplementedError�rrnrDrErrrr_9s	z&AbstractChildWatcher.add_child_handlercCs
t��dSrr�rrnrrr�remove_child_handlerDsz)AbstractChildWatcher.remove_child_handlercCs
t��dSrr�rr�rrr�attach_loopLsz AbstractChildWatcher.attach_loopcCs
t��dSrrr�rrrr%VszAbstractChildWatcher.closecCs
t��dSrrr�rrrr\]szAbstractChildWatcher.is_activecCs
t��dSrrr�rrr�	__enter__fszAbstractChildWatcher.__enter__cCs
t��dSrr�r�a�b�crrr�__exit__lszAbstractChildWatcher.__exit__N)
r�r�r�r_rrr%r\rrrrrrr"s
	rcCs2t�|�rt�|�St�|�r*t�|�S|SdSr)rw�WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS)�statusrrr�_compute_returncodeqs



r#c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�BaseChildWatchercCsd|_i|_dSr)r��
_callbacksr�rrrr�szBaseChildWatcher.__init__cCs|�d�dSr)rr�rrrr%�szBaseChildWatcher.closecCs|jdk	o|j��Sr)r�Z
is_runningr�rrrr\�szBaseChildWatcher.is_activecCs
t��dSrr)r�expected_pidrrr�_do_waitpid�szBaseChildWatcher._do_waitpidcCs
t��dSrrr�rrr�_do_waitpid_all�sz BaseChildWatcher._do_waitpid_allcCsf|jdk	r$|dkr$|jr$t�dt�|jdk	r<|j�tj�||_|dk	rb|�tj|j	�|�
�dS)NzCA loop is being detached from a child watcher with pending handlers)r�r%r*r+�RuntimeWarningr)r9�SIGCHLDrH�	_sig_chldr(rrrrr�s�
zBaseChildWatcher.attach_loopc
Cs^z|��WnLttfk
r&�Yn4tk
rX}z|j�d|d��W5d}~XYnXdS)N�$Unknown exception in SIGCHLD handler)r�r�)r(rarbrcr�r�r�rrrr+�s�zBaseChildWatcher._sig_chldN)
r�r�r�rr%r\r'r(rr+rrrrr$sr$csLeZdZ�fdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	�Z
S)rcs|j��t���dSr)r%r-rr%r�r!rrr%�s
zSafeChildWatcher.closecCs|Srrr�rrrr�szSafeChildWatcher.__enter__cCsdSrrrrrrr�szSafeChildWatcher.__exit__cGs||f|j|<|�|�dSr)r%r'rrrrr_�sz"SafeChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdS�NTF�r%rJrrrrr�s
z%SafeChildWatcher.remove_child_handlercCst|j�D]}|�|�q
dSr�r(r%r'rrrrr(�sz SafeChildWatcher._do_waitpid_allcCs�zt�|tj�\}}Wn(tk
r>|}d}t�d|�Yn.X|dkrLdSt|�}|j��rlt�	d||�z|j
�|�\}}Wn.tk
r�|j��r�tjd|dd�YnX|||f|��dS)N��8Unknown child process pid %d, will report returncode 255r�$process %s exited with returncode %s�'Child watcher got an unexpected pid: %rTr�)
rw�waitpid�WNOHANG�ChildProcessErrorr
rr#r�r�r�r%�poprJ)rr&rnr"rorDrErrrr'�s4�

�
�zSafeChildWatcher._do_waitpid)r�r�r�r%rrr_rr(r'r�rrr!rr�srcsPeZdZ�fdd�Z�fdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	�Z
S)rcs$t���t��|_i|_d|_dSr�)rr�	threadingZLock�_lock�_zombies�_forksr�r!rrrs

zFastChildWatcher.__init__cs"|j��|j��t���dSr)r%r-r:rr%r�r!rrr%s

zFastChildWatcher.closec
Cs0|j� |jd7_|W5QR�SQRXdS)Nr)r9r;r�rrrrszFastChildWatcher.__enter__c	Cs^|j�B|jd8_|js"|js0W5QR�dSt|j�}|j��W5QRXt�d|�dS)Nrz5Caught subprocesses termination from unknown pids: %s)r9r;r:r?r-r
r)rrrrZcollateral_victimsrrrrs
�zFastChildWatcher.__exit__c	Gsf|j�Fz|j�|�}Wn.tk
rF||f|j|<YW5QR�dSXW5QRX|||f|��dSr)r9r:r7rJr%)rrnrDrErorrrr_'sz"FastChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdSr-r.rrrrr5s
z%FastChildWatcher.remove_child_handlerc	Cs�zt�dtj�\}}Wntk
r,YdSX|dkr:dSt|�}|j��z|j�|�\}}WnNtk
r�|j	r�||j
|<|j��r�t
�d||�YW5QR�qd}YnX|j��r�t
�d||�W5QRX|dkr�t
�d||�q|||f|��qdS)Nr3rz,unknown process %s exited with returncode %sr2z8Caught subprocess termination from unknown pid: %d -> %d)rwr4r5r6r#r9r%r7rJr;r:r�r�r
r�r)rrnr"rorDrErrrr(<s@

�

��z FastChildWatcher._do_waitpid_all)r�r�r�rr%rrr_rr(r�rrr!rr�s
rc@sdeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dS)rcCsi|_d|_dSr)r%�_saved_sighandlerr�rrrrzszMultiLoopChildWatcher.__init__cCs
|jdk	Sr)r<r�rrrr\~szMultiLoopChildWatcher.is_activecCsT|j��|jdkrdSt�tj�}||jkr:t�d�nt�tj|j�d|_dS)Nz+SIGCHLD handler was changed by outside code)	r%r-r<r9�	getsignalr*r+r
r)rrNrrrr%�s


zMultiLoopChildWatcher.closecCs|Srrr�rrrr�szMultiLoopChildWatcher.__enter__cCsdSrr�r�exc_typeZexc_valZexc_tbrrrr�szMultiLoopChildWatcher.__exit__cGs&t��}|||f|j|<|�|�dSr)r�get_running_loopr%r')rrnrDrEr�rrrr_�sz'MultiLoopChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdSr-r.rrrrr�s
z*MultiLoopChildWatcher.remove_child_handlercCsN|jdk	rdSt�tj|j�|_|jdkr<t�d�tj|_t�tjd�dS)NzaPrevious SIGCHLD handler was set by non-Python code, restore to default handler on watcher close.F)r<r9r*r+r
rrMr@rrrrr�s


z!MultiLoopChildWatcher.attach_loopcCst|j�D]}|�|�q
dSrr/rrrrr(�sz%MultiLoopChildWatcher._do_waitpid_allc	Cs�zt�|tj�\}}Wn,tk
rB|}d}t�d|�d}YnX|dkrPdSt|�}d}z|j�|�\}}}Wn$t	k
r�tjd|dd�YnHX|�
�r�t�d||�n.|r�|��r�t�d	||�|j
|||f|��dS)
Nr0r1FrTr3r��%Loop %r that handles pid %r is closedr2)rwr4r5r6r
rr#r%r7rJ�	is_closedr�r�rm)	rr&rnr"roZ	debug_logr�rDrErrrr'�s:�
��z!MultiLoopChildWatcher._do_waitpidc	CsLz|��Wn:ttfk
r&�Yn"tk
rFtjddd�YnXdS)Nr,Tr�)r(rarbrcr
r)rrrrrrr+�szMultiLoopChildWatcher._sig_chldN)r�r�r�rr\r%rrr_rrr(r'r+rrrrrgs%rc@sjeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Ze	j
fd
d�Zdd�Zdd�Z
dd�Zdd�ZdS)rcCst�d�|_i|_dSr�)�	itertoolsr��_pid_counter�_threadsr�rrrr�szThreadedChildWatcher.__init__cCsdSr�rr�rrrr\�szThreadedChildWatcher.is_activecCs|��dSr)�
_join_threadsr�rrrr%�szThreadedChildWatcher.closecCs.dd�t|j���D�}|D]}|��qdS)NcSsg|]}|��r|js|�qSr)�is_alive�daemon��.0�threadrrr�
<listcomp>�s�z6ThreadedChildWatcher._join_threads.<locals>.<listcomp>)r(rE�valuesr�)r�threadsrKrrrrF�sz"ThreadedChildWatcher._join_threadscCs|Srrr�rrrrszThreadedChildWatcher.__enter__cCsdSrrr>rrrrszThreadedChildWatcher.__exit__cCs6dd�t|j���D�}|r2||j�d�t|d�dS)NcSsg|]}|��r|�qSr)rGrIrrrrL	s�z0ThreadedChildWatcher.__del__.<locals>.<listcomp>z0 has registered but not finished child processesr#)r(rErMr"r,)rr�rNrrrr�s�zThreadedChildWatcher.__del__cGsFt��}tj|jdt|j���||||fdd�}||j|<|��dS)Nzwaitpid-T)�target�namerErH)	rr@r8ZThreadr'�nextrDrE�start)rrnrDrEr�rKrrrr_s
�
z&ThreadedChildWatcher.add_child_handlercCsdSr�rrrrrrsz)ThreadedChildWatcher.remove_child_handlercCsdSrrrrrrrsz ThreadedChildWatcher.attach_loopcCs�zt�|d�\}}Wn(tk
r<|}d}t�d|�Yn Xt|�}|��r\t�d||�|��rtt�d||�n|j	|||f|��|j
�|�dS)Nrr0r1r2rA)rwr4r6r
rr#r�r�rBrmrEr7)rr�r&rDrErnr"rorrrr'"s&�
�z ThreadedChildWatcher._do_waitpidN)r�r�r�rr\r%rFrrr*r+r�r_rrr'rrrrr�s
	rcsDeZdZeZ�fdd�Zdd�Z�fdd�Zdd�Zd	d
�Z	�Z
S)�_UnixDefaultEventLoopPolicycst���d|_dSr)rr�_watcherr�r!rrrAs
z$_UnixDefaultEventLoopPolicy.__init__c	CsHtj�8|jdkr:t�|_tt��tj�r:|j�|j	j
�W5QRXdSr)rr9rTrrOr8�current_thread�_MainThreadr�_localr�r�rrr�
_init_watcherEs
�z)_UnixDefaultEventLoopPolicy._init_watchercs6t��|�|jdk	r2tt��tj�r2|j�|�dSr)r�set_event_looprTrOr8rUrVrrr!rrrYMs

�z*_UnixDefaultEventLoopPolicy.set_event_loopcCs|jdkr|��|jSr)rTrXr�rrrr[[s
z-_UnixDefaultEventLoopPolicy.get_child_watchercCs|jdk	r|j��||_dSr)rTr%)rrjrrr�set_child_watcheres

z-_UnixDefaultEventLoopPolicy.set_child_watcher)r�r�r�rZ
_loop_factoryrrXrYr[rZr�rrr!rrS=s
rS)1rBr�rCrwr�r9ryr�rr&r8r*�rrrrrrr	r
rr�logr
�__all__r��ImportErrorrZBaseSelectorEventLooprZ
ReadTransportrRZ_FlowControlMixinZWriteTransportrYZBaseSubprocessTransportr^rr#r$rrrrZBaseDefaultEventLoopPolicyrSrrrrrr�<module>s^	
	�NO5Ji}Y3PK [���b�s�s*__pycache__/selector_events.cpython-38.pycnu�[���U

e5dT��@s.dZdZddlZddlZddlZddlZddlZddlZddlZzddl	Z	Wne
k
rddZ	YnXddlmZddlm
Z
ddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZdd�Zdd�ZGdd�dej�ZGdd�dejej�ZGdd�de�ZGdd�de�ZdS)z�Event loop using a selector and related classes.

A selector is a "notify-when-ready" multiplexer.  For a subclass which
also includes support for signal handling, see the unix_events sub-module.
)�BaseSelectorEventLoop�N�)�base_events)�	constants)�events)�futures)�	protocols)�sslproto)�
transports)�trsock)�loggercCs8z|�|�}Wntk
r$YdSXt|j|@�SdS�NF)�get_key�KeyError�boolr)�selector�fdZevent�key�r�//usr/lib64/python3.8/asyncio/selector_events.py�_test_selector_event s
rcCs tdk	rt|tj�rtd��dS)Nz"Socket cannot be of type SSLSocket)�ssl�
isinstanceZ	SSLSocket�	TypeError)�sockrrr�_check_ssl_socket+srcs�eZdZdZdS�fdd�	ZdTddd�dd�ZdUddddejd	�d
d�ZdVdd
�Z	�fdd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdddejfdd�Zdddejfdd�Zddejfdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd9d:�Zd;d<�Z d=d>�Z!d?d@�Z"dAdB�Z#dCdD�Z$dEdF�Z%dGdH�Z&dIdJ�Z'dKdL�Z(dMdN�Z)dOdP�Z*dQdR�Z+�Z,S)WrzJSelector event loop.

    See events.EventLoop for API specification.
    NcsFt���|dkrt��}t�d|jj�||_|�	�t
��|_dS)NzUsing selector: %s)
�super�__init__�	selectorsZDefaultSelectorr�debug�	__class__�__name__�	_selector�_make_self_pipe�weakrefZWeakValueDictionary�_transports)�selfr�r rrr6s
zBaseSelectorEventLoop.__init__��extra�servercCst||||||�S�N)�_SelectorSocketTransport)r&r�protocol�waiterr)r*rrr�_make_socket_transport@s
�z,BaseSelectorEventLoop._make_socket_transportF)�server_side�server_hostnamer)r*�ssl_handshake_timeoutc	Cs0tj|||||||	d�}
t|||
||d�|
jS)N)r2r()r	ZSSLProtocolr,Z_app_transport)r&Zrawsockr-�
sslcontextr.r0r1r)r*r2Zssl_protocolrrr�_make_ssl_transportEs��z)BaseSelectorEventLoop._make_ssl_transportcCst||||||�Sr+)�_SelectorDatagramTransport)r&rr-�addressr.r)rrr�_make_datagram_transportRs
�z.BaseSelectorEventLoop._make_datagram_transportcsL|��rtd��|��rdS|��t���|jdk	rH|j��d|_dS)Nz!Cannot close a running event loop)Z
is_running�RuntimeError�	is_closed�_close_self_piper�closer"�r&r'rrr;Ws


zBaseSelectorEventLoop.closecCsB|�|j���|j��d|_|j��d|_|jd8_dS)Nr)�_remove_reader�_ssock�filenor;�_csock�
_internal_fdsr<rrrr:bs

z&BaseSelectorEventLoop._close_self_pipecCsNt��\|_|_|j�d�|j�d�|jd7_|�|j��|j�dS)NFr)	�socketZ
socketpairr>r@�setblockingrA�_add_readerr?�_read_from_selfr<rrrr#js
z%BaseSelectorEventLoop._make_self_pipecCsdSr+r�r&�datarrr�_process_self_datarsz(BaseSelectorEventLoop._process_self_datacCsXz"|j�d�}|sWqT|�|�Wqtk
r:YqYqtk
rPYqTYqXqdS)Ni)r>�recvrH�InterruptedError�BlockingIOErrorrFrrrrEusz%BaseSelectorEventLoop._read_from_selfcCsN|j}|dkrdSz|�d�Wn(tk
rH|jrDtjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketT��exc_info)r@�send�OSError�_debugrr)r&Zcsockrrr�_write_to_self�s�z$BaseSelectorEventLoop._write_to_self�dc
Cs"|�|��|j||||||�dSr+)rDr?�_accept_connection)r&�protocol_factoryrr3r*�backlogr2rrr�_start_serving�s�z$BaseSelectorEventLoop._start_servingc
Cst|�D]�}z0|��\}}	|jr0t�d||	|�|�d�Wn�tttfk
rZYdSt	k
r�}
zd|
j
t
jt
jt
j
t
jfkr�|�d|
t�|�d��|�|���|�tj|j||||||�n�W5d}
~
XYqXd|	i}|�||||||�}|�|�qdS)Nz#%r got a new connection from %r: %rFz&socket.accept() out of system resource)�message�	exceptionrB�peername)�range�acceptrQrrrCrKrJ�ConnectionAbortedErrorrP�errnoZEMFILEZENFILEZENOBUFSZENOMEM�call_exception_handlerr�TransportSocketr=r?Z
call_laterrZACCEPT_RETRY_DELAYrW�_accept_connection2Zcreate_task)
r&rUrr3r*rVr2�_�conn�addr�excr)r\rrrrT�sV�����z(BaseSelectorEventLoop._accept_connectionc
�s�d}d}zt|�}|��}	|r8|j||||	d|||d�}n|j|||	||d�}z|	IdHWntk
rx|���YnXWntttfk
r��Yn\tk
r�}
z>|jr�d|
d�}|dk	r�||d<|dk	r�||d<|�|�W5d}
~
XYnXdS)NT)r.r0r)r*r2)r.r)r*z3Error on transport creation for incoming connection)rXrYr-�	transport)	�
create_futurer4r/�
BaseExceptionr;�
SystemExit�KeyboardInterruptrQr_)r&rUrcr)r3r*r2r-rfr.re�contextrrrra�sP���z)BaseSelectorEventLoop._accept_connection2c
Cs�|}t|t�sJzt|���}Wn*tttfk
rHtd|���d�YnXz|j|}Wntk
rlYnX|��s�t	d|�d|����dS)NzInvalid file object: zFile descriptor z is used by transport )
r�intr?�AttributeErrorr�
ValueErrorr%r�
is_closingr8)r&rr?rfrrr�_ensure_fd_no_transport�s
�z-BaseSelectorEventLoop._ensure_fd_no_transportc		Gs�|��t�|||d�}z|j�|�}Wn*tk
rR|j�|tj|df�Yn>X|j|j	}\}}|j�
||tjB||f�|dk	r�|��dSr+)�
_check_closedr�Handler"rr�registerr�
EVENT_READrG�modify�cancel�	r&r�callback�argsZhandler�mask�reader�writerrrrrDs�
�z!BaseSelectorEventLoop._add_readercCs�|��rdSz|j�|�}Wntk
r2YdSX|j|j}\}}|tjM}|sd|j�|�n|j�	||d|f�|dk	r�|�
�dSdSdS�NFT)r9r"rrrrGrrt�
unregisterrurv�r&rrrzr{r|rrrr=sz$BaseSelectorEventLoop._remove_readerc		Gs�|��t�|||d�}z|j�|�}Wn*tk
rR|j�|tjd|f�Yn>X|j|j	}\}}|j�
||tjB||f�|dk	r�|��dSr+)rqrrrr"rrrsr�EVENT_WRITErGrurvrwrrr�_add_writer%s�
�z!BaseSelectorEventLoop._add_writercCs�|��rdSz|j�|�}Wntk
r2YdSX|j|j}\}}|tjM}|sd|j�|�n|j�	|||df�|dk	r�|�
�dSdSdS)�Remove a writer callback.FNT)r9r"rrrrGrr�r~rurvrrrr�_remove_writer4sz$BaseSelectorEventLoop._remove_writercGs|�|�|j||f|��S)zAdd a reader callback.)rprD�r&rrxryrrr�
add_readerKs
z BaseSelectorEventLoop.add_readercCs|�|�|�|�S)zRemove a reader callback.)rpr=�r&rrrr�
remove_readerPs
z#BaseSelectorEventLoop.remove_readercGs|�|�|j||f|��S)zAdd a writer callback..)rpr�r�rrr�
add_writerUs
z BaseSelectorEventLoop.add_writercCs|�|�|�|�S)r�)rpr�r�rrr�
remove_writerZs
z#BaseSelectorEventLoop.remove_writerc	�s�t|�|jr"|��dkr"td��z|�|�WSttfk
rFYnX|��}|��}|�	||j
|||�|�t�
|j|��|IdHS)z�Receive data from the socket.

        The return value is a bytes object representing the data received.
        The maximum amount of data to be received at once is specified by
        nbytes.
        r�the socket must be non-blockingN)rrQ�
gettimeoutrnrIrKrJrgr?r��
_sock_recv�add_done_callback�	functools�partial�_sock_read_done)r&r�n�futrrrr�	sock_recv_s�zBaseSelectorEventLoop.sock_recvcCs|�|�dSr+)r��r&rr�rrrr�tsz%BaseSelectorEventLoop._sock_read_donec
Cs�|��rdSz|�|�}Wn\ttfk
r4YdSttfk
rL�Yn6tk
rv}z|�|�W5d}~XYnX|�|�dSr+)	�donerIrKrJrirjrh�
set_exception�
set_result)r&r�rr�rGrerrrr�wsz BaseSelectorEventLoop._sock_recvc	�s�t|�|jr"|��dkr"td��z|�|�WSttfk
rFYnX|��}|��}|�	||j
|||�|�t�
|j|��|IdHS)z�Receive data from the socket.

        The received data is written into *buf* (a writable buffer).
        The return value is the number of bytes written.
        rr�N)rrQr�rn�	recv_intorKrJrgr?r��_sock_recv_intor�r�r�r�)r&r�bufr�rrrr�sock_recv_into�s�z$BaseSelectorEventLoop.sock_recv_intoc
Cs�|��rdSz|�|�}Wn\ttfk
r4YdSttfk
rL�Yn6tk
rv}z|�|�W5d}~XYnX|�|�dSr+)	r�r�rKrJrirjrhr�r�)r&r�rr��nbytesrerrrr��sz%BaseSelectorEventLoop._sock_recv_intoc	�s�t|�|jr"|��dkr"td��z|�|�}Wnttfk
rLd}YnX|t|�kr^dS|��}|�	�}|�
t�|j
|��|�||j||t|�|g�|IdHS)a�Send data to the socket.

        The socket must be connected to a remote socket. This method continues
        to send data from data until either all data has been sent or an
        error occurs. None is returned on success. On error, an exception is
        raised, and there is no way to determine how much data, if any, was
        successfully processed by the receiving end of the connection.
        rr�N)rrQr�rnrOrKrJ�lenrgr?r�r�r��_sock_write_doner��
_sock_sendall�
memoryview)r&rrGr�r�rrrr�sock_sendall�s&	
��z"BaseSelectorEventLoop.sock_sendallc
Cs�|��rdS|d}z|�||d��}Wnbttfk
rDYdSttfk
r\�Yn2tk
r�}z|�|�WY�dSd}~XYnX||7}|t|�kr�|�	d�n||d<dS)Nr)
r�rOrKrJrirjrhr�r�r�)r&r�rZview�pos�startr�rerrrr��s 
z#BaseSelectorEventLoop._sock_sendallc�s�t|�|jr"|��dkr"td��ttd�r8|jtjkrf|j||j|j	|d�IdH}|d\}}}}}|�
�}|�|||�|IdHS)zTConnect to a remote socket at address.

        This method is a coroutine.
        rr��AF_UNIX)�family�proto�loopN)rrQr�rn�hasattrrBr�r�Z_ensure_resolvedr�rg�
_sock_connect)r&rr6Zresolvedrbr�rrr�sock_connect�s�z"BaseSelectorEventLoop.sock_connectc
Cs�|��}z|�|�Wn�ttfk
rV|�t�|j|��|�||j	|||�YnNt
tfk
rn�Yn6tk
r�}z|�
|�W5d}~XYnX|�d�dSr+)r?ZconnectrKrJr�r�r�r�r��_sock_connect_cbrirjrhr�r�)r&r�rr6rrerrrr��s�z#BaseSelectorEventLoop._sock_connectcCs|�|�dSr+)r�r�rrrr�sz&BaseSelectorEventLoop._sock_write_donec
Cs�|��rdSz,|�tjtj�}|dkr6t|d|����WnZttfk
rPYnNtt	fk
rh�Yn6t
k
r�}z|�|�W5d}~XYnX|�d�dS)NrzConnect call failed )
r�Z
getsockoptrBZ
SOL_SOCKETZSO_ERRORrPrKrJrirjrhr�r�)r&r�rr6�errrerrrr�sz&BaseSelectorEventLoop._sock_connect_cbc�sBt|�|jr"|��dkr"td��|��}|�|d|�|IdHS)aWAccept a connection.

        The socket must be bound to an address and listening for connections.
        The return value is a pair (conn, address) where conn is a new socket
        object usable to send and receive data on the connection, and address
        is the address bound to the socket on the other end of the connection.
        rr�FN)rrQr�rnrg�_sock_accept)r&rr�rrr�sock_acceptsz!BaseSelectorEventLoop.sock_acceptc
Cs�|��}|r|�|�|��r"dSz|��\}}|�d�Wnnttfk
rh|�||j|d|�YnRt	t
fk
r��Yn:tk
r�}z|�|�W5d}~XYnX|�
||f�dSr})r?r�r�r\rCrKrJr�r�rirjrhr�r�)r&r�Z
registeredrrrcr6rerrrr�*s
z"BaseSelectorEventLoop._sock_acceptc	�sp|j|j=|��}|��|��IdHz |j|j|||dd�IdHW�S|��|r^|��||j|j<XdS)NF)Zfallback)	r%�_sock_fd�
is_reading�
pause_reading�_make_empty_waiter�_reset_empty_waiter�resume_readingZ
sock_sendfile�_sock)r&Ztransp�file�offset�countr�rrr�_sendfile_native<s
�z&BaseSelectorEventLoop._sendfile_nativecCs�|D]v\}}|j|j}\}}|tj@rL|dk	rL|jrB|�|�n
|�|�|tj@r|dk	r|jrp|�|�q|�|�qdSr+)	�fileobjrGrrtZ
_cancelledr=Z
_add_callbackr�r�)r&Z
event_listrrzr�r{r|rrr�_process_eventsJs
z%BaseSelectorEventLoop._process_eventscCs|�|���|��dSr+)r=r?r;)r&rrrr�
_stop_servingXsz#BaseSelectorEventLoop._stop_serving)N)N)N)NNN)-r!�
__module__�__qualname__�__doc__rr/rZSSL_HANDSHAKE_TIMEOUTr4r7r;r:r#rHrErRrWrTrarprDr=r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��
__classcell__rrr'rr0s~
����
�
	�
.�
)rcs�eZdZdZeZdZd�fdd�	Zdd�Zdd�Z	d	d
�Z
dd�Zd
d�Zdd�Z
ejfdd�Zddd�Zdd�Zdd�Zdd�Zdd�Z�ZS) �_SelectorTransportiNcs�t��||�t�|�|jd<z|��|jd<Wntk
rNd|jd<YnXd|jkr�z|��|jd<Wn tj	k
r�d|jd<YnX||_
|��|_d|_
|�|�||_|��|_d|_d|_|jdk	r�|j��||j|j<dS)NrBZsocknamerZFr)rrrr`�_extraZgetsocknamerPZgetpeernamerB�errorr�r?r��_protocol_connected�set_protocol�_server�_buffer_factory�_buffer�
_conn_lost�_closingZ_attachr%)r&r�rr-r)r*r'rrris,





z_SelectorTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���|jdk	r�|j��s�t|jj	|jt
j�}|rz|�d�n
|�d�t|jj	|jt
j�}|r�d}nd}|�
�}|�d|�d	|�d
��d�d�|��S)
N�closed�closingzfd=zread=pollingz	read=idle�pollingZidlezwrite=<z
, bufsize=�>z<{}>� )r r!r��appendr�r��_loopr9rr"rrtr��get_write_buffer_size�format�join)r&�infor��state�bufsizerrr�__repr__�s0


�
�z_SelectorTransport.__repr__cCs|�d�dSr+)�_force_closer<rrr�abort�sz_SelectorTransport.abortcCs||_d|_dS�NT)�	_protocolr��r&r-rrrr��sz_SelectorTransport.set_protocolcCs|jSr+)r�r<rrr�get_protocol�sz_SelectorTransport.get_protocolcCs|jSr+)r�r<rrrro�sz_SelectorTransport.is_closingcCsT|jr
dSd|_|j�|j�|jsP|jd7_|j�|j�|j�|jd�dS�NTr)	r�r�r=r�r�r�r��	call_soon�_call_connection_lostr<rrrr;�sz_SelectorTransport.closecCs,|jdk	r(|d|��t|d�|j��dS)Nzunclosed transport )�source)r��ResourceWarningr;)r&Z_warnrrr�__del__�s
z_SelectorTransport.__del__�Fatal error on transportcCsNt|t�r(|j��r@tjd||dd�n|j�||||jd��|�|�dS)Nz%r: %sTrM)rXrYrfr-)	rrPr��	get_debugrrr_r�r�)r&rerXrrr�_fatal_error�s

�z_SelectorTransport._fatal_errorcCsd|jr
dS|jr(|j��|j�|j�|jsBd|_|j�|j�|jd7_|j�|j	|�dSr�)
r�r��clearr�r�r�r�r=r�r��r&rerrrr��s
z_SelectorTransport._force_closecCsVz|jr|j�|�W5|j��d|_d|_d|_|j}|dk	rP|��d|_XdSr+)r�r;r�r�r�Z_detachr�Zconnection_lost)r&rer*rrrr��s
z(_SelectorTransport._call_connection_lostcCs
t|j�Sr+)r�r�r<rrrr��sz(_SelectorTransport.get_write_buffer_sizecGs"|jr
dS|jj||f|��dSr+)r�r�rDr�rrrrD�sz_SelectorTransport._add_reader)NN)r�)r!r�r��max_size�	bytearrayr�r�rr�r�r�r�ror;�warnings�warnr�r�r�r�r�rDr�rrr'rr�]s 

r�cs�eZdZdZejjZd#�fdd�	Z�fdd�Z	dd�Z
d	d
�Zdd�Zd
d�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Z�fdd�Zdd �Zd!d"�Z�ZS)$r,TNcs~d|_t��|||||�d|_d|_d|_t�|j�|j	�
|jj|�|j	�
|j
|j|j�|dk	rz|j	�
tj|d�dSr
)�_read_ready_cbrr�_eof�_paused�
_empty_waiterrZ_set_nodelayr�r�r�r��connection_maderDr��_read_readyr�_set_result_unless_cancelled)r&r�rr-r.r)r*r'rrr�s 
�
�z!_SelectorSocketTransport.__init__cs.t|tj�r|j|_n|j|_t��|�dSr+)rrZBufferedProtocol�_read_ready__get_bufferr��_read_ready__data_receivedrr�r�r'rrr�	s
z%_SelectorSocketTransport.set_protocolcCs|jo|jSr+)r�r�r<rrrr�sz#_SelectorSocketTransport.is_readingcCs>|js|jrdSd|_|j�|j�|j��r:t�d|�dS)NTz%r pauses reading)r�r�r�r=r�r�rrr<rrrr�s
z&_SelectorSocketTransport.pause_readingcCs@|js|jsdSd|_|�|j|j�|j��r<t�d|�dS)NFz%r resumes reading)	r�r�rDr�r�r�r�rrr<rrrr�s
z'_SelectorSocketTransport.resume_readingcCs|��dSr+)r�r<rrrr�$sz$_SelectorSocketTransport._read_readyc
Cs`|jr
dSz |j�d�}t|�s(td��WnLttfk
rD�Yn4tk
rv}z|�|d�WY�dSd}~XYnXz|j	�
|�}Wndttfk
r�YdSttfk
r��Yn4tk
r�}z|�|d�WY�dSd}~XYnX|�s|�
�dSz|j�|�WnJttfk
�r,�Yn0tk
�rZ}z|�|d�W5d}~XYnXdS)N���z%get_buffer() returned an empty bufferz/Fatal error: protocol.get_buffer() call failed.�$Fatal read error on socket transportz3Fatal error: protocol.buffer_updated() call failed.)r�r�Z
get_bufferr�r8rirjrhr�r�r�rKrJ�_read_ready__on_eofZbuffer_updated)r&r�rer�rrrr�'sF��z0_SelectorSocketTransport._read_ready__get_bufferc
Cs�|jr
dSz|j�|j�}Wndttfk
r6YdSttfk
rN�Yn4tk
r�}z|�	|d�WY�dSd}~XYnX|s�|�
�dSz|j�|�WnFttfk
r��Yn.tk
r�}z|�	|d�W5d}~XYnXdS)Nr�z2Fatal error: protocol.data_received() call failed.)
r�r�rIr�rKrJrirjrhr�r�r�Z
data_received)r&rGrerrrr�Ls.�z3_SelectorSocketTransport._read_ready__data_receivedc
Cs�|j��rt�d|�z|j��}WnLttfk
r>�Yn4tk
rp}z|�	|d�WY�dSd}~XYnX|r�|j�
|j�n|��dS)Nz%r received EOFz1Fatal error: protocol.eof_received() call failed.)
r�r�rrr�Zeof_receivedrirjrhr�r=r�r;)r&Z	keep_openrerrrr�es
�z,_SelectorSocketTransport._read_ready__on_eofc
Cs6t|tttf�s$tdt|�j����|jr2td��|j	dk	rDtd��|sLdS|j
rz|j
tjkrht
�d�|j
d7_
dS|j�sz|j�|�}Wnbttfk
r�Ynbttfk
r��YnJtk
r�}z|�|d�WY�dSd}~XYnX||d�}|�sdS|j�|j|j�|j�|�|��dS)N�/data argument must be a bytes-like object, not z%Cannot call write() after write_eof()z(unable to write; sendfile is in progress�socket.send() raised exception.r�%Fatal write error on socket transport)r�bytesr�r�r�typer!r�r8r�r�r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESr�warningr�r�rOrKrJrirjrhr�r�r�r��_write_ready�extend�_maybe_pause_protocol)r&rGr�rerrr�writezs:

z_SelectorSocketTransport.writec
Cs(|jstd��|jrdSz|j�|j�}Wn�ttfk
rBYn�ttfk
rZ�Yn�t	k
r�}z>|j
�|j�|j�
�|�|d�|jdk	r�|j�|�W5d}~XYnpX|r�|jd|�=|��|j�s$|j
�|j�|jdk	r�|j�d�|j�r|�d�n|j�r$|j�tj�dS)NzData should not be emptyr�)r��AssertionErrorr�r�rOrKrJrirjrhr�r�r�r�r�r�r��_maybe_resume_protocolr�r�r�r��shutdownrB�SHUT_WR)r&r�rerrrr�s4


z%_SelectorSocketTransport._write_readycCs.|js|jrdSd|_|js*|j�tj�dSr�)r�r�r�r�rrBrr<rrr�	write_eof�s
z"_SelectorSocketTransport.write_eofcCsdSr�rr<rrr�
can_write_eof�sz&_SelectorSocketTransport.can_write_eofcs*t��|�|jdk	r&|j�td��dS)NzConnection is closed by peer)rr�r�r��ConnectionErrorr�r'rrr��s

�z._SelectorSocketTransport._call_connection_lostcCs6|jdk	rtd��|j��|_|js0|j�d�|jS)NzEmpty waiter is already set)r�r8r�rgr�r�r<rrrr��s
z+_SelectorSocketTransport._make_empty_waitercCs
d|_dSr+)r�r<rrrr��sz,_SelectorSocketTransport._reset_empty_waiter)NNN)r!r�r�Z_start_tls_compatiblerZ
_SendfileModeZ
TRY_NATIVEZ_sendfile_compatiblerr�r�r�r�r�r�r�r�rrr	r
r�r�r�r�rrr'rr,�s*�%'r,csFeZdZejZd�fdd�	Zdd�Zdd�Zd
dd	�Z	d
d�Z
�ZS)r5Ncs^t��||||�||_|j�|jj|�|j�|j|j|j	�|dk	rZ|j�t
j|d�dSr+)rr�_addressr�r�r�r�rDr�r�rr�)r&r�rr-r6r.r)r'rrr�s
�
�z#_SelectorDatagramTransport.__init__cCstdd�|jD��S)Ncss|]\}}t|�VqdSr+)r�)�.0rGrbrrr�	<genexpr>�szC_SelectorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr�r<rrrr��sz0_SelectorDatagramTransport.get_write_buffer_sizec
Cs�|jr
dSz|j�|j�\}}Wn�ttfk
r8Yn�tk
rd}z|j�|�W5d}~XYnTt	t
fk
r|�Yn<tk
r�}z|�|d�W5d}~XYnX|j�
||�dS)Nz&Fatal read error on datagram transport)r�r�Zrecvfromr�rKrJrPr��error_receivedrirjrhr�Zdatagram_received�r&rGrdrerrrr��sz&_SelectorDatagramTransport._read_readyc
Cs�t|tttf�s$tdt|�j����|s,dS|jrV|d|jfkrPtd|j����|j}|j	r�|jr�|j	t
jkrxt�
d�|j	d7_	dS|j�slz,|jdr�|j�|�n|j�||�WdSttfk
r�|j�|j|j�Yn�tk
�r}z|j�|�WY�dSd}~XYnPttfk
�r6�Yn6tk
�rj}z|�|d�WY�dSd}~XYnX|j� t|�|f�|�!�dS)Nr�z!Invalid address: must be None or r�rrZ�'Fatal write error on datagram transport)"rr�r�r�rr�r!rrnr�rr�rrr�r�r�rO�sendtorKrJr�r�r��
_sendto_readyrPr�rrirjrhr�r�rrrrrr�sH
�

�z!_SelectorDatagramTransport.sendtoc
Cs|jr�|j��\}}z*|jdr.|j�|�n|j�||�Wqttfk
rj|j�||f�Yq�Yqt	k
r�}z|j
�|�WY�dSd}~XYqtt
fk
r��Yqtk
r�}z|�|d�WY�dSd}~XYqXq|��|j�s|j�|j�|j�r|�d�dS)NrZr)r��popleftr�r�rOrrKrJ�
appendleftrPr�rrirjrhr�rr�r�r�r�r�rrrrr*s2
�z(_SelectorDatagramTransport._sendto_ready)NNN)N)r!r�r��collections�dequer�rr�r�rrr�rrr'rr5�s�

+r5)r��__all__rr^r�rrBr�r$r�ImportError�rrrrrr	r
r�logrrrZ
BaseEventLooprZ_FlowControlMixinZ	Transportr�r,r5rrrr�<module>sF
1�oPK [9c��_�_/__pycache__/windows_events.cpython-38.opt-1.pycnu�[���U

e5di��@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddlmZd
ZdZdZdZdZdZdZGdd�de
j�ZGdd�de
j�ZGdd�de�ZGdd�de�Z Gdd�de!�Z"Gdd�dej#�Z$Gdd �d ej%�Z&Gd!d"�d"�Z'Gd#d$�d$ej(�Z)e$Z*Gd%d&�d&ej+�Z,Gd'd(�d(ej+�Z-e-Z.dS))z.Selector and proactor event loops for Windows.�N�)�events)�base_subprocess)�futures)�
exceptions)�proactor_events)�selector_events)�tasks)�
windows_utils)�logger)�SelectorEventLoop�ProactorEventLoop�IocpProactor�DefaultEventLoopPolicy�WindowsSelectorEventLoopPolicy�WindowsProactorEventLoopPolicy���i�i�g����MbP?g�������?cs^eZdZdZdd��fdd�
Z�fdd�Zdd	�Z�fd
d�Z�fdd
�Z�fdd�Z	�Z
S)�_OverlappedFuturez�Subclass of Future which represents an overlapped operation.

    Cancelling it will immediately cancel the overlapped operation.
    N��loopcs&t�j|d�|jr|jd=||_dS�Nr���)�super�__init__�_source_traceback�_ov)�self�ovr��	__class__��./usr/lib64/python3.8/asyncio/windows_events.pyr1sz_OverlappedFuture.__init__csHt���}|jdk	rD|jjr dnd}|�dd|�d|jjd�d��|S)N�pendingZ	completedrzoverlapped=<z, �#x�>)r�
_repr_inforr"�insert�address�r�info�staterr r!r%7s


 z_OverlappedFuture._repr_infoc
Csr|jdkrdSz|j��WnJtk
rf}z,d||d�}|jrJ|j|d<|j�|�W5d}~XYnXd|_dS)Nz&Cancelling an overlapped future failed��message�	exception�future�source_traceback)r�cancel�OSErrorr�_loop�call_exception_handler)r�exc�contextr r r!�_cancel_overlapped>s
�
z$_OverlappedFuture._cancel_overlappedcs|��t���S�N)r6rr0�rrr r!r0Nsz_OverlappedFuture.cancelcst��|�|��dSr7)r�
set_exceptionr6�rr-rr r!r9Rsz_OverlappedFuture.set_exceptioncst��|�d|_dSr7)r�
set_resultr�r�resultrr r!r;Vsz_OverlappedFuture.set_result)�__name__�
__module__�__qualname__�__doc__rr%r6r0r9r;�
__classcell__r r rr!r+srcsneZdZdZdd��fdd�
Zdd�Z�fdd	�Zd
d�Zdd
�Z�fdd�Z	�fdd�Z
�fdd�Z�ZS)�_BaseWaitHandleFuturez2Subclass of Future which represents a wait handle.Nrcs8t�j|d�|jr|jd=||_||_||_d|_dS)NrrT)rrrr�_handle�_wait_handle�_registered)rr�handle�wait_handlerrr r!r^sz_BaseWaitHandleFuture.__init__cCst�|jd�tjkS�Nr)�_winapiZWaitForSingleObjectrDZ
WAIT_OBJECT_0r8r r r!�_pollls�z_BaseWaitHandleFuture._pollcsdt���}|�d|jd���|jdk	rB|��r4dnd}|�|�|jdk	r`|�d|jd���|S)Nzhandle=r#ZsignaledZwaitingzwait_handle=)rr%�appendrDrKrEr(rr r!r%qs



z _BaseWaitHandleFuture._repr_infocCs
d|_dSr7)r�r�futr r r!�_unregister_wait_cb{sz)_BaseWaitHandleFuture._unregister_wait_cbc
Cs�|js
dSd|_|j}d|_zt�|�Wn`tk
r�}zB|jtjkrzd||d�}|jrd|j|d<|j�	|�WY�dSW5d}~XYnX|�
d�dS�NFz$Failed to unregister the wait handler+r/)rFrE�_overlappedZUnregisterWaitr1�winerror�ERROR_IO_PENDINGrr2r3rO�rrHr4r5r r r!�_unregister_wait�s$�
z&_BaseWaitHandleFuture._unregister_waitcs|��t���Sr7)rUrr0r8rr r!r0�sz_BaseWaitHandleFuture.cancelcs|��t��|�dSr7)rUrr9r:rr r!r9�sz#_BaseWaitHandleFuture.set_exceptioncs|��t��|�dSr7)rUrr;r<rr r!r;�sz _BaseWaitHandleFuture.set_result)
r>r?r@rArrKr%rOrUr0r9r;rBr r rr!rC[s
rCcsFeZdZdZdd��fdd�
Zdd�Z�fdd	�Z�fd
d�Z�ZS)�_WaitCancelFuturezoSubclass of Future which represents a wait for the cancellation of a
    _WaitHandleFuture using an event.
    Nrcst�j||||d�d|_dS)Nr)rr�_done_callback)rr�eventrHrrr r!r�sz_WaitCancelFuture.__init__cCstd��dS)Nz'_WaitCancelFuture must not be cancelled)�RuntimeErrorr8r r r!r0�sz_WaitCancelFuture.cancelcs$t��|�|jdk	r |�|�dSr7)rr;rWr<rr r!r;�s
z_WaitCancelFuture.set_resultcs$t��|�|jdk	r |�|�dSr7)rr9rWr:rr r!r9�s
z_WaitCancelFuture.set_exception)	r>r?r@rArr0r;r9rBr r rr!rV�s
rVcs6eZdZdd��fdd�
Z�fdd�Zdd�Z�ZS)	�_WaitHandleFutureNrcs<t�j||||d�||_d|_t�dddd�|_d|_dS)NrTF)rr�	_proactorZ_unregister_proactorrQZCreateEvent�_event�
_event_fut)rrrGrH�proactorrrr r!r�s
z_WaitHandleFuture.__init__csF|jdk	r"t�|j�d|_d|_|j�|j�d|_t��|�dSr7)	r\rJ�CloseHandler]r[�_unregisterrrrOrMrr r!rO�s
	z%_WaitHandleFuture._unregister_wait_cbc
Cs�|js
dSd|_|j}d|_zt�||j�Wn`tk
r�}zB|jtjkr~d||d�}|jrh|j|d<|j	�
|�WY�dSW5d}~XYnX|j�|j|j
�|_dSrP)rFrErQZUnregisterWaitExr\r1rRrSrr2r3r[�_wait_cancelrOr]rTr r r!rU�s(�

�z"_WaitHandleFuture._unregister_wait)r>r?r@rrOrUrBr r rr!rZ�srZc@s<eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZeZ	dS)
�
PipeServerzXClass representing a pipe server.

    This is much like a bound, listening socket.
    cCs,||_t��|_d|_d|_|�d�|_dS�NT)�_address�weakref�WeakSet�_free_instances�_pipe�_accept_pipe_future�_server_pipe_handle)rr'r r r!r�s

zPipeServer.__init__cCs|j|�d�}|_|S)NF)rhrj)r�tmpr r r!�_get_unconnected_pipesz PipeServer._get_unconnected_pipec
Csr|��rdStjtjB}|r&|tjO}t�|j|tjtjBtj	Btj
tjtjtj
tj�}t�|�}|j�|�|Sr7)�closedrJZPIPE_ACCESS_DUPLEXZFILE_FLAG_OVERLAPPEDZFILE_FLAG_FIRST_PIPE_INSTANCEZCreateNamedPiperdZPIPE_TYPE_MESSAGEZPIPE_READMODE_MESSAGEZ	PIPE_WAITZPIPE_UNLIMITED_INSTANCESr
ZBUFSIZEZNMPWAIT_WAIT_FOREVER�NULL�
PipeHandlerg�add)r�first�flags�h�piper r r!rjs(

��
zPipeServer._server_pipe_handlecCs
|jdkSr7)rdr8r r r!rmszPipeServer.closedcCsR|jdk	r|j��d|_|jdk	rN|jD]}|��q*d|_d|_|j��dSr7)rir0rdrg�closerh�clear)rrtr r r!rus




zPipeServer.closeN)
r>r?r@rArrlrjrmru�__del__r r r r!rb�s
rbc@seZdZdZdS)�_WindowsSelectorEventLoopz'Windows version of selector event loop.N)r>r?r@rAr r r r!rx,srxcsHeZdZdZd
�fdd�	Z�fdd�Zdd�Zd	d
�Zddd�Z�Z	S)r
z2Windows version of proactor event loop using IOCP.Ncs|dkrt�}t��|�dSr7)rrr)rr^rr r!r3szProactorEventLoop.__init__c	sXz|�|j�t���W5|jdk	rR|jj}|j��|dk	rL|j�|�d|_XdSr7)	Z_self_reading_futurerr0r[r`�	call_soonZ_loop_self_readingr�run_forever�rrrr r!rz8s

zProactorEventLoop.run_foreverc�s8|j�|�}|IdH}|�}|j||d|id�}||fS)N�addr��extra)r[�connect_pipe�_make_duplex_pipe_transport)r�protocol_factoryr'�frt�protocol�transr r r!�create_pipe_connectionKs
�z(ProactorEventLoop.create_pipe_connectionc�s.t���d�����fdd�	������gS)Nc
sd}zn|rN|��}�j�|����r4|��WdS��}�j||d�id����}|dkrdWdS�j�|�}Wn�t	k
r�}zF|r�|�
�dkr���d||d��|��n�jr�t
jd|dd�W5d}~XYn2tjk
r�|r�|��YnX|�_|���dS)	Nr|r}rzPipe accept failed)r,r-rtzAccept pipe failed on pipe %rT)�exc_info)r=rg�discardrmrur�rlr[�accept_piper1�filenor3Z_debugrZwarningr�CancelledErrorri�add_done_callback)r�rtr�r4�r'�loop_accept_piper�rZserverr r!r�VsH��
�z>ProactorEventLoop.start_serving_pipe.<locals>.loop_accept_pipe)N)rbry)rr�r'r r�r!�start_serving_pipeSs(
z$ProactorEventLoop.start_serving_pipec		�s�|��}
t||||||||f|
|d�|	��}z|
IdHWnDttfk
rT�Yn,tk
r~|��|��IdH�YnX|S)N)�waiterr~)�
create_future�_WindowsSubprocessTransport�
SystemExit�KeyboardInterrupt�
BaseExceptionruZ_wait)rr��args�shell�stdin�stdout�stderr�bufsizer~�kwargsr�Ztranspr r r!�_make_subprocess_transport�s*
���z,ProactorEventLoop._make_subprocess_transport)N)N)
r>r?r@rArrzr�r�r�rBr r rr!r
0s0�r
c@s�eZdZdZd;dd�Zdd�Zdd�Zd	d
�Zd<dd
�Zdd�Z	d=dd�Z
d>dd�Zd?dd�Zd@dd�Z
dAdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�ZdBd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�ZdCd3d4�Zd5d6�Zd7d8�Zd9d:�ZdS)Drz#Proactor implementation using IOCP.rcCsDd|_g|_t�tjtd|�|_i|_t�	�|_
g|_t�	�|_dSrI)
r2�_resultsrQ�CreateIoCompletionPort�INVALID_HANDLE_VALUErn�_iocp�_cachererfrF�
_unregistered�_stopped_serving)rZconcurrencyr r r!r�s�
zIocpProactor.__init__cCs|jdkrtd��dS)NzIocpProactor is closed)r�rYr8r r r!�
_check_closed�s
zIocpProactor._check_closedcCsFdt|j�dt|j�g}|jdkr0|�d�d|jjd�|�fS)Nzoverlapped#=%sz
result#=%srmz<%s %s>� )�lenr�r�r�rLrr>�join)rr)r r r!�__repr__�s�

zIocpProactor.__repr__cCs
||_dSr7)r2)rrr r r!�set_loop�szIocpProactor.set_loopNcCs |js|�|�|j}g|_|Sr7)r�rK)r�timeoutrkr r r!�select�s

zIocpProactor.selectcCs|j��}|�|�|Sr7)r2r�r;)r�valuerNr r r!�_result�s

zIocpProactor._resultrcCs~|�|�t�t�}z4t|tj�r6|�|��||�n|�|��|�Wnt	k
rf|�
d�YSXdd�}|�|||�S)N�c
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7��	getresultr1rRrQZERROR_NETNAME_DELETEDZERROR_OPERATION_ABORTED�ConnectionResetErrorr��r��keyrr4r r r!�finish_recv�s
�z&IocpProactor.recv.<locals>.finish_recv)�_register_with_iocprQ�
Overlappedrn�
isinstance�socketZWSARecvr�ZReadFile�BrokenPipeErrorr��	_register�r�conn�nbytesrrrr�r r r!�recv�s


zIocpProactor.recvcCs~|�|�t�t�}z4t|tj�r6|�|��||�n|�|��|�Wnt	k
rf|�
d�YSXdd�}|�|||�S)Nrc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r��s
�z+IocpProactor.recv_into.<locals>.finish_recv)r�rQr�rnr�r�ZWSARecvIntor�ZReadFileIntor�r�r�)rr��bufrrrr�r r r!�	recv_into�s


zIocpProactor.recv_intocCs`|�|�t�t�}z|�|��||�Wntk
rH|�d�YSXdd�}|�|||�S)N)r�Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r��s
�z*IocpProactor.recvfrom.<locals>.finish_recv)	r�rQr�rnZWSARecvFromr�r�r�r�r�r r r!�recvfrom�s


zIocpProactor.recvfromcCs>|�|�t�t�}|�|��|||�dd�}|�|||�S)Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!�finish_sends
�z(IocpProactor.sendto.<locals>.finish_send)r�rQr�rnZ	WSASendTor�r�)rr�r�rrr|rr�r r r!�sendto�s



zIocpProactor.sendtocCsZ|�|�t�t�}t|tj�r4|�|��||�n|�|��|�dd�}|�	|||�S)Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r�s
�z&IocpProactor.send.<locals>.finish_send)
r�rQr�rnr�r�ZWSASendr�Z	WriteFiler�)rr�r�rrrr�r r r!�sends


zIocpProactor.sendcsv|���|��j��t�t�}|����������fdd�}dd�}|�|�|�}||��}t	j
||jd�|S)NcsD|��t�d����}��tjtj|���	��
������fS)Nz@P)r��structZpackr��
setsockoptr��
SOL_SOCKETrQZSO_UPDATE_ACCEPT_CONTEXT�
settimeoutZ
gettimeoutZgetpeername)r�r�rr��r��listenerr r!�
finish_accept*s�z*IocpProactor.accept.<locals>.finish_acceptc�s4z|IdHWn tjk
r.|���YnXdSr7)rr�ru)r.r�r r r!�accept_coro3s
z(IocpProactor.accept.<locals>.accept_coror)r��_get_accept_socket�familyrQr�rnZAcceptExr�r�r	Z
ensure_futurer2)rr�rr�r�r.�coror r�r!�accept$s

	
zIocpProactor.acceptc
s��jtjkr4t����|�|j��}|�d�|S|�	��zt�
����j�WnBtk
r�}z$|j
tjkrt����ddkr��W5d}~XYnXt�t�}|����|��fdd�}|�|�|�S)Nrrcs|����tjtjd��SrI)r�r�r�r�rQZSO_UPDATE_CONNECT_CONTEXT�r�r�r�r�r r!�finish_connectVs�z,IocpProactor.connect.<locals>.finish_connect)�typer�Z
SOCK_DGRAMrQZ
WSAConnectr�r2r�r;r�Z	BindLocalr�r1rR�errnoZ	WSAEINVALZgetsocknamer�rnZ	ConnectExr�)rr�r'rN�err�r r�r!�connect@s"



zIocpProactor.connectc		Csb|�|�t�t�}|d@}|d?d@}|�|��t�|���|||dd�dd�}|�|||�S)Nr� rc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!�finish_sendfileis
�z.IocpProactor.sendfile.<locals>.finish_sendfile)	r�rQr�rnZTransmitFiler��msvcrtZ
get_osfhandler�)	rZsock�file�offset�countrZ
offset_lowZoffset_highr�r r r!�sendfile_s


�	zIocpProactor.sendfilecsJ|���t�t�}|�����}|r0|���S�fdd�}|�|�|�S)Ncs|���Sr7)r�r��rtr r!�finish_accept_pipesz4IocpProactor.accept_pipe.<locals>.finish_accept_pipe)r�rQr�rnZConnectNamedPiper�r�r�)rrtrZ	connectedr�r r�r!r�ts


zIocpProactor.accept_pipec
�srt}zt�|�}WqhWn0tk
rF}z|jtjkr6�W5d}~XYnXt|dt�}t�	|�IdHqt
�|�S)N�)�CONNECT_PIPE_INIT_DELAYrQZConnectPiper1rRZERROR_PIPE_BUSY�min�CONNECT_PIPE_MAX_DELAYr	�sleepr
ro)rr'ZdelayrGr4r r r!r�s
zIocpProactor.connect_pipecCs|�||d�S)z�Wait for a handle.

        Return a Future object. The result of the future is True if the wait
        completed, or False if the wait did not complete (on timeout).
        F)�_wait_for_handle)rrGr�r r r!�wait_for_handle�szIocpProactor.wait_for_handlecCs|�|dd�}||_|Src)r�rW)rrXZ
done_callbackrNr r r!ra�szIocpProactor._wait_cancelcs�|��|dkrtj}nt�|d�}t�t�}t�||j	|j
|�}|r\t||||jd��nt
|||||jd���jr~�jd=�fdd�}�|d|f|j|j
<�S)N�@�@rrcs���Sr7)rKr��r�r r!�finish_wait_for_handle�sz=IocpProactor._wait_for_handle.<locals>.finish_wait_for_handler)r�rJ�INFINITE�math�ceilrQr�rnZRegisterWaitWithQueuer�r'rVr2rZrr�)rrGr�Z
_is_cancel�msrrHr�r r�r!r��s*
�
�	zIocpProactor._wait_for_handlecCs0||jkr,|j�|�t�|��|jdd�dSrI)rFrprQr�r�r��r�objr r r!r��s
z IocpProactor._register_with_iocpc
Cs�|��t||jd�}|jr$|jd=|jsrz|dd|�}Wn,tk
rf}z|�|�W5d}~XYnX|�|�||||f|j|j	<|Sr)
r�rr2rr"r1r9r;r�r')rrr��callbackr�r�r�r r r!r��s

zIocpProactor._registercCs|��|j�|�dS)a
Unregister an overlapped object.

        Call this method when its future has been cancelled. The event can
        already be signalled (pending in the proactor event queue). It is also
        safe if the event is never signalled (because it was cancelled).
        N)r�r�rLr{r r r!r`�szIocpProactor._unregistercCst�|�}|�d�|SrI)r�r�)rr��sr r r!r��s

zIocpProactor._get_accept_socketcCs�|dkrt}n0|dkr td��nt�|d�}|tkr>td��t�|j|�}|dkrX�qZd}|\}}}}z|j�|�\}}	}
}WnXt	k
r�|j
��r�|j
�dd||||fd��|dtj
fkr�t�|�Yq>YnX|
|jkr�|��q>|��s>z||||	�}Wn:tk
�r@}
z|�|
�|j�|�W5d}
~
XYq>X|�|�|j�|�q>|jD]}	|j�|	jd��q`|j��dS)Nrznegative timeoutr�ztimeout too bigz8GetQueuedCompletionStatus() returned an unexpected eventz)err=%s transferred=%s key=%#x address=%#x)r,�status)r��
ValueErrorr�r�rQZGetQueuedCompletionStatusr�r��pop�KeyErrorr2Z	get_debugr3r�rJr_r�r0Zdoner1r9r�rLr;r�r'rv)rr�r�r��errZtransferredr�r'r�rr�r�r�r�r r r!rKsL


��	






zIocpProactor._pollcCs|j�|�dSr7)r�rpr�r r r!�
_stop_serving9szIocpProactor._stop_servingcCs|jdkrdSt|j���D]�\}\}}}}|��r6qt|t�rBqz|��Wqtk
r�}z6|j	dk	r�d||d�}|j
r�|j
|d<|j	�|�W5d}~XYqXqd}t�
�}	|	|}
|jr�|
t�
�kr�t�d|t�
�|	�t�
�|}
|�|�q�g|_t�|j�d|_dS)NzCancelling a future failedr+r/g�?z,%r is running after closing for %.1f seconds)r��listr��itemsZ	cancelledr�rVr0r1r2rr3�time�	monotonicr�debugrKr�rJr_)rr'rNrr�r�r4r5Z
msg_updateZ
start_timeZnext_msgr r r!ru?s@


�
 
�zIocpProactor.closecCs|��dSr7)rur8r r r!rwnszIocpProactor.__del__)r)N)r)r)r)rN)r)N)N)r>r?r@rArr�r�r�r�r�r�r�r�r�r�r�r�r�r�rr�rar�r�r�r`r�rKr�rurwr r r r!r�s8








"
 

7/rc@seZdZdd�ZdS)r�c
sPtj|f|||||d�|���_�fdd�}�jj�t�jj��}	|	�|�dS)N)r�r�r�r�r�cs�j��}��|�dSr7)�_procZpollZ_process_exited)r��
returncoder8r r!r�ys
z4_WindowsSubprocessTransport._start.<locals>.callback)	r
�Popenr�r2r[r��intrDr�)
rr�r�r�r�r�r�r�r�r�r r8r!�_startts���z"_WindowsSubprocessTransport._startN)r>r?r@rr r r r!r�rsr�c@seZdZeZdS)rN)r>r?r@r�
_loop_factoryr r r r!r�src@seZdZeZdS)rN)r>r?r@r
rr r r r!r�sr)/rArQrJr�r�r�r�r�r�re�rrrrrrr	r
�logr�__all__rnr�ZERROR_CONNECTION_REFUSEDZERROR_CONNECTION_ABORTEDr�r�ZFuturerrCrVrZ�objectrbZBaseSelectorEventLooprxZBaseProactorEventLoopr
rZBaseSubprocessTransportr�rZBaseDefaultEventLoopPolicyrrrr r r r!�<module>sR0J4;e`PK [�h���"__pycache__/runners.cpython-38.pycnu�[���U

e5d�@sBdZddlmZddlmZddlmZdd�dd�Zd	d
�ZdS))�run�)�
coroutines)�events)�tasksN)�debugcCs�t��dk	rtd��t�|�s,td�|���t��}z*t�|�|dk	rR|�
|�|�|�W�Szt
|�|�|���W5t�d�|�	�XXdS)a�Execute the coroutine and return the result.

    This function runs the passed coroutine, taking care of
    managing the asyncio event loop and finalizing asynchronous
    generators.

    This function cannot be called when another asyncio event loop is
    running in the same thread.

    If debug is True, the event loop will be run in debug mode.

    This function always creates a new event loop and closes it at the end.
    It should be used as a main entry point for asyncio programs, and should
    ideally only be called once.

    Example:

        async def main():
            await asyncio.sleep(1)
            print('hello')

        asyncio.run(main())
    Nz8asyncio.run() cannot be called from a running event loopz"a coroutine was expected, got {!r})rZ_get_running_loop�RuntimeErrorrZiscoroutine�
ValueError�formatZnew_event_loopZset_event_loop�close�_cancel_all_tasks�run_until_completeZshutdown_asyncgensZ	set_debug)�mainr�loop�r�'/usr/lib64/python3.8/asyncio/runners.pyrs"�



rcCsvt�|�}|sdS|D]}|��q|�tj||dd���|D]0}|��rNq@|��dk	r@|�d|��|d��q@dS)NT)rZreturn_exceptionsz1unhandled exception during asyncio.run() shutdown)�message�	exception�task)rZ	all_tasksZcancelrZgatherZ	cancelledrZcall_exception_handler)rZ	to_cancelrrrrr6s"

��r)�__all__�rrrrrrrrr�<module>s
.PK [l[˅	`	`)__pycache__/windows_events.cpython-38.pycnu�[���U

e5di��@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddlmZd
ZdZdZdZdZdZdZGdd�de
j�ZGdd�de
j�ZGdd�de�ZGdd�de�Z Gdd�de!�Z"Gdd�dej#�Z$Gdd �d ej%�Z&Gd!d"�d"�Z'Gd#d$�d$ej(�Z)e$Z*Gd%d&�d&ej+�Z,Gd'd(�d(ej+�Z-e-Z.dS))z.Selector and proactor event loops for Windows.�N�)�events)�base_subprocess)�futures)�
exceptions)�proactor_events)�selector_events)�tasks)�
windows_utils)�logger)�SelectorEventLoop�ProactorEventLoop�IocpProactor�DefaultEventLoopPolicy�WindowsSelectorEventLoopPolicy�WindowsProactorEventLoopPolicy���i�i�g����MbP?g�������?cs^eZdZdZdd��fdd�
Z�fdd�Zdd	�Z�fd
d�Z�fdd
�Z�fdd�Z	�Z
S)�_OverlappedFuturez�Subclass of Future which represents an overlapped operation.

    Cancelling it will immediately cancel the overlapped operation.
    N��loopcs&t�j|d�|jr|jd=||_dS�Nr���)�super�__init__�_source_traceback�_ov)�self�ovr��	__class__��./usr/lib64/python3.8/asyncio/windows_events.pyr1sz_OverlappedFuture.__init__csHt���}|jdk	rD|jjr dnd}|�dd|�d|jjd�d��|S)N�pendingZ	completedrzoverlapped=<z, �#x�>)r�
_repr_inforr"�insert�address�r�info�staterr r!r%7s


 z_OverlappedFuture._repr_infoc
Csr|jdkrdSz|j��WnJtk
rf}z,d||d�}|jrJ|j|d<|j�|�W5d}~XYnXd|_dS)Nz&Cancelling an overlapped future failed��message�	exception�future�source_traceback)r�cancel�OSErrorr�_loop�call_exception_handler)r�exc�contextr r r!�_cancel_overlapped>s
�
z$_OverlappedFuture._cancel_overlappedcs|��t���S�N)r6rr0�rrr r!r0Nsz_OverlappedFuture.cancelcst��|�|��dSr7)r�
set_exceptionr6�rr-rr r!r9Rsz_OverlappedFuture.set_exceptioncst��|�d|_dSr7)r�
set_resultr�r�resultrr r!r;Vsz_OverlappedFuture.set_result)�__name__�
__module__�__qualname__�__doc__rr%r6r0r9r;�
__classcell__r r rr!r+srcsneZdZdZdd��fdd�
Zdd�Z�fdd	�Zd
d�Zdd
�Z�fdd�Z	�fdd�Z
�fdd�Z�ZS)�_BaseWaitHandleFuturez2Subclass of Future which represents a wait handle.Nrcs8t�j|d�|jr|jd=||_||_||_d|_dS)NrrT)rrrr�_handle�_wait_handle�_registered)rr�handle�wait_handlerrr r!r^sz_BaseWaitHandleFuture.__init__cCst�|jd�tjkS�Nr)�_winapiZWaitForSingleObjectrDZ
WAIT_OBJECT_0r8r r r!�_pollls�z_BaseWaitHandleFuture._pollcsdt���}|�d|jd���|jdk	rB|��r4dnd}|�|�|jdk	r`|�d|jd���|S)Nzhandle=r#ZsignaledZwaitingzwait_handle=)rr%�appendrDrKrEr(rr r!r%qs



z _BaseWaitHandleFuture._repr_infocCs
d|_dSr7)r�r�futr r r!�_unregister_wait_cb{sz)_BaseWaitHandleFuture._unregister_wait_cbc
Cs�|js
dSd|_|j}d|_zt�|�Wn`tk
r�}zB|jtjkrzd||d�}|jrd|j|d<|j�	|�WY�dSW5d}~XYnX|�
d�dS�NFz$Failed to unregister the wait handler+r/)rFrE�_overlappedZUnregisterWaitr1�winerror�ERROR_IO_PENDINGrr2r3rO�rrHr4r5r r r!�_unregister_wait�s$�
z&_BaseWaitHandleFuture._unregister_waitcs|��t���Sr7)rUrr0r8rr r!r0�sz_BaseWaitHandleFuture.cancelcs|��t��|�dSr7)rUrr9r:rr r!r9�sz#_BaseWaitHandleFuture.set_exceptioncs|��t��|�dSr7)rUrr;r<rr r!r;�sz _BaseWaitHandleFuture.set_result)
r>r?r@rArrKr%rOrUr0r9r;rBr r rr!rC[s
rCcsFeZdZdZdd��fdd�
Zdd�Z�fdd	�Z�fd
d�Z�ZS)�_WaitCancelFuturezoSubclass of Future which represents a wait for the cancellation of a
    _WaitHandleFuture using an event.
    Nrcst�j||||d�d|_dS)Nr)rr�_done_callback)rr�eventrHrrr r!r�sz_WaitCancelFuture.__init__cCstd��dS)Nz'_WaitCancelFuture must not be cancelled)�RuntimeErrorr8r r r!r0�sz_WaitCancelFuture.cancelcs$t��|�|jdk	r |�|�dSr7)rr;rWr<rr r!r;�s
z_WaitCancelFuture.set_resultcs$t��|�|jdk	r |�|�dSr7)rr9rWr:rr r!r9�s
z_WaitCancelFuture.set_exception)	r>r?r@rArr0r;r9rBr r rr!rV�s
rVcs6eZdZdd��fdd�
Z�fdd�Zdd�Z�ZS)	�_WaitHandleFutureNrcs<t�j||||d�||_d|_t�dddd�|_d|_dS)NrTF)rr�	_proactorZ_unregister_proactorrQZCreateEvent�_event�
_event_fut)rrrGrH�proactorrrr r!r�s
z_WaitHandleFuture.__init__csF|jdk	r"t�|j�d|_d|_|j�|j�d|_t��|�dSr7)	r\rJ�CloseHandler]r[�_unregisterrrrOrMrr r!rO�s
	z%_WaitHandleFuture._unregister_wait_cbc
Cs�|js
dSd|_|j}d|_zt�||j�Wn`tk
r�}zB|jtjkr~d||d�}|jrh|j|d<|j	�
|�WY�dSW5d}~XYnX|j�|j|j
�|_dSrP)rFrErQZUnregisterWaitExr\r1rRrSrr2r3r[�_wait_cancelrOr]rTr r r!rU�s(�

�z"_WaitHandleFuture._unregister_wait)r>r?r@rrOrUrBr r rr!rZ�srZc@s<eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZeZ	dS)
�
PipeServerzXClass representing a pipe server.

    This is much like a bound, listening socket.
    cCs,||_t��|_d|_d|_|�d�|_dS�NT)�_address�weakref�WeakSet�_free_instances�_pipe�_accept_pipe_future�_server_pipe_handle)rr'r r r!r�s

zPipeServer.__init__cCs|j|�d�}|_|S)NF)rhrj)r�tmpr r r!�_get_unconnected_pipesz PipeServer._get_unconnected_pipec
Csr|��rdStjtjB}|r&|tjO}t�|j|tjtjBtj	Btj
tjtjtj
tj�}t�|�}|j�|�|Sr7)�closedrJZPIPE_ACCESS_DUPLEXZFILE_FLAG_OVERLAPPEDZFILE_FLAG_FIRST_PIPE_INSTANCEZCreateNamedPiperdZPIPE_TYPE_MESSAGEZPIPE_READMODE_MESSAGEZ	PIPE_WAITZPIPE_UNLIMITED_INSTANCESr
ZBUFSIZEZNMPWAIT_WAIT_FOREVER�NULL�
PipeHandlerg�add)r�first�flags�h�piper r r!rjs(

��
zPipeServer._server_pipe_handlecCs
|jdkSr7)rdr8r r r!rmszPipeServer.closedcCsR|jdk	r|j��d|_|jdk	rN|jD]}|��q*d|_d|_|j��dSr7)rir0rdrg�closerh�clear)rrtr r r!rus




zPipeServer.closeN)
r>r?r@rArrlrjrmru�__del__r r r r!rb�s
rbc@seZdZdZdS)�_WindowsSelectorEventLoopz'Windows version of selector event loop.N)r>r?r@rAr r r r!rx,srxcsHeZdZdZd
�fdd�	Z�fdd�Zdd�Zd	d
�Zddd�Z�Z	S)r
z2Windows version of proactor event loop using IOCP.Ncs|dkrt�}t��|�dSr7)rrr)rr^rr r!r3szProactorEventLoop.__init__c	sfz(|jdkst�|�|j�t��	�W5|jdk	r`|jj}|j��|dk	rZ|j�|�d|_XdSr7)
Z_self_reading_futurerr0r[r`�AssertionError�	call_soonZ_loop_self_readingr�run_forever�rrrr r!r{8s

zProactorEventLoop.run_foreverc�s8|j�|�}|IdH}|�}|j||d|id�}||fS)N�addr��extra)r[�connect_pipe�_make_duplex_pipe_transport)r�protocol_factoryr'�frt�protocol�transr r r!�create_pipe_connectionKs
�z(ProactorEventLoop.create_pipe_connectionc�s.t���d�����fdd�	������gS)Nc
sd}zn|rN|��}�j�|����r4|��WdS��}�j||d�id����}|dkrdWdS�j�|�}Wn�t	k
r�}zF|r�|�
�dkr���d||d��|��n�jr�t
jd|dd�W5d}~XYn2tjk
r�|r�|��YnX|�_|���dS)	Nr}r~rzPipe accept failed)r,r-rtzAccept pipe failed on pipe %rT)�exc_info)r=rg�discardrmrur�rlr[�accept_piper1�filenor3Z_debugrZwarningr�CancelledErrorri�add_done_callback)r�rtr�r4�r'�loop_accept_piper�rZserverr r!r�VsH��
�z>ProactorEventLoop.start_serving_pipe.<locals>.loop_accept_pipe)N)rbrz)rr�r'r r�r!�start_serving_pipeSs(
z$ProactorEventLoop.start_serving_pipec		�s�|��}
t||||||||f|
|d�|	��}z|
IdHWnDttfk
rT�Yn,tk
r~|��|��IdH�YnX|S)N)�waiterr)�
create_future�_WindowsSubprocessTransport�
SystemExit�KeyboardInterrupt�
BaseExceptionruZ_wait)rr��args�shell�stdin�stdout�stderr�bufsizer�kwargsr�Ztranspr r r!�_make_subprocess_transport�s*
���z,ProactorEventLoop._make_subprocess_transport)N)N)
r>r?r@rArr{r�r�r�rBr r rr!r
0s0�r
c@s�eZdZdZd;dd�Zdd�Zdd�Zd	d
�Zd<dd
�Zdd�Z	d=dd�Z
d>dd�Zd?dd�Zd@dd�Z
dAdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�ZdBd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�ZdCd3d4�Zd5d6�Zd7d8�Zd9d:�ZdS)Drz#Proactor implementation using IOCP.rcCsDd|_g|_t�tjtd|�|_i|_t�	�|_
g|_t�	�|_dSrI)
r2�_resultsrQ�CreateIoCompletionPort�INVALID_HANDLE_VALUErn�_iocp�_cachererfrF�
_unregistered�_stopped_serving)rZconcurrencyr r r!r�s�
zIocpProactor.__init__cCs|jdkrtd��dS)NzIocpProactor is closed)r�rYr8r r r!�
_check_closed�s
zIocpProactor._check_closedcCsFdt|j�dt|j�g}|jdkr0|�d�d|jjd�|�fS)Nzoverlapped#=%sz
result#=%srmz<%s %s>� )�lenr�r�r�rLrr>�join)rr)r r r!�__repr__�s�

zIocpProactor.__repr__cCs
||_dSr7)r2)rrr r r!�set_loop�szIocpProactor.set_loopNcCs |js|�|�|j}g|_|Sr7)r�rK)r�timeoutrkr r r!�select�s

zIocpProactor.selectcCs|j��}|�|�|Sr7)r2r�r;)r�valuerNr r r!�_result�s

zIocpProactor._resultrcCs~|�|�t�t�}z4t|tj�r6|�|��||�n|�|��|�Wnt	k
rf|�
d�YSXdd�}|�|||�S)N�c
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7��	getresultr1rRrQZERROR_NETNAME_DELETEDZERROR_OPERATION_ABORTED�ConnectionResetErrorr��r��keyrr4r r r!�finish_recv�s
�z&IocpProactor.recv.<locals>.finish_recv)�_register_with_iocprQ�
Overlappedrn�
isinstance�socketZWSARecvr�ZReadFile�BrokenPipeErrorr��	_register�r�conn�nbytesrrrr�r r r!�recv�s


zIocpProactor.recvcCs~|�|�t�t�}z4t|tj�r6|�|��||�n|�|��|�Wnt	k
rf|�
d�YSXdd�}|�|||�S)Nrc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r��s
�z+IocpProactor.recv_into.<locals>.finish_recv)r�rQr�rnr�r�ZWSARecvIntor�ZReadFileIntor�r�r�)rr��bufrrrr�r r r!�	recv_into�s


zIocpProactor.recv_intocCs`|�|�t�t�}z|�|��||�Wntk
rH|�d�YSXdd�}|�|||�S)N)r�Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r��s
�z*IocpProactor.recvfrom.<locals>.finish_recv)	r�rQr�rnZWSARecvFromr�r�r�r�r�r r r!�recvfrom�s


zIocpProactor.recvfromcCs>|�|�t�t�}|�|��|||�dd�}|�|||�S)Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!�finish_sends
�z(IocpProactor.sendto.<locals>.finish_send)r�rQr�rnZ	WSASendTor�r�)rr�r�rrr}rr�r r r!�sendto�s



zIocpProactor.sendtocCsZ|�|�t�t�}t|tj�r4|�|��||�n|�|��|�dd�}|�	|||�S)Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r�s
�z&IocpProactor.send.<locals>.finish_send)
r�rQr�rnr�r�ZWSASendr�Z	WriteFiler�)rr�r�rrrr�r r r!�sends


zIocpProactor.sendcsv|���|��j��t�t�}|����������fdd�}dd�}|�|�|�}||��}t	j
||jd�|S)NcsD|��t�d����}��tjtj|���	��
������fS)Nz@P)r��structZpackr��
setsockoptr��
SOL_SOCKETrQZSO_UPDATE_ACCEPT_CONTEXT�
settimeoutZ
gettimeoutZgetpeername)r�r�rr��r��listenerr r!�
finish_accept*s�z*IocpProactor.accept.<locals>.finish_acceptc�s4z|IdHWn tjk
r.|���YnXdSr7)rr�ru)r.r�r r r!�accept_coro3s
z(IocpProactor.accept.<locals>.accept_coror)r��_get_accept_socket�familyrQr�rnZAcceptExr�r�r	Z
ensure_futurer2)rr�rr�r�r.�coror r�r!�accept$s

	
zIocpProactor.acceptc
s��jtjkr4t����|�|j��}|�d�|S|�	��zt�
����j�WnBtk
r�}z$|j
tjkrt����ddkr��W5d}~XYnXt�t�}|����|��fdd�}|�|�|�S)Nrrcs|����tjtjd��SrI)r�r�r�r�rQZSO_UPDATE_CONNECT_CONTEXT�r�r�r�r�r r!�finish_connectVs�z,IocpProactor.connect.<locals>.finish_connect)�typer�Z
SOCK_DGRAMrQZ
WSAConnectr�r2r�r;r�Z	BindLocalr�r1rR�errnoZ	WSAEINVALZgetsocknamer�rnZ	ConnectExr�)rr�r'rN�err�r r�r!�connect@s"



zIocpProactor.connectc		Csb|�|�t�t�}|d@}|d?d@}|�|��t�|���|||dd�dd�}|�|||�S)Nr� rc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!�finish_sendfileis
�z.IocpProactor.sendfile.<locals>.finish_sendfile)	r�rQr�rnZTransmitFiler��msvcrtZ
get_osfhandler�)	rZsock�file�offset�countrZ
offset_lowZoffset_highr�r r r!�sendfile_s


�	zIocpProactor.sendfilecsJ|���t�t�}|�����}|r0|���S�fdd�}|�|�|�S)Ncs|���Sr7)r�r��rtr r!�finish_accept_pipesz4IocpProactor.accept_pipe.<locals>.finish_accept_pipe)r�rQr�rnZConnectNamedPiper�r�r�)rrtrZ	connectedr�r r�r!r�ts


zIocpProactor.accept_pipec
�srt}zt�|�}WqhWn0tk
rF}z|jtjkr6�W5d}~XYnXt|dt�}t�	|�IdHqt
�|�S)N�)�CONNECT_PIPE_INIT_DELAYrQZConnectPiper1rRZERROR_PIPE_BUSY�min�CONNECT_PIPE_MAX_DELAYr	�sleepr
ro)rr'ZdelayrGr4r r r!r��s
zIocpProactor.connect_pipecCs|�||d�S)z�Wait for a handle.

        Return a Future object. The result of the future is True if the wait
        completed, or False if the wait did not complete (on timeout).
        F)�_wait_for_handle)rrGr�r r r!�wait_for_handle�szIocpProactor.wait_for_handlecCs|�|dd�}||_|Src)r�rW)rrXZ
done_callbackrNr r r!ra�szIocpProactor._wait_cancelcs�|��|dkrtj}nt�|d�}t�t�}t�||j	|j
|�}|r\t||||jd��nt
|||||jd���jr~�jd=�fdd�}�|d|f|j|j
<�S)N�@�@rrcs���Sr7)rKr��r�r r!�finish_wait_for_handle�sz=IocpProactor._wait_for_handle.<locals>.finish_wait_for_handler)r�rJ�INFINITE�math�ceilrQr�rnZRegisterWaitWithQueuer�r'rVr2rZrr�)rrGr�Z
_is_cancel�msrrHr�r r�r!r��s*
�
�	zIocpProactor._wait_for_handlecCs0||jkr,|j�|�t�|��|jdd�dSrI)rFrprQr�r�r��r�objr r r!r��s
z IocpProactor._register_with_iocpc
Cs�|��t||jd�}|jr$|jd=|jsrz|dd|�}Wn,tk
rf}z|�|�W5d}~XYnX|�|�||||f|j|j	<|Sr)
r�rr2rr"r1r9r;r�r')rrr��callbackr�r�r�r r r!r��s

zIocpProactor._registercCs|��|j�|�dS)a
Unregister an overlapped object.

        Call this method when its future has been cancelled. The event can
        already be signalled (pending in the proactor event queue). It is also
        safe if the event is never signalled (because it was cancelled).
        N)r�r�rLr|r r r!r`�szIocpProactor._unregistercCst�|�}|�d�|SrI)r�r�)rr��sr r r!r��s

zIocpProactor._get_accept_socketcCs�|dkrt}n0|dkr td��nt�|d�}|tkr>td��t�|j|�}|dkrX�qZd}|\}}}}z|j�|�\}}	}
}WnXt	k
r�|j
��r�|j
�dd||||fd��|dtj
fkr�t�|�Yq>YnX|
|jkr�|��q>|��s>z||||	�}Wn:tk
�r@}
z|�|
�|j�|�W5d}
~
XYq>X|�|�|j�|�q>|jD]}	|j�|	jd��q`|j��dS)Nrznegative timeoutr�ztimeout too bigz8GetQueuedCompletionStatus() returned an unexpected eventz)err=%s transferred=%s key=%#x address=%#x)r,�status)r��
ValueErrorr�r�rQZGetQueuedCompletionStatusr�r��pop�KeyErrorr2Z	get_debugr3r�rJr_r�r0Zdoner1r9r�rLr;r�r'rv)rr�r�r��errZtransferredr�r'r�rr�r�r�r�r r r!rKsL


��	






zIocpProactor._pollcCs|j�|�dSr7)r�rpr�r r r!�
_stop_serving9szIocpProactor._stop_servingcCs|jdkrdSt|j���D]�\}\}}}}|��r6qt|t�rBqz|��Wqtk
r�}z6|j	dk	r�d||d�}|j
r�|j
|d<|j	�|�W5d}~XYqXqd}t�
�}	|	|}
|jr�|
t�
�kr�t�d|t�
�|	�t�
�|}
|�|�q�g|_t�|j�d|_dS)NzCancelling a future failedr+r/g�?z,%r is running after closing for %.1f seconds)r��listr��itemsZ	cancelledr�rVr0r1r2rr3�time�	monotonicr�debugrKr�rJr_)rr'rNrr�r�r4r5Z
msg_updateZ
start_timeZnext_msgr r r!ru?s@


�
 
�zIocpProactor.closecCs|��dSr7)rur8r r r!rwnszIocpProactor.__del__)r)N)r)r)r)rN)r)N)N)r>r?r@rArr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rar�r�r�r`r�rKr�rurwr r r r!r�s8








"
 

7/rc@seZdZdd�ZdS)r�c
sPtj|f|||||d�|���_�fdd�}�jj�t�jj��}	|	�|�dS)N)r�r�r�r�r�cs�j��}��|�dSr7)�_procZpollZ_process_exited)r��
returncoder8r r!r�ys
z4_WindowsSubprocessTransport._start.<locals>.callback)	r
�Popenr�r2r[r��intrDr�)
rr�r�r�r�r�r�r�r�r�r r8r!�_startts���z"_WindowsSubprocessTransport._startN)r>r?r@rr r r r!r�rsr�c@seZdZeZdS)rN)r>r?r@r�
_loop_factoryr r r r!r�src@seZdZeZdS)rN)r>r?r@r
rr r r r!r�sr)/rArQrJr�r�r�r�r�r�re�rrrrrrr	r
�logr�__all__rnr�ZERROR_CONNECTION_REFUSEDZERROR_CONNECTION_ABORTEDr�r�ZFuturerrCrVrZ�objectrbZBaseSelectorEventLooprxZBaseProactorEventLoopr
rZBaseSubprocessTransportr�rZBaseDefaultEventLoopPolicyrrrr r r r!�<module>sR0J4;e`PK [ٗ'99)__pycache__/sslproto.cpython-38.opt-2.pycnu�[���U

e5dJj�@s�ddlZddlZzddlZWnek
r4dZYnXddlmZddlmZddlmZddlmZddl	m
Z
dd	�Zd
ZdZ
dZd
ZGdd�de�ZGdd�dejej�ZGdd�dej�ZdS)�N�)�base_events)�	constants)�	protocols)�
transports)�loggercCs"|rtd��t��}|sd|_|S)Nz(Server side SSL needs a valid SSLContextF)�
ValueError�sslZcreate_default_contextZcheck_hostname)�server_side�server_hostname�
sslcontext�r
�(/usr/lib64/python3.8/asyncio/sslproto.py�_create_transport_contextsrZ	UNWRAPPEDZDO_HANDSHAKEZWRAPPEDZSHUTDOWNc@szeZdZdZddd�Zedd��Zedd��Zed	d
��Zedd��Z	dd
d�Z
ddd�Zdd�Zddd�Z
ddd�ZdS)�_SSLPipeiNcCsH||_||_||_t|_t��|_t��|_d|_	d|_
d|_d|_dS�NF)
�_context�_server_side�_server_hostname�
_UNWRAPPED�_stater	Z	MemoryBIO�	_incoming�	_outgoing�_sslobj�
_need_ssldata�
_handshake_cb�_shutdown_cb)�self�contextr
rr
r
r�__init__8s

z_SSLPipe.__init__cCs|jS�N)r�rr
r
rrNsz_SSLPipe.contextcCs|jSr )rr!r
r
r�
ssl_objectSsz_SSLPipe.ssl_objectcCs|jSr )rr!r
r
r�need_ssldata[sz_SSLPipe.need_ssldatacCs
|jtkSr )r�_WRAPPEDr!r
r
r�wrappedasz_SSLPipe.wrappedcCsR|jtkrtd��|jj|j|j|j|jd�|_	t
|_||_|jddd�\}}|S)Nz"handshake in progress or completed)r
r�T)�only_handshake)
rr�RuntimeErrorrZwrap_biorrrrr�
_DO_HANDSHAKEr�feed_ssldata�r�callback�ssldata�appdatar
r
r�do_handshakejs	
�z_SSLPipe.do_handshakecCsB|jtkrtd��|jtkr$td��t|_||_|�d�\}}|S)Nzno security layer presentzshutdown in progressr&)rrr(�	_SHUTDOWNrr*r+r
r
r�shutdowns	

z_SSLPipe.shutdowncCs|j��|�d�\}}dS)Nr&)rZ	write_eofr*)rr-r.r
r
r�feed_eof�s
z_SSLPipe.feed_eofFc
Cs�|jtkr"|r|g}ng}g|fSd|_|r8|j�|�g}g}z�|jtkrz|j��t|_|j	rl|�	d�|rz||fWS|jtkr�|j�
|j�}|�|�|s�q�q�nJ|jt
kr�|j��d|_t|_|jr�|��n|jtkr�|�|j�
��Wnztjtjfk
�rl}zRt|dd�}|tjtjtjfk�rP|jtk�rN|j	�rN|�	|��|tjk|_W5d}~XYnX|jj�r�|�|j�
��||fS)NF�errno)rrrr�writer)rr/r$r�read�max_size�appendr0Zunwraprr	�SSLError�CertificateError�getattr�SSL_ERROR_WANT_READ�SSL_ERROR_WANT_WRITE�SSL_ERROR_SYSCALLr�pending)r�datar'r.r-�chunk�exc�	exc_errnor
r
rr*�sZ










�

z_SSLPipe.feed_ssldatarc
Cs|jtkr6|t|�kr&||d�g}ng}|t|�fSg}t|�}d|_z(|t|�krn||j�||d��7}Wnhtjk
r�}zHt	|dd�}|j
dkr�tj}|_|tjtj
tjfkr��|tjk|_W5d}~XYnX|jjr�|�|j���|t|�k�s|jrB�qqB||fS)NFr3ZPROTOCOL_IS_SHUTDOWN)rr�len�
memoryviewrrr4r	r8r:�reasonr;r3r<r=rr>r7r5)rr?�offsetr-ZviewrArBr
r
r�feed_appdata�s4

�z_SSLPipe.feed_appdata)N)N)N)F)r)�__name__�
__module__�__qualname__r6r�propertyrr"r#r%r/r1r2r*rGr
r
r
rr$s








Krc@s�eZdZejjZdd�Zd"dd�Zdd�Z	dd	�Z
d
d�Zdd
�Ze
jfdd�Zdd�Zdd�Zdd�Zd#dd�Zdd�Zedd��Zdd�Zdd�Zd d!�ZdS)$�_SSLProtocolTransportcCs||_||_d|_dSr)�_loop�
_ssl_protocol�_closed)r�loopZssl_protocolr
r
rr!sz_SSLProtocolTransport.__init__NcCs|j�||�Sr )rN�_get_extra_info�r�name�defaultr
r
r�get_extra_info'sz$_SSLProtocolTransport.get_extra_infocCs|j�|�dSr )rN�_set_app_protocol)r�protocolr
r
r�set_protocol+sz"_SSLProtocolTransport.set_protocolcCs|jjSr )rN�
_app_protocolr!r
r
r�get_protocol.sz"_SSLProtocolTransport.get_protocolcCs|jSr )rOr!r
r
r�
is_closing1sz _SSLProtocolTransport.is_closingcCsd|_|j��dS�NT)rOrN�_start_shutdownr!r
r
r�close4sz_SSLProtocolTransport.closecCs&|js"|d|��t|d�|��dS)Nzunclosed transport )�source)rO�ResourceWarningr^)rZ_warnr
r
r�__del__?sz_SSLProtocolTransport.__del__cCs |jj}|dkrtd��|��S)Nz*SSL transport has not been initialized yet)rN�
_transportr(�
is_reading)rZtrr
r
rrcDsz _SSLProtocolTransport.is_readingcCs|jj��dSr )rNrb�
pause_readingr!r
r
rrdJsz#_SSLProtocolTransport.pause_readingcCs|jj��dSr )rNrb�resume_readingr!r
r
rreRsz$_SSLProtocolTransport.resume_readingcCs|jj�||�dSr )rNrb�set_write_buffer_limits)rZhighZlowr
r
rrfZsz-_SSLProtocolTransport.set_write_buffer_limitscCs|jj��Sr )rNrb�get_write_buffer_sizer!r
r
rrgosz+_SSLProtocolTransport.get_write_buffer_sizecCs
|jjjSr )rNrb�_protocol_pausedr!r
r
rrhssz&_SSLProtocolTransport._protocol_pausedcCs<t|tttf�s$tdt|�j����|s,dS|j�|�dS)Nz+data: expecting a bytes-like instance, got )	�
isinstance�bytes�	bytearrayrD�	TypeError�typerHrN�_write_appdata�rr?r
r
rr4xs
z_SSLProtocolTransport.writecCsdSrr
r!r
r
r�
can_write_eof�sz#_SSLProtocolTransport.can_write_eofcCs|j��d|_dSr\)rN�_abortrOr!r
r
r�abort�s
z_SSLProtocolTransport.abort)N)NN)rHrIrJrZ
_SendfileModeZFALLBACKZ_sendfile_compatiblerrUrXrZr[r^�warnings�warnrarcrdrerfrgrKrhr4rprrr
r
r
rrLs$



rLc@s�eZdZd+dd�Zdd�Zd,dd	�Zd
d�Zdd
�Zdd�Zdd�Z	dd�Z
dd�Zd-dd�Zdd�Z
dd�Zdd�Zdd�Zd d!�Zd"d#�Zd.d%d&�Zd'd(�Zd)d*�ZdS)/�SSLProtocolFNTc		Cs�tdkrtd��|dkr tj}n|dkr6td|����|sDt||�}||_|rZ|sZ||_nd|_||_t	|d�|_
t��|_
d|_||_||_|�|�t|j|�|_d|_d|_d|_d|_d|_||_||_dS)Nzstdlib ssl module not availablerz7ssl_handshake_timeout should be a positive number, got )rF)r	r(rZSSL_HANDSHAKE_TIMEOUTrrrr�_sslcontext�dict�_extra�collections�deque�_write_backlog�_write_buffer_size�_waiterrMrVrL�_app_transport�_sslpipe�_session_established�
_in_handshake�_in_shutdownrb�_call_connection_made�_ssl_handshake_timeout)	rrP�app_protocolrZwaiterr
rZcall_connection_madeZssl_handshake_timeoutr
r
rr�s@��

zSSLProtocol.__init__cCs||_t|tj�|_dSr )rYrirZBufferedProtocol�_app_protocol_is_buffer)rr�r
r
rrV�s
�zSSLProtocol._set_app_protocolcCsD|jdkrdS|j��s:|dk	r.|j�|�n|j�d�d|_dSr )r}Z	cancelledZ
set_exceptionZ
set_result�rrAr
r
r�_wakeup_waiter�s

zSSLProtocol._wakeup_waitercCs&||_t|j|j|j�|_|��dSr )rbrrvrrr�_start_handshake)r�	transportr
r
r�connection_made�s�zSSLProtocol.connection_madecCsn|jr d|_|j�|jj|�n|jdk	r2d|j_d|_d|_t|dd�rT|j	�
�|�|�d|_d|_dS)NFT�_handshake_timeout_handle)
r�rM�	call_soonrY�connection_lostr~rOrbr:r��cancelr�rr�r
r
rr��s


zSSLProtocol.connection_lostcCs|j��dSr )rY�
pause_writingr!r
r
rr��szSSLProtocol.pause_writingcCs|j��dSr )rY�resume_writingr!r
r
rr�szSSLProtocol.resume_writingcCs"|jdkrdSz|j�|�\}}WnLttfk
r<�Yn4tk
rn}z|�|d�WY�dSd}~XYnX|D]}|j�|�qt|D]�}|�rz&|jr�t	�
|j|�n|j�|�WnPttfk
r��Yn8tk
�r
}z|�|d�WY�dSd}~XYnXq�|�
��qq�dS)NzSSL error in data receivedz/application protocol failed to receive SSL data)rr*�
SystemExit�KeyboardInterrupt�
BaseException�_fatal_errorrbr4r�rZ_feed_data_to_buffered_protorY�
data_receivedr])rr?r-r.�er@Zexr
r
rr�s<
��zSSLProtocol.data_receivedcCsTzB|j��rt�d|�|�t�|js@|j	�
�}|r@t�d�W5|j��XdS)Nz%r received EOFz?returning true from eof_received() has no effect when using ssl)rbr^rM�	get_debugr�debugr��ConnectionResetErrorr�rY�eof_receivedZwarning)rZ	keep_openr
r
rr�-s


zSSLProtocol.eof_receivedcCs4||jkr|j|S|jdk	r,|j�||�S|SdSr )rxrbrUrRr
r
rrQCs



zSSLProtocol._get_extra_infocCs.|jr
dS|jr|��nd|_|�d�dS)NTr&)r�r�rqrnr!r
r
rr]Ks
zSSLProtocol._start_shutdowncCs.|j�|df�|jt|�7_|��dS)Nr)r{r7r|rC�_process_write_backlogror
r
rrnTszSSLProtocol._write_appdatacCs\|j��r$t�d|�|j��|_nd|_d|_|j�d�|j�	|j
|j�|_|�
�dS)Nz%r starts SSL handshakeT)r&r)rMr�rr��time�_handshake_start_timer�r{r7Z
call_laterr��_check_handshake_timeoutr�r�r!r
r
rr�Ys

��zSSLProtocol._start_handshakecCs*|jdkr&d|j�d�}|�t|��dS)NTz$SSL handshake is taking longer than z! seconds: aborting the connection)r�r�r��ConnectionAbortedError)r�msgr
r
rr�hs
�z$SSLProtocol._check_handshake_timeoutc
Csd|_|j��|jj}z|dk	r&|�|��}Wnbttfk
rJ�YnJtk
r�}z,t	|t
j�rld}nd}|�||�WY�dSd}~XYnX|j
��r�|j
��|j}t�d||d�|jj||��|��|d�|jr�|j�|j�|��d|_|j
�|j�dS)NFz1SSL handshake failed on verifying the certificatezSSL handshake failedz%r: SSL handshake took %.1f msg@�@)�peercert�cipher�compressionr"T)r�r�r�rr"Zgetpeercertr�r�r�rir	r9r�rMr�r�r�rr�rx�updater�r�r�rYr�r~r�r�r�r�)rZ
handshake_excZsslobjr�rAr�Zdtr
r
r�_on_handshake_completeqs8

�z"SSLProtocol._on_handshake_completec
CsB|jdks|jdkrdSz�tt|j��D]�}|jd\}}|rR|j�||�\}}n*|rj|j�|j�}d}n|j�|j	�}d}|D]}|j�
|�q�|t|�kr�||f|jd<|jjr�|j��q�|jd=|j
t|�8_
q(Wn\ttfk
r��YnDtk
�r<}z$|j�r |�|�n|�|d�W5d}~XYnXdS)NrrzFatal error on SSL transport)rbr�rangerCr{rGr/r�r1�	_finalizer4Z_pausedrer|r�r�r�r�r�)r�ir?rFr-r@rAr
r
rr��s:�
z"SSLProtocol._process_write_backlog�Fatal error on transportcCsVt|t�r(|j��r@tjd||dd�n|j�|||j|d��|jrR|j�|�dS)Nz%r: %sT)�exc_info)�messageZ	exceptionr�rW)	ri�OSErrorrMr�rr�Zcall_exception_handlerrbZ_force_close)rrAr�r
r
rr��s

�zSSLProtocol._fatal_errorcCsd|_|jdk	r|j��dSr )rrbr^r!r
r
rr��s
zSSLProtocol._finalizecCs(z|jdk	r|j��W5|��XdSr )r�rbrrr!r
r
rrq�s
zSSLProtocol._abort)FNTN)N)N)r�)rHrIrJrrVr�r�r�r�r�r�r�rQr]rnr�r�r�r�r�r�rqr
r
r
rru�s.�
.

&
		)+
ru)ryrsr	�ImportError�rrrr�logrrrr)r$r0�objectrZ_FlowControlMixinZ	TransportrLZProtocolrur
r
r
r�<module>s*
y�xPK [H�� �[�[/__pycache__/windows_events.cpython-38.opt-2.pycnu�[���U

e5di��@s�ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
ddl	mZddl	mZddl	m
Z
ddl	mZddl	mZdd	l	mZdd
l	mZddlmZdZdZd
ZdZdZdZdZGdd�dej�ZGdd�dej�ZGdd�de�ZGdd�de�ZGdd�de �Z!Gdd�dej"�Z#Gdd�dej$�Z%Gd d!�d!�Z&Gd"d#�d#ej'�Z(e#Z)Gd$d%�d%e
j*�Z+Gd&d'�d'e
j*�Z,e,Z-dS)(�N�)�events)�base_subprocess)�futures)�
exceptions)�proactor_events)�selector_events)�tasks)�
windows_utils)�logger)�SelectorEventLoop�ProactorEventLoop�IocpProactor�DefaultEventLoopPolicy�WindowsSelectorEventLoopPolicy�WindowsProactorEventLoopPolicy���i�i�g����MbP?g�������?csZeZdZdd��fdd�
Z�fdd�Zdd�Z�fd	d
�Z�fdd�Z�fd
d�Z�Z	S)�_OverlappedFutureN��loopcs&t�j|d�|jr|jd=||_dS�Nr���)�super�__init__�_source_traceback�_ov)�self�ovr��	__class__��./usr/lib64/python3.8/asyncio/windows_events.pyr1sz_OverlappedFuture.__init__csHt���}|jdk	rD|jjr dnd}|�dd|�d|jjd�d��|S)N�pendingZ	completedrzoverlapped=<z, �#x�>)r�
_repr_inforr"�insert�address�r�info�staterr r!r%7s


 z_OverlappedFuture._repr_infoc
Csr|jdkrdSz|j��WnJtk
rf}z,d||d�}|jrJ|j|d<|j�|�W5d}~XYnXd|_dS)Nz&Cancelling an overlapped future failed��message�	exception�future�source_traceback)r�cancel�OSErrorr�_loop�call_exception_handler)r�exc�contextr r r!�_cancel_overlapped>s
�
z$_OverlappedFuture._cancel_overlappedcs|��t���S�N)r6rr0�rrr r!r0Nsz_OverlappedFuture.cancelcst��|�|��dSr7)r�
set_exceptionr6�rr-rr r!r9Rsz_OverlappedFuture.set_exceptioncst��|�d|_dSr7)r�
set_resultr�r�resultrr r!r;Vsz_OverlappedFuture.set_result)
�__name__�
__module__�__qualname__rr%r6r0r9r;�
__classcell__r r rr!r+srcsjeZdZdd��fdd�
Zdd�Z�fdd�Zd	d
�Zdd�Z�fd
d�Z�fdd�Z	�fdd�Z
�ZS)�_BaseWaitHandleFutureNrcs8t�j|d�|jr|jd=||_||_||_d|_dS)NrrT)rrrr�_handle�_wait_handle�_registered)rr�handle�wait_handlerrr r!r^sz_BaseWaitHandleFuture.__init__cCst�|jd�tjkS�Nr)�_winapiZWaitForSingleObjectrCZ
WAIT_OBJECT_0r8r r r!�_pollls�z_BaseWaitHandleFuture._pollcsdt���}|�d|jd���|jdk	rB|��r4dnd}|�|�|jdk	r`|�d|jd���|S)Nzhandle=r#ZsignaledZwaitingzwait_handle=)rr%�appendrCrJrDr(rr r!r%qs



z _BaseWaitHandleFuture._repr_infocCs
d|_dSr7)r�r�futr r r!�_unregister_wait_cb{sz)_BaseWaitHandleFuture._unregister_wait_cbc
Cs�|js
dSd|_|j}d|_zt�|�Wn`tk
r�}zB|jtjkrzd||d�}|jrd|j|d<|j�	|�WY�dSW5d}~XYnX|�
d�dS�NFz$Failed to unregister the wait handler+r/)rErD�_overlappedZUnregisterWaitr1�winerror�ERROR_IO_PENDINGrr2r3rN�rrGr4r5r r r!�_unregister_wait�s$�
z&_BaseWaitHandleFuture._unregister_waitcs|��t���Sr7)rTrr0r8rr r!r0�sz_BaseWaitHandleFuture.cancelcs|��t��|�dSr7)rTrr9r:rr r!r9�sz#_BaseWaitHandleFuture.set_exceptioncs|��t��|�dSr7)rTrr;r<rr r!r;�sz _BaseWaitHandleFuture.set_result)r>r?r@rrJr%rNrTr0r9r;rAr r rr!rB[s
rBcsBeZdZdd��fdd�
Zdd�Z�fdd�Z�fd	d
�Z�ZS)�_WaitCancelFutureNrcst�j||||d�d|_dS)Nr)rr�_done_callback)rr�eventrGrrr r!r�sz_WaitCancelFuture.__init__cCstd��dS)Nz'_WaitCancelFuture must not be cancelled)�RuntimeErrorr8r r r!r0�sz_WaitCancelFuture.cancelcs$t��|�|jdk	r |�|�dSr7)rr;rVr<rr r!r;�s
z_WaitCancelFuture.set_resultcs$t��|�|jdk	r |�|�dSr7)rr9rVr:rr r!r9�s
z_WaitCancelFuture.set_exception)r>r?r@rr0r;r9rAr r rr!rU�srUcs6eZdZdd��fdd�
Z�fdd�Zdd�Z�ZS)	�_WaitHandleFutureNrcs<t�j||||d�||_d|_t�dddd�|_d|_dS)NrTF)rr�	_proactorZ_unregister_proactorrPZCreateEvent�_event�
_event_fut)rrrFrG�proactorrrr r!r�s
z_WaitHandleFuture.__init__csF|jdk	r"t�|j�d|_d|_|j�|j�d|_t��|�dSr7)	r[rI�CloseHandler\rZ�_unregisterrrrNrLrr r!rN�s
	z%_WaitHandleFuture._unregister_wait_cbc
Cs�|js
dSd|_|j}d|_zt�||j�Wn`tk
r�}zB|jtjkr~d||d�}|jrh|j|d<|j	�
|�WY�dSW5d}~XYnX|j�|j|j
�|_dSrO)rErDrPZUnregisterWaitExr[r1rQrRrr2r3rZ�_wait_cancelrNr\rSr r r!rT�s(�

�z"_WaitHandleFuture._unregister_wait)r>r?r@rrNrTrAr r rr!rY�srYc@s8eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZeZdS)�
PipeServercCs,||_t��|_d|_d|_|�d�|_dS�NT)�_address�weakref�WeakSet�_free_instances�_pipe�_accept_pipe_future�_server_pipe_handle)rr'r r r!r�s

zPipeServer.__init__cCs|j|�d�}|_|S�NF)rgri)r�tmpr r r!�_get_unconnected_pipesz PipeServer._get_unconnected_pipec
Csr|��rdStjtjB}|r&|tjO}t�|j|tjtjBtj	Btj
tjtjtj
tj�}t�|�}|j�|�|Sr7)�closedrIZPIPE_ACCESS_DUPLEXZFILE_FLAG_OVERLAPPEDZFILE_FLAG_FIRST_PIPE_INSTANCEZCreateNamedPipercZPIPE_TYPE_MESSAGEZPIPE_READMODE_MESSAGEZ	PIPE_WAITZPIPE_UNLIMITED_INSTANCESr
ZBUFSIZEZNMPWAIT_WAIT_FOREVER�NULL�
PipeHandlerf�add)r�first�flags�h�piper r r!ris(

��
zPipeServer._server_pipe_handlecCs
|jdkSr7)rcr8r r r!rmszPipeServer.closedcCsR|jdk	r|j��d|_|jdk	rN|jD]}|��q*d|_d|_|j��dSr7)rhr0rcrf�closerg�clear)rrtr r r!rus




zPipeServer.closeN)	r>r?r@rrlrirmru�__del__r r r r!ra�s
rac@seZdZdS)�_WindowsSelectorEventLoopN)r>r?r@r r r r!rx,srxcsDeZdZd�fdd�	Z�fdd�Zdd�Zdd	�Zd
d
d�Z�ZS)r
Ncs|dkrt�}t��|�dSr7)rrr)rr]rr r!r3szProactorEventLoop.__init__c	sXz|�|j�t���W5|jdk	rR|jj}|j��|dk	rL|j�|�d|_XdSr7)	Z_self_reading_futurerr0rZr_�	call_soonZ_loop_self_readingr�run_forever�rrrr r!rz8s

zProactorEventLoop.run_foreverc�s8|j�|�}|IdH}|�}|j||d|id�}||fS)N�addr��extra)rZ�connect_pipe�_make_duplex_pipe_transport)r�protocol_factoryr'�frt�protocol�transr r r!�create_pipe_connectionKs
�z(ProactorEventLoop.create_pipe_connectionc�s.t���d�����fdd�	������gS)Nc
sd}zn|rN|��}�j�|����r4|��WdS��}�j||d�id����}|dkrdWdS�j�|�}Wn�t	k
r�}zF|r�|�
�dkr���d||d��|��n�jr�t
jd|dd�W5d}~XYn2tjk
r�|r�|��YnX|�_|���dS)	Nr|r}rzPipe accept failed)r,r-rtzAccept pipe failed on pipe %rT)�exc_info)r=rf�discardrmrur�rlrZ�accept_piper1�filenor3Z_debugrZwarningr�CancelledErrorrh�add_done_callback)r�rtr�r4�r'�loop_accept_piper�rZserverr r!r�VsH��
�z>ProactorEventLoop.start_serving_pipe.<locals>.loop_accept_pipe)N)rary)rr�r'r r�r!�start_serving_pipeSs(
z$ProactorEventLoop.start_serving_pipec		�s�|��}
t||||||||f|
|d�|	��}z|
IdHWnDttfk
rT�Yn,tk
r~|��|��IdH�YnX|S)N)�waiterr~)�
create_future�_WindowsSubprocessTransport�
SystemExit�KeyboardInterrupt�
BaseExceptionruZ_wait)rr��args�shell�stdin�stdout�stderr�bufsizer~�kwargsr�Ztranspr r r!�_make_subprocess_transport�s*
���z,ProactorEventLoop._make_subprocess_transport)N)N)	r>r?r@rrzr�r�r�rAr r rr!r
0s0�r
c@s�eZdZd:dd�Zdd�Zdd�Zdd	�Zd;dd�Zd
d�Zd<dd�Z	d=dd�Z
d>dd�Zd?dd�Zd@dd�Z
dd�Zdd�Zdd�Zd d!�Zd"d#�ZdAd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�ZdBd2d3�Zd4d5�Zd6d7�Zd8d9�Zd
S)CrrcCsDd|_g|_t�tjtd|�|_i|_t�	�|_
g|_t�	�|_dSrH)
r2�_resultsrP�CreateIoCompletionPort�INVALID_HANDLE_VALUErn�_iocp�_cacherdrerE�
_unregistered�_stopped_serving)rZconcurrencyr r r!r�s�
zIocpProactor.__init__cCs|jdkrtd��dS)NzIocpProactor is closed)r�rXr8r r r!�
_check_closed�s
zIocpProactor._check_closedcCsFdt|j�dt|j�g}|jdkr0|�d�d|jjd�|�fS)Nzoverlapped#=%sz
result#=%srmz<%s %s>� )�lenr�r�r�rKrr>�join)rr)r r r!�__repr__�s�

zIocpProactor.__repr__cCs
||_dSr7)r2)rrr r r!�set_loop�szIocpProactor.set_loopNcCs |js|�|�|j}g|_|Sr7)r�rJ)r�timeoutrkr r r!�select�s

zIocpProactor.selectcCs|j��}|�|�|Sr7)r2r�r;)r�valuerMr r r!�_result�s

zIocpProactor._resultrcCs~|�|�t�t�}z4t|tj�r6|�|��||�n|�|��|�Wnt	k
rf|�
d�YSXdd�}|�|||�S)N�c
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7��	getresultr1rQrPZERROR_NETNAME_DELETEDZERROR_OPERATION_ABORTED�ConnectionResetErrorr��r��keyrr4r r r!�finish_recv�s
�z&IocpProactor.recv.<locals>.finish_recv)�_register_with_iocprP�
Overlappedrn�
isinstance�socketZWSARecvr�ZReadFile�BrokenPipeErrorr��	_register�r�conn�nbytesrrrr�r r r!�recv�s


zIocpProactor.recvcCs~|�|�t�t�}z4t|tj�r6|�|��||�n|�|��|�Wnt	k
rf|�
d�YSXdd�}|�|||�S)Nrc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r��s
�z+IocpProactor.recv_into.<locals>.finish_recv)r�rPr�rnr�r�ZWSARecvIntor�ZReadFileIntor�r�r�)rr��bufrrrr�r r r!�	recv_into�s


zIocpProactor.recv_intocCs`|�|�t�t�}z|�|��||�Wntk
rH|�d�YSXdd�}|�|||�S)N)r�Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r��s
�z*IocpProactor.recvfrom.<locals>.finish_recv)	r�rPr�rnZWSARecvFromr�r�r�r�r�r r r!�recvfrom�s


zIocpProactor.recvfromcCs>|�|�t�t�}|�|��|||�dd�}|�|||�S)Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!�finish_sends
�z(IocpProactor.sendto.<locals>.finish_send)r�rPr�rnZ	WSASendTor�r�)rr�r�rrr|rr�r r r!�sendto�s



zIocpProactor.sendtocCsZ|�|�t�t�}t|tj�r4|�|��||�n|�|��|�dd�}|�	|||�S)Nc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!r�s
�z&IocpProactor.send.<locals>.finish_send)
r�rPr�rnr�r�ZWSASendr�Z	WriteFiler�)rr�r�rrrr�r r r!�sends


zIocpProactor.sendcsv|���|��j��t�t�}|����������fdd�}dd�}|�|�|�}||��}t	j
||jd�|S)NcsD|��t�d����}��tjtj|���	��
������fS)Nz@P)r��structZpackr��
setsockoptr��
SOL_SOCKETrPZSO_UPDATE_ACCEPT_CONTEXT�
settimeoutZ
gettimeoutZgetpeername)r�r�rr��r��listenerr r!�
finish_accept*s�z*IocpProactor.accept.<locals>.finish_acceptc�s4z|IdHWn tjk
r.|���YnXdSr7)rr�ru)r.r�r r r!�accept_coro3s
z(IocpProactor.accept.<locals>.accept_coror)r��_get_accept_socket�familyrPr�rnZAcceptExr�r�r	Z
ensure_futurer2)rr�rr�r�r.�coror r�r!�accept$s

	
zIocpProactor.acceptc
s��jtjkr4t����|�|j��}|�d�|S|�	��zt�
����j�WnBtk
r�}z$|j
tjkrt����ddkr��W5d}~XYnXt�t�}|����|��fdd�}|�|�|�S)Nrrcs|����tjtjd��SrH)r�r�r�r�rPZSO_UPDATE_CONNECT_CONTEXT�r�r�r�r�r r!�finish_connectVs�z,IocpProactor.connect.<locals>.finish_connect)�typer�Z
SOCK_DGRAMrPZ
WSAConnectr�r2r�r;r�Z	BindLocalr�r1rQ�errnoZ	WSAEINVALZgetsocknamer�rnZ	ConnectExr�)rr�r'rM�err�r r�r!�connect@s"



zIocpProactor.connectc		Csb|�|�t�t�}|d@}|d?d@}|�|��t�|���|||dd�dd�}|�|||�S)Nr� rc
SsRz
|��WStk
rL}z$|jtjtjfkr:t|j��n�W5d}~XYnXdSr7r�r�r r r!�finish_sendfileis
�z.IocpProactor.sendfile.<locals>.finish_sendfile)	r�rPr�rnZTransmitFiler��msvcrtZ
get_osfhandler�)	rZsock�file�offset�countrZ
offset_lowZoffset_highr�r r r!�sendfile_s


�	zIocpProactor.sendfilecsJ|���t�t�}|�����}|r0|���S�fdd�}|�|�|�S)Ncs|���Sr7)r�r��rtr r!�finish_accept_pipesz4IocpProactor.accept_pipe.<locals>.finish_accept_pipe)r�rPr�rnZConnectNamedPiper�r�r�)rrtrZ	connectedr�r r�r!r�ts


zIocpProactor.accept_pipec
�srt}zt�|�}WqhWn0tk
rF}z|jtjkr6�W5d}~XYnXt|dt�}t�	|�IdHqt
�|�S)N�)�CONNECT_PIPE_INIT_DELAYrPZConnectPiper1rQZERROR_PIPE_BUSY�min�CONNECT_PIPE_MAX_DELAYr	�sleepr
ro)rr'ZdelayrFr4r r r!r�s
zIocpProactor.connect_pipecCs|�||d�Srj)�_wait_for_handle)rrFr�r r r!�wait_for_handle�szIocpProactor.wait_for_handlecCs|�|dd�}||_|Srb)r�rV)rrWZ
done_callbackrMr r r!r`�szIocpProactor._wait_cancelcs�|��|dkrtj}nt�|d�}t�t�}t�||j	|j
|�}|r\t||||jd��nt
|||||jd���jr~�jd=�fdd�}�|d|f|j|j
<�S)N�@�@rrcs���Sr7)rJr��r�r r!�finish_wait_for_handle�sz=IocpProactor._wait_for_handle.<locals>.finish_wait_for_handler)r�rI�INFINITE�math�ceilrPr�rnZRegisterWaitWithQueuer�r'rUr2rYrr�)rrFr�Z
_is_cancel�msrrGr�r r�r!r��s*
�
�	zIocpProactor._wait_for_handlecCs0||jkr,|j�|�t�|��|jdd�dSrH)rErprPr�r�r��r�objr r r!r��s
z IocpProactor._register_with_iocpc
Cs�|��t||jd�}|jr$|jd=|jsrz|dd|�}Wn,tk
rf}z|�|�W5d}~XYnX|�|�||||f|j|j	<|Sr)
r�rr2rr"r1r9r;r�r')rrr��callbackr�r�r�r r r!r��s

zIocpProactor._registercCs|��|j�|�dSr7)r�r�rKr{r r r!r_�szIocpProactor._unregistercCst�|�}|�d�|SrH)r�r�)rr��sr r r!r��s

zIocpProactor._get_accept_socketcCs�|dkrt}n0|dkr td��nt�|d�}|tkr>td��t�|j|�}|dkrX�qZd}|\}}}}z|j�|�\}}	}
}WnXt	k
r�|j
��r�|j
�dd||||fd��|dtj
fkr�t�|�Yq>YnX|
|jkr�|��q>|��s>z||||	�}Wn:tk
�r@}
z|�|
�|j�|�W5d}
~
XYq>X|�|�|j�|�q>|jD]}	|j�|	jd��q`|j��dS)Nrznegative timeoutr�ztimeout too bigz8GetQueuedCompletionStatus() returned an unexpected eventz)err=%s transferred=%s key=%#x address=%#x)r,�status)r��
ValueErrorr�r�rPZGetQueuedCompletionStatusr�r��pop�KeyErrorr2Z	get_debugr3r�rIr^r�r0Zdoner1r9r�rKr;r�r'rv)rr�r�r��errZtransferredr�r'r�rr�r�r�r�r r r!rJsL


��	






zIocpProactor._pollcCs|j�|�dSr7)r�rpr�r r r!�
_stop_serving9szIocpProactor._stop_servingcCs|jdkrdSt|j���D]�\}\}}}}|��r6qt|t�rBqz|��Wqtk
r�}z6|j	dk	r�d||d�}|j
r�|j
|d<|j	�|�W5d}~XYqXqd}t�
�}	|	|}
|jr�|
t�
�kr�t�d|t�
�|	�t�
�|}
|�|�q�g|_t�|j�d|_dS)NzCancelling a future failedr+r/g�?z,%r is running after closing for %.1f seconds)r��listr��itemsZ	cancelledr�rUr0r1r2rr3�time�	monotonicr�debugrJr�rIr^)rr'rMrr�r�r4r5Z
msg_updateZ
start_timeZnext_msgr r r!ru?s@


�
 
�zIocpProactor.closecCs|��dSr7)rur8r r r!rwnszIocpProactor.__del__)r)N)r)r)r)rN)r)N)N)r>r?r@rr�r�r�r�r�r�r�r�r�r�r�r�r�r�rr�r`r�r�r�r_r�rJr�rurwr r r r!r�s6








"
 

7/rc@seZdZdd�ZdS)r�c
sPtj|f|||||d�|���_�fdd�}�jj�t�jj��}	|	�|�dS)N)r�r�r�r�r�cs�j��}��|�dSr7)�_procZpollZ_process_exited)r��
returncoder8r r!r�ys
z4_WindowsSubprocessTransport._start.<locals>.callback)	r
�Popenr�r2rZr��intrCr�)
rr�r�r�r�r�r�r�r�r�r r8r!�_startts���z"_WindowsSubprocessTransport._startN)r>r?r@rr r r r!r�rsr�c@seZdZeZdS)rN)r>r?r@r�
_loop_factoryr r r r!r�src@seZdZeZdS)rN)r>r?r@r
rr r r r!r�sr).rPrIr�r�r�r�r�r�rd�rrrrrrr	r
�logr�__all__rnr�ZERROR_CONNECTION_REFUSEDZERROR_CONNECTION_ABORTEDr�r�ZFuturerrBrUrY�objectraZBaseSelectorEventLooprxZBaseProactorEventLoopr
rZBaseSubprocessTransportr�rZBaseDefaultEventLoopPolicyrrrr r r r!�<module>sP0J4;e`PK [�o2y�/�/%__pycache__/transports.cpython-38.pycnu�[���U

e5d�(�@s|dZdZGdd�d�ZGdd�de�ZGdd�de�ZGdd	�d	ee�ZGd
d�de�ZGdd
�d
e�ZGdd�de�ZdS)zAbstract Transport class.)�
BaseTransport�
ReadTransport�WriteTransport�	Transport�DatagramTransport�SubprocessTransportc@sHeZdZdZdZddd�Zddd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)rzBase class for transports.��_extraNcCs|dkri}||_dS�Nr)�self�extra�r�*/usr/lib64/python3.8/asyncio/transports.py�__init__szBaseTransport.__init__cCs|j�||�S)z#Get optional transport information.)r�get)r
�name�defaultrrr
�get_extra_infoszBaseTransport.get_extra_infocCst�dS)z2Return True if the transport is closing or closed.N��NotImplementedError�r
rrr
�
is_closingszBaseTransport.is_closingcCst�dS)aClose the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        Nrrrrr
�closeszBaseTransport.closecCst�dS)zSet a new protocol.Nr)r
�protocolrrr
�set_protocol%szBaseTransport.set_protocolcCst�dS)zReturn the current protocol.Nrrrrr
�get_protocol)szBaseTransport.get_protocol)N)N)�__name__�
__module__�__qualname__�__doc__�	__slots__rrrrrrrrrr
r	s


rc@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
rz#Interface for read-only transports.rcCst�dS)z*Return True if the transport is receiving.Nrrrrr
�
is_reading3szReadTransport.is_readingcCst�dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        Nrrrrr
�
pause_reading7szReadTransport.pause_readingcCst�dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        Nrrrrr
�resume_reading?szReadTransport.resume_readingN)rrrrrr r!r"rrrr
r.s
rc@sNeZdZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)rz$Interface for write-only transports.rNcCst�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        Nr�r
�high�lowrrr
�set_write_buffer_limitsMsz&WriteTransport.set_write_buffer_limitscCst�dS)z,Return the current size of the write buffer.Nrrrrr
�get_write_buffer_sizebsz$WriteTransport.get_write_buffer_sizecCst�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        Nr)r
�datarrr
�writefszWriteTransport.writecCsd�|�}|�|�dS)z�Write a list (or any iterable) of data bytes to the transport.

        The default implementation concatenates the arguments and
        calls write() on the result.
        �N)�joinr))r
Zlist_of_datar(rrr
�
writelinesns
zWriteTransport.writelinescCst�dS)z�Close the write end after flushing buffered data.

        (This is like typing ^D into a UNIX program reading from stdin.)

        Data may still be received.
        Nrrrrr
�	write_eofwszWriteTransport.write_eofcCst�dS)zAReturn True if this transport supports write_eof(), False if not.Nrrrrr
�
can_write_eof�szWriteTransport.can_write_eofcCst�dS�z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        Nrrrrr
�abort�szWriteTransport.abort)NN)rrrrrr&r'r)r,r-r.r0rrrr
rHs
		rc@seZdZdZdZdS)raSInterface representing a bidirectional transport.

    There may be several implementations, but typically, the user does
    not implement new transports; rather, the platform provides some
    useful transports that are implemented using the platform's best
    practices.

    The user never instantiates a transport directly; they call a
    utility function, passing it a protocol factory and other
    information necessary to create the transport and protocol.  (E.g.
    EventLoop.create_connection() or EventLoop.create_server().)

    The utility function will asynchronously create a transport and a
    protocol and hook them up by calling the protocol's
    connection_made() method, passing it the transport.

    The implementation here raises NotImplemented for every method
    except writelines(), which calls write() in a loop.
    rN)rrrrrrrrr
r�src@s&eZdZdZdZddd�Zdd�ZdS)	rz(Interface for datagram (UDP) transports.rNcCst�dS)aSend data to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        addr is target socket address.
        If addr is None use target address pointed on transport creation.
        Nr)r
r(Zaddrrrr
�sendto�szDatagramTransport.sendtocCst�dSr/rrrrr
r0�szDatagramTransport.abort)N)rrrrrr1r0rrrr
r�s

rc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)rrcCst�dS)zGet subprocess id.Nrrrrr
�get_pid�szSubprocessTransport.get_pidcCst�dS)z�Get subprocess returncode.

        See also
        http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
        Nrrrrr
�get_returncode�sz"SubprocessTransport.get_returncodecCst�dS)z&Get transport for pipe with number fd.Nr)r
�fdrrr
�get_pipe_transport�sz&SubprocessTransport.get_pipe_transportcCst�dS)z�Send signal to subprocess.

        See also:
        docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
        Nr)r
�signalrrr
�send_signal�szSubprocessTransport.send_signalcCst�dS)aLStop the subprocess.

        Alias for close() method.

        On Posix OSs the method sends SIGTERM to the subprocess.
        On Windows the Win32 API function TerminateProcess()
         is called to stop the subprocess.

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
        Nrrrrr
�	terminate�szSubprocessTransport.terminatecCst�dS)z�Kill the subprocess.

        On Posix OSs the function sends SIGKILL to the subprocess.
        On Windows kill() is an alias for terminate().

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
        Nrrrrr
�kill�s	zSubprocessTransport.killN)
rrrrr2r3r5r7r8r9rrrr
r�srcsZeZdZdZdZd�fdd�	Zdd�Zdd	�Zd
d�Zddd
�Z	ddd�Z
dd�Z�ZS)�_FlowControlMixinavAll the logic for (write) flow control in a mix-in base class.

    The subclass must implement get_write_buffer_size().  It must call
    _maybe_pause_protocol() whenever the write buffer size increases,
    and _maybe_resume_protocol() whenever it decreases.  It may also
    override set_write_buffer_limits() (e.g. to specify different
    defaults).

    The subclass constructor must call super().__init__(extra).  This
    will call set_write_buffer_limits().

    The user may call set_write_buffer_limits() and
    get_write_buffer_size(), and their protocol's pause_writing() and
    resume_writing() may be called.
    )�_loop�_protocol_paused�_high_water�
_low_waterNcs0t��|�|dk	st�||_d|_|��dS)NF)�superr�AssertionErrorr;r<�_set_write_buffer_limits)r
rZloop��	__class__rr
rs
z_FlowControlMixin.__init__c
Cs�|��}||jkrdS|js�d|_z|j��WnRttfk
rJ�Yn:tk
r�}z|j�	d|||jd��W5d}~XYnXdS)NTzprotocol.pause_writing() failed��messageZ	exceptionZ	transportr)
r'r=r<�	_protocolZ
pause_writing�
SystemExit�KeyboardInterrupt�
BaseExceptionr;�call_exception_handler)r
�size�excrrr
�_maybe_pause_protocols 
�z'_FlowControlMixin._maybe_pause_protocolc
Cs�|jr||��|jkr|d|_z|j��WnRttfk
rB�Yn:tk
rz}z|j�	d|||jd��W5d}~XYnXdS)NFz protocol.resume_writing() failedrD)
r<r'r>rFZresume_writingrGrHrIr;rJ)r
rLrrr
�_maybe_resume_protocol!s��z(_FlowControlMixin._maybe_resume_protocolcCs|j|jfSr	)r>r=rrrr
�get_write_buffer_limits1sz)_FlowControlMixin.get_write_buffer_limitscCsj|dkr|dkrd}nd|}|dkr.|d}||krBdksZntd|�d|�d���||_||_dS)Ni��zhigh (z) must be >= low (z) must be >= 0)�
ValueErrorr=r>r#rrr
rA4s�z*_FlowControlMixin._set_write_buffer_limitscCs|j||d�|��dS)N)r$r%)rArMr#rrr
r&Dsz)_FlowControlMixin.set_write_buffer_limitscCst�dSr	rrrrr
r'Hsz'_FlowControlMixin.get_write_buffer_size)NN)NN)NN)
rrrrrrrMrNrOrAr&r'�
__classcell__rrrBr
r:�s

r:N)	r�__all__rrrrrrr:rrrr
�<module>s%F6PK [�;j%%.__pycache__/windows_utils.cpython-38.opt-1.pycnu�[���U

e5d��@s�dZddlZejdkred��ddlZddlZddlZddlZddlZddl	Z	ddl
Z
dZdZej
Z
ejZe��Zdded	�d
d�ZGdd
�d
�ZGdd�dej�ZdS)z)Various Windows specific bits and pieces.�NZwin32z
win32 only)�pipe�Popen�PIPE�
PipeHandlei F)TT)�duplex�
overlapped�bufsizec
Cs$tjd�t��tt��d�}|r>tj}tj	tj
B}||}}ntj}tj
}d|}}|tjO}|drp|tj
O}|dr�tj
}nd}d}	}
z\t�||tjd||tjtj�}	t�||dtjtj|tj�}
tj|	dd�}|�d�|	|
fWS|	dk	�rt�|	�|
dk	�rt�|
��YnXdS)zELike os.pipe() but with overlapped support and using handles not fds.z\\.\pipe\python-pipe-{:d}-{:d}-)�prefixr�NT�r)�tempfileZmktemp�format�os�getpid�next�
_mmap_counter�_winapiZPIPE_ACCESS_DUPLEXZGENERIC_READZ
GENERIC_WRITEZPIPE_ACCESS_INBOUNDZFILE_FLAG_FIRST_PIPE_INSTANCEZFILE_FLAG_OVERLAPPEDZCreateNamedPipeZ	PIPE_WAITZNMPWAIT_WAIT_FOREVERZNULLZ
CreateFileZ
OPEN_EXISTINGZConnectNamedPipeZGetOverlappedResult�CloseHandle)rrrZaddressZopenmode�accessZobsizeZibsizeZflags_and_attribsZh1Zh2Zov�r�-/usr/lib64/python3.8/asyncio/windows_utils.pyr sb��


��





rc@sbeZdZdZdd�Zdd�Zedd��Zdd	�Ze	j
d
�dd�Zej
fd
d�Zdd�Zdd�ZdS)rz�Wrapper for an overlapped pipe handle which is vaguely file-object like.

    The IOCP event loop can use these instead of socket objects.
    cCs
||_dS�N��_handle��self�handlerrr�__init__VszPipeHandle.__init__cCs2|jdk	rd|j��}nd}d|jj�d|�d�S)Nzhandle=�closed�<� �>)r�	__class__�__name__rrrr�__repr__Ys
zPipeHandle.__repr__cCs|jSrr�rrrrr`szPipeHandle.handlecCs|jdkrtd��|jS)NzI/O operation on closed pipe)r�
ValueErrorr%rrr�filenods
zPipeHandle.fileno)rcCs|jdk	r||j�d|_dSrr)rrrrr�closeis

zPipeHandle.closecCs*|jdk	r&|d|��t|d�|��dS)Nz	unclosed )�source)r�ResourceWarningr()rZ_warnrrr�__del__ns
zPipeHandle.__del__cCs|Srrr%rrr�	__enter__sszPipeHandle.__enter__cCs|��dSr)r()r�t�v�tbrrr�__exit__vszPipeHandle.__exit__N)r#�
__module__�__qualname__�__doc__rr$�propertyrr'rrr(�warnings�warnr+r,r0rrrrrQs
rcs"eZdZdZd�fdd�	Z�ZS)rz�Replacement for subprocess.Popen using overlapped pipe handles.

    The stdin, stdout, stderr are None or instances of PipeHandle.
    Nc	sxd}}}d}	}
}|tkr@tddd�\}}	t�|tj�}n|}|tkrhtdd�\}
}
t�|
d�}n|}|tkr�tdd�\}}t�|d�}n|tkr�|}n|}z�z t�j	|f|||d�|��Wn0|	|
|fD]}|dk	r�t
�|�qւYn>X|	dk	�r
t|	�|_
|
dk	�rt|
�|_|dk	�r2t|�|_W5|tk�rJt�|�|tk�r^t�|�|tk�rrt�|�XdS)N)FTT)rr)TFrr)�stdin�stdout�stderr)rr�msvcrtZopen_osfhandler�O_RDONLY�STDOUTr(�superrrrrr7r8r9)r�argsr7r8r9�kwdsZ	stdin_rfdZ
stdout_wfdZ
stderr_wfdZstdin_whZ	stdout_rhZ	stderr_rhZstdin_rhZ	stdout_whZ	stderr_wh�h�r"rrr�sN��










zPopen.__init__)NNN)r#r1r2r3r�
__classcell__rrrArr}sr)r3�sys�platform�ImportErrorr�	itertoolsr:r�
subprocessrr5�__all__ZBUFSIZErr<�countrrrrrrrr�<module>s$
1,PK [��Kl�l�,__pycache__/base_events.cpython-38.opt-1.pycnu�[���U

e5d��@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZzddlZWnek
r�dZYnXddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddl m!Z!dZ"dZ#dZ$e%e	d�Z&dZ'e(�Z)dd�Z*dd�Z+dd�Z,d+dd�Z-d,dd�Z.dd �Z/e%e	d!��r�d"d#�Z0nd$d#�Z0Gd%d&�d&ej1�Z2Gd'd(�d(ej3�Z4Gd)d*�d*ej5�Z6dS)-a�Base implementation of event loop.

The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.

Whenever a public API takes a callback, subsequent positional
arguments will be passed to the callback if/when it is called.  This
avoids the proliferation of trivial lambdas implementing closures.
Keyword arguments for the callback are not supported; this is a
conscious design decision, leaving the door open for keyword arguments
to modify the meaning of the API call itself.
�N�)�	constants)�
coroutines)�events)�
exceptions)�futures)�	protocols)�sslproto)�	staggered)�tasks)�
transports)�trsock)�logger)�
BaseEventLoop�dg�?�AF_INET6i�QcCs0|j}tt|dd�tj�r$t|j�St|�SdS)N�__self__)Z	_callback�
isinstance�getattrr�Task�reprr�str)�handle�cb�r�+/usr/lib64/python3.8/asyncio/base_events.py�_format_handleJs
rcCs(|tjkrdS|tjkrdSt|�SdS)Nz<pipe>z<stdout>)�
subprocess�PIPE�STDOUTr)�fdrrr�_format_pipeSs


r!cCsLttd�std��n4z|�tjtjd�Wntk
rFtd��YnXdS)N�SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)�hasattr�socket�
ValueError�
setsockopt�
SOL_SOCKETr"�OSError��sockrrr�_set_reuseport\s

r+c		Cs�ttd�sdS|dtjtjhks(|dkr,dS|tjkr>tj}n|tjkrPtj}ndS|dkrbd}nXt|t�rz|dkrzd}n@t|t�r�|dkr�d}n(zt	|�}Wnt
tfk
r�YdSX|tjkr�tj
g}tr�|�tj�n|g}t|t�r�|�d�}d|k�rdS|D]t}zVt�||�t�rJ|tjk�rJ|||d||||ffWS|||d||ffWSWntk
�rzYnX�q
dS)N�	inet_ptonr��Zidna�%)r#r$�IPPROTO_TCPZIPPROTO_UDP�SOCK_STREAM�
SOCK_DGRAMr�bytesr�int�	TypeErrorr%�	AF_UNSPEC�AF_INET�	_HAS_IPv6�appendr�decoder,r()	�host�port�family�type�protoZflowinfoZscopeidZafs�afrrr�_ipaddr_infogsN
�






rAcCs�t��}|D]*}|d}||kr(g||<||�|�qt|���}g}|dkr||�|dd|d��|dd|d�=|�dd�tj�tj	|��D��|S)z-Interleave list of addrinfo tuples by family.rrNcss|]}|dk	r|VqdS�Nr)�.0�arrr�	<genexpr>�s�z(_interleave_addrinfos.<locals>.<genexpr>)
�collections�OrderedDictr9�list�values�extend�	itertools�chain�
from_iterable�zip_longest)Z	addrinfosZfirst_address_family_countZaddrinfos_by_family�addrr=Zaddrinfos_listsZ	reorderedrrr�_interleave_addrinfos�s"
��rPcCs4|��s"|��}t|ttf�r"dSt�|���dSrB)�	cancelled�	exceptionr�
SystemExit�KeyboardInterruptrZ	_get_loop�stop)�fut�excrrr�_run_until_complete_cb�s
rX�TCP_NODELAYcCs@|jtjtjhkr<|jtjkr<|jtjkr<|�tjtj	d�dS�Nr)
r=r$r7rr>r1r?r0r&rYr)rrr�_set_nodelay�s
�
�r[cCsdSrBrr)rrrr[�sc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)�_SendfileFallbackProtocolcCsht|tj�std��||_|��|_|��|_|j	|_
|��|�|�|j
r^|jj
��|_nd|_dS)Nz.transport should be _FlowControlMixin instance)rrZ_FlowControlMixinr5�
_transportZget_protocol�_protoZ
is_reading�_should_resume_readingZ_protocol_paused�_should_resume_writing�
pause_reading�set_protocol�_loop�
create_future�_write_ready_fut)�self�transprrr�__init__�s


z"_SendfileFallbackProtocol.__init__c�s2|j��rtd��|j}|dkr$dS|IdHdS)NzConnection closed by peer)r]�
is_closing�ConnectionErrorre)rfrVrrr�drain�s
z_SendfileFallbackProtocol.draincCstd��dS)Nz?Invalid state: connection should have been established already.��RuntimeError)rf�	transportrrr�connection_made�sz)_SendfileFallbackProtocol.connection_madecCs@|jdk	r0|dkr$|j�td��n|j�|�|j�|�dS)NzConnection is closed by peer)reZ
set_exceptionrjr^�connection_lost)rfrWrrrrp�s
�z)_SendfileFallbackProtocol.connection_lostcCs |jdk	rdS|jj��|_dSrB)rer]rcrd�rfrrr�
pause_writing�s
z'_SendfileFallbackProtocol.pause_writingcCs$|jdkrdS|j�d�d|_dS)NF)re�
set_resultrqrrr�resume_writing�s
z(_SendfileFallbackProtocol.resume_writingcCstd��dS�Nz'Invalid state: reading should be pausedrl)rf�datarrr�
data_received�sz'_SendfileFallbackProtocol.data_receivedcCstd��dSrurlrqrrr�eof_receivedsz&_SendfileFallbackProtocol.eof_receivedc�sF|j�|j�|jr|j��|jdk	r2|j��|jrB|j��dSrB)	r]rbr^r_�resume_readingre�cancelr`rtrqrrr�restores


z!_SendfileFallbackProtocol.restoreN)�__name__�
__module__�__qualname__rhrkrorprrrtrwrxr{rrrrr\�sr\c@sxeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
edd��Zdd�Z
dd�Zdd�Zdd�ZdS)�ServercCs@||_||_d|_g|_||_||_||_||_d|_d|_	dS)NrF)
rc�_sockets�
_active_count�_waiters�_protocol_factory�_backlog�_ssl_context�_ssl_handshake_timeout�_serving�_serving_forever_fut)rf�loop�sockets�protocol_factoryZssl_context�backlog�ssl_handshake_timeoutrrrrhszServer.__init__cCsd|jj�d|j�d�S)N�<z	 sockets=�>)�	__class__r|r�rqrrr�__repr__ szServer.__repr__cCs|jd7_dSrZ)r�rqrrr�_attach#szServer._attachcCs.|jd8_|jdkr*|jdkr*|��dS)Nrr)r�r��_wakeuprqrrr�_detach'szServer._detachcCs,|j}d|_|D]}|��s|�|�qdSrB)r��doners)rf�waiters�waiterrrrr�-s
zServer._wakeupc	CsJ|jr
dSd|_|jD].}|�|j�|j�|j||j||j|j�qdS)NT)	r�r�Zlistenr�rc�_start_servingr�r�r�)rfr*rrrr�4s
�zServer._start_servingcCs|jSrB)rcrqrrr�get_loop>szServer.get_loopcCs|jSrB)r�rqrrr�
is_servingAszServer.is_servingcCs"|jdkrdStdd�|jD��S)Nrcss|]}t�|�VqdSrB)r
ZTransportSocket)rC�srrrrEHsz!Server.sockets.<locals>.<genexpr>)r��tuplerqrrrr�Ds
zServer.socketscCsn|j}|dkrdSd|_|D]}|j�|�qd|_|jdk	rX|j��sX|j��d|_|jdkrj|��dS)NFr)	r�rcZ
_stop_servingr�r�r�rzr�r�)rfr�r*rrr�closeJs
�

zServer.closec�s"|��tjd|jd�IdHdS)Nr�r�)r�r�sleeprcrqrrr�
start_serving]szServer.start_servingc	�s�|jdk	rtd|�d���|jdkr4td|�d���|��|j��|_zLz|jIdHWn6tjk
r�z|��|�	�IdHW5�XYnXW5d|_XdS)Nzserver z, is already being awaited on serve_forever()z
 is closed)
r�rmr�r�rcrdrZCancelledErrorr��wait_closedrqrrr�
serve_forevercs 

�
zServer.serve_foreverc�s<|jdks|jdkrdS|j��}|j�|�|IdHdSrB)r�r�rcrdr9)rfr�rrrr�xs

zServer.wait_closedN)r|r}r~rhr�r�r�r�r�r�r��propertyr�r�r�r�r�rrrrrs


rc@sPeZdZdd�Zdd�Zdd�Zdd�d	d
�Zdd�Zd
d�Zd�ddd�dd�Z	d�ddddddd�dd�Z
d�dd�Zd�dd�Zd�dd�Z
d�dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zejfd7d8�Zd9d:�Zd;d<�Zdd=�d>d?�Z dd=�d@dA�Z!dd=�dBdC�Z"dDdE�Z#dFdG�Z$dHdI�Z%dd=�dJdK�Z&dLdM�Z'dNdO�Z(dPdQ�Z)dRdRdRdRdS�dTdU�Z*d�dVdW�Z+d�ddX�dYdZ�Z,d[d\�Z-d]d^�Z.d_d`�Z/d�dadb�Z0d�ddRdRdRdddddddc�
ddde�Z1d�dfdg�Z2d�ddX�dhdi�Z3djdk�Z4dldm�Z5ddddn�dodp�Z6d�dRdRdRe7ddddq�drds�Z8dRe9j:dRdRdS�dtdu�Z;dvdw�Z<d�e9j=e9j>ddxddddddy�	dzd{�Z?ddd|�d}d~�Z@dd��ZAd�d��ZBd�d��ZCeDjEeDjEeDjEdddRdddd��	d�d��ZFeDjEeDjEeDjEdddRdddd��	d�d��ZGd�d��ZHd�d��ZId�d��ZJd�d��ZKd�d��ZLd�d��ZMd�d��ZNd�d��ZOd�d��ZPd�d��ZQd�d��ZRdS)�rcCs�d|_d|_d|_t��|_g|_d|_d|_d|_	t
�d�j|_
d|_|�t���d|_d|_d|_d|_d|_t��|_d|_dS)NrF�	monotonicg�������?)�_timer_cancelled_count�_closed�	_stoppingrF�deque�_ready�
_scheduled�_default_executorZ
_internal_fds�
_thread_id�time�get_clock_infoZ
resolution�_clock_resolution�_exception_handler�	set_debugrZ_is_debug_mode�slow_callback_duration�_current_handle�
_task_factory�"_coroutine_origin_tracking_enabled�&_coroutine_origin_tracking_saved_depth�weakrefZWeakSet�
_asyncgens�_asyncgens_shutdown_calledrqrrrrh�s$

zBaseEventLoop.__init__c	Cs.d|jj�d|���d|���d|���d�	S)Nr�z	 running=z closed=z debug=r�)r�r|�
is_running�	is_closed�	get_debugrqrrrr��s,�zBaseEventLoop.__repr__cCstj|d�S)z,Create a Future object attached to the loop.r�)rZFuturerqrrrrd�szBaseEventLoop.create_futureN)�namecCsN|��|jdkr2tj|||d�}|jrJ|jd=n|�||�}t�||�|S)zDSchedule a coroutine object.

        Return a task object.
        N)r�r����)�
_check_closedr�rr�_source_tracebackZ_set_task_name)rf�coror�Ztaskrrr�create_task�s

zBaseEventLoop.create_taskcCs"|dk	rt|�std��||_dS)awSet a task factory that will be used by loop.create_task().

        If factory is None the default task factory will be set.

        If factory is a callable, it should have a signature matching
        '(loop, coro)', where 'loop' will be a reference to the active
        event loop, 'coro' will be a coroutine object.  The callable
        must return a Future.
        Nz'task factory must be a callable or None)�callabler5r�)rf�factoryrrr�set_task_factory�s
zBaseEventLoop.set_task_factorycCs|jS)z<Return a task factory, or None if the default one is in use.)r�rqrrr�get_task_factory�szBaseEventLoop.get_task_factory)�extra�servercCst�dS)zCreate socket transport.N��NotImplementedError)rfr*�protocolr�r�r�rrr�_make_socket_transport�sz$BaseEventLoop._make_socket_transportFT)�server_side�server_hostnamer�r�r��call_connection_madecCst�dS)zCreate SSL transport.Nr�)rfZrawsockr��
sslcontextr�r�r�r�r�r�r�rrr�_make_ssl_transport�sz!BaseEventLoop._make_ssl_transportcCst�dS)zCreate datagram transport.Nr�)rfr*r��addressr�r�rrr�_make_datagram_transport�sz&BaseEventLoop._make_datagram_transportcCst�dS)zCreate read pipe transport.Nr��rf�piper�r�r�rrr�_make_read_pipe_transport�sz'BaseEventLoop._make_read_pipe_transportcCst�dS)zCreate write pipe transport.Nr�r�rrr�_make_write_pipe_transport�sz(BaseEventLoop._make_write_pipe_transportc	
�st�dS)zCreate subprocess transport.Nr�)
rfr��args�shell�stdin�stdout�stderr�bufsizer��kwargsrrr�_make_subprocess_transport�sz(BaseEventLoop._make_subprocess_transportcCst�dS)z�Write a byte to self-pipe, to wake up the event loop.

        This may be called from a different thread.

        The subclass is responsible for implementing the self-pipe.
        Nr�rqrrr�_write_to_self�szBaseEventLoop._write_to_selfcCst�dS)zProcess selector events.Nr�)rf�
event_listrrr�_process_events�szBaseEventLoop._process_eventscCs|jrtd��dS)NzEvent loop is closed)r�rmrqrrrr��szBaseEventLoop._check_closedcCs*|j�|�|��s&|�|j|���dSrB)r��discardr��call_soon_threadsafer��aclose�rf�agenrrr�_asyncgen_finalizer_hook�sz&BaseEventLoop._asyncgen_finalizer_hookcCs.|jrtjd|�d�t|d�|j�|�dS)Nzasynchronous generator z3 was scheduled after loop.shutdown_asyncgens() call��source)r��warnings�warn�ResourceWarningr��addr�rrr�_asyncgen_firstiter_hooks
�z&BaseEventLoop._asyncgen_firstiter_hookc�s�d|_t|j�sdSt|j�}|j��tjdd�|D�d|d��IdH}t||�D]*\}}t|t	�rT|�
d|��||d��qTdS)z,Shutdown all active asynchronous generators.TNcSsg|]}|���qSr)r�)rCZagrrr�
<listcomp>sz4BaseEventLoop.shutdown_asyncgens.<locals>.<listcomp>)Zreturn_exceptionsr�z;an error occurred during closing of asynchronous generator )�messagerRZasyncgen)r��lenr�rH�clearr�gather�zipr�	Exception�call_exception_handler)rfZ
closing_agensZresults�resultr�rrr�shutdown_asyncgenss"


�
�z BaseEventLoop.shutdown_asyncgenscCs(|��rtd��t��dk	r$td��dS)Nz"This event loop is already runningz7Cannot run the event loop while another loop is running)r�rmrZ_get_running_looprqrrr�_check_running&s�zBaseEventLoop._check_runningc	Cs�|��|��|�|j�t��|_t��}tj	|j
|jd�z t
�|�|��|jrLq^qLW5d|_d|_t
�d�|�d�tj	|�XdS)zRun until stop() is called.)�	firstiter�	finalizerFN)r�r��_set_coroutine_origin_tracking�_debug�	threading�	get_identr��sys�get_asyncgen_hooks�set_asyncgen_hooksr�r�r�rZ_set_running_loop�	_run_once)rfZold_agen_hooksrrr�run_forever-s$
�


zBaseEventLoop.run_foreverc	Cs�|��|��t�|�}tj||d�}|r4d|_|�t�z<z|�
�Wn*|rp|��rp|��sp|�
��YnXW5|�	t�X|��s�td��|��S)a\Run until the Future is done.

        If the argument is a coroutine, it is wrapped in a Task.

        WARNING: It would be disastrous to call run_until_complete()
        with the same coroutine twice -- it would wrap it in two
        different Tasks and that can't be good.

        Return the Future's result, or raise its exception.
        r�Fz+Event loop stopped before Future completed.)r�r�rZisfuturerZ
ensure_futureZ_log_destroy_pendingZadd_done_callbackrXZremove_done_callbackrr�rQrRrmr�)rfZfutureZnew_taskrrr�run_until_completeDs"
z BaseEventLoop.run_until_completecCs
d|_dS)z�Stop running the event loop.

        Every callback already scheduled will still run.  This simply informs
        run_forever to stop looping after a complete iteration.
        TN)r�rqrrrrUjszBaseEventLoop.stopcCsj|��rtd��|jrdS|jr,t�d|�d|_|j��|j��|j	}|dk	rfd|_	|j
dd�dS)z�Close the event loop.

        This clears the queues and shuts down the executor,
        but does not wait for the executor to finish.

        The event loop must not be running.
        z!Cannot close a running event loopNzClose %rTF)�wait)r�rmr�r�r�debugr�r�r�r�Zshutdown�rf�executorrrrr�rs

zBaseEventLoop.closecCs|jS)z*Returns True if the event loop was closed.)r�rqrrrr��szBaseEventLoop.is_closedcCs0|��s,|d|��t|d�|��s,|��dS)Nzunclosed event loop r�)r�r�r�r�)rfZ_warnrrr�__del__�szBaseEventLoop.__del__cCs
|jdk	S)z*Returns True if the event loop is running.N)r�rqrrrr��szBaseEventLoop.is_runningcCst��S)z�Return the time according to the event loop's clock.

        This is a float expressed in seconds since an epoch, but the
        epoch, precision, accuracy and drift are unspecified and may
        differ per event loop.
        )r�r�rqrrrr��szBaseEventLoop.time)�contextcGs2|j|��||f|�d|i�}|jr.|jd=|S)a8Arrange for a callback to be called at a given time.

        Return a Handle: an opaque object with a cancel() method that
        can be used to cancel the call.

        The delay can be an int or float, expressed in seconds.  It is
        always relative to the current time.

        Each callback will be called exactly once.  If two callbacks
        are scheduled for exactly the same time, it undefined which
        will be called first.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        rr�)�call_atr�r�)rfZdelay�callbackrr��timerrrr�
call_later�s�zBaseEventLoop.call_latercGsZ|��|jr"|��|�|d�t�|||||�}|jrB|jd=t�|j	|�d|_	|S)z|Like call_later(), but uses an absolute time.

        Absolute time corresponds to the event loop's time() method.
        r
r�T)
r�r��
_check_thread�_check_callbackrZTimerHandler��heapq�heappushr�)rf�whenrrr�rrrrr
�szBaseEventLoop.call_atcGsB|��|jr"|��|�|d�|�|||�}|jr>|jd=|S)aTArrange for a callback to be called as soon as possible.

        This operates as a FIFO queue: callbacks are called in the
        order in which they are registered.  Each callback will be
        called exactly once.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        �	call_soonr�)r�r�rr�
_call_soonr��rfrrr�rrrrr�s
zBaseEventLoop.call_sooncCsDt�|�st�|�r$td|�d���t|�s@td|�d|����dS)Nzcoroutines cannot be used with z()z"a callable object was expected by z(), got )rZiscoroutineZiscoroutinefunctionr5r�)rfr�methodrrrr�s
�
��zBaseEventLoop._check_callbackcCs.t�||||�}|jr|jd=|j�|�|S)Nr�)rZHandler�r�r9)rfrr�rrrrrr�s
zBaseEventLoop._call_sooncCs,|jdkrdSt��}||jkr(td��dS)aoCheck that the current thread is the thread running the event loop.

        Non-thread-safe methods of this class make this assumption and will
        likely behave incorrectly when the assumption is violated.

        Should only be called when (self._debug == True).  The caller is
        responsible for checking this condition for performance reasons.
        NzMNon-thread-safe operation invoked on an event loop other than the current one)r�r�rrm)rfZ	thread_idrrrr�s	

�zBaseEventLoop._check_threadcGsB|��|jr|�|d�|�|||�}|jr6|jd=|��|S)z"Like call_soon(), but thread-safe.r�r�)r�r�rrr�r�rrrrr��sz"BaseEventLoop.call_soon_threadsafecGsZ|��|jr|�|d�|dkr@|j}|dkr@tj��}||_tj|j|f|��|d�S)N�run_in_executorr�)	r�r�rr��
concurrentr�ThreadPoolExecutorZwrap_futureZsubmit)rfr
�funcr�rrrrs
�zBaseEventLoop.run_in_executorcCs&t|tjj�st�dtd�||_dS)Nz{Using the default executor that is not an instance of ThreadPoolExecutor is deprecated and will be prohibited in Python 3.9�)rrrrr�r��DeprecationWarningr�r	rrr�set_default_executors�z"BaseEventLoop.set_default_executorcCs�|�d|��g}|r$|�d|���|r8|�d|���|rL|�d|���|r`|�d|���d�|�}t�d|�|��}t�||||||�}	|��|}
d|�d	|
d
d�d|	��}|
|jkr�t�|�n
t�|�|	S)
N�:zfamily=ztype=zproto=zflags=�, zGet address info %szGetting address info z took g@�@z.3fzms: )	r9�joinrrr�r$�getaddrinfor��info)rfr;r<r=r>r?�flags�msg�t0�addrinfo�dtrrr�_getaddrinfo_debugs&


z BaseEventLoop._getaddrinfo_debugr�r=r>r?r&c
�s2|jr|j}ntj}|�d|||||||�IdHSrB)r�r+r$r$r)rfr;r<r=r>r?r&Zgetaddr_funcrrrr$2s�zBaseEventLoop.getaddrinfoc�s|�dtj||�IdHSrB)rr$�getnameinfo)rfZsockaddrr&rrrr-<s�zBaseEventLoop.getnameinfo)�fallbackc
�s�|jr|��dkrtd��|�||||�z|�||||�IdHWStjk
rl}z
|s\�W5d}~XYnX|�||||�IdHS)Nrzthe socket must be non-blocking)r�Z
gettimeoutr%�_check_sendfile_params�_sock_sendfile_nativer�SendfileNotAvailableError�_sock_sendfile_fallback)rfr*�file�offset�countr.rWrrr�
sock_sendfile@s��zBaseEventLoop.sock_sendfilec�st�d|�d���dS)Nz-syscall sendfile is not available for socket z and file {file!r} combination�rr1�rfr*r3r4r5rrrr0Ns
�z#BaseEventLoop._sock_sendfile_nativec

�s�|r|�|�|rt|tj�ntj}t|�}d}zt|rNt|||�}|dkrNq�t|�d|�}|�d|j|�IdH}	|	szq�|�	||d|	��IdH||	7}q2|W�S|dkr�t|d�r�|�||�XdS)Nr�seek)
r9�minrZ!SENDFILE_FALLBACK_READBUFFER_SIZE�	bytearrayr#�
memoryviewr�readintoZsock_sendall)
rfr*r3r4r5�	blocksize�buf�
total_sent�view�readrrrr2Us,
��
z%BaseEventLoop._sock_sendfile_fallbackcCs�dt|dd�krtd��|jtjks,td��|dk	rbt|t�sLtd�|���|dkrbtd�|���t|t�sztd�|���|dkr�td�|���dS)N�b�modez$file should be opened in binary modez+only SOCK_STREAM type sockets are supportedz+count must be a positive integer (got {!r})rz0offset must be a non-negative integer (got {!r}))	rr%r>r$r1rr4r5�formatr8rrrr/os2
��
����z$BaseEventLoop._check_sendfile_paramsc�s@g}|�|�|\}}}}}	d}
z�tj|||d�}
|
�d�|dk	r�|D]r\}}}}}z|
�|�Wq�WqHtk
r�}z0d|�d|j����}
t|j|
�}|�|�W5d}~XYqHXqH|���|�	|
|	�IdH|
WStk
�r}z"|�|�|
dk	�r
|
�
��W5d}~XYn |
dk	�r4|
�
��YnXdS)z$Create, bind and connect one socket.N�r=r>r?Fz*error while attempting to bind on address �: )r9r$�setblocking�bindr(�strerror�lower�errno�pop�sock_connectr�)rfrZ	addr_infoZlocal_addr_infosZ
my_exceptionsr=Ztype_r?�_r�r*ZladdrrWr'rrr�
_connect_sock�s:



�


zBaseEventLoop._connect_sock)
�sslr=r?r&r*�
local_addrr�r��happy_eyeballs_delay�
interleavec
	�sl|
dk	r|std��|
dkr0|r0|s,td��|}
|dk	rD|sDtd��|dk	rX|
dkrXd}
|dk	sj|dk	�r�|dk	rztd���j||f|tj||�d�IdH}|s�td��|	dk	r܈j|	|tj||�d�IdH��s�td��nd�|
r�t||
�}g�|dk�rH|D]D}z ���|��IdH}W�qvWntk
�r@Y�qYnX�qn.tj���fd	d
�|D�|�d�IdH\}}}|dk�r dd
��D��t	��dk�r��d�nJt
�d��t�fdd
��D���r҈d�td�d�
dd
��D�����n.|dk�rtd��|jtjk�r td|�����j||||
|d�IdH\}}�j�rd|�d�}t�d|||||�||fS)a�Connect to a TCP server.

        Create a streaming transport connection to a given Internet host and
        port: socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_STREAM. protocol_factory must be
        a callable returning a protocol instance.

        This method is a coroutine which will try to establish the connection
        in the background.  When successful, the coroutine returns a
        (transport, protocol) pair.
        Nz+server_hostname is only meaningful with sslz:You must set server_hostname when using ssl without a host�1ssl_handshake_timeout is only meaningful with sslr�8host/port and sock can not be specified at the same time�r=r>r?r&r��!getaddrinfo() returned empty listc3s |]}t��j�|��VqdSrB)�	functools�partialrP)rCr))r�laddr_infosrfrrrE�s��z2BaseEventLoop.create_connection.<locals>.<genexpr>r�cSsg|]}|D]}|�qqSrr)rC�subrWrrrr��sz3BaseEventLoop.create_connection.<locals>.<listcomp>rc3s|]}t|��kVqdSrB�r�rCrW)�modelrrrEszMultiple exceptions: {}r"css|]}t|�VqdSrBr]r^rrrrE
sz5host and port was not specified and no sock specified�"A Stream Socket was expected, got )r�r$z%r connected to %s:%r: (%r, %r))r%�_ensure_resolvedr$r1r(rPrPr
Zstaggered_racer�r�allrEr#r>�_create_connection_transportr��get_extra_inforr)rfr�r;r<rQr=r?r&r*rRr�r�rSrT�infosr)rOrnr�r)rr[r_rfr�create_connection�s�����


�
��

�
���
�zBaseEventLoop.create_connectionc	�s�|�d�|�}|��}|rHt|t�r*dn|}	|j|||	||||d�}
n|�|||�}
z|IdHWn|
���YnX|
|fS)NF�r�r�r�)rHrdr�boolr�r�r�)rfr*r�rQr�r�r�r�r�r�rnrrrrc%s*
�z*BaseEventLoop._create_connection_transportc
�s�|��rtd��t|dtjj�}|tjjkr:td|����|tjjkr�z|�||||�IdHWStj	k
r�}z
|sx�W5d}~XYnX|s�td|����|�
||||�IdHS)a�Send a file to transport.

        Return the total number of bytes which were sent.

        The method uses high-performance os.sendfile if available.

        file must be a regular file object opened in binary mode.

        offset tells from where to start reading the file. If specified,
        count is the total number of bytes to transmit as opposed to
        sending the file until EOF is reached. File position is updated on
        return or also in case of error in which case file.tell()
        can be used to figure out the number of bytes
        which were sent.

        fallback set to True makes asyncio to manually read and send
        the file when the platform does not support the sendfile syscall
        (e.g. Windows or SSL socket on Unix).

        Raise SendfileNotAvailableError if the system does not support
        sendfile syscall and fallback is False.
        zTransport is closingZ_sendfile_compatiblez(sendfile is not supported for transport NzHfallback is disabled and native sendfile is not supported for transport )rirmrrZ
_SendfileModeZUNSUPPORTEDZ
TRY_NATIVE�_sendfile_nativerr1�_sendfile_fallback)rfrnr3r4r5r.rDrWrrr�sendfile?s4�����zBaseEventLoop.sendfilec�st�d��dS)Nz!sendfile syscall is not supportedr7)rfrgr3r4r5rrrrins�zBaseEventLoop._sendfile_nativec
�s�|r|�|�|rt|d�nd}t|�}d}t|�}z�|rXt|||�}|dkrX|W�bSt|�d|�}	|�d|j|	�IdH}
|
s�|W�0S|�	�IdH|�
|	d|
��||
7}q6W5|dkr�t|d�r�|�||�|��IdHXdS)Ni@rr9)r9r:r;r\r#r{r<rr=rk�write)rfrgr3r4r5r>r?r@r?rArBrrrrjrs*
z BaseEventLoop._sendfile_fallbackrgc
�s�tdkrtd��t|tj�s*td|����t|dd�sFtd|�d���|��}tj|||||||dd�}|�	�|�
|�|�|j|�}	|�|j
�}
z|IdHWn.tk
r�|��|	��|
���YnX|jS)	zzUpgrade transport to TLS.

        Return a new transport that *protocol* should start using
        immediately.
        Nz"Python ssl module is not availablez@sslcontext is expected to be an instance of ssl.SSLContext, got Z_start_tls_compatibleFz
transport z  is not supported by start_tls())r�r�)rQrmrZ
SSLContextr5rrdr	ZSSLProtocolrarbrrory�
BaseExceptionr�rzZ_app_transport)rfrnr�r�r�r�r�r�Zssl_protocolZ
conmade_cbZ	resume_cbrrr�	start_tls�sB	�
��
zBaseEventLoop.start_tls)r=r?r&�
reuse_address�
reuse_port�allow_broadcastr*c �s�|
dk	r�|
jtjkr"td|
�����s>�s>|s>|s>|s>|s>|	r~t��||||||	d�}d�dd�|��D��}td|�d���|
�d	�d}
�n�s��s�|d
kr�td��||fdff}�n�ttd
��r�|tj	k�r���fD]}|dk	r�t
|t�s�td��qڈ�rx�d
dk�rxz"t
�t�
��j��r.t���WnFtk
�rFYn2tk
�rv}zt�d�|�W5d}~XYnX||f��fff}n�i}d
�fd�ffD]�\}}|dk	�r�|j||tj|||d�IdH}|�s�td��|D]:\}}}}}||f}||k�rddg||<||||<�q�q���fdd�|��D�}|�sHtd��g}|tk	�rv|�rftd��ntjdtdd�|D]�\\}}\}}d}
d}
zxtj|tj|d�}
|�r�t|
�|	�r�|
�tjtjd�|
�d	���r�|
�|���r|	�s|� |
|�IdH|}
Wn^tk
�rJ}z |
dk	�r0|
�!�|�"|�W5d}~XYn&|
dk	�rb|
�!��YnX�q|�qz|d
�|�}|�#�}|�$|
||
|�}|j%�r̈�r�t�&d��||�nt�'d�||�z|IdHWn|�!��YnX||fS)zCreate datagram connection.NzA UDP Socket was expected, got )rR�remote_addrr=r?r&rorprqr"css$|]\}}|r|�d|��VqdS)�=Nr)rC�k�vrrrrE�sz9BaseEventLoop.create_datagram_endpoint.<locals>.<genexpr>zKsocket modifier keyword arguments can not be used when sock is specified. (�)Frzunexpected address family)NN�AF_UNIXzstring is expected)r�z2Unable to check or remove stale UNIX socket %r: %rrrWrXcs8g|]0\}}�r|ddks�r,|ddks||f�qS)rNrr)rC�keyZ	addr_pair�rRrrrrr��s�z:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address informationz~Passing `reuse_address=True` is no longer supported, as the usage of SO_REUSEPORT in UDP poses a significant security concern.zdThe *reuse_address* parameter has been deprecated as of 3.5.10 and is scheduled for removal in 3.11.r)�
stacklevelrFz@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))(r>r$r2r%�dictr#�itemsrHr#rwrrr5�stat�S_ISSOCK�os�st_mode�remove�FileNotFoundErrorr(r�errorra�_unsetr�r�rr+r&r'ZSO_BROADCASTrIrNr�r9rdr�r�r%r) rfr�rRrrr=r?r&rorprqr*ZoptsZproblemsZr_addrZaddr_pairs_inforO�errZ
addr_infos�idxreZfamrOZpror�ryrZ
local_addressZremote_addressrWr�r�rnrrzr�create_datagram_endpoint�s$�������
�

��
�
�

����




���z&BaseEventLoop.create_datagram_endpointc
�s\|dd�\}}t|||||f|dd���}	|	dk	r<|	gS|j||||||d�IdHSdS)Nrr,)rAr$)
rfr�r=r>r?r&r�r;r<r%rrrraLs�zBaseEventLoop._ensure_resolvedc�s8|j||f|tj||d�IdH}|s4td|�d���|S)N)r=r>r&r�zgetaddrinfo(z) returned empty list)rar$r1r()rfr;r<r=r&rerrr�_create_server_getaddrinfoXs�z(BaseEventLoop._create_server_getaddrinfor)	r=r&r*r�rQrorpr�r�c	�s�t|t�rtd��|dk	r*|dkr*td��|dk	s<�dk	�r"|dk	rLtd��|	dkrhtjdkoftjdk}	g}
|dkr|dg}n$t|t�s�t|t	j
j�s�|g}n|}����fdd	�|D�}tj
|d
�i�IdH}ttj�|��}d}�z|D�]}|\}}}}}zt�|||�}Wn8tjk
�rH�j�r@tjd|||d
d�Yq�YnX|
�|�|	�rl|�tjtjd
�|
�rzt|�t�r�|tjk�r�ttd��r�|�tj tj!d
�z|�"|�Wq�t#k
�r�}z t#|j$d||j%�&�f�d�W5d}~XYq�Xq�d
}W5|�s|
D]}|���qXn4|dk�r4td��|j'tj(k�rPtd|����|g}
|
D]}|�)d��qZt*�|
||||�}|�r�|�+�tj,d�d�IdH�j�r�t�-d|�|S)a1Create a TCP server.

        The host parameter can be a string, in that case the TCP server is
        bound to host and port.

        The host parameter can also be a sequence of strings and in that case
        the TCP server is bound to all hosts of the sequence. If a host
        appears multiple times (possibly indirectly e.g. when hostnames
        resolve to the same IP address), the server is only bound once to that
        host.

        Return a Server object which can be used to stop the service.

        This method is a coroutine.
        z*ssl argument must be an SSLContext or NoneNrUrV�posix�cygwinr.csg|]}�j|���d��qS))r=r&)r�)rCr;�r=r&r<rfrrr��s�
�z/BaseEventLoop.create_server.<locals>.<listcomp>r�Fz: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 specifiedr`rr�z
%r is serving).rrhr5r%r�r�r�platformrrF�abc�Iterablerr��setrKrLrMr�r$r�r�r�warningr9r&r'ZSO_REUSEADDRr+r8rr#r�ZIPV6_V6ONLYrIr(rLrJrKr>r1rHrr�r�r%)rfr�r;r<r=r&r*r�rQrorpr�r�r�ZhostsZfsreZ	completed�resr@Zsocktyper?Z	canonnameZsar�r�rr�r�
create_server`s�
��
��
�

������
�zBaseEventLoop.create_server)rQr�c�sv|jtjkrtd|����|dk	r.|s.td��|j|||dd|d�IdH\}}|jrn|�d�}t�d|||�||fS)	aHandle an accepted connection.

        This is used by servers that accept connections outside of
        asyncio but that use asyncio to handle connections.

        This method is a coroutine.  When completed, the coroutine
        returns a (transport, protocol) pair.
        r`NrUr.T)r�r�r$z%r handled: (%r, %r))	r>r$r1r%rcr�rdrr)rfr�r*rQr�rnr�rrr�connect_accepted_socket�s$��
z%BaseEventLoop.connect_accepted_socketc�sd|�}|��}|�|||�}z|IdHWn|���YnX|jr\t�d|��||�||fS)Nz Read pipe %r connected: (%r, %r))rdr�r�r�rr�fileno�rfr�r�r�r�rnrrr�connect_read_pipe�s�zBaseEventLoop.connect_read_pipec�sd|�}|��}|�|||�}z|IdHWn|���YnX|jr\t�d|��||�||fS)Nz!Write pipe %r connected: (%r, %r))rdr�r�r�rrr�r�rrr�connect_write_pipes�z BaseEventLoop.connect_write_pipecCs�|g}|dk	r"|�dt|����|dk	rJ|tjkrJ|�dt|����n8|dk	rf|�dt|����|dk	r�|�dt|����t�d�|��dS)Nzstdin=zstdout=stderr=zstdout=zstderr=� )r9r!rrrrr#)rfr'r�r�r�r%rrr�_log_subprocessszBaseEventLoop._log_subprocess)	r�r�r��universal_newlinesr�r��encoding�errors�textc	�s�t|ttf�std��|r"td��|s.td��|dkr>td��|rJtd��|	dk	rZtd��|
dk	rjtd��|�}
d}|jr�d	|}|�||||�|j|
|d
||||f|�IdH}|jr�|dk	r�t�d||�||
fS)Nzcmd must be a string� universal_newlines must be Falsezshell must be Truer�bufsize must be 0�text must be False�encoding must be None�errors must be Nonezrun shell command %rT�%s: %r)	rr3rr%r�r�r�rr%)rfr��cmdr�r�r�r�r�r�r�r�r�r�r��	debug_logrnrrr�subprocess_shellsB��
zBaseEventLoop.subprocess_shellc	�s�|rtd��|rtd��|dkr(td��|r4td��|	dk	rDtd��|
dk	rTtd��|f|}|�}d}|jr�d|��}|�||||�|j||d	||||f|
�IdH}|jr�|dk	r�t�d
||�||fS)Nr�zshell must be Falserr�r�r�r�zexecute program Fr�)r%r�r�r�rr%)rfr�Zprogramr�r�r�r�r�r�r�r�r�r�r�Z
popen_argsr�r�rnrrr�subprocess_execCs@

��
zBaseEventLoop.subprocess_execcCs|jS)zKReturn an exception handler, or None if the default one is in use.
        )r�rqrrr�get_exception_handleresz#BaseEventLoop.get_exception_handlercCs(|dk	rt|�std|����||_dS)a�Set handler as the new event loop exception handler.

        If handler is None, the default exception handler will
        be set.

        If handler is a callable object, it should have a
        signature matching '(loop, context)', where 'loop'
        will be a reference to the active event loop, 'context'
        will be a dict object (see `call_exception_handler()`
        documentation for details about context).
        Nz+A callable object or None is expected, got )r�r5r�)rfZhandlerrrr�set_exception_handlerjsz#BaseEventLoop.set_exception_handlerc	Cs|�d�}|sd}|�d�}|dk	r6t|�||jf}nd}d|kr`|jdk	r`|jjr`|jj|d<|g}t|�D]�}|dkr|qn||}|dkr�d	�t�|��}d
}||�	�7}n2|dkr�d	�t�|��}d}||�	�7}nt
|�}|�|�d|���qntj
d
�|�|d�dS)aEDefault exception handler.

        This is called when an exception occurs and no exception
        handler is set, and can be called by a custom exception
        handler that wants to defer to the default behavior.

        This default handler logs the error message and other
        context-dependent information.  In debug mode, a truncated
        stack trace is also appended showing where the given object
        (e.g. a handle or future or task) was created, if any.

        The context parameter has the same meaning as in
        `call_exception_handler()`.
        r�z!Unhandled exception in event looprRNFZsource_tracebackZhandle_traceback>r�rRr.z+Object created at (most recent call last):
z+Handle created at (most recent call last):
rG�
r�)�getr>�
__traceback__r�r��sortedr#�	traceback�format_list�rstriprr9rr�)	rfrr�rRr�Z	log_linesry�value�tbrrr�default_exception_handler{s<

���z'BaseEventLoop.default_exception_handlercCs�|jdkrVz|�|�Wq�ttfk
r2�Yq�tk
rRtjddd�Yq�Xn�z|�||�Wn�ttfk
r��Ynttk
r�}zVz|�d||d��Wn:ttfk
r��Yn"tk
r�tjddd�YnXW5d}~XYnXdS)aDCall the current event loop's exception handler.

        The context argument is a dict containing the following keys:

        - 'message': Error message;
        - 'exception' (optional): Exception object;
        - 'future' (optional): Future instance;
        - 'task' (optional): Task instance;
        - 'handle' (optional): Handle instance;
        - 'protocol' (optional): Protocol instance;
        - 'transport' (optional): Transport instance;
        - 'socket' (optional): Socket instance;
        - 'asyncgen' (optional): Asynchronous generator that caused
                                 the exception.

        New keys maybe introduced in the future.

        Note: do not overload this method in an event loop subclass.
        For custom exception handling, use the
        `set_exception_handler()` method.
        Nz&Exception in default exception handlerTr�z$Unhandled error in exception handler)r�rRrzeException in default exception handler while handling an unexpected error in custom exception handler)r�r�rSrTrmrr�)rfrrWrrrr��s4
���z$BaseEventLoop.call_exception_handlercCs|jr
dS|j�|�dS)z3Add a Handle to _scheduled (TimerHandle) or _ready.N)�
_cancelledr�r9�rfrrrr�
_add_callback�szBaseEventLoop._add_callbackcCs|�|�|��dS)z6Like _add_callback() but called from a signal handler.N)r�r�r�rrr�_add_callback_signalsafe�s
z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)z3Notification that a TimerHandle has been cancelled.rN)r�r�r�rrr�_timer_handle_cancelled�sz%BaseEventLoop._timer_handle_cancelledc	Cs�t|j�}|tkr`|j|tkr`g}|jD]}|jr<d|_q*|�|�q*t�|�||_d|_n4|jr�|jdjr�|jd8_t�	|j�}d|_q`d}|j
s�|jr�d}n*|jr�|jdj}t
td||���t�}|j�|�}|�|�|��|j}|j�r:|jd}|j|k�r�q:t�	|j�}d|_|j
�|�q�t|j
�}t|�D]|}	|j
��}|j�rf�qL|j�r�zD||_|��}
|��|��|
}||jk�r�t�dt|�|�W5d|_Xn|���qLd}dS)z�Run one full iteration of the event loop.

        This calls all currently ready callbacks, polls for I/O,
        schedules the resulting callbacks, and finally schedules
        'call_later' callbacks.
        FrrNzExecuting %s took %.3f seconds)r�r��_MIN_SCHEDULED_TIMER_HANDLESr��%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr�r9r�heapify�heappopr�r�Z_whenr:�maxr��MAXIMUM_SELECT_TIMEOUTZ	_selectorZselectr�r��range�popleftr�r�Z_runr�rr�r)rfZsched_countZ
new_scheduledrZtimeoutrr�Zend_timeZntodo�ir(r*rrrr�sj
��





�
zBaseEventLoop._run_oncecCsHt|�t|j�krdS|r2t��|_t�tj�nt�|j�||_dSrB)rhr�r�#get_coroutine_origin_tracking_depthr��#set_coroutine_origin_tracking_depthrZDEBUG_STACK_DEPTH�rfZenabledrrrr�Fs���z,BaseEventLoop._set_coroutine_origin_trackingcCs|jSrB)r�rqrrrr�UszBaseEventLoop.get_debugcCs ||_|��r|�|j|�dSrB)r�r�r�r�r�rrrr�XszBaseEventLoop.set_debug)N)N)NNN)NN)NN)N)r)rN)N)NN)FN)rN)NN)NN)Sr|r}r~rhr�rdr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrUr�r�r�r�rr�r�rr
rrrrr�rr r+r$r-r6r0r2r/rPrfrcrkrirjrnr�r�r$r1rar�r6Z
AI_PASSIVEr�r�r�r�r�rrr�r�r�r�r�r�r�r�r�rr�r�r�rrrrr�sF���
�
�
�
�
		&	
	�

�
%���
�/�/���	��w��%�"29Nr)rr)r)7�__doc__rFZcollections.abcZconcurrent.futuresrrYrrKr�r$r~rr�r�r�rr�r�rQ�ImportErrorr.rrrrrrr	r
rrr
�logr�__all__r�r�r#r8r��objectr�rr!r+rArPrXr[ZProtocolr\ZAbstractServerrZAbstractEventLooprrrrr�<module>sd

		
;


DoPK [�T
��__pycache__/log.cpython-38.pycnu�[���U

e5d|�@sdZddlZe�e�ZdS)zLogging configuration.�N)�__doc__ZloggingZ	getLogger�__package__Zlogger�rr�#/usr/lib64/python3.8/asyncio/log.py�<module>sPK [)��(&(&&__pycache__/locks.cpython-38.opt-2.pycnu�[���U

e5d|C�@s�dZddlZddlZddlZddlmZddlmZddlmZddlmZGdd	�d	�Z	Gd
d�d�Z
Gdd
�d
e
�ZGdd�d�ZGdd�de
�Z
Gdd�de
�ZGdd�de�ZdS))�Lock�Event�	Condition�	Semaphore�BoundedSemaphore�N�)�events)�futures)�
exceptions)�
coroutinesc@s$eZdZdd�Zdd�Zdd�ZdS)�_ContextManagercCs
||_dS�N)�_lock)�self�lock�r�%/usr/lib64/python3.8/asyncio/locks.py�__init__"sz_ContextManager.__init__cCsdSr
r�rrrr�	__enter__%sz_ContextManager.__enter__cGsz|j��W5d|_XdSr
)r�release�r�argsrrr�__exit__*sz_ContextManager.__exit__N)�__name__�
__module__�__qualname__rrrrrrrrsrc@sReZdZdd�Zdd�Zejdd��Zej	e_	dd�Z
d	d
�Zdd�Zd
d�Z
dS)�_ContextManagerMixincCstd��dS)Nz9"yield from" should be used as context manager expression)�RuntimeErrorrrrrr2s�z_ContextManagerMixin.__enter__cGsdSr
rrrrrr6sz_ContextManagerMixin.__exit__ccs&tjdtdd�|��EdHt|�S)NzD'with (yield from lock)' is deprecated use 'async with lock' instead���
stacklevel)�warnings�warn�DeprecationWarning�acquirerrrrr�__iter__;s�z_ContextManagerMixin.__iter__c�s|��IdHt|�Sr
)r%rrrrrZ
__acquire_ctxUsz"_ContextManagerMixin.__acquire_ctxcCstjdtdd�|����S)Nz='with await lock' is deprecated use 'async with lock' insteadrr )r"r#r$�!_ContextManagerMixin__acquire_ctx�	__await__rrrrr(Ys
�z_ContextManagerMixin.__await__c�s|��IdHdSr
)r%rrrr�
__aenter__`sz_ContextManagerMixin.__aenter__c�s|��dSr
)r)r�exc_type�exc�tbrrr�	__aexit__fsz_ContextManagerMixin.__aexit__N)rrrrr�types�	coroutiner&rZ
_is_coroutiner'r(r)r-rrrrr1s
rcsJeZdZdd�dd�Z�fdd�Zdd�Zd	d
�Zdd�Zd
d�Z�Z	S)rN��loopcCs:d|_d|_|dkr t��|_n||_tjdtdd�dS�NF�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.rr )�_waiters�_lockedr�get_event_loop�_loopr"r#r$�rr1rrrr�s�z
Lock.__init__csLt���}|jrdnd}|jr2|�dt|j���}d|dd��d|�d�S�	N�lockedZunlocked�
, waiters:�<r���� [�]>)�super�__repr__r5r4�len�r�resZextra��	__class__rrrA�s

z
Lock.__repr__cCs|jSr
)r5rrrrr:�szLock.lockedc	�s�|js.|jdks$tdd�|jD��r.d|_dS|jdkrBt��|_|j��}|j�|�z"z|IdHW5|j�|�XWn&t	j
k
r�|js�|���YnXd|_dS)Ncss|]}|��VqdSr
)�	cancelled)�.0�wrrr�	<genexpr>�szLock.acquire.<locals>.<genexpr>T)r5r4�all�collections�dequer7�
create_future�append�remover
�CancelledError�_wake_up_first�r�futrrrr%�s&�


zLock.acquirecCs"|jrd|_|��ntd��dS)NFzLock is not acquired.)r5rRrrrrrr�s
zLock.releasecCsJ|js
dSztt|j��}Wntk
r2YdSX|��sF|�d�dS�NT)r4�next�iter�
StopIteration�done�
set_resultrSrrrrR�szLock._wake_up_first)
rrrrrAr:r%rrR�
__classcell__rrrErrjs6 rcsJeZdZdd�dd�Z�fdd�Zdd�Zd	d
�Zdd�Zd
d�Z�Z	S)rNr0cCs>t��|_d|_|dkr$t��|_n||_tjdt	dd�dSr2)
rLrMr4�_valuerr6r7r"r#r$r8rrrrs
�zEvent.__init__csLt���}|jrdnd}|jr2|�dt|j���}d|dd��d|�d�S)	N�setZunsetr;r<rr=r>r?)r@rAr\r4rBrCrErrrAs

zEvent.__repr__cCs|jSr
�r\rrrr�is_setszEvent.is_setcCs.|js*d|_|jD]}|��s|�d�qdSrU)r\r4rYrZrSrrrr]s

z	Event.setcCs
d|_dS)NFr^rrrr�clear"szEvent.clearc	�sF|jr
dS|j��}|j�|�z|IdHW�dS|j�|�XdSrU)r\r7rNr4rOrPrSrrr�wait(s

z
Event.wait)
rrrrrAr_r]r`rar[rrrErr�s	rcsNeZdZddd�dd�Z�fdd�Zdd�Zd	d
�Zddd
�Zdd�Z�Z	S)rNr0cCs~|dkrt��|_n||_tjdtdd�|dkr>t|d�}n|j|jk	rRtd��||_|j	|_	|j
|_
|j|_t�
�|_dS)Nr3rr r0z"loop argument must agree with lock)rr6r7r"r#r$r�
ValueErrorrr:r%rrLrMr4)rrr1rrrrEs �zCondition.__init__csNt���}|��rdnd}|jr4|�dt|j���}d|dd��d|�d�Sr9)r@rAr:r4rBrCrErrrA[s

zCondition.__repr__c�s�|��std��|��z@|j��}|j�	|�z|IdHW�W�dS|j�
|�XW5d}z|��IdHWq�Wq^tjk
r�d}Yq^Xq^|r�tj�XdS)Nzcannot wait on un-acquired lockFT)r:rrr%r
rQr7rNr4rOrP)rrGrTrrrrabs$

zCondition.waitc�s$|�}|s |��IdH|�}q|Sr
)ra)rZ	predicate�resultrrr�wait_for�s
zCondition.wait_forrcCsJ|��std��d}|jD]*}||kr*qF|��s|d7}|�d�qdS)Nz!cannot notify on un-acquired lockrrF)r:rr4rYrZ)r�n�idxrTrrr�notify�s
zCondition.notifycCs|�t|j��dSr
)rgrBr4rrrr�
notify_all�szCondition.notify_all)N)r)
rrrrrArardrgrhr[rrrErr;s
%
rcsLeZdZddd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z�Z	S)rrNr0cCsN|dkrtd��||_t��|_|dkr4t��|_n||_tj	dt
dd�dS)Nrz$Semaphore initial value must be >= 0r3rr )rbr\rLrMr4rr6r7r"r#r$�r�valuer1rrrr�s
�zSemaphore.__init__csVt���}|��rdn
d|j��}|jr<|�dt|j���}d|dd��d|�d�S)	Nr:zunlocked, value:r;r<rr=r>r?)r@rAr:r\r4rBrCrErrrA�s

zSemaphore.__repr__cCs,|jr(|j��}|��s|�d�dSqdSr
)r4�popleftrYrZ)rZwaiterrrr�
_wake_up_next�s


zSemaphore._wake_up_nextcCs
|jdkS)Nrr^rrrrr:�szSemaphore.lockedc�st|jdkrb|j��}|j�|�z|IdHWq|��|jdkrX|��sX|���YqXq|jd8_dS)NrrT)r\r7rNr4rOZcancelrGrlrSrrrr%�s	


zSemaphore.acquirecCs|jd7_|��dS)Nr)r\rlrrrrr�szSemaphore.release)r)
rrrrrArlr:r%rr[rrrErr�s
rcs0eZdZddd��fdd�Z�fdd�Z�ZS)	rrNr0cs.|rtjdtdd�||_t�j||d�dS)Nr3rr r0)r"r#r$�_bound_valuer@rrirErrr
s�zBoundedSemaphore.__init__cs"|j|jkrtd��t���dS)Nz(BoundedSemaphore released too many times)r\rmrbr@rrrErrrszBoundedSemaphore.release)r)rrrrrr[rrrErrs	r)�__all__rLr.r"�rr	r
rrrrrrrrrrrr�<module>s"9DzNPK [��X6GG*__pycache__/constants.cpython-38.opt-1.pycnu�[���U

e5dx�@s2ddlZdZdZdZdZdZGdd�dej�ZdS)	�N���
gN@ic@s$eZdZe��Ze��Ze��ZdS)�
_SendfileModeN)�__name__�
__module__�__qualname__�enum�autoZUNSUPPORTEDZ
TRY_NATIVEZFALLBACK�rr�)/usr/lib64/python3.8/asyncio/constants.pyrsr)r	Z!LOG_THRESHOLD_FOR_CONNLOST_WRITESZACCEPT_RETRY_DELAYZDEBUG_STACK_DEPTHZSSL_HANDSHAKE_TIMEOUTZ!SENDFILE_FALLBACK_READBUFFER_SIZE�Enumrrrrr�<module>sPK [���
		)__pycache__/format_helpers.cpython-38.pycnu�[���U

e5dd	�@sdddlZddlZddlZddlZddlZddlmZdd�Zdd�Zdd	�Z	ddd�Z
dd
d�ZdS)�N�)�	constantscCsVt�|�}t�|�r&|j}|j|jfSt|tj�r<t	|j
�St|tj�rRt	|j
�SdS�N)�inspectZunwrapZ
isfunction�__code__�co_filename�co_firstlineno�
isinstance�	functools�partial�_get_function_source�func�
partialmethod)r
�code�r�./usr/lib64/python3.8/asyncio/format_helpers.pyr
s



rcCs8t||d�}t|�}|r4|d|d�d|d��7}|S)Nz at r�:r)�_format_callbackr)r
�args�	func_repr�sourcerrr�_format_callback_sources
rcCsHg}|r|�dd�|D��|r8|�dd�|��D��d�d�|��S)z�Format function arguments and keyword arguments.

    Special case for a single parameter: ('hello',) is formatted as ('hello').
    css|]}t�|�VqdSr��reprlib�repr)�.0�argrrr�	<genexpr>&sz*_format_args_and_kwargs.<locals>.<genexpr>css&|]\}}|�dt�|���VqdS)�=Nr)r�k�vrrrr(sz({})z, )�extend�items�format�join)r�kwargsr"rrr�_format_args_and_kwargssr&�cCs�t|tj�r.t||�|}t|j|j|j|�St|d�rF|j	rF|j	}n t|d�r^|j
r^|j
}nt|�}|t||�7}|r�||7}|S)N�__qualname__�__name__)r	r
rr&rr
r�keywords�hasattrr(r)r)r
rr%�suffixrrrrr,srcCsD|dkrt��j}|dkr tj}tjjt�|�|dd�}|�	�|S)zlReplacement for traceback.extract_stack() that only does the
    necessary work for asyncio debug mode.
    NF)�limit�lookup_lines)
�sys�	_getframe�f_backrZDEBUG_STACK_DEPTH�	traceback�StackSummary�extract�
walk_stack�reverse)�fr-�stackrrr�
extract_stack>s
�r9)r')NN)r
rrr/r2r'rrrr&rr9rrrr�<module>s
PK [����+__pycache__/subprocess.cpython-38.opt-1.pycnu�[���U

e5d��@s�dZddlZddlZddlmZddlmZddlmZddlmZddlm	Z	ej
Z
ejZejZGd	d
�d
ej
ej�ZGdd�d�Zddddejfd
d�Zddddejd�dd�ZdS))�create_subprocess_exec�create_subprocess_shell�N�)�events)�	protocols)�streams)�tasks)�loggercsXeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Z�ZS)�SubprocessStreamProtocolz0Like StreamReaderProtocol, but for a subprocess.csHt�j|d�||_d|_|_|_d|_d|_g|_|j	�
�|_dS)N��loopF)�super�__init__�_limit�stdin�stdout�stderr�
_transport�_process_exited�	_pipe_fds�_loopZ
create_future�
_stdin_closed)�self�limitr��	__class__��*/usr/lib64/python3.8/asyncio/subprocess.pyrsz!SubprocessStreamProtocol.__init__cCsn|jjg}|jdk	r&|�d|j���|jdk	rB|�d|j���|jdk	r^|�d|j���d�d�|��S)Nzstdin=zstdout=zstderr=z<{}>� )r�__name__r�appendrr�format�join)r�inforrr�__repr__s



z!SubprocessStreamProtocol.__repr__cCs�||_|�d�}|dk	rDtj|j|jd�|_|j�|�|j�	d�|�d�}|dk	r�tj|j|jd�|_
|j
�|�|j�	d�|�d�}|dk	r�tj||d|jd�|_dS)Nr�rr�r)�protocol�readerr)
r�get_pipe_transportr�StreamReaderrrrZ
set_transportrr r�StreamWriterr)r�	transportZstdout_transportZstderr_transportZstdin_transportrrr�connection_made)s,
�
�
�z(SubprocessStreamProtocol.connection_madecCs:|dkr|j}n|dkr |j}nd}|dk	r6|�|�dS)Nrr&)rrZ	feed_data)r�fd�datar(rrr�pipe_data_receivedAsz+SubprocessStreamProtocol.pipe_data_receivedcCs�|dkrN|j}|dk	r|��|�|�|dkr>|j�d�n|j�|�dS|dkr^|j}n|dkrn|j}nd}|dk	r�|dkr�|��n
|�|�||j	kr�|j	�
|�|��dS)Nrrr&)r�closeZconnection_lostrZ
set_resultZ
set_exceptionrrZfeed_eofr�remove�_maybe_close_transport)rr.�exc�piper(rrr�pipe_connection_lostKs*



z-SubprocessStreamProtocol.pipe_connection_lostcCsd|_|��dS)NT)rr3�rrrr�process_exitedfsz'SubprocessStreamProtocol.process_exitedcCs(t|j�dkr$|jr$|j��d|_dS)Nr)�lenrrrr1r7rrrr3js
z/SubprocessStreamProtocol._maybe_close_transportcCs||jkr|jSdS�N)rr)r�streamrrr�_get_close_waiteros
z*SubprocessStreamProtocol._get_close_waiter)
r�
__module__�__qualname__�__doc__rr$r-r0r6r8r3r<�
__classcell__rrrrr
s	

r
c@sjeZdZdd�Zdd�Zedd��Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
ddd�ZdS)�ProcesscCs8||_||_||_|j|_|j|_|j|_|��|_dSr:)rZ	_protocolrrrrZget_pid�pid)rr,r'rrrrruszProcess.__init__cCsd|jj�d|j�d�S)N�<r�>)rrrBr7rrrr$~szProcess.__repr__cCs
|j��Sr:)rZget_returncoder7rrr�
returncode�szProcess.returncodec�s|j��IdHS)z?Wait until the process exit and return the process return code.N)rZ_waitr7rrr�wait�szProcess.waitcCs|j�|�dSr:)r�send_signal)r�signalrrrrG�szProcess.send_signalcCs|j��dSr:)r�	terminater7rrrrI�szProcess.terminatecCs|j��dSr:)r�killr7rrrrJ�szProcess.killc
�s�|j��}|j�|�|r,t�d|t|��z|j��IdHWn8tt	fk
rx}z|rht�d||�W5d}~XYnX|r�t�d|�|j�
�dS)Nz%%r communicate: feed stdin (%s bytes)z%r communicate: stdin got %rz%r communicate: close stdin)r�	get_debugr�writer	�debugr9Zdrain�BrokenPipeError�ConnectionResetErrorr1)r�inputrMr4rrr�_feed_stdin�s 
� zProcess._feed_stdinc�sdSr:rr7rrr�_noop�sz
Process._noopc�s�|j�|�}|dkr|j}n|j}|j��rJ|dkr8dnd}t�d||�|��IdH}|j��r�|dkrndnd}t�d||�|�	�|S)Nr&rrrz%r communicate: read %sz%r communicate: close %s)
rr)rrrrKr	rM�readr1)rr.r,r;�name�outputrrr�_read_stream�s

zProcess._read_streamNc�s�|dk	r|�|�}n|��}|jdk	r2|�d�}n|��}|jdk	rP|�d�}n|��}tj||||jd�IdH\}}}|��IdH||fS)Nrr&r)	rQrRrrVrrZgatherrrF)rrPrrrrrr�communicate�s


�zProcess.communicate)N)rr=r>rr$�propertyrErFrGrIrJrQrRrVrWrrrrrAts	
rAc
�sb�dkrt���ntjdtdd���fdd�}�j||f|||d�|��IdH\}}	t||	��S)N�ZThe loop argument is deprecated since Python 3.8 and scheduled for removal in Python 3.10.r&��
stacklevelcst��d�S�Nr%�r
rr%rr�<lambda>�s�z)create_subprocess_shell.<locals>.<lambda>�rrr)r�get_event_loop�warnings�warn�DeprecationWarningZsubprocess_shellrA)
�cmdrrrrr�kwds�protocol_factoryr,r'rr%rr�s$
����r)rrrrrc�sf�dkrt���ntjdtdd���fdd�}�j||f|�|||d�|��IdH\}	}
t|	|
��S)NrYr&rZcst��d�Sr\r]rr%rrr^�s�z(create_subprocess_exec.<locals>.<lambda>r_)rr`rarbrcZsubprocess_execrA)Zprogramrrrrr�argsrerfr,r'rr%rr�s(
�����r)�__all__�
subprocessra�rrrr�logr	�PIPEZSTDOUTZDEVNULLZFlowControlMixinZSubprocessProtocolr
rAZ_DEFAULT_LIMITrrrrrr�<module>s.�bV�
�PK [��X6GG$__pycache__/constants.cpython-38.pycnu�[���U

e5dx�@s2ddlZdZdZdZdZdZGdd�dej�ZdS)	�N���
gN@ic@s$eZdZe��Ze��Ze��ZdS)�
_SendfileModeN)�__name__�
__module__�__qualname__�enum�autoZUNSUPPORTEDZ
TRY_NATIVEZFALLBACK�rr�)/usr/lib64/python3.8/asyncio/constants.pyrsr)r	Z!LOG_THRESHOLD_FOR_CONNLOST_WRITESZACCEPT_RETRY_DELAYZDEBUG_STACK_DEPTHZSSL_HANDSHAKE_TIMEOUTZ!SENDFILE_FALLBACK_READBUFFER_SIZE�Enumrrrrr�<module>sPK [k*�	�	+__pycache__/exceptions.cpython-38.opt-1.pycnu�[���U

e5da�@sldZdZGdd�de�ZGdd�de�ZGdd�de�ZGdd	�d	e�ZGd
d�de	�Z
Gdd
�d
e�ZdS)zasyncio exceptions.)�CancelledError�InvalidStateError�TimeoutError�IncompleteReadError�LimitOverrunError�SendfileNotAvailableErrorc@seZdZdZdS)rz!The Future or Task was cancelled.N��__name__�
__module__�__qualname__�__doc__�rr�*/usr/lib64/python3.8/asyncio/exceptions.pyr	src@seZdZdZdS)rz*The operation exceeded the given deadline.Nrrrrr
r
src@seZdZdZdS)rz+The operation is not allowed in this state.Nrrrrr
rsrc@seZdZdZdS)rz~Sendfile syscall is not available.

    Raised if OS does not support sendfile syscall for given socket or
    file type.
    Nrrrrr
rsrcs(eZdZdZ�fdd�Zdd�Z�ZS)rz�
    Incomplete read error. Attributes:

    - partial: read bytes string before the end of stream was reached
    - expected: total number of expected bytes (or None if unknown)
    cs@|dkrdnt|�}t��t|��d|�d��||_||_dS)NZ	undefinedz bytes read on a total of z expected bytes)�repr�super�__init__�len�partial�expected)�selfrrZ
r_expected��	__class__rr
r$szIncompleteReadError.__init__cCst|�|j|jffS�N)�typerr�rrrr
�
__reduce__+szIncompleteReadError.__reduce__�rr	r
rrr�
__classcell__rrrr
rsrcs(eZdZdZ�fdd�Zdd�Z�ZS)rz�Reached the buffer limit while looking for a separator.

    Attributes:
    - consumed: total number of to be consumed bytes.
    cst��|�||_dSr)rr�consumed)r�messagerrrr
r5szLimitOverrunError.__init__cCst|�|jd|jffS)N�)r�argsrrrrr
r9szLimitOverrunError.__reduce__rrrrr
r/srN)r�__all__�
BaseExceptionr�	Exceptionrr�RuntimeErrorr�EOFErrorrrrrrr
�<module>sPK [��X6GG*__pycache__/constants.cpython-38.opt-2.pycnu�[���U

e5dx�@s2ddlZdZdZdZdZdZGdd�dej�ZdS)	�N���
gN@ic@s$eZdZe��Ze��Ze��ZdS)�
_SendfileModeN)�__name__�
__module__�__qualname__�enum�autoZUNSUPPORTEDZ
TRY_NATIVEZFALLBACK�rr�)/usr/lib64/python3.8/asyncio/constants.pyrsr)r	Z!LOG_THRESHOLD_FOR_CONNLOST_WRITESZACCEPT_RETRY_DELAYZDEBUG_STACK_DEPTHZSSL_HANDSHAKE_TIMEOUTZ!SENDFILE_FALLBACK_READBUFFER_SIZE�Enumrrrrr�<module>sPK [��yy(__pycache__/windows_utils.cpython-38.pycnu�[���U

e5d��@s�dZddlZejdkred��ddlZddlZddlZddlZddlZddl	Z	ddl
Z
dZdZej
Z
ejZe��Zdded	�d
d�ZGdd
�d
�ZGdd�dej�ZdS)z)Various Windows specific bits and pieces.�NZwin32z
win32 only)�pipe�Popen�PIPE�
PipeHandlei F)TT)�duplex�
overlapped�bufsizec
Cs$tjd�t��tt��d�}|r>tj}tj	tj
B}||}}ntj}tj
}d|}}|tjO}|drp|tj
O}|dr�tj
}nd}d}	}
z\t�||tjd||tjtj�}	t�||dtjtj|tj�}
tj|	dd�}|�d�|	|
fWS|	dk	�rt�|	�|
dk	�rt�|
��YnXdS)zELike os.pipe() but with overlapped support and using handles not fds.z\\.\pipe\python-pipe-{:d}-{:d}-)�prefixr�NT�r)�tempfileZmktemp�format�os�getpid�next�
_mmap_counter�_winapiZPIPE_ACCESS_DUPLEXZGENERIC_READZ
GENERIC_WRITEZPIPE_ACCESS_INBOUNDZFILE_FLAG_FIRST_PIPE_INSTANCEZFILE_FLAG_OVERLAPPEDZCreateNamedPipeZ	PIPE_WAITZNMPWAIT_WAIT_FOREVERZNULLZ
CreateFileZ
OPEN_EXISTINGZConnectNamedPipeZGetOverlappedResult�CloseHandle)rrrZaddressZopenmode�accessZobsizeZibsizeZflags_and_attribsZh1Zh2Zov�r�-/usr/lib64/python3.8/asyncio/windows_utils.pyr sb��


��





rc@sbeZdZdZdd�Zdd�Zedd��Zdd	�Ze	j
d
�dd�Zej
fd
d�Zdd�Zdd�ZdS)rz�Wrapper for an overlapped pipe handle which is vaguely file-object like.

    The IOCP event loop can use these instead of socket objects.
    cCs
||_dS�N��_handle��self�handlerrr�__init__VszPipeHandle.__init__cCs2|jdk	rd|j��}nd}d|jj�d|�d�S)Nzhandle=�closed�<� �>)r�	__class__�__name__rrrr�__repr__Ys
zPipeHandle.__repr__cCs|jSrr�rrrrr`szPipeHandle.handlecCs|jdkrtd��|jS)NzI/O operation on closed pipe)r�
ValueErrorr%rrr�filenods
zPipeHandle.fileno)rcCs|jdk	r||j�d|_dSrr)rrrrr�closeis

zPipeHandle.closecCs*|jdk	r&|d|��t|d�|��dS)Nz	unclosed )�source)r�ResourceWarningr()rZ_warnrrr�__del__ns
zPipeHandle.__del__cCs|Srrr%rrr�	__enter__sszPipeHandle.__enter__cCs|��dSr)r()r�t�v�tbrrr�__exit__vszPipeHandle.__exit__N)r#�
__module__�__qualname__�__doc__rr$�propertyrr'rrr(�warnings�warnr+r,r0rrrrrQs
rcs"eZdZdZd�fdd�	Z�ZS)rz�Replacement for subprocess.Popen using overlapped pipe handles.

    The stdin, stdout, stderr are None or instances of PipeHandle.
    Nc	s�|�d�rt�|�dd�dks"t�d}}}d}	}
}|tkrbtddd�\}}	t�|tj�}n|}|tkr�tdd�\}
}
t�|
d�}n|}|tkr�tdd�\}}t�|d�}n|tkr�|}n|}z�z t
�j|f|||d	�|��Wn0|	|
|fD]}|dk	r�t�
|�q��Yn>X|	dk	�r,t|	�|_|
dk	�r@t|
�|_|dk	�rTt|�|_W5|tk�rlt�	|�|tk�r�t�	|�|tk�r�t�	|�XdS)
NZuniversal_newlinesrr)FTT)rr)TFr)�stdin�stdout�stderr)�get�AssertionErrorrr�msvcrtZopen_osfhandler�O_RDONLY�STDOUTr(�superrrrrr7r8r9)r�argsr7r8r9�kwdsZ	stdin_rfdZ
stdout_wfdZ
stderr_wfdZstdin_whZ	stdout_rhZ	stderr_rhZstdin_rhZ	stdout_whZ	stderr_wh�h�r"rrr�sR��










zPopen.__init__)NNN)r#r1r2r3r�
__classcell__rrrCrr}sr)r3�sys�platform�ImportErrorr�	itertoolsr<r�
subprocessrr5�__all__ZBUFSIZErr>�countrrrrrrrr�<module>s$
1,PK [�Ŀ � !__pycache__/queues.cpython-38.pycnu�[���U

e5d �@s�dZddlZddlZddlZddlmZddlmZGdd�de�ZGdd	�d	e�Z	Gd
d�d�Z
Gdd
�d
e
�ZGdd�de
�ZdS))�Queue�
PriorityQueue�	LifoQueue�	QueueFull�
QueueEmpty�N�)�events)�locksc@seZdZdZdS)rz;Raised when Queue.get_nowait() is called on an empty Queue.N��__name__�
__module__�__qualname__�__doc__�rr�&/usr/lib64/python3.8/asyncio/queues.pyrsrc@seZdZdZdS)rzDRaised when the Queue.put_nowait() method is called on a full Queue.Nr
rrrrrsrc@s�eZdZdZd)dd�dd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Ze
dd��Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�ZdS)*raA queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "await put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded asyncio application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    rN��loopcCsp|dkrt��|_n||_tjdtdd�||_t��|_	t��|_
d|_tj
|d�|_|j��|�|�dS)Nz[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.�)�
stacklevelrr)rZget_event_loop�_loop�warnings�warn�DeprecationWarning�_maxsize�collections�deque�_getters�_putters�_unfinished_tasksr	ZEvent�	_finished�set�_init)�self�maxsizerrrr�__init__!s�


zQueue.__init__cCst��|_dS�N)rr�_queue�r"r#rrrr!6szQueue._initcCs
|j��Sr%)r&�popleft�r"rrr�_get9sz
Queue._getcCs|j�|�dSr%�r&�append�r"�itemrrr�_put<sz
Queue._putcCs&|r"|��}|��s|�d�q"qdSr%)r(ZdoneZ
set_result)r"�waitersZwaiterrrr�_wakeup_nextAs

zQueue._wakeup_nextcCs(dt|�j�dt|�d�d|���d�S)N�<z at z#x� �>)�typer�id�_formatr)rrr�__repr__IszQueue.__repr__cCsdt|�j�d|���d�S)Nr2r3r4)r5rr7r)rrr�__str__Lsz
Queue.__str__cCs~d|j��}t|dd�r,|dt|j���7}|jrH|dt|j��d�7}|jrd|dt|j��d�7}|jrz|d|j��7}|S)Nzmaxsize=r&z _queue=z
 _getters[�]z
 _putters[z tasks=)r�getattr�listr&r�lenrr)r"�resultrrrr7Osz
Queue._formatcCs
t|j�S)zNumber of items in the queue.)r=r&r)rrr�qsize[szQueue.qsizecCs|jS)z%Number of items allowed in the queue.)rr)rrrr#_sz
Queue.maxsizecCs|jS)z3Return True if the queue is empty, False otherwise.�r&r)rrr�emptydszQueue.emptycCs |jdkrdS|��|jkSdS)z�Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        rFN)rr?r)rrr�fullhs
z
Queue.fullc�s�|��r�|j��}|j�|�z|IdHWq|��z|j�|�Wntk
r`YnX|��s~|��s~|�	|j��YqXq|�
|�S)z�Put an item into the queue.

        Put an item into the queue. If the queue is full, wait until a free
        slot is available before adding item.
        N)rBr�
create_futurerr,�cancel�remove�
ValueError�	cancelledr1�
put_nowait)r"r.Zputterrrr�putss

z	Queue.putcCs>|��rt�|�|�|jd7_|j��|�|j�dS)zyPut an item into the queue without blocking.

        If no free slot is immediately available, raise QueueFull.
        rN)rBrr/rr�clearr1rr-rrrrH�s

zQueue.put_nowaitc�s�|��r�|j��}|j�|�z|IdHWq|��z|j�|�Wntk
r`YnX|��s~|��s~|�	|j��YqXq|�
�S)zoRemove and return an item from the queue.

        If queue is empty, wait until an item is available.
        N)rArrCrr,rDrErFrGr1�
get_nowait)r"�getterrrr�get�s

z	Queue.getcCs$|��rt�|��}|�|j�|S)z�Remove and return an item from the queue.

        Return an item if one is immediately available, else raise QueueEmpty.
        )rArr*r1rr-rrrrK�s
zQueue.get_nowaitcCs8|jdkrtd��|jd8_|jdkr4|j��dS)a$Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).

        Raises ValueError if called more times than there were items placed in
        the queue.
        rz!task_done() called too many timesrN)rrFrr r)rrr�	task_done�s


zQueue.task_donec�s|jdkr|j��IdHdS)aBlock until all items in the queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer calls task_done() to
        indicate that the item was retrieved and all work on it is complete.
        When the count of unfinished tasks drops to zero, join() unblocks.
        rN)rr�waitr)rrr�join�s
z
Queue.join)r)rrr
rr$r!r*r/r1r8r9r7r?�propertyr#rArBrIrHrMrKrNrPrrrrrs(
rc@s4eZdZdZdd�Zejfdd�Zejfdd�Z	dS)	rz�A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    cCs
g|_dSr%r@r'rrrr!�szPriorityQueue._initcCs||j|�dSr%r@)r"r.�heappushrrrr/�szPriorityQueue._putcCs
||j�Sr%r@)r"�heappoprrrr*�szPriorityQueue._getN)
rrr
rr!�heapqrRr/rSr*rrrrr�src@s(eZdZdZdd�Zdd�Zdd�ZdS)	rzEA subclass of Queue that retrieves most recently added entries first.cCs
g|_dSr%r@r'rrrr!�szLifoQueue._initcCs|j�|�dSr%r+r-rrrr/�szLifoQueue._putcCs
|j��Sr%)r&�popr)rrrr*�szLifoQueue._getN)rrr
rr!r/r*rrrrr�sr)
�__all__rrTr�rr	�	Exceptionrrrrrrrrr�<module>sKPK [�]������&__pycache__/unix_events.cpython-38.pycnu�[���U

e5dۿ�@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
mZddl
mZddl
mZddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddl
mZdd
l
mZddlmZdZe
jdkr�ed��dd�ZGdd�dej�ZGdd�dej �Z!Gdd�dej"ej#�Z$Gdd�dej%�Z&Gdd�d�Z'dd�Z(Gd d!�d!e'�Z)Gd"d#�d#e)�Z*Gd$d%�d%e)�Z+Gd&d'�d'e'�Z,Gd(d)�d)e'�Z-Gd*d+�d+ej.�Z/eZ0e/Z1dS),z2Selector event loop for Unix with signal handling.�N�)�base_events)�base_subprocess)�	constants)�
coroutines)�events)�
exceptions)�futures)�selector_events)�tasks)�
transports)�logger)�SelectorEventLoop�AbstractChildWatcher�SafeChildWatcher�FastChildWatcher�MultiLoopChildWatcher�ThreadedChildWatcher�DefaultEventLoopPolicyZwin32z+Signals are not really supported on WindowscCsdS)zDummy signal handler.N�)�signum�framerr�+/usr/lib64/python3.8/asyncio/unix_events.py�_sighandler_noop*srcs�eZdZdZd)�fdd�	Z�fdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
d*dd�Zd+dd�Zd,dd�Z
dd�Zd-ddddd�dd�Zd.dddddd�dd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Z�ZS)/�_UnixSelectorEventLoopzdUnix event loop.

    Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
    Ncst��|�i|_dS�N)�super�__init__�_signal_handlers)�self�selector��	__class__rrr5sz_UnixSelectorEventLoop.__init__csZt���t��s.t|j�D]}|�|�qn(|jrVtjd|�d�t	|d�|j�
�dS)NzClosing the loop z@ on interpreter shutdown stage, skipping signal handlers removal��source)r�close�sys�
is_finalizing�listr�remove_signal_handler�warnings�warn�ResourceWarning�clear�r�sigr!rrr%9s
�z_UnixSelectorEventLoop.closecCs|D]}|sq|�|�qdSr)�_handle_signal)r�datarrrr�_process_self_dataGsz)_UnixSelectorEventLoop._process_self_datac
GsLt�|�st�|�rtd��|�|�|��zt�|j�	��Wn2t
tfk
rt}ztt
|���W5d}~XYnXt�|||d�}||j|<zt�|t�t�|d�Wn�tk
�rF}zz|j|=|j�szt�d�Wn4t
tfk
�r}zt�d|�W5d}~XYnX|jtjk�r4td|�d���n�W5d}~XYnXdS)z�Add a handler for a signal.  UNIX only.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        z3coroutines cannot be used with add_signal_handler()NF����set_wakeup_fd(-1) failed: %s�sig � cannot be caught)rZiscoroutineZiscoroutinefunction�	TypeError�
_check_signalZ
_check_closed�signal�
set_wakeup_fdZ_csock�fileno�
ValueError�OSError�RuntimeError�strrZHandlerr�siginterruptr
�info�errno�EINVAL)rr/�callback�args�exc�handleZnexcrrr�add_signal_handlerNs2
�

z)_UnixSelectorEventLoop.add_signal_handlercCs8|j�|�}|dkrdS|jr*|�|�n
|�|�dS)z2Internal helper that is the actual signal handler.N)r�getZ
_cancelledr)Z_add_callback_signalsafe)rr/rGrrrr0{sz%_UnixSelectorEventLoop._handle_signalc
Cs�|�|�z|j|=Wntk
r,YdSX|tjkr@tj}ntj}zt�||�WnBtk
r�}z$|jtj	kr�t
d|�d���n�W5d}~XYnX|js�zt�d�Wn2ttfk
r�}zt
�d|�W5d}~XYnXdS)zwRemove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        Fr5r6Nr3r4T)r8r�KeyErrorr9�SIGINT�default_int_handler�SIG_DFLr=rBrCr>r:r<r
rA)rr/�handlerrFrrrr)�s(

z,_UnixSelectorEventLoop.remove_signal_handlercCs6t|t�std|����|t��kr2td|����dS)z�Internal helper to validate a signal.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        zsig must be an int, not zinvalid signal number N)�
isinstance�intr7r9�
valid_signalsr<r.rrrr8�s
z$_UnixSelectorEventLoop._check_signalcCst|||||�Sr)�_UnixReadPipeTransport�r�pipe�protocol�waiter�extrarrr�_make_read_pipe_transport�sz0_UnixSelectorEventLoop._make_read_pipe_transportcCst|||||�Sr)�_UnixWritePipeTransportrSrrr�_make_write_pipe_transport�sz1_UnixSelectorEventLoop._make_write_pipe_transportc	

�s�t����}
|
��std��|��}t||||||||f||d�|	��}|
�|��|j|�z|IdHWnDt	t
fk
r��Yn,tk
r�|��|�
�IdH�YnXW5QRX|S)NzRasyncio.get_child_watcher() is not activated, subprocess support is not installed.)rVrW)r�get_child_watcher�	is_activer>�
create_future�_UnixSubprocessTransport�add_child_handlerZget_pid�_child_watcher_callback�
SystemExit�KeyboardInterrupt�
BaseExceptionr%Z_wait)
rrUrE�shell�stdin�stdout�stderr�bufsizerW�kwargs�watcherrV�transprrr�_make_subprocess_transport�s8

���
�z1_UnixSelectorEventLoop._make_subprocess_transportcCs|�|j|�dSr)�call_soon_threadsafeZ_process_exited)r�pid�
returncoderkrrrr`�sz._UnixSelectorEventLoop._child_watcher_callback)�ssl�sock�server_hostname�ssl_handshake_timeoutc	�s |dkst|t�st�|r,|dkrLtd��n |dk	r<td��|dk	rLtd��|dk	r�|dk	rdtd��t�|�}t�tjtjd�}z |�	d�|�
||�IdHWq�|���Yq�Xn@|dkr�td��|jtjks�|j
tjkr�td|����|�	d�|j|||||d	�IdH\}}||fS)
Nz/you have to pass server_hostname when using sslz+server_hostname is only meaningful with ssl�1ssl_handshake_timeout is only meaningful with ssl�3path and sock can not be specified at the same timerFzno path and sock were specified�.A UNIX Domain Stream Socket was expected, got )rs)rOr?�AssertionErrorr<�os�fspath�socket�AF_UNIX�SOCK_STREAM�setblockingZsock_connectr%�family�typeZ_create_connection_transport)	r�protocol_factory�pathrprqrrrs�	transportrUrrr�create_unix_connection�sT���



��
�z-_UnixSelectorEventLoop.create_unix_connection�dT)rq�backlogrprs�
start_servingc
�s�t|t�rtd��|dk	r&|s&td��|dk	�rH|dk	r@td��t�|�}t�tjtj�}|ddkr�z t	�
t�	|�j�r�t�|�WnBt
k
r�Yn0tk
r�}zt�d||�W5d}~XYnXz|�|�Wnltk
�r0}	z8|��|	jtjk�rd|�d�}
ttj|
�d�n�W5d}	~	XYn|���YnXn<|dk�rZtd	��|jtjk�sv|jtjk�r�td
|����|�d�t�||g||||�}|�r�|��tjd|d�IdH|S)
Nz*ssl argument must be an SSLContext or Nonertrur)r�z2Unable to check or remove stale UNIX socket %r: %rzAddress z is already in usez-path was not specified, and no sock specifiedrvF)�loop)rO�boolr7r<rxryrzr{r|�stat�S_ISSOCK�st_mode�remove�FileNotFoundErrorr=r
�errorZbindr%rBZ
EADDRINUSEr~rr}rZServerZ_start_servingr�sleep)rr�r�rqr�rprsr��errrF�msgZserverrrr�create_unix_serversn
�
�
�

�
��
�z)_UnixSelectorEventLoop.create_unix_serverc
�s�z
tjWn,tk
r6}zt�d��W5d}~XYnXz|��}Wn2ttjfk
rv}zt�d��W5d}~XYnXzt�|�j	}Wn,t
k
r�}zt�d��W5d}~XYnX|r�|n|}	|	s�dS|��}
|�|
d|||||	d�|
IdHS)Nzos.sendfile() is not availableznot a regular filer)
rx�sendfile�AttributeErrorr�SendfileNotAvailableErrorr;�io�UnsupportedOperation�fstat�st_sizer=r]�_sock_sendfile_native_impl)rrq�file�offset�countrFr;r�Zfsize�	blocksize�futrrr�_sock_sendfile_nativeJs2
��z,_UnixSelectorEventLoop._sock_sendfile_nativec	Cs,|��}	|dk	r|�|�|��r4|�|||�dS|rd||}|dkrd|�|||�|�|�dSzt�|	|||�}
W�nDttfk
r�|dkr�|�	||�|�
|	|j||	||||||�
Y�nbtk
�rj}z�|dk	�r|j
t
jk�rt|�tk	�rtdt
j�}||_|}|dk�rBt�d�}
|�|||�|�|
�n|�|||�|�|�W5d}~XYn�ttfk
�r��Yn�tk
�r�}z|�|||�|�|�W5d}~XYnjX|
dk�r�|�|||�|�|�nD||
7}||
7}|dk�r
|�	||�|�
|	|j||	||||||�
dS)Nrzsocket is not connectedzos.sendfile call failed)r;�
remove_writer�	cancelled�_sock_sendfile_update_fileposZ
set_resultrxr��BlockingIOError�InterruptedError�_sock_add_cancellation_callbackZ
add_writerr�r=rBZENOTCONNr�ConnectionError�	__cause__rr�Z
set_exceptionrarbrc)rr�Z
registered_fdrqr;r�r�r��
total_sent�fdZsentrF�new_excr�rrrr�as�

�


�
��
�

�z1_UnixSelectorEventLoop._sock_sendfile_native_implcCs|dkrt�||tj�dS�Nr)rx�lseek�SEEK_SET)rr;r�r�rrrr��sz4_UnixSelectorEventLoop._sock_sendfile_update_fileposcs��fdd�}|�|�dS)Ncs&|��r"���}|dkr"��|�dS)Nr3)r�r;r�)r�r��rrqrr�cb�szB_UnixSelectorEventLoop._sock_add_cancellation_callback.<locals>.cb)Zadd_done_callback)rr�rqr�rr�rr��sz6_UnixSelectorEventLoop._sock_add_cancellation_callback)N)NN)NN)N)N)N)�__name__�
__module__�__qualname__�__doc__rr%r2rHr0r)r8rXrZrlr`r�r�r�r�r�r��
__classcell__rrr!rr/sH-
 �
�
�
��.��CFrcs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Ze
jfdd�Zddd�Zdd�Zdd�Z�ZS) rRiNcs�t��|�||jd<||_||_|��|_||_d|_d|_	t
�|j�j}t
�|�s�t
�|�s�t
�|�s�d|_d|_d|_td��t
�|jd�|j�|jj|�|j�|jj|j|j�|dk	r�|j�tj|d�dS)NrTFz)Pipe transport is for pipes/sockets only.)rr�_extra�_loop�_piper;�_fileno�	_protocol�_closing�_pausedrxr�r�r��S_ISFIFOr��S_ISCHRr<�set_blocking�	call_soon�connection_made�_add_reader�_read_readyr	�_set_result_unless_cancelled)rr�rTrUrVrW�moder!rrr�s:


���
�z_UnixReadPipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���t|jdd�}|jdk	r�|dk	r�t�	||jt
j�}|r�|�d�q�|�d�n |jdk	r�|�d�n
|�d�d�d	�
|��S)
N�closed�closing�fd=�	_selector�polling�idle�open�<{}>� )r"r�r��appendr�r��getattrr�r
�_test_selector_event�	selectorsZ
EVENT_READ�format�join)rrAr r�rrr�__repr__�s(


�

z_UnixReadPipeTransport.__repr__c
Cs�zt�|j|j�}WnDttfk
r,Yn�tk
rX}z|�|d�W5d}~XYn^X|rl|j�	|�nJ|j
��r�t�
d|�d|_|j
�|j�|j
�|jj�|j
�|jd�dS)Nz"Fatal read error on pipe transport�%r was closed by peerT)rx�readr��max_sizer�r�r=�_fatal_errorr�Z
data_receivedr��	get_debugr
rAr��_remove_readerr�Zeof_received�_call_connection_lost)rr1rFrrrr��s
z"_UnixReadPipeTransport._read_readycCs>|js|jrdSd|_|j�|j�|j��r:t�d|�dS)NTz%r pauses reading)r�r�r�r�r�r�r
�debug�rrrr�
pause_reading�s
z$_UnixReadPipeTransport.pause_readingcCsB|js|jsdSd|_|j�|j|j�|j��r>t�d|�dS)NFz%r resumes reading)	r�r�r�r�r�r�r�r
r�r�rrr�resume_readings
z%_UnixReadPipeTransport.resume_readingcCs
||_dSr�r��rrUrrr�set_protocol
sz#_UnixReadPipeTransport.set_protocolcCs|jSrr�r�rrr�get_protocolsz#_UnixReadPipeTransport.get_protocolcCs|jSr�r�r�rrr�
is_closingsz!_UnixReadPipeTransport.is_closingcCs|js|�d�dSr)r��_closer�rrrr%sz_UnixReadPipeTransport.closecCs,|jdk	r(|d|��t|d�|j��dS�Nzunclosed transport r#�r�r,r%�r�_warnrrr�__del__s
z_UnixReadPipeTransport.__del__�Fatal error on pipe transportcCsZt|t�r4|jtjkr4|j��rLtjd||dd�n|j�||||j	d��|�
|�dS�Nz%r: %sT��exc_info)�message�	exceptionr�rU)rOr=rBZEIOr�r�r
r��call_exception_handlerr�r��rrFr�rrrr�s
�z#_UnixReadPipeTransport._fatal_errorcCs(d|_|j�|j�|j�|j|�dS�NT)r�r�r�r�r�r��rrFrrrr�-sz_UnixReadPipeTransport._closecCs4z|j�|�W5|j��d|_d|_d|_XdSr�r�r%r�r�Zconnection_lostr�rrrr�2s
z,_UnixReadPipeTransport._call_connection_lost)NN)r�)r�r�r�r�rr�r�r�r�r�r�r�r%r*r+r�r�r�r�r�rrr!rrR�s
rRcs�eZdZd%�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zejfdd�Zdd�Zd&dd �Zd'd!d"�Zd#d$�Z�ZS)(rYNc
s�t��||�||jd<||_|��|_||_t�|_d|_	d|_
t�|j�j
}t�|�}t�|�}t�|�}	|s�|s�|	s�d|_d|_d|_td��t�|jd�|j�|jj|�|	s�|r�tj�d�s�|j�|jj|j|j�|dk	r�|j�tj|d�dS)NrTrFz?Pipe transport is only for pipes, sockets and character devicesZaix)rrr�r�r;r�r��	bytearray�_buffer�
_conn_lostr�rxr�r�r�r�r�r�r<r�r�r�r�r&�platform�
startswithr�r�r	r�)
rr�rTrUrVrWr�Zis_charZis_fifoZ	is_socketr!rrr?s:




�
�z _UnixWritePipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���t|jdd�}|jdk	r�|dk	r�t�	||jt
j�}|r�|�d�n
|�d�|��}|�d|���n |jdk	r�|�d�n
|�d�d	�
d
�|��S)Nr�r�r�r�r�r�zbufsize=r�r�r�)r"r�r�r�r�r�r�r�r
r�r�ZEVENT_WRITE�get_write_buffer_sizer�r�)rrAr r�rhrrrr�ds,


�


z _UnixWritePipeTransport.__repr__cCs
t|j�Sr)�lenr�r�rrrr�|sz-_UnixWritePipeTransport.get_write_buffer_sizecCs6|j��rt�d|�|jr*|�t��n|��dS)Nr�)r�r�r
rAr�r��BrokenPipeErrorr�rrrr�s

z#_UnixWritePipeTransport._read_readyc
CsRt|tttf�stt|���t|t�r.t|�}|s6dS|jsB|jrj|jtj	krXt
�d�|jd7_dS|j�s8zt
�|j|�}Wntttfk
r�d}YnZttfk
r��YnBtk
r�}z$|jd7_|�|d�WY�dSd}~XYnX|t|�k�rdS|dk�r&t|�|d�}|j�|j|j�|j|7_|��dS)Nz=pipe closed by peer or os.write(pipe, data) raised exception.rr�#Fatal write error on pipe transport)rO�bytesr��
memoryviewrw�reprr�r�rZ!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningr�rx�writer�r�r�rarbrcr�r�r�Z_add_writer�_write_readyZ_maybe_pause_protocol)rr1�nrFrrrr�s8


z_UnixWritePipeTransport.writec
Cs|jstd��zt�|j|j�}Wn�ttfk
r:Yn�ttfk
rR�Yn�t	k
r�}z6|j�
�|jd7_|j�
|j�|�|d�W5d}~XYnhX|t|j�kr�|j�
�|j�
|j�|��|jr�|j�|j�|�d�dS|dk�r|jd|�=dS)NzData should not be emptyrrr)r�rwrxrr�r�r�rarbrcr-r�r��_remove_writerr�r�Z_maybe_resume_protocolr�r�r�)rrrFrrrr�s,



z$_UnixWritePipeTransport._write_readycCsdSr�rr�rrr�
can_write_eof�sz%_UnixWritePipeTransport.can_write_eofcCsB|jr
dS|jst�d|_|js>|j�|j�|j�|jd�dSr�)	r�r�rwr�r�r�r�r�r�r�rrr�	write_eof�s
z!_UnixWritePipeTransport.write_eofcCs
||_dSrr�r�rrrr��sz$_UnixWritePipeTransport.set_protocolcCs|jSrr�r�rrrr��sz$_UnixWritePipeTransport.get_protocolcCs|jSrr�r�rrrr��sz"_UnixWritePipeTransport.is_closingcCs|jdk	r|js|��dSr)r�r�rr�rrrr%�sz_UnixWritePipeTransport.closecCs,|jdk	r(|d|��t|d�|j��dSr�r�r�rrrr��s
z_UnixWritePipeTransport.__del__cCs|�d�dSr)r�r�rrr�abort�sz_UnixWritePipeTransport.abortr�cCsNt|t�r(|j��r@tjd||dd�n|j�||||jd��|�|�dSr�)	rOr=r�r�r
r�r�r�r�r�rrrr��s

�z$_UnixWritePipeTransport._fatal_errorcCsFd|_|jr|j�|j�|j��|j�|j�|j�|j|�dSr�)	r�r�r�r	r�r-r�r�r�r�rrrr��s
z_UnixWritePipeTransport._closecCs4z|j�|�W5|j��d|_d|_d|_XdSrr�r�rrrr��s
z-_UnixWritePipeTransport._call_connection_lost)NN)r�)N)r�r�r�rr�r�r�rrr
rr�r�r�r%r*r+r�rr�r�r�r�rrr!rrY<s"%	#	

rYc@seZdZdd�ZdS)r^c		Ks�d}|tjkrt��\}}zPtj|f||||d|d�|��|_|dk	rh|��t|��d|d�|j_	d}W5|dk	r�|��|��XdS)NF)rdrerfrgZuniversal_newlinesrh�wb)�	buffering)
�
subprocess�PIPErzZ
socketpairr%�Popen�_procr��detachre)	rrErdrerfrgrhriZstdin_wrrr�_starts.
���z_UnixSubprocessTransport._startN)r�r�r�rrrrrr^	sr^c@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)raHAbstract base class for monitoring child processes.

    Objects derived from this class monitor a collection of subprocesses and
    report their termination or interruption by a signal.

    New callbacks are registered with .add_child_handler(). Starting a new
    process must be done within a 'with' block to allow the watcher to suspend
    its activity until the new process if fully registered (this is needed to
    prevent a race condition in some implementations).

    Example:
        with watcher:
            proc = subprocess.Popen("sleep 1")
            watcher.add_child_handler(proc.pid, callback)

    Notes:
        Implementations of this class must be thread-safe.

        Since child watcher objects may catch the SIGCHLD signal and call
        waitpid(-1), there should be only one active object per process.
    cGs
t��dS)aRegister a new child handler.

        Arrange for callback(pid, returncode, *args) to be called when
        process 'pid' terminates. Specifying another callback for the same
        process replaces the previous handler.

        Note: callback() must be thread-safe.
        N��NotImplementedError�rrnrDrErrrr_9s	z&AbstractChildWatcher.add_child_handlercCs
t��dS)z�Removes the handler for process 'pid'.

        The function returns True if the handler was successfully removed,
        False if there was nothing to remove.Nr�rrnrrr�remove_child_handlerDsz)AbstractChildWatcher.remove_child_handlercCs
t��dS)z�Attach the watcher to an event loop.

        If the watcher was previously attached to an event loop, then it is
        first detached before attaching to the new loop.

        Note: loop may be None.
        Nr�rr�rrr�attach_loopLsz AbstractChildWatcher.attach_loopcCs
t��dS)zlClose the watcher.

        This must be called to make sure that any underlying resource is freed.
        Nrr�rrrr%VszAbstractChildWatcher.closecCs
t��dS)z�Return ``True`` if the watcher is active and is used by the event loop.

        Return True if the watcher is installed and ready to handle process exit
        notifications.

        Nrr�rrrr\]szAbstractChildWatcher.is_activecCs
t��dS)zdEnter the watcher's context and allow starting new processes

        This function must return selfNrr�rrr�	__enter__fszAbstractChildWatcher.__enter__cCs
t��dS)zExit the watcher's contextNr�r�a�b�crrr�__exit__lszAbstractChildWatcher.__exit__N)r�r�r�r�r_rrr%r\rr!rrrrr"s
	rcCs2t�|�rt�|�St�|�r*t�|�S|SdSr)rx�WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS)�statusrrr�_compute_returncodeqs



r'c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�BaseChildWatchercCsd|_i|_dSr)r��
_callbacksr�rrrr�szBaseChildWatcher.__init__cCs|�d�dSr)rr�rrrr%�szBaseChildWatcher.closecCs|jdk	o|j��Sr)r�Z
is_runningr�rrrr\�szBaseChildWatcher.is_activecCs
t��dSrr)r�expected_pidrrr�_do_waitpid�szBaseChildWatcher._do_waitpidcCs
t��dSrrr�rrr�_do_waitpid_all�sz BaseChildWatcher._do_waitpid_allcCs~|dkst|tj�st�|jdk	r<|dkr<|jr<t�dt�|jdk	rT|j�	t
j�||_|dk	rz|�t
j|j
�|��dS)NzCA loop is being detached from a child watcher with pending handlers)rOrZAbstractEventLooprwr�r)r*r+�RuntimeWarningr)r9�SIGCHLDrH�	_sig_chldr,rrrrr�s�
zBaseChildWatcher.attach_loopc
Cs^z|��WnLttfk
r&�Yn4tk
rX}z|j�d|d��W5d}~XYnXdS)N�$Unknown exception in SIGCHLD handler)r�r�)r,rarbrcr�r�r�rrrr/�s�zBaseChildWatcher._sig_chldN)
r�r�r�rr%r\r+r,rr/rrrrr(sr(csPeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)rad'Safe' child watcher implementation.

    This implementation avoids disrupting other code spawning processes by
    polling explicitly each process in the SIGCHLD handler instead of calling
    os.waitpid(-1).

    This is a safe solution but it has a significant overhead when handling a
    big number of children (O(n) each time SIGCHLD is raised)
    cs|j��t���dSr)r)r-rr%r�r!rrr%�s
zSafeChildWatcher.closecCs|Srrr�rrrr�szSafeChildWatcher.__enter__cCsdSrrrrrrr!�szSafeChildWatcher.__exit__cGs||f|j|<|�|�dSr)r)r+rrrrr_�sz"SafeChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdS�NTF�r)rJrrrrr�s
z%SafeChildWatcher.remove_child_handlercCst|j�D]}|�|�q
dSr�r(r)r+rrrrr,�sz SafeChildWatcher._do_waitpid_allcCs�|dkst�zt�|tj�\}}Wn(tk
rJ|}d}t�d|�Yn.X|dkrXdSt|�}|j�	�rxt�
d||�z|j�|�\}}Wn.t
k
r�|j�	�r�tjd|dd�YnX|||f|��dS)Nr��8Unknown child process pid %d, will report returncode 255�$process %s exited with returncode %s�'Child watcher got an unexpected pid: %rTr�)rwrx�waitpid�WNOHANG�ChildProcessErrorr
rr'r�r�r�r)�poprJ)rr*rnr&rorDrErrrr+�s6�

�
�zSafeChildWatcher._do_waitpid)r�r�r�r�r%rr!r_rr,r+r�rrr!rr�s
rcsTeZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)raW'Fast' child watcher implementation.

    This implementation reaps every terminated processes by calling
    os.waitpid(-1) directly, possibly breaking other code spawning processes
    and waiting for their termination.

    There is no noticeable overhead when handling a big number of children
    (O(1) each time a child terminates).
    cs$t���t��|_i|_d|_dSr�)rr�	threadingZLock�_lock�_zombies�_forksr�r!rrrs

zFastChildWatcher.__init__cs"|j��|j��t���dSr)r)r-r>rr%r�r!rrr%s

zFastChildWatcher.closec
Cs0|j� |jd7_|W5QR�SQRXdS)Nr)r=r?r�rrrrszFastChildWatcher.__enter__c	Cs^|j�B|jd8_|js"|js0W5QR�dSt|j�}|j��W5QRXt�d|�dS)Nrz5Caught subprocesses termination from unknown pids: %s)r=r?r>r?r-r
r)rrrr Zcollateral_victimsrrrr!s
�zFastChildWatcher.__exit__c	Gst|jstd��|j�Fz|j�|�}Wn.tk
rT||f|j|<YW5QR�dSXW5QRX|||f|��dS)NzMust use the context manager)r?rwr=r>r;rJr))rrnrDrErorrrr_'sz"FastChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdSr1r2rrrrr5s
z%FastChildWatcher.remove_child_handlerc	Cs�zt�dtj�\}}Wntk
r,YdSX|dkr:dSt|�}|j��z|j�|�\}}WnNtk
r�|j	r�||j
|<|j��r�t
�d||�YW5QR�qd}YnX|j��r�t
�d||�W5QRX|dkr�t
�d||�q|||f|��qdS)Nr3rz,unknown process %s exited with returncode %sr6z8Caught subprocess termination from unknown pid: %d -> %d)rxr8r9r:r'r=r)r;rJr?r>r�r�r
r�r)rrnr&rorDrErrrr,<s@

�

��z FastChildWatcher._do_waitpid_all)r�r�r�r�rr%rr!r_rr,r�rrr!rr�s	rc@sheZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)ra~A watcher that doesn't require running loop in the main thread.

    This implementation registers a SIGCHLD signal handler on
    instantiation (which may conflict with other code that
    install own handler for this signal).

    The solution is safe but it has a significant overhead when
    handling a big number of processes (*O(n)* each time a
    SIGCHLD is received).
    cCsi|_d|_dSr)r)�_saved_sighandlerr�rrrrzszMultiLoopChildWatcher.__init__cCs
|jdk	Sr)r@r�rrrr\~szMultiLoopChildWatcher.is_activecCsT|j��|jdkrdSt�tj�}||jkr:t�d�nt�tj|j�d|_dS)Nz+SIGCHLD handler was changed by outside code)	r)r-r@r9�	getsignalr.r/r
r)rrNrrrr%�s


zMultiLoopChildWatcher.closecCs|Srrr�rrrr�szMultiLoopChildWatcher.__enter__cCsdSrr�r�exc_typeZexc_valZexc_tbrrrr!�szMultiLoopChildWatcher.__exit__cGs&t��}|||f|j|<|�|�dSr)r�get_running_loopr)r+)rrnrDrEr�rrrr_�sz'MultiLoopChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdSr1r2rrrrr�s
z*MultiLoopChildWatcher.remove_child_handlercCsN|jdk	rdSt�tj|j�|_|jdkr<t�d�tj|_t�tjd�dS)NzaPrevious SIGCHLD handler was set by non-Python code, restore to default handler on watcher close.F)r@r9r.r/r
rrMr@rrrrr�s


z!MultiLoopChildWatcher.attach_loopcCst|j�D]}|�|�q
dSrr3rrrrr,�sz%MultiLoopChildWatcher._do_waitpid_allc	Cs�|dkst�zt�|tj�\}}Wn,tk
rN|}d}t�d|�d}YnX|dkr\dSt|�}d}z|j�	|�\}}}Wn$t
k
r�tjd|dd�YnHX|��r�t�d||�n.|r�|��r�t�
d	||�|j|||f|��dS)
Nrr4r5FTr7r��%Loop %r that handles pid %r is closedr6)rwrxr8r9r:r
rr'r)r;rJ�	is_closedr�r�rm)	rr*rnr&roZ	debug_logr�rDrErrrr+�s<�
��z!MultiLoopChildWatcher._do_waitpidc	CsLz|��Wn:ttfk
r&�Yn"tk
rFtjddd�YnXdS)Nr0Tr�)r,rarbrcr
r)rrrrrrr/�szMultiLoopChildWatcher._sig_chldN)r�r�r�r�rr\r%rr!r_rrr,r+r/rrrrrgs%rc@sneZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	e
jfdd�Zdd�Z
dd�Zdd�Zdd�ZdS)raAThreaded child watcher implementation.

    The watcher uses a thread per process
    for waiting for the process finish.

    It doesn't require subscription on POSIX signal
    but a thread creation is not free.

    The watcher has O(1) complexity, its performance doesn't depend
    on amount of spawn processes.
    cCst�d�|_i|_dSr�)�	itertoolsr��_pid_counter�_threadsr�rrrr�szThreadedChildWatcher.__init__cCsdSr�rr�rrrr\�szThreadedChildWatcher.is_activecCs|��dSr)�
_join_threadsr�rrrr%�szThreadedChildWatcher.closecCs.dd�t|j���D�}|D]}|��qdS)z%Internal: Join all non-daemon threadscSsg|]}|��r|js|�qSr)�is_alive�daemon��.0�threadrrr�
<listcomp>�s�z6ThreadedChildWatcher._join_threads.<locals>.<listcomp>N)r(rI�valuesr�)r�threadsrOrrrrJ�sz"ThreadedChildWatcher._join_threadscCs|Srrr�rrrrszThreadedChildWatcher.__enter__cCsdSrrrBrrrr!szThreadedChildWatcher.__exit__cCs6dd�t|j���D�}|r2||j�d�t|d�dS)NcSsg|]}|��r|�qSr)rKrMrrrrP	s�z0ThreadedChildWatcher.__del__.<locals>.<listcomp>z0 has registered but not finished child processesr#)r(rIrQr"r,)rr�rRrrrr�s�zThreadedChildWatcher.__del__cGsFt��}tj|jdt|j���||||fdd�}||j|<|��dS)Nzwaitpid-T)�target�namerErL)	rrDr<ZThreadr+�nextrHrI�start)rrnrDrEr�rOrrrr_s
�
z&ThreadedChildWatcher.add_child_handlercCsdSr�rrrrrrsz)ThreadedChildWatcher.remove_child_handlercCsdSrrrrrrrsz ThreadedChildWatcher.attach_loopcCs�|dkst�zt�|d�\}}Wn(tk
rH|}d}t�d|�Yn Xt|�}|��rht�d||�|�	�r�t�d||�n|j
|||f|��|j�|�dS)Nrr4r5r6rE)
rwrxr8r:r
rr'r�r�rFrmrIr;)rr�r*rDrErnr&rorrrr+"s(�
�z ThreadedChildWatcher._do_waitpidN)r�r�r�r�rr\r%rJrr!r*r+r�r_rrr+rrrrr�s	rcsHeZdZdZeZ�fdd�Zdd�Z�fdd�Zdd	�Z	d
d�Z
�ZS)�_UnixDefaultEventLoopPolicyz:UNIX event loop policy with a watcher for child processes.cst���d|_dSr)rr�_watcherr�r!rrrAs
z$_UnixDefaultEventLoopPolicy.__init__c	CsHtj�8|jdkr:t�|_tt��tj�r:|j�|j	j
�W5QRXdSr)rr=rXrrOr<�current_thread�_MainThreadr�_localr�r�rrr�
_init_watcherEs
�z)_UnixDefaultEventLoopPolicy._init_watchercs6t��|�|jdk	r2tt��tj�r2|j�|�dS)z�Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        N)r�set_event_looprXrOr<rYrZrrr!rrr]Ms

�z*_UnixDefaultEventLoopPolicy.set_event_loopcCs|jdkr|��|jS)z~Get the watcher for child processes.

        If not yet set, a ThreadedChildWatcher object is automatically created.
        N)rXr\r�rrrr[[s
z-_UnixDefaultEventLoopPolicy.get_child_watchercCs4|dkst|t�st�|jdk	r*|j��||_dS)z$Set the watcher for child processes.N)rOrrwrXr%)rrjrrr�set_child_watcheres

z-_UnixDefaultEventLoopPolicy.set_child_watcher)r�r�r�r�rZ
_loop_factoryrr\r]r[r^r�rrr!rrW=s
rW)2r�rBr�rGrxr�r9rzr�rr&r<r*�rrrrrrr	r
rr�logr
�__all__r��ImportErrorrZBaseSelectorEventLooprZ
ReadTransportrRZ_FlowControlMixinZWriteTransportrYZBaseSubprocessTransportr^rr'r(rrrrZBaseDefaultEventLoopPolicyrWrrrrrr�<module>s`	
	�NO5Ji}Y3PK [`��S�S)__pycache__/sslproto.cpython-38.opt-1.pycnu�[���U

e5dJj�@s�ddlZddlZzddlZWnek
r4dZYnXddlmZddlmZddlmZddlmZddl	m
Z
dd	�Zd
ZdZ
dZd
ZGdd�de�ZGdd�dejej�ZGdd�dej�ZdS)�N�)�base_events)�	constants)�	protocols)�
transports)�loggercCs"|rtd��t��}|sd|_|S)Nz(Server side SSL needs a valid SSLContextF)�
ValueError�sslZcreate_default_contextZcheck_hostname)�server_side�server_hostname�
sslcontext�r
�(/usr/lib64/python3.8/asyncio/sslproto.py�_create_transport_contextsrZ	UNWRAPPEDZDO_HANDSHAKEZWRAPPEDZSHUTDOWNc@s~eZdZdZdZddd�Zedd��Zedd	��Zed
d��Z	edd
��Z
ddd�Zddd�Zdd�Z
ddd�Zddd�ZdS)�_SSLPipeaAn SSL "Pipe".

    An SSL pipe allows you to communicate with an SSL/TLS protocol instance
    through memory buffers. It can be used to implement a security layer for an
    existing connection where you don't have access to the connection's file
    descriptor, or for some reason you don't want to use it.

    An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
    data is passed through untransformed. In wrapped mode, application level
    data is encrypted to SSL record level data and vice versa. The SSL record
    level is the lowest level in the SSL protocol suite and is what travels
    as-is over the wire.

    An SslPipe initially is in "unwrapped" mode. To start SSL, call
    do_handshake(). To shutdown SSL again, call unwrap().
    iNcCsH||_||_||_t|_t��|_t��|_d|_	d|_
d|_d|_dS)a�
        The *context* argument specifies the ssl.SSLContext to use.

        The *server_side* argument indicates whether this is a server side or
        client side transport.

        The optional *server_hostname* argument can be used to specify the
        hostname you are connecting to. You may only specify this parameter if
        the _ssl module supports Server Name Indication (SNI).
        NF)
�_context�_server_side�_server_hostname�
_UNWRAPPED�_stater	Z	MemoryBIO�	_incoming�	_outgoing�_sslobj�
_need_ssldata�
_handshake_cb�_shutdown_cb)�self�contextr
rr
r
r�__init__8s

z_SSLPipe.__init__cCs|jS)z*The SSL context passed to the constructor.)r�rr
r
rrNsz_SSLPipe.contextcCs|jS)z^The internal ssl.SSLObject instance.

        Return None if the pipe is not wrapped.
        )rrr
r
r�
ssl_objectSsz_SSLPipe.ssl_objectcCs|jS)zgWhether more record level data is needed to complete a handshake
        that is currently in progress.)rrr
r
r�need_ssldata[sz_SSLPipe.need_ssldatacCs
|jtkS)zj
        Whether a security layer is currently in effect.

        Return False during handshake.
        )r�_WRAPPEDrr
r
r�wrappedasz_SSLPipe.wrappedcCsR|jtkrtd��|jj|j|j|j|jd�|_	t
|_||_|jddd�\}}|S)aLStart the SSL handshake.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the handshake is complete. The callback will be
        called with None if successful, else an exception instance.
        z"handshake in progress or completed)r
r�T)�only_handshake)
rr�RuntimeErrorrZwrap_biorrrrr�
_DO_HANDSHAKEr�feed_ssldata�r�callback�ssldata�appdatar
r
r�do_handshakejs	
�z_SSLPipe.do_handshakecCsB|jtkrtd��|jtkr$td��t|_||_|�d�\}}|S)a1Start the SSL shutdown sequence.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the shutdown is complete. The callback will be
        called without arguments.
        zno security layer presentzshutdown in progressr$)rrr&�	_SHUTDOWNrr(r)r
r
r�shutdowns	

z_SSLPipe.shutdowncCs|j��|�d�\}}dS)z�Send a potentially "ragged" EOF.

        This method will raise an SSL_ERROR_EOF exception if the EOF is
        unexpected.
        r$N)rZ	write_eofr()rr+r,r
r
r�feed_eof�s
z_SSLPipe.feed_eofFc
Cs�|jtkr"|r|g}ng}g|fSd|_|r8|j�|�g}g}z�|jtkrz|j��t|_|j	rl|�	d�|rz||fWS|jtkr�|j�
|j�}|�|�|s�q�q�nJ|jt
kr�|j��d|_t|_|jr�|��n|jtkr�|�|j�
��Wnztjtjfk
�rl}zRt|dd�}|tjtjtjfk�rP|jtk�rN|j	�rN|�	|��|tjk|_W5d}~XYnX|jj�r�|�|j�
��||fS)a�Feed SSL record level data into the pipe.

        The data must be a bytes instance. It is OK to send an empty bytes
        instance. This can be used to get ssldata for a handshake initiated by
        this endpoint.

        Return a (ssldata, appdata) tuple. The ssldata element is a list of
        buffers containing SSL data that needs to be sent to the remote SSL.

        The appdata element is a list of buffers containing plaintext data that
        needs to be forwarded to the application. The appdata list may contain
        an empty buffer indicating an SSL "close_notify" alert. This alert must
        be acknowledged by calling shutdown().
        FN�errno)rrrr�writer'rr-r"r�read�max_size�appendr.Zunwraprr	�SSLError�CertificateError�getattr�SSL_ERROR_WANT_READ�SSL_ERROR_WANT_WRITE�SSL_ERROR_SYSCALLr�pending)r�datar%r,r+�chunk�exc�	exc_errnor
r
rr(�sZ










�

z_SSLPipe.feed_ssldatarc
Cs|jtkr6|t|�kr&||d�g}ng}|t|�fSg}t|�}d|_z(|t|�krn||j�||d��7}Wnhtjk
r�}zHt	|dd�}|j
dkr�tj}|_|tjtj
tjfkr��|tjk|_W5d}~XYnX|jjr�|�|j���|t|�k�s|jrB�qqB||fS)aFeed plaintext data into the pipe.

        Return an (ssldata, offset) tuple. The ssldata element is a list of
        buffers containing record level data that needs to be sent to the
        remote SSL instance. The offset is the number of plaintext bytes that
        were processed, which may be less than the length of data.

        NOTE: In case of short writes, this call MUST be retried with the SAME
        buffer passed into the *data* argument (i.e. the id() must be the
        same). This is an OpenSSL requirement. A further particularity is that
        a short write will always have offset == 0, because the _ssl module
        does not enable partial writes. And even though the offset is zero,
        there will still be encrypted data in ssldata.
        NFr1ZPROTOCOL_IS_SHUTDOWN)rr�len�
memoryviewrrr2r	r6r8�reasonr9r1r:r;rr<r5r3)rr=�offsetr+Zviewr?r@r
r
r�feed_appdata�s4

�z_SSLPipe.feed_appdata)N)N)N)F)r)�__name__�
__module__�__qualname__�__doc__r4r�propertyrr r!r#r-r/r0r(rEr
r
r
rr$s 








Krc@s�eZdZejjZdd�Zd"dd�Zdd�Z	dd	�Z
d
d�Zdd
�Ze
jfdd�Zdd�Zdd�Zdd�Zd#dd�Zdd�Zedd��Zdd�Zdd�Zd d!�ZdS)$�_SSLProtocolTransportcCs||_||_d|_dS)NF)�_loop�
_ssl_protocol�_closed)r�loopZssl_protocolr
r
rr!sz_SSLProtocolTransport.__init__NcCs|j�||�S)z#Get optional transport information.)rM�_get_extra_info�r�name�defaultr
r
r�get_extra_info'sz$_SSLProtocolTransport.get_extra_infocCs|j�|�dS�N)rM�_set_app_protocol)r�protocolr
r
r�set_protocol+sz"_SSLProtocolTransport.set_protocolcCs|jjSrU)rM�
_app_protocolrr
r
r�get_protocol.sz"_SSLProtocolTransport.get_protocolcCs|jSrU)rNrr
r
r�
is_closing1sz _SSLProtocolTransport.is_closingcCsd|_|j��dS)a
Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        TN)rNrM�_start_shutdownrr
r
r�close4sz_SSLProtocolTransport.closecCs&|js"|d|��t|d�|��dS)Nzunclosed transport )�source)rN�ResourceWarningr])rZ_warnr
r
r�__del__?sz_SSLProtocolTransport.__del__cCs |jj}|dkrtd��|��S)Nz*SSL transport has not been initialized yet)rM�
_transportr&�
is_reading)rZtrr
r
rrbDsz _SSLProtocolTransport.is_readingcCs|jj��dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        N)rMra�
pause_readingrr
r
rrcJsz#_SSLProtocolTransport.pause_readingcCs|jj��dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        N)rMra�resume_readingrr
r
rrdRsz$_SSLProtocolTransport.resume_readingcCs|jj�||�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        N)rMra�set_write_buffer_limits)rZhighZlowr
r
rreZsz-_SSLProtocolTransport.set_write_buffer_limitscCs|jj��S)z,Return the current size of the write buffer.)rMra�get_write_buffer_sizerr
r
rrfosz+_SSLProtocolTransport.get_write_buffer_sizecCs
|jjjSrU)rMra�_protocol_pausedrr
r
rrgssz&_SSLProtocolTransport._protocol_pausedcCs<t|tttf�s$tdt|�j����|s,dS|j�|�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        z+data: expecting a bytes-like instance, got N)	�
isinstance�bytes�	bytearrayrB�	TypeError�typerFrM�_write_appdata�rr=r
r
rr2xs
z_SSLProtocolTransport.writecCsdS)zAReturn True if this transport supports write_eof(), False if not.Fr
rr
r
r�
can_write_eof�sz#_SSLProtocolTransport.can_write_eofcCs|j��d|_dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        TN)rM�_abortrNrr
r
r�abort�s
z_SSLProtocolTransport.abort)N)NN)rFrGrHrZ
_SendfileModeZFALLBACKZ_sendfile_compatiblerrTrXrZr[r]�warnings�warnr`rbrcrdrerfrJrgr2rorqr
r
r
rrKs$



rKc@s�eZdZdZd,dd�Zdd�Zd-d	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Zd.dd�Z
dd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd/d&d'�Zd(d)�Zd*d+�ZdS)0�SSLProtocolz�SSL protocol.

    Implementation of SSL on top of a socket using incoming and outgoing
    buffers which are ssl.MemoryBIO objects.
    FNTc		Cs�tdkrtd��|dkr tj}n|dkr6td|����|sDt||�}||_|rZ|sZ||_nd|_||_t	|d�|_
t��|_
d|_||_||_|�|�t|j|�|_d|_d|_d|_d|_d|_||_||_dS)Nzstdlib ssl module not availablerz7ssl_handshake_timeout should be a positive number, got )rF)r	r&rZSSL_HANDSHAKE_TIMEOUTrrrr�_sslcontext�dict�_extra�collections�deque�_write_backlog�_write_buffer_size�_waiterrLrVrK�_app_transport�_sslpipe�_session_established�
_in_handshake�_in_shutdownra�_call_connection_made�_ssl_handshake_timeout)	rrO�app_protocolrZwaiterr
rZcall_connection_madeZssl_handshake_timeoutr
r
rr�s@��

zSSLProtocol.__init__cCs||_t|tj�|_dSrU)rYrhrZBufferedProtocol�_app_protocol_is_buffer)rr�r
r
rrV�s
�zSSLProtocol._set_app_protocolcCsD|jdkrdS|j��s:|dk	r.|j�|�n|j�d�d|_dSrU)r|Z	cancelledZ
set_exceptionZ
set_result�rr?r
r
r�_wakeup_waiter�s

zSSLProtocol._wakeup_waitercCs&||_t|j|j|j�|_|��dS)zXCalled when the low-level connection is made.

        Start the SSL handshake.
        N)rarrurrr~�_start_handshake)r�	transportr
r
r�connection_made�s�zSSLProtocol.connection_madecCsn|jr d|_|j�|jj|�n|jdk	r2d|j_d|_d|_t|dd�rT|j	�
�|�|�d|_d|_dS)z�Called when the low-level connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        FNT�_handshake_timeout_handle)
rrL�	call_soonrY�connection_lostr}rNrar8r��cancelr�r~r�r
r
rr��s


zSSLProtocol.connection_lostcCs|j��dS)z\Called when the low-level transport's buffer goes over
        the high-water mark.
        N)rY�
pause_writingrr
r
rr��szSSLProtocol.pause_writingcCs|j��dS)z^Called when the low-level transport's buffer drains below
        the low-water mark.
        N)rY�resume_writingrr
r
rr�szSSLProtocol.resume_writingcCs"|jdkrdSz|j�|�\}}WnLttfk
r<�Yn4tk
rn}z|�|d�WY�dSd}~XYnX|D]}|j�|�qt|D]�}|�rz&|jr�t	�
|j|�n|j�|�WnPttfk
r��Yn8tk
�r
}z|�|d�WY�dSd}~XYnXq�|�
��qq�dS)zXCalled when some SSL data is received.

        The argument is a bytes object.
        NzSSL error in data receivedz/application protocol failed to receive SSL data)r~r(�
SystemExit�KeyboardInterrupt�
BaseException�_fatal_errorrar2r�rZ_feed_data_to_buffered_protorY�
data_receivedr\)rr=r+r,�er>Zexr
r
rr�s<
��zSSLProtocol.data_receivedcCsTzB|j��rt�d|�|�t�|js@|j	�
�}|r@t�d�W5|j��XdS)aCalled when the other end of the low-level stream
        is half-closed.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        z%r received EOFz?returning true from eof_received() has no effect when using sslN)rar]rL�	get_debugr�debugr��ConnectionResetErrorr�rY�eof_receivedZwarning)rZ	keep_openr
r
rr�-s


zSSLProtocol.eof_receivedcCs4||jkr|j|S|jdk	r,|j�||�S|SdSrU)rwrarTrQr
r
rrPCs



zSSLProtocol._get_extra_infocCs.|jr
dS|jr|��nd|_|�d�dS)NTr$)r�r�rprmrr
r
rr\Ks
zSSLProtocol._start_shutdowncCs.|j�|df�|jt|�7_|��dS)Nr)rzr5r{rA�_process_write_backlogrnr
r
rrmTszSSLProtocol._write_appdatacCs\|j��r$t�d|�|j��|_nd|_d|_|j�d�|j�	|j
|j�|_|�
�dS)Nz%r starts SSL handshakeT)r$r)rLr�rr��time�_handshake_start_timer�rzr5Z
call_laterr��_check_handshake_timeoutr�r�rr
r
rr�Ys

��zSSLProtocol._start_handshakecCs*|jdkr&d|j�d�}|�t|��dS)NTz$SSL handshake is taking longer than z! seconds: aborting the connection)r�r�r��ConnectionAbortedError)r�msgr
r
rr�hs
�z$SSLProtocol._check_handshake_timeoutc
Csd|_|j��|jj}z|dk	r&|�|��}Wnbttfk
rJ�YnJtk
r�}z,t	|t
j�rld}nd}|�||�WY�dSd}~XYnX|j
��r�|j
��|j}t�d||d�|jj||��|��|d�|jr�|j�|j�|��d|_|j
�|j�dS)NFz1SSL handshake failed on verifying the certificatezSSL handshake failedz%r: SSL handshake took %.1f msg@�@)�peercert�cipher�compressionr T)r�r�r�r~r Zgetpeercertr�r�r�rhr	r7r�rLr�r�r�rr�rw�updater�r�r�rYr�r}r�rr�r�)rZ
handshake_excZsslobjr�r?r�Zdtr
r
r�_on_handshake_completeqs8

�z"SSLProtocol._on_handshake_completec
CsB|jdks|jdkrdSz�tt|j��D]�}|jd\}}|rR|j�||�\}}n*|rj|j�|j�}d}n|j�|j	�}d}|D]}|j�
|�q�|t|�kr�||f|jd<|jjr�|j��q�|jd=|j
t|�8_
q(Wn\ttfk
r��YnDtk
�r<}z$|j�r |�|�n|�|d�W5d}~XYnXdS)NrrzFatal error on SSL transport)rar~�rangerArzrEr-r�r/�	_finalizer2Z_pausedrdr{r�r�r�r�r�)r�ir=rDr+r>r?r
r
rr��s:�
z"SSLProtocol._process_write_backlog�Fatal error on transportcCsVt|t�r(|j��r@tjd||dd�n|j�|||j|d��|jrR|j�|�dS)Nz%r: %sT)�exc_info)�messageZ	exceptionr�rW)	rh�OSErrorrLr�rr�Zcall_exception_handlerraZ_force_close)rr?r�r
r
rr��s

�zSSLProtocol._fatal_errorcCsd|_|jdk	r|j��dSrU)r~rar]rr
r
rr��s
zSSLProtocol._finalizecCs(z|jdk	r|j��W5|��XdSrU)r�rarqrr
r
rrp�s
zSSLProtocol._abort)FNTN)N)N)r�)rFrGrHrIrrVr�r�r�r�r�r�r�rPr\rmr�r�r�r�r�r�rpr
r
r
rrt�s0�
.

&
		)+
rt)rxrrr	�ImportError�rrrr�logrrrr'r"r.�objectrZ_FlowControlMixinZ	TransportrKZProtocolrtr
r
r
r�<module>s*
y�xPK [���E$__pycache__/staggered.cpython-38.pycnu�[���U

e5dh�
@s�dZdZddlZddlZddlmZddlmZddlmZddlm	Z	dd	�ej
ejgejfej
eejejejej
eejej
efd
�dd�ZdS)
zFSupport for running coroutines in parallel with staggered start times.)�staggered_race�N�)�events)�
exceptions)�locks)�tasks)�loop)�coro_fns�delayr�returnc		�s��p
t���t|��d�d�g�g�tjtjdd���������fdd�����d��}��|�zfd}|t
��kr�t���IdH\}}t
|�}|D]$}|�
�r�|��s�|��r�|���q�ql���fW�S�D]}|�	�q�XdS)a�Run coroutines with staggered start times and take the first to finish.

    This method takes an iterable of coroutine functions. The first one is
    started immediately. From then on, whenever the immediately preceding one
    fails (raises an exception), or when *delay* seconds has passed, the next
    coroutine is started. This continues until one of the coroutines complete
    successfully, in which case all others are cancelled, or until all
    coroutines fail.

    The coroutines provided should be well-behaved in the following way:

    * They should only ``return`` if completed successfully.

    * They should always raise an exception if they did not complete
      successfully. In particular, if they handle cancellation, they should
      probably reraise, like this::

        try:
            # do work
        except asyncio.CancelledError:
            # undo partially completed work
            raise

    Args:
        coro_fns: an iterable of coroutine functions, i.e. callables that
            return a coroutine object when called. Use ``functools.partial`` or
            lambdas to pass arguments.

        delay: amount of time, in seconds, between starting coroutines. If
            ``None``, the coroutines will run sequentially.

        loop: the event loop to use.

    Returns:
        tuple *(winner_result, winner_index, exceptions)* where

        - *winner_result*: the result of the winning coroutine, or ``None``
          if no coroutines won.

        - *winner_index*: the index of the winning coroutine in
          ``coro_fns``, or ``None`` if no coroutines won. If the winning
          coroutine may return None on success, *winner_index* can be used
          to definitively determine whether any coroutine won.

        - *exceptions*: list of exceptions returned by the coroutines.
          ``len(exceptions)`` is equal to the number of coroutines actually
          started, and the order is the same as in ``coro_fns``. The winning
          coroutine's entry is ``None``.

    N)�previous_failedrc	
�sN|dk	r6t�tj��t�|����IdHW5QRXzt��\}}Wntk
r\YdSXt	�
�}���|��}��|�t
��|dks�t���d�t
��|dks�t�z|�IdH}WnLttfk
r��Ynptk
�r}z|�|<|��W5d}~XYn>X�dk�st�|�|�t��D]\}}||k�r,|���q,dS)N�r)�
contextlib�suppress�exceptions_mod�TimeoutErrorrZwait_for�wait�next�
StopIterationr�Event�create_task�append�len�AssertionError�
SystemExit�KeyboardInterrupt�
BaseException�set�	enumerate�cancel)	rZ
this_indexZcoro_fnZthis_failedZ	next_task�result�e�i�t�r
Z
enum_coro_fnsrr�run_one_coroZ
running_tasksZwinner_indexZ
winner_result��)/usr/lib64/python3.8/asyncio/staggered.pyr%Rs4 


z$staggered_race.<locals>.run_one_coror)rZget_running_loopr�typing�Optionalrrrrrrrr�doneZ	cancelledZ	exception)	r	r
rZ
first_taskr#Z
done_countr*�_�dr&r$r'rs,=
�0
r)�__doc__�__all__rr(�rrrrr�Iterable�Callable�	Awaitabler)�floatZAbstractEventLoopZTupleZAny�intZList�	Exceptionrr&r&r&r'�<module>s&����PK [g<2��^�^ __pycache__/tasks.cpython-38.pycnu�[���U

e5d���@svdZdZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddlm
Z
ddlmZddlmZdd	lmZdd
l
mZe�d�jZdBdd�ZdCd
d�ZdDdd�Zdd�ZGdd�dej�ZeZzddlZWnek
r�YnXejZZdd�dd�Zejj Z ejj!Z!ejj"Z"dde"d�dd�Z#dd�Z$dd�dd�Z%d d!�Z&d"d#�Z'ddd$�d%d&�Z(ej)d'd(��Z*dEdd�d)d*�Z+dd�d+d,�Z,ej)d-d.��Z-ee-_Gd/d0�d0ej.�Z/dd1d2�d3d4�Z0dd�d5d6�Z1d7d8�Z2e
�3�Z4iZ5d9d:�Z6d;d<�Z7d=d>�Z8d?d@�Z9e6Z:e9Z;e7Z<e8Z=z$ddAlm6Z6m9Z9m7Z7m8Z8m4Z4m5Z5Wnek
�r`YnXe6Z>e9Z?e7Z@e8ZAdS)Fz0Support for tasks, coroutines and the scheduler.)�Task�create_task�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�wait�wait_for�as_completed�sleep�gather�shield�
ensure_future�run_coroutine_threadsafe�current_task�	all_tasks�_register_task�_unregister_task�_enter_task�_leave_task�N�)�
base_tasks)�
coroutines)�events)�
exceptions)�futures)�
_is_coroutinecCs|dkrt��}t�|�S)z!Return a currently executed task.N)r�get_running_loop�_current_tasks�get��loop�r!�%/usr/lib64/python3.8/asyncio/tasks.pyr"srcs^�dkrt���d}ztt�}WqLtk
rF|d7}|dkrB�YqXqLq�fdd�|D�S)z'Return a set of all tasks for the loop.Nrr��cs&h|]}t�|��kr|��s|�qSr!)r�	_get_loop�done��.0�trr!r"�	<setcomp><s�zall_tasks.<locals>.<setcomp>)rr�list�
_all_tasks�RuntimeError�r �iZtasksr!rr"r)srcs^�dkrt���d}ztt�}WqLtk
rF|d7}|dkrB�YqXqLq�fdd�|D�S)Nrrr#csh|]}t�|��kr|�qSr!)rr$r&rr!r"r)Usz$_all_tasks_compat.<locals>.<setcomp>)r�get_event_loopr*r+r,r-r!rr"�_all_tasks_compat@sr0cCs4|dk	r0z
|j}Wntk
r&Yn
X||�dS�N)�set_name�AttributeError)�task�namer2r!r!r"�_set_task_nameXs
r6cs�eZdZdZdZed%dd��Zed&dd��Zddd��fd	d
�
Z�fdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�dd�Zddd�dd�Zdd �Zd'�fd!d"�	Zd#d$�Z�ZS)(rz A coroutine wrapped in a Future.TNcCs(tjdtdd�|dkr t��}t|�S)z�Return the currently running task in an event loop or None.

        By default the current task for the current event loop is returned.

        None is returned when called not in the context of a Task.
        zVTask.current_task() is deprecated since Python 3.7, use asyncio.current_task() instead���
stacklevelN)�warnings�warn�DeprecationWarningrr/r��clsr r!r!r"rts�zTask.current_taskcCstjdtdd�t|�S)z|Return a set of all tasks for an event loop.

        By default all tasks for the current event loop are returned.
        zPTask.all_tasks() is deprecated since Python 3.7, use asyncio.all_tasks() insteadr7r8)r:r;r<r0r=r!r!r"r�s
�zTask.all_tasks)r r5cs�t�j|d�|jr|jd=t�|�s:d|_td|����|dkrRdt���|_n
t	|�|_d|_
d|_||_t
��|_|jj|j|jd�t|�dS)Nr���Fza coroutine was expected, got zTask-��context)�super�__init__�_source_tracebackr�iscoroutine�_log_destroy_pending�	TypeError�_task_name_counter�_name�str�_must_cancel�_fut_waiter�_coro�contextvarsZcopy_context�_context�_loop�	call_soon�_Task__stepr)�self�coror r5��	__class__r!r"rC�s


z
Task.__init__csF|jtjkr8|jr8|dd�}|jr,|j|d<|j�|�t���dS)Nz%Task was destroyed but it is pending!)r4�messageZsource_traceback)	Z_staterZ_PENDINGrFrDrPZcall_exception_handlerrB�__del__)rSrArUr!r"rX�s�
zTask.__del__cCs
t�|�Sr1)rZ_task_repr_info�rSr!r!r"�
_repr_info�szTask._repr_infocCs|jSr1)rMrYr!r!r"�get_coro�sz
Task.get_corocCs|jSr1)rIrYr!r!r"�get_name�sz
Task.get_namecCst|�|_dSr1)rJrI)rS�valuer!r!r"r2�sz
Task.set_namecCstd��dS)Nz*Task does not support set_result operation�r,)rS�resultr!r!r"�
set_result�szTask.set_resultcCstd��dS)Nz-Task does not support set_exception operationr^)rS�	exceptionr!r!r"�
set_exception�szTask.set_exception)�limitcCst�||�S)a�Return the list of stack frames for this task's coroutine.

        If the coroutine is not done, this returns the stack where it is
        suspended.  If the coroutine has completed successfully or was
        cancelled, this returns an empty list.  If the coroutine was
        terminated by an exception, this returns the list of traceback
        frames.

        The frames are always ordered from oldest to newest.

        The optional limit gives the maximum number of frames to
        return; by default all available frames are returned.  Its
        meaning differs depending on whether a stack or a traceback is
        returned: the newest frames of a stack are returned, but the
        oldest frames of a traceback are returned.  (This matches the
        behavior of the traceback module.)

        For reasons beyond our control, only one stack frame is
        returned for a suspended coroutine.
        )rZ_task_get_stack)rSrcr!r!r"�	get_stack�szTask.get_stack)rc�filecCst�|||�S)anPrint the stack or traceback for this task's coroutine.

        This produces output similar to that of the traceback module,
        for the frames retrieved by get_stack().  The limit argument
        is passed to get_stack().  The file argument is an I/O stream
        to which the output is written; by default output is written
        to sys.stderr.
        )rZ_task_print_stack)rSrcrer!r!r"�print_stack�s	zTask.print_stackcCs4d|_|��rdS|jdk	r*|j��r*dSd|_dS)a�Request that this task cancel itself.

        This arranges for a CancelledError to be thrown into the
        wrapped coroutine on the next cycle through the event loop.
        The coroutine then has a chance to clean up or even deny
        the request using try/except/finally.

        Unlike Future.cancel, this does not guarantee that the
        task will be cancelled: the exception might be caught and
        acted upon, delaying cancellation of the task or preventing
        cancellation completely.  The task may also return a value or
        raise a different exception.

        Immediately after this method is called, Task.cancelled() will
        not return True (unless the task was already cancelled).  A
        task will be marked as cancelled when the wrapped coroutine
        terminates with a CancelledError exception (even if cancel()
        was not called).
        FNT)Z_log_tracebackr%rL�cancelrKrYr!r!r"rg�s

zTask.cancelc
s�|��rt�d|�d|����|jr>t|tj�s8t��}d|_|j}d|_t|j	|��zfz"|dkrp|�d�}n
|�|�}Wn�t
k
r�}z*|jr�d|_t���nt��|j�W5d}~XY�n�tjk
r�t���Y�n�ttfk
�r}zt��|��W5d}~XY�n�tk
�rL}zt��|�W5d}~XY�npXt|dd�}|dk	�r@t�|�|j	k	�r�td|�d|�d��}|j	j|j||jd�n�|�r||k�r�td	|���}|j	j|j||jd�n8d|_|j|j|jd�||_|j�r>|j���r>d|_n*td
|�d|���}|j	j|j||jd�n||dk�r`|j	j|j|jd�n\t �!|��r�td|�d|���}|j	j|j||jd�n$td
|���}|j	j|j||jd�W5t
|j	|�d}XdS)Nz_step(): already done: z, F�_asyncio_future_blockingzTask z got Future z attached to a different loopr@zTask cannot await on itself: z-yield was used instead of yield from in task z with z;yield was used instead of yield from for generator in task zTask got bad yield: )"r%rZInvalidStateErrorrK�
isinstance�CancelledErrorrMrLrrPr�send�throw�
StopIterationrBrgr`r]�KeyboardInterrupt�
SystemExitrb�
BaseException�getattrrr$r,rQrRrOrh�add_done_callback�
_Task__wakeup�inspectZisgenerator)rS�excrTr_Zblocking�new_excrUr!r"Z__steps��  
��
�����
���
zTask.__stepc
CsJz|��Wn,tk
r8}z|�|�W5d}~XYn
X|��d}dSr1)r_rprR)rS�futurerur!r!r"Z__wakeup[sz
Task.__wakeup)N)N)N)�__name__�
__module__�__qualname__�__doc__rF�classmethodrrrCrXrZr[r\r2r`rbrdrfrgrRrs�
__classcell__r!r!rUr"rbs&
!Tr)r5cCs t��}|�|�}t||�|S)z]Schedule the execution of a coroutine object in a spawn task.

    Return a Task object.
    )rrrr6)rTr5r r4r!r!r"rxs

r)r �timeout�return_whenc�s�t�|�st�|�r(tdt|�j����|s4td��|tt	t
fkrPtd|�����dkrbt���nt
jdtdd��fdd	�t|�D�}t|||��IdHS)
a�Wait for the Futures and coroutines given by fs to complete.

    The fs iterable must not be empty.

    Coroutines will be wrapped in Tasks.

    Returns two sets of Future: (done, pending).

    Usage:

        done, pending = await asyncio.wait(fs)

    Note: This does not raise TimeoutError! Futures that aren't done
    when the timeout occurs are returned in the second set.
    zexpect a list of futures, not z#Set of coroutines/Futures is empty.zInvalid return_when value: N�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r7r8csh|]}t|�d��qS�r�r�r'�frr!r"r)�szwait.<locals>.<setcomp>)r�isfuturerrErG�typerx�
ValueErrorrrrrrr:r;r<�set�_wait)�fsr r~rr!rr"r�s
�rcGs|��s|�d�dSr1)r%r`)�waiter�argsr!r!r"�_release_waiter�sr�rc
�s�|dkrt��}ntjdtdd�|dkr4|IdHS|dkr�t||d�}|��rX|��St||d�IdHz|��Wn.t	j
k
r�}zt	��|�W5d}~XYn
Xt	���|��}|�
|t|�}t�t|�}t||d�}|�|�z�z|IdHWnPt	j
k
�rF|���r$|��YW�dS|�|�t||d�IdH�YnX|���r^|��W�*S|�|�t||d�IdHt	���W5|��XdS)a�Wait for the single Future or coroutine to complete, with timeout.

    Coroutine will be wrapped in Task.

    Returns result of the Future or coroutine.  When a timeout occurs,
    it cancels the task and raises TimeoutError.  To avoid the task
    cancellation, wrap it in shield().

    If the wait is cancelled, the task is also cancelled.

    This function is a coroutine.
    Nr�r7r8rr)rrr:r;r<rr%r_�_cancel_and_waitrrj�TimeoutError�
create_future�
call_laterr��	functools�partialrrrg�remove_done_callback)�futr~r rur��timeout_handle�cbr!r!r"r�sL

�





rc
�s�|std��|���d�|dk	r.|�|t���t|������fdd�}|D]}|�|�qLz�IdHW5�dk	r|���|D]}|�|�q�Xt�t�}}|D]"}|�	�r�|�
|�q�|�
|�q�||fS)zVInternal helper for wait().

    The fs argument must be a collection of Futures.
    zSet of Futures is empty.NcsZ�d8��dks4�tks4�tkrV|��sV|��dk	rV�dk	rD������sV��d�dS)Nrr)rr�	cancelledrargr%r`�r��Zcounterrr�r�r!r"�_on_completions���
�z_wait.<locals>._on_completion)�AssertionErrorr�r�r��lenrrrgr�r�r%�add)r�r~rr r�r�r%Zpendingr!r�r"r��s*r�c	�sF|��}t�t|�}|�|�z|��|IdHW5|�|�XdS)z<Cancel the *fut* future or task and wait until it completes.N)r�r�r�r�rrr�rg)r�r r�r�r!r!r"r�&s
r�)r r~c#s�t�|�st�|�r(tdt|�j����ddlm}|�d���dkrPt	�
��ntjdt
dd��fd	d
�t|�D��d����fdd�}���fd
d���fdd�}�D]}|���q��r�|dk	r҈�||��tt���D]}|�Vq�dS)a^Return an iterator whose values are coroutines.

    When waiting for the yielded coroutines you'll get the results (or
    exceptions!) of the original Futures (or coroutines), in the order
    in which and as soon as they complete.

    This differs from PEP 3148; the proper way to use this is:

        for f in as_completed(fs):
            result = await f  # The 'await' may raise.
            # Use result.

    If a timeout is specified, the 'await' will raise
    TimeoutError when the timeout occurs before all Futures are done.

    Note: The futures 'f' are not necessarily members of fs.
    z#expect an iterable of futures, not r)�QueuerNr�r7r8csh|]}t|�d��qSr�r�r�rr!r"r)Uszas_completed.<locals>.<setcomp>cs*�D]}|�����d�q���dSr1)r��
put_nowait�clearr�)r�r%�todor!r"�_on_timeoutXs
z!as_completed.<locals>._on_timeoutcs4�sdS��|���|��s0�dk	r0���dSr1)�remover�rgr�)r%r�r�r!r"r�^s

z$as_completed.<locals>._on_completionc�s$���IdH}|dkrtj�|��Sr1)rrr�r_r�)r%r!r"�
_wait_for_onefsz#as_completed.<locals>._wait_for_one)rr�rrErGr�rxZqueuesr�rr/r:r;r<r�rrr��ranger�)r�r r~r�r�r�r��_r!)r�r%r r�r�r"r7s*

�rccs
dVdS)z�Skip one event loop run cycle.

    This is a private helper for 'asyncio.sleep()', used
    when the 'delay' is set to 0.  It uses a bare 'yield'
    expression (which Task.__step knows how to handle)
    instead of creating a Future object.
    Nr!r!r!r!r"�__sleep0us	r�c�sr|dkrt�IdH|S|dkr*t��}ntjdtdd�|��}|�|tj	||�}z|IdHW�S|�
�XdS)z9Coroutine that completes after a given time (in seconds).rNr�r7r8)r�rrr:r;r<r�r�rZ_set_result_unless_cancelledrg)Zdelayr_r rw�hr!r!r"r	�s$
��r	cCs�t�|�r6|dkrt��}|�|�}|jr2|jd=|St�|�rb|dk	r^|t�|�k	r^t	d��|St
�|�r|tt
|�|d�Std��dS)zmWrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    Nr?zRThe future belongs to a different loop than the one specified as the loop argumentrz:An asyncio.Future, a coroutine or an awaitable is required)rrErr/rrDrr�r$r�rtZisawaitabler�_wrap_awaitablerG)Zcoro_or_futurer r4r!r!r"r�s



rccs|��EdHS)z�Helper for asyncio.ensure_future().

    Wraps awaitable (an object with __await__) into a coroutine
    that will later be wrapped in a Task by ensure_future().
    N)�	__await__)Z	awaitabler!r!r"r��sr�cs.eZdZdZdd��fdd�
Zdd�Z�ZS)�_GatheringFuturez�Helper for gather().

    This overrides cancel() to cancel all the children and act more
    like Task.cancel(), which doesn't immediately mark itself as
    cancelled.
    Nrcst�j|d�||_d|_dS)NrF)rBrC�	_children�_cancel_requested)rS�childrenr rUr!r"rC�sz_GatheringFuture.__init__cCs6|��rdSd}|jD]}|��rd}q|r2d|_|S)NFT)r%r�rgr�)rSZretZchildr!r!r"rg�s
z_GatheringFuture.cancel)rxryrzr{rCrgr}r!r!rUr"r��sr�F)r �return_exceptionscs�|s<|dkrt��}ntjdtdd�|�����g��S�����fdd�}i}g�d�d�|D]f}||kr�t||d�}|dkr�t�	|�}||k	r�d	|_
�d
7�|||<|�|�n||}��|�qdt
�|d���S)a�Return a future aggregating results from the given coroutines/futures.

    Coroutines will be wrapped in a future and scheduled in the event
    loop. They will not necessarily be scheduled in the same order as
    passed in.

    All futures must share the same event loop.  If all the tasks are
    done successfully, the returned future's result is the list of
    results (in the order of the original sequence, not necessarily
    the order of results arrival).  If *return_exceptions* is True,
    exceptions in the tasks are treated the same as successful
    results, and gathered in the result list; otherwise, the first
    raised exception will be immediately propagated to the returned
    future.

    Cancellation: if the outer Future is cancelled, all children (that
    have not completed yet) are also cancelled.  If any child is
    cancelled, this is treated as if it raised CancelledError --
    the outer Future is *not* cancelled in this case.  (This is to
    prevent the cancellation of one child to cause other children to
    be cancelled.)

    If *return_exceptions* is False, cancelling gather() after it
    has been marked done won't cancel any submitted awaitables.
    For instance, gather can be marked done after propagating an
    exception to the caller, therefore, calling ``gather.cancel()``
    after catching an exception (raised by one of the awaitables) from
    gather won't cancel any other awaitables.
    Nr�r7r8cs��d7����r$|��s |��dS�sd|��rFt��}��|�dS|��}|dk	rd��|�dS��kr�g}�D]8}|��r�t��}n|��}|dkr�|��}|�|�qt�jrĈ�t���n
��	|�dS)Nr)
r%r�rarrjrbr_�appendr�r`)r�ruZresults�res�r�Z	nfinishedZnfuts�outerr�r!r"�_done_callbacks4


zgather.<locals>._done_callbackrrFr)rr/r:r;r<r�r`rrr$rFrrr�r�)r r�Zcoros_or_futuresr�Z
arg_to_fut�argr�r!r�r"r
�s:
�
1
r
cst|dk	rtjdtdd�t||d�����r0�St���}|����fdd����fdd	�}������|��S)
a.Wait for a future, shielding it from cancellation.

    The statement

        res = await shield(something())

    is exactly equivalent to the statement

        res = await something()

    *except* that if the coroutine containing it is cancelled, the
    task running in something() is not cancelled.  From the POV of
    something(), the cancellation did not happen.  But its caller is
    still cancelled, so the yield-from expression still raises
    CancelledError.  Note: If something() is cancelled by other means
    this will still cancel shield().

    If you want to completely ignore cancellation (not recommended)
    you can combine shield() with a try/except clause, as follows:

        try:
            res = await shield(something())
        except CancelledError:
            res = None
    Nr�r7r8rcs\���r|��s|��dS|��r.���n*|��}|dk	rJ��|�n��|���dSr1)r�rargrbr`r_)�innerru�r�r!r"�_inner_done_callbackus
z$shield.<locals>._inner_done_callbackcs���s����dSr1)r%r�r�)r�r�r!r"�_outer_done_callback�sz$shield.<locals>._outer_done_callback)	r:r;r<rr%rr$r�rr)r�r r�r!)r�r�r�r"rPs�


rcs:t���std��tj������fdd�}��|��S)zsSubmit a coroutine object to a given event loop.

    Return a concurrent.futures.Future to access the result.
    zA coroutine object is requiredc
slzt�t��d���WnNttfk
r2�Yn6tk
rf}z���rT��|��W5d}~XYnXdS)Nr)rZ
_chain_futurerrornrpZset_running_or_notify_cancelrb)ru�rTrwr r!r"�callback�s
z*run_coroutine_threadsafe.<locals>.callback)rrErG�
concurrentr�FutureZcall_soon_threadsafe)rTr r�r!r�r"r
�s



r
cCst�|�dS)z3Register a new task in asyncio as executed by loop.N)r+r��r4r!r!r"r�srcCs4t�|�}|dk	r(td|�d|�d���|t|<dS)NzCannot enter into task z while another task z is being executed.�rrr,�r r4rr!r!r"r�s
rcCs2t�|�}||k	r(td|�d|�d���t|=dS)Nz
Leaving task z! does not match the current task �.r�r�r!r!r"r�s
rcCst�|�dS)zUnregister a task.N)r+�discardr�r!r!r"r�sr)rrrrr+r)N)N)N)N)Br{�__all__Zconcurrent.futuresr�rNr�rt�	itertools�typesr:�weakref�rrrrrr�count�__next__rHrrr0r6Z	_PyFuturerZ_PyTaskZ_asyncio�ImportErrorZ_CTaskrrrrrr�rr�r�r�	coroutiner�r	rr�r�r�r
rr
ZWeakSetr+rrrrrZ_py_register_taskZ_py_unregister_taskZ_py_enter_taskZ_py_leave_taskZ_c_register_taskZ_c_unregister_taskZ
_c_enter_taskZ
_c_leave_taskr!r!r!r"�<module>s�	





#H,>

x?$PK [�S�Y�s�s0__pycache__/selector_events.cpython-38.opt-1.pycnu�[���U

e5dT��@s.dZdZddlZddlZddlZddlZddlZddlZddlZzddl	Z	Wne
k
rddZ	YnXddlmZddlm
Z
ddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZdd�Zdd�ZGdd�dej�ZGdd�dejej�ZGdd�de�ZGdd�de�ZdS)z�Event loop using a selector and related classes.

A selector is a "notify-when-ready" multiplexer.  For a subclass which
also includes support for signal handling, see the unix_events sub-module.
)�BaseSelectorEventLoop�N�)�base_events)�	constants)�events)�futures)�	protocols)�sslproto)�
transports)�trsock)�loggercCs8z|�|�}Wntk
r$YdSXt|j|@�SdS�NF)�get_key�KeyError�boolr)�selector�fdZevent�key�r�//usr/lib64/python3.8/asyncio/selector_events.py�_test_selector_event s
rcCs tdk	rt|tj�rtd��dS)Nz"Socket cannot be of type SSLSocket)�ssl�
isinstanceZ	SSLSocket�	TypeError)�sockrrr�_check_ssl_socket+srcs�eZdZdZdS�fdd�	ZdTddd�dd�ZdUddddejd	�d
d�ZdVdd
�Z	�fdd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdddejfdd�Zdddejfdd�Zddejfdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd9d:�Zd;d<�Z d=d>�Z!d?d@�Z"dAdB�Z#dCdD�Z$dEdF�Z%dGdH�Z&dIdJ�Z'dKdL�Z(dMdN�Z)dOdP�Z*dQdR�Z+�Z,S)WrzJSelector event loop.

    See events.EventLoop for API specification.
    NcsFt���|dkrt��}t�d|jj�||_|�	�t
��|_dS)NzUsing selector: %s)
�super�__init__�	selectorsZDefaultSelectorr�debug�	__class__�__name__�	_selector�_make_self_pipe�weakrefZWeakValueDictionary�_transports)�selfr�r rrr6s
zBaseSelectorEventLoop.__init__��extra�servercCst||||||�S�N)�_SelectorSocketTransport)r&r�protocol�waiterr)r*rrr�_make_socket_transport@s
�z,BaseSelectorEventLoop._make_socket_transportF)�server_side�server_hostnamer)r*�ssl_handshake_timeoutc	Cs0tj|||||||	d�}
t|||
||d�|
jS)N)r2r()r	ZSSLProtocolr,Z_app_transport)r&Zrawsockr-�
sslcontextr.r0r1r)r*r2Zssl_protocolrrr�_make_ssl_transportEs��z)BaseSelectorEventLoop._make_ssl_transportcCst||||||�Sr+)�_SelectorDatagramTransport)r&rr-�addressr.r)rrr�_make_datagram_transportRs
�z.BaseSelectorEventLoop._make_datagram_transportcsL|��rtd��|��rdS|��t���|jdk	rH|j��d|_dS)Nz!Cannot close a running event loop)Z
is_running�RuntimeError�	is_closed�_close_self_piper�closer"�r&r'rrr;Ws


zBaseSelectorEventLoop.closecCsB|�|j���|j��d|_|j��d|_|jd8_dS)Nr)�_remove_reader�_ssock�filenor;�_csock�
_internal_fdsr<rrrr:bs

z&BaseSelectorEventLoop._close_self_pipecCsNt��\|_|_|j�d�|j�d�|jd7_|�|j��|j�dS)NFr)	�socketZ
socketpairr>r@�setblockingrA�_add_readerr?�_read_from_selfr<rrrr#js
z%BaseSelectorEventLoop._make_self_pipecCsdSr+r�r&�datarrr�_process_self_datarsz(BaseSelectorEventLoop._process_self_datacCsXz"|j�d�}|sWqT|�|�Wqtk
r:YqYqtk
rPYqTYqXqdS)Ni)r>�recvrH�InterruptedError�BlockingIOErrorrFrrrrEusz%BaseSelectorEventLoop._read_from_selfcCsN|j}|dkrdSz|�d�Wn(tk
rH|jrDtjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketT��exc_info)r@�send�OSError�_debugrr)r&Zcsockrrr�_write_to_self�s�z$BaseSelectorEventLoop._write_to_self�dc
Cs"|�|��|j||||||�dSr+)rDr?�_accept_connection)r&�protocol_factoryrr3r*�backlogr2rrr�_start_serving�s�z$BaseSelectorEventLoop._start_servingc
Cst|�D]�}z0|��\}}	|jr0t�d||	|�|�d�Wn�tttfk
rZYdSt	k
r�}
zd|
j
t
jt
jt
j
t
jfkr�|�d|
t�|�d��|�|���|�tj|j||||||�n�W5d}
~
XYqXd|	i}|�||||||�}|�|�qdS)Nz#%r got a new connection from %r: %rFz&socket.accept() out of system resource)�message�	exceptionrB�peername)�range�acceptrQrrrCrKrJ�ConnectionAbortedErrorrP�errnoZEMFILEZENFILEZENOBUFSZENOMEM�call_exception_handlerr�TransportSocketr=r?Z
call_laterrZACCEPT_RETRY_DELAYrW�_accept_connection2Zcreate_task)
r&rUrr3r*rVr2�_�conn�addr�excr)r\rrrrT�sV�����z(BaseSelectorEventLoop._accept_connectionc
�s�d}d}zt|�}|��}	|r8|j||||	d|||d�}n|j|||	||d�}z|	IdHWntk
rx|���YnXWntttfk
r��Yn\tk
r�}
z>|jr�d|
d�}|dk	r�||d<|dk	r�||d<|�|�W5d}
~
XYnXdS)NT)r.r0r)r*r2)r.r)r*z3Error on transport creation for incoming connection)rXrYr-�	transport)	�
create_futurer4r/�
BaseExceptionr;�
SystemExit�KeyboardInterruptrQr_)r&rUrcr)r3r*r2r-rfr.re�contextrrrra�sP���z)BaseSelectorEventLoop._accept_connection2c
Cs�|}t|t�sJzt|���}Wn*tttfk
rHtd|���d�YnXz|j|}Wntk
rlYnX|��s�t	d|�d|����dS)NzInvalid file object: zFile descriptor z is used by transport )
r�intr?�AttributeErrorr�
ValueErrorr%r�
is_closingr8)r&rr?rfrrr�_ensure_fd_no_transport�s
�z-BaseSelectorEventLoop._ensure_fd_no_transportc		Gs�|��t�|||d�}z|j�|�}Wn*tk
rR|j�|tj|df�Yn>X|j|j	}\}}|j�
||tjB||f�|dk	r�|��dSr+)�
_check_closedr�Handler"rr�registerr�
EVENT_READrG�modify�cancel�	r&r�callback�argsZhandler�mask�reader�writerrrrrDs�
�z!BaseSelectorEventLoop._add_readercCs�|��rdSz|j�|�}Wntk
r2YdSX|j|j}\}}|tjM}|sd|j�|�n|j�	||d|f�|dk	r�|�
�dSdSdS�NFT)r9r"rrrrGrrt�
unregisterrurv�r&rrrzr{r|rrrr=sz$BaseSelectorEventLoop._remove_readerc		Gs�|��t�|||d�}z|j�|�}Wn*tk
rR|j�|tjd|f�Yn>X|j|j	}\}}|j�
||tjB||f�|dk	r�|��dSr+)rqrrrr"rrrsr�EVENT_WRITErGrurvrwrrr�_add_writer%s�
�z!BaseSelectorEventLoop._add_writercCs�|��rdSz|j�|�}Wntk
r2YdSX|j|j}\}}|tjM}|sd|j�|�n|j�	|||df�|dk	r�|�
�dSdSdS)�Remove a writer callback.FNT)r9r"rrrrGrr�r~rurvrrrr�_remove_writer4sz$BaseSelectorEventLoop._remove_writercGs|�|�|j||f|��S)zAdd a reader callback.)rprD�r&rrxryrrr�
add_readerKs
z BaseSelectorEventLoop.add_readercCs|�|�|�|�S)zRemove a reader callback.)rpr=�r&rrrr�
remove_readerPs
z#BaseSelectorEventLoop.remove_readercGs|�|�|j||f|��S)zAdd a writer callback..)rpr�r�rrr�
add_writerUs
z BaseSelectorEventLoop.add_writercCs|�|�|�|�S)r�)rpr�r�rrr�
remove_writerZs
z#BaseSelectorEventLoop.remove_writerc	�s�t|�|jr"|��dkr"td��z|�|�WSttfk
rFYnX|��}|��}|�	||j
|||�|�t�
|j|��|IdHS)z�Receive data from the socket.

        The return value is a bytes object representing the data received.
        The maximum amount of data to be received at once is specified by
        nbytes.
        r�the socket must be non-blockingN)rrQ�
gettimeoutrnrIrKrJrgr?r��
_sock_recv�add_done_callback�	functools�partial�_sock_read_done)r&r�n�futrrrr�	sock_recv_s�zBaseSelectorEventLoop.sock_recvcCs|�|�dSr+)r��r&rr�rrrr�tsz%BaseSelectorEventLoop._sock_read_donec
Cs�|��rdSz|�|�}Wn\ttfk
r4YdSttfk
rL�Yn6tk
rv}z|�|�W5d}~XYnX|�|�dSr+)	�donerIrKrJrirjrh�
set_exception�
set_result)r&r�rr�rGrerrrr�wsz BaseSelectorEventLoop._sock_recvc	�s�t|�|jr"|��dkr"td��z|�|�WSttfk
rFYnX|��}|��}|�	||j
|||�|�t�
|j|��|IdHS)z�Receive data from the socket.

        The received data is written into *buf* (a writable buffer).
        The return value is the number of bytes written.
        rr�N)rrQr�rn�	recv_intorKrJrgr?r��_sock_recv_intor�r�r�r�)r&r�bufr�rrrr�sock_recv_into�s�z$BaseSelectorEventLoop.sock_recv_intoc
Cs�|��rdSz|�|�}Wn\ttfk
r4YdSttfk
rL�Yn6tk
rv}z|�|�W5d}~XYnX|�|�dSr+)	r�r�rKrJrirjrhr�r�)r&r�rr��nbytesrerrrr��sz%BaseSelectorEventLoop._sock_recv_intoc	�s�t|�|jr"|��dkr"td��z|�|�}Wnttfk
rLd}YnX|t|�kr^dS|��}|�	�}|�
t�|j
|��|�||j||t|�|g�|IdHS)a�Send data to the socket.

        The socket must be connected to a remote socket. This method continues
        to send data from data until either all data has been sent or an
        error occurs. None is returned on success. On error, an exception is
        raised, and there is no way to determine how much data, if any, was
        successfully processed by the receiving end of the connection.
        rr�N)rrQr�rnrOrKrJ�lenrgr?r�r�r��_sock_write_doner��
_sock_sendall�
memoryview)r&rrGr�r�rrrr�sock_sendall�s&	
��z"BaseSelectorEventLoop.sock_sendallc
Cs�|��rdS|d}z|�||d��}Wnbttfk
rDYdSttfk
r\�Yn2tk
r�}z|�|�WY�dSd}~XYnX||7}|t|�kr�|�	d�n||d<dS)Nr)
r�rOrKrJrirjrhr�r�r�)r&r�rZview�pos�startr�rerrrr��s 
z#BaseSelectorEventLoop._sock_sendallc�s�t|�|jr"|��dkr"td��ttd�r8|jtjkrf|j||j|j	|d�IdH}|d\}}}}}|�
�}|�|||�|IdHS)zTConnect to a remote socket at address.

        This method is a coroutine.
        rr��AF_UNIX)�family�proto�loopN)rrQr�rn�hasattrrBr�r�Z_ensure_resolvedr�rg�
_sock_connect)r&rr6Zresolvedrbr�rrr�sock_connect�s�z"BaseSelectorEventLoop.sock_connectc
Cs�|��}z|�|�Wn�ttfk
rV|�t�|j|��|�||j	|||�YnNt
tfk
rn�Yn6tk
r�}z|�
|�W5d}~XYnX|�d�dSr+)r?ZconnectrKrJr�r�r�r�r��_sock_connect_cbrirjrhr�r�)r&r�rr6rrerrrr��s�z#BaseSelectorEventLoop._sock_connectcCs|�|�dSr+)r�r�rrrr�sz&BaseSelectorEventLoop._sock_write_donec
Cs�|��rdSz,|�tjtj�}|dkr6t|d|����WnZttfk
rPYnNtt	fk
rh�Yn6t
k
r�}z|�|�W5d}~XYnX|�d�dS)NrzConnect call failed )
r�Z
getsockoptrBZ
SOL_SOCKETZSO_ERRORrPrKrJrirjrhr�r�)r&r�rr6�errrerrrr�sz&BaseSelectorEventLoop._sock_connect_cbc�sBt|�|jr"|��dkr"td��|��}|�|d|�|IdHS)aWAccept a connection.

        The socket must be bound to an address and listening for connections.
        The return value is a pair (conn, address) where conn is a new socket
        object usable to send and receive data on the connection, and address
        is the address bound to the socket on the other end of the connection.
        rr�FN)rrQr�rnrg�_sock_accept)r&rr�rrr�sock_acceptsz!BaseSelectorEventLoop.sock_acceptc
Cs�|��}|r|�|�|��r"dSz|��\}}|�d�Wnnttfk
rh|�||j|d|�YnRt	t
fk
r��Yn:tk
r�}z|�|�W5d}~XYnX|�
||f�dSr})r?r�r�r\rCrKrJr�r�rirjrhr�r�)r&r�Z
registeredrrrcr6rerrrr�*s
z"BaseSelectorEventLoop._sock_acceptc	�sp|j|j=|��}|��|��IdHz |j|j|||dd�IdHW�S|��|r^|��||j|j<XdS)NF)Zfallback)	r%�_sock_fd�
is_reading�
pause_reading�_make_empty_waiter�_reset_empty_waiter�resume_readingZ
sock_sendfile�_sock)r&Ztransp�file�offset�countr�rrr�_sendfile_native<s
�z&BaseSelectorEventLoop._sendfile_nativecCs�|D]v\}}|j|j}\}}|tj@rL|dk	rL|jrB|�|�n
|�|�|tj@r|dk	r|jrp|�|�q|�|�qdSr+)	�fileobjrGrrtZ
_cancelledr=Z
_add_callbackr�r�)r&Z
event_listrrzr�r{r|rrr�_process_eventsJs
z%BaseSelectorEventLoop._process_eventscCs|�|���|��dSr+)r=r?r;)r&rrrr�
_stop_servingXsz#BaseSelectorEventLoop._stop_serving)N)N)N)NNN)-r!�
__module__�__qualname__�__doc__rr/rZSSL_HANDSHAKE_TIMEOUTr4r7r;r:r#rHrErRrWrTrarprDr=r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��
__classcell__rrr'rr0s~
����
�
	�
.�
)rcs�eZdZdZeZdZd�fdd�	Zdd�Zdd�Z	d	d
�Z
dd�Zd
d�Zdd�Z
ejfdd�Zddd�Zdd�Zdd�Zdd�Zdd�Z�ZS) �_SelectorTransportiNcs�t��||�t�|�|jd<z|��|jd<Wntk
rNd|jd<YnXd|jkr�z|��|jd<Wn tj	k
r�d|jd<YnX||_
|��|_d|_
|�|�||_|��|_d|_d|_|jdk	r�|j��||j|j<dS)NrBZsocknamerZFr)rrrr`�_extraZgetsocknamerPZgetpeernamerB�errorr�r?r��_protocol_connected�set_protocol�_server�_buffer_factory�_buffer�
_conn_lost�_closingZ_attachr%)r&r�rr-r)r*r'rrris,





z_SelectorTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���|jdk	r�|j��s�t|jj	|jt
j�}|rz|�d�n
|�d�t|jj	|jt
j�}|r�d}nd}|�
�}|�d|�d	|�d
��d�d�|��S)
N�closed�closingzfd=zread=pollingz	read=idle�pollingZidlezwrite=<z
, bufsize=�>z<{}>� )r r!r��appendr�r��_loopr9rr"rrtr��get_write_buffer_size�format�join)r&�infor��state�bufsizerrr�__repr__�s0


�
�z_SelectorTransport.__repr__cCs|�d�dSr+)�_force_closer<rrr�abort�sz_SelectorTransport.abortcCs||_d|_dS�NT)�	_protocolr��r&r-rrrr��sz_SelectorTransport.set_protocolcCs|jSr+)r�r<rrr�get_protocol�sz_SelectorTransport.get_protocolcCs|jSr+)r�r<rrrro�sz_SelectorTransport.is_closingcCsT|jr
dSd|_|j�|j�|jsP|jd7_|j�|j�|j�|jd�dS�NTr)	r�r�r=r�r�r�r��	call_soon�_call_connection_lostr<rrrr;�sz_SelectorTransport.closecCs,|jdk	r(|d|��t|d�|j��dS)Nzunclosed transport )�source)r��ResourceWarningr;)r&Z_warnrrr�__del__�s
z_SelectorTransport.__del__�Fatal error on transportcCsNt|t�r(|j��r@tjd||dd�n|j�||||jd��|�|�dS)Nz%r: %sTrM)rXrYrfr-)	rrPr��	get_debugrrr_r�r�)r&rerXrrr�_fatal_error�s

�z_SelectorTransport._fatal_errorcCsd|jr
dS|jr(|j��|j�|j�|jsBd|_|j�|j�|jd7_|j�|j	|�dSr�)
r�r��clearr�r�r�r�r=r�r��r&rerrrr��s
z_SelectorTransport._force_closecCsVz|jr|j�|�W5|j��d|_d|_d|_|j}|dk	rP|��d|_XdSr+)r�r;r�r�r�Z_detachr�Zconnection_lost)r&rer*rrrr��s
z(_SelectorTransport._call_connection_lostcCs
t|j�Sr+)r�r�r<rrrr��sz(_SelectorTransport.get_write_buffer_sizecGs"|jr
dS|jj||f|��dSr+)r�r�rDr�rrrrD�sz_SelectorTransport._add_reader)NN)r�)r!r�r��max_size�	bytearrayr�r�rr�r�r�r�ror;�warnings�warnr�r�r�r�r�rDr�rrr'rr�]s 

r�cs�eZdZdZejjZd#�fdd�	Z�fdd�Z	dd�Z
d	d
�Zdd�Zd
d�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Z�fdd�Zdd �Zd!d"�Z�ZS)$r,TNcs~d|_t��|||||�d|_d|_d|_t�|j�|j	�
|jj|�|j	�
|j
|j|j�|dk	rz|j	�
tj|d�dSr
)�_read_ready_cbrr�_eof�_paused�
_empty_waiterrZ_set_nodelayr�r�r�r��connection_maderDr��_read_readyr�_set_result_unless_cancelled)r&r�rr-r.r)r*r'rrr�s 
�
�z!_SelectorSocketTransport.__init__cs.t|tj�r|j|_n|j|_t��|�dSr+)rrZBufferedProtocol�_read_ready__get_bufferr��_read_ready__data_receivedrr�r�r'rrr�	s
z%_SelectorSocketTransport.set_protocolcCs|jo|jSr+)r�r�r<rrrr�sz#_SelectorSocketTransport.is_readingcCs>|js|jrdSd|_|j�|j�|j��r:t�d|�dS)NTz%r pauses reading)r�r�r�r=r�r�rrr<rrrr�s
z&_SelectorSocketTransport.pause_readingcCs@|js|jsdSd|_|�|j|j�|j��r<t�d|�dS)NFz%r resumes reading)	r�r�rDr�r�r�r�rrr<rrrr�s
z'_SelectorSocketTransport.resume_readingcCs|��dSr+)r�r<rrrr�$sz$_SelectorSocketTransport._read_readyc
Cs`|jr
dSz |j�d�}t|�s(td��WnLttfk
rD�Yn4tk
rv}z|�|d�WY�dSd}~XYnXz|j	�
|�}Wndttfk
r�YdSttfk
r��Yn4tk
r�}z|�|d�WY�dSd}~XYnX|�s|�
�dSz|j�|�WnJttfk
�r,�Yn0tk
�rZ}z|�|d�W5d}~XYnXdS)N���z%get_buffer() returned an empty bufferz/Fatal error: protocol.get_buffer() call failed.�$Fatal read error on socket transportz3Fatal error: protocol.buffer_updated() call failed.)r�r�Z
get_bufferr�r8rirjrhr�r�r�rKrJ�_read_ready__on_eofZbuffer_updated)r&r�rer�rrrr�'sF��z0_SelectorSocketTransport._read_ready__get_bufferc
Cs�|jr
dSz|j�|j�}Wndttfk
r6YdSttfk
rN�Yn4tk
r�}z|�	|d�WY�dSd}~XYnX|s�|�
�dSz|j�|�WnFttfk
r��Yn.tk
r�}z|�	|d�W5d}~XYnXdS)Nr�z2Fatal error: protocol.data_received() call failed.)
r�r�rIr�rKrJrirjrhr�r�r�Z
data_received)r&rGrerrrr�Ls.�z3_SelectorSocketTransport._read_ready__data_receivedc
Cs�|j��rt�d|�z|j��}WnLttfk
r>�Yn4tk
rp}z|�	|d�WY�dSd}~XYnX|r�|j�
|j�n|��dS)Nz%r received EOFz1Fatal error: protocol.eof_received() call failed.)
r�r�rrr�Zeof_receivedrirjrhr�r=r�r;)r&Z	keep_openrerrrr�es
�z,_SelectorSocketTransport._read_ready__on_eofc
Cs6t|tttf�s$tdt|�j����|jr2td��|j	dk	rDtd��|sLdS|j
rz|j
tjkrht
�d�|j
d7_
dS|j�sz|j�|�}Wnbttfk
r�Ynbttfk
r��YnJtk
r�}z|�|d�WY�dSd}~XYnX||d�}|�sdS|j�|j|j�|j�|�|��dS)N�/data argument must be a bytes-like object, not z%Cannot call write() after write_eof()z(unable to write; sendfile is in progress�socket.send() raised exception.r�%Fatal write error on socket transport)r�bytesr�r�r�typer!r�r8r�r�r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESr�warningr�r�rOrKrJrirjrhr�r�r�r��_write_ready�extend�_maybe_pause_protocol)r&rGr�rerrr�writezs:

z_SelectorSocketTransport.writec
Cs|jr
dSz|j�|j�}Wn�ttfk
r4Yn�ttfk
rL�Yn�tk
r�}z>|j	�
|j�|j��|�
|d�|jdk	r�|j�|�W5d}~XYnnX|r�|jd|�=|��|j�s|j	�
|j�|jdk	r�|j�d�|jr�|�d�n|j�r|j�tj�dS)Nr�)r�r�rOr�rKrJrirjrhr�r�r�r�r�r�r��_maybe_resume_protocolr�r�r�r��shutdownrB�SHUT_WR)r&r�rerrrr�s2


z%_SelectorSocketTransport._write_readycCs.|js|jrdSd|_|js*|j�tj�dSr�)r�r�r�r�rrBrr<rrr�	write_eof�s
z"_SelectorSocketTransport.write_eofcCsdSr�rr<rrr�
can_write_eof�sz&_SelectorSocketTransport.can_write_eofcs*t��|�|jdk	r&|j�td��dS)NzConnection is closed by peer)rr�r�r��ConnectionErrorr�r'rrr��s

�z._SelectorSocketTransport._call_connection_lostcCs6|jdk	rtd��|j��|_|js0|j�d�|jS)NzEmpty waiter is already set)r�r8r�rgr�r�r<rrrr��s
z+_SelectorSocketTransport._make_empty_waitercCs
d|_dSr+)r�r<rrrr��sz,_SelectorSocketTransport._reset_empty_waiter)NNN)r!r�r�Z_start_tls_compatiblerZ
_SendfileModeZ
TRY_NATIVEZ_sendfile_compatiblerr�r�r�r�r�r�r�r�rrrr	r�r�r�r�rrr'rr,�s*�%'r,csFeZdZejZd�fdd�	Zdd�Zdd�Zd
dd	�Z	d
d�Z
�ZS)r5Ncs^t��||||�||_|j�|jj|�|j�|j|j|j	�|dk	rZ|j�t
j|d�dSr+)rr�_addressr�r�r�r�rDr�r�rr�)r&r�rr-r6r.r)r'rrr�s
�
�z#_SelectorDatagramTransport.__init__cCstdd�|jD��S)Ncss|]\}}t|�VqdSr+)r�)�.0rGrbrrr�	<genexpr>�szC_SelectorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr�r<rrrr��sz0_SelectorDatagramTransport.get_write_buffer_sizec
Cs�|jr
dSz|j�|j�\}}Wn�ttfk
r8Yn�tk
rd}z|j�|�W5d}~XYnTt	t
fk
r|�Yn<tk
r�}z|�|d�W5d}~XYnX|j�
||�dS)Nz&Fatal read error on datagram transport)r�r�Zrecvfromr�rKrJrPr��error_receivedrirjrhr�Zdatagram_received�r&rGrdrerrrr��sz&_SelectorDatagramTransport._read_readyc
Cs�t|tttf�s$tdt|�j����|s,dS|jrV|d|jfkrPtd|j����|j}|j	r�|jr�|j	t
jkrxt�
d�|j	d7_	dS|j�slz,|jdr�|j�|�n|j�||�WdSttfk
r�|j�|j|j�Yn�tk
�r}z|j�|�WY�dSd}~XYnPttfk
�r6�Yn6tk
�rj}z|�|d�WY�dSd}~XYnX|j� t|�|f�|�!�dS)Nr�z!Invalid address: must be None or r�rrZ�'Fatal write error on datagram transport)"rr�r�r�rr�r!rrnr�rr�rrr�r�r�rO�sendtorKrJr�r�r��
_sendto_readyrPr�rrirjrhr�r�rrrrrr�sH
�

�z!_SelectorDatagramTransport.sendtoc
Cs|jr�|j��\}}z*|jdr.|j�|�n|j�||�Wqttfk
rj|j�||f�Yq�Yqt	k
r�}z|j
�|�WY�dSd}~XYqtt
fk
r��Yqtk
r�}z|�|d�WY�dSd}~XYqXq|��|j�s|j�|j�|j�r|�d�dS)NrZr)r��popleftr�r�rOrrKrJ�
appendleftrPr�rrirjrhr�rr�r�r�r�r�rrrrr*s2
�z(_SelectorDatagramTransport._sendto_ready)NNN)N)r!r�r��collections�dequer�rr�r�rrr�rrr'rr5�s�

+r5)r��__all__rr^r�rrBr�r$r�ImportError�rrrrrr	r
r�logrrrZ
BaseEventLooprZ_FlowControlMixinZ	Transportr�r,r5rrrr�<module>sF
1�oPK [��M�""+__pycache__/subprocess.cpython-38.opt-2.pycnu�[���U

e5d��@s�dZddlZddlZddlmZddlmZddlmZddlmZddlm	Z	ej
Z
ejZejZGd	d
�d
ej
ej�ZGdd�d�Zddddejfd
d�Zddddejd�dd�ZdS))�create_subprocess_exec�create_subprocess_shell�N�)�events)�	protocols)�streams)�tasks)�loggercsTeZdZ�fdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
�ZS)�SubprocessStreamProtocolcsHt�j|d�||_d|_|_|_d|_d|_g|_|j	�
�|_dS)N��loopF)�super�__init__�_limit�stdin�stdout�stderr�
_transport�_process_exited�	_pipe_fds�_loopZ
create_future�
_stdin_closed)�self�limitr��	__class__��*/usr/lib64/python3.8/asyncio/subprocess.pyrsz!SubprocessStreamProtocol.__init__cCsn|jjg}|jdk	r&|�d|j���|jdk	rB|�d|j���|jdk	r^|�d|j���d�d�|��S)Nzstdin=zstdout=zstderr=z<{}>� )r�__name__r�appendrr�format�join)r�inforrr�__repr__s



z!SubprocessStreamProtocol.__repr__cCs�||_|�d�}|dk	rDtj|j|jd�|_|j�|�|j�	d�|�d�}|dk	r�tj|j|jd�|_
|j
�|�|j�	d�|�d�}|dk	r�tj||d|jd�|_dS)Nr�rr�r)�protocol�readerr)
r�get_pipe_transportr�StreamReaderrrrZ
set_transportrr r�StreamWriterr)r�	transportZstdout_transportZstderr_transportZstdin_transportrrr�connection_made)s,
�
�
�z(SubprocessStreamProtocol.connection_madecCs:|dkr|j}n|dkr |j}nd}|dk	r6|�|�dS)Nrr&)rrZ	feed_data)r�fd�datar(rrr�pipe_data_receivedAsz+SubprocessStreamProtocol.pipe_data_receivedcCs�|dkrN|j}|dk	r|��|�|�|dkr>|j�d�n|j�|�dS|dkr^|j}n|dkrn|j}nd}|dk	r�|dkr�|��n
|�|�||j	kr�|j	�
|�|��dS)Nrrr&)r�closeZconnection_lostrZ
set_resultZ
set_exceptionrrZfeed_eofr�remove�_maybe_close_transport)rr.�exc�piper(rrr�pipe_connection_lostKs*



z-SubprocessStreamProtocol.pipe_connection_lostcCsd|_|��dS)NT)rr3�rrrr�process_exitedfsz'SubprocessStreamProtocol.process_exitedcCs(t|j�dkr$|jr$|j��d|_dS)Nr)�lenrrrr1r7rrrr3js
z/SubprocessStreamProtocol._maybe_close_transportcCs||jkr|jSdS�N)rr)r�streamrrr�_get_close_waiteros
z*SubprocessStreamProtocol._get_close_waiter)r�
__module__�__qualname__rr$r-r0r6r8r3r<�
__classcell__rrrrr
s	

r
c@sjeZdZdd�Zdd�Zedd��Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
ddd�ZdS)�ProcesscCs8||_||_||_|j|_|j|_|j|_|��|_dSr:)rZ	_protocolrrrrZget_pid�pid)rr,r'rrrrruszProcess.__init__cCsd|jj�d|j�d�S)N�<r�>)rrrAr7rrrr$~szProcess.__repr__cCs
|j��Sr:)rZget_returncoder7rrr�
returncode�szProcess.returncodec�s|j��IdHSr:)rZ_waitr7rrr�wait�szProcess.waitcCs|j�|�dSr:)r�send_signal)r�signalrrrrF�szProcess.send_signalcCs|j��dSr:)r�	terminater7rrrrH�szProcess.terminatecCs|j��dSr:)r�killr7rrrrI�szProcess.killc
�s�|j��}|j�|�|r,t�d|t|��z|j��IdHWn8tt	fk
rx}z|rht�d||�W5d}~XYnX|r�t�d|�|j�
�dS)Nz%%r communicate: feed stdin (%s bytes)z%r communicate: stdin got %rz%r communicate: close stdin)r�	get_debugr�writer	�debugr9Zdrain�BrokenPipeError�ConnectionResetErrorr1)r�inputrLr4rrr�_feed_stdin�s 
� zProcess._feed_stdinc�sdSr:rr7rrr�_noop�sz
Process._noopc�s�|j�|�}|dkr|j}n|j}|j��rJ|dkr8dnd}t�d||�|��IdH}|j��r�|dkrndnd}t�d||�|�	�|S)Nr&rrrz%r communicate: read %sz%r communicate: close %s)
rr)rrrrJr	rL�readr1)rr.r,r;�name�outputrrr�_read_stream�s

zProcess._read_streamNc�s�|dk	r|�|�}n|��}|jdk	r2|�d�}n|��}|jdk	rP|�d�}n|��}tj||||jd�IdH\}}}|��IdH||fS)Nrr&r)	rPrQrrUrrZgatherrrE)rrOrrrrrr�communicate�s


�zProcess.communicate)N)rr=r>rr$�propertyrDrErFrHrIrPrQrUrVrrrrr@ts	
r@c
�sb�dkrt���ntjdtdd���fdd�}�j||f|||d�|��IdH\}}	t||	��S)N�ZThe loop argument is deprecated since Python 3.8 and scheduled for removal in Python 3.10.r&��
stacklevelcst��d�S�Nr%�r
rr%rr�<lambda>�s�z)create_subprocess_shell.<locals>.<lambda>�rrr)r�get_event_loop�warnings�warn�DeprecationWarningZsubprocess_shellr@)
�cmdrrrrr�kwds�protocol_factoryr,r'rr%rr�s$
����r)rrrrrc�sf�dkrt���ntjdtdd���fdd�}�j||f|�|||d�|��IdH\}	}
t|	|
��S)NrXr&rYcst��d�Sr[r\rr%rrr]�s�z(create_subprocess_exec.<locals>.<lambda>r^)rr_r`rarbZsubprocess_execr@)Zprogramrrrrr�argsrdrer,r'rr%rr�s(
�����r)�__all__�
subprocessr`�rrrr�logr	�PIPEZSTDOUTZDEVNULLZFlowControlMixinZSubprocessProtocolr
r@Z_DEFAULT_LIMITrrrrrr�<module>s.�bV�
�PK [����+__pycache__/coroutines.cpython-38.opt-1.pycnu�[���U

e5d]"�@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddlmZdd	�Ze�ZGd
d�d�Zdd
�Ze�Zdd�ZejejejjefZe�Zdd�Zdd�ZdS))�	coroutine�iscoroutinefunction�iscoroutine�N�)�base_futures)�	constants)�format_helpers)�loggercCs"tjjp tjjo ttj�d��S)NZPYTHONASYNCIODEBUG)�sys�flags�dev_mode�ignore_environment�bool�os�environ�get�rr�*/usr/lib64/python3.8/asyncio/coroutines.py�_is_debug_modes�rc@s�eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zddd
�Zdd�Z	e
dd��Ze
dd��Ze
dd��Z
dd�Ze
dd��Zdd�ZdS)�CoroWrapperNcCs>||_||_t�t�d��|_t|dd�|_t|dd�|_	dS)Nr�__name__�__qualname__)
�gen�funcr�
extract_stackr
�	_getframe�_source_traceback�getattrrr)�selfrrrrr�__init__'s
zCoroWrapper.__init__cCsJt|�}|jr4|jd}|d|d�d|d��7}d|jj�d|�d�S)	N���z
, created at r�:r�<� �>)�_format_coroutiner�	__class__r)r�	coro_repr�framerrr�__repr__/s

zCoroWrapper.__repr__cCs|S�Nr�rrrr�__iter__7szCoroWrapper.__iter__cCs|j�d�Sr*�r�sendr+rrr�__next__:szCoroWrapper.__next__cCs|j�|�Sr*r-)r�valuerrrr.=szCoroWrapper.sendcCs|j�|||�Sr*)r�throw)r�typer0�	tracebackrrrr1@szCoroWrapper.throwcCs
|j��Sr*)r�closer+rrrr4CszCoroWrapper.closecCs|jjSr*)r�gi_framer+rrrr5FszCoroWrapper.gi_framecCs|jjSr*)r�
gi_runningr+rrrr6JszCoroWrapper.gi_runningcCs|jjSr*)r�gi_coder+rrrr7NszCoroWrapper.gi_codecCs|Sr*rr+rrr�	__await__RszCoroWrapper.__await__cCs|jjSr*)r�gi_yieldfromr+rrrr9UszCoroWrapper.gi_yieldfromcCs�t|dd�}t|dd�}|dk	r||jdkr||�d�}t|dd�}|rrd�t�|��}|dtj�d	�7}||��7}t�	|�dS)
Nrr5r z was never yielded fromrr�zB
Coroutine object created at (most recent call last, truncated to z last lines):
)
r�f_lasti�joinr3�format_listrZDEBUG_STACK_DEPTH�rstripr	�error)rrr(�msg�tbrrr�__del__Ys
zCoroWrapper.__del__)N)NN)r�
__module__rrr)r,r/r.r1r4�propertyr5r6r7r8r9rBrrrrr$s"





rcsztjdtdd�t���r�St���r.��nt����fdd���t�	���t
sX�}nt�����fdd��}t|_|S)z�Decorator to mark coroutines.

    If the coroutine is not yielded from before it is destroyed,
    an error message is logged.
    zN"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead�)�
stacklevelc?sr�||�}t�|�s(t�|�s(t|t�r4|EdH}n:z
|j}Wntk
rRYnXt|tj	j
�rn|�EdH}|Sr*)rZisfuture�inspectZisgenerator�
isinstancerr8�AttributeError�collections�abc�	Awaitable)�args�kw�resZ
await_meth�rrr�corozs
�
zcoroutine.<locals>.corocs@t�||��d�}|jr |jd=t�dd�|_t�dd�|_|S)NrPr rr)rrrrr)rM�kwds�w�rQrrr�wrapper�szcoroutine.<locals>.wrapper)�warnings�warn�DeprecationWarningrGr�isgeneratorfunction�	functools�wraps�typesr�_DEBUG�
_is_coroutine)rrUrrTrris"�


rcCst�|�pt|dd�tkS)z6Return True if func is a decorated coroutine function.r^N)rGrrr^rPrrrr�s
�rcCs@t|�tkrdSt|t�r8tt�dkr4t�t|��dSdSdS)z)Return True if obj is a coroutine object.T�dFN)r2�_iscoroutine_typecacherH�_COROUTINE_TYPES�len�add)�objrrrr�s
rc
sht|t���fdd�}dd�}d}t|d�r:|jr:|j}nt|d�rP|jrP|j}||�}|sr||�rn|�d�S|Sd}t|d�r�|jr�|j}nt|d	�r�|jr�|j}|jp�d
}d}��r$|jdk	�r$t	�
|j��s$t�|j�}|dk	r�|\}}|dk�r|�d|�d
|��}	n|�d|�d
|��}	n@|dk	�rJ|j
}|�d|�d
|��}	n|j}|�d|�d
|��}	|	S)Ncs`�rt�|jdi�St|d�r,|jr,|j}n*t|d�rD|jrD|j}ndt|�j�d�}|�d�S)Nrrrr"z without __name__>z())rZ_format_callbackr�hasattrrrr2)rQ�	coro_name�Zis_corowrapperrr�get_name�sz#_format_coroutine.<locals>.get_namecSsHz|jWStk
rBz|jWYStk
r<YYdSXYnXdS)NF)�
cr_runningrIr6)rQrrr�
is_running�sz%_format_coroutine.<locals>.is_running�cr_coder7z runningr5�cr_framez<empty co_filename>rz done, defined at r!z running, defined at z running at )rHrrerkr7r5rl�co_filenamerrGrYrZ_get_function_source�f_lineno�co_firstlineno)
rQrhrjZ	coro_coderfZ
coro_frame�filename�lineno�sourcer'rrgrr%�sJ
	

�
�

r%) �__all__Zcollections.abcrJrZrGrr
r3r\rVr:rrr�logr	rr]rr�objectr^r�
CoroutineType�
GeneratorTyperK�	Coroutinera�setr`rr%rrrr�<module>s2E8�PK [*�J;��$__pycache__/log.cpython-38.opt-2.pycnu�[���U

e5d|�@sddlZe�e�ZdS)�N)ZloggingZ	getLogger�__package__Zlogger�rr�#/usr/lib64/python3.8/asyncio/log.py�<module>sPK [�m���8�8(__pycache__/streams.cpython-38.opt-2.pycnu�[���U

e5d h�@s&dZddlZddlZddlZddlZeed�r6ed7ZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlm
Z
ddlmZd
Zdded�dd�Zd ded�dd�Zeed�r�d!ded�dd�Zd"ded�dd�ZGdd�dej�ZGdd�deej�ZGdd�d�ZGdd�d�ZdS)#)�StreamReader�StreamWriter�StreamReaderProtocol�open_connection�start_server�NZAF_UNIX)�open_unix_connection�start_unix_server�)�
coroutines)�events)�
exceptions)�format_helpers)�	protocols)�logger)�sleepi)�loop�limitc	�st|dkrt��}ntjdtdd�t||d�}t||d��|j�fdd�||f|�IdH\}}t|�||�}||fS)N�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.���
stacklevel�rr�rcs�S�N�r��protocolr�'/usr/lib64/python3.8/asyncio/streams.py�<lambda>5�z!open_connection.<locals>.<lambda>)	r�get_event_loop�warnings�warn�DeprecationWarningrrZcreate_connectionr)	�host�portrr�kwds�reader�	transport�_�writerrrrrs"
�
��rc�sJ�dkrt���ntjdtdd����fdd�}�j|||f|�IdHS)Nrrrcst��d�}t|��d�}|S�Nrr�rr�r'r��client_connected_cbrrrr�factoryXs
�zstart_server.<locals>.factory)rr r!r"r#Z
create_server)r/r$r%rrr&r0rr.rr:s
�rc�sr|dkrt��}ntjdtdd�t||d�}t||d��|j�fdd�|f|�IdH\}}t|�||�}||fS)Nrrrrrcs�Srrrrrrrprz&open_unix_connection.<locals>.<lambda>)	rr r!r"r#rrZcreate_unix_connectionr)�pathrrr&r'r(r)r*rrrrds 
�
��rc�sH�dkrt���ntjdtdd����fdd�}�j||f|�IdHS)Nrrrcst��d�}t|��d�}|Sr+r,r-r.rrr0~s
�z"start_unix_server.<locals>.factory)rr r!r"r#Zcreate_unix_server)r/r1rrr&r0rr.rrts
�rc@s>eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�FlowControlMixinNcCs0|dkrt��|_n||_d|_d|_d|_dS�NF)rr �_loop�_paused�
_drain_waiter�_connection_lost)�selfrrrr�__init__�szFlowControlMixin.__init__cCs d|_|j��rt�d|�dS)NTz%r pauses writing)r5r4�	get_debugr�debug�r8rrr�
pause_writing�s
zFlowControlMixin.pause_writingcCsFd|_|j��rt�d|�|j}|dk	rBd|_|��sB|�d�dS)NFz%r resumes writing)r5r4r:rr;r6�done�
set_result�r8�waiterrrr�resume_writing�s
zFlowControlMixin.resume_writingcCsVd|_|jsdS|j}|dkr"dSd|_|��r4dS|dkrH|�d�n
|�|�dS�NT)r7r5r6r>r?�
set_exception�r8�excrArrr�connection_lost�sz FlowControlMixin.connection_lostc�s<|jrtd��|jsdS|j}|j��}||_|IdHdS)NzConnection lost)r7�ConnectionResetErrorr5r6r4�
create_futurer@rrr�
_drain_helper�s
zFlowControlMixin._drain_helpercCst�dSr)�NotImplementedError�r8�streamrrr�_get_close_waiter�sz"FlowControlMixin._get_close_waiter)N)	�__name__�
__module__�__qualname__r9r=rBrGrJrNrrrrr2�s

	r2csbeZdZdZd�fdd�	Zedd��Zdd�Z�fdd	�Zd
d�Z	dd
�Z
dd�Zdd�Z�Z
S)rNcsnt�j|d�|dk	r,t�|�|_|j|_nd|_|dk	r@||_d|_d|_d|_	||_
d|_|j�
�|_dS)NrF)�superr9�weakref�ref�_stream_reader_wr�_source_traceback�_strong_reader�_reject_connection�_stream_writer�
_transport�_client_connected_cb�	_over_sslr4rI�_closed)r8Z
stream_readerr/r��	__class__rrr9�s
zStreamReaderProtocol.__init__cCs|jdkrdS|��Sr)rUr<rrr�_stream_reader�s
z#StreamReaderProtocol._stream_readercCs�|jr6ddi}|jr|j|d<|j�|�|��dS||_|j}|dk	rT|�|�|�d�dk	|_	|j
dk	r�t||||j�|_|�
||j�}t
�|�r�|j�|�d|_dS)N�messagezpAn open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.Zsource_tracebackZ
sslcontext)rXrVr4Zcall_exception_handler�abortrZr`�
set_transport�get_extra_infor\r[rrYr
ZiscoroutineZcreate_taskrW)r8r(�contextr'�resrrr�connection_made�s2�


��
z$StreamReaderProtocol.connection_madecsx|j}|dk	r*|dkr |��n
|�|�|j��sV|dkrJ|j�d�n|j�|�t��|�d|_d|_	d|_
dSr)r`�feed_eofrDr]r>r?rRrGrUrYrZ)r8rFr'r^rrrG
s


z$StreamReaderProtocol.connection_lostcCs|j}|dk	r|�|�dSr)r`�	feed_data)r8�datar'rrr�
data_receivedsz"StreamReaderProtocol.data_receivedcCs$|j}|dk	r|��|jr dSdS)NFT)r`rhr\)r8r'rrr�eof_received sz!StreamReaderProtocol.eof_receivedcCs|jSr)r]rLrrrrN+sz&StreamReaderProtocol._get_close_waitercCs"|j}|��r|��s|��dSr)r]r>�	cancelled�	exception)r8�closedrrr�__del__.szStreamReaderProtocol.__del__)NN)rOrPrQrVr9�propertyr`rgrGrkrlrNrp�
__classcell__rrr^rr�s	
rc@sreZdZdd�Zdd�Zedd��Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
ddd�Zdd�ZdS)rcCs4||_||_||_||_|j��|_|j�d�dSr)rZ�	_protocol�_readerr4rIZ
_complete_futr?)r8r(rr'rrrrr9@szStreamWriter.__init__cCs@|jjd|j��g}|jdk	r0|�d|j���d�d�|��S)N�
transport=zreader=�<{}>� )r_rOrZrt�append�format�join�r8�inforrr�__repr__Js
zStreamWriter.__repr__cCs|jSr�rZr<rrrr(PszStreamWriter.transportcCs|j�|�dSr)rZ�write�r8rjrrrrTszStreamWriter.writecCs|j�|�dSr)rZ�
writelinesr�rrrr�WszStreamWriter.writelinescCs
|j��Sr)rZ�	write_eofr<rrrr�ZszStreamWriter.write_eofcCs
|j��Sr)rZ�
can_write_eofr<rrrr�]szStreamWriter.can_write_eofcCs
|j��Sr)rZ�closer<rrrr�`szStreamWriter.closecCs
|j��Sr)rZ�
is_closingr<rrrr�cszStreamWriter.is_closingc�s|j�|�IdHdSr)rsrNr<rrr�wait_closedfszStreamWriter.wait_closedNcCs|j�||�Sr)rZrd)r8�name�defaultrrrrdiszStreamWriter.get_extra_infoc�sL|jdk	r |j��}|dk	r |�|j��r8td�IdH|j��IdHdS)Nr)rtrnrZr�rrsrJ)r8rFrrr�drainls



zStreamWriter.drain)N)rOrPrQr9r}rqr(rr�r�r�r�r�r�rdr�rrrrr6s



rc@s�eZdZdZedfdd�Zdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd&dd�Zd'dd�Zd d!�Zd"d#�Zd$d%�ZdS)(rNcCsv|dkrtd��||_|dkr*t��|_n||_t�|_d|_d|_d|_	d|_
d|_|j��rrt
�t�d��|_dS)NrzLimit cannot be <= 0Fr	)�
ValueError�_limitrr r4�	bytearray�_buffer�_eof�_waiter�
_exceptionrZr5r:r
�
extract_stack�sys�	_getframerV)r8rrrrrr9�s 
�zStreamReader.__init__cCs�dg}|jr"|�t|j��d��|jr2|�d�|jtkrN|�d|j���|jrf|�d|j���|jr~|�d|j���|jr�|�d|j���|j	r�|�d�d	�
d
�|��S)Nrz bytes�eofzlimit=zwaiter=z
exception=ruZpausedrvrw)r�rx�lenr�r��_DEFAULT_LIMITr�r�rZr5ryrzr{rrrr}�s 


zStreamReader.__repr__cCs|jSr)r�r<rrrrn�szStreamReader.exceptioncCs0||_|j}|dk	r,d|_|��s,|�|�dSr)r�r�rmrDrErrrrD�szStreamReader.set_exceptioncCs*|j}|dk	r&d|_|��s&|�d�dSr)r�rmr?r@rrr�_wakeup_waiter�s
zStreamReader._wakeup_waitercCs
||_dSrr~)r8r(rrrrc�szStreamReader.set_transportcCs*|jr&t|j�|jkr&d|_|j��dSr3)r5r�r�r�rZ�resume_readingr<rrr�_maybe_resume_transport�sz$StreamReader._maybe_resume_transportcCsd|_|��dSrC)r�r�r<rrrrh�szStreamReader.feed_eofcCs|jo|jSr)r�r�r<rrr�at_eof�szStreamReader.at_eofcCst|sdS|j�|�|��|jdk	rp|jspt|j�d|jkrpz|j��Wntk
rhd|_YnXd|_dS)NrT)	r��extendr�rZr5r�r�Z
pause_readingrKr�rrrri�s
��zStreamReader.feed_datac�sX|jdk	rt|�d���|jr.d|_|j��|j��|_z|jIdHW5d|_XdS)NzF() called while another coroutine is already waiting for incoming dataF)r��RuntimeErrorr5rZr�r4rI)r8Z	func_namerrr�_wait_for_data�s	
�
zStreamReader._wait_for_datac
�s�d}t|�}z|�|�IdH}Wn�tjk
rN}z|jWY�Sd}~XYnhtjk
r�}zH|j�||j�r�|jd|j|�=n
|j�	�|�
�t|jd��W5d}~XYnX|S)N�
r)
r��	readuntilr�IncompleteReadError�partial�LimitOverrunErrorr��
startswith�consumed�clearr�r��args)r8�sep�seplen�line�errr�readline	s
 zStreamReader.readliner�c�s�t|�}|dkrtd��|jdk	r(|j�d}t|j�}|||kr||j�||�}|dkrZq�|d|}||jkr|t�d|��|jr�t	|j�}|j�
�t�|d��|�d�IdHq,||jkr�t�d|��|jd||�}|jd||�=|�
�t	|�S)Nrz,Separator should be at least one-byte string���r	z2Separator is not found, and chunk exceed the limitr�z2Separator is found, but chunk is longer than limit)r�r�r�r��findr�rr�r��bytesr�r�r�r�)r8Z	separatorr��offsetZbuflenZisep�chunkrrrr�(s>


�


�zStreamReader.readuntilr�c�s�|jdk	r|j�|dkrdS|dkrVg}|�|j�IdH}|s@qL|�|�q(d�|�S|jsr|jsr|�d�IdHt|jd|��}|jd|�=|�	�|S)Nrr�read)
r�r�r�rxrzr�r�r�r�r�)r8�nZblocks�blockrjrrrr��s"

zStreamReader.readc�s�|dkrtd��|jdk	r |j�|dkr,dSt|j�|krr|jr`t|j�}|j��t�||��|�	d�IdHq,t|j�|kr�t|j�}|j��nt|jd|��}|jd|�=|�
�|S)Nrz*readexactly size can not be less than zeror�readexactly)r�r�r�r�r�r�r�rr�r�r�)r8r�Z
incompleterjrrrr��s&



zStreamReader.readexactlycCs|Srrr<rrr�	__aiter__�szStreamReader.__aiter__c�s|��IdH}|dkrt�|S)Nr)r��StopAsyncIteration)r8�valrrr�	__anext__�szStreamReader.__anext__)r�)r�)rOrPrQrVr�r9r}rnrDr�rcr�rhr�rir�r�r�r�r�r�r�rrrrr�s$	
[
2)r)NN)NN)N)N)�__all__Zsocketr�r!rS�hasattr�r
rrr
r�logrZtasksrr�rrrrZProtocolr2rrrrrrr�<module>sF
�!�'
��DkPPK [T=T\W�W�,__pycache__/base_events.cpython-38.opt-2.pycnu�[���U

e5d��@s�ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZzddlZWnek
r�dZYnXddlmZddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlm Z dZ!dZ"dZ#e$ed�Z%dZ&e'�Z(dd�Z)dd�Z*dd�Z+d*dd�Z,d+dd�Z-dd�Z.e$ed ��r�d!d"�Z/nd#d"�Z/Gd$d%�d%ej0�Z1Gd&d'�d'ej2�Z3Gd(d)�d)ej4�Z5dS),�N�)�	constants)�
coroutines)�events)�
exceptions)�futures)�	protocols)�sslproto)�	staggered)�tasks)�
transports)�trsock)�logger)�
BaseEventLoop�dg�?�AF_INET6i�QcCs0|j}tt|dd�tj�r$t|j�St|�SdS)N�__self__)Z	_callback�
isinstance�getattrr�Task�reprr�str)�handle�cb�r�+/usr/lib64/python3.8/asyncio/base_events.py�_format_handleJs
rcCs(|tjkrdS|tjkrdSt|�SdS)Nz<pipe>z<stdout>)�
subprocess�PIPE�STDOUTr)�fdrrr�_format_pipeSs


r!cCsLttd�std��n4z|�tjtjd�Wntk
rFtd��YnXdS)N�SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)�hasattr�socket�
ValueError�
setsockopt�
SOL_SOCKETr"�OSError��sockrrr�_set_reuseport\s

r+c		Cs�ttd�sdS|dtjtjhks(|dkr,dS|tjkr>tj}n|tjkrPtj}ndS|dkrbd}nXt|t�rz|dkrzd}n@t|t�r�|dkr�d}n(zt	|�}Wnt
tfk
r�YdSX|tjkr�tj
g}tr�|�tj�n|g}t|t�r�|�d�}d|k�rdS|D]t}zVt�||�t�rJ|tjk�rJ|||d||||ffWS|||d||ffWSWntk
�rzYnX�q
dS)N�	inet_ptonr��Zidna�%)r#r$�IPPROTO_TCPZIPPROTO_UDP�SOCK_STREAM�
SOCK_DGRAMr�bytesr�int�	TypeErrorr%�	AF_UNSPEC�AF_INET�	_HAS_IPv6�appendr�decoder,r()	�host�port�family�type�protoZflowinfoZscopeidZafs�afrrr�_ipaddr_infogsN
�






rAcCs�t��}|D]*}|d}||kr(g||<||�|�qt|���}g}|dkr||�|dd|d��|dd|d�=|�dd�tj�tj	|��D��|S)Nrrcss|]}|dk	r|VqdS�Nr)�.0�arrr�	<genexpr>�s�z(_interleave_addrinfos.<locals>.<genexpr>)
�collections�OrderedDictr9�list�values�extend�	itertools�chain�
from_iterable�zip_longest)Z	addrinfosZfirst_address_family_countZaddrinfos_by_family�addrr=Zaddrinfos_listsZ	reorderedrrr�_interleave_addrinfos�s"
��rPcCs4|��s"|��}t|ttf�r"dSt�|���dSrB)�	cancelled�	exceptionr�
SystemExit�KeyboardInterruptrZ	_get_loop�stop)�fut�excrrr�_run_until_complete_cb�s
rX�TCP_NODELAYcCs@|jtjtjhkr<|jtjkr<|jtjkr<|�tjtj	d�dS�Nr)
r=r$r7rr>r1r?r0r&rYr)rrr�_set_nodelay�s
�
�r[cCsdSrBrr)rrrr[�sc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)�_SendfileFallbackProtocolcCsht|tj�std��||_|��|_|��|_|j	|_
|��|�|�|j
r^|jj
��|_nd|_dS)Nz.transport should be _FlowControlMixin instance)rrZ_FlowControlMixinr5�
_transportZget_protocol�_protoZ
is_reading�_should_resume_readingZ_protocol_paused�_should_resume_writing�
pause_reading�set_protocol�_loop�
create_future�_write_ready_fut)�self�transprrr�__init__�s


z"_SendfileFallbackProtocol.__init__c�s2|j��rtd��|j}|dkr$dS|IdHdS)NzConnection closed by peer)r]�
is_closing�ConnectionErrorre)rfrVrrr�drain�s
z_SendfileFallbackProtocol.draincCstd��dS)Nz?Invalid state: connection should have been established already.��RuntimeError)rf�	transportrrr�connection_made�sz)_SendfileFallbackProtocol.connection_madecCs@|jdk	r0|dkr$|j�td��n|j�|�|j�|�dS)NzConnection is closed by peer)reZ
set_exceptionrjr^�connection_lost)rfrWrrrrp�s
�z)_SendfileFallbackProtocol.connection_lostcCs |jdk	rdS|jj��|_dSrB)rer]rcrd�rfrrr�
pause_writing�s
z'_SendfileFallbackProtocol.pause_writingcCs$|jdkrdS|j�d�d|_dS)NF)re�
set_resultrqrrr�resume_writing�s
z(_SendfileFallbackProtocol.resume_writingcCstd��dS�Nz'Invalid state: reading should be pausedrl)rf�datarrr�
data_received�sz'_SendfileFallbackProtocol.data_receivedcCstd��dSrurlrqrrr�eof_receivedsz&_SendfileFallbackProtocol.eof_receivedc�sF|j�|j�|jr|j��|jdk	r2|j��|jrB|j��dSrB)	r]rbr^r_�resume_readingre�cancelr`rtrqrrr�restores


z!_SendfileFallbackProtocol.restoreN)�__name__�
__module__�__qualname__rhrkrorprrrtrwrxr{rrrrr\�sr\c@sxeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
edd��Zdd�Z
dd�Zdd�Zdd�ZdS)�ServercCs@||_||_d|_g|_||_||_||_||_d|_d|_	dS)NrF)
rc�_sockets�
_active_count�_waiters�_protocol_factory�_backlog�_ssl_context�_ssl_handshake_timeout�_serving�_serving_forever_fut)rf�loop�sockets�protocol_factoryZssl_context�backlog�ssl_handshake_timeoutrrrrhszServer.__init__cCsd|jj�d|j�d�S)N�<z	 sockets=�>)�	__class__r|r�rqrrr�__repr__ szServer.__repr__cCs|jd7_dSrZ)r�rqrrr�_attach#szServer._attachcCs.|jd8_|jdkr*|jdkr*|��dS)Nrr)r�r��_wakeuprqrrr�_detach'szServer._detachcCs,|j}d|_|D]}|��s|�|�qdSrB)r��doners)rf�waiters�waiterrrrr�-s
zServer._wakeupc	CsJ|jr
dSd|_|jD].}|�|j�|j�|j||j||j|j�qdS�NT)	r�r�Zlistenr�rc�_start_servingr�r�r�)rfr*rrrr�4s
�zServer._start_servingcCs|jSrB)rcrqrrr�get_loop>szServer.get_loopcCs|jSrB)r�rqrrr�
is_servingAszServer.is_servingcCs"|jdkrdStdd�|jD��S)Nrcss|]}t�|�VqdSrB)r
ZTransportSocket)rC�srrrrEHsz!Server.sockets.<locals>.<genexpr>)r��tuplerqrrrr�Ds
zServer.socketscCsn|j}|dkrdSd|_|D]}|j�|�qd|_|jdk	rX|j��sX|j��d|_|jdkrj|��dS)NFr)	r�rcZ
_stop_servingr�r�r�rzr�r�)rfr�r*rrr�closeJs
�

zServer.closec�s"|��tjd|jd�IdHdS)Nr�r�)r�r�sleeprcrqrrr�
start_serving]szServer.start_servingc	�s�|jdk	rtd|�d���|jdkr4td|�d���|��|j��|_zLz|jIdHWn6tjk
r�z|��|�	�IdHW5�XYnXW5d|_XdS)Nzserver z, is already being awaited on serve_forever()z
 is closed)
r�rmr�r�rcrdrZCancelledErrorr��wait_closedrqrrr�
serve_forevercs 

�
zServer.serve_foreverc�s<|jdks|jdkrdS|j��}|j�|�|IdHdSrB)r�r�rcrdr9)rfr�rrrr�xs

zServer.wait_closedN)r|r}r~rhr�r�r�r�r�r�r��propertyr�r�r�r�r�rrrrrs


rc@sPeZdZdd�Zdd�Zdd�Zdd�d	d
�Zdd�Zd
d�Zd�ddd�dd�Z	d�ddddddd�dd�Z
d�dd�Zd�dd�Zd�dd�Z
d�dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zejfd7d8�Zd9d:�Zd;d<�Zdd=�d>d?�Z dd=�d@dA�Z!dd=�dBdC�Z"dDdE�Z#dFdG�Z$dHdI�Z%dd=�dJdK�Z&dLdM�Z'dNdO�Z(dPdQ�Z)dRdRdRdRdS�dTdU�Z*d�dVdW�Z+d�ddX�dYdZ�Z,d[d\�Z-d]d^�Z.d_d`�Z/d�dadb�Z0d�ddRdRdRdddddddc�
ddde�Z1d�dfdg�Z2d�ddX�dhdi�Z3djdk�Z4dldm�Z5ddddn�dodp�Z6d�dRdRdRe7ddddq�drds�Z8dRe9j:dRdRdS�dtdu�Z;dvdw�Z<d�e9j=e9j>ddxddddddy�	dzd{�Z?ddd|�d}d~�Z@dd��ZAd�d��ZBd�d��ZCeDjEeDjEeDjEdddRdddd��	d�d��ZFeDjEeDjEeDjEdddRdddd��	d�d��ZGd�d��ZHd�d��ZId�d��ZJd�d��ZKd�d��ZLd�d��ZMd�d��ZNd�d��ZOd�d��ZPd�d��ZQd�d��ZRdS)�rcCs�d|_d|_d|_t��|_g|_d|_d|_d|_	t
�d�j|_
d|_|�t���d|_d|_d|_d|_d|_t��|_d|_dS)NrF�	monotonicg�������?)�_timer_cancelled_count�_closed�	_stoppingrF�deque�_ready�
_scheduled�_default_executorZ
_internal_fds�
_thread_id�time�get_clock_infoZ
resolution�_clock_resolution�_exception_handler�	set_debugrZ_is_debug_mode�slow_callback_duration�_current_handle�
_task_factory�"_coroutine_origin_tracking_enabled�&_coroutine_origin_tracking_saved_depth�weakrefZWeakSet�
_asyncgens�_asyncgens_shutdown_calledrqrrrrh�s$

zBaseEventLoop.__init__c	Cs.d|jj�d|���d|���d|���d�	S)Nr�z	 running=z closed=z debug=r�)r�r|�
is_running�	is_closed�	get_debugrqrrrr��s,�zBaseEventLoop.__repr__cCstj|d�S)Nr�)rZFuturerqrrrrd�szBaseEventLoop.create_futureN)�namecCsN|��|jdkr2tj|||d�}|jrJ|jd=n|�||�}t�||�|S)N)r�r����)�
_check_closedr�rr�_source_tracebackZ_set_task_name)rf�coror�Ztaskrrr�create_task�s

zBaseEventLoop.create_taskcCs"|dk	rt|�std��||_dS)Nz'task factory must be a callable or None)�callabler5r�)rf�factoryrrr�set_task_factory�s
zBaseEventLoop.set_task_factorycCs|jSrB)r�rqrrr�get_task_factory�szBaseEventLoop.get_task_factory)�extra�servercCst�dSrB��NotImplementedError)rfr*�protocolr�r�r�rrr�_make_socket_transport�sz$BaseEventLoop._make_socket_transportFT)�server_side�server_hostnamer�r�r��call_connection_madecCst�dSrBr�)rfZrawsockr��
sslcontextr�r�r�r�r�r�r�rrr�_make_ssl_transport�sz!BaseEventLoop._make_ssl_transportcCst�dSrBr�)rfr*r��addressr�r�rrr�_make_datagram_transport�sz&BaseEventLoop._make_datagram_transportcCst�dSrBr��rf�piper�r�r�rrr�_make_read_pipe_transport�sz'BaseEventLoop._make_read_pipe_transportcCst�dSrBr�r�rrr�_make_write_pipe_transport�sz(BaseEventLoop._make_write_pipe_transportc	
�st�dSrBr�)
rfr��args�shell�stdin�stdout�stderr�bufsizer��kwargsrrr�_make_subprocess_transport�sz(BaseEventLoop._make_subprocess_transportcCst�dSrBr�rqrrr�_write_to_self�szBaseEventLoop._write_to_selfcCst�dSrBr�)rf�
event_listrrr�_process_events�szBaseEventLoop._process_eventscCs|jrtd��dS)NzEvent loop is closed)r�rmrqrrrr��szBaseEventLoop._check_closedcCs*|j�|�|��s&|�|j|���dSrB)r��discardr��call_soon_threadsafer��aclose�rf�agenrrr�_asyncgen_finalizer_hook�sz&BaseEventLoop._asyncgen_finalizer_hookcCs.|jrtjd|�d�t|d�|j�|�dS)Nzasynchronous generator z3 was scheduled after loop.shutdown_asyncgens() call��source)r��warnings�warn�ResourceWarningr��addr�rrr�_asyncgen_firstiter_hooks
�z&BaseEventLoop._asyncgen_firstiter_hookc�s�d|_t|j�sdSt|j�}|j��tjdd�|D�d|d��IdH}t||�D]*\}}t|t	�rT|�
d|��||d��qTdS)NTcSsg|]}|���qSr)r�)rCZagrrr�
<listcomp>sz4BaseEventLoop.shutdown_asyncgens.<locals>.<listcomp>)Zreturn_exceptionsr�z;an error occurred during closing of asynchronous generator )�messagerRZasyncgen)r��lenr�rH�clearr�gather�zipr�	Exception�call_exception_handler)rfZ
closing_agensZresults�resultr�rrr�shutdown_asyncgenss"


�
�z BaseEventLoop.shutdown_asyncgenscCs(|��rtd��t��dk	r$td��dS)Nz"This event loop is already runningz7Cannot run the event loop while another loop is running)r�rmrZ_get_running_looprqrrr�_check_running&s�zBaseEventLoop._check_runningc	Cs�|��|��|�|j�t��|_t��}tj	|j
|jd�z t
�|�|��|jrLq^qLW5d|_d|_t
�d�|�d�tj	|�XdS)N)�	firstiter�	finalizerF)r�r��_set_coroutine_origin_tracking�_debug�	threading�	get_identr��sys�get_asyncgen_hooks�set_asyncgen_hooksr�r�r�rZ_set_running_loop�	_run_once)rfZold_agen_hooksrrr�run_forever-s$
�


zBaseEventLoop.run_foreverc	Cs�|��|��t�|�}tj||d�}|r4d|_|�t�z<z|�
�Wn*|rp|��rp|��sp|�
��YnXW5|�	t�X|��s�td��|��S)Nr�Fz+Event loop stopped before Future completed.)r�r�rZisfuturerZ
ensure_futureZ_log_destroy_pendingZadd_done_callbackrXZremove_done_callbackrr�rQrRrmr�)rfZfutureZnew_taskrrr�run_until_completeDs"
z BaseEventLoop.run_until_completecCs
d|_dSr�)r�rqrrrrUjszBaseEventLoop.stopcCsj|��rtd��|jrdS|jr,t�d|�d|_|j��|j��|j	}|dk	rfd|_	|j
dd�dS)Nz!Cannot close a running event loopzClose %rTF)�wait)r�rmr�r�r�debugr�r�r�r�Zshutdown�rf�executorrrrr�rs

zBaseEventLoop.closecCs|jSrB)r�rqrrrr��szBaseEventLoop.is_closedcCs0|��s,|d|��t|d�|��s,|��dS)Nzunclosed event loop r�)r�r�r�r�)rfZ_warnrrr�__del__�szBaseEventLoop.__del__cCs
|jdk	SrB)r�rqrrrr��szBaseEventLoop.is_runningcCst��SrB)r�r�rqrrrr��szBaseEventLoop.time)�contextcGs2|j|��||f|�d|i�}|jr.|jd=|S)Nr
r�)�call_atr�r�)rfZdelay�callbackr
r��timerrrr�
call_later�s�zBaseEventLoop.call_latercGsZ|��|jr"|��|�|d�t�|||||�}|jrB|jd=t�|j	|�d|_	|S)Nrr�T)
r�r��
_check_thread�_check_callbackrZTimerHandler��heapq�heappushr�)rf�whenrr
r�rrrrr�szBaseEventLoop.call_atcGsB|��|jr"|��|�|d�|�|||�}|jr>|jd=|S)N�	call_soonr�)r�r�rr�
_call_soonr��rfrr
r�rrrrr�s
zBaseEventLoop.call_sooncCsDt�|�st�|�r$td|�d���t|�s@td|�d|����dS)Nzcoroutines cannot be used with z()z"a callable object was expected by z(), got )rZiscoroutineZiscoroutinefunctionr5r�)rfr�methodrrrr�s
�
��zBaseEventLoop._check_callbackcCs.t�||||�}|jr|jd=|j�|�|S)Nr�)rZHandler�r�r9)rfrr�r
rrrrr�s
zBaseEventLoop._call_sooncCs,|jdkrdSt��}||jkr(td��dS)NzMNon-thread-safe operation invoked on an event loop other than the current one)r�rrrm)rfZ	thread_idrrrr�s	

�zBaseEventLoop._check_threadcGsB|��|jr|�|d�|�|||�}|jr6|jd=|��|S)Nr�r�)r�r�rrr�r�rrrrr��sz"BaseEventLoop.call_soon_threadsafecGsZ|��|jr|�|d�|dkr@|j}|dkr@tj��}||_tj|j|f|��|d�S)N�run_in_executorr�)	r�r�rr��
concurrentr�ThreadPoolExecutorZwrap_futureZsubmit)rfr�funcr�rrrrs
�zBaseEventLoop.run_in_executorcCs&t|tjj�st�dtd�||_dS)Nz{Using the default executor that is not an instance of ThreadPoolExecutor is deprecated and will be prohibited in Python 3.9�)rrrrr�r��DeprecationWarningr�r
rrr�set_default_executors�z"BaseEventLoop.set_default_executorcCs�|�d|��g}|r$|�d|���|r8|�d|���|rL|�d|���|r`|�d|���d�|�}t�d|�|��}t�||||||�}	|��|}
d|�d	|
d
d�d|	��}|
|jkr�t�|�n
t�|�|	S)
N�:zfamily=ztype=zproto=zflags=�, zGet address info %szGetting address info z took g@�@z.3fzms: )	r9�joinrr	r�r$�getaddrinfor��info)rfr;r<r=r>r?�flags�msg�t0�addrinfo�dtrrr�_getaddrinfo_debugs&


z BaseEventLoop._getaddrinfo_debugr�r=r>r?r'c
�s2|jr|j}ntj}|�d|||||||�IdHSrB)r�r,r$r%r)rfr;r<r=r>r?r'Zgetaddr_funcrrrr%2s�zBaseEventLoop.getaddrinfoc�s|�dtj||�IdHSrB)rr$�getnameinfo)rfZsockaddrr'rrrr.<s�zBaseEventLoop.getnameinfo)�fallbackc
�s�|jr|��dkrtd��|�||||�z|�||||�IdHWStjk
rl}z
|s\�W5d}~XYnX|�||||�IdHS)Nrzthe socket must be non-blocking)r�Z
gettimeoutr%�_check_sendfile_params�_sock_sendfile_nativer�SendfileNotAvailableError�_sock_sendfile_fallback)rfr*�file�offset�countr/rWrrr�
sock_sendfile@s��zBaseEventLoop.sock_sendfilec�st�d|�d���dS)Nz-syscall sendfile is not available for socket z and file {file!r} combination�rr2�rfr*r4r5r6rrrr1Ns
�z#BaseEventLoop._sock_sendfile_nativec

�s�|r|�|�|rt|tj�ntj}t|�}d}zt|rNt|||�}|dkrNq�t|�d|�}|�d|j|�IdH}	|	szq�|�	||d|	��IdH||	7}q2|W�S|dkr�t|d�r�|�||�XdS)Nr�seek)
r:�minrZ!SENDFILE_FALLBACK_READBUFFER_SIZE�	bytearrayr#�
memoryviewr�readintoZsock_sendall)
rfr*r4r5r6�	blocksize�buf�
total_sent�view�readrrrr3Us,
��
z%BaseEventLoop._sock_sendfile_fallbackcCs�dt|dd�krtd��|jtjks,td��|dk	rbt|t�sLtd�|���|dkrbtd�|���t|t�sztd�|���|dkr�td�|���dS)N�b�modez$file should be opened in binary modez+only SOCK_STREAM type sockets are supportedz+count must be a positive integer (got {!r})rz0offset must be a non-negative integer (got {!r}))	rr%r>r$r1rr4r5�formatr9rrrr0os2
��
����z$BaseEventLoop._check_sendfile_paramsc�s@g}|�|�|\}}}}}	d}
z�tj|||d�}
|
�d�|dk	r�|D]r\}}}}}z|
�|�Wq�WqHtk
r�}z0d|�d|j����}
t|j|
�}|�|�W5d}~XYqHXqH|���|�	|
|	�IdH|
WStk
�r}z"|�|�|
dk	�r
|
�
��W5d}~XYn |
dk	�r4|
�
��YnXdS)N�r=r>r?Fz*error while attempting to bind on address �: )r9r$�setblocking�bindr(�strerror�lower�errno�pop�sock_connectr�)rfrZ	addr_infoZlocal_addr_infosZ
my_exceptionsr=Ztype_r?�_r�r*ZladdrrWr(rrr�
_connect_sock�s:



�


zBaseEventLoop._connect_sock)
�sslr=r?r'r*�
local_addrr�r��happy_eyeballs_delay�
interleavec
	�sl|
dk	r|std��|
dkr0|r0|s,td��|}
|dk	rD|sDtd��|dk	rX|
dkrXd}
|dk	sj|dk	�r�|dk	rztd���j||f|tj||�d�IdH}|s�td��|	dk	r܈j|	|tj||�d�IdH��s�td��nd�|
r�t||
�}g�|dk�rH|D]D}z ���|��IdH}W�qvWntk
�r@Y�qYnX�qn.tj���fdd	�|D�|�d
�IdH\}}}|dk�r dd��D��t	��dk�r��d
�nJt
�d
��t�fdd	��D���r҈d
�td�d�
dd	��D�����n.|dk�rtd��|jtjk�r td|�����j||||
|d�IdH\}}�j�rd|�d�}t�d|||||�||fS)Nz+server_hostname is only meaningful with sslz:You must set server_hostname when using ssl without a host�1ssl_handshake_timeout is only meaningful with sslr�8host/port and sock can not be specified at the same time�r=r>r?r'r��!getaddrinfo() returned empty listc3s |]}t��j�|��VqdSrB)�	functools�partialrQ)rCr*)r�laddr_infosrfrrrE�s��z2BaseEventLoop.create_connection.<locals>.<genexpr>r�cSsg|]}|D]}|�qqSrr)rC�subrWrrrr��sz3BaseEventLoop.create_connection.<locals>.<listcomp>rc3s|]}t|��kVqdSrB�r�rCrW)�modelrrrEszMultiple exceptions: {}r#css|]}t|�VqdSrBr^r_rrrrE
sz5host and port was not specified and no sock specified�"A Stream Socket was expected, got )r�r$z%r connected to %s:%r: (%r, %r))r%�_ensure_resolvedr$r1r(rPrQr
Zstaggered_racer�r�allrFr$r>�_create_connection_transportr��get_extra_inforr	)rfr�r;r<rRr=r?r'r*rSr�r�rTrU�infosr*rPrnr�r)rr\r`rfr�create_connection�s�����


�
��

�
���
�zBaseEventLoop.create_connectionc	�s�|�d�|�}|��}|rHt|t�r*dn|}	|j|||	||||d�}
n|�|||�}
z|IdHWn|
���YnX|
|fS)NF�r�r�r�)rIrdr�boolr�r�r�)rfr*r�rRr�r�r�r�r�r�rnrrrrd%s*
�z*BaseEventLoop._create_connection_transportc
�s�|��rtd��t|dtjj�}|tjjkr:td|����|tjjkr�z|�||||�IdHWStj	k
r�}z
|sx�W5d}~XYnX|s�td|����|�
||||�IdHS)NzTransport is closingZ_sendfile_compatiblez(sendfile is not supported for transport zHfallback is disabled and native sendfile is not supported for transport )rirmrrZ
_SendfileModeZUNSUPPORTEDZ
TRY_NATIVE�_sendfile_nativerr2�_sendfile_fallback)rfrnr4r5r6r/rErWrrr�sendfile?s4�����zBaseEventLoop.sendfilec�st�d��dS)Nz!sendfile syscall is not supportedr8)rfrgr4r5r6rrrrjns�zBaseEventLoop._sendfile_nativec
�s�|r|�|�|rt|d�nd}t|�}d}t|�}z�|rXt|||�}|dkrX|W�bSt|�d|�}	|�d|j|	�IdH}
|
s�|W�0S|�	�IdH|�
|	d|
��||
7}q6W5|dkr�t|d�r�|�||�|��IdHXdS)Ni@rr:)r:r;r<r\r#r{r=rr>rk�write)rfrgr4r5r6r?r@rAr?rBrCrrrrkrs*
z BaseEventLoop._sendfile_fallbackrhc
�s�tdkrtd��t|tj�s*td|����t|dd�sFtd|�d���|��}tj|||||||dd�}|�	�|�
|�|�|j|�}	|�|j
�}
z|IdHWn.tk
r�|��|	��|
���YnX|jS)Nz"Python ssl module is not availablez@sslcontext is expected to be an instance of ssl.SSLContext, got Z_start_tls_compatibleFz
transport z  is not supported by start_tls())r�r�)rRrmrZ
SSLContextr5rrdr	ZSSLProtocolrarbrrory�
BaseExceptionr�rzZ_app_transport)rfrnr�r�r�r�r�r�Zssl_protocolZ
conmade_cbZ	resume_cbrrr�	start_tls�sB	�
��
zBaseEventLoop.start_tls)r=r?r'�
reuse_address�
reuse_port�allow_broadcastr*c �s�|
dk	r�|
jtjkr"td|
�����s>�s>|s>|s>|s>|s>|	r~t��||||||	d�}d�dd�|��D��}td|�d���|
�d�d}
�n�s��s�|d	kr�td
��||fdff}�n�ttd��r�|tj	k�r���fD]}|dk	r�t
|t�s�td
��qڈ�rx�d	dk�rxz"t
�t�
��j��r.t���WnFtk
�rFYn2tk
�rv}zt�d�|�W5d}~XYnX||f��fff}n�i}d	�fd�ffD]�\}}|dk	�r�|j||tj|||d�IdH}|�s�td��|D]:\}}}}}||f}||k�rddg||<||||<�q�q���fdd�|��D�}|�sHtd��g}|tk	�rv|�rftd��ntjdtdd�|D]�\\}}\}}d}
d}
zxtj|tj|d�}
|�r�t|
�|	�r�|
�tjtjd�|
�d���r�|
�|���r|	�s|� |
|�IdH|}
Wn^tk
�rJ}z |
dk	�r0|
�!�|�"|�W5d}~XYn&|
dk	�rb|
�!��YnX�q|�qz|d	�|�}|�#�}|�$|
||
|�}|j%�r̈�r�t�&d��||�nt�'d�||�z|IdHWn|�!��YnX||fS)NzA UDP Socket was expected, got )rS�remote_addrr=r?r'rprqrrr#css$|]\}}|r|�d|��VqdS)�=Nr)rC�k�vrrrrE�sz9BaseEventLoop.create_datagram_endpoint.<locals>.<genexpr>zKsocket modifier keyword arguments can not be used when sock is specified. (�)Frzunexpected address family)NN�AF_UNIXzstring is expected)r�z2Unable to check or remove stale UNIX socket %r: %rrrXrYcs8g|]0\}}�r|ddks�r,|ddks||f�qS)rNrr)rC�keyZ	addr_pair�rSrsrrr��s�z:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address informationz~Passing `reuse_address=True` is no longer supported, as the usage of SO_REUSEPORT in UDP poses a significant security concern.zdThe *reuse_address* parameter has been deprecated as of 3.5.10 and is scheduled for removal in 3.11.r)�
stacklevelrGz@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))(r>r$r2r%�dictr$�itemsrIr#rxrrr5�stat�S_ISSOCK�os�st_mode�remove�FileNotFoundErrorr(r�errorrb�_unsetr�r�r r+r&r'ZSO_BROADCASTrJrOr�r9rdr�r�r&r	) rfr�rSrsr=r?r'rprqrrr*ZoptsZproblemsZr_addrZaddr_pairs_inforO�errZ
addr_infos�idxrfZfamrPZpror�rzrZ
local_addressZremote_addressrWr�r�rnrr{r�create_datagram_endpoint�s$�������
�

��
�
�

����




���z&BaseEventLoop.create_datagram_endpointc
�s\|dd�\}}t|||||f|dd���}	|	dk	r<|	gS|j||||||d�IdHSdS)Nrr-)rAr%)
rfr�r=r>r?r'r�r;r<r&rrrrbLs�zBaseEventLoop._ensure_resolvedc�s8|j||f|tj||d�IdH}|s4td|�d���|S)N)r=r>r'r�zgetaddrinfo(z) returned empty list)rbr$r1r()rfr;r<r=r'rfrrr�_create_server_getaddrinfoXs�z(BaseEventLoop._create_server_getaddrinfor)	r=r'r*r�rRrprqr�r�c	�s�t|t�rtd��|dk	r*|dkr*td��|dk	s<�dk	�r"|dk	rLtd��|	dkrhtjdkoftjdk}	g}
|dkr|dg}n$t|t�s�t|t	j
j�s�|g}n|}����fdd�|D�}tj
|d	�i�IdH}ttj�|��}d
}�z|D�]}|\}}}}}zt�|||�}Wn8tjk
�rH�j�r@tjd|||dd
�Yq�YnX|
�|�|	�rl|�tjtjd�|
�rzt|�t�r�|tjk�r�ttd��r�|�tj tj!d�z|�"|�Wq�t#k
�r�}z t#|j$d||j%�&�f�d�W5d}~XYq�Xq�d}W5|�s|
D]}|���qXn4|dk�r4td��|j'tj(k�rPtd|����|g}
|
D]}|�)d
��qZt*�|
||||�}|�r�|�+�tj,d�d�IdH�j�r�t�-d|�|S)Nz*ssl argument must be an SSLContext or NonerVrW�posix�cygwinr.csg|]}�j|���d��qS))r=r')r�)rCr;�r=r'r<rfrrr��s�
�z/BaseEventLoop.create_server.<locals>.<listcomp>r�Fz: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 specifiedrarr�z
%r is serving).rrir5r%r�r�r�platformrrF�abc�Iterablerr��setrKrLrMr�r$r�r�r�warningr9r&r'ZSO_REUSEADDRr+r8rr#r�ZIPV6_V6ONLYrJr(rMrKrLr>r1rIrr�r�r&)rfr�r;r<r=r'r*r�rRrprqr�r�r�ZhostsZfsrfZ	completed�resr@Zsocktyper?Z	canonnameZsar�r�rr�r�
create_server`s�
��
��
�

������
�zBaseEventLoop.create_server)rRr�c�sv|jtjkrtd|����|dk	r.|s.td��|j|||dd|d�IdH\}}|jrn|�d�}t�d|||�||fS)NrarVr.T)r�r�r$z%r handled: (%r, %r))	r>r$r1r%rdr�rerr	)rfr�r*rRr�rnr�rrr�connect_accepted_socket�s$��
z%BaseEventLoop.connect_accepted_socketc�sd|�}|��}|�|||�}z|IdHWn|���YnX|jr\t�d|��||�||fS)Nz Read pipe %r connected: (%r, %r))rdr�r�r�rr	�fileno�rfr�r�r�r�rnrrr�connect_read_pipe�s�zBaseEventLoop.connect_read_pipec�sd|�}|��}|�|||�}z|IdHWn|���YnX|jr\t�d|��||�||fS)Nz!Write pipe %r connected: (%r, %r))rdr�r�r�rr	r�r�rrr�connect_write_pipes�z BaseEventLoop.connect_write_pipecCs�|g}|dk	r"|�dt|����|dk	rJ|tjkrJ|�dt|����n8|dk	rf|�dt|����|dk	r�|�dt|����t�d�|��dS)Nzstdin=zstdout=stderr=zstdout=zstderr=� )r9r!rrrr	r$)rfr(r�r�r�r&rrr�_log_subprocessszBaseEventLoop._log_subprocess)	r�r�r��universal_newlinesr�r��encoding�errors�textc	�s�t|ttf�std��|r"td��|s.td��|dkr>td��|rJtd��|	dk	rZtd��|
dk	rjtd��|�}
d}|jr�d	|}|�||||�|j|
|d
||||f|�IdH}|jr�|dk	r�t�d||�||
fS)Nzcmd must be a string� universal_newlines must be Falsezshell must be Truer�bufsize must be 0�text must be False�encoding must be None�errors must be Nonezrun shell command %rT�%s: %r)	rr3rr%r�r�r�rr&)rfr��cmdr�r�r�r�r�r�r�r�r�r�r��	debug_logrnrrr�subprocess_shellsB��
zBaseEventLoop.subprocess_shellc	�s�|rtd��|rtd��|dkr(td��|r4td��|	dk	rDtd��|
dk	rTtd��|f|}|�}d}|jr�d|��}|�||||�|j||d	||||f|
�IdH}|jr�|dk	r�t�d
||�||fS)Nr�zshell must be Falserr�r�r�r�zexecute program Fr�)r%r�r�r�rr&)rfr�Zprogramr�r�r�r�r�r�r�r�r�r�r�Z
popen_argsr�r�rnrrr�subprocess_execCs@

��
zBaseEventLoop.subprocess_execcCs|jSrB)r�rqrrr�get_exception_handleresz#BaseEventLoop.get_exception_handlercCs(|dk	rt|�std|����||_dS)Nz+A callable object or None is expected, got )r�r5r�)rfZhandlerrrr�set_exception_handlerjsz#BaseEventLoop.set_exception_handlerc	Cs|�d�}|sd}|�d�}|dk	r6t|�||jf}nd}d|kr`|jdk	r`|jjr`|jj|d<|g}t|�D]�}|dkr|qn||}|dkr�d�t�|��}d	}||�	�7}n2|dkr�d�t�|��}d
}||�	�7}nt
|�}|�|�d|���qntj
d�|�|d
�dS)Nr�z!Unhandled exception in event looprRFZsource_tracebackZhandle_traceback>r�rRr.z+Object created at (most recent call last):
z+Handle created at (most recent call last):
rH�
r�)�getr>�
__traceback__r�r��sortedr$�	traceback�format_list�rstriprr9rr�)	rfr
r�rRr�Z	log_linesrz�value�tbrrr�default_exception_handler{s<

���z'BaseEventLoop.default_exception_handlercCs�|jdkrVz|�|�Wq�ttfk
r2�Yq�tk
rRtjddd�Yq�Xn�z|�||�Wn�ttfk
r��Ynttk
r�}zVz|�d||d��Wn:ttfk
r��Yn"tk
r�tjddd�YnXW5d}~XYnXdS)Nz&Exception in default exception handlerTr�z$Unhandled error in exception handler)r�rRr
zeException in default exception handler while handling an unexpected error in custom exception handler)r�r�rSrTrnrr�)rfr
rWrrrr��s4
���z$BaseEventLoop.call_exception_handlercCs|jr
dS|j�|�dSrB)�
_cancelledr�r9�rfrrrr�
_add_callback�szBaseEventLoop._add_callbackcCs|�|�|��dSrB)r�r�r�rrr�_add_callback_signalsafe�s
z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dSrZ)r�r�r�rrr�_timer_handle_cancelled�sz%BaseEventLoop._timer_handle_cancelledc	Cs�t|j�}|tkr`|j|tkr`g}|jD]}|jr<d|_q*|�|�q*t�|�||_d|_n4|jr�|jdjr�|jd8_t�	|j�}d|_q`d}|j
s�|jr�d}n*|jr�|jdj}t
td||���t�}|j�|�}|�|�|��|j}|j�r:|jd}|j|k�r�q:t�	|j�}d|_|j
�|�q�t|j
�}t|�D]|}	|j
��}|j�rf�qL|j�r�zD||_|��}
|��|��|
}||jk�r�t�dt|�|�W5d|_Xn|���qLd}dS)NFrrzExecuting %s took %.3f seconds)r�r��_MIN_SCHEDULED_TIMER_HANDLESr��%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr�r9r�heapify�heappopr�r�Z_whenr;�maxr��MAXIMUM_SELECT_TIMEOUTZ	_selectorZselectr�r��range�popleftr�r�Z_runr�rr�r)rfZsched_countZ
new_scheduledrZtimeoutrr�Zend_timeZntodo�ir)r+rrrr�sj
��





�
zBaseEventLoop._run_oncecCsHt|�t|j�krdS|r2t��|_t�tj�nt�|j�||_dSrB)rir�r�#get_coroutine_origin_tracking_depthr��#set_coroutine_origin_tracking_depthrZDEBUG_STACK_DEPTH�rfZenabledrrrr�Fs���z,BaseEventLoop._set_coroutine_origin_trackingcCs|jSrB)r�rqrrrr�UszBaseEventLoop.get_debugcCs ||_|��r|�|j|�dSrB)r�r�r�r�r�rrrr�XszBaseEventLoop.set_debug)N)N)NNN)NN)NN)N)r)rN)N)NN)FN)rN)NN)NN)Sr|r}r~rhr�rdr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrUr�r�r�r�rr�r�rrrrrrr�rr!r,r%r.r7r1r3r0rQrgrdrlrjrkror�r�r$r1rbr�r6Z
AI_PASSIVEr�r�r�r�r�rrr�r�r�r�r�r�r�r�r�rr�r�r�rrrrr�sF���
�
�
�
�
		&	
	�

�
%���
�/�/���	��w��%�"29Nr)rr)r)6rFZcollections.abcZconcurrent.futuresrrZrrKr�r$rrrr�r�rr�r�rR�ImportErrorr.rrrrrrr	r
rrr
�logr�__all__r�r�r#r8r��objectr�rr!r+rArPrXr[ZProtocolr\ZAbstractServerrZAbstractEventLooprrrrr�<module>sb

		
;


DoPK [ۂ�U
+
+(__pycache__/futures.cpython-38.opt-1.pycnu�[���U

e5db3�@s�dZdZddlZddlZddlZddlZddlmZddlm	Z	ddlm
Z
ddlmZejZej
Z
ejZejZejdZGd	d
�d
�ZeZdd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�dd�ZzddlZWnek
r�YnXejZZdS)z.A Future class similar to the one in PEP 3148.)�Future�wrap_future�isfuture�N�)�base_futures)�events)�
exceptions)�format_helpersc@s�eZdZdZeZdZdZdZdZ	dZ
dZdd�dd�Ze
jZdd�Zd	d
�Zedd��Zejd
d��Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Z e Z!dS)'ra,This class is *almost* compatible with concurrent.futures.Future.

    Differences:

    - This class is not thread-safe.

    - result() and exception() do not take a timeout argument and
      raise an exception when the future isn't done yet.

    - Callbacks registered with add_done_callback() are always called
      via the event loop's call_soon().

    - This class is not compatible with the wait() and as_completed()
      methods in the concurrent.futures package.

    (In Python 3.4 or later we may be able to unify the implementations.)
    NF��loopcCs@|dkrt��|_n||_g|_|j��r<t�t�d��|_	dS)z�Initialize the future.

        The optional event_loop argument allows explicitly setting the event
        loop object used by the future. If it's not provided, the future uses
        the default event loop.
        Nr)
r�get_event_loop�_loop�
_callbacksZ	get_debugr	�
extract_stack�sys�	_getframe�_source_traceback��selfr�r�'/usr/lib64/python3.8/asyncio/futures.py�__init__Ds
�zFuture.__init__cCsd�|jjd�|����S)Nz<{} {}>� )�format�	__class__�__name__�join�
_repr_info�rrrr�__repr__Vs
�zFuture.__repr__cCsF|js
dS|j}|jj�d�||d�}|jr6|j|d<|j�|�dS)Nz exception was never retrieved)�message�	exception�futureZsource_traceback)�_Future__log_traceback�
_exceptionrrrr
Zcall_exception_handler)r�exc�contextrrr�__del__Zs�
zFuture.__del__cCs|jS�N)r#rrrr�_log_tracebackjszFuture._log_tracebackcCst|�rtd��d|_dS)Nz'_log_traceback can only be set to FalseF)�bool�
ValueErrorr#)r�valrrrr)nscCs|j}|dkrtd��|S)z-Return the event loop the Future is bound to.Nz!Future object is not initialized.)r
�RuntimeErrorrrrr�get_looptszFuture.get_loopcCs&d|_|jtkrdSt|_|��dS)z�Cancel the future and schedule callbacks.

        If the future is already done or cancelled, return False.  Otherwise,
        change the future's state to cancelled, schedule the callbacks and
        return True.
        FT)r#�_state�_PENDING�
_CANCELLED�_Future__schedule_callbacksrrrr�cancel{s
z
Future.cancelcCsH|jdd�}|sdSg|jdd�<|D]\}}|jj|||d�q(dS)z�Internal: Ask the event loop to call all callbacks.

        The callbacks are scheduled to be called as soon as possible. Also
        clears the callback list.
        N�r&)rr
�	call_soon)rZ	callbacks�callback�ctxrrrZ__schedule_callbacks�szFuture.__schedule_callbackscCs
|jtkS)z(Return True if the future was cancelled.)r/r1rrrr�	cancelled�szFuture.cancelledcCs
|jtkS)z�Return True if the future is done.

        Done means either that a result / exception are available, or that the
        future was cancelled.
        )r/r0rrrr�done�szFuture.donecCs@|jtkrtj�|jtkr$t�d��d|_|jdk	r:|j�|jS)aReturn the result this future represents.

        If the future has been cancelled, raises CancelledError.  If the
        future's result isn't yet available, raises InvalidStateError.  If
        the future is done and has an exception set, this exception is raised.
        zResult is not ready.FN)	r/r1r�CancelledError�	_FINISHED�InvalidStateErrorr#r$�_resultrrrr�result�s



z
Future.resultcCs0|jtkrtj�|jtkr$t�d��d|_|jS)a&Return the exception that was set on this future.

        The exception (or None if no exception was set) is returned only if
        the future is done.  If the future has been cancelled, raises
        CancelledError.  If the future isn't done yet, raises
        InvalidStateError.
        zException is not set.F)r/r1rr:r;r<r#r$rrrrr!�s


zFuture.exceptionr4cCsB|jtkr|jj|||d�n |dkr.t��}|j�||f�dS)z�Add a callback to be run when the future becomes done.

        The callback is called with a single argument - the future object. If
        the future is already done when this is called, the callback is
        scheduled with call_soon.
        r4N)r/r0r
r5�contextvarsZcopy_contextr�append)r�fnr&rrr�add_done_callback�s

zFuture.add_done_callbackcs<�fdd�|jD�}t|j�t|�}|r8||jdd�<|S)z}Remove all instances of a callback from the "call when done" list.

        Returns the number of callbacks removed.
        cs g|]\}}|�kr||f�qSrr)�.0�fr7�rArr�
<listcomp>�s�z/Future.remove_done_callback.<locals>.<listcomp>N)r�len)rrAZfiltered_callbacksZ
removed_countrrEr�remove_done_callback�s
�zFuture.remove_done_callbackcCs8|jtkr t�|j�d|����||_t|_|��dS)z�Mark the future done and set its result.

        If the future is already done when this method is called, raises
        InvalidStateError.
        �: N)r/r0rr<r=r;r2)rr>rrr�
set_result�s

zFuture.set_resultcCsb|jtkr t�|j�d|����t|t�r0|�}t|�tkrDtd��||_t	|_|�
�d|_dS)z�Mark the future done and set an exception.

        If the future is already done when this method is called, raises
        InvalidStateError.
        rIzPStopIteration interacts badly with generators and cannot be raised into a FutureTN)r/r0rr<�
isinstance�type�
StopIteration�	TypeErrorr$r;r2r#)rr!rrr�
set_exception�s

zFuture.set_exceptionccs,|��sd|_|V|��s$td��|��S)NTzawait wasn't used with future)r9�_asyncio_future_blockingr-r>rrrr�	__await__szFuture.__await__)"r�
__module__�__qualname__�__doc__r0r/r=r$r
rrPr#rrZ_future_repr_inforrr'�propertyr)�setterr.r3r2r8r9r>r!rBrHrJrOrQ�__iter__rrrrrs:

rcCs,z
|j}Wntk
rYnX|�S|jSr()r.�AttributeErrorr
)�futr.rrr�	_get_loops
rZcCs|��rdS|�|�dS)z?Helper setting the result only if the future was not cancelled.N)r8rJ)rYr>rrr�_set_result_unless_cancelledsr[cCsXt|�}|tjjkr tj|j�S|tjjkr8tj|j�S|tjjkrPtj|j�S|SdSr()rL�
concurrent�futuresr:r�args�TimeoutErrorr<)r%Z	exc_classrrr�_convert_future_exc#sr`cCsR|��r|��|��sdS|��}|dk	r<|�t|��n|��}|�|�dS)z8Copy state from a future to a concurrent.futures.Future.N)r8r3Zset_running_or_notify_cancelr!rOr`r>rJ)r\�sourcer!r>rrr�_set_concurrent_future_state/srbcCsT|��rdS|��r|��n2|��}|dk	r>|�t|��n|��}|�|�dS)zqInternal helper to copy state from another Future.

    The other Future may be a concurrent.futures.Future.
    N)r8r3r!rOr`r>rJ)ra�destr!r>rrr�_copy_future_state>s
rdcs�t��st�tjj�std��t��s<t�tjj�s<td��t��rLt��nd�t��r`t��nd�dd�����fdd�}����fdd	�}��|���|�dS)
aChain two futures so that when one completes, so does the other.

    The result (or exception) of source will be copied to destination.
    If destination is cancelled, source gets cancelled too.
    Compatible with both asyncio.Future and concurrent.futures.Future.
    z(A future is required for source argumentz-A future is required for destination argumentNcSs"t|�rt||�n
t||�dSr()rrdrb)r"�otherrrr�
_set_statebsz!_chain_future.<locals>._set_statecs2|��r.�dks��kr"���n���j�dSr()r8r3�call_soon_threadsafe)�destination)�	dest_loopra�source_looprr�_call_check_cancelhs
z)_chain_future.<locals>._call_check_cancelcsJ���r�dk	r���rdS�dks,��kr8��|�n����|�dSr()r8Z	is_closedrg)ra)rfrirhrjrr�_call_set_stateos��z&_chain_future.<locals>._call_set_state)rrKr\r]rrNrZrB)rarhrkrlr)rfrirhrarjr�
_chain_futureRs��	
rmr
cCs2t|�r|S|dkrt��}|��}t||�|S)z&Wrap concurrent.futures.Future object.N)rrrZ
create_futurerm)r"rZ
new_futurerrrr|s
r)rT�__all__Zconcurrent.futuresr\r?Zloggingr�rrrr	rr0r1r;�DEBUGZSTACK_DEBUGrZ	_PyFuturerZr[r`rbrdrmrZ_asyncio�ImportErrorZ_CFuturerrrr�<module>s:
q*
PK [��b��%__pycache__/subprocess.cpython-38.pycnu�[���U

e5d��@s�dZddlZddlZddlmZddlmZddlmZddlmZddlm	Z	ej
Z
ejZejZGd	d
�d
ej
ej�ZGdd�d�Zddddejfd
d�Zddddejd�dd�ZdS))�create_subprocess_exec�create_subprocess_shell�N�)�events)�	protocols)�streams)�tasks)�loggercsXeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Z�ZS)�SubprocessStreamProtocolz0Like StreamReaderProtocol, but for a subprocess.csHt�j|d�||_d|_|_|_d|_d|_g|_|j	�
�|_dS)N��loopF)�super�__init__�_limit�stdin�stdout�stderr�
_transport�_process_exited�	_pipe_fds�_loopZ
create_future�
_stdin_closed)�self�limitr��	__class__��*/usr/lib64/python3.8/asyncio/subprocess.pyrsz!SubprocessStreamProtocol.__init__cCsn|jjg}|jdk	r&|�d|j���|jdk	rB|�d|j���|jdk	r^|�d|j���d�d�|��S)Nzstdin=zstdout=zstderr=z<{}>� )r�__name__r�appendrr�format�join)r�inforrr�__repr__s



z!SubprocessStreamProtocol.__repr__cCs�||_|�d�}|dk	rDtj|j|jd�|_|j�|�|j�	d�|�d�}|dk	r�tj|j|jd�|_
|j
�|�|j�	d�|�d�}|dk	r�tj||d|jd�|_dS)Nr�rr�r)�protocol�readerr)
r�get_pipe_transportr�StreamReaderrrrZ
set_transportrr r�StreamWriterr)r�	transportZstdout_transportZstderr_transportZstdin_transportrrr�connection_made)s,
�
�
�z(SubprocessStreamProtocol.connection_madecCs:|dkr|j}n|dkr |j}nd}|dk	r6|�|�dS)Nrr&)rrZ	feed_data)r�fd�datar(rrr�pipe_data_receivedAsz+SubprocessStreamProtocol.pipe_data_receivedcCs�|dkrN|j}|dk	r|��|�|�|dkr>|j�d�n|j�|�dS|dkr^|j}n|dkrn|j}nd}|dk	r�|dkr�|��n
|�|�||j	kr�|j	�
|�|��dS)Nrrr&)r�closeZconnection_lostrZ
set_resultZ
set_exceptionrrZfeed_eofr�remove�_maybe_close_transport)rr.�exc�piper(rrr�pipe_connection_lostKs*



z-SubprocessStreamProtocol.pipe_connection_lostcCsd|_|��dS)NT)rr3�rrrr�process_exitedfsz'SubprocessStreamProtocol.process_exitedcCs(t|j�dkr$|jr$|j��d|_dS)Nr)�lenrrrr1r7rrrr3js
z/SubprocessStreamProtocol._maybe_close_transportcCs||jkr|jSdS�N)rr)r�streamrrr�_get_close_waiteros
z*SubprocessStreamProtocol._get_close_waiter)
r�
__module__�__qualname__�__doc__rr$r-r0r6r8r3r<�
__classcell__rrrrr
s	

r
c@sjeZdZdd�Zdd�Zedd��Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
ddd�ZdS)�ProcesscCs8||_||_||_|j|_|j|_|j|_|��|_dSr:)rZ	_protocolrrrrZget_pid�pid)rr,r'rrrrruszProcess.__init__cCsd|jj�d|j�d�S)N�<r�>)rrrBr7rrrr$~szProcess.__repr__cCs
|j��Sr:)rZget_returncoder7rrr�
returncode�szProcess.returncodec�s|j��IdHS)z?Wait until the process exit and return the process return code.N)rZ_waitr7rrr�wait�szProcess.waitcCs|j�|�dSr:)r�send_signal)r�signalrrrrG�szProcess.send_signalcCs|j��dSr:)r�	terminater7rrrrI�szProcess.terminatecCs|j��dSr:)r�killr7rrrrJ�szProcess.killc
�s�|j��}|j�|�|r,t�d|t|��z|j��IdHWn8tt	fk
rx}z|rht�d||�W5d}~XYnX|r�t�d|�|j�
�dS)Nz%%r communicate: feed stdin (%s bytes)z%r communicate: stdin got %rz%r communicate: close stdin)r�	get_debugr�writer	�debugr9Zdrain�BrokenPipeError�ConnectionResetErrorr1)r�inputrMr4rrr�_feed_stdin�s 
� zProcess._feed_stdinc�sdSr:rr7rrr�_noop�sz
Process._noopc�s�|j�|�}|dkr|j}n|dks(t�|j}|j��rV|dkrDdnd}t�d||�|�	�IdH}|j��r�|dkrzdnd}t�d||�|�
�|S)Nr&rrrz%r communicate: read %sz%r communicate: close %s)rr)r�AssertionErrorrrrKr	rM�readr1)rr.r,r;�name�outputrrr�_read_stream�s

zProcess._read_streamNc�s�|dk	r|�|�}n|��}|jdk	r2|�d�}n|��}|jdk	rP|�d�}n|��}tj||||jd�IdH\}}}|��IdH||fS)Nrr&r)	rQrRrrWrrZgatherrrF)rrPrrrrrr�communicate�s


�zProcess.communicate)N)rr=r>rr$�propertyrErFrGrIrJrQrRrWrXrrrrrAts	
rAc
�sb�dkrt���ntjdtdd���fdd�}�j||f|||d�|��IdH\}}	t||	��S)N�ZThe loop argument is deprecated since Python 3.8 and scheduled for removal in Python 3.10.r&��
stacklevelcst��d�S�Nr%�r
rr%rr�<lambda>�s�z)create_subprocess_shell.<locals>.<lambda>�rrr)r�get_event_loop�warnings�warn�DeprecationWarningZsubprocess_shellrA)
�cmdrrrrr�kwds�protocol_factoryr,r'rr%rr�s$
����r)rrrrrc�sf�dkrt���ntjdtdd���fdd�}�j||f|�|||d�|��IdH\}	}
t|	|
��S)NrZr&r[cst��d�Sr]r^rr%rrr_�s�z(create_subprocess_exec.<locals>.<lambda>r`)rrarbrcrdZsubprocess_execrA)Zprogramrrrrr�argsrfrgr,r'rr%rr�s(
�����r)�__all__�
subprocessrb�rrrr�logr	�PIPEZSTDOUTZDEVNULLZFlowControlMixinZSubprocessProtocolr
rAZ_DEFAULT_LIMITrrrrrr�<module>s.�bV�
�PK [$��'��%__pycache__/base_tasks.cpython-38.pycnu�[���U

e5d�	�@sDddlZddlZddlmZddlmZdd�Zdd�Zd	d
�ZdS)�N�)�base_futures)�
coroutinescCsnt�|�}|jrd|d<|�dd|���t�|j�}|�dd|�d��|jdk	rj|�dd	|j���|S)
NZ
cancellingrrzname=%r�zcoro=<�>�z	wait_for=)	rZ_future_repr_infoZ_must_cancel�insertZget_namerZ_format_coroutine�_coroZ_fut_waiter)�task�info�coro�r
�*/usr/lib64/python3.8/asyncio/base_tasks.py�_task_repr_infos

rcCs�g}t|jd�r|jj}n0t|jd�r0|jj}nt|jd�rF|jj}nd}|dk	r�|dk	r�|dk	rt|dkrlq�|d8}|�|�|j}qR|��nH|jdk	r�|jj	}|dk	r�|dk	r�|dkr�q�|d8}|�|j
�|j}q�|S)N�cr_frame�gi_frame�ag_framerr)�hasattrr	rrr�append�f_back�reverse�
_exception�
__traceback__�tb_frame�tb_next)r
�limitZframes�f�tbr
r
r�_task_get_stacks6





rcCs�g}t�}|j|d�D]Z}|j}|j}|j}|j}	||krN|�|�t�|�t�	|||j
�}
|�|||	|
f�q|j}|s�t
d|��|d�n2|dk	r�t
d|�d�|d�nt
d|�d�|d�tj||d�|dk	r�t�|j|�D]}
t
|
|dd�q�dS)	N)rz
No stack for )�filezTraceback for z (most recent call last):z
Stack for �)r�end)�setZ	get_stack�f_lineno�f_code�co_filename�co_name�add�	linecache�
checkcache�getline�	f_globalsrr�print�	traceback�
print_list�format_exception_only�	__class__)r
rr�extracted_list�checkedr�lineno�co�filename�name�line�excr
r
r�_task_print_stack<s,

r9)r(r-r rrrrr9r
r
r
r�<module>s#PK [�5BB)__pycache__/__main__.cpython-38.opt-1.pycnu�[���U

e5d
�@sJddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZGdd�dej�Z
Gdd�dej�Zedk�rFe��Ze�e�d	eiZd
D]Ze�eee<q�e
ee�ZdadazddlZWnek
r�YnXe�Zde_e��ze��Wn6e k
�r>t�r6t�!��s6t�"�daYq�Yq�X�qFq�dS)
�N�)�futurescs$eZdZ�fdd�Zdd�Z�ZS)�AsyncIOInteractiveConsolecs*t��|�|jjjtjO_||_dS)N)�super�__init__�compileZcompiler�flags�astZPyCF_ALLOW_TOP_LEVEL_AWAIT�loop)�self�localsr
��	__class__��(/usr/lib64/python3.8/asyncio/__main__.pyrsz"AsyncIOInteractiveConsole.__init__csttj������fdd�}t�|�z
���WStk
rD�Yn,tk
rntrb��	d�n��
�YnXdS)Nc
sdadat���j�}z
|�}Wnztk
r6�Ynftk
rj}zda��|�WY�dSd}~XYn2tk
r�}z��|�WY�dSd}~XYnXt	�
|�s���|�dSz�j�
|�at�t��Wn.tk
�r�}z��|�W5d}~XYnXdS)NFT)�repl_future�repl_future_interrupted�types�FunctionTyper�
SystemExit�KeyboardInterruptZ
set_exception�
BaseException�inspectZiscoroutineZ
set_resultr
Zcreate_taskrZ
_chain_future)�func�coroZex�exc��codeZfuturerrr�callbacks,




z3AsyncIOInteractiveConsole.runcode.<locals>.callbackz
KeyboardInterrupt
)�
concurrentrZFuturer
�call_soon_threadsafe�resultrrr�writeZ
showtraceback)rrrrrr�runcodes


z!AsyncIOInteractiveConsole.runcode)�__name__�
__module__�__qualname__rr#�
__classcell__rrr
rrsrc@seZdZdd�ZdS)�
REPLThreadcCsZz6dtj�dtj�dt	tdd��d	�}t
j|d
d�W5tjddtd�t�tj�XdS)N�ignorez ^coroutine .* was never awaited$)�message�categoryz
asyncio REPL z on zy
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
Zps1z>>> zimport asynciozexiting asyncio REPL...)�bannerZexitmsg)�warnings�filterwarnings�RuntimeWarningr
r �stop�sys�version�platform�getattr�consoleZinteract)rr,rrr�runFs"��
�zREPLThread.runN)r$r%r&r6rrrrr(Dsr(�__main__�asyncio>�__builtins__�__spec__r$�__file__�
__loader__�__package__FT)#r	r8rZconcurrent.futuresrrr1Z	threadingrr-�rZInteractiveConsolerZThreadr(r$Znew_event_loopr
Zset_event_loopZrepl_locals�keyrr5rr�readline�ImportErrorZrepl_threadZdaemon�startZrun_foreverrZdoneZcancelrrrr�<module>sF6



PK [��M%!%!!__pycache__/trsock.cpython-38.pycnu�[���U

e5d��@s"ddlZddlZGdd�d�ZdS)�Nc@s�eZdZdZdZejd�dd�Zdd�Zedd	��Z	ed
d��Z
edd
��Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Z d8d9�Z!d:d;�Z"d<d=�Z#d>d?�Z$d@dA�Z%dBdC�Z&dDdE�Z'dFdG�Z(dHdI�Z)dJdK�Z*dLdM�Z+dNdO�Z,dPdQ�Z-dRdS�Z.dTdU�Z/dVdW�Z0dXdY�Z1dZd[�Z2d\S)]�TransportSocketz�A socket-like wrapper for exposing real transport sockets.

    These objects can be safely returned by APIs like
    `transport.get_extra_info('socket')`.  All potentially disruptive
    operations (like "socket.close()") are banned.
    ��_sock)�sockcCs
||_dS�Nr)�selfr�r�&/usr/lib64/python3.8/asyncio/trsock.py�__init__szTransportSocket.__init__cCstjd|�d�t|d�dS)NzUsing z� on sockets returned from get_extra_info('socket') will be prohibited in asyncio 3.9. Please report your use case to bugs.python.org.)�source)�warnings�warn�DeprecationWarning)rZwhatrrr	�_nas

�zTransportSocket._nacCs|jjSr)r�family�rrrr	rszTransportSocket.familycCs|jjSr)r�typerrrr	rszTransportSocket.typecCs|jjSr)r�protorrrr	r"szTransportSocket.protocCs�d|���d|j�d|j�d|j��}|��dkr�z|��}|rN|�d|��}Wntjk
rfYnXz|��}|r�|�d|��}Wntjk
r�YnX|�d�S)	Nz<asyncio.TransportSocket fd=z	, family=z, type=z, proto=���z, laddr=z, raddr=�>)�filenorrr�getsockname�socket�error�getpeername)r�sZladdrZraddrrrr	�__repr__&s $�zTransportSocket.__repr__cCstd��dS)Nz/Cannot serialize asyncio.TransportSocket object)�	TypeErrorrrrr	�__getstate__=szTransportSocket.__getstate__cCs
|j��Sr)rrrrrr	r@szTransportSocket.filenocCs
|j��Sr)r�duprrrr	rCszTransportSocket.dupcCs
|j��Sr)r�get_inheritablerrrr	r FszTransportSocket.get_inheritablecCs|j�|�dSr)r�shutdown)rZhowrrr	r!IszTransportSocket.shutdowncOs|jj||�Sr)r�
getsockopt�r�args�kwargsrrr	r"NszTransportSocket.getsockoptcOs|jj||�dSr)r�
setsockoptr#rrr	r&QszTransportSocket.setsockoptcCs
|j��Sr)rrrrrr	rTszTransportSocket.getpeernamecCs
|j��Sr)rrrrrr	rWszTransportSocket.getsocknamecCs
|j��Sr)r�
getsockbynamerrrr	r'ZszTransportSocket.getsockbynamecCs|�d�|j��S)Nzaccept() method)rr�acceptrrrr	r(]s
zTransportSocket.acceptcOs|�d�|jj||�S)Nzconnect() method)rr�connectr#rrr	r)as
zTransportSocket.connectcOs|�d�|jj||�S)Nzconnect_ex() method)rr�
connect_exr#rrr	r*es
zTransportSocket.connect_excOs|�d�|jj||�S)Nz
bind() method)rr�bindr#rrr	r+is
zTransportSocket.bindcOs|�d�|jj||�S)Nzioctl() method)rr�ioctlr#rrr	r,ms
zTransportSocket.ioctlcOs|�d�|jj||�S)Nzlisten() method)rr�listenr#rrr	r-qs
zTransportSocket.listencCs|�d�|j��S)Nzmakefile() method)rr�makefilerrrr	r.us
zTransportSocket.makefilecOs|�d�|jj||�S)Nzsendfile() method)rr�sendfiler#rrr	r/ys
zTransportSocket.sendfilecCs|�d�|j��S)Nzclose() method)rr�closerrrr	r0}s
zTransportSocket.closecCs|�d�|j��S)Nzdetach() method)rr�detachrrrr	r1�s
zTransportSocket.detachcOs|�d�|jj||�S)Nzsendmsg_afalg() method)rr�
sendmsg_afalgr#rrr	r2�s
zTransportSocket.sendmsg_afalgcOs|�d�|jj||�S)Nzsendmsg() method)rr�sendmsgr#rrr	r3�s
zTransportSocket.sendmsgcOs|�d�|jj||�S)Nzsendto() method)rr�sendtor#rrr	r4�s
zTransportSocket.sendtocOs|�d�|jj||�S)Nz
send() method)rr�sendr#rrr	r5�s
zTransportSocket.sendcOs|�d�|jj||�S)Nzsendall() method)rr�sendallr#rrr	r6�s
zTransportSocket.sendallcOs|�d�|jj||�S)Nzset_inheritable() method)rr�set_inheritabler#rrr	r7�s
zTransportSocket.set_inheritablecCs|�d�|j�|�S)Nzshare() method)rr�share)rZ
process_idrrr	r8�s
zTransportSocket.sharecOs|�d�|jj||�S)Nzrecv_into() method)rr�	recv_intor#rrr	r9�s
zTransportSocket.recv_intocOs|�d�|jj||�S)Nzrecvfrom_into() method)rr�
recvfrom_intor#rrr	r:�s
zTransportSocket.recvfrom_intocOs|�d�|jj||�S)Nzrecvmsg_into() method)rr�recvmsg_intor#rrr	r;�s
zTransportSocket.recvmsg_intocOs|�d�|jj||�S)Nzrecvmsg() method)rr�recvmsgr#rrr	r<�s
zTransportSocket.recvmsgcOs|�d�|jj||�S)Nzrecvfrom() method)rr�recvfromr#rrr	r=�s
zTransportSocket.recvfromcOs|�d�|jj||�S)Nz
recv() method)rr�recvr#rrr	r>�s
zTransportSocket.recvcCs|dkrdStd��dS)Nrz<settimeout(): only 0 timeout is allowed on transport sockets��
ValueError)r�valuerrr	�
settimeout�s
�zTransportSocket.settimeoutcCsdS)Nrrrrrr	�
gettimeout�szTransportSocket.gettimeoutcCs|sdStd��dS)Nz3setblocking(): transport sockets cannot be blockingr?)r�flagrrr	�setblocking�s
�zTransportSocket.setblockingcCs|�d�|j��S�Nzcontext manager protocol)rr�	__enter__rrrr	rG�s
zTransportSocket.__enter__cGs|�d�|jj|�SrF)rr�__exit__)r�errrrr	rH�s
zTransportSocket.__exit__N)3�__name__�
__module__�__qualname__�__doc__�	__slots__rr
r�propertyrrrrrrrr r!r"r&rrr'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>rBrCrErGrHrrrr	rsb


r)rrrrrrr	�<module>sPK [�5BB#__pycache__/__main__.cpython-38.pycnu�[���U

e5d
�@sJddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZGdd�dej�Z
Gdd�dej�Zedk�rFe��Ze�e�d	eiZd
D]Ze�eee<q�e
ee�ZdadazddlZWnek
r�YnXe�Zde_e��ze��Wn6e k
�r>t�r6t�!��s6t�"�daYq�Yq�X�qFq�dS)
�N�)�futurescs$eZdZ�fdd�Zdd�Z�ZS)�AsyncIOInteractiveConsolecs*t��|�|jjjtjO_||_dS)N)�super�__init__�compileZcompiler�flags�astZPyCF_ALLOW_TOP_LEVEL_AWAIT�loop)�self�localsr
��	__class__��(/usr/lib64/python3.8/asyncio/__main__.pyrsz"AsyncIOInteractiveConsole.__init__csttj������fdd�}t�|�z
���WStk
rD�Yn,tk
rntrb��	d�n��
�YnXdS)Nc
sdadat���j�}z
|�}Wnztk
r6�Ynftk
rj}zda��|�WY�dSd}~XYn2tk
r�}z��|�WY�dSd}~XYnXt	�
|�s���|�dSz�j�
|�at�t��Wn.tk
�r�}z��|�W5d}~XYnXdS)NFT)�repl_future�repl_future_interrupted�types�FunctionTyper�
SystemExit�KeyboardInterruptZ
set_exception�
BaseException�inspectZiscoroutineZ
set_resultr
Zcreate_taskrZ
_chain_future)�func�coroZex�exc��codeZfuturerrr�callbacks,




z3AsyncIOInteractiveConsole.runcode.<locals>.callbackz
KeyboardInterrupt
)�
concurrentrZFuturer
�call_soon_threadsafe�resultrrr�writeZ
showtraceback)rrrrrr�runcodes


z!AsyncIOInteractiveConsole.runcode)�__name__�
__module__�__qualname__rr#�
__classcell__rrr
rrsrc@seZdZdd�ZdS)�
REPLThreadcCsZz6dtj�dtj�dt	tdd��d	�}t
j|d
d�W5tjddtd�t�tj�XdS)N�ignorez ^coroutine .* was never awaited$)�message�categoryz
asyncio REPL z on zy
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
Zps1z>>> zimport asynciozexiting asyncio REPL...)�bannerZexitmsg)�warnings�filterwarnings�RuntimeWarningr
r �stop�sys�version�platform�getattr�consoleZinteract)rr,rrr�runFs"��
�zREPLThread.runN)r$r%r&r6rrrrr(Dsr(�__main__�asyncio>�__builtins__�__spec__r$�__file__�
__loader__�__package__FT)#r	r8rZconcurrent.futuresrrr1Z	threadingrr-�rZInteractiveConsolerZThreadr(r$Znew_event_loopr
Zset_event_loopZrepl_locals�keyrr5rr�readline�ImportErrorZrepl_threadZdaemon�startZrun_foreverrZdoneZcancelrrrr�<module>sF6



PK [ft�,S^S^*__pycache__/proactor_events.cpython-38.pycnu�[���U

e5d<}�@sTdZdZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
ddl	mZddl	mZddl	m
Z
dd	l	mZdd
l	mZddl	mZddl	mZdd
lmZdd�ZGdd�dejej�ZGdd�deej�ZGdd�deej�ZGdd�de�ZGdd�de�ZGdd�deeej�ZGdd�deeej�Z Gdd�de
j!�Z"dS) z�Event loop using a proactor and related classes.

A proactor is a "notify-on-completion" multiplexer.  Currently a
proactor is only implemented on Windows with IOCP.
)�BaseProactorEventLoop�N�)�base_events)�	constants)�futures)�
exceptions)�	protocols)�sslproto)�
transports)�trsock)�loggercCs�t�|�|jd<z|��|jd<Wn0tjk
rR|j��rNtj	d|dd�YnXd|jkr�z|�
�|jd<Wn tjk
r�d|jd<YnXdS)N�socketZsocknamezgetsockname() failed on %rT��exc_info�peername)r�TransportSocket�_extraZgetsocknamer
�error�_loop�	get_debugr�warningZgetpeername)�	transport�sock�r�//usr/lib64/python3.8/asyncio/proactor_events.py�_set_socket_extras
�
rcs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
ejfdd�Z
ddd�Zdd�Zdd�Zdd�Z�ZS)�_ProactorBasePipeTransportz*Base class for pipe and socket transports.Ncs�t��||�|�|�||_|�|�||_d|_d|_d|_d|_	d|_
d|_d|_|jdk	rl|j�
�|j�|jj|�|dk	r�|j�tj|d�dS)NrF)�super�__init__�
_set_extra�_sock�set_protocol�_server�_buffer�	_read_fut�
_write_fut�_pending_write�
_conn_lost�_closing�_eof_writtenZ_attachr�	call_soon�	_protocolZconnection_maderZ_set_result_unless_cancelled��self�loopr�protocol�waiter�extra�server��	__class__rrr2s(




�z#_ProactorBasePipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|jdk	rP|�d|j�����|jdk	rl|�d|j���|jdk	r�|�d|j���|jr�|�dt	|j����|j
r�|�d�d�d	�|��S)
N�closed�closingzfd=zread=zwrite=zwrite_bufsize=zEOF writtenz<{}>� )
r4�__name__r �appendr(�filenor$r%r#�lenr)�format�join)r-�inforrr�__repr__Hs 






z#_ProactorBasePipeTransport.__repr__cCs||jd<dS)N�pipe)r�r-rrrrrZsz%_ProactorBasePipeTransport._set_extracCs
||_dS�N�r+)r-r/rrrr!]sz'_ProactorBasePipeTransport.set_protocolcCs|jSrBrC�r-rrr�get_protocol`sz'_ProactorBasePipeTransport.get_protocolcCs|jSrB)r(rDrrr�
is_closingcsz%_ProactorBasePipeTransport.is_closingcCs\|jr
dSd|_|jd7_|js>|jdkr>|j�|jd�|jdk	rX|j��d|_dS)NTr)	r(r'r#r%rr*�_call_connection_lostr$�cancelrDrrr�closefs

z _ProactorBasePipeTransport.closecCs*|jdk	r&|d|��t|d�|��dS)Nzunclosed transport )�source)r �ResourceWarningrI)r-Z_warnrrr�__del__qs
z"_ProactorBasePipeTransport.__del__�Fatal error on pipe transportc	CsVzDt|t�r*|j��rBtjd||dd�n|j�||||jd��W5|�|�XdS)Nz%r: %sTr)�message�	exceptionrr/)	�_force_close�
isinstance�OSErrorrrr�debug�call_exception_handlerr+)r-�excrNrrr�_fatal_errorvs

�z'_ProactorBasePipeTransport._fatal_errorcCs�|jdk	r6|j��s6|dkr*|j�d�n|j�|�|jr@dSd|_|jd7_|jrj|j��d|_|jr�|j��d|_d|_	d|_
|j�|j
|�dS)NTrr)�
_empty_waiter�done�
set_resultZ
set_exceptionr(r'r%rHr$r&r#rr*rG)r-rUrrrrP�s"

z'_ProactorBasePipeTransport._force_closec	Cs^z|j�	|�W5t|jd�r,|j�tj�|j��d|_|j}|dk	rX|��d|_XdS)N�shutdown)
�hasattrr rZr
Z	SHUT_RDWRrIr"Z_detachr+Zconnection_lost)r-rUr2rrrrG�s
z0_ProactorBasePipeTransport._call_connection_lostcCs"|j}|jdk	r|t|j�7}|SrB)r&r#r;)r-�sizerrr�get_write_buffer_size�s
z0_ProactorBasePipeTransport.get_write_buffer_size)NNN)rM)r8�
__module__�__qualname__�__doc__rr?rr!rErFrI�warnings�warnrLrVrPrGr]�
__classcell__rrr3rr.s �
rcsTeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	ddd�Z
�ZS)�_ProactorReadPipeTransportzTransport for read pipes.Ncs:d|_d|_t��||||||�|j�|j�d|_dS)NTF)�
_pending_data�_pausedrrrr*�
_loop_readingr,r3rrr�s
z#_ProactorReadPipeTransport.__init__cCs|jo|jSrB)rfr(rDrrr�
is_reading�sz%_ProactorReadPipeTransport.is_readingcCs0|js|jrdSd|_|j��r,t�d|�dS)NTz%r pauses reading)r(rfrrrrSrDrrr�
pause_reading�s

z(_ProactorReadPipeTransport.pause_readingcCsn|js|jsdSd|_|jdkr0|j�|jd�|j}d|_|dk	rT|j�|j|�|j��rjt	�
d|�dS)NFz%r resumes reading)r(rfr$rr*rgre�_data_receivedrrrS�r-�datarrr�resume_reading�s

z)_ProactorReadPipeTransport.resume_readingc
Cs�|j��rt�d|�z|j��}WnLttfk
r>�Yn4tk
rp}z|�	|d�WY�dSd}~XYnX|s~|�
�dS)Nz%r received EOFz1Fatal error: protocol.eof_received() call failed.)rrrrSr+Zeof_received�
SystemExit�KeyboardInterrupt�
BaseExceptionrVrI)r-Z	keep_openrUrrr�
_eof_received�s
�z(_ProactorReadPipeTransport._eof_receivedc
Cs�|jr|jdkst�||_dS|s.|��dSt|jtj�r�zt�|j|�Wq�t	t
fk
rh�Yq�tk
r�}z|�|d�WY�dSd}~XYq�Xn|j�
|�dS)Nz3Fatal error: protocol.buffer_updated() call failed.)rfre�AssertionErrorrqrQr+rZBufferedProtocolZ_feed_data_to_buffered_protornrorprVZ
data_received)r-rlrUrrrrj�s$�z)_ProactorReadPipeTransport._data_receivedc
Cs�d}�zrz�|dk	rP|j|ks0|jdkr,|js0t�d|_|��rH|��}n|��|jrfd}WW��dS|dkrzWW��dS|js�|jj	�
|jd�|_Wn�tk
r�}z0|js�|�
|d�n|j��r�tjddd�W5d}~XYn�tk
�r}z|�|�W5d}~XYnftk
�r>}z|�
|d�W5d}~XYn8tjk
�r^|j�sZ�YnX|j�sv|j�|j�W5|dk	�r�|�|�XdS)N�i�z"Fatal read error on pipe transportz*Read error on pipe transport while closingTr)rjr$r(rrrX�resultrHrfr�	_proactor�recvr �ConnectionAbortedErrorrVrrrS�ConnectionResetErrorrPrRr�CancelledError�add_done_callbackrg)r-�futrlrUrrrrgsF�

�
z(_ProactorReadPipeTransport._loop_reading)NNN)N)r8r^r_r`rrhrirmrqrjrgrcrrr3rrd�s�	rdcs^eZdZdZdZ�fdd�Zdd�Zddd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Z�Z
S)�_ProactorBaseWritePipeTransportzTransport for write pipes.Tcst�j||�d|_dSrB)rrrW�r-�args�kwr3rrrGsz(_ProactorBaseWritePipeTransport.__init__cCs�t|tttf�s$tdt|�j����|jr2td��|j	dk	rDtd��|sLdS|j
rz|j
tjkrht
�d�|j
d7_
dS|jdkr�|jdks�t�|jt|�d�n.|js�t|�|_|��n|j�|�|��dS)Nz/data argument must be a bytes-like object, not zwrite_eof() already calledz(unable to write; sendfile is in progresszsocket.send() raised exception.r)rl)rQ�bytes�	bytearray�
memoryview�	TypeError�typer8r)�RuntimeErrorrWr'r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESrrr%r#rr�
_loop_writing�_maybe_pause_protocol�extendrkrrr�writeKs.�




z%_ProactorBaseWritePipeTransport.writeNc
Csx�z|dk	r"|jdkr"|jr"WdS||jks0t�d|_d|_|rH|��|dkr\|j}d|_|s�|jrv|j�|jd�|j	r�|j
�tj
�|��n\|jj�|j
|�|_|j��s�|jdks�t�t|�|_|j�|j�|��n|j�|j�|jdk	�r|jdk�r|j�d�Wn\tk
�rD}z|�|�W5d}~XYn0tk
�rr}z|�|d�W5d}~XYnXdS)Nrz#Fatal write error on pipe transport)r%r(rrr&rtr#rr*rGr)r rZr
�SHUT_WR�_maybe_resume_protocolru�sendrXr;rzr�r�rWrYrxrPrRrV)r-�frlrUrrrr�qs<



z-_ProactorBaseWritePipeTransport._loop_writingcCsdS�NTrrDrrr�
can_write_eof�sz-_ProactorBaseWritePipeTransport.can_write_eofcCs|��dSrB)rIrDrrr�	write_eof�sz)_ProactorBaseWritePipeTransport.write_eofcCs|�d�dSrB�rPrDrrr�abort�sz%_ProactorBaseWritePipeTransport.abortcCs:|jdk	rtd��|j��|_|jdkr4|j�d�|jS)NzEmpty waiter is already set)rWr�rZ
create_futurer%rYrDrrr�_make_empty_waiter�s

z2_ProactorBaseWritePipeTransport._make_empty_waitercCs
d|_dSrB)rWrDrrr�_reset_empty_waiter�sz3_ProactorBaseWritePipeTransport._reset_empty_waiter)NN)r8r^r_r`Z_start_tls_compatiblerr�r�r�r�r�r�r�rcrrr3rr|As&
)r|cs$eZdZ�fdd�Zdd�Z�ZS)�_ProactorWritePipeTransportcs4t�j||�|jj�|jd�|_|j�|j�dS)N�)	rrrrurvr r$rz�_pipe_closedr}r3rrr�sz$_ProactorWritePipeTransport.__init__cCsv|��rdS|��dkst�|jr4|jdks0t�dS||jksLt||jf��d|_|jdk	rj|�t��n|��dS)Nrs)	Z	cancelledrtrrr(r$r%rP�BrokenPipeErrorrI)r-r{rrrr��s
z(_ProactorWritePipeTransport._pipe_closed)r8r^r_rr�rcrrr3rr��sr�csXeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zddd�Zdd
d�Z	ddd�Z
�ZS)�_ProactorDatagramTransportiNcs>||_d|_t�j|||||d�t��|_|j�|j	�dS)N)r0r1)
�_addressrWrr�collections�dequer#rr*rg)r-r.rr/�addressr0r1r3rrr�s

z#_ProactorDatagramTransport.__init__cCst||�dSrB�rrArrrr�sz%_ProactorDatagramTransport._set_extracCstdd�|jD��S)Ncss|]\}}t|�VqdSrB)r;)�.0rl�_rrr�	<genexpr>�szC_ProactorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr#rDrrrr]�sz0_ProactorDatagramTransport.get_write_buffer_sizecCs|�d�dSrBr�rDrrrr��sz _ProactorDatagramTransport.abortcCs�t|tttf�stdt|���|s&dS|jdk	rN|d|jfkrNtd|j����|jr�|jr�|jt	j
krpt�d�|jd7_dS|j
�t|�|f�|jdkr�|��|��dS)Nz,data argument must be bytes-like object (%r)z!Invalid address: must be None or z!socket.sendto() raised exception.r)rQr�r�r�r�r�r��
ValueErrorr'rr�rrr#r9r%r�r�)r-rl�addrrrr�sendto�s&�
�

z!_ProactorDatagramTransport.sendtoc
Csz�|jrWdS||jkst�d|_|r.|��|jr@|jr\|jr\|jrV|j�|j	d�WdS|j�
�\}}|jdk	r�|jj�|j
|�|_n|jjj|j
||d�|_WnZtk
r�}z|j�|�W5d}~XYnDtk
r�}z|�|d�W5d}~XYnX|j�|j�|��dS)N)r�z'Fatal write error on datagram transport)r'r%rrrtr#r�r(rr*rG�popleftrur�r r�rRr+�error_received�	ExceptionrVrzr�r�)r-r{rlr�rUrrrr��s4
��z(_ProactorDatagramTransport._loop_writingc
CsVd}�z4z�|jrWW��$dS|j|ks:|jdkr6|js:t�d|_|dk	r�|��}|jrdd}WW��dS|jdk	r|||j}}n|\}}|jr�WW��dS|jdk	r�|jj	�
|j|j�|_n|jj	�
|j|j�|_WnNtk
r�}z|j�|�W5d}~XYn<tjk
�r|j�s�YnX|jdk	�r8|j�|j�W5|�rP|j�||�XdSrB)r+Zdatagram_receivedr'r$r(rrrtr�rrurvr �max_sizeZrecvfromrRr�rryrzrg)r-r{rlr��resrUrrrrgsD�



��
z(_ProactorDatagramTransport._loop_reading)NNN)N)N)N)r8r^r_r�rrr]r�r�r�rgrcrrr3rr��s�

!r�c@s eZdZdZdd�Zdd�ZdS)�_ProactorDuplexPipeTransportzTransport for duplex pipes.cCsdS)NFrrDrrrr�Jsz*_ProactorDuplexPipeTransport.can_write_eofcCst�dSrB)�NotImplementedErrorrDrrrr�Msz&_ProactorDuplexPipeTransport.write_eofN)r8r^r_r`r�r�rrrrr�Esr�csBeZdZdZejjZd�fdd�	Zdd�Z	dd�Z
d	d
�Z�ZS)�_ProactorSocketTransportz Transport for connected sockets.Ncs$t��||||||�t�|�dSrB)rrrZ_set_nodelayr,r3rrrXsz!_ProactorSocketTransport.__init__cCst||�dSrBr�rArrrr]sz#_ProactorSocketTransport._set_extracCsdSr�rrDrrrr�`sz&_ProactorSocketTransport.can_write_eofcCs2|js|jrdSd|_|jdkr.|j�tj�dSr�)r(r)r%r rZr
r�rDrrrr�cs

z"_ProactorSocketTransport.write_eof)NNN)
r8r^r_r`rZ
_SendfileModeZ
TRY_NATIVEZ_sendfile_compatiblerrr�r�rcrrr3rr�Qs�r�cs�eZdZ�fdd�Zd3dd�Zd4dddddd�dd	�Zd5d
d�Zd6dd
�Zd7dd�Zd8dd�Z	�fdd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd9d&d'�Zd(d)�Zd:d+d,�Zd-d.�Zd/d0�Zd1d2�Z�ZS);rcsht���t�d|jj�||_||_d|_i|_	|�
|�|��t�
�t��krdt�|j���dS)NzUsing proactor: %s)rrrrSr4r8ru�	_selector�_self_reading_future�_accept_futuresZset_loop�_make_self_pipe�	threading�current_thread�main_thread�signal�
set_wakeup_fd�_csockr:)r-Zproactorr3rrrms

zBaseProactorEventLoop.__init__NcCst||||||�SrB)r�)r-rr/r0r1r2rrr�_make_socket_transportzs
�z,BaseProactorEventLoop._make_socket_transportF)�server_side�server_hostnamer1r2�ssl_handshake_timeoutc	Cs0tj|||||||	d�}
t|||
||d�|
jS)N)r��r1r2)r	ZSSLProtocolr�Z_app_transport)r-Zrawsockr/�
sslcontextr0r�r�r1r2r�Zssl_protocolrrr�_make_ssl_transports��z)BaseProactorEventLoop._make_ssl_transportcCst||||||�SrB)r�)r-rr/r�r0r1rrr�_make_datagram_transport�s
�z.BaseProactorEventLoop._make_datagram_transportcCst|||||�SrB)r��r-rr/r0r1rrr�_make_duplex_pipe_transport�s�z1BaseProactorEventLoop._make_duplex_pipe_transportcCst|||||�SrB)rdr�rrr�_make_read_pipe_transport�sz/BaseProactorEventLoop._make_read_pipe_transportcCst|||||�SrB)r�r�rrr�_make_write_pipe_transport�s�z0BaseProactorEventLoop._make_write_pipe_transportcsj|��rtd��|��rdSt��t��kr6t�d�|��|�	�|j
��d|_
d|_t
���dS)Nz!Cannot close a running event loop���)Z
is_runningr��	is_closedr�r�r�r�r��_stop_accept_futures�_close_self_piperurIr�rrDr3rrrI�s

zBaseProactorEventLoop.closec�s|j�||�IdHSrB)rurv)r-r�nrrr�	sock_recv�szBaseProactorEventLoop.sock_recvc�s|j�||�IdHSrB)ruZ	recv_into)r-rZbufrrr�sock_recv_into�sz$BaseProactorEventLoop.sock_recv_intoc�s|j�||�IdHSrB)rur�)r-rrlrrr�sock_sendall�sz"BaseProactorEventLoop.sock_sendallc�s|j�||�IdHSrB)ruZconnect)r-rr�rrr�sock_connect�sz"BaseProactorEventLoop.sock_connectc�s|j�|�IdHSrB)ru�acceptrArrr�sock_accept�sz!BaseProactorEventLoop.sock_acceptc
�s(z|��}Wn2ttjfk
r>}zt�d��W5d}~XYnXzt�|�j}Wn,t	k
r|}zt�d��W5d}~XYnX|r�|n|}|s�dSt
|d�}|r�t
|||�n|}	t
||�}d}
zLt
|	||�}|dkr�|
W�0S|j�
||||�IdH||7}|
|7}
q�W5|
dk�r"|�|�XdS)Nznot a regular filerl��)r:�AttributeError�io�UnsupportedOperationrZSendfileNotAvailableError�os�fstat�st_sizerR�min�seekru�sendfile)r-r�file�offset�countr:�errZfsizeZ	blocksizeZend_posZ
total_sentrrr�_sock_sendfile_native�s0


z+BaseProactorEventLoop._sock_sendfile_nativec�sZ|��}|��|��IdHz |j|j|||dd�IdHW�S|��|rT|��XdS)NF)Zfallback)rhrir�r�rmZ
sock_sendfiler )r-Ztranspr�r�r�rmrrr�_sendfile_native�s�z&BaseProactorEventLoop._sendfile_nativecCsL|jdk	r|j��d|_|j��d|_|j��d|_|jd8_dS)Nr)r�rH�_ssockrIr��
_internal_fdsrDrrrr��s



z&BaseProactorEventLoop._close_self_pipecCs:t��\|_|_|j�d�|j�d�|jd7_dS)NFr)r
Z
socketpairr�r�Zsetblockingr�rDrrrr��sz%BaseProactorEventLoop._make_self_pipec
Cs�z4|dk	r|��|j|k	r"WdS|j�|jd�}Wnbtjk
rLYdSttfk
rd�YnFt	k
r�}z|�
d||d��W5d}~XYnX||_|�|j�dS)Niz.Error on reading from the event loop self pipe)rNrOr.)
rtr�rurvr�rryrnrorprTrz�_loop_self_reading)r-r�rUrrrr��s$
�z(BaseProactorEventLoop._loop_self_readingcCsN|j}|dkrdSz|�d�Wn(tk
rH|jrDtjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketTr)r�r�rR�_debugrrS)r-Zcsockrrr�_write_to_selfs�z$BaseProactorEventLoop._write_to_self�dcs(d�������fdd�	�����dS)Nc
s,z�|dk	rn|��\}}�jr,t�d�||���}�dk	rX�j||�dd|i��d�n�j||d|i�d����r|WdS�j���}Wn�t	k
r�}zH��
�dkrʈ�d|t�
��d�����n�jr�tjd	�dd
�W5d}~XYn8tjk
�r���YnX|�j��
�<|���dS)Nz#%r got a new connection from %r: %rTr)r�r1r2r�r�r�zAccept failed on a socket)rNrOr
zAccept failed on socket %rr)rtr�rrSr�r�r�rur�rRr:rTrrrIrryr�rz)r�Zconnr�r/rU�r.�protocol_factoryr-r2rr�r�rrr./s\����
�z2BaseProactorEventLoop._start_serving.<locals>.loop)N)r*)r-r�rr�r2Zbacklogr�rr�r�_start_serving+s%z$BaseProactorEventLoop._start_servingcCsdSrBr)r-Z
event_listrrr�_process_eventsVsz%BaseProactorEventLoop._process_eventscCs&|j��D]}|��q
|j��dSrB)r��valuesrH�clear)r-�futurerrrr�Zs
z*BaseProactorEventLoop._stop_accept_futurescCs6|j�|��d�}|r|��|j�|�|��dSrB)r��popr:rHru�
_stop_servingrI)r-rr�rrrr�_s
z#BaseProactorEventLoop._stop_serving)NNN)N)NNN)NN)NN)NN)N)NNr�N)r8r^r_rr�r�r�r�r�r�rIr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rcrrr3rrks\
�
���
�
�
�


�
+r)#r`�__all__r�r�r
rar�r�r��rrrrrr	r
r�logrrZ_FlowControlMixinZ
BaseTransportrZ
ReadTransportrdZWriteTransportr|r�r�Z	Transportr�r�Z
BaseEventLooprrrrr�<module>sR���n��PK [�P�% % '__pycache__/trsock.cpython-38.opt-2.pycnu�[���U

e5d��@s"ddlZddlZGdd�d�ZdS)�Nc@s�eZdZdZejd�dd�Zdd�Zedd��Zed	d
��Z	edd��Z
d
d�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Z d9d:�Z!d;d<�Z"d=d>�Z#d?d@�Z$dAdB�Z%dCdD�Z&dEdF�Z'dGdH�Z(dIdJ�Z)dKdL�Z*dMdN�Z+dOdP�Z,dQdR�Z-dSdT�Z.dUdV�Z/dWdX�Z0dYdZ�Z1d[S)\�TransportSocket��_sock)�sockcCs
||_dS�Nr)�selfr�r�&/usr/lib64/python3.8/asyncio/trsock.py�__init__szTransportSocket.__init__cCstjd|�d�t|d�dS)NzUsing z� on sockets returned from get_extra_info('socket') will be prohibited in asyncio 3.9. Please report your use case to bugs.python.org.)�source)�warnings�warn�DeprecationWarning)rZwhatrrr	�_nas

�zTransportSocket._nacCs|jjSr)r�family�rrrr	rszTransportSocket.familycCs|jjSr)r�typerrrr	rszTransportSocket.typecCs|jjSr)r�protorrrr	r"szTransportSocket.protocCs�d|���d|j�d|j�d|j��}|��dkr�z|��}|rN|�d|��}Wntjk
rfYnXz|��}|r�|�d|��}Wntjk
r�YnX|�d�S)	Nz<asyncio.TransportSocket fd=z	, family=z, type=z, proto=���z, laddr=z, raddr=�>)�filenorrr�getsockname�socket�error�getpeername)r�sZladdrZraddrrrr	�__repr__&s $�zTransportSocket.__repr__cCstd��dS)Nz/Cannot serialize asyncio.TransportSocket object)�	TypeErrorrrrr	�__getstate__=szTransportSocket.__getstate__cCs
|j��Sr)rrrrrr	r@szTransportSocket.filenocCs
|j��Sr)r�duprrrr	rCszTransportSocket.dupcCs
|j��Sr)r�get_inheritablerrrr	r FszTransportSocket.get_inheritablecCs|j�|�dSr)r�shutdown)rZhowrrr	r!IszTransportSocket.shutdowncOs|jj||�Sr)r�
getsockopt�r�args�kwargsrrr	r"NszTransportSocket.getsockoptcOs|jj||�dSr)r�
setsockoptr#rrr	r&QszTransportSocket.setsockoptcCs
|j��Sr)rrrrrr	rTszTransportSocket.getpeernamecCs
|j��Sr)rrrrrr	rWszTransportSocket.getsocknamecCs
|j��Sr)r�
getsockbynamerrrr	r'ZszTransportSocket.getsockbynamecCs|�d�|j��S)Nzaccept() method)rr�acceptrrrr	r(]s
zTransportSocket.acceptcOs|�d�|jj||�S)Nzconnect() method)rr�connectr#rrr	r)as
zTransportSocket.connectcOs|�d�|jj||�S)Nzconnect_ex() method)rr�
connect_exr#rrr	r*es
zTransportSocket.connect_excOs|�d�|jj||�S)Nz
bind() method)rr�bindr#rrr	r+is
zTransportSocket.bindcOs|�d�|jj||�S)Nzioctl() method)rr�ioctlr#rrr	r,ms
zTransportSocket.ioctlcOs|�d�|jj||�S)Nzlisten() method)rr�listenr#rrr	r-qs
zTransportSocket.listencCs|�d�|j��S)Nzmakefile() method)rr�makefilerrrr	r.us
zTransportSocket.makefilecOs|�d�|jj||�S)Nzsendfile() method)rr�sendfiler#rrr	r/ys
zTransportSocket.sendfilecCs|�d�|j��S)Nzclose() method)rr�closerrrr	r0}s
zTransportSocket.closecCs|�d�|j��S)Nzdetach() method)rr�detachrrrr	r1�s
zTransportSocket.detachcOs|�d�|jj||�S)Nzsendmsg_afalg() method)rr�
sendmsg_afalgr#rrr	r2�s
zTransportSocket.sendmsg_afalgcOs|�d�|jj||�S)Nzsendmsg() method)rr�sendmsgr#rrr	r3�s
zTransportSocket.sendmsgcOs|�d�|jj||�S)Nzsendto() method)rr�sendtor#rrr	r4�s
zTransportSocket.sendtocOs|�d�|jj||�S)Nz
send() method)rr�sendr#rrr	r5�s
zTransportSocket.sendcOs|�d�|jj||�S)Nzsendall() method)rr�sendallr#rrr	r6�s
zTransportSocket.sendallcOs|�d�|jj||�S)Nzset_inheritable() method)rr�set_inheritabler#rrr	r7�s
zTransportSocket.set_inheritablecCs|�d�|j�|�S)Nzshare() method)rr�share)rZ
process_idrrr	r8�s
zTransportSocket.sharecOs|�d�|jj||�S)Nzrecv_into() method)rr�	recv_intor#rrr	r9�s
zTransportSocket.recv_intocOs|�d�|jj||�S)Nzrecvfrom_into() method)rr�
recvfrom_intor#rrr	r:�s
zTransportSocket.recvfrom_intocOs|�d�|jj||�S)Nzrecvmsg_into() method)rr�recvmsg_intor#rrr	r;�s
zTransportSocket.recvmsg_intocOs|�d�|jj||�S)Nzrecvmsg() method)rr�recvmsgr#rrr	r<�s
zTransportSocket.recvmsgcOs|�d�|jj||�S)Nzrecvfrom() method)rr�recvfromr#rrr	r=�s
zTransportSocket.recvfromcOs|�d�|jj||�S)Nz
recv() method)rr�recvr#rrr	r>�s
zTransportSocket.recvcCs|dkrdStd��dS)Nrz<settimeout(): only 0 timeout is allowed on transport sockets��
ValueError)r�valuerrr	�
settimeout�s
�zTransportSocket.settimeoutcCsdS)Nrrrrrr	�
gettimeout�szTransportSocket.gettimeoutcCs|sdStd��dS)Nz3setblocking(): transport sockets cannot be blockingr?)r�flagrrr	�setblocking�s
�zTransportSocket.setblockingcCs|�d�|j��S�Nzcontext manager protocol)rr�	__enter__rrrr	rG�s
zTransportSocket.__enter__cGs|�d�|jj|�SrF)rr�__exit__)r�errrrr	rH�s
zTransportSocket.__exit__N)2�__name__�
__module__�__qualname__�	__slots__rr
r�propertyrrrrrrrr r!r"r&rrr'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>rBrCrErGrHrrrr	rs`	


r)rrrrrrr	�<module>sPK [k*�	�	%__pycache__/exceptions.cpython-38.pycnu�[���U

e5da�@sldZdZGdd�de�ZGdd�de�ZGdd�de�ZGdd	�d	e�ZGd
d�de	�Z
Gdd
�d
e�ZdS)zasyncio exceptions.)�CancelledError�InvalidStateError�TimeoutError�IncompleteReadError�LimitOverrunError�SendfileNotAvailableErrorc@seZdZdZdS)rz!The Future or Task was cancelled.N��__name__�
__module__�__qualname__�__doc__�rr�*/usr/lib64/python3.8/asyncio/exceptions.pyr	src@seZdZdZdS)rz*The operation exceeded the given deadline.Nrrrrr
r
src@seZdZdZdS)rz+The operation is not allowed in this state.Nrrrrr
rsrc@seZdZdZdS)rz~Sendfile syscall is not available.

    Raised if OS does not support sendfile syscall for given socket or
    file type.
    Nrrrrr
rsrcs(eZdZdZ�fdd�Zdd�Z�ZS)rz�
    Incomplete read error. Attributes:

    - partial: read bytes string before the end of stream was reached
    - expected: total number of expected bytes (or None if unknown)
    cs@|dkrdnt|�}t��t|��d|�d��||_||_dS)NZ	undefinedz bytes read on a total of z expected bytes)�repr�super�__init__�len�partial�expected)�selfrrZ
r_expected��	__class__rr
r$szIncompleteReadError.__init__cCst|�|j|jffS�N)�typerr�rrrr
�
__reduce__+szIncompleteReadError.__reduce__�rr	r
rrr�
__classcell__rrrr
rsrcs(eZdZdZ�fdd�Zdd�Z�ZS)rz�Reached the buffer limit while looking for a separator.

    Attributes:
    - consumed: total number of to be consumed bytes.
    cst��|�||_dSr)rr�consumed)r�messagerrrr
r5szLimitOverrunError.__init__cCst|�|jd|jffS)N�)r�argsrrrrr
r9szLimitOverrunError.__reduce__rrrrr
r/srN)r�__all__�
BaseExceptionr�	Exceptionrr�RuntimeErrorr�EOFErrorrrrrrr
�<module>sPK [Yy�L

__main__.pynu�[���import ast
import asyncio
import code
import concurrent.futures
import inspect
import sys
import threading
import types
import warnings

from . import futures


class AsyncIOInteractiveConsole(code.InteractiveConsole):

    def __init__(self, locals, loop):
        super().__init__(locals)
        self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

        self.loop = loop

    def runcode(self, code):
        future = concurrent.futures.Future()

        def callback():
            global repl_future
            global repl_future_interrupted

            repl_future = None
            repl_future_interrupted = False

            func = types.FunctionType(code, self.locals)
            try:
                coro = func()
            except SystemExit:
                raise
            except KeyboardInterrupt as ex:
                repl_future_interrupted = True
                future.set_exception(ex)
                return
            except BaseException as ex:
                future.set_exception(ex)
                return

            if not inspect.iscoroutine(coro):
                future.set_result(coro)
                return

            try:
                repl_future = self.loop.create_task(coro)
                futures._chain_future(repl_future, future)
            except BaseException as exc:
                future.set_exception(exc)

        loop.call_soon_threadsafe(callback)

        try:
            return future.result()
        except SystemExit:
            raise
        except BaseException:
            if repl_future_interrupted:
                self.write("\nKeyboardInterrupt\n")
            else:
                self.showtraceback()


class REPLThread(threading.Thread):

    def run(self):
        try:
            banner = (
                f'asyncio REPL {sys.version} on {sys.platform}\n'
                f'Use "await" directly instead of "asyncio.run()".\n'
                f'Type "help", "copyright", "credits" or "license" '
                f'for more information.\n'
                f'{getattr(sys, "ps1", ">>> ")}import asyncio'
            )

            console.interact(
                banner=banner,
                exitmsg='exiting asyncio REPL...')
        finally:
            warnings.filterwarnings(
                'ignore',
                message=r'^coroutine .* was never awaited$',
                category=RuntimeWarning)

            loop.call_soon_threadsafe(loop.stop)


if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    repl_locals = {'asyncio': asyncio}
    for key in {'__name__', '__package__',
                '__loader__', '__spec__',
                '__builtins__', '__file__'}:
        repl_locals[key] = locals()[key]

    console = AsyncIOInteractiveConsole(repl_locals, loop)

    repl_future = None
    repl_future_interrupted = False

    try:
        import readline  # NoQA
    except ImportError:
        pass

    repl_thread = REPLThread()
    repl_thread.daemon = True
    repl_thread.start()

    while True:
        try:
            loop.run_forever()
        except KeyboardInterrupt:
            if repl_future and not repl_future.done():
                repl_future.cancel()
                repl_future_interrupted = True
            continue
        else:
            break
PK [ّ>hhstaggered.pynu�[���"""Support for running coroutines in parallel with staggered start times."""

__all__ = 'staggered_race',

import contextlib
import typing

from . import events
from . import exceptions as exceptions_mod
from . import locks
from . import tasks


async def staggered_race(
        coro_fns: typing.Iterable[typing.Callable[[], typing.Awaitable]],
        delay: typing.Optional[float],
        *,
        loop: events.AbstractEventLoop = None,
) -> typing.Tuple[
    typing.Any,
    typing.Optional[int],
    typing.List[typing.Optional[Exception]]
]:
    """Run coroutines with staggered start times and take the first to finish.

    This method takes an iterable of coroutine functions. The first one is
    started immediately. From then on, whenever the immediately preceding one
    fails (raises an exception), or when *delay* seconds has passed, the next
    coroutine is started. This continues until one of the coroutines complete
    successfully, in which case all others are cancelled, or until all
    coroutines fail.

    The coroutines provided should be well-behaved in the following way:

    * They should only ``return`` if completed successfully.

    * They should always raise an exception if they did not complete
      successfully. In particular, if they handle cancellation, they should
      probably reraise, like this::

        try:
            # do work
        except asyncio.CancelledError:
            # undo partially completed work
            raise

    Args:
        coro_fns: an iterable of coroutine functions, i.e. callables that
            return a coroutine object when called. Use ``functools.partial`` or
            lambdas to pass arguments.

        delay: amount of time, in seconds, between starting coroutines. If
            ``None``, the coroutines will run sequentially.

        loop: the event loop to use.

    Returns:
        tuple *(winner_result, winner_index, exceptions)* where

        - *winner_result*: the result of the winning coroutine, or ``None``
          if no coroutines won.

        - *winner_index*: the index of the winning coroutine in
          ``coro_fns``, or ``None`` if no coroutines won. If the winning
          coroutine may return None on success, *winner_index* can be used
          to definitively determine whether any coroutine won.

        - *exceptions*: list of exceptions returned by the coroutines.
          ``len(exceptions)`` is equal to the number of coroutines actually
          started, and the order is the same as in ``coro_fns``. The winning
          coroutine's entry is ``None``.

    """
    # TODO: when we have aiter() and anext(), allow async iterables in coro_fns.
    loop = loop or events.get_running_loop()
    enum_coro_fns = enumerate(coro_fns)
    winner_result = None
    winner_index = None
    exceptions = []
    running_tasks = []

    async def run_one_coro(
            previous_failed: typing.Optional[locks.Event]) -> None:
        # Wait for the previous task to finish, or for delay seconds
        if previous_failed is not None:
            with contextlib.suppress(exceptions_mod.TimeoutError):
                # Use asyncio.wait_for() instead of asyncio.wait() here, so
                # that if we get cancelled at this point, Event.wait() is also
                # cancelled, otherwise there will be a "Task destroyed but it is
                # pending" later.
                await tasks.wait_for(previous_failed.wait(), delay)
        # Get the next coroutine to run
        try:
            this_index, coro_fn = next(enum_coro_fns)
        except StopIteration:
            return
        # Start task that will run the next coroutine
        this_failed = locks.Event()
        next_task = loop.create_task(run_one_coro(this_failed))
        running_tasks.append(next_task)
        assert len(running_tasks) == this_index + 2
        # Prepare place to put this coroutine's exceptions if not won
        exceptions.append(None)
        assert len(exceptions) == this_index + 1

        try:
            result = await coro_fn()
        except (SystemExit, KeyboardInterrupt):
            raise
        except BaseException as e:
            exceptions[this_index] = e
            this_failed.set()  # Kickstart the next coroutine
        else:
            # Store winner's results
            nonlocal winner_index, winner_result
            assert winner_index is None
            winner_index = this_index
            winner_result = result
            # Cancel all other tasks. We take care to not cancel the current
            # task as well. If we do so, then since there is no `await` after
            # here and CancelledError are usually thrown at one, we will
            # encounter a curious corner case where the current task will end
            # up as done() == True, cancelled() == False, exception() ==
            # asyncio.CancelledError. This behavior is specified in
            # https://bugs.python.org/issue30048
            for i, t in enumerate(running_tasks):
                if i != this_index:
                    t.cancel()

    first_task = loop.create_task(run_one_coro(None))
    running_tasks.append(first_task)
    try:
        # Wait for a growing list of tasks to all finish: poor man's version of
        # curio's TaskGroup or trio's nursery
        done_count = 0
        while done_count != len(running_tasks):
            done, _ = await tasks.wait(running_tasks)
            done_count = len(done)
            # If run_one_coro raises an unhandled exception, it's probably a
            # programming error, and I want to see it.
            if __debug__:
                for d in done:
                    if d.done() and not d.cancelled() and d.exception():
                        raise d.exception()
        return winner_result, winner_index, exceptions
    finally:
        # Make sure no tasks are left running if we leave this function
        for t in running_tasks:
            t.cancel()
PK [���
��	trsock.pynu�[���import socket
import warnings


class TransportSocket:

    """A socket-like wrapper for exposing real transport sockets.

    These objects can be safely returned by APIs like
    `transport.get_extra_info('socket')`.  All potentially disruptive
    operations (like "socket.close()") are banned.
    """

    __slots__ = ('_sock',)

    def __init__(self, sock: socket.socket):
        self._sock = sock

    def _na(self, what):
        warnings.warn(
            f"Using {what} on sockets returned from get_extra_info('socket') "
            f"will be prohibited in asyncio 3.9. Please report your use case "
            f"to bugs.python.org.",
            DeprecationWarning, source=self)

    @property
    def family(self):
        return self._sock.family

    @property
    def type(self):
        return self._sock.type

    @property
    def proto(self):
        return self._sock.proto

    def __repr__(self):
        s = (
            f"<asyncio.TransportSocket fd={self.fileno()}, "
            f"family={self.family!s}, type={self.type!s}, "
            f"proto={self.proto}"
        )

        if self.fileno() != -1:
            try:
                laddr = self.getsockname()
                if laddr:
                    s = f"{s}, laddr={laddr}"
            except socket.error:
                pass
            try:
                raddr = self.getpeername()
                if raddr:
                    s = f"{s}, raddr={raddr}"
            except socket.error:
                pass

        return f"{s}>"

    def __getstate__(self):
        raise TypeError("Cannot serialize asyncio.TransportSocket object")

    def fileno(self):
        return self._sock.fileno()

    def dup(self):
        return self._sock.dup()

    def get_inheritable(self):
        return self._sock.get_inheritable()

    def shutdown(self, how):
        # asyncio doesn't currently provide a high-level transport API
        # to shutdown the connection.
        self._sock.shutdown(how)

    def getsockopt(self, *args, **kwargs):
        return self._sock.getsockopt(*args, **kwargs)

    def setsockopt(self, *args, **kwargs):
        self._sock.setsockopt(*args, **kwargs)

    def getpeername(self):
        return self._sock.getpeername()

    def getsockname(self):
        return self._sock.getsockname()

    def getsockbyname(self):
        return self._sock.getsockbyname()

    def accept(self):
        self._na('accept() method')
        return self._sock.accept()

    def connect(self, *args, **kwargs):
        self._na('connect() method')
        return self._sock.connect(*args, **kwargs)

    def connect_ex(self, *args, **kwargs):
        self._na('connect_ex() method')
        return self._sock.connect_ex(*args, **kwargs)

    def bind(self, *args, **kwargs):
        self._na('bind() method')
        return self._sock.bind(*args, **kwargs)

    def ioctl(self, *args, **kwargs):
        self._na('ioctl() method')
        return self._sock.ioctl(*args, **kwargs)

    def listen(self, *args, **kwargs):
        self._na('listen() method')
        return self._sock.listen(*args, **kwargs)

    def makefile(self):
        self._na('makefile() method')
        return self._sock.makefile()

    def sendfile(self, *args, **kwargs):
        self._na('sendfile() method')
        return self._sock.sendfile(*args, **kwargs)

    def close(self):
        self._na('close() method')
        return self._sock.close()

    def detach(self):
        self._na('detach() method')
        return self._sock.detach()

    def sendmsg_afalg(self, *args, **kwargs):
        self._na('sendmsg_afalg() method')
        return self._sock.sendmsg_afalg(*args, **kwargs)

    def sendmsg(self, *args, **kwargs):
        self._na('sendmsg() method')
        return self._sock.sendmsg(*args, **kwargs)

    def sendto(self, *args, **kwargs):
        self._na('sendto() method')
        return self._sock.sendto(*args, **kwargs)

    def send(self, *args, **kwargs):
        self._na('send() method')
        return self._sock.send(*args, **kwargs)

    def sendall(self, *args, **kwargs):
        self._na('sendall() method')
        return self._sock.sendall(*args, **kwargs)

    def set_inheritable(self, *args, **kwargs):
        self._na('set_inheritable() method')
        return self._sock.set_inheritable(*args, **kwargs)

    def share(self, process_id):
        self._na('share() method')
        return self._sock.share(process_id)

    def recv_into(self, *args, **kwargs):
        self._na('recv_into() method')
        return self._sock.recv_into(*args, **kwargs)

    def recvfrom_into(self, *args, **kwargs):
        self._na('recvfrom_into() method')
        return self._sock.recvfrom_into(*args, **kwargs)

    def recvmsg_into(self, *args, **kwargs):
        self._na('recvmsg_into() method')
        return self._sock.recvmsg_into(*args, **kwargs)

    def recvmsg(self, *args, **kwargs):
        self._na('recvmsg() method')
        return self._sock.recvmsg(*args, **kwargs)

    def recvfrom(self, *args, **kwargs):
        self._na('recvfrom() method')
        return self._sock.recvfrom(*args, **kwargs)

    def recv(self, *args, **kwargs):
        self._na('recv() method')
        return self._sock.recv(*args, **kwargs)

    def settimeout(self, value):
        if value == 0:
            return
        raise ValueError(
            'settimeout(): only 0 timeout is allowed on transport sockets')

    def gettimeout(self):
        return 0

    def setblocking(self, flag):
        if not flag:
            return
        raise ValueError(
            'setblocking(): transport sockets cannot be blocking')

    def __enter__(self):
        self._na('context manager protocol')
        return self._sock.__enter__()

    def __exit__(self, *err):
        self._na('context manager protocol')
        return self._sock.__exit__(*err)
PK[v��4f4f	events.pynu�[���PK[��,��(�(
mftransports.pynu�[���PK[#ƅ� h h
��streams.pynu�[���PK[�xD�JjJj��sslproto.pynu�[���PK[�4/�"�"bbase_subprocess.pynu�[���PK[l5Z
�:�:
L�test_utils.pynu�[���PK[�pCP	|�compat.pynu�[���PK[=�|C|C��locks.pynu�[���PK[V�CC���windows_utils.pynu�[���PK[l�������tasks.pynu�[���PK[�h���
G�subprocess.pynu�[���PK[(s8�xx�constants.pynu�[���PK[��yT�T���selector_events.pynu�[���PK[6߾ê�%R[__pycache__/subprocess.cpython-36.pycnu�[���PK[��)�)Qv__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK[@!�)ŘŘ,�y__pycache__/base_events.cpython-36.opt-1.pycnu�[���PK[P�\~zz,�__pycache__/base_events.cpython-36.opt-2.pycnu�[���PK[�f��I�I&L�__pycache__/tasks.cpython-36.opt-1.pycnu�[���PK[�X��"�"&��__pycache__/locks.cpython-36.opt-2.pycnu�[���PK[��o�5�5"��__pycache__/futures.cpython-36.pycnu�[���PK[�%�O�S�S)�0__pycache__/windows_events.cpython-36.pycnu�[���PK[�H�O�O/�__pycache__/windows_events.cpython-36.opt-2.pycnu�[���PK[6����D�D'�__pycache__/events.cpython-36.opt-2.pycnu�[���PK[�����'T__pycache__/compat.cpython-36.opt-1.pycnu�[���PK[�a��Z<Z<&�__pycache__/locks.cpython-36.opt-1.pycnu�[���PK[mʀ��L�L(9Z__pycache__/streams.cpython-36.opt-1.pycnu�[���PK[vԊ����&E�__pycache__/base_events.cpython-36.pycnu�[���PK[�����$NA__pycache__/log.cpython-36.opt-1.pycnu�[���PK[K�[[*~B__pycache__/protocols.cpython-36.opt-1.pycnu�[���PK["4���'3Z__pycache__/queues.cpython-36.opt-2.pycnu�[���PK[��yOyO#1p__pycache__/sslproto.cpython-36.pycnu�[���PK[��ь��*��__pycache__/constants.cpython-36.opt-1.pycnu�[���PK[Ea�#mm0T�__pycache__/selector_events.cpython-36.opt-2.pycnu�[���PK[��ь��$�.__pycache__/constants.cpython-36.pycnu�[���PK[3'~��-0__pycache__/base_futures.cpython-36.opt-2.pycnu�[���PK[Y����(7__pycache__/futures.cpython-36.opt-2.pycnu�[���PK[7�+��)EU__pycache__/__init__.cpython-36.opt-2.pycnu�[���PK[D��o?o?0rX__pycache__/proactor_events.cpython-36.opt-2.pycnu�[���PK[��)�#A�__pycache__/__init__.cpython-36.pycnu�[���PK[P�f�#�#0��__pycache__/base_subprocess.cpython-36.opt-1.pycnu�[���PK[VWX�EE%п__pycache__/test_utils.cpython-36.pycnu�[���PK[�;�.4.4(8	__pycache__/streams.cpython-36.opt-2.pycnu�[���PK[�`���*�9	__pycache__/protocols.cpython-36.opt-2.pycnu�[���PK[��t�GsGs0�B	__pycache__/selector_events.cpython-36.opt-1.pycnu�[���PK[����j#j#0m�	__pycache__/base_subprocess.cpython-36.opt-2.pycnu�[���PK[�#�~� � !7�	__pycache__/queues.cpython-36.pycnu�[���PK[1<���J�J ^�	__pycache__/tasks.cpython-36.pycnu�[���PK[ϤУ'EF
__pycache__/base_futures.cpython-36.pycnu�[���PK[�pä�b�b!�N
__pycache__/events.cpython-36.pycnu�[���PK[�ny�0$0$*�
__pycache__/base_subprocess.cpython-36.pycnu�[���PK[h8�"��.t�
__pycache__/windows_utils.cpython-36.opt-1.pycnu�[���PK[4]�j!j!%��
__pycache__/coroutines.cpython-36.pycnu�[���PK[{fU���*?
__pycache__/constants.cpython-36.opt-2.pycnu�[���PK[�>B�+{__pycache__/transports.cpython-36.opt-2.pycnu�[���PK[�����!�'__pycache__/compat.cpython-36.pycnu�[���PK[C�s//++__pycache__/transports.cpython-36.opt-1.pycnu�[���PK[G��4GG%oZ__pycache__/base_tasks.cpython-36.pycnu�[���PK[ϤУ-b__pycache__/base_futures.cpython-36.opt-1.pycnu�[���PK[/F\:(ij__pycache__/windows_utils.cpython-36.pycnu�[���PK[��z�4�4(�__pycache__/futures.cpython-36.opt-1.pycnu�[���PK[��� � +�__pycache__/coroutines.cpython-36.opt-1.pycnu�[���PK[5�h�@�@0:�__pycache__/proactor_events.cpython-36.opt-1.pycnu�[���PK[����$�__pycache__/log.cpython-36.opt-2.pycnu�[���PK[�%�O�S�S/�__pycache__/windows_events.cpython-36.opt-1.pycnu�[���PK[�gғg�g,�l__pycache__/unix_events.cpython-36.opt-2.pycnu�[���PK[����M�M"��__pycache__/streams.cpython-36.pycnu�[���PK[G��4GG+#
__pycache__/base_tasks.cpython-36.opt-1.pycnu�[���PK[�a��Z<Z< �*
__pycache__/locks.cpython-36.pycnu�[���PK[�x�mDmD+Sg
__pycache__/test_utils.cpython-36.opt-1.pycnu�[���PK[�E(�gg'�
__pycache__/compat.cpython-36.opt-2.pycnu�[���PK[#���]w]w&ٮ
__pycache__/unix_events.cpython-36.pycnu�[���PK[ U��44)�&__pycache__/sslproto.cpython-36.opt-2.pycnu�[���PK[��ېb�b'�Z__pycache__/events.cpython-36.opt-1.pycnu�[���PK[�#�~� � 'ͽ__pycache__/queues.cpython-36.opt-1.pycnu�[���PK[����N�N)��__pycache__/sslproto.cpython-36.opt-1.pycnu�[���PK[�R�ӸA�A*.__pycache__/proactor_events.cpython-36.pycnu�[���PK[$��dvv,p__pycache__/unix_events.cpython-36.opt-1.pycnu�[���PK[�»��+v�__pycache__/subprocess.cpython-36.opt-1.pycnu�[���PK[	��[?[?+]__pycache__/test_utils.cpython-36.opt-2.pycnu�[���PK[�����A__pycache__/log.cpython-36.pycnu�[���PK[G��4GG+=B__pycache__/base_tasks.cpython-36.opt-2.pycnu�[���PK[s�58�s�s*�I__pycache__/selector_events.cpython-36.pycnu�[���PK[K�[[$��__pycache__/protocols.cpython-36.pycnu�[���PK[i|MZ�.�.&i�__pycache__/tasks.cpython-36.opt-2.pycnu�[���PK[H�V1  +�__pycache__/coroutines.cpython-36.opt-2.pycnu�[���PK[���ee.%__pycache__/windows_utils.cpython-36.opt-2.pycnu�[���PK[������+�7__pycache__/subprocess.cpython-36.opt-2.pycnu�[���PK[Q*_//%!R__pycache__/transports.cpython-36.pycnu�[���PK[̡��b3b3
��futures.pynu�[���PK[a��ۿۿ0�unix_events.pynu�[���PK[����

Iubase_futures.pynu�[���PK[E{C�||�log.pynu�[���PK[��n�	�	
H�base_tasks.pynu�[���PK['J��i�i�(�windows_events.pynu�[���PK[�������
__init__.pynu�[���PK[0��  	�queues.pynu�[���PK[VW�<}<}00proactor_events.pynu�[���PK[�H������base_events.pynu�[���PK[���]"]"
��coroutines.pynu�[���PK[|�q���3�protocols.pynu�[���PK [��Zd	d	Oformat_helpers.pynu�[���PK [z/%:
�runners.pynu�[���PK [yPaa
4exceptions.pynu�[���PK [��M%!%!'� __pycache__/trsock.cpython-38.opt-1.pycnu�[���PK [ߋ�ѢP�P"NB__pycache__/streams.cpython-38.pycnu�[���PK [[k�AA&B�__pycache__/tasks.cpython-38.opt-2.pycnu�[���PK [�\@��/�/+��__pycache__/transports.cpython-38.opt-1.pycnu�[���PK [�x��**/�__pycache__/format_helpers.cpython-38.opt-2.pycnu�[���PK [�ar�$�$*G
__pycache__/base_subprocess.cpython-38.pycnu�[���PK [���/$$0k2__pycache__/base_subprocess.cpython-38.opt-2.pycnu�[���PK [�H��m�m!�V__pycache__/events.cpython-38.pycnu�[���PK [�h���(��__pycache__/runners.cpython-38.opt-1.pycnu�[���PK [i�.CHH'��__pycache__/queues.cpython-38.opt-2.pycnu�[���PK [6�8+��)Q�__pycache__/__init__.cpython-38.opt-2.pycnu�[���PK [wI<wss+b�__pycache__/exceptions.cpython-38.opt-2.pycnu�[���PK [?��O�O(0�__pycache__/streams.cpython-38.opt-1.pycnu�[���PK [���1N�N�&>__pycache__/base_events.cpython-38.pycnu�[���PK [7�!�!$�__pycache__/protocols.cpython-38.pycnu�[���PK [�ۤ�YmYm0�'__pycache__/selector_events.cpython-38.opt-2.pycnu�[���PK [��?�?&p�__pycache__/locks.cpython-38.opt-1.pycnu�[���PK [�5BB)��__pycache__/__main__.cpython-38.opt-2.pycnu�[���PK [���kk*S�__pycache__/staggered.cpython-38.opt-1.pycnu�[���PK [��,�*�__pycache__/staggered.cpython-38.opt-2.pycnu�[���PK [�N&%��__pycache__/coroutines.cpython-38.pycnu�[���PK [˼��-�-�,�__pycache__/unix_events.cpython-38.opt-1.pycnu�[���PK [��?�? f�__pycache__/locks.cpython-38.pycnu�[���PK [���+�+"��__pycache__/futures.cpython-38.pycnu�[���PK [�?�`��(�__pycache__/runners.cpython-38.opt-2.pycnu�[���PK [���I�I'__pycache__/events.cpython-38.opt-2.pycnu�[���PK [\dkss.*h__pycache__/windows_utils.cpython-38.opt-2.pycnu�[���PK [��q�ll-�w__pycache__/base_futures.cpython-38.opt-1.pycnu�[���PK [	�?�/m/m'�__pycache__/events.cpython-38.opt-1.pycnu�[���PK [C��ktTtT#J�__pycache__/sslproto.cpython-38.pycnu�[���PK [$��'��+B__pycache__/base_tasks.cpython-38.opt-2.pycnu�[���PK [��q�ll'J__pycache__/base_futures.cpython-38.pycnu�[���PK [r׉nn-�Q__pycache__/base_futures.cpython-38.opt-2.pycnu�[���PK [��+�[�[0�X__pycache__/proactor_events.cpython-38.opt-2.pycnu�[���PK [7�!�!*��__pycache__/protocols.cpython-38.opt-1.pycnu�[���PK [�	�j$j$0��__pycache__/base_subprocess.cpython-38.opt-1.pycnu�[���PK [�Ŀ � 'm�__pycache__/queues.cpython-38.opt-1.pycnu�[���PK [�T
��$�__pycache__/log.cpython-38.opt-1.pycnu�[���PK [$��'��+�__pycache__/base_tasks.cpython-38.opt-1.pycnu�[���PK [���  (�%__pycache__/futures.cpython-38.opt-2.pycnu�[���PK [�	u�

*(D__pycache__/protocols.cpython-38.opt-2.pycnu�[���PK [-w/��)�Q__pycache__/__init__.cpython-38.opt-1.pycnu�[���PK [���
		/�T__pycache__/format_helpers.cpython-38.opt-1.pycnu�[���PK [�����+e^__pycache__/coroutines.cpython-38.opt-2.pycnu�[���PK [�с�^�^&�w__pycache__/tasks.cpython-38.opt-1.pycnu�[���PK [2�
��+|�__pycache__/transports.cpython-38.opt-2.pycnu�[���PK [�O�=]=]0��__pycache__/proactor_events.cpython-38.opt-1.pycnu�[���PK [-w/��#%O__pycache__/__init__.cpython-38.pycnu�[���PK [��gF��,hR__pycache__/unix_events.cpython-38.opt-2.pycnu�[���PK [���b�s�s*��__pycache__/selector_events.cpython-38.pycnu�[���PK [9c��_�_/!M__pycache__/windows_events.cpython-38.opt-1.pycnu�[���PK [�h���"i�__pycache__/runners.cpython-38.pycnu�[���PK [l[˅	`	`)X�__pycache__/windows_events.cpython-38.pycnu�[���PK [ٗ'99)�__pycache__/sslproto.cpython-38.opt-2.pycnu�[���PK [H�� �[�[/,O__pycache__/windows_events.cpython-38.opt-2.pycnu�[���PK [�o2y�/�/%!�__pycache__/transports.cpython-38.pycnu�[���PK [�;j%%.^�__pycache__/windows_utils.cpython-38.opt-1.pycnu�[���PK [��Kl�l�,��__pycache__/base_events.cpython-38.opt-1.pycnu�[���PK [�T
���� __pycache__/log.cpython-38.pycnu�[���PK [)��(&(&&۴ __pycache__/locks.cpython-38.opt-2.pycnu�[���PK [��X6GG*Y� __pycache__/constants.cpython-38.opt-1.pycnu�[���PK [���
		)�� __pycache__/format_helpers.cpython-38.pycnu�[���PK [����+q� __pycache__/subprocess.cpython-38.opt-1.pycnu�[���PK [��X6GG$n!__pycache__/constants.cpython-38.pycnu�[���PK [k*�	�	+	!__pycache__/exceptions.cpython-38.opt-1.pycnu�[���PK [��X6GG*[!__pycache__/constants.cpython-38.opt-2.pycnu�[���PK [��yy(�!__pycache__/windows_utils.cpython-38.pycnu�[���PK [�Ŀ � !�%!__pycache__/queues.cpython-38.pycnu�[���PK [�]������&�F!__pycache__/unix_events.cpython-38.pycnu�[���PK [`��S�S)��!__pycache__/sslproto.cpython-38.opt-1.pycnu�[���PK [���E$�4"__pycache__/staggered.cpython-38.pycnu�[���PK [g<2��^�^ NE"__pycache__/tasks.cpython-38.pycnu�[���PK [�S�Y�s�s0y�"__pycache__/selector_events.cpython-38.opt-1.pycnu�[���PK [��M�""+�#__pycache__/subprocess.cpython-38.opt-2.pycnu�[���PK [����+5#__pycache__/coroutines.cpython-38.opt-1.pycnu�[���PK [*�J;��$O#__pycache__/log.cpython-38.opt-2.pycnu�[���PK [�m���8�8((P#__pycache__/streams.cpython-38.opt-2.pycnu�[���PK [T=T\W�W�,	�#__pycache__/base_events.cpython-38.opt-2.pycnu�[���PK [ۂ�U
+
+(�,$__pycache__/futures.cpython-38.opt-1.pycnu�[���PK [��b��%X$__pycache__/subprocess.cpython-38.pycnu�[���PK [$��'��%3u$__pycache__/base_tasks.cpython-38.pycnu�[���PK [�5BB)"}$__pycache__/__main__.cpython-38.opt-1.pycnu�[���PK [��M%!%!!��$__pycache__/trsock.cpython-38.pycnu�[���PK [�5BB#3�$__pycache__/__main__.cpython-38.pycnu�[���PK [ft�,S^S^*ȷ$__pycache__/proactor_events.cpython-38.pycnu�[���PK [�P�% % 'u%__pycache__/trsock.cpython-38.opt-2.pycnu�[���PK [k*�	�	%�6%__pycache__/exceptions.cpython-38.pycnu�[���PK [Yy�L

=A%__main__.pynu�[���PK [ّ>hh�N%staggered.pynu�[���PK [���
��	+f%trsock.pynu�[���PK��PKX}%