Python errno 模块,EHOSTUNREACH 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用errno.EHOSTUNREACH

项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_connect_ex_error(self):
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT)
            try:
                rc = s.connect_ex((REMOTE_HOST, 444))
                # Issue #19919: Windows machines or VMs hosted on Windows
                # machines sometimes return EWOULDBLOCK.
                errors = (
                    errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
                    errno.EWOULDBLOCK,
                )
                self.assertIn(rc, errors)
            finally:
                s.close()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_connect_ex_error(self):
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT)
            try:
                rc = s.connect_ex((REMOTE_HOST, 444))
                # Issue #19919: Windows machines or VMs hosted on Windows
                # machines sometimes return EWOULDBLOCK.
                errors = (
                    errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
                    errno.EWOULDBLOCK,
                )
                self.assertIn(rc, errors)
            finally:
                s.close()
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_connect_ex_error(self):
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT)
            try:
                rc = s.connect_ex((REMOTE_HOST, 444))
                # Issue #19919: Windows machines or VMs hosted on Windows
                # machines sometimes return EWOULDBLOCK.
                errors = (
                    errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
                    errno.EWOULDBLOCK,
                )
                self.assertIn(rc, errors)
            finally:
                s.close()
项目:spark    作者:chenguolin    | 项目源码 | 文件源码
def __handle_socket_error(self, exception):
        log.debug("Request failed with %s" % exception)
        if exception.errno in (errno.ECONNREFUSED, errno.EHOSTUNREACH):
            # if NN is down or machine is not available, pass it:
            self.namenode.next() # Failover and retry until self.max_failovers was reached
        elif isinstance(exception, socket.timeout):
            self.namenode.next() # Failover and retry until self.max_failovers was reached
        else:
            raise
项目:deb-python-eventlet    作者:openstack    | 项目源码 | 文件源码
def test_connect_timeout(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(0.1)
        gs = greenio.GreenSocket(s)

        try:
            expect_socket_timeout(gs.connect, ('192.0.2.1', 80))
        except socket.error as e:
            # unreachable is also a valid outcome
            if not get_errno(e) in (errno.EHOSTUNREACH, errno.ENETUNREACH):
                raise
项目:deb-python-eventlet    作者:openstack    | 项目源码 | 文件源码
def test_connect_ex_timeout(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(0.1)
        gs = greenio.GreenSocket(s)
        e = gs.connect_ex(('192.0.2.1', 80))
        if e not in (errno.EHOSTUNREACH, errno.ENETUNREACH):
            self.assertEqual(e, errno.EAGAIN)
项目:pydocktors    作者:Patouche    | 项目源码 | 文件源码
def test__wait_for_port_with_unsupported_errors(self, time_sleep_mock, socket_mock):
        # GIVEN
        docker_container = DockerContainer(
            image='alpine',
            wait_for_port=1234,
        )

        docker_container._client = mock.MagicMock()
        docker_container._client.containers.get.return_value.attrs = dict(
            NetworkSettings=dict(IPAddress='172.10.0.2')
        )
        docker_container._container = mock.MagicMock(id='c5f0cad13259')
        docker_container._container.logs.return_value = b'\n'.join([
            b'some container error ...',
            b'container failed to start'
        ])

        socket_mock.return_value.connect_ex.side_effect = [1, 1, errno.EHOSTUNREACH]

        # WHEN
        with self.assertRaises(DockerContainerError) as cm:
            docker_container._wait_for_port()

        # THEN
        expected_message = '\n'.join([
            '[alpine] Host 172.10.0.2 cannot be reach. The container may exit abnormally. Container logs :',
            'some container error ...',
            'container failed to start'
        ])
        self.assertEquals(str(cm.exception), expected_message, 'Message should be explicit: %s' % expected_message)
        time_sleep_mock.assert_called()
        socket_mock.assert_called_with(socket.AF_INET, socket.SOCK_STREAM)
        connect_ex_mock = socket_mock.return_value.connect_ex
        connect_ex_mock.assert_called_with(('172.10.0.2', 1234))
        docker_container._container.logs.assert_called_once_with(stream=False)
        self.assertEqual(connect_ex_mock.call_count, 3, 'Should have been called 3 times instead of {call_nb}'.format(
            call_nb=connect_ex_mock.call_count
        ))
项目:pydocktors    作者:Patouche    | 项目源码 | 文件源码
def _wait_for_port(self):
        wait_port, image, res = self.p('wait_for_port'), self.p('image'), 1
        if wait_port:
            container_id = self._container.id
            container_info = self._client.containers.get(container_id)
            ip_address = container_info.attrs['NetworkSettings']['IPAddress']
            unsupported_errors = [
                (errno.EHOSTUNREACH,
                 '[{image}] Host {ip} cannot be reach. The container may exit abnormally. Container logs :\n{logs}')
            ]

            with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
                while res != 0:
                    res = sock.connect_ex((ip_address, wait_port))
                    logger.debug(
                        '[%s] Waiting for port %d to respond (code:%d => %s).',
                        image, wait_port, res, errorcode.get(res, '--')
                    )
                    unsupported_error = next((e[1] for e in unsupported_errors if e[0] == res), None)
                    if unsupported_error:
                        raise DockerContainerError(unsupported_error.format(
                            image=image,
                            port=wait_port,
                            signal=errorcode.get(res, '--'),
                            ip=ip_address,
                            logs=self._container.logs(stream=False).decode('utf-8')
                        ))

                    time.sleep(0.1 if res != 0 else 0)
            logger.debug('[%s] Port %d is now responding.', image, wait_port)
项目:eAPI-Scripts    作者:GADify    | 项目源码 | 文件源码
def GetVersion(x):
   verLoc = 19
   IP = "10.0.0." + str(x)
   switch = Server( "https://" + ScriptUser + ":" + ScriptPass + "@" + IP + "/command-api" )
   # Results in Host Unreach never happening, but [ . ] means same thing 
   #         without waiting
   socket.setdefaulttimeout(3)
   try:
      response = switch.runCmds( 1, [ "show version" ] )
   except socket.error,ERR :
       ErrorCode = ERR[0]
       if ErrorCode == errno.ECONNREFUSED:
          win.addstr(x, verLoc -6, "        [ Err " + str(ErrorCode) + ": No eAPI ]          ")
          refresh() 
       elif ErrorCode == errno.EHOSTUNREACH:
          # Never hit with lower socket timeout
          win.addstr(x, verLoc, "Err " + str(ErrorCode) + ": Pwr off or Aboot ]          ")
          refresh() 
       elif ErrorCode == errno.ECONNRESET:
          win.addstr(x, verLoc, "Err " + str(ErrorCode) + ": Con RST ]          ")
          refresh() 
   else:
      win.addstr(x, verLoc, response[0]["version"] + " ]")
      memTotal = response[0]["memTotal"]
      memFree  = response[0]["memFree"]
      percentUsed = 100 - round((float(memFree) / float(memTotal)) * 100, 1)
      win.addstr(x, verLoc+24, str(percentUsed) + "% ]" )
      refresh()
项目:pipypd    作者:stressfm    | 项目源码 | 文件源码
def main():
    global HOST, PORT, EOF, MAXTRIES
    global s, tries, loops
    try:
        s.connect((HOST, PORT))
        while True:
            # Measure timing using GPIO4
            risetime = RCtime(4)
            # Send to the connected socket
            # (as we're using UDP, we must
            # send separate messages)
            s.sendall('foo %s%s' % (loops, EOF))
            s.sendall('bar %s%s' % (risetime, EOF))
            # Advance counter
            loops = loops + 1
    except socket.error as err:
        errcode = err[0]
        if errcode==errno.ECONNREFUSED:
            print 'Connection refused by host!'
        elif errcode==errno.ENETDOWN:
            print 'No network connection!'
        elif errcode==errno.ENETUNREACH:
            print 'Network unreachable!'
        elif errcode==errno.ENETRESET:
            print 'Network dropped connection!'
        elif errcode==errno.ECONNRESET:
            print 'Connection reset by peer!'
        elif errcode==errno.EHOSTDOWN:
            print 'Host is down!'
        elif errcode==errno.EHOSTUNREACH:
            print 'No route to host!'
        else:
            print 'Caught: %s!' % err

        if tries >= MAXTRIES:
            GPIO.cleanup()
            s.close()
            print 'No connection. Exiting.'
        else:
            print 'Tried %i of %i times.\nWaiting %is...' % (tries, MAXTRIES, tries/10)
            time.sleep(tries/10)
            tries = tries + 1
            main()
    except KeyboardInterrupt:
        GPIO.cleanup()
        s.close()
        print '%i loops' % loops
项目:eAPI-Scripts    作者:GADify    | 项目源码 | 文件源码
def BaselineEOS(switchNumber):
      location = 28 
      IP = "10.0.0." + str(switchNumber)

      #print "Switch " + str(switchNumber).zfill(2) + ": ", 

      #Connect to Switch via eAPI
      target = "https://" + ScriptUser + ":" + ScriptPass + "@" + IP + "/command-api"
      switch = jsonrpclib.Server( target )

      # capture Connection problem messages
      # Map of erronos is here: http://www.python.org/doc//current/library/errno.html
      try:
         response = switch.runCmds( 1, 
            [ "enable" , 
              "configure",
              "delete EOS*.swi",
              "copy " + FileServer + EOSVer + " flash:",
              "boot system flash:" + EOSVer, 
              "write erase now", 
              "reload now"
            ], "text")

      except KeyboardInterrupt:
         print "Caught Keyboard Interrupt - Exiting"
         sys.exit()

      except socket.error,ERR :
          # Socket Errors
          ErrorCode = ERR[0]
          if ErrorCode == errno.ECONNREFUSED:
             win.addstr(switchNumber, location -15, "        [ Err " + str(ErrorCode) + ": No eAPI ]          ")
             refresh()
          elif ErrorCode == errno.EHOSTUNREACH:
             # Never hit with lower socket timeout
             win.addstr(switchNumber, location -15, "        [ Err " + str(ErrorCode) + ": Pwr off | Aboot ]  ")
             refresh()
          elif ErrorCode == errno.ECONNRESET:
             win.addstr(switchNumber, location -15, "        [ Err " + str(ErrorCode) + ": Con RST ]          ")
             refresh()

      except jsonrpclib.ProtocolError:
         # Capture eAPI errors
         result = jsonrpclib.loads( jsonrpclib.history.response )
         print result["error"]["message"]
         for error in result["error"]["data"][-1]["errors"]:
            print error

      except (xmlrpclib.ProtocolError, xmlrpclib.ResponseError), errormsg:
         # Capture XML Error (usually bad password)
         message = str(errormsg)
         message = message.replace(ScriptUser, "user")
         message = message.replace(ScriptPass, "pass")
         print message

      else:
         win.addstr(switchNumber, location, "[ Done ]")
         refresh()
项目:gazelle-cli    作者:spiritualized    | 项目源码 | 文件源码
def _make_request( self, loc, headers, data = None, retry = True ):
        last_e = None
        utserver_retry = False
        retries = 0
        max_retries = self._retry_max if retry else 1
        try:
            while retries < max_retries or utserver_retry:
                try:
                    self._request.data = data
                    self._connection.request( self._request.get_method( ), self._request.selector + loc, self._request.data, headers )
                    resp = self._connection.getresponse( )
                    if resp.status == 400:
                        last_e = utorrent.uTorrentError( resp.read( ).decode( "utf8" ).strip( ) )
                        # if uTorrent server alpha is bound to the same port as WebUI then it will respond with "invalid request" to the first request in the connection
                        # apparently this is no longer the case, TODO: remove this hack
                        if ( not self._utorrent or type( self._utorrent ) == utorrent.uTorrent.LinuxServer ) and not utserver_retry:
                            utserver_retry = True
                            continue
                        raise last_e
                    elif resp.status == 404 or resp.status == 401:
                        raise utorrent.uTorrentError( "Request {}: {}".format( loc, resp.reason ) )
                    elif resp.status != 200 and resp.status != 206:
                        raise utorrent.uTorrentError( "{}: {}".format( resp.reason, resp.status ) )
                    self._cookies.extract_cookies( resp, self._request )
                    if len( self._cookies ) > 0:
                        self._request.add_header( "Cookie", "; ".join(
                            ["{}={}".format( utorrent._url_quote( c.name ), utorrent._url_quote( c.value ) ) for c in self._cookies] ) )
                    return resp
                # retry when utorrent returns bad data
                except ( http.client.CannotSendRequest, http.client.BadStatusLine ) as e:
                    last_e = e
                    self._connection.close( )
                # name resolution failed
                except socket.gaierror as e:
                    raise utorrent.uTorrentError( e.strerror )
                # socket errors
                except socket.error as e:
                    # retry on timeout
                    if str( e ) == "timed out": # some peculiar handling for timeout error
                        last_e = utorrent.uTorrentError( "Timeout after {} tries".format( max_retries ) )
                        self._connection.close( )
                    # retry after pause on specific windows errors
                    elif e.errno == 10053 or e.errno == 10054:
                        # Windows specific socket errors:
                        # 10053 - An established connection was aborted by the software in your host machine
                        # 10054 - An existing connection was forcibly closed by the remote host
                        last_e = e
                        self._connection.close( )
                        time.sleep( 2 )
                    elif e.errno == errno.ECONNREFUSED or e.errno == errno.ECONNRESET or errno == errno.EHOSTUNREACH:
                        raise utorrent.uTorrentError( e.strerror )
                    else:
                        raise e
                retries += 1
            if last_e:
                raise last_e
        except Exception as e:
            self._connection.close( )
            raise e
        return None