]>
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);
29 my $pvelogdir = "/var/log/pve";
30 my $pvetaskdir = "$pvelogdir/tasks";
35 # flock: we use one file handle per process, so lock file
36 # can be called multiple times and succeeds for the same process.
38 my $lock_handles = {};
41 my ($filename, $timeout, $code, @param) = @_;
45 $timeout = 10 if !$timeout;
49 local $SIG{ALRM
} = sub { die "got timeout (can't lock '$filename')\n"; };
53 if (!$lock_handles->{$$}->{$filename}) {
54 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
55 die "can't open lock file '$filename' - $!\n";
58 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
|LOCK_NB
)) {
59 print STDERR
"trying to aquire lock...";
60 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
)) {
61 print STDERR
" failed\n";
62 die "can't aquire lock for '$filename' - $!\n";
68 $res = &$code(@param);
75 if ($lock_handles->{$$}->{$filename}) {
76 my $fh = $lock_handles->{$$}->{$filename};
77 $lock_handles->{$$}->{$filename} = undef;
91 sub file_set_contents
{
92 my ($filename, $data, $perm) = @_;
94 $perm = 0644 if !defined($perm);
96 my $tmpname = "$filename.tmp.$$";
99 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
100 die "unable to open file '$tmpname' - $!\n" if !$fh;
101 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
102 die "closing file '$tmpname' failed - $!\n" unless close $fh;
111 if (!rename($tmpname, $filename)) {
112 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
118 sub file_get_contents
{
119 my ($filename, $max) = @_;
121 my $fh = IO
::File-
>new($filename, "r") ||
122 die "can't open '$filename' - $!\n";
124 my $content = safe_read_from
($fh, $max);
131 sub file_read_firstline
{
134 my $fh = IO
::File-
>new ($filename, "r");
135 return undef if !$fh;
143 my ($fh, $max, $oneline) = @_;
145 $max = 32768 if !$max;
150 while ($count = sysread($fh, $input, 8192, $br)) {
152 die "input too long - aborting\n" if $br > $max;
153 if ($oneline && $input =~ m/^(.*)\n/) {
158 die "unable to read input - $!\n" if !defined($count);
164 my ($cmd, %param) = @_;
168 $cmd = [ $cmd ] if !ref($cmd);
170 my $cmdstr = join (' ', @$cmd);
179 my $reader = IO
::File-
>new();
180 my $writer = IO
::File-
>new();
181 my $error = IO
::File-
>new();
187 foreach my $p (keys %param) {
188 if ($p eq 'timeout') {
189 $timeout = $param{$p};
190 } elsif ($p eq 'umask') {
192 } elsif ($p eq 'errmsg') {
193 $errmsg = $param{$p};
195 print STDERR
"$laststderr\n" if $laststderr;
198 } elsif ($p eq 'input') {
200 } elsif ($p eq 'outfunc') {
201 $outfunc = $param{$p};
202 } elsif ($p eq 'errfunc') {
203 $errfunc = $param{$p};
205 die "got unknown parameter '$p' for run_command\n";
209 # try to avoid locale related issues/warnings
210 my $lang = $param{lang
} || 'C';
215 local $ENV{LANG
} = $lang;
217 # suppress LVM warnings like: "File descriptor 3 left open";
218 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
220 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
226 if ($orig_pid != $$) {
234 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
235 $oldtimeout = alarm($timeout) if $timeout;
237 print $writer $input if defined $input;
240 my $select = new IO
::Select
;
241 $select->add($reader);
242 $select->add($error);
247 my $starttime = time();
249 while ($select->count) {
250 my @handles = $select->can_read(1);
252 foreach my $h (@handles) {
254 my $count = sysread ($h, $buf, 4096);
255 if (!defined ($count)) {
261 $select->remove ($h) if !$count;
266 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
281 } elsif ($h eq $error) {
285 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
304 &$outfunc($outlog) if $outfunc && $outlog;
305 &$errfunc($errlog) if $errfunc && $errlog;
310 die "failed to execute\n";
311 } elsif (my $sig = ($? & 127)) {
312 die "got signal $sig\n";
313 } elsif (my $ec = ($? >> 8)) {
314 if ($errmsg && $laststderr) {
315 my $lerr = $laststderr;
319 die "exit code $ec\n";
329 print STDERR
"$laststderr\n" if $laststderr;
331 umask ($old_umask) if defined($old_umask);
333 alarm($oldtimeout) if $oldtimeout;
336 if ($pid && ($err eq "got timeout\n")) {
339 die "command '$cmdstr' failed: $err";
345 die "command '$cmdstr' failed: $err";
351 my $listtxt = shift || '';
353 $listtxt =~ s/[,;\0]/ /g;
354 $listtxt =~ s/^\s+//;
356 my @data = split (/\s+/, $listtxt);
364 return $txt if !defined($txt);
372 # simple uri templates like "/vms/{vmid}"
373 sub template_replace
{
374 my ($tmpl, $data) = @_;
377 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
379 $res .= ($data->{$3} || '-') if $2;
385 my ($filename, $fh, $data) = @_;
389 my $res = print $fh $data;
391 die "write to '$filename' failed\n" if !$res;
397 'at' => 'ftp.at.debian.org',
398 'au' => 'ftp.au.debian.org',
399 'be' => 'ftp.be.debian.org',
400 'bg' => 'ftp.bg.debian.org',
401 'br' => 'ftp.br.debian.org',
402 'ca' => 'ftp.ca.debian.org',
403 'ch' => 'ftp.ch.debian.org',
404 'cl' => 'ftp.cl.debian.org',
405 'cz' => 'ftp.cz.debian.org',
406 'de' => 'ftp.de.debian.org',
407 'dk' => 'ftp.dk.debian.org',
408 'ee' => 'ftp.ee.debian.org',
409 'es' => 'ftp.es.debian.org',
410 'fi' => 'ftp.fi.debian.org',
411 'fr' => 'ftp.fr.debian.org',
412 'gr' => 'ftp.gr.debian.org',
413 'hk' => 'ftp.hk.debian.org',
414 'hr' => 'ftp.hr.debian.org',
415 'hu' => 'ftp.hu.debian.org',
416 'ie' => 'ftp.ie.debian.org',
417 'is' => 'ftp.is.debian.org',
418 'it' => 'ftp.it.debian.org',
419 'jp' => 'ftp.jp.debian.org',
420 'kr' => 'ftp.kr.debian.org',
421 'mx' => 'ftp.mx.debian.org',
422 'nl' => 'ftp.nl.debian.org',
423 'no' => 'ftp.no.debian.org',
424 'nz' => 'ftp.nz.debian.org',
425 'pl' => 'ftp.pl.debian.org',
426 'pt' => 'ftp.pt.debian.org',
427 'ro' => 'ftp.ro.debian.org',
428 'ru' => 'ftp.ru.debian.org',
429 'se' => 'ftp.se.debian.org',
430 'si' => 'ftp.si.debian.org',
431 'sk' => 'ftp.sk.debian.org',
432 'tr' => 'ftp.tr.debian.org',
433 'tw' => 'ftp.tw.debian.org',
434 'gb' => 'ftp.uk.debian.org',
435 'us' => 'ftp.us.debian.org',
441 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
442 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
443 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
444 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
445 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
446 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
447 #'et' => [], # Ethopia or Estonia ??
448 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
449 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
450 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
451 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
452 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
453 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
454 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
455 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
456 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
457 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
458 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
459 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
460 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
461 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
462 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
463 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
464 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
465 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
466 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
467 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
468 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
469 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
470 #'sv' => [], Swedish ?
477 my ($param, $key) = @_;
479 my $res = $param->{$key};
480 delete $param->{$key};
487 for (my $p = 5900; $p < 6000; $p++) {
489 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
490 LocalAddr
=> 'localhost',
501 die "unable to find free vnc port";
504 # NOTE: NFS syscall can't be interrupted, so alarm does
505 # not work to provide timeouts.
506 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
507 # So the spawn external 'df' process instead of using
508 # Filesys::Df (which uses statfs syscall)
510 my ($path, $timeout) = @_;
512 my $cmd = [ 'df', '-P', '-B', '1', $path];
522 if (my ($fsid, $total, $used, $avail) = $line =~
523 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
531 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
538 # We use this to uniquely identify a process.
539 # An 'Unique Process ID' has the following format:
540 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
545 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
546 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
551 my ($upid, $noerr) = @_;
556 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
557 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]+):$/) {
559 $res->{pid
} = hex($2);
560 $res->{pstart
} = hex($3);
561 $res->{starttime
} = hex($4);
566 my $subdir = substr($4, 7, 8);
567 $filename = "$pvetaskdir/$subdir/$upid";
570 return undef if $noerr;
571 die "unable to parse worker upid '$upid'\n";
574 return wantarray ?
($res, $filename) : $res;
580 my ($task, $filename) = upid_decode
($upid);
582 my $dirname = dirname
($filename);
585 my $wwwid = getpwnam('www-data') ||
586 die "getpwnam failed";
590 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
591 die "unable to create output file '$filename' - $!\n";
592 chown $wwwid, $outfh;
597 sub upid_read_status
{
600 my ($task, $filename) = upid_decode
($upid);
601 my $fh = IO
::File-
>new($filename, "r");
602 return "unable to open file - $!" if !$fh;
604 sysseek($fh, -$maxlen, 2);
606 my $br = sysread($fh, $readbuf, $maxlen);
609 return "unable to extract last line"
610 if $readbuf !~ m/\n?(.+)$/;
612 if ($line =~ m/^TASK OK$/) {
614 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
617 return "unexpected status";
620 return "unable to read tail (got $br bytes)";
623 # useful functions to store comments in config files
627 # all control and hi-bit characters, and ':'
628 my $unsafe = "^\x20-\x39\x3b-\x7e";
629 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
635 return Encode
::decode
("utf8", uri_unescape
($data));