]> git.proxmox.com Git - pve-common.git/blob - src/PVE/Tools.pm
Tools::run_with_timeout improvement + hires alarm
[pve-common.git] / src / PVE / Tools.pm
1 package PVE::Tools;
2
3 use strict;
4 use warnings;
5 use POSIX qw(EINTR);
6 use IO::Socket::IP;
7 use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED);
8 use IO::Select;
9 use File::Basename;
10 use File::Path qw(make_path);
11 use IO::File;
12 use IO::Dir;
13 use IPC::Open3;
14 use Fcntl qw(:DEFAULT :flock);
15 use base 'Exporter';
16 use URI::Escape;
17 use Encode;
18 use Digest::SHA;
19 use Text::ParseWords;
20 use String::ShellQuote;
21 use Time::HiRes qw(usleep gettimeofday tv_interval alarm);
22
23 # avoid warning when parsing long hex values with hex()
24 no warnings 'portable'; # Support for 64-bit ints required
25
26 our @EXPORT_OK = qw(
27 $IPV6RE
28 $IPV4RE
29 lock_file
30 lock_file_full
31 run_command
32 file_set_contents
33 file_get_contents
34 file_read_firstline
35 dir_glob_regex
36 dir_glob_foreach
37 split_list
38 template_replace
39 safe_print
40 trim
41 extract_param
42 );
43
44 my $pvelogdir = "/var/log/pve";
45 my $pvetaskdir = "$pvelogdir/tasks";
46
47 mkdir $pvelogdir;
48 mkdir $pvetaskdir;
49
50 my $IPV4OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
51 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
52 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
53 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
54
55 our $IPV6RE = "(?:" .
56 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
57 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
58 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
59 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
60 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
61 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
62 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
63 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
64 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
65
66 sub run_with_timeout {
67 my ($timeout, $code, @param) = @_;
68
69 die "got timeout\n" if $timeout <= 0;
70
71 my $prev_alarm = alarm 0; # suspend outer alarm early
72
73 my $sigcount = 0;
74
75 my $res;
76
77 eval {
78 local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; };
79 local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" };
80 local $SIG{__DIE__}; # see SA bug 4631
81
82 alarm($timeout);
83
84 eval { $res = &$code(@param); };
85
86 alarm(0); # avoid race conditions
87
88 die $@ if $@;
89 };
90
91 my $err = $@;
92
93 alarm $prev_alarm;
94
95 # this shouldn't happen anymore?
96 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
97
98 die $err if $err;
99
100 return $res;
101 }
102
103 # flock: we use one file handle per process, so lock file
104 # can be called multiple times and succeeds for the same process.
105
106 my $lock_handles = {};
107
108 sub lock_file_full {
109 my ($filename, $timeout, $shared, $code, @param) = @_;
110
111 $timeout = 10 if !$timeout;
112
113 my $mode = $shared ? LOCK_SH : LOCK_EX;
114
115 my $lock_func = sub {
116 if (!$lock_handles->{$$}->{$filename}) {
117 $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") ||
118 die "can't open file - $!\n";
119 }
120
121 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB)) {
122 print STDERR "trying to aquire lock...";
123 my $success;
124 while(1) {
125 $success = flock($lock_handles->{$$}->{$filename}, $mode);
126 # try again on EINTR (see bug #273)
127 if ($success || ($! != EINTR)) {
128 last;
129 }
130 }
131 if (!$success) {
132 print STDERR " failed\n";
133 die "can't aquire lock - $!\n";
134 }
135 print STDERR " OK\n";
136 }
137 };
138
139 my $res;
140
141 eval { run_with_timeout($timeout, $lock_func); };
142 my $err = $@;
143 if ($err) {
144 $err = "can't lock file '$filename' - $err";
145 } else {
146 eval { $res = &$code(@param) };
147 $err = $@;
148 }
149
150 if (my $fh = $lock_handles->{$$}->{$filename}) {
151 $lock_handles->{$$}->{$filename} = undef;
152 close ($fh);
153 }
154
155 if ($err) {
156 $@ = $err;
157 return undef;
158 }
159
160 $@ = undef;
161
162 return $res;
163 }
164
165
166 sub lock_file {
167 my ($filename, $timeout, $code, @param) = @_;
168
169 return lock_file_full($filename, $timeout, 0, $code, @param);
170 }
171
172 sub file_set_contents {
173 my ($filename, $data, $perm) = @_;
174
175 $perm = 0644 if !defined($perm);
176
177 my $tmpname = "$filename.tmp.$$";
178
179 eval {
180 my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm);
181 die "unable to open file '$tmpname' - $!\n" if !$fh;
182 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
183 die "closing file '$tmpname' failed - $!\n" unless close $fh;
184 };
185 my $err = $@;
186
187 if ($err) {
188 unlink $tmpname;
189 die $err;
190 }
191
192 if (!rename($tmpname, $filename)) {
193 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
194 unlink $tmpname;
195 die $msg;
196 }
197 }
198
199 sub file_get_contents {
200 my ($filename, $max) = @_;
201
202 my $fh = IO::File->new($filename, "r") ||
203 die "can't open '$filename' - $!\n";
204
205 my $content = safe_read_from($fh, $max);
206
207 close $fh;
208
209 return $content;
210 }
211
212 sub file_read_firstline {
213 my ($filename) = @_;
214
215 my $fh = IO::File->new ($filename, "r");
216 return undef if !$fh;
217 my $res = <$fh>;
218 chomp $res if $res;
219 $fh->close;
220 return $res;
221 }
222
223 sub safe_read_from {
224 my ($fh, $max, $oneline) = @_;
225
226 $max = 32768 if !$max;
227
228 my $br = 0;
229 my $input = '';
230 my $count;
231 while ($count = sysread($fh, $input, 8192, $br)) {
232 $br += $count;
233 die "input too long - aborting\n" if $br > $max;
234 if ($oneline && $input =~ m/^(.*)\n/) {
235 $input = $1;
236 last;
237 }
238 }
239 die "unable to read input - $!\n" if !defined($count);
240
241 return $input;
242 }
243
244 sub run_command {
245 my ($cmd, %param) = @_;
246
247 my $old_umask;
248 my $cmdstr;
249
250 if (!ref($cmd)) {
251 $cmdstr = $cmd;
252 if ($cmd =~ m/\|/) {
253 # see 'man bash' for option pipefail
254 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
255 } else {
256 $cmd = [ $cmd ];
257 }
258 } else {
259 $cmdstr = cmd2string($cmd);
260 }
261
262 my $errmsg;
263 my $laststderr;
264 my $timeout;
265 my $oldtimeout;
266 my $pid;
267
268 my $outfunc;
269 my $errfunc;
270 my $logfunc;
271 my $input;
272 my $output;
273 my $afterfork;
274
275 eval {
276
277 foreach my $p (keys %param) {
278 if ($p eq 'timeout') {
279 $timeout = $param{$p};
280 } elsif ($p eq 'umask') {
281 $old_umask = umask($param{$p});
282 } elsif ($p eq 'errmsg') {
283 $errmsg = $param{$p};
284 } elsif ($p eq 'input') {
285 $input = $param{$p};
286 } elsif ($p eq 'output') {
287 $output = $param{$p};
288 } elsif ($p eq 'outfunc') {
289 $outfunc = $param{$p};
290 } elsif ($p eq 'errfunc') {
291 $errfunc = $param{$p};
292 } elsif ($p eq 'logfunc') {
293 $logfunc = $param{$p};
294 } elsif ($p eq 'afterfork') {
295 $afterfork = $param{$p};
296 } else {
297 die "got unknown parameter '$p' for run_command\n";
298 }
299 }
300
301 if ($errmsg) {
302 my $origerrfunc = $errfunc;
303 $errfunc = sub {
304 if ($laststderr) {
305 if ($origerrfunc) {
306 &$origerrfunc("$laststderr\n");
307 } else {
308 print STDERR "$laststderr\n" if $laststderr;
309 }
310 }
311 $laststderr = shift;
312 };
313 }
314
315 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
316 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
317 my $error = IO::File->new();
318
319 # try to avoid locale related issues/warnings
320 my $lang = $param{lang} || 'C';
321
322 my $orig_pid = $$;
323
324 eval {
325 local $ENV{LC_ALL} = $lang;
326
327 # suppress LVM warnings like: "File descriptor 3 left open";
328 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
329
330 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
331
332 # if we pipe fron STDIN, open3 closes STDIN, so we we
333 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
334 # as soon as we open a new file.
335 # to avoid that we open /dev/null
336 if (!ref($writer) && !defined(fileno(STDIN))) {
337 POSIX::close(0);
338 open(STDIN, "</dev/null");
339 }
340 };
341
342 my $err = $@;
343
344 # catch exec errors
345 if ($orig_pid != $$) {
346 warn "ERROR: $err";
347 POSIX::_exit (1);
348 kill ('KILL', $$);
349 }
350
351 die $err if $err;
352
353 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
354 $oldtimeout = alarm($timeout) if $timeout;
355
356 &$afterfork() if $afterfork;
357
358 if (ref($writer)) {
359 print $writer $input if defined $input;
360 close $writer;
361 }
362
363 my $select = new IO::Select;
364 $select->add($reader) if ref($reader);
365 $select->add($error);
366
367 my $outlog = '';
368 my $errlog = '';
369
370 my $starttime = time();
371
372 while ($select->count) {
373 my @handles = $select->can_read(1);
374
375 foreach my $h (@handles) {
376 my $buf = '';
377 my $count = sysread ($h, $buf, 4096);
378 if (!defined ($count)) {
379 my $err = $!;
380 kill (9, $pid);
381 waitpid ($pid, 0);
382 die $err;
383 }
384 $select->remove ($h) if !$count;
385 if ($h eq $reader) {
386 if ($outfunc || $logfunc) {
387 eval {
388 $outlog .= $buf;
389 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
390 my $line = $1;
391 &$outfunc($line) if $outfunc;
392 &$logfunc($line) if $logfunc;
393 }
394 };
395 my $err = $@;
396 if ($err) {
397 kill (9, $pid);
398 waitpid ($pid, 0);
399 die $err;
400 }
401 } else {
402 print $buf;
403 *STDOUT->flush();
404 }
405 } elsif ($h eq $error) {
406 if ($errfunc || $logfunc) {
407 eval {
408 $errlog .= $buf;
409 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
410 my $line = $1;
411 &$errfunc($line) if $errfunc;
412 &$logfunc($line) if $logfunc;
413 }
414 };
415 my $err = $@;
416 if ($err) {
417 kill (9, $pid);
418 waitpid ($pid, 0);
419 die $err;
420 }
421 } else {
422 print STDERR $buf;
423 *STDERR->flush();
424 }
425 }
426 }
427 }
428
429 &$outfunc($outlog) if $outfunc && $outlog;
430 &$logfunc($outlog) if $logfunc && $outlog;
431
432 &$errfunc($errlog) if $errfunc && $errlog;
433 &$logfunc($errlog) if $logfunc && $errlog;
434
435 waitpid ($pid, 0);
436
437 if ($? == -1) {
438 die "failed to execute\n";
439 } elsif (my $sig = ($? & 127)) {
440 die "got signal $sig\n";
441 } elsif (my $ec = ($? >> 8)) {
442 if (!($ec == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
443 if ($errmsg && $laststderr) {
444 my $lerr = $laststderr;
445 $laststderr = undef;
446 die "$lerr\n";
447 }
448 die "exit code $ec\n";
449 }
450 }
451
452 alarm(0);
453 };
454
455 my $err = $@;
456
457 alarm(0);
458
459 if ($errmsg && $laststderr) {
460 &$errfunc(undef); # flush laststderr
461 }
462
463 umask ($old_umask) if defined($old_umask);
464
465 alarm($oldtimeout) if $oldtimeout;
466
467 if ($err) {
468 if ($pid && ($err eq "got timeout\n")) {
469 kill (9, $pid);
470 waitpid ($pid, 0);
471 die "command '$cmdstr' failed: $err";
472 }
473
474 if ($errmsg) {
475 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
476 die "$errmsg: $err";
477 } else {
478 die "command '$cmdstr' failed: $err";
479 }
480 }
481
482 return undef;
483 }
484
485 sub split_list {
486 my $listtxt = shift || '';
487
488 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
489
490 $listtxt =~ s/[,;]/ /g;
491 $listtxt =~ s/^\s+//;
492
493 my @data = split (/\s+/, $listtxt);
494
495 return @data;
496 }
497
498 sub trim {
499 my $txt = shift;
500
501 return $txt if !defined($txt);
502
503 $txt =~ s/^\s+//;
504 $txt =~ s/\s+$//;
505
506 return $txt;
507 }
508
509 # simple uri templates like "/vms/{vmid}"
510 sub template_replace {
511 my ($tmpl, $data) = @_;
512
513 return $tmpl if !$tmpl;
514
515 my $res = '';
516 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
517 $res .= $1 if $1;
518 $res .= ($data->{$3} || '-') if $2;
519 }
520 return $res;
521 }
522
523 sub safe_print {
524 my ($filename, $fh, $data) = @_;
525
526 return if !$data;
527
528 my $res = print $fh $data;
529
530 die "write to '$filename' failed\n" if !$res;
531 }
532
533 sub debmirrors {
534
535 return {
536 'at' => 'ftp.at.debian.org',
537 'au' => 'ftp.au.debian.org',
538 'be' => 'ftp.be.debian.org',
539 'bg' => 'ftp.bg.debian.org',
540 'br' => 'ftp.br.debian.org',
541 'ca' => 'ftp.ca.debian.org',
542 'ch' => 'ftp.ch.debian.org',
543 'cl' => 'ftp.cl.debian.org',
544 'cz' => 'ftp.cz.debian.org',
545 'de' => 'ftp.de.debian.org',
546 'dk' => 'ftp.dk.debian.org',
547 'ee' => 'ftp.ee.debian.org',
548 'es' => 'ftp.es.debian.org',
549 'fi' => 'ftp.fi.debian.org',
550 'fr' => 'ftp.fr.debian.org',
551 'gr' => 'ftp.gr.debian.org',
552 'hk' => 'ftp.hk.debian.org',
553 'hr' => 'ftp.hr.debian.org',
554 'hu' => 'ftp.hu.debian.org',
555 'ie' => 'ftp.ie.debian.org',
556 'is' => 'ftp.is.debian.org',
557 'it' => 'ftp.it.debian.org',
558 'jp' => 'ftp.jp.debian.org',
559 'kr' => 'ftp.kr.debian.org',
560 'mx' => 'ftp.mx.debian.org',
561 'nl' => 'ftp.nl.debian.org',
562 'no' => 'ftp.no.debian.org',
563 'nz' => 'ftp.nz.debian.org',
564 'pl' => 'ftp.pl.debian.org',
565 'pt' => 'ftp.pt.debian.org',
566 'ro' => 'ftp.ro.debian.org',
567 'ru' => 'ftp.ru.debian.org',
568 'se' => 'ftp.se.debian.org',
569 'si' => 'ftp.si.debian.org',
570 'sk' => 'ftp.sk.debian.org',
571 'tr' => 'ftp.tr.debian.org',
572 'tw' => 'ftp.tw.debian.org',
573 'gb' => 'ftp.uk.debian.org',
574 'us' => 'ftp.us.debian.org',
575 };
576 }
577
578 my $keymaphash = {
579 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
580 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
581 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
582 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
583 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
584 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
585 #'et' => [], # Ethopia or Estonia ??
586 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
587 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
588 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
589 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
590 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
591 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
592 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
593 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
594 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
595 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
596 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
597 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
598 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
599 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
600 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
601 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
602 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
603 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
604 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
605 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
606 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
607 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
608 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
609 #'th' => [],
610 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
611 };
612
613 my $kvmkeymaparray = [];
614 foreach my $lc (keys %$keymaphash) {
615 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
616 }
617
618 sub kvmkeymaps {
619 return $keymaphash;
620 }
621
622 sub kvmkeymaplist {
623 return $kvmkeymaparray;
624 }
625
626 sub extract_param {
627 my ($param, $key) = @_;
628
629 my $res = $param->{$key};
630 delete $param->{$key};
631
632 return $res;
633 }
634
635 # Note: we use this to wait until vncterm/spiceterm is ready
636 sub wait_for_vnc_port {
637 my ($port, $timeout) = @_;
638
639 $timeout = 5 if !$timeout;
640 my $sleeptime = 0;
641 my $starttime = [gettimeofday];
642 my $elapsed;
643
644 while (($elapsed = tv_interval($starttime)) < $timeout) {
645 if (my $fh = IO::File->new ("/proc/net/tcp", "r")) {
646 while (defined (my $line = <$fh>)) {
647 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
648 if ($port == hex($2)) {
649 close($fh);
650 return 1;
651 }
652 }
653 }
654 close($fh);
655 }
656 $sleeptime += 100000 if $sleeptime < 1000000;
657 usleep($sleeptime);
658 }
659
660 return undef;
661 }
662
663 sub next_unused_port {
664 my ($range_start, $range_end, $family) = @_;
665
666 # We use a file to register allocated ports.
667 # Those registrations expires after $expiretime.
668 # We use this to avoid race conditions between
669 # allocation and use of ports.
670
671 my $filename = "/var/tmp/pve-reserved-ports";
672
673 my $code = sub {
674
675 my $expiretime = 5;
676 my $ctime = time();
677
678 my $ports = {};
679
680 if (my $fh = IO::File->new ($filename, "r")) {
681 while (my $line = <$fh>) {
682 if ($line =~ m/^(\d+)\s(\d+)$/) {
683 my ($port, $timestamp) = ($1, $2);
684 if (($timestamp + $expiretime) > $ctime) {
685 $ports->{$port} = $timestamp; # not expired
686 }
687 }
688 }
689 }
690
691 my $newport;
692
693 for (my $p = $range_start; $p < $range_end; $p++) {
694 next if $ports->{$p}; # reserved
695
696 my $sock = IO::Socket::IP->new(Listen => 5,
697 LocalPort => $p,
698 ReuseAddr => 1,
699 Family => $family,
700 Proto => 0,
701 GetAddrInfoFlags => 0);
702
703 if ($sock) {
704 close($sock);
705 $newport = $p;
706 $ports->{$p} = $ctime;
707 last;
708 }
709 }
710
711 my $data = "";
712 foreach my $p (keys %$ports) {
713 $data .= "$p $ports->{$p}\n";
714 }
715
716 file_set_contents($filename, $data);
717
718 return $newport;
719 };
720
721 my $p = lock_file($filename, 10, $code);
722 die $@ if $@;
723
724 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
725
726 return $p;
727 }
728
729 sub next_migrate_port {
730 my ($family) = @_;
731 return next_unused_port(60000, 60050, $family);
732 }
733
734 sub next_vnc_port {
735 my ($family) = @_;
736 return next_unused_port(5900, 6000, $family);
737 }
738
739 sub next_spice_port {
740 my ($family) = @_;
741 return next_unused_port(61000, 61099, $family);
742 }
743
744 # NOTE: NFS syscall can't be interrupted, so alarm does
745 # not work to provide timeouts.
746 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
747 # So the spawn external 'df' process instead of using
748 # Filesys::Df (which uses statfs syscall)
749 sub df {
750 my ($path, $timeout) = @_;
751
752 my $cmd = [ 'df', '-P', '-B', '1', $path];
753
754 my $res = {
755 total => 0,
756 used => 0,
757 avail => 0,
758 };
759
760 my $parser = sub {
761 my $line = shift;
762 if (my ($fsid, $total, $used, $avail) = $line =~
763 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
764 $res = {
765 total => $total,
766 used => $used,
767 avail => $avail,
768 };
769 }
770 };
771 eval { run_command($cmd, timeout => $timeout, outfunc => $parser); };
772 warn $@ if $@;
773
774 return $res;
775 }
776
777 # UPID helper
778 # We use this to uniquely identify a process.
779 # An 'Unique Process ID' has the following format:
780 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
781
782 sub upid_encode {
783 my $d = shift;
784
785 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
786 # more that 8 characters for pstart
787 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
788 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
789 $d->{user});
790 }
791
792 sub upid_decode {
793 my ($upid, $noerr) = @_;
794
795 my $res;
796 my $filename;
797
798 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
799 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
800 if ($upid =~ m/^UPID:([a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/) {
801 $res->{node} = $1;
802 $res->{pid} = hex($3);
803 $res->{pstart} = hex($4);
804 $res->{starttime} = hex($5);
805 $res->{type} = $6;
806 $res->{id} = $7;
807 $res->{user} = $8;
808
809 my $subdir = substr($5, 7, 8);
810 $filename = "$pvetaskdir/$subdir/$upid";
811
812 } else {
813 return undef if $noerr;
814 die "unable to parse worker upid '$upid'\n";
815 }
816
817 return wantarray ? ($res, $filename) : $res;
818 }
819
820 sub upid_open {
821 my ($upid) = @_;
822
823 my ($task, $filename) = upid_decode($upid);
824
825 my $dirname = dirname($filename);
826 make_path($dirname);
827
828 my $wwwid = getpwnam('www-data') ||
829 die "getpwnam failed";
830
831 my $perm = 0640;
832
833 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
834 die "unable to create output file '$filename' - $!\n";
835 chown $wwwid, -1, $outfh;
836
837 return $outfh;
838 };
839
840 sub upid_read_status {
841 my ($upid) = @_;
842
843 my ($task, $filename) = upid_decode($upid);
844 my $fh = IO::File->new($filename, "r");
845 return "unable to open file - $!" if !$fh;
846 my $maxlen = 4096;
847 sysseek($fh, -$maxlen, 2);
848 my $readbuf = '';
849 my $br = sysread($fh, $readbuf, $maxlen);
850 close($fh);
851 if ($br) {
852 return "unable to extract last line"
853 if $readbuf !~ m/\n?(.+)$/;
854 my $line = $1;
855 if ($line =~ m/^TASK OK$/) {
856 return 'OK';
857 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
858 return $1;
859 } else {
860 return "unexpected status";
861 }
862 }
863 return "unable to read tail (got $br bytes)";
864 }
865
866 # useful functions to store comments in config files
867 sub encode_text {
868 my ($text) = @_;
869
870 # all control and hi-bit characters, and ':'
871 my $unsafe = "^\x20-\x39\x3b-\x7e";
872 return uri_escape(Encode::encode("utf8", $text), $unsafe);
873 }
874
875 sub decode_text {
876 my ($data) = @_;
877
878 return Encode::decode("utf8", uri_unescape($data));
879 }
880
881 sub decode_utf8_parameters {
882 my ($param) = @_;
883
884 foreach my $p (qw(comment description firstname lastname)) {
885 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
886 }
887
888 return $param;
889 }
890
891 sub random_ether_addr {
892
893 my ($seconds, $microseconds) = gettimeofday;
894
895 my $rand = Digest::SHA::sha1_hex($$, rand(), $seconds, $microseconds);
896
897 my $mac = '';
898 for (my $i = 0; $i < 6; $i++) {
899 my $ss = hex(substr($rand, $i*2, 2));
900 if (!$i) {
901 $ss &= 0xfe; # clear multicast
902 $ss |= 2; # set local id
903 }
904 $ss = sprintf("%02X", $ss);
905
906 if (!$i) {
907 $mac .= "$ss";
908 } else {
909 $mac .= ":$ss";
910 }
911 }
912
913 return $mac;
914 }
915
916 sub shellquote {
917 my $str = shift;
918
919 return String::ShellQuote::shell_quote($str);
920 }
921
922 sub cmd2string {
923 my ($cmd) = @_;
924
925 die "no arguments" if !$cmd;
926
927 return $cmd if !ref($cmd);
928
929 my @qa = ();
930 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
931
932 return join (' ', @qa);
933 }
934
935 # split an shell argument string into an array,
936 sub split_args {
937 my ($str) = @_;
938
939 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
940 }
941
942 sub dump_logfile {
943 my ($filename, $start, $limit, $filter) = @_;
944
945 my $lines = [];
946 my $count = 0;
947
948 my $fh = IO::File->new($filename, "r");
949 if (!$fh) {
950 $count++;
951 push @$lines, { n => $count, t => "unable to open file - $!"};
952 return ($count, $lines);
953 }
954
955 $start = 0 if !$start;
956 $limit = 50 if !$limit;
957
958 my $line;
959
960 if ($filter) {
961 # duplicate code, so that we do not slow down normal path
962 while (defined($line = <$fh>)) {
963 next if $line !~ m/$filter/;
964 next if $count++ < $start;
965 next if $limit <= 0;
966 chomp $line;
967 push @$lines, { n => $count, t => $line};
968 $limit--;
969 }
970 } else {
971 while (defined($line = <$fh>)) {
972 next if $count++ < $start;
973 next if $limit <= 0;
974 chomp $line;
975 push @$lines, { n => $count, t => $line};
976 $limit--;
977 }
978 }
979
980 close($fh);
981
982 # HACK: ExtJS store.guaranteeRange() does not like empty array
983 # so we add a line
984 if (!$count) {
985 $count++;
986 push @$lines, { n => $count, t => "no content"};
987 }
988
989 return ($count, $lines);
990 }
991
992 sub dump_journal {
993 my ($start, $limit, $filter) = @_;
994
995 my $lines = [];
996 my $count = 0;
997
998 $start = 0 if !$start;
999 $limit = 50 if !$limit;
1000
1001 my $parser = sub {
1002 my $line = shift;
1003
1004 return if $count++ < $start;
1005 return if $limit <= 0;
1006 push @$lines, { n => int($count), t => $line};
1007 $limit--;
1008 };
1009
1010 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1011 run_command($cmd, outfunc => $parser);
1012
1013 # HACK: ExtJS store.guaranteeRange() does not like empty array
1014 # so we add a line
1015 if (!$count) {
1016 $count++;
1017 push @$lines, { n => $count, t => "no content"};
1018 }
1019
1020 return ($count, $lines);
1021 }
1022
1023 sub dir_glob_regex {
1024 my ($dir, $regex) = @_;
1025
1026 my $dh = IO::Dir->new ($dir);
1027 return wantarray ? () : undef if !$dh;
1028
1029 while (defined(my $tmp = $dh->read)) {
1030 if (my @res = $tmp =~ m/^($regex)$/) {
1031 $dh->close;
1032 return wantarray ? @res : $tmp;
1033 }
1034 }
1035 $dh->close;
1036
1037 return wantarray ? () : undef;
1038 }
1039
1040 sub dir_glob_foreach {
1041 my ($dir, $regex, $func) = @_;
1042
1043 my $dh = IO::Dir->new ($dir);
1044 if (defined $dh) {
1045 while (defined(my $tmp = $dh->read)) {
1046 if (my @res = $tmp =~ m/^($regex)$/) {
1047 &$func (@res);
1048 }
1049 }
1050 }
1051 }
1052
1053 sub assert_if_modified {
1054 my ($digest1, $digest2) = @_;
1055
1056 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1057 die "detected modified configuration - file changed by other user? Try again.\n";
1058 }
1059 }
1060
1061 # Digest for short strings
1062 # like FNV32a, but we only return 31 bits (positive numbers)
1063 sub fnv31a {
1064 my ($string) = @_;
1065
1066 my $hval = 0x811c9dc5;
1067
1068 foreach my $c (unpack('C*', $string)) {
1069 $hval ^= $c;
1070 $hval += (
1071 (($hval << 1) ) +
1072 (($hval << 4) ) +
1073 (($hval << 7) ) +
1074 (($hval << 8) ) +
1075 (($hval << 24) ) );
1076 $hval = $hval & 0xffffffff;
1077 }
1078 return $hval & 0x7fffffff;
1079 }
1080
1081 sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1082
1083 sub unpack_sockaddr_in46 {
1084 my ($sin) = @_;
1085 my $family = Socket::sockaddr_family($sin);
1086 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1087 : Socket::unpack_sockaddr_in($sin));
1088 return ($family, $port, $host);
1089 }
1090
1091 sub getaddrinfo_all {
1092 my ($hostname, @opts) = @_;
1093 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
1094 @opts );
1095 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
1096 die "failed to get address info for: $hostname: $err\n" if $err;
1097 return @res;
1098 }
1099
1100 sub get_host_address_family {
1101 my ($hostname, $socktype) = @_;
1102 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1103 return $res[0]->{family};
1104 }
1105
1106 # Parses any sane kind of host, or host+port pair:
1107 # The port is always optional and thus may be undef.
1108 sub parse_host_and_port {
1109 my ($address) = @_;
1110 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1111 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1112 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1113 {
1114 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1115 }
1116 return; # nothing
1117 }
1118
1119 1;