def logOn(self, chatui):
"""Log on to this account.
Takes care to not start a connection if a connection is
already in progress. You will need to implement
L{_startLogOn} for this to work, and it would be a good idea
to override L{_loginFailed} too.
@returntype: Deferred L{interfaces.IClient}
"""
if (not self._isConnecting) and (not self._isOnline):
self._isConnecting = 1
d = self._startLogOn(chatui)
d.addCallback(self._cb_logOn)
# if chatui is not None:
# (I don't particularly like having to pass chatUI to this function,
# but we haven't factored it out yet.)
d.addCallback(chatui.registerAccountClient)
d.addErrback(self._loginFailed)
return d
else:
raise error.ConnectError("Connection in progress")
python类ConnectError()的实例源码
def logOn(self, chatui):
"""Log on to this account.
Takes care to not start a connection if a connection is
already in progress. You will need to implement
L{_startLogOn} for this to work, and it would be a good idea
to override L{_loginFailed} too.
@returntype: Deferred L{interfaces.IClient}
"""
if (not self._isConnecting) and (not self._isOnline):
self._isConnecting = 1
d = self._startLogOn(chatui)
d.addCallback(self._cb_logOn)
# if chatui is not None:
# (I don't particularly like having to pass chatUI to this function,
# but we haven't factored it out yet.)
d.addCallback(chatui.registerAccountClient)
d.addErrback(self._loginFailed)
return d
else:
raise error.ConnectError("Connection in progress")
def make_restconf_connection(self, get_timeout=None):
client = self._rest_client
if client is None:
client = AdtranRestClient(self.ip_address,
self.rest_port,
self.rest_username,
self.rest_password,
self.timeout)
timeout = get_timeout or self.timeout
try:
request = client.request('GET', self.HELLO_URI, name='hello', timeout=timeout)
results = yield request
if isinstance(results, dict) and 'module-info' in results:
self._rest_client = client
returnValue(results)
else:
from twisted.internet.error import ConnectError
self._rest_client = None
raise ConnectError(string='Results received but unexpected data type or contents')
except Exception:
self._rest_client = None
raise
def logOn(self, chatui):
"""Log on to this account.
Takes care to not start a connection if a connection is
already in progress. You will need to implement
L{_startLogOn} for this to work, and it would be a good idea
to override L{_loginFailed} too.
@returntype: Deferred L{interfaces.IClient}
"""
if (not self._isConnecting) and (not self._isOnline):
self._isConnecting = 1
d = self._startLogOn(chatui)
d.addCallback(self._cb_logOn)
# if chatui is not None:
# (I don't particularly like having to pass chatUI to this function,
# but we haven't factored it out yet.)
d.addCallback(chatui.registerAccountClient)
d.addErrback(self._loginFailed)
return d
else:
raise error.ConnectError("Connection in progress")
def test_clientConnectionFailed(self):
"""
Calls to L{_WrappingFactory.clientConnectionLost} should errback the
L{_WrappingFactory._onConnection} L{Deferred}
"""
wf = endpoints._WrappingFactory(TestFactory())
expectedFailure = Failure(error.ConnectError(string="fail"))
wf.clientConnectionFailed(None, expectedFailure)
errors = []
def gotError(f):
errors.append(f)
wf._onConnection.addErrback(gotError)
self.assertEqual(errors, [expectedFailure])
def test_endpointConnectFailure(self):
"""
If an endpoint tries to connect to a non-listening port it gets
a C{ConnectError} failure.
"""
expectedError = error.ConnectError(string="Connection Failed")
mreactor = RaisingMemoryReactor(connectException=expectedError)
clientFactory = object()
ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
mreactor, clientFactory)
d = ep.connect(clientFactory)
receivedExceptions = []
def checkFailure(f):
receivedExceptions.append(f.value)
d.addErrback(checkFailure)
self.assertEqual(receivedExceptions, [expectedError])
def test_endpointConnectFailureAfterIteration(self):
"""
If a connection attempt initiated by
L{HostnameEndpoint.connect} fails only after
L{HostnameEndpoint} has exhausted the list of possible server
addresses, the returned L{Deferred} will fail with
C{ConnectError}.
"""
expectedError = error.ConnectError(string="Connection Failed")
mreactor = MemoryReactor()
clientFactory = object()
ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
mreactor, clientFactory)
d = ep.connect(clientFactory)
mreactor.advance(0.3)
host, port, factory, timeout, bindAddress = mreactor.tcpClients[0]
factory.clientConnectionFailed(mreactor.connectors[0], expectedError)
self.assertEqual(self.failureResultOf(d).value, expectedError)
self.assertEqual([], mreactor.getDelayedCalls())
def test_endpointConnectFailure(self):
"""
If an endpoint tries to connect to a non-listening port it gets
a C{ConnectError} failure.
"""
expectedError = error.ConnectError(string="Connection Failed")
mreactor = RaisingMemoryReactorWithClock(connectException=expectedError)
clientFactory = object()
ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
mreactor, clientFactory)
d = ep.connect(clientFactory)
mreactor.advance(0.3)
self.assertEqual(self.failureResultOf(d).value, expectedError)
self.assertEqual([], mreactor.getDelayedCalls())
def test_alreadyConnecting(self):
"""
Test that it can fail sensibly when someone tried to connect before
we did.
"""
account = self.makeAccount()
ui = self.makeUI()
account.logOn(ui)
self.assertRaises(error.ConnectError, account.logOn, ui)
def connect_unix(self, path, factory):
server = self._socket_paths.get(path)
from landscape.lib.tests.test_amp import FakeConnector
if server:
connector = FakeConnector(factory, server)
connector.connect()
else:
connector = object() # Fake connector
failure = Failure(ConnectError("No such file or directory"))
factory.clientConnectionFailed(connector, failure)
return connector
def test_get_remote_object_failure(self):
"""
If the factory fails to establish a connection the deferreds returned
by C{getRemoteObject} will fail.
"""
deferred = self.factory.getRemoteObject()
self.factory.continueTrying = False # Don't retry
self.factory.clientConnectionFailed(None, Failure(ConnectError()))
self.failureResultOf(deferred).trap(ConnectError)
def test_connect_with_max_retries(self):
"""
If L{MethodCallClientFactory.maxRetries} is set, then the factory
will give up trying to connect after that amout of times.
"""
self.port.stopListening()
self.client.maxRetries = 0
reactor.connectUNIX(self.socket, self.client)
yield self.assertFailure(self.client.getRemoteObject(), ConnectError)
def test_connect_with_max_retries(self):
"""
If C{max_retries} is passed to L{RemoteObjectConnector.connect},
then it will give up trying to connect after that amount of times.
"""
self.log_helper.ignore_errors("Error while connecting to test")
deferred = self.connector.connect(max_retries=2)
self.assertNoResult(deferred)
return
self.failureResultOf(deferred).trap(ConnectError)
def test_connect_logs_errors(self):
"""
Connection errors are logged.
"""
self.log_helper.ignore_errors("Error while connecting to test")
def assert_log(ignored):
self.assertIn("Error while connecting to test",
self.logfile.getvalue())
result = self.connector.connect(max_retries=0)
self.assertFailure(result, ConnectError)
return result.addCallback(assert_log)
def test_alreadyConnecting(self):
"""
Test that it can fail sensibly when someone tried to connect before
we did.
"""
account = self.makeAccount()
ui = self.makeUI()
account.logOn(ui)
self.assertRaises(error.ConnectError, account.logOn, ui)
def test_alreadyConnecting(self):
"""
Test that it can fail sensibly when someone tried to connect before
we did.
"""
account = self.makeAccount()
ui = self.makeUI()
account.logOn(ui)
self.assertRaises(error.ConnectError, account.logOn, ui)
def connectionLost(self, reason):
"""
Invoked by lower-level logic when it's time to clean the socket up.
Depending on the state of the connection, either inform the attached
L{Connector} that the connection attempt has failed, or inform the
connected L{IProtocol} that the established connection has been lost.
@param reason: the reason that the connection was terminated
@type reason: L{Failure}
"""
if not self.connected:
self.failIfNotConnected(error.ConnectError(string=reason))
else:
self._commonConnection.connectionLost(self, reason)
self.connector.connectionLost(reason)
def test_nonTuple(self):
"""
L{error.getConnectError} converts to a L{error.ConnectError} given
an argument that cannot be unpacked.
"""
e = Exception()
result = error.getConnectError(e)
self.assertCorrectException(None, e, result, error.ConnectError)
def handle_failure(self, failure, request):
# type: (Failure, Request) -> None
"""
Handle a failure. For connection errors, we do nothing - no chance to send anything. For client errors, we show
an informative error message. For server errors, we show a generic message, and log the error.
:param failure: Failure instance
:param request: Twisted request
"""
exception = failure.value # type: Exception
# Connection errors. This is business as usual on the Internet. We do nothing - we can't reach the client to
# tell them about it anyways, and it's not worth logging.
if any(isinstance(exception, exc_type) for exc_type in {
CancelledError, ConnectError, ConnectionDone, ConnectionLost
}):
return
# Client error - we expose the error message to the client, but don't log anything.
if isinstance(exception, Error):
web_error = exception # type: Error
status_code = int(web_error.status)
if 400 <= status_code < 500:
message = str(exception)
self.send_error(status_code, message, request)
return
# Server error - we don't let the client see any part of the exception, since it might expose internals. But we
# totally need to log it.
error_msg = str(exception)
context = "{} @ {} ({})".format(type(exception).__name__, request.uri.decode(), error_msg)
log.err(exception, context)
self.send_error(INTERNAL_SERVER_ERROR, "Server-side error", request)
def onReceiveFail(self, failure):
e = failure.value
if isinstance(e, defer.CancelledError):
return
retry, level, msg = (False, None, None) # NOT USED.
self._errorMsgCheck(e.message)
# Handle errors on which we should retry the receive.
if 'OperationTimeout' in e.message:
retry, level, msg = (
True,
logging.DEBUG,
"OperationTimeout on {}"
.format(self.config.id))
elif isinstance(e, ConnectError):
retry, level, msg = (
isinstance(e, TimeoutError),
logging.WARN,
"network error on {}: {}"
.format(self.config.id, e.message or 'timeout'))
if isinstance(e, TimeoutError):
self.network_failures += 1
# Handle errors on which we should start over.
else:
retry, level, msg = (
False,
logging.WARN,
"receive failure on {}: {}"
.format(self.config.id, e))
if self.data_deferred and not self.data_deferred.called:
self.data_deferred.errback(failure)
LOG.log(level, msg)
if self.network_failures >= MAX_NETWORK_FAILURES:
yield self.stop()
self.reset()
if retry:
self.receive()
else:
yield self.restart()
defer.returnValue(None)