]>
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 # flock: we use one file handle per process, so lock file
39 # can be called multiple times and succeeds for the same process.
41 my $lock_handles = {};
44 my ($filename, $timeout, $code, @param) = @_;
48 $timeout = 10 if !$timeout;
52 local $SIG{ALRM
} = sub { die "got timeout (can't lock '$filename')\n"; };
56 if (!$lock_handles->{$$}->{$filename}) {
57 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
58 die "can't open lock file '$filename' - $!\n";
61 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
|LOCK_NB
)) {
62 print STDERR
"trying to aquire lock...";
63 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
)) {
64 print STDERR
" failed\n";
65 die "can't aquire lock for '$filename' - $!\n";
71 $res = &$code(@param);
78 if ($lock_handles->{$$}->{$filename}) {
79 my $fh = $lock_handles->{$$}->{$filename};
80 $lock_handles->{$$}->{$filename} = undef;
94 sub file_set_contents
{
95 my ($filename, $data, $perm) = @_;
97 $perm = 0644 if !defined($perm);
99 my $tmpname = "$filename.tmp.$$";
102 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
103 die "unable to open file '$tmpname' - $!\n" if !$fh;
104 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
105 die "closing file '$tmpname' failed - $!\n" unless close $fh;
114 if (!rename($tmpname, $filename)) {
115 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
121 sub file_get_contents
{
122 my ($filename, $max) = @_;
124 my $fh = IO
::File-
>new($filename, "r") ||
125 die "can't open '$filename' - $!\n";
127 my $content = safe_read_from
($fh, $max);
134 sub file_read_firstline
{
137 my $fh = IO
::File-
>new ($filename, "r");
138 return undef if !$fh;
146 my ($fh, $max, $oneline) = @_;
148 $max = 32768 if !$max;
153 while ($count = sysread($fh, $input, 8192, $br)) {
155 die "input too long - aborting\n" if $br > $max;
156 if ($oneline && $input =~ m/^(.*)\n/) {
161 die "unable to read input - $!\n" if !defined($count);
167 my ($cmd, %param) = @_;
171 $cmd = [ $cmd ] if !ref($cmd);
173 my $cmdstr = cmd2string
($cmd);
188 foreach my $p (keys %param) {
189 if ($p eq 'timeout') {
190 $timeout = $param{$p};
191 } elsif ($p eq 'umask') {
193 } elsif ($p eq 'errmsg') {
194 $errmsg = $param{$p};
196 print STDERR
"$laststderr\n" if $laststderr;
199 } elsif ($p eq 'input') {
201 } elsif ($p eq 'output') {
202 $output = $param{$p};
203 } elsif ($p eq 'outfunc') {
204 $outfunc = $param{$p};
205 } elsif ($p eq 'errfunc') {
206 $errfunc = $param{$p};
207 } elsif ($p eq 'logfunc') {
208 $logfunc = $param{$p};
210 die "got unknown parameter '$p' for run_command\n";
214 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
215 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
216 my $error = IO
::File-
>new();
218 # try to avoid locale related issues/warnings
219 my $lang = $param{lang
} || 'C';
224 local $ENV{LC_ALL
} = $lang;
226 # suppress LVM warnings like: "File descriptor 3 left open";
227 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
229 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
231 # if we pipe fron STDIN, open3 closes STDIN, so we we
232 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
233 # as soon as we open a new file.
234 # to avoid that we open /dev/null
235 if (!ref($writer) && !defined(fileno(STDIN
))) {
237 open(STDIN
, "</dev/null");
244 if ($orig_pid != $$) {
252 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
253 $oldtimeout = alarm($timeout) if $timeout;
256 print $writer $input if defined $input;
260 my $select = new IO
::Select
;
261 $select->add($reader) if ref($reader);
262 $select->add($error);
267 my $starttime = time();
269 while ($select->count) {
270 my @handles = $select->can_read(1);
272 foreach my $h (@handles) {
274 my $count = sysread ($h, $buf, 4096);
275 if (!defined ($count)) {
281 $select->remove ($h) if !$count;
283 if ($outfunc || $logfunc) {
286 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
288 &$outfunc($line) if $outfunc;
289 &$logfunc($line) if $logfunc;
302 } elsif ($h eq $error) {
303 if ($errfunc || $logfunc) {
306 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
308 &$errfunc($line) if $errfunc;
309 &$logfunc($line) if $logfunc;
326 &$outfunc($outlog) if $outfunc && $outlog;
327 &$logfunc($outlog) if $logfunc && $outlog;
329 &$errfunc($errlog) if $errfunc && $errlog;
330 &$logfunc($errlog) if $logfunc && $errlog;
335 die "failed to execute\n";
336 } elsif (my $sig = ($? & 127)) {
337 die "got signal $sig\n";
338 } elsif (my $ec = ($? >> 8)) {
339 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
340 if ($errmsg && $laststderr) {
341 my $lerr = $laststderr;
345 die "exit code $ec\n";
356 print STDERR
"$laststderr\n" if $laststderr;
358 umask ($old_umask) if defined($old_umask);
360 alarm($oldtimeout) if $oldtimeout;
363 if ($pid && ($err eq "got timeout\n")) {
366 die "command '$cmdstr' failed: $err";
372 die "command '$cmdstr' failed: $err";
380 my $listtxt = shift || '';
382 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
384 $listtxt =~ s/[,;]/ /g;
385 $listtxt =~ s/^\s+//;
387 my @data = split (/\s+/, $listtxt);
395 return $txt if !defined($txt);
403 # simple uri templates like "/vms/{vmid}"
404 sub template_replace
{
405 my ($tmpl, $data) = @_;
408 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
410 $res .= ($data->{$3} || '-') if $2;
416 my ($filename, $fh, $data) = @_;
420 my $res = print $fh $data;
422 die "write to '$filename' failed\n" if !$res;
428 'at' => 'ftp.at.debian.org',
429 'au' => 'ftp.au.debian.org',
430 'be' => 'ftp.be.debian.org',
431 'bg' => 'ftp.bg.debian.org',
432 'br' => 'ftp.br.debian.org',
433 'ca' => 'ftp.ca.debian.org',
434 'ch' => 'ftp.ch.debian.org',
435 'cl' => 'ftp.cl.debian.org',
436 'cz' => 'ftp.cz.debian.org',
437 'de' => 'ftp.de.debian.org',
438 'dk' => 'ftp.dk.debian.org',
439 'ee' => 'ftp.ee.debian.org',
440 'es' => 'ftp.es.debian.org',
441 'fi' => 'ftp.fi.debian.org',
442 'fr' => 'ftp.fr.debian.org',
443 'gr' => 'ftp.gr.debian.org',
444 'hk' => 'ftp.hk.debian.org',
445 'hr' => 'ftp.hr.debian.org',
446 'hu' => 'ftp.hu.debian.org',
447 'ie' => 'ftp.ie.debian.org',
448 'is' => 'ftp.is.debian.org',
449 'it' => 'ftp.it.debian.org',
450 'jp' => 'ftp.jp.debian.org',
451 'kr' => 'ftp.kr.debian.org',
452 'mx' => 'ftp.mx.debian.org',
453 'nl' => 'ftp.nl.debian.org',
454 'no' => 'ftp.no.debian.org',
455 'nz' => 'ftp.nz.debian.org',
456 'pl' => 'ftp.pl.debian.org',
457 'pt' => 'ftp.pt.debian.org',
458 'ro' => 'ftp.ro.debian.org',
459 'ru' => 'ftp.ru.debian.org',
460 'se' => 'ftp.se.debian.org',
461 'si' => 'ftp.si.debian.org',
462 'sk' => 'ftp.sk.debian.org',
463 'tr' => 'ftp.tr.debian.org',
464 'tw' => 'ftp.tw.debian.org',
465 'gb' => 'ftp.uk.debian.org',
466 'us' => 'ftp.us.debian.org',
472 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
473 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
474 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
475 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
476 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
477 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
478 #'et' => [], # Ethopia or Estonia ??
479 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
480 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
481 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
482 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
483 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
484 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
485 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
486 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
487 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
488 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
489 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
490 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
491 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
492 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
493 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
494 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
495 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
496 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
497 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
498 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
499 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
500 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
501 #'sv' => [], Swedish ?
508 my ($param, $key) = @_;
510 my $res = $param->{$key};
511 delete $param->{$key};
518 for (my $p = 5900; $p < 6000; $p++) {
520 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
521 LocalAddr
=> 'localhost',
532 die "unable to find free vnc port";
535 # NOTE: NFS syscall can't be interrupted, so alarm does
536 # not work to provide timeouts.
537 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
538 # So the spawn external 'df' process instead of using
539 # Filesys::Df (which uses statfs syscall)
541 my ($path, $timeout) = @_;
543 my $cmd = [ 'df', '-P', '-B', '1', $path];
553 if (my ($fsid, $total, $used, $avail) = $line =~
554 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
562 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
569 # We use this to uniquely identify a process.
570 # An 'Unique Process ID' has the following format:
571 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
576 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
577 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
582 my ($upid, $noerr) = @_;
587 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
588 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]+):$/) {
590 $res->{pid
} = hex($2);
591 $res->{pstart
} = hex($3);
592 $res->{starttime
} = hex($4);
597 my $subdir = substr($4, 7, 8);
598 $filename = "$pvetaskdir/$subdir/$upid";
601 return undef if $noerr;
602 die "unable to parse worker upid '$upid'\n";
605 return wantarray ?
($res, $filename) : $res;
611 my ($task, $filename) = upid_decode
($upid);
613 my $dirname = dirname
($filename);
616 my $wwwid = getpwnam('www-data') ||
617 die "getpwnam failed";
621 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
622 die "unable to create output file '$filename' - $!\n";
623 chown $wwwid, -1, $outfh;
628 sub upid_read_status
{
631 my ($task, $filename) = upid_decode
($upid);
632 my $fh = IO
::File-
>new($filename, "r");
633 return "unable to open file - $!" if !$fh;
635 sysseek($fh, -$maxlen, 2);
637 my $br = sysread($fh, $readbuf, $maxlen);
640 return "unable to extract last line"
641 if $readbuf !~ m/\n?(.+)$/;
643 if ($line =~ m/^TASK OK$/) {
645 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
648 return "unexpected status";
651 return "unable to read tail (got $br bytes)";
654 # useful functions to store comments in config files
658 # all control and hi-bit characters, and ':'
659 my $unsafe = "^\x20-\x39\x3b-\x7e";
660 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
666 return Encode
::decode
("utf8", uri_unescape
($data));
669 sub random_ether_addr
{
671 my $rand = Digest
::SHA1
::sha1_hex
(rand(), time());
674 for (my $i = 0; $i < 6; $i++) {
675 my $ss = hex(substr($rand, $i*2, 2));
677 $ss &= 0xfe; # clear multicast
678 $ss |= 2; # set local id
680 $ss = sprintf("%02X", $ss);
695 return String
::ShellQuote
::shell_quote
($str);
701 die "no arguments" if !$cmd;
703 return $cmd if !ref($cmd);
706 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
708 return join (' ', @qa);
711 # split an shell argument string into an array,
715 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
719 my ($filename, $start, $limit) = @_;
724 my $fh = IO
::File-
>new($filename, "r");
727 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
728 return ($count, $lines);
731 $start = 0 if !$start;
732 $limit = 50 if !$limit;
735 while (defined($line = <$fh>)) {
736 next if $count++ < $start;
739 push @$lines, { n
=> $count, t
=> $line};
745 # HACK: ExtJS store.guaranteeRange() does not like empty array
749 push @$lines, { n
=> $count, t
=> "no content"};
752 return ($count, $lines);