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