PageRenderTime 119ms CodeModel.GetById 83ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/twisted/internet/error.py

https://github.com/jessta/TwistedBot
Python | 455 lines | 409 code | 26 blank | 20 comment | 9 complexity | 8ef10c1465995c99a265806e57a4745f MD5 | raw file
  1# Copyright (c) Twisted Matrix Laboratories.
  2# See LICENSE for details.
  3
  4"""
  5Exceptions and errors for use in twisted.internet modules.
  6"""
  7
  8from __future__ import division, absolute_import
  9
 10import socket
 11
 12from twisted.python import deprecate
 13from twisted.python.versions import Version
 14
 15
 16
 17class BindError(Exception):
 18    """An error occurred binding to an interface"""
 19
 20    def __str__(self):
 21        s = self.__doc__
 22        if self.args:
 23            s = '%s: %s' % (s, ' '.join(self.args))
 24        s = '%s.' % s
 25        return s
 26
 27
 28
 29class CannotListenError(BindError):
 30    """
 31    This gets raised by a call to startListening, when the object cannotstart
 32    listening.
 33
 34    @ivar interface: the interface I tried to listen on
 35    @ivar port: the port I tried to listen on
 36    @ivar socketError: the exception I got when I tried to listen
 37    @type socketError: L{socket.error}
 38    """
 39    def __init__(self, interface, port, socketError):
 40        BindError.__init__(self, interface, port, socketError)
 41        self.interface = interface
 42        self.port = port
 43        self.socketError = socketError
 44
 45    def __str__(self):
 46        iface = self.interface or 'any'
 47        return "Couldn't listen on %s:%s: %s." % (iface, self.port,
 48                                                 self.socketError)
 49
 50
 51
 52class MulticastJoinError(Exception):
 53    """
 54    An attempt to join a multicast group failed.
 55    """
 56
 57
 58
 59class MessageLengthError(Exception):
 60    """Message is too long to send"""
 61
 62    def __str__(self):
 63        s = self.__doc__
 64        if self.args:
 65            s = '%s: %s' % (s, ' '.join(self.args))
 66        s = '%s.' % s
 67        return s
 68
 69
 70
 71class DNSLookupError(IOError):
 72    """DNS lookup failed"""
 73
 74    def __str__(self):
 75        s = self.__doc__
 76        if self.args:
 77            s = '%s: %s' % (s, ' '.join(self.args))
 78        s = '%s.' % s
 79        return s
 80
 81
 82
 83class ConnectInProgressError(Exception):
 84    """A connect operation was started and isn't done yet."""
 85
 86
 87# connection errors
 88
 89class ConnectError(Exception):
 90    """An error occurred while connecting"""
 91
 92    def __init__(self, osError=None, string=""):
 93        self.osError = osError
 94        Exception.__init__(self, string)
 95
 96    def __str__(self):
 97        s = self.__doc__ or self.__class__.__name__
 98        if self.osError:
 99            s = '%s: %s' % (s, self.osError)
100        if self.args[0]:
101            s = '%s: %s' % (s, self.args[0])
102        s = '%s.' % s
103        return s
104
105
106
107class ConnectBindError(ConnectError):
108    """Couldn't bind"""
109
110
111
112class UnknownHostError(ConnectError):
113    """Hostname couldn't be looked up"""
114
115
116
117class NoRouteError(ConnectError):
118    """No route to host"""
119
120
121
122class ConnectionRefusedError(ConnectError):
123    """Connection was refused by other side"""
124
125
126
127class TCPTimedOutError(ConnectError):
128    """TCP connection timed out"""
129
130
131
132class BadFileError(ConnectError):
133    """File used for UNIX socket is no good"""
134
135
136
137class ServiceNameUnknownError(ConnectError):
138    """Service name given as port is unknown"""
139
140
141
142class UserError(ConnectError):
143    """User aborted connection"""
144
145
146
147class TimeoutError(UserError):
148    """User timeout caused connection failure"""
149
150
151
152class SSLError(ConnectError):
153    """An SSL error occurred"""
154
155
156
157class VerifyError(Exception):
158    """Could not verify something that was supposed to be signed.
159    """
160
161
162
163class PeerVerifyError(VerifyError):
164    """The peer rejected our verify error.
165    """
166
167
168
169class CertificateError(Exception):
170    """
171    We did not find a certificate where we expected to find one.
172    """
173
174
175
176try:
177    import errno
178    errnoMapping = {
179        errno.ENETUNREACH: NoRouteError,
180        errno.ECONNREFUSED: ConnectionRefusedError,
181        errno.ETIMEDOUT: TCPTimedOutError,
182    }
183    if hasattr(errno, "WSAECONNREFUSED"):
184        errnoMapping[errno.WSAECONNREFUSED] = ConnectionRefusedError
185        errnoMapping[errno.WSAENETUNREACH] = NoRouteError
186except ImportError:
187    errnoMapping = {}
188
189
190
191def getConnectError(e):
192    """Given a socket exception, return connection error."""
193    if isinstance(e, Exception):
194        args = e.args
195    else:
196        args = e
197    try:
198        number, string = args
199    except ValueError:
200        return ConnectError(string=e)
201
202    if hasattr(socket, 'gaierror') and isinstance(e, socket.gaierror):
203        # Only works in 2.2 in newer. Really that means always; #5978 covers
204        # this and other wierdnesses in this function.
205        klass = UnknownHostError
206    else:
207        klass = errnoMapping.get(number, ConnectError)
208    return klass(number, string)
209
210
211
212class ConnectionClosed(Exception):
213    """
214    Connection was closed, whether cleanly or non-cleanly.
215    """
216
217
218
219class ConnectionLost(ConnectionClosed):
220    """Connection to the other side was lost in a non-clean fashion"""
221
222    def __str__(self):
223        s = self.__doc__
224        if self.args:
225            s = '%s: %s' % (s, ' '.join(self.args))
226        s = '%s.' % s
227        return s
228
229
230
231class ConnectionAborted(ConnectionLost):
232    """
233    Connection was aborted locally, using
234    L{twisted.internet.interfaces.ITCPTransport.abortConnection}.
235
236    @since: 11.1
237    """
238
239
240
241class ConnectionDone(ConnectionClosed):
242    """Connection was closed cleanly"""
243
244    def __str__(self):
245        s = self.__doc__
246        if self.args:
247            s = '%s: %s' % (s, ' '.join(self.args))
248        s = '%s.' % s
249        return s
250
251
252
253class FileDescriptorOverrun(ConnectionLost):
254    """
255    A mis-use of L{IUNIXTransport.sendFileDescriptor} caused the connection to
256    be closed.
257
258    Each file descriptor sent using C{sendFileDescriptor} must be associated
259    with at least one byte sent using L{ITransport.write}.  If at any point
260    fewer bytes have been written than file descriptors have been sent, the
261    connection is closed with this exception.
262    """
263
264
265
266class ConnectionFdescWentAway(ConnectionLost):
267    """Uh""" #TODO
268
269
270
271class AlreadyCalled(ValueError):
272    """Tried to cancel an already-called event"""
273
274    def __str__(self):
275        s = self.__doc__
276        if self.args:
277            s = '%s: %s' % (s, ' '.join(self.args))
278        s = '%s.' % s
279        return s
280
281
282
283class AlreadyCancelled(ValueError):
284    """Tried to cancel an already-cancelled event"""
285
286    def __str__(self):
287        s = self.__doc__
288        if self.args:
289            s = '%s: %s' % (s, ' '.join(self.args))
290        s = '%s.' % s
291        return s
292
293
294
295class PotentialZombieWarning(Warning):
296    """
297    Emitted when L{IReactorProcess.spawnProcess} is called in a way which may
298    result in termination of the created child process not being reported.
299
300    Deprecated in Twisted 10.0.
301    """
302    MESSAGE = (
303        "spawnProcess called, but the SIGCHLD handler is not "
304        "installed. This probably means you have not yet "
305        "called reactor.run, or called "
306        "reactor.run(installSignalHandler=0). You will probably "
307        "never see this process finish, and it may become a "
308        "zombie process.")
309
310deprecate.deprecatedModuleAttribute(
311    Version("Twisted", 10, 0, 0),
312    "There is no longer any potential for zombie process.",
313    __name__,
314    "PotentialZombieWarning")
315
316
317
318class ProcessDone(ConnectionDone):
319    """A process has ended without apparent errors"""
320
321    def __init__(self, status):
322        Exception.__init__(self, "process finished with exit code 0")
323        self.exitCode = 0
324        self.signal = None
325        self.status = status
326
327
328
329class ProcessTerminated(ConnectionLost):
330    """A process has ended with a probable error condition"""
331
332    def __init__(self, exitCode=None, signal=None, status=None):
333        self.exitCode = exitCode
334        self.signal = signal
335        self.status = status
336        s = "process ended"
337        if exitCode is not None: s = s + " with exit code %s" % exitCode
338        if signal is not None: s = s + " by signal %s" % signal
339        Exception.__init__(self, s)
340
341
342
343class ProcessExitedAlready(Exception):
344    """
345    The process has already exited and the operation requested can no longer
346    be performed.
347    """
348
349
350
351class NotConnectingError(RuntimeError):
352    """The Connector was not connecting when it was asked to stop connecting"""
353
354    def __str__(self):
355        s = self.__doc__
356        if self.args:
357            s = '%s: %s' % (s, ' '.join(self.args))
358        s = '%s.' % s
359        return s
360
361
362
363class NotListeningError(RuntimeError):
364    """The Port was not listening when it was asked to stop listening"""
365
366    def __str__(self):
367        s = self.__doc__
368        if self.args:
369            s = '%s: %s' % (s, ' '.join(self.args))
370        s = '%s.' % s
371        return s
372
373
374
375class ReactorNotRunning(RuntimeError):
376    """
377    Error raised when trying to stop a reactor which is not running.
378    """
379
380
381class ReactorNotRestartable(RuntimeError):
382    """
383    Error raised when trying to run a reactor which was stopped.
384    """
385
386
387
388class ReactorAlreadyRunning(RuntimeError):
389    """
390    Error raised when trying to start the reactor multiple times.
391    """
392
393
394class ReactorAlreadyInstalledError(AssertionError):
395    """
396    Could not install reactor because one is already installed.
397    """
398
399
400
401class ConnectingCancelledError(Exception):
402    """
403    An C{Exception} that will be raised when an L{IStreamClientEndpoint} is
404    cancelled before it connects.
405
406    @ivar address: The L{IAddress} that is the destination of the
407        cancelled L{IStreamClientEndpoint}.
408    """
409
410    def __init__(self, address):
411        """
412        @param address: The L{IAddress} that is the destination of the
413            L{IStreamClientEndpoint} that was cancelled.
414        """
415        Exception.__init__(self, address)
416        self.address = address
417
418
419
420class UnsupportedAddressFamily(Exception):
421    """
422    An attempt was made to use a socket with an address family (eg I{AF_INET},
423    I{AF_INET6}, etc) which is not supported by the reactor.
424    """
425
426
427
428class UnsupportedSocketType(Exception):
429    """
430    An attempt was made to use a socket of a type (eg I{SOCK_STREAM},
431    I{SOCK_DGRAM}, etc) which is not supported by the reactor.
432    """
433
434
435class AlreadyListened(Exception):
436    """
437    An attempt was made to listen on a file descriptor which can only be
438    listened on once.
439    """
440
441
442__all__ = [
443    'BindError', 'CannotListenError', 'MulticastJoinError',
444    'MessageLengthError', 'DNSLookupError', 'ConnectInProgressError',
445    'ConnectError', 'ConnectBindError', 'UnknownHostError', 'NoRouteError',
446    'ConnectionRefusedError', 'TCPTimedOutError', 'BadFileError',
447    'ServiceNameUnknownError', 'UserError', 'TimeoutError', 'SSLError',
448    'VerifyError', 'PeerVerifyError', 'CertificateError',
449    'getConnectError', 'ConnectionClosed', 'ConnectionLost',
450    'ConnectionDone', 'ConnectionFdescWentAway', 'AlreadyCalled',
451    'AlreadyCancelled', 'PotentialZombieWarning', 'ProcessDone',
452    'ProcessTerminated', 'ProcessExitedAlready', 'NotConnectingError',
453    'NotListeningError', 'ReactorNotRunning', 'ReactorAlreadyRunning',
454    'ReactorAlreadyInstalledError', 'ConnectingCancelledError',
455    'UnsupportedAddressFamily', 'UnsupportedSocketType']