]>
git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
9 use File
::Path
qw(make_path);
13 use Fcntl
qw(:DEFAULT :flock);
19 use String
::ShellQuote
;
20 use Time
::HiRes
qw(usleep gettimeofday tv_interval);
40 my $pvelogdir = "/var/log/pve";
41 my $pvetaskdir = "$pvelogdir/tasks";
46 my $IPV4OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
47 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
48 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
49 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
52 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
53 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
54 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
55 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
56 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
57 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
58 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
59 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
60 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
62 sub run_with_timeout
{
63 my ($timeout, $code, @param) = @_;
65 die "got timeout\n" if $timeout <= 0;
73 local $SIG{ALRM
} = sub { $sigcount++; }; # catch alarm outside eval
76 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
77 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
78 local $SIG{__DIE__
}; # see SA bug 4631
80 $prev_alarm = alarm($timeout);
82 $res = &$code(@param);
84 alarm(0); # avoid race conditions
89 alarm($prev_alarm) if defined($prev_alarm);
91 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
98 # flock: we use one file handle per process, so lock file
99 # can be called multiple times and succeeds for the same process.
101 my $lock_handles = {};
104 my ($filename, $timeout, $shared, $code, @param) = @_;
106 $timeout = 10 if !$timeout;
108 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
110 my $lock_func = sub {
111 if (!$lock_handles->{$$}->{$filename}) {
112 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
113 die "can't open file - $!\n";
116 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
117 print STDERR
"trying to aquire lock...";
120 $success = flock($lock_handles->{$$}->{$filename}, $mode);
121 # try again on EINTR (see bug #273)
122 if ($success || ($! != EINTR
)) {
127 print STDERR
" failed\n";
128 die "can't aquire lock - $!\n";
130 print STDERR
" OK\n";
136 eval { run_with_timeout
($timeout, $lock_func); };
139 $err = "can't lock file '$filename' - $err";
141 eval { $res = &$code(@param) };
145 if ($lock_handles->{$$}->{$filename}) {
146 my $fh = $lock_handles->{$$}->{$filename};
147 $lock_handles->{$$}->{$filename} = undef;
163 my ($filename, $timeout, $code, @param) = @_;
165 return lock_file_full
($filename, $timeout, 0, $code, @param);
168 sub file_set_contents
{
169 my ($filename, $data, $perm) = @_;
171 $perm = 0644 if !defined($perm);
173 my $tmpname = "$filename.tmp.$$";
176 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
177 die "unable to open file '$tmpname' - $!\n" if !$fh;
178 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
179 die "closing file '$tmpname' failed - $!\n" unless close $fh;
188 if (!rename($tmpname, $filename)) {
189 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
195 sub file_get_contents
{
196 my ($filename, $max) = @_;
198 my $fh = IO
::File-
>new($filename, "r") ||
199 die "can't open '$filename' - $!\n";
201 my $content = safe_read_from
($fh, $max);
208 sub file_read_firstline
{
211 my $fh = IO
::File-
>new ($filename, "r");
212 return undef if !$fh;
220 my ($fh, $max, $oneline) = @_;
222 $max = 32768 if !$max;
227 while ($count = sysread($fh, $input, 8192, $br)) {
229 die "input too long - aborting\n" if $br > $max;
230 if ($oneline && $input =~ m/^(.*)\n/) {
235 die "unable to read input - $!\n" if !defined($count);
241 my ($cmd, %param) = @_;
249 # see 'man bash' for option pipefail
250 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
255 $cmdstr = cmd2string
($cmd);
273 foreach my $p (keys %param) {
274 if ($p eq 'timeout') {
275 $timeout = $param{$p};
276 } elsif ($p eq 'umask') {
277 $old_umask = umask($param{$p});
278 } elsif ($p eq 'errmsg') {
279 $errmsg = $param{$p};
280 } elsif ($p eq 'input') {
282 } elsif ($p eq 'output') {
283 $output = $param{$p};
284 } elsif ($p eq 'outfunc') {
285 $outfunc = $param{$p};
286 } elsif ($p eq 'errfunc') {
287 $errfunc = $param{$p};
288 } elsif ($p eq 'logfunc') {
289 $logfunc = $param{$p};
290 } elsif ($p eq 'afterfork') {
291 $afterfork = $param{$p};
293 die "got unknown parameter '$p' for run_command\n";
298 my $origerrfunc = $errfunc;
302 &$origerrfunc("$laststderr\n");
304 print STDERR
"$laststderr\n" if $laststderr;
311 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
312 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
313 my $error = IO
::File-
>new();
315 # try to avoid locale related issues/warnings
316 my $lang = $param{lang
} || 'C';
321 local $ENV{LC_ALL
} = $lang;
323 # suppress LVM warnings like: "File descriptor 3 left open";
324 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
326 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
328 # if we pipe fron STDIN, open3 closes STDIN, so we we
329 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
330 # as soon as we open a new file.
331 # to avoid that we open /dev/null
332 if (!ref($writer) && !defined(fileno(STDIN
))) {
334 open(STDIN
, "</dev/null");
341 if ($orig_pid != $$) {
349 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
350 $oldtimeout = alarm($timeout) if $timeout;
352 &$afterfork() if $afterfork;
355 print $writer $input if defined $input;
359 my $select = new IO
::Select
;
360 $select->add($reader) if ref($reader);
361 $select->add($error);
366 my $starttime = time();
368 while ($select->count) {
369 my @handles = $select->can_read(1);
371 foreach my $h (@handles) {
373 my $count = sysread ($h, $buf, 4096);
374 if (!defined ($count)) {
380 $select->remove ($h) if !$count;
382 if ($outfunc || $logfunc) {
385 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
387 &$outfunc($line) if $outfunc;
388 &$logfunc($line) if $logfunc;
401 } elsif ($h eq $error) {
402 if ($errfunc || $logfunc) {
405 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
407 &$errfunc($line) if $errfunc;
408 &$logfunc($line) if $logfunc;
425 &$outfunc($outlog) if $outfunc && $outlog;
426 &$logfunc($outlog) if $logfunc && $outlog;
428 &$errfunc($errlog) if $errfunc && $errlog;
429 &$logfunc($errlog) if $logfunc && $errlog;
434 die "failed to execute\n";
435 } elsif (my $sig = ($? & 127)) {
436 die "got signal $sig\n";
437 } elsif (my $ec = ($? >> 8)) {
438 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
439 if ($errmsg && $laststderr) {
440 my $lerr = $laststderr;
444 die "exit code $ec\n";
455 if ($errmsg && $laststderr) {
456 &$errfunc(undef); # flush laststderr
459 umask ($old_umask) if defined($old_umask);
461 alarm($oldtimeout) if $oldtimeout;
464 if ($pid && ($err eq "got timeout\n")) {
467 die "command '$cmdstr' failed: $err";
471 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
474 die "command '$cmdstr' failed: $err";
482 my $listtxt = shift || '';
484 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
486 $listtxt =~ s/[,;]/ /g;
487 $listtxt =~ s/^\s+//;
489 my @data = split (/\s+/, $listtxt);
497 return $txt if !defined($txt);
505 # simple uri templates like "/vms/{vmid}"
506 sub template_replace
{
507 my ($tmpl, $data) = @_;
509 return $tmpl if !$tmpl;
512 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
514 $res .= ($data->{$3} || '-') if $2;
520 my ($filename, $fh, $data) = @_;
524 my $res = print $fh $data;
526 die "write to '$filename' failed\n" if !$res;
532 'at' => 'ftp.at.debian.org',
533 'au' => 'ftp.au.debian.org',
534 'be' => 'ftp.be.debian.org',
535 'bg' => 'ftp.bg.debian.org',
536 'br' => 'ftp.br.debian.org',
537 'ca' => 'ftp.ca.debian.org',
538 'ch' => 'ftp.ch.debian.org',
539 'cl' => 'ftp.cl.debian.org',
540 'cz' => 'ftp.cz.debian.org',
541 'de' => 'ftp.de.debian.org',
542 'dk' => 'ftp.dk.debian.org',
543 'ee' => 'ftp.ee.debian.org',
544 'es' => 'ftp.es.debian.org',
545 'fi' => 'ftp.fi.debian.org',
546 'fr' => 'ftp.fr.debian.org',
547 'gr' => 'ftp.gr.debian.org',
548 'hk' => 'ftp.hk.debian.org',
549 'hr' => 'ftp.hr.debian.org',
550 'hu' => 'ftp.hu.debian.org',
551 'ie' => 'ftp.ie.debian.org',
552 'is' => 'ftp.is.debian.org',
553 'it' => 'ftp.it.debian.org',
554 'jp' => 'ftp.jp.debian.org',
555 'kr' => 'ftp.kr.debian.org',
556 'mx' => 'ftp.mx.debian.org',
557 'nl' => 'ftp.nl.debian.org',
558 'no' => 'ftp.no.debian.org',
559 'nz' => 'ftp.nz.debian.org',
560 'pl' => 'ftp.pl.debian.org',
561 'pt' => 'ftp.pt.debian.org',
562 'ro' => 'ftp.ro.debian.org',
563 'ru' => 'ftp.ru.debian.org',
564 'se' => 'ftp.se.debian.org',
565 'si' => 'ftp.si.debian.org',
566 'sk' => 'ftp.sk.debian.org',
567 'tr' => 'ftp.tr.debian.org',
568 'tw' => 'ftp.tw.debian.org',
569 'gb' => 'ftp.uk.debian.org',
570 'us' => 'ftp.us.debian.org',
575 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
576 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
577 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
578 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
579 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
580 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
581 #'et' => [], # Ethopia or Estonia ??
582 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
583 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
584 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
585 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
586 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
587 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
588 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
589 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
590 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
591 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
592 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
593 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
594 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
595 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
596 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
597 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
598 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
599 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
600 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
601 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
602 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
603 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
604 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
606 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
609 my $kvmkeymaparray = [];
610 foreach my $lc (keys %$keymaphash) {
611 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
619 return $kvmkeymaparray;
623 my ($param, $key) = @_;
625 my $res = $param->{$key};
626 delete $param->{$key};
631 # Note: we use this to wait until vncterm/spiceterm is ready
632 sub wait_for_vnc_port
{
633 my ($port, $timeout) = @_;
635 $timeout = 5 if !$timeout;
637 my $starttime = [gettimeofday
];
640 while (($elapsed = tv_interval
($starttime)) < $timeout) {
641 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
642 while (defined (my $line = <$fh>)) {
643 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
644 if ($port == hex($2)) {
652 $sleeptime += 100000 if $sleeptime < 1000000;
659 sub next_unused_port
{
660 my ($range_start, $range_end) = @_;
662 # We use a file to register allocated ports.
663 # Those registrations expires after $expiretime.
664 # We use this to avoid race conditions between
665 # allocation and use of ports.
667 my $filename = "/var/tmp/pve-reserved-ports";
676 if (my $fh = IO
::File-
>new ($filename, "r")) {
677 while (my $line = <$fh>) {
678 if ($line =~ m/^(\d+)\s(\d+)$/) {
679 my ($port, $timestamp) = ($1, $2);
680 if (($timestamp + $expiretime) > $ctime) {
681 $ports->{$port} = $timestamp; # not expired
689 for (my $p = $range_start; $p < $range_end; $p++) {
690 next if $ports->{$p}; # reserved
692 my $sock = IO
::Socket
::INET-
>new(Listen
=> 5,
693 LocalAddr
=> 'localhost',
701 $ports->{$p} = $ctime;
707 foreach my $p (keys %$ports) {
708 $data .= "$p $ports->{$p}\n";
711 file_set_contents
($filename, $data);
716 my $p = lock_file
($filename, 10, $code);
719 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
724 sub next_migrate_port
{
725 return next_unused_port
(60000, 60010);
729 return next_unused_port
(5900, 6000);
732 sub next_spice_port
{
733 return next_unused_port
(61000, 61099);
736 # NOTE: NFS syscall can't be interrupted, so alarm does
737 # not work to provide timeouts.
738 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
739 # So the spawn external 'df' process instead of using
740 # Filesys::Df (which uses statfs syscall)
742 my ($path, $timeout) = @_;
744 my $cmd = [ 'df', '-P', '-B', '1', $path];
754 if (my ($fsid, $total, $used, $avail) = $line =~
755 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
763 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
770 # We use this to uniquely identify a process.
771 # An 'Unique Process ID' has the following format:
772 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
777 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
778 # more that 8 characters for pstart
779 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
780 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
785 my ($upid, $noerr) = @_;
790 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
791 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
792 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,9}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/) {
794 $res->{pid
} = hex($3);
795 $res->{pstart
} = hex($4);
796 $res->{starttime
} = hex($5);
801 my $subdir = substr($5, 7, 8);
802 $filename = "$pvetaskdir/$subdir/$upid";
805 return undef if $noerr;
806 die "unable to parse worker upid '$upid'\n";
809 return wantarray ?
($res, $filename) : $res;
815 my ($task, $filename) = upid_decode
($upid);
817 my $dirname = dirname
($filename);
820 my $wwwid = getpwnam('www-data') ||
821 die "getpwnam failed";
825 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
826 die "unable to create output file '$filename' - $!\n";
827 chown $wwwid, -1, $outfh;
832 sub upid_read_status
{
835 my ($task, $filename) = upid_decode
($upid);
836 my $fh = IO
::File-
>new($filename, "r");
837 return "unable to open file - $!" if !$fh;
839 sysseek($fh, -$maxlen, 2);
841 my $br = sysread($fh, $readbuf, $maxlen);
844 return "unable to extract last line"
845 if $readbuf !~ m/\n?(.+)$/;
847 if ($line =~ m/^TASK OK$/) {
849 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
852 return "unexpected status";
855 return "unable to read tail (got $br bytes)";
858 # useful functions to store comments in config files
862 # all control and hi-bit characters, and ':'
863 my $unsafe = "^\x20-\x39\x3b-\x7e";
864 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
870 return Encode
::decode
("utf8", uri_unescape
($data));
873 sub decode_utf8_parameters
{
876 foreach my $p (qw(comment description firstname lastname)) {
877 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
883 sub random_ether_addr
{
885 my $rand = Digest
::SHA
::sha1_hex
(rand(), time());
888 for (my $i = 0; $i < 6; $i++) {
889 my $ss = hex(substr($rand, $i*2, 2));
891 $ss &= 0xfe; # clear multicast
892 $ss |= 2; # set local id
894 $ss = sprintf("%02X", $ss);
909 return String
::ShellQuote
::shell_quote
($str);
915 die "no arguments" if !$cmd;
917 return $cmd if !ref($cmd);
920 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
922 return join (' ', @qa);
925 # split an shell argument string into an array,
929 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
933 my ($filename, $start, $limit) = @_;
938 my $fh = IO
::File-
>new($filename, "r");
941 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
942 return ($count, $lines);
945 $start = 0 if !$start;
946 $limit = 50 if !$limit;
949 while (defined($line = <$fh>)) {
950 next if $count++ < $start;
953 push @$lines, { n
=> $count, t
=> $line};
959 # HACK: ExtJS store.guaranteeRange() does not like empty array
963 push @$lines, { n
=> $count, t
=> "no content"};
966 return ($count, $lines);
970 my ($dir, $regex) = @_;
972 my $dh = IO
::Dir-
>new ($dir);
973 return wantarray ?
() : undef if !$dh;
975 while (defined(my $tmp = $dh->read)) {
976 if (my @res = $tmp =~ m/^($regex)$/) {
978 return wantarray ?
@res : $tmp;
983 return wantarray ?
() : undef;
986 sub dir_glob_foreach
{
987 my ($dir, $regex, $func) = @_;
989 my $dh = IO
::Dir-
>new ($dir);
991 while (defined(my $tmp = $dh->read)) {
992 if (my @res = $tmp =~ m/^($regex)$/) {