blib/lib/Net/Waiter.pm untested

filter: Statementstmt 0.0% 0 / 425 Branchbran 0.0% 0 / 108 Conditioncond 0.0% 0 / 38 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 0.0% 0 / 66 Podpod 0.0% 0 / 59 totaltotal 0.0% 0 / 716 CC 55 SCAR 37.3
CC
55
Cov
0%
__run_prefork
156.0
run
132.0
new
72.0
CRAP 41.8
1 ##############################################################################
2 #
3 # Net::Waiter concise INET socket server
4 # (c) Vladi Belperchinov-Shabanski "Cade" 2015-2024
5 # http://cade.noxrun.com
6 # <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
7 #
8 # GPL
9 #
10 ##############################################################################
11 package Net::Waiter;
12 use strict;
13 use POSIX ":sys_wait_h";
14 use IO::Socket::INET;
15 use Sys::SigAction qw( set_sig_handler );
16 use IPC::Shareable;
17 use Data::Dumper;
18  
19 our $VERSION = '1.19';
20  
21 $Data::Dumper::Terse = 1;
22
23 ##############################################################################
24
25 sub new
26 {
27 my $class = shift;
28 $class = ref( $class ) || $class;
29
30 my %opt = @_;
31
32 my $self = {
33 PORT => $opt{ 'PORT' }, # which port to listen on
34 PREFORK => $opt{ 'PREFORK' }, # how many preforked processes, 0 means forking server
35 MAXFORK => $opt{ 'MAXFORK' } || 1024, # max count of forked processes
36 NOFORK => $opt{ 'NOFORK' }, # foreground process
37 TIMEOUT => $opt{ 'TIMEOUT' } || 4, # timeout for accept(), default 4 seconds
38  
39 PX_IDLE => $opt{ 'PX_IDLE' } || 31, # process exit idle, used in preforked processes
40
41 PROP_SIGUSR => $opt{ 'PROP_SIGUSR' },
42  
43 DEBUG => $opt{ 'DEBUG' }, # debug level, true to enable or positive number for debug level
44
45 SSL => $opt{ 'SSL' }, # use SSL
46 OPT => \%opt,
47 };
48  
49 if( $opt{ 'SSL' } )
50 {
51 $self->{ 'SSL_OPTS' } = {};
52 while( my ( $k, $v ) = each %opt )
53 {
54 next unless $k =~ /^SSL_/;
55 $self->{ 'SSL_OPTS' }{ $k } = $v;
56 }
57 }
58  
59 my $pf = $self->{ 'PREFORK' };
60 my $mf = $self->{ 'MAXFORK' };
61 if( $pf < 0 )
62 {
63 # if PREFORK is negative, it will be absolute prefork and maxfork count
64 $self->{ 'PREFORK' } = abs( $pf );
65 $self->{ 'MAXFORK' } = abs( $pf ) unless $mf > 0;
66 }
67  
68 # timeout cap
69 $self->{ 'TIMEOUT' } = 1 if $self->{ 'TIMEOUT' } < 1; # avoid busyloop
70 $self->{ 'TIMEOUT' } = 3600 if $self->{ 'TIMEOUT' } > 3600; # 1 hour max should be enough :)
71  
72 $self->{ 'PX_IDLE' } = 31 if $self->{ 'PX_IDLE' } < 1;
73
74 bless $self, $class;
75 return $self;
76 }
77  
78 ##############################################################################
79  
80 sub run
81 {
82 my $self = shift;
83  
84 $self->{ 'PARENT_PID' } = $$;
85  
86 if( $self->ssl_in_use() )
87 {
88 eval { require IO::Socket::SSL; };
89 die "SSL not available: $@" if $@;
90 };
91  
92 $SIG{ 'INT' } = sub { $self->break_main_loop(); };
93 $SIG{ 'TERM' } = sub { $self->break_main_loop(); };
94 $SIG{ 'CHLD' } = sub { $self->__sig_child(); };
95 $SIG{ 'HUP' } = sub { $self->__sig_hup(); };
96 $SIG{ 'USR1' } = sub { $self->__sig_usr1(); };
97 $SIG{ 'USR2' } = sub { $self->__sig_usr2(); };
98 $SIG{ 'RTMIN' } = sub { $self->__sig_kid_idle() };
99 $SIG{ 'RTMAX' } = sub { $self->__sig_kid_busy() };
100  
101 srand();
102  
103 $self->on_server_begin();
104  
105 my $server_socket;
106  
107 my $sock_pkg;
108 my %sock_opts;
109 if( $self->ssl_in_use() )
110 {
111 my %sock_opts = %{ $self->{ 'SSL_OPTS' } };
112 $sock_opts{ 'SSL_error_trap' } = sub { shift; $self->on_ssl_error( shift() ); },
113 $sock_pkg = 'IO::Socket::SSL';
114 }
115 else
116 {
117 $sock_pkg = 'IO::Socket::INET';
118 }
119  
120 $server_socket = $sock_pkg->new(
121 Proto => 'tcp',
122 LocalPort => $self->{ 'PORT' },
123 Listen => 128,
124 ReuseAddr => 1,
125 Blocking => 0,
126  
127 %sock_opts,
128 );
129  
130 if( ! $server_socket )
131 {
132 # cannot open server port
133 return 100;
134 }
135 else
136 {
137 binmode( $server_socket );
138 $self->{ 'SERVER_SOCKET' } = $server_socket;
139 $self->on_listen_ok();
140 }
141  
142 $self->__reinstall_sha();
143  
144 while(4)
145 {
146 last if $self->{ 'BREAK_MAIN_LOOP' };
147
148 if( $self->{ 'PREFORK' } > 0 )
149 {
150 $self->__run_prefork( $server_socket );
151 sleep(4); # will be interrupted by busy/free signals
152 }
153 else
154 {
155 $self->__run_forking( $server_socket );
156 # no need for sleep since, select/accept will block for a while (4 sec)
157 }
158  
159 eval
160 {
161 $self->__sha_lock_rw( 'MASTER STATS UPDATE' );
162  
163 $self->{ 'KIDS_BUSY' } = 0;
164 for my $cpid ( keys %{ $self->{ 'SHA' }{ 'PIDS' } } )
165 {
166 next unless $cpid > 0;
167 if( ! exists $self->{ 'KID_PIDS' }{ $cpid } )
168 {
169 delete $self->{ 'SHA' }{ 'PIDS' }{ $cpid };
170 }
171 else
172 {
173 my $v = $self->{ 'SHA' }{ 'PIDS' }{ $cpid };
174 my ( $b, $c ) = split /:/, $v;
175 $self->{ 'KIDS_BUSY' }++ if $b eq '*';
176 }
177 }
178 $self->{ 'STAT' }{ 'BUSY_COUNT' } = $self->{ 'SHA' }{ 'STAT' }{ 'BUSY_COUNT' };
179  
180 $self->__sha_unlock( 'MASTER STATS UPDATE' );
181 };
182 if( $@ )
183 {
184 $self->log( "error: main loop kids stats management: $@" );
185 $self->log( "status: reinstalling SHA, trying to recover..." );
186  
187 eval
188 {
189 $self->__sha_unlock( 'MASTER STATS UPDATE' );
190 };
191 # do not need result, if cannot be unlocked there is far bigger problem
192  
193 $self->stop_all_kids( 'TERM' );
194 $self->stop_all_kids( 'KILL' );
195 sleep(1);
196
197 $self->{ 'KIDS_BUSY' } = 0;
198
199 $self->__reinstall_sha();
200 }
201
202 }
203  
204 $self->stop_all_kids( 'TERM' );
205
206 tied( %{ $self->{ 'SHA' } } )->clean_up();
207 delete $self->{ 'SHA' };
208  
209 $self->on_server_close( $server_socket );
210 close( $server_socket );
211  
212 return 0;
213 }
214  
215 sub __run_forking
216 {
217 my $self = shift;
218 my $server_socket = shift;
219  
220 if( ! socket_can_read( $server_socket, $self->{ 'TIMEOUT' } ) )
221 {
222 $self->on_forking_idle();
223 return '0E0';
224 }
225  
226 my $client_socket = $server_socket->accept() or return '0E0';
227 if( ! $client_socket )
228 {
229 $self->on_accept_error();
230 return;
231 }
232  
233 binmode( $client_socket );
234 $self->{ 'CLIENT_SOCKET' } = $client_socket;
235  
236 my $peerhost = $client_socket->peerhost();
237 my $peerport = $client_socket->peerport();
238 my $sockhost = $client_socket->sockhost();
239 my $sockport = $client_socket->sockport();
240  
241 $self->on_accept_ok( $client_socket );
242
243 my $mf = $self->{ 'MAXFORK' };
244 if( $mf > 0 and $self->{ 'KIDS' } >= $mf )
245 {
246 $self->on_maxforked( $client_socket );
247 $self->on_close( $client_socket );
248 $client_socket->close();
249 return;
250 }
251  
252 my $pid;
253 if( ! $self->{ 'NOFORK' } )
254 {
255 $pid = fork();
256 if( ! defined $pid )
257 {
258 die "fatal: fork failed: $!";
259 }
260 if( $pid )
261 {
262 $self->{ 'FORKS' }++;
263 $self->{ 'KIDS' }++;
264 $self->{ 'KID_PIDS' }{ $pid } = 1;
265 $self->on_fork_ok( $pid );
266 $client_socket->close();
267 next;
268 }
269 }
270 # --------- kid here ---------
271 $self->{ 'CHILD' } = 1;
272 delete $self->{ 'SERVER_SOCKET' };
273 delete $self->{ 'KIDS' };
274 delete $self->{ 'KID_PIDS' };
275  
276 # reinstall signal handlers in the kid
277 $SIG{ 'INT' } = sub { $self->break_main_loop(); };
278 $SIG{ 'TERM' } = sub { $self->break_main_loop(); };
279 $SIG{ 'HUP' } = sub { $self->__child_sig_hup(); };
280 $SIG{ 'USR1' } = sub { $self->__child_sig_usr1(); };
281 $SIG{ 'USR2' } = sub { $self->__child_sig_usr2(); };
282 $SIG{ 'RTMIN' } = sub { $self->__sig_kid_idle() };
283 $SIG{ 'RTMAX' } = sub { $self->__sig_kid_busy() };
284 # ignored here, if smb needs it, should reinstall
285 $SIG{ 'CHLD' } = 'IGNORE';
286  
287 $self->{ 'SHA' } = new IPC::Shareable key => $self->{ 'SHA_KEY' } or die "fatal: cannot attach shared memory segment\n";
288  
289 srand();
290  
291 $client_socket->autoflush( 1 );
292 $self->on_child_start();
293  
294 $self->im_busy();
295 $self->on_process( $client_socket );
296 $self->on_close( $client_socket );
297 $client_socket->close();
298 $self->im_idle();
299
300 $self->on_child_exit();
301  
302 if( ! $self->{ 'NOFORK' } )
303 {
304 exit();
305 }
306 # ------- child exits here -------
307 }
308  
309 my $__prefork_next_stat = time() + 4;
310 sub __run_prefork
311 {
312 my $self = shift;
313 my $server_socket = shift;
314  
315 my $prefork_count = $self->{ 'PREFORK' };
316  
317 my $kk = $self->{ 'KIDS' }; # kids k'ount ;)
318 my $bk = $self->get_busy_kids_count(); # busy count
319 my $ik = $kk - $bk; # idle kids count
320  
321 my $tk = $prefork_count;
322 #$tk = $kk + $prefork_count / 2 if $kk > $prefork_count and $ik < ( 1 + $prefork_count / 10 );
323 $tk = $kk + $prefork_count if $ik <= ( 1 + $kk / 10 );
324  
325 my $mf = $self->{ 'MAXFORK' };
326 $tk = $mf if $mf > 0 and $tk > $mf; # MAXFORK cap
327  
328 if( time() > $__prefork_next_stat )
329 {
330 $self->{ 'STAT' }{ 'IDLE_FREQ' }{ int( $ik / 5 ) * 5 }++ if $bk > 0;
331 $self->__prefork_print_stat() if $self->{ 'DEBUG' };
332 $__prefork_next_stat = time() + 4;
333 }
334 my $tbk = $self->{ 'STAT' }{ 'BUSY_COUNT' };
335 $self->log_debug( "debug: kids: $kk busy: $bk idle: $ik to_fork: $tk will_fork?: $kk < $tk total busy count: $tbk" );
336  
337 while( $self->{ 'KIDS' } < $tk )
338 {
339 my $pid;
340 $pid = fork();
341 if( ! defined $pid )
342 {
343 die "fatal: fork failed: $!";
344 }
345 if( $pid )
346 {
347 $self->{ 'FORKS' }++;
348 $self->{ 'KIDS' }++;
349 $self->{ 'KID_PIDS' }{ $pid } = 1;
350 $self->on_fork_ok( $pid );
351 $self->{ 'STAT' }{ 'SPAWNS' }++;
352 }
353 else
354 {
355 # --------- child here ---------
356 $self->{ 'CHILD' } = 1;
357 $self->{ 'SPTIME' } = time();
358 delete $self->{ 'SERVER_SOCKET' };
359 delete $self->{ 'KIDS' };
360 delete $self->{ 'KID_PIDS' };
361  
362 # reinstall signal handlers in the kid
363 $SIG{ 'INT' } = sub { $self->break_main_loop(); };
364 $SIG{ 'TERM' } = sub { $self->break_main_loop(); };
365 $SIG{ 'HUP' } = sub { $self->__child_sig_hup(); };
366 $SIG{ 'USR1' } = sub { $self->__child_sig_usr1(); };
367 $SIG{ 'USR2' } = sub { $self->__child_sig_usr2(); };
368 $SIG{ 'RTMIN' } = sub { $self->__sig_kid_idle() };
369 $SIG{ 'RTMAX' } = sub { $self->__sig_kid_busy() };
370 # ignored here, if smb needs it, should reinstall
371 $SIG{ 'CHLD' } = 'IGNORE';
372  
373 $self->{ 'SHA' } = new IPC::Shareable key => $self->{ 'SHA_KEY' } or die "fatal: cannot attach shared memory segment\n";
374
375 srand();
376  
377 $self->on_child_start();
378
379 $self->im_idle();
380  
381 my $kid_idle;
382 while(4)
383 {
384 last if $self->{ 'BREAK_MAIN_LOOP' };
385 last unless $self->__run_preforked_child( $server_socket );
386 $kid_idle = $self->{ 'LPTIME' } > 0 ? time() - $self->{ 'LPTIME' } : - ( time() - $self->{ 'SPTIME' } );
387 last if $self->{ 'LPTIME' } > 0 and $kid_idle > $self->{ 'PX_IDLE' };
388  
389 my $tt = $0;
390 $tt =~ s/ \[-?\d+\]//;
391 $0 = $tt . " [$kid_idle]";
392 }
393 $self->on_child_exit();
394  
395 exit;
396 # ------- child exits here -------
397 }
398 }
399 }
400  
401 sub __run_preforked_child
402 {
403 my $self = shift;
404 my $server_socket = shift;
405  
406 if( ! socket_can_read( $server_socket, $self->{ 'TIMEOUT' } ) )
407 {
408 $self->on_prefork_child_idle();
409 return '0E0';
410 }
411  
412 my $client_socket = $server_socket->accept() or return '0E0';
413  
414 binmode( $client_socket );
415 $self->{ 'CLIENT_SOCKET' } = $client_socket;
416  
417 my $peerhost = $client_socket->peerhost();
418 my $peerport = $client_socket->peerport();
419 my $sockhost = $client_socket->sockhost();
420 my $sockport = $client_socket->sockport();
421  
422 $self->on_accept_ok( $client_socket );
423  
424 $self->{ 'BUSY_COUNT' }++;
425 $self->im_busy();
426 $client_socket->autoflush( 1 );
427 my $res = $self->on_process( $client_socket );
428 $self->on_close( $client_socket );
429 $client_socket->close();
430 $self->im_idle();
431  
432 $self->{ 'LPTIME' } = time(); # last processing time
433
434 return $res;
435 }
436  
437 sub __prefork_print_stat
438 {
439 my $self = shift;
440  
441 eval
442 {
443 $self->__sha_lock_ro( 'MASTER SHARED STATE' );
444 $self->log_debug( "debug: shared memory state:\n" . Dumper( $self->{ 'SHA' } ) );
445 $self->__sha_unlock( 'MASTER SHARED STATE' );
446 };
447 if( $@ )
448 {
449 $self->log_debug( "debug: stats unavailable" );
450 return;
451 }
452  
453 $self->log_debug( "debug: stats:\n" . Dumper( $self->{ 'STAT' } ) );
454  
455 my $_c = 10;
456 for my $k ( sort { $self->{ 'STAT' }{ 'IDLE_FREQ' }{ $b } <=> $self->{ 'STAT' }{ 'IDLE_FREQ' }{ $a } } keys %{ $self->{ 'STAT' }{ 'IDLE_FREQ' } } )
457 {
458 my $v = $self->{ 'STAT' }{ 'IDLE_FREQ' }{ $k };
459 $self->log_debug( sprintf( "debug: %3d idle(s) => %3d time(s)", $k, $v ) );
460 last unless $_c--;
461 }
462 }
463  
464 sub stop_all_kids
465 {
466 my $self = shift;
467  
468 my $sig = shift || 'TERM';
469
470 my $wait_time = time();
471 while( $self->{ 'KIDS' } and ( time() - $wait_time < 8 ) )
472 {
473 $self->log( "status: waiting current kids, sending $sig: " . $self->{ 'KIDS' } );
474 $self->propagate_signal( $sig );
475 sleep(1); # will be cancelled on SIGCHILD anyway...
476 }
477
478 return 1;
479 }
480  
481 ##############################################################################
482  
483 sub __reinstall_sha
484 {
485 my $self = shift;
486  
487 tied( %{ $self->{ 'SHA' } } )->clean_up() if $self->{ 'SHA' };
488  
489 my $tm = time();
490 my $sha_key = $self->{ 'SHA_KEY' } = "$0.$$.$tm";
491 $self->{ 'SHA' } = new IPC::Shareable key => $sha_key, size => 256*1024, mode => 0600, create => 1 or die "fatal: cannot create shared memory segment\n";
492
493 # must be initialized, otherwise kids will create own shared memory segments and parent cannot release them! undocumented
494 $self->{ 'SHA' }{ 'PIDS' } = {};
495 $self->{ 'SHA' }{ 'STAT' } = {};
496
497 return 1;
498 }
499  
500 #use Data::Tools;
501 sub __sha_lock_ro
502 {
503 my $self = shift;
504 return $self->__sha_obtain_lock( IPC::Shareable::LOCK_SH, 'SH' );
505 }
506  
507 sub __sha_lock_rw
508 {
509 my $self = shift;
510 return $self->__sha_obtain_lock( IPC::Shareable::LOCK_EX, 'EX' );
511 }
512  
513 sub __sha_unlock
514 {
515 my $self = shift;
516 return $self->__sha_obtain_lock( IPC::Shareable::LOCK_UN, 'UN' );
517 }
518  
519  
520 sub __sha_obtain_lock
521 {
522 my $self = shift;
523 my $op = shift;
524 my $str = shift;
525
526 my $limit = 4;
527 my $rc;
528 while( ! $rc )
529 {
530 $rc = tied( %{ $self->{ 'SHA' } } )->lock( $op );
531 return $rc if $rc;
532 next if $!{EINTR} or $!{EAGAIN};
533 $self->log( "error: cannot obtain $str lock for SHA! [$rc] $! retry in 1 second" );
534 last if $self->{ 'BREAK_MAIN_LOOP' };
535 last unless $limit--;
536 sleep(1);
537 }
538 $self->log( "error: cannot obtain $str lock for SHA! $!" );
539 my $ppid = $self->get_parent_pid();
540 die "error: [$ppid/$$] cannot obtain $str lock for SHA! $!, will exit\n";
541 return undef;
542 }
543  
544 ##############################################################################
545  
546 sub get_server_socket
547 {
548 my $self = shift;
549
550 return exists $self->{ 'SERVER_SOCKET' } ? $self->{ 'SERVER_SOCKET' } : undef;
551 }
552  
553 sub get_client_socket
554 {
555 my $self = shift;
556
557 return exists $self->{ 'CLIENT_SOCKET' } ? $self->{ 'CLIENT_SOCKET' } : undef;
558 }
559  
560 sub get_busy_kids_count
561 {
562 my $self = shift;
563
564 return wantarray ? ( $self->{ 'KIDS_BUSY' }, $self->{ 'KIDS' } ) : $self->{ 'KIDS_BUSY' };
565 }
566  
567 sub get_kids_count
568 {
569 my $self = shift;
570
571 return $self->{ 'KIDS' };
572 }
573  
574 sub get_parent_pid
575 {
576 my $self = shift;
577
578 return $self->{ 'PARENT_PID' };
579 }
580  
581 sub get_kid_pids
582 {
583 my $self = shift;
584  
585 return () if $self->is_child();
586
587 return keys %{ $self->{ 'KID_PIDS' } || {} };
588 }
589  
590 sub im_busy
591 {
592 my $self = shift;
593
594 return $self->__im_in_state( '*' );
595 }
596  
597 sub im_idle
598 {
599 my $self = shift;
600
601 return $self->__im_in_state( '-' );
602 }
603  
604 sub __im_in_state
605 {
606 my $self = shift;
607 my $state = uc shift;
608  
609 my $ppid = $self->get_parent_pid();
610 return 0 if $ppid == $$; # states are available only for kids
611  
612 my $set_state = $state . ":" . $self->{ 'BUSY_COUNT' };
613  
614 $self->__sha_lock_rw( 'KID STATE' );
615 $self->{ 'SHA' }{ 'PIDS' }{ $$ } = $set_state;
616 $self->{ 'SHA' }{ 'STAT' }{ 'BUSY_COUNT' }++ if $state eq '*';
617 $self->__sha_unlock( 'KID STATE' );
618  
619 my $tt = $0;
620 $tt =~ s/ \| .+//;
621 $0 = $tt . ' | ' . $set_state;
622
623 return kill( 'RTMIN', $ppid ) if $state eq '-';
624 return kill( 'RTMAX', $ppid ) if $state eq '*';
625 return 0;
626 }
627  
628 ##############################################################################
629  
630 sub break_main_loop
631 {
632 my $self = shift;
633
634 $self->{ 'BREAK_MAIN_LOOP' } = 1;
635 }
636  
637 sub ssl_in_use
638 {
639 my $self = shift;
640
641 return $self->{ 'SSL' };
642 }
643  
644 sub is_child
645 {
646 my $self = shift;
647
648 return $self->{ 'CHILD' };
649 }
650  
651 sub propagate_signal
652 {
653 my $self = shift;
654 my $sig = shift;
655
656 for my $kpid ( $self->get_kid_pids() )
657 {
658 kill( $sig, $kpid );
659 }
660 }
661  
662 sub __sig_child
663 {
664 my $self = shift;
665  
666 while( ( my $cpid = waitpid( -1, WNOHANG ) ) > 0 )
667 {
668 $self->{ 'KIDS' }--;
669 delete $self->{ 'KID_PIDS' }{ $cpid };
670 $self->on_sig_child( $cpid, $? );
671 }
672 $SIG{ 'CHLD' } = sub { $self->__sig_child(); };
673 }
674  
675 sub __sig_hup
676 {
677 my $self = shift;
678  
679 $self->on_sig_hup();
680 $SIG{ 'HUP ' } = sub { $self->__sig_hup(); };
681 }
682  
683 sub __sig_usr1
684 {
685 my $self = shift;
686  
687 $self->on_sig_usr1();
688 $self->propagate_signal( 'USR1' ) if $self->{ 'PROP_SIGUSR' };
689 $SIG{ 'USR1' } = sub { $self->__sig_usr1(); };
690 }
691  
692 sub __sig_usr2
693 {
694 my $self = shift;
695  
696 $self->on_sig_usr2();
697 $self->propagate_signal( 'USR2' ) if $self->{ 'PROP_SIGUSR' };
698 $SIG{ 'USR2' } = sub { $self->__sig_usr2(); };
699 }
700  
701 sub __child_sig_hup
702 {
703 my $self = shift;
704  
705 $self->on_child_sig_hup();
706 $SIG{ 'HUP' } = sub { $self->__child_sig_hup(); };
707 }
708  
709 sub __child_sig_usr1
710 {
711 my $self = shift;
712  
713 $self->on_child_sig_usr1();
714 $SIG{ 'USR1' } = sub { $self->__child_sig_usr1(); };
715 }
716  
717 sub __child_sig_usr2
718 {
719 my $self = shift;
720  
721 $self->on_child_sig_usr2();
722 $SIG{ 'USR2' } = sub { $self->__child_sig_usr2(); };
723 }
724  
725  
726 # used only for waking up preforked servers main loop sleep
727 sub __sig_kid_idle
728 {
729 my $self = shift;
730  
731 $SIG{ 'RTMIN' } = sub { $self->__sig_kid_idle() };
732 }
733  
734 # used only for waking up preforked servers main loop sleep
735 sub __sig_kid_busy
736 {
737 my $self = shift;
738  
739 $SIG{ 'RTMAX' } = sub { $self->__sig_kid_busy() };
740 }
741  
742 ##############################################################################
743  
744 sub on_server_begin
745 {
746 }
747  
748 sub on_listen_ok
749 {
750 }
751  
752 sub on_accept_error
753 {
754 }
755  
756 sub on_accept_ok
757 {
758 }
759  
760 sub on_fork_ok
761 {
762 }
763  
764 # called when connection is accepted and processing requested on socket data
765 sub on_process
766 {
767 }
768  
769 # called on preforked childs, when accept timeouts
770 sub on_prefork_child_idle
771 {
772 }
773  
774 # called on forking mode parent side, when noone connects in 'TIMEOUT' secods.
775 sub on_forking_idle
776 {
777 }
778  
779 sub on_maxforked
780 {
781 }
782  
783 # called right after fork, in the forked child, after initial setup but just before processing start
784 sub on_child_start
785 {
786 }
787  
788 # called just before forked or preforked child exits
789 sub on_child_exit
790 {
791 }
792  
793 sub on_close
794 {
795 }
796  
797 sub on_server_close
798 {
799 }
800  
801 sub on_ssl_error
802 {
803 }
804  
805 sub on_sig_child
806 {
807 }
808  
809 sub on_sig_hup
810 {
811 }
812  
813 sub on_sig_usr1
814 {
815 }
816  
817 sub on_sig_usr2
818 {
819 }
820  
821 sub on_child_sig_hup
822 {
823 }
824  
825 sub on_child_sig_usr1
826 {
827 }
828  
829 sub on_child_sig_usr2
830 {
831 }
832  
833  
834 ##############################################################################
835  
836 # backported from Data::Tools::Socket to reduce dependency
837 # https://metacpan.org/pod/Data::Tools
838 # https://github.com/cade-vs/perl-data-tools
839  
840 sub socket_can_write
841 {
842 my $sock = shift;
843 my $timeout = shift;
844  
845 my $win;
846 vec( $win, fileno( $sock ), 1 ) = 1;
847 return select( undef, $win, undef, $timeout ) > 0;
848 }
849  
850 sub socket_can_read
851 {
852 my $sock = shift;
853 my $timeout = shift;
854  
855 my $rin;
856 vec( $rin, fileno( $sock ), 1 ) = 1;
857 return select( $rin, undef, undef, $timeout ) > 0;
858 }
859  
860 ##############################################################################
861  
862 # this function is used to log messages including debug. should be reimplemented
863 sub log
864 {
865 my $self = shift;
866 # should be reimplemented
867 print STDERR "$_\n" for @_;
868 }
869  
870 # used for debug log messages when DEBUG is enabled
871 sub log_debug
872 {
873 my $self = shift;
874 return unless $self->{ 'DEBUG' };
875 return $self->log( @_ );
876 }
877  
878 ##############################################################################
879  
880 =pod
881  
882  
883 =head1 NAME
884  
885 Net::Waiter compact INET socket server
886  
887 =head1 SYNOPSIS
888  
889 package MyWaiter;
890 use strict;
891 use parent qw( Net::Waiter );
892  
893 sub on_accept_ok
894 {
895 my $self = shift;
896 my $sock = shift;
897 my $peerhost = $sock->peerhost();
898 print "client connected from $peerhost\n";
899 }
900  
901 sub on_process
902 {
903 my $self = shift;
904 my $sock = shift;
905 print $sock "hello world\n";
906 }
907  
908 #--------------------------------------------------
909  
910 packgage main;
911 use strict;
912 use MyWaiter;
913  
914 my $server = MyWaiter->new( PORT => 9123 );
915 my $res = $server->run();
916 print "waiter result: $res\n"; # 0 is ok, >0 is error
917  
918 =head1 DESCRIPTION
919  
920 Net::Waiter is a base class which implements compact INET network socket server.
921  
922 =head1 METHODS/FUNCTIONS
923  
924 =head2 new( OPTION => VALUE, ... )
925  
926 Creates new Net::Waiter object and sets its options:
927  
928 PORT => 9123, # which port to listen on
929 PREFORK => 8, # how many preforked processes
930 MAXFORK => 32, # max count of preforked processes
931 NOFORK => 0, # if 1 will not fork, only single client will be accepted
932 TIMEOUT => 4, # timeout for accepting connections, defaults to 4 seconds
933 SSL => 1, # use SSL
934  
935 PX_IDLE => 31, # prefork exit idle time, defaults to 31
936  
937 PROP_SIGUSR => 1, # if true, will propagate USR1/USR2 signals to childs
938
939 DEBUG => 1, # enable debug mode, prints debug messages
940  
941 if PREFORK is negative, the absolute value will be used both for PREFORK and
942 MAXFORK counts.
943  
944 if SSL is enabled then additional IO::Socket::SSL options can be added:
945  
946 SSL_cert_file => 'cert.pem',
947 SSL_key_file => 'key.pem',
948 SSL_ca_file => 'ca.pem',
949 SSL_verify_mode => 1,
950  
951 for further details, check IO::Socket::SSL docs. all SSL_ options are allowed.
952
953 =head2 run()
954  
955 This executes server main loop. It will create new server socket, set
956 options (listen port, ssl options, etc.) then fork and call handlers along
957 the way.
958  
959 Run returns exit code:
960  
961 0 -- ok
962 100 -- cannot create server listen socket
963  
964 =head2 break_main_loop()
965  
966 Breaks main server loop. Calling break_main_loop() is possible from parent
967 server process handler functions (see HANDLER FUNCTIONS below) but it will
968 not break the main loop immediately. It will just raise flag which will stop
969 when control is returned to the next server loop.
970  
971 =head2 ssl_in_use()
972  
973 Returns true (1) if current setup uses SSL (useful mostly inside handlers).
974  
975 =head2 is_child()
976  
977 Returns true (1) if this process is client/child process (useful mostly inside handlers).
978  
979 =head2 get_server_socket()
980  
981 Returns server (listening) socket object. Valid in parent only, otherwise returns undef.
982  
983 =head2 get_client_socket()
984  
985 Returns connected client socket.
986  
987 =head2 get_busy_kids_count()
988  
989 Returns the count of all forked busy processes (which are already accepted connection).
990 In array contect returns two integers: busy process count and all forked processes count.
991 This method is accessible from parent and all forked processes and reflect all processes.
992  
993 Returns client (connected) socket object. Valid in kids only, otherwise returns undef.
994  
995 =head2 get_kid_pids()
996  
997 Returns list of forked child pids. Available only in parent processes.
998  
999 =head2 propagate_signal( 'SIGNAME' )
1000  
1001 Sends signal 'SIGNAME' to all child processes.
1002  
1003 =head1 EVENT HANDLING FUNCTIONS
1004  
1005 All of the following methods are empty in the base implementation and are
1006 expected to be reimplemented. The list order below is chronological but the
1007 most important function which must be reimplemented is on_process().
1008  
1009 =head2 on_listen_ok()
1010  
1011 Called when listen socket is ready but no connection is accepted yet.
1012  
1013 =head2 on_accept_error()
1014  
1015 Called if there is an error with accepting connections.
1016  
1017 =head2 on_accept_ok( $client_socket )
1018  
1019 Called when new connection is accepted without error.
1020  
1021 =head2 on_fork_ok( $child_pid )
1022  
1023 Called when new process is forked. This will be executed inside the server
1024 (parent) process and will have forked (child) process pid as 1st argument.
1025  
1026 =head2 on_process( $client_socket )
1027  
1028 Called when socket is ready to be used. This is the place where the actual
1029 work must be done.
1030  
1031 =head2 on_prefork_child_idle
1032  
1033 Called on preforked childs, when accept timeouts (see 'TIMEOUT' option).
1034  
1035 =head2 on_forking_idle
1036  
1037 Called on forking mode parent, when accept timeouts (see 'TIMEOUT' option).
1038  
1039 =head2 on_maxforked( $client_socket )
1040  
1041 Called if client socket is accepted but MAXFORK count reached. This can be
1042 used to advise the situation over the socket and will be called right before
1043 client socket close.
1044  
1045 note: this handler is only used for FORKING server. preforked servers will
1046 not accept the socket at all if MAXFORK has been reached. the reason is that
1047 forking server may release child process during the accept() call.
1048  
1049 =head2 on_child_start()
1050  
1051 Called right after fork, in the forked child, after initial setup but just before processing start.
1052  
1053 =head2 on_child_exit()
1054  
1055 Called inside a child, just before forked or preforked child exits.
1056  
1057 =head2 on_close( $client_socket )
1058  
1059 Called right before client socket will be closed. And after on_process().
1060 Will be called and when MAXFORK has been reached also.
1061  
1062 =head2 on_server_close()
1063  
1064 Called right before server (listen) socket is closed (i.e. when main loop
1065 is interrupted). This is the last handler to be called on each run().
1066  
1067 =head2 on_ssl_error( $ssl_handshake_error )
1068  
1069 Called when SSL handshake or other error encountered. Gets error message as 1st argument.
1070  
1071 =head2 on_sig_child( $child_pid )
1072  
1073 Called when child/client process finishes. It executes only inside the parent/server
1074 process and gets child pid as 1st argument.
1075  
1076 =head2 on_sig_usr1()
1077  
1078 Called when server process receives USR1 signal.
1079  
1080 =head2 on_sig_usr2()
1081  
1082 Called when server process receives USR2 signal.
1083
1084 =head2 on_child_sig_usr1()
1085  
1086 Called when forked (child) process receives USR1 signal.
1087  
1088 =head2 on_child_sig_usr2()
1089  
1090 Called when forked (child) process receives USR2 signal.
1091  
1092 =head2 log() and log_debug()
1093  
1094 Called when Waiter prints (debug) messages. Should be reimplemented to use
1095 specific log facility. By default it prints messages to STDERR. Can be
1096 reimplemented empty to supress any messages.
1097
1098 =head1 NOTES
1099  
1100 in PREFORK mode, fixed initial number of processes will be forked. each will
1101 accept socket and wait for connection. if waiting time for accept reaches a
1102 limit (default to 31 seconds, see PX_IDLE option above) the process will exit
1103 and main process will decide if new one should be forked or not.
1104  
1105 PREFORK process count may momentarily fall under the initial/lower count limit
1106 if several processes exit on idle.
1107  
1108 SIG_CHLD handler defaults to IGNORE in child processes.
1109 whoever forks further here, should reinstall signal handler if needed.
1110  
1111 =head1 TODO
1112  
1113 (more docs)
1114  
1115 =head1 REQUIRED MODULES
1116  
1117 Net::Waiter tries to use as little modules as possible. Currenlty only those
1118 core modules are in use:
1119  
1120 * IO::Socket::INET
1121 * POSIX ":sys_wait_h";
1122 * IO::Socket::INET;
1123 * Sys::SigAction qw( set_sig_handler );
1124 * IPC::Shareable;
1125 * Data::Dumper;
1126  
1127 =head1 DEMO
1128  
1129 For demo server check 'demo' directory in the source tar package or at the
1130 GITHUB repository:
1131  
1132 https://github.com/cade-vs/perl-net-waiter/tree/master/demo
1133  
1134 =head1 GITHUB REPOSITORY
1135  
1136 https://github.com/cade-vs/perl-net-waiter
1137  
1138 git@github.com:cade-vs/perl-net-waiter.git
1139  
1140 git clone git://github.com/cade-vs/perl-net-waiter.git
1141
1142 =head1 AUTHOR
1143  
1144 Vladi Belperchinov-Shabanski "Cade"
1145  
1146 <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
1147  
1148 http://cade.noxrun.com
1149  
1150 =cut
1151  
1152 ##############################################################################
1153 1;