]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
8 use File
::Path
qw(make_path);
12 use Fcntl
qw(:DEFAULT :flock);
18 use String
::ShellQuote
;
36 my $pvelogdir = "/var/log/pve";
37 my $pvetaskdir = "$pvelogdir/tasks";
42 sub run_with_timeout
{
43 my ($timeout, $code, @param) = @_;
45 die "got timeout\n" if $timeout <= 0;
53 local $SIG{ALRM
} = sub { $sigcount++; }; # catch alarm outside eval
56 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
57 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
58 local $SIG{__DIE__
}; # see SA bug 4631
60 $prev_alarm = alarm($timeout);
62 $res = &$code(@param);
64 alarm(0); # avoid race conditions
69 alarm($prev_alarm) if defined($prev_alarm);
71 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
78 # flock: we use one file handle per process, so lock file
79 # can be called multiple times and succeeds for the same process.
81 my $lock_handles = {};
84 my ($filename, $timeout, $shared, $code, @param) = @_;
86 $timeout = 10 if !$timeout;
88 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
91 if (!$lock_handles->{$$}->{$filename}) {
92 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
93 die "can't open file - $!\n";
96 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
97 print STDERR
"trying to aquire lock...";
100 $success = flock($lock_handles->{$$}->{$filename}, $mode);
101 # try again on EINTR (see bug #273)
102 if ($success || ($! != EINTR
)) {
107 print STDERR
" failed\n";
108 die "can't aquire lock - $!\n";
110 print STDERR
" OK\n";
116 eval { run_with_timeout
($timeout, $lock_func); };
119 $err = "can't lock file '$filename' - $err";
121 eval { $res = &$code(@param) };
125 if ($lock_handles->{$$}->{$filename}) {
126 my $fh = $lock_handles->{$$}->{$filename};
127 $lock_handles->{$$}->{$filename} = undef;
143 my ($filename, $timeout, $code, @param) = @_;
145 return lock_file_full
($filename, $timeout, 0, $code, @param);
148 sub file_set_contents
{
149 my ($filename, $data, $perm) = @_;
151 $perm = 0644 if !defined($perm);
153 my $tmpname = "$filename.tmp.$$";
156 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
157 die "unable to open file '$tmpname' - $!\n" if !$fh;
158 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
159 die "closing file '$tmpname' failed - $!\n" unless close $fh;
168 if (!rename($tmpname, $filename)) {
169 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
175 sub file_get_contents
{
176 my ($filename, $max) = @_;
178 my $fh = IO
::File-
>new($filename, "r") ||
179 die "can't open '$filename' - $!\n";
181 my $content = safe_read_from
($fh, $max);
188 sub file_read_firstline
{
191 my $fh = IO
::File-
>new ($filename, "r");
192 return undef if !$fh;
200 my ($fh, $max, $oneline) = @_;
202 $max = 32768 if !$max;
207 while ($count = sysread($fh, $input, 8192, $br)) {
209 die "input too long - aborting\n" if $br > $max;
210 if ($oneline && $input =~ m/^(.*)\n/) {
215 die "unable to read input - $!\n" if !defined($count);
221 my ($cmd, %param) = @_;
229 # see 'man bash' for option pipefail
230 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
235 $cmdstr = cmd2string
($cmd);
253 foreach my $p (keys %param) {
254 if ($p eq 'timeout') {
255 $timeout = $param{$p};
256 } elsif ($p eq 'umask') {
257 $old_umask = umask($param{$p});
258 } elsif ($p eq 'errmsg') {
259 $errmsg = $param{$p};
260 } elsif ($p eq 'input') {
262 } elsif ($p eq 'output') {
263 $output = $param{$p};
264 } elsif ($p eq 'outfunc') {
265 $outfunc = $param{$p};
266 } elsif ($p eq 'errfunc') {
267 $errfunc = $param{$p};
268 } elsif ($p eq 'logfunc') {
269 $logfunc = $param{$p};
270 } elsif ($p eq 'afterfork') {
271 $afterfork = $param{$p};
273 die "got unknown parameter '$p' for run_command\n";
278 my $origerrfunc = $errfunc;
282 &$origerrfunc("$laststderr\n");
284 print STDERR
"$laststderr\n" if $laststderr;
291 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
292 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
293 my $error = IO
::File-
>new();
295 # try to avoid locale related issues/warnings
296 my $lang = $param{lang
} || 'C';
301 local $ENV{LC_ALL
} = $lang;
303 # suppress LVM warnings like: "File descriptor 3 left open";
304 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
306 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
308 # if we pipe fron STDIN, open3 closes STDIN, so we we
309 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
310 # as soon as we open a new file.
311 # to avoid that we open /dev/null
312 if (!ref($writer) && !defined(fileno(STDIN
))) {
314 open(STDIN
, "</dev/null");
321 if ($orig_pid != $$) {
329 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
330 $oldtimeout = alarm($timeout) if $timeout;
332 &$afterfork() if $afterfork;
335 print $writer $input if defined $input;
339 my $select = new IO
::Select
;
340 $select->add($reader) if ref($reader);
341 $select->add($error);
346 my $starttime = time();
348 while ($select->count) {
349 my @handles = $select->can_read(1);
351 foreach my $h (@handles) {
353 my $count = sysread ($h, $buf, 4096);
354 if (!defined ($count)) {
360 $select->remove ($h) if !$count;
362 if ($outfunc || $logfunc) {
365 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
367 &$outfunc($line) if $outfunc;
368 &$logfunc($line) if $logfunc;
381 } elsif ($h eq $error) {
382 if ($errfunc || $logfunc) {
385 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
387 &$errfunc($line) if $errfunc;
388 &$logfunc($line) if $logfunc;
405 &$outfunc($outlog) if $outfunc && $outlog;
406 &$logfunc($outlog) if $logfunc && $outlog;
408 &$errfunc($errlog) if $errfunc && $errlog;
409 &$logfunc($errlog) if $logfunc && $errlog;
414 die "failed to execute\n";
415 } elsif (my $sig = ($? & 127)) {
416 die "got signal $sig\n";
417 } elsif (my $ec = ($? >> 8)) {
418 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
419 if ($errmsg && $laststderr) {
420 my $lerr = $laststderr;
424 die "exit code $ec\n";
435 if ($errmsg && $laststderr) {
436 &$errfunc(undef); # flush laststderr
439 umask ($old_umask) if defined($old_umask);
441 alarm($oldtimeout) if $oldtimeout;
444 if ($pid && ($err eq "got timeout\n")) {
447 die "command '$cmdstr' failed: $err";
451 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
454 die "command '$cmdstr' failed: $err";
462 my $listtxt = shift || '';
464 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
466 $listtxt =~ s/[,;]/ /g;
467 $listtxt =~ s/^\s+//;
469 my @data = split (/\s+/, $listtxt);
477 return $txt if !defined($txt);
485 # simple uri templates like "/vms/{vmid}"
486 sub template_replace
{
487 my ($tmpl, $data) = @_;
489 return $tmpl if !$tmpl;
492 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
494 $res .= ($data->{$3} || '-') if $2;
500 my ($filename, $fh, $data) = @_;
504 my $res = print $fh $data;
506 die "write to '$filename' failed\n" if !$res;
512 'at' => 'ftp.at.debian.org',
513 'au' => 'ftp.au.debian.org',
514 'be' => 'ftp.be.debian.org',
515 'bg' => 'ftp.bg.debian.org',
516 'br' => 'ftp.br.debian.org',
517 'ca' => 'ftp.ca.debian.org',
518 'ch' => 'ftp.ch.debian.org',
519 'cl' => 'ftp.cl.debian.org',
520 'cz' => 'ftp.cz.debian.org',
521 'de' => 'ftp.de.debian.org',
522 'dk' => 'ftp.dk.debian.org',
523 'ee' => 'ftp.ee.debian.org',
524 'es' => 'ftp.es.debian.org',
525 'fi' => 'ftp.fi.debian.org',
526 'fr' => 'ftp.fr.debian.org',
527 'gr' => 'ftp.gr.debian.org',
528 'hk' => 'ftp.hk.debian.org',
529 'hr' => 'ftp.hr.debian.org',
530 'hu' => 'ftp.hu.debian.org',
531 'ie' => 'ftp.ie.debian.org',
532 'is' => 'ftp.is.debian.org',
533 'it' => 'ftp.it.debian.org',
534 'jp' => 'ftp.jp.debian.org',
535 'kr' => 'ftp.kr.debian.org',
536 'mx' => 'ftp.mx.debian.org',
537 'nl' => 'ftp.nl.debian.org',
538 'no' => 'ftp.no.debian.org',
539 'nz' => 'ftp.nz.debian.org',
540 'pl' => 'ftp.pl.debian.org',
541 'pt' => 'ftp.pt.debian.org',
542 'ro' => 'ftp.ro.debian.org',
543 'ru' => 'ftp.ru.debian.org',
544 'se' => 'ftp.se.debian.org',
545 'si' => 'ftp.si.debian.org',
546 'sk' => 'ftp.sk.debian.org',
547 'tr' => 'ftp.tr.debian.org',
548 'tw' => 'ftp.tw.debian.org',
549 'gb' => 'ftp.uk.debian.org',
550 'us' => 'ftp.us.debian.org',
555 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
556 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
557 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
558 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
559 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
560 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
561 #'et' => [], # Ethopia or Estonia ??
562 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
563 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
564 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
565 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
566 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
567 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
568 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
569 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
570 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
571 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
572 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
573 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
574 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
575 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
576 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
577 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
578 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
579 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
580 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
581 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
582 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
583 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
584 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
586 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
589 my $kvmkeymaparray = [];
590 foreach my $lc (keys %$keymaphash) {
591 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
599 return $kvmkeymaparray;
603 my ($param, $key) = @_;
605 my $res = $param->{$key};
606 delete $param->{$key};
611 # Note: we use this to wait until vncterm is ready
612 sub wait_for_vnc_port
{
613 my ($port, $timeout) = @_;
615 $timeout = 5 if !$timeout;
617 for (my $i = 0; $i < $timeout; $i++) {
618 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
619 while (defined (my $line = <$fh>)) {
620 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
621 if ($port == hex($2)) {
637 for (my $p = 5900; $p < 6000; $p++) {
639 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
640 LocalAddr
=> 'localhost',
651 die "unable to find free vnc port";
654 # NOTE: NFS syscall can't be interrupted, so alarm does
655 # not work to provide timeouts.
656 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
657 # So the spawn external 'df' process instead of using
658 # Filesys::Df (which uses statfs syscall)
660 my ($path, $timeout) = @_;
662 my $cmd = [ 'df', '-P', '-B', '1', $path];
672 if (my ($fsid, $total, $used, $avail) = $line =~
673 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
681 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
688 # We use this to uniquely identify a process.
689 # An 'Unique Process ID' has the following format:
690 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
695 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
696 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
701 my ($upid, $noerr) = @_;
706 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
707 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]+):$/) {
709 $res->{pid
} = hex($3);
710 $res->{pstart
} = hex($4);
711 $res->{starttime
} = hex($5);
716 my $subdir = substr($5, 7, 8);
717 $filename = "$pvetaskdir/$subdir/$upid";
720 return undef if $noerr;
721 die "unable to parse worker upid '$upid'\n";
724 return wantarray ?
($res, $filename) : $res;
730 my ($task, $filename) = upid_decode
($upid);
732 my $dirname = dirname
($filename);
735 my $wwwid = getpwnam('www-data') ||
736 die "getpwnam failed";
740 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
741 die "unable to create output file '$filename' - $!\n";
742 chown $wwwid, -1, $outfh;
747 sub upid_read_status
{
750 my ($task, $filename) = upid_decode
($upid);
751 my $fh = IO
::File-
>new($filename, "r");
752 return "unable to open file - $!" if !$fh;
754 sysseek($fh, -$maxlen, 2);
756 my $br = sysread($fh, $readbuf, $maxlen);
759 return "unable to extract last line"
760 if $readbuf !~ m/\n?(.+)$/;
762 if ($line =~ m/^TASK OK$/) {
764 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
767 return "unexpected status";
770 return "unable to read tail (got $br bytes)";
773 # useful functions to store comments in config files
777 # all control and hi-bit characters, and ':'
778 my $unsafe = "^\x20-\x39\x3b-\x7e";
779 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
785 return Encode
::decode
("utf8", uri_unescape
($data));
788 sub decode_utf8_parameters
{
791 foreach my $p (qw(comment description firstname lastname)) {
792 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
798 sub random_ether_addr
{
800 my $rand = Digest
::SHA
::sha1_hex
(rand(), time());
803 for (my $i = 0; $i < 6; $i++) {
804 my $ss = hex(substr($rand, $i*2, 2));
806 $ss &= 0xfe; # clear multicast
807 $ss |= 2; # set local id
809 $ss = sprintf("%02X", $ss);
824 return String
::ShellQuote
::shell_quote
($str);
830 die "no arguments" if !$cmd;
832 return $cmd if !ref($cmd);
835 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
837 return join (' ', @qa);
840 # split an shell argument string into an array,
844 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
848 my ($filename, $start, $limit) = @_;
853 my $fh = IO
::File-
>new($filename, "r");
856 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
857 return ($count, $lines);
860 $start = 0 if !$start;
861 $limit = 50 if !$limit;
864 while (defined($line = <$fh>)) {
865 next if $count++ < $start;
868 push @$lines, { n
=> $count, t
=> $line};
874 # HACK: ExtJS store.guaranteeRange() does not like empty array
878 push @$lines, { n
=> $count, t
=> "no content"};
881 return ($count, $lines);
885 my ($dir, $regex) = @_;
887 my $dh = IO
::Dir-
>new ($dir);
888 return wantarray ?
() : undef if !$dh;
890 while (defined(my $tmp = $dh->read)) {
891 if (my @res = $tmp =~ m/^($regex)$/) {
893 return wantarray ?
@res : $tmp;
898 return wantarray ?
() : undef;
901 sub dir_glob_foreach
{
902 my ($dir, $regex, $func) = @_;
904 my $dh = IO
::Dir-
>new ($dir);
906 while (defined(my $tmp = $dh->read)) {
907 if (my @res = $tmp =~ m/^($regex)$/) {