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