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 - terminate them
196 foreach my $cpid (keys %{$self->{workers
}}) {
197 kill(15, $cpid); # TERM childs
200 return if $self->{got_hup_signal
} &&
201 $self->{leave_children_open_on_reload
};
203 # nicely shutdown childs (give them max 10 seconds to shut down)
204 my $previous_alarm = alarm(10);
206 local $SIG{ALRM
} = sub { die "timeout\n" };
208 while ((my $pid = waitpid (-1, 0)) > 0) {
209 if (defined($self->{workers
}->{$pid})) {
210 delete($self->{workers
}->{$pid});
211 syslog
('info', "worker $pid finished");
214 alarm(0); # avoid race condition
218 alarm ($previous_alarm);
221 syslog
('err', "error stopping workers (will kill them now) - $err");
222 foreach my $cpid (keys %{$self->{workers
}}) {
223 # KILL childs still alive!
224 if (kill (0, $cpid)) {
225 delete($self->{workers
}->{$cpid});
226 syslog
("err", "kill worker $cpid");
234 my $server_run = sub {
235 my ($self, $debug) = @_;
237 # fixme: handle restart lockfd
238 &$lockpidfile($self);
240 # remove FD_CLOEXEC bit to reuse on exec
241 $self->{daemon_lock_fh
}->fcntl(Fcntl
::F_SETFD
(), 0);
243 $ENV{PVE_DAEMON_LOCK_FD
} = $self->{daemon_lock_fh
}->fileno;
248 $self->{debug
} = 1 if $debug;
253 open STDIN
, '</dev/null' || die "can't read /dev/null";
254 open STDOUT
, '>/dev/null' || die "can't write /dev/null";
257 if (!$self->{env_restart_pve_daemon
} && !$debug) {
258 PVE
::INotify
::inotify_close
();
260 if (!defined ($spid)) {
261 die "can't put server into background - fork failed";
262 } elsif ($spid) { # parent
265 PVE
::INotify
::inotify_init
();
268 if ($self->{env_restart_pve_daemon
}) {
269 syslog
('info' , "restarting server");
271 &$writepidfile($self);
272 syslog
('info' , "starting server");
277 open STDERR
, '>&STDOUT' || die "can't close STDERR\n";
279 my $old_sig_term = $SIG{TERM
};
280 local $SIG{TERM
} = sub {
281 local ($@, $!, $?); # do not overwrite error vars
282 syslog
('info', "received signal TERM");
283 &$terminate_server($self);
284 &$server_cleanup($self);
285 &$old_sig_term(@_) if $old_sig_term;
288 my $old_sig_quit = $SIG{QUIT
};
289 local $SIG{QUIT
} = sub {
290 local ($@, $!, $?); # do not overwrite error vars
291 syslog
('info', "received signal QUIT");
292 &$terminate_server($self);
293 &$server_cleanup($self);
294 &$old_sig_quit(@_) if $old_sig_quit;
297 my $old_sig_int = $SIG{INT
};
298 local $SIG{INT
} = sub {
299 local ($@, $!, $?); # do not overwrite error vars
300 syslog
('info', "received signal INT");
301 $SIG{INT
} = 'DEFAULT'; # allow to terminate now
302 &$terminate_server($self);
303 &$server_cleanup($self);
304 &$old_sig_int(@_) if $old_sig_int;
308 local ($@, $!, $?); # do not overwrite error vars
309 syslog
('info', "received signal HUP");
310 $self->{got_hup_signal
} = 1;
311 if ($self->{max_workers
}) {
312 &$terminate_server($self);
313 } elsif ($self->can('hup')) {
314 eval { $self->hup() };
320 if ($self->{max_workers
}) {
321 my $old_sig_chld = $SIG{CHLD
};
322 local $SIG{CHLD
} = sub {
323 local ($@, $!, $?); # do not overwrite error vars
324 &$finish_workers($self);
325 &$old_sig_chld(@_) if $old_sig_chld;
329 &$start_workers($self);
331 &$finish_workers($self);
332 last if $self->{terminate
};
342 syslog
('err', "ERROR: $err");
344 # fixme: kill all workers
346 if (my $wait_time = $self->{restart_on_error
}) {
347 $self->restart_daemon($wait_time);
349 $self->exit_daemon(-1);
353 if ($self->{got_hup_signal
}) {
354 $self->restart_daemon();
356 $self->exit_daemon(0);
361 my ($this, $name, $cmdline, %params) = @_;
363 $name = 'daemon' if !$name; # should not happen
371 my $restart = $ENV{RESTART_PVE_DAEMON
};
372 delete $ENV{RESTART_PVE_DAEMON
};
374 my $lockfd = $ENV{PVE_DAEMON_LOCK_FD
};
375 delete $ENV{PVE_DAEMON_LOCK_FD
};
377 if (defined($lockfd)) {
378 die "unable to parse lock fd '$lockfd'\n"
379 if $lockfd !~ m/^(\d+)$/;
380 $lockfd = $1; # untaint
383 die "please run as root\n" if !$restart && ($> != 0);
385 die "can't create more that one PVE::Daemon" if $daemon_initialized;
386 $daemon_initialized = 1;
388 PVE
::INotify
::inotify_init
();
390 my $class = ref($this) || $this;
394 run_dir
=> '/var/run',
395 env_restart_pve_daemon
=> $restart,
396 env_pve_lock_fd
=> $lockfd,
401 foreach my $opt (keys %params) {
402 my $value = $params{$opt};
403 if ($opt eq 'restart_on_error') {
404 $self->{$opt} = $value;
405 } elsif ($opt eq 'stop_wait_time') {
406 $self->{$opt} = $value;
407 } elsif ($opt eq 'run_dir') {
408 $self->{$opt} = $value;
409 } elsif ($opt eq 'max_workers') {
410 $self->{$opt} = $value;
411 } elsif ($opt eq 'leave_children_open_on_reload') {
412 $self->{$opt} = $value;
414 die "unknown daemon option '$opt'\n";
418 if ($restart && $self->{max_workers
}) {
419 if (my $wpids = $ENV{PVE_DAEMON_WORKER_PIDS
}) {
420 foreach my $pid (split(':', $wpids)) {
421 if ($pid =~ m/^(\d+)$/) {
422 $self->{old_workers
}->{$1} = 1;
428 $self->{pidfile
} = "$self->{run_dir}/${name}.pid";
430 $self->{nodename
} = PVE
::INotify
::nodename
();
432 $self->{cmdline
} = [];
434 foreach my $el (@$cmdline) {
435 $el =~ m/^(.*)$/; # untaint
436 push @{$self->{cmdline
}}, $1;
450 my ($self, $status) = @_;
452 syslog
("info", "server stopped");
454 &$server_cleanup($self);
460 my ($self, $waittime) = @_;
462 syslog
('info', "server shutdown (restart)");
464 $ENV{RESTART_PVE_DAEMON
} = 1;
466 if ($self->{max_workers
}) {
467 my @workers = keys %{$self->{workers
}};
468 push @workers, keys %{$self->{old_workers
}};
469 $ENV{PVE_DAEMON_WORKER_PIDS
} = join(':', @workers);
472 sleep($waittime) if $waittime; # avoid high server load due to restarts
474 PVE
::INotify
::inotify_close
();
476 exec (@{$self->{cmdline
}});
478 exit (-1); # never reached?
481 # please overwrite in subclass
482 # this is called at startup - before forking
488 # please overwrite in subclass
492 syslog
('info' , "server closing");
494 if (!$self->{max_workers
}) {
496 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
500 # please define in subclass
504 # syslog('info' , "received signal HUP (restart)");
507 # please overwrite in subclass
512 syslog
('info' , "server is running");
518 my ($self, $debug) = @_;
520 eval { &$server_run($self, $debug); };
522 &$log_err("start failed - $err");
530 my $pid_str = PVE
::Tools
::file_read_firstline
($self->{pidfile
});
532 return 0 if !$pid_str;
534 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
544 my $pid = &$read_pid($self);
547 my $res = PVE
::ProcFSTools
::check_process_running
($pid) ?
1 : 0;
548 return wantarray ?
($res, $pid) : $res;
551 return wantarray ?
(0, 0) : 0;
557 my $pid = &$read_pid($self);
561 if (PVE
::ProcFSTools
::check_process_running
($pid)) {
562 kill(15, $pid); # send TERM signal
564 my $wait_time = $self->{stop_wait_time
} || 5;
566 for (my $i = 0; $i < $wait_time; $i++) {
567 $running = PVE
::ProcFSTools
::check_process_running
($pid);
572 syslog
('err', "server still running - send KILL") if $running;
579 if (-f
$self->{pidfile
}) {
581 # try to get the lock
582 &$lockpidfile($self);
583 &$server_cleanup($self);
586 &$log_err("cleanup failed - $err");
591 sub register_start_command
{
592 my ($self, $description) = @_;
594 my $class = ref($self);
596 $class->register_method({
600 description
=> $description || "Start the daemon.",
602 additionalProperties
=> 0,
605 description
=> "Debug mode - stay in foreground",
612 returns
=> { type
=> 'null' },
617 $self->start($param->{debug
});
623 my $reload_daemon = sub {
624 my ($self, $use_hup) = @_;
626 if ($self->{env_restart_pve_daemon
}) {
629 my ($running, $pid) = $self->running();
634 syslog
('info', "send HUP to $pid");
644 sub register_restart_command
{
645 my ($self, $use_hup, $description) = @_;
647 my $class = ref($self);
649 $class->register_method({
653 description
=> $description || "Restart the daemon (or start if not running).",
655 additionalProperties
=> 0,
658 returns
=> { type
=> 'null' },
663 &$reload_daemon($self, $use_hup);
669 sub register_reload_command
{
670 my ($self, $description) = @_;
672 my $class = ref($self);
674 $class->register_method({
678 description
=> $description || "Reload daemon configuration (or start if not running).",
680 additionalProperties
=> 0,
683 returns
=> { type
=> 'null' },
688 &$reload_daemon($self, 1);
694 sub register_stop_command
{
695 my ($self, $description) = @_;
697 my $class = ref($self);
699 $class->register_method({
703 description
=> $description || "Stop the daemon.",
705 additionalProperties
=> 0,
708 returns
=> { type
=> 'null' },
719 sub register_status_command
{
720 my ($self, $description) = @_;
722 my $class = ref($self);
724 $class->register_method({
728 description
=> "Get daemon status.",
730 additionalProperties
=> 0,
735 enum
=> ['stopped', 'running'],
740 return $self->running() ?
'running' : 'stopped';