--- AnyEvent/lib/AnyEvent.pm 2010/11/23 04:45:59 1.338 +++ AnyEvent/lib/AnyEvent.pm 2011/10/01 22:39:29 1.387 @@ -2,8 +2,8 @@ AnyEvent - the DBI of event loop programming -EV, Event, Glib, Tk, Perl, Event::Lib, Irssi, rxvt-unicode, IO::Async, Qt -and POE are various supported event loops/environments. +EV, Event, Glib, Tk, Perl, Event::Lib, Irssi, rxvt-unicode, IO::Async, Qt, +FLTK and POE are various supported event loops/environments. =head1 SYNOPSIS @@ -87,12 +87,12 @@ AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works fine. AnyEvent + Tk works fine etc. etc. but none of these work together -with the rest: POE + IO::Async? No go. Tk + Event? No go. Again: if -your module uses one of those, every user of your module has to use it, -too. But if your module uses AnyEvent, it works transparently with all -event models it supports (including stuff like IO::Async, as long as those -use one of the supported event loops. It is easy to add new event loops -to AnyEvent, too, so it is future-proof). +with the rest: POE + EV? No go. Tk + Event? No go. Again: if your module +uses one of those, every user of your module has to use it, too. But if +your module uses AnyEvent, it works transparently with all event models it +supports (including stuff like IO::Async, as long as those use one of the +supported event loops. It is easy to add new event loops to AnyEvent, too, +so it is future-proof). In addition to being free of having to use I, AnyEvent also is free of bloat and policy: with POE or similar @@ -123,11 +123,11 @@ During the first call of any watcher-creation method, the module tries to detect the currently loaded event loop by probing whether one of the -following modules is already loaded: L, L, +following modules is already loaded: L, L, L, L, L, L, L, L. The first one found is used. If none are detected, the module tries to load the first four modules in the order given; but note that if L is not -available, the pure-perl L should always work, so +available, the pure-perl L should always work, so the other two are not normally tried. Because AnyEvent first checks for modules that are already loaded, loading @@ -144,9 +144,9 @@ as very few modules hardcode event loops without announcing this very loudly. -The pure-perl implementation of AnyEvent is called -C. Like other event modules you can load it -explicitly and enjoy the high availability of that event loop :) +The pure-perl implementation of AnyEvent is called C. Like +other event modules you can load it explicitly and enjoy the high +availability of that event loop :) =head1 WATCHERS @@ -358,9 +358,9 @@ =item AnyEvent->now_update -Some event loops (such as L or L) cache -the current time for each loop iteration (see the discussion of L<< -AnyEvent->now >>, above). +Some event loops (such as L or L) cache the current +time for each loop iteration (see the discussion of L<< AnyEvent->now >>, +above). When a callback runs for a long time (or when the process sleeps), then this "current" time will differ substantially from the real time, which @@ -417,9 +417,9 @@ =head3 Safe/Unsafe Signals -Perl signals can be either "safe" (synchronous to opcode handling) or -"unsafe" (asynchronous) - the former might get delayed indefinitely, the -latter might corrupt your memory. +Perl signals can be either "safe" (synchronous to opcode handling) +or "unsafe" (asynchronous) - the former might delay signal delivery +indefinitely, the latter might corrupt your memory. AnyEvent signal handlers are, in addition, synchronous to the event loop, i.e. they will not interrupt your running perl program but will only be @@ -428,23 +428,21 @@ =head3 Signal Races, Delays and Workarounds -Many event loops (e.g. Glib, Tk, Qt, IO::Async) do not support attaching -callbacks to signals in a generic way, which is a pity, as you cannot -do race-free signal handling in perl, requiring C libraries for -this. AnyEvent will try to do its best, which means in some cases, -signals will be delayed. The maximum time a signal might be delayed is -specified in C<$AnyEvent::MAX_SIGNAL_LATENCY> (default: 10 seconds). This -variable can be changed only before the first signal watcher is created, -and should be left alone otherwise. This variable determines how often -AnyEvent polls for signals (in case a wake-up was missed). Higher values -will cause fewer spurious wake-ups, which is better for power and CPU -saving. +Many event loops (e.g. Glib, Tk, Qt, IO::Async) do not support +attaching callbacks to signals in a generic way, which is a pity, +as you cannot do race-free signal handling in perl, requiring +C libraries for this. AnyEvent will try to do its best, which +means in some cases, signals will be delayed. The maximum time +a signal might be delayed is 10 seconds by default, but can +be overriden via C<$ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY}> or +C<$AnyEvent::MAX_SIGNAL_LATENCY> - see the Ö +section for details. All these problems can be avoided by installing the optional L module, which works with most event loops. It will not work with inherently broken event loops such as L or L -(and not with L currently, as POE does its own workaround with -one-second latency). For those, you just have to suffer the delays. +(and not with L currently). For those, you just have to suffer the +delays. =head2 CHILD PROCESS WATCHERS @@ -484,8 +482,8 @@ C). As most event loops do not support waiting for child events, they will be -emulated by AnyEvent in most cases, in which the latency and race problems -mentioned in the description of signal watchers apply. +emulated by AnyEvent in most cases, in which case the latency and race +problems mentioned in the description of signal watchers apply. Example: fork a process and wait for it @@ -862,7 +860,7 @@ AnyEvent itself. AnyEvent::Impl::EV based on EV (interface to libev, best choice). - AnyEvent::Impl::Perl pure-perl implementation, fast and portable. + AnyEvent::Impl::Perl pure-perl AnyEvent::Loop, fast and portable. =item Backends that are transparently being picked up when they are used. @@ -878,6 +876,9 @@ AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse. AnyEvent::Impl::POE based on POE, very slow, some limitations. AnyEvent::Impl::Irssi used when running within irssi. + AnyEvent::Impl::IOAsync based on IO::Async. + AnyEvent::Impl::Cocoa based on Cocoa::EventLoop. + AnyEvent::Impl::FLTK based on FLTK (fltk 2 binding). =item Backends with special needs. @@ -888,14 +889,6 @@ AnyEvent::Impl::Qt based on Qt. -Support for IO::Async can only be partial, as it is too broken and -architecturally limited to even support the AnyEvent API. It also -is the only event loop that needs the loop to be set explicitly, so -it can only be used by a main program knowing about AnyEvent. See -L for the gory details. - - AnyEvent::Impl::IOAsync based on IO::Async, cannot be autoprobed. - =item Event loops that are indirectly supported via other backends. Some event loops can be supported via other modules: @@ -941,6 +934,10 @@ have created an AnyEvent watcher anyway, that is, as late as possible at runtime, and not e.g. during initialisation of your module. +The effect of calling this function is as if a watcher had been created +(specifically, actions that happen "when the first watcher is created" +happen when calling detetc as well). + If you need to do some initialisation before AnyEvent watchers are created, use C. @@ -1012,6 +1009,64 @@ push @AnyEvent::post_detect, sub { require Coro::AnyEvent }; } +=item AnyEvent::postpone { BLOCK } + +Arranges for the block to be executed as soon as possible, but not before +the call itself returns. In practise, the block will be executed just +before the event loop polls for new events, or shortly afterwards. + +This function never returns anything (to make the C idiom more useful. + +To understand the usefulness of this function, consider a function that +asynchronously does something for you and returns some transaction +object or guard to let you cancel the operation. For example, +C: + + # start a conenction attempt unless one is active + $self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub { + delete $self->{connect_guard}; + ... + }; + +Imagine that this function could instantly call the callback, for +example, because it detects an obvious error such as a negative port +number. Invoking the callback before the function returns causes problems +however: the callback will be called and will try to delete the guard +object. But since the function hasn't returned yet, there is nothing to +delete. When the function eventually returns it will assign the guard +object to C<< $self->{connect_guard} >>, where it will likely never be +deleted, so the program thinks it is still trying to connect. + +This is where C should be used. Instead of calling the +callback directly on error: + + $cb->(undef), return # signal error to callback, BAD! + if $some_error_condition; + +It should use C: + + AnyEvent::postpone { $cb->(undef) }, return # signal error to callback, later + if $some_error_condition; + +=item AnyEvent::log $level, $msg[, @args] + +Log the given C<$msg> at the given C<$level>. + +If L is not loaded then this function makes a simple test +to see whether the message will be logged. If the test succeeds it will +load AnyEvent::Log and call C - consequently, look at +the L documentation for details. + +If the test fails it will simply return. Right now this happens when a +numerical loglevel is used and it is larger than the level specified via +C<$ENV{PERL_ANYEVENT_VERBOSE}>. + +If you want to sprinkle loads of logging calls around your code, consider +creating a logger callback with the C function, +which can reduce typing, codesize and can reduce the logging overhead +enourmously. + =back =head1 WHAT TO DO IN A MODULE @@ -1054,7 +1109,7 @@ might choose the wrong one unless you load the correct one yourself. You can chose to use a pure-perl implementation by loading the -C module, which gives you similar behaviour +C module, which gives you similar behaviour everywhere, but letting AnyEvent chose the model is generally better. =head2 MAINLOOP EMULATION @@ -1077,9 +1132,12 @@ =head1 OTHER MODULES The following is a non-exhaustive list of additional modules that use -AnyEvent as a client and can therefore be mixed easily with other AnyEvent -modules and other event loops in the same program. Some of the modules -come as part of AnyEvent, the others are available via CPAN. +AnyEvent as a client and can therefore be mixed easily with other +AnyEvent modules and other event loops in the same program. Some of the +modules come as part of AnyEvent, the others are available via CPAN (see +L for +a longer non-exhaustive list), and the list is heavily biased towards +modules of the AnyEvent author himself :) =over 4 @@ -1110,35 +1168,31 @@ the curious, IGS is the International Go Server and FCP is the Freenet Client Protocol). -=item L +=item L + +Truly asynchronous (as opposed to non-blocking) I/O, should be in the +toolbox of every event programmer. AnyEvent::AIO transparently fuses +L and AnyEvent together, giving AnyEvent access to event-based +file I/O, and much more. + +=item L -Here be danger! +AnyEvent is good for non-blocking stuff, but it can't detect file or +path changes (e.g. "watch this directory for new files", "watch this +file for changes"). The L module promises to +do just that in a portbale fashion, supporting inotify on GNU/Linux and +some weird, without doubt broken, stuff on OS X to monitor files. It can +fall back to blocking scans at regular intervals transparently on other +platforms, so it's about as portable as it gets. -As Pauli would put it, "Not only is it not right, it's not even wrong!" - -there are so many things wrong with AnyEvent::Handle::UDP, most notably -its use of a stream-based API with a protocol that isn't streamable, that -the only way to improve it is to delete it. - -It features data corruption (but typically only under load) and general -confusion. On top, the author is not only clueless about UDP but also -fact-resistant - some gems of his understanding: "connect doesn't work -with UDP", "UDP packets are not IP packets", "UDP only has datagrams, not -packets", "I don't need to implement proper error checking as UDP doesn't -support error checking" and so on - he doesn't even understand what's -wrong with his module when it is explained to him. +(I haven't used it myself, but I haven't heard anybody complaining about +it yet). =item L Executes L requests asynchronously in a proxy process for you, notifying you in an event-based way when the operation is finished. -=item L - -Truly asynchronous (as opposed to non-blocking) I/O, should be in the -toolbox of every event programmer. AnyEvent::AIO transparently fuses -L and AnyEvent together, giving AnyEvent access to event-based -file I/O, and much more. - =item L A simple embedded webserver. @@ -1149,7 +1203,19 @@ =item L -Has special support for AnyEvent via L. +Has special support for AnyEvent via L, which allows you +to simply invert the flow control - don't call us, we will call you: + + async { + Coro::AnyEvent::sleep 5; # creates a 5s timer and waits for it + print "5 seconds later!\n"; + + Coro::AnyEvent::readable *STDIN; # uses an I/O watcher + my $line = ; # works for ttys + + AnyEvent::HTTP::http_get "url", Coro::rouse_cb; + my ($body, $hdr) = Coro::rouse_wait; + }; =back @@ -1159,8 +1225,8 @@ # basically a tuned-down version of common::sense sub common_sense { - # from common:.sense 3.3 - ${^WARNING_BITS} ^= ${^WARNING_BITS} ^ "\x3c\x3f\x33\x00\x0f\xf3\x0f\xc0\xf0\xfc\x33\x00"; + # from common:.sense 3.4 + ${^WARNING_BITS} ^= ${^WARNING_BITS} ^ "\x3c\x3f\x33\x00\x0f\xf0\x0f\xc0\xf0\xfc\x33\x00"; # use strict vars subs - NO UTF-8, as Util.pm doesn't like this atm. (uts46data.pl) $^H |= 0x00000600; } @@ -1169,15 +1235,13 @@ use Carp (); -our $VERSION = '5.29'; +our $VERSION = '6.02'; our $MODEL; - -our $AUTOLOAD; our @ISA; - our @REGISTRY; - our $VERBOSE; +our %PROTOCOL; # (ipv4|ipv6) => (1|2), higher numbers are preferred +our $MAX_SIGNAL_LATENCY = $ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY} || 10; # executes after the BEGIN block below (tainting!) BEGIN { require "AnyEvent/constants.pl"; @@ -1187,79 +1251,179 @@ delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV} if ${^TAINT}; - $VERBOSE = $ENV{PERL_ANYEVENT_VERBOSE}*1; + $ENV{"PERL_ANYEVENT_$_"} = $ENV{"AE_$_"} + for grep s/^AE_// && !exists $ENV{"PERL_ANYEVENT_$_"}, keys %ENV; -} + @ENV{grep /^PERL_ANYEVENT_/, keys %ENV} = () + if ${^TAINT}; -our $MAX_SIGNAL_LATENCY = 10; + # $ENV{PERL_ANYEVENT_xxx} now valid -our %PROTOCOL; # (ipv4|ipv6) => (1|2), higher numbers are preferred + $VERBOSE = length $ENV{PERL_ANYEVENT_VERBOSE} ? $ENV{PERL_ANYEVENT_VERBOSE}*1 : 4; -{ my $idx; $PROTOCOL{$_} = ++$idx for reverse split /\s*,\s*/, $ENV{PERL_ANYEVENT_PROTOCOLS} || "ipv4,ipv6"; } -my @models = ( - [EV:: => AnyEvent::Impl::EV:: , 1], - [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl:: , 1], +our @post_detect; + +sub post_detect(&) { + my ($cb) = @_; + + push @post_detect, $cb; + + defined wantarray + ? bless \$cb, "AnyEvent::Util::postdetect" + : () +} + +sub AnyEvent::Util::postdetect::DESTROY { + @post_detect = grep $_ != ${$_[0]}, @post_detect; +} + +our $POSTPONE_W; +our @POSTPONE; + +sub _postpone_exec { + undef $POSTPONE_W; + + &{ shift @POSTPONE } + while @POSTPONE; +} + +sub postpone(&) { + push @POSTPONE, shift; + + $POSTPONE_W ||= AE::timer (0, 0, \&_postpone_exec); + + () +} + +sub log($$;@) { + # only load the big bloated module when we actually are about to log something + if ($_[0] <= ($VERBOSE || 1)) { # also catches non-numeric levels(!) and fatal + require AnyEvent::Log; # among other things, sets $VERBOSE to 9 + # AnyEvent::Log overwrites this function + goto &log; + } + + 0 # not logged +} + +sub logger($;$) { + package AnyEvent::Log; + + my ($level, $renabled) = @_; + + $$renabled = $level <= $VERBOSE; + + my $pkg = (caller)[0]; + + my $logger = [$pkg, $level, $renabled]; + + our %LOGGER; + $LOGGER{$logger+0} = $logger; + + require AnyEvent::Util; + my $guard = AnyEvent::Util::guard (sub { + # "clean up" + delete $LOGGER{$logger+0}; + }); + + sub { + return 0 unless $$renabled; + + $guard if 0; # keep guard alive, but don't cause runtime overhead + require AnyEvent::Log unless $AnyEvent::Log::VERSION; + package AnyEvent::Log; + _log ($logger->[0], $level, @_) # logger->[0] has been converted at load time + } +} + +if (length $ENV{PERL_ANYEVENT_LOG}) { + require AnyEvent::Log; # AnyEvent::Log does the thing for us +} + +our @models = ( + [EV:: => AnyEvent::Impl::EV::], + [AnyEvent::Loop:: => AnyEvent::Impl::Perl::], # everything below here will not (normally) be autoprobed - # as the pureperl backend should work everywhere + # as the pure perl backend should work everywhere # and is usually faster - [Event:: => AnyEvent::Impl::Event::, 1], - [Glib:: => AnyEvent::Impl::Glib:: , 1], # becomes extremely slow with many watchers + [Irssi:: => AnyEvent::Impl::Irssi::], # Irssi has a bogus "Event" package, so msut be near the top + [Event:: => AnyEvent::Impl::Event::], # slow, stable + [Glib:: => AnyEvent::Impl::Glib::], # becomes extremely slow with many watchers + # everything below here should not be autoloaded [Event::Lib:: => AnyEvent::Impl::EventLib::], # too buggy - [Irssi:: => AnyEvent::Impl::Irssi::], # Irssi has a bogus "Event" package [Tk:: => AnyEvent::Impl::Tk::], # crashes with many handles [Qt:: => AnyEvent::Impl::Qt::], # requires special main program [POE::Kernel:: => AnyEvent::Impl::POE::], # lasciate ogni speranza [Wx:: => AnyEvent::Impl::POE::], [Prima:: => AnyEvent::Impl::POE::], - # IO::Async is just too broken - we would need workarounds for its - # byzantine signal and broken child handling, among others. - # IO::Async is rather hard to detect, as it doesn't have any - # obvious default class. - [IO::Async:: => AnyEvent::Impl::IOAsync::], # requires special main program - [IO::Async::Loop:: => AnyEvent::Impl::IOAsync::], # requires special main program - [IO::Async::Notifier:: => AnyEvent::Impl::IOAsync::], # requires special main program - [AnyEvent::Impl::IOAsync:: => AnyEvent::Impl::IOAsync::], # requires special main program + [IO::Async::Loop:: => AnyEvent::Impl::IOAsync::], # a bitch to autodetect + [Cocoa::EventLoop:: => AnyEvent::Impl::Cocoa::], + [FLTK:: => AnyEvent::Impl::FLTK::], ); -our %method = map +($_ => 1), - qw(io timer time now now_update signal child idle condvar one_event DESTROY); +our @isa_hook; -our @post_detect; +sub _isa_set { + my @pkg = ("AnyEvent", (map $_->[0], grep defined, @isa_hook), $MODEL); -sub post_detect(&) { - my ($cb) = @_; - - push @post_detect, $cb; + @{"$pkg[$_-1]::ISA"} = $pkg[$_] + for 1 .. $#pkg; - defined wantarray - ? bless \$cb, "AnyEvent::Util::postdetect" - : () + grep $_ && $_->[1], @isa_hook + and AE::_reset (); } -sub AnyEvent::Util::postdetect::DESTROY { - @post_detect = grep $_ != ${$_[0]}, @post_detect; +# used for hooking AnyEvent::Strict and AnyEvent::Debug::Wrap into the class hierarchy +sub _isa_hook($$;$) { + my ($i, $pkg, $reset_ae) = @_; + + $isa_hook[$i] = $pkg ? [$pkg, $reset_ae] : undef; + + _isa_set; } +# all autoloaded methods reserve the complete glob, not just the method slot. +# due to bugs in perls method cache implementation. +our @methods = qw(io timer time now now_update signal child idle condvar); + sub detect() { - # free some memory - *detect = sub () { $MODEL }; + return $MODEL if $MODEL; # some programs keep references to detect + + # IO::Async::Loop::AnyEvent is extremely evil, refuse to work with it + # the author knows about the problems and what it does to AnyEvent as a whole + # (and the ability of others to use AnyEvent), but simply wants to abuse AnyEvent + # anyway. + AnyEvent::log fatal => "AnyEvent: IO::Async::Loop::AnyEvent detected - this module is broken by design,\n" + . "abuses internals and breaks AnyEvent, will not continue." + if exists $INC{"IO/Async/Loop/AnyEvent.pm"}; local $!; # for good measure - local $SIG{__DIE__}; + local $SIG{__DIE__}; # we use eval - if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z]+)$/) { - my $model = "AnyEvent::Impl::$1"; + # free some memory + *detect = sub () { $MODEL }; + # undef &func doesn't correctly update the method cache. grmbl. + # so we delete the whole glob. grmbl. + # otoh, perl doesn't let me undef an active usb, but it lets me free + # a glob with an active sub. hrm. i hope it works, but perl is + # usually buggy in this department. sigh. + delete @{"AnyEvent::"}{@methods}; + undef @methods; + + if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z0-9:]+)$/) { + my $model = $1; + $model = "AnyEvent::Impl::$model" unless $model =~ s/::$//; if (eval "require $model") { + AnyEvent::log 7 => "loaded model '$model' (forced by \$ENV{PERL_ANYEVENT_MODEL}), using it."; $MODEL = $model; - warn "AnyEvent: loaded model '$model' (forced by \$ENV{PERL_ANYEVENT_MODEL}), using it.\n" if $VERBOSE >= 2; } else { - warn "AnyEvent: unable to load model '$model' (from \$ENV{PERL_ANYEVENT_MODEL}):\n$@" if $VERBOSE; + AnyEvent::log 4 => "unable to load model '$model' (from \$ENV{PERL_ANYEVENT_MODEL}):\n$@"; } } @@ -1269,8 +1433,8 @@ my ($package, $model) = @$_; if (${"$package\::VERSION"} > 0) { if (eval "require $model") { + AnyEvent::log 7 => "autodetected model '$model', using it."; $MODEL = $model; - warn "AnyEvent: autodetected model '$model', using it.\n" if $VERBOSE >= 2; last; } } @@ -1279,39 +1443,65 @@ unless ($MODEL) { # try to autoload a model for (@REGISTRY, @models) { - my ($package, $model, $autoload) = @$_; + my ($package, $model) = @$_; if ( - $autoload - and eval "require $package" + eval "require $package" and ${"$package\::VERSION"} > 0 and eval "require $model" ) { + AnyEvent::log 7 => "autoloaded model '$model', using it."; $MODEL = $model; - warn "AnyEvent: autoloaded model '$model', using it.\n" if $VERBOSE >= 2; last; } } $MODEL - or die "AnyEvent: backend autodetection failed - did you properly install AnyEvent?\n"; + or AnyEvent::log fatal => "AnyEvent: backend autodetection failed - did you properly install AnyEvent?"; } } - @models = (); # free probe data + # free memory only needed for probing + undef @models; + undef @REGISTRY; push @{"$MODEL\::ISA"}, "AnyEvent::Base"; - unshift @ISA, $MODEL; # now nuke some methods that are overridden by the backend. - # SUPER is not allowed. + # SUPER usage is not allowed in these. for (qw(time signal child idle)) { undef &{"AnyEvent::Base::$_"} if defined &{"$MODEL\::$_"}; } - require AnyEvent::Strict if $ENV{PERL_ANYEVENT_STRICT}; + _isa_set; + + # we're officially open! + + if ($ENV{PERL_ANYEVENT_STRICT}) { + require AnyEvent::Strict; + } + + if ($ENV{PERL_ANYEVENT_DEBUG_WRAP}) { + require AnyEvent::Debug; + AnyEvent::Debug::wrap ($ENV{PERL_ANYEVENT_DEBUG_WRAP}); + } + + if (length $ENV{PERL_ANYEVENT_DEBUG_SHELL}) { + require AnyEvent::Socket; + require AnyEvent::Debug; + + my $shell = $ENV{PERL_ANYEVENT_DEBUG_SHELL}; + $shell =~ s/\$\$/$$/g; + + my ($host, $service) = AnyEvent::Socket::parse_hostport ($shell); + $AnyEvent::Debug::SHELL = AnyEvent::Debug::shell ($host, $service); + } + + # now the anyevent environment is set up as the user told us to, so + # call the actual user code - post detects (shift @post_detect)->() while @post_detect; + undef @post_detect; *post_detect = sub(&) { shift->(); @@ -1322,16 +1512,14 @@ $MODEL } -sub AUTOLOAD { - (my $func = $AUTOLOAD) =~ s/.*://; - - $method{$func} - or Carp::croak "$func: not a valid AnyEvent class method"; - - detect; - - my $class = shift; - $class->$func (@_); +for my $name (@methods) { + *$name = sub { + detect; + # we use goto because + # a) it makes the thunk more transparent + # b) it allows us to delete the thunk later + goto &{ UNIVERSAL::can AnyEvent => "SUPER::$name" } + }; } # utility function to dup a filehandle. this is used by many backends @@ -1365,45 +1553,55 @@ our $VERSION = $AnyEvent::VERSION; -# fall back to the main API by default - backends and AnyEvent::Base -# implementations can overwrite these. +sub _reset() { + eval q{ + # fall back to the main API by default - backends and AnyEvent::Base + # implementations can overwrite these. -sub io($$$) { - AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2]) -} + sub io($$$) { + AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2]) + } -sub timer($$$) { - AnyEvent->timer (after => $_[0], interval => $_[1], cb => $_[2]) -} + sub timer($$$) { + AnyEvent->timer (after => $_[0], interval => $_[1], cb => $_[2]) + } -sub signal($$) { - AnyEvent->signal (signal => $_[0], cb => $_[1]) -} + sub signal($$) { + AnyEvent->signal (signal => $_[0], cb => $_[1]) + } -sub child($$) { - AnyEvent->child (pid => $_[0], cb => $_[1]) -} + sub child($$) { + AnyEvent->child (pid => $_[0], cb => $_[1]) + } -sub idle($) { - AnyEvent->idle (cb => $_[0]) -} + sub idle($) { + AnyEvent->idle (cb => $_[0]); + } -sub cv(;&) { - AnyEvent->condvar (@_ ? (cb => $_[0]) : ()) -} + sub cv(;&) { + AnyEvent->condvar (@_ ? (cb => $_[0]) : ()) + } -sub now() { - AnyEvent->now -} + sub now() { + AnyEvent->now + } -sub now_update() { - AnyEvent->now_update -} + sub now_update() { + AnyEvent->now_update + } + + sub time() { + AnyEvent->time + } -sub time() { - AnyEvent->time + *postpone = \&AnyEvent::postpone; + *log = \&AnyEvent::log; + }; + die if $@; } +BEGIN { _reset } + package AnyEvent::Base; # default implementations for many methods @@ -1412,15 +1610,17 @@ eval q{ # poor man's autoloading {} # probe for availability of Time::HiRes if (eval "use Time::HiRes (); Time::HiRes::time (); 1") { - warn "AnyEvent: using Time::HiRes for sub-second timing accuracy.\n" if $VERBOSE >= 8; - *AE::time = \&Time::HiRes::time; + *time = sub { Time::HiRes::time () }; + *AE::time = \& Time::HiRes::time ; + *now = \&time; + AnyEvent::log 8 => "AnyEvent: using Time::HiRes for sub-second timing accuracy."; # if (eval "use POSIX (); (POSIX::times())... } else { - warn "AnyEvent: using built-in time(), WARNING, no sub-second resolution!\n" if $VERBOSE; - *AE::time = sub (){ time }; # epic fail + *time = sub { CORE::time }; + *AE::time = sub (){ CORE::time }; + *now = \&time; + AnyEvent::log 3 => "using built-in time(), WARNING, no sub-second resolution!"; } - - *time = sub { AE::time }; # different prototypes }; die if $@; @@ -1428,10 +1628,14 @@ } *now = \&time; - sub now_update { } +sub _poll { + Carp::croak "$AnyEvent::MODEL does not support blocking waits. Caught"; +} + # default implementation for ->condvar +# in fact, the default should not be overwritten sub condvar { eval q{ # poor man's autoloading {} @@ -1519,13 +1723,13 @@ eval q{ # poor man's autoloading {} # probe for availability of Async::Interrupt if (_have_async_interrupt) { - warn "AnyEvent: using Async::Interrupt for race-free signal handling.\n" if $VERBOSE >= 8; + AnyEvent::log 8 => "using Async::Interrupt for race-free signal handling."; $SIGPIPE_R = new Async::Interrupt::EventPipe; $SIG_IO = AE::io $SIGPIPE_R->fileno, 0, \&_signal_exec; } else { - warn "AnyEvent: using emulated perl signal handling with latency timer.\n" if $VERBOSE >= 8; + AnyEvent::log 8 => "using emulated perl signal handling with latency timer."; if (AnyEvent::WIN32) { require AnyEvent::Util; @@ -1611,7 +1815,7 @@ while (%SIG_EV) { for (keys %SIG_EV) { delete $SIG_EV{$_}; - $_->() for values %{ $SIG_CB{$_} || {} }; + &$_ for values %{ $SIG_CB{$_} || {} }; } } }; @@ -1626,7 +1830,6 @@ our %PID_CB; our $CHLD_W; our $CHLD_DELAY_W; -our $WNOHANG; # used by many Impl's sub _emit_childstatus($$) { @@ -1643,21 +1846,16 @@ my $pid; AnyEvent->_emit_childstatus ($pid, $?) - while ($pid = waitpid -1, $WNOHANG) > 0; + while ($pid = waitpid -1, WNOHANG) > 0; }; *child = sub { my (undef, %arg) = @_; - defined (my $pid = $arg{pid} + 0) - or Carp::croak "required option 'pid' is missing"; - - $PID_CB{$pid}{$arg{cb}} = $arg{cb}; + my $pid = $arg{pid}; + my $cb = $arg{cb}; - # WNOHANG is almost cetrainly 1 everywhere - $WNOHANG ||= $^O =~ /^(?:openbsd|netbsd|linux|freebsd|cygwin|MSWin32)$/ - ? 1 - : eval { local $SIG{__DIE__}; require POSIX; &POSIX::WNOHANG } || 1; + $PID_CB{$pid}{$cb+0} = $cb; unless ($CHLD_W) { $CHLD_W = AE::signal CHLD => \&_sigchld; @@ -1665,13 +1863,13 @@ &_sigchld; } - bless [$pid, $arg{cb}], "AnyEvent::Base::child" + bless [$pid, $cb+0], "AnyEvent::Base::child" }; *AnyEvent::Base::child::DESTROY = sub { - my ($pid, $cb) = @{$_[0]}; + my ($pid, $icb) = @{$_[0]}; - delete $PID_CB{$pid}{$cb}; + delete $PID_CB{$pid}{$icb}; delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} }; undef $CHLD_W unless keys %PID_CB; @@ -1694,9 +1892,9 @@ $rcb = sub { if ($cb) { - $w = _time; + $w = AE::time; &$cb; - $w = _time - $w; + $w = AE::time - $w; # never use more then 50% of the time for the idle watcher, # within some limits @@ -1753,6 +1951,10 @@ # nop } +sub _wait { + AnyEvent->_poll until $_[0]{_ae_sent}; +} + sub send { my $cv = shift; $cv->{_ae_sent} = [@_]; @@ -1769,20 +1971,21 @@ $_[0]{_ae_sent} } -sub _wait { - $WAITING - and !$_[0]{_ae_sent} - and Carp::croak "AnyEvent::CondVar: recursive blocking wait detected"; +sub recv { + unless ($_[0]{_ae_sent}) { + $WAITING + and Carp::croak "AnyEvent::CondVar: recursive blocking wait attempted"; - local $WAITING = 1; - AnyEvent->one_event while !$_[0]{_ae_sent}; -} + local $WAITING = 1; + $_[0]->_wait; + } -sub recv { - $_[0]->_wait; + $_[0]{_ae_croak} + and Carp::croak $_[0]{_ae_croak}; - Carp::croak $_[0]{_ae_croak} if $_[0]{_ae_croak}; - wantarray ? @{ $_[0]{_ae_sent} } : $_[0]{_ae_sent}[0] + wantarray + ? @{ $_[0]{_ae_sent} } + : $_[0]{_ae_sent}[0] } sub cb { @@ -1808,7 +2011,7 @@ # undocumented/compatibility with pre-3.4 *broadcast = \&send; -*wait = \&_wait; +*wait = \&recv; =head1 ERROR AND EXCEPTION HANDLING @@ -1830,31 +2033,89 @@ =head1 ENVIRONMENT VARIABLES -The following environment variables are used by this module or its -submodules. +AnyEvent supports a number of environment variables that tune the +runtime behaviour. They are usually evaluated when AnyEvent is +loaded, initialised, or a submodule that uses them is loaded. Many of +them also cause AnyEvent to load additional modules - for example, +C causes the L module to be +loaded. + +All the environment variables documented here start with +C, which is what AnyEvent considers its own +namespace. Other modules are encouraged (but by no means required) to use +C if they have registered the AnyEvent::Submodule +namespace on CPAN, for any submodule. For example, L could +be expected to use C (it should not access env +variables starting with C, see below). + +All variables can also be set via the C prefix, that is, instead +of setting C you can also set C. In +case there is a clash btween anyevent and another program that uses +C you can set the corresponding C +variable to the empty string, as those variables take precedence. + +When AnyEvent is first loaded, it copies all C env variables +to their C counterpart unless that variable already +exists. If taint mode is on, then AnyEvent will remove I environment +variables starting with C from C<%ENV> (or replace them +with C or the empty string, if the corresaponding C variable +is set). + +The exact algorithm is currently: + + 1. if taint mode enabled, delete all PERL_ANYEVENT_xyz variables from %ENV + 2. copy over AE_xyz to PERL_ANYEVENT_xyz unless the latter alraedy exists + 3. if taint mode enabled, set all PERL_ANYEVENT_xyz variables to undef. -Note that AnyEvent will remove I environment variables starting with -C from C<%ENV> when it is loaded while taint mode is -enabled. +This ensures that child processes will not see the C variables. + +The following environment variables are currently known to AnyEvent: =over 4 =item C -By default, AnyEvent will be completely silent except in fatal -conditions. You can set this environment variable to make AnyEvent more -talkative. - -When set to C<1> or higher, causes AnyEvent to warn about unexpected -conditions, such as not being able to load the event model specified by -C. +By default, AnyEvent will only log messages with loglevel C<3> +(C) or higher (see L). You can set this +environment variable to a numerical loglevel to make AnyEvent more (or +less) talkative. + +If you want to do more than just set the global logging level +you should have a look at C, which allows much more +complex specifications. + +When set to C<0> (C), then no messages whatsoever will be logged with +the default logging settings. + +When set to C<5> or higher (C), causes AnyEvent to warn about +unexpected conditions, such as not being able to load the event model +specified by C, or a guard callback throwing an +exception - this is the minimum recommended level. -When set to C<2> or higher, cause AnyEvent to report to STDERR which event -model it chooses. +When set to C<7> or higher (info), cause AnyEvent to report which event model it +chooses. -When set to C<8> or higher, then AnyEvent will report extra information on +When set to C<8> or higher (debug), then AnyEvent will report extra information on which optional modules it loads and how it implements certain features. +=item C + +Accepts rather complex logging specifications. For example, you could log +all C messages of some module to stderr, warnings and above to +stderr, and errors and above to syslog, with: + + PERL_ANYEVENT_LOG=Some::Module=debug,+log:filter=warn,+%syslog:%syslog=error,syslog + +For the rather extensive details, see L. + +This variable is evaluated when AnyEvent (or L) is loaded, +so will take effect even before AnyEvent has initialised itself. + +Note that specifying this environment variable causes the L +module to be loaded, while C does not, so only +using the latter saves a few hundred kB of memory until the first message +is being logged. + =item C AnyEvent does not do much argument checking by default, as thorough @@ -1870,18 +2131,50 @@ C in your environment while developing programs can be very useful, however. +=item C + +If this env variable is nonempty, then its contents will be interpreted by +C and C (after +replacing every occurance of C<$$> by the process pid). The shell object +is saved in C<$AnyEvent::Debug::SHELL>. + +This happens when the first watcher is created. + +For example, to bind a debug shell on a unix domain socket in +F<< /tmp/debug.sock >>, you could use this: + + PERL_ANYEVENT_DEBUG_SHELL=/tmp/debug\$\$.sock perlprog + # connect with e.g.: socat readline /tmp/debug123.sock + +Or to bind to tcp port 4545 on localhost: + + PERL_ANYEVENT_DEBUG_SHELL=127.0.0.1:4545 perlprog + # connect with e.g.: telnet localhost 4545 + +Note that creating sockets in F or on localhost is very unsafe on +multiuser systems. + +=item C + +Can be set to C<0>, C<1> or C<2> and enables wrapping of all watchers for +debugging purposes. See C for details. + =item C This can be used to specify the event model to be used by AnyEvent, before -auto detection and -probing kicks in. It must be a string consisting -entirely of ASCII letters. The string C gets prepended -and the resulting module name is loaded and if the load was successful, -used as event model. If it fails to load AnyEvent will proceed with +auto detection and -probing kicks in. + +It normally is a string consisting entirely of ASCII letters (e.g. C +or C). The string C gets prepended and the +resulting module name is loaded and - if the load was successful - used as +event model backend. If it fails to load then AnyEvent will proceed with auto detection and -probing. -This functionality might change in future versions. +If the string ends with C<::> instead (e.g. C) then +nothing gets prepended and the module name is used as-is (hint: C<::> at +the end of a string designates a module name and quotes it appropriately). -For example, to force the pure perl model (L) you +For example, to force the pure perl model (L) you could start your program like this: PERL_ANYEVENT_MODEL=Perl perl ... @@ -1907,12 +2200,18 @@ addresses. C support either IPv4 or IPv6, but prefer IPv6 over IPv4. +=item C + +This variable, if specified, overrides the F file used by +LC<::resolve_sockaddr>, i.e. hosts aliases will be read +from that file instead. + =item C -Used by L to decide whether to use the EDNS0 extension -for DNS. This extension is generally useful to reduce DNS traffic, but -some (broken) firewalls drop such DNS packets, which is why it is off by -default. +Used by L to decide whether to use the EDNS0 extension for +DNS. This extension is generally useful to reduce DNS traffic, especially +when DNSSEC is involved, but some (broken) firewalls drop such DNS +packets, which is why it is off by default. Setting this variable to C<1> will cause L to announce EDNS0 in its DNS requests. @@ -1928,18 +2227,40 @@ resolver - this is the maximum number of parallel DNS requests that are sent to the DNS server. +=item C + +Perl has inherently racy signal handling (you can basically choose between +losing signals and memory corruption) - pure perl event loops (including +C, when C isn't available) therefore +have to poll regularly to avoid losing signals. + +Some event loops are racy, but don't poll regularly, and some event loops +are written in C but are still racy. For those event loops, AnyEvent +installs a timer that regularly wakes up the event loop. + +By default, the interval for this timer is C<10> seconds, but you can +override this delay with this environment variable (or by setting +the C<$AnyEvent::MAX_SIGNAL_LATENCY> variable before creating signal +watchers). + +Lower values increase CPU (and energy) usage, higher values can introduce +long delays when reaping children or waiting for signals. + +The L module, if available, will be used to avoid this +polling (with most event loops). + =item C -The file to use instead of F (or OS-specific -configuration) in the default resolver. When set to the empty string, no -default config will be used. +The absolute path to a F-style file to use instead of +F (or the OS-specific configuration) in the default +resolver, or the empty string to select the default configuration. =item C, C. When neither C nor C was specified during L context creation, and either of these environment -variables exist, they will be used to specify CA certificate locations -instead of a system-dependent default. +variables are nonempty, they will be used to specify CA certificate +locations instead of a system-dependent default. =item C and C @@ -2281,7 +2602,7 @@ =item * The overhead AnyEvent adds is usually much smaller than the overhead of the actual event loop, only with extremely fast event loops such as EV -adds AnyEvent significant overhead. +does AnyEvent add significant overhead. =item * You should avoid POE like the plague if you want performance or reasonable memory usage. @@ -2590,7 +2911,7 @@ This module is part of perl since release 5.008. It will be used when the chosen event library does not come with a timing source of its own. The -pure-perl event loop (L) will additionally use it to +pure-perl event loop (L) will additionally load it to try to use a monotonic clock for timing stability. =back @@ -2666,17 +2987,23 @@ FAQ: L. -Utility functions: L. +Utility functions: L (misc. grab-bag), L +(simply logging). + +Development/Debugging: L (stricter checking), +L (interactive shell, watcher tracing). -Event modules: L, L, L, L, L, -L, L, L, L, L. +Supported event modules: L, L, L, +L, L, L, L, L, L, +L, L, L. Implementations: L, L, L, L, L, L, L, -L, L, L. +L, L, L, +L. -Non-blocking file handles, sockets, TCP clients and +Non-blocking handles, pipes, stream sockets, TCP clients and servers: L, L, L. Asynchronous DNS: L.