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 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
|
package Mojo::Server::Prefork;
use Mojo::Base 'Mojo::Server::Daemon';
use Fcntl ':flock';
use File::Spec::Functions qw(catfile tmpdir);
use IO::Poll qw(POLLIN POLLPRI);
use List::Util 'shuffle';
use Mojo::Util 'steady_time';
use POSIX 'WNOHANG';
use Scalar::Util 'weaken';
use Time::HiRes ();
has accepts => 1000;
has [qw(accept_interval multi_accept)];
has [qw(cleanup lock_timeout)] => 1;
has [qw(graceful_timeout heartbeat_timeout)] => 20;
has heartbeat_interval => 5;
has lock_file => sub { catfile tmpdir, 'prefork.lock' };
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->{lock_file}) { unlink $file if -w $file }
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 run {
my $self = shift;
# No Windows support
say 'Preforking not available for Windows.' and exit 0 if $^O eq 'MSWin32';
# Prepare lock file and event loop
$self->{lock_file} = $self->lock_file . ".$$";
my $loop = $self->ioloop->max_accepts($self->accepts);
$loop->$_($self->$_ // $loop->$_) for qw(accept_interval multi_accept);
# Pipe for worker communication
pipe($self->{reader}, $self->{writer}) or die "Can't create pipe: $!";
$self->{poll} = IO::Poll->new;
$self->{poll}->mask($self->{reader}, POLLIN | POLLPRI);
# Clean manager environment
local $SIG{INT} = local $SIG{TERM} = sub { $self->_term };
local $SIG{CHLD} = sub {
while ((my $pid = waitpid -1, WNOHANG) > 0) {
$self->app->log->debug("Worker $pid stopped.")
if delete $self->emit(reap => $pid)->{pool}{$pid};
}
};
local $SIG{QUIT} = sub { $self->_term(1) };
local $SIG{TTIN} = sub { $self->workers($self->workers + 1) };
local $SIG{TTOU} = sub {
$self->workers($self->workers - 1) if $self->workers > 0;
return unless $self->workers;
$self->{pool}{shuffle keys %{$self->{pool}}}{graceful} ||= steady_time;
};
# Preload application before starting workers
$self->start->app->log->info("Manager $$ started.");
$self->{running} = 1;
$self->_manage while $self->{running};
}
sub _heartbeat {
my $self = shift;
# Poll for heartbeats
my $poll = $self->{poll};
$poll->poll(1);
return unless $poll->handles(POLLIN | POLLPRI);
return unless $self->{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};
$self->emit(heartbeat => $1) and $w->{time} = $time;
$w->{graceful} ||= $time if $2;
}
}
sub _manage {
my $self = shift;
# Spawn more workers 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->emit('wait')->_heartbeat;
my $interval = $self->heartbeat_interval;
my $ht = $self->heartbeat_timeout;
my $gt = $self->graceful_timeout;
my $time = steady_time;
my $log = $self->app->log;
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("Trying to stop worker $pid gracefully.")
and kill 'QUIT', $pid
if $graceful && !$w->{quit}++;
$w->{force} = 1 if $graceful && $graceful + $gt <= $time;
# Normal stop
$log->debug("Stopping worker $pid.") and kill 'KILL', $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;
# Prepare lock file
my $file = $self->{lock_file};
$self->app->log->error(qq{Can't open lock file "$file": $!})
unless open my $handle, '>', $file;
# Change user/group
$self->setuidgid->cleanup(0);
# Accept mutex
my $loop = $self->ioloop->lock(
sub {
# Blocking ("ualarm" can't be imported on Windows)
my $lock;
if ($_[0]) {
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
my $old = Time::HiRes::ualarm $self->lock_timeout * 1000000;
$lock = flock $handle, LOCK_EX;
Time::HiRes::ualarm $old;
1;
} or $lock = $@ eq "alarm\n" ? 0 : die $@;
}
# Non-blocking
else { $lock = flock $handle, LOCK_EX | LOCK_NB }
return $lock;
}
);
$loop->unlock(sub { flock $handle, LOCK_UN });
# Heartbeat messages (stop sending during graceful stop)
weaken $self;
$loop->recurring(
$self->heartbeat_interval => sub {
my $graceful = shift->max_connections ? 0 : 1;
$self->{writer}->syswrite("$$:$graceful\n") or exit 0;
}
);
# Clean worker environment
$SIG{$_} = 'DEFAULT' for qw(INT TERM CHLD TTIN TTOU);
$SIG{QUIT} = sub { $loop->max_connections(0) };
delete @$self{qw(poll reader)};
$self->app->log->debug("Worker $$ started.");
$loop->start;
exit 0;
}
sub _term {
my ($self, $graceful) = @_;
$self->emit(finish => $graceful)->{finished} = 1;
$self->{graceful} = 1 if $graceful;
}
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 IPv6, SOCKS5 as well as
TLS support, the optional modules L<EV> (4.0+), L<IO::Socket::IP> (0.20+),
L<IO::Socket::Socks> (0.64+) and L<IO::Socket::SSL> (1.84+) will be used
automatically if they are installed. Individual features can also be disabled
with the C<MOJO_NO_IPV6>, 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
Shutdown server immediately.
=head2 QUIT
Shutdown 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 INT, TERM
Stop worker immediately.
=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 accept_interval
my $interval = $prefork->accept_interval;
$prefork = $prefork->accept_interval(0.5);
Interval in seconds for trying to reacquire the accept mutex, passed along to
L<Mojo::IOLoop/"accept_interval">. Note that changing this value can affect
performance and idle CPU usage.
=head2 accepts
my $accepts = $prefork->accepts;
$prefork = $prefork->accepts(100);
Maximum number of connections a worker is allowed to accept before stopping
gracefully, 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, and that worker processes will stop
sending heartbeat messages once the limit has been reached.
=head2 cleanup
my $bool = $prefork->cleanup;
$prefork = $prefork->cleanup($bool);
Delete L</"lock_file"> and L</"pid_file"> automatically once they are 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_intrval;
$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 lock_file
my $file = $prefork->lock_file;
$prefork = $prefork->lock_file('/tmp/prefork.lock');
Full path of accept mutex lock file prefix, to which the process id will be
appended, defaults to a random temporary path.
=head2 lock_timeout
my $timeout = $prefork->lock_timeout;
$prefork = $prefork->lock_timeout(0.5);
Maximum amount of time in seconds a worker may block when waiting for the
accept mutex, defaults to C<1>. Note that changing this value can affect
performance and idle CPU usage.
=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 a random temporary path.
=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 the number of concurrent 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 run
$prefork->run;
Run server.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.
=cut
|