test
CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
HTTP.py
Go to the documentation of this file.
1 from cStringIO import StringIO
2 from pycurl import *
3 
5  """Manager of multiple concurrent or overlapping HTTP requests.
6 
7 This is a utility class acting as a pump of several overlapping
8 HTTP requests against any number of HTTP or HTTPS servers. It
9 uses a configurable number of simultaneous connections, ten by
10 default. The actual connection layer is handled using curl, and
11 the client classes need to aware of this to a limited degree.
12 
13 The client supplies optional callback methods for initialising,
14 responding and handling errors on connections. At the very least
15 the request response callback should be defined.
16 
17 This class is not designed for multi-threaded use. It employs
18 overlapping requests, but in a single thread. Only one thread
19 at a time should be calling `process()`; several threads may
20 call `.put()` provided the caller uses a mutex so that only one
21 thread calls into the method at a time."""
22 
23  def __init__(self, num_connections = 10, ssl_opts = None,
24  user_agent = None, request_headers = None,
25  request_init = None, request_respond = None,
26  request_error = None, handle_init = None):
27  """Initialise the request manager. The arguments are:
28 
29 :arg num_connections: maximum number of simultaneous connections.
30 :arg ssl_opts: optional SSLOptions (Monitoring.Core.X509) for SSL
31 X509 parametre values, e.g. for X509 client authentication.
32 :arg user_agent: sets user agent identification string if defined.
33 :arg request_headers: if defined, specifies list of additional HTTP
34 request headers to be added to each request.
35 :arg request_init: optional callback to initialise requests; the
36 default assumes each task is a URL to access and sets the `URL`
37 property on the curl object to the task value.
38 :arg request_respond: callback for handling responses; at the very
39 minimum this should be defined as the default one does nothing.
40 :arg request_error: callback for handling connection errors; the
41 default one raises a RuntimeException.
42 :arg handle_init: callback for customising connection handles at
43 creation time; the callback will be invoked for each connection
44 object as it's created and queued to the idle connection list."""
45  self.request_respond = request_respond or self._request_respond
46  self.request_error = request_error or self._request_error
47  self.request_init = request_init or self._request_init
48  self.cm = CurlMulti()
49  self.handles = [Curl() for i in xrange(0, num_connections)]
50  self.free = [c for c in self.handles]
51  self.queue = []
52 
53  for c in self.handles:
54  c.buffer = None
55  c.setopt(NOSIGNAL, 1)
56  c.setopt(TIMEOUT, 300)
57  c.setopt(CONNECTTIMEOUT, 30)
58  c.setopt(FOLLOWLOCATION, 1)
59  c.setopt(MAXREDIRS, 5)
60  if user_agent:
61  c.setopt(USERAGENT, user_agent)
62  if ssl_opts:
63  c.setopt(CAPATH, ssl_opts.ca_path)
64  c.setopt(SSLCERT, ssl_opts.cert_file)
65  c.setopt(SSLKEY, ssl_opts.key_file)
66  if ssl_opts.key_pass:
67  c.setopt(SSLKEYPASSWD, ssl_opts.key_pass)
68  if request_headers:
69  c.setopt(HTTPHEADER, request_headers)
70  if handle_init:
71  handle_init(c)
72 
73  def _request_init(self, c, url):
74  """Default request initialisation callback."""
75  c.setopt(URL, url)
76 
77  def _request_error(self, c, task, errmsg, errno):
78  """Default request error callback."""
79  raise RuntimeError((task, errmsg, errno))
80 
81  def _request_respond(self, *args):
82  """Default request response callback."""
83  pass
84 
85  def put(self, task):
86  """Add a new task. The task object should be a tuple and is
87 passed to ``request_init`` callback passed to the constructor."""
88  self.queue.append(task)
89 
90  def process(self):
91  """Process pending requests until none are left.
92 
93 This method processes all requests queued with `.put()` until they
94 have been fully processed. It calls the ``request_respond`` callback
95 for all successfully completed requests, and ``request_error`` for
96 all failed ones.
97 
98 Any new requests added by callbacks by invoking ``put()`` are also
99 processed before returning."""
100  npending = 0
101  while self.queue or npending:
102  while self.queue and self.free:
103  c = self.free.pop()
104  c.task = self.queue.pop(0)
105  c.buffer = b = StringIO()
106  c.setopt(WRITEFUNCTION, b.write)
107  self.request_init(c, *c.task)
108  self.cm.add_handle(c)
109  npending += 1
110 
111  while True:
112  ret, nhandles = self.cm.perform()
113  if ret != E_CALL_MULTI_PERFORM:
114  break
115 
116  while True:
117  numq, ok, err = self.cm.info_read()
118 
119  for c in ok:
120  assert npending > 0
121  self.cm.remove_handle(c)
122  self.request_respond(c)
123  c.buffer = None
124  self.free.append(c)
125  npending -= 1
126 
127  for c, errno, errmsg in err:
128  assert npending > 0
129  self.cm.remove_handle(c)
130  self.free.append(c)
131  npending -= 1
132  self.request_error(c, c.task, errmsg, errno)
133 
134  if numq == 0:
135  break
136 
137  self.cm.select(1.)
138 
def _request_error
Definition: HTTP.py:77
def _request_respond
Definition: HTTP.py:81
def _request_init
Definition: HTTP.py:73