/usr/share/perl5/Mojo/Server/Prefork.pm is in libmojolicious-perl 6.15+dfsg-1ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | package Mojo::Server::Prefork;
use Mojo::Base 'Mojo::Server::Daemon';
use File::Spec::Functions qw(catfile tmpdir);
use Mojo::Util 'steady_time';
use POSIX 'WNOHANG';
use Scalar::Util 'weaken';
has accepts => 1000;
has cleanup => 1;
has [qw(graceful_timeout heartbeat_timeout)] => 20;
has heartbeat_interval => 5;
has 'multi_accept';
has pid_file => sub { catfile tmpdir, 'prefork.pid' };
has workers => 4;
sub DESTROY {
my $self = shift;
# Worker
return unless $self->cleanup;
# Manager
if (my $file = $self->pid_file) { unlink $file if -w $file }
}
sub check_pid {
my $file = shift->pid_file;
return undef unless open my $handle, '<', $file;
my $pid = <$handle>;
chomp $pid;
# Running
return $pid if $pid && kill 0, $pid;
# Not running
unlink $file if -w $file;
return undef;
}
sub ensure_pid_file {
my $self = shift;
# Check if PID file already exists
return if -e (my $file = $self->pid_file);
# Create PID file
$self->app->log->info(qq{Creating process id file "$file"});
die qq{Can't create process id file "$file": $!}
unless open my $handle, '>', $file;
chmod 0644, $handle;
print $handle $$;
}
sub healthy {
scalar grep { $_->{healthy} } values %{shift->{pool}};
}
sub run {
my $self = shift;
# No Windows support
say 'Preforking is not available for Windows.' and exit 0
if $^O eq 'MSWin32';
# Prepare event loop
my $loop = $self->ioloop->max_accepts($self->accepts);
if (defined(my $multi = $self->multi_accept)) { $loop->multi_accept($multi) }
# Pipe for worker communication
pipe($self->{reader}, $self->{writer}) or die "Can't create pipe: $!";
# Clean manager environment
local $SIG{CHLD} = sub {
while ((my $pid = waitpid -1, WNOHANG) > 0) {
$self->emit(reap => $pid)->_stopped($pid);
}
};
local $SIG{INT} = local $SIG{TERM} = sub { $self->_term };
local $SIG{QUIT} = sub { $self->_term(1) };
local $SIG{TTIN} = sub { $self->workers($self->workers + 1) };
local $SIG{TTOU} = sub {
$self->workers > 0 ? $self->workers($self->workers - 1) : return;
for my $w (values %{$self->{pool}}) {
($w->{graceful} = steady_time) and last unless $w->{graceful};
}
};
# Preload application before starting workers
$self->start->app->log->info("Manager $$ started");
$self->{running} = 1;
$self->_manage while $self->{running};
}
sub _heartbeat { shift->{writer}->syswrite("$$:$_[0]\n") or exit 0 }
sub _manage {
my $self = shift;
# Spawn more workers if necessary and check PID file
if (!$self->{finished}) {
$self->_spawn while keys %{$self->{pool}} < $self->workers;
$self->ensure_pid_file;
}
# Shutdown
elsif (!keys %{$self->{pool}}) { return delete $self->{running} }
# Wait for heartbeats
$self->_wait;
my $interval = $self->heartbeat_interval;
my $ht = $self->heartbeat_timeout;
my $gt = $self->graceful_timeout;
my $log = $self->app->log;
my $time = steady_time;
for my $pid (keys %{$self->{pool}}) {
next unless my $w = $self->{pool}{$pid};
# No heartbeat (graceful stop)
$log->error("Worker $pid has no heartbeat, restarting")
and $w->{graceful} = $time
if !$w->{graceful} && ($w->{time} + $interval + $ht <= $time);
# Graceful stop with timeout
my $graceful = $w->{graceful} ||= $self->{graceful} ? $time : undef;
$log->debug("Stopping worker $pid gracefully")
and (kill 'QUIT', $pid or $self->_stopped($pid))
if $graceful && !$w->{quit}++;
$w->{force} = 1 if $graceful && $graceful + $gt <= $time;
# Normal stop
$log->debug("Stopping worker $pid")
and (kill 'KILL', $pid or $self->_stopped($pid))
if $w->{force} || ($self->{finished} && !$graceful);
}
}
sub _spawn {
my $self = shift;
# Manager
die "Can't fork: $!" unless defined(my $pid = fork);
return $self->emit(spawn => $pid)->{pool}{$pid} = {time => steady_time}
if $pid;
# Heartbeat messages
my $loop = $self->cleanup(0)->ioloop;
my $finished = 0;
$loop->on(finish => sub { $finished = 1 });
weaken $self;
my $cb = sub { $self->_heartbeat($finished) };
$loop->next_tick($cb);
$loop->recurring($self->heartbeat_interval => $cb);
# Clean worker environment
$SIG{$_} = 'DEFAULT' for qw(CHLD INT TERM TTIN TTOU);
$SIG{QUIT} = sub { $loop->stop_gracefully };
delete $self->{reader};
srand;
$self->app->log->debug("Worker $$ started");
$loop->start;
exit 0;
}
sub _stopped {
my ($self, $pid) = @_;
return unless my $w = delete $self->{pool}{$pid};
my $log = $self->app->log;
$log->debug("Worker $pid stopped");
$log->error("Worker $pid stopped too early, shutting down") and $self->_term
unless $w->{healthy};
}
sub _term {
my ($self, $graceful) = @_;
@{$self->emit(finish => $graceful)}{qw(finished graceful)} = (1, $graceful);
}
sub _wait {
my $self = shift;
# Poll for heartbeats
my $reader = $self->emit('wait')->{reader};
return unless Mojo::Util::_readable(1000, fileno($reader));
return unless $reader->sysread(my $chunk, 4194304);
# Update heartbeats (and stop gracefully if necessary)
my $time = steady_time;
while ($chunk =~ /(\d+):(\d)\n/g) {
next unless my $w = $self->{pool}{$1};
@$w{qw(healthy time)} = (1, $time) and $self->emit(heartbeat => $1);
$w->{graceful} ||= $time if $2;
}
}
1;
=encoding utf8
=head1 NAME
Mojo::Server::Prefork - Preforking non-blocking I/O HTTP and WebSocket server
=head1 SYNOPSIS
use Mojo::Server::Prefork;
my $prefork = Mojo::Server::Prefork->new(listen => ['http://*:8080']);
$prefork->unsubscribe('request');
$prefork->on(request => sub {
my ($prefork, $tx) = @_;
# Request
my $method = $tx->req->method;
my $path = $tx->req->url->path;
# Response
$tx->res->code(200);
$tx->res->headers->content_type('text/plain');
$tx->res->body("$method request for $path!");
# Resume transaction
$tx->resume;
});
$prefork->run;
=head1 DESCRIPTION
L<Mojo::Server::Prefork> is a full featured, UNIX optimized, preforking
non-blocking I/O HTTP and WebSocket server, built around the very well tested
and reliable L<Mojo::Server::Daemon>, with IPv6, TLS, Comet (long polling),
keep-alive and multiple event loop support. Note that the server uses signals
for process management, so you should avoid modifying signal handlers in your
applications.
For better scalability (epoll, kqueue) and to provide non-blocking name
resolution, SOCKS5 as well as TLS support, the optional modules L<EV> (4.0+),
L<Net::DNS::Native> (0.15+), L<IO::Socket::Socks> (0.64+) and
L<IO::Socket::SSL> (1.84+) will be used automatically if possible. Individual
features can also be disabled with the C<MOJO_NO_NDN>, C<MOJO_NO_SOCKS> and
C<MOJO_NO_TLS> environment variables.
See L<Mojolicious::Guides::Cookbook/"DEPLOYMENT"> for more.
=head1 MANAGER SIGNALS
The L<Mojo::Server::Prefork> manager process can be controlled at runtime with
the following signals.
=head2 INT, TERM
Shut down server immediately.
=head2 QUIT
Shut down server gracefully.
=head2 TTIN
Increase worker pool by one.
=head2 TTOU
Decrease worker pool by one.
=head1 WORKER SIGNALS
L<Mojo::Server::Prefork> worker processes can be controlled at runtime with the
following signals.
=head2 QUIT
Stop worker gracefully.
=head1 EVENTS
L<Mojo::Server::Prefork> inherits all events from L<Mojo::Server::Daemon> and
can emit the following new ones.
=head2 finish
$prefork->on(finish => sub {
my ($prefork, $graceful) = @_;
...
});
Emitted when the server shuts down.
$prefork->on(finish => sub {
my ($prefork, $graceful) = @_;
say $graceful ? 'Graceful server shutdown' : 'Server shutdown';
});
=head2 heartbeat
$prefork->on(heartbeat => sub {
my ($prefork, $pid) = @_;
...
});
Emitted when a heartbeat message has been received from a worker.
$prefork->on(heartbeat => sub {
my ($prefork, $pid) = @_;
say "Worker $pid has a heartbeat";
});
=head2 reap
$prefork->on(reap => sub {
my ($prefork, $pid) = @_;
...
});
Emitted when a child process dies.
$prefork->on(reap => sub {
my ($prefork, $pid) = @_;
say "Worker $pid stopped";
});
=head2 spawn
$prefork->on(spawn => sub {
my ($prefork, $pid) = @_;
...
});
Emitted when a worker process is spawned.
$prefork->on(spawn => sub {
my ($prefork, $pid) = @_;
say "Worker $pid started";
});
=head2 wait
$prefork->on(wait => sub {
my $prefork = shift;
...
});
Emitted when the manager starts waiting for new heartbeat messages.
$prefork->on(wait => sub {
my $prefork = shift;
my $workers = $prefork->workers;
say "Waiting for heartbeat messages from $workers workers";
});
=head1 ATTRIBUTES
L<Mojo::Server::Prefork> inherits all attributes from L<Mojo::Server::Daemon>
and implements the following new ones.
=head2 accepts
my $accepts = $prefork->accepts;
$prefork = $prefork->accepts(100);
Maximum number of connections a worker is allowed to accept before stopping
gracefully and then getting replaced with a newly started worker, passed along
to L<Mojo::IOLoop/"max_accepts">, defaults to C<1000>. Setting the value to
C<0> will allow workers to accept new connections indefinitely. Note that up to
half of this value can be subtracted randomly to improve load balancing.
=head2 cleanup
my $bool = $prefork->cleanup;
$prefork = $prefork->cleanup($bool);
Delete L</"pid_file"> automatically once it is not needed anymore, defaults to
a true value.
=head2 graceful_timeout
my $timeout = $prefork->graceful_timeout;
$prefork = $prefork->graceful_timeout(15);
Maximum amount of time in seconds stopping a worker gracefully may take before
being forced, defaults to C<20>.
=head2 heartbeat_interval
my $interval = $prefork->heartbeat_interval;
$prefork = $prefork->heartbeat_interval(3);
Heartbeat interval in seconds, defaults to C<5>.
=head2 heartbeat_timeout
my $timeout = $prefork->heartbeat_timeout;
$prefork = $prefork->heartbeat_timeout(2);
Maximum amount of time in seconds before a worker without a heartbeat will be
stopped gracefully, defaults to C<20>.
=head2 multi_accept
my $multi = $prefork->multi_accept;
$prefork = $prefork->multi_accept(100);
Number of connections to accept at once, passed along to
L<Mojo::IOLoop/"multi_accept">.
=head2 pid_file
my $file = $prefork->pid_file;
$prefork = $prefork->pid_file('/tmp/prefork.pid');
Full path of process id file, defaults to C<prefork.pid> in a temporary
directory.
=head2 workers
my $workers = $prefork->workers;
$prefork = $prefork->workers(10);
Number of worker processes, defaults to C<4>. A good rule of thumb is two
worker processes per CPU core for applications that perform mostly non-blocking
operations, blocking operations often require more and benefit from decreasing
concurrency with L<Mojo::Server::Daemon/"clients"> (often as low as C<1>).
=head1 METHODS
L<Mojo::Server::Prefork> inherits all methods from L<Mojo::Server::Daemon> and
implements the following new ones.
=head2 check_pid
my $pid = $prefork->check_pid;
Get process id for running server from L</"pid_file"> or delete it if server is
not running.
say 'Server is not running' unless $prefork->check_pid;
=head2 ensure_pid_file
$prefork->ensure_pid_file;
Ensure L</"pid_file"> exists.
=head2 healthy
my $healthy = $prefork->healthy;
Number of currently active worker processes with a heartbeat.
=head2 run
$prefork->run;
Run server.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.
=cut
|