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
7 # modules and constants and variables, oh my
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.
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.
23 use XMLRPC::Transport::HTTP; #SOAP::Transport::HTTP;
24 use XMLRPC::Lite; # for XMLRPC::Serializer
26 use FS::Daemon qw( daemonize1 drop_root logfile daemonize2 );
27 use FS::UID qw( adminsuidsetup forksuidsetup dbh );
30 use FS::ClientAPI_XMLRPC; #FS::SelfService::XMLRPC;
33 my $FREESIDE_LOG = "%%%FREESIDE_LOG%%%";
34 my $FREESIDE_LOCK = "%%%FREESIDE_LOCK%%%";
35 my $lock_file = "$FREESIDE_LOCK/selfservice-xmlrpcd.writelock";
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'],
48 my $user = shift or die &usage;
50 $FS::Daemon::NOSIG = 1;
51 $FS::Daemon::PID_NEWSTYLE = 1;
52 daemonize1('selfservice-xmlrpcd');
54 POE::Kernel->has_forked(); #daemonize forks...
58 adminsuidsetup($user);
60 logfile("$FREESIDE_LOG/selfservice-xmlrpcd.log");
64 my $conf = new FS::Conf;
66 die "not running; selfservice-xmlrpc conf option is off\n"
67 unless $conf->exists('selfservice-xmlrpc');
69 #parent doesn't need to hold a DB connection open
77 server_spawn(MAX_PROCESSES);
85 ### Spawn the main server. This will run as the parent process.
88 my ($max_processes) = @_;
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 },
101 heap => { max_processes => MAX_PROCESSES },
105 ### The main server session has started. Set up the server socket and
106 ### bookkeeping information, then fork the initial child processes.
109 my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
111 $heap->{server} = POE::Wheel::SocketFactory->new
112 ( BindPort => SERVER_PORT,
113 SuccessEvent => "got_connection",
114 FailureEvent => "got_error",
118 $kernel->sig( INT => "got_sig_int" );
119 $kernel->sig( TERM => "got_sig_int" ); #huh
121 $heap->{children} = {};
122 $heap->{is_a_child} = 0;
124 warn "Server $$ has begun listening on port ", SERVER_PORT, "\n";
126 $kernel->yield("do_fork");
129 ### The server session has shut down. If this process has any
130 ### children, signal them to shutdown too.
134 DEBUG and warn "Server $$ stopped.\n";
136 if ( my @children = keys %{ $heap->{children} } ) {
137 DEBUG and warn "Server $$ is signaling children to stop.\n";
138 kill INT => @children;
142 ### The server session has encountered an error. Shut it down.
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",
149 delete $heap->{server};
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.
157 my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
159 return if $heap->{is_a_child};
161 #my $current_children = keys %{ $heap->{children} };
162 #for ( $current_children + 2 .. $heap->{max_processes} ) {
163 while (scalar(keys %{$heap->{children}}) < $heap->{max_processes}) {
165 DEBUG and warn "Server $$ is attempting to fork.\n";
169 unless ( defined($pid) ) {
171 warn( "Server $$ fork failed: $!\n",
172 "Server $$ will retry fork shortly.\n",
174 $kernel->delay( do_fork => 1 );
178 # Parent. Add the child process to its list.
180 $heap->{children}->{$pid} = 1;
181 $kernel->sig_child($pid, "got_sig_child");
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} = {};
191 #freeside db connection, etc.
192 forksuidsetup($user);
198 ### The server session received SIGINT. Don't handle the signal,
199 ### which in turn will trigger the process to exit gracefully.
201 sub server_got_sig_int {
202 my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
203 DEBUG and warn "Server $$ received SIGINT/TERM.\n";
205 if ( my @children = keys %{ $heap->{children} } ) {
206 DEBUG and warn "Server $$ is signaling children to stop.\n";
207 kill INT => @children;
210 delete $heap->{server};
211 $kernel->sig_handled();
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.
218 sub server_got_sig_child {
219 my ( $kernel, $heap, $child_pid ) = @_[ KERNEL, HEAP, ARG1 ];
221 return unless delete $heap->{children}->{$child_pid};
223 DEBUG and warn "Server $$ reaped child $child_pid.\n";
224 $kernel->yield("do_fork") if exists $_[HEAP]->{server};
227 ### The server session received a connection request. Spawn off a
228 ### client handler session to parse the request and respond to it.
230 sub server_got_connection {
231 my ( $heap, $socket, $peer_addr, $peer_port ) = @_[ HEAP, ARG0, ARG1, ARG2 ];
233 DEBUG and warn "Server $$ received a connection.\n";
235 POE::Session->create(
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 },
246 peer_addr => $peer_addr,
247 peer_port => $peer_port,
251 # Gracefully exit if testing process churn.
252 delete $heap->{server}
253 if TESTING_CHURN and $heap->{is_a_child} and ( rand() < 0.1 );
256 ### The client handler has started. Wrap its socket in a ReadWrite
257 ### wheel to begin interacting with it.
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",
270 DEBUG and warn "Client handler $$/", $_[SESSION]->ID, " started.\n";
273 ### The client handler has stopped. Log that fact.
276 DEBUG and warn "Client handler $$/", $_[SESSION]->ID, " stopped.\n";
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.
285 sub client_got_request {
286 my ( $heap, $request ) = @_[ HEAP, ARG0 ];
288 forksuidsetup($user) unless dbh && dbh->ping;
290 my $serializer = new XMLRPC::Serializer(typelookup => \%typelookup);
292 #my $soap = SOAP::Transport::HTTP::Server
293 my $soap = XMLRPC::Transport::HTTP::Server
295 -> dispatch_to('FS::ClientAPI_XMLRPC')
296 -> serializer($serializer);
299 warn "Client handler $$/", $_[SESSION]->ID, " is handling a request.\n";
301 if ( $request->isa("HTTP::Response") ) {
302 $heap->{client}->put($request);
306 $soap->request($request);
308 my $response = $soap->response;
310 $heap->{client}->put($response);
313 ### The client handler received an error. Stop the ReadWrite wheel,
314 ### which also closes the socket.
316 sub client_got_error {
317 my ( $heap, $operation, $errnum, $errstr ) = @_[ HEAP, ARG0, ARG1, ARG2 ];
319 warn( "Client handler $$/", $_[SESSION]->ID,
320 " got $operation error $errnum: $errstr\n",
321 "Client handler $$/", $_[SESSION]->ID, " is shutting down.\n"
323 delete $heap->{client};
326 ### The client handler has flushed its response to the socket. We're
327 ### done with the client connection, so stop the ReadWrite wheel.
329 sub client_flushed_request {
332 warn( "Client handler $$/", $_[SESSION]->ID,
333 " flushed its response.\n",
334 "Client handler $$/", $_[SESSION]->ID, " is shutting down.\n"
336 delete $heap->{client};
340 die "Usage:\n\n freeside-selfservice-xmlrpcd user\n";