]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Daemon.pm
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 # * correctly daemonize (redirect STDIN/STDOUT)
9 # * restart by stop/start, exec, or signal HUP
10 # * daemon restart on error (option 'restart_on_error')
11 # * handle worker processes (option 'max_workers')
18 use POSIX
":sys_wait_h";
21 use Time
::HiRes qw
(gettimeofday
);
23 use base
qw(PVE::CLIHandler);
25 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
27 my $daemon_initialized = 0; # we only allow one instance
29 my $close_daemon_lock = sub {
32 return if !$self->{daemon_lock_fh
};
34 close $self->{daemon_lock_fh
};
35 delete $self->{daemon_lock_fh
};
41 print STDERR
"$msg\n";
42 syslog
('err', "%s", $msg);
45 # call this if you fork() from child
46 # Note: we already call this for workers, so it is only required
47 # if you fork inside a simple daemon (max_workers == 0).
48 sub after_fork_cleanup
{
51 &$close_daemon_lock($self);
53 PVE
::INotify
::inotify_close
();
55 for my $sig (qw(CHLD HUP INT TERM QUIT)) {
56 $SIG{$sig} = 'DEFAULT'; # restore default handler
57 # AnyEvent signals only works if $SIG{XX} is
58 # undefined (perl event loop)
59 delete $SIG{$sig}; # so that we can handle events with AnyEvent
63 my $lockpidfile = sub {
66 my $lkfn = $self->{pidfile
} . ".lock";
68 if (my $fd = $self->{env_pve_lock_fd
}) {
70 $self->{daemon_lock_fh
} = IO
::Handle-
>new_from_fd($fd, "a");
74 $self->{daemon_lock_fh
} = IO
::File-
>new(">>$lkfn");
77 if (!$self->{daemon_lock_fh
}) {
78 die "can't open lock '$lkfn' - $!\n";
81 for (my $i = 0; $i < 5; $i ++) {
82 return if flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
);
86 if (!flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
)) {
87 &$close_daemon_lock($self);
90 my ($running, $pid) = $self->running();
92 die "can't aquire lock '$lkfn' - daemon already started (pid = $pid)\n";
94 die "can't aquire lock '$lkfn' - $err\n";
99 my $writepidfile = sub {
102 my $pidfile = $self->{pidfile
};
104 die "can't open pid file '$pidfile' - $!\n" if !open (PIDFH
, ">$pidfile");
110 my $server_cleanup = sub {
113 unlink $self->{pidfile
} . ".lock";
114 unlink $self->{pidfile
};
117 my $finish_workers = sub {
120 foreach my $cpid (keys %{$self->{workers
}}) {
121 my $waitpid = waitpid($cpid, WNOHANG
);
122 if (defined($waitpid) && ($waitpid == $cpid)) {
123 delete ($self->{workers
}->{$cpid});
124 syslog
('info', "worker $cpid finished");
129 my $start_workers = sub {
132 return if $self->{terminate
};
135 foreach my $cpid (keys %{$self->{workers
}}) {
139 my $need = $self->{max_workers
} - $count;
141 return if $need <= 0;
143 syslog
('info', "starting $need worker(s)");
148 if (!defined ($pid)) {
149 syslog
('err', "can't fork worker");
151 } elsif ($pid) { # parent
152 $self->{workers
}->{$pid} = 1;
153 syslog
('info', "worker $pid started");
156 $0 = "$self->{name} worker";
158 $self->after_fork_cleanup();
160 eval { $self->run(); };
163 sleep(5); # avoid fast restarts
166 syslog
('info', "worker exit");
172 my $terminate_server = sub {
175 $self->{terminate
} = 1; # set flag to avoid worker restart
177 if (!$self->{max_workers
}) {
178 eval { $self->shutdown(); };
183 eval { $self->shutdown(); };
186 # we have workers - terminate them
188 foreach my $cpid (keys %{$self->{workers
}}) {
189 kill(15, $cpid); # TERM childs
192 # nicely shutdown childs (give them max 10 seconds to shut down)
193 my $previous_alarm = alarm(10);
195 local $SIG{ALRM
} = sub { die "timeout\n" };
197 while ((my $pid = waitpid (-1, 0)) > 0) {
198 if (defined($self->{workers
}->{$pid})) {
199 delete($self->{workers
}->{$pid});
200 syslog
('info', "worker $pid finished");
203 alarm(0); # avoid race condition
207 alarm ($previous_alarm);
210 syslog
('err', "error stopping workers (will kill them now) - $err");
211 foreach my $cpid (keys %{$self->{workers
}}) {
212 # KILL childs still alive!
213 if (kill (0, $cpid)) {
214 delete($self->{workers
}->{$cpid});
215 syslog
("err", "kill worker $cpid");
223 my $server_run = sub {
224 my ($self, $debug) = @_;
226 # fixme: handle restart lockfd
227 &$lockpidfile($self);
229 # remove FD_CLOEXEC bit to reuse on exec
230 $self->{daemon_lock_fh
}->fcntl(Fcntl
::F_SETFD
(), 0);
232 $ENV{PVE_DAEMON_LOCK_FD
} = $self->{daemon_lock_fh
}->fileno;
237 $self->{debug
} = 1 if $debug;
242 open STDIN
, '</dev/null' || die "can't read /dev/null";
243 open STDOUT
, '>/dev/null' || die "can't write /dev/null";
246 if (!$self->{env_restart_pve_daemon
} && !$debug) {
247 PVE
::INotify
::inotify_close
();
249 if (!defined ($spid)) {
250 die "can't put server into background - fork failed";
251 } elsif ($spid) { # parent
254 PVE
::INotify
::inotify_init
();
257 if ($self->{env_restart_pve_daemon
}) {
258 syslog
('info' , "restarting server");
260 &$writepidfile($self);
261 syslog
('info' , "starting server");
266 open STDERR
, '>&STDOUT' || die "can't close STDERR\n";
268 my $old_sig_term = $SIG{TERM
};
269 local $SIG{TERM
} = sub {
270 local ($@, $!, $?); # do not overwrite error vars
271 syslog
('info', "received signal TERM");
272 &$terminate_server($self);
273 &$server_cleanup($self);
274 &$old_sig_term(@_) if $old_sig_term;
277 my $old_sig_quit = $SIG{QUIT
};
278 local $SIG{QUIT
} = sub {
279 local ($@, $!, $?); # do not overwrite error vars
280 syslog
('info', "received signal QUIT");
281 &$terminate_server($self);
282 &$server_cleanup($self);
283 &$old_sig_quit(@_) if $old_sig_quit;
286 my $old_sig_int = $SIG{INT
};
287 local $SIG{INT
} = sub {
288 local ($@, $!, $?); # do not overwrite error vars
289 syslog
('info', "received signal INT");
290 $SIG{INT
} = 'DEFAULT'; # allow to terminate now
291 &$terminate_server($self);
292 &$server_cleanup($self);
293 &$old_sig_int(@_) if $old_sig_int;
297 local ($@, $!, $?); # do not overwrite error vars
298 syslog
('info', "received signal HUP");
299 if ($self->{max_workers
}) {
300 &$terminate_server($self);
301 $self->{got_hup_signal
} = 1;
302 } elsif ($self->can('hup')) {
303 eval { $self->hup() };
309 if ($self->{max_workers
}) {
310 my $old_sig_chld = $SIG{CHLD
};
311 local $SIG{CHLD
} = sub {
312 local ($@, $!, $?); # do not overwrite error vars
313 &$finish_workers($self);
314 &$old_sig_chld(@_) if $old_sig_chld;
318 &$start_workers($self);
320 &$finish_workers($self);
321 last if $self->{terminate
};
331 syslog
('err', "ERROR: $err");
333 # fixme: kill all workers
335 if (my $wait_time = $self->{restart_on_error
}) {
336 $self->restart_daemon($wait_time);
338 $self->exit_daemon(-1);
342 if ($self->{got_hup_signal
}) {
343 $self->restart_daemon();
345 $self->exit_daemon(0);
350 my ($this, $name, $cmdline, %params) = @_;
352 die "missing name" if !$name;
356 my $restart = $ENV{RESTART_PVE_DAEMON
};
357 delete $ENV{RESTART_PVE_DAEMON
};
359 my $lockfd = $ENV{PVE_DAEMON_LOCK_FD
};
360 delete $ENV{PVE_DAEMON_LOCK_FD
};
362 die "please run as root\n" if !$restart && ($> != 0);
364 die "can't create more that one PVE::Daemon" if $daemon_initialized;
365 $daemon_initialized = 1;
367 PVE
::INotify
::inotify_init
();
369 my $class = ref($this) || $this;
373 run_dir
=> '/var/run',
374 env_restart_pve_daemon
=> $restart,
375 env_pve_lock_fd
=> $lockfd,
379 foreach my $opt (keys %params) {
380 my $value = $params{$opt};
381 if ($opt eq 'restart_on_error') {
382 $self->{$opt} = $value;
383 } elsif ($opt eq 'stop_wait_time') {
384 $self->{$opt} = $value;
385 } elsif ($opt eq 'run_dir') {
386 $self->{$opt} = $value;
387 } elsif ($opt eq 'max_workers') {
388 $self->{$opt} = $value;
390 die "unknown option '$opt'";
394 $self->{pidfile
} = "$self->{run_dir}/${name}.pid";
396 $self->{nodename
} = PVE
::INotify
::nodename
();
398 $self->{cmdline
} = [];
400 foreach my $el (@$cmdline) {
401 $el =~ m/^(.*)$/; # untaint
402 push @{$self->{cmdline
}}, $1;
411 my ($self, $status) = @_;
413 syslog
("info", "server stopped");
415 &$server_cleanup($self);
421 my ($self, $waittime) = @_;
423 syslog
('info', "server shutdown (restart)");
425 $ENV{RESTART_PVE_DAEMON
} = 1;
427 sleep($waittime) if $waittime; # avoid high server load due to restarts
429 PVE
::INotify
::inotify_close
();
431 exec (@{$self->{cmdline
}});
433 exit (-1); # never reached?
436 # please overwrite in subclass
437 # this is called at startup - before forking
443 # please overwrite in subclass
447 syslog
('info' , "server closing");
449 if (!$self->{max_workers
}) {
451 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
455 # please define in subclass
459 # syslog('info' , "received signal HUP (restart)");
462 # please overwrite in subclass
467 syslog
('info' , "server is running");
473 my ($self, $debug) = @_;
475 eval { &$server_run($self, $debug); };
477 &$log_err("start failed - $err");
485 my $pid_str = PVE
::Tools
::file_read_firstline
($self->{pidfile
});
487 return 0 if !$pid_str;
489 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
499 my $pid = &$read_pid($self);
502 my $res = PVE
::ProcFSTools
::check_process_running
($pid) ?
1 : 0;
503 return wantarray ?
($res, $pid) : $res;
506 return wantarray ?
(0, 0) : 0;
512 my $pid = &$read_pid($self);
516 if (PVE
::ProcFSTools
::check_process_running
($pid)) {
517 kill(15, $pid); # send TERM signal
519 my $wait_time = $self->{stop_wait_time
} || 5;
521 for (my $i = 0; $i < $wait_time; $i++) {
522 $running = PVE
::ProcFSTools
::check_process_running
($pid);
527 syslog
('err', "server still running - send KILL") if $running;
534 if (-f
$self->{pidfile
}) {
536 # try to get the lock
537 &$lockpidfile($self);
538 &$server_cleanup($self);
541 &$log_err("cleanup failed - $err");
546 sub register_start_command
{
547 my ($self, $class, $description) = @_;
549 $class->register_method({
553 description
=> $description || "Start the daemon.",
555 additionalProperties
=> 0,
558 description
=> "Debug mode - stay in foreground",
565 returns
=> { type
=> 'null' },
570 $self->start($param->{debug
});
576 my $reload_daemon = sub {
577 my ($self, $use_hup) = @_;
579 if ($self->{env_restart_pve_daemon
}) {
582 my ($running, $pid) = $self->running();
587 syslog
('info', "send HUP to $pid");
597 sub register_restart_command
{
598 my ($self, $class, $use_hup, $description) = @_;
600 $class->register_method({
604 description
=> $description || "Restart the daemon (or start if not running).",
606 additionalProperties
=> 0,
609 returns
=> { type
=> 'null' },
614 &$reload_daemon($self, $use_hup);
620 sub register_reload_command
{
621 my ($self, $class, $description) = @_;
623 $class->register_method({
627 description
=> $description || "Reload daemon configuration (or start if not running).",
629 additionalProperties
=> 0,
632 returns
=> { type
=> 'null' },
637 &$reload_daemon($self, 1);
643 sub register_stop_command
{
644 my ($self, $class, $description) = @_;
646 $class->register_method({
650 description
=> $description || "Stop the daemon.",
652 additionalProperties
=> 0,
655 returns
=> { type
=> 'null' },
666 sub register_status_command
{
667 my ($self, $class, $description) = @_;
669 $class->register_method({
673 description
=> "Get daemon status.",
675 additionalProperties
=> 0,
680 enum
=> ['stopped', 'running'],
685 return $self->running() ?
'running' : 'stopped';