]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
985b31ef4ec4a1523cda4e669846a719068cb0f1
8 use File
::Path
qw(make_path);
11 use Fcntl
qw(:DEFAULT :flock);
30 my $pvelogdir = "/var/log/pve";
31 my $pvetaskdir = "$pvelogdir/tasks";
36 # flock: we use one file handle per process, so lock file
37 # can be called multiple times and succeeds for the same process.
39 my $lock_handles = {};
42 my ($filename, $timeout, $code, @param) = @_;
46 $timeout = 10 if !$timeout;
50 local $SIG{ALRM
} = sub { die "got timeout (can't lock '$filename')\n"; };
54 if (!$lock_handles->{$$}->{$filename}) {
55 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
56 die "can't open lock file '$filename' - $!\n";
59 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
|LOCK_NB
)) {
60 print STDERR
"trying to aquire lock...";
61 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
)) {
62 print STDERR
" failed\n";
63 die "can't aquire lock for '$filename' - $!\n";
69 $res = &$code(@param);
76 if ($lock_handles->{$$}->{$filename}) {
77 my $fh = $lock_handles->{$$}->{$filename};
78 $lock_handles->{$$}->{$filename} = undef;
92 sub file_set_contents
{
93 my ($filename, $data, $perm) = @_;
95 $perm = 0644 if !defined($perm);
97 my $tmpname = "$filename.tmp.$$";
100 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
101 die "unable to open file '$tmpname' - $!\n" if !$fh;
102 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
103 die "closing file '$tmpname' failed - $!\n" unless close $fh;
112 if (!rename($tmpname, $filename)) {
113 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
119 sub file_get_contents
{
120 my ($filename, $max) = @_;
122 my $fh = IO
::File-
>new($filename, "r") ||
123 die "can't open '$filename' - $!\n";
125 my $content = safe_read_from
($fh, $max);
132 sub file_read_firstline
{
135 my $fh = IO
::File-
>new ($filename, "r");
136 return undef if !$fh;
144 my ($fh, $max, $oneline) = @_;
146 $max = 32768 if !$max;
151 while ($count = sysread($fh, $input, 8192, $br)) {
153 die "input too long - aborting\n" if $br > $max;
154 if ($oneline && $input =~ m/^(.*)\n/) {
159 die "unable to read input - $!\n" if !defined($count);
165 my ($cmd, %param) = @_;
169 $cmd = [ $cmd ] if !ref($cmd);
171 my $cmdstr = join (' ', @$cmd);
180 my $reader = IO
::File-
>new();
181 my $writer = IO
::File-
>new();
182 my $error = IO
::File-
>new();
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 'outfunc') {
202 $outfunc = $param{$p};
203 } elsif ($p eq 'errfunc') {
204 $errfunc = $param{$p};
206 die "got unknown parameter '$p' for run_command\n";
210 # try to avoid locale related issues/warnings
211 my $lang = $param{lang
} || 'C';
216 local $ENV{LC_ALL
} = $lang;
218 # suppress LVM warnings like: "File descriptor 3 left open";
219 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
221 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
227 if ($orig_pid != $$) {
235 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
236 $oldtimeout = alarm($timeout) if $timeout;
238 print $writer $input if defined $input;
241 my $select = new IO
::Select
;
242 $select->add($reader);
243 $select->add($error);
248 my $starttime = time();
250 while ($select->count) {
251 my @handles = $select->can_read(1);
253 foreach my $h (@handles) {
255 my $count = sysread ($h, $buf, 4096);
256 if (!defined ($count)) {
262 $select->remove ($h) if !$count;
267 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
282 } elsif ($h eq $error) {
286 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
305 &$outfunc($outlog) if $outfunc && $outlog;
306 &$errfunc($errlog) if $errfunc && $errlog;
311 die "failed to execute\n";
312 } elsif (my $sig = ($? & 127)) {
313 die "got signal $sig\n";
314 } elsif (my $ec = ($? >> 8)) {
315 if ($errmsg && $laststderr) {
316 my $lerr = $laststderr;
320 die "exit code $ec\n";
330 print STDERR
"$laststderr\n" if $laststderr;
332 umask ($old_umask) if defined($old_umask);
334 alarm($oldtimeout) if $oldtimeout;
337 if ($pid && ($err eq "got timeout\n")) {
340 die "command '$cmdstr' failed: $err";
346 die "command '$cmdstr' failed: $err";
352 my $listtxt = shift || '';
354 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
356 $listtxt =~ s/[,;]/ /g;
357 $listtxt =~ s/^\s+//;
359 my @data = split (/\s+/, $listtxt);
367 return $txt if !defined($txt);
375 # simple uri templates like "/vms/{vmid}"
376 sub template_replace
{
377 my ($tmpl, $data) = @_;
380 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
382 $res .= ($data->{$3} || '-') if $2;
388 my ($filename, $fh, $data) = @_;
392 my $res = print $fh $data;
394 die "write to '$filename' failed\n" if !$res;
400 'at' => 'ftp.at.debian.org',
401 'au' => 'ftp.au.debian.org',
402 'be' => 'ftp.be.debian.org',
403 'bg' => 'ftp.bg.debian.org',
404 'br' => 'ftp.br.debian.org',
405 'ca' => 'ftp.ca.debian.org',
406 'ch' => 'ftp.ch.debian.org',
407 'cl' => 'ftp.cl.debian.org',
408 'cz' => 'ftp.cz.debian.org',
409 'de' => 'ftp.de.debian.org',
410 'dk' => 'ftp.dk.debian.org',
411 'ee' => 'ftp.ee.debian.org',
412 'es' => 'ftp.es.debian.org',
413 'fi' => 'ftp.fi.debian.org',
414 'fr' => 'ftp.fr.debian.org',
415 'gr' => 'ftp.gr.debian.org',
416 'hk' => 'ftp.hk.debian.org',
417 'hr' => 'ftp.hr.debian.org',
418 'hu' => 'ftp.hu.debian.org',
419 'ie' => 'ftp.ie.debian.org',
420 'is' => 'ftp.is.debian.org',
421 'it' => 'ftp.it.debian.org',
422 'jp' => 'ftp.jp.debian.org',
423 'kr' => 'ftp.kr.debian.org',
424 'mx' => 'ftp.mx.debian.org',
425 'nl' => 'ftp.nl.debian.org',
426 'no' => 'ftp.no.debian.org',
427 'nz' => 'ftp.nz.debian.org',
428 'pl' => 'ftp.pl.debian.org',
429 'pt' => 'ftp.pt.debian.org',
430 'ro' => 'ftp.ro.debian.org',
431 'ru' => 'ftp.ru.debian.org',
432 'se' => 'ftp.se.debian.org',
433 'si' => 'ftp.si.debian.org',
434 'sk' => 'ftp.sk.debian.org',
435 'tr' => 'ftp.tr.debian.org',
436 'tw' => 'ftp.tw.debian.org',
437 'gb' => 'ftp.uk.debian.org',
438 'us' => 'ftp.us.debian.org',
444 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
445 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
446 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
447 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
448 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
449 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
450 #'et' => [], # Ethopia or Estonia ??
451 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
452 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
453 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
454 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
455 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
456 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
457 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
458 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
459 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
460 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
461 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
462 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
463 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
464 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
465 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
466 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
467 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
468 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
469 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
470 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
471 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
472 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
473 #'sv' => [], Swedish ?
480 my ($param, $key) = @_;
482 my $res = $param->{$key};
483 delete $param->{$key};
490 for (my $p = 5900; $p < 6000; $p++) {
492 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
493 LocalAddr
=> 'localhost',
504 die "unable to find free vnc port";
507 # NOTE: NFS syscall can't be interrupted, so alarm does
508 # not work to provide timeouts.
509 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
510 # So the spawn external 'df' process instead of using
511 # Filesys::Df (which uses statfs syscall)
513 my ($path, $timeout) = @_;
515 my $cmd = [ 'df', '-P', '-B', '1', $path];
525 if (my ($fsid, $total, $used, $avail) = $line =~
526 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
534 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
541 # We use this to uniquely identify a process.
542 # An 'Unique Process ID' has the following format:
543 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
548 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
549 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
554 my ($upid, $noerr) = @_;
559 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
560 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]+):$/) {
562 $res->{pid
} = hex($2);
563 $res->{pstart
} = hex($3);
564 $res->{starttime
} = hex($4);
569 my $subdir = substr($4, 7, 8);
570 $filename = "$pvetaskdir/$subdir/$upid";
573 return undef if $noerr;
574 die "unable to parse worker upid '$upid'\n";
577 return wantarray ?
($res, $filename) : $res;
583 my ($task, $filename) = upid_decode
($upid);
585 my $dirname = dirname
($filename);
588 my $wwwid = getpwnam('www-data') ||
589 die "getpwnam failed";
593 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
594 die "unable to create output file '$filename' - $!\n";
595 chown $wwwid, $outfh;
600 sub upid_read_status
{
603 my ($task, $filename) = upid_decode
($upid);
604 my $fh = IO
::File-
>new($filename, "r");
605 return "unable to open file - $!" if !$fh;
607 sysseek($fh, -$maxlen, 2);
609 my $br = sysread($fh, $readbuf, $maxlen);
612 return "unable to extract last line"
613 if $readbuf !~ m/\n?(.+)$/;
615 if ($line =~ m/^TASK OK$/) {
617 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
620 return "unexpected status";
623 return "unable to read tail (got $br bytes)";
626 # useful functions to store comments in config files
630 # all control and hi-bit characters, and ':'
631 my $unsafe = "^\x20-\x39\x3b-\x7e";
632 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
638 return Encode
::decode
("utf8", uri_unescape
($data));
641 sub random_ether_addr
{
643 my $rand = Digest
::SHA1
::sha1_hex
(rand(), time());
646 for (my $i = 0; $i < 6; $i++) {
647 my $ss = hex(substr($rand, $i*2, 2));
649 $ss &= 0xfe; # clear multicast
650 $ss |= 2; # set local id
652 $ss = sprintf("%02X", $ss);