Python os.strerror() Examples

The following are 30 code examples of os.strerror(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: libc.py    From benchexec with Apache License 2.0 6 votes vote down vote up
def _check_errno(result, func, arguments):
    assert func.restype in [c_int, c_void_p]
    if (func.restype == c_int and result == -1) or (
        func.restype == c_void_p and c_void_p(result).value == c_void_p(-1).value
    ):
        errno = _ctypes.get_errno()
        try:
            func_name = func.__name__
        except AttributeError:
            func_name = "__unknown__"
        msg = (
            func_name
            + "("
            + ", ".join(map(str, arguments))
            + ") failed: "
            + _os.strerror(errno)
        )
        raise OSError(errno, msg)
    return result


# off_t is a signed integer type required for mmap.
# In my tests it is equal to long on both 32bit and 64bit x86 Linux. 
Example #2
Source File: simple_httpclient_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def test_connection_refused(self):
        cleanup_func, port = refusing_port()
        self.addCleanup(cleanup_func)
        with ExpectLog(gen_log, ".*", required=False):
            with self.assertRaises(socket.error) as cm:
                self.fetch("http://127.0.0.1:%d/" % port, raise_error=True)

        if sys.platform != "cygwin":
            # cygwin returns EPERM instead of ECONNREFUSED here
            contains_errno = str(errno.ECONNREFUSED) in str(cm.exception)
            if not contains_errno and hasattr(errno, "WSAECONNREFUSED"):
                contains_errno = str(errno.WSAECONNREFUSED) in str(  # type: ignore
                    cm.exception
                )
            self.assertTrue(contains_errno, cm.exception)
            # This is usually "Connection refused".
            # On windows, strerror is broken and returns "Unknown error".
            expected_message = os.strerror(errno.ECONNREFUSED)
            self.assertTrue(expected_message in str(cm.exception), cm.exception) 
Example #3
Source File: simple_httpclient_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_connection_refused(self):
        cleanup_func, port = refusing_port()
        self.addCleanup(cleanup_func)
        with ExpectLog(gen_log, ".*", required=False):
            self.http_client.fetch("http://127.0.0.1:%d/" % port, self.stop)
            response = self.wait()
        self.assertEqual(599, response.code)

        if sys.platform != 'cygwin':
            # cygwin returns EPERM instead of ECONNREFUSED here
            contains_errno = str(errno.ECONNREFUSED) in str(response.error)
            if not contains_errno and hasattr(errno, "WSAECONNREFUSED"):
                contains_errno = str(errno.WSAECONNREFUSED) in str(response.error)
            self.assertTrue(contains_errno, response.error)
            # This is usually "Connection refused".
            # On windows, strerror is broken and returns "Unknown error".
            expected_message = os.strerror(errno.ECONNREFUSED)
            self.assertTrue(expected_message in str(response.error),
                            response.error) 
Example #4
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example #5
Source File: util.py    From oscrypto with MIT License 6 votes vote down vote up
def _extract_error():
    """
    Extracts the last OS error message into a python unicode string

    :return:
        A unicode string error message
    """

    error_num = errno()

    try:
        error_string = os.strerror(error_num)
    except (ValueError):
        return str_cls(error_num)

    if isinstance(error_string, str_cls):
        return error_string

    return _try_decode(error_string) 
Example #6
Source File: test_socketserver.py    From BinderFilter with MIT License 6 votes vote down vote up
def mocked_select_module(self):
        """Mocks the select.select() call to raise EINTR for first call"""
        old_select = select.select

        class MockSelect:
            def __init__(self):
                self.called = 0

            def __call__(self, *args):
                self.called += 1
                if self.called == 1:
                    # raise the exception on first call
                    raise select.error(errno.EINTR, os.strerror(errno.EINTR))
                else:
                    # Return real select value for consecutive calls
                    return old_select(*args)

        select.select = MockSelect()
        try:
            yield select.select
        finally:
            select.select = old_select 
Example #7
Source File: test_socketserver.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def mocked_select_module(self):
        """Mocks the select.select() call to raise EINTR for first call"""
        old_select = select.select

        class MockSelect:
            def __init__(self):
                self.called = 0

            def __call__(self, *args):
                self.called += 1
                if self.called == 1:
                    # raise the exception on first call
                    raise select.error(errno.EINTR, os.strerror(errno.EINTR))
                else:
                    # Return real select value for consecutive calls
                    return old_select(*args)

        select.select = MockSelect()
        try:
            yield select.select
        finally:
            select.select = old_select 
Example #8
Source File: iostream.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            gen_log.warning("Connect error on fd %d: %s",
                            self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        self._connecting = False 
Example #9
Source File: simple_httpclient_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def test_connection_refused(self):
        server_socket, port = bind_unused_port()
        server_socket.close()
        with ExpectLog(gen_log, ".*", required=False):
            self.http_client.fetch("http://localhost:%d/" % port, self.stop)
            response = self.wait()
        self.assertEqual(599, response.code)

        if sys.platform != 'cygwin':
            # cygwin returns EPERM instead of ECONNREFUSED here
            self.assertTrue(str(errno.ECONNREFUSED) in str(response.error),
                            response.error)
            # This is usually "Connection refused".
            # On windows, strerror is broken and returns "Unknown error".
            expected_message = os.strerror(errno.ECONNREFUSED)
            self.assertTrue(expected_message in str(response.error),
                            response.error) 
Example #10
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example #11
Source File: pomp_loop_thread.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _add_fd_to_loop(self, fd, cb, fd_events, userdata=None):
        if cb is None:
            self.logger.info(
                "Cannot add fd '{}' to pomp loop without "
                "a valid callback function".format(fd)
            )
            return None
        self.fd_userdata[fd] = userdata
        userdata = ctypes.cast(
            ctypes.pointer(ctypes.py_object(userdata)), ctypes.c_void_p
        )
        self.c_fd_userdata[fd] = userdata
        self.pomp_fd_callbacks[fd] = od.pomp_fd_event_cb_t(cb)
        res = od.pomp_loop_add(
            self.pomp_loop,
            ctypes.c_int32(fd),
            od.uint32_t(int(fd_events)),
            self.pomp_fd_callbacks[fd],
            userdata
        )
        if res != 0:
            raise RuntimeError(
                "Cannot add fd '{}' to pomp loop: {} ({})".format(
                    fd, os.strerror(-res), res)
            ) 
Example #12
Source File: server.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def _make_gevent_unix_socket(self, socket_file):
        # the socket file must not exist prior to bind()
        if os.path.exists(socket_file):
            # avoid nuking regular files and symbolic links (could be a mistype or security issue)
            if os.path.isfile(socket_file) or os.path.islink(socket_file):
                raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), socket_file)
            os.remove(socket_file)

        unix_sock = WSGIServer.get_listener(socket_file, family=socket.AF_UNIX)
        self.unix_socket_file = socket_file

        # ensure current user and group have r/w permissions, no permissions for other users
        # this way the socket can be shared in a semi-secure manner
        # between the user running calibre-web and the user running the fronting webserver
        os.chmod(socket_file, 0o660)

        return unix_sock 
Example #13
Source File: metadata.py    From pi-timolo with MIT License 6 votes vote down vote up
def _instantiate_image(self, filename):
        """Instanciate the exiv2 image.

        Args:
        filename -- str(path to an image file)
        """
        # This method is meant to be overridden in unit tests to easily replace
        # the internal image reference by a mock.
        if not os.path.exists(filename) or not os.path.isfile(filename):
            raise IOError(ENOENT, os.strerror(ENOENT), filename)

        # Remember the reference timestamps before doing any access to the file
        stat = os.stat(filename)
        self._atime = stat.st_atime
        self._mtime = stat.st_mtime
        return libexiv2python._Image(filename) 
Example #14
Source File: transport.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def read(self, timeout):
        if self.tty is not None:
            self.tty.timeout = max(timeout/1E3, 0.05)
            frame = bytearray(self.tty.read(6))
            if frame is None or len(frame) == 0:
                raise IOError(errno.ETIMEDOUT, os.strerror(errno.ETIMEDOUT))
            if frame.startswith(b"\x00\x00\xff\x00\xff\x00"):
                log.log(logging.DEBUG-1, "<<< %s", hexlify(frame).decode())
                return frame
            LEN = frame[3]
            if LEN == 0xFF:
                frame += self.tty.read(3)
                LEN = frame[5] << 8 | frame[6]
            frame += self.tty.read(LEN + 1)
            log.log(logging.DEBUG-1, "<<< %s", hexlify(frame).decode())
            return frame 
Example #15
Source File: perf.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
def _create_file_from_fd(pfd):
    """Validates file description and creates a file-like object"""
    # -1 is returned on error: http://man7.org/linux/man-pages/man2/open.2.html#RETURN_VALUE
    if pfd == -1:
        INVALID_ARG_ERRNO = 22
        errno = ctypes.get_errno()
        if errno == INVALID_ARG_ERRNO:
            raise UnableToOpenPerfEvents('Invalid perf event file descriptor: {}, {}. '
                                         'For cgroup based perf counters it may indicate there is '
                                         'no enough hardware counters for measure all metrics!'
                                         'If traceback shows problem in perf_uncore '
                                         'it could be problem with PERF_FORMAT_GROUP in'
                                         'perf_event_attr structure for perf_event_open syscall.'
                                         'Older kernel cannot handle with extended format group.'
                                         'Kernel cannot be 3.10.0-862.el7.x86_64 or lower.'
                                         ''.format(errno, os.strerror(errno)))
        else:
            raise UnableToOpenPerfEvents('Invalid perf event file descriptor: {}, {}.'
                                         .format(errno, os.strerror(errno)))
    return os.fdopen(pfd, 'rb') 
Example #16
Source File: cgroups_allocations.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
def _migrate_page_call(pid, max_node, old_nodes, new_node) -> int:
    """Wrapper on migrate_pages function using libc syscall"""

    pid = int(pid)
    max = ctypes.c_ulong(max_node + 1)
    old = ctypes.pointer(ctypes.c_ulong(old_nodes))
    new = ctypes.pointer(ctypes.c_ulong(new_node))

    # Example memory_migrate(256, pid, 5, 13 -> b'1101', 2 -> b'0010')
    result = LIBC.syscall(NR_MIGRATE_PAGES, pid, max, old, new)

    if result == -1:
        errno = ctypes.get_errno()
        raise UnableToMigratePages('Unable to migrate pages: {}, {}.'
                                   .format(errno, os.strerror(errno)))
    log.log(TRACE, 'Number of not moved pages (return from migrate_pages syscall): %d', result)
    return result 
Example #17
Source File: acr122.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def command(self, cmd_code, cmd_data, timeout):
        """Send a host command and return the chip response.

        """
        log.log(logging.DEBUG-1, "{} {}".format(self.CMD[cmd_code],
                                                hexlify(cmd_data).decode()))

        frame = bytearray([0xD4, cmd_code]) + bytearray(cmd_data)
        frame = bytearray([0xFF, 0x00, 0x00, 0x00, len(frame)]) + frame

        frame = self.ccid_xfr_block(frame, timeout)
        if not frame or len(frame) < 4:
            log.error("insufficient data for decoding chip response")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        if not (frame[0] == 0xD5 and frame[1] == cmd_code + 1):
            log.error("received invalid chip response")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        if not (frame[-2] == 0x90 and frame[-1] == 0x00):
            log.error("received pseudo apdu with error status")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        return frame[2:-2] 
Example #18
Source File: acr122.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def ccid_xfr_block(self, data, timeout=0.1):
        """Encapsulate host command *data* into an PC/SC Escape command to
        send to the device and extract the chip response if received
        within *timeout* seconds.

        """
        frame = struct.pack("<BI5B", 0x6F, len(data), 0, 0, 0, 0, 0) + data
        self.transport.write(bytearray(frame))
        frame = self.transport.read(int(timeout * 1000))
        if not frame or len(frame) < 10:
            log.error("insufficient data for decoding ccid response")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        if frame[0] != 0x80:
            log.error("expected a RDR_to_PC_DataBlock")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        if len(frame) != 10 + struct.unpack("<I", memoryview(frame)[1:5])[0]:
            log.error("RDR_to_PC_DataBlock length mismatch")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        return frame[10:] 
Example #19
Source File: rmTimeUtils.py    From rainmachine-developer-resources with GNU General Public License v3.0 6 votes vote down vote up
def monotonicTime(self, asSeconds = True):
        t = timespec()
        if self.clock_gettime(rmMonotonicTime.CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
            errno_ = ctypes.get_errno()
            if self.fallback:
                log.info("Monotonic Clock Error ! Reverting to time.time() fallback")
                return self.monotonicFallback(asSeconds)
            else:
                raise OSError(errno_, os.strerror(errno_))

        if asSeconds:
            return t.tv_sec

        return t.tv_sec + t.tv_nsec * 1e-9


#-----------------------------------------------------------------------------------------------
#
#
# 
Example #20
Source File: test_runexecutor.py    From benchexec with Apache License 2.0 6 votes vote down vote up
def setUp(self, *args, **kwargs):
        try:
            container.execute_in_namespace(lambda: 0)
        except OSError as e:
            self.skipTest("Namespaces not supported: {}".format(os.strerror(e.errno)))

        dir_modes = kwargs.pop(
            "dir_modes",
            {
                "/": containerexecutor.DIR_READ_ONLY,
                "/home": containerexecutor.DIR_HIDDEN,
                "/tmp": containerexecutor.DIR_HIDDEN,
            },
        )

        self.runexecutor = RunExecutor(
            use_namespaces=True, dir_modes=dir_modes, *args, **kwargs
        ) 
Example #21
Source File: pn53x.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def __init__(self, chipset, logger):
        self.chipset = chipset
        self.log = logger

        try:
            chipset_communication = self.chipset.diagnose('line')
        except Chipset.Error:
            chipset_communication = False

        if chipset_communication is False:
            self.log.error("chipset communication test failed")
            raise IOError(errno.EIO, os.strerror(errno.EIO))

        # for line in self._print_ciu_register_page(0, 1, 2, 3):
        #     self.log.debug(line)

        # for addr in range(0, 0x03FF, 16):
        #     xram = self.chipset.read_register(*range(addr, addr+16))
        #     xram = ' '.join(["%02X" % x for x in xram])
        #     self.log.debug("0x%04X: %s", addr, xram) 
Example #22
Source File: timeout.py    From kano-toolset with GNU General Public License v2.0 6 votes vote down vote up
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator 
Example #23
Source File: pdraw.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def unref(self):
        """
        This function decrements the reference counter of the underlying buffer(s)
        """
        try:
            res = od.vbuf_unref(self._buf)
            if res != 0:
                self.logger.error("vbuf_unref unpacked frame error: {} {} {}".format(
                    self._media_id,
                    os.strerror(-res),
                    ctypes.addressof(self._buf.contents)
                ))
        finally:
            if self._yuv_packed_buffer:
                res = od.vbuf_unref(self._yuv_packed_buffer)
                if res != 0:
                    self.logger.error("vbuf_unref packed frame error: {} {} {}".format(
                        self._media_id,
                        os.strerror(-res),
                        ctypes.addressof(self._buf.contents)
                    )) 
Example #24
Source File: __init__.py    From nfcpy with European Union Public License 1.1 5 votes vote down vote up
def exchange(self, send_data, timeout):
        """Exchange data with an activated target (*send_data* is a command
        frame) or as an activated target (*send_data* is a response
        frame). Returns a target response frame (if data is send to an
        activated target) or a next command frame (if data is send
        from an activated target). Returns None if the communication
        link broke during exchange (if data is sent as a target). The
        timeout is the number of seconds to wait for data to return,
        if the timeout expires an nfc.clf.TimeoutException is
        raised. Other nfc.clf.CommunicationError exceptions may be raised if
        an error is detected during communication.

        """
        with self.lock:
            if self.device is None:
                raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))

            log.debug(">>> %s timeout=%s", print_data(send_data), str(timeout))

            if isinstance(self.target, RemoteTarget):
                exchange = self.device.send_cmd_recv_rsp
            elif isinstance(self.target, LocalTarget):
                exchange = self.device.send_rsp_recv_cmd
            else:
                log.error("no target for data exchange")
                return None

            send_time = time.time()
            rcvd_data = exchange(self.target, send_data, timeout)
            recv_time = time.time() - send_time

            log.debug("<<< %s %.3fs", print_data(rcvd_data), recv_time)
            return rcvd_data 
Example #25
Source File: utils_misc.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def monotonic_time():
    """
    Get monotonic time
    """
    def monotonic_time_os():
        """
        Get monotonic time using ctypes
        """
        class struct_timespec(ctypes.Structure):
            _fields_ = [('tv_sec', ctypes.c_long), ('tv_nsec', ctypes.c_long)]

        lib = ctypes.CDLL("librt.so.1", use_errno=True)
        clock_gettime = lib.clock_gettime
        clock_gettime.argtypes = [
            ctypes.c_int, ctypes.POINTER(struct_timespec)]

        timespec = struct_timespec()
        # CLOCK_MONOTONIC_RAW == 4
        if not clock_gettime(4, ctypes.pointer(timespec)) == 0:
            errno = ctypes.get_errno()
            raise OSError(errno, os.strerror(errno))

        return timespec.tv_sec + timespec.tv_nsec * 10 ** -9

    monotonic_attribute = getattr(time, "monotonic", None)
    if callable(monotonic_attribute):
        # Introduced in Python 3.3
        return time.monotonic()
    else:
        return monotonic_time_os() 
Example #26
Source File: utils_net.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def dellink(self):
        '''
        Delete the interface. Equivalent to 'ip link delete NAME'.
        '''
        # create socket
        sock = socket.socket(socket.AF_NETLINK,
                             socket.SOCK_RAW,
                             arch.NETLINK_ROUTE)

        # Get the interface index
        interface_index = self.get_index()

        # send data to socket
        sock.send(self.__netlink_pack(msgtype=arch.RTM_DELLINK,
                                      flags=arch.NLM_F_REQUEST | arch.NLM_F_ACK,
                                      seq=1, pid=0,
                                      data=struct.pack('BxHiII',
                                                       arch.AF_PACKET,
                                                       0, interface_index, 0, 0)))

        # receive data from socket
        try:
            while True:
                data_recv = sock.recv(1024)
                for msgtype, flags, mseq, pid, data in \
                        self.__netlink_unpack(data_recv):
                    if msgtype == arch.NLMSG_ERROR:
                        (err_no,) = struct.unpack("i", data[:4])
                        if err_no == 0:
                            return 0
                        else:
                            raise DelLinkError(self.name, os.strerror(-err_no))
                    else:
                        raise DelLinkError(self.name, "unexpected error")
        finally:
            sock.close() 
Example #27
Source File: network_namespace.py    From octavia with Apache License 2.0 5 votes vote down vote up
def _error_handler(result, func, arguments):
        if result == -1:
            errno = ctypes.get_errno()
            raise OSError(errno, os.strerror(errno)) 
Example #28
Source File: namespace.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def get_errno_msg():
    try:
        libc.__errno_location.restype = ctypes.POINTER(ctypes.c_int)
        errno = libc.__errno_location().contents.value
        errno_msg = os.strerror(errno)
        return errno_msg
    except (OSError, AttributeError):
        # Getting an error while trying to get the errorno
        return 'unknown error' 
Example #29
Source File: asyncore.py    From meddle with MIT License 5 votes vote down vote up
def _strerror(err):
    try:
        return os.strerror(err)
    except (ValueError, OverflowError, NameError):
        if err in errorcode:
            return errorcode[err]
        return "Unknown error %s" %err 
Example #30
Source File: iostream.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def _handle_connect(self) -> None:
        try:
            err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        except socket.error as e:
            # Hurd doesn't allow SO_ERROR for loopback sockets because all
            # errors for such sockets are reported synchronously.
            if errno_from_exception(e) == errno.ENOPROTOOPT:
                err = 0
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning(
                    "Connect error on fd %s: %s",
                    self.socket.fileno(),
                    errno.errorcode[err],
                )
            self.close()
            return
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future_set_result_unless_cancelled(future, self)
        self._connecting = False