blib/lib/IO/Multiplex/KQueue.pm untested

filter: Statementstmt 0.0% 0 / 293 Branchbran 0.0% 0 / 128 Conditioncond 0.0% 0 / 93 MC/DCmcdc 0.0% 0 / 59 Subroutinesub 0.0% 0 / 44 Podpod 0.0% 0 / 30 totaltotal 0.0% 0 / 647 CC 65 SCAR 60.3
CC
65
Cov
0%
loop
1260.0
shutdown
42.0
write
30.0
CRAP 417.7
1 # $Id: IOMultiplexKQueue.pm 116 2005-12-22 04:25:28Z in2 $
2 package IO::Multiplex::KQueue;
3  
4 =head1 NAME
5  
6 IO::Multiplex::KQueue - IO::Multiplex by kqueue(2)
7  
8 =head1 SYNOPSIS
9  
10 use IO::Multiplex::KQueue;
11  
12 my $mux = new IO::Multiplex::KQueue;
13 $mux->add($fh1);
14 $mux->add(\*FH2);
15 $mux->set_callback_object(...);
16 $mux->listen($server_socket);
17 $mux->loop;
18  
19 sub mux_input {
20 ...
21 }
22  
23  
24 =head1 DESCRIPTION
25  
26 C<IO::Multiplex::KQueue> is kqueue(2) IO::Multiplex implementation with
27 compatible interface to C<IO::Multiplex> (version 1.08).
28 Please refer C<IO::Multiplex> for details.
29  
30 Just install C<IO::KQueue> and replace C<IO::Multiplex> with
31 C<IO::Multiplex::KQueue> in your source code.
32  
33 =head1 EXAMPLES
34  
35 =head2 Orignal Source
36  
37 use IO::Socket;
38 use IO::Multiplex;
39  
40 # Create a multiplex object
41 my $mux = new IO::Multiplex;
42  
43 =head2 Using IO::Multiplex::KQueue
44  
45 use IO::Socket;
46 use IO::Multiplex::KQueue;
47  
48 # Create a multiplex object
49 my $mux = new IO::Multiplex::KQueue;
50 # done! no futher modification!
51  
52 =cut
53  
54 use strict;
55 use POSIX qw(errno_h BUFSIZ);
56 use vars qw($VERSION);
57 use Socket;
58 use FileHandle qw(autoflush);
59 use IO::Handle;
60 use Fcntl;
61 use Carp qw(carp);
62 use IO::KQueue;
63  
64 $VERSION = '0.02';
65  
66 BEGIN {
67 eval {
68 # Can optionally use Hi Res timers if available
69 require Time::HiRes;
70 Time::HiRes->import ('time');
71 }
72 };
73  
74 # This is what you want. Trust me.
75 $SIG{PIPE} = 'IGNORE';
76  
77 sub new
78 {
79 my $package = shift;
80 my $self = bless { _kq => IO::KQueue->new(),
81 _fhs => {},
82 _handles => {},
83 _timerkeys => {},
84 _timers => [],
85 _listen => {} } => $package;
86 return $self;
87 }
88  
89 sub listen
90 {
91 my $self = shift;
92 my $fh = shift;
93  
94 $self->add($fh);
95 $self->{_fhs}{"$fh"}{listen} = 1;
96 }
97  
98 sub add
99 {
100 my $self = shift;
101 my $fh = shift;
102  
103 return if $self->{_fhs}{"$fh"};
104  
105 nonblock($fh);
106 autoflush($fh, 1);
107 $self->{_fhs}{"$fh"}{udp_true} =
108 (SOCK_DGRAM == unpack("i", scalar getsockopt($fh,Socket::SOL_SOCKET(),Socket::SO_TYPE())));
109 $self->{_fhs}{"$fh"}{inbuffer} = '';
110 $self->{_fhs}{"$fh"}{outbuffer} = '';
111 $self->{_fhs}{"$fh"}{fileno} = fileno($fh);
112 $self->{_handles}{"$fh"} = $fh;
113 #fd_set($self->{_readers}, $fh, 1);
114 $self->EV_SET($fh, EVFILT_READ, EV_ADD, 0, 5, [$fh, EVFILT_READ]);
115 tie *$fh, "IO::Multiplex::KQueue::Handle", $self, $fh;
116 return $fh;
117 }
118  
119 sub remove
120 {
121 my $self = shift;
122 my $fh = shift;
123 #fd_set($self->{_writers}, $fh, 0);
124 #fd_set($self->{_readers}, $fh, 0);
125 eval {
126 # according to kqueue(2): Events which are attached to file
127 # descriptors are automatically deleted on the last close of
128 # the descriptor. (different behavior between select(2) and kqueue(2))
129 # removing a fd which is already closed will cause "set kevent
130 # failed: No such file or directory"
131 $self->EV_SET($fh, EVFILT_READ, EV_DELETE);
132 $self->EV_SET($fh, EVFILT_WRITE, EV_DELETE);
133 };
134 delete $self->{_fhs}{"$fh"};
135 delete $self->{_handles}{"$fh"};
136 $self->_removeTimer($fh);
137 untie *$fh;
138 }
139  
140 sub set_callback_object
141 {
142 my $self = shift;
143 my $obj = shift;
144 my $fh = shift;
145 return if $fh && !exists($self->{_fhs}{"$fh"});
146  
147 my $old = $fh ? $self->{_fhs}{"$fh"}{object} : $self->{_object};
148  
149 $fh ? $self->{_fhs}{"$fh"}{object} : $self->{_object} = $obj;
150 return $old;
151 }
152  
153 sub kill_output
154 {
155 my $self = shift;
156 my $fh = shift;
157 return unless $fh && exists($self->{_fhs}{"$fh"});
158  
159 $self->{_fhs}{"$fh"}{outbuffer} = '';
160 $self->EV_SET($fh, EVFILT_WRITE, EV_DELETE);
161 }
162  
163 sub outbuffer
164 {
165 my $self = shift;
166 my $fh = shift;
167 return unless $fh && exists($self->{_fhs}{"$fh"});
168  
169 if (@_) {
170 $self->{_fhs}{"$fh"}{outbuffer} = $_[0] if @_;
171 #fd_set($self->{_writers}, $fh, 0) if !$_[0];
172 $self->EV_SET($fh, EVFILT_WRITE, EV_ADD, 0, 0, [$fh, EVFILT_WRITE]);
173 }
174  
175 return $self->{_fhs}{"$fh"}{outbuffer};
176 }
177  
178 sub inbuffer
179 {
180 my $self = shift;
181 my $fh = shift;
182 return unless $fh && exists($self->{_fhs}{"$fh"});
183  
184 if (@_) {
185 $self->{_fhs}{"$fh"}{inbuffer} = $_[0] if @_;
186 }
187  
188 return $self->{_fhs}{"$fh"}{inbuffer};
189 }
190  
191 sub set_timeout
192 {
193 my $self = shift;
194 my $fh = shift;
195 my $timeout = shift;
196 return unless $fh && exists($self->{_fhs}{"$fh"});
197  
198 if (defined $timeout) {
199 $self->_addTimer($fh, $timeout + time);
200 } else {
201 $self->_removeTimer($fh);
202 }
203 }
204  
205 sub handles
206 {
207 my $self = shift;
208  
209 return grep(!$self->{_fhs}{"$_"}{listen}, values %{$self->{_handles}});
210 }
211  
212 sub _addTimer {
213 my $self = shift;
214 my $fh = shift;
215 my $time = shift;
216  
217 # Set a key so that we can quickly tell if a given $fh has
218 # a timer set
219 $self->{_timerkeys}{"$fh"} = 1;
220  
221 # Store the timeout in an array, and resort it
222 @{$self->{_timers}} = sort { $a->[1] <=> $b->[1] } (@{$self->{_timers}}, [ $fh, $time ] );
223 }
224  
225 sub _removeTimer {
226 my $self = shift;
227 my $fh = shift;
228  
229 # Return quickly if no timer is set
230 return unless exists $self->{_timerkeys}{"$fh"};
231  
232 # Remove the timeout from the sorted array
233 @{$self->{_timers}} = grep { $_->[0] ne $fh } @{$self->{_timers}};
234  
235 # Get rid of the key
236 delete $self->{_timerkeys}{"$fh"};
237 }
238  
239 sub loop
240 {
241 my $self = shift;
242 my $heartbeat = shift;
243 $self->{_endloop} = 0;
244  
245 warn "heartbeat is not supported in IO::Multiplex::KQueue"
246 if( $heartbeat );
247 while (!$self->{_endloop} && keys %{$self->{_fhs}}) {
248 my $rv;
249 my $data;
250 my $rdready;
251 my $wrready;
252 my $timeout = undef;
253 my @results = undef;
254 if (@{$self->{_timers}}) {
255 $timeout = $self->{_timers}[0][1] - time;
256 }
257  
258 @results = $self->{_kq}->kevent($timeout);
259  
260 unless(@results) {
261 if ($! == EINTR || $! == EAGAIN) {
262 next;
263 } elsif( @{$self->{_timers}} ){
264 $self->_checkTimeouts();
265 next;
266 } else {
267 warn "kevent exists without event!?";
268 next;
269 }
270 }
271  
272 foreach my $kevent (@results) {
273 my($fh, $action) = @{$kevent->[KQ_UDATA]};
274 # Avoid creating a permanent empty hash ref for "$fh"
275 # by attempting to access its {object} element
276 # if it has already been closed.
277 next unless exists $self->{_fhs}{"$fh"};
278  
279 # Get the callback object.
280 my $obj = $self->{_fhs}{"$fh"}{object} ||
281 $self->{_object};
282  
283 # Is this descriptor ready for reading?
284 if( $action == EVFILT_READ ){
285 if ($self->{_fhs}{"$fh"}{listen}) {
286 # It's a server socket, so a new connection is
287 # waiting to be accepted
288 my $client = $fh->accept;
289 next unless ($client);
290 $self->add($client);
291 $obj->mux_connection($self, $client)
292 if $obj && $obj->can("mux_connection");
293 } else {
294 if ($self->is_udp($fh)) {
295 $rv = recv($fh, $data, BUFSIZ, 0);
296 if (defined $rv) {
297 # Remember where the last UDP packet came from
298 $self->{_fhs}{"$fh"}{udp_peer} = $rv;
299 }
300 } else {
301 $rv = &POSIX::read(fileno($fh), $data, BUFSIZ);
302 }
303  
304 if (defined($rv) && length($data)) {
305 # Append the data to the client's receive buffer,
306 # and call process_input to see if anything needs to
307 # be done.
308 $self->{_fhs}{"$fh"}{inbuffer} .= $data;
309 $obj->mux_input($self, $fh,
310 \$self->{_fhs}{"$fh"}{inbuffer})
311 if $obj && $obj->can("mux_input");
312 } else {
313 unless (defined $rv) {
314 next if
315 $! == EINTR ||
316 $! == EAGAIN ||
317 $! == EWOULDBLOCK;
318 warn "IO::Multiplex::KQueue read error: $!"
319 if $! != ECONNRESET;
320 }
321 # There's an error, or we received EOF. If
322 # there's pending data to be written, we leave
323 # the connection open so it can be sent. If
324 # the other end is closed for writing, the
325 # send will error and we close down there.
326 # Either way, we remove it from _readers as
327 # we're no longer interested in reading from
328 # it.
329 #fd_set($self->{_readers}, $fh, 0);
330 $self->EV_SET($fh, EVFILT_READ, EV_DELETE);
331 $obj->mux_eof($self, $fh,
332 \$self->{_fhs}{"$fh"}{inbuffer})
333 if $obj && $obj->can("mux_eof");
334  
335 if (exists $self->{_fhs}{"$fh"}) {
336 delete $self->{_fhs}{"$fh"}{inbuffer};
337 # The mux_eof handler could have responded
338 # with a shutdown for writing.
339 $self->close($fh)
340 unless exists $self->{_fhs}{"$fh"} &&
341 exists $self->{_fhs}{"$fh"}{outbuffer};
342 }
343 next;
344 }
345 }
346 } # end if readable
347 next unless exists $self->{_fhs}{"$fh"};
348  
349 if( $action == EVFILT_WRITE ){
350 unless ($self->{_fhs}{"$fh"}{outbuffer}) {
351 #fd_set($self->{_writers}, $fh, 0);
352 $self->EV_SET($fh, EVFILT_WRITE, EV_DELETE);
353 $obj->mux_outbuffer_empty($self, $fh)
354 if ($obj && $obj->can("mux_outbuffer_empty"));
355 next;
356 }
357 $rv = &POSIX::write(fileno($fh),
358 $self->{_fhs}{"$fh"}{outbuffer},
359 length($self->{_fhs}{"$fh"}{outbuffer}));
360 unless (defined($rv)) {
361 # We got an error writing to it. If it's
362 # EWOULDBLOCK (shouldn't happen if select told us
363 # we can write) or EAGAIN, or EINTR we don't worry
364 # about it. otherwise, close it down.
365 unless ($! == EWOULDBLOCK ||
366 $! == EINTR ||
367 $! == EAGAIN) {
368 if ($! == EPIPE) {
369 $obj->mux_epipe($self, $fh)
370 if $obj && $obj->can("mux_epipe");
371 } else {
372 warn "IO::Multiplex: write error: $!\n";
373 }
374 $self->close($fh);
375 }
376 next;
377 }
378 substr($self->{_fhs}{"$fh"}{outbuffer}, 0, $rv) = '';
379 unless ($self->{_fhs}{"$fh"}{outbuffer}) {
380 # Mark us as not writable if there's nothing more to
381 # write
382 #fd_set($self->{_writers}, $fh, 0);
383 $self->EV_SET($fh, EVFILT_WRITE, EV_DELETE);
384 $obj->mux_outbuffer_empty($self, $fh)
385 if ($obj && $obj->can("mux_outbuffer_empty"));
386  
387 if ($self->{_fhs}{"$fh"}{shutdown}) {
388 # If we've been marked for shutdown after write
389 # do it.
390 shutdown($fh, 1);
391 delete $self->{_fhs}{"$fh"}{outbuffer};
392 unless (exists $self->{_fhs}{"$fh"}{inbuffer}) {
393 # We'd previously been shutdown for reading
394 # also, so close out completely
395 $self->close($fh);
396 next;
397 }
398 }
399 }
400 } # End if writeable
401  
402 next unless exists $self->{_fhs}{"$fh"};
403  
404 } # End foreach $fh (...)
405  
406 $self->_checkTimeouts() if @{$self->{_timers}};
407  
408 } # End while(loop)
409 }
410  
411 sub _checkTimeouts {
412 my $self = shift;
413  
414 # Get the current time
415 my $time = time;
416  
417 # Copy all of the timers that should go off into
418 # a temporary array. This allows us to modify the
419 # real array as we process the timers, without
420 # interfering with the loop.
421  
422 my @timers = ();
423 foreach my $timer (@{$self->{_timers}}) {
424 # If the timer is in the future, we can stop
425 last if $timer->[1] > $time;
426 push @timers, $timer;
427 }
428  
429 foreach my $timer (@timers) {
430 my $fh = $timer->[0];
431 $self->_removeTimer($fh);
432  
433 next unless exists $self->{_fhs}{"$fh"};
434  
435 my $obj = $self->{_fhs}{"$fh"}{object} || $self->{_object};
436 $obj->mux_timeout($self, $fh) if $obj && $obj->can("mux_timeout");
437 }
438 }
439  
440 sub endloop
441 {
442 my $self = shift;
443 $self->{_endloop} = 1;
444 }
445  
446 sub udp_peer {
447 my $self = shift;
448 my $fh = shift;
449 return $self->{_fhs}{"$fh"}{udp_peer};
450 }
451  
452 sub is_udp {
453 my $self = shift;
454 my $fh = shift;
455 return $self->{_fhs}{"$fh"}{udp_true};
456 }
457  
458 sub write
459 {
460 my $self = shift;
461 my $fh = shift;
462 my $data = shift;
463 return unless $fh && exists($self->{_fhs}{"$fh"});
464  
465 if ($self->{_fhs}{"$fh"}{shutdown}) {
466 $! = EPIPE;
467 return undef;
468 }
469 if ($self->is_udp($fh)) {
470 if (my $udp_peer = $self->udp_peer($fh)) {
471 # Send the packet back to the last peer that said something
472 return send($fh, $data, 0, $udp_peer);
473 } else {
474 # No udp_peer yet?
475 # This better be a connect()ed UDP socket
476 # or else this will fail with ENOTCONN
477 return send($fh, $data, 0);
478 }
479 }
480 $self->{_fhs}{"$fh"}{outbuffer} .= $data;
481 #fd_set($self->{_writers}, $fh, 1);
482 $self->EV_SET($fh, EVFILT_WRITE, EV_ADD, 0, 0, [$fh, EVFILT_WRITE]);
483 return length($data);
484 }
485  
486 sub shutdown
487 {
488 my $self = shift;
489 my $fh = shift;
490 my $which = shift;
491 return unless $fh && exists($self->{_fhs}{"$fh"});
492  
493 if ($which == 0 || $which == 2) {
494 # Shutdown for reading. We can do this now.
495 shutdown($fh, 0);
496 # The mux_eof hook must be run from the main loop to consume
497 # the rest of the inbuffer if there is anything left.
498 # It will also remove $fh from _readers.
499 }
500  
501 if ($which == 1 || $which == 2) {
502 # Shutdown for writing. Only do this now if there is no pending
503 # data.
504 if ($self->{_fhs}{"$fh"}{outbuffer}) {
505 $self->{_fhs}{"$fh"}{shutdown} = 1;
506 } else {
507 shutdown($fh, 1);
508 delete $self->{_fhs}{"$fh"}{outbuffer};
509 }
510 }
511 # Delete the descriptor if it's totally gone.
512 unless (exists $self->{_fhs}{"$fh"}{inbuffer} ||
513 exists $self->{_fhs}{"$fh"}{outbuffer}) {
514 $self->close($fh);
515 }
516 }
517  
518 sub close
519 {
520 my $self = shift;
521 my $fh = shift;
522 return unless exists $self->{_fhs}{"$fh"};
523  
524 my $obj = $self->{_fhs}{"$fh"}{object} || $self->{_object};
525 warn "closeing with read buffer" if $self->{_fhs}{"$fh"}{inbuffer};
526 warn "closeing with write buffer" if $self->{_fhs}{"$fh"}{outbuffer};
527  
528 #fd_set($self->{_readers}, $fh, 0);
529 #fd_set($self->{_writers}, $fh, 0);
530 #in kqueue(2):
531 # Events which are attached to file descriptors are
532 # automatically deleted on the last close of the descriptor.
533  
534 delete $self->{_fhs}{"$fh"};
535 delete $self->{_handles}{"$fh"};
536 untie *$fh;
537 close $fh;
538 $obj->mux_close($self, $fh) if $obj && $obj->can("mux_close");
539 }
540  
541 # We set non-blocking mode on all descriptors. If we don't, then send
542 # might block if the data is larger than the kernel can accept all at once,
543 # even though select told us we can write. With non-blocking mode, we
544 # get a partial write in those circumstances, which is what we want.
545  
546 sub nonblock
547 {
548 my $fh = shift;
549 my $flags = fcntl($fh, F_GETFL, 0)
550 or die "fcntl F_GETFL: $!\n";
551 fcntl($fh, F_SETFL, $flags | O_NONBLOCK)
552 or die "fcntl F_SETFL $!\n";
553 }
554  
555 sub EV_SET
556 {
557 my $self = shift;
558 my $fh = shift;
559 $self->{_kq}->EV_SET($self->{_fhs}{"$fh"}{fileno}, @_);
560 }
561  
562 # We tie handles into this package to handle write buffering.
563  
564 package IO::Multiplex::KQueue::Handle;
565  
566 use strict;
567 use Tie::Handle;
568 use Carp;
569 use vars qw(@ISA);
570 @ISA = qw(Tie::Handle);
571  
572 sub FILENO
573 {
574 my $self = shift;
575 return ($self->{_mux}->{_fhs}->{"$self->{_fh}"}->{fileno});
576 }
577  
578  
579 sub TIEHANDLE
580 {
581 my $package = shift;
582 my $mux = shift;
583 my $fh = shift;
584  
585 my $self = bless { _mux => $mux,
586 _fh => $fh } => $package;
587 return $self;
588 }
589  
590 sub WRITE
591 {
592 my $self = shift;
593 my ($msg, $len, $offset) = @_;
594 $offset ||= 0;
595 return $self->{_mux}->write($self->{_fh}, substr($msg, $offset, $len));
596 }
597  
598 sub CLOSE
599 {
600 my $self = shift;
601 return $self->{_mux}->shutdown($self->{_fh}, 2);
602 }
603  
604 sub READ
605 {
606 carp "Do not read from a muxed file handle";
607 }
608  
609 sub READLINE
610 {
611 carp "Do not read from a muxed file handle";
612 }
613  
614 sub FETCH
615 {
616 return "Fnord";
617 }
618  
619 1;
620  
621 __END__