convenience.py 5.7 KB

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