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