]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Daemon.pm
f03e7cf9f0aec047e9eb5a896dd698212913e624
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 close $self->{daemon_lock_fh
};
42 delete $self->{daemon_lock_fh
};
45 my $lockpidfile = sub {
48 my $lkfn = $self->{pidfile
} . ".lock";
50 $self->{daemon_lock_fh
} = IO
::File-
>new(">>$lkfn");
51 if (!$self->{daemon_lock_fh
}) {
52 my $msg = "can't aquire lock on file '$lkfn' - $!";
57 for (my $i = 0; $i < 5; $i ++) {
58 return if flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
);
62 if (!flock ($self->{daemon_lock_fh
}, LOCK_EX
|LOCK_NB
)) {
63 &$close_daemon_lock($self);
64 my $msg = "can't aquire lock '$lkfn' - $!";
70 my $writepidfile = sub {
73 my $pidfile = $self->{pidfile
};
75 if (!open (PIDFH
, ">$pidfile")) {
76 my $msg = "can't open pid file '$pidfile' - $!";
84 my $server_cleanup = sub {
87 unlink $self->{pidfile
} . ".lock";
88 unlink $self->{pidfile
};
91 my $finish_workers = sub {
94 foreach my $cpid (keys %{$self->{workers
}}) {
95 my $waitpid = waitpid($cpid, WNOHANG
);
96 if (defined($waitpid) && ($waitpid == $cpid)) {
97 delete ($self->{workers
}->{$cpid});
98 syslog
('info', "worker $cpid finished");
103 my $start_workers = sub {
106 return if $self->{terminate
};
109 foreach my $cpid (keys %{$self->{workers
}}) {
113 my $need = $self->{max_workers
} - $count;
115 return if $need <= 0;
117 syslog
('info', "starting $need worker(s)");
122 if (!defined ($pid)) {
123 syslog
('err', "can't fork worker");
125 } elsif ($pid) { # parent
126 $self->{workers
}->{$pid} = 1;
127 syslog
('info', "worker $pid started");
130 $0 = "$self->{name} worker";
132 &$close_daemon_lock($self);
134 PVE
::INotify
::inotify_close
();
136 for my $sig (qw(CHLD HUP INT TERM QUIT)) {
137 $SIG{$sig} = 'DEFAULT'; # restore default handler
138 # AnyEvent signals only works if $SIG{XX} is
139 # undefined (perl event loop)
140 delete $SIG{$sig}; # so that we can handle events with AnyEvent
143 eval { $self->run(); };
146 sleep(5); # avoid fast restarts
149 syslog
('info', "worker exit");
155 my $terminate_server = sub {
158 $self->{terminate
} = 1; # set flag to avoid worker restart
160 if (!$self->{max_workers
}) {
161 eval { $self->shutdown(); };
166 eval { $self->shutdown(); };
169 # we have workers - terminate them
171 foreach my $cpid (keys %{$self->{workers
}}) {
172 kill(15, $cpid); # TERM childs
175 # nicely shutdown childs (give them max 10 seconds to shut down)
176 my $previous_alarm = alarm(10);
178 local $SIG{ALRM
} = sub { die "timeout\n" };
180 while ((my $pid = waitpid (-1, 0)) > 0) {
181 if (defined($self->{workers
}->{$pid})) {
182 delete($self->{workers
}->{$pid});
183 syslog
('info', "worker $pid finished");
186 alarm(0); # avoid race condition
190 alarm ($previous_alarm);
193 syslog
('err', "error stopping workers (will kill them now) - $err");
194 foreach my $cpid (keys %{$self->{workers
}}) {
195 # KILL childs still alive!
196 if (kill (0, $cpid)) {
197 delete($self->{workers
}->{$cpid});
198 syslog
("err", "kill worker $cpid");
206 my $server_run = sub {
207 my ($self, $debug) = @_;
209 &$lockpidfile($self);
214 my $restart = $ENV{RESTART_PVE_DAEMON
};
216 delete $ENV{RESTART_PVE_DAEMON
};
218 $self->{debug
} = 1 if $debug;
223 open STDIN
, '</dev/null' || die "can't read /dev/null";
224 open STDOUT
, '>/dev/null' || die "can't write /dev/null";
227 if (!$restart && !$debug) {
228 PVE
::INotify
::inotify_close
();
230 if (!defined ($spid)) {
231 my $msg = "can't put server into background - fork failed";
234 } elsif ($spid) { # parent
237 PVE
::INotify
::inotify_init
();
240 &$writepidfile($self);
245 syslog
('info' , "restarting server");
247 syslog
('info' , "starting server");
250 open STDERR
, '>&STDOUT' || die "can't close STDERR\n";
252 my $old_sig_term = $SIG{TERM
};
253 local $SIG{TERM
} = sub {
254 local ($@, $!, $?); # do not overwrite error vars
255 syslog
('info', "received signal TERM");
256 &$terminate_server($self);
257 &$server_cleanup($self);
258 &$old_sig_term(@_) if $old_sig_term;
261 my $old_sig_quit = $SIG{QUIT
};
262 local $SIG{QUIT
} = sub {
263 local ($@, $!, $?); # do not overwrite error vars
264 syslog
('info', "received signal QUIT");
265 &$terminate_server($self);
266 &$server_cleanup($self);
267 &$old_sig_quit(@_) if $old_sig_quit;
270 my $old_sig_int = $SIG{INT
};
271 local $SIG{INT
} = sub {
272 local ($@, $!, $?); # do not overwrite error vars
273 syslog
('info', "received signal INT");
274 $SIG{INT
} = 'DEFAULT'; # allow to terminate now
275 &$terminate_server($self);
276 &$server_cleanup($self);
277 &$old_sig_int(@_) if $old_sig_int;
281 local ($@, $!, $?); # do not overwrite error vars
282 syslog
('info', "received signal HUP");
283 if ($self->{max_workers
}) {
284 &$terminate_server($self);
285 $self->{got_hup_signal
} = 1;
286 } elsif ($self->can('hup')) {
287 eval { $self->hup() };
293 if ($self->{max_workers
}) {
294 my $old_sig_chld = $SIG{CHLD
};
295 local $SIG{CHLD
} = sub {
296 local ($@, $!, $?); # do not overwrite error vars
297 &$finish_workers($self);
298 &$old_sig_chld(@_) if $old_sig_chld;
302 &$start_workers($self);
304 &$finish_workers($self);
305 last if $self->{terminate
};
315 syslog
('err', "ERROR: $err");
317 # fixme: kill all workers
319 if (my $wait_time = $self->{restart_on_error
}) {
320 $self->restart_daemon($wait_time);
322 $self->exit_daemon(-1);
326 if ($self->{got_hup_signal
}) {
327 $self->restart_daemon();
329 $self->exit_daemon(0);
334 my ($this, $name, $cmdline, %params) = @_;
336 die "please run as root\n" if !$ENV{RESTART_PVE_DAEMON
} && ($> != 0);
338 die "missing name" if !$name;
340 die "can't create more that one PVE::Daemon" if $daemon_initialized;
341 $daemon_initialized = 1;
343 PVE
::INotify
::inotify_init
();
347 my $class = ref($this) || $this;
351 run_dir
=> '/var/run',
355 foreach my $opt (keys %params) {
356 my $value = $params{$opt};
357 if ($opt eq 'restart_on_error') {
358 $self->{$opt} = $value;
359 } elsif ($opt eq 'stop_wait_time') {
360 $self->{$opt} = $value;
361 } elsif ($opt eq 'run_dir') {
362 $self->{$opt} = $value;
363 } elsif ($opt eq 'max_workers') {
364 $self->{$opt} = $value;
366 die "unknown option '$opt'";
370 $self->{pidfile
} = "$self->{run_dir}/${name}.pid";
372 $self->{nodename
} = PVE
::INotify
::nodename
();
374 $self->{cmdline
} = [];
376 foreach my $el (@$cmdline) {
377 $el =~ m/^(.*)$/; # untaint
378 push @{$self->{cmdline
}}, $1;
387 my ($self, $status) = @_;
389 syslog
("info", "server stopped");
391 &$server_cleanup($self);
397 my ($self, $waittime) = @_;
399 syslog
('info', "server shutdown (restart)");
401 $ENV{RESTART_PVE_DAEMON
} = 1;
403 sleep($waittime) if $waittime; # avoid high server load due to restarts
405 PVE
::INotify
::inotify_close
();
407 exec (@{$self->{cmdline
}});
409 exit (-1); # never reached?
412 # please overwrite in subclass
413 # this is called at startup - before forking
419 # please overwrite in subclass
423 syslog
('info' , "server closing");
425 if (!$self->{max_workers
}) {
427 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
431 # please define in subclass
435 # syslog('info' , "received signal HUP (restart)");
438 # please overwrite in subclass
443 syslog
('info' , "server is running");
449 my ($self, $debug) = @_;
451 &$server_run($self, $debug);
457 my $pid_str = PVE
::Tools
::file_read_firstline
($self->{pidfile
});
459 return 0 if !$pid_str;
461 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
471 my $pid = &$read_pid($self);
474 my $res = PVE
::ProcFSTools
::check_process_running
($pid) ?
1 : 0;
475 return wantarray ?
($res, $pid) : $res;
478 return wantarray ?
(0, 0) : 0;
484 my $pid = &$read_pid($self);
488 if (PVE
::ProcFSTools
::check_process_running
($pid)) {
489 kill(15, $pid); # send TERM signal
491 my $wait_time = $self->{stop_wait_time
} || 5;
493 for (my $i = 0; $i < $wait_time; $i++) {
494 $running = PVE
::ProcFSTools
::check_process_running
($pid);
499 syslog
('err', "server still running - send KILL") if $running;
506 if (-f
$self->{pidfile
}) {
507 # try to get the lock
508 &$lockpidfile($self);
509 &$server_cleanup($self);
513 sub register_start_command
{
514 my ($self, $class, $description) = @_;
516 $class->register_method({
520 description
=> $description || "Start the daemon.",
522 additionalProperties
=> 0,
525 description
=> "Debug mode - stay in foreground",
532 returns
=> { type
=> 'null' },
537 $self->start($param->{debug
});
543 my $reload_daemon = sub {
544 my ($self, $use_hup) = @_;
546 if (my $restart = $ENV{RESTART_PVE_DAEMON
}) {
549 my ($running, $pid) = $self->running();
554 syslog
('info', "send HUP to $pid");
564 sub register_restart_command
{
565 my ($self, $class, $use_hup, $description) = @_;
567 $class->register_method({
571 description
=> $description || "Restart the daemon (or start if not running).",
573 additionalProperties
=> 0,
576 returns
=> { type
=> 'null' },
581 &$reload_daemon($self, $use_hup);
587 sub register_reload_command
{
588 my ($self, $class, $description) = @_;
590 $class->register_method({
594 description
=> $description || "Reload daemon configuration (or start if not running).",
596 additionalProperties
=> 0,
599 returns
=> { type
=> 'null' },
604 &$reload_daemon($self, 1);
610 sub register_stop_command
{
611 my ($self, $class, $description) = @_;
613 $class->register_method({
617 description
=> $description || "Stop the daemon.",
619 additionalProperties
=> 0,
622 returns
=> { type
=> 'null' },
633 sub register_status_command
{
634 my ($self, $class, $description) = @_;
636 $class->register_method({
640 description
=> "Get daemon status.",
642 additionalProperties
=> 0,
647 enum
=> ['stopped', 'running'],
652 return $self->running() ?
'running' : 'stopped';