Imported Upstream version 3.2.0
[debian/amanda] / perl / Amanda / MainLoop.pm
1 # This file was automatically generated by SWIG (http://www.swig.org).
2 # Version 1.3.39
3 #
4 # Do not make changes to this file unless you know what you are doing--modify
5 # the SWIG interface file instead.
6
7 package Amanda::MainLoop;
8 use base qw(Exporter);
9 use base qw(DynaLoader);
10 package Amanda::MainLoopc;
11 bootstrap Amanda::MainLoop;
12 package Amanda::MainLoop;
13 @EXPORT = qw();
14
15 # ---------- BASE METHODS -------------
16
17 package Amanda::MainLoop;
18
19 sub TIEHASH {
20     my ($classname,$obj) = @_;
21     return bless $obj, $classname;
22 }
23
24 sub CLEAR { }
25
26 sub FIRSTKEY { }
27
28 sub NEXTKEY { }
29
30 sub FETCH {
31     my ($self,$field) = @_;
32     my $member_func = "swig_${field}_get";
33     $self->$member_func();
34 }
35
36 sub STORE {
37     my ($self,$field,$newval) = @_;
38     my $member_func = "swig_${field}_set";
39     $self->$member_func($newval);
40 }
41
42 sub this {
43     my $ptr = shift;
44     return tied(%$ptr);
45 }
46
47
48 # ------- FUNCTION WRAPPERS --------
49
50 package Amanda::MainLoop;
51
52 *run_c = *Amanda::MainLoopc::run_c;
53 *quit = *Amanda::MainLoopc::quit;
54 *timeout_source = *Amanda::MainLoopc::timeout_source;
55 *idle_source = *Amanda::MainLoopc::idle_source;
56 *child_watch_source = *Amanda::MainLoopc::child_watch_source;
57 *fd_source = *Amanda::MainLoopc::fd_source;
58
59 ############# Class : Amanda::MainLoop::Source ##############
60
61 package Amanda::MainLoop::Source;
62 use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
63 @ISA = qw( Amanda::MainLoop );
64 %OWNER = ();
65 %ITERATORS = ();
66 sub new {
67     my $pkg = shift;
68     my $self = Amanda::MainLoopc::new_Source(@_);
69     bless $self, $pkg if defined($self);
70 }
71
72 sub DESTROY {
73     return unless $_[0]->isa('HASH');
74     my $self = tied(%{$_[0]});
75     return unless defined $self;
76     delete $ITERATORS{$self};
77     if (exists $OWNER{$self}) {
78         Amanda::MainLoopc::delete_Source($self);
79         delete $OWNER{$self};
80     }
81 }
82
83 *set_callback = *Amanda::MainLoopc::Source_set_callback;
84 *remove = *Amanda::MainLoopc::Source_remove;
85 sub DISOWN {
86     my $self = shift;
87     my $ptr = tied(%$self);
88     delete $OWNER{$ptr};
89 }
90
91 sub ACQUIRE {
92     my $self = shift;
93     my $ptr = tied(%$self);
94     $OWNER{$ptr} = 1;
95 }
96
97
98 # ------- VARIABLE STUBS --------
99
100 package Amanda::MainLoop;
101
102 *G_IO_IN = *Amanda::MainLoopc::G_IO_IN;
103 *G_IO_OUT = *Amanda::MainLoopc::G_IO_OUT;
104 *G_IO_PRI = *Amanda::MainLoopc::G_IO_PRI;
105 *G_IO_ERR = *Amanda::MainLoopc::G_IO_ERR;
106 *G_IO_HUP = *Amanda::MainLoopc::G_IO_HUP;
107 *G_IO_NVAL = *Amanda::MainLoopc::G_IO_NVAL;
108
109 @EXPORT_OK = ();
110 %EXPORT_TAGS = ();
111
112
113 =head1 NAME
114
115 Amanda::MainLoop - Perl interface to the Glib MainLoop
116
117 =head1 SYNOPSIS
118
119     use Amanda::MainLoop;
120
121     my $to = Amanda::MainLoop::timeout_source(2000);
122     $to->set_callback(sub {
123         print "Time's Up!\n";
124         $to->remove();              # dont' re-queue this timeout
125         Amanda::MainLoop::quit();   # return from Amanda::MainLoop::run
126     });
127
128     Amanda::MainLoop::run();
129
130 Note that all functions in this module are individually available for
131 export, e.g.,
132
133     use Amanda::MainLoop qw(run quit);
134
135 =head1 OVERVIEW
136
137 The main event loop of an application is a tight loop which waits for
138 events, and calls functions to respond to those events.  This design
139 allows an IO-bound application to multitask within a single thread, by
140 responding to IO events as they occur instead of blocking on
141 particular IO operations.
142
143 The Amanda security API, transfer API, and other components rely on
144 the event loop to allow them to respond to their own events in a
145 timely fashion.
146
147 The overall structure of an application, then, is to initialize its
148 state, register callbacks for some events, and begin looping.  In each
149 iteration, the loop waits for interesting events to occur (data
150 available for reading or writing, timeouts, etc.), and then calls
151 functions to handle those interesting things.  Thus, the application
152 spends most of its time waiting.  When some application-defined state
153 is reached, the loop is terminated and the application cleans up and
154 exits.
155
156 The Glib main loop takes place within a call to
157 C<Amanda::MainLoop::run()>.  This function executes until a call to
158 C<Amanda::MainLoop::quit()> occurs, at which point C<run()> returns.
159 You can check whether the loop is running with
160 C<Amanda::MainLoop::is_running()>.
161
162 =head1 HIGH-LEVEL INTERFACE
163
164 The functions in this section are intended to make asynchronous
165 programming as simple as possible.  They are implemented on top of the
166 interfaces described in the LOW-LEVEL INTERFACE section.
167
168 =head3 call_later
169
170 In most cases, a callback does not need to be invoked immediately.  In
171 fact, because Perl does not do tail-call optimization, a long chain of
172 callbacks may cause the perl stack to grow unnecessarily.
173
174 The solution is to queue the callback for execution on the next
175 iteration of the main loop, and C<call_later($cb, @args)> does exactly
176 this.
177
178     sub might_delay {
179         my ($cb) = @_;
180         if (can_do_it_now()) {
181             my $result = do_it();
182             Amanda::MainLoop::call_later($cb, $result)
183         } else {
184             # ..
185         }
186     }
187
188 When starting the main loop, an application usually has a sub that
189 should run after the loop has started.  C<call_later> works in this
190 situation, too.
191
192     my $main = sub {
193         # ..
194         Amanda::MainLoop::quit();
195     };
196     Amanda::MainLoop::call_later($main);
197     # ..
198     Amanda::MainLoop::run();
199
200 =head3 make_cb
201
202 As an optimization, C<make_cb> wraps a sub with a call to call_later
203 while also naming the sub (using C<Sub::Name>, if available):
204
205     my $fetched_cb = make_cb(fetched_cb => sub {
206         # .. callback body
207     }
208
209 In general, C<make_cb> should be used whenever a callback is passed to
210 some other library.  For example, the Changer API (see
211 L<Amanda::Changer>) might be invoked like this:
212
213     my $reset_finished_cb = make_cb(reset_finished_cb => sub {
214         my ($err) = @_;
215         die "while resetting: $err" if $err;
216         # ..
217     });
218
219 Be careful I<not> to use C<make_cb> in cases where some action must
220 take place before the next iteration of the main loop.  In practice,
221 this means C<make_cb> should be avoided with file-descriptor
222 callbacks, which will trigger repeatedly until the descriptors' needs
223 are addressed.
224
225 C<make_cb> is exported automatically.
226
227 =head3 call_after
228
229 Sometimes you need the MainLoop equivalent of C<sleep()>.  That comes
230 in the form of C<call_later($delay, $cb, @args)>, which takes a delay
231 (in milliseconds), a sub, and an arbitrary number of arguments.  The
232 sub is called with the arguments after the delay has elapsed.
233
234     sub countdown {
235         my $counter;
236         $counter = sub {
237             print "$i..\n";
238             if ($i) {
239                 Amanda::MainLoop::call_after(1000, $counter, $i-1);
240             }
241         }
242         $counter->(10);
243     }
244
245 The function returns the underlying event source (see below), enabling
246 the caller to cancel the pending call:
247
248     my $tosrc = Amanda::MainLoop::call_after(15000, $timeout_cb):
249     # ...data arrives before timeout...
250     $tosrc->remove();
251
252 =head3 call_on_child_termination
253
254 To monitor a child process for termination, give its pid to
255 C<call_on_child_termination($pid, $cb, @args)>.  When the child exits
256 for any reason, this will collect its exit status (via C<waitpid>) and
257 call C<$cb> as
258
259     $cb->($exitstatus, @args);
260
261 Like C<call_after>, this function returns the event source to allow
262 early cancellation if desired.
263
264 =head3 async_read
265
266     async_read(
267         fd => $fd,
268         size => $size,        # optional, default 0
269         async_read_cb => $async_read_cb,
270         args => [ .. ]);      # optional
271
272 This function will read C<$size> bytes when they are available from
273 file descriptor C<$fd>, and invoke the callback with the results:
274
275     $async_read_cb->($err, $buf, @args);
276
277 If C<$size> is zero, then the callback will get whatever data is
278 available as soon as it is available, up to an arbitrary buffer size.
279 If C<$size> is nonzero, then a short read may still occur if C<$size>
280 bytes do not become available simultaneously.  On EOF, C<$buf> will be
281 the empty string.  It is the caller's responsibility to set C<$fd> to
282 non-blocking mode.  Note that not all operating sytems generate errors
283 that might be reported here.  For example, on Solaris an invalid file
284 descriptor will be silently ignored.
285
286 The return value is an event source, and calling its C<remove> method
287 will cancel the read.  It is an error to have more than one
288 C<async_read> operation on a single file descriptor at any time, and
289 will lead to unpredictable results.
290
291 This function adds a new FdSource every time it is invoked, so it is
292 not well-suited to processing large amounts of data.  For that
293 purpose, consider using the low-level interface or, better, the
294 transfer architecture (see L<Amanda::Xfer>).
295
296 =head3 async_write
297
298     async_write(
299         fd => $fd,
300         data => $data,
301         async_write_cb => $async_write_cb,
302         args => [ .. ]);      # optional
303
304 This function will write C<$data> to file descriptor C<$fd> and invoke
305 the callback with the number of bytes written:
306
307     $cb->($err, $bytes_written, @args);
308
309 If C<$bytes_written> is less than then length of <$data>, then an
310 error occurred, and is given in C<$err>.  As for C<async_read>, the
311 caller should set C<$fd> to non-blocking mode.  Multiple parallel
312 invocations of this function for the same file descriptor are allowed
313 and will be serialized in the order the calls were made:
314
315     async_write($fd, "HELLO!\n",
316         async_write_cb => make_cb(wrote_hello => sub {
317             print "wrote 'HELLO!'\n";
318         }));
319     async_write($fd, "GOODBYE!\n",
320         async_write_cb => make_cb(wrote_goodbye => sub {
321             print "wrote 'GOODBYE!'\n";
322         }));
323
324 In this case, the two strings are guaranteed to be written in the same
325 order, and the callbacks will be called in the correct order.
326
327 Like async_read, this function may add a new FdSource every time it is
328 invoked, so it is not well-suited to processing large amounts of data.
329
330 =head3 synchronized
331
332 Java has the notion of a "synchronized" method, which can only execute in one
333 thread at any time.  This is a particular application of a lock, in which the
334 lock is acquired when the method begins, and released when it finishes.
335
336 With C<Amanda::MainLoop>, this functionality is generally not needed because
337 there is no unexpected preemeption. However, if you break up a long-running
338 operation (that doesn't allow concurrency) into several callbacks, you'll need
339 to ensure that at most one of those operations is going on at a time. The
340 C<synchronized> function manages that for you.
341
342 The function takes a C<$lock> argument, which should be initialized to an empty
343 arrayref (C<[]>).  It is used like this:
344
345     use Amanda::MainLoop 'synchronized';
346     # ..
347     sub dump_data {
348         my $self = shift;
349         my ($arg1, $arg2, $dump_cb) = @_;
350
351         synchronized($self->{'lock'}, $dump_cb, sub {
352             my ($dump_cb) = @_; # IMPORTANT! See below
353             $self->do_dump_data($arg1, $arg2, $dump_cb);
354         };
355     }
356
357 Here, C<do_dump_data> may take a long time to complete (perhaps it starts
358 a long-running data transfer) but only one such operation is allowed at any
359 time and other C<Amanda::MainLoop> callbacks may occur (e.g. a timeout).
360 When the critical operation is complete, it calls C<$dump_cb> which will
361 release the lock before transferring control to the caller.
362
363 Note that the C<$dump_cb> in the inner C<sub> shadows that in
364 C<dump_data> -- this is intentional, the a call to the the inner
365 C<$dump_cb> is how C<synchronized> knows that the operation has completed.
366
367 Several methods may be synchronized with one another by simply sharing the same
368 lock.
369
370 =head1 ASYNCHRONOUS STYLE
371
372 When writing asynchronous code, it's easy to write code that is *very*
373 difficult to read or debug.  The suggestions in this section will help
374 write code that is more readable, and also ensure that all asynchronous
375 code in Amanda uses similar, common idioms.
376
377 =head2 USING CALLBACKS
378
379 Most often, callbacks are short, and can be specified as anonymous
380 subs.  They should be specified with make_cb, like this:
381
382     some_async_function(make_cb(foo_cb => sub {
383         my ($x, $y) = @_;
384         # ...
385     }));
386
387 If a callback is more than about two lines, specify it in a named
388 variable, rather than directly in the function call:
389
390     my $foo_cb = make_cb(foo_cb => sub {
391         my ($src) = @_;
392         # .
393         # .  long function
394         # .
395     });
396     some_async_function($foo_cb);
397
398 When using callbacks from an object-oriented package, it is often
399 useful to treat a method as a callback.  This requires an anonymous
400 sub "wrapper", which can be written on one line:
401
402     some_async_function(sub { $self->foo_cb(@_) });
403
404 =head2 LINEARITY
405
406 The single most important factor in readability is linearity.  If a function
407 that performs operations A, B, and C in that order, then the code for A, B, and
408 C should appear in that order in the source file.  This seems obvious, but it's
409 all too easy to write
410
411     sub three_ops {
412         my $do_c = sub { .. };
413         my $do_b = sub { .. $do_c->() .. };
414         my $do_a = sub { .. $do_b->() .. };
415         $do_a->();
416     }
417
418 Which isn't very readable.  Be readable.
419
420 =head2 SINGLE ENTRY AND EXIT
421
422 Amanda's use of callbacks emulates continuation-passing style.  As such, when a
423 function finishes -- whether successfully or with an error -- it should call a
424 single callback.  This ensures that the function has a simple control
425 interface: perform the operation and call the callback.
426
427 =head2 MULTIPLE STEPS
428
429 Some operations require a long squence of asynchronous operations.  For
430 example, often the results of one operation are required to initiate
431 another.  The I<step> syntax is useful to make this much more readable, and
432 also eliminate some nasty reference-counting bugs.  The idea is that each "step"
433 in the process gets its own sub, and then each step calls the next step.  The
434 first step defined will be called automatically.
435
436     sub send_file {
437         my ($hostname, $port, $data, $sendfile_cb) = @_;
438         my ($addr, $socket); # shared lexical variables
439         my $steps = define_steps
440                 cb_ref => \$sendfile_cb;
441         step lookup_addr => sub {
442             return async_gethostbyname(hostname => $hostname,
443                                 ghbn_cb => $steps->{'got_addr'});
444         };
445         step ghbn_cb => sub {
446             my ($err, $hostinfo) = @_;
447             die $err if $err;
448             $addr = $hostinfo->{'ipaddr'};
449             return $steps->{'connect'}->();
450         };
451         step connect => sub {
452             return async_connect(
453                 ipaddr => $addr,
454                 port => $port,
455                 connect_cb => $steps->{'connect_cb'},
456             );
457         };
458         step connect_cb => sub {
459             my ($err, $conn_sock) = @_;
460             die $err if $err;
461             $socket = $conn_sock;
462             return $steps->{'write_block'}->();
463         };
464         # ...
465     }
466
467 The C<define_steps> function sets the stage.  It is given a reference to the
468 callback for this function (recall there is only one exit point!), and
469 "patches" that reference to free C<$steps>, which otherwise forms a reference
470 loop, on exit.
471
472 WARNING: if the function or method needs to do any kind of setup before its
473 first step, that setup should be done either in a C<setup> step or I<before>
474 the C<define_steps> invocation.  Do not write any statements other than step
475 declarations after the C<define_steps> call.
476
477 Note that there are more steps in this example than are strictly necessary: the
478 body of C<connect> could be appended to C<ghbn_cb>.  The extra steps make the
479 overall operation more readable by adding "punctuation" to separate the task of
480 handling a callback (C<ghbn_cb>) from starting the next operation (C<connect>).
481
482 Also note that the enclosing scope contains some lexical (C<my>)
483 variables which are shared by several of the callbacks.
484
485 All of the steps are wrapped by C<make_cb>, so each step will be executed on a
486 separate iteration of the MainLoop.  This generally has the effect of making
487 asynchronous functions share CPU time more fairly.  Sometimes, especially when
488 using the low-level interface, a callback must be called immediately.  To
489 achieve this for all callbacks, add C<< immediate => 1 >> to the C<define_steps>
490 invocation:
491
492     my $steps = define_steps
493             cb_ref => \$finished_cb,
494             immediate => 1;
495
496 To do the same for a single step, add the same keyword to the C<step> invocation:
497
498     step immediate => 1,
499          connect => sub { .. };
500
501 =head2 JOINING ASYNCHRONOUS "THREADS"
502
503 With slow operations, it is often useful to perform multiple operations
504 simultaneously.  As an example, the following code might run two system
505 commands simultaneously and capture their output:
506
507     sub run_two_commands {
508         my ($finished_cb) = @_;
509         my $running_commands = 0;
510         my ($result1, $result2);
511         my $steps = define_steps
512             cb_ref => \$finished_cb;
513         step start => sub {
514             $running_commands++;
515             run_command($command1,
516                 run_cb => $steps->{'command1_done'});
517             $running_commands++;
518             run_command($command2,
519                 run_cb => $steps->{'command2_done'});
520         };
521         step command1_done => sub {
522             $result1 = $_[0];
523             $steps->{'maybe_done'}->();
524         };
525         step command2_done => sub {
526             $result2 = $_[0];
527             $steps->{'maybe_done'}->();
528         };
529         step maybe_done => sub {
530             return if --$running_commands; # not done yet
531             $finished_cb->($result1, $result2);
532         };
533     }
534
535 It is tempting to optimize out the C<$running_commands> with something like:
536
537     step maybe_done { ## BAD!
538         return unless defined $result1 and defined $result2;
539         $finished_cb->($result1, $result2);
540     }
541
542 However this can lead to trouble.  Remember that define_steps automatically
543 applies C<make_cb> to each step, so a C<maybe_done> is not invoked immediately
544 by C<command1_done> and C<command2_done> - instead, C<maybe_done> is scheduled
545 for invocation in the next loop of the mainloop (via C<call_later>).  If both
546 commands finish before C<maybe_done> is invoked, C<call_later> will be called
547 I<twice>, with both C<$result1> and C<$result2> defined both times.  The result
548 is that C<$finished_cb> is called twice, and mayhem ensues.
549
550 This is a complex case, but worth understanding if you want to be able to debug
551 difficult MainLoop bugs.
552
553 =head2 WRITING ASYNCHRONOUS INTERFACES
554
555 When designing a library or interface that will accept and invoke
556 callbacks, follow these guidelines so that users of the interface will
557 not need to remember special rules.
558
559 Each callback signature within a package should always have the same
560 name, ending with C<_cb>.  For example, a hypothetical
561 C<Amanda::Estimate> module might provide its estimates through a
562 callback with four parameters.  This callback should be referred to as
563 C<estimate_cb> throughout the package, and its parameters should be
564 clearly defined in the package's documentation.  It should take
565 positional parameters only.  If error conditions must also be
566 communicated via the callback, then the first parameter should be an
567 C<$error> parameter, which is undefined when no error has occurred.
568 The Changer API's C<res_cb> is typical of such a callback signature.
569
570 A caller can only know that an operation is complete by the invocation
571 of the callback, so it is important that a callback be invoked
572 I<exactly once> in all circumstances.  Even in an error condition, the
573 caller needs to know that the operation has failed.  Also beware of
574 bugs that might cause a callback to be invoked twice.
575
576 Functions or methods taking callbacks as arguments should either take
577 only a callback (like C<call_later>), or take hash-key parameters,
578 where the callback's key is the signature name.  For example, the
579 C<Amanda::Estimate> package might define a function like
580 C<perform_estimate>, invoked something like this:
581
582     my $estimate_cb = make_cb(estimate_cb => sub {
583         my ($err, $size, $level) = @_;
584         die $err if $err;
585         # ...
586     });
587     Amanda::Estimate::perform_estimate(
588         host => $host,
589         disk => $disk,
590         estimate_cb => $estimate_cb,
591     );
592
593 When invoking a user-supplied callback within the library, there is no
594 need to wrap it in a C<call_later> invocation, as the user already
595 supplied that wrapper via C<make_cb>, or is not interested in using
596 such a wrapper.
597
598 Callbacks are a form of continuation
599 (L<http://en.wikipedia.org/wiki/Continuations>), and as such should
600 only be called at the I<end> of a function.  Do not do anything after
601 invoking a callback, as you cannot know what processing has gone on in
602 the callback.
603
604     sub estimate_done {
605         # ...
606         $self->{'estimate_cb'}->(undef, $size, $level);
607         $self->{'estimate_in_progress'} = 0; # BUG!!
608     }
609
610 In this case, the C<estimate_cb> invocation may have called
611 C<perform_estimate> again, setting C<estimate_in_progress> back to 1.
612 A technique to avoid this pitfall is to always C<return> a callback's
613 result, even though that result is not important.  This makes the bug
614 much more apparent:
615
616     sub estimate_done {
617         # ...
618         return $self->{'estimate_cb'}->(undef, $size, $level);
619         $self->{'estimate_in_progress'} = 0; # BUG (this just looks silly)
620     }
621
622 =head1 LOW-LEVEL INTERFACE
623
624 MainLoop events are generated by event sources.  A source may produce
625 multiple events over its lifetime.  The higher-level methods in the
626 previous section provide a more Perlish abstraction of event sources,
627 but for efficiency it is sometimes necessary to use event sources
628 directly.
629
630 The method C<< $src->set_callback(\&cb) >> sets the function that will
631 be called for a given source, and "attaches" the source to the main
632 loop so that it will begin generating events.  The arguments to the
633 callback depend on the event source, but the first argument is always
634 the source itself.  Unless specified, no other arguments are provided.
635
636 Event sources persist until they are removed with
637 C<< $src->remove() >>, even if the source itself is no longer accessible from Perl.
638 Although Glib supports it, there is no provision for "automatically"
639 removing an event source.  Also, calling C<< $src->remove() >> more than
640 once is a potentially-fatal error. As an example:
641
642   sub start_timer {
643     my ($loops) = @_;
644     Amanda::MainLoop::timeout_source(200)->set_callback(sub {
645       my ($src) = @_;
646       print "timer\n";
647       if (--$loops <= 0) {
648         $src->remove();
649         Amanda::MainLoop::quit();
650       }
651     });
652   }
653   start_timer(10);
654   Amanda::MainLoop::run();
655
656 There is no means in place to specify extra arguments to be provided
657 to a source callback when it is set.  If the callback needs access to
658 other data, it should use a Perl closure in the form of lexically
659 scoped variables and an anonymous sub.  In fact, this is exactly what
660 the higher-level functions (described above) do.
661
662 =head2 Timeout
663
664   my $src = Amanda::MainLoop::timeout_source(10000);
665
666 A timeout source will create events at the specified interval,
667 specified in milliseconds (thousandths of a second).  The events will
668 continue until the source is destroyed.
669
670 =head2 Idle
671
672   my $src = Amanda::MainLoop::idle_source(2);
673
674 An idle source will create events continuously except when a
675 higher-priority source is emitting events.  Priorities are generally
676 small positive integers, with larger integers denoting lower
677 priorities.  The events will continue until the source is destroyed.
678
679 =head2 Child Watch
680
681   my $src = Amanda::MainLoop::child_watch_source($pid);
682
683 A child watch source will issue an event when the process with the
684 given PID dies.  To avoid race conditions, it will issue an event even
685 if the process dies before the source is created.  The callback is
686 called with three arguments: the event source, the PID, and the
687 child's exit status.
688
689 Note that this source is totally incompatible with any thing that
690 would cause perl to change the SIGCHLD handler.  If SIGCHLD is
691 changed, under some circumstances the module will recognize this
692 circumstance, add a warning to the debug log, and continue operating.
693 However, it is impossible to catch all possible situations.
694
695 =head2 File Descriptor
696
697   my $src = Amanda::MainLoop::fd_source($fd, $G_IO_IN);
698
699 This source will issue an event whenever one of the given conditions
700 is true for the given file (a file handle or integer file descriptor).
701 The conditions are from Glib's GIOCondition, and are C<$G_IO_IN>,
702 C<G_IO_OUT>, C<$G_IO_PRI>, C<$G_IO_ERR>, C<$G_IO_HUP>, and
703 C<$G_IO_NVAL>.  These constants are available with the import tag
704 C<:GIOCondition>.
705
706 Generally, when reading from a file descriptor, use
707 C<$G_IO_IN|$G_IO_HUP|$G_IO_ERR> to ensure that an EOF triggers an
708 event as well.  Writing to a file descriptor can simply use
709 C<$G_IO_OUT|$G_IO_ERR>.
710
711 The callback attached to an FdSource should read from or write to the
712 underlying file descriptor before returning, or it will be called
713 again in the next iteration of the main loop, which can lead to
714 unexpected results.  Do I<not> use C<make_cb> here!
715
716 =head2 Combining Event Sources
717
718 Event sources are often set up in groups, e.g., a long-term operation
719 and a timeout.  When this is the case, be careful that all sources are
720 removed when the operation is complete.  The easiest way to accomplish
721 this is to include all sources in a lexical scope and remove them at
722 the appropriate times:
723
724     {
725         my $op_src = long_operation_src();
726         my $timeout_src = Amanda::MainLoop::timeout_source($timeout);
727
728         sub finish {
729             $op_src->remove();
730             $timeout_src->remove();
731         }
732
733         $op_src->set_callback(sub {
734             print "Operation complete\n";
735             finish();
736         });
737
738         $timeout_src->set_callback(sub {
739             print "Operation timed out\n";
740             finish();
741         });
742     }
743
744 =head2 Relationship to Glib
745
746 Glib's main event loop is described in the Glib manual:
747 L<http://library.gnome.org/devel/glib/stable/glib-The-Main-Event-Loop.html>.
748 Note that Amanda depends only on the functionality available in
749 Glib-2.2.0, so many functions described in that document are not
750 available in Amanda.  This module provides a much-simplified interface
751 to the glib library, and is not intended as a generic wrapper for it:
752 Amanda's perl-accessible main loop only runs a single C<GMainContext>,
753 and always runs in the main thread; and (aside from idle sources),
754 event priorities are not accessible from Perl.
755
756 =cut
757
758
759
760
761 use POSIX;
762 use Carp;
763
764 ## basic functions
765
766 BEGIN {
767     my $have_sub_name = eval "use Sub::Name; 1";
768     if (!$have_sub_name) {
769         eval <<'EOF'
770             sub subname {
771                 my ($name, $sub) = @_;
772                 $sub;
773             }
774 EOF
775     }
776 }
777
778 # glib's g_is_main_loop_running() seems inaccurate, so we just
779 # track that information locally..
780 my $mainloop_running = 0;
781 sub run {
782     $mainloop_running = 1;
783     run_c();
784     $mainloop_running = 0;
785 }
786 push @EXPORT_OK, "run";
787
788 sub is_running {
789     return $mainloop_running;
790 }
791 push @EXPORT_OK, "is_running";
792
793 # quit is a direct call to C
794 push @EXPORT_OK, "quit";
795
796 ## utility functions
797
798 my @waiting_to_call_later;
799 sub call_later {
800     my ($sub, @args) = @_;
801
802     confess "undefined sub" unless ($sub);
803
804     # add the callback if nothing is waiting right now
805     if (!@waiting_to_call_later) {
806         timeout_source(0)->set_callback(sub {
807             my ($src) = @_;
808             $src->remove();
809
810             while (@waiting_to_call_later) {
811                 my ($sub, @args) = @{shift @waiting_to_call_later};
812                 $sub->(@args) if $sub;
813             }
814         });
815     }
816
817     push @waiting_to_call_later, [ $sub, @args ];
818 }
819 push @EXPORT_OK, "call_later";
820
821 sub make_cb {
822     my ($name, $sub) = @_;
823
824     if ($sub) {
825         my ($pkg, $filename, $line) = caller;
826         my $newname = sprintf('$%s::%s@l%s', $pkg, $name, $line);
827         $sub = subname($newname => $sub);
828     } else {
829         $sub = $name; # no name => sub is actually in first parameter
830     }
831
832     sub {
833         Amanda::MainLoop::call_later($sub, @_);
834     };
835 }
836 push @EXPORT, 'make_cb';
837
838 sub call_after {
839     my ($delay_ms, $sub, @args) = @_;
840
841     confess "undefined sub" unless ($sub);
842
843     my $src = timeout_source($delay_ms);
844     $src->set_callback(sub {
845         $src->remove();
846         $sub->(@args);
847     });
848
849     return $src;
850 }
851 push @EXPORT_OK, "call_after";
852
853 sub call_on_child_termination {
854     my ($pid, $cb, @args) = @_;
855
856     confess "undefined sub" unless ($cb);
857
858     my $src = child_watch_source($pid);
859     $src->set_callback(sub {
860         my ($src, $pid, $exitstatus) = @_;
861         $src->remove();
862         return $cb->($exitstatus);
863     });
864 }
865 push @EXPORT_OK, "call_on_child_termination";
866
867 sub async_read {
868     my %params = @_;
869     my $fd = $params{'fd'};
870     my $size = $params{'size'} || 0;
871     my $cb = $params{'async_read_cb'};
872     my @args;
873     @args = @{$params{'args'}} if exists $params{'args'};
874
875     my $fd_cb = sub {
876         my ($src) = @_;
877         $src->remove();
878
879         my $buf;
880         my $res = POSIX::read($fd, $buf, $size || 32768);
881         if (!defined $res) {
882             return $cb->($!, undef, @args);
883         } else {
884             return $cb->(undef, $buf, @args);
885         }
886     };
887     my $src = fd_source($fd, $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
888     $src->set_callback($fd_cb);
889     return $src;
890 }
891 push @EXPORT_OK, "async_read";
892
893 my %outstanding_writes;
894 sub async_write {
895     my %params = @_;
896     my $fd = $params{'fd'};
897     my $data = $params{'data'};
898     my $cb = $params{'async_write_cb'};
899     my @args;
900     @args = @{$params{'args'}} if exists $params{'args'};
901
902     # more often than not, writes will not block, so just try it.
903     if (!exists $outstanding_writes{$fd}) {
904         my $res = POSIX::write($fd, $data, length($data));
905         if (!defined $res) {
906             if ($! != POSIX::EAGAIN) {
907                 return $cb->($!, 0, @args);
908             }
909         } elsif ($res eq length($data)) {
910             return $cb->(undef, $res, @args);
911         } else {
912             # chop off whatever data was written
913             $data = substr($data, $res);
914         }
915     }
916
917     if (!exists $outstanding_writes{$fd}) {
918         my $fd_writes = $outstanding_writes{$fd} = [];
919         my $src = fd_source($fd, $G_IO_OUT|$G_IO_HUP|$G_IO_ERR);
920
921         # (note that this does not coalesce consecutive outstanding writes
922         # into a single POSIX::write call)
923         my $fd_cb = sub {
924             my $ow = $fd_writes->[0];
925             my ($buf, $nwritten, $len, $cb, $args) = @$ow;
926
927             my $res = POSIX::write($fd, $buf, $len-$nwritten);
928             if (!defined $res) {
929                 shift @$fd_writes;
930                 $cb->($!, $nwritten, @$args);
931             } else {
932                 $ow->[1] = $nwritten = $nwritten + $res;
933                 if ($nwritten == $len) {
934                     shift @$fd_writes;
935                     $cb->(undef, $nwritten, @$args);
936                 } else {
937                     $ow->[0] = substr($buf, $res);
938                 }
939             }
940
941             # (the following is *intentionally* done after calling $cb, allowing
942             # $cb to add a new message to $fd_writes if desired, and thus avoid
943             # removing and re-adding the source)
944             if (@$fd_writes == 0) {
945                 $src->remove();
946                 delete $outstanding_writes{$fd};
947             }
948         };
949
950         $src->set_callback($fd_cb);
951     }
952     
953     push @{$outstanding_writes{$fd}}, [ $data, 0, length($data), $cb, \@args ];
954 }
955 push @EXPORT_OK, "async_write";
956
957 sub synchronized {
958     my ($lock, $orig_cb, $sub) = @_;
959     my $continuation_cb;
960
961     $continuation_cb = sub {
962         my @args = @_;
963
964         # shift this invocation off the queue
965         my ($last_sub, $last_orig_cb) = @{ shift @$lock };
966
967         # start the next invocation, if the queue isn't empty
968         if (@$lock) {
969             Amanda::MainLoop::call_later($lock->[0][0], $continuation_cb);
970         }
971
972         # call through to the original callback for the last invocation
973         return $last_orig_cb->(@args);
974     };
975
976     # push this sub onto the lock queue
977     if ((push @$lock, [ $sub, $orig_cb ]) == 1) {
978         # if this is the first addition to the queue, start it
979         $sub->($continuation_cb);
980     }
981 }
982 push @EXPORT_OK, "synchronized";
983
984 {   # privat variables to track the "current" step definition
985     my $current_steps;
986     my $immediate;
987     my $first_step;
988
989     sub define_steps (@) {
990         my (%params) = @_;
991         my $cb_ref = $params{'cb_ref'};
992         my %steps;
993
994         croak "cb_ref is undefined" unless defined $cb_ref;
995         croak "cb_ref is not a reference" unless ref($cb_ref) eq 'REF';
996         croak "cb_ref is not a code double-reference" unless ref($$cb_ref) eq 'CODE';
997
998         # arrange to clear out $steps when $exit_cb is called; this eliminates
999         # reference loops (values in %steps are closures which point to %steps).
1000         # This also clears $current_steps, which is likely holding a reference to
1001         # the steps hash.
1002         my $orig_cb = $$cb_ref;
1003         $$cb_ref = sub {
1004             %steps = ();
1005             $current_steps = undef;
1006             goto $orig_cb;
1007         };
1008
1009         # set up state
1010         $current_steps = \%steps;
1011         $immediate = $params{'immediate'};
1012         $first_step = 1;
1013
1014         return $current_steps;
1015     }
1016     push @EXPORT, "define_steps";
1017
1018     sub step (@) {
1019         my (%params) = @_;
1020         my $step_immediate = $immediate || $params{'immediate'};
1021         delete $params{'immediate'} if $step_immediate;
1022
1023         my ($name) = keys %params;
1024         my $cb = $params{$name};
1025
1026         croak "expected a sub at key $name" unless ref($cb) eq 'CODE';
1027
1028         # make the sub delayed
1029         unless ($step_immediate) {
1030             my $orig_cb = $cb;
1031             $cb = sub { Amanda::MainLoop::call_later($orig_cb, @_); }
1032         }
1033
1034         # patch up the callback
1035         my ($pkg, $filename, $line) = caller;
1036         my $newname = sprintf('$%s::%s@l%s', $pkg, $name, $line);
1037         $cb = subname($newname => $cb);
1038
1039         # store the step for later
1040         $current_steps->{$name} = $cb;
1041
1042         # and invoke it, if it's the first step given
1043         if ($first_step) {
1044             if ($step_immediate) {
1045                 call_later($cb);
1046             } else {
1047                 $cb->();
1048             }
1049         }
1050         $first_step = 0;
1051     }
1052     push @EXPORT, "step";
1053 }
1054
1055 push @EXPORT_OK, qw(GIOCondition_to_strings);
1056 push @{$EXPORT_TAGS{"GIOCondition"}}, qw(GIOCondition_to_strings);
1057
1058 my %_GIOCondition_VALUES;
1059 #Convert a flag value to a list of names for flags that are set.
1060 sub GIOCondition_to_strings {
1061     my ($flags) = @_;
1062     my @result = ();
1063
1064     for my $k (keys %_GIOCondition_VALUES) {
1065         my $v = $_GIOCondition_VALUES{$k};
1066
1067         #is this a matching flag?
1068         if (($v == 0 && $flags == 0) || ($v != 0 && ($flags & $v) == $v)) {
1069             push @result, $k;
1070         }
1071     }
1072
1073 #by default, just return the number as a 1-element list
1074     if (!@result) {
1075         return ($flags);
1076     }
1077
1078     return @result;
1079 }
1080
1081 push @EXPORT_OK, qw($G_IO_IN);
1082 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_IN);
1083
1084 $_GIOCondition_VALUES{"G_IO_IN"} = $G_IO_IN;
1085
1086 push @EXPORT_OK, qw($G_IO_OUT);
1087 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_OUT);
1088
1089 $_GIOCondition_VALUES{"G_IO_OUT"} = $G_IO_OUT;
1090
1091 push @EXPORT_OK, qw($G_IO_PRI);
1092 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_PRI);
1093
1094 $_GIOCondition_VALUES{"G_IO_PRI"} = $G_IO_PRI;
1095
1096 push @EXPORT_OK, qw($G_IO_ERR);
1097 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_ERR);
1098
1099 $_GIOCondition_VALUES{"G_IO_ERR"} = $G_IO_ERR;
1100
1101 push @EXPORT_OK, qw($G_IO_HUP);
1102 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_HUP);
1103
1104 $_GIOCondition_VALUES{"G_IO_HUP"} = $G_IO_HUP;
1105
1106 push @EXPORT_OK, qw($G_IO_NVAL);
1107 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_NVAL);
1108
1109 $_GIOCondition_VALUES{"G_IO_NVAL"} = $G_IO_NVAL;
1110
1111 #copy symbols in GIOCondition to constants
1112 push @{$EXPORT_TAGS{"constants"}},  @{$EXPORT_TAGS{"GIOCondition"}};
1113 1;