]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
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) = @_;
209 $cmdstr = cmd2string
($cmd);
226 foreach my $p (keys %param) {
227 if ($p eq 'timeout') {
228 $timeout = $param{$p};
229 } elsif ($p eq 'umask') {
231 } elsif ($p eq 'errmsg') {
232 $errmsg = $param{$p};
233 } elsif ($p eq 'input') {
235 } elsif ($p eq 'output') {
236 $output = $param{$p};
237 } elsif ($p eq 'outfunc') {
238 $outfunc = $param{$p};
239 } elsif ($p eq 'errfunc') {
240 $errfunc = $param{$p};
241 } elsif ($p eq 'logfunc') {
242 $logfunc = $param{$p};
244 die "got unknown parameter '$p' for run_command\n";
249 my $origerrfunc = $errfunc;
253 &$origerrfunc("$laststderr\n");
255 print STDERR
"$laststderr\n" if $laststderr;
262 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
263 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
264 my $error = IO
::File-
>new();
266 # try to avoid locale related issues/warnings
267 my $lang = $param{lang
} || 'C';
272 local $ENV{LC_ALL
} = $lang;
274 # suppress LVM warnings like: "File descriptor 3 left open";
275 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
277 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
279 # if we pipe fron STDIN, open3 closes STDIN, so we we
280 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
281 # as soon as we open a new file.
282 # to avoid that we open /dev/null
283 if (!ref($writer) && !defined(fileno(STDIN
))) {
285 open(STDIN
, "</dev/null");
292 if ($orig_pid != $$) {
300 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
301 $oldtimeout = alarm($timeout) if $timeout;
304 print $writer $input if defined $input;
308 my $select = new IO
::Select
;
309 $select->add($reader) if ref($reader);
310 $select->add($error);
315 my $starttime = time();
317 while ($select->count) {
318 my @handles = $select->can_read(1);
320 foreach my $h (@handles) {
322 my $count = sysread ($h, $buf, 4096);
323 if (!defined ($count)) {
329 $select->remove ($h) if !$count;
331 if ($outfunc || $logfunc) {
334 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
336 &$outfunc($line) if $outfunc;
337 &$logfunc($line) if $logfunc;
350 } elsif ($h eq $error) {
351 if ($errfunc || $logfunc) {
354 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
356 &$errfunc($line) if $errfunc;
357 &$logfunc($line) if $logfunc;
374 &$outfunc($outlog) if $outfunc && $outlog;
375 &$logfunc($outlog) if $logfunc && $outlog;
377 &$errfunc($errlog) if $errfunc && $errlog;
378 &$logfunc($errlog) if $logfunc && $errlog;
383 die "failed to execute\n";
384 } elsif (my $sig = ($? & 127)) {
385 die "got signal $sig\n";
386 } elsif (my $ec = ($? >> 8)) {
387 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
388 if ($errmsg && $laststderr) {
389 my $lerr = $laststderr;
393 die "exit code $ec\n";
404 if ($errmsg && $laststderr) {
405 &$errfunc(undef); # flush laststderr
408 umask ($old_umask) if defined($old_umask);
410 alarm($oldtimeout) if $oldtimeout;
413 if ($pid && ($err eq "got timeout\n")) {
416 die "command '$cmdstr' failed: $err";
422 die "command '$cmdstr' failed: $err";
430 my $listtxt = shift || '';
432 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
434 $listtxt =~ s/[,;]/ /g;
435 $listtxt =~ s/^\s+//;
437 my @data = split (/\s+/, $listtxt);
445 return $txt if !defined($txt);
453 # simple uri templates like "/vms/{vmid}"
454 sub template_replace
{
455 my ($tmpl, $data) = @_;
458 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
460 $res .= ($data->{$3} || '-') if $2;
466 my ($filename, $fh, $data) = @_;
470 my $res = print $fh $data;
472 die "write to '$filename' failed\n" if !$res;
478 'at' => 'ftp.at.debian.org',
479 'au' => 'ftp.au.debian.org',
480 'be' => 'ftp.be.debian.org',
481 'bg' => 'ftp.bg.debian.org',
482 'br' => 'ftp.br.debian.org',
483 'ca' => 'ftp.ca.debian.org',
484 'ch' => 'ftp.ch.debian.org',
485 'cl' => 'ftp.cl.debian.org',
486 'cz' => 'ftp.cz.debian.org',
487 'de' => 'ftp.de.debian.org',
488 'dk' => 'ftp.dk.debian.org',
489 'ee' => 'ftp.ee.debian.org',
490 'es' => 'ftp.es.debian.org',
491 'fi' => 'ftp.fi.debian.org',
492 'fr' => 'ftp.fr.debian.org',
493 'gr' => 'ftp.gr.debian.org',
494 'hk' => 'ftp.hk.debian.org',
495 'hr' => 'ftp.hr.debian.org',
496 'hu' => 'ftp.hu.debian.org',
497 'ie' => 'ftp.ie.debian.org',
498 'is' => 'ftp.is.debian.org',
499 'it' => 'ftp.it.debian.org',
500 'jp' => 'ftp.jp.debian.org',
501 'kr' => 'ftp.kr.debian.org',
502 'mx' => 'ftp.mx.debian.org',
503 'nl' => 'ftp.nl.debian.org',
504 'no' => 'ftp.no.debian.org',
505 'nz' => 'ftp.nz.debian.org',
506 'pl' => 'ftp.pl.debian.org',
507 'pt' => 'ftp.pt.debian.org',
508 'ro' => 'ftp.ro.debian.org',
509 'ru' => 'ftp.ru.debian.org',
510 'se' => 'ftp.se.debian.org',
511 'si' => 'ftp.si.debian.org',
512 'sk' => 'ftp.sk.debian.org',
513 'tr' => 'ftp.tr.debian.org',
514 'tw' => 'ftp.tw.debian.org',
515 'gb' => 'ftp.uk.debian.org',
516 'us' => 'ftp.us.debian.org',
521 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
522 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
523 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
524 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
525 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
526 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
527 #'et' => [], # Ethopia or Estonia ??
528 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
529 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
530 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
531 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
532 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
533 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
534 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
535 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
536 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
537 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
538 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
539 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
540 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
541 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
542 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
543 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
544 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
545 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
546 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
547 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
548 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
549 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
550 #'sv' => [], Swedish ?
555 my $kvmkeymaparray = [];
556 foreach my $lc (keys %$keymaphash) {
557 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
565 return $kvmkeymaparray;
569 my ($param, $key) = @_;
571 my $res = $param->{$key};
572 delete $param->{$key};
579 for (my $p = 5900; $p < 6000; $p++) {
581 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
582 LocalAddr
=> 'localhost',
593 die "unable to find free vnc port";
596 # NOTE: NFS syscall can't be interrupted, so alarm does
597 # not work to provide timeouts.
598 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
599 # So the spawn external 'df' process instead of using
600 # Filesys::Df (which uses statfs syscall)
602 my ($path, $timeout) = @_;
604 my $cmd = [ 'df', '-P', '-B', '1', $path];
614 if (my ($fsid, $total, $used, $avail) = $line =~
615 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
623 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
630 # We use this to uniquely identify a process.
631 # An 'Unique Process ID' has the following format:
632 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
637 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
638 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
643 my ($upid, $noerr) = @_;
648 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
649 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]+):$/) {
651 $res->{pid
} = hex($2);
652 $res->{pstart
} = hex($3);
653 $res->{starttime
} = hex($4);
658 my $subdir = substr($4, 7, 8);
659 $filename = "$pvetaskdir/$subdir/$upid";
662 return undef if $noerr;
663 die "unable to parse worker upid '$upid'\n";
666 return wantarray ?
($res, $filename) : $res;
672 my ($task, $filename) = upid_decode
($upid);
674 my $dirname = dirname
($filename);
677 my $wwwid = getpwnam('www-data') ||
678 die "getpwnam failed";
682 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
683 die "unable to create output file '$filename' - $!\n";
684 chown $wwwid, -1, $outfh;
689 sub upid_read_status
{
692 my ($task, $filename) = upid_decode
($upid);
693 my $fh = IO
::File-
>new($filename, "r");
694 return "unable to open file - $!" if !$fh;
696 sysseek($fh, -$maxlen, 2);
698 my $br = sysread($fh, $readbuf, $maxlen);
701 return "unable to extract last line"
702 if $readbuf !~ m/\n?(.+)$/;
704 if ($line =~ m/^TASK OK$/) {
706 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
709 return "unexpected status";
712 return "unable to read tail (got $br bytes)";
715 # useful functions to store comments in config files
719 # all control and hi-bit characters, and ':'
720 my $unsafe = "^\x20-\x39\x3b-\x7e";
721 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
727 return Encode
::decode
("utf8", uri_unescape
($data));
730 sub decode_utf8_parameters
{
733 foreach my $p (qw(comment description firstname lastname)) {
734 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
740 sub random_ether_addr
{
742 my $rand = Digest
::SHA1
::sha1_hex
(rand(), time());
745 for (my $i = 0; $i < 6; $i++) {
746 my $ss = hex(substr($rand, $i*2, 2));
748 $ss &= 0xfe; # clear multicast
749 $ss |= 2; # set local id
751 $ss = sprintf("%02X", $ss);
766 return String
::ShellQuote
::shell_quote
($str);
772 die "no arguments" if !$cmd;
774 return $cmd if !ref($cmd);
777 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
779 return join (' ', @qa);
782 # split an shell argument string into an array,
786 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
790 my ($filename, $start, $limit) = @_;
795 my $fh = IO
::File-
>new($filename, "r");
798 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
799 return ($count, $lines);
802 $start = 0 if !$start;
803 $limit = 50 if !$limit;
806 while (defined($line = <$fh>)) {
807 next if $count++ < $start;
810 push @$lines, { n
=> $count, t
=> $line};
816 # HACK: ExtJS store.guaranteeRange() does not like empty array
820 push @$lines, { n
=> $count, t
=> "no content"};
823 return ($count, $lines);