]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
8b2725e3aff2f718c5cef3818648865cf394d428
8 use File
::Path
qw(make_path);
11 use Fcntl
qw(:DEFAULT :flock);
17 use String
::ShellQuote
;
32 my $pvelogdir = "/var/log/pve";
33 my $pvetaskdir = "$pvelogdir/tasks";
38 sub run_with_timeout
{
39 my ($timeout, $code, @param) = @_;
41 die "got timeout\n" if $timeout <= 0;
49 local $SIG{ALRM
} = sub { $sigcount++; }; # catch alarm outside eval
52 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
53 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
54 local $SIG{__DIE__
}; # see SA bug 4631
56 $prev_alarm = alarm($timeout);
58 $res = &$code(@param);
60 alarm(0); # avoid race conditions
65 alarm($prev_alarm) if defined($prev_alarm);
67 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
74 # flock: we use one file handle per process, so lock file
75 # can be called multiple times and succeeds for the same process.
77 my $lock_handles = {};
80 my ($filename, $timeout, $code, @param) = @_;
82 $timeout = 10 if !$timeout;
85 if (!$lock_handles->{$$}->{$filename}) {
86 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
87 die "can't open file - $!\n";
90 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
|LOCK_NB
)) {
91 print STDERR
"trying to aquire lock...";
92 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
)) {
93 print STDERR
" failed\n";
94 die "can't aquire lock - $!\n";
102 eval { run_with_timeout
($timeout, $lock_func); };
105 $err = "can't lock file '$filename' - $err";
107 eval { $res = &$code(@param) };
111 if ($lock_handles->{$$}->{$filename}) {
112 my $fh = $lock_handles->{$$}->{$filename};
113 $lock_handles->{$$}->{$filename} = undef;
127 sub file_set_contents
{
128 my ($filename, $data, $perm) = @_;
130 $perm = 0644 if !defined($perm);
132 my $tmpname = "$filename.tmp.$$";
135 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
136 die "unable to open file '$tmpname' - $!\n" if !$fh;
137 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
138 die "closing file '$tmpname' failed - $!\n" unless close $fh;
147 if (!rename($tmpname, $filename)) {
148 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
154 sub file_get_contents
{
155 my ($filename, $max) = @_;
157 my $fh = IO
::File-
>new($filename, "r") ||
158 die "can't open '$filename' - $!\n";
160 my $content = safe_read_from
($fh, $max);
167 sub file_read_firstline
{
170 my $fh = IO
::File-
>new ($filename, "r");
171 return undef if !$fh;
179 my ($fh, $max, $oneline) = @_;
181 $max = 32768 if !$max;
186 while ($count = sysread($fh, $input, 8192, $br)) {
188 die "input too long - aborting\n" if $br > $max;
189 if ($oneline && $input =~ m/^(.*)\n/) {
194 die "unable to read input - $!\n" if !defined($count);
200 my ($cmd, %param) = @_;
204 $cmd = [ $cmd ] if !ref($cmd);
206 my $cmdstr = cmd2string
($cmd);
222 foreach my $p (keys %param) {
223 if ($p eq 'timeout') {
224 $timeout = $param{$p};
225 } elsif ($p eq 'umask') {
227 } elsif ($p eq 'errmsg') {
228 $errmsg = $param{$p};
229 } elsif ($p eq 'input') {
231 } elsif ($p eq 'output') {
232 $output = $param{$p};
233 } elsif ($p eq 'outfunc') {
234 $outfunc = $param{$p};
235 } elsif ($p eq 'errfunc') {
236 $errfunc = $param{$p};
237 } elsif ($p eq 'logfunc') {
238 $logfunc = $param{$p};
240 die "got unknown parameter '$p' for run_command\n";
245 my $origerrfunc = $errfunc;
249 &$origerrfunc("$laststderr\n");
251 print STDERR
"$laststderr\n" if $laststderr;
258 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
259 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
260 my $error = IO
::File-
>new();
262 # try to avoid locale related issues/warnings
263 my $lang = $param{lang
} || 'C';
268 local $ENV{LC_ALL
} = $lang;
270 # suppress LVM warnings like: "File descriptor 3 left open";
271 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
273 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
275 # if we pipe fron STDIN, open3 closes STDIN, so we we
276 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
277 # as soon as we open a new file.
278 # to avoid that we open /dev/null
279 if (!ref($writer) && !defined(fileno(STDIN
))) {
281 open(STDIN
, "</dev/null");
288 if ($orig_pid != $$) {
296 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
297 $oldtimeout = alarm($timeout) if $timeout;
300 print $writer $input if defined $input;
304 my $select = new IO
::Select
;
305 $select->add($reader) if ref($reader);
306 $select->add($error);
311 my $starttime = time();
313 while ($select->count) {
314 my @handles = $select->can_read(1);
316 foreach my $h (@handles) {
318 my $count = sysread ($h, $buf, 4096);
319 if (!defined ($count)) {
325 $select->remove ($h) if !$count;
327 if ($outfunc || $logfunc) {
330 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
332 &$outfunc($line) if $outfunc;
333 &$logfunc($line) if $logfunc;
346 } elsif ($h eq $error) {
347 if ($errfunc || $logfunc) {
350 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
352 &$errfunc($line) if $errfunc;
353 &$logfunc($line) if $logfunc;
370 &$outfunc($outlog) if $outfunc && $outlog;
371 &$logfunc($outlog) if $logfunc && $outlog;
373 &$errfunc($errlog) if $errfunc && $errlog;
374 &$logfunc($errlog) if $logfunc && $errlog;
379 die "failed to execute\n";
380 } elsif (my $sig = ($? & 127)) {
381 die "got signal $sig\n";
382 } elsif (my $ec = ($? >> 8)) {
383 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
384 if ($errmsg && $laststderr) {
385 my $lerr = $laststderr;
389 die "exit code $ec\n";
400 if ($errmsg && $laststderr) {
401 &$errfunc(undef); # flush laststderr
404 umask ($old_umask) if defined($old_umask);
406 alarm($oldtimeout) if $oldtimeout;
409 if ($pid && ($err eq "got timeout\n")) {
412 die "command '$cmdstr' failed: $err";
418 die "command '$cmdstr' failed: $err";
426 my $listtxt = shift || '';
428 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
430 $listtxt =~ s/[,;]/ /g;
431 $listtxt =~ s/^\s+//;
433 my @data = split (/\s+/, $listtxt);
441 return $txt if !defined($txt);
449 # simple uri templates like "/vms/{vmid}"
450 sub template_replace
{
451 my ($tmpl, $data) = @_;
454 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
456 $res .= ($data->{$3} || '-') if $2;
462 my ($filename, $fh, $data) = @_;
466 my $res = print $fh $data;
468 die "write to '$filename' failed\n" if !$res;
474 'at' => 'ftp.at.debian.org',
475 'au' => 'ftp.au.debian.org',
476 'be' => 'ftp.be.debian.org',
477 'bg' => 'ftp.bg.debian.org',
478 'br' => 'ftp.br.debian.org',
479 'ca' => 'ftp.ca.debian.org',
480 'ch' => 'ftp.ch.debian.org',
481 'cl' => 'ftp.cl.debian.org',
482 'cz' => 'ftp.cz.debian.org',
483 'de' => 'ftp.de.debian.org',
484 'dk' => 'ftp.dk.debian.org',
485 'ee' => 'ftp.ee.debian.org',
486 'es' => 'ftp.es.debian.org',
487 'fi' => 'ftp.fi.debian.org',
488 'fr' => 'ftp.fr.debian.org',
489 'gr' => 'ftp.gr.debian.org',
490 'hk' => 'ftp.hk.debian.org',
491 'hr' => 'ftp.hr.debian.org',
492 'hu' => 'ftp.hu.debian.org',
493 'ie' => 'ftp.ie.debian.org',
494 'is' => 'ftp.is.debian.org',
495 'it' => 'ftp.it.debian.org',
496 'jp' => 'ftp.jp.debian.org',
497 'kr' => 'ftp.kr.debian.org',
498 'mx' => 'ftp.mx.debian.org',
499 'nl' => 'ftp.nl.debian.org',
500 'no' => 'ftp.no.debian.org',
501 'nz' => 'ftp.nz.debian.org',
502 'pl' => 'ftp.pl.debian.org',
503 'pt' => 'ftp.pt.debian.org',
504 'ro' => 'ftp.ro.debian.org',
505 'ru' => 'ftp.ru.debian.org',
506 'se' => 'ftp.se.debian.org',
507 'si' => 'ftp.si.debian.org',
508 'sk' => 'ftp.sk.debian.org',
509 'tr' => 'ftp.tr.debian.org',
510 'tw' => 'ftp.tw.debian.org',
511 'gb' => 'ftp.uk.debian.org',
512 'us' => 'ftp.us.debian.org',
517 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
518 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
519 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
520 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
521 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
522 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
523 #'et' => [], # Ethopia or Estonia ??
524 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
525 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
526 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
527 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
528 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
529 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
530 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
531 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
532 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
533 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
534 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
535 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
536 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
537 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
538 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
539 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
540 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
541 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
542 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
543 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
544 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
545 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
546 #'sv' => [], Swedish ?
551 my $kvmkeymaparray = [];
552 foreach my $lc (keys %$keymaphash) {
553 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
561 return $kvmkeymaparray;
565 my ($param, $key) = @_;
567 my $res = $param->{$key};
568 delete $param->{$key};
575 for (my $p = 5900; $p < 6000; $p++) {
577 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
578 LocalAddr
=> 'localhost',
589 die "unable to find free vnc port";
592 # NOTE: NFS syscall can't be interrupted, so alarm does
593 # not work to provide timeouts.
594 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
595 # So the spawn external 'df' process instead of using
596 # Filesys::Df (which uses statfs syscall)
598 my ($path, $timeout) = @_;
600 my $cmd = [ 'df', '-P', '-B', '1', $path];
610 if (my ($fsid, $total, $used, $avail) = $line =~
611 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
619 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
626 # We use this to uniquely identify a process.
627 # An 'Unique Process ID' has the following format:
628 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
633 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
634 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
639 my ($upid, $noerr) = @_;
644 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
645 if ($upid =~ m/^UPID:([A-Za-z][[:alnum:]\-]*[[:alnum:]]+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/) {
647 $res->{pid
} = hex($2);
648 $res->{pstart
} = hex($3);
649 $res->{starttime
} = hex($4);
654 my $subdir = substr($4, 7, 8);
655 $filename = "$pvetaskdir/$subdir/$upid";
658 return undef if $noerr;
659 die "unable to parse worker upid '$upid'\n";
662 return wantarray ?
($res, $filename) : $res;
668 my ($task, $filename) = upid_decode
($upid);
670 my $dirname = dirname
($filename);
673 my $wwwid = getpwnam('www-data') ||
674 die "getpwnam failed";
678 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
679 die "unable to create output file '$filename' - $!\n";
680 chown $wwwid, -1, $outfh;
685 sub upid_read_status
{
688 my ($task, $filename) = upid_decode
($upid);
689 my $fh = IO
::File-
>new($filename, "r");
690 return "unable to open file - $!" if !$fh;
692 sysseek($fh, -$maxlen, 2);
694 my $br = sysread($fh, $readbuf, $maxlen);
697 return "unable to extract last line"
698 if $readbuf !~ m/\n?(.+)$/;
700 if ($line =~ m/^TASK OK$/) {
702 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
705 return "unexpected status";
708 return "unable to read tail (got $br bytes)";
711 # useful functions to store comments in config files
715 # all control and hi-bit characters, and ':'
716 my $unsafe = "^\x20-\x39\x3b-\x7e";
717 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
723 return Encode
::decode
("utf8", uri_unescape
($data));
726 sub random_ether_addr
{
728 my $rand = Digest
::SHA1
::sha1_hex
(rand(), time());
731 for (my $i = 0; $i < 6; $i++) {
732 my $ss = hex(substr($rand, $i*2, 2));
734 $ss &= 0xfe; # clear multicast
735 $ss |= 2; # set local id
737 $ss = sprintf("%02X", $ss);
752 return String
::ShellQuote
::shell_quote
($str);
758 die "no arguments" if !$cmd;
760 return $cmd if !ref($cmd);
763 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
765 return join (' ', @qa);
768 # split an shell argument string into an array,
772 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
776 my ($filename, $start, $limit) = @_;
781 my $fh = IO
::File-
>new($filename, "r");
784 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
785 return ($count, $lines);
788 $start = 0 if !$start;
789 $limit = 50 if !$limit;
792 while (defined($line = <$fh>)) {
793 next if $count++ < $start;
796 push @$lines, { n
=> $count, t
=> $line};
802 # HACK: ExtJS store.guaranteeRange() does not like empty array
806 push @$lines, { n
=> $count, t
=> "no content"};
809 return ($count, $lines);