/
Prefork.pm
470 lines (338 loc) · 11 KB
/
Prefork.pm
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
# Copyright (C) 2008-2010, Sebastian Riedel.
package Mojo::Server::Daemon::Prefork;
use strict;
use warnings;
use base 'Mojo::Server::Daemon';
use Carp 'croak';
use IO::File;
use IO::Poll 'POLLIN';
use IO::Socket;
use POSIX qw/setsid WNOHANG/;
use constant DEBUG => $ENV{MOJO_SERVER_DEBUG} || 0;
__PACKAGE__->attr(cleanup_interval => 15);
__PACKAGE__->attr(idle_timeout => 30);
__PACKAGE__->attr(max_clients => 1);
__PACKAGE__->attr(max_requests => 1000);
__PACKAGE__->attr(max_servers => 100);
__PACKAGE__->attr(max_spare_servers => 10);
__PACKAGE__->attr([qw/min_spare_servers start_servers/] => 5);
use constant CHUNK_SIZE => $ENV{MOJO_CHUNK_SIZE} || 8192;
# Marge? Since I'm not talking to Lisa,
# would you please ask her to pass me the syrup?
# Dear, please pass your father the syrup, Lisa.
# Bart, tell Dad I will only pass the syrup if it won't be used on any meat
# product.
# You dunkin' your sausages in that syrup homeboy?
# Marge, tell Bart I just want to drink a nice glass of syrup like I do every
# morning.
# Tell him yourself, you're ignoring Lisa, not Bart.
# Bart, thank your mother for pointing that out.
# Homer, you're not not-talking to me and secondly I heard what you said.
# Lisa, tell your mother to get off my case.
# Uhhh, dad, Lisa's the one you're not talking to.
# Bart, go to your room.
sub accept_lock {
my ($self, $blocking) = @_;
# Idle
$self->child_status('idle') if $blocking;
# Lock
my $lock = $self->SUPER::accept_lock($blocking);
# Busy
$self->child_status('busy') if $lock;
return $lock;
}
sub child { shift->ioloop->start }
sub child_status {
my ($self, $status) = @_;
$self->{_child_write}->syswrite("$$ $status\n")
or croak "Can't write to parent: $!";
}
sub daemonize {
my $self = shift;
# Fork and kill parent
croak "Can't fork: $!" unless defined(my $child = fork);
exit 0 if $child;
setsid() or croak "Can't start a new session: $!";
# Close file handles
open STDIN, '</dev/null';
open STDOUT, '>/dev/null';
open STDERR, '>&STDOUT';
# Change paths
chdir '/';
umask(0);
$ENV{PATH} = '/bin:/sbin:/usr/bin:/usr/sbin';
return $$;
}
sub parent {
my $self = shift;
# Prepare ioloop
$self->prepare_ioloop;
}
sub run {
my $self = shift;
# PID file
$self->prepare_pid_file;
# No windows support
die "Prefork daemon not available for Windows.\n" if $^O eq 'MSWin32';
# Pipe for child communication
pipe($self->{_child_read}, $self->{_child_write})
or croak "Can't create pipe: $!";
$self->{_child_poll} = IO::Poll->new;
$self->{_child_poll}->mask($self->{_child_read}, POLLIN);
# Parent signals
my $done = 0;
$SIG{INT} = $SIG{TERM} = sub { $done++ };
$SIG{CHLD} = sub { $self->_reap_child };
$SIG{USR1} = sub {
# Reload app
delete $self->{app};
$self->app;
# Bring all children to a greceful shutdown
my $children = $self->{_children} || {};
kill 'HUP', $_ for keys %$children;
};
# Preload application
$self->app;
# Parent stuff
$self->parent;
$self->app->log->debug('Prefork parent started.') if DEBUG;
# Prefork
$self->_spawn_child for (1 .. $self->start_servers);
# We try to make spawning and killing as smooth as possible
$self->{_cleanup} = time + $self->cleanup_interval;
$self->{_spawn} = 1;
# Mainloop
while (!$done) {
$self->_read_messages;
$self->_manage_children;
}
# Kill em all
$self->_kill_children;
exit 0;
}
sub _cleanup_children {
my $self = shift;
my $children = $self->{_children} || {};
for my $pid (keys %$children) {
delete $self->_children->{$pid} unless kill 0, $pid;
}
}
sub _kill_children {
my $self = shift;
# Close pipe
$self->{_child_read} = undef;
# Kill all children
my $children = $self->{_children} || {};
while (%$children) {
# Die die die
for my $pid (keys %$children) {
$self->app->log->debug("Killing prefork child $pid.") if DEBUG;
kill 'TERM', $pid;
}
# Cleanup
$self->_cleanup_children;
# Wait
sleep 1;
}
# Remove PID file
unlink $self->pid_file;
}
sub _manage_children {
my $self = shift;
# Make sure we have enough idle processes
my $children = $self->{_children} || {};
my @idle = sort { $a <=> $b }
grep { ($children->{$_}->{state} || '') eq 'idle' }
keys %$children;
# Debug
if (DEBUG) {
my $idle = @idle;
my $total = keys %$children;
my $spawn = $self->{_spawn};
$self->app->log->debug(
"$idle of $total children idle, 1 listen (spawn $spawn).");
}
# Need more children
if (@idle < $self->min_spare_servers) {
for (1 .. $self->{_spawn}) {
last if $self->max_servers <= keys %$children;
$self->_spawn_child;
}
# Spawn counter
$self->{_spawn} = $self->{_spawn} * 2;
$self->{_spawn} = 8 if $self->{_spawn} > 8;
}
# Too many children
elsif ((@idle > $self->max_spare_servers)) {
# Kill one at a time
my $timeout = time - $self->idle_timeout;
for my $idle (@idle) {
next unless $timeout > $children->{$idle}->{time};
kill 'HUP', $idle;
$self->app->log->debug("Prefork child $idle stopped.") if DEBUG;
# Spawn counter
$self->{_spawn} = $self->{_spawn} / 2 if $self->{_spawn} >= 2;
last;
}
}
# Remove dead child processes every 30 seconds
if (time > $self->{_cleanup}) {
$self->_cleanup_children;
$self->{_cleanup} = time + $self->cleanup_interval;
}
}
sub _read_messages {
my $self = shift;
# Read messages
my $poll = $self->{_child_poll};
$poll->poll(1);
my @readers = $poll->handles(POLLIN);
my $buffer = '';
if (@readers) {
return unless $self->{_child_read}->sysread(my $chunk, CHUNK_SIZE);
$buffer .= $chunk;
}
# Parse messages
my $pos = 0;
while (length $buffer) {
# Full message
$pos = index $buffer, "\n";
last if $pos < 0;
# Parse
my $message = substr $buffer, 0, $pos + 1, '';
next unless $message =~ /^(\d+)\ (\w+)\n$/;
my $pid = $1;
my $state = $2;
# Update status
if ($state eq 'done') { delete $self->{_children}->{$pid} }
else {
$self->{_children}->{$pid} = {
state => $state,
time => time
};
}
}
}
sub _reap_child {
my $self = shift;
while ((my $child = waitpid(-1, WNOHANG)) > 0) {
$self->app->log->debug("Prefork child $child died.") if DEBUG;
delete $self->{_children}->{$child};
}
}
sub _spawn_child {
my $self = shift;
# Fork
croak "Can't fork: $!" unless defined(my $child = fork);
# Parent takes care of child
if ($child) {
$self->{_children}->{$child} = {state => 'idle', time => time};
}
# Child
else {
# Prepare environment
$self->prepare_lock_file;
# Signal handlers
$SIG{HUP} = $SIG{INT} = $SIG{TERM} = sub { exit 0 };
$SIG{CHLD} = 'DEFAULT';
}
# Do child stuff
unless ($child) {
$self->app->log->debug('Prefork child started.') if DEBUG;
# No need for child reader
close($self->{_child_read});
delete $self->{_child_poll};
# Parent will send a HUP signal when there are too many children idle
my $done = 0;
$SIG{HUP} = sub { $self->ioloop->max_connections(0) };
# User and group
$self->setuidgid;
# Spin
while (!$done) {
$self->child;
$done++ if $self->ioloop->max_connections <= 0;
}
# Done
$self->child_status('done');
delete $self->{_child_write};
exit 0;
}
return $child;
}
1;
__END__
=head1 NAME
Mojo::Server::Daemon::Prefork - Preforking HTTP 1.1 And WebSocket Server
=head1 SYNOPSIS
use Mojo::Daemon::Prefork;
my $daemon = Mojo::Daemon::Prefork->new;
$daemon->port(8080);
$daemon->run;
=head1 DESCRIPTION
L<Mojo::Server::Daemon::Prefork> is a full featured preforking HTTP 1.1 and
WebSocket server using a dynamic worker pool with C<IPv6>, C<TLS>, C<epoll>,
C<kqueue>, hot deployment, UNIX domain socket sharing and optional async io
support.
Optional modules L<IO::KQueue>, L<IO::Epoll>, L<IO::Socket::INET6> and
L<IO::Socket::SSL> are supported transparently and used if installed.
=head1 ATTRIBUTES
L<Mojo::Server::Daemon::Prefork> inherits all attributes from
L<Mojo::Server::Daemon> and implements the following new ones.
=head2 C<cleanup_interval>
my $cleanup_interval = $daemon->cleanup_interval;
$daemon = $daemon->cleanup_interval(15);
Cleanup interval for workers in seconds, defaults to C<15>.
=head2 C<idle_timeout>
my $idle_timeout = $daemon->idle_timeout;
$daemon = $daemon->idle_timeout(30);
Timeout for workers to be idle in seconds, defaults to C<30>.
=head2 C<max_clients>
my $max_clients = $daemon->max_clients;
$daemon = $daemon->max_clients(1);
Maximum number of parallel client connections handled by worker, defaults to
C<1>.
=head2 C<max_requests>
my $max_requests = $daemon->max_requests;
$daemon = $daemon->max_requests(1);
Maximum number of requests a worker process is allowed to handle, defaults to
C<1000>.
=head2 C<max_servers>
my $max_servers = $daemon->max_servers;
$daemon = $daemon->max_servers(100);
Maximum number of active workers, defaults to C<100>.
=head2 C<max_spare_servers>
my $max_spare_servers = $daemon->max_spare_servers;
$daemon = $daemon->max_spare_servers(10);
Maximum number of idle workers, default to C<10>.
=head2 C<min_spare_servers>
my $min_spare_servers = $daemon->min_spare_servers;
$daemon = $daemon->min_spare_servers(5);
Minimal number of idle workers, defaults to C<5>.
=head2 C<start_servers>
my $start_servers = $daemon->start_servers;
$daemon = $daemon->start_servers(5);
Number of workers to spawn at server startup, defaults to C<5>.
=head1 METHODS
L<Mojo::Server::Daemon::Prefork> inherits all methods from
L<Mojo::Server::Daemon> and implements the following new ones.
=head2 C<accept_lock>
my $lock = $daemon->accept_lock($blocking);
Try to get the accept lock.
=head2 C<child>
$daemon->child;
Worker process.
=head2 C<child_status>
$daemon->child_status('idle');
Change status for worker process.
=head2 C<daemonize>
$daemon->daemonize;
Daemonize manager process.
=head2 C<parent>
$daemon->parent;
Manager process.
=head2 C<run>
$daemon->run;
Start server.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.
=cut