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