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