]> git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
fix typo
[pve-common.git] / data / PVE / Tools.pm
1 package PVE::Tools;
2
3 use strict;
4 use warnings;
5 use POSIX qw(EINTR);
6 use IO::Socket::INET;
7 use IO::Select;
8 use File::Basename;
9 use File::Path qw(make_path);
10 use IO::File;
11 use IO::Dir;
12 use IPC::Open3;
13 use Fcntl qw(:DEFAULT :flock);
14 use base 'Exporter';
15 use URI::Escape;
16 use Encode;
17 use Digest::SHA;
18 use Text::ParseWords;
19 use String::ShellQuote;
20 use Time::HiRes qw(usleep gettimeofday tv_interval);
21
22 our @EXPORT_OK = qw(
23 $IPV6RE
24 $IPV4RE
25 lock_file
26 lock_file_full
27 run_command
28 file_set_contents
29 file_get_contents
30 file_read_firstline
31 dir_glob_regex
32 dir_glob_foreach
33 split_list
34 template_replace
35 safe_print
36 trim
37 extract_param
38 );
39
40 my $pvelogdir = "/var/log/pve";
41 my $pvetaskdir = "$pvelogdir/tasks";
42
43 mkdir $pvelogdir;
44 mkdir $pvetaskdir;
45
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))";
50
51 our $IPV6RE = "(?:" .
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)?::" . ")))";
61
62 sub run_with_timeout {
63 my ($timeout, $code, @param) = @_;
64
65 die "got timeout\n" if $timeout <= 0;
66
67 my $prev_alarm;
68
69 my $sigcount = 0;
70
71 my $res;
72
73 local $SIG{ALRM} = sub { $sigcount++; }; # catch alarm outside eval
74
75 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
79
80 $prev_alarm = alarm($timeout);
81
82 $res = &$code(@param);
83
84 alarm(0); # avoid race conditions
85 };
86
87 my $err = $@;
88
89 alarm($prev_alarm) if defined($prev_alarm);
90
91 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
92
93 die $err if $err;
94
95 return $res;
96 }
97
98 # flock: we use one file handle per process, so lock file
99 # can be called multiple times and succeeds for the same process.
100
101 my $lock_handles = {};
102
103 sub lock_file_full {
104 my ($filename, $timeout, $shared, $code, @param) = @_;
105
106 $timeout = 10 if !$timeout;
107
108 my $mode = $shared ? LOCK_SH : LOCK_EX;
109
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";
114 }
115
116 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB)) {
117 print STDERR "trying to aquire lock...";
118 my $success;
119 while(1) {
120 $success = flock($lock_handles->{$$}->{$filename}, $mode);
121 # try again on EINTR (see bug #273)
122 if ($success || ($! != EINTR)) {
123 last;
124 }
125 }
126 if (!$success) {
127 print STDERR " failed\n";
128 die "can't aquire lock - $!\n";
129 }
130 print STDERR " OK\n";
131 }
132 };
133
134 my $res;
135
136 eval { run_with_timeout($timeout, $lock_func); };
137 my $err = $@;
138 if ($err) {
139 $err = "can't lock file '$filename' - $err";
140 } else {
141 eval { $res = &$code(@param) };
142 $err = $@;
143 }
144
145 if ($lock_handles->{$$}->{$filename}) {
146 my $fh = $lock_handles->{$$}->{$filename};
147 $lock_handles->{$$}->{$filename} = undef;
148 close ($fh);
149 }
150
151 if ($err) {
152 $@ = $err;
153 return undef;
154 }
155
156 $@ = undef;
157
158 return $res;
159 }
160
161
162 sub lock_file {
163 my ($filename, $timeout, $code, @param) = @_;
164
165 return lock_file_full($filename, $timeout, 0, $code, @param);
166 }
167
168 sub file_set_contents {
169 my ($filename, $data, $perm) = @_;
170
171 $perm = 0644 if !defined($perm);
172
173 my $tmpname = "$filename.tmp.$$";
174
175 eval {
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;
180 };
181 my $err = $@;
182
183 if ($err) {
184 unlink $tmpname;
185 die $err;
186 }
187
188 if (!rename($tmpname, $filename)) {
189 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
190 unlink $tmpname;
191 die $msg;
192 }
193 }
194
195 sub file_get_contents {
196 my ($filename, $max) = @_;
197
198 my $fh = IO::File->new($filename, "r") ||
199 die "can't open '$filename' - $!\n";
200
201 my $content = safe_read_from($fh, $max);
202
203 close $fh;
204
205 return $content;
206 }
207
208 sub file_read_firstline {
209 my ($filename) = @_;
210
211 my $fh = IO::File->new ($filename, "r");
212 return undef if !$fh;
213 my $res = <$fh>;
214 chomp $res if $res;
215 $fh->close;
216 return $res;
217 }
218
219 sub safe_read_from {
220 my ($fh, $max, $oneline) = @_;
221
222 $max = 32768 if !$max;
223
224 my $br = 0;
225 my $input = '';
226 my $count;
227 while ($count = sysread($fh, $input, 8192, $br)) {
228 $br += $count;
229 die "input too long - aborting\n" if $br > $max;
230 if ($oneline && $input =~ m/^(.*)\n/) {
231 $input = $1;
232 last;
233 }
234 }
235 die "unable to read input - $!\n" if !defined($count);
236
237 return $input;
238 }
239
240 sub run_command {
241 my ($cmd, %param) = @_;
242
243 my $old_umask;
244 my $cmdstr;
245
246 if (!ref($cmd)) {
247 $cmdstr = $cmd;
248 if ($cmd =~ m/|/) {
249 # see 'man bash' for option pipefail
250 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
251 } else {
252 $cmd = [ $cmd ];
253 }
254 } else {
255 $cmdstr = cmd2string($cmd);
256 }
257
258 my $errmsg;
259 my $laststderr;
260 my $timeout;
261 my $oldtimeout;
262 my $pid;
263
264 my $outfunc;
265 my $errfunc;
266 my $logfunc;
267 my $input;
268 my $output;
269 my $afterfork;
270
271 eval {
272
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') {
281 $input = $param{$p};
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};
292 } else {
293 die "got unknown parameter '$p' for run_command\n";
294 }
295 }
296
297 if ($errmsg) {
298 my $origerrfunc = $errfunc;
299 $errfunc = sub {
300 if ($laststderr) {
301 if ($origerrfunc) {
302 &$origerrfunc("$laststderr\n");
303 } else {
304 print STDERR "$laststderr\n" if $laststderr;
305 }
306 }
307 $laststderr = shift;
308 };
309 }
310
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();
314
315 # try to avoid locale related issues/warnings
316 my $lang = $param{lang} || 'C';
317
318 my $orig_pid = $$;
319
320 eval {
321 local $ENV{LC_ALL} = $lang;
322
323 # suppress LVM warnings like: "File descriptor 3 left open";
324 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
325
326 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
327
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))) {
333 POSIX::close(0);
334 open(STDIN, "</dev/null");
335 }
336 };
337
338 my $err = $@;
339
340 # catch exec errors
341 if ($orig_pid != $$) {
342 warn "ERROR: $err";
343 POSIX::_exit (1);
344 kill ('KILL', $$);
345 }
346
347 die $err if $err;
348
349 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
350 $oldtimeout = alarm($timeout) if $timeout;
351
352 &$afterfork() if $afterfork;
353
354 if (ref($writer)) {
355 print $writer $input if defined $input;
356 close $writer;
357 }
358
359 my $select = new IO::Select;
360 $select->add($reader) if ref($reader);
361 $select->add($error);
362
363 my $outlog = '';
364 my $errlog = '';
365
366 my $starttime = time();
367
368 while ($select->count) {
369 my @handles = $select->can_read(1);
370
371 foreach my $h (@handles) {
372 my $buf = '';
373 my $count = sysread ($h, $buf, 4096);
374 if (!defined ($count)) {
375 my $err = $!;
376 kill (9, $pid);
377 waitpid ($pid, 0);
378 die $err;
379 }
380 $select->remove ($h) if !$count;
381 if ($h eq $reader) {
382 if ($outfunc || $logfunc) {
383 eval {
384 $outlog .= $buf;
385 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
386 my $line = $1;
387 &$outfunc($line) if $outfunc;
388 &$logfunc($line) if $logfunc;
389 }
390 };
391 my $err = $@;
392 if ($err) {
393 kill (9, $pid);
394 waitpid ($pid, 0);
395 die $err;
396 }
397 } else {
398 print $buf;
399 *STDOUT->flush();
400 }
401 } elsif ($h eq $error) {
402 if ($errfunc || $logfunc) {
403 eval {
404 $errlog .= $buf;
405 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
406 my $line = $1;
407 &$errfunc($line) if $errfunc;
408 &$logfunc($line) if $logfunc;
409 }
410 };
411 my $err = $@;
412 if ($err) {
413 kill (9, $pid);
414 waitpid ($pid, 0);
415 die $err;
416 }
417 } else {
418 print STDERR $buf;
419 *STDERR->flush();
420 }
421 }
422 }
423 }
424
425 &$outfunc($outlog) if $outfunc && $outlog;
426 &$logfunc($outlog) if $logfunc && $outlog;
427
428 &$errfunc($errlog) if $errfunc && $errlog;
429 &$logfunc($errlog) if $logfunc && $errlog;
430
431 waitpid ($pid, 0);
432
433 if ($? == -1) {
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;
441 $laststderr = undef;
442 die "$lerr\n";
443 }
444 die "exit code $ec\n";
445 }
446 }
447
448 alarm(0);
449 };
450
451 my $err = $@;
452
453 alarm(0);
454
455 if ($errmsg && $laststderr) {
456 &$errfunc(undef); # flush laststderr
457 }
458
459 umask ($old_umask) if defined($old_umask);
460
461 alarm($oldtimeout) if $oldtimeout;
462
463 if ($err) {
464 if ($pid && ($err eq "got timeout\n")) {
465 kill (9, $pid);
466 waitpid ($pid, 0);
467 die "command '$cmdstr' failed: $err";
468 }
469
470 if ($errmsg) {
471 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
472 die "$errmsg: $err";
473 } else {
474 die "command '$cmdstr' failed: $err";
475 }
476 }
477
478 return undef;
479 }
480
481 sub split_list {
482 my $listtxt = shift || '';
483
484 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
485
486 $listtxt =~ s/[,;]/ /g;
487 $listtxt =~ s/^\s+//;
488
489 my @data = split (/\s+/, $listtxt);
490
491 return @data;
492 }
493
494 sub trim {
495 my $txt = shift;
496
497 return $txt if !defined($txt);
498
499 $txt =~ s/^\s+//;
500 $txt =~ s/\s+$//;
501
502 return $txt;
503 }
504
505 # simple uri templates like "/vms/{vmid}"
506 sub template_replace {
507 my ($tmpl, $data) = @_;
508
509 return $tmpl if !$tmpl;
510
511 my $res = '';
512 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
513 $res .= $1 if $1;
514 $res .= ($data->{$3} || '-') if $2;
515 }
516 return $res;
517 }
518
519 sub safe_print {
520 my ($filename, $fh, $data) = @_;
521
522 return if !$data;
523
524 my $res = print $fh $data;
525
526 die "write to '$filename' failed\n" if !$res;
527 }
528
529 sub debmirrors {
530
531 return {
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',
571 };
572 }
573
574 my $keymaphash = {
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'],
605 #'th' => [],
606 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
607 };
608
609 my $kvmkeymaparray = [];
610 foreach my $lc (keys %$keymaphash) {
611 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
612 }
613
614 sub kvmkeymaps {
615 return $keymaphash;
616 }
617
618 sub kvmkeymaplist {
619 return $kvmkeymaparray;
620 }
621
622 sub extract_param {
623 my ($param, $key) = @_;
624
625 my $res = $param->{$key};
626 delete $param->{$key};
627
628 return $res;
629 }
630
631 # Note: we use this to wait until vncterm/spiceterm is ready
632 sub wait_for_vnc_port {
633 my ($port, $timeout) = @_;
634
635 $timeout = 5 if !$timeout;
636 my $sleeptime = 0;
637 my $starttime = [gettimeofday];
638 my $elapsed;
639
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)) {
645 close($fh);
646 return 1;
647 }
648 }
649 }
650 close($fh);
651 }
652 $sleeptime += 100000 if $sleeptime < 1000000;
653 usleep($sleeptime);
654 }
655
656 return undef;
657 }
658
659 sub next_unused_port {
660 my ($range_start, $range_end) = @_;
661
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.
666
667 my $filename = "/var/tmp/pve-reserved-ports";
668
669 my $code = sub {
670
671 my $expiretime = 5;
672 my $ctime = time();
673
674 my $ports = {};
675
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
682 }
683 }
684 }
685 }
686
687 my $newport;
688
689 for (my $p = $range_start; $p < $range_end; $p++) {
690 next if $ports->{$p}; # reserved
691
692 my $sock = IO::Socket::INET->new(Listen => 5,
693 LocalAddr => 'localhost',
694 LocalPort => $p,
695 ReuseAddr => 1,
696 Proto => 0);
697
698 if ($sock) {
699 close($sock);
700 $newport = $p;
701 $ports->{$p} = $ctime;
702 last;
703 }
704 }
705
706 my $data = "";
707 foreach my $p (keys %$ports) {
708 $data .= "$p $ports->{$p}\n";
709 }
710
711 file_set_contents($filename, $data);
712
713 return $newport;
714 };
715
716 my $p = lock_file($filename, 10, $code);
717 die $@ if $@;
718
719 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
720
721 return $p;
722 }
723
724 sub next_migrate_port {
725 return next_unused_port(60000, 60010);
726 }
727
728 sub next_vnc_port {
729 return next_unused_port(5900, 6000);
730 }
731
732 sub next_spice_port {
733 return next_unused_port(61000, 61099);
734 }
735
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)
741 sub df {
742 my ($path, $timeout) = @_;
743
744 my $cmd = [ 'df', '-P', '-B', '1', $path];
745
746 my $res = {
747 total => 0,
748 used => 0,
749 avail => 0,
750 };
751
752 my $parser = sub {
753 my $line = shift;
754 if (my ($fsid, $total, $used, $avail) = $line =~
755 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
756 $res = {
757 total => $total,
758 used => $used,
759 avail => $avail,
760 };
761 }
762 };
763 eval { run_command($cmd, timeout => $timeout, outfunc => $parser); };
764 warn $@ if $@;
765
766 return $res;
767 }
768
769 # UPID helper
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"
773
774 sub upid_encode {
775 my $d = shift;
776
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},
781 $d->{user});
782 }
783
784 sub upid_decode {
785 my ($upid, $noerr) = @_;
786
787 my $res;
788 my $filename;
789
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]+):$/) {
793 $res->{node} = $1;
794 $res->{pid} = hex($3);
795 $res->{pstart} = hex($4);
796 $res->{starttime} = hex($5);
797 $res->{type} = $6;
798 $res->{id} = $7;
799 $res->{user} = $8;
800
801 my $subdir = substr($5, 7, 8);
802 $filename = "$pvetaskdir/$subdir/$upid";
803
804 } else {
805 return undef if $noerr;
806 die "unable to parse worker upid '$upid'\n";
807 }
808
809 return wantarray ? ($res, $filename) : $res;
810 }
811
812 sub upid_open {
813 my ($upid) = @_;
814
815 my ($task, $filename) = upid_decode($upid);
816
817 my $dirname = dirname($filename);
818 make_path($dirname);
819
820 my $wwwid = getpwnam('www-data') ||
821 die "getpwnam failed";
822
823 my $perm = 0640;
824
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;
828
829 return $outfh;
830 };
831
832 sub upid_read_status {
833 my ($upid) = @_;
834
835 my ($task, $filename) = upid_decode($upid);
836 my $fh = IO::File->new($filename, "r");
837 return "unable to open file - $!" if !$fh;
838 my $maxlen = 4096;
839 sysseek($fh, -$maxlen, 2);
840 my $readbuf = '';
841 my $br = sysread($fh, $readbuf, $maxlen);
842 close($fh);
843 if ($br) {
844 return "unable to extract last line"
845 if $readbuf !~ m/\n?(.+)$/;
846 my $line = $1;
847 if ($line =~ m/^TASK OK$/) {
848 return 'OK';
849 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
850 return $1;
851 } else {
852 return "unexpected status";
853 }
854 }
855 return "unable to read tail (got $br bytes)";
856 }
857
858 # useful functions to store comments in config files
859 sub encode_text {
860 my ($text) = @_;
861
862 # all control and hi-bit characters, and ':'
863 my $unsafe = "^\x20-\x39\x3b-\x7e";
864 return uri_escape(Encode::encode("utf8", $text), $unsafe);
865 }
866
867 sub decode_text {
868 my ($data) = @_;
869
870 return Encode::decode("utf8", uri_unescape($data));
871 }
872
873 sub decode_utf8_parameters {
874 my ($param) = @_;
875
876 foreach my $p (qw(comment description firstname lastname)) {
877 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
878 }
879
880 return $param;
881 }
882
883 sub random_ether_addr {
884
885 my ($seconds, $microseconds) = gettimeofday;
886
887 my $rand = Digest::SHA::sha1_hex($$, rand(), $seconds, $microseconds);
888
889 my $mac = '';
890 for (my $i = 0; $i < 6; $i++) {
891 my $ss = hex(substr($rand, $i*2, 2));
892 if (!$i) {
893 $ss &= 0xfe; # clear multicast
894 $ss |= 2; # set local id
895 }
896 $ss = sprintf("%02X", $ss);
897
898 if (!$i) {
899 $mac .= "$ss";
900 } else {
901 $mac .= ":$ss";
902 }
903 }
904
905 return $mac;
906 }
907
908 sub shellquote {
909 my $str = shift;
910
911 return String::ShellQuote::shell_quote($str);
912 }
913
914 sub cmd2string {
915 my ($cmd) = @_;
916
917 die "no arguments" if !$cmd;
918
919 return $cmd if !ref($cmd);
920
921 my @qa = ();
922 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
923
924 return join (' ', @qa);
925 }
926
927 # split an shell argument string into an array,
928 sub split_args {
929 my ($str) = @_;
930
931 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
932 }
933
934 sub dump_logfile {
935 my ($filename, $start, $limit, $filter) = @_;
936
937 my $lines = [];
938 my $count = 0;
939
940 my $fh = IO::File->new($filename, "r");
941 if (!$fh) {
942 $count++;
943 push @$lines, { n => $count, t => "unable to open file - $!"};
944 return ($count, $lines);
945 }
946
947 $start = 0 if !$start;
948 $limit = 50 if !$limit;
949
950 my $line;
951
952 if ($filter) {
953 # duplicate code, so that we do not slow down normal path
954 while (defined($line = <$fh>)) {
955 next if $line !~ m/$filter/;
956 next if $count++ < $start;
957 next if $limit <= 0;
958 chomp $line;
959 push @$lines, { n => $count, t => $line};
960 $limit--;
961 }
962 } else {
963 while (defined($line = <$fh>)) {
964 next if $count++ < $start;
965 next if $limit <= 0;
966 chomp $line;
967 push @$lines, { n => $count, t => $line};
968 $limit--;
969 }
970 }
971
972 close($fh);
973
974 # HACK: ExtJS store.guaranteeRange() does not like empty array
975 # so we add a line
976 if (!$count) {
977 $count++;
978 push @$lines, { n => $count, t => "no content"};
979 }
980
981 return ($count, $lines);
982 }
983
984 sub dir_glob_regex {
985 my ($dir, $regex) = @_;
986
987 my $dh = IO::Dir->new ($dir);
988 return wantarray ? () : undef if !$dh;
989
990 while (defined(my $tmp = $dh->read)) {
991 if (my @res = $tmp =~ m/^($regex)$/) {
992 $dh->close;
993 return wantarray ? @res : $tmp;
994 }
995 }
996 $dh->close;
997
998 return wantarray ? () : undef;
999 }
1000
1001 sub dir_glob_foreach {
1002 my ($dir, $regex, $func) = @_;
1003
1004 my $dh = IO::Dir->new ($dir);
1005 if (defined $dh) {
1006 while (defined(my $tmp = $dh->read)) {
1007 if (my @res = $tmp =~ m/^($regex)$/) {
1008 &$func (@res);
1009 }
1010 }
1011 }
1012 }
1013
1014 sub assert_if_modified {
1015 my ($digest1, $digest2) = @_;
1016
1017 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1018 die "detected modified configuration - file changed by other user? Try again.\n";
1019 }
1020 }
1021
1022 1;