blib/lib/HADaemon/Control.pm untested

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