]> git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
4c4e25958ad38336ae44b05cce672d9bbbc76f22
[pve-common.git] / data / PVE / Tools.pm
1 package PVE::Tools;
2
3 use strict;
4 use POSIX;
5 use IO::Socket::INET;
6 use IO::Select;
7 use File::Basename;
8 use File::Path qw(make_path);
9 use IO::File;
10 use IPC::Open3;
11 use Fcntl qw(:DEFAULT :flock);
12 use base 'Exporter';
13 use URI::Escape;
14 use Encode;
15 use Digest::SHA1;
16
17 our @EXPORT_OK = qw(
18 lock_file
19 run_command
20 file_set_contents
21 file_get_contents
22 file_read_firstline
23 split_list
24 template_replace
25 safe_print
26 trim
27 extract_param
28 );
29
30 my $pvelogdir = "/var/log/pve";
31 my $pvetaskdir = "$pvelogdir/tasks";
32
33 mkdir $pvelogdir;
34 mkdir $pvetaskdir;
35
36 # flock: we use one file handle per process, so lock file
37 # can be called multiple times and succeeds for the same process.
38
39 my $lock_handles = {};
40
41 sub lock_file {
42 my ($filename, $timeout, $code, @param) = @_;
43
44 my $res;
45
46 $timeout = 10 if !$timeout;
47
48 eval {
49
50 local $SIG{ALRM} = sub { die "got timeout (can't lock '$filename')\n"; };
51
52 alarm ($timeout);
53
54 if (!$lock_handles->{$$}->{$filename}) {
55 $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") ||
56 die "can't open lock file '$filename' - $!\n";
57 }
58
59 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX|LOCK_NB)) {
60 print STDERR "trying to aquire lock...";
61 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX)) {
62 print STDERR " failed\n";
63 die "can't aquire lock for '$filename' - $!\n";
64 }
65 print STDERR " OK\n";
66 }
67 alarm (0);
68
69 $res = &$code(@param);
70 };
71
72 my $err = $@;
73
74 alarm (0);
75
76 if ($lock_handles->{$$}->{$filename}) {
77 my $fh = $lock_handles->{$$}->{$filename};
78 $lock_handles->{$$}->{$filename} = undef;
79 close ($fh);
80 }
81
82 if ($err) {
83 $@ = $err;
84 return undef;
85 }
86
87 $@ = undef;
88
89 return $res;
90 }
91
92 sub file_set_contents {
93 my ($filename, $data, $perm) = @_;
94
95 $perm = 0644 if !defined($perm);
96
97 my $tmpname = "$filename.tmp.$$";
98
99 eval {
100 my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm);
101 die "unable to open file '$tmpname' - $!\n" if !$fh;
102 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
103 die "closing file '$tmpname' failed - $!\n" unless close $fh;
104 };
105 my $err = $@;
106
107 if ($err) {
108 unlink $tmpname;
109 die $err;
110 }
111
112 if (!rename($tmpname, $filename)) {
113 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
114 unlink $tmpname;
115 die $msg;
116 }
117 }
118
119 sub file_get_contents {
120 my ($filename, $max) = @_;
121
122 my $fh = IO::File->new($filename, "r") ||
123 die "can't open '$filename' - $!\n";
124
125 my $content = safe_read_from($fh, $max);
126
127 close $fh;
128
129 return $content;
130 }
131
132 sub file_read_firstline {
133 my ($filename) = @_;
134
135 my $fh = IO::File->new ($filename, "r");
136 return undef if !$fh;
137 my $res = <$fh>;
138 chomp $res;
139 $fh->close;
140 return $res;
141 }
142
143 sub safe_read_from {
144 my ($fh, $max, $oneline) = @_;
145
146 $max = 32768 if !$max;
147
148 my $br = 0;
149 my $input = '';
150 my $count;
151 while ($count = sysread($fh, $input, 8192, $br)) {
152 $br += $count;
153 die "input too long - aborting\n" if $br > $max;
154 if ($oneline && $input =~ m/^(.*)\n/) {
155 $input = $1;
156 last;
157 }
158 }
159 die "unable to read input - $!\n" if !defined($count);
160
161 return $input;
162 }
163
164 sub run_command {
165 my ($cmd, %param) = @_;
166
167 my $old_umask;
168
169 $cmd = [ $cmd ] if !ref($cmd);
170
171 my $cmdstr = join (' ', @$cmd);
172
173 my $errmsg;
174 my $laststderr;
175 my $timeout;
176 my $oldtimeout;
177 my $pid;
178
179 eval {
180 my $input;
181 my $output;
182 my $outfunc;
183 my $errfunc;
184 my $logfunc;
185
186 foreach my $p (keys %param) {
187 if ($p eq 'timeout') {
188 $timeout = $param{$p};
189 } elsif ($p eq 'umask') {
190 umask($param{$p});
191 } elsif ($p eq 'errmsg') {
192 $errmsg = $param{$p};
193 $errfunc = sub {
194 print STDERR "$laststderr\n" if $laststderr;
195 $laststderr = shift;
196 };
197 } elsif ($p eq 'input') {
198 $input = $param{$p};
199 } elsif ($p eq 'output') {
200 $output = $param{$p};
201 } elsif ($p eq 'outfunc') {
202 $outfunc = $param{$p};
203 } elsif ($p eq 'errfunc') {
204 $errfunc = $param{$p};
205 } elsif ($p eq 'logfunc') {
206 $logfunc = $param{$p};
207 } else {
208 die "got unknown parameter '$p' for run_command\n";
209 }
210 }
211
212 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
213 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
214 my $error = IO::File->new();
215
216 # try to avoid locale related issues/warnings
217 my $lang = $param{lang} || 'C';
218
219 my $orig_pid = $$;
220
221 eval {
222 local $ENV{LC_ALL} = $lang;
223
224 # suppress LVM warnings like: "File descriptor 3 left open";
225 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
226
227 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
228
229 # if we pipe fron STDIN, open3 closes STDIN, so we we
230 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
231 # as soon as we open a new file.
232 # to avoid that we open /dev/null
233 if (!ref($writer) && !defined(fileno(STDIN))) {
234 POSIX::close(0);
235 open(STDIN, "</dev/null");
236 }
237 };
238
239 my $err = $@;
240
241 # catch exec errors
242 if ($orig_pid != $$) {
243 warn "ERROR: $err";
244 POSIX::_exit (1);
245 kill ('KILL', $$);
246 }
247
248 die $err if $err;
249
250 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
251 $oldtimeout = alarm($timeout) if $timeout;
252
253 if (ref($writer)) {
254 print $writer $input if defined $input;
255 close $writer;
256 }
257
258 my $select = new IO::Select;
259 $select->add($reader) if ref($reader);
260 $select->add($error);
261
262 my $outlog = '';
263 my $errlog = '';
264
265 my $starttime = time();
266
267 while ($select->count) {
268 my @handles = $select->can_read(1);
269
270 foreach my $h (@handles) {
271 my $buf = '';
272 my $count = sysread ($h, $buf, 4096);
273 if (!defined ($count)) {
274 my $err = $!;
275 kill (9, $pid);
276 waitpid ($pid, 0);
277 die $err;
278 }
279 $select->remove ($h) if !$count;
280 if ($h eq $reader) {
281 if ($outfunc || $logfunc) {
282 eval {
283 $outlog .= $buf;
284 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
285 my $line = $1;
286 &$outfunc($line) if $outfunc;
287 &$logfunc($line) if $logfunc;
288 }
289 };
290 my $err = $@;
291 if ($err) {
292 kill (9, $pid);
293 waitpid ($pid, 0);
294 die $err;
295 }
296 } else {
297 print $buf;
298 *STDOUT->flush();
299 }
300 } elsif ($h eq $error) {
301 if ($errfunc || $logfunc) {
302 eval {
303 $errlog .= $buf;
304 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
305 my $line = $1;
306 &$errfunc($line) if $errfunc;
307 &$logfunc($line) if $logfunc;
308 }
309 };
310 my $err = $@;
311 if ($err) {
312 kill (9, $pid);
313 waitpid ($pid, 0);
314 die $err;
315 }
316 } else {
317 print STDERR $buf;
318 *STDERR->flush();
319 }
320 }
321 }
322 }
323
324 &$outfunc($outlog) if $outfunc && $outlog;
325 &$logfunc($outlog) if $logfunc && $outlog;
326
327 &$errfunc($errlog) if $errfunc && $errlog;
328 &$logfunc($errlog) if $logfunc && $errlog;
329
330 waitpid ($pid, 0);
331
332 if ($? == -1) {
333 die "failed to execute\n";
334 } elsif (my $sig = ($? & 127)) {
335 die "got signal $sig\n";
336 } elsif (my $ec = ($? >> 8)) {
337 if (!($ec == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
338 if ($errmsg && $laststderr) {
339 my $lerr = $laststderr;
340 $laststderr = undef;
341 die "$lerr\n";
342 }
343 die "exit code $ec\n";
344 }
345 }
346
347 alarm(0);
348 };
349
350 my $err = $@;
351
352 alarm(0);
353
354 print STDERR "$laststderr\n" if $laststderr;
355
356 umask ($old_umask) if defined($old_umask);
357
358 alarm($oldtimeout) if $oldtimeout;
359
360 if ($err) {
361 if ($pid && ($err eq "got timeout\n")) {
362 kill (9, $pid);
363 waitpid ($pid, 0);
364 die "command '$cmdstr' failed: $err";
365 }
366
367 if ($errmsg) {
368 die "$errmsg: $err";
369 } else {
370 die "command '$cmdstr' failed: $err";
371 }
372 }
373
374 return undef;
375 }
376
377 sub split_list {
378 my $listtxt = shift || '';
379
380 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
381
382 $listtxt =~ s/[,;]/ /g;
383 $listtxt =~ s/^\s+//;
384
385 my @data = split (/\s+/, $listtxt);
386
387 return @data;
388 }
389
390 sub trim {
391 my $txt = shift;
392
393 return $txt if !defined($txt);
394
395 $txt =~ s/^\s+//;
396 $txt =~ s/\s+$//;
397
398 return $txt;
399 }
400
401 # simple uri templates like "/vms/{vmid}"
402 sub template_replace {
403 my ($tmpl, $data) = @_;
404
405 my $res = '';
406 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
407 $res .= $1 if $1;
408 $res .= ($data->{$3} || '-') if $2;
409 }
410 return $res;
411 }
412
413 sub safe_print {
414 my ($filename, $fh, $data) = @_;
415
416 return if !$data;
417
418 my $res = print $fh $data;
419
420 die "write to '$filename' failed\n" if !$res;
421 }
422
423 sub debmirrors {
424
425 return {
426 'at' => 'ftp.at.debian.org',
427 'au' => 'ftp.au.debian.org',
428 'be' => 'ftp.be.debian.org',
429 'bg' => 'ftp.bg.debian.org',
430 'br' => 'ftp.br.debian.org',
431 'ca' => 'ftp.ca.debian.org',
432 'ch' => 'ftp.ch.debian.org',
433 'cl' => 'ftp.cl.debian.org',
434 'cz' => 'ftp.cz.debian.org',
435 'de' => 'ftp.de.debian.org',
436 'dk' => 'ftp.dk.debian.org',
437 'ee' => 'ftp.ee.debian.org',
438 'es' => 'ftp.es.debian.org',
439 'fi' => 'ftp.fi.debian.org',
440 'fr' => 'ftp.fr.debian.org',
441 'gr' => 'ftp.gr.debian.org',
442 'hk' => 'ftp.hk.debian.org',
443 'hr' => 'ftp.hr.debian.org',
444 'hu' => 'ftp.hu.debian.org',
445 'ie' => 'ftp.ie.debian.org',
446 'is' => 'ftp.is.debian.org',
447 'it' => 'ftp.it.debian.org',
448 'jp' => 'ftp.jp.debian.org',
449 'kr' => 'ftp.kr.debian.org',
450 'mx' => 'ftp.mx.debian.org',
451 'nl' => 'ftp.nl.debian.org',
452 'no' => 'ftp.no.debian.org',
453 'nz' => 'ftp.nz.debian.org',
454 'pl' => 'ftp.pl.debian.org',
455 'pt' => 'ftp.pt.debian.org',
456 'ro' => 'ftp.ro.debian.org',
457 'ru' => 'ftp.ru.debian.org',
458 'se' => 'ftp.se.debian.org',
459 'si' => 'ftp.si.debian.org',
460 'sk' => 'ftp.sk.debian.org',
461 'tr' => 'ftp.tr.debian.org',
462 'tw' => 'ftp.tw.debian.org',
463 'gb' => 'ftp.uk.debian.org',
464 'us' => 'ftp.us.debian.org',
465 };
466 }
467
468 sub kvmkeymaps {
469 return {
470 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
471 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
472 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
473 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
474 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
475 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
476 #'et' => [], # Ethopia or Estonia ??
477 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
478 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
479 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
480 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
481 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
482 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
483 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
484 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
485 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
486 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
487 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
488 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
489 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
490 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
491 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
492 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
493 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
494 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
495 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
496 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
497 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
498 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
499 #'sv' => [], Swedish ?
500 #'th' => [],
501 #'tr' => [],
502 };
503 }
504
505 sub extract_param {
506 my ($param, $key) = @_;
507
508 my $res = $param->{$key};
509 delete $param->{$key};
510
511 return $res;
512 }
513
514 sub next_vnc_port {
515
516 for (my $p = 5900; $p < 6000; $p++) {
517
518 my $sock = IO::Socket::INET->new (Listen => 5,
519 LocalAddr => 'localhost',
520 LocalPort => $p,
521 ReuseAddr => 1,
522 Proto => 0);
523
524 if ($sock) {
525 close ($sock);
526 return $p;
527 }
528 }
529
530 die "unable to find free vnc port";
531 };
532
533 # NOTE: NFS syscall can't be interrupted, so alarm does
534 # not work to provide timeouts.
535 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
536 # So the spawn external 'df' process instead of using
537 # Filesys::Df (which uses statfs syscall)
538 sub df {
539 my ($path, $timeout) = @_;
540
541 my $cmd = [ 'df', '-P', '-B', '1', $path];
542
543 my $res = {
544 total => 0,
545 used => 0,
546 avail => 0,
547 };
548
549 my $parser = sub {
550 my $line = shift;
551 if (my ($fsid, $total, $used, $avail) = $line =~
552 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
553 $res = {
554 total => $total,
555 used => $used,
556 avail => $avail,
557 };
558 }
559 };
560 eval { run_command($cmd, timeout => $timeout, outfunc => $parser); };
561 warn $@ if $@;
562
563 return $res;
564 }
565
566 # UPID helper
567 # We use this to uniquely identify a process.
568 # An 'Unique Process ID' has the following format:
569 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
570
571 sub upid_encode {
572 my $d = shift;
573
574 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
575 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
576 $d->{user});
577 }
578
579 sub upid_decode {
580 my ($upid, $noerr) = @_;
581
582 my $res;
583 my $filename;
584
585 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
586 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]+):$/) {
587 $res->{node} = $1;
588 $res->{pid} = hex($2);
589 $res->{pstart} = hex($3);
590 $res->{starttime} = hex($4);
591 $res->{type} = $5;
592 $res->{id} = $6;
593 $res->{user} = $7;
594
595 my $subdir = substr($4, 7, 8);
596 $filename = "$pvetaskdir/$subdir/$upid";
597
598 } else {
599 return undef if $noerr;
600 die "unable to parse worker upid '$upid'\n";
601 }
602
603 return wantarray ? ($res, $filename) : $res;
604 }
605
606 sub upid_open {
607 my ($upid) = @_;
608
609 my ($task, $filename) = upid_decode($upid);
610
611 my $dirname = dirname($filename);
612 make_path($dirname);
613
614 my $wwwid = getpwnam('www-data') ||
615 die "getpwnam failed";
616
617 my $perm = 0640;
618
619 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
620 die "unable to create output file '$filename' - $!\n";
621 chown $wwwid, $outfh;
622
623 return $outfh;
624 };
625
626 sub upid_read_status {
627 my ($upid) = @_;
628
629 my ($task, $filename) = upid_decode($upid);
630 my $fh = IO::File->new($filename, "r");
631 return "unable to open file - $!" if !$fh;
632 my $maxlen = 1024;
633 sysseek($fh, -$maxlen, 2);
634 my $readbuf = '';
635 my $br = sysread($fh, $readbuf, $maxlen);
636 close($fh);
637 if ($br) {
638 return "unable to extract last line"
639 if $readbuf !~ m/\n?(.+)$/;
640 my $line = $1;
641 if ($line =~ m/^TASK OK$/) {
642 return 'OK';
643 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
644 return $1;
645 } else {
646 return "unexpected status";
647 }
648 }
649 return "unable to read tail (got $br bytes)";
650 }
651
652 # useful functions to store comments in config files
653 sub encode_text {
654 my ($text) = @_;
655
656 # all control and hi-bit characters, and ':'
657 my $unsafe = "^\x20-\x39\x3b-\x7e";
658 return uri_escape(Encode::encode("utf8", $text), $unsafe);
659 }
660
661 sub decode_text {
662 my ($data) = @_;
663
664 return Encode::decode("utf8", uri_unescape($data));
665 }
666
667 sub random_ether_addr {
668
669 my $rand = Digest::SHA1::sha1_hex(rand(), time());
670
671 my $mac = '';
672 for (my $i = 0; $i < 6; $i++) {
673 my $ss = hex(substr($rand, $i*2, 2));
674 if (!$i) {
675 $ss &= 0xfe; # clear multicast
676 $ss |= 2; # set local id
677 }
678 $ss = sprintf("%02X", $ss);
679
680 if (!$i) {
681 $mac .= "$ss";
682 } else {
683 $mac .= ":$ss";
684 }
685 }
686
687 return $mac;
688 }
689
690 1;