1 # This file was automatically generated by SWIG (http://www.swig.org).
4 # Do not make changes to this file unless you know what you are doing--modify
5 # the SWIG interface file instead.
7 package Amanda::MainLoop;
9 use base qw(DynaLoader);
10 package Amanda::MainLoopc;
11 bootstrap Amanda::MainLoop;
12 package Amanda::MainLoop;
15 # ---------- BASE METHODS -------------
17 package Amanda::MainLoop;
20 my ($classname,$obj) = @_;
21 return bless $obj, $classname;
31 my ($self,$field) = @_;
32 my $member_func = "swig_${field}_get";
33 $self->$member_func();
37 my ($self,$field,$newval) = @_;
38 my $member_func = "swig_${field}_set";
39 $self->$member_func($newval);
48 # ------- FUNCTION WRAPPERS --------
50 package Amanda::MainLoop;
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;
59 ############# Class : Amanda::MainLoop::Source ##############
61 package Amanda::MainLoop::Source;
62 use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
63 @ISA = qw( Amanda::MainLoop );
68 my $self = Amanda::MainLoopc::new_Source(@_);
69 bless $self, $pkg if defined($self);
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);
83 *set_callback = *Amanda::MainLoopc::Source_set_callback;
84 *remove = *Amanda::MainLoopc::Source_remove;
87 my $ptr = tied(%$self);
93 my $ptr = tied(%$self);
98 # ------- VARIABLE STUBS --------
100 package Amanda::MainLoop;
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;
115 Amanda::MainLoop - Perl interface to the Glib MainLoop
119 use Amanda::MainLoop;
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
128 Amanda::MainLoop::run();
130 Note that all functions in this module are individually available for
133 use Amanda::MainLoop qw(run quit);
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.
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
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
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()>.
162 =head1 HIGH-LEVEL INTERFACE
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.
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.
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
180 if (can_do_it_now()) {
181 my $result = do_it();
182 Amanda::MainLoop::call_later($cb, $result)
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
194 Amanda::MainLoop::quit();
196 Amanda::MainLoop::call_later($main);
198 Amanda::MainLoop::run();
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):
205 my $fetched_cb = make_cb(fetched_cb => sub {
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:
213 my $reset_finished_cb = make_cb(reset_finished_cb => sub {
215 die "while resetting: $err" if $err;
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
225 C<make_cb> is exported automatically.
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.
239 Amanda::MainLoop::call_after(1000, $counter, $i-1);
245 The function returns the underlying event source (see below), enabling
246 the caller to cancel the pending call:
248 my $tosrc = Amanda::MainLoop::call_after(15000, $timeout_cb):
249 # ...data arrives before timeout...
252 =head3 call_on_child_termination
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
259 $cb->($exitstatus, @args);
261 Like C<call_after>, this function returns the event source to allow
262 early cancellation if desired.
268 size => $size, # optional, default 0
269 async_read_cb => $async_read_cb,
270 args => [ .. ]); # optional
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:
275 $async_read_cb->($err, $buf, @args);
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.
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.
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>).
301 async_write_cb => $async_write_cb,
302 args => [ .. ]); # optional
304 This function will write C<$data> to file descriptor C<$fd> and invoke
305 the callback with the number of bytes written:
307 $cb->($err, $bytes_written, @args);
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:
315 async_write($fd, "HELLO!\n",
316 async_write_cb => make_cb(wrote_hello => sub {
317 print "wrote 'HELLO!'\n";
319 async_write($fd, "GOODBYE!\n",
320 async_write_cb => make_cb(wrote_goodbye => sub {
321 print "wrote 'GOODBYE!'\n";
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.
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.
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.
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.
342 The function takes a C<$lock> argument, which should be initialized to an empty
343 arrayref (C<[]>). It is used like this:
345 use Amanda::MainLoop 'synchronized';
349 my ($arg1, $arg2, $dump_cb) = @_;
351 synchronized($self->{'lock'}, $dump_cb, sub {
352 my ($dump_cb) = @_; # IMPORTANT! See below
353 $self->do_dump_data($arg1, $arg2, $dump_cb);
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.
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.
367 Several methods may be synchronized with one another by simply sharing the same
370 =head1 ASYNCHRONOUS STYLE
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.
377 =head2 USING CALLBACKS
379 Most often, callbacks are short, and can be specified as anonymous
380 subs. They should be specified with make_cb, like this:
382 some_async_function(make_cb(foo_cb => sub {
387 If a callback is more than about two lines, specify it in a named
388 variable, rather than directly in the function call:
390 my $foo_cb = make_cb(foo_cb => sub {
396 some_async_function($foo_cb);
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:
402 some_async_function(sub { $self->foo_cb(@_) });
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
412 my $do_c = sub { .. };
413 my $do_b = sub { .. $do_c->() .. };
414 my $do_a = sub { .. $do_b->() .. };
418 Which isn't very readable. Be readable.
420 =head2 SINGLE ENTRY AND EXIT
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.
427 =head2 MULTIPLE STEPS
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.
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'});
445 step ghbn_cb => sub {
446 my ($err, $hostinfo) = @_;
448 $addr = $hostinfo->{'ipaddr'};
449 return $steps->{'connect'}->();
451 step connect => sub {
452 return async_connect(
455 connect_cb => $steps->{'connect_cb'},
458 step connect_cb => sub {
459 my ($err, $conn_sock) = @_;
461 $socket = $conn_sock;
462 return $steps->{'write_block'}->();
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
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.
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>).
482 Also note that the enclosing scope contains some lexical (C<my>)
483 variables which are shared by several of the callbacks.
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>
492 my $steps = define_steps
493 cb_ref => \$finished_cb,
496 To do the same for a single step, add the same keyword to the C<step> invocation:
499 connect => sub { .. };
501 =head2 JOINING ASYNCHRONOUS "THREADS"
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:
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;
515 run_command($command1,
516 run_cb => $steps->{'command1_done'});
518 run_command($command2,
519 run_cb => $steps->{'command2_done'});
521 step command1_done => sub {
523 $steps->{'maybe_done'}->();
525 step command2_done => sub {
527 $steps->{'maybe_done'}->();
529 step maybe_done => sub {
530 return if --$running_commands; # not done yet
531 $finished_cb->($result1, $result2);
535 It is tempting to optimize out the C<$running_commands> with something like:
537 step maybe_done { ## BAD!
538 return unless defined $result1 and defined $result2;
539 $finished_cb->($result1, $result2);
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.
550 This is a complex case, but worth understanding if you want to be able to debug
551 difficult MainLoop bugs.
553 =head2 WRITING ASYNCHRONOUS INTERFACES
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.
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.
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.
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:
582 my $estimate_cb = make_cb(estimate_cb => sub {
583 my ($err, $size, $level) = @_;
587 Amanda::Estimate::perform_estimate(
590 estimate_cb => $estimate_cb,
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
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
606 $self->{'estimate_cb'}->(undef, $size, $level);
607 $self->{'estimate_in_progress'} = 0; # BUG!!
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
618 return $self->{'estimate_cb'}->(undef, $size, $level);
619 $self->{'estimate_in_progress'} = 0; # BUG (this just looks silly)
622 =head1 LOW-LEVEL INTERFACE
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
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.
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:
644 Amanda::MainLoop::timeout_source(200)->set_callback(sub {
649 Amanda::MainLoop::quit();
654 Amanda::MainLoop::run();
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.
664 my $src = Amanda::MainLoop::timeout_source(10000);
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.
672 my $src = Amanda::MainLoop::idle_source(2);
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.
681 my $src = Amanda::MainLoop::child_watch_source($pid);
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
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.
695 =head2 File Descriptor
697 my $src = Amanda::MainLoop::fd_source($fd, $G_IO_IN);
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
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>.
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!
716 =head2 Combining Event Sources
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:
725 my $op_src = long_operation_src();
726 my $timeout_src = Amanda::MainLoop::timeout_source($timeout);
730 $timeout_src->remove();
733 $op_src->set_callback(sub {
734 print "Operation complete\n";
738 $timeout_src->set_callback(sub {
739 print "Operation timed out\n";
744 =head2 Relationship to Glib
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.
767 my $have_sub_name = eval "use Sub::Name; 1";
768 if (!$have_sub_name) {
771 my ($name, $sub) = @_;
778 # glib's g_is_main_loop_running() seems inaccurate, so we just
779 # track that information locally..
780 my $mainloop_running = 0;
782 $mainloop_running = 1;
784 $mainloop_running = 0;
786 push @EXPORT_OK, "run";
789 return $mainloop_running;
791 push @EXPORT_OK, "is_running";
793 # quit is a direct call to C
794 push @EXPORT_OK, "quit";
798 my @waiting_to_call_later;
800 my ($sub, @args) = @_;
802 confess "undefined sub" unless ($sub);
804 # add the callback if nothing is waiting right now
805 if (!@waiting_to_call_later) {
806 timeout_source(0)->set_callback(sub {
810 while (@waiting_to_call_later) {
811 my ($sub, @args) = @{shift @waiting_to_call_later};
812 $sub->(@args) if $sub;
817 push @waiting_to_call_later, [ $sub, @args ];
819 push @EXPORT_OK, "call_later";
822 my ($name, $sub) = @_;
825 my ($pkg, $filename, $line) = caller;
826 my $newname = sprintf('$%s::%s@l%s', $pkg, $name, $line);
827 $sub = subname($newname => $sub);
829 $sub = $name; # no name => sub is actually in first parameter
833 Amanda::MainLoop::call_later($sub, @_);
836 push @EXPORT, 'make_cb';
839 my ($delay_ms, $sub, @args) = @_;
841 confess "undefined sub" unless ($sub);
843 my $src = timeout_source($delay_ms);
844 $src->set_callback(sub {
851 push @EXPORT_OK, "call_after";
853 sub call_on_child_termination {
854 my ($pid, $cb, @args) = @_;
856 confess "undefined sub" unless ($cb);
858 my $src = child_watch_source($pid);
859 $src->set_callback(sub {
860 my ($src, $pid, $exitstatus) = @_;
862 return $cb->($exitstatus);
865 push @EXPORT_OK, "call_on_child_termination";
869 my $fd = $params{'fd'};
870 my $size = $params{'size'} || 0;
871 my $cb = $params{'async_read_cb'};
873 @args = @{$params{'args'}} if exists $params{'args'};
880 my $res = POSIX::read($fd, $buf, $size || 32768);
882 return $cb->($!, undef, @args);
884 return $cb->(undef, $buf, @args);
887 my $src = fd_source($fd, $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
888 $src->set_callback($fd_cb);
891 push @EXPORT_OK, "async_read";
893 my %outstanding_writes;
896 my $fd = $params{'fd'};
897 my $data = $params{'data'};
898 my $cb = $params{'async_write_cb'};
900 @args = @{$params{'args'}} if exists $params{'args'};
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));
906 if ($! != POSIX::EAGAIN) {
907 return $cb->($!, 0, @args);
909 } elsif ($res eq length($data)) {
910 return $cb->(undef, $res, @args);
912 # chop off whatever data was written
913 $data = substr($data, $res);
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);
921 # (note that this does not coalesce consecutive outstanding writes
922 # into a single POSIX::write call)
924 my $ow = $fd_writes->[0];
925 my ($buf, $nwritten, $len, $cb, $args) = @$ow;
927 my $res = POSIX::write($fd, $buf, $len-$nwritten);
930 $cb->($!, $nwritten, @$args);
932 $ow->[1] = $nwritten = $nwritten + $res;
933 if ($nwritten == $len) {
935 $cb->(undef, $nwritten, @$args);
937 $ow->[0] = substr($buf, $res);
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) {
946 delete $outstanding_writes{$fd};
950 $src->set_callback($fd_cb);
953 push @{$outstanding_writes{$fd}}, [ $data, 0, length($data), $cb, \@args ];
955 push @EXPORT_OK, "async_write";
958 my ($lock, $orig_cb, $sub) = @_;
961 $continuation_cb = sub {
964 # shift this invocation off the queue
965 my ($last_sub, $last_orig_cb) = @{ shift @$lock };
967 # start the next invocation, if the queue isn't empty
969 Amanda::MainLoop::call_later($lock->[0][0], $continuation_cb);
972 # call through to the original callback for the last invocation
973 return $last_orig_cb->(@args);
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);
982 push @EXPORT_OK, "synchronized";
984 { # privat variables to track the "current" step definition
989 sub define_steps (@) {
991 my $cb_ref = $params{'cb_ref'};
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';
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
1002 my $orig_cb = $$cb_ref;
1005 $current_steps = undef;
1010 $current_steps = \%steps;
1011 $immediate = $params{'immediate'};
1014 return $current_steps;
1016 push @EXPORT, "define_steps";
1020 my $step_immediate = $immediate || $params{'immediate'};
1021 delete $params{'immediate'} if $step_immediate;
1023 my ($name) = keys %params;
1024 my $cb = $params{$name};
1026 croak "expected a sub at key $name" unless ref($cb) eq 'CODE';
1028 # make the sub delayed
1029 unless ($step_immediate) {
1031 $cb = sub { Amanda::MainLoop::call_later($orig_cb, @_); }
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);
1039 # store the step for later
1040 $current_steps->{$name} = $cb;
1042 # and invoke it, if it's the first step given
1044 if ($step_immediate) {
1052 push @EXPORT, "step";
1055 push @EXPORT_OK, qw(GIOCondition_to_strings);
1056 push @{$EXPORT_TAGS{"GIOCondition"}}, qw(GIOCondition_to_strings);
1058 my %_GIOCondition_VALUES;
1059 #Convert a flag value to a list of names for flags that are set.
1060 sub GIOCondition_to_strings {
1064 for my $k (keys %_GIOCondition_VALUES) {
1065 my $v = $_GIOCondition_VALUES{$k};
1067 #is this a matching flag?
1068 if (($v == 0 && $flags == 0) || ($v != 0 && ($flags & $v) == $v)) {
1073 #by default, just return the number as a 1-element list
1081 push @EXPORT_OK, qw($G_IO_IN);
1082 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_IN);
1084 $_GIOCondition_VALUES{"G_IO_IN"} = $G_IO_IN;
1086 push @EXPORT_OK, qw($G_IO_OUT);
1087 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_OUT);
1089 $_GIOCondition_VALUES{"G_IO_OUT"} = $G_IO_OUT;
1091 push @EXPORT_OK, qw($G_IO_PRI);
1092 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_PRI);
1094 $_GIOCondition_VALUES{"G_IO_PRI"} = $G_IO_PRI;
1096 push @EXPORT_OK, qw($G_IO_ERR);
1097 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_ERR);
1099 $_GIOCondition_VALUES{"G_IO_ERR"} = $G_IO_ERR;
1101 push @EXPORT_OK, qw($G_IO_HUP);
1102 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_HUP);
1104 $_GIOCondition_VALUES{"G_IO_HUP"} = $G_IO_HUP;
1106 push @EXPORT_OK, qw($G_IO_NVAL);
1107 push @{$EXPORT_TAGS{"GIOCondition"}}, qw($G_IO_NVAL);
1109 $_GIOCondition_VALUES{"G_IO_NVAL"} = $G_IO_NVAL;
1111 #copy symbols in GIOCondition to constants
1112 push @{$EXPORT_TAGS{"constants"}}, @{$EXPORT_TAGS{"GIOCondition"}};