blib/lib/HADaemon/Control.pm untested

filter: Statementstmt 0.0% 0 / 629 Branchbran 0.0% 0 / 184 Conditioncond 0.0% 0 / 290 Subroutinesub 0.0% 0 / 70 Podpod 0.0% 0 / 57 totaltotal 0.0% 0 / 1230 CC 92 SCAR 32.5
CC
92
Cov
0%
_fork
132.0
do_restart
56.0
_acquire_lock_and_launch_program
56.0
CRAP 25.7
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.003';
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->_check_pid_via_kill($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 _check_pid_via_kill {
618 my ($self, $pid) = @_;
619  
620 my $kill_result = kill 0 => $pid;
621 my $os_error = $!;
622  
623 if (!$kill_result and $os_error == POSIX::EINVAL) {
624 $self->die("_check_pid_via_kill: kill returned EINVAL, this is very weird");
625 }
626 elsif (!$kill_result and $os_error == POSIX::EPERM) {
627 # process exists but might belong to a different UID, that's fine
628 $kill_result = 1;
629 }
630 elsif (!$kill_result and $os_error == POSIX::ESRCH) {
631 # process not found, that's fine
632 }
633  
634 return $kill_result;
635 }
636  
637 sub _wait_standbys_to_complete {
638 my ($self) = @_;
639 $self->trace('_wait_all_standbys_to_complete()');
640  
641 my $end = Time::HiRes::time + $self->_standby_timeout;
642 while (Time::HiRes::time < $end) {
643 return 1 if $self->_standby_running() == 0;
644 Time::HiRes::sleep(0.1);
645 }
646  
647 return 0;
648 }
649  
650 sub _fork {
651 my ($self) = @_;
652 $self->trace("_double_fork()");
653 my $parent_pid = $$;
654  
655 my $pid = fork();
656 $pid and $self->trace("forked $pid");
657  
658 if ($pid == 0) { # Child, launch the process here
659 # Become session leader
660 POSIX::setsid() or $self->die("failed to setsid: $!");
661  
662 my $pid2 = fork();
663 $pid2 and $self->trace("forked $pid2");
664  
665 if ($pid2 == 0) { # Our double fork.
666 if ($self->close_fds_on_start) {
667 # close all file handlers but logging one
668 my $log_fd = fileno($self->{log_fh});
669 my $max_fd = POSIX::sysconf( &POSIX::_SC_OPEN_MAX );
670 $max_fd = 64 if !defined $max_fd or $max_fd < 0;
671 $log_fd != $_ and POSIX::close($_) foreach (3 .. $max_fd);
672 }
673  
674 # reopening STDIN, STDOUT, STDERR and redirect them to log_file
675 # I need to redirect them because otherwise standbys will keep
676 # handles inherited from parent opened for unpredictable amount of time.
677 # When a standby become main, it redirect its STDOUT STDERR to
678 # $self->stdout_file and $self->stderr_file respectively
679 $self->trace("redirect std file handles to " . $self->log_file);
680 open(STDIN, '<', '/dev/null') or $self->die("Failed to open STDIN: $!");
681 open(STDOUT, '>>', $self->log_file) or $self->die("Failed to open STDOUT to " . $self->log_file . ": $!");
682 open(STDERR, '>>', $self->log_file) or $self->die("Failed to open STDERR to " . $self->log_file . ": $!");
683  
684 if ($self->gid) {
685 $self->trace("setgid(" . $self->gid . ")");
686 POSIX::setgid($self->gid) or $self->die("failed to setgid: $!");
687 }
688  
689 if ($self->uid) {
690 $self->trace("setuid(" . $self->uid . ")");
691 POSIX::setuid($self->uid) or $self->die("failed to setuid: $!");
692  
693 $ENV{USER} = $self->{user};
694 $ENV{HOME} = $self->{user_home_dir};
695 $self->trace("\$ENV{USER} => " . $ENV{USER});
696 $self->trace("\$ENV{HOME} => " . $ENV{HOME});
697 }
698  
699 if ($self->umask) {
700 umask($self->umask) or $self->warn("failed to umask: $!");
701 $self->trace("umask(" . $self->umask . ")");
702 }
703  
704 if ($self->directory) {
705 chdir($self->directory) or $self->die("failed to chdir to " . $self->directory . ": $!");
706 $self->trace("chdir(" . $self->directory . ")");
707 }
708  
709 $self->process_name_change
710 and $0 = $self->name;
711  
712 exit($self->_acquire_lock_and_launch_program() // 0);
713 } elsif (not defined $pid2) {
714 $self->warn("cannot fork: $!");
715 POSIX::_exit(1);
716 } else {
717 $self->info("parent process ($parent_pid) forked child ($pid2)");
718 POSIX::_exit(0);
719 }
720 } elsif (not defined $pid) { # We couldn't fork =(
721 $self->die("cannot fork: $!");
722 } else {
723 # Wait until first kid terminates
724 $self->trace("waitpid()");
725 waitpid($pid, 0);
726 }
727 }
728  
729 sub _redirect_std_filehandles {
730 my ($self) = @_;
731  
732 my $stdout = $self->stdout_file;
733 if ($stdout && $stdout ne $self->log_file) {
734 open(STDOUT, '>>', $stdout) or $self->die("Failed to open STDOUT to $stdout: $!");
735 $self->trace("STDOUT redirected to $stdout");
736 }
737  
738 my $stderr = $self->stderr_file;
739 if ($stderr && $stderr ne $self->log_file) {
740 open(STDERR, '>>', $stderr) or $self->die("Failed to open STDERR to $stderr: $!");
741 $self->trace("STDERR redirected to $stderr");
742 }
743 }
744  
745 sub _acquire_lock_and_launch_program {
746 my ($self) = @_;
747 $self->trace("_acquire_lock_and_launch_program()");
748 return if $self->_check_stop_file();
749  
750 my $pid_file = $self->_build_pid_file("unknown-$$");
751 $self->_write_file($pid_file, $$);
752 $self->{pid_file} = $pid_file;
753  
754 my $ipc = IPC::ConcurrencyLimit::WithStandby->new(%{ $self->ipc_cl_options });
755  
756 # have to duplicate this logic from IPC::CL:WS
757 my $retries_classback = $ipc->{retries};
758 if (ref $retries_classback ne 'CODE') {
759 my $max_retries = $retries_classback;
760 $retries_classback = sub { return $_[0] != $max_retries + 1 };
761 }
762  
763 my $ipc_weak = $ipc;
764 weaken($ipc_weak);
765  
766 $ipc->{retries} = sub {
767 if ($_[0] == 1) { # run code on first attempt
768 my $id = $ipc_weak->{standby_lock}->lock_id();
769 $self->info("acquired standby lock $id");
770  
771 # adjusting name of pidfile
772 my $pid_file = $self->_build_pid_file("standby-$id");
773 $self->_rename_file($self->{pid_file}, $pid_file);
774 $self->{pid_file} = $pid_file;
775 }
776  
777 return 0 if $self->_check_stop_file();
778 return $retries_classback->(@_);
779 };
780  
781 my $id = $ipc->get_lock();
782 if (not $id) {
783 $self->_unlink_file($self->{pid_file});
784 $self->info('failed to acquire both locks, exiting...');
785 return 1;
786 }
787  
788 $self->info("acquired main lock id: " . $ipc->lock_id());
789  
790 $self->{ipc_cl_lock_id} = $ipc->lock_id;
791
792 # now pid file should be 'main-$id'
793 $pid_file = $self->_build_pid_file("main-$id");
794 $self->_rename_file($self->{pid_file}, $pid_file);
795 $self->{pid_file} = $pid_file;
796  
797 my $res = 0;
798 if (not $self->_check_stop_file()) {
799 # redirect stdou stderr if needed
800 $self->_redirect_std_filehandles();
801  
802 # let client be aware of lock fd
803 my $lock_fd = $self->_main_lock_fd($ipc);
804 $lock_fd and $ENV{HADC_lock_fd} = $lock_fd;
805  
806 # reset close-on-exec flag is required
807 $self->reset_close_on_exec_main_lock_fd
808 and $self->_reset_close_on_exec_main_lock_fd($ipc);
809  
810 # about to start the app, log_fh is not needed anymore
811 close($self->{log_fh});
812  
813 # start the app
814 $res = $self->_launch_program();
815 }
816  
817 $self->_unlink_file($self->{pid_file});
818 return $res // 0;
819 }
820  
821 sub _launch_program {
822 my ($self) = @_;
823 $self->trace("_launch_program()");
824 my @args = @{ $self->program_args // [] };
825 return $self->program->($self, @args);
826 }
827  
828 sub _expected_main_processes {
829 my ($self) = @_;
830 my $num = $self->{ipc_cl_options}->{max_procs} // 0;
831 my @expected = map { "main-$_" } ( 1 .. $num );
832 return wantarray ? @expected : scalar @expected;
833 }
834  
835 sub _expected_standby_processes {
836 my ($self) = @_;
837 my $num = $self->{ipc_cl_options}->{standby_max_procs} // 0;
838 my @expected = map { "standby-$_" } ( 1 .. $num );
839 return wantarray ? @expected : scalar @expected;
840 }
841  
842 #####################################
843 # file routines
844 #####################################
845 sub _build_pid_file {
846 my ($self, $type) = @_;
847 return $self->pid_dir . "/$type.pid";
848 }
849  
850 sub _build_main_stop_file {
851 my ($self, $pid) = @_;
852 return ($self->main_stop_file =~ s/%p/$pid/gr);
853 }
854  
855 sub _build_main_upgrade_file {
856 my ($self, $pid) = @_;
857 return ($self->main_upgrade_file =~ s/%p/$pid/gr);
858 }
859  
860 sub _read_file {
861 my ($self, $file) = @_;
862 return undef unless -f $file;
863  
864 open(my $fh, '<', $file) or $self->die("failed to read $file: $!");
865 my $content = do { local $/; <$fh> };
866 close($fh);
867  
868 $self->trace("read '$content' from file ($file)");
869 return $content;
870 }
871  
872 sub _write_file {
873 my ($self, $file, $content) = @_;
874 $content //= '';
875  
876 open(my $fh, '>', $file) or $self->die("failed to write $file: $!");
877 print $fh $content;
878 close($fh);
879  
880 $self->trace("wrote '$content' to file ($file)");
881 }
882  
883 sub _rename_file {
884 my ($self, $old_file, $new_file) = @_;
885 rename($old_file, $new_file) or $self->die("failed to rename '$old_file' to '$new_file': $!");
886 $self->trace("rename pid file ($old_file) to ($new_file)");
887 }
888  
889 sub _unlink_file {
890 my ($self, $file) = @_;
891 return unless -f $file;
892 unlink($file) or $self->die("failed to unlink file '$file': $!");
893 $self->trace("unlink file ($file)");
894 }
895  
896 sub _create_dir {
897 my ($self, $dir) = @_;
898 if (-d $dir) {
899 $self->trace("Dir exists ($dir) - no need to create");
900 } else {
901 my $make_path_args = { mode => 0755, error => \my $errors };
902 if ($self->uid) {
903 $make_path_args->{user} = $self->uid;
904 }
905 if ($self->gid) {
906 $make_path_args->{group} = $self->gid;
907 }
908  
909 make_path($dir, $make_path_args);
910 @$errors and $self->die("failed make_path: " . join(' ', map { keys $_, values $_ } @$errors));
911 $self->trace("Created dir ($dir)");
912 }
913 }
914  
915 sub _precreate_directories {
916 my ($self) = @_;
917 $self->_create_dir($self->pid_dir);
918 $self->_create_dir($self->{ipc_cl_options}->{path});
919 $self->_create_dir($self->{ipc_cl_options}->{standby_path});
920  
921 if ($self->{main_stop_file}) {
922 $self->_create_dir(dirname($self->{main_stop_file}));
923 }
924 if ($self->{standby_stop_file}) {
925 $self->_create_dir(dirname($self->{standby_stop_file}));
926 }
927 if ($self->{main_upgrade_file}) {
928 $self->_create_dir(dirname($self->{main_upgrade_file}));
929 }
930 }
931  
932 sub _check_stop_file {
933 my $self = shift;
934 if (-f $self->standby_stop_file()) {
935 $self->info('standby stop file detected');
936 return 1;
937 } else {
938 return 0;
939 }
940 }
941  
942 #####################################
943 # uid/gid routines
944 #####################################
945 sub user {
946 my ($self, $user) = @_;
947  
948 if ($user) {
949 my $uid = getpwnam($user)
950 or die "Error: Couldn't get uid for non-existent user $user";
951  
952 $self->{uid} = $uid;
953 $self->{user} = $user;
954 $self->trace("Set UID => $uid");
955 }
956  
957 return $self->{user};
958 }
959  
960 sub group {
961 my ($self, $group) = @_;
962  
963 if ($group) {
964 my $gid = getgrnam($group)
965 or die "Error: Couldn't get gid for non-existent group $group";
966  
967 $self->{gid} = $gid;
968 $self->{group} = $group;
969 $self->trace("Set GID => $gid");
970 }
971  
972 return $self->{group};
973 }
974  
975 #####################################
976 # lock detection logic
977 #####################################
978 sub detect_stolen_lock {
979 my ($self) = @_;
980 $self->_main_running() != $self->_expected_main_processes() && $self->_standby_running() == $self->_expected_standby_processes()
981 and $self->warn("one of main processes failed to acquire main lock, something is possibly holding it!!!");
982 }
983  
984 sub _main_lock_fd {
985 my ($self, $ipc) = @_;
986 if ( exists $ipc->{main_lock}
987 && exists $ipc->{main_lock}->{lock_obj}
988 && exists $ipc->{main_lock}->{lock_obj}->{lock_fh})
989 {
990 my $fd = fileno($ipc->{main_lock}->{lock_obj}->{lock_fh});
991 $self->trace("detected lock fd: $fd");
992 return $fd;
993 }
994  
995 $self->warn("failed to detect lock fd");
996 return undef;
997 }
998  
999 sub _reset_close_on_exec_main_lock_fd {
1000 my ($self, $ipc) = @_;
1001 if ( exists $ipc->{main_lock}
1002 && exists $ipc->{main_lock}->{lock_obj}
1003 && exists $ipc->{main_lock}->{lock_obj}->{lock_fh})
1004 {
1005 $self->info("reset close-on-exec main lock fd");
1006 my $fh = $ipc->{main_lock}->{lock_obj}->{lock_fh};
1007 my $flags = fcntl($fh, Fcntl::F_GETFD, 0) or $self->die("fcntl F_GETFD: $!");
1008 fcntl($fh, Fcntl::F_SETFD, $flags & ~Fcntl::FD_CLOEXEC) or $self->die("fcntl F_SETFD: $!");
1009 }
1010 }
1011  
1012 #####################################
1013 # misc
1014 #####################################
1015 sub pretty_print {
1016 my ($self, $process_type, $message, $color) = @_;
1017 return if $self->quiet;
1018  
1019 $color //= "green"; # Green is no color.
1020 my $code = $self->color_map->{$color} //= 32; # Green is invalid.
1021  
1022 local $| = 1;
1023 $process_type =~ s/-/ #/;
1024  
1025 if ($ENV{HADC_NO_COLORS}) {
1026 printf("%-40s: %-40s %40s\n", $self->name, $process_type, "[$message]");
1027 } else {
1028 printf("%-40s: %-40s %40s\n", $self->name, $process_type, "\033[$code" ."m[$message]\033[0m");
1029 }
1030 }
1031  
1032 sub _log {
1033 my ($self, $level, $message) = @_;
1034  
1035 # some commands, such as help|foregournd, don't need loggin
1036 # so do lazy initialization
1037 if (not exists $self->{log_fh}) {
1038 open(my $fh, '>>', $self->log_file) or die "failed to open logfile '" . $self->log_file . "': $!\n";
1039 chown(($self->uid // -1), ($self->gid // -1), $fh) if $self->uid || $self->gid;
1040 $self->{log_fh} = $fh;
1041 }
1042  
1043 if ($self->{log_fh} && defined fileno($self->{log_fh})) {
1044 my $now = Time::HiRes::time();
1045 my ($sec, $ms) = split(/[.]/, $now);
1046 my $date = POSIX::strftime("%Y-%m-%d %H:%M:%S", localtime($now)) . sprintf('.%05d', $ms // 0);
1047 printf { $self->{log_fh} } "[%s][%d][%s] %s\n", $date, $$, $level, $message;
1048 $self->{log_fh}->flush();
1049 }
1050 }
1051  
1052 sub _print_check_log_file_for_details {
1053 my ($self) = @_;
1054 printf("check %s for details\n", $self->log_file);
1055 }
1056  
1057 sub _all_actions {
1058 my ($self) = @_;
1059 no strict 'refs';
1060 return map { m/^do_(.+)/ ? $1 : () } keys %{ ref($self) . '::' };
1061 }
1062  
1063 sub _standby_timeout {
1064 my $timeout = int(shift->{ipc_cl_options}->{interval} // 0) * 3;
1065 return $timeout < 1 ? 1 : $timeout;
1066 }
1067  
1068 sub info { $_[0]->_log('INFO', $_[1]); }
1069 sub trace { $ENV{HADC_TRACE} and $_[0]->_log('TRACE', $_[1]); }
1070 sub warn { $_[0]->_log('WARN', $_[1]); warn $_[1] . "\n"; }
1071 sub die { $_[0]->_log('CRIT', $_[1]); die $_[1] . "\n"; }
1072  
1073 #####################################
1074 # init script logic
1075 #####################################
1076 sub _dump_init_script {
1077 my ( $self ) = @_;
1078  
1079 my $data;
1080 while ( my $line = <DATA> ) {
1081 last if $line =~ /^__END__$/;
1082 $data .= $line;
1083 }
1084  
1085 # So, instead of expanding run_template to use a real DSL
1086 # or making TT a dependancy, I'm just going to fake template
1087 # IF logic.
1088 my $init_source_file = $self->init_config
1089 ? $self->run_template(
1090 '[ -r [% FILE %] ] && . [% FILE %]',
1091 { FILE => $self->init_config } )
1092 : "";
1093  
1094 print $self->_run_template(
1095 $data,
1096 {
1097 HEADER => 'Generated at ' . scalar(localtime) . ' with HADaemon::Control ' . ($self->VERSION // 'DEV'),
1098 NAME => $self->name // '',
1099 REQUIRED_START => $self->lsb_start // '',
1100 REQUIRED_STOP => $self->lsb_stop // '',
1101 SHORT_DESCRIPTION => $self->lsb_sdesc // '',
1102 DESCRIPTION => $self->lsb_desc // '',
1103 SCRIPT => $self->path // abs_path($0),
1104 INIT_SOURCE_FILE => $init_source_file,
1105 INIT_CODE_BLOCK => $self->init_code // '',
1106 }
1107 );
1108  
1109 return 0;
1110 }
1111  
1112 sub _run_template {
1113 my ($self, $content, $config) = @_;
1114 $content =~ s/\[% (.*?) %\]/$config->{$1}/g;
1115 return $content;
1116 }
1117  
1118 1;
1119  
1120 __DATA__