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