fix leaking db connections in freeside-selfservice-xmlrpcd, RT#7780
[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 dbh );
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 #parent doesn't need to hold a DB connection open
70 dbh->disconnect;
71 undef $FS::UID::dbh;
72
73 ###
74 # the main loop
75 ###
76
77 server_spawn(MAX_PROCESSES);
78 POE::Kernel->run();
79 exit;
80
81 ###
82 # the subroutines
83 ###
84
85 ### Spawn the main server.  This will run as the parent process.
86
87 sub server_spawn {
88     my ($max_processes) = @_;
89
90     POE::Session->create(
91       inline_states => {
92         _start         => \&server_start,
93         _stop          => \&server_stop,
94         do_fork        => \&server_do_fork,
95         got_error      => \&server_got_error,
96         got_sig_int    => \&server_got_sig_int,
97         got_sig_child  => \&server_got_sig_child,
98         got_connection => \&server_got_connection,
99         _child         => sub { undef },
100       },
101       heap => { max_processes => MAX_PROCESSES },
102     );
103 }
104
105 ### The main server session has started.  Set up the server socket and
106 ### bookkeeping information, then fork the initial child processes.
107
108 sub server_start {
109     my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
110
111     $heap->{server} = POE::Wheel::SocketFactory->new
112       ( BindPort => SERVER_PORT,
113         SuccessEvent => "got_connection",
114         FailureEvent => "got_error",
115         Reuse        => "yes",
116       );
117
118     $kernel->sig( INT  => "got_sig_int" );
119     $kernel->sig( TERM => "got_sig_int" ); #huh
120
121     $heap->{children}   = {};
122     $heap->{is_a_child} = 0;
123
124     warn "Server $$ has begun listening on port ", SERVER_PORT, "\n";
125
126     $kernel->yield("do_fork");
127 }
128
129 ### The server session has shut down.  If this process has any
130 ### children, signal them to shutdown too.
131
132 sub server_stop {
133     my $heap = $_[HEAP];
134     DEBUG and warn "Server $$ stopped.\n";
135
136     if ( my @children = keys %{ $heap->{children} } ) {
137         DEBUG and warn "Server $$ is signaling children to stop.\n";
138         kill INT => @children;
139     }
140 }
141
142 ### The server session has encountered an error.  Shut it down.
143
144 sub server_got_error {
145     my ( $heap, $syscall, $errno, $error ) = @_[ HEAP, ARG0 .. ARG2 ];
146       warn( "Server $$ got $syscall error $errno: $error\n",
147         "Server $$ is shutting down.\n",
148       );
149     delete $heap->{server};
150 }
151
152 ### The server has a need to fork off more children.  Only honor that
153 ### request form the parent, otherwise we would surely "forkbomb".
154 ### Fork off as many child processes as we need.
155
156 sub server_do_fork {
157     my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
158
159     return if $heap->{is_a_child};
160
161     #my $current_children = keys %{ $heap->{children} };
162     #for ( $current_children + 2 .. $heap->{max_processes} ) {
163     while (scalar(keys %{$heap->{children}}) < $heap->{max_processes}) {
164
165         DEBUG and warn "Server $$ is attempting to fork.\n";
166
167         my $pid = fork();
168
169         unless ( defined($pid) ) {
170             DEBUG and
171               warn( "Server $$ fork failed: $!\n",
172                 "Server $$ will retry fork shortly.\n",
173               );
174             $kernel->delay( do_fork => 1 );
175             return;
176         }
177
178         # Parent.  Add the child process to its list.
179         if ($pid) {
180             $heap->{children}->{$pid} = 1;
181             $kernel->sig_child($pid, "got_sig_child");
182             next;
183         }
184
185         # Child.  Clear the child process list.
186         $kernel->has_forked();
187         DEBUG and warn "Server $$ forked successfully.\n";
188         $heap->{is_a_child} = 1;
189         $heap->{children}   = {};
190
191         #freeside db connection, etc.
192         forksuidsetup($user);
193
194         return;
195     }
196 }
197
198 ### The server session received SIGINT.  Don't handle the signal,
199 ### which in turn will trigger the process to exit gracefully.
200
201 sub server_got_sig_int {
202     my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
203     DEBUG and warn "Server $$ received SIGINT/TERM.\n";
204
205     if ( my @children = keys %{ $heap->{children} } ) {
206         DEBUG and warn "Server $$ is signaling children to stop.\n";
207         kill INT => @children;
208     }
209
210     delete $heap->{server};
211     $kernel->sig_handled();
212 }
213
214 ### The server session received a SIGCHLD, indicating that some child
215 ### server has gone away.  Remove the child's process ID from our
216 ### list, and trigger more fork() calls to spawn new children.
217
218 sub server_got_sig_child {
219     my ( $kernel, $heap, $child_pid ) = @_[ KERNEL, HEAP, ARG1 ];
220
221     return unless delete $heap->{children}->{$child_pid};
222
223    DEBUG and warn "Server $$ reaped child $child_pid.\n";
224    $kernel->yield("do_fork") if exists $_[HEAP]->{server};
225 }
226
227 ### The server session received a connection request.  Spawn off a
228 ### client handler session to parse the request and respond to it.
229
230 sub server_got_connection {
231     my ( $heap, $socket, $peer_addr, $peer_port ) = @_[ HEAP, ARG0, ARG1, ARG2 ];
232
233     DEBUG and warn "Server $$ received a connection.\n";
234
235     POE::Session->create(
236       inline_states => {
237         _start      => \&client_start,
238         _stop       => \&client_stop,
239         got_request => \&client_got_request,
240         got_flush   => \&client_flushed_request,
241         got_error   => \&client_got_error,
242         _parent     => sub { 0 },
243       },
244       heap => {
245         socket    => $socket,
246         peer_addr => $peer_addr,
247         peer_port => $peer_port,
248       },
249     );
250
251     # Gracefully exit if testing process churn.
252     delete $heap->{server}
253       if TESTING_CHURN and $heap->{is_a_child} and ( rand() < 0.1 );
254 }
255
256 ### The client handler has started.  Wrap its socket in a ReadWrite
257 ### wheel to begin interacting with it.
258
259 sub client_start {
260     my $heap = $_[HEAP];
261
262     $heap->{client} = POE::Wheel::ReadWrite->new
263       ( Handle => $heap->{socket},
264         Filter       => POE::Filter::HTTPD->new(),
265         InputEvent   => "got_request",
266         ErrorEvent   => "got_error",
267         FlushedEvent => "got_flush",
268       );
269
270     DEBUG and warn "Client handler $$/", $_[SESSION]->ID, " started.\n";
271 }
272
273 ### The client handler has stopped.  Log that fact.
274
275 sub client_stop {
276     DEBUG and warn "Client handler $$/", $_[SESSION]->ID, " stopped.\n";
277 }
278
279 ### The client handler has received a request.  If it's an
280 ### HTTP::Response object, it means some error has occurred while
281 ### parsing the request.  Send that back and return immediately.
282 ### Otherwise parse and process the request, generating and sending an
283 ### HTTP::Response object in response.
284
285 sub client_got_request {
286     my ( $heap, $request ) = @_[ HEAP, ARG0 ];
287
288     forksuidsetup($user) unless dbh && dbh->ping;
289
290     my $serializer = new XMLRPC::Serializer(typelookup => \%typelookup);
291
292     #my $soap = SOAP::Transport::HTTP::Server
293     my $soap = XMLRPC::Transport::HTTP::Server
294                -> new
295                -> dispatch_to('FS::ClientAPI_XMLRPC')
296                -> serializer($serializer);
297
298     DEBUG and
299       warn "Client handler $$/", $_[SESSION]->ID, " is handling a request.\n";
300
301     if ( $request->isa("HTTP::Response") ) {
302         $heap->{client}->put($request);
303         return;
304     }
305
306     $soap->request($request);
307     $soap->handle;
308     my $response = $soap->response;
309
310     $heap->{client}->put($response);
311 }
312
313 ### The client handler received an error.  Stop the ReadWrite wheel,
314 ### which also closes the socket.
315
316 sub client_got_error {
317     my ( $heap, $operation, $errnum, $errstr ) = @_[ HEAP, ARG0, ARG1, ARG2 ];
318     DEBUG and
319       warn( "Client handler $$/", $_[SESSION]->ID,
320         " got $operation error $errnum: $errstr\n",
321         "Client handler $$/", $_[SESSION]->ID, " is shutting down.\n"
322       );
323     delete $heap->{client};
324 }
325
326 ### The client handler has flushed its response to the socket.  We're
327 ### done with the client connection, so stop the ReadWrite wheel.
328
329 sub client_flushed_request {
330     my $heap = $_[HEAP];
331     DEBUG and
332       warn( "Client handler $$/", $_[SESSION]->ID,
333         " flushed its response.\n",
334         "Client handler $$/", $_[SESSION]->ID, " is shutting down.\n"
335       );
336     delete $heap->{client};
337 }
338
339 sub usage {
340   die "Usage:\n\n  freeside-selfservice-xmlrpcd user\n";
341 }
342
343 ###
344 # the end
345 ###
346
347 1;