ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-Fork-RPC/README
(Generate patch)

Comparing AnyEvent-Fork-RPC/README (file contents):
Revision 1.2 by root, Thu Apr 18 20:04:51 2013 UTC vs.
Revision 1.5 by root, Thu May 12 16:54:43 2016 UTC

1NAME 1NAME
2 AnyEvent::Fork::RPC - simple RPC extension for AnyEvent::Fork 2 AnyEvent::Fork::RPC - simple RPC extension for AnyEvent::Fork
3 3
4 THE API IS NOT FINISHED, CONSIDER THIS A TECHNOLOGY DEMO
5
6SYNOPSIS 4SYNOPSIS
5 use AnyEvent::Fork;
7 use AnyEvent::Fork::RPC; 6 use AnyEvent::Fork::RPC;
8 # use AnyEvent::Fork is not needed
9 7
10 my $rpc = AnyEvent::Fork 8 my $rpc = AnyEvent::Fork
11 ->new 9 ->new
12 ->require ("MyModule") 10 ->require ("MyModule")
13 ->AnyEvent::Fork::RPC::run ( 11 ->AnyEvent::Fork::RPC::run (
25 23
26 $cv->recv; 24 $cv->recv;
27 25
28DESCRIPTION 26DESCRIPTION
29 This module implements a simple RPC protocol and backend for processes 27 This module implements a simple RPC protocol and backend for processes
30 created via AnyEvent::Fork, allowing you to call a function in the child 28 created via AnyEvent::Fork or AnyEvent::Fork::Remote, allowing you to
31 process and receive its return values (up to 4GB serialised). 29 call a function in the child process and receive its return values (up
30 to 4GB serialised).
32 31
33 It implements two different backends: a synchronous one that works like 32 It implements two different backends: a synchronous one that works like
34 a normal function call, and an asynchronous one that can run multiple 33 a normal function call, and an asynchronous one that can run multiple
35 jobs concurrently in the child, using AnyEvent. 34 jobs concurrently in the child, using AnyEvent.
36 35
37 It also implements an asynchronous event mechanism from the child to the 36 It also implements an asynchronous event mechanism from the child to the
38 parent, that could be used for progress indications or other 37 parent, that could be used for progress indications or other
39 information. 38 information.
40
41 Loading this module also always loads AnyEvent::Fork, so you can make a
42 separate "use AnyEvent::Fork" if you wish, but you don't have to.
43 39
44EXAMPLES 40EXAMPLES
45 Example 1: Synchronous Backend 41 Example 1: Synchronous Backend
46 Here is a simple example that implements a backend that executes 42 Here is a simple example that implements a backend that executes
47 "unlink" and "rmdir" calls, and reports their status back. It also 43 "unlink" and "rmdir" calls, and reports their status back. It also
49 which is clearly silly, but illustrates the use of events. 45 which is clearly silly, but illustrates the use of events.
50 46
51 First the parent process: 47 First the parent process:
52 48
53 use AnyEvent; 49 use AnyEvent;
50 use AnyEvent::Fork;
54 use AnyEvent::Fork::RPC; 51 use AnyEvent::Fork::RPC;
55 52
56 my $done = AE::cv; 53 my $done = AE::cv;
57 54
58 my $rpc = AnyEvent::Fork 55 my $rpc = AnyEvent::Fork
59 ->new 56 ->new
60 ->require ("MyWorker") 57 ->require ("MyWorker")
61 ->AnyEvent::Fork::RPC::run ("MyWorker::run", 58 ->AnyEvent::Fork::RPC::run ("MyWorker::run",
62 on_error => sub { warn "FATAL: $_[0]"; exit 1 }, 59 on_error => sub { warn "ERROR: $_[0]"; exit 1 },
63 on_event => sub { warn "$_[0] requests handled\n" }, 60 on_event => sub { warn "$_[0] requests handled\n" },
64 on_destroy => $done, 61 on_destroy => $done,
65 ); 62 );
66 63
67 for my $id (1..6) { 64 for my $id (1..6) {
173 child process may exit at any time, so you should call $done only when 170 child process may exit at any time, so you should call $done only when
174 you really *are* done. 171 you really *are* done.
175 172
176 Example 2: Asynchronous Backend 173 Example 2: Asynchronous Backend
177 This example implements multiple count-downs in the child, using 174 This example implements multiple count-downs in the child, using
178 AnyEvent timers. While this is a bit silly (one could use timers in te 175 AnyEvent timers. While this is a bit silly (one could use timers in the
179 parent just as well), it illustrates the ability to use AnyEvent in the 176 parent just as well), it illustrates the ability to use AnyEvent in the
180 child and the fact that responses can arrive in a different order then 177 child and the fact that responses can arrive in a different order then
181 the requests. 178 the requests.
182 179
183 It also shows how to embed the actual child code into a "__DATA__" 180 It also shows how to embed the actual child code into a "__DATA__"
188 look so silly anymore. 185 look so silly anymore.
189 186
190 Without further ado, here is the code: 187 Without further ado, here is the code:
191 188
192 use AnyEvent; 189 use AnyEvent;
190 use AnyEvent::Fork;
193 use AnyEvent::Fork::RPC; 191 use AnyEvent::Fork::RPC;
194 192
195 my $done = AE::cv; 193 my $done = AE::cv;
196 194
197 my $rpc = AnyEvent::Fork 195 my $rpc = AnyEvent::Fork
198 ->new 196 ->new
199 ->require ("AnyEvent::Fork::RPC::Async") 197 ->require ("AnyEvent::Fork::RPC::Async")
200 ->eval (do { local $/; <DATA> }) 198 ->eval (do { local $/; <DATA> })
201 ->AnyEvent::Fork::RPC::run ("run", 199 ->AnyEvent::Fork::RPC::run ("run",
202 async => 1, 200 async => 1,
203 on_error => sub { warn "FATAL: $_[0]"; exit 1 }, 201 on_error => sub { warn "ERROR: $_[0]"; exit 1 },
204 on_event => sub { print $_[0] }, 202 on_event => sub { print $_[0] },
205 on_destroy => $done, 203 on_destroy => $done,
206 ); 204 );
207 205
208 for my $count (3, 2, 1) { 206 for my $count (3, 2, 1) {
284 282
285 This concludes the async example. Since AnyEvent::Fork does not actually 283 This concludes the async example. Since AnyEvent::Fork does not actually
286 fork, you are free to use about any module in the child, not just 284 fork, you are free to use about any module in the child, not just
287 AnyEvent, but also IO::AIO, or Tk for example. 285 AnyEvent, but also IO::AIO, or Tk for example.
288 286
287 Example 3: Asynchronous backend with Coro
288 With Coro you can create a nice asynchronous backend implementation by
289 defining an rpc server function that creates a new Coro thread for every
290 request that calls a function "normally", i.e. the parameters from the
291 parent process are passed to it, and any return values are returned to
292 the parent process, e.g.:
293
294 package My::Arith;
295
296 sub add {
297 return $_[0] + $_[1];
298 }
299
300 sub mul {
301 return $_[0] * $_[1];
302 }
303
304 sub run {
305 my ($done, $func, @arg) = @_;
306
307 Coro::async_pool {
308 $done->($func->(@arg));
309 };
310 }
311
312 The "run" function creates a new thread for every invocation, using the
313 first argument as function name, and calls the $done callback on it's
314 return values. This makes it quite natural to define the "add" and "mul"
315 functions to add or multiply two numbers and return the result.
316
317 Since this is the asynchronous backend, it's quite possible to define
318 RPC function that do I/O or wait for external events - their execution
319 will overlap as needed.
320
321 The above could be used like this:
322
323 my $rpc = AnyEvent::Fork
324 ->new
325 ->require ("MyWorker")
326 ->AnyEvent::Fork::RPC::run ("My::Arith::run",
327 on_error => ..., on_event => ..., on_destroy => ...,
328 );
329
330 $rpc->(add => 1, 3, Coro::rouse_cb); say Coro::rouse_wait;
331 $rpc->(mul => 3, 2, Coro::rouse_cb); say Coro::rouse_wait;
332
333 The "say"'s will print 4 and 6.
334
335 Example 4: Forward AnyEvent::Log messages using "on_event"
336 This partial example shows how to use the "event" function to forward
337 AnyEvent::Log messages to the parent.
338
339 For this, the parent needs to provide a suitable "on_event":
340
341 ->AnyEvent::Fork::RPC::run (
342 on_event => sub {
343 if ($_[0] eq "ae_log") {
344 my (undef, $level, $message) = @_;
345 AE::log $level, $message;
346 } else {
347 # other event types
348 }
349 },
350 )
351
352 In the child, as early as possible, the following code should
353 reconfigure AnyEvent::Log to log via "AnyEvent::Fork::RPC::event":
354
355 $AnyEvent::Log::LOG->log_cb (sub {
356 my ($timestamp, $orig_ctx, $level, $message) = @{+shift};
357
358 if (defined &AnyEvent::Fork::RPC::event) {
359 AnyEvent::Fork::RPC::event (ae_log => $level, $message);
360 } else {
361 warn "[$$ before init] $message\n";
362 }
363 });
364
365 There is an important twist - the "AnyEvent::Fork::RPC::event" function
366 is only defined when the child is fully initialised. If you redirect the
367 log messages in your "init" function for example, then the "event"
368 function might not yet be available. This is why the log callback checks
369 whether the fucntion is there using "defined", and only then uses it to
370 log the message.
371
289PARENT PROCESS USAGE 372PARENT PROCESS USAGE
290 This module exports nothing, and only implements a single function: 373 This module exports nothing, and only implements a single function:
291 374
292 my $rpc = AnyEvent::Fork::RPC::run $fork, $function, [key => value...] 375 my $rpc = AnyEvent::Fork::RPC::run $fork, $function, [key => value...]
293 The traditional way to call it. But it is way cooler to call it in 376 The traditional way to call it. But it is way cooler to call it in
311 Called on (fatal) errors, with a descriptive (hopefully) 394 Called on (fatal) errors, with a descriptive (hopefully)
312 message. If this callback is not provided, but "on_event" is, 395 message. If this callback is not provided, but "on_event" is,
313 then the "on_event" callback is called with the first argument 396 then the "on_event" callback is called with the first argument
314 being the string "error", followed by the error message. 397 being the string "error", followed by the error message.
315 398
316 If neither handler is provided it prints the error to STDERR and 399 If neither handler is provided, then the error is reported with
317 will start failing badly. 400 loglevel "error" via "AE::log".
318 401
319 on_event => $cb->(...) 402 on_event => $cb->(...)
320 Called for every call to the "AnyEvent::Fork::RPC::event" 403 Called for every call to the "AnyEvent::Fork::RPC::event"
321 function in the child, with the arguments of that function 404 function in the child, with the arguments of that function
322 passed to the callback. 405 passed to the callback.
343 It is called very early - before the serialisers are created or 426 It is called very early - before the serialisers are created or
344 the $function name is resolved into a function reference, so it 427 the $function name is resolved into a function reference, so it
345 could be used to load any modules that provide the serialiser or 428 could be used to load any modules that provide the serialiser or
346 function. It can not, however, create events. 429 function. It can not, however, create events.
347 430
431 done => $function (default "CORE::exit")
432 The function to call when the asynchronous backend detects an
433 end of file condition when reading from the communications
434 socket *and* there are no outstanding requests. It's ignored by
435 the synchronous backend.
436
437 By overriding this you can prolong the life of a RPC process
438 after e.g. the parent has exited by running the event loop in
439 the provided function (or simply calling it, for example, when
440 your child process uses EV you could provide EV::run as "done"
441 function).
442
443 Of course, in that case you are responsible for exiting at the
444 appropriate time and not returning from
445
348 async => $boolean (default: 0) 446 async => $boolean (default: 0)
349 The default server used in the child does all I/O blockingly, 447 The default server used in the child does all I/O blockingly,
350 and only allows a single RPC call to execute concurrently. 448 and only allows a single RPC call to execute concurrently.
351 449
352 Setting "async" to a true value switches to another 450 Setting "async" to a true value switches to another
371 to be transferred between the processes. For this, they have to 469 to be transferred between the processes. For this, they have to
372 be frozen and thawed in both parent and child processes. 470 be frozen and thawed in both parent and child processes.
373 471
374 By default, only octet strings can be passed between the 472 By default, only octet strings can be passed between the
375 processes, which is reasonably fast and efficient and requires 473 processes, which is reasonably fast and efficient and requires
376 no extra modules. 474 no extra modules (the "AnyEvent::Fork::RPC" distribution does
475 not provide these extra serialiser modules).
377 476
378 For more complicated use cases, you can provide your own freeze 477 For more complicated use cases, you can provide your own freeze
379 and thaw functions, by specifying a string with perl source 478 and thaw functions, by specifying a string with perl source
380 code. It's supposed to return two code references when 479 code. It's supposed to return two code references when
381 evaluated: the first receives a list of perl values and must 480 evaluated: the first receives a list of perl values and must
385 If you need an external module for serialisation, then you can 484 If you need an external module for serialisation, then you can
386 either pre-load it into your AnyEvent::Fork process, or you can 485 either pre-load it into your AnyEvent::Fork process, or you can
387 add a "use" or "require" statement into the serialiser string. 486 add a "use" or "require" statement into the serialiser string.
388 Or both. 487 Or both.
389 488
390 Here are some examples - some of them are also available as 489 Here are some examples - all of them are also available as
391 global variables that make them easier to use. 490 global variables that make them easier to use.
392 491
393 octet strings - $AnyEvent::Fork::RPC::STRING_SERIALISER 492 $AnyEvent::Fork::RPC::STRING_SERIALISER - octet strings only
394 This serialiser concatenates length-prefixes octet strings, 493 This serialiser (currently the default) concatenates
395 and is the default. 494 length-prefixes octet strings, and is the default. That
495 means you can only pass (and return) strings containing
496 character codes 0-255.
497
498 The main advantages of this serialiser are the high speed
499 and that it doesn't need another module. The main
500 disadvantage is that you are very limited in what you can
501 pass - only octet strings.
396 502
397 Implementation: 503 Implementation:
398 504
399 ( 505 (
400 sub { pack "(w/a*)*", @_ }, 506 sub { pack "(w/a*)*", @_ },
401 sub { unpack "(w/a*)*", shift } 507 sub { unpack "(w/a*)*", shift }
402 ) 508 )
403 509
510 $AnyEvent::Fork::RPC::CBOR_XS_SERIALISER - uses CBOR::XS
511 This serialiser creates CBOR::XS arrays - you have to make
512 sure the CBOR::XS module is installed for this serialiser to
513 work. It can be beneficial for sharing when you preload the
514 CBOR::XS module in a template process.
515
516 CBOR::XS is about as fast as the octet string serialiser,
517 but supports complex data structures (similar to JSON) and
518 is faster than any of the other serialisers. If you have the
519 CBOR::XS module available, it's the best choice.
520
521 The encoder enables "allow_sharing" (so this serialisation
522 method can encode cyclic and self-referencing data
523 structures).
524
525 Implementation:
526
527 use CBOR::XS ();
528 (
529 sub { CBOR::XS::encode_cbor_sharing \@_ },
530 sub { @{ CBOR::XS::decode_cbor shift } }
531 )
532
404 json - $AnyEvent::Fork::RPC::JSON_SERIALISER 533 $AnyEvent::Fork::RPC::JSON_SERIALISER - uses JSON::XS or JSON
405 This serialiser creates JSON arrays - you have to make sure 534 This serialiser creates JSON arrays - you have to make sure
406 the JSON module is installed for this serialiser to work. It 535 the JSON module is installed for this serialiser to work. It
407 can be beneficial for sharing when you preload the JSON 536 can be beneficial for sharing when you preload the JSON
408 module in a template process. 537 module in a template process.
409 538
417 ( 546 (
418 sub { JSON::encode_json \@_ }, 547 sub { JSON::encode_json \@_ },
419 sub { @{ JSON::decode_json shift } } 548 sub { @{ JSON::decode_json shift } }
420 ) 549 )
421 550
422 storable - $AnyEvent::Fork::RPC::STORABLE_SERIALISER 551 $AnyEvent::Fork::RPC::STORABLE_SERIALISER - Storable
423 This serialiser uses Storable, which means it has high 552 This serialiser uses Storable, which means it has high
424 chance of serialising just about anything you throw at it, 553 chance of serialising just about anything you throw at it,
425 at the cost of having very high overhead per operation. It 554 at the cost of having very high overhead per operation. It
426 also comes with perl. 555 also comes with perl. It should be used when you need to
556 serialise complex data structures.
427 557
428 Implementation: 558 Implementation:
429 559
430 use Storable (); 560 use Storable ();
431 ( 561 (
432 sub { Storable::freeze \@_ }, 562 sub { Storable::freeze \@_ },
563 sub { @{ Storable::thaw shift } }
564 )
565
566 $AnyEvent::Fork::RPC::NSTORABLE_SERIALISER - portable Storable
567 This serialiser also uses Storable, but uses it's "network"
568 format to serialise data, which makes it possible to talk to
569 different perl binaries (for example, when talking to a
570 process created with AnyEvent::Fork::Remote).
571
572 Implementation:
573
574 use Storable ();
575 (
576 sub { Storable::nfreeze \@_ },
433 sub { @{ Storable::thaw shift } } 577 sub { @{ Storable::thaw shift } }
434 ) 578 )
435 579
436 See the examples section earlier in this document for some actual 580 See the examples section earlier in this document for some actual
437 examples. 581 examples.
471 the child process to the parent, except that there is no notion of 615 the child process to the parent, except that there is no notion of
472 return values. 616 return values.
473 617
474 See the examples section earlier in this document for some actual 618 See the examples section earlier in this document for some actual
475 examples. 619 examples.
620
621 PROCESS EXIT
622 If and when the child process exits depends on the backend and
623 configuration. Apart from explicit exits (e.g. by calling "exit") or
624 runtime conditions (uncaught exceptions, signals etc.), the backends
625 exit under these conditions:
626
627 Synchronous Backend
628 The synchronous backend is very simple: when the process waits for
629 another request to arrive and the writing side (usually in the
630 parent) is closed, it will exit normally, i.e. as if your main
631 program reached the end of the file.
632
633 That means that if your parent process exits, the RPC process will
634 usually exit as well, either because it is idle anyway, or because
635 it executes a request. In the latter case, you will likely get an
636 error when the RPc process tries to send the results to the parent
637 (because agruably, you shouldn't exit your parent while there are
638 still outstanding requests).
639
640 The process is usually quiescent when it happens, so it should
641 rarely be a problem, and "END" handlers can be used to clean up.
642
643 Asynchronous Backend
644 For the asynchronous backend, things are more complicated: Whenever
645 it listens for another request by the parent, it might detect that
646 the socket was closed (e.g. because the parent exited). It will sotp
647 listening for new requests and instead try to write out any
648 remaining data (if any) or simply check whether the socket can be
649 written to. After this, the RPC process is effectively done - no new
650 requests are incoming, no outstanding request data can be written
651 back.
652
653 Since chances are high that there are event watchers that the RPC
654 server knows nothing about (why else would one use the async backend
655 if not for the ability to register watchers?), the event loop would
656 often happily continue.
657
658 This is why the asynchronous backend explicitly calls "CORE::exit"
659 when it is done (under other circumstances, such as when there is an
660 I/O error and there is outstanding data to write, it will log a
661 fatal message via AnyEvent::Log, also causing the program to exit).
662
663 You can override this by specifying a function name to call via the
664 "done" parameter instead.
476 665
477ADVANCED TOPICS 666ADVANCED TOPICS
478 Choosing a backend 667 Choosing a backend
479 So how do you decide which backend to use? Well, that's your problem to 668 So how do you decide which backend to use? Well, that's your problem to
480 solve, but here are some thoughts on the matter: 669 solve, but here are some thoughts on the matter:
529 1000 jobs are queued and the jobs are slow, they will all run 718 1000 jobs are queued and the jobs are slow, they will all run
530 concurrently. The child must implement some queueing/limiting 719 concurrently. The child must implement some queueing/limiting
531 mechanism if this causes problems. Alternatively, the parent could 720 mechanism if this causes problems. Alternatively, the parent could
532 limit the amount of rpc calls that are outstanding. 721 limit the amount of rpc calls that are outstanding.
533 722
534 Blocking use of condvars is not supported. 723 Blocking use of condvars is not supported (in the main thread,
724 outside of e.g. Coro threads).
535 725
536 Using event-based modules such as IO::AIO, Gtk2, Tk and so on is 726 Using event-based modules such as IO::AIO, Gtk2, Tk and so on is
537 easy. 727 easy.
538 728
539 Passing file descriptors 729 Passing file descriptors
553 the half it has passed earlier. 743 the half it has passed earlier.
554 744
555 Here is some (untested) pseudocode to that effect: 745 Here is some (untested) pseudocode to that effect:
556 746
557 use AnyEvent::Util; 747 use AnyEvent::Util;
748 use AnyEvent::Fork;
558 use AnyEvent::Fork::RPC; 749 use AnyEvent::Fork::RPC;
559 use IO::FDPass; 750 use IO::FDPass;
560 751
561 my ($s1, $s2) = AnyEvent::Util::portable_socketpair; 752 my ($s1, $s2) = AnyEvent::Util::portable_socketpair;
562 753
598 789
599 Of course, this might be blocking if you pass a lot of file descriptors, 790 Of course, this might be blocking if you pass a lot of file descriptors,
600 so you might want to look into AnyEvent::FDpasser which can handle the 791 so you might want to look into AnyEvent::FDpasser which can handle the
601 gory details. 792 gory details.
602 793
794EXCEPTIONS
795 There are no provisions whatsoever for catching exceptions at this time
796 - in the child, exceptions might kill the process, causing calls to be
797 lost and the parent encountering a fatal error. In the parent,
798 exceptions in the result callback will not be caught and cause undefined
799 behaviour.
800
603SEE ALSO 801SEE ALSO
604 AnyEvent::Fork, to create the processes in the first place. 802 AnyEvent::Fork, to create the processes in the first place.
803
804 AnyEvent::Fork::Remote, likewise, but helpful for remote processes.
605 805
606 AnyEvent::Fork::Pool, to manage whole pools of processes. 806 AnyEvent::Fork::Pool, to manage whole pools of processes.
607 807
608AUTHOR AND CONTACT INFORMATION 808AUTHOR AND CONTACT INFORMATION
609 Marc Lehmann <schmorp@schmorp.de> 809 Marc Lehmann <schmorp@schmorp.de>

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines