| 1 |
#! /usr/bin/env python |
| 2 |
# vi:ts=4:et |
| 3 |
|
| 4 |
# Retrieves a single URL using the CurlMulti.socket_action calls, using |
| 5 |
# select as the I/O polling mechanism: |
| 6 |
# |
| 7 |
# First, create a Multi object, and set socket and timer callbacks on it. |
| 8 |
# Observed side effect: this causes the timer callback to be immediately |
| 9 |
# invoked with the zero value for the timeout. |
| 10 |
# |
| 11 |
# The timer callback is very simple - it stores the timeout value passed |
| 12 |
# into it in the global state for future use by the select calls that |
| 13 |
# we will be making. |
| 14 |
# |
| 15 |
# The socket callback is more complicated. Its job is to add and remove |
| 16 |
# socket handles to/from the data structure that we use for waiting for |
| 17 |
# activity on them. The callback is invoked with a socket handle and the |
| 18 |
# needed action (add for reading, add for writing or remove). |
| 19 |
# Since this script utilizes the select call for waiting for activity, |
| 20 |
# the socket callback updates the list of sockets which we should be |
| 21 |
# polling for readability and the list that we should be polling for |
| 22 |
# writability, which are then passed to the select call (and both of the |
| 23 |
# sets are passed as the sockets to wait for errors/exceptions on). |
| 24 |
# |
| 25 |
# Next, create a Curl object (mapping to a libcurl easy handle), set the URL |
| 26 |
# we are going to retrieve as well as any transfer options. This script sets |
| 27 |
# the timeout to 5 seconds to be able to test failing transfers easily. |
| 28 |
# |
| 29 |
# Add the Curl object to the Multi object. |
| 30 |
# |
| 31 |
# Invoke Multi.socket_action to start the retrieval operation. |
| 32 |
# Observed side effect: this causes the timer callback to be invoked |
| 33 |
# with a greater than zero value for the timeout. |
| 34 |
# |
| 35 |
# By now we should have initialized our own state, which this script does |
| 36 |
# prior to invoking any libcurl functions. Importantly, the state includes |
| 37 |
# the timeout value that was communicated to us by libcurl. |
| 38 |
# |
| 39 |
# Run a loop which waits for activity on any of the sockets used by libcurl. |
| 40 |
# The sockets are set that the socket callback has produced as of the |
| 41 |
# present moment; the timeout is the most recent timeout value received by |
| 42 |
# the timer callback. |
| 43 |
# |
| 44 |
# Importantly, the loop should not simply sleep for the entire |
| 45 |
# timeout interval, as that would cause the transfer to take a very long time. |
| 46 |
# It is *required* to use something like a select call to wait for activity |
| 47 |
# on any of the sockets currently active for *up to* the timeout value. |
| 48 |
# |
| 49 |
# The loop terminates when the number of active transfers (handles in libcurl |
| 50 |
# parlance) reaches zero. This number is provided by each socket_action |
| 51 |
# call, which is why each call (even the ones that are called due to |
| 52 |
# timeout being reached, as opposed to any socket activity) must update |
| 53 |
# the number of running handles. |
| 54 |
# |
| 55 |
# After the loop terminates, clean up everything: remove the easy object from |
| 56 |
# the multi object, close the easy object, close the multi object. |
| 57 |
|
| 58 |
import sys, select |
| 59 |
import pycurl |
| 60 |
from io import BytesIO |
| 61 |
|
| 62 |
if len(sys.argv) > 1: |
| 63 |
url = sys.argv[1] |
| 64 |
else: |
| 65 |
url = 'https://www.python.org' |
| 66 |
|
| 67 |
state = { |
| 68 |
'rlist': [], |
| 69 |
'wlist': [], |
| 70 |
'running': None, |
| 71 |
'timeout': None, |
| 72 |
'result': None, |
| 73 |
# If the transfer failed, code and msg will be filled in. |
| 74 |
'code': None, |
| 75 |
'msg': None, |
| 76 |
} |
| 77 |
|
| 78 |
def socket_fn(what, sock_fd, multi, socketp): |
| 79 |
if what == pycurl.POLL_IN or what == pycurl.POLL_INOUT: |
| 80 |
state['rlist'].append(sock_fd) |
| 81 |
elif what == pycurl.POLL_OUT or what == pycurl.POLL_INOUT: |
| 82 |
state['wlist'].append(sock_fd) |
| 83 |
elif what == pycurl.POLL_REMOVE: |
| 84 |
if sock_fd in state['rlist']: |
| 85 |
state['rlist'].remove(sock_fd) |
| 86 |
if sock_fd in state['wlist']: |
| 87 |
state['wlist'].remove(sock_fd) |
| 88 |
else: |
| 89 |
raise Exception("Unknown value of what: %s" % what) |
| 90 |
|
| 91 |
def work(timeout): |
| 92 |
rready, wready, xready = select.select( |
| 93 |
state['rlist'], state['wlist'], set(state['rlist']) | set(state['wlist']), timeout) |
| 94 |
|
| 95 |
if len(rready) == 0 and len(wready) == 0 and len(xready) == 0: |
| 96 |
# The number of running handles must be updated after each |
| 97 |
# call to socket_action, which includes those with the SOCKET_TIMEOUT |
| 98 |
# argument (otherwise e.g. a transfer which failed due to |
| 99 |
# exceeding the connection timeout would hang). |
| 100 |
_, running = multi.socket_action(pycurl.SOCKET_TIMEOUT, 0) |
| 101 |
else: |
| 102 |
for sock_fd in rready: |
| 103 |
# socket_action returns a tuple whose first element is always the |
| 104 |
# CURLE_OK value (0), ignore it and use the second element only. |
| 105 |
_, running = multi.socket_action(sock_fd, pycurl.CSELECT_IN) |
| 106 |
for sock_fd in wready: |
| 107 |
_, running = multi.socket_action(sock_fd, pycurl.CSELECT_OUT) |
| 108 |
for sock_fd in xready: |
| 109 |
_, running = multi.socket_action(sock_fd, pycurl.CSELECT_ERR) |
| 110 |
|
| 111 |
# Since we are only performing a single transfer, we could call |
| 112 |
# Multi.info_read after the I/O loop terminates. |
| 113 |
# In practice, you would probably use socket_action with multiple |
| 114 |
# transfers, and you may want to be notified about transfer completion |
| 115 |
# as soon as the result is available. |
| 116 |
if state['running'] is not None and running != state['running']: |
| 117 |
# Some handle has completed. |
| 118 |
# |
| 119 |
# Note that socket_action was potentially called multiple times |
| 120 |
# in this function (e.g. if both a read handle became ready and a |
| 121 |
# different write handle became ready), therefore it is possible |
| 122 |
# that multiple handles have completed. In this particular script |
| 123 |
# we are only performing a single transfer (one |
| 124 |
# Curl object / easy handle), therefore only one transfer can ever |
| 125 |
# possibly complete. |
| 126 |
qmsg, successes, failures = multi.info_read() |
| 127 |
# We should have retrieved all of the available statuses, leaving |
| 128 |
# none in the queue. |
| 129 |
assert qmsg == 0 |
| 130 |
|
| 131 |
# We have only one transfer. |
| 132 |
assert len(successes) == 1 and len(failures) == 0 or \ |
| 133 |
len(successes) == 0 and len(failures) == 1 |
| 134 |
|
| 135 |
if successes: |
| 136 |
state['result'] = True |
| 137 |
if failures: |
| 138 |
state['result'] = False |
| 139 |
# The failures array contains tuples of |
| 140 |
# (easy object, CURLE code, error message). |
| 141 |
_easy, state['code'], state['msg'] = failures[0] |
| 142 |
|
| 143 |
state['running'] = running |
| 144 |
|
| 145 |
def timer_fn(timeout_ms): |
| 146 |
if timeout_ms < 0: |
| 147 |
# libcurl passes a negative timeout value when no further |
| 148 |
# calls should be made. |
| 149 |
state['timeout'] = None |
| 150 |
else: |
| 151 |
state['timeout'] = timeout_ms / 1000.0 |
| 152 |
|
| 153 |
multi = pycurl.CurlMulti() |
| 154 |
multi.setopt(pycurl.M_SOCKETFUNCTION, socket_fn) |
| 155 |
multi.setopt(pycurl.M_TIMERFUNCTION, timer_fn) |
| 156 |
|
| 157 |
easy = pycurl.Curl() |
| 158 |
easy.setopt(pycurl.URL, url) |
| 159 |
# Uncomment to see what libcurl is doing throughout the transfer. |
| 160 |
#easy.setopt(pycurl.VERBOSE, 1) |
| 161 |
easy.setopt(pycurl.CONNECTTIMEOUT, 5) |
| 162 |
easy.setopt(pycurl.LOW_SPEED_TIME, 5) |
| 163 |
easy.setopt(pycurl.LOW_SPEED_LIMIT, 1) |
| 164 |
_io = BytesIO() |
| 165 |
easy.setopt(pycurl.WRITEDATA, _io) |
| 166 |
|
| 167 |
multi.add_handle(easy) |
| 168 |
|
| 169 |
handles = multi.socket_action(pycurl.SOCKET_TIMEOUT, 0) |
| 170 |
# This should invoke the timer function with a timeout value. |
| 171 |
|
| 172 |
while True: |
| 173 |
if state['running'] == 0: |
| 174 |
break |
| 175 |
else: |
| 176 |
# By the time we get here, timer function should have been already |
| 177 |
# invoked at least once so that we have a libcurl-supplied |
| 178 |
# timeout value. But in case this hasn't happened, default the timeout |
| 179 |
# to 1 second. |
| 180 |
timeout = state['timeout'] |
| 181 |
if timeout is None: |
| 182 |
raise Exception('Need to poll for I/O but the timeout is not set!') |
| 183 |
work(timeout) |
| 184 |
|
| 185 |
multi.remove_handle(easy) |
| 186 |
easy.close() |
| 187 |
multi.close() |
| 188 |
|
| 189 |
# Uncomment to print the retrieved contents. |
| 190 |
#print(_io.getvalue().decode()) |
| 191 |
|
| 192 |
if state['result'] is None: |
| 193 |
raise Exception('Script finished without a result!') |
| 194 |
if state['result']: |
| 195 |
print('Transfer successful, retrieved %d bytes' % len(_io.getvalue())) |
| 196 |
else: |
| 197 |
print('Transfer failed with code %d: %s' % (state['code'], state['msg'])) |