convenience.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import sys
  2. from eventlet import greenio
  3. from eventlet import greenthread
  4. from eventlet import greenpool
  5. from eventlet.green import socket
  6. from eventlet.support import greenlets as greenlet
  7. def connect(addr, family=socket.AF_INET, bind=None):
  8. """Convenience function for opening client sockets.
  9. :param addr: Address of the server to connect to. For TCP sockets, this is a (host, port) tuple.
  10. :param family: Socket family, optional. See :mod:`socket` documentation for available families.
  11. :param bind: Local address to bind to, optional.
  12. :return: The connected green socket object.
  13. """
  14. sock = socket.socket(family, socket.SOCK_STREAM)
  15. if bind is not None:
  16. sock.bind(bind)
  17. sock.connect(addr)
  18. return sock
  19. def listen(addr, family=socket.AF_INET, backlog=50):
  20. """Convenience function for opening server sockets. This
  21. socket can be used in :func:`~eventlet.serve` or a custom ``accept()`` loop.
  22. Sets SO_REUSEADDR on the socket to save on annoyance.
  23. :param addr: Address to listen on. For TCP sockets, this is a (host, port) tuple.
  24. :param family: Socket family, optional. See :mod:`socket` documentation for available families.
  25. :param backlog: The maximum number of queued connections. Should be at least 1; the maximum value is system-dependent.
  26. :return: The listening green socket object.
  27. """
  28. sock = socket.socket(family, socket.SOCK_STREAM)
  29. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  30. sock.bind(addr)
  31. sock.listen(backlog)
  32. return sock
  33. class StopServe(Exception):
  34. """Exception class used for quitting :func:`~eventlet.serve` gracefully."""
  35. pass
  36. def _stop_checker(t, server_gt, conn):
  37. try:
  38. try:
  39. t.wait()
  40. finally:
  41. conn.close()
  42. except greenlet.GreenletExit:
  43. pass
  44. except Exception:
  45. greenthread.kill(server_gt, *sys.exc_info())
  46. def serve(sock, handle, concurrency=1000):
  47. """Runs a server on the supplied socket. Calls the function *handle* in a
  48. separate greenthread for every incoming client connection. *handle* takes
  49. two arguments: the client socket object, and the client address::
  50. def myhandle(client_sock, client_addr):
  51. print "client connected", client_addr
  52. eventlet.serve(eventlet.listen(('127.0.0.1', 9999)), myhandle)
  53. Returning from *handle* closes the client socket.
  54. :func:`serve` blocks the calling greenthread; it won't return until
  55. the server completes. If you desire an immediate return,
  56. spawn a new greenthread for :func:`serve`.
  57. Any uncaught exceptions raised in *handle* are raised as exceptions
  58. from :func:`serve`, terminating the server, so be sure to be aware of the
  59. exceptions your application can raise. The return value of *handle* is
  60. ignored.
  61. Raise a :class:`~eventlet.StopServe` exception to gracefully terminate the
  62. server -- that's the only way to get the server() function to return rather
  63. than raise.
  64. The value in *concurrency* controls the maximum number of
  65. greenthreads that will be open at any time handling requests. When
  66. the server hits the concurrency limit, it stops accepting new
  67. connections until the existing ones complete.
  68. """
  69. pool = greenpool.GreenPool(concurrency)
  70. server_gt = greenthread.getcurrent()
  71. while True:
  72. try:
  73. conn, addr = sock.accept()
  74. gt = pool.spawn(handle, conn, addr)
  75. gt.link(_stop_checker, server_gt, conn)
  76. conn, addr, gt = None, None, None
  77. except StopServe:
  78. return
  79. def wrap_ssl(sock, *a, **kw):
  80. """Convenience function for converting a regular socket into an
  81. SSL socket. Has the same interface as :func:`ssl.wrap_socket`,
  82. but works on 2.5 or earlier, using PyOpenSSL (though note that it
  83. ignores the *cert_reqs*, *ssl_version*, *ca_certs*,
  84. *do_handshake_on_connect*, and *suppress_ragged_eofs* arguments
  85. when using PyOpenSSL).
  86. The preferred idiom is to call wrap_ssl directly on the creation
  87. method, e.g., ``wrap_ssl(connect(addr))`` or
  88. ``wrap_ssl(listen(addr), server_side=True)``. This way there is
  89. no "naked" socket sitting around to accidentally corrupt the SSL
  90. session.
  91. :return Green SSL object.
  92. """
  93. return wrap_ssl_impl(sock, *a, **kw)
  94. try:
  95. from eventlet.green import ssl
  96. wrap_ssl_impl = ssl.wrap_socket
  97. except ImportError:
  98. # < 2.6, trying PyOpenSSL
  99. try:
  100. from eventlet.green.OpenSSL import SSL
  101. def wrap_ssl_impl(sock, keyfile=None, certfile=None, server_side=False,
  102. cert_reqs=None, ssl_version=None, ca_certs=None,
  103. do_handshake_on_connect=True,
  104. suppress_ragged_eofs=True, ciphers=None):
  105. # theoretically the ssl_version could be respected in this
  106. # next line
  107. context = SSL.Context(SSL.SSLv23_METHOD)
  108. if certfile is not None:
  109. context.use_certificate_file(certfile)
  110. if keyfile is not None:
  111. context.use_privatekey_file(keyfile)
  112. context.set_verify(SSL.VERIFY_NONE, lambda *x: True)
  113. connection = SSL.Connection(context, sock)
  114. if server_side:
  115. connection.set_accept_state()
  116. else:
  117. connection.set_connect_state()
  118. return connection
  119. except ImportError:
  120. def wrap_ssl_impl(*a, **kw):
  121. raise ImportError("To use SSL with Eventlet, "
  122. "you must install PyOpenSSL or use Python 2.6 or later.")