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
38 my $close_daemon_lock = sub {
41 return if !$self->{daemon_lock_fh
};
43 close $self->{daemon_lock_fh
};
44 delete $self->{daemon_lock_fh
};
50 print STDERR
"$msg\n";
51 syslog
('err', "%s", $msg);
54 # call this if you fork() from child
55 # Note: we already call this for workers, so it is only required
56 # if you fork inside a simple daemon (max_workers == 0).
57 sub after_fork_cleanup
{
60 &$close_daemon_lock($self);
62 PVE
::INotify
::inotify_close
();
64 for my $sig (qw(CHLD HUP INT TERM QUIT)) {
65 $SIG{$sig} = 'DEFAULT'; # restore default handler
66 # AnyEvent signals only works if $SIG{XX} is
67 # undefined (perl event loop)
68 delete $SIG{$sig}; # so that we can handle events with AnyEvent
72 my $lockpidfile = sub {
75 my $lkfn = $self->{pidfile
} . ".lock";
79 if (my $fd = $self->{env_pve_lock_fd
}) {
81 $self->{daemon_lock_fh
} = IO
::Handle-
>new_from_fd($fd, "a");
86 $self->{daemon_lock_fh
} = IO
::File-
>new(">>$lkfn");
89 if (!$self->{daemon_lock_fh
}) {
90 die "can't open lock '$lkfn' - $!\n";
93 for (my $i = 0; $i < $waittime; $i ++) {
94 return if flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
);
98 if (!flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
)) {
99 &$close_daemon_lock($self);
102 my ($running, $pid) = $self->running();
104 die "can't aquire lock '$lkfn' - daemon already started (pid = $pid)\n";
106 die "can't aquire lock '$lkfn' - $err\n";
111 my $writepidfile = sub {
114 my $pidfile = $self->{pidfile
};
116 die "can't open pid file '$pidfile' - $!\n" if !open (PIDFH
, ">$pidfile");
122 my $server_cleanup = sub {
125 unlink $self->{pidfile
} . ".lock";
126 unlink $self->{pidfile
};
129 my $finish_workers = sub {
132 foreach my $id (qw(workers old_workers)) {
133 foreach my $cpid (keys %{$self->{$id}}) {
134 my $waitpid = waitpid($cpid, WNOHANG
);
135 if (defined($waitpid) && ($waitpid == $cpid)) {
136 delete ($self->{$id}->{$cpid});
137 syslog
('info', "worker $cpid finished");
143 my $start_workers = sub {
146 return if $self->{terminate
};
149 foreach my $cpid (keys %{$self->{workers
}}) {
153 my $need = $self->{max_workers
} - $count;
155 return if $need <= 0;
157 syslog
('info', "starting $need worker(s)");
162 if (!defined ($pid)) {
163 syslog
('err', "can't fork worker");
165 } elsif ($pid) { # parent
166 $self->{workers
}->{$pid} = 1;
167 syslog
('info', "worker $pid started");
170 $0 = "$self->{name} worker";
172 $self->after_fork_cleanup();
174 eval { $self->run(); };
177 sleep(5); # avoid fast restarts
180 syslog
('info', "worker exit");
186 my $terminate_server = sub {
187 my ($self, $allow_open_children) = @_;
189 $self->{terminate
} = 1; # set flag to avoid worker restart
191 if (!$self->{max_workers
}) {
192 eval { $self->shutdown(); };
197 eval { $self->shutdown(); };
200 # we have workers - send TERM signal
202 foreach my $cpid (keys %{$self->{workers
}}) {
203 kill(15, $cpid); # TERM childs
206 # if configured, leave children running on HUP
207 return if $allow_open_children &&
208 $self->{leave_children_open_on_reload
};
210 # else, send TERM to old workers
211 foreach my $cpid (keys %{$self->{old_workers
}}) {
212 kill(15, $cpid); # TERM childs
215 # nicely shutdown childs (give them max 10 seconds to shut down)
216 my $previous_alarm = alarm(10);
218 local $SIG{ALRM
} = sub { die "timeout\n" };
220 while ((my $pid = waitpid (-1, 0)) > 0) {
221 foreach my $id (qw(workers old_workers)) {
222 if (defined($self->{$id}->{$pid})) {
223 delete($self->{$id}->{$pid});
224 syslog
('info', "worker $pid finished");
228 alarm(0); # avoid race condition
232 alarm ($previous_alarm);
235 syslog
('err', "error stopping workers (will kill them now) - $err");
236 foreach my $id (qw(workers old_workers)) {
237 foreach my $cpid (keys %{$self->{$id}}) {
238 # KILL childs still alive!
239 if (kill (0, $cpid)) {
240 delete($self->{$id}->{$cpid});
241 syslog
("err", "kill worker $cpid");
253 initlog
($self->{name
});
255 my $restart = $ENV{RESTART_PVE_DAEMON
};
256 delete $ENV{RESTART_PVE_DAEMON
};
257 $self->{env_restart_pve_daemon
} = $restart;
259 my $lockfd = $ENV{PVE_DAEMON_LOCK_FD
};
260 delete $ENV{PVE_DAEMON_LOCK_FD
};
261 if (defined($lockfd)) {
262 die "unable to parse lock fd '$lockfd'\n"
263 if $lockfd !~ m/^(\d+)$/;
264 $lockfd = $1; # untaint
266 $self->{env_pve_lock_fd
} = $lockfd;
268 die "please run as root\n" if !$restart && ($> != 0);
270 die "can't create more that one PVE::Daemon" if $daemon_initialized;
271 $daemon_initialized = 1;
273 PVE
::INotify
::inotify_init
();
275 if (my $gidstr = $self->{setgid
}) {
276 my $gid = getgrnam($gidstr) || die "getgrnam failed - $!\n";
277 POSIX
::setgid
($gid) || die "setgid $gid failed - $!\n";
278 $EGID = "$gid $gid"; # this calls setgroups
280 die "detected strange gid\n" if !($GID eq "$gid $gid" && $EGID eq "$gid $gid");
283 if (my $uidstr = $self->{setuid
}) {
284 my $uid = getpwnam($uidstr) || die "getpwnam failed - $!\n";
285 POSIX
::setuid
($uid) || die "setuid $uid failed - $!\n";
287 die "detected strange uid\n" if !($UID == $uid && $EUID == $uid);
290 if ($restart && $self->{max_workers
}) {
291 if (my $wpids = $ENV{PVE_DAEMON_WORKER_PIDS
}) {
292 foreach my $pid (split(':', $wpids)) {
293 if ($pid =~ m/^(\d+)$/) {
294 $self->{old_workers
}->{$1} = 1;
300 $self->{nodename
} = PVE
::INotify
::nodename
();
303 my $server_run = sub {
304 my ($self, $debug) = @_;
306 # fixme: handle restart lockfd
307 &$lockpidfile($self);
309 # remove FD_CLOEXEC bit to reuse on exec
310 $self->{daemon_lock_fh
}->fcntl(Fcntl
::F_SETFD
(), 0);
312 $ENV{PVE_DAEMON_LOCK_FD
} = $self->{daemon_lock_fh
}->fileno;
317 $self->{debug
} = 1 if $debug;
322 open STDIN
, '</dev/null' || die "can't read /dev/null";
323 open STDOUT
, '>/dev/null' || die "can't write /dev/null";
326 if (!$self->{env_restart_pve_daemon
} && !$debug) {
327 PVE
::INotify
::inotify_close
();
329 if (!defined ($spid)) {
330 die "can't put server into background - fork failed";
331 } elsif ($spid) { # parent
334 PVE
::INotify
::inotify_init
();
337 if ($self->{env_restart_pve_daemon
}) {
338 syslog
('info' , "restarting server");
340 &$writepidfile($self);
341 syslog
('info' , "starting server");
346 open STDERR
, '>&STDOUT' || die "can't close STDERR\n";
348 my $old_sig_term = $SIG{TERM
};
349 local $SIG{TERM
} = sub {
350 local ($@, $!, $?); # do not overwrite error vars
351 syslog
('info', "received signal TERM");
352 &$terminate_server($self, 0);
353 &$server_cleanup($self);
354 &$old_sig_term(@_) if $old_sig_term;
357 my $old_sig_quit = $SIG{QUIT
};
358 local $SIG{QUIT
} = sub {
359 local ($@, $!, $?); # do not overwrite error vars
360 syslog
('info', "received signal QUIT");
361 &$terminate_server($self, 0);
362 &$server_cleanup($self);
363 &$old_sig_quit(@_) if $old_sig_quit;
366 my $old_sig_int = $SIG{INT
};
367 local $SIG{INT
} = sub {
368 local ($@, $!, $?); # do not overwrite error vars
369 syslog
('info', "received signal INT");
370 $SIG{INT
} = 'DEFAULT'; # allow to terminate now
371 &$terminate_server($self, 0);
372 &$server_cleanup($self);
373 &$old_sig_int(@_) if $old_sig_int;
377 local ($@, $!, $?); # do not overwrite error vars
378 syslog
('info', "received signal HUP");
379 $self->{got_hup_signal
} = 1;
380 if ($self->{max_workers
}) {
381 &$terminate_server($self, 1);
382 } elsif ($self->can('hup')) {
383 eval { $self->hup() };
389 if ($self->{max_workers
}) {
390 my $old_sig_chld = $SIG{CHLD
};
391 local $SIG{CHLD
} = sub {
392 local ($@, $!, $?); # do not overwrite error vars
393 &$finish_workers($self);
394 &$old_sig_chld(@_) if $old_sig_chld;
397 # catch worker finished during restart phase
398 &$finish_workers($self);
400 # now loop forever (until we receive terminate signal)
402 &$start_workers($self);
404 &$finish_workers($self);
405 last if $self->{terminate
};
415 syslog
('err', "ERROR: $err");
417 &$terminate_server($self, 1);
419 if (my $wait_time = $self->{restart_on_error
}) {
420 $self->restart_daemon($wait_time);
422 $self->exit_daemon(-1);
426 if ($self->{got_hup_signal
}) {
427 $self->restart_daemon();
429 $self->exit_daemon(0);
434 my ($this, $name, $cmdline, %params) = @_;
436 $name = 'daemon' if !$name; # should not happen
441 my $class = ref($this) || $this;
445 pidfile
=> "/var/run/${name}.pid",
451 foreach my $opt (keys %params) {
452 my $value = $params{$opt};
453 if ($opt eq 'restart_on_error') {
454 $self->{$opt} = $value;
455 } elsif ($opt eq 'stop_wait_time') {
456 $self->{$opt} = $value;
457 } elsif ($opt eq 'pidfile') {
458 $self->{$opt} = $value;
459 } elsif ($opt eq 'max_workers') {
460 $self->{$opt} = $value;
461 } elsif ($opt eq 'leave_children_open_on_reload') {
462 $self->{$opt} = $value;
463 } elsif ($opt eq 'setgid') {
464 $self->{$opt} = $value;
465 } elsif ($opt eq 'setuid') {
466 $self->{$opt} = $value;
468 die "unknown daemon option '$opt'\n";
474 $self->{cmdline
} = [map { /^(.*)$/ } @$cmdline];
487 my ($self, $status) = @_;
489 syslog
("info", "server stopped");
491 &$server_cleanup($self);
497 my ($self, $waittime) = @_;
499 syslog
('info', "server shutdown (restart)");
501 $ENV{RESTART_PVE_DAEMON
} = 1;
503 if ($self->{max_workers
}) {
504 my @workers = keys %{$self->{workers
}};
505 push @workers, keys %{$self->{old_workers
}};
506 $ENV{PVE_DAEMON_WORKER_PIDS
} = join(':', @workers);
509 sleep($waittime) if $waittime; # avoid high server load due to restarts
511 PVE
::INotify
::inotify_close
();
513 exec (@{$self->{cmdline
}});
515 exit (-1); # never reached?
518 # please overwrite in subclass
519 # this is called at startup - before forking
525 # please overwrite in subclass
529 syslog
('info' , "server closing");
531 if (!$self->{max_workers
}) {
533 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
537 # please define in subclass
541 # syslog('info' , "received signal HUP (restart)");
544 # please overwrite in subclass
549 syslog
('info' , "server is running");
555 my ($self, $debug) = @_;
559 &$server_run($self, $debug);
562 &$log_err("start failed - $err");
570 my $pid_str = PVE
::Tools
::file_read_firstline
($self->{pidfile
});
572 return 0 if !$pid_str;
574 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
581 # checks if the process was started by systemd
582 my $init_ppid = sub {
584 if (getppid() == 1) {
594 my $pid = &$read_pid($self);
597 my $res = PVE
::ProcFSTools
::check_process_running
($pid) ?
1 : 0;
598 return wantarray ?
($res, $pid) : $res;
601 return wantarray ?
(0, 0) : 0;
607 my $pid = &$read_pid($self);
611 if (PVE
::ProcFSTools
::check_process_running
($pid)) {
612 kill(15, $pid); # send TERM signal
614 my $wait_time = $self->{stop_wait_time
} || 5;
616 for (my $i = 0; $i < $wait_time; $i++) {
617 $running = PVE
::ProcFSTools
::check_process_running
($pid);
622 syslog
('err', "server still running - send KILL") if $running;
629 if (-f
$self->{pidfile
}) {
631 # try to get the lock
632 &$lockpidfile($self);
633 &$server_cleanup($self);
636 &$log_err("cleanup failed - $err");
641 sub register_start_command
{
642 my ($self, $description) = @_;
644 my $class = ref($self);
646 $class->register_method({
650 description
=> $description || "Start the daemon.",
652 additionalProperties
=> 0,
655 description
=> "Debug mode - stay in foreground",
662 returns
=> { type
=> 'null' },
668 $self->start($param->{debug
});
670 PVE
::Tools
::run_command
(['systemctl', 'start', $self->{name
}]);
677 my $reload_daemon = sub {
678 my ($self, $use_hup) = @_;
680 if ($self->{env_restart_pve_daemon
}) {
683 my ($running, $pid) = $self->running();
688 syslog
('info', "send HUP to $pid");
698 sub register_restart_command
{
699 my ($self, $use_hup, $description) = @_;
701 my $class = ref($self);
703 $class->register_method({
707 description
=> $description || "Restart the daemon (or start if not running).",
709 additionalProperties
=> 0,
712 returns
=> { type
=> 'null' },
718 &$reload_daemon($self, $use_hup);
720 PVE
::Tools
::run_command
(['systemctl', $use_hup ?
'reload-or-restart' : 'restart', $self->{name
}]);
727 sub register_reload_command
{
728 my ($self, $description) = @_;
730 my $class = ref($self);
732 $class->register_method({
736 description
=> $description || "Reload daemon configuration (or start if not running).",
738 additionalProperties
=> 0,
741 returns
=> { type
=> 'null' },
746 &$reload_daemon($self, 1);
752 sub register_stop_command
{
753 my ($self, $description) = @_;
755 my $class = ref($self);
757 $class->register_method({
761 description
=> $description || "Stop the daemon.",
763 additionalProperties
=> 0,
766 returns
=> { type
=> 'null' },
774 PVE
::Tools
::run_command
(['systemctl', 'stop', $self->{name
}]);
781 sub register_status_command
{
782 my ($self, $description) = @_;
784 my $class = ref($self);
786 $class->register_method({
790 description
=> "Get daemon status.",
792 additionalProperties
=> 0,
797 enum
=> ['stopped', 'running'],
802 return $self->running() ?
'running' : 'stopped';
808 sub create_reusable_socket
{
809 my ($self, $port, $host, $family) = @_;
811 die "no port specifed" if !$port;
813 my ($socket, $sockfd);
815 if (defined($sockfd = $ENV{"PVE_DAEMON_SOCKET_$port"}) &&
816 $self->{env_restart_pve_daemon
}) {
818 die "unable to parse socket fd '$sockfd'\n"
819 if $sockfd !~ m/^(\d+)$/;
820 $sockfd = $1; # untaint
822 $socket = IO
::Socket
::IP-
>new;
823 $socket->fdopen($sockfd, 'w') ||
824 die "cannot fdopen file descriptor '$sockfd' - $!\n";
828 $socket = IO
::Socket
::IP-
>new(
834 GetAddrInfoFlags
=> 0,
836 die "unable to create socket - $@\n";
838 # we often observe delays when using Nagle algorithm,
839 # so we disable that to maximize performance
840 setsockopt($socket, IPPROTO_TCP
, TCP_NODELAY
, 1);
842 $ENV{"PVE_DAEMON_SOCKET_$port"} = $socket->fileno;
845 # remove FD_CLOEXEC bit to reuse on exec
846 $socket->fcntl(Fcntl
::F_SETFD
(), 0);