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;
25 use POSIX qw/:sys_wait_h :errno_h/;
26 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
29 our $chatty = 1; # disable for production
31 use constant STATUS_PIPE_DATA_SIZE => 12;
34 my($class, $service, %args) = @_;
35 my $self = bless(\%args, $class);
37 $self->{service} = $service; # service name
38 $self->{num_children} = 0; # number of child processes
39 $self->{osrf_handle} = undef; # xmpp handle
40 $self->{routers} = []; # list of registered routers
41 $self->{active_list} = []; # list of active children
42 $self->{idle_list} = []; # list of idle children
44 $self->{stderr_log} = $self->{stderr_log_path} . "/${service}_stderr.log"
45 if $self->{stderr_log_path};
47 $self->{min_spare_children} ||= 0;
49 $self->{max_spare_children} = $self->{min_spare_children} + 1 if
50 $self->{max_spare_children} and
51 $self->{max_spare_children} <= $self->{min_spare_children};
56 # ----------------------------------------------------------------
57 # Disconnects from routers and waits for child processes to exit.
58 # ----------------------------------------------------------------
63 $logger->info("server: shutting down and cleaning up...");
65 # don't get sidetracked by signals while we're cleaning up.
66 # it could result in unexpected behavior with list traversal
67 $SIG{CHLD} = 'IGNORE';
69 # terminate the child processes
70 $self->kill_child($_) for
71 (@{$self->{idle_list}}, @{$self->{active_list}});
74 $self->unregister_routers;
76 $self->{osrf_handle}->disconnect;
78 # clean up our dead children
79 $self->reap_children(1);
81 exit(0) unless $no_exit;
85 # ----------------------------------------------------------------
86 # Waits on the jabber socket for inbound data from the router.
87 # Each new message is passed off to a child process for handling.
88 # At regular intervals, wake up for min/max spare child maintenance
89 # ----------------------------------------------------------------
93 $logger->set_service($self->{service});
95 $SIG{$_} = sub { $self->cleanup; } for (qw/INT TERM QUIT/);
96 $SIG{CHLD} = sub { $self->reap_children(); };
98 $self->spawn_children;
99 $self->build_osrf_handle;
100 $self->register_routers;
107 $self->{child_died} = 0;
109 my $msg = $self->{osrf_handle}->process($wait_time);
111 # we woke up for any reason, reset the wait time to allow
112 # for idle maintenance as necessary
117 if(my $child = pop(@{$self->{idle_list}})) {
119 # we have an idle child to handle the request
120 $chatty and $logger->internal("server: passing request to idle child $child");
121 push(@{$self->{active_list}}, $child);
122 $self->write_child($child, $msg);
124 } elsif($self->{num_children} < $self->{max_children}) {
126 # spawning a child to handle the request
127 $chatty and $logger->internal("server: spawning child to handle request");
128 $self->write_child($self->spawn_child(1), $msg);
132 $logger->warn("server: no children available, waiting...");
133 $self->check_status(1); # block until child is available
135 my $child = pop(@{$self->{idle_list}});
136 push(@{$self->{active_list}}, $child);
137 $self->write_child($child, $msg);
142 # don't perform idle maint immediately when woken by SIGCHLD
143 unless($self->{child_died}) {
145 # when we hit equilibrium, there's no need for regular
146 # maintenance, so set wait_time to 'forever'
148 !$self->perform_idle_maintenance and # no maintenance performed this time
149 @{$self->{active_list}} == 0; # no active children
155 # ----------------------------------------------------------------
156 # Launch a new spare child or kill an extra spare child. To
157 # prevent large-scale spawning or die-offs, spawn or kill only
158 # 1 process per idle maintenance loop.
159 # Returns true if any idle maintenance occurred, 0 otherwise
160 # ----------------------------------------------------------------
161 sub perform_idle_maintenance {
164 # spawn 1 spare child per maintenance loop if necessary
165 if( $self->{min_spare_children} and
166 $self->{num_children} < $self->{max_children} and
167 scalar(@{$self->{idle_list}}) < $self->{min_spare_children} ) {
169 $chatty and $logger->internal("server: spawning spare child");
173 # kill 1 excess spare child per maintenance loop if necessary
174 } elsif($self->{max_spare_children} and
175 $self->{num_children} > $self->{min_children} and
176 scalar(@{$self->{idle_list}}) > $self->{max_spare_children} ) {
178 $chatty and $logger->internal("server: killing spare child");
188 my $child = shift || pop(@{$self->{idle_list}}) or return;
189 $chatty and $logger->internal("server: killing child $child");
190 kill('TERM', $child->{pid});
193 # ----------------------------------------------------------------
194 # Jabber connection inbound message arrive on.
195 # ----------------------------------------------------------------
196 sub build_osrf_handle {
199 my $conf = OpenSRF::Utils::Config->current;
200 my $username = $conf->bootstrap->username;
201 my $password = $conf->bootstrap->passwd;
202 my $domain = $conf->bootstrap->domain;
203 my $port = $conf->bootstrap->port;
204 my $resource = $self->{service} . '_listener_' . $conf->env->hostname;
206 $logger->debug("server: inbound connecting as $username\@$domain/$resource on port $port");
208 $self->{osrf_handle} =
209 OpenSRF::Transport::SlimJabber::Client->new(
210 username => $username,
211 resource => $resource,
212 password => $password,
217 $self->{osrf_handle}->initialize;
221 # ----------------------------------------------------------------
222 # Sends request data to a child process
223 # ----------------------------------------------------------------
225 my($self, $child, $msg) = @_;
226 my $xml = $msg->to_xml;
227 syswrite($child->{pipe_to_child}, $xml);
230 # ----------------------------------------------------------------
231 # Checks to see if any child process has reported its availability
232 # In blocking mode, blocks until a child has reported.
233 # ----------------------------------------------------------------
235 my($self, $block) = @_;
237 return unless @{$self->{active_list}};
239 my $read_set = IO::Select->new;
240 $read_set->add($_->{pipe_to_child}) for @{$self->{active_list}};
246 # if can_read or sysread is interrupted while bloking, go back and
247 # wait again until we have at least 1 free child
249 if(my @handles = $read_set->can_read(($block) ? undef : 0)) {
251 for my $pipe (@handles) {
252 sysread($pipe, $pid, STATUS_PIPE_DATA_SIZE) or next;
253 push(@pids, int($pid));
257 last unless $block and !@pids;
262 $chatty and $logger->internal("server: ".scalar(@pids)." children reporting for duty: (@pids)");
267 # move the children from the active list to the idle list
268 for my $proc (@{$self->{active_list}}) {
269 if(grep { $_ == $proc->{pid} } @pids) {
270 push(@{$self->{idle_list}}, $proc);
272 push(@new_actives, $proc);
276 $self->{active_list} = [@new_actives];
278 $chatty and $logger->internal(sprintf(
279 "server: %d idle and %d active children after status update",
280 scalar(@{$self->{idle_list}}), scalar(@{$self->{active_list}})));
283 # ----------------------------------------------------------------
284 # Cleans up any child processes that have exited.
285 # In shutdown mode, block until all children have washed ashore
286 # ----------------------------------------------------------------
288 my($self, $shutdown) = @_;
289 $self->{child_died} = 1;
293 my $pid = waitpid(-1, ($shutdown) ? 0 : WNOHANG);
296 $chatty and $logger->internal("server: reaping child $pid");
298 my ($child) = grep {$_->{pid} == $pid} (@{$self->{active_list}}, @{$self->{idle_list}});
300 close($child->{pipe_to_parent});
301 close($child->{pipe_to_child});
302 delete $child->{$_} for keys %$child; # destroy with a vengeance
304 $self->{num_children}--;
305 $self->{active_list} = [ grep { $_->{pid} != $pid } @{$self->{active_list}} ];
306 $self->{idle_list} = [ grep { $_->{pid} != $pid } @{$self->{idle_list}} ];
309 $self->spawn_children unless $shutdown;
311 $chatty and $logger->internal(sprintf(
312 "server: %d idle and %d active children after reap_children",
313 scalar(@{$self->{idle_list}}), scalar(@{$self->{active_list}})));
317 # ----------------------------------------------------------------
318 # Spawn up to max_children processes
319 # ----------------------------------------------------------------
322 $self->spawn_child while $self->{num_children} < $self->{min_children};
325 # ----------------------------------------------------------------
326 # Spawns a new child. If $active is set, the child goes directly
327 # into the active_list.
328 # ----------------------------------------------------------------
330 my($self, $active) = @_;
332 my $child = OpenSRF::Server::Child->new($self);
334 # socket for sending message data to the child
336 $child->{pipe_to_child},
337 $child->{pipe_to_parent},
338 AF_UNIX, SOCK_STREAM, PF_UNSPEC)) {
339 $logger->error("server: error creating data socketpair: $!");
343 $child->{pipe_to_child}->autoflush(1);
344 $child->{pipe_to_parent}->autoflush(1);
346 $child->{pid} = fork();
348 if($child->{pid}) { # parent process
349 $self->{num_children}++;
353 push(@{$self->{active_list}}, $child);
355 push(@{$self->{idle_list}}, $child);
358 $chatty and $logger->internal("server: server spawned child $child with ".$self->{num_children}." total children");
362 } else { # child process
364 $SIG{$_} = 'DEFAULT' for (qw/INT TERM QUIT HUP/);
366 if($self->{stderr_log}) {
368 $chatty and $logger->internal("server: redirecting STDERR to " . $self->{stderr_log});
371 unless( open(STDERR, '>>' . $self->{stderr_log}) ) {
372 $logger->error("server: unable to open STDERR log file: " . $self->{stderr_log} . " : $@");
373 open STDERR, '>/dev/null'; # send it back to /dev/null
381 OpenSRF::Transport::PeerHandle->retrieve->disconnect;
383 $logger->error("server: child process died: $@") if $@;
388 # ----------------------------------------------------------------
389 # Sends the register command to the configured routers
390 # ----------------------------------------------------------------
391 sub register_routers {
394 my $conf = OpenSRF::Utils::Config->current;
395 my $routers = $conf->bootstrap->routers;
396 my $router_name = $conf->bootstrap->router_name;
399 for my $router (@$routers) {
402 if( !$router->{services} ||
403 !$router->{services}->{service} ||
405 ref($router->{services}->{service}) eq 'ARRAY' and
406 grep { $_ eq $self->{service} } @{$router->{services}->{service}}
407 ) || $router->{services}->{service} eq $self->{service}) {
409 my $name = $router->{name};
410 my $domain = $router->{domain};
411 push(@targets, "$name\@$domain/router");
415 push(@targets, "$router_name\@$router/router");
420 $logger->info("server: registering with router $_");
421 $self->{osrf_handle}->send(
423 body => 'registering',
424 router_command => 'register',
425 router_class => $self->{service}
429 $self->{routers} = \@targets;
432 # ----------------------------------------------------------------
433 # Sends the unregister command to any routers we have registered
435 # ----------------------------------------------------------------
436 sub unregister_routers {
438 return unless $self->{osrf_handle}->tcp_connected;
440 for my $router (@{$self->{routers}}) {
441 $logger->info("server: disconnecting from router $router");
442 $self->{osrf_handle}->send(
444 body => "unregistering",
445 router_command => "unregister",
446 router_class => $self->{service}
452 package OpenSRF::Server::Child;
455 use OpenSRF::Transport;
456 use OpenSRF::Application;
457 use OpenSRF::Transport::PeerHandle;
458 use OpenSRF::Transport::SlimJabber::XMPPMessage;
459 use OpenSRF::Utils::Logger qw($logger);
460 use OpenSRF::DomainObject::oilsResponse qw/:status/;
461 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
462 use Time::HiRes qw(time);
463 use POSIX qw/:sys_wait_h :errno_h/;
465 use overload '""' => sub { return '[' . shift()->{pid} . ']'; };
468 my($class, $parent) = @_;
469 my $self = bless({}, $class);
470 $self->{pid} = 0; # my process ID
471 $self->{parent} = $parent; # Controller parent process
472 $self->{num_requests} = 0; # total serviced requests
478 my $flags = fcntl($fh, F_GETFL, 0);
479 fcntl($fh, F_SETFL, $flags | O_NONBLOCK);
484 my $flags = fcntl($fh, F_GETFL, 0);
485 $flags &= ~O_NONBLOCK;
486 fcntl($fh, F_SETFL, $flags);
489 # ----------------------------------------------------------------
490 # Connects to Jabber and runs the application child_init
491 # ----------------------------------------------------------------
494 my $service = $self->{parent}->{service};
495 $0 = "OpenSRF Drone [$service]";
496 OpenSRF::Transport::PeerHandle->construct($service);
497 OpenSRF::Application->application_implementation->child_init
498 if (OpenSRF::Application->application_implementation->can('child_init'));
501 # ----------------------------------------------------------------
502 # Waits for messages from the parent process, handles the message,
503 # then goes into the keepalive loop if this is a stateful session.
504 # When max_requests is hit, the process exits.
505 # ----------------------------------------------------------------
508 my $network = OpenSRF::Transport::PeerHandle->retrieve;
510 # main child run loop. Ends when this child hits max requests.
513 my $data = $self->wait_for_request or next;
515 # Update process name to show activity
519 # Discard extraneous data from the jabber socket
520 if(!$network->flush_socket()) {
521 $logger->error("server: network disconnected! child dropping request and exiting: $data");
525 my $session = OpenSRF::Transport->handler(
526 $self->{parent}->{service},
527 OpenSRF::Transport::SlimJabber::XMPPMessage->new(xml => $data)
530 $self->keepalive_loop($session);
532 last if ++$self->{num_requests} == $self->{parent}->{max_requests};
534 # Tell the parent process we are available to process requests
537 # Repair process name
541 $chatty and $logger->internal("server: child process shutting down after reaching max_requests");
543 OpenSRF::Application->application_implementation->child_exit
544 if (OpenSRF::Application->application_implementation->can('child_exit'));
547 # ----------------------------------------------------------------
548 # waits for a request data on the parent pipe and returns it.
549 # ----------------------------------------------------------------
550 sub wait_for_request {
554 my $read_size = 1024;
558 # Start out blocking, when data is available, read it all
561 my $n = sysread($self->{pipe_to_parent}, $buf, $read_size);
564 $logger->error("server: error reading data pipe: $!") unless EAGAIN == $!;
568 last if $n <= 0; # no data left to read
572 last if $n < $read_size; # done reading all data
574 $self->set_nonblock($self->{pipe_to_parent}) unless $nonblock;
578 $self->set_block($self->{pipe_to_parent}) if $nonblock;
583 # ----------------------------------------------------------------
584 # If this is a stateful opensrf session, wait up to $keepalive
585 # seconds for subsequent requests from the client
586 # ----------------------------------------------------------------
588 my($self, $session) = @_;
589 my $keepalive = $self->{parent}->{keepalive};
591 while($session->state and $session->state == $session->CONNECTED) {
593 unless( $session->queue_wait($keepalive) ) {
595 # client failed to disconnect before timeout
596 $logger->info("server: no request was received in $keepalive seconds, exiting stateful session");
598 my $res = OpenSRF::DomainObject::oilsConnectStatus->new(
599 status => "Disconnected on timeout",
600 statusCode => STATUS_TIMEOUT
603 $session->status($res);
604 $session->state($session->DISCONNECTED);
609 $chatty and $logger->internal("server: child done with request(s)");
613 # ----------------------------------------------------------------
614 # Report our availability to our parent process
615 # ----------------------------------------------------------------
619 $self->{pipe_to_parent},
620 sprintf("%*s", OpenSRF::Server::STATUS_PIPE_DATA_SIZE, $self->{pid})