| 1 | ############################################################################## | ||
| 2 | # | ||
| 3 | # Data::Tools::Process::ForkPool fork process control pool | ||
| 4 | # Copyright (c) 2026 Vladi Belperchinov-Shabanski "Cade" | ||
| 5 | # <cade@noxrun.com> | ||
| 6 | # http://cade.noxrun.com/ | ||
| 7 | # | ||
| 8 | # GPL | ||
| 9 | # | ||
| 10 | ############################################################################## | ||
| 11 | # | ||
| 12 | # NOTE: all forked processes of a pool are placed in the pool's own process | ||
| 13 | # group (pgrp) by the fork pool manager. the pool reaps and signals its | ||
| 14 | # forked processes by that pgrp, so forked processes must NOT change their | ||
| 15 | # pgrp (no setpgrp(), setsid(), daemonizing, etc.). a forked process which | ||
| 16 | # leaves the pool's pgrp will never be reaped or signalled by the pool. | ||
| 17 | # a forked process which runs its own (nested) fork pool places its own | ||
| 18 | # forked processes in a new pgrp, so they are not reached by the outer | ||
| 19 | # pool's fpool_signal_all(), fpool_stop_all() or fpool_kill_all(). the | ||
| 20 | # forked process must stop its own pools itself. | ||
| 21 | # | ||
| 22 | # NOTE: when fork pools are used, they should be the only means of forking | ||
| 23 | # processes in the supervisor. the pools are not meant to be mixed with bare | ||
| 24 | # fork(), Data::Tools::Process::Forks or any other code which calls | ||
| 25 | # waitpid( -1, ... ) or wait(). such code may reap the pool's forked | ||
| 26 | # processes, then the pool never sees them exit: their count never drops | ||
| 27 | # and the pool's pgrp is kept after the group is gone, so later its number | ||
| 28 | # may be reused and fpool_signal_all() could signal an unrelated pgrp. | ||
| 29 | # $SIG{ 'CHLD' } = 'IGNORE' has the same effect (children are auto-reaped). | ||
| 30 | # system(), backticks (qx//) and piped open() are safe to use in the | ||
| 31 | # supervisor: they fork internally but wait only for their own child pid. | ||
| 32 | # | ||
| 33 | # NOTE: signals are NOT propagated to the pool's forked processes. | ||
| 34 | # terminal signals (Ctrl-C INT, Ctrl-\ QUIT, Ctrl-Z TSTP, HUP on terminal | ||
| 35 | # close) are sent only to the terminal's foreground pgrp, which is the | ||
| 36 | # supervisor's own pgrp, not the pool's one. signals sent to the | ||
| 37 | # supervisor's pid or pgrp (kill, shell job control) do not reach the pool | ||
| 38 | # either. | ||
| 39 | # | ||
| 40 | # the fork pool does not install signal handlers. what to do on a signal is | ||
| 41 | # high-level logic, and there can be multiple pools, so the supervisor | ||
| 42 | # code must catch the signals it cares about and propagate them to each | ||
| 43 | # pool with fpool_signal_all(), fpool_stop_all() or fpool_kill_all(). | ||
| 44 | # signal handlers should only set a flag, the main loop should do the rest. | ||
| 45 | # | ||
| 46 | # forked processes inherit the supervisor's %SIG handlers. the forked sub | ||
| 47 | # should set its own handlers (or reset them to 'DEFAULT') first. | ||
| 48 | # | ||
| 49 | # if the supervisor dies without stopping the pools (uncaught signal, KILL, | ||
| 50 | # crash), forked processes keep running. they can detect this by EOF from | ||
| 51 | # fpool_recv_super() (returns undef) or by getppid() change. | ||
| 52 | # | ||
| 53 | # NOTE: forked processes finish with exit(), so END blocks and destructors | ||
| 54 | # of objects inherited from the supervisor DO run in forked processes too. | ||
| 55 | # this is intentional, some END blocks must run in the forked processes. | ||
| 56 | # END blocks which must run only in the supervisor should check the pid: | ||
| 57 | # | ||
| 58 | # my $SUPER_PID = $$; | ||
| 59 | # END { if( $$ == $SUPER_PID ) { ...supervisor only cleanup... } } | ||
| 60 | # | ||
| 61 | # inherited DBI handles should have AutoInactiveDestroy set, otherwise a | ||
| 62 | # forked process exit closes the supervisor's database connection. | ||
| 63 | # | ||
| 64 | # NOTE: messages sent by a forked process right before it exits may be lost. | ||
| 65 | # when an exited process is reaped (fpool_wait_one(), fpool_wait_all() or | ||
| 66 | # fpool_manage(), which reaps before reading), its socket is closed and its | ||
| 67 | # unread and queued messages are discarded. a forked process which must | ||
| 68 | # deliver a result before exit should wait for an acknowledge message from | ||
| 69 | # the supervisor (fpool_recv_super()) before it returns. | ||
| 70 | # | ||
| 71 | ############################################################################## | ||
| 72 | package Data::Tools::Process::ForkPool; | ||
| 73 | use strict; | ||
| 74 | use Exporter; | ||
| 75 | use POSIX qw( WNOHANG ); | ||
| 76 | use IO::Poll qw( POLLIN POLLHUP POLLERR ); | ||
| 77 | use Net::Tools::Socket::Pair; | ||
| 78 | use Net::Tools::Socket::Err; | ||
| 79 | use Data::Dumper; | ||
| 80 | use Exception::Sink; | ||
| 81 | |||
| 82 | our $VERSION = '1.60'; | ||
| 83 | |||
| 84 | our @ISA = qw( Exporter ); | ||
| 85 | our @EXPORT = qw( | ||
| 86 | fpool_manage | ||
| 87 | fpool_wait_all | ||
| 88 | fpool_wait_one | ||
| 89 | fpool_fork_one | ||
| 90 | |||
| 91 | fpool_stats | ||
| 92 | |||
| 93 | fpool_update_state | ||
| 94 | fpool_count | ||
| 95 | fpool_busy_count | ||
| 96 | |||
| 97 | fpool_signal_all | ||
| 98 | fpool_stop_all | ||
| 99 | fpool_kill_all | ||
| 100 | |||
| 101 | fpool_send_to | ||
| 102 | fpool_recv_from | ||
| 103 | |||
| 104 | fpool_send_super | ||
| 105 | fpool_recv_super | ||
| 106 | fpool_iam_busy | ||
| 107 | fpool_iam_idle | ||
| 108 | ); | ||
| 109 | |||
| 110 | # max queued non-state messages per forked process, 0 means no limit. | ||
| 111 | # when full, the oldest messages are discarded and counted in MSG_DROPPED. | ||
| 112 | our $MSG_QUEUE_MAX = 0; | ||
| 113 | |||
| 114 | my %POOLS; | ||
| 115 | my $SUPER_SOCK; # uplink messages socket | ||
| 116 | |||
| 117 | |||
| 118 | sub fpool_manage | ||
| 119 | { | ||
| 120 | my $pool = uc shift; # pool name | ||
| 121 | my $fsub = shift; # subroutine to fork | ||
| 122 | my $min = shift; # min fork count for this pool | ||
| 123 | my $max = shift; # max | ||
| 124 | my $step = shift; # step to increase if all forked are busy, may overflow to max+step-1, then waits to fall to max | ||
| 125 | # rest of @_ are passed to $fsub | ||
| 126 | |||
| 127 | return undef unless ref( $fsub ) eq 'CODE'; | ||
| 128 | |||
| 129 | $min = 0 if $min < 0 or ! $min; | ||
| 130 | $max = $min if $max < 0 or ! $max or $max < $min; | ||
| 131 | $step = int( $max / 10 ) + 1 if $step <= 0; | ||
| 132 | |||
| 133 | my $phr = $POOLS{ $pool } ||= {}; | ||
| 134 | |||
| 135 | fpool_wait_all( $pool ); | ||
| 136 | fpool_update_state( $pool ); | ||
| 137 | |||
| 138 | my $fc = $phr->{ 'FORKS_COUNT' } || 0; | ||
| 139 | my $bc = $phr->{ 'BUSY_COUNT' } || 0; | ||
| 140 | |||
| 141 | my $z = 0; | ||
| 142 | if( $fc < $min ) | ||
| 143 | { | ||
| 144 | $z = $min - $fc; # fill up to min | ||
| 145 | $z = $step if $z < $step; # step need to keep up | ||
| 146 | } | ||
| 147 | elsif( $fc < $max and $bc >= $fc ) | ||
| 148 | { | ||
| 149 | # all busy, grow by step. empty pool counts as all busy (0 >= 0), so with | ||
| 150 | # min 0, step new processes are forked whenever the pool is empty | ||
| 151 | $z = $step; | ||
| 152 | } | ||
| 153 | |||
| 154 | my $nc = 0; # new forks count | ||
| 155 | while( $z-- > 0 ) | ||
| 156 | { | ||
| 157 | $nc++ if fpool_fork_one( $pool, $fsub, @_ ); | ||
| 158 | } | ||
| 159 | |||
| 160 | return $nc; | ||
| 161 | } | ||
| 162 | |||
| 163 | sub fpool_fork_one | ||
| 164 | { | ||
| 165 | my $pool = uc shift; # pool name | ||
| 166 | my $fsub = shift; # subroutine to fork | ||
| 167 | # rest of @_ are passed to $fsub | ||
| 168 | |||
| 169 | return undef unless ref( $fsub ) eq 'CODE'; | ||
| 170 | my $phr = $POOLS{ $pool } ||= {}; # creates the pool if needed | ||
| 171 | |||
| 172 | my ( $super_sock, $forked_sock ) = socketpair_create(); | ||
| 173 | return undef unless $super_sock and $forked_sock; | ||
| 174 | |||
| 175 | my $pid = fork(); | ||
| 176 | if( ! defined $pid ) | ||
| 177 | { | ||
| 178 | # error, but will still be in the parent | ||
| 179 | close( $super_sock ); | ||
| 180 | close( $forked_sock ); | ||
| 181 | return undef; | ||
| 182 | } | ||
| 183 | |||
| 184 | if( $pid ) | ||
| 185 | { | ||
| 186 | # print "--> forked [$pid]\n"; | ||
| 187 | # supervisor here | ||
| 188 | close( $super_sock ); | ||
| 189 | $phr->{ 'PGRP' } = $pid if $phr->{ 'FORKS_COUNT' } == 0; # this is first fork, create new pgrp | ||
| 190 | setpgrp( $pid, $phr->{ 'PGRP' } ); | ||
| 191 | |||
| 192 | $phr->{ 'PIDS' }{ $pid } = { 'SOCK' => $forked_sock }; | ||
| 193 | $phr->{ 'FORKS_COUNT' }++; | ||
| 194 | $phr->{ 'IO::POLL' } ||= IO::Poll->new(); | ||
| 195 | $phr->{ 'IO::POLL' }->mask( $forked_sock => POLLIN ); | ||
| 196 | $phr->{ 'FH_PID_MAP' }{ $forked_sock } = $pid; | ||
| 197 | return $pid; | ||
| 198 | } | ||
| 199 | |||
| 200 | # forked here | ||
| 201 | # print " [$$] here\n"; | ||
| 202 | # pool's pgrp, must not be changed by the forked process, see NOTE at the top | ||
| 203 | $phr->{ 'PGRP' } ||= $$; | ||
| 204 | setpgrp( $$, $phr->{ 'PGRP' } ); | ||
| 205 | __fpool_reset(); # allow forked minion's own fork pools | ||
| 206 | |||
| 207 | close( $forked_sock ); | ||
| 208 | $SUPER_SOCK = $super_sock; | ||
| 209 | |||
| 210 | # never return to the parent's code, even if $fsub dies inside parent's eval | ||
| 211 | my $ex = eval { $fsub->( @_ ) }; | ||
| 212 | if( $@ ) | ||
| 213 | { | ||
| 214 | print STDERR $@; | ||
| 215 | exit 255; | ||
| 216 | } | ||
| 217 | # exit() runs END blocks and destructors here too, see NOTE at the top | ||
| 218 | exit $ex; | ||
| 219 | } | ||
| 220 | |||
| 221 | # reaps all already exited processes of specified pool, does not block | ||
| 222 | # returns count of reaped processes | ||
| 223 | sub fpool_wait_all | ||
| 224 | { | ||
| 225 | my $pool = uc shift; # pool name | ||
| 226 | my $phr = $POOLS{ $pool } or return undef; | ||
| 227 | return undef unless $phr->{ 'FORKS_COUNT' } > 0; | ||
| 228 | |||
| 229 | my $xc; | ||
| 230 | |||
| 231 | while( 42 ) | ||
| 232 | { | ||
| 233 | my ( $pid, $exit, $xsig ) = fpool_wait_one( $pool ); | ||
| 234 | last unless $pid; | ||
| 235 | $xc++; | ||
| 236 | # print " <-- exit ( $pid, $exit, $xsig, $name )\n"; | ||
| 237 | } | ||
| 238 | |||
| 239 | return $xc; | ||
| 240 | } | ||
| 241 | |||
| 242 | # reaps one or none already exited process of specified pool, does not block | ||
| 243 | sub fpool_wait_one | ||
| 244 | { | ||
| 245 | my $pool = uc shift; # pool name | ||
| 246 | my $phr = $POOLS{ $pool } or return wantarray ? () : undef; | ||
| 247 | return wantarray ? () : undef unless $phr->{ 'FORKS_COUNT' } > 0; | ||
| 248 | |||
| 249 | my $pid = waitpid( - $phr->{ 'PGRP' }, WNOHANG ); | ||
| 250 | return wantarray ? () : undef if $pid <= 0; | ||
| 251 | |||
| 252 | my $status = $?; | ||
| 253 | my $exit = $status >> 8; # exit code | ||
| 254 | my $xsig = $status & 127; # exit signal | ||
| 255 | |||
| 256 | my $sock = $phr->{ 'PIDS' }{ $pid }{ 'SOCK' }; | ||
| 257 | if( $sock ) | ||
| 258 | { | ||
| 259 | $phr->{ 'IO::POLL' }->remove( $sock ) if $phr->{ 'IO::POLL' }; | ||
| 260 | delete $phr->{ 'FH_PID_MAP' }{ $sock }; | ||
| 261 | close( $sock ); | ||
| 262 | } | ||
| 263 | my $pr = delete $phr->{ 'PIDS' }{ $pid }; | ||
| 264 | $phr->{ 'FORKS_COUNT' }--; | ||
| 265 | $phr->{ 'BUSY_COUNT' }-- if $pr->{ 'BUSY' }; | ||
| 266 | delete $phr->{ 'PGRP' } if $phr->{ 'FORKS_COUNT' } == 0; | ||
| 267 | |||
| 268 | # print " <-- exit ( $pid, $exit, $xsig, $name )\n"; | ||
| 269 | # TODO: callback with ( $pid, $exit, $xsig, $name ) | ||
| 270 | |||
| 271 | return wantarray ? ( $pid, $exit, $xsig, $status ) : $pid; | ||
| 272 | } | ||
| 273 | |||
| 274 | sub __fpool_reset | ||
| 275 | { | ||
| 276 | # forked process inherits supervisor's sockets to its sibling processes | ||
| 277 | for my $phr ( values %POOLS ) | ||
| 278 | { | ||
| 279 | close( $_->{ 'SOCK' } ) for grep { $_->{ 'SOCK' } } values %{ $phr->{ 'PIDS' } }; | ||
| 280 | } | ||
| 281 | close( $SUPER_SOCK ) if $SUPER_SOCK; # nested pool, own supervisor's socket | ||
| 282 | $SUPER_SOCK = undef; | ||
| 283 | %POOLS = (); | ||
| 284 | return 1; | ||
| 285 | } | ||
| 286 | |||
| 287 | ### supervisor API ########################################################### | ||
| 288 | |||
| 289 | sub fpool_send_to | ||
| 290 | { | ||
| 291 | my $pool = uc shift; # pool name | ||
| 292 | my $pid = shift; | ||
| 293 | |||
| 294 | my $phr = $POOLS{ $pool } or return undef; | ||
| 295 | my $pr = $phr->{ 'PIDS' }{ $pid } or return undef; | ||
| 296 | my $pid_sock = $pr->{ 'SOCK' }; | ||
| 297 | |||
| 298 | return undef unless $pid_sock; # the socket connected to the forked worker | ||
| 299 | return socketpair_send( $pid_sock, shift() ); | ||
| 300 | } | ||
| 301 | |||
| 302 | sub fpool_recv_from | ||
| 303 | { | ||
| 304 | my $pool = uc shift; # pool name | ||
| 305 | my $pid = shift; | ||
| 306 | my $data = shift; | ||
| 307 | |||
| 308 | boom "expected scalar reference" unless ref( $data ) eq 'SCALAR'; | ||
| 309 | $$data = undef; | ||
| 310 | |||
| 311 | my $phr = $POOLS{ $pool } or return undef; | ||
| 312 | my $pr = $phr->{ 'PIDS' }{ $pid } or return undef; | ||
| 313 | |||
| 314 | # returns next non-state message, queued by fpool_update_state() | ||
| 315 | return 0 unless $pr->{ 'MSG_QUEUE' } and @{ $pr->{ 'MSG_QUEUE' } } > 0; | ||
| 316 | $$data = shift @{ $pr->{ 'MSG_QUEUE' } }; | ||
| 317 | return 1; | ||
| 318 | } | ||
| 319 | |||
| 320 | # returns text report: busy count, forks count and PID => busy state list | ||
| 321 | # busy state is from the last fpool_update_state() call | ||
| 322 | sub fpool_stats | ||
| 323 | { | ||
| 324 | my $pool = uc shift; # pool name | ||
| 325 | |||
| 326 | my $phr = $POOLS{ $pool } or return undef; | ||
| 327 | my $pids = $phr->{ 'PIDS' } || {}; | ||
| 328 | |||
| 329 | my $text = "POOL [$pool] busy [" . ( $phr->{ "BUSY_COUNT" } || 0 ) . "] forks [" . ( $phr->{ "FORKS_COUNT" } || 0 ) . "]\n"; | ||
| 330 | for my $pid ( sort { $a <=> $b } keys %$pids ) | ||
| 331 | { | ||
| 332 | $text .= " $pid => " . ( $pids->{ $pid }{ 'BUSY' } ? '*' : '-' ) . "\n"; | ||
| 333 | } | ||
| 334 | |||
| 335 | return $text; | ||
| 336 | } | ||
| 337 | |||
| 338 | # reads all pending messages, up to 8 per call, from each ready forked process | ||
| 339 | # socket of the pool (non-blocking), the rest are delayed to the next call of | ||
| 340 | # fpool_update_state(). | ||
| 341 | # on EOF the socket is removed from the poll set (closed when reaped). | ||
| 342 | # updates per-process busy state, BUSY is 1 or 0, | ||
| 343 | # from "STATE:*" (busy) / "STATE:-" (idle) | ||
| 344 | # other messages are kept in $POOLS{ $pool }{ 'PIDS' }{ $pid }{ 'MSG_QUEUE' }, | ||
| 345 | # up to $MSG_QUEUE_MAX (0 = no limit), see fpool_recv_from() | ||
| 346 | # returns the new $POOLS{ $pool }{ 'BUSY_COUNT' } or undef if no such pool | ||
| 347 | sub fpool_update_state | ||
| 348 | { | ||
| 349 | my $pool = uc shift; # pool name | ||
| 350 | |||
| 351 | my $phr = $POOLS{ $pool } or return undef; | ||
| 352 | my $poll = $phr->{ 'IO::POLL' } or return 0; | ||
| 353 | |||
| 354 | my $msg; | ||
| 355 | $poll->poll( 0 ); # do not wait | ||
| 356 | for my $fh ( $poll->handles( POLLIN | POLLHUP | POLLERR ) ) | ||
| 357 | { | ||
| 358 | my $pid = $phr->{ 'FH_PID_MAP' }{ $fh }; | ||
| 359 | my $pr = $pid ? $phr->{ 'PIDS' }{ $pid } : undef; | ||
| 360 | if( ! $pr ) | ||
| 361 | { | ||
| 362 | $poll->remove( $fh ); # forked process already reaped | ||
| 363 | next; | ||
| 364 | } | ||
| 365 | |||
| 366 | my $mrl = 8; # message read limit | ||
| 367 | my $res; | ||
| 368 | while( $mrl-- > 0 ) | ||
| 369 | { | ||
| 370 | $res = socketpair_recv( $fh, \$msg ); | ||
| 371 | if( ! defined $res ) | ||
| 372 | { | ||
| 373 | # undef is a hard error (EOF, worker closed its socket), stop polling it, | ||
| 374 | # otherwise poll() keeps returning it as ready, socket is closed when the | ||
| 375 | # worker is reaped. 0 with any $SOCK_ERR is temporary, the socket is kept | ||
| 376 | $poll->remove( $fh ); | ||
| 377 | last; | ||
| 378 | } | ||
| 379 | # oversized message was discarded by socketpair_recv(), read the next one | ||
| 380 | next if $res == 0 and $SOCK_ERR == SOCK_E_TOOBIG; | ||
| 381 | last unless $res == 1; | ||
| 382 | |||
| 383 | if( $msg =~ /^STATE:([*-])\z/ ) | ||
| 384 | { | ||
| 385 | $pr->{ 'BUSY' } = $1 eq '*' ? 1 : 0; | ||
| 386 | } | ||
| 387 | else | ||
| 388 | { | ||
| 389 | # queue full, discard oldest messages to make room for the new one | ||
| 390 | while( $MSG_QUEUE_MAX > 0 and $pr->{ 'MSG_QUEUE' } and @{ $pr->{ 'MSG_QUEUE' } } >= $MSG_QUEUE_MAX ) | ||
| 391 | { | ||
| 392 | shift @{ $pr->{ 'MSG_QUEUE' } }; | ||
| 393 | $pr->{ 'MSG_DROPPED' }++; | ||
| 394 | } | ||
| 395 | push @{ $pr->{ 'MSG_QUEUE' } }, $msg; | ||
| 396 | } | ||
| 397 | } | ||
| 398 | } | ||
| 399 | |||
| 400 | # count from the map, so repeated states and reaped processes are not counted | ||
| 401 | $phr->{ 'BUSY_COUNT' } = grep { $_->{ 'BUSY' } } values %{ $phr->{ 'PIDS' } }; | ||
| 402 | |||
| 403 | return $phr->{ 'BUSY_COUNT' }; | ||
| 404 | } | ||
| 405 | |||
| 406 | sub fpool_signal_all | ||
| 407 | { | ||
| 408 | my $pool = uc shift; # pool name | ||
| 409 | my $sig = shift // return undef; | ||
| 410 | |||
| 411 | my $phr = $POOLS{ $pool } or return undef; | ||
| 412 | return undef unless $phr->{ 'PGRP' }; | ||
| 413 | |||
| 414 | kill( $sig, - $phr->{ 'PGRP' } ); | ||
| 415 | } | ||
| 416 | |||
| 417 | sub fpool_stop_all | ||
| 418 | { | ||
| 419 | return fpool_signal_all( shift(), 'TERM' ); | ||
| 420 | } | ||
| 421 | |||
| 422 | sub fpool_kill_all | ||
| 423 | { | ||
| 424 | return fpool_signal_all( shift(), 'KILL' ); | ||
| 425 | } | ||
| 426 | |||
| 427 | sub fpool_count | ||
| 428 | { | ||
| 429 | my $pool = uc shift; # pool name | ||
| 430 | |||
| 431 | my $phr = $POOLS{ $pool } or return undef; | ||
| 432 | return $phr->{ 'FORKS_COUNT' }; | ||
| 433 | } | ||
| 434 | |||
| 435 | sub fpool_busy_count | ||
| 436 | { | ||
| 437 | my $pool = uc shift; # pool name | ||
| 438 | |||
| 439 | my $phr = $POOLS{ $pool } or return undef; | ||
| 440 | return $phr->{ 'BUSY_COUNT' }; | ||
| 441 | } | ||
| 442 | |||
| 443 | ### forked sub API ########################################################### | ||
| 444 | |||
| 445 | sub fpool_send_super | ||
| 446 | { | ||
| 447 | return undef unless $SUPER_SOCK; # the socket connected to the supervisor | ||
| 448 | return socketpair_send( $SUPER_SOCK, shift() ); | ||
| 449 | } | ||
| 450 | |||
| 451 | sub fpool_recv_super | ||
| 452 | { | ||
| 453 | return undef unless $SUPER_SOCK; # the socket connected to the supervisor | ||
| 454 | return socketpair_recv( $SUPER_SOCK, shift() ); | ||
| 455 | } | ||
| 456 | |||
| 457 | sub fpool_iam_busy | ||
| 458 | { | ||
| 459 | fpool_send_super( 'STATE:*' ); | ||
| 460 | } | ||
| 461 | |||
| 462 | sub fpool_iam_idle | ||
| 463 | { | ||
| 464 | fpool_send_super( 'STATE:-' ); | ||
| 465 | } | ||
| 466 | |||
| 467 | ############################################################################## | ||
| 468 | 1; | ||
| 469 | |||
| 470 | |||
| 471 | =pod | ||
| 472 | |||
| 473 | =head1 NAME | ||
| 474 | |||
| 475 | Data::Tools::Process::ForkPool - pools of forked processes with messaging | ||
| 476 | |||
| 477 | =head1 SYNOPSIS | ||
| 478 | |||
| 479 | use Data::Tools::Process::ForkPool; | ||
| 480 | use Time::HiRes qw( sleep ); | ||
| 481 | |||
| 482 | # supervisor main loop | ||
| 483 | while( ! $STOP ) | ||
| 484 | { | ||
| 485 | # reap exited, read states, keep 2..16 workers, grow by 2 when all busy | ||
| 486 | fpool_manage( 'WORKERS', \&worker, 2, 16, 2, @worker_args ); | ||
| 487 | |||
| 488 | for my $pid ( @pids_of_interest ) | ||
| 489 | { | ||
| 490 | my $msg; | ||
| 491 | while( fpool_recv_from( 'WORKERS', $pid, \$msg ) ) | ||
| 492 | { | ||
| 493 | # one message from $pid in $msg | ||
| 494 | } | ||
| 495 | } | ||
| 496 | sleep( 0.1 ); | ||
| 497 | } | ||
| 498 | fpool_stop_all( 'WORKERS' ); | ||
| 499 | |||
| 500 | # forked worker | ||
| 501 | sub worker | ||
| 502 | { | ||
| 503 | $SIG{ 'TERM' } = 'DEFAULT'; | ||
| 504 | fpool_iam_idle(); | ||
| 505 | while( 1 ) | ||
| 506 | { | ||
| 507 | my $job; | ||
| 508 | my $res = fpool_recv_super( \$job ); | ||
| 509 | return 0 unless defined $res; # supervisor gone | ||
| 510 | if( ! $res ) { sleep( 0.1 ); next } # nothing yet | ||
| 511 | fpool_iam_busy(); | ||
| 512 | fpool_send_super( "done: $job" ); | ||
| 513 | fpool_iam_idle(); | ||
| 514 | } | ||
| 515 | } | ||
| 516 | |||
| 517 | =head1 DESCRIPTION | ||
| 518 | |||
| 519 | A fork pool is a named set of forked processes running the same sub. The | ||
| 520 | supervisor keeps the pool between a minimum and a maximum count and grows | ||
| 521 | it when all forked processes report busy. Each forked process is connected | ||
| 522 | to the supervisor by its own L<Net::Tools::Socket::Pair> socket, used for | ||
| 523 | messages both ways and for the busy/idle state. | ||
| 524 | |||
| 525 | Pool names are case insensitive (upper cased). There may be many pools in | ||
| 526 | one supervisor, and a forked process may run its own (nested) pools. | ||
| 527 | |||
| 528 | All forked processes of a pool are placed in the pool's own process group, | ||
| 529 | which is used to reap and signal them. See the NOTES below and at the top | ||
| 530 | of the module source for the rules this implies (no setpgrp() or setsid() | ||
| 531 | in forked processes, no other fork()/wait() code in the supervisor, no | ||
| 532 | $SIG{ 'CHLD' } = 'IGNORE', signals are not propagated, etc.). | ||
| 533 | |||
| 534 | All functions are exported by default. Functions return undef on errors | ||
| 535 | like an unknown pool or pid. They do not set or clear C<$SOCK_ERR>; it is | ||
| 536 | set only by the L<Net::Tools::Socket::Pair> calls they make, so check it | ||
| 537 | only after a socket call result (0 or undef from send/recv). | ||
| 538 | |||
| 539 | =head1 MESSAGES | ||
| 540 | |||
| 541 | Messages are byte strings up to C<$Net::Tools::Socket::Pair::MSG_MAX> | ||
| 542 | (128 KiB) long, sent and received whole. Data structures must be | ||
| 543 | serialized first. The messages "STATE:*" and "STATE:-" are reserved for | ||
| 544 | fpool_iam_busy() and fpool_iam_idle(). | ||
| 545 | |||
| 546 | Messages from forked processes are read by fpool_update_state() (called by | ||
| 547 | fpool_manage()) into a per-process queue, from which fpool_recv_from() | ||
| 548 | returns them. Messages to forked processes are read directly by | ||
| 549 | fpool_recv_super(). | ||
| 550 | |||
| 551 | $Data::Tools::Process::ForkPool::MSG_QUEUE_MAX limits each queue, 0 (the | ||
| 552 | default) means no limit. When a queue is full, its oldest messages are | ||
| 553 | discarded. | ||
| 554 | |||
| 555 | =head1 SUPERVISOR FUNCTIONS | ||
| 556 | |||
| 557 | =head2 fpool_manage( $pool, \&sub, $min, $max, $step, @args ) | ||
| 558 | |||
| 559 | Creates the pool if needed, reaps exited processes (fpool_wait_all()), | ||
| 560 | reads states and messages (fpool_update_state()) and then forks new | ||
| 561 | processes running C<< \&sub->( @args ) >>: | ||
| 562 | |||
| 563 | * up to $min, at least $step at a time | ||
| 564 | * $step more, if all processes are busy and the count is below $max | ||
| 565 | |||
| 566 | $min defaults to 0, $max to $min (also when smaller than $min), $step to | ||
| 567 | int( $max / 10 ) + 1. The count may overshoot $max by up to $step - 1. | ||
| 568 | |||
| 569 | Should be called periodically from the supervisor's main loop. Returns the | ||
| 570 | count of new processes, or undef if \&sub is not a code reference. | ||
| 571 | |||
| 572 | =head2 fpool_fork_one( $pool, \&sub, @args ) | ||
| 573 | |||
| 574 | Forks one process in the pool, creates the pool if needed. Returns the new | ||
| 575 | pid in the supervisor, undef on error. Use it instead of fpool_manage() for | ||
| 576 | an own growing policy, with fpool_wait_one(), fpool_update_state(), | ||
| 577 | fpool_count() and fpool_busy_count(). | ||
| 578 | |||
| 579 | The forked process never returns from it: it runs C<< \&sub->( @args ) >> | ||
| 580 | and exits with its return value. If \&sub dies, the error is printed to | ||
| 581 | STDERR and it exits with 255. exit() runs END blocks and destructors in the | ||
| 582 | forked process too. | ||
| 583 | |||
| 584 | =head2 fpool_wait_all( $pool ) | ||
| 585 | |||
| 586 | Reaps all already exited processes of the pool, does not block. Returns | ||
| 587 | the count of reaped processes, undef if none were reaped or there is no | ||
| 588 | such pool. Unread messages of a reaped process are discarded. | ||
| 589 | |||
| 590 | =head2 fpool_wait_one( $pool ) | ||
| 591 | |||
| 592 | Reaps one already exited process of the pool, does not block. Returns its | ||
| 593 | pid, or in list context ( $pid, $exit_code, $signal, $status ), where | ||
| 594 | $status is the raw wait status ($?, with the core dump flag). Returns undef | ||
| 595 | (empty list) if none exited or there is no such pool. | ||
| 596 | |||
| 597 | =head2 fpool_update_state( $pool ) | ||
| 598 | |||
| 599 | Reads pending messages from the forked processes without waiting, up to 8 | ||
| 600 | per process per call, the rest are read on the next call. "STATE:*" and | ||
| 601 | "STATE:-" update the busy state of the process, other messages are queued | ||
| 602 | for fpool_recv_from(). Returns the busy count (0 for a pool which has not | ||
| 603 | forked yet), or undef if there is no such pool. | ||
| 604 | |||
| 605 | =head2 fpool_count( $pool ) / fpool_busy_count( $pool ) | ||
| 606 | |||
| 607 | Return the count of processes in the pool and how many of them are busy, | ||
| 608 | as of the last fpool_update_state(). undef if there is no such pool. | ||
| 609 | |||
| 610 | =head2 fpool_stats( $pool ) | ||
| 611 | |||
| 612 | Returns a text report: pool name, busy and process counts and the busy | ||
| 613 | state ('*' busy, '-' idle) of each pid. undef if there is no such pool. | ||
| 614 | |||
| 615 | =head2 fpool_signal_all( $pool, $signal ) | ||
| 616 | |||
| 617 | Sends $signal ('TERM', 'HUP', 9, etc.) to all processes of the pool (its | ||
| 618 | process group). Returns the result of kill(), undef if there is no such | ||
| 619 | pool or it has no processes. | ||
| 620 | |||
| 621 | fpool_stop_all( $pool ) sends TERM, fpool_kill_all( $pool ) sends KILL. | ||
| 622 | |||
| 623 | =head2 fpool_send_to( $pool, $pid, $data ) | ||
| 624 | |||
| 625 | Sends message $data to the forked process $pid. Returns the | ||
| 626 | socketpair_send() result: 1 sent, 0 not sent (queue full, etc.), undef | ||
| 627 | if the process closed its socket, or undef if there is no such pool or pid. | ||
| 628 | |||
| 629 | =head2 fpool_recv_from( $pool, $pid, \$data ) | ||
| 630 | |||
| 631 | Takes the next queued message from the forked process $pid into $data. | ||
| 632 | Returns 1 for a message, 0 if the queue is empty, undef if there is no | ||
| 633 | such pool or pid. $data is set to undef whenever the result is not 1. | ||
| 634 | Dies (boom) if \$data is not a scalar reference. Messages are queued only | ||
| 635 | by fpool_update_state() (and fpool_manage()). | ||
| 636 | |||
| 637 | =head1 FORKED PROCESS FUNCTIONS | ||
| 638 | |||
| 639 | These work only in a process forked by fpool_fork_one() or fpool_manage(), | ||
| 640 | elsewhere they return undef. | ||
| 641 | |||
| 642 | =head2 fpool_send_super( $data ) | ||
| 643 | |||
| 644 | Sends message $data to the supervisor. Returns the socketpair_send() | ||
| 645 | result: 1 sent, 0 not sent, undef if the supervisor is gone. | ||
| 646 | |||
| 647 | =head2 fpool_recv_super( \$data ) | ||
| 648 | |||
| 649 | Reads the next message from the supervisor into $data, does not wait. | ||
| 650 | Returns the socketpair_recv() result: 1 for a message, 0 if nothing is | ||
| 651 | waiting, undef if the supervisor is gone. | ||
| 652 | |||
| 653 | =head2 fpool_iam_busy() / fpool_iam_idle() | ||
| 654 | |||
| 655 | Report the busy or idle state to the supervisor, as seen by | ||
| 656 | fpool_busy_count() and used by fpool_manage() to grow the pool. | ||
| 657 | |||
| 658 | =head1 NOTES | ||
| 659 | |||
| 660 | =over 4 | ||
| 661 | |||
| 662 | =item * | ||
| 663 | |||
| 664 | Forked processes must not change their process group (setpgrp(), setsid(), | ||
| 665 | daemonizing), otherwise the pool never reaps or signals them. | ||
| 666 | |||
| 667 | =item * | ||
| 668 | |||
| 669 | The pools should be the only means of forking in the supervisor. Other code | ||
| 670 | which calls wait() or waitpid( -1, ... ), and $SIG{ 'CHLD' } = 'IGNORE', | ||
| 671 | may reap the pool's processes behind its back. system(), qx// and piped | ||
| 672 | open() are safe. | ||
| 673 | |||
| 674 | =item * | ||
| 675 | |||
| 676 | Signals are not propagated to the pools. The supervisor must catch the | ||
| 677 | signals it cares about and call fpool_signal_all(), fpool_stop_all() or | ||
| 678 | fpool_kill_all() for each pool. Forked processes inherit the supervisor's | ||
| 679 | %SIG and should set their own handlers first. | ||
| 680 | |||
| 681 | =item * | ||
| 682 | |||
| 683 | If the supervisor dies without stopping the pools, forked processes keep | ||
| 684 | running. They see it as undef from fpool_recv_super() or a getppid() | ||
| 685 | change. | ||
| 686 | |||
| 687 | =item * | ||
| 688 | |||
| 689 | Messages sent by a forked process right before it exits may be lost when | ||
| 690 | it is reaped. A process which must deliver a result should wait for an | ||
| 691 | acknowledge from the supervisor before it returns. | ||
| 692 | |||
| 693 | =item * | ||
| 694 | |||
| 695 | Inherited DBI handles should have AutoInactiveDestroy set, END blocks meant | ||
| 696 | for the supervisor only should check $$. | ||
| 697 | |||
| 698 | =item * | ||
| 699 | |||
| 700 | Works on Linux only, see L<Net::Tools::Socket::Pair>. | ||
| 701 | |||
| 702 | =back | ||
| 703 | |||
| 704 | =head1 SEE ALSO | ||
| 705 | |||
| 706 | L<Net::Tools::Socket::Pair>, L<Net::Tools::Socket::Err>, | ||
| 707 | L<Data::Tools::Process::Forks> | ||
| 708 | |||
| 709 | =head1 AUTHOR | ||
| 710 | |||
| 711 | Vladi Belperchinov-Shabanski "Cade" | ||
| 712 | <cade@noxrun.com> | ||
| 713 | http://cade.noxrun.com/ | ||
| 714 | |||
| 715 | =head1 COPYRIGHT AND LICENSE | ||
| 716 | |||
| 717 | Copyright (c) 2026 Vladi Belperchinov-Shabanski "Cade" | ||
| 718 | |||
| 719 | This program is free software; you can redistribute it and/or modify it | ||
| 720 | under the terms of the GNU General Public License as published by the | ||
| 721 | Free Software Foundation; either version 2 of the License, or (at your | ||
| 722 | option) any later version. | ||
| 723 | |||
| 724 | =cut |