1 # ----------------------------------------------------------------
2 # Copyright (C) 2010 Equinox Software, Inc.
3 # Bill Erickson <erickson@esilibrary.com>
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.
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;
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;
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/;
31 our $chatty = 1; # disable for production
33 use constant STATUS_PIPE_DATA_SIZE => 12;
34 use constant WRITE_PIPE_DATA_SIZE => 12;
37 my($class, $service, %args) = @_;
38 my $self = bless(\%args, $class);
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
50 $self->{stderr_log} = $self->{stderr_log_path} . "/${service}_stderr.log"
51 if $self->{stderr_log_path};
53 $self->{min_spare_children} ||= 0;
54 $self->{max_backlog_queue} ||= 1000;
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};
63 # ----------------------------------------------------------------
64 # Disconnects from routers and waits for child processes to exit.
65 # ----------------------------------------------------------------
71 $logger->info("server: shutting down and cleaning up...");
74 $self->unregister_routers;
77 # graceful shutdown waits for all active
78 # children to complete their in-process tasks.
80 while (@{$self->{active_list}}) {
81 $logger->info("server: graceful shutdown with ".
82 @{$self->{active_list}}." active children...");
84 # block until a child is becomes available
85 $self->check_status(1);
87 $logger->info("server: all clear for graceful shutdown");
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';
94 # terminate the child processes
95 $self->kill_child($_) for
96 (@{$self->{idle_list}}, @{$self->{active_list}});
98 $self->{osrf_handle}->disconnect;
100 # clean up our dead children
101 $self->reap_children(1);
103 exit(0) unless $no_exit;
106 # ----------------------------------------------------------------
107 # SIGHUP handler. Kill all idle children. Copy list of active
108 # children into sighup_pending list for later cleanup.
109 # ----------------------------------------------------------------
112 $logger->info("server: caught SIGHUP; reloading children");
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(
119 config_file => OpenSRF::Utils::Config->current->FILE
122 # force-reload the logger config
123 OpenSRF::Utils::Logger::set_config(1);
125 # copy active list into pending list for later cleanup
126 $self->{sighup_pending} = [ @{$self->{active_list}} ];
128 # idle_list will be modified as children are reaped.
129 my @idle = @{$self->{idle_list}};
131 # idle children are the reaper's plaything
132 $self->kill_child($_) for @idle;
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 # ----------------------------------------------------------------
143 $logger->set_service($self->{service});
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; };
152 $self->spawn_children;
153 $self->build_osrf_handle;
154 $self->register_routers;
157 my @max_children_msg_queue;
161 my $from_network = 0;
164 $self->{child_died} = 0;
166 my $msg = shift(@max_children_msg_queue);
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);
172 # we woke up for any reason, reset the wait time to allow
173 # for idle maintenance as necessary
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);
182 } elsif(my $child = pop(@{$self->{idle_list}})) {
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);
189 } elsif($self->{num_children} < $self->{max_children}) {
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);
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");
201 push @max_children_msg_queue, $msg;
203 unshift @max_children_msg_queue, $msg;
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.
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);
218 $chatty and $logger->debug("server: queuing new message after a re-queue");
219 push @max_children_msg_queue, $msg;
223 # We'll just have to wait
224 $self->check_status(1); # block until child is available
230 # don't perform idle maint immediately when woken by SIGCHLD
231 unless($self->{child_died}) {
233 # when we hit equilibrium, there's no need for regular
234 # maintenance, so set wait_time to 'forever'
236 !$self->perform_idle_maintenance and # no maintenance performed this time
237 @{$self->{active_list}} == 0; # no active children
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 {
252 $chatty and $logger->internal(
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}
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} ) {
267 $chatty and $logger->internal("server: spawning spare child");
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} ) {
276 $chatty and $logger->internal("server: killing spare child");
286 my $child = shift || pop(@{$self->{idle_list}}) or return;
287 $chatty and $logger->internal("server: killing child $child");
288 kill('TERM', $child->{pid});
291 # ----------------------------------------------------------------
292 # Jabber connection inbound message arrive on.
293 # ----------------------------------------------------------------
294 sub build_osrf_handle {
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;
304 $logger->debug("server: inbound connecting as $username\@$domain/$resource on port $port");
306 $self->{osrf_handle} =
307 OpenSRF::Transport::SlimJabber::Client->new(
308 username => $username,
309 resource => $resource,
310 password => $password,
315 $self->{osrf_handle}->initialize;
319 # ----------------------------------------------------------------
320 # Sends request data to a child process
321 # ----------------------------------------------------------------
323 my($self, $child, $msg) = @_;
324 my $xml = encode_utf8(decode_utf8($msg->to_xml));
326 # tell the child how much data to expect, minus the header
328 {use bytes; $write_size = length($xml)}
329 $write_size = sprintf("%*s", WRITE_PIPE_DATA_SIZE, $write_size);
333 $self->{sig_pipe} = 0;
334 local $SIG{'PIPE'} = sub { $self->{sig_pipe} = 1; };
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
349 # send message to child data pipe
350 syswrite($child->{pipe_to_child}, $write_size . $xml);
352 last unless $self->{sig_pipe};
353 $logger->error("server: got SIGPIPE writing to $child, retrying...");
354 usleep(50000); # 50 msec
357 $logger->error("server: unable to send request message to child $child") if $self->{sig_pipe};
360 # ----------------------------------------------------------------
361 # Checks to see if any child process has reported its availability
362 # In blocking mode, blocks until a child has reported.
363 # ----------------------------------------------------------------
365 my($self, $block) = @_;
367 return unless @{$self->{active_list}};
373 # if can_read or sysread is interrupted while bloking, go back and
374 # wait again until we have at least 1 free child
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}};
380 if(my @handles = $read_set->can_read(($block) ? undef : 0)) {
382 for my $pipe (@handles) {
383 sysread($pipe, $pid, STATUS_PIPE_DATA_SIZE) or next;
384 push(@pids, int($pid));
388 last unless $block and !@pids;
393 $chatty and $logger->internal("server: ".scalar(@pids)." children reporting for duty: (@pids)");
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);
403 push(@new_actives, $proc);
407 $self->{active_list} = [@new_actives];
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}})));
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.
416 for my $child (@{$self->{sighup_pending}}) {
417 if (grep {$_ == $child->{pid}} @pids) {
419 $chatty and $logger->internal(
420 "server: killing previously-active ".
421 "child after receiving SIGHUP: $child");
423 # remove the pending child
424 $self->{sighup_pending} = [
425 grep {$_->{pid} != $child->{pid}}
426 @{$self->{sighup_pending}}
429 # kill the pending child
430 $self->kill_child($child)
435 # ----------------------------------------------------------------
436 # Cleans up any child processes that have exited.
437 # In shutdown mode, block until all children have washed ashore
438 # ----------------------------------------------------------------
440 my($self, $shutdown) = @_;
441 $self->{child_died} = 1;
445 my $pid = waitpid(-1, ($shutdown) ? 0 : WNOHANG);
448 $chatty and $logger->internal("server: reaping child $pid");
450 my $child = $self->{pid_map}->{$pid};
452 close($child->{pipe_to_parent});
453 close($child->{pipe_to_child});
455 $self->{active_list} = [ grep { $_->{pid} != $pid } @{$self->{active_list}} ];
456 $self->{idle_list} = [ grep { $_->{pid} != $pid } @{$self->{idle_list}} ];
458 $self->{num_children}--;
459 delete $self->{pid_map}->{$pid};
460 delete $child->{$_} for keys %$child; # destroy with a vengeance
463 $self->spawn_children unless $shutdown;
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}})));
470 # ----------------------------------------------------------------
471 # Spawn up to max_children processes
472 # ----------------------------------------------------------------
475 $self->spawn_child while $self->{num_children} < $self->{min_children};
478 # ----------------------------------------------------------------
479 # Spawns a new child. If $active is set, the child goes directly
480 # into the active_list.
481 # ----------------------------------------------------------------
483 my($self, $active) = @_;
485 my $child = OpenSRF::Server::Child->new($self);
487 # socket for sending message data to the child
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: $!");
496 $child->{pipe_to_child}->autoflush(1);
497 $child->{pipe_to_parent}->autoflush(1);
499 $child->{pid} = fork();
501 if($child->{pid}) { # parent process
502 $self->{num_children}++;
503 $self->{pid_map}->{$child->{pid}} = $child;
506 push(@{$self->{active_list}}, $child);
508 push(@{$self->{idle_list}}, $child);
511 $chatty and $logger->internal("server: server spawned child $child with ".$self->{num_children}." total children");
515 } else { # child process
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/;
521 if($self->{stderr_log}) {
523 $chatty and $logger->internal("server: redirecting STDERR to " . $self->{stderr_log});
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
536 OpenSRF::Transport::PeerHandle->retrieve->disconnect;
538 $logger->error("server: child process died: $@") if $@;
543 # ----------------------------------------------------------------
544 # Sends the register command to the configured routers
545 # ----------------------------------------------------------------
546 sub register_routers {
549 my $conf = OpenSRF::Utils::Config->current;
550 my $routers = $conf->bootstrap->routers;
551 my $router_name = $conf->bootstrap->router_name;
554 for my $router (@$routers) {
557 if( !$router->{services} ||
558 !$router->{services}->{service} ||
560 ref($router->{services}->{service}) eq 'ARRAY' and
561 grep { $_ eq $self->{service} } @{$router->{services}->{service}}
562 ) || $router->{services}->{service} eq $self->{service}) {
564 my $name = $router->{name};
565 my $domain = $router->{domain};
566 push(@targets, "$name\@$domain/router");
570 push(@targets, "$router_name\@$router/router");
575 $logger->info("server: registering with router $_");
576 $self->{osrf_handle}->send(
578 body => 'registering',
579 router_command => 'register',
580 router_class => $self->{service}
584 $self->{routers} = \@targets;
587 # ----------------------------------------------------------------
588 # Sends the unregister command to any routers we have registered
590 # ----------------------------------------------------------------
591 sub unregister_routers {
593 return unless $self->{osrf_handle}->tcp_connected;
595 for my $router (@{$self->{routers}}) {
596 $logger->info("server: disconnecting from router $router");
597 $self->{osrf_handle}->send(
599 body => "unregistering",
600 router_command => "unregister",
601 router_class => $self->{service}
607 package OpenSRF::Server::Child;
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/;
620 use overload '""' => sub { return '[' . shift()->{pid} . ']'; };
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
634 my $flags = fcntl($fh, F_GETFL, 0);
635 fcntl($fh, F_SETFL, $flags | O_NONBLOCK);
640 my $flags = fcntl($fh, F_GETFL, 0);
641 $flags &= ~O_NONBLOCK;
642 fcntl($fh, F_SETFL, $flags);
645 # ----------------------------------------------------------------
646 # Connects to Jabber and runs the application child_init
647 # ----------------------------------------------------------------
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'));
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 # ----------------------------------------------------------------
664 my $network = OpenSRF::Transport::PeerHandle->retrieve;
666 # main child run loop. Ends when this child hits max requests.
669 my $data = $self->wait_for_request or next;
671 # Update process name to show activity
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");
681 my $session = OpenSRF::Transport->handler(
682 $self->{parent}->{service},
683 OpenSRF::Transport::SlimJabber::XMPPMessage->new(xml => $data)
686 my $recycle = $self->keepalive_loop($session);
688 last if ++$self->{num_requests} == $self->{parent}->{max_requests};
691 $chatty && $logger->internal(
692 "server: child exiting early on force_recycle");
696 # Tell the parent process we are available to process requests
699 # Repair process name
703 $chatty and $logger->internal("server: child process shutting down after reaching max_requests");
705 OpenSRF::Application->application_implementation->child_exit
706 if (OpenSRF::Application->application_implementation->can('child_exit'));
709 # ----------------------------------------------------------------
710 # waits for a request data on the parent pipe and returns it.
711 # ----------------------------------------------------------------
712 sub wait_for_request {
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
725 # wait for some data to start arriving
726 my $read_set = IO::Select->new;
727 $read_set->add($read_pipe);
730 # if can_read is interrupted while blocking,
731 # go back and wait again until it succeeds.
732 last if $read_set->can_read;
735 # parent started writing, let's start reading
736 $self->set_nonblock($read_pipe);
739 # read all of the available data
742 my $nbytes = sysread($self->{pipe_to_parent}, $buf, $buf_size);
744 unless(defined $nbytes) {
746 $logger->error("server: error reading data from parent: $!. ".
747 "bytes_needed=$bytes_needed; bytes_recvd=$bytes_recvd; data=$data");
753 last if $nbytes <= 0; # no more data available for reading
755 $bytes_recvd += $nbytes;
759 $self->set_block($self->{pipe_to_parent});
760 return undef if $read_error;
762 # extract the data size and remove the header from the final data
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);
771 if ($bytes_recvd == $bytes_needed) {
772 # we've read all the data. Nothing left to do
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");
784 # ----------------------------------------------------------------
785 # If this is a stateful opensrf session, wait up to $keepalive
786 # seconds for subsequent requests from the client
787 # ----------------------------------------------------------------
789 my($self, $session) = @_;
790 my $keepalive = $self->{parent}->{keepalive};
792 while($session->state and $session->state == $session->CONNECTED) {
794 unless( $session->queue_wait($keepalive) ) {
796 # client failed to disconnect before timeout
797 $logger->info("server: no request was received in $keepalive seconds, exiting stateful session");
799 my $res = OpenSRF::DomainObject::oilsConnectStatus->new(
800 status => "Disconnected on timeout",
801 statusCode => STATUS_TIMEOUT
804 $session->status($res);
805 $session->state($session->DISCONNECTED);
810 $chatty and $logger->internal("server: child done with request(s)");
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;
822 # ----------------------------------------------------------------
823 # Report our availability to our parent process
824 # ----------------------------------------------------------------
830 $self->{sig_pipe} = 0;
831 local $SIG{'PIPE'} = sub { $self->{sig_pipe} = 1; };
834 $self->{pipe_to_parent},
835 sprintf("%*s", OpenSRF::Server::STATUS_PIPE_DATA_SIZE, $self->{pid})
838 last unless $self->{sig_pipe};
839 $logger->error("server: $self got SIGPIPE writing status to parent, retrying...");
840 usleep(50000); # 50 msec
843 $logger->error("server: $self unable to send status to parent") if $self->{sig_pipe};