]>
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";
420 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
423 die "command '$cmdstr' failed: $err";
431 my $listtxt = shift || '';
433 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
435 $listtxt =~ s/[,;]/ /g;
436 $listtxt =~ s/^\s+//;
438 my @data = split (/\s+/, $listtxt);
446 return $txt if !defined($txt);
454 # simple uri templates like "/vms/{vmid}"
455 sub template_replace
{
456 my ($tmpl, $data) = @_;
458 return $tmpl if !$tmpl;
461 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
463 $res .= ($data->{$3} || '-') if $2;
469 my ($filename, $fh, $data) = @_;
473 my $res = print $fh $data;
475 die "write to '$filename' failed\n" if !$res;
481 'at' => 'ftp.at.debian.org',
482 'au' => 'ftp.au.debian.org',
483 'be' => 'ftp.be.debian.org',
484 'bg' => 'ftp.bg.debian.org',
485 'br' => 'ftp.br.debian.org',
486 'ca' => 'ftp.ca.debian.org',
487 'ch' => 'ftp.ch.debian.org',
488 'cl' => 'ftp.cl.debian.org',
489 'cz' => 'ftp.cz.debian.org',
490 'de' => 'ftp.de.debian.org',
491 'dk' => 'ftp.dk.debian.org',
492 'ee' => 'ftp.ee.debian.org',
493 'es' => 'ftp.es.debian.org',
494 'fi' => 'ftp.fi.debian.org',
495 'fr' => 'ftp.fr.debian.org',
496 'gr' => 'ftp.gr.debian.org',
497 'hk' => 'ftp.hk.debian.org',
498 'hr' => 'ftp.hr.debian.org',
499 'hu' => 'ftp.hu.debian.org',
500 'ie' => 'ftp.ie.debian.org',
501 'is' => 'ftp.is.debian.org',
502 'it' => 'ftp.it.debian.org',
503 'jp' => 'ftp.jp.debian.org',
504 'kr' => 'ftp.kr.debian.org',
505 'mx' => 'ftp.mx.debian.org',
506 'nl' => 'ftp.nl.debian.org',
507 'no' => 'ftp.no.debian.org',
508 'nz' => 'ftp.nz.debian.org',
509 'pl' => 'ftp.pl.debian.org',
510 'pt' => 'ftp.pt.debian.org',
511 'ro' => 'ftp.ro.debian.org',
512 'ru' => 'ftp.ru.debian.org',
513 'se' => 'ftp.se.debian.org',
514 'si' => 'ftp.si.debian.org',
515 'sk' => 'ftp.sk.debian.org',
516 'tr' => 'ftp.tr.debian.org',
517 'tw' => 'ftp.tw.debian.org',
518 'gb' => 'ftp.uk.debian.org',
519 'us' => 'ftp.us.debian.org',
524 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
525 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
526 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
527 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
528 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
529 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
530 #'et' => [], # Ethopia or Estonia ??
531 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
532 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
533 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
534 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
535 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
536 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
537 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
538 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
539 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
540 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
541 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
542 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
543 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
544 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
545 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
546 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
547 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
548 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
549 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
550 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
551 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
552 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
553 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
558 my $kvmkeymaparray = [];
559 foreach my $lc (keys %$keymaphash) {
560 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
568 return $kvmkeymaparray;
572 my ($param, $key) = @_;
574 my $res = $param->{$key};
575 delete $param->{$key};
582 for (my $p = 5900; $p < 6000; $p++) {
584 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
585 LocalAddr
=> 'localhost',
596 die "unable to find free vnc port";
599 # NOTE: NFS syscall can't be interrupted, so alarm does
600 # not work to provide timeouts.
601 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
602 # So the spawn external 'df' process instead of using
603 # Filesys::Df (which uses statfs syscall)
605 my ($path, $timeout) = @_;
607 my $cmd = [ 'df', '-P', '-B', '1', $path];
617 if (my ($fsid, $total, $used, $avail) = $line =~
618 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
626 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
633 # We use this to uniquely identify a process.
634 # An 'Unique Process ID' has the following format:
635 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
640 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
641 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
646 my ($upid, $noerr) = @_;
651 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
652 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]+):$/) {
654 $res->{pid
} = hex($2);
655 $res->{pstart
} = hex($3);
656 $res->{starttime
} = hex($4);
661 my $subdir = substr($4, 7, 8);
662 $filename = "$pvetaskdir/$subdir/$upid";
665 return undef if $noerr;
666 die "unable to parse worker upid '$upid'\n";
669 return wantarray ?
($res, $filename) : $res;
675 my ($task, $filename) = upid_decode
($upid);
677 my $dirname = dirname
($filename);
680 my $wwwid = getpwnam('www-data') ||
681 die "getpwnam failed";
685 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
686 die "unable to create output file '$filename' - $!\n";
687 chown $wwwid, -1, $outfh;
692 sub upid_read_status
{
695 my ($task, $filename) = upid_decode
($upid);
696 my $fh = IO
::File-
>new($filename, "r");
697 return "unable to open file - $!" if !$fh;
699 sysseek($fh, -$maxlen, 2);
701 my $br = sysread($fh, $readbuf, $maxlen);
704 return "unable to extract last line"
705 if $readbuf !~ m/\n?(.+)$/;
707 if ($line =~ m/^TASK OK$/) {
709 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
712 return "unexpected status";
715 return "unable to read tail (got $br bytes)";
718 # useful functions to store comments in config files
722 # all control and hi-bit characters, and ':'
723 my $unsafe = "^\x20-\x39\x3b-\x7e";
724 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
730 return Encode
::decode
("utf8", uri_unescape
($data));
733 sub decode_utf8_parameters
{
736 foreach my $p (qw(comment description firstname lastname)) {
737 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
743 sub random_ether_addr
{
745 my $rand = Digest
::SHA1
::sha1_hex
(rand(), time());
748 for (my $i = 0; $i < 6; $i++) {
749 my $ss = hex(substr($rand, $i*2, 2));
751 $ss &= 0xfe; # clear multicast
752 $ss |= 2; # set local id
754 $ss = sprintf("%02X", $ss);
769 return String
::ShellQuote
::shell_quote
($str);
775 die "no arguments" if !$cmd;
777 return $cmd if !ref($cmd);
780 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
782 return join (' ', @qa);
785 # split an shell argument string into an array,
789 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
793 my ($filename, $start, $limit) = @_;
798 my $fh = IO
::File-
>new($filename, "r");
801 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
802 return ($count, $lines);
805 $start = 0 if !$start;
806 $limit = 50 if !$limit;
809 while (defined($line = <$fh>)) {
810 next if $count++ < $start;
813 push @$lines, { n
=> $count, t
=> $line};
819 # HACK: ExtJS store.guaranteeRange() does not like empty array
823 push @$lines, { n
=> $count, t
=> "no content"};
826 return ($count, $lines);