cleanup and put comments on the deadlock workaround in miniloop
[scpubgit/Object-Remote.git] / lib / Object / Remote / MiniLoop.pm
CommitLineData
9e72f0cf 1package Object::Remote::MiniLoop;
2
3use IO::Select;
befabdee 4use Time::HiRes qw(time);
f4a85080 5use Object::Remote::Logging qw( :log :dlog router );
9e72f0cf 6use Moo;
7
e1a0b9ca 8BEGIN {
9 $SIG{PIPE} = sub { log_debug { "Got a PIPE signal" } };
10
11 router()->exclude_forwarding
12}
4e446335 13
9e72f0cf 14# this is ro because we only actually set it using local in sub run
9e72f0cf 15has is_running => (is => 'ro', clearer => 'stop');
353556c4 16#maximum duration that select() will block - undef means indefinite,
17#0 means no blocking, otherwise maximum time in seconds
18has block_duration => ( is => 'rw' );
9e72f0cf 19
20has _read_watches => (is => 'ro', default => sub { {} });
21has _read_select => (is => 'ro', default => sub { IO::Select->new });
22
fbd3b8ec 23has _write_watches => (is => 'ro', default => sub { {} });
24has _write_select => (is => 'ro', default => sub { IO::Select->new });
25
befabdee 26has _timers => (is => 'ro', default => sub { [] });
27
9e72f0cf 28sub pass_watches_to {
29 my ($self, $new_loop) = @_;
a63cd862 30 log_debug { "passing watches to new run loop" };
9e72f0cf 31 foreach my $fh ($self->_read_select->handles) {
32 $new_loop->watch_io(
33 handle => $fh,
34 on_read_ready => $self->_read_watches->{$fh}
35 );
36 }
fbd3b8ec 37 foreach my $fh ($self->_write_select->handles) {
38 $new_loop->watch_io(
39 handle => $fh,
40 on_write_ready => $self->_write_watches->{$fh}
41 );
42 }
9e72f0cf 43}
44
45sub watch_io {
46 my ($self, %watch) = @_;
47 my $fh = $watch{handle};
90115979 48 Dlog_debug { "Adding IO watch for $_" } $fh;
6b7b2732 49
9e72f0cf 50 if (my $cb = $watch{on_read_ready}) {
90115979 51 log_trace { "IO watcher is registering with select for reading" };
9e72f0cf 52 $self->_read_select->add($fh);
53 $self->_read_watches->{$fh} = $cb;
54 }
fbd3b8ec 55 if (my $cb = $watch{on_write_ready}) {
90115979 56 log_trace { "IO watcher is registering with select for writing" };
fbd3b8ec 57 $self->_write_select->add($fh);
58 $self->_write_watches->{$fh} = $cb;
59 }
498c4ad5 60 return;
9e72f0cf 61}
62
63sub unwatch_io {
64 my ($self, %watch) = @_;
65 my $fh = $watch{handle};
9d64d2d9 66 Dlog_debug { "Removing IO watch for $_" } $fh;
9e72f0cf 67 if ($watch{on_read_ready}) {
9d64d2d9 68 log_trace { "IO watcher is removing read from select()" };
9e72f0cf 69 $self->_read_select->remove($fh);
70 delete $self->_read_watches->{$fh};
71 }
fbd3b8ec 72 if ($watch{on_write_ready}) {
9d64d2d9 73 log_trace { "IO watcher is removing write from select()" };
fbd3b8ec 74 $self->_write_select->remove($fh);
75 delete $self->_write_watches->{$fh};
76 }
befabdee 77 return;
78}
79
f8080c1c 80sub _sort_timers {
81 my ($self, @new) = @_;
82 my $timers = $self->_timers;
83
84 log_trace { "Sorting timers" };
85
86 @{$timers} = sort { $a->[0] <=> $b->[0] } @{$timers}, @new;
87 return;
88}
89
befabdee 90sub watch_time {
91 my ($self, %watch) = @_;
f8080c1c 92 my $at;
93
94 Dlog_trace { "watch_time() invoked with $_" } \%watch;
95
96 if (exists($watch{every})) {
97 $at = time() + $watch{every};
98 } elsif (exists($watch{after})) {
99 $at = time() + $watch{after};
100 } elsif (exists($watch{at})) {
37efeb68 101 $at = $watch{at};
f8080c1c 102 } else {
37efeb68 103 die "watch_time requires every, after or at";
f8080c1c 104 }
105
befabdee 106 die "watch_time requires code" unless my $code = $watch{code};
107 my $timers = $self->_timers;
f8080c1c 108 my $new = [ $at => $code, $watch{every} ];
109 $self->_sort_timers($new);
c824fdf3 110 log_debug { "Created new timer with id '$new' that expires at '$at'" };
befabdee 111 return "$new";
112}
113
114sub unwatch_time {
115 my ($self, $id) = @_;
8d757beb 116 log_trace { "Removing timer with id of '$id'" };
befabdee 117 @$_ = grep !($_ eq $id), @$_ for $self->_timers;
118 return;
9e72f0cf 119}
120
5d59cb98 121sub _next_timer_expires_delay {
122 my ($self) = @_;
123 my $timers = $self->_timers;
353556c4 124 my $delay_max = $self->block_duration;
5d59cb98 125
126 return $delay_max unless @$timers;
127 my $duration = $timers->[0]->[0] - time;
128
129 log_trace { "next timer fires in '$duration' seconds " };
130
131 if ($duration < 0) {
132 $duration = 0;
a6786dda 133 } elsif (defined $delay_max && $duration > $delay_max) {
134 $duration = $delay_max;
5d59cb98 135 }
a6786dda 136
5d59cb98 137 return $duration;
138}
139
9e72f0cf 140sub loop_once {
141 my ($self) = @_;
142 my $read = $self->_read_watches;
fbd3b8ec 143 my $write = $self->_write_watches;
5d59cb98 144 my $read_count = 0;
145 my $write_count = 0;
a63cd862 146 my @c = caller;
5d59cb98 147 my $wait_time = $self->_next_timer_expires_delay;
8f43bcd9 148 log_trace {
149 sprintf("Run loop: loop_once() has been invoked by $c[1]:$c[2] with read:%i write:%i select timeout:%s",
150 scalar(keys(%$read)), scalar(keys(%$write)), defined $wait_time ? $wait_time : 'indefinite' )
151 };
fbd3b8ec 152 my ($readable, $writeable) = IO::Select->select(
5d59cb98 153 $self->_read_select, $self->_write_select, undef, $wait_time
154 );
6b7b2732 155 log_trace {
5d59cb98 156 my $readable_count = defined $readable ? scalar(@$readable) : 0;
157 my $writable_count = defined $writeable ? scalar(@$writeable) : 0;
158 "Run loop: select returned readable:$readable_count writeable:$writable_count";
a63cd862 159 };
9e72f0cf 160 # I would love to trap errors in the select call but IO::Select doesn't
161 # differentiate between an error and a timeout.
162 # -- no, love, mst.
6b7b2732 163
a63cd862 164 log_trace { "Reading from all ready filehandles" };
9e72f0cf 165 foreach my $fh (@$readable) {
5d59cb98 166 next unless $read->{$fh};
167 $read_count++;
168 $read->{$fh}();
67028d62 169 #FIXME this is a rough workaround for race conditions that can cause deadlocks
170 #under load
171 last;
fbd3b8ec 172 }
a63cd862 173 log_trace { "Writing to all ready filehandles" };
fbd3b8ec 174 foreach my $fh (@$writeable) {
5d59cb98 175 next unless $write->{$fh};
176 $write_count++;
177 $write->{$fh}();
67028d62 178 #FIXME this is a rough workaround for race conditions that can cause deadlocks
179 #under load
180 last;
9e72f0cf 181 }
7790ca36 182
5d59cb98 183 log_trace { "Read from $read_count filehandles; wrote to $write_count filehandles" };
befabdee 184 my $timers = $self->_timers;
185 my $now = time();
a63cd862 186 log_trace { "Checking timers" };
befabdee 187 while (@$timers and $timers->[0][0] <= $now) {
f8080c1c 188 my $active = $timers->[0];
b7a853b3 189 Dlog_trace { "Found timer that needs to be executed: '$active'" };
f8080c1c 190
191 if (defined($active->[2])) {
192 #handle the case of an 'every' timer
67028d62 193 $active->[0] = time() + $active->[2];
f8080c1c 194 Dlog_trace { "scheduling timer for repeat execution at $_"} $active->[0];
195 $self->_sort_timers;
196 } else {
197 #it doesn't repeat again so get rid of it
67028d62 198 shift(@$timers);
f8080c1c 199 }
200
201 #execute the timer
202 $active->[1]->();
befabdee 203 }
f8080c1c 204
6b7b2732 205 log_trace { "Run loop: single loop is completed" };
befabdee 206 return;
9e72f0cf 207}
208
6c597351 209sub want_run {
210 my ($self) = @_;
c0a45a55 211 Dlog_debug { "Run loop: Incremeting want_running, is now $_" }
5d59cb98 212 ++$self->{want_running};
6c597351 213}
214
215sub run_while_wanted {
216 my ($self) = @_;
9d64d2d9 217 log_debug { my $wr = $self->{want_running}; "Run loop: run_while_wanted() invoked; want_running: $wr" };
6c597351 218 $self->loop_once while $self->{want_running};
a63cd862 219 log_debug { "Run loop: run_while_wanted() completed" };
befabdee 220 return;
6c597351 221}
222
223sub want_stop {
224 my ($self) = @_;
5d59cb98 225 if (! $self->{want_running}) {
226 log_debug { "Run loop: want_stop() was called but want_running was not true" };
227 return;
228 }
229 Dlog_debug { "Run loop: decrimenting want_running, is now $_" }
230 --$self->{want_running};
6c597351 231}
232
9e72f0cf 233sub run {
234 my ($self) = @_;
6b7b2732 235 log_trace { "Run loop: run() invoked" };
9e72f0cf 236 local $self->{is_running} = 1;
237 while ($self->is_running) {
238 $self->loop_once;
239 }
6b7b2732 240 log_trace { "Run loop: run() completed" };
befabdee 241 return;
9e72f0cf 242}
243
2441;