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