-
Notifications
You must be signed in to change notification settings - Fork 2
/
slides.txt
560 lines (411 loc) · 14.7 KB
/
slides.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
= Using asyncio in Python 3.4
:author: Aaron Maxwell <amax@redsymbol.net>
:backend: slidy
:max-width: 45em
:source-highlighter: pygments
:data-uri:
:icons:
*+git clone git@github.com:redsymbol/asyncio-class.git+*
To fully participate: make sure you have Python 3.4 installed on your
machine, and are able to start up the Python interpreter. (Earlier
versions aren't compatible with this course.) If you don't, get it
from python.org now, while we're waiting to get started.
== Concepts
asyncio is a module implementing asynchronous I/O, built into Python
3. Some of its key concepts:
* event loops
* coroutines
* transports
* protocols
A decent starting point: http://python.org/dev/peps/pep-3156/
== asyncio uses "yield from"
Python 3.4 introduced the "yield from" expression. It looks similar
to, but behaves different from, a simple "yield".
(Personally, I think it should be a separate single token - say,
"yieldfrom" - to highlight its different semantics. I encourage you to
think of it that way.)
Learn about this in PEP 380.
== Event Loops
* Built-in construct managing event waiting and dispatch
* Normally you can just use the default loop
* Can be configured, modified, refined, etc. when you do
[source,python]
----
# Most of the time, you'll just start your '__main__' function
# with something like this.
import asyncio
loop = asyncio.get_event_loop()
----
== Coroutines
In Python asyncio, a coroutine is a generator that follows certain
conventions.
A generator is a coroutine if it:
* returns a value (to the calling coroutine)
* yields from a future
* yields from another coroutine
Note that it doesn't just yield (i.e. it's "yield from <something>",
not "yield <value>".
See "The difference between yield and yield-from" by Guido:
https://groups.google.com/forum/#!topic/python-tulip/bmphRrryuFk
== More Coroutine Fun Facts
* Coroutines can only run when the event loop is running
* Coroutines don't start running automatically.
* You schedule coroutines to run by:
- yielding from it (in another calling coroutine)
- create a task, then schedule it
- or use loop.create_task(coro()) do both in one step
== Coroutines
Coroutines are technically optional in asyncio. But you should use
them, as a lot of asyncio's functionality and expressive power becomes
much much easily accessible.
The trade-off is that you must learn to think in new ways; coroutines
and 3.4's "yield from" construct are rare in mainstream programming
languages, so you likely haven't worked with anything like them
before.
Further self-education:
* PEP 342 - "Coroutines via Enhanced Generators" (how Python
coroutines extend Python generators)
* PEP 380 - "Syntax for Delegating to a Subgenerator" (the "yield from" PEP)
== Futures in asyncio
* A Future represents a computation in progress - the asynchronous
execution of a callable.
* asyncio.Future is _almost_ compatible with
concurrent.futures.Future
* you can yield from a future!
Important methods:
* done() - True iff the future has a result
* set_result() - Complete the future with a given result
* result() - Return the result, or raise an exception if none set yet.
* cancel() - Cancel the future.
== Future exercise
Open a Python 3 terminal, and type the following:
[source,python]
----
import asyncio
future = asyncio.Future()
----
Play with invoking the following methods on the future object:
* done()
* result()
* set_result('Your Name')
* cancelled()
* cancel()
== Futures Eventually Have A Result
[source,python]
----
>>> import asyncio
>>> future = asyncio.Future()
>>> future.done()
False
>>> # This raises an exception, because the future is not yet done.
... future.result()
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/home/amax/opt/Python-3.4.1/lib/python3.4/asyncio/futures.py", line 237, in result
raise InvalidStateError('Result is not ready.')
asyncio.futures.InvalidStateError: Result is not ready.
>>> future.set_result('foo')
>>> future.done()
True
>>> future.result()
'foo'
----
== Tasks are a kind of Future
* A Task manages an independently running coroutine
* In fact, asyncio.Task subclasses asyncio.Future
== You start a coroutine running with a Task
In asyncio, when you define a coroutine - which, remember, is a
generator - it doesn't start executing right away.
You run it by wrapping the coroutine in a task, and then running that
task in the event loop.
(This is the run_until_complete() method.)
[source,python]
----
import asyncio
# create a task object, and then...
loop = asyncio.get_event_loop()
loop.run_until_complete(task)
----
== Creating a task
Open a file named task_demo.py, and type in the following (you can
skip the comments).
[source,python]
----
import asyncio
@asyncio.coroutine
def my_coro():
print('Hello, YOUR NAME')
# The factory function async() takes either a coroutine
# object or a future, and wraps it in a task.
task = asyncio.Task(my_coro())
# Note that I passed the coroutine *object*, not function.
# I.e. "my_coro()" not "my_coro"
loop = asyncio.get_event_loop()
loop.run_until_complete(task)
----
(What happens if you comment out the last line?)
== Transports
* Represents an I/O endpoint for network or local communication
* Think of it as a generalization of both a network socket and file
handle, with useful methods
* can be bidirectional/streaming; unidirectional; datagram; or
subprocess (piped I/O)
== Protocols
* Represents the application layer, i.e. _what_ bytes are sent over a
transport
* Always used in conjunction with transports
* Can be streaming (bi-dir), datagram, or custom
* There are a few standard reusable protocol classes. Substantial
software systems will implement their own
== Transports vs. Protocols
A transport is responsible for _how_ bytes are transmitted.
A protocol defines _what_ bytes to transmit, and when.
Asyncio separates these concerns, so they can be more easily
composed. This is uncommon but powerful.
== Implementing a Protocol
asyncio provides a base Protocol class, that you can use to implement
protocols for TCP servers.
You implement a protocol by subclassing asyncio.Protocol, and
overriding certain methods. The ones we will look at are:
* connection_made(self, transport)
* data_received(self, data)
* connection_lost(self, exc)
== Let's Make an Echo Server
You will need:
* telnet, or some variant of netcat (nc, ncat, etc.)
* Python 3.4
Create a file named "echo_server_simple.py" and start it like this:
[source,python]
----
import asyncio
PORT = 4242
class SimpleEchoProtocol(asyncio.Protocol):
pass
----
== Creating The Server
The event loop has a method called create_server we are going to
leverage. It handles creating and passing the transport to the
protocol methods for us.
Add the following lines to the end of echo_server_simple.py:
[source,python]
----
loop = asyncio.get_event_loop()
pending_server = loop.create_server(SimpleEchoProtocol, 'localhost', PORT)
server = loop.run_until_complete(pending_server)
loop.run_until_complete(server.wait_closed())
----
create_server() returns a coroutine. The server starts when this
coroutine is run by the event loop.
== Making the connection
The Protocol.connection_made method is invoked when a client makes an
incoming TCP connection. Its argument is a transport object, which in
this case represents a TCP socket connection. The code for
create_server conveniently provides for us.
[source,python]
----
import asyncio
PORT = 4242
class SimpleEchoProtocol(asyncio.Protocol):
def connection_made(self, transport):
print('Connection made')
# We keep the transport object, so we can
# write to it later.
self.transport = transport
----
== Receiving Data
When inbound data is received on the socket, the protocol's
data_received method is invoked. Since this is an echo server, we want
to parrot what we receive right back.
Add the following method to SimpleEchoProtocol:
[source,python]
----
# new method of SimpleEchoProtocol
def data_received(self, data):
print(data)
# This is why we kept the transport when
# making the connection.
self.transport.write(b'echo:')
self.transport.write(data)
----
== Closing the connection
When the connection is broken, the protocol object's connection_lost
method is invoked. If this is done cleanly, its argument is None; else
it is passed an exception object.
Add this method to SimpleEchoProtocol:
[source,python]
----
# new method of SimpleEchoProtocol
def connection_lost(self, exc):
print("Connection lost! Closing server...")
# This variable "server" will be in global scope by
# the time the method is invoked.
server.close()
----
== Test it out
[source,bash]
----
# In one terminal tab:
python3 echo_server_simple.py
# In another tab:
netcat localhost 4242
# Or you can use telnet, or nc, or ncat, or...
telnet localhost 4242
----
Type in a few characters and press <enter> at the telnet
prompt. Notice what it replies with. Look at the python3 process tab,
and note its output.
== Using Tasks
We just implemented a simple TCP server using asyncio's Protocol
abstraction. Another way to implement servers is by using Tasks.
Let's implement the echo server again, using the task approach.
Along the way, we will also learn about using callbacks in asyncio.
== Callbacks for futures and tasks
asyncio.Future has a method named add_done_callback. This lets you
register a callable, that is invoked when the future is done.
(Remember, a task is a future too - one that runs a coroutine.)
The callback is passed the task object as an argument.
== Task callback example
Type the following into a file named run_task.py:
[source,python]
----
import asyncio
task = asyncio.Task(asyncio.sleep(1))
def announce_task_done(task):
print("Task is done: " + str(id(task)))
task.add_done_callback(announce_task_done)
asyncio.get_event_loop().run_until_complete(task)
----
Then invoke with "python3 run_task.py".
What happens if you omit the last line?
What happens if you _duplicate_ the last line, so it is run twice?
== Helper function: asyncio.start_server
start_server takes a callable argument (along with a host and
port). The callable is a callback that handles a client connection.
Each new connection on the protocol re-invokes it.
[source,python]
----
import asyncio
def client_connected_handler(client_reader, client_writer):
print('Got connection from client')
pending_server = asyncio.start_server(client_connected_handler,
'localhost', PORT)
----
== Simple Callback Server
Create a file named echo_server_task.py and type this in:
[source,python]
----
import asyncio
PORT = 4242
NUM_CLIENTS = 0
def client_connected_handler(client_reader, client_writer):
print('Got connection from client')
loop = asyncio.get_event_loop()
pending_server = asyncio.start_server(client_connected_handler,
'localhost', PORT)
server = loop.run_until_complete(pending_server)
try:
loop.run_forever()
except KeyboardInterrupt:
print('\n{} Clients Served'.format(NUM_CLIENTS))
finally:
loop.close()
----
Then run with python3, and connect with telnet or netcat as before.
== Echoing action
We want to add in actual echoing behavior. The echoing action is
handled by fetching data from the reader, and writing it right back to
the writer. Add this function to echo_server_task.py:
[source,python]
----
@asyncio.coroutine
def handle_client(client_reader, client_writer):
print('New client')
while not client_reader.at_eof():
data = (yield from client_reader.readline())
print(data)
client_writer.write(b'echo:' + data)
----
The next step is to wire it up to the server, so it is applied to
incoming connections.
== Scheduling The Task
To make this connection, we will use a task. Modify client_connected_handler like so:
[source,python]
----
def client_done(future):
global NUM_CLIENTS
NUM_CLIENTS += 1
print('Client done')
def client_connected_handler(client_reader, client_writer):
task = asyncio.Task(handle_client(client_reader, client_writer))
task.add_done_callback(client_done)
----
Then start your echo server again, and try to connect.
== Thank you!
For being beta testers for this free class in asyncio.
Contact me any time:
- Aaron Maxwell
- amax@redsymbol.net
- http://linkedin.com/in/aaronmaxwell
- "redsymbol" on github, hacker news, twitter, etc.
////////////////
== Why Separate them?
Most networking libraries don't explicity have separate abstractions
for transports and protocols. Even the standard library often doesn't
separate them, internally; the code for each is mixed together.
However, it is a powerful generalization that lets us use the same
protocols over different, even new transports (e.g. RPC), and even
nest protocols (e.g. JSON-RPC).
The ideas of transport and protocol are fleshed out more in PEP 3153,
"Asynchronous IO support"
== More Advanced Background
These are things that don't necessarily have anything to do with
Python, but are worth your time if you want to master the full range
of what asyncio makes possible.
* "Multi-core scaling: it’s not multi-threaded" by Robert Graham - http://blog.erratasec.com/2013/02/multi-core-scaling-its-not-multi.html
* "Linux System Programming (2nd Ed.), by Robert Love (pub. O'Reilly) - My *FAVORITE*
software book of 2013 (and 2014, so far). Has a great chapter on
threads programming, though to get the most out of it you'll want to
read most of the rest of the book too.
TODO: Tasks
[source,python]
----
def foo(x):
print(x)
foo("Hello World")
----
"The difference between yield and yield-from" by Guido:
https://groups.google.com/forum/#!topic/python-tulip/bmphRrryuFk
(It also explains why coroutines in asyncio use just yield from, and
not yield.)
== Resources
asyncio (formerly named "tulip"):
* http://python.org/dev/peps/pep-3156/
* http://docs.python.org/3.4/library/asyncio.html
Coroutines:
* http://python.org/dev/peps/pep-0342/
* http://www.dabeaz.com/coroutines/
Misc:
* Great article by Glyph putting asyncio in larger context - https://glyph.twistedmatrix.com/2014/02/unyielding.html
* Excellent gentle tutorial - http://www.getoffmalawn.com/blog/playing-with-asyncio
* "yield from" PEP - http://python.org/dev/peps/pep-0380/
== Example
[source,python]
----
# This is a coroutine.
import asyncio
@asyncio.coroutine
def transfer_data(src_reader, dest_writer):
# Handle the requests for a specific client with a line oriented protocol
while True:
# Read a line
data = (yield from src_reader.readline())
# Send it to the destination
dest_writer.write(data)
----
== Coroutines
* In Python, a coroutine is a generator
* In asyncio, a generator that follows certain conventions
* In particular, produces values via "return" or "yield from" (or
throwing an exception)
* Does NOT use "yield"
////////////////