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')
15 # * run as different user using setuid/setgid
24 use POSIX
":sys_wait_h";
26 use Socket
qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
30 use Time
::HiRes qw
(gettimeofday
);
32 use base
qw(PVE::CLIHandler);
34 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
36 my $daemon_initialized = 0; # we only allow one instance
37 my $daemon_sockets = [];
39 my $close_daemon_lock = sub {
42 return if !$self->{daemon_lock_fh
};
44 close $self->{daemon_lock_fh
};
45 delete $self->{daemon_lock_fh
};
51 print STDERR
"$msg\n";
52 syslog
('err', "%s", $msg);
55 # call this if you fork() from child
56 # Note: we already call this for workers, so it is only required
57 # if you fork inside a simple daemon (max_workers == 0).
58 sub after_fork_cleanup
{
61 &$close_daemon_lock($self);
63 PVE
::INotify
::inotify_close
();
65 for my $sig (qw(CHLD HUP INT TERM QUIT)) {
66 $SIG{$sig} = 'DEFAULT'; # restore default handler
67 # AnyEvent signals only works if $SIG{XX} is
68 # undefined (perl event loop)
69 delete $SIG{$sig}; # so that we can handle events with AnyEvent
73 my $lockpidfile = sub {
76 my $lkfn = $self->{pidfile
} . ".lock";
80 if (my $fd = $self->{env_pve_lock_fd
}) {
82 $self->{daemon_lock_fh
} = IO
::Handle-
>new_from_fd($fd, "a");
87 $self->{daemon_lock_fh
} = IO
::File-
>new(">>$lkfn");
90 if (!$self->{daemon_lock_fh
}) {
91 die "can't open lock '$lkfn' - $!\n";
94 for (my $i = 0; $i < $waittime; $i ++) {
95 return if flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
);
99 if (!flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
)) {
100 &$close_daemon_lock($self);
103 my ($running, $pid) = $self->running();
105 die "can't aquire lock '$lkfn' - daemon already started (pid = $pid)\n";
107 die "can't aquire lock '$lkfn' - $err\n";
112 my $writepidfile = sub {
115 my $pidfile = $self->{pidfile
};
117 die "can't open pid file '$pidfile' - $!\n" if !open (PIDFH
, ">$pidfile");
123 my $server_cleanup = sub {
126 unlink $self->{pidfile
} . ".lock";
127 unlink $self->{pidfile
};
130 my $finish_workers = sub {
133 foreach my $id (qw(workers old_workers)) {
134 foreach my $cpid (keys %{$self->{$id}}) {
135 my $waitpid = waitpid($cpid, WNOHANG
);
136 if (defined($waitpid) && ($waitpid == $cpid)) {
137 delete ($self->{$id}->{$cpid});
138 syslog
('info', "worker $cpid finished");
144 my $start_workers = sub {
147 return if $self->{terminate
};
150 foreach my $cpid (keys %{$self->{workers
}}) {
154 my $need = $self->{max_workers
} - $count;
156 return if $need <= 0;
158 syslog
('info', "starting $need worker(s)");
163 if (!defined ($pid)) {
164 syslog
('err', "can't fork worker");
166 } elsif ($pid) { # parent
167 $self->{workers
}->{$pid} = 1;
168 syslog
('info', "worker $pid started");
171 $0 = "$self->{name} worker";
173 $self->after_fork_cleanup();
175 eval { $self->run(); };
178 sleep(5); # avoid fast restarts
181 syslog
('info', "worker exit");
187 my $terminate_server = sub {
188 my ($self, $allow_open_children) = @_;
190 $self->{terminate
} = 1; # set flag to avoid worker restart
192 if (!$self->{max_workers
}) {
193 eval { $self->shutdown(); };
198 eval { $self->shutdown(); };
201 # we have workers - send TERM signal
203 foreach my $cpid (keys %{$self->{workers
}}) {
204 kill(15, $cpid); # TERM childs
207 # if configured, leave children running on HUP
208 return if $allow_open_children &&
209 $self->{leave_children_open_on_reload
};
211 # else, send TERM to old workers
212 foreach my $cpid (keys %{$self->{old_workers
}}) {
213 kill(15, $cpid); # TERM childs
216 # nicely shutdown childs (give them max 10 seconds to shut down)
217 my $previous_alarm = alarm(10);
219 local $SIG{ALRM
} = sub { die "timeout\n" };
221 while ((my $pid = waitpid (-1, 0)) > 0) {
222 foreach my $id (qw(workers old_workers)) {
223 if (defined($self->{$id}->{$pid})) {
224 delete($self->{$id}->{$pid});
225 syslog
('info', "worker $pid finished");
229 alarm(0); # avoid race condition
233 alarm ($previous_alarm);
236 syslog
('err', "error stopping workers (will kill them now) - $err");
237 foreach my $id (qw(workers old_workers)) {
238 foreach my $cpid (keys %{$self->{$id}}) {
239 # KILL childs still alive!
240 if (kill (0, $cpid)) {
241 delete($self->{$id}->{$cpid});
242 syslog
("err", "kill worker $cpid");
254 initlog
($self->{name
});
256 my $restart = $ENV{RESTART_PVE_DAEMON
};
257 delete $ENV{RESTART_PVE_DAEMON
};
258 $self->{env_restart_pve_daemon
} = $restart;
260 my $lockfd = $ENV{PVE_DAEMON_LOCK_FD
};
261 delete $ENV{PVE_DAEMON_LOCK_FD
};
262 if (defined($lockfd)) {
263 die "unable to parse lock fd '$lockfd'\n"
264 if $lockfd !~ m/^(\d+)$/;
265 $lockfd = $1; # untaint
267 $self->{env_pve_lock_fd
} = $lockfd;
269 die "please run as root\n" if !$restart && ($> != 0);
271 die "can't create more that one PVE::Daemon" if $daemon_initialized;
272 $daemon_initialized = 1;
274 PVE
::INotify
::inotify_init
();
276 if (my $gidstr = $self->{setgid
}) {
277 my $gid = getgrnam($gidstr) || die "getgrnam failed - $!\n";
278 POSIX
::setgid
($gid) || die "setgid $gid failed - $!\n";
279 $EGID = "$gid $gid"; # this calls setgroups
281 die "detected strange gid\n" if !($GID eq "$gid $gid" && $EGID eq "$gid $gid");
284 if (my $uidstr = $self->{setuid
}) {
285 my $uid = getpwnam($uidstr) || die "getpwnam failed - $!\n";
286 POSIX
::setuid
($uid) || die "setuid $uid failed - $!\n";
288 die "detected strange uid\n" if !($UID == $uid && $EUID == $uid);
291 if ($restart && $self->{max_workers
}) {
292 if (my $wpids = $ENV{PVE_DAEMON_WORKER_PIDS
}) {
293 foreach my $pid (split(':', $wpids)) {
294 if ($pid =~ m/^(\d+)$/) {
295 $self->{old_workers
}->{$1} = 1;
301 $self->{nodename
} = PVE
::INotify
::nodename
();
304 my $server_run = sub {
305 my ($self, $debug) = @_;
307 # fixme: handle restart lockfd
308 &$lockpidfile($self);
310 # remove FD_CLOEXEC bit to reuse on exec
311 $self->{daemon_lock_fh
}->fcntl(Fcntl
::F_SETFD
(), 0);
313 $ENV{PVE_DAEMON_LOCK_FD
} = $self->{daemon_lock_fh
}->fileno;
318 $self->{debug
} = 1 if $debug;
323 open STDIN
, '</dev/null' || die "can't read /dev/null";
324 open STDOUT
, '>/dev/null' || die "can't write /dev/null";
327 if (!$self->{env_restart_pve_daemon
} && !$debug) {
328 PVE
::INotify
::inotify_close
();
330 if (!defined ($spid)) {
331 die "can't put server into background - fork failed";
332 } elsif ($spid) { # parent
335 PVE
::INotify
::inotify_init
();
338 if ($self->{env_restart_pve_daemon
}) {
339 syslog
('info' , "restarting server");
341 &$writepidfile($self);
342 syslog
('info' , "starting server");
347 open STDERR
, '>&STDOUT' || die "can't close STDERR\n";
349 my $old_sig_term = $SIG{TERM
};
350 local $SIG{TERM
} = sub {
351 local ($@, $!, $?); # do not overwrite error vars
352 syslog
('info', "received signal TERM");
353 &$terminate_server($self, 0);
354 &$server_cleanup($self);
355 &$old_sig_term(@_) if $old_sig_term;
358 my $old_sig_quit = $SIG{QUIT
};
359 local $SIG{QUIT
} = sub {
360 local ($@, $!, $?); # do not overwrite error vars
361 syslog
('info', "received signal QUIT");
362 &$terminate_server($self, 0);
363 &$server_cleanup($self);
364 &$old_sig_quit(@_) if $old_sig_quit;
367 my $old_sig_int = $SIG{INT
};
368 local $SIG{INT
} = sub {
369 local ($@, $!, $?); # do not overwrite error vars
370 syslog
('info', "received signal INT");
371 $SIG{INT
} = 'DEFAULT'; # allow to terminate now
372 &$terminate_server($self, 0);
373 &$server_cleanup($self);
374 &$old_sig_int(@_) if $old_sig_int;
378 local ($@, $!, $?); # do not overwrite error vars
379 syslog
('info', "received signal HUP");
380 $self->{got_hup_signal
} = 1;
381 if ($self->{max_workers
}) {
382 &$terminate_server($self, 1);
383 } elsif ($self->can('hup')) {
384 eval { $self->hup() };
390 if ($self->{max_workers
}) {
391 my $old_sig_chld = $SIG{CHLD
};
392 local $SIG{CHLD
} = sub {
393 local ($@, $!, $?); # do not overwrite error vars
394 &$finish_workers($self);
395 &$old_sig_chld(@_) if $old_sig_chld;
398 # catch worker finished during restart phase
399 &$finish_workers($self);
401 # now loop forever (until we receive terminate signal)
403 &$start_workers($self);
405 &$finish_workers($self);
406 last if $self->{terminate
};
416 syslog
('err', "ERROR: $err");
418 &$terminate_server($self, 1);
420 if (my $wait_time = $self->{restart_on_error
}) {
421 $self->restart_daemon($wait_time);
423 $self->exit_daemon(-1);
427 if ($self->{got_hup_signal
}) {
428 $self->restart_daemon();
430 $self->exit_daemon(0);
435 my ($this, $name, $cmdline, %params) = @_;
437 $name = 'daemon' if !$name; # should not happen
442 my $class = ref($this) || $this;
446 pidfile
=> "/var/run/${name}.pid",
452 foreach my $opt (keys %params) {
453 my $value = $params{$opt};
454 if ($opt eq 'restart_on_error') {
455 $self->{$opt} = $value;
456 } elsif ($opt eq 'stop_wait_time') {
457 $self->{$opt} = $value;
458 } elsif ($opt eq 'pidfile') {
459 $self->{$opt} = $value;
460 } elsif ($opt eq 'max_workers') {
461 $self->{$opt} = $value;
462 } elsif ($opt eq 'leave_children_open_on_reload') {
463 $self->{$opt} = $value;
464 } elsif ($opt eq 'setgid') {
465 $self->{$opt} = $value;
466 } elsif ($opt eq 'setuid') {
467 $self->{$opt} = $value;
469 die "unknown daemon option '$opt'\n";
475 $self->{cmdline
} = [map { /^(.*)$/ } @$cmdline];
488 my ($self, $status) = @_;
490 syslog
("info", "server stopped");
492 &$server_cleanup($self);
498 my ($self, $waittime) = @_;
500 syslog
('info', "server shutdown (restart)");
502 $ENV{RESTART_PVE_DAEMON
} = 1;
504 foreach my $ds (@$daemon_sockets) {
505 $ds->fcntl(Fcntl
::F_SETFD
(), 0);
508 if ($self->{max_workers
}) {
509 my @workers = keys %{$self->{workers
}};
510 push @workers, keys %{$self->{old_workers
}};
511 $ENV{PVE_DAEMON_WORKER_PIDS
} = join(':', @workers);
514 sleep($waittime) if $waittime; # avoid high server load due to restarts
516 PVE
::INotify
::inotify_close
();
518 exec (@{$self->{cmdline
}});
520 exit (-1); # never reached?
523 # please overwrite in subclass
524 # this is called at startup - before forking
530 # please overwrite in subclass
534 syslog
('info' , "server closing");
536 if (!$self->{max_workers
}) {
538 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
542 # please define in subclass
546 # syslog('info' , "received signal HUP (restart)");
549 # please overwrite in subclass
554 syslog
('info' , "server is running");
560 my ($self, $debug) = @_;
564 &$server_run($self, $debug);
567 &$log_err("start failed - $err");
575 my $pid_str = PVE
::Tools
::file_read_firstline
($self->{pidfile
});
577 return 0 if !$pid_str;
579 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
586 # checks if the process was started by systemd
587 my $init_ppid = sub {
589 if (getppid() == 1) {
599 my $pid = &$read_pid($self);
602 my $res = PVE
::ProcFSTools
::check_process_running
($pid) ?
1 : 0;
603 return wantarray ?
($res, $pid) : $res;
606 return wantarray ?
(0, 0) : 0;
612 my $pid = &$read_pid($self);
616 if (PVE
::ProcFSTools
::check_process_running
($pid)) {
617 kill(15, $pid); # send TERM signal
619 my $wait_time = $self->{stop_wait_time
} || 5;
621 for (my $i = 0; $i < $wait_time; $i++) {
622 $running = PVE
::ProcFSTools
::check_process_running
($pid);
627 syslog
('err', "server still running - send KILL") if $running;
634 if (-f
$self->{pidfile
}) {
636 # try to get the lock
637 &$lockpidfile($self);
638 &$server_cleanup($self);
641 &$log_err("cleanup failed - $err");
646 sub register_start_command
{
647 my ($self, $description) = @_;
649 my $class = ref($self);
651 $class->register_method({
655 description
=> $description || "Start the daemon.",
657 additionalProperties
=> 0,
660 description
=> "Debug mode - stay in foreground",
667 returns
=> { type
=> 'null' },
673 $self->start($param->{debug
});
675 PVE
::Tools
::run_command
(['systemctl', 'start', $self->{name
}]);
682 my $reload_daemon = sub {
683 my ($self, $use_hup) = @_;
685 if ($self->{env_restart_pve_daemon
}) {
688 my ($running, $pid) = $self->running();
693 syslog
('info', "send HUP to $pid");
703 sub register_restart_command
{
704 my ($self, $use_hup, $description) = @_;
706 my $class = ref($self);
708 $class->register_method({
712 description
=> $description || "Restart the daemon (or start if not running).",
714 additionalProperties
=> 0,
717 returns
=> { type
=> 'null' },
723 &$reload_daemon($self, $use_hup);
725 PVE
::Tools
::run_command
(['systemctl', $use_hup ?
'reload-or-restart' : 'restart', $self->{name
}]);
732 sub register_reload_command
{
733 my ($self, $description) = @_;
735 my $class = ref($self);
737 $class->register_method({
741 description
=> $description || "Reload daemon configuration (or start if not running).",
743 additionalProperties
=> 0,
746 returns
=> { type
=> 'null' },
751 &$reload_daemon($self, 1);
757 sub register_stop_command
{
758 my ($self, $description) = @_;
760 my $class = ref($self);
762 $class->register_method({
766 description
=> $description || "Stop the daemon.",
768 additionalProperties
=> 0,
771 returns
=> { type
=> 'null' },
779 PVE
::Tools
::run_command
(['systemctl', 'stop', $self->{name
}]);
786 sub register_status_command
{
787 my ($self, $description) = @_;
789 my $class = ref($self);
791 $class->register_method({
795 description
=> "Get daemon status.",
797 additionalProperties
=> 0,
802 enum
=> ['stopped', 'running'],
807 return $self->running() ?
'running' : 'stopped';
813 sub create_reusable_socket
{
814 my ($self, $port, $host, $family) = @_;
816 die "no port specifed" if !$port;
818 my ($socket, $sockfd);
820 if (defined($sockfd = $ENV{"PVE_DAEMON_SOCKET_$port"}) &&
821 $self->{env_restart_pve_daemon
}) {
823 die "unable to parse socket fd '$sockfd'\n"
824 if $sockfd !~ m/^(\d+)$/;
825 $sockfd = $1; # untaint
827 $socket = IO
::Socket
::IP-
>new;
828 $socket->fdopen($sockfd, 'w') ||
829 die "cannot fdopen file descriptor '$sockfd' - $!\n";
831 $socket->fcntl(Fcntl
::F_SETFD
(), Fcntl
::FD_CLOEXEC
);
834 $socket = IO
::Socket
::IP-
>new(
840 GetAddrInfoFlags
=> 0,
842 die "unable to create socket - $@\n";
844 # we often observe delays when using Nagle algorithm,
845 # so we disable that to maximize performance
846 setsockopt($socket, IPPROTO_TCP
, TCP_NODELAY
, 1);
848 $ENV{"PVE_DAEMON_SOCKET_$port"} = $socket->fileno;
851 push @$daemon_sockets, $socket;