1 |
=head1 Message Passing for the Non-Blocked Mind |
2 |
|
3 |
=head1 Introduction and Terminology |
4 |
|
5 |
This is a tutorial about how to get the swing of the new L<AnyEvent::MP> |
6 |
module, which allows programs to transparently pass messages within the |
7 |
process and to other processes on the same or a different host. |
8 |
|
9 |
What kind of messages? Basically a message here means a list of Perl |
10 |
strings, numbers, hashes and arrays, anything that can be expressed as a |
11 |
L<JSON> text (as JSON is the default serialiser in the protocol). Here are |
12 |
two examples: |
13 |
|
14 |
write_log => 1251555874, "action was successful.\n" |
15 |
123, ["a", "b", "c"], { foo => "bar" } |
16 |
|
17 |
When using L<AnyEvent::MP> it is customary to use a descriptive string as |
18 |
first element of a message that indicates the type of the message. This |
19 |
element is called a I<tag> in L<AnyEvent::MP>, as some API functions |
20 |
(C<rcv>) support matching it directly. |
21 |
|
22 |
Supposedly you want to send a ping message with your current time to |
23 |
somewhere, this is how such a message might look like (in Perl syntax): |
24 |
|
25 |
ping => 1251381636 |
26 |
|
27 |
Now that we know what a message is, to which entities are those |
28 |
messages being I<passed>? They are I<passed> to I<ports>. A I<port> is |
29 |
a destination for messages but also a context to execute code: when |
30 |
a runtime error occurs while executing code belonging to a port, the |
31 |
exception will be raised on the port and can even travel to interested |
32 |
parties on other nodes, which makes supervision of distributed processes |
33 |
easy. |
34 |
|
35 |
How do these ports relate to things you know? Each I<port> belongs |
36 |
to a I<node>, and a I<node> is just the UNIX process that runs your |
37 |
L<AnyEvent::MP> application. |
38 |
|
39 |
Each I<node> is distinguished from other I<nodes> running on the same or |
40 |
another host in a network by its I<node ID>. A I<node ID> is simply a |
41 |
unique string chosen manually or assigned by L<AnyEvent::MP> in some way |
42 |
(UNIX nodename, random string...). |
43 |
|
44 |
Here is a diagram about how I<nodes>, I<ports> and UNIX processes relate |
45 |
to each other. The setup consists of two nodes (more are of course |
46 |
possible): Node C<A> (in UNIX process 7066) with the ports C<ABC> and |
47 |
C<DEF>. And the node C<B> (in UNIX process 8321) with the ports C<FOO> and |
48 |
C<BAR>. |
49 |
|
50 |
|
51 |
|- PID: 7066 -| |- PID: 8321 -| |
52 |
| | | | |
53 |
| Node ID: A | | Node ID: B | |
54 |
| | | | |
55 |
| Port ABC =|= <----\ /-----> =|= Port FOO | |
56 |
| | X | | |
57 |
| Port DEF =|= <----/ \-----> =|= Port BAR | |
58 |
| | | | |
59 |
|-------------| |-------------| |
60 |
|
61 |
The strings for the I<port IDs> here are just for illustrative |
62 |
purposes: Even though I<ports> in L<AnyEvent::MP> are also identified by |
63 |
strings, they can't be chosen manually and are assigned by the system |
64 |
dynamically. These I<port IDs> are unique within a network and can also be |
65 |
used to identify senders, or even as message tags for instance. |
66 |
|
67 |
The next sections will explain the API of L<AnyEvent::MP> by going through |
68 |
a few simple examples. Later some more complex idioms are introduced, |
69 |
which are hopefully useful to solve some real world problems. |
70 |
|
71 |
=head2 Passing Your First Message |
72 |
|
73 |
For starters, let's have a look at the messaging API. The following |
74 |
example is just a demo to show the basic elements of message passing with |
75 |
L<AnyEvent::MP>. |
76 |
|
77 |
The example should print: C<Ending with: 123>, in a rather complicated |
78 |
way, by passing some message to a port. |
79 |
|
80 |
use AnyEvent; |
81 |
use AnyEvent::MP; |
82 |
|
83 |
my $end_cv = AnyEvent->condvar; |
84 |
|
85 |
my $port = port; |
86 |
|
87 |
rcv $port, test => sub { |
88 |
my ($data) = @_; |
89 |
$end_cv->send ($data); |
90 |
}; |
91 |
|
92 |
snd $port, test => 123; |
93 |
|
94 |
print "Ending with: " . $end_cv->recv . "\n"; |
95 |
|
96 |
It already uses most of the essential functions inside |
97 |
L<AnyEvent::MP>: First there is the C<port> function which creates a |
98 |
I<port> and will return it's I<port ID>, a simple string. |
99 |
|
100 |
This I<port ID> can be used to send messages to the port and install |
101 |
handlers to receive messages on the port. Since it is a simple string |
102 |
it can be safely passed to other I<nodes> in the network when you want |
103 |
to refer to that specific port (usually used for RPC, where you need |
104 |
to tell the other end which I<port> to send the reply to - messages in |
105 |
L<AnyEvent::MP> have a destination, but no source). |
106 |
|
107 |
The next function is C<rcv>: |
108 |
|
109 |
rcv $port, test => sub { ... }; |
110 |
|
111 |
It installs a receiver callback on the I<port> that specified as the first |
112 |
argument (it only works for "local" ports, i.e. ports created on the same |
113 |
node). The next argument, in this example C<test>, specifies a I<tag> to |
114 |
match. This means that whenever a message with the first element being |
115 |
the string C<test> is received, the callback is called with the remaining |
116 |
parts of that message. |
117 |
|
118 |
Messages can be sent with the C<snd> function, which is used like this in |
119 |
the example above: |
120 |
|
121 |
snd $port, test => 123; |
122 |
|
123 |
This will send the message C<'test', 123> to the I<port> with the I<port |
124 |
ID> stored in C<$port>. Since in this case the receiver has a I<tag> match |
125 |
on C<test> it will call the callback with the first argument being the |
126 |
number C<123>. |
127 |
|
128 |
The callback is a typical AnyEvent idiom: the callback just passes |
129 |
that number on to the I<condition variable> C<$end_cv> which will then |
130 |
pass the value to the print. Condition variables are out of the scope |
131 |
of this tutorial and not often used with ports, so please consult the |
132 |
L<AnyEvent::Intro> about them. |
133 |
|
134 |
Passing messages inside just one process is boring. Before we can move on |
135 |
and do interprocess message passing we first have to make sure some things |
136 |
have been set up correctly for our nodes to talk to each other. |
137 |
|
138 |
=head2 System Requirements and System Setup |
139 |
|
140 |
Before we can start with real IPC we have to make sure some things work on |
141 |
your system. |
142 |
|
143 |
First we have to setup a I<shared secret>: for two L<AnyEvent::MP> |
144 |
I<nodes> to be able to communicate with each other over the network it is |
145 |
necessary to setup the same I<shared secret> for both of them, so they can |
146 |
prove their trustworthyness to each other. |
147 |
|
148 |
The easiest way is to set this up is to use the F<aemp> utility: |
149 |
|
150 |
aemp gensecret |
151 |
|
152 |
This creates a F<$HOME/.perl-anyevent-mp> config file and generates a |
153 |
random shared secret. You can copy this file to any other system and |
154 |
then communicate over the network (via TCP) with it. You can also select |
155 |
your own shared secret (F<aemp setsecret>) and for increased security |
156 |
requirements you can even create (or configure) a TLS certificate (F<aemp |
157 |
gencert>), causing connections to not just be securely authenticated, but |
158 |
also to be encrypted and protected against tinkering. |
159 |
|
160 |
Connections will only be successfully established when the I<nodes> |
161 |
that want to connect to each other have the same I<shared secret> (or |
162 |
successfully verify the TLS certificate of the other side, in which case |
163 |
no shared secret is required). |
164 |
|
165 |
B<If something does not work as expected, and for example tcpdump shows |
166 |
that the connections are closed almost immediately, you should make sure |
167 |
that F<~/.perl-anyevent-mp> is the same on all hosts/user accounts that |
168 |
you try to connect with each other!> |
169 |
|
170 |
Thats is all for now, you will find some more advanced fiddling with the |
171 |
C<aemp> utility later. |
172 |
|
173 |
=head2 Shooting the Trouble |
174 |
|
175 |
Sometimes things go wrong, and AnyEvent::MP, being a professional module, |
176 |
does not gratuitously spill out messages to your screen. |
177 |
|
178 |
To help troubleshooting any issues, there are two environment variables |
179 |
that you can set. The first, C<AE_VERBOSE> sets the logging level of |
180 |
L<AnyEvent::Log>, which AnyEvent::MP uses. The default is C<4>, which |
181 |
means nothing much is printed. You can increase it to C<8> or C<9> to get |
182 |
more verbose output. This is example output when starting a node (somewhat |
183 |
abridged to get shorter lines): |
184 |
|
185 |
2012-03-22 01:41:43.59 debug AE::Util: using Guard module to implement guards. |
186 |
2012-03-22 01:41:43.62 debug AE::MP::Kernel: node cerebro/slwK2LEq7O starting up. |
187 |
2012-03-22 01:41:43.62 debug AE::MP::Kernel: node listens on [10.0.0.1:52110]. |
188 |
2012-03-22 01:41:43.62 trace AE::MP::Kernel: trying connect to seed node 10.0.0.19:4040. |
189 |
2012-03-22 01:41:43.66 trace AE::MP::Transport: 10.0.0.19:4040 connected as rain. |
190 |
2012-03-22 01:41:43.66 info AE::MP::Kernel: rain is up. |
191 |
|
192 |
A lot of info, but at least you can see that it does something. To only |
193 |
get info about AnyEvent::MP, you can use C<AE_LOG=AnyEvent::MP=+log> in |
194 |
your environment. |
195 |
|
196 |
The other environment variable that can be useful is |
197 |
C<PERL_ANYEVENT_MP_TRACE>, which, when set to a true value, will cause |
198 |
most messages that are sent or received to be printed. For example, F<aemp |
199 |
restart rijk> might output these message exchanges: |
200 |
|
201 |
SND rijk <- [null,"eval","AnyEvent::Watchdog::Util::restart; ()","aemp/cerebro/z4kUPp2JT4#b"] |
202 |
SND rain <- [null,"g_slave",{"'l":{"aemp/cerebro/z4kUPp2JT4":["10.0.0.1:48168"]}}] |
203 |
SND rain <- [null,"g_find","rijk"] |
204 |
RCV rain -> ["","g_found","rijk",["10.0.0.23:4040"]] |
205 |
RCV rijk -> ["b",""] |
206 |
|
207 |
=head1 PART 1: Passing Messages Between Processes |
208 |
|
209 |
=head2 The Receiver |
210 |
|
211 |
Lets split the previous example up into two programs: one that contains |
212 |
the sender and one for the receiver. First the receiver application, in |
213 |
full: |
214 |
|
215 |
use AnyEvent; |
216 |
use AnyEvent::MP; |
217 |
|
218 |
configure nodeid => "eg_receiver/%u", binds => ["*:4040"]; |
219 |
|
220 |
my $port = port; |
221 |
db_set eg_receivers => $port; |
222 |
|
223 |
rcv $port, test => sub { |
224 |
my ($data, $reply_port) = @_; |
225 |
|
226 |
print "Received data: " . $data . "\n"; |
227 |
}; |
228 |
|
229 |
AnyEvent->condvar->recv; |
230 |
|
231 |
Now, that wasn't too bad, was it? OK, let's go through the new functions |
232 |
that have been used. |
233 |
|
234 |
=head3 C<configure> and Joining and Maintaining the Network |
235 |
|
236 |
First let's have a look at C<configure>: |
237 |
|
238 |
configure nodeid => "eg_receiver/%u", binds => ["*:4040"]; |
239 |
|
240 |
Before we are able to send messages to other nodes we have to initialise |
241 |
ourself to become a "distributed node". Initialising a node means naming |
242 |
the node and binding some TCP listeners so that other nodes can |
243 |
contact it. |
244 |
|
245 |
Additionally, to actually link all nodes in a network together, you can |
246 |
specify a number of seed addresses, which will be used by the node to |
247 |
connect itself into an existing network, as we will see shortly. |
248 |
|
249 |
All of this (and more) can be passed to the C<configure> function - later |
250 |
we will see how we can do all this without even passing anything to |
251 |
C<configure>! |
252 |
|
253 |
The first parameter, C<nodeid>, specified the node ID (in this case |
254 |
C<eg_receiver/%u> - the default is to use the node name of the current |
255 |
host plus C</%u>, which goves the node a name with a random suffix to |
256 |
make it unique, but for this example we want the node to have a bit more |
257 |
personality, and name it C<eg_receiver> with a random suffix. |
258 |
|
259 |
Why the random suffix? Node IDs need to be unique within the network and |
260 |
appending a random suffix is the easiest way to do that. |
261 |
|
262 |
The second parameter, C<binds>, specifies a list of C<address:port> pairs |
263 |
to bind TCP listeners on. The special "address" of C<*> means to bind on |
264 |
every local IP address (this might not work on every OS, so explicit IP |
265 |
addresses are best). |
266 |
|
267 |
The reason to bind on a TCP port is not just that other nodes can connect |
268 |
to us: if no binds are specified, the node will still bind on a dynamic |
269 |
port on all local addresses - but in this case we won't know the port, and |
270 |
cannot tell other nodes to connect to it as seed node. |
271 |
|
272 |
Now, a I<seed> is simply the TCP address of some other node in the |
273 |
network, often the same string as used for the C<binds> parameter of the |
274 |
other node. The need for seeds is easy to explain: I<somehow> the nodes |
275 |
of an aemp network have to find each other, and often this means over the |
276 |
internet. So broadcasts are out. |
277 |
|
278 |
Instead, a node usually specifies the addresses of one or few (for |
279 |
redundancy) other nodes, some of which should be up. Two nodes can set |
280 |
each other as seeds without any issues. You could even specify all nodes |
281 |
as seeds for all nodes, for total redundancy. But the common case is to |
282 |
have some more or less central, stable servers running seed services for |
283 |
other nodes. |
284 |
|
285 |
All you need to do to ensure that an AnyEvent::MP network connects |
286 |
together is to make sure that all seed nodes are connected together via |
287 |
their seed connections, i.e., all connections from seed nodes to I<their> |
288 |
seed nodes form a connected graph. |
289 |
|
290 |
A node tries to keep connections open to all of it's seed nodes at all |
291 |
times, while other connections are made on demand only. |
292 |
|
293 |
The simplest way to do that would be for all nodes to use the same seed |
294 |
nodes: seed nodes would seed each other, and all other nodes would connect |
295 |
to the seed nodes. |
296 |
|
297 |
All of this ensures that the network stays one network - even if all the |
298 |
nodes in one half of the net are separated from the nodes in the other |
299 |
half by some network problem, once that is over, they will eventually |
300 |
become a single network again. |
301 |
|
302 |
In addition to creating the network, a node also expects the seed nodes to |
303 |
run the shared database service - if need be, by automatically starting |
304 |
it, so you don't normally need to configure this explicitly. |
305 |
|
306 |
The process of joining a network takes time, during which the node |
307 |
is already running. This means it takes time until the node is |
308 |
fully connected, and information about services in the network are |
309 |
available. This is why most AnyEvent::MP programs either just register |
310 |
themselves in the database and wait to be "found" by others, or they start |
311 |
to monitor the database until some nodes of the required type show up. |
312 |
|
313 |
We will see how this is done later, in the sender program. |
314 |
|
315 |
=head3 Registering the Receiver |
316 |
|
317 |
Coming back to our example, after the node has been configured for network |
318 |
access, it is time to publish some service, namely the receive service. |
319 |
|
320 |
For that, let's look at the next lines: |
321 |
|
322 |
my $port = port; |
323 |
db_set eg_receivers => $port; |
324 |
|
325 |
The C<port> function has already been discussed. It simply creates a new |
326 |
I<port> and returns the I<port ID>. The C<db_set> function, however, is |
327 |
new: The first argument is the name of a I<database family> and the second |
328 |
argument is the name of a I<subkey> within that family. The third argument |
329 |
would be the I<value> to be associated with the family and subkey, but, |
330 |
since it is missing, it will simply be C<undef>. |
331 |
|
332 |
What is a "family" you wonder? Well, AnyEvent::MP comes with a distributed |
333 |
database. This database runs on so-called "global" nodes, which usually |
334 |
are the seed nodes of your network. The database structure is "simply" a |
335 |
hash of hashes of values. |
336 |
|
337 |
To illustrate this with Perl syntax, assume the database was stored in |
338 |
C<%DB>, then the C<db_set> function more or less would do this: |
339 |
|
340 |
$DB{eg_receivers}{$port} = undef; |
341 |
|
342 |
So the ominous "family" selects a hash in the database, and the "subkey" |
343 |
is simply the key in this hash - C<db_set> very much works like this |
344 |
assignment. |
345 |
|
346 |
The family namespace is shared by all nodes in a network, so the names |
347 |
should be reasonably unique, for example, they could start with the name |
348 |
of your module, or the name of the program, using your port name or node |
349 |
name as subkey. |
350 |
|
351 |
The purpose behind adding this key to the database is that the sender can |
352 |
look it up and find our port. We will shortly see how. |
353 |
|
354 |
The last step in the example is to set up a receiver callback for those |
355 |
messages, just as was discussed in the first example. We again match |
356 |
for the tag C<test>. The difference is that this time we don't exit the |
357 |
application after receiving the first message. Instead we continue to wait |
358 |
for new messages indefinitely. |
359 |
|
360 |
=head2 The Sender |
361 |
|
362 |
OK, now let's take a look at the sender code: |
363 |
|
364 |
use AnyEvent; |
365 |
use AnyEvent::MP; |
366 |
|
367 |
configure nodeid => "eg_sender/%u", seeds => ["*:4040"]; |
368 |
|
369 |
my $guard = db_mon eg_receivers => sub { |
370 |
my ($family, $a, $c, $d) = @_; |
371 |
return unless %$family; |
372 |
|
373 |
# now there are some receivers, send them a message |
374 |
snd $_ => test => time |
375 |
for keys %$family; |
376 |
}; |
377 |
|
378 |
AnyEvent->condvar->recv; |
379 |
|
380 |
It's even less code. The C<configure> serves the same purpose as in the |
381 |
receiver, but instead of specifying binds we specify a list of seeds - the |
382 |
only seed happens to be the same as the bind used by the receiver, which |
383 |
therefore becomes our seed node. |
384 |
|
385 |
Remember the part about having to wait till things become available? Well, |
386 |
after configure returns, nothing has been done yet - the node is not |
387 |
connected to the network, knows nothing about the database contents, and |
388 |
it can take ages (for a computer :) for this situation to change. |
389 |
|
390 |
Therefore, the sender waits, in this case by using the C<db_mon> |
391 |
function. This function registers an interest in a specific database |
392 |
family (in this case C<eg_receivers>). Each time something inside the |
393 |
family changes (a key is added, changed or deleted), it will call our |
394 |
callback with the family hash as first argument, and the list of keys as |
395 |
second argument. |
396 |
|
397 |
The callback only checks whether the C<%$family> has is empty - if it is, |
398 |
then it doesn't do anything. But eventually the family will contain the |
399 |
port subkey we set in the sender. Then it will send a message to it (and |
400 |
any other receiver in the same family). Likewise, should the receiver go |
401 |
away and come back, or should another receiver come up, it will again send |
402 |
a message to all of them. |
403 |
|
404 |
You can experiment by having multiple receivers - you have to change the |
405 |
"binds" parameter in the receiver to the seeds used in the sender to start |
406 |
up additional receivers, but then you can start as many as you like. If |
407 |
you specify proper IP addresses for the seeds, you can even run them on |
408 |
different computers. |
409 |
|
410 |
Each time you start the sender, it will send a message to all receivers it |
411 |
finds (you have to interrupt it manually afterwards). |
412 |
|
413 |
Additional experiments you could try include using |
414 |
C<PERL_ANYEVENT_MP_TRACE=1> to see which messages are exchanged, or |
415 |
starting the sender before the receiver and see how long it then takes to |
416 |
find the receiver. |
417 |
|
418 |
=head3 Splitting Network Configuration and Application Code |
419 |
|
420 |
OK, so far, this works reasonably. In the real world, however, the person |
421 |
configuring your application to run on a specific network (the end user |
422 |
or network administrator) is often different to the person coding the |
423 |
application. |
424 |
|
425 |
Or to put it differently: the arguments passed to configure are usually |
426 |
provided not by the programmer, but by whoever is deploying the program - |
427 |
even in the example above, we would like to be able to just start senders |
428 |
and receivers without having to patch the programs. |
429 |
|
430 |
To make this easy, AnyEvent::MP supports a simple configuration database, |
431 |
using profiles, which can be managed using the F<aemp> command-line |
432 |
utility (yes, this section is about the advanced tinkering mentioned |
433 |
before). |
434 |
|
435 |
When you change both programs above to simply call |
436 |
|
437 |
configure; |
438 |
|
439 |
then AnyEvent::MP tries to look up a profile using the current node name |
440 |
in its configuration database, falling back to some global default. |
441 |
|
442 |
You can run "generic" nodes using the F<aemp> utility as well, and we will |
443 |
exploit this in the following way: we configure a profile "seed" and run |
444 |
a node using it, whose sole purpose is to be a seed node for our example |
445 |
programs. |
446 |
|
447 |
We bind the seed node to port 4040 on all interfaces: |
448 |
|
449 |
aemp profile seed binds "*:4040" |
450 |
|
451 |
And we configure all nodes to use this as seed node (this only works when |
452 |
running on the same host, for multiple machines you would replace the C<*> |
453 |
by the IP address or hostname of the node running the seed), by changing |
454 |
the global settings shared between all profiles: |
455 |
|
456 |
aemp seeds "*:4040" |
457 |
|
458 |
Then we run the seed node: |
459 |
|
460 |
aemp run profile seed |
461 |
|
462 |
After that, we can start as many other nodes as we want, and they will |
463 |
all use our generic seed node to discover each other. The reason we can |
464 |
start our existing programs even though they specify "incompatible" |
465 |
parameters to C<configure> is that the configuration file (by default) |
466 |
takes precedence over any arguments passed to C<configure>. |
467 |
|
468 |
That's all for now - next we will teach you about monitoring by writing a |
469 |
simple chat client and server :) |
470 |
|
471 |
=head1 PART 2: Monitoring, Supervising, Exception Handling and Recovery |
472 |
|
473 |
That's a mouthful, so what does it mean? Our previous example is what one |
474 |
could call "very loosely coupled" - the sender doesn't care about whether |
475 |
there are any receivers, and the receivers do not care if there is any |
476 |
sender. |
477 |
|
478 |
This can work fine for simple services, but most real-world applications |
479 |
want to ensure that the side they are expecting to be there is actually |
480 |
there. Going one step further: most bigger real-world applications even |
481 |
want to ensure that if some component is missing, or has crashed, it will |
482 |
still be there, by recovering and restarting the service. |
483 |
|
484 |
AnyEvent::MP supports this by catching exceptions and network problems, |
485 |
and notifying interested parties of these. |
486 |
|
487 |
=head2 Exceptions, Port Context, Network Errors and Monitors |
488 |
|
489 |
=head3 Exceptions |
490 |
|
491 |
Exceptions are handled on a per-port basis: all receive callbacks are |
492 |
executed in a special context, the so-called I<port-context>: code |
493 |
that throws an otherwise uncaught exception will cause the port to be |
494 |
C<kil>led. Killed ports are destroyed automatically (killing ports is |
495 |
actually the only way to free ports). |
496 |
|
497 |
Ports can be monitored, even from a different node and host, and when a |
498 |
port is killed, any entity monitoring it will be notified. |
499 |
|
500 |
Here is a simple example: |
501 |
|
502 |
use AnyEvent::MP; |
503 |
|
504 |
# create a port, it always dies |
505 |
my $port = port { die "oops" }; |
506 |
|
507 |
# monitor it |
508 |
mon $port, sub { |
509 |
warn "$port was killed (with reason @_)"; |
510 |
}; |
511 |
|
512 |
# now send it some message, causing it to die: |
513 |
snd $port; |
514 |
|
515 |
AnyEvent->condvar->recv; |
516 |
|
517 |
It first creates a port whose only action is to throw an exception, |
518 |
and the monitors it with the C<mon> function. Afterwards it sends it a |
519 |
message, causing it to die and call the monitoring callback: |
520 |
|
521 |
anon/6WmIpj.a was killed (with reason die oops at xxx line 5.) at xxx line 9. |
522 |
|
523 |
The callback was actually passed two arguments: C<die>, to indicate it |
524 |
did throw an I<exception> as opposed to, say, a network error, and the |
525 |
exception message itself. |
526 |
|
527 |
What happens when a port is killed before we have a chance to monitor |
528 |
it? Granted, this is highly unlikely in our example, but when you program |
529 |
in a network this can easily happen due to races between nodes. |
530 |
|
531 |
use AnyEvent::MP; |
532 |
|
533 |
my $port = port { die "oops" }; |
534 |
|
535 |
snd $port; |
536 |
|
537 |
mon $port, sub { |
538 |
warn "$port was killed (with reason @_)"; |
539 |
}; |
540 |
|
541 |
AnyEvent->condvar->recv; |
542 |
|
543 |
This time we will get something else: |
544 |
|
545 |
2012-03-21 00:50:36 <2> unmonitored local port fADb died with reason: die oops at - line 3. |
546 |
anon/fADb was killed (with reason no_such_port cannot monitor nonexistent port) |
547 |
|
548 |
The first line is an error message that is printed when a port dies that |
549 |
isn't being monitored, because that is normally a bug. When later a C<mon> |
550 |
is attempted, it is immediately killed, because the port is already |
551 |
gone. The kill reason is now C<no_such_port> with some descriptive (we |
552 |
hope) error message. |
553 |
|
554 |
As you probably suspect from these examples, the kill reason is usually |
555 |
some identifier as first argument and a human-readable error message as |
556 |
second argument - all kill reasons by AnyEvent::MP itself follow this |
557 |
pattern. But the kill reason can be anything: it is simply a list of |
558 |
values you can choose yourself. It can even be nothing (an empty list) - |
559 |
this is called a "normal" kill. |
560 |
|
561 |
Apart from die'ing, you can kill ports manually using the C<kil> |
562 |
function. Using the C<kil> function will be treated like an error when a |
563 |
non-empty reason is specified: |
564 |
|
565 |
kil $port, custom_error => "don't like your steenking face"; |
566 |
|
567 |
And a I<normal> kill without any reason arguments: |
568 |
|
569 |
kil $port; |
570 |
|
571 |
By now you probably wonder what this "normal" kill business is: A common |
572 |
idiom is to not specify a callback to C<mon>, but another port, such as |
573 |
C<$SELF>: |
574 |
|
575 |
mon $port, $SELF; |
576 |
|
577 |
This basically means "monitor $port and kill me when it crashes" - and |
578 |
the thing is, a "normal" kill does not count as a crash. This way you can |
579 |
easily link ports together and make them crash together on errors, while |
580 |
allowing you to remove a port silently when it has done it's job properly. |
581 |
|
582 |
=head3 Port Context |
583 |
|
584 |
Code runs in the so-called "port context". That means C<$SELF> contains |
585 |
its own port ID and exceptions that the code throws will be caught. |
586 |
|
587 |
Since AnyEvent::MP is event-based, it is not uncommon to register |
588 |
callbacks from within C<rcv> handlers. As example, assume that the |
589 |
following port receive handler wants to C<die> a second later, using |
590 |
C<after>: |
591 |
|
592 |
my $port = port { |
593 |
after 1, sub { die "oops" }; |
594 |
}; |
595 |
|
596 |
If you try this out, you would find it does not work - when the C<after> |
597 |
callback is executed, it does not run in the port context anymore, so |
598 |
exceptions will not be caught. |
599 |
|
600 |
For these cases, AnyEvent::MP exports a special "closure constructor" |
601 |
called C<psub>, which works mostly like perl's built-in C<sub>: |
602 |
|
603 |
my $port = port { |
604 |
after 1, psub { die "oops" }; |
605 |
}; |
606 |
|
607 |
C<psub> remembers the port context and returns a code reference. When the |
608 |
code reference is invoked, it will run the code block within the context |
609 |
that it was created in, so exception handling once more works as expected. |
610 |
|
611 |
There is even a way to temporarily execute code in the context of some |
612 |
port, namely C<peval>: |
613 |
|
614 |
peval $port, sub { |
615 |
# die'ing here will kil $port |
616 |
}; |
617 |
|
618 |
The C<peval> function temporarily replaces C<$SELF> by the given C<$port> |
619 |
and then executes the given sub in a port context. |
620 |
|
621 |
=head3 Network Errors and the AEMP Guarantee |
622 |
|
623 |
Earlier we mentioned another important source of monitoring failures: |
624 |
network problems. When a node loses connection to another node, it will |
625 |
invoke all monitoring actions, just as if the port was killed, I<even if |
626 |
it is possible that the port is still happily alive on another node> (not |
627 |
being able to talk to a node means we have no clue what's going on with |
628 |
it, it could be crashed, but also still running without knowing we lost |
629 |
the connection). |
630 |
|
631 |
So another way to view monitors is: "notify me when some of my messages |
632 |
couldn't be delivered". AEMP has a guarantee about message delivery to a |
633 |
port: After starting a monitor, any message sent to a port will either |
634 |
be delivered, or, when it is lost, any further messages will also be lost |
635 |
until the monitoring action is invoked. After that, further messages |
636 |
I<might> get delivered again. |
637 |
|
638 |
This doesn't sound like a very big guarantee, but it is kind of the best |
639 |
you can get while staying sane: Specifically, it means that there will be |
640 |
no "holes" in the message sequence: all messages sent are delivered in |
641 |
order, without any of them missing in between, and when some were lost, |
642 |
you I<will> be notified of that, so you can take recovery action. |
643 |
|
644 |
And, obviously, the guarantee only works in the presence of |
645 |
correctly-working hardware, and no relevant bugs inside AEMP itself. |
646 |
|
647 |
=head3 Supervising |
648 |
|
649 |
OK, so how is this crashing-everything-stuff going to make applications |
650 |
I<more> stable? Well, in fact, the goal is not really to make them |
651 |
more stable, but to make them more resilient against actual errors |
652 |
and crashes. And this is not done by crashing I<everything>, but by |
653 |
crashing everything except a I<supervisor> that then cleans up and sgtarts |
654 |
everything again. |
655 |
|
656 |
A supervisor is simply some code that ensures that an application (or a |
657 |
part of it) is running, and if it crashes, is restarted properly. That is, |
658 |
it supervises a service by starting and restarting it, as necessary. |
659 |
|
660 |
To show how to do all this we will create a simple chat server that can |
661 |
handle many chat clients. Both server and clients can be killed and |
662 |
restarted, and even crash, to some extent, without disturbing the chat |
663 |
functionality. |
664 |
|
665 |
=head2 Chatting, the Resilient Way |
666 |
|
667 |
Without further ado, here is the chat server (to run it, we assume the |
668 |
set-up explained earlier, with a separate F<aemp run seed> node): |
669 |
|
670 |
use common::sense; |
671 |
use AnyEvent::MP; |
672 |
|
673 |
configure; |
674 |
|
675 |
my %clients; |
676 |
|
677 |
sub msg { |
678 |
print "relaying: $_[0]\n"; |
679 |
snd $_, $_[0] |
680 |
for values %clients; |
681 |
} |
682 |
|
683 |
our $server = port; |
684 |
|
685 |
rcv $server, join => sub { |
686 |
my ($client, $nick) = @_; |
687 |
|
688 |
$clients{$client} = $client; |
689 |
|
690 |
mon $client, sub { |
691 |
delete $clients{$client}; |
692 |
msg "$nick (quits, @_)"; |
693 |
}; |
694 |
msg "$nick (joins)"; |
695 |
}; |
696 |
|
697 |
rcv $server, privmsg => sub { |
698 |
my ($nick, $msg) = @_; |
699 |
msg "$nick: $msg"; |
700 |
}; |
701 |
|
702 |
db_set eg_chat_server => $server; |
703 |
|
704 |
warn "server ready.\n"; |
705 |
|
706 |
AnyEvent->condvar->recv; |
707 |
|
708 |
Looks like a lot, but it is actually quite simple: after your usual |
709 |
preamble (this time we use common sense), we define a helper function that |
710 |
sends some message to every registered chat client: |
711 |
|
712 |
sub msg { |
713 |
print "relaying: $_[0]\n"; |
714 |
snd $_, $_[0] |
715 |
for values %clients; |
716 |
} |
717 |
|
718 |
The clients are stored in the hash C<%client>. Then we define a server |
719 |
port and install two receivers on it, C<join>, which is sent by clients |
720 |
to join the chat, and C<privmsg>, that clients use to send actual chat |
721 |
messages. |
722 |
|
723 |
C<join> is most complicated. It expects the client port and the nickname |
724 |
to be passed in the message, and registers the client in C<%clients>. |
725 |
|
726 |
rcv $server, join => sub { |
727 |
my ($client, $nick) = @_; |
728 |
|
729 |
$clients{$client} = $client; |
730 |
|
731 |
The next step is to monitor the client. The monitoring action removes the |
732 |
client and sends a quit message with the error to all remaining clients. |
733 |
|
734 |
mon $client, sub { |
735 |
delete $clients{$client}; |
736 |
msg "$nick (quits, @_)"; |
737 |
}; |
738 |
|
739 |
And finally, it creates a join message and sends it to all clients. |
740 |
|
741 |
msg "$nick (joins)"; |
742 |
}; |
743 |
|
744 |
The C<privmsg> callback simply broadcasts the message to all clients: |
745 |
|
746 |
rcv $server, privmsg => sub { |
747 |
my ($nick, $msg) = @_; |
748 |
msg "$nick: $msg"; |
749 |
}; |
750 |
|
751 |
And finally, the server registers itself in the server group, so that |
752 |
clients can find it: |
753 |
|
754 |
db_set eg_chat_server => $server; |
755 |
|
756 |
Well, well... and where is this supervisor stuff? Well... we cheated, |
757 |
it's not there. To not overcomplicate the example, we only put it into |
758 |
the..... CLIENT! |
759 |
|
760 |
=head3 The Client, and a Supervisor! |
761 |
|
762 |
Again, here is the client, including supervisor, which makes it a bit |
763 |
longer: |
764 |
|
765 |
use common::sense; |
766 |
use AnyEvent::MP; |
767 |
|
768 |
my $nick = shift || "anonymous"; |
769 |
|
770 |
configure; |
771 |
|
772 |
my ($client, $server); |
773 |
|
774 |
sub server_connect { |
775 |
my $db_mon; |
776 |
$db_mon = db_mon eg_chat_server => sub { |
777 |
return unless %{ $_[0] }; |
778 |
undef $db_mon; |
779 |
|
780 |
print "\rconnecting...\n"; |
781 |
|
782 |
$client = port { print "\r \r@_\n> " }; |
783 |
mon $client, sub { |
784 |
print "\rdisconnected @_\n"; |
785 |
&server_connect; |
786 |
}; |
787 |
|
788 |
$server = (keys %{ $_[0] })[0]; |
789 |
|
790 |
snd $server, join => $client, $nick; |
791 |
mon $server, $client; |
792 |
}; |
793 |
} |
794 |
|
795 |
server_connect; |
796 |
|
797 |
my $w = AnyEvent->io (fh => 0, poll => 'r', cb => sub { |
798 |
chomp (my $line = <STDIN>); |
799 |
print "> "; |
800 |
snd $server, privmsg => $nick, $line |
801 |
if $server; |
802 |
}); |
803 |
|
804 |
$| = 1; |
805 |
print "> "; |
806 |
AnyEvent->condvar->recv; |
807 |
|
808 |
The first thing the client does is to store the nick name (which is |
809 |
expected as the only command line argument) in C<$nick>, for further |
810 |
usage. |
811 |
|
812 |
The next relevant thing is... finally... the supervisor: |
813 |
|
814 |
sub server_connect { |
815 |
my $db_mon; |
816 |
$db_mon = db_mon eg_chat_server => sub { |
817 |
return unless %{ $_[0] }; |
818 |
undef $db_mon; # stop monitoring |
819 |
|
820 |
This monitors the C<eg_chat_server> database family. It waits until a |
821 |
chat server becomes available. When that happens, it "connects" to it |
822 |
by creating a client port that receives and prints chat messages, and |
823 |
monitoring it: |
824 |
|
825 |
$client = port { print "\r \r@_\n> " }; |
826 |
mon $client, sub { |
827 |
print "\rdisconnected @_\n"; |
828 |
&server_connect; |
829 |
}; |
830 |
|
831 |
If the client port dies (for whatever reason), the "supervisor" will start |
832 |
looking for a server again - the semantics of C<db_mon> ensure that it |
833 |
will immediately find it if there is a server port. |
834 |
|
835 |
After this, everything is ready: the client will send a C<join> message |
836 |
with its local port to the server, and start monitoring it: |
837 |
|
838 |
$server = (keys %{ $_[0] })[0]; |
839 |
|
840 |
snd $server, join => $client, $nick; |
841 |
mon $server, $client; |
842 |
} |
843 |
|
844 |
This second monitor will ensure that, when the server port crashes or goes |
845 |
away (e.g. due to network problems), the client port will be killed as |
846 |
well. This tells the user that the client was disconnected, and will then |
847 |
start to connect the server again. |
848 |
|
849 |
The rest of the program deals with the boring details of actually invoking |
850 |
the supervisor function to start the whole client process and handle the |
851 |
actual terminal input, sending it to the server. |
852 |
|
853 |
Now... the "supervisor" in this example is a bit of a cheat - it doesn't |
854 |
really clean up much (because the cleanup done by AnyEvent::MP suffices), |
855 |
and there isn't much of a restarting action either - if the server isn't |
856 |
there because it crashed, well, it isn't there. |
857 |
|
858 |
In the real world, one would often add a timeout that would trigger when |
859 |
the server couldn't be found within some time limit, and then complain, |
860 |
or even try to start a new server. Or the supervisor would have to do |
861 |
some real cleanups, such as rolling back database transactions when the |
862 |
database thread crashes. For this simple chat server, however, this simple |
863 |
supervisor works fine. Hopefully future versions of AnyEvent::MP will |
864 |
offer some predefined supervisors, for now you will have to code it on |
865 |
your own. |
866 |
|
867 |
You should now try to start the server and one or more clients in different |
868 |
terminal windows (and the seed node): |
869 |
|
870 |
perl eg/chat_client nick1 |
871 |
perl eg/chat_client nick2 |
872 |
perl eg/chat_server |
873 |
aemp run profile seed |
874 |
|
875 |
And then you can experiment with chatting, killing one or more clients, or |
876 |
stopping and restarting the server, to see the monitoring in action. |
877 |
|
878 |
The crucial point you should understand from this example is that |
879 |
monitoring is usually symmetric: when you monitor some other port, |
880 |
potentially on another node, that other port usually should monitor you, |
881 |
too, so when the connection dies, both ports get killed, or at least both |
882 |
sides can take corrective action. Exceptions are "servers" that serve |
883 |
multiple clients at once and might only wish to clean up, and supervisors, |
884 |
who of course should not normally get killed (unless they, too, have a |
885 |
supervisor). |
886 |
|
887 |
If you often think in object-oriented terms, then you can think of a port |
888 |
as an object: C<port> is the constructor, the receive callbacks set by |
889 |
C<rcv> act as methods, the C<kil> function becomes the explicit destructor |
890 |
and C<mon> installs a destructor hook. Unlike conventional object oriented |
891 |
programming, it can make sense to exchange port IDs more freely (for |
892 |
example, to monitor one port from another), because it is cheap to send |
893 |
port IDs over the network, and AnyEvent::MP blurs the distinction between |
894 |
local and remote ports. |
895 |
|
896 |
Lastly, there is ample room for improvement in this example: the server |
897 |
should probably remember the nickname in the C<join> handler instead of |
898 |
expecting it in every chat message, it should probably monitor itself, and |
899 |
the client should not try to send any messages unless a server is actually |
900 |
connected. |
901 |
|
902 |
=head1 PART 3: TIMTOWTDI: Virtual Connections |
903 |
|
904 |
The chat system developed in the previous sections is very "traditional" |
905 |
in a way: you start some server(s) and some clients statically and they |
906 |
start talking to each other. |
907 |
|
908 |
Sometimes applications work more like "services": They can run on almost |
909 |
any node and even talk to copies of themselves on other nodes in case they |
910 |
are distributed. The L<AnyEvent::MP::Global> service for example monitors |
911 |
nodes joining the network and sometimes even starts itself on other nodes. |
912 |
|
913 |
One good way to design such services is to put them into a module and |
914 |
create "virtual connections" to other nodes. We call this the "bridge |
915 |
head" method, because you start by I<creating a remote port> (the bridge |
916 |
head) and from that you start to bootstrap your application. |
917 |
|
918 |
Since that sounds rather theoretical, let us redesign the chat server and |
919 |
client using this design method. |
920 |
|
921 |
As usual, we start with the full program - here is the server: |
922 |
|
923 |
use common::sense; |
924 |
use AnyEvent::MP; |
925 |
|
926 |
configure; |
927 |
|
928 |
db_set eg_chat_server2 => $NODE; |
929 |
|
930 |
my %clients; |
931 |
|
932 |
sub msg { |
933 |
print "relaying: $_[0]\n"; |
934 |
snd $_, $_[0] |
935 |
for values %clients; |
936 |
} |
937 |
|
938 |
sub client_connect { |
939 |
my ($client, $nick) = @_; |
940 |
|
941 |
mon $client; |
942 |
mon $client, psub { |
943 |
delete $clients{$client}; |
944 |
msg "$nick (quits, @_)"; |
945 |
}; |
946 |
|
947 |
$clients{$client} = $client; |
948 |
|
949 |
msg "$nick (joins)"; |
950 |
|
951 |
rcv $SELF, sub { msg "$nick: $_[0]" }; |
952 |
} |
953 |
|
954 |
warn "server ready.\n"; |
955 |
|
956 |
AnyEvent->condvar->recv; |
957 |
|
958 |
It starts out not much different then the previous example, except that |
959 |
this time, we register the node port in the database and not a port we |
960 |
created - the clients only want to know which node the server should |
961 |
be running on, and there can only be one such server (or service) per |
962 |
node. In fact, the clients could also use some kind of election mechanism, |
963 |
to find the node with lowest node ID, or lowest load, or something like |
964 |
that. |
965 |
|
966 |
The much more interesting difference to the previous server is that |
967 |
indeed no server port is created - the server consists only of code, |
968 |
and "does" nothing by itself. All it "does" is to define a function |
969 |
named C<client_connect>, which expects a client port and a nick name as |
970 |
arguments. It then monitors the client port and binds a receive callback |
971 |
on C<$SELF>, which expects messages that in turn are broadcast to all |
972 |
clients. |
973 |
|
974 |
The two C<mon> calls are a bit tricky - the first C<mon> is a shorthand |
975 |
for C<mon $client, $SELF>. The second does the normal "client has gone |
976 |
away" clean-up action. |
977 |
|
978 |
The last line, the C<rcv $SELF>, is a good hint that something interesting |
979 |
is going on. And indeed, when looking at the client code, you can see a |
980 |
new function, C<spawn>: |
981 |
#todo# |
982 |
|
983 |
use common::sense; |
984 |
use AnyEvent::MP; |
985 |
|
986 |
my $nick = shift; |
987 |
|
988 |
configure; |
989 |
|
990 |
$| = 1; |
991 |
|
992 |
my $port = port; |
993 |
|
994 |
my ($client, $server); |
995 |
|
996 |
sub server_connect { |
997 |
my $servernodes = grp_get "eg_chat_server2" |
998 |
or return after 1, \&server_connect; |
999 |
|
1000 |
print "\rconnecting...\n"; |
1001 |
|
1002 |
$client = port { print "\r \r@_\n> " }; |
1003 |
mon $client, sub { |
1004 |
print "\rdisconnected @_\n"; |
1005 |
&server_connect; |
1006 |
}; |
1007 |
|
1008 |
$server = spawn $servernodes->[0], "::client_connect", $client, $nick; |
1009 |
mon $server, $client; |
1010 |
} |
1011 |
|
1012 |
server_connect; |
1013 |
|
1014 |
my $w = AnyEvent->io (fh => 0, poll => 'r', cb => sub { |
1015 |
chomp (my $line = <STDIN>); |
1016 |
print "> "; |
1017 |
snd $server, $line |
1018 |
if $server; |
1019 |
}); |
1020 |
|
1021 |
print "> "; |
1022 |
AnyEvent->condvar->recv; |
1023 |
|
1024 |
The client is quite similar to the previous one, but instead of contacting |
1025 |
the server I<port> (which no longer exists), it C<spawn>s (creates) a new |
1026 |
the server I<port on node>: |
1027 |
|
1028 |
$server = spawn $servernodes->[0], "::client_connect", $client, $nick; |
1029 |
mon $server, $client; |
1030 |
|
1031 |
And of course the first thing after creating it is monitoring it. |
1032 |
|
1033 |
Phew, let's go through this in slow motion: the C<spawn> function creates |
1034 |
a new port on a remote node and returns its port ID. After creating |
1035 |
the port it calls a function on the remote node, passing any remaining |
1036 |
arguments to it, and - most importantly - executes the function within |
1037 |
the context of the new port, so it can be manipulated by referring to |
1038 |
C<$SELF>. The init function can reside in a module (actually it normally |
1039 |
I<should> reside in a module) - AnyEvent::MP will automatically load the |
1040 |
module if the function isn't defined. |
1041 |
|
1042 |
The C<spawn> function returns immediately, which means you can instantly |
1043 |
send messages to the port, long before the remote node has even heard |
1044 |
of our request to create a port on it. In fact, the remote node might |
1045 |
not even be running. Despite these troubling facts, everything should |
1046 |
work just fine: if the node isn't running (or the init function throws an |
1047 |
exception), then the monitor will trigger because the port doesn't exist. |
1048 |
|
1049 |
If the spawn message gets delivered, but the monitoring message is not |
1050 |
because of network problems (extremely unlikely, but monitoring, after |
1051 |
all, is implemented by passing a message, and messages can get lost), then |
1052 |
this connection loss will eventually trigger the monitoring action. On the |
1053 |
remote node (which in return monitors the client) the port will also be |
1054 |
cleaned up on connection loss. When the remote node comes up again and our |
1055 |
monitoring message can be delivered, it will instantly fail because the |
1056 |
port has been cleaned up in the meantime. |
1057 |
|
1058 |
If your head is spinning by now, that's fine - just keep in mind, after |
1059 |
creating a port using C<spawn>, monitor it on the local node, and monitor |
1060 |
"the other side" from the remote node, and all will be cleaned up just |
1061 |
fine. |
1062 |
|
1063 |
=head2 Services |
1064 |
|
1065 |
Above it was mentioned that C<spawn> automatically loads modules. This can |
1066 |
be exploited in various useful ways. |
1067 |
|
1068 |
Assume for a moment you put the server into a file called |
1069 |
F<mymod/chatserver.pm> reachable from the current directory. Then you |
1070 |
could run a node there with: |
1071 |
|
1072 |
aemp run |
1073 |
|
1074 |
The other nodes could C<spawn> the server by using |
1075 |
C<mymod::chatserver::client_connect> as init function - without any other |
1076 |
configuration. |
1077 |
|
1078 |
Likewise, when you have some service that starts automatically when loaded |
1079 |
(similar to AnyEvent::MP::Global), then you can configure this service |
1080 |
statically: |
1081 |
|
1082 |
aemp profile mysrvnode services mymod::service:: |
1083 |
aemp run profile mysrvnode |
1084 |
|
1085 |
And the module will automatically be loaded in the node, as specifying a |
1086 |
module name (with C<::>-suffix) will simply load the module, which is then |
1087 |
free to do whatever it wants. |
1088 |
|
1089 |
Of course, you can also do it in the much more standard way by writing |
1090 |
a module (e.g. C<BK::Backend::IRC>), installing it as part of a module |
1091 |
distribution and then configure nodes. For example, if I wanted to run the |
1092 |
Bummskraut IRC backend on a machine named "ruth", I could do this: |
1093 |
|
1094 |
aemp profile ruth addservice BK::Backend::IRC:: |
1095 |
|
1096 |
And any F<aemp run> on that host will automatically have the Bummskraut |
1097 |
IRC backend running. |
1098 |
|
1099 |
There are plenty of possibilities you can use - it's all up to you how you |
1100 |
structure your application. |
1101 |
|
1102 |
=head1 PART 4: Coro::MP - selective receive |
1103 |
|
1104 |
Not all problems lend themselves naturally to an event-based solution: |
1105 |
sometimes things are easier if you can decide in what order you want to |
1106 |
receive messages, regardless of the order in which they were sent. |
1107 |
|
1108 |
In these cases, L<Coro::MP> can provide a nice solution: instead of |
1109 |
registering callbacks for each message type, C<Coro::MP> attaches a |
1110 |
(coro-) thread to a port. The thread can then opt to selectively receive |
1111 |
messages it is interested in. Other messages are not lost, but queued, and |
1112 |
can be received at a later time. |
1113 |
|
1114 |
The C<Coro::MP> module is not part of L<AnyEvent::MP>, but a separate |
1115 |
module. It is, however, tightly integrated into C<AnyEvent::MP> - the |
1116 |
ports it creates are fully compatible to C<AnyEvent::MP> ports. |
1117 |
|
1118 |
In fact, C<Coro::MP> is more of an extension than a separate module: all |
1119 |
functions exported by C<AnyEvent::MP> are exported by it as well. |
1120 |
|
1121 |
To illustrate how programing with C<Coro::MP> looks like, consider the |
1122 |
following (slightly contrived) example: Let's implement a server that |
1123 |
accepts a C<< (write_file =>, $port, $path) >> message with a (source) |
1124 |
port and a filename, followed by as many C<< (data => $port, $data) >> |
1125 |
messages as required to fill the file, followed by an empty C<< (data => |
1126 |
$port) >> message. |
1127 |
|
1128 |
The server only writes a single file at a time, other requests will stay |
1129 |
in the queue until the current file has been finished. |
1130 |
|
1131 |
Here is an example implementation that uses L<Coro::AIO> and largely |
1132 |
ignores error handling: |
1133 |
|
1134 |
my $ioserver = port_async { |
1135 |
while () { |
1136 |
my ($tag, $port, $path) = get_cond; |
1137 |
|
1138 |
$tag eq "write_file" |
1139 |
or die "only write_file messages expected"; |
1140 |
|
1141 |
my $fh = aio_open $path, O_WRONLY|O_CREAT, 0666 |
1142 |
or die "$path: $!"; |
1143 |
|
1144 |
while () { |
1145 |
my (undef, undef, $data) = get_cond { |
1146 |
$_[0] eq "data" && $_[1] eq $port |
1147 |
} 5 |
1148 |
or die "timeout waiting for data message from $port\n"; |
1149 |
|
1150 |
length $data or last; |
1151 |
|
1152 |
aio_write $fh, undef, undef, $data, 0; |
1153 |
}; |
1154 |
} |
1155 |
}; |
1156 |
|
1157 |
mon $ioserver, sub { |
1158 |
warn "ioserver was killed: @_\n"; |
1159 |
}; |
1160 |
|
1161 |
Let's go through it, section by section. |
1162 |
|
1163 |
my $ioserver = port_async { |
1164 |
|
1165 |
Ports can be created by attaching a thread to an existing port via |
1166 |
C<rcv_async>, or as in this example, by calling C<port_async> with the |
1167 |
code to execute as a thread. The C<async> component comes from the fact |
1168 |
that threads are created using the C<Coro::async> function. |
1169 |
|
1170 |
The thread runs in a normal port context (so C<$SELF> is set). In |
1171 |
addition, when the thread returns, it will be C<kil> I<normally>, i.e. |
1172 |
without a reason argument. |
1173 |
|
1174 |
while () { |
1175 |
my ($tag, $port, $path) = get_cond; |
1176 |
or die "only write_file messages expected"; |
1177 |
|
1178 |
The thread is supposed to serve many file writes, which is why it |
1179 |
executes in a loop. The first thing it does is fetch the next message, |
1180 |
using C<get_cond>, the "conditional message get". Without arguments, it |
1181 |
merely fetches the I<next> message from the queue, which I<must> be a |
1182 |
C<write_file> message. |
1183 |
|
1184 |
The message contains the C<$path> to the file, which is then created: |
1185 |
|
1186 |
my $fh = aio_open $path, O_WRONLY|O_CREAT, 0666 |
1187 |
or die "$path: $!"; |
1188 |
|
1189 |
Then we enter a loop again, to serve as many C<data> messages as |
1190 |
necessary: |
1191 |
|
1192 |
while () { |
1193 |
my (undef, undef, $data) = get_cond { |
1194 |
$_[0] eq "data" && $_[1] eq $port |
1195 |
} 5 |
1196 |
or die "timeout waiting for data message from $port\n"; |
1197 |
|
1198 |
This time, the condition is not empty, but instead a code block: similarly |
1199 |
to grep, the code block will be called with C<@_> set to each message in |
1200 |
the queue, and it has to return whether it wants to receive the message or |
1201 |
not. |
1202 |
|
1203 |
In this case we are interested in C<data> messages (C<< $_[0] eq "data" |
1204 |
>>), whose first element is the source port (C<< $_[1] eq $port >>). |
1205 |
|
1206 |
The condition must be this strict, as it is possible to receive both |
1207 |
C<write_file> messages and C<data> messages from other ports while we |
1208 |
handle the file writing. |
1209 |
|
1210 |
The lone C<5> argument at the end is a timeout - when no matching message |
1211 |
is received within C<5> seconds, we assume an error and C<die>. |
1212 |
|
1213 |
When an empty C<data> message is received we are done and can close the |
1214 |
file (which is done automatically as C<$fh> goes out of scope): |
1215 |
|
1216 |
length $data or last; |
1217 |
|
1218 |
Otherwise we need to write the data: |
1219 |
|
1220 |
aio_write $fh, undef, undef, $data, 0; |
1221 |
|
1222 |
And that's basically it. Note that every port thread should have some |
1223 |
kind of supervisor. In our case, the supervisor simply prints any error |
1224 |
message: |
1225 |
|
1226 |
mon $ioserver, sub { |
1227 |
warn "ioserver was killed: @_\n"; |
1228 |
}; |
1229 |
|
1230 |
Here is a usage example: |
1231 |
|
1232 |
port_async { |
1233 |
snd $ioserver, write_file => $SELF, "/tmp/unsafe"; |
1234 |
snd $ioserver, data => $SELF, "abc\n"; |
1235 |
snd $ioserver, data => $SELF, "def\n"; |
1236 |
snd $ioserver, data => $SELF; |
1237 |
}; |
1238 |
|
1239 |
The messages are sent without any flow control or acknowledgement (feel |
1240 |
free to improve). Also, the source port does not actually need to be a |
1241 |
port - any unique ID will do - but port identifiers happen to be a simple |
1242 |
source of network-wide unique IDs. |
1243 |
|
1244 |
Apart from C<get_cond> as seen above, there are other ways to receive |
1245 |
messages. The C<write_file> message above could also selectively be |
1246 |
received using a C<get> call: |
1247 |
|
1248 |
my ($port, $path) = get "write_file"; |
1249 |
|
1250 |
This is simpler, but when some other code part sends an unexpected message |
1251 |
to the C<$ioserver> it will stay in the queue forever. As a rule of thumb, |
1252 |
every threaded port should have a "fetch next message unconditionally" |
1253 |
somewhere, to avoid filling up the queue. |
1254 |
|
1255 |
Finally, it is also possible to use more switch-like C<get_conds>: |
1256 |
|
1257 |
get_cond { |
1258 |
$_[0] eq "msg1" and return sub { |
1259 |
my (undef, @msg1_data) = @_; |
1260 |
...; |
1261 |
}; |
1262 |
|
1263 |
$_[0] eq "msg2" and return sub { |
1264 |
my (undef, @msg2_data) = @_; |
1265 |
...; |
1266 |
}; |
1267 |
|
1268 |
die "unexpected message $_[0] received"; |
1269 |
}; |
1270 |
|
1271 |
=head1 THE END |
1272 |
|
1273 |
This is the end of this introduction, but hopefully not the end of |
1274 |
your career as AEMP user. I hope the tutorial was enough to make the |
1275 |
basic concepts clear. Keep in mind that distributed programming is not |
1276 |
completely trivial, in fact, it's pretty complicated. We hope AEMP makes |
1277 |
it simpler and will be useful to create exciting new applications. |
1278 |
|
1279 |
=head1 SEE ALSO |
1280 |
|
1281 |
L<AnyEvent::MP> |
1282 |
|
1283 |
L<AnyEvent::MP::Global> |
1284 |
|
1285 |
L<Coro::MP> |
1286 |
|
1287 |
L<AnyEvent> |
1288 |
|
1289 |
=head1 AUTHOR |
1290 |
|
1291 |
Robin Redeker <elmex@ta-sa.org> |
1292 |
Marc Lehmann <schmorp@schmorp.de> |
1293 |
|