]>
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 $SIG{'__WARN__'} = sub {
30 syslog
('warning', "WARNING: %s", $t);
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
};
47 # call this if you fork() from child
48 # Note: we already call this for workers, so it is only required
49 # if you fork inside a simple daemon (max_workers == 0).
50 sub after_fork_cleanup
{
53 &$close_daemon_lock($self);
55 PVE
::INotify
::inotify_close
();
57 for my $sig (qw(CHLD HUP INT TERM QUIT)) {
58 $SIG{$sig} = 'DEFAULT'; # restore default handler
59 # AnyEvent signals only works if $SIG{XX} is
60 # undefined (perl event loop)
61 delete $SIG{$sig}; # so that we can handle events with AnyEvent
65 my $lockpidfile = sub {
68 my $lkfn = $self->{pidfile
} . ".lock";
70 $self->{daemon_lock_fh
} = IO
::File-
>new(">>$lkfn");
71 if (!$self->{daemon_lock_fh
}) {
72 my $msg = "can't aquire lock on file '$lkfn' - $!";
77 for (my $i = 0; $i < 5; $i ++) {
78 return if flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
);
82 if (!flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
)) {
83 &$close_daemon_lock($self);
84 my $msg = "can't aquire lock '$lkfn' - $!";
90 my $writepidfile = sub {
93 my $pidfile = $self->{pidfile
};
95 if (!open (PIDFH
, ">$pidfile")) {
96 my $msg = "can't open pid file '$pidfile' - $!";
104 my $server_cleanup = sub {
107 unlink $self->{pidfile
} . ".lock";
108 unlink $self->{pidfile
};
111 my $finish_workers = sub {
114 foreach my $cpid (keys %{$self->{workers
}}) {
115 my $waitpid = waitpid($cpid, WNOHANG
);
116 if (defined($waitpid) && ($waitpid == $cpid)) {
117 delete ($self->{workers
}->{$cpid});
118 syslog
('info', "worker $cpid finished");
123 my $start_workers = sub {
126 return if $self->{terminate
};
129 foreach my $cpid (keys %{$self->{workers
}}) {
133 my $need = $self->{max_workers
} - $count;
135 return if $need <= 0;
137 syslog
('info', "starting $need worker(s)");
142 if (!defined ($pid)) {
143 syslog
('err', "can't fork worker");
145 } elsif ($pid) { # parent
146 $self->{workers
}->{$pid} = 1;
147 syslog
('info', "worker $pid started");
150 $0 = "$self->{name} worker";
152 $self->after_fork_cleanup();
154 eval { $self->run(); };
157 sleep(5); # avoid fast restarts
160 syslog
('info', "worker exit");
166 my $terminate_server = sub {
169 $self->{terminate
} = 1; # set flag to avoid worker restart
171 if (!$self->{max_workers
}) {
172 eval { $self->shutdown(); };
177 eval { $self->shutdown(); };
180 # we have workers - terminate them
182 foreach my $cpid (keys %{$self->{workers
}}) {
183 kill(15, $cpid); # TERM childs
186 # nicely shutdown childs (give them max 10 seconds to shut down)
187 my $previous_alarm = alarm(10);
189 local $SIG{ALRM
} = sub { die "timeout\n" };
191 while ((my $pid = waitpid (-1, 0)) > 0) {
192 if (defined($self->{workers
}->{$pid})) {
193 delete($self->{workers
}->{$pid});
194 syslog
('info', "worker $pid finished");
197 alarm(0); # avoid race condition
201 alarm ($previous_alarm);
204 syslog
('err', "error stopping workers (will kill them now) - $err");
205 foreach my $cpid (keys %{$self->{workers
}}) {
206 # KILL childs still alive!
207 if (kill (0, $cpid)) {
208 delete($self->{workers
}->{$cpid});
209 syslog
("err", "kill worker $cpid");
217 my $server_run = sub {
218 my ($self, $debug) = @_;
220 &$lockpidfile($self);
225 $self->{debug
} = 1 if $debug;
230 open STDIN
, '</dev/null' || die "can't read /dev/null";
231 open STDOUT
, '>/dev/null' || die "can't write /dev/null";
234 if (!$self->{env_restart_pve_daemon
} && !$debug) {
235 PVE
::INotify
::inotify_close
();
237 if (!defined ($spid)) {
238 my $msg = "can't put server into background - fork failed";
241 } elsif ($spid) { # parent
244 PVE
::INotify
::inotify_init
();
247 &$writepidfile($self);
251 if ($self->{env_restart_pve_daemon
}) {
252 syslog
('info' , "restarting server");
254 syslog
('info' , "starting server");
257 open STDERR
, '>&STDOUT' || die "can't close STDERR\n";
259 my $old_sig_term = $SIG{TERM
};
260 local $SIG{TERM
} = sub {
261 local ($@, $!, $?); # do not overwrite error vars
262 syslog
('info', "received signal TERM");
263 &$terminate_server($self);
264 &$server_cleanup($self);
265 &$old_sig_term(@_) if $old_sig_term;
268 my $old_sig_quit = $SIG{QUIT
};
269 local $SIG{QUIT
} = sub {
270 local ($@, $!, $?); # do not overwrite error vars
271 syslog
('info', "received signal QUIT");
272 &$terminate_server($self);
273 &$server_cleanup($self);
274 &$old_sig_quit(@_) if $old_sig_quit;
277 my $old_sig_int = $SIG{INT
};
278 local $SIG{INT
} = sub {
279 local ($@, $!, $?); # do not overwrite error vars
280 syslog
('info', "received signal INT");
281 $SIG{INT
} = 'DEFAULT'; # allow to terminate now
282 &$terminate_server($self);
283 &$server_cleanup($self);
284 &$old_sig_int(@_) if $old_sig_int;
288 local ($@, $!, $?); # do not overwrite error vars
289 syslog
('info', "received signal HUP");
290 if ($self->{max_workers
}) {
291 &$terminate_server($self);
292 $self->{got_hup_signal
} = 1;
293 } elsif ($self->can('hup')) {
294 eval { $self->hup() };
300 if ($self->{max_workers
}) {
301 my $old_sig_chld = $SIG{CHLD
};
302 local $SIG{CHLD
} = sub {
303 local ($@, $!, $?); # do not overwrite error vars
304 &$finish_workers($self);
305 &$old_sig_chld(@_) if $old_sig_chld;
309 &$start_workers($self);
311 &$finish_workers($self);
312 last if $self->{terminate
};
322 syslog
('err', "ERROR: $err");
324 # fixme: kill all workers
326 if (my $wait_time = $self->{restart_on_error
}) {
327 $self->restart_daemon($wait_time);
329 $self->exit_daemon(-1);
333 if ($self->{got_hup_signal
}) {
334 $self->restart_daemon();
336 $self->exit_daemon(0);
341 my ($this, $name, $cmdline, %params) = @_;
343 my $restart = $ENV{RESTART_PVE_DAEMON
};
345 delete $ENV{RESTART_PVE_DAEMON
};
347 die "please run as root\n" if !$restart && ($> != 0);
349 die "missing name" if !$name;
351 die "can't create more that one PVE::Daemon" if $daemon_initialized;
352 $daemon_initialized = 1;
354 PVE
::INotify
::inotify_init
();
358 my $class = ref($this) || $this;
362 run_dir
=> '/var/run',
363 env_restart_pve_daemon
=> $restart,
367 foreach my $opt (keys %params) {
368 my $value = $params{$opt};
369 if ($opt eq 'restart_on_error') {
370 $self->{$opt} = $value;
371 } elsif ($opt eq 'stop_wait_time') {
372 $self->{$opt} = $value;
373 } elsif ($opt eq 'run_dir') {
374 $self->{$opt} = $value;
375 } elsif ($opt eq 'max_workers') {
376 $self->{$opt} = $value;
378 die "unknown option '$opt'";
382 $self->{pidfile
} = "$self->{run_dir}/${name}.pid";
384 $self->{nodename
} = PVE
::INotify
::nodename
();
386 $self->{cmdline
} = [];
388 foreach my $el (@$cmdline) {
389 $el =~ m/^(.*)$/; # untaint
390 push @{$self->{cmdline
}}, $1;
399 my ($self, $status) = @_;
401 syslog
("info", "server stopped");
403 &$server_cleanup($self);
409 my ($self, $waittime) = @_;
411 syslog
('info', "server shutdown (restart)");
413 $ENV{RESTART_PVE_DAEMON
} = 1;
415 sleep($waittime) if $waittime; # avoid high server load due to restarts
417 PVE
::INotify
::inotify_close
();
419 exec (@{$self->{cmdline
}});
421 exit (-1); # never reached?
424 # please overwrite in subclass
425 # this is called at startup - before forking
431 # please overwrite in subclass
435 syslog
('info' , "server closing");
437 if (!$self->{max_workers
}) {
439 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
443 # please define in subclass
447 # syslog('info' , "received signal HUP (restart)");
450 # please overwrite in subclass
455 syslog
('info' , "server is running");
461 my ($self, $debug) = @_;
463 &$server_run($self, $debug);
469 my $pid_str = PVE
::Tools
::file_read_firstline
($self->{pidfile
});
471 return 0 if !$pid_str;
473 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
483 my $pid = &$read_pid($self);
486 my $res = PVE
::ProcFSTools
::check_process_running
($pid) ?
1 : 0;
487 return wantarray ?
($res, $pid) : $res;
490 return wantarray ?
(0, 0) : 0;
496 my $pid = &$read_pid($self);
500 if (PVE
::ProcFSTools
::check_process_running
($pid)) {
501 kill(15, $pid); # send TERM signal
503 my $wait_time = $self->{stop_wait_time
} || 5;
505 for (my $i = 0; $i < $wait_time; $i++) {
506 $running = PVE
::ProcFSTools
::check_process_running
($pid);
511 syslog
('err', "server still running - send KILL") if $running;
518 if (-f
$self->{pidfile
}) {
519 # try to get the lock
520 &$lockpidfile($self);
521 &$server_cleanup($self);
525 sub register_start_command
{
526 my ($self, $class, $description) = @_;
528 $class->register_method({
532 description
=> $description || "Start the daemon.",
534 additionalProperties
=> 0,
537 description
=> "Debug mode - stay in foreground",
544 returns
=> { type
=> 'null' },
549 $self->start($param->{debug
});
555 my $reload_daemon = sub {
556 my ($self, $use_hup) = @_;
558 if ($self->{env_restart_pve_daemon
}) {
561 my ($running, $pid) = $self->running();
566 syslog
('info', "send HUP to $pid");
576 sub register_restart_command
{
577 my ($self, $class, $use_hup, $description) = @_;
579 $class->register_method({
583 description
=> $description || "Restart the daemon (or start if not running).",
585 additionalProperties
=> 0,
588 returns
=> { type
=> 'null' },
593 &$reload_daemon($self, $use_hup);
599 sub register_reload_command
{
600 my ($self, $class, $description) = @_;
602 $class->register_method({
606 description
=> $description || "Reload daemon configuration (or start if not running).",
608 additionalProperties
=> 0,
611 returns
=> { type
=> 'null' },
616 &$reload_daemon($self, 1);
622 sub register_stop_command
{
623 my ($self, $class, $description) = @_;
625 $class->register_method({
629 description
=> $description || "Stop the daemon.",
631 additionalProperties
=> 0,
634 returns
=> { type
=> 'null' },
645 sub register_status_command
{
646 my ($self, $class, $description) = @_;
648 $class->register_method({
652 description
=> "Get daemon status.",
654 additionalProperties
=> 0,
659 enum
=> ['stopped', 'running'],
664 return $self->running() ?
'running' : 'stopped';