Imported Upstream version 3.3.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 In some case, you want to execute some code when the step finish, it can
502 be done by defining a finalize code in define_steps:
503
504     my $steps = define_steps
505             cb_ref => \$finished_cb,
506             finalize => sub { .. };
507
508 =head2 JOINING ASYNCHRONOUS "THREADS"
509
510 With slow operations, it is often useful to perform multiple operations
511 simultaneously.  As an example, the following code might run two system
512 commands simultaneously and capture their output:
513
514     sub run_two_commands {
515         my ($finished_cb) = @_;
516         my $running_commands = 0;
517         my ($result1, $result2);
518         my $steps = define_steps
519             cb_ref => \$finished_cb;
520         step start => sub {
521             $running_commands++;
522             run_command($command1,
523                 run_cb => $steps->{'command1_done'});
524             $running_commands++;
525             run_command($command2,
526                 run_cb => $steps->{'command2_done'});
527         };
528         step command1_done => sub {
529             $result1 = $_[0];
530             $steps->{'maybe_done'}->();
531         };
532         step command2_done => sub {
533             $result2 = $_[0];
534             $steps->{'maybe_done'}->();
535         };
536         step maybe_done => sub {
537             return if --$running_commands; # not done yet
538             $finished_cb->($result1, $result2);
539         };
540     }
541
542 It is tempting to optimize out the C<$running_commands> with something like:
543
544     step maybe_done { ## BAD!
545         return unless defined $result1 and defined $result2;
546         $finished_cb->($result1, $result2);
547     }
548
549 However this can lead to trouble.  Remember that define_steps automatically
550 applies C<make_cb> to each step, so a C<maybe_done> is not invoked immediately
551 by C<command1_done> and C<command2_done> - instead, C<maybe_done> is scheduled
552 for invocation in the next loop of the mainloop (via C<call_later>).  If both
553 commands finish before C<maybe_done> is invoked, C<call_later> will be called
554 I<twice>, with both C<$result1> and C<$result2> defined both times.  The result
555 is that C<$finished_cb> is called twice, and mayhem ensues.
556
557 This is a complex case, but worth understanding if you want to be able to debug
558 difficult MainLoop bugs.
559
560 =head2 WRITING ASYNCHRONOUS INTERFACES
561
562 When designing a library or interface that will accept and invoke
563 callbacks, follow these guidelines so that users of the interface will
564 not need to remember special rules.
565
566 Each callback signature within a package should always have the same
567 name, ending with C<_cb>.  For example, a hypothetical
568 C<Amanda::Estimate> module might provide its estimates through a
569 callback with four parameters.  This callback should be referred to as
570 C<estimate_cb> throughout the package, and its parameters should be
571 clearly defined in the package's documentation.  It should take
572 positional parameters only.  If error conditions must also be
573 communicated via the callback, then the first parameter should be an
574 C<$error> parameter, which is undefined when no error has occurred.
575 The Changer API's C<res_cb> is typical of such a callback signature.
576
577 A caller can only know that an operation is complete by the invocation
578 of the callback, so it is important that a callback be invoked
579 I<exactly once> in all circumstances.  Even in an error condition, the
580 caller needs to know that the operation has failed.  Also beware of
581 bugs that might cause a callback to be invoked twice.
582
583 Functions or methods taking callbacks as arguments should either take
584 only a callback (like C<call_later>), or take hash-key parameters,
585 where the callback's key is the signature name.  For example, the
586 C<Amanda::Estimate> package might define a function like
587 C<perform_estimate>, invoked something like this:
588
589     my $estimate_cb = make_cb(estimate_cb => sub {
590         my ($err, $size, $level) = @_;
591         die $err if $err;
592         # ...
593     });
594     Amanda::Estimate::perform_estimate(
595         host => $host,
596         disk => $disk,
597         estimate_cb => $estimate_cb,
598     );
599
600 When invoking a user-supplied callback within the library, there is no
601 need to wrap it in a C<call_later> invocation, as the user already
602 supplied that wrapper via C<make_cb>, or is not interested in using
603 such a wrapper.
604
605 Callbacks are a form of continuation
606 (L<http://en.wikipedia.org/wiki/Continuations>), and as such should
607 only be called at the I<end> of a function.  Do not do anything after
608 invoking a callback, as you cannot know what processing has gone on in
609 the callback.
610
611     sub estimate_done {
612         # ...
613         $self->{'estimate_cb'}->(undef, $size, $level);
614         $self->{'estimate_in_progress'} = 0; # BUG!!
615     }
616
617 In this case, the C<estimate_cb> invocation may have called
618 C<perform_estimate> again, setting C<estimate_in_progress> back to 1.
619 A technique to avoid this pitfall is to always C<return> a callback's
620 result, even though that result is not important.  This makes the bug
621 much more apparent:
622
623     sub estimate_done {
624         # ...
625         return $self->{'estimate_cb'}->(undef, $size, $level);
626         $self->{'estimate_in_progress'} = 0; # BUG (this just looks silly)
627     }
628
629 =head1 LOW-LEVEL INTERFACE
630
631 MainLoop events are generated by event sources.  A source may produce
632 multiple events over its lifetime.  The higher-level methods in the
633 previous section provide a more Perlish abstraction of event sources,
634 but for efficiency it is sometimes necessary to use event sources
635 directly.
636
637 The method C<< $src->set_callback(\&cb) >> sets the function that will
638 be called for a given source, and "attaches" the source to the main
639 loop so that it will begin generating events.  The arguments to the
640 callback depend on the event source, but the first argument is always
641 the source itself.  Unless specified, no other arguments are provided.
642
643 Event sources persist until they are removed with
644 C<< $src->remove() >>, even if the source itself is no longer accessible from Perl.
645 Although Glib supports it, there is no provision for "automatically"
646 removing an event source.  Also, calling C<< $src->remove() >> more than
647 once is a potentially-fatal error. As an example:
648
649   sub start_timer {
650     my ($loops) = @_;
651     Amanda::MainLoop::timeout_source(200)->set_callback(sub {
652       my ($src) = @_;
653       print "timer\n";
654       if (--$loops <= 0) {
655         $src->remove();
656         Amanda::MainLoop::quit();
657       }
658     });
659   }
660   start_timer(10);
661   Amanda::MainLoop::run();
662
663 There is no means in place to specify extra arguments to be provided
664 to a source callback when it is set.  If the callback needs access to
665 other data, it should use a Perl closure in the form of lexically
666 scoped variables and an anonymous sub.  In fact, this is exactly what
667 the higher-level functions (described above) do.
668
669 =head2 Timeout
670
671   my $src = Amanda::MainLoop::timeout_source(10000);
672
673 A timeout source will create events at the specified interval,
674 specified in milliseconds (thousandths of a second).  The events will
675 continue until the source is destroyed.
676
677 =head2 Idle
678
679   my $src = Amanda::MainLoop::idle_source(2);
680
681 An idle source will create events continuously except when a
682 higher-priority source is emitting events.  Priorities are generally
683 small positive integers, with larger integers denoting lower
684 priorities.  The events will continue until the source is destroyed.
685
686 =head2 Child Watch
687
688   my $src = Amanda::MainLoop::child_watch_source($pid);
689
690 A child watch source will issue an event when the process with the
691 given PID dies.  To avoid race conditions, it will issue an event even
692 if the process dies before the source is created.  The callback is
693 called with three arguments: the event source, the PID, and the
694 child's exit status.
695
696 Note that this source is totally incompatible with any thing that
697 would cause perl to change the SIGCHLD handler.  If SIGCHLD is
698 changed, under some circumstances the module will recognize this
699 circumstance, add a warning to the debug log, and continue operating.
700 However, it is impossible to catch all possible situations.
701
702 =head2 File Descriptor
703
704   my $src = Amanda::MainLoop::fd_source($fd, $G_IO_IN);
705
706 This source will issue an event whenever one of the given conditions
707 is true for the given file (a file handle or integer file descriptor).
708 The conditions are from Glib's GIOCondition, and are C<$G_IO_IN>,
709 C<G_IO_OUT>, C<$G_IO_PRI>, C<$G_IO_ERR>, C<$G_IO_HUP>, and
710 C<$G_IO_NVAL>.  These constants are available with the import tag
711 C<:GIOCondition>.
712
713 Generally, when reading from a file descriptor, use
714 C<$G_IO_IN|$G_IO_HUP|$G_IO_ERR> to ensure that an EOF triggers an
715 event as well.  Writing to a file descriptor can simply use
716 C<$G_IO_OUT|$G_IO_ERR>.
717
718 The callback attached to an FdSource should read from or write to the
719 underlying file descriptor before returning, or it will be called
720 again in the next iteration of the main loop, which can lead to
721 unexpected results.  Do I<not> use C<make_cb> here!
722
723 =head2 Combining Event Sources
724
725 Event sources are often set up in groups, e.g., a long-term operation
726 and a timeout.  When this is the case, be careful that all sources are
727 removed when the operation is complete.  The easiest way to accomplish
728 this is to include all sources in a lexical scope and remove them at
729 the appropriate times:
730
731     {
732         my $op_src = long_operation_src();
733         my $timeout_src = Amanda::MainLoop::timeout_source($timeout);
734
735         sub finish {
736             $op_src->remove();
737             $timeout_src->remove();
738         }
739
740         $op_src->set_callback(sub {
741             print "Operation complete\n";
742             finish();
743         });
744
745         $timeout_src->set_callback(sub {
746             print "Operation timed out\n";
747             finish();
748         });
749     }
750
751 =head2 Relationship to Glib
752
753 Glib's main event loop is described in the Glib manual:
754 L<http://library.gnome.org/devel/glib/stable/glib-The-Main-Event-Loop.html>.
755 Note that Amanda depends only on the functionality available in
756 Glib-2.2.0, so many functions described in that document are not
757 available in Amanda.  This module provides a much-simplified interface
758 to the glib library, and is not intended as a generic wrapper for it:
759 Amanda's perl-accessible main loop only runs a single C<GMainContext>,
760 and always runs in the main thread; and (aside from idle sources),
761 event priorities are not accessible from Perl.
762
763 =cut
764
765
766
767
768 use POSIX;
769 use Carp;
770
771 ## basic functions
772
773 BEGIN {
774     my $have_sub_name = eval "use Sub::Name; 1";
775     if (!$have_sub_name) {
776         eval <<'EOF'
777             sub subname {
778                 my ($name, $sub) = @_;
779                 $sub;
780             }
781 EOF
782     }
783 }
784
785 # glib's g_is_main_loop_running() seems inaccurate, so we just
786 # track that information locally..
787 my $mainloop_running = 0;
788 sub run {
789     $mainloop_running = 1;
790     run_c();
791     $mainloop_running = 0;
792 }
793 push @EXPORT_OK, "run";
794
795 sub is_running {
796     return $mainloop_running;
797 }
798 push @EXPORT_OK, "is_running";
799
800 # quit is a direct call to C
801 push @EXPORT_OK, "quit";
802
803 ## utility functions
804
805 my @waiting_to_call_later;
806 sub call_later {
807     my ($sub, @args) = @_;
808
809     confess "undefined sub" unless ($sub);
810
811     # add the callback if nothing is waiting right now
812     if (!@waiting_to_call_later) {
813         timeout_source(0)->set_callback(sub {
814             my ($src) = @_;
815             $src->remove();
816
817             while (@waiting_to_call_later) {
818                 my ($sub, @args) = @{shift @waiting_to_call_later};
819                 $sub->(@args) if $sub;
820             }
821         });
822     }
823
824     push @waiting_to_call_later, [ $sub, @args ];
825 }
826 push @EXPORT_OK, "call_later";
827
828 sub make_cb {
829     my ($name, $sub) = @_;
830
831     if ($sub) {
832         my ($pkg, $filename, $line) = caller;
833         my $newname = sprintf('$%s::%s@l%s', $pkg, $name, $line);
834         $sub = subname($newname => $sub);
835     } else {
836         $sub = $name; # no name => sub is actually in first parameter
837     }
838
839     sub {
840         Amanda::MainLoop::call_later($sub, @_);
841     };
842 }
843 push @EXPORT, 'make_cb';
844
845 sub call_after {
846     my ($delay_ms, $sub, @args) = @_;
847
848     confess "undefined sub" unless ($sub);
849
850     my $src = timeout_source($delay_ms);
851     $src->set_callback(sub {
852         $src->remove();
853         $sub->(@args);
854     });
855
856     return $src;
857 }
858 push @EXPORT_OK, "call_after";
859
860 sub call_on_child_termination {
861     my ($pid, $cb, @args) = @_;
862
863     confess "undefined sub" unless ($cb);
864
865     my $src = child_watch_source($pid);
866     $src->set_callback(sub {
867         my ($src, $pid, $exitstatus) = @_;
868         $src->remove();
869         return $cb->($exitstatus);
870     });
871 }
872 push @EXPORT_OK, "call_on_child_termination";
873
874 sub async_read {
875     my %params = @_;
876     my $fd = $params{'fd'};
877     my $size = $params{'size'} || 0;
878     my $cb = $params{'async_read_cb'};
879     my @args;
880     @args = @{$params{'args'}} if exists $params{'args'};
881
882     my $fd_cb = sub {
883         my ($src) = @_;
884         $src->remove();
885
886         my $buf;
887         my $res = POSIX::read($fd, $buf, $size || 32768);
888         if (!defined $res) {
889             return $cb->($!, undef, @args);
890         } else {
891             return $cb->(undef, $buf, @args);
892         }
893     };
894     my $src = fd_source($fd, $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
895     $src->set_callback($fd_cb);
896     return $src;
897 }
898 push @EXPORT_OK, "async_read";
899
900 my %outstanding_writes;
901 sub async_write {
902     my %params = @_;
903     my $fd = $params{'fd'};
904     my $data = $params{'data'};
905     my $cb = $params{'async_write_cb'};
906     my @args;
907     @args = @{$params{'args'}} if exists $params{'args'};
908
909     # more often than not, writes will not block, so just try it.
910     if (!exists $outstanding_writes{$fd}) {
911         my $res = POSIX::write($fd, $data, length($data));
912         if (!defined $res) {
913             if ($! != POSIX::EAGAIN) {
914                 return $cb->($!, 0, @args);
915             }
916         } elsif ($res eq length($data)) {
917             return $cb->(undef, $res, @args);
918         } else {
919             # chop off whatever data was written
920             $data = substr($data, $res);
921         }
922     }
923
924     if (!exists $outstanding_writes{$fd}) {
925         my $fd_writes = $outstanding_writes{$fd} = [];
926         my $src = fd_source($fd, $G_IO_OUT|$G_IO_HUP|$G_IO_ERR);
927
928         # (note that this does not coalesce consecutive outstanding writes
929         # into a single POSIX::write call)
930         my $fd_cb = sub {
931             my $ow = $fd_writes->[0];
932             my ($buf, $nwritten, $len, $cb, $args) = @$ow;
933
934             my $res = POSIX::write($fd, $buf, $len-$nwritten);
935             if (!defined $res) {
936                 shift @$fd_writes;
937                 $cb->($!, $nwritten, @$args);
938             } else {
939                 $ow->[1] = $nwritten = $nwritten + $res;
940                 if ($nwritten == $len) {
941                     shift @$fd_writes;
942                     $cb->(undef, $nwritten, @$args);
943                 } else {
944                     $ow->[0] = substr($buf, $res);
945                 }
946             }
947
948             # (the following is *intentionally* done after calling $cb, allowing
949             # $cb to add a new message to $fd_writes if desired, and thus avoid
950             # removing and re-adding the source)
951             if (@$fd_writes == 0) {
952                 $src->remove();
953                 delete $outstanding_writes{$fd};
954             }
955         };
956
957         $src->set_callback($fd_cb);
958     }
959     
960     push @{$outstanding_writes{$fd}}, [ $data, 0, length($data), $cb, \@args ];
961 }
962 push @EXPORT_OK, "async_write";
963
964 sub synchronized {
965     my ($lock, $orig_cb, $sub) = @_;
966     my $continuation_cb;
967
968     $continuation_cb = sub {
969         my @args = @_;
970
971         # shift this invocation off the queue
972         my ($last_sub, $last_orig_cb) = @{ shift @$lock };
973
974         # start the next invocation, if the queue isn't empty
975         if (@$lock) {
976             Amanda::MainLoop::call_later($lock->[0][0], $continuation_cb);
977         }
978
979         # call through to the original callback for the last invocation
980         return $last_orig_cb->(@args);
981     };
982
983     # push this sub onto the lock queue
984     if ((push @$lock, [ $sub, $orig_cb ]) == 1) {
985         # if this is the first addition to the queue, start it
986         $sub->($continuation_cb);
987     }
988 }
989 push @EXPORT_OK, "synchronized";
990
991 {   # privat variables to track the "current" step definition
992     my $current_steps;
993     my $immediate;
994     my $first_step;
995
996     sub define_steps (@) {
997         my (%params) = @_;
998         my $cb_ref = $params{'cb_ref'};
999         my $finalize = $params{'finalize'};
1000         my %steps;
1001
1002         croak "cb_ref is undefined" unless defined $cb_ref;
1003         croak "cb_ref is not a reference" unless ref($cb_ref) eq 'REF';
1004         croak "cb_ref is not a code double-reference" unless ref($$cb_ref) eq 'CODE';
1005
1006         # arrange to clear out $steps when $exit_cb is called; this eliminates
1007         # reference loops (values in %steps are closures which point to %steps).
1008         # This also clears $current_steps, which is likely holding a reference to
1009         # the steps hash.
1010         my $orig_cb = $$cb_ref;
1011         $$cb_ref = sub {
1012             %steps = ();
1013             $current_steps = undef;
1014             $finalize->() if defined($finalize);
1015             goto $orig_cb;
1016         };
1017
1018         # set up state
1019         $current_steps = \%steps;
1020         $immediate = $params{'immediate'};
1021         $first_step = 1;
1022
1023         return $current_steps;
1024     }
1025     push @EXPORT, "define_steps";
1026
1027     sub step (@) {
1028         my (%params) = @_;
1029         my $step_immediate = $immediate || $params{'immediate'};
1030         delete $params{'immediate'} if $step_immediate;
1031
1032         my ($name) = keys %params;
1033         my $cb = $params{$name};
1034
1035         croak "expected a sub at key $name" unless ref($cb) eq 'CODE';
1036
1037         # make the sub delayed
1038         unless ($step_immediate) {
1039             my $orig_cb = $cb;
1040             $cb = sub { Amanda::MainLoop::call_later($orig_cb, @_); }
1041         }
1042
1043         # patch up the callback
1044         my ($pkg, $filename, $line) = caller;
1045         my $newname = sprintf('$%s::%s@l%s', $pkg, $name, $line);
1046         $cb = subname($newname => $cb);
1047
1048         # store the step for later
1049         $current_steps->{$name} = $cb;
1050
1051         # and invoke it, if it's the first step given
1052         if ($first_step) {
1053             if ($step_immediate) {
1054                 call_later($cb);
1055             } else {
1056                 $cb->();
1057             }
1058         }
1059         $first_step = 0;
1060     }
1061     push @EXPORT, "step";
1062 }
1063
1064 push @EXPORT_OK, qw(GIOCondition_to_strings);
1065 push @{$EXPORT_TAGS{"GIOCondition"}}, qw(GIOCondition_to_strings);
1066
1067 my %_GIOCondition_VALUES;
1068 #Convert a flag value to a list of names for flags that are set.
1069 sub GIOCondition_to_strings {
1070     my ($flags) = @_;
1071     my @result = ();
1072
1073     for my $k (keys %_GIOCondition_VALUES) {
1074         my $v = $_GIOCondition_VALUES{$k};
1075
1076         #is this a matching flag?
1077         if (($v == 0 && $flags == 0) || ($v != 0 && ($flags & $v) == $v)) {
1078             push @result, $k;
1079         }
1080     }
1081
1082 #by default, just return the number as a 1-element list
1083     if (!@result) {
1084         return ($flags);
1085     }
1086
1087     return @result;
1088 }
1089
1090 push @EXPORT_OK, qw($G_IO_IN);
1091 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_IN);
1092
1093 $_GIOCondition_VALUES{"G_IO_IN"} = $G_IO_IN;
1094
1095 push @EXPORT_OK, qw($G_IO_OUT);
1096 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_OUT);
1097
1098 $_GIOCondition_VALUES{"G_IO_OUT"} = $G_IO_OUT;
1099
1100 push @EXPORT_OK, qw($G_IO_PRI);
1101 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_PRI);
1102
1103 $_GIOCondition_VALUES{"G_IO_PRI"} = $G_IO_PRI;
1104
1105 push @EXPORT_OK, qw($G_IO_ERR);
1106 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_ERR);
1107
1108 $_GIOCondition_VALUES{"G_IO_ERR"} = $G_IO_ERR;
1109
1110 push @EXPORT_OK, qw($G_IO_HUP);
1111 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_HUP);
1112
1113 $_GIOCondition_VALUES{"G_IO_HUP"} = $G_IO_HUP;
1114
1115 push @EXPORT_OK, qw($G_IO_NVAL);
1116 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_NVAL);
1117
1118 $_GIOCondition_VALUES{"G_IO_NVAL"} = $G_IO_NVAL;
1119
1120 #copy symbols in GIOCondition to constants
1121 push @{$EXPORT_TAGS{"constants"}},  @{$EXPORT_TAGS{"GIOCondition"}};
1122 1;