]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
735cbdeda65eaac934437315d7ac6553c8b32354
9 use File
::Path
qw(make_path);
13 use Fcntl
qw(:DEFAULT :flock);
19 use String
::ShellQuote
;
39 my $pvelogdir = "/var/log/pve";
40 my $pvetaskdir = "$pvelogdir/tasks";
45 my $IPV4OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
46 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
47 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
48 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
51 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
52 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
53 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
54 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
55 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
56 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
57 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
58 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
59 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
61 sub run_with_timeout
{
62 my ($timeout, $code, @param) = @_;
64 die "got timeout\n" if $timeout <= 0;
72 local $SIG{ALRM
} = sub { $sigcount++; }; # catch alarm outside eval
75 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
76 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
77 local $SIG{__DIE__
}; # see SA bug 4631
79 $prev_alarm = alarm($timeout);
81 $res = &$code(@param);
83 alarm(0); # avoid race conditions
88 alarm($prev_alarm) if defined($prev_alarm);
90 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
97 # flock: we use one file handle per process, so lock file
98 # can be called multiple times and succeeds for the same process.
100 my $lock_handles = {};
103 my ($filename, $timeout, $shared, $code, @param) = @_;
105 $timeout = 10 if !$timeout;
107 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
109 my $lock_func = sub {
110 if (!$lock_handles->{$$}->{$filename}) {
111 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
112 die "can't open file - $!\n";
115 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
116 print STDERR
"trying to aquire lock...";
119 $success = flock($lock_handles->{$$}->{$filename}, $mode);
120 # try again on EINTR (see bug #273)
121 if ($success || ($! != EINTR
)) {
126 print STDERR
" failed\n";
127 die "can't aquire lock - $!\n";
129 print STDERR
" OK\n";
135 eval { run_with_timeout
($timeout, $lock_func); };
138 $err = "can't lock file '$filename' - $err";
140 eval { $res = &$code(@param) };
144 if ($lock_handles->{$$}->{$filename}) {
145 my $fh = $lock_handles->{$$}->{$filename};
146 $lock_handles->{$$}->{$filename} = undef;
162 my ($filename, $timeout, $code, @param) = @_;
164 return lock_file_full
($filename, $timeout, 0, $code, @param);
167 sub file_set_contents
{
168 my ($filename, $data, $perm) = @_;
170 $perm = 0644 if !defined($perm);
172 my $tmpname = "$filename.tmp.$$";
175 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
176 die "unable to open file '$tmpname' - $!\n" if !$fh;
177 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
178 die "closing file '$tmpname' failed - $!\n" unless close $fh;
187 if (!rename($tmpname, $filename)) {
188 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
194 sub file_get_contents
{
195 my ($filename, $max) = @_;
197 my $fh = IO
::File-
>new($filename, "r") ||
198 die "can't open '$filename' - $!\n";
200 my $content = safe_read_from
($fh, $max);
207 sub file_read_firstline
{
210 my $fh = IO
::File-
>new ($filename, "r");
211 return undef if !$fh;
219 my ($fh, $max, $oneline) = @_;
221 $max = 32768 if !$max;
226 while ($count = sysread($fh, $input, 8192, $br)) {
228 die "input too long - aborting\n" if $br > $max;
229 if ($oneline && $input =~ m/^(.*)\n/) {
234 die "unable to read input - $!\n" if !defined($count);
240 my ($cmd, %param) = @_;
248 # see 'man bash' for option pipefail
249 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
254 $cmdstr = cmd2string
($cmd);
272 foreach my $p (keys %param) {
273 if ($p eq 'timeout') {
274 $timeout = $param{$p};
275 } elsif ($p eq 'umask') {
276 $old_umask = umask($param{$p});
277 } elsif ($p eq 'errmsg') {
278 $errmsg = $param{$p};
279 } elsif ($p eq 'input') {
281 } elsif ($p eq 'output') {
282 $output = $param{$p};
283 } elsif ($p eq 'outfunc') {
284 $outfunc = $param{$p};
285 } elsif ($p eq 'errfunc') {
286 $errfunc = $param{$p};
287 } elsif ($p eq 'logfunc') {
288 $logfunc = $param{$p};
289 } elsif ($p eq 'afterfork') {
290 $afterfork = $param{$p};
292 die "got unknown parameter '$p' for run_command\n";
297 my $origerrfunc = $errfunc;
301 &$origerrfunc("$laststderr\n");
303 print STDERR
"$laststderr\n" if $laststderr;
310 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
311 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
312 my $error = IO
::File-
>new();
314 # try to avoid locale related issues/warnings
315 my $lang = $param{lang
} || 'C';
320 local $ENV{LC_ALL
} = $lang;
322 # suppress LVM warnings like: "File descriptor 3 left open";
323 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
325 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
327 # if we pipe fron STDIN, open3 closes STDIN, so we we
328 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
329 # as soon as we open a new file.
330 # to avoid that we open /dev/null
331 if (!ref($writer) && !defined(fileno(STDIN
))) {
333 open(STDIN
, "</dev/null");
340 if ($orig_pid != $$) {
348 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
349 $oldtimeout = alarm($timeout) if $timeout;
351 &$afterfork() if $afterfork;
354 print $writer $input if defined $input;
358 my $select = new IO
::Select
;
359 $select->add($reader) if ref($reader);
360 $select->add($error);
365 my $starttime = time();
367 while ($select->count) {
368 my @handles = $select->can_read(1);
370 foreach my $h (@handles) {
372 my $count = sysread ($h, $buf, 4096);
373 if (!defined ($count)) {
379 $select->remove ($h) if !$count;
381 if ($outfunc || $logfunc) {
384 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
386 &$outfunc($line) if $outfunc;
387 &$logfunc($line) if $logfunc;
400 } elsif ($h eq $error) {
401 if ($errfunc || $logfunc) {
404 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
406 &$errfunc($line) if $errfunc;
407 &$logfunc($line) if $logfunc;
424 &$outfunc($outlog) if $outfunc && $outlog;
425 &$logfunc($outlog) if $logfunc && $outlog;
427 &$errfunc($errlog) if $errfunc && $errlog;
428 &$logfunc($errlog) if $logfunc && $errlog;
433 die "failed to execute\n";
434 } elsif (my $sig = ($? & 127)) {
435 die "got signal $sig\n";
436 } elsif (my $ec = ($? >> 8)) {
437 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
438 if ($errmsg && $laststderr) {
439 my $lerr = $laststderr;
443 die "exit code $ec\n";
454 if ($errmsg && $laststderr) {
455 &$errfunc(undef); # flush laststderr
458 umask ($old_umask) if defined($old_umask);
460 alarm($oldtimeout) if $oldtimeout;
463 if ($pid && ($err eq "got timeout\n")) {
466 die "command '$cmdstr' failed: $err";
470 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
473 die "command '$cmdstr' failed: $err";
481 my $listtxt = shift || '';
483 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
485 $listtxt =~ s/[,;]/ /g;
486 $listtxt =~ s/^\s+//;
488 my @data = split (/\s+/, $listtxt);
496 return $txt if !defined($txt);
504 # simple uri templates like "/vms/{vmid}"
505 sub template_replace
{
506 my ($tmpl, $data) = @_;
508 return $tmpl if !$tmpl;
511 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
513 $res .= ($data->{$3} || '-') if $2;
519 my ($filename, $fh, $data) = @_;
523 my $res = print $fh $data;
525 die "write to '$filename' failed\n" if !$res;
531 'at' => 'ftp.at.debian.org',
532 'au' => 'ftp.au.debian.org',
533 'be' => 'ftp.be.debian.org',
534 'bg' => 'ftp.bg.debian.org',
535 'br' => 'ftp.br.debian.org',
536 'ca' => 'ftp.ca.debian.org',
537 'ch' => 'ftp.ch.debian.org',
538 'cl' => 'ftp.cl.debian.org',
539 'cz' => 'ftp.cz.debian.org',
540 'de' => 'ftp.de.debian.org',
541 'dk' => 'ftp.dk.debian.org',
542 'ee' => 'ftp.ee.debian.org',
543 'es' => 'ftp.es.debian.org',
544 'fi' => 'ftp.fi.debian.org',
545 'fr' => 'ftp.fr.debian.org',
546 'gr' => 'ftp.gr.debian.org',
547 'hk' => 'ftp.hk.debian.org',
548 'hr' => 'ftp.hr.debian.org',
549 'hu' => 'ftp.hu.debian.org',
550 'ie' => 'ftp.ie.debian.org',
551 'is' => 'ftp.is.debian.org',
552 'it' => 'ftp.it.debian.org',
553 'jp' => 'ftp.jp.debian.org',
554 'kr' => 'ftp.kr.debian.org',
555 'mx' => 'ftp.mx.debian.org',
556 'nl' => 'ftp.nl.debian.org',
557 'no' => 'ftp.no.debian.org',
558 'nz' => 'ftp.nz.debian.org',
559 'pl' => 'ftp.pl.debian.org',
560 'pt' => 'ftp.pt.debian.org',
561 'ro' => 'ftp.ro.debian.org',
562 'ru' => 'ftp.ru.debian.org',
563 'se' => 'ftp.se.debian.org',
564 'si' => 'ftp.si.debian.org',
565 'sk' => 'ftp.sk.debian.org',
566 'tr' => 'ftp.tr.debian.org',
567 'tw' => 'ftp.tw.debian.org',
568 'gb' => 'ftp.uk.debian.org',
569 'us' => 'ftp.us.debian.org',
574 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
575 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
576 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
577 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
578 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
579 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
580 #'et' => [], # Ethopia or Estonia ??
581 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
582 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
583 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
584 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
585 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
586 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
587 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
588 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
589 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
590 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
591 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
592 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
593 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
594 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
595 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
596 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
597 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
598 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
599 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
600 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
601 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
602 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
603 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
605 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
608 my $kvmkeymaparray = [];
609 foreach my $lc (keys %$keymaphash) {
610 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
618 return $kvmkeymaparray;
622 my ($param, $key) = @_;
624 my $res = $param->{$key};
625 delete $param->{$key};
630 # Note: we use this to wait until vncterm is ready
631 sub wait_for_vnc_port
{
632 my ($port, $timeout) = @_;
634 $timeout = 5 if !$timeout;
636 for (my $i = 0; $i < $timeout; $i++) {
637 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
638 while (defined (my $line = <$fh>)) {
639 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
640 if ($port == hex($2)) {
654 sub next_unused_port
{
655 my ($range_start, $range_end) = @_;
657 # We use a file to register allocated ports.
658 # Those registrations expires after $expiretime.
659 # We use this to avoid race conditions between
660 # allocation and use of ports.
662 my $filename = "/var/tmp/pve-reserved-ports";
671 if (my $fh = IO
::File-
>new ($filename, "r")) {
672 while (my $line = <$fh>) {
673 if ($line =~ m/^(\d+)\s(\d+)$/) {
674 my ($port, $timestamp) = ($1, $2);
675 if (($timestamp + $expiretime) > $ctime) {
676 $ports->{$port} = $timestamp; # not expired
684 for (my $p = $range_start; $p < $range_end; $p++) {
685 next if $ports->{$p}; # reserved
687 my $sock = IO
::Socket
::INET-
>new(Listen
=> 5,
688 LocalAddr
=> 'localhost',
696 $ports->{$p} = $ctime;
702 foreach my $p (keys %$ports) {
703 $data .= "$p $ports->{$p}\n";
706 file_set_contents
($filename, $data);
711 my $p = lock_file
($filename, 10, $code);
714 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
719 sub next_migrate_port
{
720 return next_unused_port
(60000, 60010);
724 return next_unused_port
(5900, 6000);
727 # NOTE: NFS syscall can't be interrupted, so alarm does
728 # not work to provide timeouts.
729 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
730 # So the spawn external 'df' process instead of using
731 # Filesys::Df (which uses statfs syscall)
733 my ($path, $timeout) = @_;
735 my $cmd = [ 'df', '-P', '-B', '1', $path];
745 if (my ($fsid, $total, $used, $avail) = $line =~
746 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
754 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
761 # We use this to uniquely identify a process.
762 # An 'Unique Process ID' has the following format:
763 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
768 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
769 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
774 my ($upid, $noerr) = @_;
779 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
780 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}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/) {
782 $res->{pid
} = hex($3);
783 $res->{pstart
} = hex($4);
784 $res->{starttime
} = hex($5);
789 my $subdir = substr($5, 7, 8);
790 $filename = "$pvetaskdir/$subdir/$upid";
793 return undef if $noerr;
794 die "unable to parse worker upid '$upid'\n";
797 return wantarray ?
($res, $filename) : $res;
803 my ($task, $filename) = upid_decode
($upid);
805 my $dirname = dirname
($filename);
808 my $wwwid = getpwnam('www-data') ||
809 die "getpwnam failed";
813 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
814 die "unable to create output file '$filename' - $!\n";
815 chown $wwwid, -1, $outfh;
820 sub upid_read_status
{
823 my ($task, $filename) = upid_decode
($upid);
824 my $fh = IO
::File-
>new($filename, "r");
825 return "unable to open file - $!" if !$fh;
827 sysseek($fh, -$maxlen, 2);
829 my $br = sysread($fh, $readbuf, $maxlen);
832 return "unable to extract last line"
833 if $readbuf !~ m/\n?(.+)$/;
835 if ($line =~ m/^TASK OK$/) {
837 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
840 return "unexpected status";
843 return "unable to read tail (got $br bytes)";
846 # useful functions to store comments in config files
850 # all control and hi-bit characters, and ':'
851 my $unsafe = "^\x20-\x39\x3b-\x7e";
852 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
858 return Encode
::decode
("utf8", uri_unescape
($data));
861 sub decode_utf8_parameters
{
864 foreach my $p (qw(comment description firstname lastname)) {
865 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
871 sub random_ether_addr
{
873 my $rand = Digest
::SHA
::sha1_hex
(rand(), time());
876 for (my $i = 0; $i < 6; $i++) {
877 my $ss = hex(substr($rand, $i*2, 2));
879 $ss &= 0xfe; # clear multicast
880 $ss |= 2; # set local id
882 $ss = sprintf("%02X", $ss);
897 return String
::ShellQuote
::shell_quote
($str);
903 die "no arguments" if !$cmd;
905 return $cmd if !ref($cmd);
908 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
910 return join (' ', @qa);
913 # split an shell argument string into an array,
917 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
921 my ($filename, $start, $limit) = @_;
926 my $fh = IO
::File-
>new($filename, "r");
929 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
930 return ($count, $lines);
933 $start = 0 if !$start;
934 $limit = 50 if !$limit;
937 while (defined($line = <$fh>)) {
938 next if $count++ < $start;
941 push @$lines, { n
=> $count, t
=> $line};
947 # HACK: ExtJS store.guaranteeRange() does not like empty array
951 push @$lines, { n
=> $count, t
=> "no content"};
954 return ($count, $lines);
958 my ($dir, $regex) = @_;
960 my $dh = IO
::Dir-
>new ($dir);
961 return wantarray ?
() : undef if !$dh;
963 while (defined(my $tmp = $dh->read)) {
964 if (my @res = $tmp =~ m/^($regex)$/) {
966 return wantarray ?
@res : $tmp;
971 return wantarray ?
() : undef;
974 sub dir_glob_foreach
{
975 my ($dir, $regex, $func) = @_;
977 my $dh = IO
::Dir-
>new ($dir);
979 while (defined(my $tmp = $dh->read)) {
980 if (my @res = $tmp =~ m/^($regex)$/) {