3 # Abstract class to implement Daemons
6 # * lock and write PID file /var/run/$name.pid to make sure onyl
7 # one instance is running.
8 # * keep lock open during restart
9 # * correctly daemonize (redirect STDIN/STDOUT)
10 # * restart by stop/start, exec, or signal HUP
11 # * daemon restart on error (option 'restart_on_error')
12 # * handle worker processes (option 'max_workers')
13 # * allow to restart while workers are still runningl
14 # (option 'leave_children_open_on_reload')
21 use POSIX
":sys_wait_h";
24 use Time
::HiRes qw
(gettimeofday
);
26 use base
qw(PVE::CLIHandler);
28 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
30 my $daemon_initialized = 0; # we only allow one instance
32 my $close_daemon_lock = sub {
35 return if !$self->{daemon_lock_fh
};
37 close $self->{daemon_lock_fh
};
38 delete $self->{daemon_lock_fh
};
44 print STDERR
"$msg\n";
45 syslog
('err', "%s", $msg);
48 # call this if you fork() from child
49 # Note: we already call this for workers, so it is only required
50 # if you fork inside a simple daemon (max_workers == 0).
51 sub after_fork_cleanup
{
54 &$close_daemon_lock($self);
56 PVE
::INotify
::inotify_close
();
58 for my $sig (qw(CHLD HUP INT TERM QUIT)) {
59 $SIG{$sig} = 'DEFAULT'; # restore default handler
60 # AnyEvent signals only works if $SIG{XX} is
61 # undefined (perl event loop)
62 delete $SIG{$sig}; # so that we can handle events with AnyEvent
66 my $lockpidfile = sub {
69 my $lkfn = $self->{pidfile
} . ".lock";
73 if (my $fd = $self->{env_pve_lock_fd
}) {
75 $self->{daemon_lock_fh
} = IO
::Handle-
>new_from_fd($fd, "a");
80 $self->{daemon_lock_fh
} = IO
::File-
>new(">>$lkfn");
83 if (!$self->{daemon_lock_fh
}) {
84 die "can't open lock '$lkfn' - $!\n";
87 for (my $i = 0; $i < $waittime; $i ++) {
88 return if flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
);
92 if (!flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
)) {
93 &$close_daemon_lock($self);
96 my ($running, $pid) = $self->running();
98 die "can't aquire lock '$lkfn' - daemon already started (pid = $pid)\n";
100 die "can't aquire lock '$lkfn' - $err\n";
105 my $writepidfile = sub {
108 my $pidfile = $self->{pidfile
};
110 die "can't open pid file '$pidfile' - $!\n" if !open (PIDFH
, ">$pidfile");
116 my $server_cleanup = sub {
119 unlink $self->{pidfile
} . ".lock";
120 unlink $self->{pidfile
};
123 my $finish_workers = sub {
126 foreach my $id (qw(workers old_workers)) {
127 foreach my $cpid (keys %{$self->{$id}}) {
128 my $waitpid = waitpid($cpid, WNOHANG
);
129 if (defined($waitpid) && ($waitpid == $cpid)) {
130 delete ($self->{$id}->{$cpid});
131 syslog
('info', "worker $cpid finished");
137 my $start_workers = sub {
140 return if $self->{terminate
};
143 foreach my $cpid (keys %{$self->{workers
}}) {
147 my $need = $self->{max_workers
} - $count;
149 return if $need <= 0;
151 syslog
('info', "starting $need worker(s)");
156 if (!defined ($pid)) {
157 syslog
('err', "can't fork worker");
159 } elsif ($pid) { # parent
160 $self->{workers
}->{$pid} = 1;
161 syslog
('info', "worker $pid started");
164 $0 = "$self->{name} worker";
166 $self->after_fork_cleanup();
168 eval { $self->run(); };
171 sleep(5); # avoid fast restarts
174 syslog
('info', "worker exit");
180 my $terminate_server = sub {
183 $self->{terminate
} = 1; # set flag to avoid worker restart
185 if (!$self->{max_workers
}) {
186 eval { $self->shutdown(); };
191 eval { $self->shutdown(); };
194 # we have workers - send TERM signal
196 foreach my $cpid (keys %{$self->{workers
}}) {
197 kill(15, $cpid); # TERM childs
200 # if configured, leave children running on HUP
201 return if $self->{got_hup_signal
} &&
202 $self->{leave_children_open_on_reload
};
204 # else, send TERM to old workers
205 foreach my $cpid (keys %{$self->{old_workers
}}) {
206 kill(15, $cpid); # TERM childs
209 # nicely shutdown childs (give them max 10 seconds to shut down)
210 my $previous_alarm = alarm(10);
212 local $SIG{ALRM
} = sub { die "timeout\n" };
214 while ((my $pid = waitpid (-1, 0)) > 0) {
215 foreach my $id (qw(workers old_workers)) {
216 if (defined($self->{$id}->{$pid})) {
217 delete($self->{$id}->{$pid});
218 syslog
('info', "worker $pid finished");
222 alarm(0); # avoid race condition
226 alarm ($previous_alarm);
229 syslog
('err', "error stopping workers (will kill them now) - $err");
230 foreach my $id (qw(workers old_workers)) {
231 foreach my $cpid (keys %{$self->{$id}}) {
232 # KILL childs still alive!
233 if (kill (0, $cpid)) {
234 delete($self->{$id}->{$cpid});
235 syslog
("err", "kill worker $cpid");
244 my $server_run = sub {
245 my ($self, $debug) = @_;
247 # fixme: handle restart lockfd
248 &$lockpidfile($self);
250 # remove FD_CLOEXEC bit to reuse on exec
251 $self->{daemon_lock_fh
}->fcntl(Fcntl
::F_SETFD
(), 0);
253 $ENV{PVE_DAEMON_LOCK_FD
} = $self->{daemon_lock_fh
}->fileno;
258 $self->{debug
} = 1 if $debug;
263 open STDIN
, '</dev/null' || die "can't read /dev/null";
264 open STDOUT
, '>/dev/null' || die "can't write /dev/null";
267 if (!$self->{env_restart_pve_daemon
} && !$debug) {
268 PVE
::INotify
::inotify_close
();
270 if (!defined ($spid)) {
271 die "can't put server into background - fork failed";
272 } elsif ($spid) { # parent
275 PVE
::INotify
::inotify_init
();
278 if ($self->{env_restart_pve_daemon
}) {
279 syslog
('info' , "restarting server");
281 &$writepidfile($self);
282 syslog
('info' , "starting server");
287 open STDERR
, '>&STDOUT' || die "can't close STDERR\n";
289 my $old_sig_term = $SIG{TERM
};
290 local $SIG{TERM
} = sub {
291 local ($@, $!, $?); # do not overwrite error vars
292 syslog
('info', "received signal TERM");
293 &$terminate_server($self);
294 &$server_cleanup($self);
295 &$old_sig_term(@_) if $old_sig_term;
298 my $old_sig_quit = $SIG{QUIT
};
299 local $SIG{QUIT
} = sub {
300 local ($@, $!, $?); # do not overwrite error vars
301 syslog
('info', "received signal QUIT");
302 &$terminate_server($self);
303 &$server_cleanup($self);
304 &$old_sig_quit(@_) if $old_sig_quit;
307 my $old_sig_int = $SIG{INT
};
308 local $SIG{INT
} = sub {
309 local ($@, $!, $?); # do not overwrite error vars
310 syslog
('info', "received signal INT");
311 $SIG{INT
} = 'DEFAULT'; # allow to terminate now
312 &$terminate_server($self);
313 &$server_cleanup($self);
314 &$old_sig_int(@_) if $old_sig_int;
318 local ($@, $!, $?); # do not overwrite error vars
319 syslog
('info', "received signal HUP");
320 $self->{got_hup_signal
} = 1;
321 if ($self->{max_workers
}) {
322 &$terminate_server($self);
323 } elsif ($self->can('hup')) {
324 eval { $self->hup() };
330 if ($self->{max_workers
}) {
331 my $old_sig_chld = $SIG{CHLD
};
332 local $SIG{CHLD
} = sub {
333 local ($@, $!, $?); # do not overwrite error vars
334 &$finish_workers($self);
335 &$old_sig_chld(@_) if $old_sig_chld;
339 &$start_workers($self);
341 &$finish_workers($self);
342 last if $self->{terminate
};
352 syslog
('err', "ERROR: $err");
354 &$terminate_server($self);
356 if (my $wait_time = $self->{restart_on_error
}) {
357 $self->restart_daemon($wait_time);
359 $self->exit_daemon(-1);
363 if ($self->{got_hup_signal
}) {
364 $self->restart_daemon();
366 $self->exit_daemon(0);
371 my ($this, $name, $cmdline, %params) = @_;
373 $name = 'daemon' if !$name; # should not happen
381 my $restart = $ENV{RESTART_PVE_DAEMON
};
382 delete $ENV{RESTART_PVE_DAEMON
};
384 my $lockfd = $ENV{PVE_DAEMON_LOCK_FD
};
385 delete $ENV{PVE_DAEMON_LOCK_FD
};
387 if (defined($lockfd)) {
388 die "unable to parse lock fd '$lockfd'\n"
389 if $lockfd !~ m/^(\d+)$/;
390 $lockfd = $1; # untaint
393 die "please run as root\n" if !$restart && ($> != 0);
395 die "can't create more that one PVE::Daemon" if $daemon_initialized;
396 $daemon_initialized = 1;
398 PVE
::INotify
::inotify_init
();
400 my $class = ref($this) || $this;
404 run_dir
=> '/var/run',
405 env_restart_pve_daemon
=> $restart,
406 env_pve_lock_fd
=> $lockfd,
411 foreach my $opt (keys %params) {
412 my $value = $params{$opt};
413 if ($opt eq 'restart_on_error') {
414 $self->{$opt} = $value;
415 } elsif ($opt eq 'stop_wait_time') {
416 $self->{$opt} = $value;
417 } elsif ($opt eq 'run_dir') {
418 $self->{$opt} = $value;
419 } elsif ($opt eq 'max_workers') {
420 $self->{$opt} = $value;
421 } elsif ($opt eq 'leave_children_open_on_reload') {
422 $self->{$opt} = $value;
424 die "unknown daemon option '$opt'\n";
428 if ($restart && $self->{max_workers
}) {
429 if (my $wpids = $ENV{PVE_DAEMON_WORKER_PIDS
}) {
430 foreach my $pid (split(':', $wpids)) {
431 if ($pid =~ m/^(\d+)$/) {
432 $self->{old_workers
}->{$1} = 1;
438 $self->{pidfile
} = "$self->{run_dir}/${name}.pid";
440 $self->{nodename
} = PVE
::INotify
::nodename
();
442 $self->{cmdline
} = [];
444 foreach my $el (@$cmdline) {
445 $el =~ m/^(.*)$/; # untaint
446 push @{$self->{cmdline
}}, $1;
460 my ($self, $status) = @_;
462 syslog
("info", "server stopped");
464 &$server_cleanup($self);
470 my ($self, $waittime) = @_;
472 syslog
('info', "server shutdown (restart)");
474 $ENV{RESTART_PVE_DAEMON
} = 1;
476 if ($self->{max_workers
}) {
477 my @workers = keys %{$self->{workers
}};
478 push @workers, keys %{$self->{old_workers
}};
479 $ENV{PVE_DAEMON_WORKER_PIDS
} = join(':', @workers);
482 sleep($waittime) if $waittime; # avoid high server load due to restarts
484 PVE
::INotify
::inotify_close
();
486 exec (@{$self->{cmdline
}});
488 exit (-1); # never reached?
491 # please overwrite in subclass
492 # this is called at startup - before forking
498 # please overwrite in subclass
502 syslog
('info' , "server closing");
504 if (!$self->{max_workers
}) {
506 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
510 # please define in subclass
514 # syslog('info' , "received signal HUP (restart)");
517 # please overwrite in subclass
522 syslog
('info' , "server is running");
528 my ($self, $debug) = @_;
530 eval { &$server_run($self, $debug); };
532 &$log_err("start failed - $err");
540 my $pid_str = PVE
::Tools
::file_read_firstline
($self->{pidfile
});
542 return 0 if !$pid_str;
544 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
554 my $pid = &$read_pid($self);
557 my $res = PVE
::ProcFSTools
::check_process_running
($pid) ?
1 : 0;
558 return wantarray ?
($res, $pid) : $res;
561 return wantarray ?
(0, 0) : 0;
567 my $pid = &$read_pid($self);
571 if (PVE
::ProcFSTools
::check_process_running
($pid)) {
572 kill(15, $pid); # send TERM signal
574 my $wait_time = $self->{stop_wait_time
} || 5;
576 for (my $i = 0; $i < $wait_time; $i++) {
577 $running = PVE
::ProcFSTools
::check_process_running
($pid);
582 syslog
('err', "server still running - send KILL") if $running;
589 if (-f
$self->{pidfile
}) {
591 # try to get the lock
592 &$lockpidfile($self);
593 &$server_cleanup($self);
596 &$log_err("cleanup failed - $err");
601 sub register_start_command
{
602 my ($self, $description) = @_;
604 my $class = ref($self);
606 $class->register_method({
610 description
=> $description || "Start the daemon.",
612 additionalProperties
=> 0,
615 description
=> "Debug mode - stay in foreground",
622 returns
=> { type
=> 'null' },
627 $self->start($param->{debug
});
633 my $reload_daemon = sub {
634 my ($self, $use_hup) = @_;
636 if ($self->{env_restart_pve_daemon
}) {
639 my ($running, $pid) = $self->running();
644 syslog
('info', "send HUP to $pid");
654 sub register_restart_command
{
655 my ($self, $use_hup, $description) = @_;
657 my $class = ref($self);
659 $class->register_method({
663 description
=> $description || "Restart the daemon (or start if not running).",
665 additionalProperties
=> 0,
668 returns
=> { type
=> 'null' },
673 &$reload_daemon($self, $use_hup);
679 sub register_reload_command
{
680 my ($self, $description) = @_;
682 my $class = ref($self);
684 $class->register_method({
688 description
=> $description || "Reload daemon configuration (or start if not running).",
690 additionalProperties
=> 0,
693 returns
=> { type
=> 'null' },
698 &$reload_daemon($self, 1);
704 sub register_stop_command
{
705 my ($self, $description) = @_;
707 my $class = ref($self);
709 $class->register_method({
713 description
=> $description || "Stop the daemon.",
715 additionalProperties
=> 0,
718 returns
=> { type
=> 'null' },
729 sub register_status_command
{
730 my ($self, $description) = @_;
732 my $class = ref($self);
734 $class->register_method({
738 description
=> "Get daemon status.",
740 additionalProperties
=> 0,
745 enum
=> ['stopped', 'running'],
750 return $self->running() ?
'running' : 'stopped';