]>
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 if (my $fd = $self->{env_pve_lock_fd
}) {
72 $self->{daemon_lock_fh
} = IO
::Handle-
>new_from_fd($fd, "a");
76 $self->{daemon_lock_fh
} = IO
::File-
>new(">>$lkfn");
79 if (!$self->{daemon_lock_fh
}) {
80 die "can't open lock '$lkfn' - $!\n";
83 for (my $i = 0; $i < 5; $i ++) {
84 return if flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
);
88 if (!flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
)) {
89 &$close_daemon_lock($self);
90 die "can't aquire lock '$lkfn' - $!\n";
94 my $writepidfile = sub {
97 my $pidfile = $self->{pidfile
};
99 if (!open (PIDFH
, ">$pidfile")) {
100 my $msg = "can't open pid file '$pidfile' - $!";
101 syslog
('err', $msg);
108 my $server_cleanup = sub {
111 unlink $self->{pidfile
} . ".lock";
112 unlink $self->{pidfile
};
115 my $finish_workers = sub {
118 foreach my $cpid (keys %{$self->{workers
}}) {
119 my $waitpid = waitpid($cpid, WNOHANG
);
120 if (defined($waitpid) && ($waitpid == $cpid)) {
121 delete ($self->{workers
}->{$cpid});
122 syslog
('info', "worker $cpid finished");
127 my $start_workers = sub {
130 return if $self->{terminate
};
133 foreach my $cpid (keys %{$self->{workers
}}) {
137 my $need = $self->{max_workers
} - $count;
139 return if $need <= 0;
141 syslog
('info', "starting $need worker(s)");
146 if (!defined ($pid)) {
147 syslog
('err', "can't fork worker");
149 } elsif ($pid) { # parent
150 $self->{workers
}->{$pid} = 1;
151 syslog
('info', "worker $pid started");
154 $0 = "$self->{name} worker";
156 $self->after_fork_cleanup();
158 eval { $self->run(); };
161 sleep(5); # avoid fast restarts
164 syslog
('info', "worker exit");
170 my $terminate_server = sub {
173 $self->{terminate
} = 1; # set flag to avoid worker restart
175 if (!$self->{max_workers
}) {
176 eval { $self->shutdown(); };
181 eval { $self->shutdown(); };
184 # we have workers - terminate them
186 foreach my $cpid (keys %{$self->{workers
}}) {
187 kill(15, $cpid); # TERM childs
190 # nicely shutdown childs (give them max 10 seconds to shut down)
191 my $previous_alarm = alarm(10);
193 local $SIG{ALRM
} = sub { die "timeout\n" };
195 while ((my $pid = waitpid (-1, 0)) > 0) {
196 if (defined($self->{workers
}->{$pid})) {
197 delete($self->{workers
}->{$pid});
198 syslog
('info', "worker $pid finished");
201 alarm(0); # avoid race condition
205 alarm ($previous_alarm);
208 syslog
('err', "error stopping workers (will kill them now) - $err");
209 foreach my $cpid (keys %{$self->{workers
}}) {
210 # KILL childs still alive!
211 if (kill (0, $cpid)) {
212 delete($self->{workers
}->{$cpid});
213 syslog
("err", "kill worker $cpid");
221 my $server_run = sub {
222 my ($self, $debug) = @_;
224 # fixme: handle restart lockfd
225 &$lockpidfile($self);
227 # remove FD_CLOEXEC bit to reuse on exec
228 $self->{daemon_lock_fh
}->fcntl(Fcntl
::F_SETFD
(), 0);
230 $ENV{PVE_DAEMON_LOCK_FD
} = $self->{daemon_lock_fh
}->fileno;
232 # my $fd = POSIX::dup($self->{daemon_lock_fh}) ||
233 # die "unable to duplicate daemon_lock_fh\n";
239 $self->{debug
} = 1 if $debug;
244 open STDIN
, '</dev/null' || die "can't read /dev/null";
245 open STDOUT
, '>/dev/null' || die "can't write /dev/null";
248 if (!$self->{env_restart_pve_daemon
} && !$debug) {
249 PVE
::INotify
::inotify_close
();
251 if (!defined ($spid)) {
252 my $msg = "can't put server into background - fork failed";
255 } elsif ($spid) { # parent
258 PVE
::INotify
::inotify_init
();
261 &$writepidfile($self);
265 if ($self->{env_restart_pve_daemon
}) {
266 syslog
('info' , "restarting server");
268 syslog
('info' , "starting server");
271 open STDERR
, '>&STDOUT' || die "can't close STDERR\n";
273 my $old_sig_term = $SIG{TERM
};
274 local $SIG{TERM
} = sub {
275 local ($@, $!, $?); # do not overwrite error vars
276 syslog
('info', "received signal TERM");
277 &$terminate_server($self);
278 &$server_cleanup($self);
279 &$old_sig_term(@_) if $old_sig_term;
282 my $old_sig_quit = $SIG{QUIT
};
283 local $SIG{QUIT
} = sub {
284 local ($@, $!, $?); # do not overwrite error vars
285 syslog
('info', "received signal QUIT");
286 &$terminate_server($self);
287 &$server_cleanup($self);
288 &$old_sig_quit(@_) if $old_sig_quit;
291 my $old_sig_int = $SIG{INT
};
292 local $SIG{INT
} = sub {
293 local ($@, $!, $?); # do not overwrite error vars
294 syslog
('info', "received signal INT");
295 $SIG{INT
} = 'DEFAULT'; # allow to terminate now
296 &$terminate_server($self);
297 &$server_cleanup($self);
298 &$old_sig_int(@_) if $old_sig_int;
302 local ($@, $!, $?); # do not overwrite error vars
303 syslog
('info', "received signal HUP");
304 if ($self->{max_workers
}) {
305 &$terminate_server($self);
306 $self->{got_hup_signal
} = 1;
307 } elsif ($self->can('hup')) {
308 eval { $self->hup() };
314 if ($self->{max_workers
}) {
315 my $old_sig_chld = $SIG{CHLD
};
316 local $SIG{CHLD
} = sub {
317 local ($@, $!, $?); # do not overwrite error vars
318 &$finish_workers($self);
319 &$old_sig_chld(@_) if $old_sig_chld;
323 &$start_workers($self);
325 &$finish_workers($self);
326 last if $self->{terminate
};
336 syslog
('err', "ERROR: $err");
338 # fixme: kill all workers
340 if (my $wait_time = $self->{restart_on_error
}) {
341 $self->restart_daemon($wait_time);
343 $self->exit_daemon(-1);
347 if ($self->{got_hup_signal
}) {
348 $self->restart_daemon();
350 $self->exit_daemon(0);
355 my ($this, $name, $cmdline, %params) = @_;
357 die "missing name" if !$name;
361 my $restart = $ENV{RESTART_PVE_DAEMON
};
362 delete $ENV{RESTART_PVE_DAEMON
};
364 my $lockfd = $ENV{PVE_DAEMON_LOCK_FD
};
365 delete $ENV{PVE_DAEMON_LOCK_FD
};
367 die "please run as root\n" if !$restart && ($> != 0);
369 die "can't create more that one PVE::Daemon" if $daemon_initialized;
370 $daemon_initialized = 1;
372 PVE
::INotify
::inotify_init
();
374 my $class = ref($this) || $this;
378 run_dir
=> '/var/run',
379 env_restart_pve_daemon
=> $restart,
380 env_pve_lock_fd
=> $lockfd,
384 foreach my $opt (keys %params) {
385 my $value = $params{$opt};
386 if ($opt eq 'restart_on_error') {
387 $self->{$opt} = $value;
388 } elsif ($opt eq 'stop_wait_time') {
389 $self->{$opt} = $value;
390 } elsif ($opt eq 'run_dir') {
391 $self->{$opt} = $value;
392 } elsif ($opt eq 'max_workers') {
393 $self->{$opt} = $value;
395 die "unknown option '$opt'";
399 $self->{pidfile
} = "$self->{run_dir}/${name}.pid";
401 $self->{nodename
} = PVE
::INotify
::nodename
();
403 $self->{cmdline
} = [];
405 foreach my $el (@$cmdline) {
406 $el =~ m/^(.*)$/; # untaint
407 push @{$self->{cmdline
}}, $1;
416 my ($self, $status) = @_;
418 syslog
("info", "server stopped");
420 &$server_cleanup($self);
426 my ($self, $waittime) = @_;
428 syslog
('info', "server shutdown (restart)");
430 $ENV{RESTART_PVE_DAEMON
} = 1;
432 sleep($waittime) if $waittime; # avoid high server load due to restarts
434 PVE
::INotify
::inotify_close
();
436 exec (@{$self->{cmdline
}});
438 exit (-1); # never reached?
441 # please overwrite in subclass
442 # this is called at startup - before forking
448 # please overwrite in subclass
452 syslog
('info' , "server closing");
454 if (!$self->{max_workers
}) {
456 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
460 # please define in subclass
464 # syslog('info' , "received signal HUP (restart)");
467 # please overwrite in subclass
472 syslog
('info' , "server is running");
478 my ($self, $debug) = @_;
480 eval { &$server_run($self, $debug); };
482 syslog
('err', "start failed - $err");
489 my $pid_str = PVE
::Tools
::file_read_firstline
($self->{pidfile
});
491 return 0 if !$pid_str;
493 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
503 my $pid = &$read_pid($self);
506 my $res = PVE
::ProcFSTools
::check_process_running
($pid) ?
1 : 0;
507 return wantarray ?
($res, $pid) : $res;
510 return wantarray ?
(0, 0) : 0;
516 my $pid = &$read_pid($self);
520 if (PVE
::ProcFSTools
::check_process_running
($pid)) {
521 kill(15, $pid); # send TERM signal
523 my $wait_time = $self->{stop_wait_time
} || 5;
525 for (my $i = 0; $i < $wait_time; $i++) {
526 $running = PVE
::ProcFSTools
::check_process_running
($pid);
531 syslog
('err', "server still running - send KILL") if $running;
538 if (-f
$self->{pidfile
}) {
540 # try to get the lock
541 &$lockpidfile($self);
542 &$server_cleanup($self);
545 syslog
('err', "cleanup failed - $err");
550 sub register_start_command
{
551 my ($self, $class, $description) = @_;
553 $class->register_method({
557 description
=> $description || "Start the daemon.",
559 additionalProperties
=> 0,
562 description
=> "Debug mode - stay in foreground",
569 returns
=> { type
=> 'null' },
574 $self->start($param->{debug
});
580 my $reload_daemon = sub {
581 my ($self, $use_hup) = @_;
583 if ($self->{env_restart_pve_daemon
}) {
586 my ($running, $pid) = $self->running();
591 syslog
('info', "send HUP to $pid");
601 sub register_restart_command
{
602 my ($self, $class, $use_hup, $description) = @_;
604 $class->register_method({
608 description
=> $description || "Restart the daemon (or start if not running).",
610 additionalProperties
=> 0,
613 returns
=> { type
=> 'null' },
618 &$reload_daemon($self, $use_hup);
624 sub register_reload_command
{
625 my ($self, $class, $description) = @_;
627 $class->register_method({
631 description
=> $description || "Reload daemon configuration (or start if not running).",
633 additionalProperties
=> 0,
636 returns
=> { type
=> 'null' },
641 &$reload_daemon($self, 1);
647 sub register_stop_command
{
648 my ($self, $class, $description) = @_;
650 $class->register_method({
654 description
=> $description || "Stop the daemon.",
656 additionalProperties
=> 0,
659 returns
=> { type
=> 'null' },
670 sub register_status_command
{
671 my ($self, $class, $description) = @_;
673 $class->register_method({
677 description
=> "Get daemon status.",
679 additionalProperties
=> 0,
684 enum
=> ['stopped', 'running'],
689 return $self->running() ?
'running' : 'stopped';