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