helios.pl untested

filter: Statementstmt 0.0% 0 / 481 Branchbran 0.0% 0 / 180 Conditioncond 0.0% 0 / 94 MC/DCmcdc 0.0% 0 / 58 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 860 CC 39 SCAR 37.0
CC
39
Cov
0%
reaper
110.0
workers_to_launch
110.0
running_process_check
42.0
CRAP 40.3
1 #!/usr/bin/env perl
2  
3 use 5.008;
4 use strict;
5 use warnings;
6 use FindBin ();
7 use File::Basename ();
8 use File::Spec;
9 use Getopt::Long;
10 use POSIX;
11 use Sys::Hostname;
12 # [LH] 2013-08-04: Added Fcntl for better pidfile locking. [RT81914]
13 use Fcntl qw(:DEFAULT :flock);
14  
15 use Helios;
16 use Helios::Error;
17 use Helios::LogEntry::Levels qw(:all);
18 # [LH] [2013-10-04]: Switched to using Helios::TS for virtual jobtypes.
19 use Helios::TS;
20 use Helios::Config;
21  
22 our $VERSION = '2.80';
23  
24 # FILE CHANGE HISTORY
25 # [2012-01-08]: Added a check to try to prevent loading code outside of @INC.
26 # [2012-01-09]: Modified check to prevent loading code outside of @INC.
27 # [2012-03-25]: Added code to prevent a worker process from changing into a
28 # daemon due to odd (and uncommon) database connection instability.
29 # [2012-03-27]: Changed $DEFAULTS{ZERO_SLEEP_INTERVAL} to 10. Added code to
30 # add "registration_interval" as a configuration parameter. Added
31 # $DEFAULTS{REGISTRATION_INTERVAL} and set to 60. Changed
32 # $REGISTRATION_INTERVAL to 60.
33 # [2012-04-01]: Changed service module loaded notification to report version
34 # only if the module has a $VERSION set. Changed service initialization to use
35 # the prep() method instead of getConfigFromIni() and getConfigFromDb() to
36 # ensure proper initialization of loggers and Data::ObjectDriver database
37 # connection.
38 # [2012-05-20]: Removed old commented out calls to getConfigFrom*(),
39 # clean_shutdown(), and logMsg() (logging a HALT message). Removed 2 empty
40 # comments.
41 # [LH] [2012-07-11]: Switched from using TheSchwartz to using
42 # Helios::TheSchwartz. Added WORKER_BLITZ_FACTOR feature to launch workers
43 # faster when there are less than MAX_WORKERS jobs available. Stopped closing
44 # STDOUT, STDIN, and STDERR when helios.pl daemonizes because it was causing
45 # problems with some services.
46 # [LH] [2012-07-15]: Added to use Helios::Config, and changed configuration
47 # update code to use Helios::Config instead of getConfigFromDb(). Added
48 # debugging messages for ZERO_SLEEP_INTERVAL and REGISTRATION_INTERVAL.
49 # [LH] [2012-07-26]: Changed "worker_blitz_factor" config param to
50 # "WORKER_BLITZ_FACTOR". Added new code to better handle database connections
51 # after a fork() so worker processes do not share or disconnect the daemon's
52 # connections.
53 # [LH] [2012-07-29]: Added DOUBLE_CLUTCH_INTERVAL config parameter to control
54 # WORKER_MAX_TTL functionality better than ZERO_LAUNCH_INTERVAL. Updated
55 # copyright info.
56 # [LH] [2012-09-05]: Changed DOUBLE_CLUTCH_INTERVAL to
57 # WORKER_MAX_TTL_WAIT_INTERVAL.
58 # [LH] [2012-09-28]: Removed old commented out code.
59 # [LH] [2012-10-12]: Replaced code attempting to prevent loading of modules
60 # outside of @INC with new require_module() function.
61 # [LH] [2012-12-11]: Added code to apply WORKER_MAX_TTL after registration in
62 # daemon main loop. [RT81709]
63 # [LH] [2013-08-04]: Implemented new PID file locking scheme to fix [RT81914].
64 # Replaced write_pid_file() and mostly rewrote running_process_check() to
65 # prevent a PID file race condition.
66 # [LH] [2013-08-19]: Added comments for clarification of fix for [RT81914].
67 # [LH] [2013-09-21]: Added code to enable job prioritization features in
68 # Helios::TheSchwartz. Added code to implement WORKER_LAUNCH_PATTERN feature.
69 # [LH] [2013-10-04]: Added code to implement "virtual jobtypes." Switched to
70 # using Helios::TS instead of Helios::TheSchwartz. Changed command line
71 # option parsing to accomodate options other than "--clear-halt". Removed
72 # old commented out code for class name sanity checking and class loading.
73 # Removed old code to calculate workers to launch, also removed code for
74 # WORKER_BLITZ_FACTOR feature (WORKER_LAUNCH_PATTERN replaces it).
75 # [LH] [2013-10-18]: Replaced most try {} blocks with eval {}. Changed option
76 # handling to better handle --help and fix --version. Added --debug option.
77 # Changed $CLASS to $OPT_CLASS like all the other $OPT_* option variables.
78 # Added startup message so user knows which collective db the daemon connected
79 # to. Partially updated POD with new options and mentioned new
80 # Helios::Configuration POD; also added mention of zero_sleep_interval option.
81 # [LH] [2013-11-24]: Removed use of Error module as all use of try {} catch {}
82 # blocks have been removed. Changed command line option handling so jobtypes
83 # can be specified with multiple --jobtype options as well as a single comma-
84 # delimited --jobtypes argument. Removed old commented out code. Database
85 # reconnect code now dumps all cached database connections before attempting
86 # a reconnect.
87 # [LH] [2014-02-28] POD updates. Updated copyright info. Changed
88 # WORKER_LAUNCH_PATTERN values to "linear","dynamic", and "optimistic".
89  
90 =head1 NAME
91  
92 helios.pl - Launch a daemon to service jobs in the Helios job processing system
93  
94 =head1 SYNOPSIS
95  
96 # Make sure HELIOS_INI is set and exported. Optionally enable debug mode.
97 export HELIOS_INI=/path/to/helios.ini
98 [export HELIOS_DEBUG=1]
99 # Full command line options
100 helios.pl [--service=<service class>] [--jobtypes=<jobtypename,jobtypename>] \
101 [--clear-halt] [--version] [--help]
102  
103 # Simple cmd line example: start a daemon with the Helios::TestService service.
104 helios.pl Helios::TestService
105
106 # More complex: start a Helios::TestService daemon, but have it run MyService jobs.
107 helios.pl --service=Helios::TestService --jobtypes=MyService
108  
109 # Just prints version info.
110 helios.pl --version
111
112 # Prints this help page.
113 helios.pl --help
114  
115 =head1 DESCRIPTION
116  
117 The helios.pl program, given a Helios service class, will launch a daemon
118 to service Helios jobs of that class. The number of worker processes to run
119 concurrently and various other parameters are set via a helios.ini file and the
120 Helios collective database (the connection information of which is also defined
121 in helios.ini).
122  
123 Under normal operation, helios.pl will attempt to load the service class
124 specified on the command line and read the contents of the helios.ini file. If
125 successful, it will attempt to connect to the Helios collective
126 database specified in helios.ini and read the configuration parameters relevant
127 to the loaded service class from there. If that is successful, helios.pl will
128 then daemonize and start servicing jobs of the specified class. If additional
129 jobtypes are specified with the --jobtypes option, jobs of those additional
130 types will also be serviced by the loaded service class.
131  
132 =head1 helios.pl COMMAND LINE OPTIONS
133  
134 =head2 --service [REQUIRED]
135  
136 The --service option specifies the name of the Helios service to load and
137 launch worker processes for. If you specify the name as the first option on
138 the command line, you can actually drop the '--service=' part, as helios.pl
139 will assume the first option is the service class name.
140  
141 Examples:
142  
143 helios.pl --service=MyService
144 --OR--
145 helios.pl MyService
146  
147 =head2 --jobtypes
148  
149 Normally, a Helios service will run jobs belonging to its own jobtype (the
150 service class name matches the jobtype name). However, as of Helios 2.80, a
151 Helios service can run jobs of multiple jobtypes if necessary. These
152 additional jobtypes should be specified on the helios.pl command line with the
153 --jobtypes option. You can specify multiple jobtypes by separating them with
154 commas, or specify multiple --jobtype values. (Thanks to helios.pl's use of
155 L<Getopt::Long>, '--jobtype' and '--jobtypes' are interchangable.)
156  
157 Examples:
158  
159 # MyService handles jobs of jobtype "MyService" (the default)
160 helios.pl MyService
161
162 # MyService handles MyService jobs and MyIndexer jobs
163 helios.pl MyService --jobtype=MyIndexer
164
165 # MyService handles MyService, MyIndexer, and MyMailer jobs
166 helios.pl MyService --jobtypes=MyIndexer,MyMailer
167 --OR--
168 helios.pl MyService --jobtype=MyIndexer --jobtype=MyMailer
169  
170 For more information about jobtypes and how they relate to jobs and services,
171 see the L<Helios::JobType> man page.
172
173 =head2 --clear-halt
174  
175 If the --clear-halt option is specified, helios.pl will attempt to remove a HALT
176 parameter specified in the Helios configuration for the specified service on the
177 current host. This is helpful if you shutdown your Helios service daemon using
178 the Helios::Panoptes Collective Admin view. Note that it will NOT remove a HALT
179 specified globally (where host = '*').
180  
181 =head2 --version
182  
183 The --version option displays the Helios framework version and the helios.pl
184 version and then exits.
185  
186 =head2 --help
187  
188 The --help option displays this documentation.
189  
190 =head1 helios.pl ENVIRONMENT VARIABLES
191  
192 The Helios framework relies directly on two environment variables to function
193 correctly. Both should be exported as well as set to ensure the helios.pl
194 child processes can see them as well as the main helios.pl daemon.
195  
196 =head2 HELIOS_INI [REQUIRED]
197  
198 The full path to the helios.ini configuration file. This should be an absolute
199 path, not a relative one. The default is to use a helios.ini in the current
200 directory if it exists, which will work if you are running in Debug Mode (see
201 HELIOS_DEBUG below), but will cause problems if helios.pl is running normally.
202  
203 I<Default: ./helios.ini>
204  
205 =head2 HELIOS_DEBUG
206  
207 Setting HELIOS_DEBUG to 1 causes helios.pl to run in Debug Mode. In Debug Mode,
208 helios.pl will not disconnect from the terminal and will output extra debugging
209 information to the screen and the Helios log. It will also enable debug mode
210 on the service class, which may support the output of extra debugging
211 information if you so choose.
212  
213 I<Default: undef>
214  
215 =head1 HELIOS.INI
216  
217 The initial parameters for helios.pl are defined in an INI-style configuration
218 file typically named "helios.ini". The file's location is normally specified
219 by setting the HELIOS_INI environment variable before helios.pl is started.
220  
221 A helios.ini file normally contains a [global] section with the parameters
222 necessary to connect to the Helios collective database, and any parameters local
223 to the host on which the Helios service is currently running. In addition,
224 each service class may have its own section in helios.ini containing
225 parameters specfic to that service on that host.
226  
227 Example helios.ini:
228  
229 [global]
230 dsn=dbi:mysql:host=10.1.0.21;db=helios_db
231 user=helios
232 password=password
233  
234 [LongRunningJobService]
235 master_launch_interval=60
236 zero_launch_interval=90
237  
238 [AnotherService]
239 OVERDRIVE=1
240 MAX_WORKERS=3
241  
242 =head2 Helios.ini Parameters for helios.pl
243  
244 This section just covers the basic config options for helios.pl. For a
245 complete list of built-in Helios config options, consult the
246 L<Helios::Configuration> man page.
247  
248 =head3 Configuration options to place in the [global] section:
249  
250 These options will be the same for all Helios services running a host that
251 share the same collective database, so these options must be placed in a
252 helios.ini section named [global] so they are visible to all running helios.pl
253 instances.
254  
255 =over 4
256  
257 =item dsn [REQUIRED]
258  
259 Datasource name for the Helios collective database. The collective database
260 houses the data structures for service configuration, jobtypes, job queuing and
261 history, and the default logging subsystem.
262  
263 I<Default: none>
264  
265 =item user [REQUIRED]
266  
267 Database user for the datasource name described above.
268  
269 I<Default: none>
270  
271 =item password [REQUIRED]
272  
273 Database password for the datasource name described above.
274  
275 I<Default: none>
276  
277 =item pid_path
278  
279 The location where helios.pl should write the PID file for this service
280 instance. The name of the PID file will be a variation on the service class's
281 name.
282  
283 I<Default: /var/run/helios>
284  
285 =back
286  
287 =head3 Configuration options to place in individual service sections:
288  
289 The options listed in this section are available to tune helios.pl to work
290 better with your Helios service class and the jobs it needs to service. These
291 are read at startup and, unlike some other Helios config options, cannot be
292 dynamically changed while helios.pl is running. If you wish to tune one of
293 these parameters, reset the parameter and restart the service daemon.
294  
295 =over 4
296  
297 =item master_launch_interval
298  
299 Set the master_launch_interval to determine how long helios.pl should sleep
300 after launching workers before accessing the database to update its
301 configuration parameters and check for waiting jobs. The default is 1 second,
302 which should be sufficient for most applications.
303  
304 I<Default: 1>
305  
306 =item zero_launch_interval
307  
308 Set the zero_launch_interval to determine how long helios.pl should sleep after
309 reaching its MAX_WORKERS limit. The default is 10 sec. If jobs are running
310 long enough that helios.pl is frequently hitting the MAX_WORKERS limit (there
311 are waiting jobs but helios.pl can't launch new workers because previously
312 launched jobs are still running), increasing the zero_launch_interval will
313 reduce needless database traffic.
314  
315 I<Default: 10>
316  
317 =item zero_sleep_interval
318  
319 Set the zero_sleep_interval to adjust the amount of time between checks for
320 available jobs in the job queue when the job queue is empty. If the helios.pl
321 daemon determines there are no available jobs for a service, it sleeps
322 zero_sleep_interval seconds and then checks for jobs again. The default is 10
323 sec. If you notice jobs are sitting in the job queue too long before workers
324 are launched to service them, reduce this number to cause jobs to be started
325 faster. If you have a small number of jobs and do not care if they sit in the
326 job queue for a few seconds before being serviced, increase this number to
327 reduce database queries.
328  
329 I<Default: 10>
330  
331 =back
332  
333 =head1 HELIOS_CONFIG_* AND HELIOS CTRL PANEL (helios_params_tb)
334  
335 In addition to helios.ini, certain helios.pl configuration options can be set
336 via the helios_config_* commands or the Ctrl Panel or Collective Admin views
337 in the Helios::Panoptes web admin interface. These configuration options are
338 read by helios.pl from the HELIOS_PARAMS_TB table in the Helios collective
339 database. For more information on configuration parameters available to tune
340 how a service runs jobs, see the L<Helios::Configuration> man page. For more
341 information on the L<helios_config_get>, L<helios_config_set>,
342 L<helios_config_unset> commands and the L<Helios::Panoptes> web admin
343 interface, see their respective man pages or Perl POD.
344  
345 =cut
346  
347 # for SIGHUP support
348 our @ORIGINAL_ARGV = @ARGV;
349 my $basename = File::Basename::basename($0);
350 our $HELIOS_PL_PATH = File::Spec->catfile($FindBin::Bin, $basename);
351  
352 # globals settings
353 our $DEBUG_MODE = $ENV{HELIOS_DEBUG};
354 our $HELIOS_INI = $ENV{HELIOS_INI};
355 # BEGIN CODE Copyright (C) 2013 by Logical Helion, LLC.
356 # [LH] [2013-10-04]: Virtual jobtypes. We have to parse the cmd line args
357 # in a completely different way, but still maintain backward compatibility.
358 # if the first cmd line switch starts with '-', then all the options are
359 # "proper." If not, then the first option is the service class, and the
360 # remaining options will be proper.
361 our $OPT_CLASS = '';
362 our $OPT_CLEAR_HALT = 0;
363 our $OPT_DEBUG = 0;
364 our $OPT_HELP = 0;
365 our @OPT_JOBTYPES = ();
366 our $OPT_VERSION = 0;
367 if ( defined($ARGV[0]) && $ARGV[0] !~ /^\-/) {
368 $OPT_CLASS = shift @ARGV;
369 }
370 GetOptions(
371 "service=s" => \$OPT_CLASS,
372 "clear-halt" => \$OPT_CLEAR_HALT,
373 "help" => \$OPT_HELP,
374 "jobtypes=s" => \@OPT_JOBTYPES,
375 "version" => \$OPT_VERSION,
376 "debug" => \$OPT_DEBUG,
377 );
378 our @ALT_JOBTYPES = split(/,/, join(','=>@OPT_JOBTYPES));
379 $DEBUG_MODE = 1 if $OPT_DEBUG;
380 # END CODE Copyright (C) 2013 by Logical Helion, LLC.
381  
382 # other globals
383 # max workers will default to 1 if not set elsewhere
384 our %DEFAULTS = (
385 MAX_WORKERS => 1,
386 HELIOS_INI => File::Spec->catfile(File::Spec->curdir,'helios.ini'),
387 PID_PATH => File::Spec->catfile(File::Spec->rootdir, 'var', 'run', 'helios'),
388 MASTER_LAUNCH_INTERVAL => 1,
389 ZERO_LAUNCH_INTERVAL => 10,
390 ZERO_SLEEP_INTERVAL => 10,
391 REGISTRATION_INTERVAL => 60,
392 WORKER_BLITZ_FACTOR => 1,
393 WORKER_MAX_TTL_WAIT_INTERVAL => 20,
394 PRIORITIZE_JOBS => 0,
395 WORKER_LAUNCH_PATTERN => 'linear',
396 );
397 our $CLEAN_SHUTDOWN = 1; # used to determine if we should remove the PID file or not (at least for now)
398  
399 our $HOLD_LOG_INTERVAL = 3600; # to reduce needless log msg in log_tb while HOLDing
400 our $HOLD_LOG_LAST = 0;
401  
402 our $MASTER_LAUNCH_INTERVAL;
403 our $ZERO_LAUNCH_INTERVAL;
404  
405 our $START_TIME = time(); # used to measure uptime from the registry table
406 our $REGISTRATION_INTERVAL = 60; # used to periodically register daemon in database
407 our $REGISTRATION_LAST = 0;
408  
409 our $PID_FILE; # globally accessible PID file location
410 # [LH] 2013-08-04: Added $PID_FILE_H as a filehandle for better pidfile locking. [RT81914]
411 our $PID_FILE_H; # globally accessible PID file handle
412 our $SAFE_MODE_DELAY = 45; # SAFE MODE support; number of secs to wait
413 our $SAFE_MODE_RETRIES = 5; # SAFE MODE support; number of times to retry
414  
415 our $ZERO_SLEEP_INTERVAL; # to reduce needless checking of the database
416 our $ZERO_SLEEP_LOG_INTERVAL = 3600; # to reduce needless log msgs in log_tb
417 our $ZERO_SLEEP_LOG_LAST = 0;
418 our $WORKER_MAX_TTL_WAIT_INTERVAL = 20; # for WORKER_MAX_TTL functionality
419  
420 our $WORKER_PROCESS = 0; # used to indicate process has become a worker process
421 # this is used in addition to getppid() to prevent workers
422 # from becoming daemons in case of database instability
423  
424 our $WORKER_BLITZ_FACTOR = 1; # used to determine how many workers to launch
425 our $HELIOS_DB_CONN; # database handle to help with DBI+forking issues
426  
427 # print help if asked
428 # [LH] [2013-10-04]: New @ARGV parsing for "--help".
429 if ( $OPT_HELP ) {
430 require Pod::Usage;
431 Pod::Usage::pod2usage(-verbose => 2, -exitstatus => 0);
432 }
433  
434 # conditionally load module or die in the attempt
435 my $worker_class = $OPT_CLASS;
436 print "Helios ",$Helios::VERSION,"\n";
437 print "helios.pl Service Daemon version $VERSION\n";
438 # --version support
439 # BEGIN CODE Copyright (C) 2013 by Logical Helion, LLC.
440 # [LH] [2013-10-04]: New @ARGV parsing for "--version".
441 # [LH] [2013-10-18]: New @ARGV parsing for --service.
442 if ( $OPT_VERSION ) { exit(0); }
443 unless ($OPT_CLASS) {
444 warn("The name of a service class is required.\n");
445 exit(1);
446 }
447 # END CODE Copyright (C) 2013 by Logical Helion, LLC.
448 print "Attempting to load $worker_class...\n";
449 require_module($worker_class);
450  
451 if ( defined($worker_class->VERSION) ) {
452 print $worker_class, ' ', $worker_class->VERSION," loaded.\n";
453 } else{
454 print $worker_class," loaded.\n";
455 }
456 if ($DEBUG_MODE) { print "Debug Mode enabled.\n"; }
457  
458 # instantiate a worker to access the necessary settings
459 my $worker = new $worker_class;
460 $worker->setHostname(hostname);
461 if ( defined($HELIOS_INI) ) {
462 $worker->setIniFile( $HELIOS_INI );
463 } else {
464 $worker->setIniFile( $DEFAULTS{HELIOS_INI} );
465 }
466 $worker->setJobType($worker_class);
467 # BEGIN CODE Copyright (C) 2013 by Logical Helion, LLC.
468 # [LH] [2013-10-04]: Virtual jobtypes set & init.
469 if (@ALT_JOBTYPES) {
470 $worker->setAltJobTypes(@ALT_JOBTYPES);
471 $worker->lookupAltJobtypeids();
472 print "Servicing jobtypes: ", join(' ' => ($worker->getJobType(), $worker->getAltJobTypes())),"\n";
473 }
474 # END CODE Copyright (C) 2013 by Logical Helion, LLC.
475 $worker->debug($DEBUG_MODE);
476 eval {
477 $worker->prep();
478 };
479 if ($@) {
480 die("FAILED to get configuration: $@");
481 }
482  
483 my $params = $worker->getConfig();
484 if ($DEBUG_MODE) {
485 print "--INITIAL PARAMS--\n";
486 foreach my $param (keys %$params) {
487 print $param, ":", $params->{$param},"\n";
488 }
489 }
490  
491 # SETUP OPERATIONAL PARAMETERS
492 if ( defined($params->{master_launch_interval}) ) {
493 $MASTER_LAUNCH_INTERVAL = $params->{master_launch_interval};
494 } else {
495 $MASTER_LAUNCH_INTERVAL = $DEFAULTS{MASTER_LAUNCH_INTERVAL};
496 }
497 if ( defined($params->{zero_launch_interval}) ) {
498 $ZERO_LAUNCH_INTERVAL = $params->{zero_launch_interval};
499 } else {
500 $ZERO_LAUNCH_INTERVAL = $DEFAULTS{ZERO_LAUNCH_INTERVAL};
501 }
502 if ( defined($params->{zero_sleep_interval}) ) {
503 $ZERO_SLEEP_INTERVAL = $params->{zero_sleep_interval};
504 } else {
505 $ZERO_SLEEP_INTERVAL = $DEFAULTS{ZERO_SLEEP_INTERVAL};
506 }
507 if ( defined($params->{registration_interval}) ) {
508 $REGISTRATION_INTERVAL = $params->{registration_interval};
509 } else {
510 $REGISTRATION_INTERVAL = $DEFAULTS{REGISTRATION_INTERVAL};
511 }
512 if ( defined($params->{WORKER_BLITZ_FACTOR}) ) {
513 $WORKER_BLITZ_FACTOR = $params->{WORKER_BLITZ_FACTOR};
514 } else {
515 $WORKER_BLITZ_FACTOR = $DEFAULTS{WORKER_BLITZ_FACTOR};
516 }
517 if ( defined($params->{WORKER_MAX_TTL_WAIT_INTERVAL}) ) {
518 $WORKER_MAX_TTL_WAIT_INTERVAL = $params->{WORKER_MAX_TTL_WAIT_INTERVAL};
519 } else {
520 $WORKER_MAX_TTL_WAIT_INTERVAL = $DEFAULTS{WORKER_MAX_TTL_WAIT_INTERVAL};
521 }
522  
523 # make a globally accessible database handle
524 # to make it easier to clean up CachedKids after a fork()
525 $HELIOS_DB_CONN = $worker->dbConnect();
526 # [LH] [2013-10-18]: Added startup message so user knows which collective db
527 # we connected to
528 print "Connected to collective database: ",$params->{dsn},"\n";
529  
530 if ($DEBUG_MODE) {
531 print "MASTER LAUNCH INTERVAL: $MASTER_LAUNCH_INTERVAL\n";
532 print "ZERO LAUNCH INTERVAL: $ZERO_LAUNCH_INTERVAL\n";
533 print "ZERO SLEEP_INTERVAL: $ZERO_SLEEP_INTERVAL\n";
534 print "REGISTRATION_INTERVAL: $REGISTRATION_INTERVAL\n";
535 print "WORKER BLITZ FACTOR: $WORKER_BLITZ_FACTOR\n";
536 }
537  
538 my %workers;
539 my $pid;
540  
541 my $waiting_jobs = 0;
542 my $running_workers = 0;
543 my $max_workers = $DEFAULTS{MAX_WORKERS};
544  
545 our $DATABASES_INFO = [
546 { dsn => $params->{dsn},
547 user => $params->{user},
548 pass => $params->{password}
549 }
550 ];
551  
552 my $times_thru_loop = 0;
553 my $times_waiting = 0;
554 my $times_sleeping = 0;
555  
556 # attempt to clear a HALT parameter, if specified
557 # then we'll check to see if HALT is still there
558 # if it is, we'll have to stop here rather than
559 # daemonize and launch the main loop
560 # [LH] [2013-10-04]: New @ARGV parsing for "--clear-halt".
561 if ( $OPT_CLEAR_HALT ) {
562 clear_halt();
563 $worker->prep();
564 $params = $worker->getConfig();
565 }
566 if ( defined($params->{HALT}) ) {
567 print STDERR "HALT is set for this service class.\n";
568 print STDERR "Please clear it and try again.\n";
569 print STDERR $worker_class," HALTED.\n";
570 exit(1);
571 }
572 # final check before we launch:
573 # check to make sure a daemon for this service isn't already running
574 if ( running_process_check($params->{pid_path}) ) {
575 print STDERR $worker->errstr(),"\n";
576 exit(1);
577 }
578  
579 # Daemonize unless we're in debug mode
580 unless ($DEBUG_MODE) {
581 daemonize();
582 } else {
583 # print debug message
584 print "Writing pid file...\n";
585 write_pid_file($params->{pid_path}) or die($worker->errstr);
586 print "Executing main loop...\n";
587 }
588  
589 # set up signal handler to reap dead children
590 $SIG{CHLD} = \&reaper;
591 $SIG{TERM} = \&terminator;
592  
593  
594 =head1 HELIOS OPERATION
595  
596 After initial setup, the helios.pl daemon will enter a main operation loop where configuration
597 parameters are refreshed, the job queue is checked, and worker processes are launched and
598 cleaned up after. A HOLD = 1 parameter will temporarily cause the loop to pause processing, while
599 a HALT parameter will cause the helios.pl daemon to exit the loop, clean up, and exit.
600  
601 There are several steps in the helios.pl main operation loop:
602  
603 =over 4
604  
605 =item 1.
606  
607 Refresh configuration parameters from database.
608  
609 =item 2.
610  
611 Check job queue to see if there are jobs of the correct jobtype(s) available
612 for processing (if not, sleep for zero_sleep_interval seconds and start again).
613  
614 =item 3.
615  
616 If there are jobs available, check to see how many worker processes are currently running.
617 If MAX_WORKERS workers are already running, sleep for zero_launch_interval seconds and
618 start again. The zero_launch_interval setting should be long enough to allow at least some of
619 the running jobs to complete (the default is 10 secs).
620  
621 =item 4.
622  
623 If there are jobs available and the MAX_WORKERS limit has not been reached,
624 determine the number of additional workers to launch and launch them. The
625 number of workers to launch is governed by the WORKER_LAUNCH_PATTERN
626 configuration parameter; see the L<Helios::Configuration> man page for more
627 information.
628  
629 =item 5.
630  
631 Sleep master_launch_interval seconds and start the operation loop again.
632  
633 =back
634  
635 =cut
636  
637 MAIN_LOOP:{
638 # [LH] [2013-11-24]: Replaced try {} otherwise {} block with eval {} or do {}.
639 eval {
640
641 # while not halted
642 while (!defined($params->{HALT}) ) {
643
644 $times_thru_loop++;
645
646 # recheck db parameters
647 $params = undef;
648 $params = Helios::Config->parseConfig();
649
650 # DAEMON REGISTRATION
651 # every $REGISTRATION_INTERVAL seconds, (re)register this daemon in the database
652 if ( ($REGISTRATION_LAST + $REGISTRATION_INTERVAL) < time() ) {
653 register();
654 $REGISTRATION_LAST = time();
655 # [LH] 2012-12-11: Copied WORKER_MAX_TTL/double_clutch() call from HOLD code below
656 # to enable WORKER_MAX_TTL in Normal Mode as well as Hold Mode. [RT81709]
657 if ( defined($params->{WORKER_MAX_TTL}) && $params->{WORKER_MAX_TTL} > 0
658 && scalar(keys %workers) ) {
659 double_clutch();
660 }
661 }
662
663 # HOLDING JOB PROCESSING
664 # hold launching jobs temporarily
665 if ( defined($params->{HOLD}) && ($params->{HOLD} == 1) ) {
666 if ( $HOLD_LOG_LAST + $HOLD_LOG_INTERVAL < time() ) {
667 $worker->logMsg(LOG_NOTICE, "$0 $worker_class HOLDING");
668 $HOLD_LOG_LAST = time();
669 }
670 if ($DEBUG_MODE) { print "$0 $worker_class HOLDING\n"; }
671 sleep 60;
672 # after the first cycle through HOLD, the workers had BETTER be dead
673 if ( defined($params->{WORKER_MAX_TTL}) && $params->{WORKER_MAX_TTL} > 0
674 && scalar(keys %workers) ) {
675 double_clutch();
676 }
677 next;
678 }
679 # once we're not holding anymore, we'll want to log the next time we enter HOLD mode
680 $HOLD_LOG_LAST = 0;
681
682  
683 # DETERMINING WORKERS TO LAUNCH
684 $waiting_jobs = $worker->jobsWaiting();
685 $running_workers = scalar(keys %workers);
686 $max_workers = defined($params->{MAX_WORKERS}) ? $params->{MAX_WORKERS} : $DEFAULTS{MAX_WORKERS};
687 if ($DEBUG_MODE) { $worker->logMsg(LOG_DEBUG, "MAX WORKERS: $max_workers"); }
688 if ($DEBUG_MODE) { $worker->logMsg(LOG_DEBUG, "RUNNING WORKERS: $running_workers"); }
689
690 # if no waiting jobs, sleep
691 if ($DEBUG_MODE) {
692 print $waiting_jobs, " waiting ",$worker_class, " jobs.\n";
693 $worker->logMsg(LOG_DEBUG, $waiting_jobs . " waiting " . $worker_class . " jobs.");
694 }
695 unless ( $waiting_jobs ) {
696 $times_sleeping++;
697 # only log the "0 workers running, 0 workers in queue. SLEEPING" message every $ZERO_SLEEP_LOG_INTERVAL seconds
698 # (necessary to prevent overwhelming database logging with messages we don't care about)
699 if ( ($running_workers == 0) && (($ZERO_SLEEP_LOG_LAST + $ZERO_SLEEP_LOG_INTERVAL ) < time()) ) {
700 $worker->logMsg(LOG_NOTICE, $running_workers." workers running, ".$waiting_jobs." in queue. SLEEPING");
701 $ZERO_SLEEP_LOG_LAST = time();
702 }
703 sleep $ZERO_SLEEP_INTERVAL;
704 next;
705 }
706 # once we're not zero sleeping ("0 workers running, 0 workers in queue")
707 # we'll want to log the next time we go into zero sleep
708 $ZERO_SLEEP_LOG_LAST = 0;
709
710  
711 # LAUNCHING WORKERS
712 # if we've got to this part of the loop, we have jobs that need workers to launch
713 # (though we still may not do it if we've already reached our limit)
714 # [LH] [2013-09-21]: Added code to implement WORKER_LAUNCH_PATTERN feature.
715 my $workers_to_launch = workers_to_launch($waiting_jobs, $running_workers, $max_workers);
716 $worker->logMsg(LOG_NOTICE, "$waiting_jobs jobs waiting; $running_workers workers running; launching $workers_to_launch workers");
717 for (my $i = 0; $i < $workers_to_launch; $i++) {
718
719 FORK: {
720 if ($pid = fork) {
721 # I'm the parent!
722 $workers{$pid} = time();
723 if ($DEBUG_MODE) { $worker->logMsg(LOG_NOTICE, $worker->getJobType()." process $pid launched"); }
724 sleep 1;
725 } elsif (defined $pid) { # $pid is zero here if defined
726 # I'm the child!
727 $WORKER_PROCESS = 1;
728
729 # BEGIN CODE Copyright (C) 2012 by Logical Helion, LLC.
730 # BEFORE WE LAUNCH THE WORKER,
731 # clean up the database connections from the parent
732 # we'll set InactiveDestroy on the existing connections
733 # then we'll clear them, leaving the parent connections
734 # free of any influence of the children
735 # NOTE: with DBI >= 1.614, all we'd have to do is
736 # set AutoInactiveDestroy on all the connections
737 # but to support the DBI (1.52) bundled with RHEL & CentOS 5,
738 # we have to make do with what we have
739 my $ck = $HELIOS_DB_CONN->{Driver}->{CachedKids};
740 foreach (keys %$ck) {
741 $ck->{$_}->{InactiveDestroy} = 1;
742 }
743 %$ck = ();
744 # END CODE Copyright (C) 2012 by Logical Helion, LLC.
745  
746 # NOW, launch the worker
747 launch_worker();
748 } elsif ($! == EAGAIN) {
749 # EAGAIN is the supposedly recoverable fork error
750 sleep 2;
751 redo FORK;
752 } else {
753 # weird fork error
754 die "Can't fork: $!\n";
755 }
756 }
757
758 }
759  
760  
761 # SLEEP INTERVAL AFTER LAUNCHING
762 # depending on the worker type, we may need to wait before we go back to the top of the loop
763 # (pull new parameters and waiting job count from the database)
764 # This can help reduce needless database traffic
765  
766 # if there are running jobs but we didn't launch any
767 # (max workers has been reached) sleep for a short while
768 # to reduce needless "spinning" (and db access)
769 if ( $workers_to_launch <= 0 ) {
770 if ( $DEBUG_MODE ) { $worker->logMsg(LOG_DEBUG, "MAX WORKERS REACHED, SLEEPING"); }
771 sleep $ZERO_LAUNCH_INTERVAL;
772 if ( defined($params->{WORKER_MAX_TTL}) && $params->{WORKER_MAX_TTL} > 0 ) {
773 double_clutch();
774 }
775 next;
776 }
777  
778 # if we did launch jobs, depending on the type of worker we may not want to re-check the database yet
779 # longer-running jobs (eg Helios::BatchWorker) don't need to have the db checked immediately after launch
780 # shorter-running jobs (eg IndexWorker) have likely already completed in the time it took to launch them
781 # and we want to launch as many as possible as quickly as possible (esp. if there's a Mass Index operation)
782 if ($MASTER_LAUNCH_INTERVAL) {
783 if ( $DEBUG_MODE ) { $worker->logMsg(LOG_DEBUG, "MASTER LAUNCH INTERVAL $MASTER_LAUNCH_INTERVAL, SLEEPING"); }
784 sleep $MASTER_LAUNCH_INTERVAL;
785 }
786 }
787 # [LH] [2013-11-24]: Replaced try {} otherwise {} block with eval {} or do {}.
788 1;
789 } or do {
790 my $e = shift;
791 # if we're a worker process and we ended up here
792 # it's a fluke caused by the database instability
793 # we have to bail out and hope the service daemon survives
794 # since the default logger will also be affected by this error, we can't log anything either :(
795 if ( (getppid() > 1) || ($WORKER_PROCESS == 1) ) { exit(42); }
796 if ($DEBUG_MODE) {
797 print "EXCEPTION THROWN: ",$e->text,"\n";
798 print "ATTEMPTING TO RECONNECT...\n";
799 }
800 # BEGIN CODE Copyright (C) 2013 by Logical Helion, LLC.
801 #[] dump all the database connections
802 # [LH] [2013-11-24]: Dump all the cached db connections so we can make
803 # sure we're starting over.
804 my $ck = $HELIOS_DB_CONN->{Driver}->{CachedKids};
805 %$ck = ();
806 $HELIOS_DB_CONN->disconnect() if ( ref($HELIOS_DB_CONN) && $HELIOS_DB_CONN->isa('DBI'));
807 # END CODE Copyright (C) 2013 by Logical Helion, LLC.
808  
809 my $retry;
810 my $return_code = 0;
811 for($retry = 1; $retry <= $SAFE_MODE_RETRIES; $retry++) {
812 my $success = 0;
813 # [LH] [2013-11-24]: Replaced try {} otherwise {} block with eval {} or do {}.
814 eval {
815 $success = $worker->dbConnect();
816 1;
817 } or do {
818 # actually, if we fail, we do nothing
819 };
820 if ($success) {
821 $return_code = 1;
822 last;
823 }
824 sleep $SAFE_MODE_DELAY;
825 }
826 if ($DEBUG_MODE && $return_code) {
827 print "DATABASE CONNECTION REESTABLISHED!\n";
828 } elsif ($DEBUG_MODE) {
829 print "DATABASE RECONNECTION ATTEMPTS FAILED!\n";
830 }
831 if ($return_code) {
832 # BEGIN CODE Copyright (C) 2013 by Logical Helion, LLC.
833 # [LH] [2013-11-24]: Reconnect the main db connection variable before
834 # we go back to the main loop.
835 $HELIOS_DB_CONN = $worker->dbConnect();
836 # END CODE Copyright (C) 2013 by Logical Helion, LLC.
837 $worker->logMsg(LOG_CRIT, "Exiting SAFE MODE; Reestablished connection to database after exception: ".$e->text);
838 $worker->errstr(undef);
839 redo MAIN_LOOP;
840 } else {
841 $worker->errstr("Unable to reconnect to ".$params->{dsn}.": ".$e->text);
842 $CLEAN_SHUTDOWN = 0;
843 last MAIN_LOOP;
844 }
845 };
846
847 } # end of MAIN_LOOP
848  
849 # shutdown procedures
850 if ($CLEAN_SHUTDOWN) {
851 # if we're cleanly shutting down (we were told to via helios_params_tb)
852 # unregister from Helios database
853 # remove our PID
854 terminator();
855 } else {
856 # if we've had a db error, this will throw an exception when it tries to log to the database
857 # BUT BEFORE it does that, the error will have been logged to the local syslog daemon
858 $worker->logMsg(LOG_ERR,"$0 $worker_class HALTED on error: ".$worker->errstr);
859 }
860  
861 if ($DEBUG_MODE) { print "$0 $worker_class HALTED!\n"; }
862  
863 exit();
864  
865  
866 =head1 SUBROUTINES
867  
868 The helios.pl program calls several of its own functions at various times
869 during startup, shutdown, and during main loop operation. These are probably
870 only of limited interest, but are documented here for those wanting to
871 understand better the guts of the helios.pl daemon.
872  
873 =head1 PROCESS CONTROL FUNCTIONS
874  
875 =head2 daemonize()
876  
877 The daemonize() function is called to turn the Helios program into a daemon
878 servicing jobs of a particular class. It forks a new process, which disconnects
879 from the launching terminal.
880  
881 Normally, daemonization would also include setting up signal handling, but the
882 daemonize() function isn't called in debug mode, so signal traps are actually
883 set up in the main program.
884  
885 =cut
886  
887 sub daemonize {
888 # prep system interaction stuff
889 # attempt to be a good daemon (unlike in the past)
890 chdir File::Spec->rootdir();
891 # don't think I need these w/close()ing them below,
892 # but I'll put them in for perlipc's sake anyway
893 open STDIN, '/dev/null';
894 open STDOUT, '>/dev/null';
895 open STDERR, '>/dev/null';
896
897 my $pid = fork;
898 # make sure fork was successful
899 unless ( defined($pid) ) {
900 die "Cannot daemonize: $!";
901 }
902  
903 # we forked, but are we parent or child?
904 if ($pid) {
905 # we got a PID, so we're the parent ("shell-called process")
906 # print a nice message about daemonizing and exit
907 print "$worker_class daemon launched.\n";
908 exit();
909 }
910  
911 # we got 0, so we're the "child", or the parent daemon
912 # we need to write our PID out to a file
913 # and then disconnect completely from the shell
914 write_pid_file($params->{pid_path}) or die($worker->errstr);
915  
916 # Detach from the shell entirely by setting our own
917 # session and making our own process group
918 # as well as closing any standard open filehandles.
919 POSIX::setsid();
920 # close (STDIN);
921 # close (STDOUT);
922 # close (STDERR);
923  
924 # set up signal handling in main process
925 }
926  
927  
928 =head2 double_clutch()
929  
930 The double_clutch() function implements the WORKER_MAX_TTL functionality. If
931 the WORKER_MAX_TTL parameter is set for a service, the service daemon
932 periodically calls double_clutch() to check the workers and clean up any that
933 have run too long. The double_clutch() function waits a certain amount of time
934 (WORKER_MAX_TTL_WAIT_INTERVAL secs), then checks the amount of time each of the
935 running workers has been active. If a worker has been running longer than the
936 service's WORKER_MAX_TTL, the worker is killed (by sending it a SIGKILL signal).
937  
938 =cut
939  
940 sub double_clutch {
941 # BEGIN CODE Copyright (C) 2012 by Logical Helion, LLC.
942 # check each running worker to see if it has been running too long
943 # (too long: WORKER_MAX_TTL seconds + WORKER_MAX_TTL_WAIT_INTERVAL "fudge factor")
944 # END CODE Copyright (C) 2012 by Logical Helion, LLC.
945 foreach my $pid (keys %workers) {
946 # BEGIN CODE Copyright (C) 2012 by Logical Helion, LLC.
947 my $time_to_die = $workers{$pid} + $params->{WORKER_MAX_TTL} + $WORKER_MAX_TTL_WAIT_INTERVAL;
948 # END CODE Copyright (C) 2012 by Logical Helion, LLC.
949 if ( time() > $time_to_die ) {
950 kill 9, $pid;
951 delete $workers{$pid};
952 $worker->logMsg(LOG_ERR, "Killed process $pid (exceeded WORKER_MAX_TTL)");
953 }
954 }
955 return 1;
956 }
957  
958  
959 =head2 launch_worker()
960  
961 The launch_worker() function launches a new worker process.
962 After the fork() from the main process, the new child process will call
963 launch_worker() to instantiate and configure a new L<Helios::TS> job queuing
964 system object and start the worker on its way by calling the object's work()
965 method. If the OVERDRIVE run mode is enabled for the service, the
966 work_until_done() method is called instead. See L<Helios::Configuration> for
967 information about running workers in OVERDRIVE vs. Normal Mode.
968  
969 =cut
970  
971 sub launch_worker {
972 # just in case this would cause a problem in worker process
973 $SIG{CHLD} = 'DEFAULT';
974 $SIG{TERM} = 'DEFAULT';
975
976 # BEGIN CODE Copyright (C) 2012-3 by Logical Helion, LLC.
977 # [LH] [2013-09-21]: Added code to enable job prioritization features in Helios::TheSchwartz.
978 # [LH] [2013-10-04]: Virtual jobtypes: switched to using Helios::TS.
979 my Helios::TS $client = Helios::TS->new(
980 databases => $DATABASES_INFO,
981 prioritize => defined($params->{PRIORITIZE_JOBS}) ? $params->{PRIORITIZE_JOBS} : $DEFAULTS{PRIORITIZE_JOBS}
982 );
983 # END CODE Copyright (C) 2012-3 by Logical Helion, LLC.
984 $client->can_do($worker_class);
985 # BEGIN CODE Copyright (C) 2013 by Logical Helion, LLC.
986 # [LH] [2013-10-04]: Virtual jobtypes: Set up Helios::TS object with
987 # alt jobtypes and designate the "Active Worker Class" (the service class
988 # that is actually running the jobs).
989 if ($worker->getAltJobTypes) {
990 $client->set_active_worker_class($worker_class);
991 for ($worker->getAltJobTypes) {
992 $client->can_do($_);
993 }
994 }
995 # END CODE Copyright (C) 2013 by Logical Helion, LLC.
996 my $return;
997 if ( defined($params->{OVERDRIVE}) && $params->{OVERDRIVE} == 1 ) {
998 $return = $client->work_until_done();
999 } else {
1000 $return = $client->work_once();
1001 }
1002 exit($return);
1003 }
1004  
1005  
1006 =head1 SIGNAL HANDLERS
1007  
1008 =head2 reaper()
1009  
1010 The reaper() function is responsible for cleaning up after dead child processes. It's called when
1011 helios.pl receives a SIG_CHLD signal. The function reaps any children with waitpid(), removes the
1012 children's PID from the $workers hash of running workers, and re-establishes itself as the signal
1013 handler for the next SIG_CHLD signal.
1014  
1015 =cut
1016  
1017 sub reaper {
1018 my $pid;
1019 if ($DEBUG_MODE) { print "REAPING!\n"; }
1020 while (($pid = waitpid(-1, &WNOHANG)) > 0) {
1021 if ($pid == -1) {
1022 if ($DEBUG_MODE) { print "REAPED IGNORING\n"; }
1023 # no child waiting. Ignore it.
1024 } elsif (WIFEXITED($?)) {
1025 delete $workers{$pid};
1026 if ($DEBUG_MODE) { print "REAPED Process $pid exited.\n"; }
1027 if ($DEBUG_MODE) { print "REAPED $pid: $?\n"; }
1028 } else {
1029 if ($DEBUG_MODE) { print "REAPED False alarm on $pid.\n" }
1030 }
1031 }
1032 if ($DEBUG_MODE) { print "FINISHED REAPING\n"; }
1033 $SIG{CHLD} = \&reaper;
1034 if ($DEBUG_MODE) { print "EXIT REAPER!\n"; }
1035 }
1036  
1037  
1038 =head2 terminator()
1039  
1040 The terminator() function is responsible for shutting down a Helios service
1041 instance when helios.pl receives a SIGTERM signal. The shutdown process
1042 performs several steps:
1043  
1044 =over 4
1045  
1046 =item *
1047  
1048 Sets HALT in the Helios config params for the loaded service, so the
1049 worker processes know to exit at the end of their current job
1050  
1051 =item *
1052  
1053 Sleeps a certain amount of time (zero_launch_interval x 2 secs) to
1054 allow worker processes to complete the jobs they are processing and exit
1055  
1056 =item *
1057  
1058 Reaps any ended worker processes, and forcably kills any that are still
1059 running. After zero_launch_interval seconds, workers for a particular service
1060 should have exited if HALT is set. If you use this method of shutting down
1061 Helios services and repeatedly see a particular service's workers not exiting
1062 properly, increase the value of the zero_launch_interval configuration
1063 parameter for that service in your helios.ini or Helios::Panoptes Ctrl Panel.
1064  
1065 =item *
1066  
1067 Clears the HALT parameter set earlier, since all of the workers are now
1068 shut down (one way or the other).
1069  
1070 =item *
1071  
1072 Removes the service's PID file written in the pid_path set in
1073 helios.ini
1074  
1075 =item *
1076  
1077 Unregister's with the Helios collective's registry table in the Helios
1078 database
1079  
1080 =item *
1081  
1082 Issues a final log message indicating the loaded service has shut down
1083 on the current host
1084  
1085 =back
1086  
1087 Once all these steps are complete, the helios.pl program exits.
1088  
1089  
1090 =cut
1091  
1092 sub terminator {
1093 my $TERM = 0;
1094 # did we receive a SIGTERM, or was the HALT config param set?
1095 if ( defined($params->{HALT}) ) {
1096 $worker->logMsg(LOG_NOTICE, "HALTING $OPT_CLASS on host ".$worker->getHostname());
1097 } else {
1098 # tell the workers they need exit
1099 $TERM = 1;
1100 $worker->logMsg(LOG_NOTICE, "Received TERM signal; HALTING $OPT_CLASS on host ".$worker->getHostname());
1101 $worker->logMsg(LOG_NOTICE, "Setting HALT for $OPT_CLASS on host ".$worker->getHostname());
1102 set_halt();
1103 }
1104  
1105 # sleep long enough for the workers to shutdown on their own
1106 $SIG{CHLD} = 'DEFAULT';
1107 sleep $ZERO_LAUNCH_INTERVAL;
1108 sleep $ZERO_LAUNCH_INTERVAL;
1109 # reap any processes that ended while we were sleeping
1110 $worker->logMsg(LOG_NOTICE, "Reaping $OPT_CLASS workers on host ".$worker->getHostname());
1111 reaper();
1112
1113 # kill any workers still running (they've had plenty of time to end on their own)
1114 foreach my $pid (keys %workers) {
1115 if ( kill 0 => $pid ) {
1116 # it's still alive, kill it
1117 kill 9, $pid;
1118 $worker->logMsg(LOG_ERR, "Killed process $pid (shutdown $OPT_CLASS instance)");
1119 }
1120 delete $workers{$pid};
1121 }
1122
1123 # workers are all taken care of, shutdown ourself
1124 # only clear the HALT if we received a SIGTERM (we set the halt ourselves)
1125 if ($TERM) {
1126 clear_halt();
1127 $worker->logMsg(LOG_NOTICE, "Cleared HALT for $OPT_CLASS on host ".$worker->getHostname());
1128 }
1129 clean_shutdown();
1130 $worker->logMsg(LOG_NOTICE, "$OPT_CLASS on host ".$worker->getHostname().' HALTED.');
1131 exit(1);
1132 }
1133  
1134  
1135 # [LH] 2013-08-04: Added 2nd paragraph to write_pid_file() documentation to
1136 # help explain how new running_process_check()/write_pid_file() works.
1137  
1138 =head1 PID FILE FUNCTIONS
1139  
1140 =head2 write_pid_file($pid_path)
1141  
1142 Writes a PID file to a location (defaults to /var/run/helios) to track which daemons are
1143 running. The file will be named after the service class running, all lowercase, with colons
1144 replaced by underscores. For example, the PID file for a service class named
1145 'SearchIndex::LoadTestWorker' will be named "searchindex__loadtestworker.pid". To change the
1146 location where the PID file is created, set the pid_path option in helios.ini.
1147  
1148 The running_process_check() function should be run before this function to
1149 exclusively lock the PID file.
1150  
1151 =cut
1152  
1153 sub write_pid_file {
1154 # BEGIN CODE Copyright (C) 2013 Logical Helion, LLC.
1155 # [LH] 2013-08-04: Rewrote write_pid_file() to take advantage of the
1156 # exclusive lock on the pidfile created by running_process_check().
1157 # [RT81914]
1158  
1159 # Rewind the PID file handle opened by running_process_check(),
1160 # write our own PID in the file, and
1161 # signal to the calling routine it's OK to finish start up.
1162 seek($PID_FILE_H, 0, 0) or do {
1163 $worker->errstr("Cannot rewind $PID_FILE: ".$!);
1164 close($PID_FILE_H);
1165 return 0;
1166 };
1167 print $PID_FILE_H $$,"\n";
1168 truncate($PID_FILE_H, tell($PID_FILE_H)) or do {
1169 $worker->errstr("Cannot truncate $PID_FILE after writing PID: ".$!);
1170 close($PID_FILE_H);
1171 return 0;
1172 };
1173 close($PID_FILE_H);
1174 # END CODE Copyright (C) 2013 Logical Helion, LLC
1175  
1176 return 1;
1177 }
1178  
1179  
1180 =head2 remove_pid_file($pid_file)
1181  
1182 During a clean shutdown, remove_pid_file() is called to delete the PID file
1183 associated with the service daemon.
1184  
1185 =cut
1186  
1187 sub remove_pid_file {
1188 my $pid_file = shift;
1189 unless ( defined($pid_file) ) {
1190 $pid_file = $PID_FILE;
1191 }
1192 unlink $pid_file or do { $worker->errstr("Cannot remove PID file $pid_file: ".$!); return undef; };
1193 return 1;
1194 }
1195  
1196  
1197 # [LH] 2013-08-04: Added 2nd paragraph below to explain how new running_process_check() works.
1198  
1199 =head2 running_process_check($pid_path)
1200  
1201 Given the pid_path, check to see if a $pid_file for the loaded service class exists and, if it does,
1202 check to see if that process is still running. If the file doesn't exist or it does but isn't
1203 running, this function returns 0. If the process is still running, record the error and return the
1204 running process's pid to signal that service startup should halt.
1205  
1206 If the PID file does not exist, running_process_check() creates it. The PID
1207 file is then exclusively locked to prevent other daemons for the same service
1208 from writing to it. This helps ensure multiple Helios daemons for same
1209 service will not start up at the same time.
1210  
1211 =cut
1212  
1213 sub running_process_check {
1214 my $pid_path = shift;
1215 # Determine where the PID file should be
1216 unless (defined($pid_path) ) { $pid_path = $DEFAULTS{PID_PATH}; }
1217  
1218 # Determine PID filename
1219 my $filename = lc($worker_class);
1220 $filename =~ s/\:/\_/g;
1221 $PID_FILE = File::Spec->catfile($pid_path, $filename.'.pid');
1222 if ($DEBUG_MODE) { print "Checking $PID_FILE\n"; }
1223  
1224 # check if this file exists
1225 # if it does, check if that process is still running
1226 # bail if it is
1227 # BEGIN CODE Copyright (C) 2013 Logical Helion, LLC.
1228 # [LH] 2013-08-04: Rewrote this piece of running_process_check() to put
1229 # an exclusive lock on the pidfile (also creating it if it doesn't exist).
1230 # Also switched to using the relatively portable Perl kill() instead of
1231 # grep-ing shell output to determine whether the process in the pidfile
1232 # is still running. [RT81914]
1233 sysopen($PID_FILE_H, $PID_FILE, O_RDWR | O_CREAT) or do {
1234 $worker->errstr("Cannot open $PID_FILE: ".$!);
1235 return 1;
1236 };
1237 flock($PID_FILE_H, LOCK_EX | LOCK_NB) or do {
1238 $worker->errstr("Cannot lock $PID_FILE (another daemon already starting for this service?): ".$!);
1239 close($PID_FILE_H);
1240 return 1;
1241 };
1242
1243 my $pid_in_file = <$PID_FILE_H>;
1244 chomp $pid_in_file if defined($pid_in_file);
1245 # if there's an actual, valid pid in the file,
1246 # check to see if that process is still running
1247 if ( defined($pid_in_file) && $pid_in_file !~ /\D/ && $pid_in_file > 1) {
1248 my $proc_count = kill 0, $pid_in_file;
1249 if ($proc_count > 0) {
1250 $worker->errstr($worker->getJobType()." service daemon already running (process ".$pid_in_file.").");
1251 close($PID_FILE_H);
1252 return $pid_in_file;
1253 }
1254 }
1255
1256 # END CODE Copyright (C) 2013 Logical Helion, LLC.
1257
1258 return 0;
1259 }
1260  
1261  
1262 =head1 OTHER FUNCTIONS
1263  
1264 =head2 clean_shutdown()
1265  
1266 The clean_shutdown function is called when helios.pl is intentionally shutdown
1267 (setting a HALT parameter in the Helios::Panoptes Ctrl Panel or sending the
1268 helios.pl process a TERM signal). It removes the PID file created on
1269 startup and unregisters the service instance from the collective database.
1270  
1271 =cut
1272  
1273 sub clean_shutdown {
1274 remove_pid_file() or $worker->logMsg(LOG_CRIT, $worker->errstr);
1275 unregister() or $worker->logMsg(LOG_CRIT, $worker->errstr);
1276 return 1;
1277 }
1278  
1279  
1280 =head2 register()
1281  
1282 The register() function records information about the currently running worker daemon in the
1283 database. The register() function is designed to be run every $REGISTRATION_INTERVAL seconds.
1284 That way, if a service daemon dies off unexpectedly (without calling unregister()), it can be
1285 determined that something has happened to the daemon and it possibly needs to be restarted.
1286  
1287 (In reality, register() and unregister() are only necessary to provide a display for Panoptes,
1288 to more easily assess system status and facilitate the HALTing of service daemons or HOLDing of
1289 job processing.)
1290  
1291 =cut
1292  
1293 sub register {
1294 # [LH] [2013-10-18]: Replaced try {} block with eval {}.
1295 eval {
1296 my $dbh = $worker->dbConnect();
1297 $dbh->do("DELETE FROM helios_worker_registry_tb WHERE worker_class = ? AND host = ?", undef,
1298 $worker->getJobType(), $worker->getHostname) or die;
1299 $dbh->do("INSERT INTO helios_worker_registry_tb (register_time, start_time, worker_class, worker_version, host, process_id) VALUES (?,?,?,?,?,?)", undef,
1300 time(), $START_TIME, $worker->getJobType(), $worker->VERSION, $worker->getHostname, $$) or die;
1301 1;
1302 } or do {
1303 throw Helios::Error::DatabaseError($DBI::errstr);
1304 };
1305 return 1;
1306 }
1307  
1308  
1309 =head2 unregister()
1310  
1311 The unregister() function removes any record of the currently running daemon from the database.
1312 It is called whenever there is a clean shutdown.
1313  
1314 =cut
1315  
1316 sub unregister {
1317 # [LH] [2013-10-18]: Replaced try {} block with eval {}.
1318 eval {
1319 my $dbh = $worker->dbConnect();
1320 $dbh->do("DELETE FROM helios_worker_registry_tb WHERE worker_class = ? AND host = ?", undef,
1321 $worker->getJobType(), $worker->getHostname) or die;
1322 $dbh->disconnect();
1323 1;
1324 } or do {
1325 throw Helios::Error::DatabaseError($DBI::errstr);
1326 };
1327 return 1;
1328 }
1329  
1330  
1331 =head2 set_halt()
1332  
1333 Set a HALT parameter for the currently loaded service on the current host to
1334 signal to all of the worker processes that they need to exit. This function is
1335 used by the terminator() function to safely signal to workers they need to exit
1336 when the current job is completed.
1337  
1338 =cut
1339  
1340 sub set_halt {
1341 # [LH] [2013-10-18]: Replaced try {} block with eval {}.
1342 eval {
1343 if ($DEBUG_MODE) {
1344 print "Attempting to set HALT for ",$worker->getJobType()," on ",$worker->getHostname(),"\n";
1345 }
1346 my $dbh = $worker->dbConnect();
1347 $dbh->do("INSERT INTO helios_params_tb (worker_class, host, param, value) VALUES (?,?,?,?)", undef,
1348 $worker->getJobType(), $worker->getHostname, 'HALT', '1');
1349 1;
1350 } or do {
1351 throw Helios::Error::DatabaseError($DBI::errstr);
1352 };
1353 return 1;
1354 }
1355  
1356  
1357 =head2 clear_halt()
1358  
1359 If the --clear-halt option is specified on the command line, clear_halt() is called to attempt to
1360 clear the HALT parameter in the HELIOS_PARAMS_TB. For safety reasons, it only clears a HALT for
1361 the loaded service class AND the specific host helios.pl is running on; it will not clear a global
1362 HALT parameter (where the host is specified as '*').
1363  
1364 =cut
1365  
1366 sub clear_halt {
1367 # [LH] [2013-10-18]: Replaced try {} block with eval {}.
1368 eval {
1369 if ($DEBUG_MODE) {
1370 print "Attempting to delete HALT for ",$worker->getJobType()," on ",$worker->getHostname(),"\n";
1371 }
1372 my $dbh = $worker->dbConnect();
1373 $dbh->do("DELETE FROM helios_params_tb WHERE worker_class = ? AND host = ? AND param = ?", undef,
1374 $worker->getJobType(), $worker->getHostname, 'HALT');
1375 1;
1376 } or do {
1377 throw Helios::Error::DatabaseError($DBI::errstr);
1378 };
1379 return 1;
1380 }
1381  
1382 # BEGIN CODE Copyright (C) 2012 by Logical Helion, LLC.
1383 # [LH] 2012-10-12: Added this method to more securely load module code at runtime.
1384  
1385 sub require_module {
1386 my $service_class = shift;
1387
1388 if ( $service_class !~ /^[A-Za-z]([A-Za-z0-9_\-]|:{2})*[A-Za-z0-9_\-]$/ ) {
1389 print STDERR "Sorry, requested name is invalid: $service_class\n";
1390 exit(1);
1391 }
1392 unless ( $service_class->can('new') ) {
1393 eval {
1394 my $class_file = $service_class;
1395 $class_file .= '.pm';
1396 $class_file =~ s/::/\//g;
1397 require $class_file;
1398 1;
1399 } or do {
1400 my $E = $@;
1401 print STDERR "Perl module $service_class could not be loaded: $E\n";
1402 exit(1);
1403 };
1404 }
1405 unless ($service_class->isa('Helios::Service')) {
1406 print STDERR "$service_class is not a subclass of Helios::Service.\n";
1407 exit(1);
1408 }
1409 return 1;
1410 }
1411  
1412 # END CODE Copyright (C) 2012 by Logical Helion, LLC.
1413  
1414 # BEGIN CODE Copyright (C) 2012-4 by Logical Helion, LLC.
1415 # [LH] [2013-09-21]: Code to implement WORKER_LAUNCH_PATTERN feature.
1416 # [LH] [2014-02-28]: Changed algorithm names to: linear, dynamic, optimistic.
1417 # Wrote documentation for function.
1418  
1419 =head2 workers_to_launch($waiting_jobs, $running_workers, $max_workers)
1420  
1421 Given the number of waiting jobs, currently running workers, and maximum
1422 workers to launch, workers_to_launch() returns the number of worker processes
1423 helios.pl should launch to correctly handle the current job workload. There
1424 are several different algorithms helios.pl can use to determine this number,
1425 which is dependent on the environment, available resources, and type of
1426 application. See L<Helios::Configuration> for the list of possible values and
1427 an explanation of the worker launching algorithms.
1428  
1429 =cut
1430  
1431 sub workers_to_launch {
1432 my $waiting_jobs = shift;
1433 my $running_workers = shift;
1434 my $max_workers = shift;
1435 my $wlp = defined($params->{WORKER_LAUNCH_PATTERN}) ? $params->{WORKER_LAUNCH_PATTERN} : $DEFAULTS{WORKER_LAUNCH_PATTERN};
1436  
1437 # how many workers are we able to launch?
1438 my $available_workers = $max_workers - $running_workers;
1439
1440 # if we cannot launch any more workers, then we cannot launch any workers
1441 if ( $available_workers <= 0 ) {
1442 return 0;
1443 }
1444  
1445 # if the waiting jobs >= max_workers, forget all the launcher patterns and blitz
1446 if ( $waiting_jobs >= $max_workers ) {
1447 return $available_workers;
1448 }
1449  
1450 # ok, we might be able to launch some workers
1451 SWITCH: {
1452 # optimistic
1453 # for big, fast collective databases with lots of short running jobs
1454 if ( $wlp eq 'optimistic') {
1455 # launch a worker for each waiting job,
1456 # or all available workers
1457 # whichever is less
1458 if ( $available_workers < $waiting_jobs ) {
1459 return $available_workers;
1460 } else {
1461 return $waiting_jobs;
1462 }
1463 }
1464 # dynamic
1465 # for fast collectives that need to launch workers more slowly
1466 # e.g. an app with a slow or limited shared resource
1467 # this will be the the Helios 3.x default
1468 if ( $wlp eq 'dynamic') {
1469 # launch the difference between running workers and waiting jobs
1470 # e.g. 14 waiting jobs, 10 workers running, launch 4
1471 # if waiting jobs exceed available workers, just launch available workers
1472 my $diff = $waiting_jobs - $running_workers;
1473 if ( $diff <= 0 ) { $diff = 1; }
1474 if ( $available_workers < $diff ) {
1475 return $available_workers;
1476 } else {
1477 return $diff;
1478 }
1479 }
1480 # linear
1481 # for slow collective databases, or apps that only run a
1482 # smaller number of jobs, or longer running jobs
1483 # this was the Helios 2.x default
1484 if ( $wlp eq 'linear') {
1485 return 1;
1486 }
1487 # the default is actually 'linear'
1488 return 1;
1489 }
1490  
1491  
1492 }
1493  
1494 # END CODE Copyright (C) 2012-4 by Logical Helion, LLC.
1495  
1496  
1497 =head1 SEE ALSO
1498  
1499 L<Helios>, L<Helios::Tutorial>, L<Helios::Service>, L<Helios::Configuration>
1500  
1501 =head1 AUTHOR
1502  
1503 Andrew Johnson, E<lt>lajandy at cpan dotorgE<gt>
1504  
1505 =head1 COPYRIGHT AND LICENSE
1506  
1507 Copyright (C) 2007-9 by CEB Toolbox, Inc.
1508  
1509 Portions of this software, where noted, are
1510 Copyright (C) 2012-2014 by Logical Helion, LLC.
1511  
1512 This program is free software; you can redistribute it and/or modify
1513 it under the same terms as Perl itself, either Perl version 5.8.0 or,
1514 at your option, any later version of Perl 5 you may have available.
1515  
1516 =head1 WARRANTY
1517  
1518 This software comes with no warranty of any kind.
1519  
1520 =cut
1521