blib/lib/HADaemon/Control.pm untested

filter: Statementstmt 0.0% 0 / 622 Branchbran 0.0% 0 / 178 Conditioncond 0.0% 0 / 281 Subroutinesub 0.0% 0 / 69 Podpod 0.0% 0 / 56 totaltotal 0.0% 0 / 1206 CC 89 SCAR 32.5
CC
89
Cov
0%
_fork
132.0
do_restart
56.0
_acquire_lock_and_launch_program
56.0
CRAP 25.9
1 package HADaemon::Control;
2  
3 use v5.14;
4 use strict;
5 use warnings;
6  
7 use Fcntl ();
8 use POSIX ();
9 use Time::HiRes;
10 use Cwd qw(abs_path);
11 use File::Path qw(make_path);
12 use File::Basename qw(dirname);
13 use Scalar::Util qw(weaken);
14 use IPC::ConcurrencyLimit::WithStandby;
15  
16 our $VERSION = '1.002';
17  
18 # Accessor building
19 my @accessors = qw(
20 pid_dir quiet color_map name stop_file_kill_timeout signal_kill_timeout kill_timeout
21 stop_signals program program_args stdout_file stderr_file umask directory ipc_cl_options
22 main_stop_file standby_stop_file uid gid log_file process_name_change close_fds_on_start
23 path init_config init_code lsb_start lsb_stop lsb_sdesc lsb_desc reset_close_on_exec_main_lock_fd
24 main_upgrade_file upgrade_timeout
25 );
26  
27 foreach my $method (@accessors) {
28 no strict 'refs';
29 *$method = sub {
30 my $self = shift;
31 $self->{$method} = shift if @_;
32 return $self->{$method};
33 }
34 }
35  
36 sub new {
37 my ($class, @in) = @_;
38 my $args = ref $in[0] eq 'HASH' ? $in[0] : { @in };
39  
40 my $self = bless {
41 color_map => { red => 31, green => 32 },
42 quiet => 0,
43 }, $class;
44  
45 foreach my $accessor (@accessors) {
46 if (exists $args->{$accessor}) {
47 $self->{$accessor} = delete $args->{$accessor};
48 }
49 }
50  
51 $self->user(delete $args->{user}) if exists $args->{user};
52 $self->group(delete $args->{group}) if exists $args->{group};
53  
54 die "Unknown arguments to the constructor: " . join(' ' , keys %$args)
55 if keys %$args;
56  
57 return $self;
58 }
59  
60 sub run {
61 my ($self) = @_;
62 return $self->run_command(@ARGV);
63 }
64  
65 sub run_command {
66 my ($self, $arg) = @_;
67  
68 # Error Checking.
69 $self->program && ref $self->program eq 'CODE'
70 or die "Error: program must be defined and must be coderef\n";
71 $self->name
72 or die "Error: name must be defined\n";
73 $self->pid_dir
74 or die "Error: pid_dir must be defined\n";
75 $self->log_file
76 or die "Error: log_file must be defined\n";
77  
78 defined($self->kill_timeout)
79 or $self->kill_timeout(1);
80  
81 defined($self->close_fds_on_start)
82 or $self->close_fds_on_start(1);
83  
84 $self->standby_stop_file
85 or $self->standby_stop_file($self->pid_dir . '/standby-stop-file');
86  
87 # ipc_cl_options default settings
88 $self->{ipc_cl_options} //= {};
89 $self->{ipc_cl_options}->{type} //= 'Flock';
90 $self->{ipc_cl_options}->{max_procs} //= 1;
91 $self->{ipc_cl_options}->{standby_max_procs} //= 1;
92 $self->{ipc_cl_options}->{interval} //= 1;
93 $self->{ipc_cl_options}->{retries} //= sub { 1 };
94 $self->{ipc_cl_options}->{path} //= $self->pid_dir . '/lock/';
95 $self->{ipc_cl_options}->{standby_path} //= $self->pid_dir . '/lock-standby/';
96  
97 # ipc_cl_options error checking
98 $self->{ipc_cl_options}->{type} ne 'Flock'
99 and die "can work only with Flock backend\n";
100 $self->{ipc_cl_options}->{max_procs} < 1
101 and die "ipc_cl_options: 'max_procs' should be at least 1\n";
102 $self->{process_name_change}
103 and $self->{ipc_cl_options}->{process_name_change} = 1;
104  
105 if ($self->uid) {
106 my @uiddata = getpwuid($self->uid);
107 @uiddata or die "failed to get info about " . $self->uid . "\n";
108  
109 if (!$self->gid) {
110 $self->gid($uiddata[3]);
111 $self->trace("Implicit GID => " . $uiddata[3]);
112 }
113  
114 $self->user
115 or $self->{user} = $uiddata[0];
116  
117 $self->{user_home_dir} = $uiddata[7];
118 }
119  
120 my $called_with = $arg // '';
121 $called_with =~ s/^[-]+//g;
122  
123 if (!$called_with) {
124 return $self->do_help();
125 }
126  
127 # $self->can() create new record in class hash
128 # so $self->_all_actions includes it as well
129 if (not grep { $_ eq $called_with } $self->_all_actions) {
130 warn "Error: unknown action $called_with\n";
131 return $self->do_help();
132 }
133  
134 my $action = "do_$called_with";
135 return $self->$action() // 0;
136 }
137  
138 #####################################
139 # commands
140 #####################################
141 sub do_start {
142 my ($self) = @_;
143 $self->info('do_start()');
144  
145 my $expected_main = $self->_expected_main_processes();
146 my $expected_standby = $self->_expected_standby_processes();
147 if ( $self->_main_running() == $expected_main
148 && $self->_standby_running() == $expected_standby)
149 {
150 $self->pretty_print('starting main + standby processes', 'Already Running');
151 $self->trace("do_start(): all processes are already running");
152 return 0;
153 }
154  
155 $self->_precreate_directories();
156 $self->_unlink_file($self->standby_stop_file);
157  
158 if ($self->_fork_mains() && $self->_fork_standbys()) {
159 $self->pretty_print('starting main + standby processes', 'OK');
160 return 0;
161 }
162  
163 $self->pretty_print('starting main + standby processes', 'Failed', 'red');
164 $self->do_status();
165 $self->detect_stolen_lock();
166 $self->_print_check_log_file_for_details();
167  
168 return 1;
169 }
170  
171 sub do_stop {
172 my ($self) = @_;
173 $self->info('do_stop()');
174  
175 if (!$self->_main_running() && !$self->_standby_running()) {
176 $self->pretty_print('stopping main + standby processes', 'Not Running', 'red');
177 $self->trace("do_stop(): all processes are not running");
178 return 0;
179 }
180  
181 $self->_precreate_directories();
182 $self->_write_file($self->standby_stop_file);
183 $self->_wait_standbys_to_complete();
184  
185 my %mains = map {
186 $_ => $self->_pid_of_process_type($_)
187 } $self->_expected_main_processes();
188  
189 my %running_pids = $self->_kill_pids(values %mains);
190  
191 foreach my $type (%mains) {
192 my $pid = $mains{$type};
193 if ($pid && !exists $running_pids{$pid}) {
194 $self->_unlink_file($self->_build_pid_file($type));
195 }
196 }
197  
198 if ($self->_main_running() == 0 && $self->_standby_running() == 0) {
199 $self->pretty_print('stopping main + standby processes', 'OK');
200 return 0;
201 }
202  
203 $self->pretty_print('stopping main + standby processes', 'Failed', 'red');
204 $self->do_status();
205 $self->_print_check_log_file_for_details();
206 return 1;
207 }
208  
209 sub do_restart {
210 my ($self) = @_;
211 $self->info('do_restart()');
212  
213 # shortcut
214 if (!$self->_main_running() && !$self->_standby_running()) {
215 return $self->do_start();
216 }
217  
218 # another shortcut
219 if ($self->{ipc_cl_options}->{standby_max_procs} <= 0) {
220 return $self->do_hard_restart();
221 }
222  
223 # stoping standby
224 $self->_precreate_directories();
225 $self->_write_file($self->standby_stop_file);
226  
227 if (not $self->_wait_standbys_to_complete()) {
228 $self->pretty_print('stopping standby processes', 'Failed', 'red');
229 $self->warn("all standby processes should be stopped at this moment. Can't move forward");
230 $self->_print_check_log_file_for_details();
231 return 1;
232 }
233  
234 $self->pretty_print('stopping standby processes', 'OK');
235  
236 # starting standby
237 $self->_unlink_file($self->standby_stop_file);
238  
239 if (!$self->_fork_standbys()) {
240 $self->pretty_print('starting standby', 'Failed', 'red');
241 $self->warn("all standby processes should be running at this moment. Can't move forward");
242 $self->_print_check_log_file_for_details();
243 return 1;
244 }
245  
246 $self->pretty_print('starting standby processes', 'OK');
247  
248 my %mains = map {
249 my $type = $_;
250 my $pid = $self->_pid_of_process_type($type)
251 or $self->trace("Main process $type is not running"),
252 next;
253  
254 $type => $pid;
255 } $self->_expected_main_processes();
256  
257 # killing mains, stanbys should be promoted instantly
258 my %running_pids = $self->_kill_pids(values %mains);
259  
260 foreach my $type (%mains) {
261 my $pid = $mains{$type};
262 if ($pid && exists $running_pids{$pid}) {
263 # failed to restart process
264 $self->pretty_print($type, 'Failed to restart', 'red');
265 }
266 }
267  
268 # starting mains
269 if (!$self->_fork_mains() || !$self->_fork_standbys()) {
270 $self->pretty_print('restarting main + standby processes', 'Failed', 'red');
271 $self->warn("all main + standby processes should be running at this moment");
272  
273 $self->do_status();
274 $self->detect_stolen_lock();
275 $self->_print_check_log_file_for_details();
276 return 1;
277 }
278  
279 $self->pretty_print('restarting main processes', 'OK');
280 return 0;
281 }
282  
283 sub do_upgrade {
284 my ($self) = @_;
285 $self->info('do_upgrade()');
286 $self->main_upgrade_file or $self->die("upgrade requires 'main_upgrade_file'");
287  
288 # shortcut
289 if (!$self->_main_running() && !$self->_standby_running()) {
290 return $self->do_start();
291 }
292  
293 # stoping standby
294 $self->_precreate_directories();
295 $self->_write_file($self->standby_stop_file);
296  
297 if (not $self->_wait_standbys_to_complete()) {
298 $self->pretty_print('stopping standby processes', 'Failed', 'red');
299 $self->warn("all standby processes should be stopped at this moment. Can't move forward");
300 $self->_print_check_log_file_for_details();
301 return 1;
302 }
303  
304 $self->pretty_print('stopping standby processes', 'OK');
305  
306 # starting standby
307 $self->_unlink_file($self->standby_stop_file);
308  
309 if (!$self->_fork_standbys()) {
310 $self->pretty_print('starting standby', 'Failed', 'red');
311 $self->warn("all standby processes should be running at this moment. Can't move forward");
312 $self->_print_check_log_file_for_details();
313 return 1;
314 }
315  
316 $self->pretty_print('starting standby processes', 'OK');
317  
318 my %mains = map {
319 my $type = $_;
320 my $pid = $self->_pid_of_process_type($type)
321 or $self->trace("Main process $type is not running"),
322 next;
323  
324 $type => $pid;
325 } $self->_expected_main_processes();
326  
327 # upgrading mains, stanbys should be promoted instantly
328 my %failed_to_upgrade_pids = $self->_upgrade_pids(values %mains);
329 if (!%failed_to_upgrade_pids) {
330 $self->pretty_print('upgrading main processes', 'OK');
331 return 0;
332 }
333  
334 foreach my $type (%mains) {
335 my $pid = $mains{$type};
336 if ($pid && exists $failed_to_upgrade_pids{$pid}) {
337 $self->pretty_print($type, 'Failed to upgrade', 'red');
338 }
339 }
340  
341 return 1;
342 }
343  
344 sub do_hard_restart {
345 my ($self) = @_;
346 $self->info('do_hard_restart()');
347  
348 $self->do_stop();
349 return $self->do_start();
350 }
351  
352 sub do_status {
353 my ($self) = @_;
354 $self->info('do_status()');
355  
356 my $exit_code = 0;
357 foreach my $type ($self->_expected_main_processes(), $self->_expected_standby_processes()) {
358 if ($self->_pid_of_process_type($type)) {
359 $self->pretty_print("$type status", 'Running');
360 } else {
361 $exit_code = 1;
362 $self->pretty_print("$type status", 'Not Running', 'red');
363 }
364 }
365  
366 return $exit_code;
367 }
368  
369 sub do_fork {
370 my ($self) = @_;
371 $self->info('do_fork()');
372  
373 return 1 if $self->_check_stop_file();
374  
375 $self->_precreate_directories();
376 $self->_fork_mains();
377 $self->_fork_standbys();
378  
379 return 0;
380 }
381  
382 sub do_reload {
383 my ($self) = @_;
384 $self->info('do_reload()');
385  
386 foreach my $type ($self->_expected_main_processes()) {
387 my $pid = $self->_pid_of_process_type($type);
388 if ($pid) {
389 $self->_kill_or_die('HUP', $pid);
390 $self->pretty_print($type, 'Reloaded');
391 } else {
392 $self->pretty_print("$type status", 'Not Running', 'red');
393 }
394 }
395 }
396  
397 sub do_get_init_file {
398 my ($self) = @_;
399 $self->info('do_get_init_file()');
400 return $self->_dump_init_script();
401 }
402  
403 sub do_foreground {
404 my ($self) = @_;
405 $self->quiet(1);
406 return $self->_launch_program();
407 }
408  
409 sub do_help {
410 my ($self) = @_;
411 my $allowed_actions = join('|', reverse sort $self->_all_actions());
412 print "Usage: $0 [$allowed_actions]\n\n";
413 return 0;
414 }
415  
416 #####################################
417 # routines to work with processes
418 #####################################
419 sub _fork_mains {
420 my ($self) = @_;
421 my $expected_main = $self->_expected_main_processes();
422  
423 for (1..3) {
424 my $to_start = $expected_main - $self->_main_running();
425 $self->_fork() foreach (1 .. $to_start);
426  
427 my $end = Time::HiRes::time + $self->_standby_timeout;
428 while (Time::HiRes::time < $end) {
429 return 1 if $self->_main_running() == $expected_main;
430 Time::HiRes::sleep(0.1);
431 }
432 }
433  
434 return 0;
435 }
436  
437 sub _fork_standbys {
438 my ($self) = @_;
439 my $expected_standby = $self->_expected_standby_processes();
440  
441 for (1..3) {
442 my $to_start = $expected_standby - $self->_standby_running();
443 $self->_fork() foreach (1 .. $to_start);
444  
445 my $end = Time::HiRes::time + $self->_standby_timeout;
446 while (Time::HiRes::time < $end) {
447 return 1 if $self->_standby_running() == $expected_standby;
448 Time::HiRes::sleep(0.1);
449 }
450 }
451  
452 return 0;
453 }
454  
455 sub _main_running {
456 my ($self) = @_;
457 my @running = grep { $self->_pid_of_process_type($_) } $self->_expected_main_processes();
458 return wantarray ? @running : scalar @running;
459 }
460  
461 sub _standby_running {
462 my ($self) = @_;
463 my @running = grep { $self->_pid_of_process_type($_) } $self->_expected_standby_processes();
464 return wantarray ? @running : scalar @running;
465 }
466  
467 sub _pid_running {
468 my ($self, $pid) = @_;
469  
470 if (not $pid) {
471 $self->trace("_pid_running: invalid pid"),
472 return 0;
473 }
474  
475 my $res = $self->_kill_or_die(0, $pid);
476 $self->trace("pid $pid is " . ($res ? 'running' : 'not running'));
477 return $res;
478 }
479  
480 sub _pid_of_process_type {
481 my ($self, $type) = @_;
482 my $pidfile = $self->_build_pid_file($type);
483 my $pid = $self->_read_file($pidfile);
484 return $pid && $self->_pid_running($pid) ? $pid : undef;
485 }
486  
487 sub _upgrade_pids {
488 my ($self, @p) = @_;
489 $self->trace("_upgrade_pids(): @p");
490  
491 $self->main_upgrade_file or $self->die("upgrade requires 'main_upgrade_file'");
492 my $upgrade_timeout = $self->upgrade_timeout // $self->kill_timeout;
493  
494 my %pids = map {
495 my $pid_and_maybe_cmd = $_;
496 if ($ENV{HADC_TRACE} && open(my $fh, '<', "/proc/$_/cmdline")) {
497 my $cmd = <$fh>;
498 close $fh;
499 $pid_and_maybe_cmd .= " ($cmd)" if $cmd;
500 }
501  
502 $_ => $pid_and_maybe_cmd
503 } grep { $_ } @p;
504  
505 my %upgrade_files;
506 foreach my $pid (keys %pids) {
507 my $file = $self->_build_main_upgrade_file($pid);
508 $upgrade_files{$pid} = $file;
509 $self->_write_file($file);
510 }
511  
512 my $end = Time::HiRes::time + $upgrade_timeout;
513 while (%pids && Time::HiRes::time < $end) {
514 foreach my $pid (keys %pids) {
515 if (not -f $upgrade_files{$pid}) {
516 $self->trace("Successfully upgraded $pids{$pid} via upgrade file");
517 delete $pids{$pid}
518 }
519 }
520  
521 Time::HiRes::sleep(0.1);
522 }
523  
524 foreach my $pid (keys %pids) {
525 $self->info("Failed to upgrade process $pids{$pid} via upgrade file (will drop the file)");
526 $self->_unlink_file($upgrade_files{$pid});
527 }
528  
529 return %pids;
530 }
531  
532 sub _kill_pids {
533 my ($self, @p) = @_;
534 $self->trace("_kill_pids(): @p");
535  
536 my %pids = map {
537 my $pid_and_maybe_cmd = $_;
538 if ($ENV{HADC_TRACE} && open(my $fh, '<', "/proc/$_/cmdline")) {
539 my $cmd = <$fh>;
540 close $fh;
541 $pid_and_maybe_cmd .= " ($cmd)" if $cmd;
542 }
543  
544 $_ => $pid_and_maybe_cmd
545 } grep { $_ } @p;
546  
547 # first create all stopfiles if necessary
548 if ($self->main_stop_file) {
549 foreach my $pid (keys %pids) {
550 $self->_write_file($self->_build_main_stop_file($pid));
551 }
552  
553 my $stop_file_timeout = $self->stop_file_kill_timeout // $self->kill_timeout;
554 my $end = Time::HiRes::time + $stop_file_timeout;
555  
556 while (%pids && Time::HiRes::time < $end) {
557 foreach my $pid (keys %pids) {
558 if (not $self->_pid_running($pid)) {
559 $self->trace("Successfully killed $pids{$pid} via stop file");
560 $self->_unlink_file($self->_build_main_stop_file($pid));
561 delete $pids{$pid}
562 }
563  
564 }
565  
566 Time::HiRes::sleep(0.1);
567 }
568  
569 foreach my $pid (keys %pids) {
570 $self->info("Failed to kill process $pids{$pid} via stop file");
571 $self->_unlink_file($self->_build_main_stop_file($pid));
572 }
573 }
574  
575 my @stop_signals = @{ $self->stop_signals // [qw(TERM TERM INT KILL)] };
576 my $signal_timeout = $self->signal_kill_timeout // $self->kill_timeout;
577  
578 foreach my $signal (@stop_signals) {
579 foreach my $pid (keys %pids) {
580 $self->trace("Sending $signal signal to pid $pids{$pid}...");
581 $self->_kill_or_die($signal, $pid);
582 }
583  
584 my $end = Time::HiRes::time + $signal_timeout;
585 while (%pids && Time::HiRes::time < $end) {
586 foreach my $pid (keys %pids) {
587 if (not $self->_pid_running($pid)) {
588 $self->trace("Successfully killed $pids{$pid}");
589 delete $pids{$pid}
590 }
591  
592 Time::HiRes::sleep(0.1);
593 }
594 }
595 }
596  
597 foreach my $pid (keys %pids) {
598 $self->trace("Failed to kill $pids{$pid}");
599 }
600  
601 return %pids;
602 }
603  
604 sub _kill_or_die {
605 my ($self, $signal, $pid) = @_;
606  
607 my $res = kill($signal, $pid);
608 if (!$res && $! != POSIX::ESRCH) {
609 # don't want to die if proccess simply doesn't exists
610 my $msg = "failed to send signal to pid $pid: $!" . ($! == POSIX::EPERM ? ' (not enough permissions, probably should run as root)' : '');
611 $self->die($msg);
612 }
613  
614 return $res;
615 }
616  
617 sub _wait_standbys_to_complete {
618 my ($self) = @_;
619 $self->trace('_wait_all_standbys_to_complete()');
620  
621 my $end = Time::HiRes::time + $self->_standby_timeout;
622 while (Time::HiRes::time < $end) {
623 return 1 if $self->_standby_running() == 0;
624 Time::HiRes::sleep(0.1);
625 }
626  
627 return 0;
628 }
629  
630 sub _fork {
631 my ($self) = @_;
632 $self->trace("_double_fork()");
633 my $parent_pid = $$;
634  
635 my $pid = fork();
636 $pid and $self->trace("forked $pid");
637  
638 if ($pid == 0) { # Child, launch the process here
639 # Become session leader
640 POSIX::setsid() or $self->die("failed to setsid: $!");
641  
642 my $pid2 = fork();
643 $pid2 and $self->trace("forked $pid2");
644  
645 if ($pid2 == 0) { # Our double fork.
646 if ($self->close_fds_on_start) {
647 # close all file handlers but logging one
648 my $log_fd = fileno($self->{log_fh});
649 my $max_fd = POSIX::sysconf( &POSIX::_SC_OPEN_MAX );
650 $max_fd = 64 if !defined $max_fd or $max_fd < 0;
651 $log_fd != $_ and POSIX::close($_) foreach (3 .. $max_fd);
652 }
653  
654 # reopening STDIN, STDOUT, STDERR and redirect them to log_file
655 # I need to redirect them because otherwise standbys will keep
656 # handles inherited from parent opened for unpredictable amount of time.
657 # When a standby become main, it redirect its STDOUT STDERR to
658 # $self->stdout_file and $self->stderr_file respectively
659 $self->trace("redirect std file handles to " . $self->log_file);
660 open(STDIN, '<', '/dev/null') or $self->die("Failed to open STDIN: $!");
661 open(STDOUT, '>>', $self->log_file) or $self->die("Failed to open STDOUT to " . $self->log_file . ": $!");
662 open(STDERR, '>>', $self->log_file) or $self->die("Failed to open STDERR to " . $self->log_file . ": $!");
663  
664 if ($self->gid) {
665 $self->trace("setgid(" . $self->gid . ")");
666 POSIX::setgid($self->gid) or $self->die("failed to setgid: $!");
667 }
668  
669 if ($self->uid) {
670 $self->trace("setuid(" . $self->uid . ")");
671 POSIX::setuid($self->uid) or $self->die("failed to setuid: $!");
672  
673 $ENV{USER} = $self->{user};
674 $ENV{HOME} = $self->{user_home_dir};
675 $self->trace("\$ENV{USER} => " . $ENV{USER});
676 $self->trace("\$ENV{HOME} => " . $ENV{HOME});
677 }
678  
679 if ($self->umask) {
680 umask($self->umask) or $self->warn("failed to umask: $!");
681 $self->trace("umask(" . $self->umask . ")");
682 }
683  
684 if ($self->directory) {
685 chdir($self->directory) or $self->die("failed to chdir to " . $self->directory . ": $!");
686 $self->trace("chdir(" . $self->directory . ")");
687 }
688  
689 $self->process_name_change
690 and $0 = $self->name;
691  
692 exit($self->_acquire_lock_and_launch_program() // 0);
693 } elsif (not defined $pid2) {
694 $self->warn("cannot fork: $!");
695 POSIX::_exit(1);
696 } else {
697 $self->info("parent process ($parent_pid) forked child ($pid2)");
698 POSIX::_exit(0);
699 }
700 } elsif (not defined $pid) { # We couldn't fork =(
701 $self->die("cannot fork: $!");
702 } else {
703 # Wait until first kid terminates
704 $self->trace("waitpid()");
705 waitpid($pid, 0);
706 }
707 }
708  
709 sub _redirect_std_filehandles {
710 my ($self) = @_;
711  
712 my $stdout = $self->stdout_file;
713 if ($stdout && $stdout ne $self->log_file) {
714 open(STDOUT, '>>', $stdout) or $self->die("Failed to open STDOUT to $stdout: $!");
715 $self->trace("STDOUT redirected to $stdout");
716 }
717  
718 my $stderr = $self->stderr_file;
719 if ($stderr && $stderr ne $self->log_file) {
720 open(STDERR, '>>', $stderr) or $self->die("Failed to open STDERR to $stderr: $!");
721 $self->trace("STDERR redirected to $stderr");
722 }
723 }
724  
725 sub _acquire_lock_and_launch_program {
726 my ($self) = @_;
727 $self->trace("_acquire_lock_and_launch_program()");
728 return if $self->_check_stop_file();
729  
730 my $pid_file = $self->_build_pid_file("unknown-$$");
731 $self->_write_file($pid_file, $$);
732 $self->{pid_file} = $pid_file;
733  
734 my $ipc = IPC::ConcurrencyLimit::WithStandby->new(%{ $self->ipc_cl_options });
735  
736 # have to duplicate this logic from IPC::CL:WS
737 my $retries_classback = $ipc->{retries};
738 if (ref $retries_classback ne 'CODE') {
739 my $max_retries = $retries_classback;
740 $retries_classback = sub { return $_[0] != $max_retries + 1 };
741 }
742  
743 my $ipc_weak = $ipc;
744 weaken($ipc_weak);
745  
746 $ipc->{retries} = sub {
747 if ($_[0] == 1) { # run code on first attempt
748 my $id = $ipc_weak->{standby_lock}->lock_id();
749 $self->info("acquired standby lock $id");
750  
751 # adjusting name of pidfile
752 my $pid_file = $self->_build_pid_file("standby-$id");
753 $self->_rename_file($self->{pid_file}, $pid_file);
754 $self->{pid_file} = $pid_file;
755 }
756  
757 return 0 if $self->_check_stop_file();
758 return $retries_classback->(@_);
759 };
760  
761 my $id = $ipc->get_lock();
762 if (not $id) {
763 $self->_unlink_file($self->{pid_file});
764 $self->info('failed to acquire both locks, exiting...');
765 return 1;
766 }
767  
768 $self->info("acquired main lock id: " . $ipc->lock_id());
769  
770 $self->{ipc_cl_lock_id} = $ipc->lock_id;
771
772 # now pid file should be 'main-$id'
773 $pid_file = $self->_build_pid_file("main-$id");
774 $self->_rename_file($self->{pid_file}, $pid_file);
775 $self->{pid_file} = $pid_file;
776  
777 my $res = 0;
778 if (not $self->_check_stop_file()) {
779 # redirect stdou stderr if needed
780 $self->_redirect_std_filehandles();
781  
782 # let client be aware of lock fd
783 my $lock_fd = $self->_main_lock_fd($ipc);
784 $lock_fd and $ENV{HADC_lock_fd} = $lock_fd;
785  
786 # reset close-on-exec flag is required
787 $self->reset_close_on_exec_main_lock_fd
788 and $self->_reset_close_on_exec_main_lock_fd($ipc);
789  
790 # about to start the app, log_fh is not needed anymore
791 close($self->{log_fh});
792  
793 # start the app
794 $res = $self->_launch_program();
795 }
796  
797 $self->_unlink_file($self->{pid_file});
798 return $res // 0;
799 }
800  
801 sub _launch_program {
802 my ($self) = @_;
803 $self->trace("_launch_program()");
804 my @args = @{ $self->program_args // [] };
805 return $self->program->($self, @args);
806 }
807  
808 sub _expected_main_processes {
809 my ($self) = @_;
810 my $num = $self->{ipc_cl_options}->{max_procs} // 0;
811 my @expected = map { "main-$_" } ( 1 .. $num );
812 return wantarray ? @expected : scalar @expected;
813 }
814  
815 sub _expected_standby_processes {
816 my ($self) = @_;
817 my $num = $self->{ipc_cl_options}->{standby_max_procs} // 0;
818 my @expected = map { "standby-$_" } ( 1 .. $num );
819 return wantarray ? @expected : scalar @expected;
820 }
821  
822 #####################################
823 # file routines
824 #####################################
825 sub _build_pid_file {
826 my ($self, $type) = @_;
827 return $self->pid_dir . "/$type.pid";
828 }
829  
830 sub _build_main_stop_file {
831 my ($self, $pid) = @_;
832 return ($self->main_stop_file =~ s/%p/$pid/gr);
833 }
834  
835 sub _build_main_upgrade_file {
836 my ($self, $pid) = @_;
837 return ($self->main_upgrade_file =~ s/%p/$pid/gr);
838 }
839  
840 sub _read_file {
841 my ($self, $file) = @_;
842 return undef unless -f $file;
843  
844 open(my $fh, '<', $file) or $self->die("failed to read $file: $!");
845 my $content = do { local $/; <$fh> };
846 close($fh);
847  
848 $self->trace("read '$content' from file ($file)");
849 return $content;
850 }
851  
852 sub _write_file {
853 my ($self, $file, $content) = @_;
854 $content //= '';
855  
856 open(my $fh, '>', $file) or $self->die("failed to write $file: $!");
857 print $fh $content;
858 close($fh);
859  
860 $self->trace("wrote '$content' to file ($file)");
861 }
862  
863 sub _rename_file {
864 my ($self, $old_file, $new_file) = @_;
865 rename($old_file, $new_file) or $self->die("failed to rename '$old_file' to '$new_file': $!");
866 $self->trace("rename pid file ($old_file) to ($new_file)");
867 }
868  
869 sub _unlink_file {
870 my ($self, $file) = @_;
871 return unless -f $file;
872 unlink($file) or $self->die("failed to unlink file '$file': $!");
873 $self->trace("unlink file ($file)");
874 }
875  
876 sub _create_dir {
877 my ($self, $dir) = @_;
878 if (-d $dir) {
879 $self->trace("Dir exists ($dir) - no need to create");
880 } else {
881 my $make_path_args = { mode => 0755, error => \my $errors };
882 if ($self->uid) {
883 $make_path_args->{user} = $self->uid;
884 }
885 if ($self->gid) {
886 $make_path_args->{group} = $self->gid;
887 }
888  
889 make_path($dir, $make_path_args);
890 @$errors and $self->die("failed make_path: " . join(' ', map { keys $_, values $_ } @$errors));
891 $self->trace("Created dir ($dir)");
892 }
893 }
894  
895 sub _precreate_directories {
896 my ($self) = @_;
897 $self->_create_dir($self->pid_dir);
898 $self->_create_dir($self->{ipc_cl_options}->{path});
899 $self->_create_dir($self->{ipc_cl_options}->{standby_path});
900  
901 if ($self->{main_stop_file}) {
902 $self->_create_dir(dirname($self->{main_stop_file}));
903 }
904 if ($self->{standby_stop_file}) {
905 $self->_create_dir(dirname($self->{standby_stop_file}));
906 }
907 if ($self->{main_upgrade_file}) {
908 $self->_create_dir(dirname($self->{main_upgrade_file}));
909 }
910 }
911  
912 sub _check_stop_file {
913 my $self = shift;
914 if (-f $self->standby_stop_file()) {
915 $self->info('standby stop file detected');
916 return 1;
917 } else {
918 return 0;
919 }
920 }
921  
922 #####################################
923 # uid/gid routines
924 #####################################
925 sub user {
926 my ($self, $user) = @_;
927  
928 if ($user) {
929 my $uid = getpwnam($user)
930 or die "Error: Couldn't get uid for non-existent user $user";
931  
932 $self->{uid} = $uid;
933 $self->{user} = $user;
934 $self->trace("Set UID => $uid");
935 }
936  
937 return $self->{user};
938 }
939  
940 sub group {
941 my ($self, $group) = @_;
942  
943 if ($group) {
944 my $gid = getgrnam($group)
945 or die "Error: Couldn't get gid for non-existent group $group";
946  
947 $self->{gid} = $gid;
948 $self->{group} = $group;
949 $self->trace("Set GID => $gid");
950 }
951  
952 return $self->{group};
953 }
954  
955 #####################################
956 # lock detection logic
957 #####################################
958 sub detect_stolen_lock {
959 my ($self) = @_;
960 $self->_main_running() != $self->_expected_main_processes() && $self->_standby_running() == $self->_expected_standby_processes()
961 and $self->warn("one of main processes failed to acquire main lock, something is possibly holding it!!!");
962 }
963  
964 sub _main_lock_fd {
965 my ($self, $ipc) = @_;
966 if ( exists $ipc->{main_lock}
967 && exists $ipc->{main_lock}->{lock_obj}
968 && exists $ipc->{main_lock}->{lock_obj}->{lock_fh})
969 {
970 my $fd = fileno($ipc->{main_lock}->{lock_obj}->{lock_fh});
971 $self->trace("detected lock fd: $fd");
972 return $fd;
973 }
974  
975 $self->warn("failed to detect lock fd");
976 return undef;
977 }
978  
979 sub _reset_close_on_exec_main_lock_fd {
980 my ($self, $ipc) = @_;
981 if ( exists $ipc->{main_lock}
982 && exists $ipc->{main_lock}->{lock_obj}
983 && exists $ipc->{main_lock}->{lock_obj}->{lock_fh})
984 {
985 $self->info("reset close-on-exec main lock fd");
986 my $fh = $ipc->{main_lock}->{lock_obj}->{lock_fh};
987 my $flags = fcntl($fh, Fcntl::F_GETFD, 0) or $self->die("fcntl F_GETFD: $!");
988 fcntl($fh, Fcntl::F_SETFD, $flags & ~Fcntl::FD_CLOEXEC) or $self->die("fcntl F_SETFD: $!");
989 }
990 }
991  
992 #####################################
993 # misc
994 #####################################
995 sub pretty_print {
996 my ($self, $process_type, $message, $color) = @_;
997 return if $self->quiet;
998  
999 $color //= "green"; # Green is no color.
1000 my $code = $self->color_map->{$color} //= 32; # Green is invalid.
1001  
1002 local $| = 1;
1003 $process_type =~ s/-/ #/;
1004  
1005 if ($ENV{HADC_NO_COLORS}) {
1006 printf("%-40s: %-40s %40s\n", $self->name, $process_type, "[$message]");
1007 } else {
1008 printf("%-40s: %-40s %40s\n", $self->name, $process_type, "\033[$code" ."m[$message]\033[0m");
1009 }
1010 }
1011  
1012 sub _log {
1013 my ($self, $level, $message) = @_;
1014  
1015 # some commands, such as help|foregournd, don't need loggin
1016 # so do lazy initialization
1017 if (not exists $self->{log_fh}) {
1018 open(my $fh, '>>', $self->log_file) or die "failed to open logfile '" . $self->log_file . "': $!\n";
1019 chown(($self->uid // -1), ($self->gid // -1), $fh) if $self->uid || $self->gid;
1020 $self->{log_fh} = $fh;
1021 }
1022  
1023 if ($self->{log_fh} && defined fileno($self->{log_fh})) {
1024 my $now = Time::HiRes::time();
1025 my ($sec, $ms) = split(/[.]/, $now);
1026 my $date = POSIX::strftime("%Y-%m-%d %H:%M:%S", localtime($now)) . sprintf('.%05d', $ms // 0);
1027 printf { $self->{log_fh} } "[%s][%d][%s] %s\n", $date, $$, $level, $message;
1028 $self->{log_fh}->flush();
1029 }
1030 }
1031  
1032 sub _print_check_log_file_for_details {
1033 my ($self) = @_;
1034 printf("check %s for details\n", $self->log_file);
1035 }
1036  
1037 sub _all_actions {
1038 my ($self) = @_;
1039 no strict 'refs';
1040 return map { m/^do_(.+)/ ? $1 : () } keys %{ ref($self) . '::' };
1041 }
1042  
1043 sub _standby_timeout {
1044 my $timeout = int(shift->{ipc_cl_options}->{interval} // 0) * 3;
1045 return $timeout < 1 ? 1 : $timeout;
1046 }
1047  
1048 sub info { $_[0]->_log('INFO', $_[1]); }
1049 sub trace { $ENV{HADC_TRACE} and $_[0]->_log('TRACE', $_[1]); }
1050 sub warn { $_[0]->_log('WARN', $_[1]); warn $_[1] . "\n"; }
1051 sub die { $_[0]->_log('CRIT', $_[1]); die $_[1] . "\n"; }
1052  
1053 #####################################
1054 # init script logic
1055 #####################################
1056 sub _dump_init_script {
1057 my ( $self ) = @_;
1058  
1059 my $data;
1060 while ( my $line = <DATA> ) {
1061 last if $line =~ /^__END__$/;
1062 $data .= $line;
1063 }
1064  
1065 # So, instead of expanding run_template to use a real DSL
1066 # or making TT a dependancy, I'm just going to fake template
1067 # IF logic.
1068 my $init_source_file = $self->init_config
1069 ? $self->run_template(
1070 '[ -r [% FILE %] ] && . [% FILE %]',
1071 { FILE => $self->init_config } )
1072 : "";
1073  
1074 print $self->_run_template(
1075 $data,
1076 {
1077 HEADER => 'Generated at ' . scalar(localtime) . ' with HADaemon::Control ' . ($self->VERSION // 'DEV'),
1078 NAME => $self->name // '',
1079 REQUIRED_START => $self->lsb_start // '',
1080 REQUIRED_STOP => $self->lsb_stop // '',
1081 SHORT_DESCRIPTION => $self->lsb_sdesc // '',
1082 DESCRIPTION => $self->lsb_desc // '',
1083 SCRIPT => $self->path // abs_path($0),
1084 INIT_SOURCE_FILE => $init_source_file,
1085 INIT_CODE_BLOCK => $self->init_code // '',
1086 }
1087 );
1088  
1089 return 0;
1090 }
1091  
1092 sub _run_template {
1093 my ($self, $content, $config) = @_;
1094 $content =~ s/\[% (.*?) %\]/$config->{$1}/g;
1095 return $content;
1096 }
1097  
1098 1;
1099  
1100 __DATA__