9 use File
::Path
qw(make_path);
13 use Fcntl
qw(:DEFAULT :flock);
19 use String
::ShellQuote
;
37 my $pvelogdir = "/var/log/pve";
38 my $pvetaskdir = "$pvelogdir/tasks";
43 sub run_with_timeout
{
44 my ($timeout, $code, @param) = @_;
46 die "got timeout\n" if $timeout <= 0;
54 local $SIG{ALRM
} = sub { $sigcount++; }; # catch alarm outside eval
57 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
58 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
59 local $SIG{__DIE__
}; # see SA bug 4631
61 $prev_alarm = alarm($timeout);
63 $res = &$code(@param);
65 alarm(0); # avoid race conditions
70 alarm($prev_alarm) if defined($prev_alarm);
72 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
79 # flock: we use one file handle per process, so lock file
80 # can be called multiple times and succeeds for the same process.
82 my $lock_handles = {};
85 my ($filename, $timeout, $shared, $code, @param) = @_;
87 $timeout = 10 if !$timeout;
89 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
92 if (!$lock_handles->{$$}->{$filename}) {
93 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
94 die "can't open file - $!\n";
97 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
98 print STDERR
"trying to aquire lock...";
101 $success = flock($lock_handles->{$$}->{$filename}, $mode);
102 # try again on EINTR (see bug #273)
103 if ($success || ($! != EINTR
)) {
108 print STDERR
" failed\n";
109 die "can't aquire lock - $!\n";
111 print STDERR
" OK\n";
117 eval { run_with_timeout
($timeout, $lock_func); };
120 $err = "can't lock file '$filename' - $err";
122 eval { $res = &$code(@param) };
126 if ($lock_handles->{$$}->{$filename}) {
127 my $fh = $lock_handles->{$$}->{$filename};
128 $lock_handles->{$$}->{$filename} = undef;
144 my ($filename, $timeout, $code, @param) = @_;
146 return lock_file_full
($filename, $timeout, 0, $code, @param);
149 sub file_set_contents
{
150 my ($filename, $data, $perm) = @_;
152 $perm = 0644 if !defined($perm);
154 my $tmpname = "$filename.tmp.$$";
157 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
158 die "unable to open file '$tmpname' - $!\n" if !$fh;
159 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
160 die "closing file '$tmpname' failed - $!\n" unless close $fh;
169 if (!rename($tmpname, $filename)) {
170 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
176 sub file_get_contents
{
177 my ($filename, $max) = @_;
179 my $fh = IO
::File-
>new($filename, "r") ||
180 die "can't open '$filename' - $!\n";
182 my $content = safe_read_from
($fh, $max);
189 sub file_read_firstline
{
192 my $fh = IO
::File-
>new ($filename, "r");
193 return undef if !$fh;
201 my ($fh, $max, $oneline) = @_;
203 $max = 32768 if !$max;
208 while ($count = sysread($fh, $input, 8192, $br)) {
210 die "input too long - aborting\n" if $br > $max;
211 if ($oneline && $input =~ m/^(.*)\n/) {
216 die "unable to read input - $!\n" if !defined($count);
222 my ($cmd, %param) = @_;
230 # see 'man bash' for option pipefail
231 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
236 $cmdstr = cmd2string
($cmd);
254 foreach my $p (keys %param) {
255 if ($p eq 'timeout') {
256 $timeout = $param{$p};
257 } elsif ($p eq 'umask') {
258 $old_umask = umask($param{$p});
259 } elsif ($p eq 'errmsg') {
260 $errmsg = $param{$p};
261 } elsif ($p eq 'input') {
263 } elsif ($p eq 'output') {
264 $output = $param{$p};
265 } elsif ($p eq 'outfunc') {
266 $outfunc = $param{$p};
267 } elsif ($p eq 'errfunc') {
268 $errfunc = $param{$p};
269 } elsif ($p eq 'logfunc') {
270 $logfunc = $param{$p};
271 } elsif ($p eq 'afterfork') {
272 $afterfork = $param{$p};
274 die "got unknown parameter '$p' for run_command\n";
279 my $origerrfunc = $errfunc;
283 &$origerrfunc("$laststderr\n");
285 print STDERR
"$laststderr\n" if $laststderr;
292 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
293 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
294 my $error = IO
::File-
>new();
296 # try to avoid locale related issues/warnings
297 my $lang = $param{lang
} || 'C';
302 local $ENV{LC_ALL
} = $lang;
304 # suppress LVM warnings like: "File descriptor 3 left open";
305 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
307 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
309 # if we pipe fron STDIN, open3 closes STDIN, so we we
310 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
311 # as soon as we open a new file.
312 # to avoid that we open /dev/null
313 if (!ref($writer) && !defined(fileno(STDIN
))) {
315 open(STDIN
, "</dev/null");
322 if ($orig_pid != $$) {
330 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
331 $oldtimeout = alarm($timeout) if $timeout;
333 &$afterfork() if $afterfork;
336 print $writer $input if defined $input;
340 my $select = new IO
::Select
;
341 $select->add($reader) if ref($reader);
342 $select->add($error);
347 my $starttime = time();
349 while ($select->count) {
350 my @handles = $select->can_read(1);
352 foreach my $h (@handles) {
354 my $count = sysread ($h, $buf, 4096);
355 if (!defined ($count)) {
361 $select->remove ($h) if !$count;
363 if ($outfunc || $logfunc) {
366 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
368 &$outfunc($line) if $outfunc;
369 &$logfunc($line) if $logfunc;
382 } elsif ($h eq $error) {
383 if ($errfunc || $logfunc) {
386 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
388 &$errfunc($line) if $errfunc;
389 &$logfunc($line) if $logfunc;
406 &$outfunc($outlog) if $outfunc && $outlog;
407 &$logfunc($outlog) if $logfunc && $outlog;
409 &$errfunc($errlog) if $errfunc && $errlog;
410 &$logfunc($errlog) if $logfunc && $errlog;
415 die "failed to execute\n";
416 } elsif (my $sig = ($? & 127)) {
417 die "got signal $sig\n";
418 } elsif (my $ec = ($? >> 8)) {
419 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
420 if ($errmsg && $laststderr) {
421 my $lerr = $laststderr;
425 die "exit code $ec\n";
436 if ($errmsg && $laststderr) {
437 &$errfunc(undef); # flush laststderr
440 umask ($old_umask) if defined($old_umask);
442 alarm($oldtimeout) if $oldtimeout;
445 if ($pid && ($err eq "got timeout\n")) {
448 die "command '$cmdstr' failed: $err";
452 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
455 die "command '$cmdstr' failed: $err";
463 my $listtxt = shift || '';
465 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
467 $listtxt =~ s/[,;]/ /g;
468 $listtxt =~ s/^\s+//;
470 my @data = split (/\s+/, $listtxt);
478 return $txt if !defined($txt);
486 # simple uri templates like "/vms/{vmid}"
487 sub template_replace
{
488 my ($tmpl, $data) = @_;
490 return $tmpl if !$tmpl;
493 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
495 $res .= ($data->{$3} || '-') if $2;
501 my ($filename, $fh, $data) = @_;
505 my $res = print $fh $data;
507 die "write to '$filename' failed\n" if !$res;
513 'at' => 'ftp.at.debian.org',
514 'au' => 'ftp.au.debian.org',
515 'be' => 'ftp.be.debian.org',
516 'bg' => 'ftp.bg.debian.org',
517 'br' => 'ftp.br.debian.org',
518 'ca' => 'ftp.ca.debian.org',
519 'ch' => 'ftp.ch.debian.org',
520 'cl' => 'ftp.cl.debian.org',
521 'cz' => 'ftp.cz.debian.org',
522 'de' => 'ftp.de.debian.org',
523 'dk' => 'ftp.dk.debian.org',
524 'ee' => 'ftp.ee.debian.org',
525 'es' => 'ftp.es.debian.org',
526 'fi' => 'ftp.fi.debian.org',
527 'fr' => 'ftp.fr.debian.org',
528 'gr' => 'ftp.gr.debian.org',
529 'hk' => 'ftp.hk.debian.org',
530 'hr' => 'ftp.hr.debian.org',
531 'hu' => 'ftp.hu.debian.org',
532 'ie' => 'ftp.ie.debian.org',
533 'is' => 'ftp.is.debian.org',
534 'it' => 'ftp.it.debian.org',
535 'jp' => 'ftp.jp.debian.org',
536 'kr' => 'ftp.kr.debian.org',
537 'mx' => 'ftp.mx.debian.org',
538 'nl' => 'ftp.nl.debian.org',
539 'no' => 'ftp.no.debian.org',
540 'nz' => 'ftp.nz.debian.org',
541 'pl' => 'ftp.pl.debian.org',
542 'pt' => 'ftp.pt.debian.org',
543 'ro' => 'ftp.ro.debian.org',
544 'ru' => 'ftp.ru.debian.org',
545 'se' => 'ftp.se.debian.org',
546 'si' => 'ftp.si.debian.org',
547 'sk' => 'ftp.sk.debian.org',
548 'tr' => 'ftp.tr.debian.org',
549 'tw' => 'ftp.tw.debian.org',
550 'gb' => 'ftp.uk.debian.org',
551 'us' => 'ftp.us.debian.org',
556 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
557 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
558 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
559 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
560 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
561 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
562 #'et' => [], # Ethopia or Estonia ??
563 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
564 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
565 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
566 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
567 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
568 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
569 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
570 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
571 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
572 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
573 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
574 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
575 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
576 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
577 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
578 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
579 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
580 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
581 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
582 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
583 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
584 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
585 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
587 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
590 my $kvmkeymaparray = [];
591 foreach my $lc (keys %$keymaphash) {
592 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
600 return $kvmkeymaparray;
604 my ($param, $key) = @_;
606 my $res = $param->{$key};
607 delete $param->{$key};
612 # Note: we use this to wait until vncterm is ready
613 sub wait_for_vnc_port
{
614 my ($port, $timeout) = @_;
616 $timeout = 5 if !$timeout;
618 for (my $i = 0; $i < $timeout; $i++) {
619 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
620 while (defined (my $line = <$fh>)) {
621 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
622 if ($port == hex($2)) {
636 sub next_unused_port
{
637 my ($range_start, $range_end) = @_;
639 # We use a file to register allocated ports.
640 # Those registrations expires after $expiretime.
641 # We use this to avoid race conditions between
642 # allocation and use of ports.
644 my $filename = "/var/tmp/pve-reserved-ports";
653 if (my $fh = IO
::File-
>new ($filename, "r")) {
654 while (my $line = <$fh>) {
655 if ($line =~ m/^(\d+)\s(\d+)$/) {
656 my ($port, $timestamp) = ($1, $2);
657 if (($timestamp + $expiretime) > $ctime) {
658 $ports->{$port} = $timestamp; # not expired
666 for (my $p = $range_start; $p < $range_end; $p++) {
667 next if $ports->{$p}; # reserved
669 my $sock = IO
::Socket
::INET-
>new(Listen
=> 5,
670 LocalAddr
=> 'localhost',
678 $ports->{$p} = $ctime;
684 foreach my $p (keys %$ports) {
685 $data .= "$p $ports->{$p}\n";
688 file_set_contents
($filename, $data);
693 my $p = lock_file
($filename, 10, $code);
696 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
701 sub next_migrate_port
{
702 return next_unused_port
(60000, 60010);
706 return next_unused_port
(5900, 6000);
709 # NOTE: NFS syscall can't be interrupted, so alarm does
710 # not work to provide timeouts.
711 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
712 # So the spawn external 'df' process instead of using
713 # Filesys::Df (which uses statfs syscall)
715 my ($path, $timeout) = @_;
717 my $cmd = [ 'df', '-P', '-B', '1', $path];
727 if (my ($fsid, $total, $used, $avail) = $line =~
728 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
736 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
743 # We use this to uniquely identify a process.
744 # An 'Unique Process ID' has the following format:
745 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
750 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
751 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
756 my ($upid, $noerr) = @_;
761 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
762 if ($upid =~ m/^UPID:([a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/) {
764 $res->{pid
} = hex($3);
765 $res->{pstart
} = hex($4);
766 $res->{starttime
} = hex($5);
771 my $subdir = substr($5, 7, 8);
772 $filename = "$pvetaskdir/$subdir/$upid";
775 return undef if $noerr;
776 die "unable to parse worker upid '$upid'\n";
779 return wantarray ?
($res, $filename) : $res;
785 my ($task, $filename) = upid_decode
($upid);
787 my $dirname = dirname
($filename);
790 my $wwwid = getpwnam('www-data') ||
791 die "getpwnam failed";
795 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
796 die "unable to create output file '$filename' - $!\n";
797 chown $wwwid, -1, $outfh;
802 sub upid_read_status
{
805 my ($task, $filename) = upid_decode
($upid);
806 my $fh = IO
::File-
>new($filename, "r");
807 return "unable to open file - $!" if !$fh;
809 sysseek($fh, -$maxlen, 2);
811 my $br = sysread($fh, $readbuf, $maxlen);
814 return "unable to extract last line"
815 if $readbuf !~ m/\n?(.+)$/;
817 if ($line =~ m/^TASK OK$/) {
819 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
822 return "unexpected status";
825 return "unable to read tail (got $br bytes)";
828 # useful functions to store comments in config files
832 # all control and hi-bit characters, and ':'
833 my $unsafe = "^\x20-\x39\x3b-\x7e";
834 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
840 return Encode
::decode
("utf8", uri_unescape
($data));
843 sub decode_utf8_parameters
{
846 foreach my $p (qw(comment description firstname lastname)) {
847 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
853 sub random_ether_addr
{
855 my $rand = Digest
::SHA
::sha1_hex
(rand(), time());
858 for (my $i = 0; $i < 6; $i++) {
859 my $ss = hex(substr($rand, $i*2, 2));
861 $ss &= 0xfe; # clear multicast
862 $ss |= 2; # set local id
864 $ss = sprintf("%02X", $ss);
879 return String
::ShellQuote
::shell_quote
($str);
885 die "no arguments" if !$cmd;
887 return $cmd if !ref($cmd);
890 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
892 return join (' ', @qa);
895 # split an shell argument string into an array,
899 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
903 my ($filename, $start, $limit) = @_;
908 my $fh = IO
::File-
>new($filename, "r");
911 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
912 return ($count, $lines);
915 $start = 0 if !$start;
916 $limit = 50 if !$limit;
919 while (defined($line = <$fh>)) {
920 next if $count++ < $start;
923 push @$lines, { n
=> $count, t
=> $line};
929 # HACK: ExtJS store.guaranteeRange() does not like empty array
933 push @$lines, { n
=> $count, t
=> "no content"};
936 return ($count, $lines);
940 my ($dir, $regex) = @_;
942 my $dh = IO
::Dir-
>new ($dir);
943 return wantarray ?
() : undef if !$dh;
945 while (defined(my $tmp = $dh->read)) {
946 if (my @res = $tmp =~ m/^($regex)$/) {
948 return wantarray ?
@res : $tmp;
953 return wantarray ?
() : undef;
956 sub dir_glob_foreach
{
957 my ($dir, $regex, $func) = @_;
959 my $dh = IO
::Dir-
>new ($dir);
961 while (defined(my $tmp = $dh->read)) {
962 if (my @res = $tmp =~ m/^($regex)$/) {