]>
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
;
35 my $pvelogdir = "/var/log/pve";
36 my $pvetaskdir = "$pvelogdir/tasks";
41 sub run_with_timeout
{
42 my ($timeout, $code, @param) = @_;
44 die "got timeout\n" if $timeout <= 0;
52 local $SIG{ALRM
} = sub { $sigcount++; }; # catch alarm outside eval
55 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
56 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
57 local $SIG{__DIE__
}; # see SA bug 4631
59 $prev_alarm = alarm($timeout);
61 $res = &$code(@param);
63 alarm(0); # avoid race conditions
68 alarm($prev_alarm) if defined($prev_alarm);
70 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
77 # flock: we use one file handle per process, so lock file
78 # can be called multiple times and succeeds for the same process.
80 my $lock_handles = {};
83 my ($filename, $timeout, $code, @param) = @_;
85 $timeout = 10 if !$timeout;
88 if (!$lock_handles->{$$}->{$filename}) {
89 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
90 die "can't open file - $!\n";
93 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
|LOCK_NB
)) {
94 print STDERR
"trying to aquire lock...";
95 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
)) {
96 print STDERR
" failed\n";
97 die "can't aquire lock - $!\n";
105 eval { run_with_timeout
($timeout, $lock_func); };
108 $err = "can't lock file '$filename' - $err";
110 eval { $res = &$code(@param) };
114 if ($lock_handles->{$$}->{$filename}) {
115 my $fh = $lock_handles->{$$}->{$filename};
116 $lock_handles->{$$}->{$filename} = undef;
130 sub file_set_contents
{
131 my ($filename, $data, $perm) = @_;
133 $perm = 0644 if !defined($perm);
135 my $tmpname = "$filename.tmp.$$";
138 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
139 die "unable to open file '$tmpname' - $!\n" if !$fh;
140 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
141 die "closing file '$tmpname' failed - $!\n" unless close $fh;
150 if (!rename($tmpname, $filename)) {
151 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
157 sub file_get_contents
{
158 my ($filename, $max) = @_;
160 my $fh = IO
::File-
>new($filename, "r") ||
161 die "can't open '$filename' - $!\n";
163 my $content = safe_read_from
($fh, $max);
170 sub file_read_firstline
{
173 my $fh = IO
::File-
>new ($filename, "r");
174 return undef if !$fh;
182 my ($fh, $max, $oneline) = @_;
184 $max = 32768 if !$max;
189 while ($count = sysread($fh, $input, 8192, $br)) {
191 die "input too long - aborting\n" if $br > $max;
192 if ($oneline && $input =~ m/^(.*)\n/) {
197 die "unable to read input - $!\n" if !defined($count);
203 my ($cmd, %param) = @_;
212 $cmdstr = cmd2string
($cmd);
229 foreach my $p (keys %param) {
230 if ($p eq 'timeout') {
231 $timeout = $param{$p};
232 } elsif ($p eq 'umask') {
234 } elsif ($p eq 'errmsg') {
235 $errmsg = $param{$p};
236 } elsif ($p eq 'input') {
238 } elsif ($p eq 'output') {
239 $output = $param{$p};
240 } elsif ($p eq 'outfunc') {
241 $outfunc = $param{$p};
242 } elsif ($p eq 'errfunc') {
243 $errfunc = $param{$p};
244 } elsif ($p eq 'logfunc') {
245 $logfunc = $param{$p};
247 die "got unknown parameter '$p' for run_command\n";
252 my $origerrfunc = $errfunc;
256 &$origerrfunc("$laststderr\n");
258 print STDERR
"$laststderr\n" if $laststderr;
265 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
266 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
267 my $error = IO
::File-
>new();
269 # try to avoid locale related issues/warnings
270 my $lang = $param{lang
} || 'C';
275 local $ENV{LC_ALL
} = $lang;
277 # suppress LVM warnings like: "File descriptor 3 left open";
278 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
280 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
282 # if we pipe fron STDIN, open3 closes STDIN, so we we
283 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
284 # as soon as we open a new file.
285 # to avoid that we open /dev/null
286 if (!ref($writer) && !defined(fileno(STDIN
))) {
288 open(STDIN
, "</dev/null");
295 if ($orig_pid != $$) {
303 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
304 $oldtimeout = alarm($timeout) if $timeout;
307 print $writer $input if defined $input;
311 my $select = new IO
::Select
;
312 $select->add($reader) if ref($reader);
313 $select->add($error);
318 my $starttime = time();
320 while ($select->count) {
321 my @handles = $select->can_read(1);
323 foreach my $h (@handles) {
325 my $count = sysread ($h, $buf, 4096);
326 if (!defined ($count)) {
332 $select->remove ($h) if !$count;
334 if ($outfunc || $logfunc) {
337 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
339 &$outfunc($line) if $outfunc;
340 &$logfunc($line) if $logfunc;
353 } elsif ($h eq $error) {
354 if ($errfunc || $logfunc) {
357 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
359 &$errfunc($line) if $errfunc;
360 &$logfunc($line) if $logfunc;
377 &$outfunc($outlog) if $outfunc && $outlog;
378 &$logfunc($outlog) if $logfunc && $outlog;
380 &$errfunc($errlog) if $errfunc && $errlog;
381 &$logfunc($errlog) if $logfunc && $errlog;
386 die "failed to execute\n";
387 } elsif (my $sig = ($? & 127)) {
388 die "got signal $sig\n";
389 } elsif (my $ec = ($? >> 8)) {
390 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
391 if ($errmsg && $laststderr) {
392 my $lerr = $laststderr;
396 die "exit code $ec\n";
407 if ($errmsg && $laststderr) {
408 &$errfunc(undef); # flush laststderr
411 umask ($old_umask) if defined($old_umask);
413 alarm($oldtimeout) if $oldtimeout;
416 if ($pid && ($err eq "got timeout\n")) {
419 die "command '$cmdstr' failed: $err";
423 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
426 die "command '$cmdstr' failed: $err";
434 my $listtxt = shift || '';
436 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
438 $listtxt =~ s/[,;]/ /g;
439 $listtxt =~ s/^\s+//;
441 my @data = split (/\s+/, $listtxt);
449 return $txt if !defined($txt);
457 # simple uri templates like "/vms/{vmid}"
458 sub template_replace
{
459 my ($tmpl, $data) = @_;
461 return $tmpl if !$tmpl;
464 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
466 $res .= ($data->{$3} || '-') if $2;
472 my ($filename, $fh, $data) = @_;
476 my $res = print $fh $data;
478 die "write to '$filename' failed\n" if !$res;
484 'at' => 'ftp.at.debian.org',
485 'au' => 'ftp.au.debian.org',
486 'be' => 'ftp.be.debian.org',
487 'bg' => 'ftp.bg.debian.org',
488 'br' => 'ftp.br.debian.org',
489 'ca' => 'ftp.ca.debian.org',
490 'ch' => 'ftp.ch.debian.org',
491 'cl' => 'ftp.cl.debian.org',
492 'cz' => 'ftp.cz.debian.org',
493 'de' => 'ftp.de.debian.org',
494 'dk' => 'ftp.dk.debian.org',
495 'ee' => 'ftp.ee.debian.org',
496 'es' => 'ftp.es.debian.org',
497 'fi' => 'ftp.fi.debian.org',
498 'fr' => 'ftp.fr.debian.org',
499 'gr' => 'ftp.gr.debian.org',
500 'hk' => 'ftp.hk.debian.org',
501 'hr' => 'ftp.hr.debian.org',
502 'hu' => 'ftp.hu.debian.org',
503 'ie' => 'ftp.ie.debian.org',
504 'is' => 'ftp.is.debian.org',
505 'it' => 'ftp.it.debian.org',
506 'jp' => 'ftp.jp.debian.org',
507 'kr' => 'ftp.kr.debian.org',
508 'mx' => 'ftp.mx.debian.org',
509 'nl' => 'ftp.nl.debian.org',
510 'no' => 'ftp.no.debian.org',
511 'nz' => 'ftp.nz.debian.org',
512 'pl' => 'ftp.pl.debian.org',
513 'pt' => 'ftp.pt.debian.org',
514 'ro' => 'ftp.ro.debian.org',
515 'ru' => 'ftp.ru.debian.org',
516 'se' => 'ftp.se.debian.org',
517 'si' => 'ftp.si.debian.org',
518 'sk' => 'ftp.sk.debian.org',
519 'tr' => 'ftp.tr.debian.org',
520 'tw' => 'ftp.tw.debian.org',
521 'gb' => 'ftp.uk.debian.org',
522 'us' => 'ftp.us.debian.org',
527 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
528 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
529 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
530 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
531 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
532 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
533 #'et' => [], # Ethopia or Estonia ??
534 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
535 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
536 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
537 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
538 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
539 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
540 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
541 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
542 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
543 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
544 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
545 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
546 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
547 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
548 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
549 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
550 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
551 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
552 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
553 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
554 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
555 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
556 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
558 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
561 my $kvmkeymaparray = [];
562 foreach my $lc (keys %$keymaphash) {
563 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
571 return $kvmkeymaparray;
575 my ($param, $key) = @_;
577 my $res = $param->{$key};
578 delete $param->{$key};
585 for (my $p = 5900; $p < 6000; $p++) {
587 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
588 LocalAddr
=> 'localhost',
599 die "unable to find free vnc port";
602 # NOTE: NFS syscall can't be interrupted, so alarm does
603 # not work to provide timeouts.
604 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
605 # So the spawn external 'df' process instead of using
606 # Filesys::Df (which uses statfs syscall)
608 my ($path, $timeout) = @_;
610 my $cmd = [ 'df', '-P', '-B', '1', $path];
620 if (my ($fsid, $total, $used, $avail) = $line =~
621 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
629 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
636 # We use this to uniquely identify a process.
637 # An 'Unique Process ID' has the following format:
638 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
643 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
644 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
649 my ($upid, $noerr) = @_;
654 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
655 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]+):$/) {
657 $res->{pid
} = hex($2);
658 $res->{pstart
} = hex($3);
659 $res->{starttime
} = hex($4);
664 my $subdir = substr($4, 7, 8);
665 $filename = "$pvetaskdir/$subdir/$upid";
668 return undef if $noerr;
669 die "unable to parse worker upid '$upid'\n";
672 return wantarray ?
($res, $filename) : $res;
678 my ($task, $filename) = upid_decode
($upid);
680 my $dirname = dirname
($filename);
683 my $wwwid = getpwnam('www-data') ||
684 die "getpwnam failed";
688 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
689 die "unable to create output file '$filename' - $!\n";
690 chown $wwwid, -1, $outfh;
695 sub upid_read_status
{
698 my ($task, $filename) = upid_decode
($upid);
699 my $fh = IO
::File-
>new($filename, "r");
700 return "unable to open file - $!" if !$fh;
702 sysseek($fh, -$maxlen, 2);
704 my $br = sysread($fh, $readbuf, $maxlen);
707 return "unable to extract last line"
708 if $readbuf !~ m/\n?(.+)$/;
710 if ($line =~ m/^TASK OK$/) {
712 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
715 return "unexpected status";
718 return "unable to read tail (got $br bytes)";
721 # useful functions to store comments in config files
725 # all control and hi-bit characters, and ':'
726 my $unsafe = "^\x20-\x39\x3b-\x7e";
727 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
733 return Encode
::decode
("utf8", uri_unescape
($data));
736 sub decode_utf8_parameters
{
739 foreach my $p (qw(comment description firstname lastname)) {
740 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
746 sub random_ether_addr
{
748 my $rand = Digest
::SHA
::sha1_hex
(rand(), time());
751 for (my $i = 0; $i < 6; $i++) {
752 my $ss = hex(substr($rand, $i*2, 2));
754 $ss &= 0xfe; # clear multicast
755 $ss |= 2; # set local id
757 $ss = sprintf("%02X", $ss);
772 return String
::ShellQuote
::shell_quote
($str);
778 die "no arguments" if !$cmd;
780 return $cmd if !ref($cmd);
783 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
785 return join (' ', @qa);
788 # split an shell argument string into an array,
792 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
796 my ($filename, $start, $limit) = @_;
801 my $fh = IO
::File-
>new($filename, "r");
804 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
805 return ($count, $lines);
808 $start = 0 if !$start;
809 $limit = 50 if !$limit;
812 while (defined($line = <$fh>)) {
813 next if $count++ < $start;
816 push @$lines, { n
=> $count, t
=> $line};
822 # HACK: ExtJS store.guaranteeRange() does not like empty array
826 push @$lines, { n
=> $count, t
=> "no content"};
829 return ($count, $lines);
833 my ($dir, $regex) = @_;
835 my $dh = IO
::Dir-
>new ($dir);
836 return wantarray ?
() : undef if !$dh;
838 while (defined(my $tmp = $dh->read)) {
839 if (my @res = $tmp =~ m/^($regex)$/) {
841 return wantarray ?
@res : $tmp;
846 return wantarray ?
() : undef;
849 sub dir_glob_foreach
{
850 my ($dir, $regex, $func) = @_;
852 my $dh = IO
::Dir-
>new ($dir);
854 while (defined(my $tmp = $dh->read)) {
855 if (my @res = $tmp =~ m/^($regex)$/) {