]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perl/lib/OpenSRF/Server.pm
LP#1729610: Allow queuing (for a while) during child backlog
[OpenSRF.git] / src / perl / lib / OpenSRF / Server.pm
1 # ----------------------------------------------------------------
2 # Copyright (C) 2010 Equinox Software, Inc.
3 # Bill Erickson <erickson@esilibrary.com>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 # ----------------------------------------------------------------
15 package OpenSRF::Server;
16 use strict;
17 use warnings;
18 use OpenSRF::Transport;
19 use OpenSRF::Application;
20 use OpenSRF::Utils::Config;
21 use OpenSRF::Transport::PeerHandle;
22 use OpenSRF::Utils::SettingsClient;
23 use OpenSRF::Utils::Logger qw($logger);
24 use OpenSRF::Transport::SlimJabber::Client;
25 use Encode;
26 use POSIX qw/:sys_wait_h :errno_h/;
27 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
28 use Time::HiRes qw/usleep/;
29 use IO::Select;
30 use Socket;
31 our $chatty = 1; # disable for production
32
33 use constant STATUS_PIPE_DATA_SIZE => 12;
34 use constant WRITE_PIPE_DATA_SIZE  => 12;
35
36 sub new {
37     my($class, $service, %args) = @_;
38     my $self = bless(\%args, $class);
39
40     $self->{service}        = $service; # service name
41     $self->{num_children}   = 0; # number of child processes
42     $self->{osrf_handle}    = undef; # xmpp handle
43     $self->{routers}        = []; # list of registered routers
44     $self->{active_list}    = []; # list of active children
45     $self->{idle_list}      = []; # list of idle children
46     $self->{sighup_pending} = [];
47     $self->{pid_map}        = {}; # map of child pid to child for cleaner access
48     $self->{sig_pipe}       = 0;  # true if last syswrite failed
49
50     $self->{stderr_log} = $self->{stderr_log_path} . "/${service}_stderr.log" 
51         if $self->{stderr_log_path};
52
53     $self->{min_spare_children} ||= 0;
54     $self->{max_backlog_queue} ||= 1000;
55
56     $self->{max_spare_children} = $self->{min_spare_children} + 1 if
57         $self->{max_spare_children} and
58         $self->{max_spare_children} <= $self->{min_spare_children};
59
60     return $self;
61 }
62
63 # ----------------------------------------------------------------
64 # Disconnects from routers and waits for child processes to exit.
65 # ----------------------------------------------------------------
66 sub cleanup {
67     my $self = shift;
68     my $no_exit = shift;
69     my $graceful = shift;
70
71     $logger->info("server: shutting down and cleaning up...");
72
73     # de-register routers
74     $self->unregister_routers;
75
76     if ($graceful) {
77         # graceful shutdown waits for all active 
78         # children to complete their in-process tasks.
79
80         while (@{$self->{active_list}}) {
81             $logger->info("server: graceful shutdown with ".
82                 @{$self->{active_list}}." active children...");
83
84             # block until a child is becomes available
85             $self->check_status(1);
86         }
87         $logger->info("server: all clear for graceful shutdown");
88     }
89
90     # don't get sidetracked by signals while we're cleaning up.
91     # it could result in unexpected behavior with list traversal
92     $SIG{CHLD} = 'IGNORE';
93
94     # terminate the child processes
95     $self->kill_child($_) for
96         (@{$self->{idle_list}}, @{$self->{active_list}});
97
98     $self->{osrf_handle}->disconnect;
99
100     # clean up our dead children
101     $self->reap_children(1);
102
103     exit(0) unless $no_exit;
104 }
105
106 # ----------------------------------------------------------------
107 # SIGHUP handler.  Kill all idle children.  Copy list of active
108 # children into sighup_pending list for later cleanup.
109 # ----------------------------------------------------------------
110 sub handle_sighup {
111     my $self = shift;
112     $logger->info("server: caught SIGHUP; reloading children");
113
114     # reload the opensrf config
115     # note: calling ::Config->load() results in ever-growing
116     # package names, which eventually causes an exception
117     OpenSRF::Utils::Config->current->_load(
118         force => 1,
119         config_file => OpenSRF::Utils::Config->current->FILE
120     );
121
122     # force-reload the logger config
123     OpenSRF::Utils::Logger::set_config(1);
124
125     # copy active list into pending list for later cleanup
126     $self->{sighup_pending} = [ @{$self->{active_list}} ];
127
128     # idle_list will be modified as children are reaped.
129     my @idle = @{$self->{idle_list}};
130
131     # idle children are the reaper's plaything
132     $self->kill_child($_) for @idle;
133 }
134
135 # ----------------------------------------------------------------
136 # Waits on the jabber socket for inbound data from the router.
137 # Each new message is passed off to a child process for handling.
138 # At regular intervals, wake up for min/max spare child maintenance
139 # ----------------------------------------------------------------
140 sub run {
141     my $self = shift;
142
143     $logger->set_service($self->{service});
144
145     $SIG{$_} = sub { $self->cleanup; } for (qw/INT QUIT/);
146     $SIG{TERM} = sub { $self->cleanup(0, 1); };
147     $SIG{CHLD} = sub { $self->reap_children(); };
148     $SIG{HUP} = sub { $self->handle_sighup(); };
149     $SIG{USR1} = sub { $self->unregister_routers; };
150     $SIG{USR2} = sub { $self->register_routers; };
151
152     $self->spawn_children;
153     $self->build_osrf_handle;
154     $self->register_routers;
155     my $wait_time = 1;
156
157     my @max_children_msg_queue;
158
159     # main server loop
160     while(1) {
161         my $from_network = 0;
162
163         $self->check_status;
164         $self->{child_died} = 0;
165
166         my $msg = shift(@max_children_msg_queue);
167
168         # no pending message, so wait for the next one forever
169         $from_network = $wait_time = -1 if (!$msg);
170         $msg ||= $self->{osrf_handle}->process($wait_time);
171
172         # we woke up for any reason, reset the wait time to allow
173         # for idle maintenance as necessary
174         $wait_time = 1;
175
176         if($msg) {
177
178             if ($msg->type and $msg->type eq 'error') {
179                 $logger->info("server: Listener received an XMPP error ".
180                     "message.  Likely a bounced message. sender=".$msg->from);
181
182             } elsif(my $child = pop(@{$self->{idle_list}})) {
183
184                 # we have an idle child to handle the request
185                 $chatty and $logger->internal("server: passing request to idle child $child");
186                 push(@{$self->{active_list}}, $child);
187                 $self->write_child($child, $msg);
188
189             } elsif($self->{num_children} < $self->{max_children}) {
190
191                 # spawning a child to handle the request
192                 $chatty and $logger->internal("server: spawning child to handle request");
193                 $self->write_child($self->spawn_child(1), $msg);
194
195             } else {
196                 $logger->warn("server: no children available, waiting... consider increasing " .
197                     "max_children for this application higher than $self->{max_children} ".
198                     "in the OpenSRF configuration if this message occurs frequently");
199
200                 if ($from_network) {
201                     push @max_children_msg_queue, $msg;
202                 } else {
203                     unshift @max_children_msg_queue, $msg;
204                 }
205
206                 if (@max_children_msg_queue < $self->{max_backlog_queue}) {
207                     # We still have room on the queue. Set the wait time to
208                     # 1s, waiting for a drone to be freed up and reprocess
209                     # this (and any other) queued messages.
210                     $wait_time = 1;
211                     if (!$from_network) {
212                         # if we got here, we had retrieved a message from the queue
213                         # but couldn't process it... but also hadn't fetched any
214                         # additional messages from the network. Doing so now,
215                         # as otherwise only one message will ever get queued
216                         $msg = $self->{osrf_handle}->process($wait_time);
217                         if ($msg) {
218                             $chatty and $logger->debug("server: queuing new message after a re-queue");
219                             push @max_children_msg_queue, $msg;
220                         }
221                     }
222                 } else {
223                     # We'll just have to wait
224                     $self->check_status(1); # block until child is available
225                 }
226             }
227
228         } else {
229
230             # don't perform idle maint immediately when woken by SIGCHLD
231             unless($self->{child_died}) {
232
233                 # when we hit equilibrium, there's no need for regular
234                 # maintenance, so set wait_time to 'forever'
235                 $wait_time = -1 if 
236                     !$self->perform_idle_maintenance and # no maintenance performed this time
237                     @{$self->{active_list}} == 0; # no active children 
238             }
239         }
240     }
241 }
242
243 # ----------------------------------------------------------------
244 # Launch a new spare child or kill an extra spare child.  To
245 # prevent large-scale spawning or die-offs, spawn or kill only
246 # 1 process per idle maintenance loop.
247 # Returns true if any idle maintenance occurred, 0 otherwise
248 # ----------------------------------------------------------------
249 sub perform_idle_maintenance {
250     my $self = shift;
251
252     $chatty and $logger->internal(
253         sprintf(
254             "server: %d idle, %d active, %d min_spare, %d max_spare in idle maintenance",
255             scalar(@{$self->{idle_list}}), 
256             scalar(@{$self->{active_list}}),
257             $self->{min_spare_children},
258             $self->{max_spare_children}
259         )
260     );
261
262     # spawn 1 spare child per maintenance loop if necessary
263     if( $self->{min_spare_children} and
264         $self->{num_children} < $self->{max_children} and
265         scalar(@{$self->{idle_list}}) < $self->{min_spare_children} ) {
266
267         $chatty and $logger->internal("server: spawning spare child");
268         $self->spawn_child;
269         return 1;
270
271     # kill 1 excess spare child per maintenance loop if necessary
272     } elsif($self->{max_spare_children} and
273             $self->{num_children} > $self->{min_children} and
274             scalar(@{$self->{idle_list}}) > $self->{max_spare_children} ) {
275
276         $chatty and $logger->internal("server: killing spare child");
277         $self->kill_child;
278         return 1;
279     }
280
281     return 0;
282 }
283
284 sub kill_child {
285     my $self = shift;
286     my $child = shift || pop(@{$self->{idle_list}}) or return;
287     $chatty and $logger->internal("server: killing child $child");
288     kill('TERM', $child->{pid});
289 }
290
291 # ----------------------------------------------------------------
292 # Jabber connection inbound message arrive on.
293 # ----------------------------------------------------------------
294 sub build_osrf_handle {
295     my $self = shift;
296
297     my $conf = OpenSRF::Utils::Config->current;
298     my $username = $conf->bootstrap->username;
299     my $password = $conf->bootstrap->passwd;
300     my $domain = $conf->bootstrap->domain;
301     my $port = $conf->bootstrap->port;
302     my $resource = $self->{service} . '_listener_' . $conf->env->hostname;
303
304     $logger->debug("server: inbound connecting as $username\@$domain/$resource on port $port");
305
306     $self->{osrf_handle} =
307         OpenSRF::Transport::SlimJabber::Client->new(
308             username => $username,
309             resource => $resource,
310             password => $password,
311             host => $domain,
312             port => $port,
313         );
314
315     $self->{osrf_handle}->initialize;
316 }
317
318
319 # ----------------------------------------------------------------
320 # Sends request data to a child process
321 # ----------------------------------------------------------------
322 sub write_child {
323     my($self, $child, $msg) = @_;
324     my $xml = encode_utf8(decode_utf8($msg->to_xml));
325
326     # tell the child how much data to expect, minus the header
327     my $write_size;
328     {use bytes; $write_size = length($xml)}
329     $write_size = sprintf("%*s", WRITE_PIPE_DATA_SIZE, $write_size);
330
331     for (0..2) {
332
333         $self->{sig_pipe} = 0;
334         local $SIG{'PIPE'} = sub { $self->{sig_pipe} = 1; };
335
336         # In rare cases a child can die between creation and first
337         # write, typically a result of a jabber connect error.  Before
338         # sending data to each child, confirm it's still alive.  If it's
339         # not, log the error and drop the message to prevent the parent
340         # process from dying.
341         # When a child dies, all of its attributes are deleted,
342         # so the lack of a pid means the child is dead.
343         if (!$child->{pid}) {
344             $logger->error("server: child is dead in write_child(). ".
345                 "unable to send message: $xml");
346             return; # avoid syswrite crash
347         }
348
349         # send message to child data pipe
350         syswrite($child->{pipe_to_child}, $write_size . $xml);
351
352         last unless $self->{sig_pipe};
353         $logger->error("server: got SIGPIPE writing to $child, retrying...");
354         usleep(50000); # 50 msec
355     }
356
357     $logger->error("server: unable to send request message to child $child") if $self->{sig_pipe};
358 }
359
360 # ----------------------------------------------------------------
361 # Checks to see if any child process has reported its availability
362 # In blocking mode, blocks until a child has reported.
363 # ----------------------------------------------------------------
364 sub check_status {
365     my($self, $block) = @_;
366
367     return unless @{$self->{active_list}};
368
369     my @pids;
370
371     while (1) {
372
373         # if can_read or sysread is interrupted while bloking, go back and 
374         # wait again until we have at least 1 free child
375
376         # refresh the read_set handles in case we lost a child in the previous iteration
377         my $read_set = IO::Select->new;
378         $read_set->add($_->{pipe_to_child}) for @{$self->{active_list}};
379
380         if(my @handles = $read_set->can_read(($block) ? undef : 0)) {
381             my $pid = '';
382             for my $pipe (@handles) {
383                 sysread($pipe, $pid, STATUS_PIPE_DATA_SIZE) or next;
384                 push(@pids, int($pid));
385             }
386         }
387
388         last unless $block and !@pids;
389     }
390
391     return unless @pids;
392
393     $chatty and $logger->internal("server: ".scalar(@pids)." children reporting for duty: (@pids)");
394
395     my $child;
396     my @new_actives;
397
398     # move the children from the active list to the idle list
399     for my $proc (@{$self->{active_list}}) {
400         if(grep { $_ == $proc->{pid} } @pids) {
401             push(@{$self->{idle_list}}, $proc);
402         } else {
403             push(@new_actives, $proc);
404         }
405     }
406
407     $self->{active_list} = [@new_actives];
408
409     $chatty and $logger->internal(sprintf(
410         "server: %d idle and %d active children after status update",
411             scalar(@{$self->{idle_list}}), scalar(@{$self->{active_list}})));
412
413     # some children just went from active to idle. let's see 
414     # if any of them need to be killed from a previous sighup.
415
416     for my $child (@{$self->{sighup_pending}}) {
417         if (grep {$_ == $child->{pid}} @pids) {
418
419             $chatty and $logger->internal(
420                 "server: killing previously-active ".
421                 "child after receiving SIGHUP: $child");
422
423             # remove the pending child
424             $self->{sighup_pending} = [
425                 grep {$_->{pid} != $child->{pid}} 
426                     @{$self->{sighup_pending}}
427             ];
428
429             # kill the pending child
430             $self->kill_child($child)
431         }
432     }
433 }
434
435 # ----------------------------------------------------------------
436 # Cleans up any child processes that have exited.
437 # In shutdown mode, block until all children have washed ashore
438 # ----------------------------------------------------------------
439 sub reap_children {
440     my($self, $shutdown) = @_;
441     $self->{child_died} = 1;
442
443     while(1) {
444
445         my $pid = waitpid(-1, ($shutdown) ? 0 : WNOHANG);
446         last if $pid <= 0;
447
448         $chatty and $logger->internal("server: reaping child $pid");
449
450         my $child = $self->{pid_map}->{$pid};
451
452         close($child->{pipe_to_parent});
453         close($child->{pipe_to_child});
454
455         $self->{active_list} = [ grep { $_->{pid} != $pid } @{$self->{active_list}} ];
456         $self->{idle_list} = [ grep { $_->{pid} != $pid } @{$self->{idle_list}} ];
457
458         $self->{num_children}--;
459         delete $self->{pid_map}->{$pid};
460         delete $child->{$_} for keys %$child; # destroy with a vengeance
461     }
462
463     $self->spawn_children unless $shutdown;
464
465     $chatty and $logger->internal(sprintf(
466         "server: %d idle and %d active children after reap_children",
467             scalar(@{$self->{idle_list}}), scalar(@{$self->{active_list}})));
468 }
469
470 # ----------------------------------------------------------------
471 # Spawn up to max_children processes
472 # ----------------------------------------------------------------
473 sub spawn_children {
474     my $self = shift;
475     $self->spawn_child while $self->{num_children} < $self->{min_children};
476 }
477
478 # ----------------------------------------------------------------
479 # Spawns a new child.  If $active is set, the child goes directly
480 # into the active_list.
481 # ----------------------------------------------------------------
482 sub spawn_child {
483     my($self, $active) = @_;
484
485     my $child = OpenSRF::Server::Child->new($self);
486
487     # socket for sending message data to the child
488     if(!socketpair(
489         $child->{pipe_to_child},
490         $child->{pipe_to_parent},
491         AF_UNIX, SOCK_STREAM, PF_UNSPEC)) {
492             $logger->error("server: error creating data socketpair: $!");
493             return undef;
494     }
495
496     $child->{pipe_to_child}->autoflush(1);
497     $child->{pipe_to_parent}->autoflush(1);
498
499     $child->{pid} = fork();
500
501     if($child->{pid}) { # parent process
502         $self->{num_children}++;
503         $self->{pid_map}->{$child->{pid}} = $child;
504
505         if($active) {
506             push(@{$self->{active_list}}, $child);
507         } else {
508             push(@{$self->{idle_list}}, $child);
509         }
510
511         $chatty and $logger->internal("server: server spawned child $child with ".$self->{num_children}." total children");
512
513         return $child;
514
515     } else { # child process
516
517         # recover default handling for any signal whose handler 
518         # may have been adopted from the parent process.
519         $SIG{$_} = 'DEFAULT' for qw/TERM INT QUIT HUP CHLD USR1 USR2/;
520
521         if($self->{stderr_log}) {
522
523             $chatty and $logger->internal("server: redirecting STDERR to " . $self->{stderr_log});
524
525             close STDERR;
526             unless( open(STDERR, '>>' . $self->{stderr_log}) ) {
527                 $logger->error("server: unable to open STDERR log file: " . $self->{stderr_log} . " : $@");
528                 open STDERR, '>/dev/null'; # send it back to /dev/null
529             }
530         }
531
532         $child->{pid} = $$;
533         eval {
534             $child->init;
535             $child->run;
536             OpenSRF::Transport::PeerHandle->retrieve->disconnect;
537         };
538         $logger->error("server: child process died: $@") if $@;
539         exit(0);
540     }
541 }
542
543 # ----------------------------------------------------------------
544 # Sends the register command to the configured routers
545 # ----------------------------------------------------------------
546 sub register_routers {
547     my $self = shift;
548
549     my $conf = OpenSRF::Utils::Config->current;
550     my $routers = $conf->bootstrap->routers;
551     my $router_name = $conf->bootstrap->router_name;
552     my @targets;
553
554     for my $router (@$routers) {
555         if(ref $router) {
556
557             if( !$router->{services} ||
558                 !$router->{services}->{service} ||
559                 (
560                     ref($router->{services}->{service}) eq 'ARRAY' and
561                     grep { $_ eq $self->{service} } @{$router->{services}->{service}}
562                 )  || $router->{services}->{service} eq $self->{service}) {
563
564                 my $name = $router->{name};
565                 my $domain = $router->{domain};
566                 push(@targets, "$name\@$domain/router");
567             }
568
569         } else {
570             push(@targets, "$router_name\@$router/router");
571         }
572     }
573
574     foreach (@targets) {
575         $logger->info("server: registering with router $_");
576         $self->{osrf_handle}->send(
577             to => $_,
578             body => 'registering',
579             router_command => 'register',
580             router_class => $self->{service}
581         );
582     }
583
584     $self->{routers} = \@targets;
585 }
586
587 # ----------------------------------------------------------------
588 # Sends the unregister command to any routers we have registered
589 # with.
590 # ----------------------------------------------------------------
591 sub unregister_routers {
592     my $self = shift;
593     return unless $self->{osrf_handle}->tcp_connected;
594
595     for my $router (@{$self->{routers}}) {
596         $logger->info("server: disconnecting from router $router");
597         $self->{osrf_handle}->send(
598             to => $router,
599             body => "unregistering",
600             router_command => "unregister",
601             router_class => $self->{service}
602         );
603     }
604 }
605
606
607 package OpenSRF::Server::Child;
608 use strict;
609 use warnings;
610 use OpenSRF::Transport;
611 use OpenSRF::Application;
612 use OpenSRF::Transport::PeerHandle;
613 use OpenSRF::Transport::SlimJabber::XMPPMessage;
614 use OpenSRF::Utils::Logger qw($logger);
615 use OpenSRF::DomainObject::oilsResponse qw/:status/;
616 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
617 use Time::HiRes qw(time usleep);
618 use POSIX qw/:sys_wait_h :errno_h/;
619
620 use overload '""' => sub { return '[' . shift()->{pid} . ']'; };
621
622 sub new {
623     my($class, $parent) = @_;
624     my $self = bless({}, $class);
625     $self->{pid} = 0; # my process ID
626     $self->{parent} = $parent; # Controller parent process
627     $self->{num_requests} = 0; # total serviced requests
628     $self->{sig_pipe} = 0;  # true if last syswrite failed
629     return $self;
630 }
631
632 sub set_nonblock {
633     my($self, $fh) = @_;
634     my  $flags = fcntl($fh, F_GETFL, 0);
635     fcntl($fh, F_SETFL, $flags | O_NONBLOCK);
636 }
637
638 sub set_block {
639     my($self, $fh) = @_;
640     my  $flags = fcntl($fh, F_GETFL, 0);
641     $flags &= ~O_NONBLOCK;
642     fcntl($fh, F_SETFL, $flags);
643 }
644
645 # ----------------------------------------------------------------
646 # Connects to Jabber and runs the application child_init
647 # ----------------------------------------------------------------
648 sub init {
649     my $self = shift;
650     my $service = $self->{parent}->{service};
651     $0 = "OpenSRF Drone [$service]";
652     OpenSRF::Transport::PeerHandle->construct($service);
653     OpenSRF::Application->application_implementation->child_init
654         if (OpenSRF::Application->application_implementation->can('child_init'));
655 }
656
657 # ----------------------------------------------------------------
658 # Waits for messages from the parent process, handles the message,
659 # then goes into the keepalive loop if this is a stateful session.
660 # When max_requests is hit, the process exits.
661 # ----------------------------------------------------------------
662 sub run {
663     my $self = shift;
664     my $network = OpenSRF::Transport::PeerHandle->retrieve;
665
666     # main child run loop.  Ends when this child hits max requests.
667     while(1) {
668
669         my $data = $self->wait_for_request or next;
670
671         # Update process name to show activity
672         my $orig_name = $0;
673         $0 = "$0*";
674
675         # Discard extraneous data from the jabber socket
676         if(!$network->flush_socket()) {
677             $logger->error("server: network disconnected!  child dropping request and exiting: $data");
678             exit;
679         }
680
681         my $session = OpenSRF::Transport->handler(
682             $self->{parent}->{service},
683             OpenSRF::Transport::SlimJabber::XMPPMessage->new(xml => $data)
684         );
685
686         my $recycle = $self->keepalive_loop($session);
687
688         last if ++$self->{num_requests} == $self->{parent}->{max_requests};
689
690         if ($recycle) {
691             $chatty && $logger->internal(
692                 "server: child exiting early on force_recycle");
693             last;
694         }
695
696         # Tell the parent process we are available to process requests
697         $self->send_status;
698
699         # Repair process name
700         $0 = $orig_name;
701     }
702
703     $chatty and $logger->internal("server: child process shutting down after reaching max_requests");
704
705     OpenSRF::Application->application_implementation->child_exit
706         if (OpenSRF::Application->application_implementation->can('child_exit'));
707 }
708
709 # ----------------------------------------------------------------
710 # waits for a request data on the parent pipe and returns it.
711 # ----------------------------------------------------------------
712 sub wait_for_request {
713     my $self = shift;
714
715     my $data = ''; # final request data
716     my $buf_size = 4096; # default linux pipe_buf (atomic window, not total size)
717     my $read_pipe = $self->{pipe_to_parent};
718     my $bytes_needed; # size of the data we are about to receive
719     my $bytes_recvd; # number of bytes read so far
720     my $first_read = 1; # true for first loop iteration
721     my $read_error;
722
723     while (1) {
724
725         # wait for some data to start arriving
726         my $read_set = IO::Select->new;
727         $read_set->add($read_pipe);
728     
729         while (1) {
730             # if can_read is interrupted while blocking, 
731             # go back and wait again until it succeeds.
732             last if $read_set->can_read;
733         }
734
735         # parent started writing, let's start reading
736         $self->set_nonblock($read_pipe);
737
738         while (1) {
739             # read all of the available data
740
741             my $buf = '';
742             my $nbytes = sysread($self->{pipe_to_parent}, $buf, $buf_size);
743
744             unless(defined $nbytes) {
745                 if ($! != EAGAIN) {
746                     $logger->error("server: error reading data from parent: $!.  ".
747                         "bytes_needed=$bytes_needed; bytes_recvd=$bytes_recvd; data=$data");
748                     $read_error = 1;
749                 }
750                 last;
751             }
752
753             last if $nbytes <= 0; # no more data available for reading
754
755             $bytes_recvd += $nbytes;
756             $data .= $buf;
757         }
758
759         $self->set_block($self->{pipe_to_parent});
760         return undef if $read_error;
761
762         # extract the data size and remove the header from the final data
763         if ($first_read) {
764             my $wps_size = OpenSRF::Server::WRITE_PIPE_DATA_SIZE;
765             $bytes_needed = int(substr($data, 0, $wps_size)) + $wps_size;
766             $data = substr($data, $wps_size);
767             $first_read = 0;
768         }
769
770
771         if ($bytes_recvd == $bytes_needed) {
772             # we've read all the data. Nothing left to do
773             last;
774         }
775
776         $logger->info("server: child process read all available pipe data.  ".
777             "waiting for more data from parent.  bytes_needed=$bytes_needed; bytes_recvd=$bytes_recvd");
778     }
779
780     return $data;
781 }
782
783
784 # ----------------------------------------------------------------
785 # If this is a stateful opensrf session, wait up to $keepalive
786 # seconds for subsequent requests from the client
787 # ----------------------------------------------------------------
788 sub keepalive_loop {
789     my($self, $session) = @_;
790     my $keepalive = $self->{parent}->{keepalive};
791
792     while($session->state and $session->state == $session->CONNECTED) {
793
794         unless( $session->queue_wait($keepalive) ) {
795
796             # client failed to disconnect before timeout
797             $logger->info("server: no request was received in $keepalive seconds, exiting stateful session");
798
799             my $res = OpenSRF::DomainObject::oilsConnectStatus->new(
800                 status => "Disconnected on timeout",
801                 statusCode => STATUS_TIMEOUT
802             );
803
804             $session->status($res);
805             $session->state($session->DISCONNECTED);
806             last;
807         }
808     }
809
810     $chatty and $logger->internal("server: child done with request(s)");
811
812     # Capture the recycle option value before it's clobbered.
813     # The option may be set at any point along the life of the 
814     # session.  Once set, it remains set unless 
815     # $session->force_recycle(0) is explicitly called.
816     my $recycle = $session->force_recycle;
817
818     $session->kill_me;
819     return $recycle;
820 }
821
822 # ----------------------------------------------------------------
823 # Report our availability to our parent process
824 # ----------------------------------------------------------------
825 sub send_status {
826     my $self = shift;
827
828     for (0..2) {
829
830         $self->{sig_pipe} = 0;
831         local $SIG{'PIPE'} = sub { $self->{sig_pipe} = 1; };
832
833         syswrite(
834             $self->{pipe_to_parent},
835             sprintf("%*s", OpenSRF::Server::STATUS_PIPE_DATA_SIZE, $self->{pid})
836         );
837
838         last unless $self->{sig_pipe};
839         $logger->error("server: $self got SIGPIPE writing status to parent, retrying...");
840         usleep(50000); # 50 msec
841     }
842
843     $logger->error("server: $self unable to send status to parent") if $self->{sig_pipe};
844 }
845
846
847 1;