blib/lib/HADaemon/Control.pm untested

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