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