PageRenderTime 55ms CodeModel.GetById 27ms RepoModel.GetById 0ms 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. Exceptions and errors for use in twisted.internet modules.
  5. """
  6. from __future__ import division, absolute_import
  7. import socket
  8. from twisted.python import deprecate
  9. from twisted.python.versions import Version
  10. class BindError(Exception):
  11. """An error occurred binding to an interface"""
  12. def __str__(self):
  13. s = self.__doc__
  14. if self.args:
  15. s = '%s: %s' % (s, ' '.join(self.args))
  16. s = '%s.' % s
  17. return s
  18. class CannotListenError(BindError):
  19. """
  20. This gets raised by a call to startListening, when the object cannotstart
  21. listening.
  22. @ivar interface: the interface I tried to listen on
  23. @ivar port: the port I tried to listen on
  24. @ivar socketError: the exception I got when I tried to listen
  25. @type socketError: L{socket.error}
  26. """
  27. def __init__(self, interface, port, socketError):
  28. BindError.__init__(self, interface, port, socketError)
  29. self.interface = interface
  30. self.port = port
  31. self.socketError = socketError
  32. def __str__(self):
  33. iface = self.interface or 'any'
  34. return "Couldn't listen on %s:%s: %s." % (iface, self.port,
  35. self.socketError)
  36. class MulticastJoinError(Exception):
  37. """
  38. An attempt to join a multicast group failed.
  39. """
  40. class MessageLengthError(Exception):
  41. """Message is too long to send"""
  42. def __str__(self):
  43. s = self.__doc__
  44. if self.args:
  45. s = '%s: %s' % (s, ' '.join(self.args))
  46. s = '%s.' % s
  47. return s
  48. class DNSLookupError(IOError):
  49. """DNS lookup failed"""
  50. def __str__(self):
  51. s = self.__doc__
  52. if self.args:
  53. s = '%s: %s' % (s, ' '.join(self.args))
  54. s = '%s.' % s
  55. return s
  56. class ConnectInProgressError(Exception):
  57. """A connect operation was started and isn't done yet."""
  58. # connection errors
  59. class ConnectError(Exception):
  60. """An error occurred while connecting"""
  61. def __init__(self, osError=None, string=""):
  62. self.osError = osError
  63. Exception.__init__(self, string)
  64. def __str__(self):
  65. s = self.__doc__ or self.__class__.__name__
  66. if self.osError:
  67. s = '%s: %s' % (s, self.osError)
  68. if self.args[0]:
  69. s = '%s: %s' % (s, self.args[0])
  70. s = '%s.' % s
  71. return s
  72. class ConnectBindError(ConnectError):
  73. """Couldn't bind"""
  74. class UnknownHostError(ConnectError):
  75. """Hostname couldn't be looked up"""
  76. class NoRouteError(ConnectError):
  77. """No route to host"""
  78. class ConnectionRefusedError(ConnectError):
  79. """Connection was refused by other side"""
  80. class TCPTimedOutError(ConnectError):
  81. """TCP connection timed out"""
  82. class BadFileError(ConnectError):
  83. """File used for UNIX socket is no good"""
  84. class ServiceNameUnknownError(ConnectError):
  85. """Service name given as port is unknown"""
  86. class UserError(ConnectError):
  87. """User aborted connection"""
  88. class TimeoutError(UserError):
  89. """User timeout caused connection failure"""
  90. class SSLError(ConnectError):
  91. """An SSL error occurred"""
  92. class VerifyError(Exception):
  93. """Could not verify something that was supposed to be signed.
  94. """
  95. class PeerVerifyError(VerifyError):
  96. """The peer rejected our verify error.
  97. """
  98. class CertificateError(Exception):
  99. """
  100. We did not find a certificate where we expected to find one.
  101. """
  102. try:
  103. import errno
  104. errnoMapping = {
  105. errno.ENETUNREACH: NoRouteError,
  106. errno.ECONNREFUSED: ConnectionRefusedError,
  107. errno.ETIMEDOUT: TCPTimedOutError,
  108. }
  109. if hasattr(errno, "WSAECONNREFUSED"):
  110. errnoMapping[errno.WSAECONNREFUSED] = ConnectionRefusedError
  111. errnoMapping[errno.WSAENETUNREACH] = NoRouteError
  112. except ImportError:
  113. errnoMapping = {}
  114. def getConnectError(e):
  115. """Given a socket exception, return connection error."""
  116. if isinstance(e, Exception):
  117. args = e.args
  118. else:
  119. args = e
  120. try:
  121. number, string = args
  122. except ValueError:
  123. return ConnectError(string=e)
  124. if hasattr(socket, 'gaierror') and isinstance(e, socket.gaierror):
  125. # Only works in 2.2 in newer. Really that means always; #5978 covers
  126. # this and other wierdnesses in this function.
  127. klass = UnknownHostError
  128. else:
  129. klass = errnoMapping.get(number, ConnectError)
  130. return klass(number, string)
  131. class ConnectionClosed(Exception):
  132. """
  133. Connection was closed, whether cleanly or non-cleanly.
  134. """
  135. class ConnectionLost(ConnectionClosed):
  136. """Connection to the other side was lost in a non-clean fashion"""
  137. def __str__(self):
  138. s = self.__doc__
  139. if self.args:
  140. s = '%s: %s' % (s, ' '.join(self.args))
  141. s = '%s.' % s
  142. return s
  143. class ConnectionAborted(ConnectionLost):
  144. """
  145. Connection was aborted locally, using
  146. L{twisted.internet.interfaces.ITCPTransport.abortConnection}.
  147. @since: 11.1
  148. """
  149. class ConnectionDone(ConnectionClosed):
  150. """Connection was closed cleanly"""
  151. def __str__(self):
  152. s = self.__doc__
  153. if self.args:
  154. s = '%s: %s' % (s, ' '.join(self.args))
  155. s = '%s.' % s
  156. return s
  157. class FileDescriptorOverrun(ConnectionLost):
  158. """
  159. A mis-use of L{IUNIXTransport.sendFileDescriptor} caused the connection to
  160. be closed.
  161. Each file descriptor sent using C{sendFileDescriptor} must be associated
  162. with at least one byte sent using L{ITransport.write}. If at any point
  163. fewer bytes have been written than file descriptors have been sent, the
  164. connection is closed with this exception.
  165. """
  166. class ConnectionFdescWentAway(ConnectionLost):
  167. """Uh""" #TODO
  168. class AlreadyCalled(ValueError):
  169. """Tried to cancel an already-called event"""
  170. def __str__(self):
  171. s = self.__doc__
  172. if self.args:
  173. s = '%s: %s' % (s, ' '.join(self.args))
  174. s = '%s.' % s
  175. return s
  176. class AlreadyCancelled(ValueError):
  177. """Tried to cancel an already-cancelled event"""
  178. def __str__(self):
  179. s = self.__doc__
  180. if self.args:
  181. s = '%s: %s' % (s, ' '.join(self.args))
  182. s = '%s.' % s
  183. return s
  184. class PotentialZombieWarning(Warning):
  185. """
  186. Emitted when L{IReactorProcess.spawnProcess} is called in a way which may
  187. result in termination of the created child process not being reported.
  188. Deprecated in Twisted 10.0.
  189. """
  190. MESSAGE = (
  191. "spawnProcess called, but the SIGCHLD handler is not "
  192. "installed. This probably means you have not yet "
  193. "called reactor.run, or called "
  194. "reactor.run(installSignalHandler=0). You will probably "
  195. "never see this process finish, and it may become a "
  196. "zombie process.")
  197. deprecate.deprecatedModuleAttribute(
  198. Version("Twisted", 10, 0, 0),
  199. "There is no longer any potential for zombie process.",
  200. __name__,
  201. "PotentialZombieWarning")
  202. class ProcessDone(ConnectionDone):
  203. """A process has ended without apparent errors"""
  204. def __init__(self, status):
  205. Exception.__init__(self, "process finished with exit code 0")
  206. self.exitCode = 0
  207. self.signal = None
  208. self.status = status
  209. class ProcessTerminated(ConnectionLost):
  210. """A process has ended with a probable error condition"""
  211. def __init__(self, exitCode=None, signal=None, status=None):
  212. self.exitCode = exitCode
  213. self.signal = signal
  214. self.status = status
  215. s = "process ended"
  216. if exitCode is not None: s = s + " with exit code %s" % exitCode
  217. if signal is not None: s = s + " by signal %s" % signal
  218. Exception.__init__(self, s)
  219. class ProcessExitedAlready(Exception):
  220. """
  221. The process has already exited and the operation requested can no longer
  222. be performed.
  223. """
  224. class NotConnectingError(RuntimeError):
  225. """The Connector was not connecting when it was asked to stop connecting"""
  226. def __str__(self):
  227. s = self.__doc__
  228. if self.args:
  229. s = '%s: %s' % (s, ' '.join(self.args))
  230. s = '%s.' % s
  231. return s
  232. class NotListeningError(RuntimeError):
  233. """The Port was not listening when it was asked to stop listening"""
  234. def __str__(self):
  235. s = self.__doc__
  236. if self.args:
  237. s = '%s: %s' % (s, ' '.join(self.args))
  238. s = '%s.' % s
  239. return s
  240. class ReactorNotRunning(RuntimeError):
  241. """
  242. Error raised when trying to stop a reactor which is not running.
  243. """
  244. class ReactorNotRestartable(RuntimeError):
  245. """
  246. Error raised when trying to run a reactor which was stopped.
  247. """
  248. class ReactorAlreadyRunning(RuntimeError):
  249. """
  250. Error raised when trying to start the reactor multiple times.
  251. """
  252. class ReactorAlreadyInstalledError(AssertionError):
  253. """
  254. Could not install reactor because one is already installed.
  255. """
  256. class ConnectingCancelledError(Exception):
  257. """
  258. An C{Exception} that will be raised when an L{IStreamClientEndpoint} is
  259. cancelled before it connects.
  260. @ivar address: The L{IAddress} that is the destination of the
  261. cancelled L{IStreamClientEndpoint}.
  262. """
  263. def __init__(self, address):
  264. """
  265. @param address: The L{IAddress} that is the destination of the
  266. L{IStreamClientEndpoint} that was cancelled.
  267. """
  268. Exception.__init__(self, address)
  269. self.address = address
  270. class UnsupportedAddressFamily(Exception):
  271. """
  272. An attempt was made to use a socket with an address family (eg I{AF_INET},
  273. I{AF_INET6}, etc) which is not supported by the reactor.
  274. """
  275. class UnsupportedSocketType(Exception):
  276. """
  277. An attempt was made to use a socket of a type (eg I{SOCK_STREAM},
  278. I{SOCK_DGRAM}, etc) which is not supported by the reactor.
  279. """
  280. class AlreadyListened(Exception):
  281. """
  282. An attempt was made to listen on a file descriptor which can only be
  283. listened on once.
  284. """
  285. __all__ = [
  286. 'BindError', 'CannotListenError', 'MulticastJoinError',
  287. 'MessageLengthError', 'DNSLookupError', 'ConnectInProgressError',
  288. 'ConnectError', 'ConnectBindError', 'UnknownHostError', 'NoRouteError',
  289. 'ConnectionRefusedError', 'TCPTimedOutError', 'BadFileError',
  290. 'ServiceNameUnknownError', 'UserError', 'TimeoutError', 'SSLError',
  291. 'VerifyError', 'PeerVerifyError', 'CertificateError',
  292. 'getConnectError', 'ConnectionClosed', 'ConnectionLost',
  293. 'ConnectionDone', 'ConnectionFdescWentAway', 'AlreadyCalled',
  294. 'AlreadyCancelled', 'PotentialZombieWarning', 'ProcessDone',
  295. 'ProcessTerminated', 'ProcessExitedAlready', 'NotConnectingError',
  296. 'NotListeningError', 'ReactorNotRunning', 'ReactorAlreadyRunning',
  297. 'ReactorAlreadyInstalledError', 'ConnectingCancelledError',
  298. 'UnsupportedAddressFamily', 'UnsupportedSocketType']