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