fix (probably harmless) "DBD::Pg::db disconnect failed: server closed the connection...
[freeside.git] / FS / bin / freeside-selfservice-xmlrpcd
1 #!/usr/bin/perl
2 #
3 # based on http://www.perlmonks.org/?node_id=582781 by Justin Hawkins
4 # and http://poe.perl.org/?POE_Cookbook/Web_Server_With_Forking
5
6 ###
7 # modules and constants and variables, oh my
8 ###
9
10 use warnings;
11 use strict;
12
13 use constant DEBUG         => 1;       # Enable much runtime information.
14 use constant MAX_PROCESSES => 10;      # Total server process count.
15 use constant SERVER_PORT   => 8080;    # Server port.
16 use constant TESTING_CHURN => 0;       # Randomly test process respawning.
17
18 use POE 1.2;                     # Base features.
19 use POE::Filter::HTTPD;          # For serving HTTP content.
20 use POE::Wheel::ReadWrite;       # For socket I/O.
21 use POE::Wheel::SocketFactory;   # For serving socket connections.
22
23 use XMLRPC::Transport::HTTP; #SOAP::Transport::HTTP;
24 use XMLRPC::Lite; # for XMLRPC::Serializer
25
26 use FS::Daemon qw(daemonize1 drop_root logfile daemonize2 );
27 use FS::UID qw(adminsuidsetup forksuidsetup);
28 use FS::Conf;
29 use FS::ClientAPI;
30 use FS::ClientAPI_XMLRPC; #FS::SelfService::XMLRPC;
31
32 #freeside
33 my $FREESIDE_LOG = "%%%FREESIDE_LOG%%%";
34 my $FREESIDE_LOCK = "%%%FREESIDE_LOCK%%%";
35 my $lock_file = "$FREESIDE_LOCK/selfservice-xmlrpcd.writelock";
36
37 #freeside xmlrpc.cgi
38 my %typelookup = (
39   base64 => [10, sub {$_[0] =~ /[^\x09\x0a\x0d\x20-\x7f]/}, 'as_base64'],
40   dateTime => [35, sub {$_[0] =~ /^\d{8}T\d\d:\d\d:\d\d$/}, 'as_dateTime'],
41   string => [40, sub {1}, 'as_string'],
42 );
43
44 ###
45 # freeside init
46 ###
47
48 my $user = shift or die &usage;
49
50 $FS::Daemon::NOSIG = 1;
51 $FS::Daemon::PID_NEWSTYLE = 1;
52 daemonize1('selfservice-xmlrpcd');
53
54 POE::Kernel->has_forked(); #daemonize forks...
55
56 drop_root();
57
58 adminsuidsetup($user);
59
60 logfile("$FREESIDE_LOG/selfservice-xmlrpcd.log");
61
62 daemonize2();
63
64 my $conf = new FS::Conf;
65
66 die "not running; selfservice-xmlrpc conf option is off\n"
67   unless $conf->exists('selfservice-xmlrpc');
68
69 ###
70 # the main loop
71 ###
72
73 server_spawn(MAX_PROCESSES);
74 POE::Kernel->run();
75 exit;
76
77 ###
78 # the subroutines
79 ###
80
81 ### Spawn the main server.  This will run as the parent process.
82
83 sub server_spawn {
84     my ($max_processes) = @_;
85
86     POE::Session->create(
87       inline_states => {
88         _start         => \&server_start,
89         _stop          => \&server_stop,
90         do_fork        => \&server_do_fork,
91         got_error      => \&server_got_error,
92         got_sig_int    => \&server_got_sig_int,
93         got_sig_child  => \&server_got_sig_child,
94         got_connection => \&server_got_connection,
95         _child         => sub { undef },
96       },
97       heap => { max_processes => MAX_PROCESSES },
98     );
99 }
100
101 ### The main server session has started.  Set up the server socket and
102 ### bookkeeping information, then fork the initial child processes.
103
104 sub server_start {
105     my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
106
107     $heap->{server} = POE::Wheel::SocketFactory->new
108       ( BindPort => SERVER_PORT,
109         SuccessEvent => "got_connection",
110         FailureEvent => "got_error",
111         Reuse        => "yes",
112       );
113
114     $kernel->sig( INT  => "got_sig_int" );
115     $kernel->sig( TERM => "got_sig_int" ); #huh
116
117     $heap->{children}   = {};
118     $heap->{is_a_child} = 0;
119
120     warn "Server $$ has begun listening on port ", SERVER_PORT, "\n";
121
122     $kernel->yield("do_fork");
123 }
124
125 ### The server session has shut down.  If this process has any
126 ### children, signal them to shutdown too.
127
128 sub server_stop {
129     my $heap = $_[HEAP];
130     DEBUG and warn "Server $$ stopped.\n";
131
132     if ( my @children = keys %{ $heap->{children} } ) {
133         DEBUG and warn "Server $$ is signaling children to stop.\n";
134         kill INT => @children;
135     }
136 }
137
138 ### The server session has encountered an error.  Shut it down.
139
140 sub server_got_error {
141     my ( $heap, $syscall, $errno, $error ) = @_[ HEAP, ARG0 .. ARG2 ];
142       warn( "Server $$ got $syscall error $errno: $error\n",
143         "Server $$ is shutting down.\n",
144       );
145     delete $heap->{server};
146 }
147
148 ### The server has a need to fork off more children.  Only honor that
149 ### request form the parent, otherwise we would surely "forkbomb".
150 ### Fork off as many child processes as we need.
151
152 sub server_do_fork {
153     my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
154
155     return if $heap->{is_a_child};
156
157     #my $current_children = keys %{ $heap->{children} };
158     #for ( $current_children + 2 .. $heap->{max_processes} ) {
159     while (scalar(keys %{$heap->{children}}) < $heap->{max_processes}) {
160
161         DEBUG and warn "Server $$ is attempting to fork.\n";
162
163         my $pid = fork();
164
165         unless ( defined($pid) ) {
166             DEBUG and
167               warn( "Server $$ fork failed: $!\n",
168                 "Server $$ will retry fork shortly.\n",
169               );
170             $kernel->delay( do_fork => 1 );
171             return;
172         }
173
174         # Parent.  Add the child process to its list.
175         if ($pid) {
176             $heap->{children}->{$pid} = 1;
177             $kernel->sig_child($pid, "got_sig_child");
178             next;
179         }
180
181         # Child.  Clear the child process list.
182         $kernel->has_forked();
183         DEBUG and warn "Server $$ forked successfully.\n";
184         $heap->{is_a_child} = 1;
185         $heap->{children}   = {};
186
187         return;
188     }
189 }
190
191 ### The server session received SIGINT.  Don't handle the signal,
192 ### which in turn will trigger the process to exit gracefully.
193
194 sub server_got_sig_int {
195     my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
196     DEBUG and warn "Server $$ received SIGINT/TERM.\n";
197
198     if ( my @children = keys %{ $heap->{children} } ) {
199         DEBUG and warn "Server $$ is signaling children to stop.\n";
200         kill INT => @children;
201     }
202
203     delete $heap->{server};
204     $kernel->sig_handled();
205 }
206
207 ### The server session received a SIGCHLD, indicating that some child
208 ### server has gone away.  Remove the child's process ID from our
209 ### list, and trigger more fork() calls to spawn new children.
210
211 sub server_got_sig_child {
212     my ( $kernel, $heap, $child_pid ) = @_[ KERNEL, HEAP, ARG1 ];
213
214     return unless delete $heap->{children}->{$child_pid};
215
216    DEBUG and warn "Server $$ reaped child $child_pid.\n";
217    $kernel->yield("do_fork") if exists $_[HEAP]->{server};
218 }
219
220 ### The server session received a connection request.  Spawn off a
221 ### client handler session to parse the request and respond to it.
222
223 sub server_got_connection {
224     my ( $heap, $socket, $peer_addr, $peer_port ) = @_[ HEAP, ARG0, ARG1, ARG2 ];
225
226     DEBUG and warn "Server $$ received a connection.\n";
227
228     POE::Session->create(
229       inline_states => {
230         _start      => \&client_start,
231         _stop       => \&client_stop,
232         got_request => \&client_got_request,
233         got_flush   => \&client_flushed_request,
234         got_error   => \&client_got_error,
235         _parent     => sub { 0 },
236       },
237       heap => {
238         socket    => $socket,
239         peer_addr => $peer_addr,
240         peer_port => $peer_port,
241       },
242     );
243
244     # Gracefully exit if testing process churn.
245     delete $heap->{server}
246       if TESTING_CHURN and $heap->{is_a_child} and ( rand() < 0.1 );
247 }
248
249 ### The client handler has started.  Wrap its socket in a ReadWrite
250 ### wheel to begin interacting with it.
251
252 sub client_start {
253     my $heap = $_[HEAP];
254
255     $heap->{client} = POE::Wheel::ReadWrite->new
256       ( Handle => $heap->{socket},
257         Filter       => POE::Filter::HTTPD->new(),
258         InputEvent   => "got_request",
259         ErrorEvent   => "got_error",
260         FlushedEvent => "got_flush",
261       );
262
263     DEBUG and warn "Client handler $$/", $_[SESSION]->ID, " started.\n";
264 }
265
266 ### The client handler has stopped.  Log that fact.
267
268 sub client_stop {
269     DEBUG and warn "Client handler $$/", $_[SESSION]->ID, " stopped.\n";
270 }
271
272 ### The client handler has received a request.  If it's an
273 ### HTTP::Response object, it means some error has occurred while
274 ### parsing the request.  Send that back and return immediately.
275 ### Otherwise parse and process the request, generating and sending an
276 ### HTTP::Response object in response.
277
278 sub client_got_request {
279     my ( $heap, $request ) = @_[ HEAP, ARG0 ];
280
281     freeside_kid_time();
282
283     my $serializer = new XMLRPC::Serializer(typelookup => \%typelookup);
284
285     #my $soap = SOAP::Transport::HTTP::Server
286     my $soap = XMLRPC::Transport::HTTP::Server
287                -> new
288                -> dispatch_to('FS::ClientAPI_XMLRPC')
289                -> serializer($serializer);
290
291     DEBUG and
292       warn "Client handler $$/", $_[SESSION]->ID, " is handling a request.\n";
293
294     if ( $request->isa("HTTP::Response") ) {
295         $heap->{client}->put($request);
296         return;
297     }
298
299     $soap->request($request);
300     $soap->handle;
301     my $response = $soap->response;
302
303     $heap->{client}->put($response);
304 }
305
306 #setup the database connection and other things FS::SelfService::XMLRPC
307 #expects to be in place.  aka "kid time" in freeside-selfservice-server
308 sub freeside_kid_time {
309
310   #we did need a db connection in the parent, so
311   ##get new db handle
312   $FS::UID::dbh->{InactiveDestroy} = 1;
313   forksuidsetup($user);
314
315   #i guess that was it
316 }
317
318 ### The client handler received an error.  Stop the ReadWrite wheel,
319 ### which also closes the socket.
320
321 sub client_got_error {
322     my ( $heap, $operation, $errnum, $errstr ) = @_[ HEAP, ARG0, ARG1, ARG2 ];
323     DEBUG and
324       warn( "Client handler $$/", $_[SESSION]->ID,
325         " got $operation error $errnum: $errstr\n",
326         "Client handler $$/", $_[SESSION]->ID, " is shutting down.\n"
327       );
328     delete $heap->{client};
329 }
330
331 ### The client handler has flushed its response to the socket.  We're
332 ### done with the client connection, so stop the ReadWrite wheel.
333
334 sub client_flushed_request {
335     my $heap = $_[HEAP];
336     DEBUG and
337       warn( "Client handler $$/", $_[SESSION]->ID,
338         " flushed its response.\n",
339         "Client handler $$/", $_[SESSION]->ID, " is shutting down.\n"
340       );
341     delete $heap->{client};
342 }
343
344 sub usage {
345   die "Usage:\n\n  freeside-selfservice-xmlrpcd user\n";
346 }
347
348 ###
349 # the end
350 ###
351
352 1;