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