]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
8 use File
::Path
qw(make_path);
12 use Fcntl
qw(:DEFAULT :flock);
18 use String
::ShellQuote
;
35 my $pvelogdir = "/var/log/pve";
36 my $pvetaskdir = "$pvelogdir/tasks";
41 sub run_with_timeout
{
42 my ($timeout, $code, @param) = @_;
44 die "got timeout\n" if $timeout <= 0;
52 local $SIG{ALRM
} = sub { $sigcount++; }; # catch alarm outside eval
55 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
56 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
57 local $SIG{__DIE__
}; # see SA bug 4631
59 $prev_alarm = alarm($timeout);
61 $res = &$code(@param);
63 alarm(0); # avoid race conditions
68 alarm($prev_alarm) if defined($prev_alarm);
70 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
77 # flock: we use one file handle per process, so lock file
78 # can be called multiple times and succeeds for the same process.
80 my $lock_handles = {};
83 my ($filename, $timeout, $code, @param) = @_;
85 $timeout = 10 if !$timeout;
88 if (!$lock_handles->{$$}->{$filename}) {
89 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
90 die "can't open file - $!\n";
93 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX
|LOCK_NB
)) {
94 print STDERR
"trying to aquire lock...";
97 $success = flock($lock_handles->{$$}->{$filename}, LOCK_EX
);
98 # try again on EINTR (see bug #273)
99 if ($success || ($! != EINTR
)) {
104 print STDERR
" failed\n";
105 die "can't aquire lock - $!\n";
107 print STDERR
" OK\n";
113 eval { run_with_timeout
($timeout, $lock_func); };
116 $err = "can't lock file '$filename' - $err";
118 eval { $res = &$code(@param) };
122 if ($lock_handles->{$$}->{$filename}) {
123 my $fh = $lock_handles->{$$}->{$filename};
124 $lock_handles->{$$}->{$filename} = undef;
138 sub file_set_contents
{
139 my ($filename, $data, $perm) = @_;
141 $perm = 0644 if !defined($perm);
143 my $tmpname = "$filename.tmp.$$";
146 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
147 die "unable to open file '$tmpname' - $!\n" if !$fh;
148 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
149 die "closing file '$tmpname' failed - $!\n" unless close $fh;
158 if (!rename($tmpname, $filename)) {
159 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
165 sub file_get_contents
{
166 my ($filename, $max) = @_;
168 my $fh = IO
::File-
>new($filename, "r") ||
169 die "can't open '$filename' - $!\n";
171 my $content = safe_read_from
($fh, $max);
178 sub file_read_firstline
{
181 my $fh = IO
::File-
>new ($filename, "r");
182 return undef if !$fh;
190 my ($fh, $max, $oneline) = @_;
192 $max = 32768 if !$max;
197 while ($count = sysread($fh, $input, 8192, $br)) {
199 die "input too long - aborting\n" if $br > $max;
200 if ($oneline && $input =~ m/^(.*)\n/) {
205 die "unable to read input - $!\n" if !defined($count);
211 my ($cmd, %param) = @_;
219 # see 'man bash' for option pipefail
220 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
225 $cmdstr = cmd2string
($cmd);
243 foreach my $p (keys %param) {
244 if ($p eq 'timeout') {
245 $timeout = $param{$p};
246 } elsif ($p eq 'umask') {
247 $old_umask = umask($param{$p});
248 } elsif ($p eq 'errmsg') {
249 $errmsg = $param{$p};
250 } elsif ($p eq 'input') {
252 } elsif ($p eq 'output') {
253 $output = $param{$p};
254 } elsif ($p eq 'outfunc') {
255 $outfunc = $param{$p};
256 } elsif ($p eq 'errfunc') {
257 $errfunc = $param{$p};
258 } elsif ($p eq 'logfunc') {
259 $logfunc = $param{$p};
260 } elsif ($p eq 'afterfork') {
261 $afterfork = $param{$p};
263 die "got unknown parameter '$p' for run_command\n";
268 my $origerrfunc = $errfunc;
272 &$origerrfunc("$laststderr\n");
274 print STDERR
"$laststderr\n" if $laststderr;
281 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
282 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
283 my $error = IO
::File-
>new();
285 # try to avoid locale related issues/warnings
286 my $lang = $param{lang
} || 'C';
291 local $ENV{LC_ALL
} = $lang;
293 # suppress LVM warnings like: "File descriptor 3 left open";
294 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
296 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
298 # if we pipe fron STDIN, open3 closes STDIN, so we we
299 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
300 # as soon as we open a new file.
301 # to avoid that we open /dev/null
302 if (!ref($writer) && !defined(fileno(STDIN
))) {
304 open(STDIN
, "</dev/null");
311 if ($orig_pid != $$) {
319 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
320 $oldtimeout = alarm($timeout) if $timeout;
322 &$afterfork() if $afterfork;
325 print $writer $input if defined $input;
329 my $select = new IO
::Select
;
330 $select->add($reader) if ref($reader);
331 $select->add($error);
336 my $starttime = time();
338 while ($select->count) {
339 my @handles = $select->can_read(1);
341 foreach my $h (@handles) {
343 my $count = sysread ($h, $buf, 4096);
344 if (!defined ($count)) {
350 $select->remove ($h) if !$count;
352 if ($outfunc || $logfunc) {
355 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
357 &$outfunc($line) if $outfunc;
358 &$logfunc($line) if $logfunc;
371 } elsif ($h eq $error) {
372 if ($errfunc || $logfunc) {
375 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
377 &$errfunc($line) if $errfunc;
378 &$logfunc($line) if $logfunc;
395 &$outfunc($outlog) if $outfunc && $outlog;
396 &$logfunc($outlog) if $logfunc && $outlog;
398 &$errfunc($errlog) if $errfunc && $errlog;
399 &$logfunc($errlog) if $logfunc && $errlog;
404 die "failed to execute\n";
405 } elsif (my $sig = ($? & 127)) {
406 die "got signal $sig\n";
407 } elsif (my $ec = ($? >> 8)) {
408 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
409 if ($errmsg && $laststderr) {
410 my $lerr = $laststderr;
414 die "exit code $ec\n";
425 if ($errmsg && $laststderr) {
426 &$errfunc(undef); # flush laststderr
429 umask ($old_umask) if defined($old_umask);
431 alarm($oldtimeout) if $oldtimeout;
434 if ($pid && ($err eq "got timeout\n")) {
437 die "command '$cmdstr' failed: $err";
441 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
444 die "command '$cmdstr' failed: $err";
452 my $listtxt = shift || '';
454 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
456 $listtxt =~ s/[,;]/ /g;
457 $listtxt =~ s/^\s+//;
459 my @data = split (/\s+/, $listtxt);
467 return $txt if !defined($txt);
475 # simple uri templates like "/vms/{vmid}"
476 sub template_replace
{
477 my ($tmpl, $data) = @_;
479 return $tmpl if !$tmpl;
482 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
484 $res .= ($data->{$3} || '-') if $2;
490 my ($filename, $fh, $data) = @_;
494 my $res = print $fh $data;
496 die "write to '$filename' failed\n" if !$res;
502 'at' => 'ftp.at.debian.org',
503 'au' => 'ftp.au.debian.org',
504 'be' => 'ftp.be.debian.org',
505 'bg' => 'ftp.bg.debian.org',
506 'br' => 'ftp.br.debian.org',
507 'ca' => 'ftp.ca.debian.org',
508 'ch' => 'ftp.ch.debian.org',
509 'cl' => 'ftp.cl.debian.org',
510 'cz' => 'ftp.cz.debian.org',
511 'de' => 'ftp.de.debian.org',
512 'dk' => 'ftp.dk.debian.org',
513 'ee' => 'ftp.ee.debian.org',
514 'es' => 'ftp.es.debian.org',
515 'fi' => 'ftp.fi.debian.org',
516 'fr' => 'ftp.fr.debian.org',
517 'gr' => 'ftp.gr.debian.org',
518 'hk' => 'ftp.hk.debian.org',
519 'hr' => 'ftp.hr.debian.org',
520 'hu' => 'ftp.hu.debian.org',
521 'ie' => 'ftp.ie.debian.org',
522 'is' => 'ftp.is.debian.org',
523 'it' => 'ftp.it.debian.org',
524 'jp' => 'ftp.jp.debian.org',
525 'kr' => 'ftp.kr.debian.org',
526 'mx' => 'ftp.mx.debian.org',
527 'nl' => 'ftp.nl.debian.org',
528 'no' => 'ftp.no.debian.org',
529 'nz' => 'ftp.nz.debian.org',
530 'pl' => 'ftp.pl.debian.org',
531 'pt' => 'ftp.pt.debian.org',
532 'ro' => 'ftp.ro.debian.org',
533 'ru' => 'ftp.ru.debian.org',
534 'se' => 'ftp.se.debian.org',
535 'si' => 'ftp.si.debian.org',
536 'sk' => 'ftp.sk.debian.org',
537 'tr' => 'ftp.tr.debian.org',
538 'tw' => 'ftp.tw.debian.org',
539 'gb' => 'ftp.uk.debian.org',
540 'us' => 'ftp.us.debian.org',
545 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
546 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
547 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
548 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
549 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
550 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
551 #'et' => [], # Ethopia or Estonia ??
552 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
553 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
554 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
555 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
556 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
557 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
558 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
559 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
560 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
561 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
562 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
563 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
564 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
565 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
566 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
567 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
568 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
569 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
570 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
571 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
572 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
573 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
574 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
576 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
579 my $kvmkeymaparray = [];
580 foreach my $lc (keys %$keymaphash) {
581 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
589 return $kvmkeymaparray;
593 my ($param, $key) = @_;
595 my $res = $param->{$key};
596 delete $param->{$key};
601 # Note: we use this to wait until vncterm is ready
602 sub wait_for_vnc_port
{
603 my ($port, $timeout) = @_;
605 $timeout = 5 if !$timeout;
607 for (my $i = 0; $i < $timeout; $i++) {
608 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
609 while (defined (my $line = <$fh>)) {
610 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
611 if ($port == hex($2)) {
627 for (my $p = 5900; $p < 6000; $p++) {
629 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
630 LocalAddr
=> 'localhost',
641 die "unable to find free vnc port";
644 # NOTE: NFS syscall can't be interrupted, so alarm does
645 # not work to provide timeouts.
646 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
647 # So the spawn external 'df' process instead of using
648 # Filesys::Df (which uses statfs syscall)
650 my ($path, $timeout) = @_;
652 my $cmd = [ 'df', '-P', '-B', '1', $path];
662 if (my ($fsid, $total, $used, $avail) = $line =~
663 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
671 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
678 # We use this to uniquely identify a process.
679 # An 'Unique Process ID' has the following format:
680 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
685 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
686 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
691 my ($upid, $noerr) = @_;
696 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
697 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]+):$/) {
699 $res->{pid
} = hex($3);
700 $res->{pstart
} = hex($4);
701 $res->{starttime
} = hex($5);
706 my $subdir = substr($5, 7, 8);
707 $filename = "$pvetaskdir/$subdir/$upid";
710 return undef if $noerr;
711 die "unable to parse worker upid '$upid'\n";
714 return wantarray ?
($res, $filename) : $res;
720 my ($task, $filename) = upid_decode
($upid);
722 my $dirname = dirname
($filename);
725 my $wwwid = getpwnam('www-data') ||
726 die "getpwnam failed";
730 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
731 die "unable to create output file '$filename' - $!\n";
732 chown $wwwid, -1, $outfh;
737 sub upid_read_status
{
740 my ($task, $filename) = upid_decode
($upid);
741 my $fh = IO
::File-
>new($filename, "r");
742 return "unable to open file - $!" if !$fh;
744 sysseek($fh, -$maxlen, 2);
746 my $br = sysread($fh, $readbuf, $maxlen);
749 return "unable to extract last line"
750 if $readbuf !~ m/\n?(.+)$/;
752 if ($line =~ m/^TASK OK$/) {
754 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
757 return "unexpected status";
760 return "unable to read tail (got $br bytes)";
763 # useful functions to store comments in config files
767 # all control and hi-bit characters, and ':'
768 my $unsafe = "^\x20-\x39\x3b-\x7e";
769 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
775 return Encode
::decode
("utf8", uri_unescape
($data));
778 sub decode_utf8_parameters
{
781 foreach my $p (qw(comment description firstname lastname)) {
782 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
788 sub random_ether_addr
{
790 my $rand = Digest
::SHA
::sha1_hex
(rand(), time());
793 for (my $i = 0; $i < 6; $i++) {
794 my $ss = hex(substr($rand, $i*2, 2));
796 $ss &= 0xfe; # clear multicast
797 $ss |= 2; # set local id
799 $ss = sprintf("%02X", $ss);
814 return String
::ShellQuote
::shell_quote
($str);
820 die "no arguments" if !$cmd;
822 return $cmd if !ref($cmd);
825 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
827 return join (' ', @qa);
830 # split an shell argument string into an array,
834 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
838 my ($filename, $start, $limit) = @_;
843 my $fh = IO
::File-
>new($filename, "r");
846 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
847 return ($count, $lines);
850 $start = 0 if !$start;
851 $limit = 50 if !$limit;
854 while (defined($line = <$fh>)) {
855 next if $count++ < $start;
858 push @$lines, { n
=> $count, t
=> $line};
864 # HACK: ExtJS store.guaranteeRange() does not like empty array
868 push @$lines, { n
=> $count, t
=> "no content"};
871 return ($count, $lines);
875 my ($dir, $regex) = @_;
877 my $dh = IO
::Dir-
>new ($dir);
878 return wantarray ?
() : undef if !$dh;
880 while (defined(my $tmp = $dh->read)) {
881 if (my @res = $tmp =~ m/^($regex)$/) {
883 return wantarray ?
@res : $tmp;
888 return wantarray ?
() : undef;
891 sub dir_glob_foreach
{
892 my ($dir, $regex, $func) = @_;
894 my $dh = IO
::Dir-
>new ($dir);
896 while (defined(my $tmp = $dh->read)) {
897 if (my @res = $tmp =~ m/^($regex)$/) {