]>
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);
242 foreach my $p (keys %param) {
243 if ($p eq 'timeout') {
244 $timeout = $param{$p};
245 } elsif ($p eq 'umask') {
246 $old_umask = umask($param{$p});
247 } elsif ($p eq 'errmsg') {
248 $errmsg = $param{$p};
249 } elsif ($p eq 'input') {
251 } elsif ($p eq 'output') {
252 $output = $param{$p};
253 } elsif ($p eq 'outfunc') {
254 $outfunc = $param{$p};
255 } elsif ($p eq 'errfunc') {
256 $errfunc = $param{$p};
257 } elsif ($p eq 'logfunc') {
258 $logfunc = $param{$p};
260 die "got unknown parameter '$p' for run_command\n";
265 my $origerrfunc = $errfunc;
269 &$origerrfunc("$laststderr\n");
271 print STDERR
"$laststderr\n" if $laststderr;
278 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
279 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
280 my $error = IO
::File-
>new();
282 # try to avoid locale related issues/warnings
283 my $lang = $param{lang
} || 'C';
288 local $ENV{LC_ALL
} = $lang;
290 # suppress LVM warnings like: "File descriptor 3 left open";
291 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
293 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
295 # if we pipe fron STDIN, open3 closes STDIN, so we we
296 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
297 # as soon as we open a new file.
298 # to avoid that we open /dev/null
299 if (!ref($writer) && !defined(fileno(STDIN
))) {
301 open(STDIN
, "</dev/null");
308 if ($orig_pid != $$) {
316 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
317 $oldtimeout = alarm($timeout) if $timeout;
320 print $writer $input if defined $input;
324 my $select = new IO
::Select
;
325 $select->add($reader) if ref($reader);
326 $select->add($error);
331 my $starttime = time();
333 while ($select->count) {
334 my @handles = $select->can_read(1);
336 foreach my $h (@handles) {
338 my $count = sysread ($h, $buf, 4096);
339 if (!defined ($count)) {
345 $select->remove ($h) if !$count;
347 if ($outfunc || $logfunc) {
350 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
352 &$outfunc($line) if $outfunc;
353 &$logfunc($line) if $logfunc;
366 } elsif ($h eq $error) {
367 if ($errfunc || $logfunc) {
370 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
372 &$errfunc($line) if $errfunc;
373 &$logfunc($line) if $logfunc;
390 &$outfunc($outlog) if $outfunc && $outlog;
391 &$logfunc($outlog) if $logfunc && $outlog;
393 &$errfunc($errlog) if $errfunc && $errlog;
394 &$logfunc($errlog) if $logfunc && $errlog;
399 die "failed to execute\n";
400 } elsif (my $sig = ($? & 127)) {
401 die "got signal $sig\n";
402 } elsif (my $ec = ($? >> 8)) {
403 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
404 if ($errmsg && $laststderr) {
405 my $lerr = $laststderr;
409 die "exit code $ec\n";
420 if ($errmsg && $laststderr) {
421 &$errfunc(undef); # flush laststderr
424 umask ($old_umask) if defined($old_umask);
426 alarm($oldtimeout) if $oldtimeout;
429 if ($pid && ($err eq "got timeout\n")) {
432 die "command '$cmdstr' failed: $err";
436 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
439 die "command '$cmdstr' failed: $err";
447 my $listtxt = shift || '';
449 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
451 $listtxt =~ s/[,;]/ /g;
452 $listtxt =~ s/^\s+//;
454 my @data = split (/\s+/, $listtxt);
462 return $txt if !defined($txt);
470 # simple uri templates like "/vms/{vmid}"
471 sub template_replace
{
472 my ($tmpl, $data) = @_;
474 return $tmpl if !$tmpl;
477 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
479 $res .= ($data->{$3} || '-') if $2;
485 my ($filename, $fh, $data) = @_;
489 my $res = print $fh $data;
491 die "write to '$filename' failed\n" if !$res;
497 'at' => 'ftp.at.debian.org',
498 'au' => 'ftp.au.debian.org',
499 'be' => 'ftp.be.debian.org',
500 'bg' => 'ftp.bg.debian.org',
501 'br' => 'ftp.br.debian.org',
502 'ca' => 'ftp.ca.debian.org',
503 'ch' => 'ftp.ch.debian.org',
504 'cl' => 'ftp.cl.debian.org',
505 'cz' => 'ftp.cz.debian.org',
506 'de' => 'ftp.de.debian.org',
507 'dk' => 'ftp.dk.debian.org',
508 'ee' => 'ftp.ee.debian.org',
509 'es' => 'ftp.es.debian.org',
510 'fi' => 'ftp.fi.debian.org',
511 'fr' => 'ftp.fr.debian.org',
512 'gr' => 'ftp.gr.debian.org',
513 'hk' => 'ftp.hk.debian.org',
514 'hr' => 'ftp.hr.debian.org',
515 'hu' => 'ftp.hu.debian.org',
516 'ie' => 'ftp.ie.debian.org',
517 'is' => 'ftp.is.debian.org',
518 'it' => 'ftp.it.debian.org',
519 'jp' => 'ftp.jp.debian.org',
520 'kr' => 'ftp.kr.debian.org',
521 'mx' => 'ftp.mx.debian.org',
522 'nl' => 'ftp.nl.debian.org',
523 'no' => 'ftp.no.debian.org',
524 'nz' => 'ftp.nz.debian.org',
525 'pl' => 'ftp.pl.debian.org',
526 'pt' => 'ftp.pt.debian.org',
527 'ro' => 'ftp.ro.debian.org',
528 'ru' => 'ftp.ru.debian.org',
529 'se' => 'ftp.se.debian.org',
530 'si' => 'ftp.si.debian.org',
531 'sk' => 'ftp.sk.debian.org',
532 'tr' => 'ftp.tr.debian.org',
533 'tw' => 'ftp.tw.debian.org',
534 'gb' => 'ftp.uk.debian.org',
535 'us' => 'ftp.us.debian.org',
540 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
541 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
542 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
543 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
544 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
545 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
546 #'et' => [], # Ethopia or Estonia ??
547 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
548 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
549 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
550 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
551 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
552 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
553 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
554 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
555 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
556 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
557 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
558 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
559 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
560 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
561 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
562 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
563 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
564 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
565 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
566 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
567 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
568 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
569 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
571 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
574 my $kvmkeymaparray = [];
575 foreach my $lc (keys %$keymaphash) {
576 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
584 return $kvmkeymaparray;
588 my ($param, $key) = @_;
590 my $res = $param->{$key};
591 delete $param->{$key};
596 # Note: we use this to wait until vncterm is ready
597 sub wait_for_vnc_port
{
598 my ($port, $timeout) = @_;
600 $timeout = 5 if !$timeout;
602 for (my $i = 0; $i < $timeout; $i++) {
603 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
604 while (defined (my $line = <$fh>)) {
605 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
606 if ($port == hex($2)) {
622 for (my $p = 5900; $p < 6000; $p++) {
624 my $sock = IO
::Socket
::INET-
>new (Listen
=> 5,
625 LocalAddr
=> 'localhost',
636 die "unable to find free vnc port";
639 # NOTE: NFS syscall can't be interrupted, so alarm does
640 # not work to provide timeouts.
641 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
642 # So the spawn external 'df' process instead of using
643 # Filesys::Df (which uses statfs syscall)
645 my ($path, $timeout) = @_;
647 my $cmd = [ 'df', '-P', '-B', '1', $path];
657 if (my ($fsid, $total, $used, $avail) = $line =~
658 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
666 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
673 # We use this to uniquely identify a process.
674 # An 'Unique Process ID' has the following format:
675 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
680 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
681 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
686 my ($upid, $noerr) = @_;
691 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
692 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]+):$/) {
694 $res->{pid
} = hex($3);
695 $res->{pstart
} = hex($4);
696 $res->{starttime
} = hex($5);
701 my $subdir = substr($5, 7, 8);
702 $filename = "$pvetaskdir/$subdir/$upid";
705 return undef if $noerr;
706 die "unable to parse worker upid '$upid'\n";
709 return wantarray ?
($res, $filename) : $res;
715 my ($task, $filename) = upid_decode
($upid);
717 my $dirname = dirname
($filename);
720 my $wwwid = getpwnam('www-data') ||
721 die "getpwnam failed";
725 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
726 die "unable to create output file '$filename' - $!\n";
727 chown $wwwid, -1, $outfh;
732 sub upid_read_status
{
735 my ($task, $filename) = upid_decode
($upid);
736 my $fh = IO
::File-
>new($filename, "r");
737 return "unable to open file - $!" if !$fh;
739 sysseek($fh, -$maxlen, 2);
741 my $br = sysread($fh, $readbuf, $maxlen);
744 return "unable to extract last line"
745 if $readbuf !~ m/\n?(.+)$/;
747 if ($line =~ m/^TASK OK$/) {
749 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
752 return "unexpected status";
755 return "unable to read tail (got $br bytes)";
758 # useful functions to store comments in config files
762 # all control and hi-bit characters, and ':'
763 my $unsafe = "^\x20-\x39\x3b-\x7e";
764 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
770 return Encode
::decode
("utf8", uri_unescape
($data));
773 sub decode_utf8_parameters
{
776 foreach my $p (qw(comment description firstname lastname)) {
777 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
783 sub random_ether_addr
{
785 my $rand = Digest
::SHA
::sha1_hex
(rand(), time());
788 for (my $i = 0; $i < 6; $i++) {
789 my $ss = hex(substr($rand, $i*2, 2));
791 $ss &= 0xfe; # clear multicast
792 $ss |= 2; # set local id
794 $ss = sprintf("%02X", $ss);
809 return String
::ShellQuote
::shell_quote
($str);
815 die "no arguments" if !$cmd;
817 return $cmd if !ref($cmd);
820 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
822 return join (' ', @qa);
825 # split an shell argument string into an array,
829 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
833 my ($filename, $start, $limit) = @_;
838 my $fh = IO
::File-
>new($filename, "r");
841 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
842 return ($count, $lines);
845 $start = 0 if !$start;
846 $limit = 50 if !$limit;
849 while (defined($line = <$fh>)) {
850 next if $count++ < $start;
853 push @$lines, { n
=> $count, t
=> $line};
859 # HACK: ExtJS store.guaranteeRange() does not like empty array
863 push @$lines, { n
=> $count, t
=> "no content"};
866 return ($count, $lines);
870 my ($dir, $regex) = @_;
872 my $dh = IO
::Dir-
>new ($dir);
873 return wantarray ?
() : undef if !$dh;
875 while (defined(my $tmp = $dh->read)) {
876 if (my @res = $tmp =~ m/^($regex)$/) {
878 return wantarray ?
@res : $tmp;
883 return wantarray ?
() : undef;
886 sub dir_glob_foreach
{
887 my ($dir, $regex, $func) = @_;
889 my $dh = IO
::Dir-
>new ($dir);
891 while (defined(my $tmp = $dh->read)) {
892 if (my @res = $tmp =~ m/^($regex)$/) {