]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Daemon.pm
bump version to 4.0-7
[pve-common.git] / src / PVE / Daemon.pm
CommitLineData
390802ab
DM
1package PVE::Daemon;
2
3# Abstract class to implement Daemons
4#
5# Features:
6# * lock and write PID file /var/run/$name.pid to make sure onyl
7# one instance is running.
d7950851 8# * keep lock open during restart
390802ab 9# * correctly daemonize (redirect STDIN/STDOUT)
4fc69176
DM
10# * restart by stop/start, exec, or signal HUP
11# * daemon restart on error (option 'restart_on_error')
b2132054 12# * handle worker processes (option 'max_workers')
d7950851
DM
13# * allow to restart while workers are still runningl
14# (option 'leave_children_open_on_reload')
c4ad45cf 15# * run as different user using setuid/setgid
d7950851 16
390802ab
DM
17use strict;
18use warnings;
c4ad45cf
DM
19use English;
20
390802ab
DM
21use PVE::SafeSyslog;
22use PVE::INotify;
23
24use POSIX ":sys_wait_h";
25use Fcntl ':flock';
517c1125 26use Socket qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
00dc9d0f 27use IO::Socket::IP;
517c1125 28
390802ab
DM
29use Getopt::Long;
30use Time::HiRes qw (gettimeofday);
31
32use base qw(PVE::CLIHandler);
33
390802ab
DM
34$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
35
36my $daemon_initialized = 0; # we only allow one instance
37
3206cdf6
DM
38my $close_daemon_lock = sub {
39 my ($self) = @_;
40
eead1ad8
DM
41 return if !$self->{daemon_lock_fh};
42
3206cdf6
DM
43 close $self->{daemon_lock_fh};
44 delete $self->{daemon_lock_fh};
45};
46
c5611195
DM
47my $log_err = sub {
48 my ($msg) = @_;
49 chomp $msg;
50 print STDERR "$msg\n";
51 syslog('err', "%s", $msg);
52};
53
eead1ad8
DM
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).
57sub after_fork_cleanup {
58 my ($self) = @_;
59
60 &$close_daemon_lock($self);
61
62 PVE::INotify::inotify_close();
63
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
69 }
70}
71
390802ab
DM
72my $lockpidfile = sub {
73 my ($self) = @_;
74
75 my $lkfn = $self->{pidfile} . ".lock";
76
48876459
DM
77 my $waittime = 0;
78
1a6bc2f3
DM
79 if (my $fd = $self->{env_pve_lock_fd}) {
80
81 $self->{daemon_lock_fh} = IO::Handle->new_from_fd($fd, "a");
48876459 82
1a6bc2f3
DM
83 } else {
84
48876459 85 $waittime = 5;
1a6bc2f3
DM
86 $self->{daemon_lock_fh} = IO::File->new(">>$lkfn");
87 }
88
3206cdf6 89 if (!$self->{daemon_lock_fh}) {
1a6bc2f3 90 die "can't open lock '$lkfn' - $!\n";
390802ab
DM
91 }
92
48876459 93 for (my $i = 0; $i < $waittime; $i ++) {
3206cdf6
DM
94 return if flock ($self->{daemon_lock_fh}, LOCK_EX|LOCK_NB);
95 sleep(1);
96 }
97
98 if (!flock ($self->{daemon_lock_fh}, LOCK_EX|LOCK_NB)) {
99 &$close_daemon_lock($self);
c5611195
DM
100 my $err = $!;
101
102 my ($running, $pid) = $self->running();
103 if ($running) {
104 die "can't aquire lock '$lkfn' - daemon already started (pid = $pid)\n";
105 } else {
106 die "can't aquire lock '$lkfn' - $err\n";
107 }
390802ab
DM
108 }
109};
110
111my $writepidfile = sub {
112 my ($self) = @_;
113
114 my $pidfile = $self->{pidfile};
115
c5611195
DM
116 die "can't open pid file '$pidfile' - $!\n" if !open (PIDFH, ">$pidfile");
117
390802ab
DM
118 print PIDFH "$$\n";
119 close (PIDFH);
120};
121
122my $server_cleanup = sub {
123 my ($self) = @_;
124
125 unlink $self->{pidfile} . ".lock";
126 unlink $self->{pidfile};
127};
128
b2132054
DM
129my $finish_workers = sub {
130 my ($self) = @_;
131
d7950851
DM
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");
138 }
b2132054
DM
139 }
140 }
141};
142
143my $start_workers = sub {
144 my ($self) = @_;
145
146 return if $self->{terminate};
147
148 my $count = 0;
149 foreach my $cpid (keys %{$self->{workers}}) {
150 $count++;
151 }
152
153 my $need = $self->{max_workers} - $count;
154
155 return if $need <= 0;
156
157 syslog('info', "starting $need worker(s)");
158
159 while ($need > 0) {
160 my $pid = fork;
161
162 if (!defined ($pid)) {
163 syslog('err', "can't fork worker");
164 sleep (1);
165 } elsif ($pid) { # parent
166 $self->{workers}->{$pid} = 1;
167 syslog('info', "worker $pid started");
168 $need--;
169 } else {
170 $0 = "$self->{name} worker";
171
eead1ad8 172 $self->after_fork_cleanup();
b2132054
DM
173
174 eval { $self->run(); };
175 if (my $err = $@) {
176 syslog('err', $err);
177 sleep(5); # avoid fast restarts
178 }
179
180 syslog('info', "worker exit");
181 exit (0);
182 }
183 }
184};
185
186my $terminate_server = sub {
9403080a 187 my ($self, $allow_open_children) = @_;
b2132054
DM
188
189 $self->{terminate} = 1; # set flag to avoid worker restart
190
191 if (!$self->{max_workers}) {
192 eval { $self->shutdown(); };
193 warn $@ if $@;
194 return;
195 }
196
197 eval { $self->shutdown(); };
198 warn $@ if $@;
199
f3a33995 200 # we have workers - send TERM signal
b2132054
DM
201
202 foreach my $cpid (keys %{$self->{workers}}) {
203 kill(15, $cpid); # TERM childs
204 }
205
f3a33995 206 # if configured, leave children running on HUP
9403080a 207 return if $allow_open_children &&
d7950851
DM
208 $self->{leave_children_open_on_reload};
209
f3a33995
DM
210 # else, send TERM to old workers
211 foreach my $cpid (keys %{$self->{old_workers}}) {
212 kill(15, $cpid); # TERM childs
213 }
214
b2132054
DM
215 # nicely shutdown childs (give them max 10 seconds to shut down)
216 my $previous_alarm = alarm(10);
217 eval {
218 local $SIG{ALRM} = sub { die "timeout\n" };
219
220 while ((my $pid = waitpid (-1, 0)) > 0) {
f3a33995
DM
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");
225 }
b2132054
DM
226 }
227 }
228 alarm(0); # avoid race condition
229 };
230 my $err = $@;
231
232 alarm ($previous_alarm);
233
234 if ($err) {
235 syslog('err', "error stopping workers (will kill them now) - $err");
f3a33995
DM
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");
242 kill(9, $cpid);
243 # fixme: waitpid?
244 }
b2132054
DM
245 }
246 }
247 }
248};
249
8e3e9929
WB
250sub setup {
251 my ($self) = @_;
252
253 initlog($self->{name});
254
255 my $restart = $ENV{RESTART_PVE_DAEMON};
256 delete $ENV{RESTART_PVE_DAEMON};
257 $self->{env_restart_pve_daemon} = $restart;
258
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
265 }
266 $self->{env_pve_lock_fd} = $lockfd;
267
268 die "please run as root\n" if !$restart && ($> != 0);
269
270 die "can't create more that one PVE::Daemon" if $daemon_initialized;
271 $daemon_initialized = 1;
272
273 PVE::INotify::inotify_init();
274
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
279 # just to be sure
280 die "detected strange gid\n" if !($GID eq "$gid $gid" && $EGID eq "$gid $gid");
281 }
282
283 if (my $uidstr = $self->{setuid}) {
284 my $uid = getpwnam($uidstr) || die "getpwnam failed - $!\n";
285 POSIX::setuid($uid) || die "setuid $uid failed - $!\n";
286 # just to be sure
287 die "detected strange uid\n" if !($UID == $uid && $EUID == $uid);
288 }
289
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;
295 }
296 }
297 }
298 }
299
300 $self->{nodename} = PVE::INotify::nodename();
301}
302
390802ab
DM
303my $server_run = sub {
304 my ($self, $debug) = @_;
305
1a6bc2f3 306 # fixme: handle restart lockfd
390802ab
DM
307 &$lockpidfile($self);
308
1a6bc2f3
DM
309 # remove FD_CLOEXEC bit to reuse on exec
310 $self->{daemon_lock_fh}->fcntl(Fcntl::F_SETFD(), 0);
311
312 $ENV{PVE_DAEMON_LOCK_FD} = $self->{daemon_lock_fh}->fileno;
313
390802ab
DM
314 # run in background
315 my $spid;
316
390802ab
DM
317 $self->{debug} = 1 if $debug;
318
319 $self->init();
320
321 if (!$debug) {
322 open STDIN, '</dev/null' || die "can't read /dev/null";
323 open STDOUT, '>/dev/null' || die "can't write /dev/null";
324 }
325
a8ba2293 326 if (!$self->{env_restart_pve_daemon} && !$debug) {
390802ab
DM
327 PVE::INotify::inotify_close();
328 $spid = fork();
329 if (!defined ($spid)) {
c5611195 330 die "can't put server into background - fork failed";
390802ab
DM
331 } elsif ($spid) { # parent
332 exit (0);
333 }
334 PVE::INotify::inotify_init();
335 }
336
a8ba2293 337 if ($self->{env_restart_pve_daemon}) {
390802ab
DM
338 syslog('info' , "restarting server");
339 } else {
c5611195 340 &$writepidfile($self);
390802ab
DM
341 syslog('info' , "starting server");
342 }
343
c5611195
DM
344 POSIX::setsid();
345
390802ab
DM
346 open STDERR, '>&STDOUT' || die "can't close STDERR\n";
347
b2132054
DM
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");
9403080a 352 &$terminate_server($self, 0);
b2132054
DM
353 &$server_cleanup($self);
354 &$old_sig_term(@_) if $old_sig_term;
355 };
390802ab 356
b2132054
DM
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");
9403080a 361 &$terminate_server($self, 0);
b2132054
DM
362 &$server_cleanup($self);
363 &$old_sig_quit(@_) if $old_sig_quit;
364 };
390802ab 365
b2132054
DM
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
9403080a 371 &$terminate_server($self, 0);
390802ab 372 &$server_cleanup($self);
b2132054 373 &$old_sig_int(@_) if $old_sig_int;
390802ab
DM
374 };
375
b2132054
DM
376 $SIG{HUP} = sub {
377 local ($@, $!, $?); # do not overwrite error vars
378 syslog('info', "received signal HUP");
93710700 379 $self->{got_hup_signal} = 1;
b2132054 380 if ($self->{max_workers}) {
9403080a 381 &$terminate_server($self, 1);
b2132054 382 } elsif ($self->can('hup')) {
bdb5acce
DM
383 eval { $self->hup() };
384 warn $@ if $@;
b2132054
DM
385 }
386 };
387
388 eval {
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;
395 };
396
ce0ae1ed
DM
397 # catch worker finished during restart phase
398 &$finish_workers($self);
399
400 # now loop forever (until we receive terminate signal)
401 for (;;) {
b2132054
DM
402 &$start_workers($self);
403 sleep(5);
404 &$finish_workers($self);
405 last if $self->{terminate};
406 }
bdb5acce 407
b2132054
DM
408 } else {
409 $self->run();
410 }
411 };
390802ab
DM
412 my $err = $@;
413
414 if ($err) {
415 syslog ('err', "ERROR: $err");
b2132054 416
9403080a 417 &$terminate_server($self, 1);
b2132054 418
390802ab
DM
419 if (my $wait_time = $self->{restart_on_error}) {
420 $self->restart_daemon($wait_time);
421 } else {
422 $self->exit_daemon(-1);
423 }
424 }
425
b2132054
DM
426 if ($self->{got_hup_signal}) {
427 $self->restart_daemon();
428 } else {
429 $self->exit_daemon(0);
430 }
390802ab
DM
431};
432
433sub new {
434 my ($this, $name, $cmdline, %params) = @_;
435
1ea9e6df 436 $name = 'daemon' if !$name; # should not happen
1a6bc2f3 437
1ea9e6df 438 my $self;
a8ba2293 439
1ea9e6df 440 eval {
1ea9e6df
DM
441 my $class = ref($this) || $this;
442
443 $self = bless {
444 name => $name,
309d99e7 445 pidfile => "/var/run/${name}.pid",
1ea9e6df 446 workers => {},
d7950851 447 old_workers => {},
1ea9e6df
DM
448 }, $class;
449
309d99e7 450
1ea9e6df
DM
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;
309d99e7 457 } elsif ($opt eq 'pidfile') {
1ea9e6df
DM
458 $self->{$opt} = $value;
459 } elsif ($opt eq 'max_workers') {
460 $self->{$opt} = $value;
d7950851
DM
461 } elsif ($opt eq 'leave_children_open_on_reload') {
462 $self->{$opt} = $value;
c4ad45cf
DM
463 } elsif ($opt eq 'setgid') {
464 $self->{$opt} = $value;
465 } elsif ($opt eq 'setuid') {
466 $self->{$opt} = $value;
1ea9e6df
DM
467 } else {
468 die "unknown daemon option '$opt'\n";
469 }
390802ab 470 }
d7950851 471
c4ad45cf 472
8e3e9929
WB
473 # untaint
474 $self->{cmdline} = [map { /^(.*)$/ } @$cmdline];
bdb5acce 475
1ea9e6df
DM
476 $0 = $name;
477 };
478 if (my $err = $@) {
479 &$log_err($err);
480 exit(-1);
481 }
bdb5acce 482
390802ab
DM
483 return $self;
484}
485
486sub exit_daemon {
487 my ($self, $status) = @_;
488
489 syslog("info", "server stopped");
490
491 &$server_cleanup($self);
492
493 exit($status);
494}
495
496sub restart_daemon {
497 my ($self, $waittime) = @_;
498
499 syslog('info', "server shutdown (restart)");
500
501 $ENV{RESTART_PVE_DAEMON} = 1;
502
d7950851
DM
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);
507 }
508
390802ab
DM
509 sleep($waittime) if $waittime; # avoid high server load due to restarts
510
511 PVE::INotify::inotify_close();
512
513 exec (@{$self->{cmdline}});
514
515 exit (-1); # never reached?
516}
517
518# please overwrite in subclass
519# this is called at startup - before forking
520sub init {
521 my ($self) = @_;
522
523}
524
525# please overwrite in subclass
526sub shutdown {
527 my ($self) = @_;
528
529 syslog('info' , "server closing");
530
b2132054
DM
531 if (!$self->{max_workers}) {
532 # wait for children
533 1 while (waitpid(-1, POSIX::WNOHANG()) > 0);
534 }
390802ab
DM
535}
536
bdb5acce
DM
537# please define in subclass
538#sub hup {
539# my ($self) = @_;
540#
541# syslog('info' , "received signal HUP (restart)");
542#}
390802ab
DM
543
544# please overwrite in subclass
545sub run {
546 my ($self) = @_;
547
548 for (;;) { # forever
549 syslog('info' , "server is running");
550 sleep(5);
551 }
552}
553
554sub start {
555 my ($self, $debug) = @_;
556
8e3e9929
WB
557 eval {
558 $self->setup();
559 &$server_run($self, $debug);
560 };
1a6bc2f3 561 if (my $err = $@) {
c5611195
DM
562 &$log_err("start failed - $err");
563 exit(-1);
1a6bc2f3 564 }
390802ab
DM
565}
566
bdb5acce
DM
567my $read_pid = sub {
568 my ($self) = @_;
569
570 my $pid_str = PVE::Tools::file_read_firstline($self->{pidfile});
571
572 return 0 if !$pid_str;
573
574 return 0 if $pid_str !~ m/^(\d+)$/; # untaint
575
576 my $pid = int($1);
577
578 return $pid;
579};
580
390802ab
DM
581sub running {
582 my ($self) = @_;
583
bdb5acce 584 my $pid = &$read_pid($self);
390802ab
DM
585
586 if ($pid) {
587 my $res = PVE::ProcFSTools::check_process_running($pid) ? 1 : 0;
588 return wantarray ? ($res, $pid) : $res;
589 }
590
591 return wantarray ? (0, 0) : 0;
592}
593
594sub stop {
595 my ($self) = @_;
596
bdb5acce
DM
597 my $pid = &$read_pid($self);
598
390802ab
DM
599 return if !$pid;
600
601 if (PVE::ProcFSTools::check_process_running($pid)) {
602 kill(15, $pid); # send TERM signal
603 # give some time
604 my $wait_time = $self->{stop_wait_time} || 5;
605 my $running = 1;
606 for (my $i = 0; $i < $wait_time; $i++) {
607 $running = PVE::ProcFSTools::check_process_running($pid);
608 last if !$running;
609 sleep (1);
610 }
611
612 syslog('err', "server still running - send KILL") if $running;
613
614 # to be sure
615 kill(9, $pid);
616 waitpid($pid, 0);
617 }
618
619 if (-f $self->{pidfile}) {
1a6bc2f3
DM
620 eval {
621 # try to get the lock
622 &$lockpidfile($self);
623 &$server_cleanup($self);
624 };
625 if (my $err = $@) {
c5611195 626 &$log_err("cleanup failed - $err");
1a6bc2f3 627 }
390802ab
DM
628 }
629}
630
631sub register_start_command {
da1a7f58
DM
632 my ($self, $description) = @_;
633
634 my $class = ref($self);
390802ab
DM
635
636 $class->register_method({
637 name => 'start',
638 path => 'start',
639 method => 'POST',
640 description => $description || "Start the daemon.",
641 parameters => {
642 additionalProperties => 0,
643 properties => {
644 debug => {
645 description => "Debug mode - stay in foreground",
646 type => "boolean",
647 optional => 1,
648 default => 0,
649 },
650 },
651 },
652 returns => { type => 'null' },
653
654 code => sub {
655 my ($param) = @_;
656
657 $self->start($param->{debug});
658
659 return undef;
660 }});
661}
662
bdb5acce
DM
663my $reload_daemon = sub {
664 my ($self, $use_hup) = @_;
665
a8ba2293 666 if ($self->{env_restart_pve_daemon}) {
bdb5acce
DM
667 $self->start();
668 } else {
669 my ($running, $pid) = $self->running();
670 if (!$running) {
671 $self->start();
672 } else {
673 if ($use_hup) {
b2132054
DM
674 syslog('info', "send HUP to $pid");
675 kill 1, $pid;
bdb5acce
DM
676 } else {
677 $self->stop();
678 $self->start();
679 }
680 }
681 }
682};
683
390802ab 684sub register_restart_command {
da1a7f58
DM
685 my ($self, $use_hup, $description) = @_;
686
687 my $class = ref($self);
390802ab
DM
688
689 $class->register_method({
690 name => 'restart',
691 path => 'restart',
692 method => 'POST',
693 description => $description || "Restart the daemon (or start if not running).",
694 parameters => {
695 additionalProperties => 0,
696 properties => {},
697 },
698 returns => { type => 'null' },
699
700 code => sub {
701 my ($param) = @_;
702
bdb5acce
DM
703 &$reload_daemon($self, $use_hup);
704
705 return undef;
706 }});
707}
708
709sub register_reload_command {
da1a7f58
DM
710 my ($self, $description) = @_;
711
712 my $class = ref($self);
bdb5acce
DM
713
714 $class->register_method({
715 name => 'reload',
716 path => 'reload',
717 method => 'POST',
718 description => $description || "Reload daemon configuration (or start if not running).",
719 parameters => {
720 additionalProperties => 0,
721 properties => {},
722 },
723 returns => { type => 'null' },
724
725 code => sub {
726 my ($param) = @_;
727
728 &$reload_daemon($self, 1);
390802ab
DM
729
730 return undef;
731 }});
732}
733
734sub register_stop_command {
da1a7f58
DM
735 my ($self, $description) = @_;
736
737 my $class = ref($self);
390802ab
DM
738
739 $class->register_method({
740 name => 'stop',
741 path => 'stop',
742 method => 'POST',
743 description => $description || "Stop the daemon.",
744 parameters => {
745 additionalProperties => 0,
746 properties => {},
747 },
748 returns => { type => 'null' },
749
750 code => sub {
751 my ($param) = @_;
752
753 $self->stop();
754
755 return undef;
756 }});
757}
758
759sub register_status_command {
da1a7f58
DM
760 my ($self, $description) = @_;
761
762 my $class = ref($self);
390802ab
DM
763
764 $class->register_method({
765 name => 'status',
766 path => 'status',
767 method => 'GET',
768 description => "Get daemon status.",
769 parameters => {
770 additionalProperties => 0,
771 properties => {},
772 },
773 returns => {
774 type => 'string',
775 enum => ['stopped', 'running'],
776 },
777 code => sub {
778 my ($param) = @_;
779
780 return $self->running() ? 'running' : 'stopped';
781 }});
782}
783
517c1125
DM
784# some useful helper
785
786sub create_reusable_socket {
83397d50 787 my ($self, $port, $host, $family) = @_;
517c1125
DM
788
789 die "no port specifed" if !$port;
790
791 my ($socket, $sockfd);
792
793 if (defined($sockfd = $ENV{"PVE_DAEMON_SOCKET_$port"}) &&
794 $self->{env_restart_pve_daemon}) {
795
796 die "unable to parse socket fd '$sockfd'\n"
797 if $sockfd !~ m/^(\d+)$/;
798 $sockfd = $1; # untaint
799
00dc9d0f 800 $socket = IO::Socket::IP->new;
517c1125
DM
801 $socket->fdopen($sockfd, 'w') ||
802 die "cannot fdopen file descriptor '$sockfd' - $!\n";
803
804 } else {
805
00dc9d0f 806 $socket = IO::Socket::IP->new(
517c1125
DM
807 LocalAddr => $host,
808 LocalPort => $port,
809 Listen => SOMAXCONN,
83397d50 810 Family => $family,
517c1125 811 Proto => 'tcp',
e43b3a0f 812 GetAddrInfoFlags => 0,
517c1125
DM
813 ReuseAddr => 1) ||
814 die "unable to create socket - $@\n";
815
816 # we often observe delays when using Nagle algorithm,
817 # so we disable that to maximize performance
818 setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
819
820 $ENV{"PVE_DAEMON_SOCKET_$port"} = $socket->fileno;
821 }
822
823 # remove FD_CLOEXEC bit to reuse on exec
824 $socket->fcntl(Fcntl::F_SETFD(), 0);
825
826 return $socket;
827}
828
829
390802ab
DM
8301;
831