<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># -*- perl -*-
#
# Copyright (C) 2004-2011 Daniel P. Berrange
#
# This program is free software; You can redistribute it and/or modify
# it under the same terms as Perl itself. Either:
#
# a) the GNU General Public License as published by the Free
#   Software Foundation; either version 2, or (at your option) any
#   later version,
#
# or
#
# b) the "Artistic License"
#
# The file "COPYING" distributed along with this file provides full
# details of the terms and conditions of the two licenses.

=pod

=head1 NAME

Net::DBus::Reactor - application event loop

=head1 SYNOPSIS

Create and run an event loop:

   use Net::DBus::Reactor;
   my $reactor = Net::DBus::Reactor-&gt;main();

   $reactor-&gt;run();

Manage some file handlers

   $reactor-&gt;add_read($fd,
                      Net::DBus::Callback-&gt;new(method =&gt; sub {
                         my $fd = shift;
                         ...read some data...
                      }, args =&gt; [$fd]));

   $reactor-&gt;add_write($fd,
                       Net::DBus::Callback-&gt;new(method =&gt; sub {
                          my $fd = shift;
                          ...write some data...
                       }, args =&gt; [$fd]));

Temporarily (dis|en)able a handle

   # Disable
   $reactor-&gt;toggle_read($fd, 0);
   # Enable
   $reactor-&gt;toggle_read($fd, 1);

Permanently remove a handle

   $reactor-&gt;remove_read($fd);

Manage a regular timeout every 100 milliseconds

   my $timer = $reactor-&gt;add_timeout(100,
                                     Net::DBus::Callback-&gt;new(
              method =&gt; sub {
                 ...process the alarm...
              }));

Temporarily (dis|en)able a timer

   # Disable
   $reactor-&gt;toggle_timeout($timer, 0);
   # Enable
   $reactor-&gt;toggle_timeout($timer, 1);

Permanently remove a timer

   $reactor-&gt;remove_timeout($timer);

Add a post-dispatch hook

   my $hook = $reactor-&gt;add_hook(Net::DBus::Callback-&gt;new(
         method =&gt; sub {
            ... do some work...
         }));

Remove a hook

   $reactor-&gt;remove_hook($hook);

=head1 DESCRIPTION

This class provides a general purpose event loop for
the purposes of multiplexing I/O events and timeouts
in a single process. The underlying implementation is
done using the select system call. File handles can
be registered for monitoring on read, write and exception
(out-of-band data) events. Timers can be registered
to expire with a periodic frequency. These are implemented
using the timeout parameter of the select system call.
Since this parameter merely represents an upper bound
on the amount of time the select system call is allowed
to sleep, the actual period of the timers may vary. Under
normal load this variance is typically 10 milliseconds.
Finally, hooks may be registered which will be invoked on
each iteration of the event loop (ie after processing
the file events, or timeouts indicated by the select
system call returning).

=head1 METHODS

=over 4

=cut

package Net::DBus::Reactor;

use 5.006;
use strict;
use warnings;

use Net::DBus::Binding::Watch;
use Net::DBus::Callback;
use Time::HiRes qw(gettimeofday);

=item my $reactor = Net::DBus::Reactor-&gt;new();

Creates a new event loop ready for monitoring file handles, or
generating timeouts. Except in very unusual circumstances (examples
of which I can't think up) it is not necessary or desriable to
explicitly create new reactor instances. Instead call the L&lt;main&gt;
method to get a handle to the singleton instance.

=cut

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my %params = @_;
    my $self = {};

    $self-&gt;{fds} = {
	read =&gt; {},
	write =&gt; {},
	exception =&gt; {}
    };
    $self-&gt;{timeouts} = [];
    $self-&gt;{hooks} = [];

    bless $self, $class;

    return $self;
}

use vars qw($main_reactor);

=item $reactor = Net::DBus::Reactor-&gt;main;

Return a handle to the singleton instance of the reactor. This
is the recommended way of getting hold of a reactor, since it
removes the need for modules to pass around handles to their
privately created reactors.

=cut

sub main {
    my $class = shift;
    $main_reactor = $class-&gt;new() unless defined $main_reactor;
    return $main_reactor;
}


=item $reactor-&gt;manage($connection);

=item $reactor-&gt;manage($server);

Registers a C&lt;Net::DBus::Binding::Connection&gt; or C&lt;Net::DBus::Binding::Server&gt; object
for management by the event loop. This basically involves
hooking up the watch &amp; timeout callbacks to the event loop.
For connections it will also register a hook to invoke the
C&lt;dispatch&gt; method periodically.

=cut

sub manage {
    my $self = shift;
    my $object = shift;

    if ($object-&gt;can("set_watch_callbacks")) {
	$object-&gt;set_watch_callbacks(sub {
	    my $object = shift;
	    my $watch = shift;

	    $self-&gt;_manage_watch_on($object, $watch);
	}, sub {
	    my $object = shift;
	    my $watch = shift;

	    $self-&gt;_manage_watch_off($object, $watch);
	}, sub {
	    my $object = shift;
	    my $watch = shift;

	    $self-&gt;_manage_watch_toggle($object, $watch);
	});
    }

    if ($object-&gt;can("set_timeout_callbacks")) {
	$object-&gt;set_timeout_callbacks(sub {
	    my $object = shift;
	    my $timeout = shift;
	
	    my $key = $self-&gt;add_timeout($timeout-&gt;get_interval,
					 Net::DBus::Callback-&gt;new(object =&gt; $timeout,
								  method =&gt; "handle",
								  args =&gt; []),
					 $timeout-&gt;is_enabled);
	    $timeout-&gt;set_data($key);
	}, sub {
	    my $object = shift;
	    my $timeout = shift;
	
	    my $key = $timeout-&gt;get_data;
	    $self-&gt;remove_timeout($key);
	}, sub {
	    my $object = shift;
	    my $timeout = shift;
	
	    my $key = $timeout-&gt;get_data;
	    $self-&gt;toggle_timeout($key,
				  $timeout-&gt;is_enabled,
				  $timeout-&gt;get_interval);
	});
    }

    if ($object-&gt;can("dispatch")) {
	$self-&gt;add_hook(Net::DBus::Callback-&gt;new(object =&gt; $object,
						 method =&gt; "dispatch",
						 args =&gt; []),
			1);
    }
    if ($object-&gt;can("flush")) {
	$self-&gt;add_hook(Net::DBus::Callback-&gt;new(object =&gt; $object,
						 method =&gt; "flush",
						 args =&gt; []),
			1);
    }
}


sub _manage_watch_on {
    my $self = shift;
    my $object = shift;
    my $watch = shift;
    my $flags = $watch-&gt;get_flags;

    if ($flags &amp; &amp;Net::DBus::Binding::Watch::READABLE) {
	$self-&gt;add_read($watch-&gt;get_fileno,
			Net::DBus::Callback-&gt;new(object =&gt; $watch,
					    method =&gt; "handle",
					    args =&gt; [&amp;Net::DBus::Binding::Watch::READABLE]),
			$watch-&gt;is_enabled);
    }
    if ($flags &amp; &amp;Net::DBus::Binding::Watch::WRITABLE) {
	$self-&gt;add_write($watch-&gt;get_fileno,
			 Net::DBus::Callback-&gt;new(object =&gt; $watch,
					     method =&gt; "handle",
					     args =&gt; [&amp;Net::DBus::Binding::Watch::WRITABLE]),
			 $watch-&gt;is_enabled);
    }
#    $self-&gt;add_exception($watch-&gt;get_fileno, $watch,
#			 Net::DBus::Callback-&gt;new(object =&gt; $watch,
#					     method =&gt; "handle",
#					     args =&gt; [&amp;Net::DBus::Binding::Watch::ERROR]),
#			 $watch-&gt;is_enabled);

}

sub _manage_watch_off {
    my $self = shift;
    my $object = shift;
    my $watch = shift;
    my $flags = $watch-&gt;get_flags;

    if ($flags &amp; &amp;Net::DBus::Binding::Watch::READABLE) {
	$self-&gt;remove_read($watch-&gt;get_fileno);
    }
    if ($flags &amp; &amp;Net::DBus::Binding::Watch::WRITABLE) {
	$self-&gt;remove_write($watch-&gt;get_fileno);
    }
#    $self-&gt;remove_exception($watch-&gt;get_fileno);
}

sub _manage_watch_toggle {
    my $self = shift;
    my $object = shift;
    my $watch = shift;
    my $flags = $watch-&gt;get_flags;

    if ($flags &amp; &amp;Net::DBus::Binding::Watch::READABLE) {
	$self-&gt;toggle_read($watch-&gt;get_fileno, $watch-&gt;is_enabled);
    }
    if ($flags &amp; &amp;Net::DBus::Binding::Watch::WRITABLE) {
	$self-&gt;toggle_write($watch-&gt;get_fileno, $watch-&gt;is_enabled);
    }
    $self-&gt;toggle_exception($watch-&gt;get_fileno, $watch-&gt;is_enabled);
}


=item $reactor-&gt;run();

Starts the event loop monitoring any registered
file handles and timeouts. At least one file
handle, or timer must have been registered prior
to running the reactor, otherwise it will immediately
exit. The reactor will run until all registered
file handles, or timeouts have been removed, or
disabled. The reactor can be explicitly stopped by
calling the C&lt;shutdown&gt; method.

=cut

sub run {
    my $self = shift;

    $self-&gt;{running} = 1;
    while ($self-&gt;{running}) { $self-&gt;step };
}

=item $reactor-&gt;shutdown();

Explicitly shutdown the reactor after pending
events have been processed.

=cut

sub shutdown {
    my $self = shift;
    $self-&gt;{running} = 0;
}

=item $reactor-&gt;step();

Perform one iteration of the event loop, going to
sleep until an event occurs on a registered file
handle, or a timeout occurrs. This method is generally
not required in day-to-day use.

=cut

sub step {
    my $self = shift;

    my @callbacks = $self-&gt;_dispatch_hook();

    foreach my $callback (@callbacks) {
	$callback-&gt;invoke;
    }

    my ($ri, $ric) = $self-&gt;_bits("read");
    my ($wi, $wic) = $self-&gt;_bits("write");
    my ($ei, $eic) = $self-&gt;_bits("exception");
    my $timeout = $self-&gt;_timeout($self-&gt;_now);

    if (!$ric &amp;&amp; !$wic &amp;&amp; !$eic &amp;&amp; !(defined $timeout)) {
	$self-&gt;{running} = 0;
    }

    # One of the hooks we ran might have requested shutdown
    # so check here to avoid a undesirable wait in select()
    # cf RT #39068
    return unless $self-&gt;{running};

    my ($ro, $wo, $eo);
    my $n = select($ro=$ri,$wo=$wi,$eo=$ei, (defined $timeout ? ($timeout ? $timeout/1000 : 0) : undef));

    @callbacks = ();
    if ($n &gt; 0) {
	push @callbacks, $self-&gt;_dispatch_fd("read", $ro);
	push @callbacks, $self-&gt;_dispatch_fd("write", $wo);
	push @callbacks, $self-&gt;_dispatch_fd("exception", $eo);
    }
    push @callbacks, $self-&gt;_dispatch_timeout($self-&gt;_now);
    #push @callbacks, $self-&gt;_dispatch_hook();

    foreach my $callback (@callbacks) {
	$callback-&gt;invoke;
    }

    return 1;
}

sub _now {
    my $self = shift;

    my @now = gettimeofday;

    return $now[0] * 1000 + (($now[1] - ($now[1] % 1000)) / 1000);
}

sub _bits {
    my $self = shift;
    my $type = shift;
    my $vec = '';

    my $count = 0;
    foreach (keys %{$self-&gt;{fds}-&gt;{$type}}) {
	next unless $self-&gt;{fds}-&gt;{$type}-&gt;{$_}-&gt;{enabled};

	$count++;
	vec($vec, $_, 1) = 1;
    }
    return ($vec, $count);
}

sub _timeout {
    my $self = shift;
    my $now = shift;

    my $timeout;
    foreach (@{$self-&gt;{timeouts}}) {
	next unless defined &amp;&amp; $_-&gt;{enabled};

	my $expired = $now - $_-&gt;{last_fired};
	# In case the clock was moved we handle $expired being &lt; 0 (see t/26-reactor-time-adjusted.t)
	$expired = 0 if ($expired &lt; 0);
	my $interval = ($expired &gt; $_-&gt;{interval} ? 0 : $_-&gt;{interval} - $expired);
	$timeout = $interval if !(defined $timeout) ||
	    ($interval &lt; $timeout);
    }
    return $timeout;
}


sub _dispatch_fd {
    my $self = shift;
    my $type = shift;
    my $vec = shift;

    my @callbacks;
    foreach my $fd (keys %{$self-&gt;{fds}-&gt;{$type}}) {
	next unless $self-&gt;{fds}-&gt;{$type}-&gt;{$fd}-&gt;{enabled};

	if (vec($vec, $fd, 1)) {
	    my $rec = $self-&gt;{fds}-&gt;{$type}-&gt;{$fd};
	
	    push @callbacks, $self-&gt;{fds}-&gt;{$type}-&gt;{$fd}-&gt;{callback};
	}
    }
    return @callbacks;
}


sub _dispatch_timeout {
    my $self = shift;
    my $now = shift;

    my @callbacks;
    foreach my $timeout (@{$self-&gt;{timeouts}}) {
	next unless defined($timeout) &amp;&amp; $timeout-&gt;{enabled};
	my $expired = $now - $timeout-&gt;{last_fired};
	# if system clock was adjusted last_fired can be in the future
	# (see t/26-reactor-time-adjusted.t)
	$expired = $timeout-&gt;{interval} if ($expired &lt; 0);

	# Select typically returns a little (0-10 ms) before we
	# asked it for. (8 milliseconds seems reasonable balance
	# between early timeouts &amp; extra select calls
	if ($expired &gt;= ($timeout-&gt;{interval}-8)) {
	    $timeout-&gt;{last_fired} = $now;
	    push @callbacks, $timeout-&gt;{callback};
	}
    }
    return @callbacks;
}


sub _dispatch_hook {
    my $self = shift;
    my $now = shift;

    my @callbacks;
    foreach my $hook (@{$self-&gt;{hooks}}) {
	next unless $hook-&gt;{enabled};
	push @callbacks, $hook-&gt;{callback};
    }
    return @callbacks;
}


=item $reactor-&gt;add_read($fd, $callback[, $status]);

Registers a file handle for monitoring of read
events. The C&lt;$callback&gt; parameter specifies either
a code reference to a subroutine, or an instance of
the C&lt;Net::DBus::Callback&gt; object to invoke each time
an event occurs. The optional C&lt;$status&gt; parameter is
a boolean value to specify whether the watch is
initially enabled.

=cut

sub add_read {
    my $self = shift;
    $self-&gt;_add("read", @_);
}

=item $reactor-&gt;add_write($fd, $callback[, $status]);

Registers a file handle for monitoring of write
events. The C&lt;$callback&gt; parameter specifies either
a code reference to a subroutine, or an
instance of the C&lt;Net::DBus::Callback&gt; object to invoke
each time an event occurs. The optional C&lt;$status&gt;
parameter is a boolean value to specify whether the
watch is initially enabled.

=cut

sub add_write {
    my $self = shift;
    $self-&gt;_add("write", @_);
}


=item $reactor-&gt;add_exception($fd, $callback[, $status]);

Registers a file handle for monitoring of exception
events. The C&lt;$callback&gt; parameter specifies either
a code reference to a subroutine, or  an
instance of the C&lt;Net::DBus::Callback&gt; object to invoke
each time an event occurs. The optional C&lt;$status&gt;
parameter is a boolean value to specify whether the
watch is initially enabled.

=cut

sub add_exception {
    my $self = shift;
    $self-&gt;_add("exception", @_);
}


=item my $id = $reactor-&gt;add_timeout($interval, $callback, $status);

Registers a new timeout to expire every C&lt;$interval&gt;
milliseconds. The C&lt;$callback&gt; parameter specifies either
a code reference to a subroutine, or an
instance of the C&lt;Net::DBus::Callback&gt; object to invoke
each time the timeout expires. The optional C&lt;$status&gt;
parameter is a boolean value to specify whether the
timeout is initially enabled. The return parameter is
a unique identifier which can be used to later remove
or disable the timeout.

=cut

sub add_timeout {
    my $self = shift;
    my $interval = shift;
    my $callback = shift;
    my $enabled = shift;
    $enabled = 1 unless defined $enabled;

    if (ref($callback) eq "CODE") {
	$callback = Net::DBus::Callback-&gt;new(method =&gt; $callback);
    }

    my $key;
    for (my $i = 0 ; $i &lt;= $#{$self-&gt;{timeouts}} &amp;&amp; !(defined $key); $i++) {
	$key = $i unless defined $self-&gt;{timeouts}-&gt;[$i];
    }
    $key = $#{$self-&gt;{timeouts}}+1 unless defined $key;

    $self-&gt;{timeouts}-&gt;[$key] = {
	interval =&gt; $interval,
	last_fired =&gt; $self-&gt;_now,
	callback =&gt; $callback,
	enabled =&gt; $enabled
	};

    return $key;
}


=item $reactor-&gt;remove_timeout($id);

Removes a previously registered timeout specified by
the C&lt;$id&gt; parameter.

=cut

sub remove_timeout {
    my $self = shift;
    my $key = shift;

    die "no timeout active with key '$key'"
	unless defined $self-&gt;{timeouts}-&gt;[$key];

    $self-&gt;{timeouts}-&gt;[$key] = undef;
}


=item $reactor-&gt;toggle_timeout($id, $status[, $interval]);

Updates the state of a previously registered timeout
specified by the C&lt;$id&gt; parameter. The C&lt;$status&gt;
parameter specifies whether the timeout is to be enabled
or disabled, while the optional C&lt;$interval&gt; parameter
can be used to change the period of the timeout.

=cut

sub toggle_timeout {
    my $self = shift;
    my $key = shift;
    my $enabled = shift;

    die "no timeout active with key '$key'"
	unless defined $self-&gt;{timeouts}-&gt;[$key];

    $self-&gt;{timeouts}-&gt;[$key]-&gt;{enabled} = $enabled;
    $self-&gt;{timeouts}-&gt;[$key]-&gt;{interval} = shift if @_;
}


=item my $id = $reactor-&gt;add_hook($callback[, $status]);

Registers a new hook to be fired on each iteration
of the event loop. The C&lt;$callback&gt; parameter
specifies  either a code reference to a subroutine, or
an instance of the C&lt;Net::DBus::Callback&gt;
class to invoke. The C&lt;$status&gt; parameter determines
whether the hook is initially enabled, or disabled.
The return parameter is a unique id which should
be used to later remove, or disable the hook.

=cut

sub add_hook {
    my $self = shift;
    my $callback = shift;
    my $enabled = shift;
    $enabled = 1 unless defined $enabled;

    if (ref($callback) eq "CODE") {
	$callback = Net::DBus::Callback-&gt;new(method =&gt; $callback);
    }

    my $key;
    for (my $i = 0 ; $i &lt;= $#{$self-&gt;{hooks}} &amp;&amp; !(defined $key); $i++) {
	$key = $i unless defined $self-&gt;{hooks}-&gt;[$i];
    }
    $key = $#{$self-&gt;{hooks}}+1 unless defined $key;

    $self-&gt;{hooks}-&gt;[$key] = {
	callback =&gt; $callback,
	enabled =&gt; $enabled
	};

    return $key;
}


=item $reactor-&gt;remove_hook($id)

Removes the previously registered hook identified
by C&lt;$id&gt;.

=cut

sub remove_hook {
    my $self = shift;
    my $key = shift;

    die "no hook present with key '$key'"
	unless defined $self-&gt;{hooks}-&gt;[$key];


    $self-&gt;{hooks}-&gt;[$key] = undef;
}

=item $reactor-&gt;toggle_hook($id, $status)

Updates the status of the previously registered
hook identified by C&lt;$id&gt;. The C&lt;$status&gt; parameter
determines whether the hook is to be enabled or
disabled.

=cut

sub toggle_hook {
    my $self = shift;
    my $key = shift;
    my $enabled = shift;

    $self-&gt;{hooks}-&gt;[$key]-&gt;{enabled} = $enabled;
}

sub _add {
    my $self = shift;
    my $type = shift;
    my $fd = shift;
    my $callback = shift;
    my $enabled = shift;
    $enabled = 1 unless defined $enabled;

    if (ref($callback) eq "CODE") {
	$callback = Net::DBus::Callback-&gt;new(method =&gt; $callback);
    }

    $self-&gt;{fds}-&gt;{$type}-&gt;{$fd} = {
	callback =&gt; $callback,
	enabled =&gt; $enabled
	};
}

=item $reactor-&gt;remove_read($fd);

=item $reactor-&gt;remove_write($fd);

=item $reactor-&gt;remove_exception($fd);

Removes a watch on the file handle C&lt;$fd&gt;.

=cut

sub remove_read {
    my $self = shift;
    $self-&gt;_remove("read", @_);
}

sub remove_write {
    my $self = shift;
    $self-&gt;_remove("write", @_);
}

sub remove_exception {
    my $self = shift;
    $self-&gt;_remove("exception", @_);
}

sub _remove {
    my $self = shift;
    my $type = shift;
    my $fd = shift;

    die "no handle ($type) active with fd '$fd'"
	unless exists $self-&gt;{fds}-&gt;{$type}-&gt;{$fd};

    delete $self-&gt;{fds}-&gt;{$type}-&gt;{$fd};
}

=item $reactor-&gt;toggle_read($fd, $status);

=item $reactor-&gt;toggle_write($fd, $status);

=item $reactor-&gt;toggle_exception($fd, $status);

Updates the status of a watch on the file handle C&lt;$fd&gt;.
The C&lt;$status&gt; parameter species whether the watch is
to be enabled or disabled.

=cut

sub toggle_read {
    my $self = shift;
    $self-&gt;_toggle("read", @_);
}

sub toggle_write {
    my $self = shift;
    $self-&gt;_toggle("write", @_);
}

sub toggle_exception {
    my $self = shift;
    $self-&gt;_toggle("exception", @_);
}

sub _toggle {
    my $self = shift;
    my $type = shift;
    my $fd = shift;
    my $enabled = shift;

    $self-&gt;{fds}-&gt;{$type}-&gt;{$fd}-&gt;{enabled} = $enabled;
}


1;

=pod

=back

=head1 SEE ALSO

L&lt;Net::DBus::Callback&gt;, L&lt;Net::DBus::Connection&gt;, L&lt;Net::DBus::Server&gt;

=head1 AUTHOR

Daniel Berrange E&lt;lt&gt;dan@berrange.comE&lt;gt&gt;

=head1 COPYRIGHT

Copyright 2004-2011 by Daniel Berrange

=cut
</pre></body></html>