AnyEvent

 view release on metacpan or  search on metacpan

lib/AnyEvent.pm  view on Meta::CPAN

just to exec external programs can easily beat using C<fork> and C<exec>
(or even C<system>) in most programs.

=item L<AnyEvent::Filesys::Notify>

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<AnyEvent::Filesys::Notify> 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.

(I haven't used it myself, but it seems the biggest problem with it is
it quite bad performance).

=item L<AnyEvent::DBI>

Executes L<DBI> requests asynchronously in a proxy process for you,
notifying you in an event-based way when the operation is finished.

=item L<AnyEvent::FastPing>

The fastest ping in the west.

=item L<Coro>

Has special support for AnyEvent via L<Coro::AnyEvent>, 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 = <STDIN>; # works for ttys

      AnyEvent::HTTP::http_get "url", Coro::rouse_cb;
      my ($body, $hdr) = Coro::rouse_wait;
   };

=back

=cut

package AnyEvent;

BEGIN {
   require "AnyEvent/constants.pl";
   &AnyEvent::common_sense;
}

use Carp ();

our $VERSION = 7.17;
our $MODEL;
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 {
   eval "sub TAINT (){" . (${^TAINT}*1) . "}";

   delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV}
      if ${^TAINT};

   $ENV{"PERL_ANYEVENT_$_"} = $ENV{"AE_$_"}
      for grep s/^AE_// && !exists $ENV{"PERL_ANYEVENT_$_"}, keys %ENV;

   @ENV{grep /^PERL_ANYEVENT_/, keys %ENV} = ()
      if ${^TAINT};

   # $ENV{PERL_ANYEVENT_xxx} now valid

   $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";
}

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

lib/AnyEvent.pm  view on Meta::CPAN

   $cv->{_ae_cb}
}

sub begin {
   ++$_[0]{_ae_counter};
   $_[0]{_ae_end_cb} = $_[1] if @_ > 1;
}

sub end {
   return if --$_[0]{_ae_counter};
   &{ $_[0]{_ae_end_cb} || sub { $_[0]->send } };
}

# undocumented/compatibility with pre-3.4
*broadcast = \&send;
*wait      = \&recv;

=head1 ERROR AND EXCEPTION HANDLING

In general, AnyEvent does not do any error handling - it relies on the
caller to do that if required. The L<AnyEvent::Strict> module (see also
the C<PERL_ANYEVENT_STRICT> environment variable, below) provides strict
checking of all AnyEvent methods, however, which is highly useful during
development.

As for exception handling (i.e. runtime errors and exceptions thrown while
executing a callback), this is not only highly event-loop specific, but
also not in any way wrapped by this module, as this is the job of the main
program.

The pure perl event loop simply re-throws the exception (usually
within C<< condvar->recv >>), the L<Event> and L<EV> modules call C<<
$Event/EV::DIED->() >>, L<Glib> uses C<< install_exception_handler >> and
so on.

=head1 ENVIRONMENT VARIABLES

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<PERL_ANYEVENT_DEBUG_WRAP> causes the L<AnyEvent::Debug> module to be
loaded.

All the environment variables documented here start with
C<PERL_ANYEVENT_>, which is what AnyEvent considers its own
namespace. Other modules are encouraged (but by no means required) to use
C<PERL_ANYEVENT_SUBMODULE> if they have registered the AnyEvent::Submodule
namespace on CPAN, for any submodule. For example, L<AnyEvent::HTTP> could
be expected to use C<PERL_ANYEVENT_HTTP_PROXY> (it should not access env
variables starting with C<AE_>, see below).

All variables can also be set via the C<AE_> prefix, that is, instead
of setting C<PERL_ANYEVENT_VERBOSE> you can also set C<AE_VERBOSE>. In
case there is a clash btween anyevent and another program that uses
C<AE_something> you can set the corresponding C<PERL_ANYEVENT_something>
variable to the empty string, as those variables take precedence.

When AnyEvent is first loaded, it copies all C<AE_xxx> env variables
to their C<PERL_ANYEVENT_xxx> counterpart unless that variable already
exists. If taint mode is on, then AnyEvent will remove I<all> environment
variables starting with C<PERL_ANYEVENT_> from C<%ENV> (or replace them
with C<undef> or the empty string, if the corresaponding C<AE_> 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.

This ensures that child processes will not see the C<AE_> variables.

The following environment variables are currently known to AnyEvent:

=over 4

=item C<PERL_ANYEVENT_VERBOSE>

By default, AnyEvent will log messages with loglevel C<4> (C<error>) or
higher (see L<AnyEvent::Log>). 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<PERL_ANYEVENT_LOG>, which allows much more
complex specifications.

When set to C<0> (C<off>), then no messages whatsoever will be logged with
everything else at defaults.

When set to C<5> or higher (C<warn>), AnyEvent warns about unexpected
conditions, such as not being able to load the event model specified by
C<PERL_ANYEVENT_MODEL>, or a guard callback throwing an exception - this
is the minimum recommended level for use during development.

When set to C<7> or higher (info), AnyEvent reports which event model it
chooses.

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<PERL_ANYEVENT_LOG>

Accepts rather complex logging specifications. For example, you could log
all C<debug> 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<AnyEvent::Log>.

This variable is evaluated when AnyEvent (or L<AnyEvent::Log>) is loaded,
so will take effect even before AnyEvent has initialised itself.

Note that specifying this environment variable causes the L<AnyEvent::Log>
module to be loaded, while C<PERL_ANYEVENT_VERBOSE> does not, so only
using the latter saves a few hundred kB of memory unless a module
explicitly needs the extra features of AnyEvent::Log.

=item C<PERL_ANYEVENT_STRICT>

AnyEvent does not do much argument checking by default, as thorough
argument checking is very costly. Setting this variable to a true value
will cause AnyEvent to load C<AnyEvent::Strict> and then to thoroughly
check the arguments passed to most method calls. If it finds any problems,
it will croak.

In other words, enables "strict" mode.

lib/AnyEvent.pm  view on Meta::CPAN


This means that, in general, you cannot fork and do event processing in
the child if the event library was initialised before the fork (which
usually happens when the first AnyEvent watcher is created, or the library
is loaded).

If you have to fork, you must either do so I<before> creating your first
watcher OR you must not use AnyEvent at all in the child OR you must do
something completely out of the scope of AnyEvent (see below).

The problem of doing event processing in the parent I<and> the child
is much more complicated: even for backends that I<are> fork-aware or
fork-safe, their behaviour is not usually what you want: fork clones all
watchers, that means all timers, I/O watchers etc. are active in both
parent and child, which is almost never what you want. Using C<exec>
to start worker children from some kind of manage prrocess is usually
preferred, because it is much easier and cleaner, at the expense of having
to have another binary.

In addition to logical problems with fork, there are also implementation
problems. For example, on POSIX systems, you cannot fork at all in Perl
code if a thread (I am talking of pthreads here) was ever created in the
process, and this is just the tip of the iceberg. In general, using fork
from Perl is difficult, and attempting to use fork without an exec to
implement some kind of parallel processing is almost certainly doomed.

To safely fork and exec, you should use a module such as
L<Proc::FastSpawn> that let's you safely fork and exec new processes.

If you want to do multiprocessing using processes, you can
look at the L<AnyEvent::Fork> module (and some related modules
such as L<AnyEvent::Fork::RPC>, L<AnyEvent::Fork::Pool> and
L<AnyEvent::Fork::Remote>). This module allows you to safely create
subprocesses without any limitations - you can use X11 toolkits or
AnyEvent in the children created by L<AnyEvent::Fork> safely and without
any special precautions.


=head1 SECURITY CONSIDERATIONS

AnyEvent can be forced to load any event model via
$ENV{PERL_ANYEVENT_MODEL}. While this cannot (to my knowledge) be used to
execute arbitrary code or directly gain access, it can easily be used to
make the program hang or malfunction in subtle ways, as AnyEvent watchers
will not be active when the program uses a different event model than
specified in the variable.

You can make AnyEvent completely ignore this variable by deleting it
before the first watcher gets created, e.g. with a C<BEGIN> block:

   BEGIN { delete $ENV{PERL_ANYEVENT_MODEL} }
  
   use AnyEvent;

Similar considerations apply to $ENV{PERL_ANYEVENT_VERBOSE}, as that can
be used to probe what backend is used and gain other information (which is
probably even less useful to an attacker than PERL_ANYEVENT_MODEL), and
$ENV{PERL_ANYEVENT_STRICT}.

Note that AnyEvent will remove I<all> environment variables starting with
C<PERL_ANYEVENT_> from C<%ENV> when it is loaded while taint mode is
enabled.


=head1 BUGS

Perl 5.8 has numerous memleaks that sometimes hit this module and are hard
to work around. If you suffer from memleaks, first upgrade to Perl 5.10
and check wether the leaks still show up. (Perl 5.10.0 has other annoying
memleaks, such as leaking on C<map> and C<grep> but it is usually not as
pronounced).


=head1 SEE ALSO

Tutorial/Introduction: L<AnyEvent::Intro>.

FAQ: L<AnyEvent::FAQ>.

Utility functions: L<AnyEvent::Util> (misc. grab-bag), L<AnyEvent::Log>
(simply logging).

Development/Debugging: L<AnyEvent::Strict> (stricter checking),
L<AnyEvent::Debug> (interactive shell, watcher tracing).

Supported event modules: L<AnyEvent::Loop>, L<EV>, L<EV::Glib>,
L<Glib::EV>, L<Event>, L<Glib::Event>, L<Glib>, L<Tk>, L<Event::Lib>,
L<Qt>, L<POE>, L<FLTK>, L<Cocoa::EventLoop>, L<UV>.

Implementations: L<AnyEvent::Impl::EV>, L<AnyEvent::Impl::Event>,
L<AnyEvent::Impl::Glib>, L<AnyEvent::Impl::Tk>, L<AnyEvent::Impl::Perl>,
L<AnyEvent::Impl::EventLib>, L<AnyEvent::Impl::Qt>,
L<AnyEvent::Impl::POE>, L<AnyEvent::Impl::IOAsync>, L<AnyEvent::Impl::Irssi>,
L<AnyEvent::Impl::FLTK>, L<AnyEvent::Impl::Cocoa>, L<AnyEvent::Impl::UV>.

Non-blocking handles, pipes, stream sockets, TCP clients and
servers: L<AnyEvent::Handle>, L<AnyEvent::Socket>, L<AnyEvent::TLS>.

Asynchronous File I/O: L<AnyEvent::IO>.

Asynchronous DNS: L<AnyEvent::DNS>.

Thread support: L<Coro>, L<Coro::AnyEvent>, L<Coro::EV>, L<Coro::Event>.

Nontrivial usage examples: L<AnyEvent::GPSD>, L<AnyEvent::IRC>,
L<AnyEvent::HTTP>.


=head1 AUTHOR

   Marc Lehmann <schmorp@schmorp.de>
   http://anyevent.schmorp.de

=cut

1



( run in 0.600 second using v1.01-cache-2.11-cpan-39bf76dae61 )