8 use File
::Path
qw(make_path);
11 use Fcntl
qw(:DEFAULT :flock);
31 my $pvelogdir = "/var/log/pve";
32 my $pvetaskdir = "$pvelogdir/tasks";
37 # flock: we use one file handle per process, so lock file
38 # can be called multiple times and succeeds for the same process.
40 my $lock_handles = {};
43 my ($filename, $timeout, $code, @param) = @_;
47 $timeout = 10 if !$timeout;
51 local $SIG{ALRM
} = sub { die "got timeout (can't lock '$filename')\n"; };
55 if (!$lock_handles->{$$}->{$filename}) {
56 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
57 die "can't open lock file '$filename' - $!\n";
60 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
|LOCK_NB
)) {
61 print STDERR
"trying to aquire lock...";
62 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
)) {
63 print STDERR
" failed\n";
64 die "can't aquire lock for '$filename' - $!\n";
70 $res = &$code(@param);
77 if ($lock_handles->{$$}->{$filename}) {
78 my $fh = $lock_handles->{$$}->{$filename};
79 $lock_handles->{$$}->{$filename} = undef;
93 sub file_set_contents
{
94 my ($filename, $data, $perm) = @_;
96 $perm = 0644 if !defined($perm);
98 my $tmpname = "$filename.tmp.$$";
101 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
102 die "unable to open file '$tmpname' - $!\n" if !$fh;
103 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
104 die "closing file '$tmpname' failed - $!\n" unless close $fh;
113 if (!rename($tmpname, $filename)) {
114 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
120 sub file_get_contents
{
121 my ($filename, $max) = @_;
123 my $fh = IO
::File-
>new($filename, "r") ||
124 die "can't open '$filename' - $!\n";
126 my $content = safe_read_from
($fh, $max);
133 sub file_read_firstline
{
136 my $fh = IO
::File-
>new ($filename, "r");
137 return undef if !$fh;
145 my ($fh, $max, $oneline) = @_;
147 $max = 32768 if !$max;
152 while ($count = sysread($fh, $input, 8192, $br)) {
154 die "input too long - aborting\n" if $br > $max;
155 if ($oneline && $input =~ m/^(.*)\n/) {
160 die "unable to read input - $!\n" if !defined($count);
166 my ($cmd, %param) = @_;
170 $cmd = [ $cmd ] if !ref($cmd);
172 my $cmdstr = join (' ', @$cmd);
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 'output') {
201 $output = $param{$p};
202 } elsif ($p eq 'outfunc') {
203 $outfunc = $param{$p};
204 } elsif ($p eq 'errfunc') {
205 $errfunc = $param{$p};
206 } elsif ($p eq 'logfunc') {
207 $logfunc = $param{$p};
209 die "got unknown parameter '$p' for run_command\n";
213 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
214 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
215 my $error = IO
::File-
>new();
217 # try to avoid locale related issues/warnings
218 my $lang = $param{lang
} || 'C';
223 local $ENV{LC_ALL
} = $lang;
225 # suppress LVM warnings like: "File descriptor 3 left open";
226 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
228 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
230 # if we pipe fron STDIN, open3 closes STDIN, so we we
231 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
232 # as soon as we open a new file.
233 # to avoid that we open /dev/null
234 if (!ref($writer) && !defined(fileno(STDIN
))) {
236 open(STDIN
, "</dev/null");
243 if ($orig_pid != $$) {
251 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
252 $oldtimeout = alarm($timeout) if $timeout;
255 print $writer $input if defined $input;
259 my $select = new IO
::Select
;
260 $select->add($reader) if ref($reader);
261 $select->add($error);
266 my $starttime = time();
268 while ($select->count) {
269 my @handles = $select->can_read(1);
271 foreach my $h (@handles) {
273 my $count = sysread ($h, $buf, 4096);
274 if (!defined ($count)) {
280 $select->remove ($h) if !$count;
282 if ($outfunc || $logfunc) {
285 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
287 &$outfunc($line) if $outfunc;
288 &$logfunc($line) if $logfunc;
301 } elsif ($h eq $error) {
302 if ($errfunc || $logfunc) {
305 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
307 &$errfunc($line) if $errfunc;
308 &$logfunc($line) if $logfunc;
325 &$outfunc($outlog) if $outfunc && $outlog;
326 &$logfunc($outlog) if $logfunc && $outlog;
328 &$errfunc($errlog) if $errfunc && $errlog;
329 &$logfunc($errlog) if $logfunc && $errlog;
334 die "failed to execute\n";
335 } elsif (my $sig = ($? & 127)) {
336 die "got signal $sig\n";
337 } elsif (my $ec = ($? >> 8)) {
338 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
339 if ($errmsg && $laststderr) {
340 my $lerr = $laststderr;
344 die "exit code $ec\n";
355 print STDERR
"$laststderr\n" if $laststderr;
357 umask ($old_umask) if defined($old_umask);
359 alarm($oldtimeout) if $oldtimeout;
362 if ($pid && ($err eq "got timeout\n")) {
365 die "command '$cmdstr' failed: $err";
371 die "command '$cmdstr' failed: $err";
379 my $listtxt = shift || '';
381 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
383 $listtxt =~ s/[,;]/ /g;
384 $listtxt =~ s/^\s+//;
386 my @data = split (/\s+/, $listtxt);
394 return $txt if !defined($txt);
402 # simple uri templates like "/vms/{vmid}"
403 sub template_replace
{
404 my ($tmpl, $data) = @_;
407 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
409 $res .= ($data->{$3} || '-') if $2;
415 my ($filename, $fh, $data) = @_;
419 my $res = print $fh $data;
421 die "write to '$filename' failed\n" if !$res;
427 'at' => 'ftp.at.debian.org',
428 'au' => 'ftp.au.debian.org',
429 'be' => 'ftp.be.debian.org',
430 'bg' => 'ftp.bg.debian.org',
431 'br' => 'ftp.br.debian.org',
432 'ca' => 'ftp.ca.debian.org',
433 'ch' => 'ftp.ch.debian.org',
434 'cl' => 'ftp.cl.debian.org',
435 'cz' => 'ftp.cz.debian.org',
436 'de' => 'ftp.de.debian.org',
437 'dk' => 'ftp.dk.debian.org',
438 'ee' => 'ftp.ee.debian.org',
439 'es' => 'ftp.es.debian.org',
440 'fi' => 'ftp.fi.debian.org',
441 'fr' => 'ftp.fr.debian.org',
442 'gr' => 'ftp.gr.debian.org',
443 'hk' => 'ftp.hk.debian.org',
444 'hr' => 'ftp.hr.debian.org',
445 'hu' => 'ftp.hu.debian.org',
446 'ie' => 'ftp.ie.debian.org',
447 'is' => 'ftp.is.debian.org',
448 'it' => 'ftp.it.debian.org',
449 'jp' => 'ftp.jp.debian.org',
450 'kr' => 'ftp.kr.debian.org',
451 'mx' => 'ftp.mx.debian.org',
452 'nl' => 'ftp.nl.debian.org',
453 'no' => 'ftp.no.debian.org',
454 'nz' => 'ftp.nz.debian.org',
455 'pl' => 'ftp.pl.debian.org',
456 'pt' => 'ftp.pt.debian.org',
457 'ro' => 'ftp.ro.debian.org',
458 'ru' => 'ftp.ru.debian.org',
459 'se' => 'ftp.se.debian.org',
460 'si' => 'ftp.si.debian.org',
461 'sk' => 'ftp.sk.debian.org',
462 'tr' => 'ftp.tr.debian.org',
463 'tw' => 'ftp.tw.debian.org',
464 'gb' => 'ftp.uk.debian.org',
465 'us' => 'ftp.us.debian.org',
471 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
472 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
473 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
474 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
475 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
476 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
477 #'et' => [], # Ethopia or Estonia ??
478 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
479 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
480 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
481 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
482 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
483 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
484 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
485 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
486 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
487 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
488 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
489 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
490 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
491 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
492 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
493 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
494 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
495 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
496 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
497 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
498 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
499 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
500 #'sv' => [], Swedish ?
507 my ($param, $key) = @_;
509 my $res = $param->{$key};
510 delete $param->{$key};
517 for (my $p = 5900; $p < 6000; $p++) {
519 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
520 LocalAddr
=> 'localhost',
531 die "unable to find free vnc port";
534 # NOTE: NFS syscall can't be interrupted, so alarm does
535 # not work to provide timeouts.
536 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
537 # So the spawn external 'df' process instead of using
538 # Filesys::Df (which uses statfs syscall)
540 my ($path, $timeout) = @_;
542 my $cmd = [ 'df', '-P', '-B', '1', $path];
552 if (my ($fsid, $total, $used, $avail) = $line =~
553 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
561 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
568 # We use this to uniquely identify a process.
569 # An 'Unique Process ID' has the following format:
570 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
575 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
576 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
581 my ($upid, $noerr) = @_;
586 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
587 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]+):$/) {
589 $res->{pid
} = hex($2);
590 $res->{pstart
} = hex($3);
591 $res->{starttime
} = hex($4);
596 my $subdir = substr($4, 7, 8);
597 $filename = "$pvetaskdir/$subdir/$upid";
600 return undef if $noerr;
601 die "unable to parse worker upid '$upid'\n";
604 return wantarray ?
($res, $filename) : $res;
610 my ($task, $filename) = upid_decode
($upid);
612 my $dirname = dirname
($filename);
615 my $wwwid = getpwnam('www-data') ||
616 die "getpwnam failed";
620 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
621 die "unable to create output file '$filename' - $!\n";
622 chown $wwwid, $outfh;
627 sub upid_read_status
{
630 my ($task, $filename) = upid_decode
($upid);
631 my $fh = IO
::File-
>new($filename, "r");
632 return "unable to open file - $!" if !$fh;
634 sysseek($fh, -$maxlen, 2);
636 my $br = sysread($fh, $readbuf, $maxlen);
639 return "unable to extract last line"
640 if $readbuf !~ m/\n?(.+)$/;
642 if ($line =~ m/^TASK OK$/) {
644 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
647 return "unexpected status";
650 return "unable to read tail (got $br bytes)";
653 # useful functions to store comments in config files
657 # all control and hi-bit characters, and ':'
658 my $unsafe = "^\x20-\x39\x3b-\x7e";
659 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
665 return Encode
::decode
("utf8", uri_unescape
($data));
668 sub random_ether_addr
{
670 my $rand = Digest
::SHA1
::sha1_hex
(rand(), time());
673 for (my $i = 0; $i < 6; $i++) {
674 my $ss = hex(substr($rand, $i*2, 2));
676 $ss &= 0xfe; # clear multicast
677 $ss |= 2; # set local id
679 $ss = sprintf("%02X", $ss);
694 return "''" if !defined ($str) || ($str eq '');
696 die "unable to quote string containing null (\\000) bytes"
699 # from String::ShellQuote
700 if ($str =~ m
|[^\w
!%+,\-./:@^]|) {
713 # split an shell argument string into an array,
717 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];