f399d77dbb4541116bb4ea68adf112cc6e46c79d
[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 # NOTE: NFS syscall can't be interrupted, so alarm does
733 # not work to provide timeouts.
734 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
735 # So the spawn external 'df' process instead of using
736 # Filesys::Df (which uses statfs syscall)
737 sub df {
738 my ($path, $timeout) = @_;
739
740 my $cmd = [ 'df', '-P', '-B', '1', $path];
741
742 my $res = {
743 total => 0,
744 used => 0,
745 avail => 0,
746 };
747
748 my $parser = sub {
749 my $line = shift;
750 if (my ($fsid, $total, $used, $avail) = $line =~
751 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
752 $res = {
753 total => $total,
754 used => $used,
755 avail => $avail,
756 };
757 }
758 };
759 eval { run_command($cmd, timeout => $timeout, outfunc => $parser); };
760 warn $@ if $@;
761
762 return $res;
763 }
764
765 # UPID helper
766 # We use this to uniquely identify a process.
767 # An 'Unique Process ID' has the following format:
768 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
769
770 sub upid_encode {
771 my $d = shift;
772
773 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
774 # more that 8 characters for pstart
775 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
776 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
777 $d->{user});
778 }
779
780 sub upid_decode {
781 my ($upid, $noerr) = @_;
782
783 my $res;
784 my $filename;
785
786 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
787 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
788 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]+):$/) {
789 $res->{node} = $1;
790 $res->{pid} = hex($3);
791 $res->{pstart} = hex($4);
792 $res->{starttime} = hex($5);
793 $res->{type} = $6;
794 $res->{id} = $7;
795 $res->{user} = $8;
796
797 my $subdir = substr($5, 7, 8);
798 $filename = "$pvetaskdir/$subdir/$upid";
799
800 } else {
801 return undef if $noerr;
802 die "unable to parse worker upid '$upid'\n";
803 }
804
805 return wantarray ? ($res, $filename) : $res;
806 }
807
808 sub upid_open {
809 my ($upid) = @_;
810
811 my ($task, $filename) = upid_decode($upid);
812
813 my $dirname = dirname($filename);
814 make_path($dirname);
815
816 my $wwwid = getpwnam('www-data') ||
817 die "getpwnam failed";
818
819 my $perm = 0640;
820
821 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
822 die "unable to create output file '$filename' - $!\n";
823 chown $wwwid, -1, $outfh;
824
825 return $outfh;
826 };
827
828 sub upid_read_status {
829 my ($upid) = @_;
830
831 my ($task, $filename) = upid_decode($upid);
832 my $fh = IO::File->new($filename, "r");
833 return "unable to open file - $!" if !$fh;
834 my $maxlen = 4096;
835 sysseek($fh, -$maxlen, 2);
836 my $readbuf = '';
837 my $br = sysread($fh, $readbuf, $maxlen);
838 close($fh);
839 if ($br) {
840 return "unable to extract last line"
841 if $readbuf !~ m/\n?(.+)$/;
842 my $line = $1;
843 if ($line =~ m/^TASK OK$/) {
844 return 'OK';
845 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
846 return $1;
847 } else {
848 return "unexpected status";
849 }
850 }
851 return "unable to read tail (got $br bytes)";
852 }
853
854 # useful functions to store comments in config files
855 sub encode_text {
856 my ($text) = @_;
857
858 # all control and hi-bit characters, and ':'
859 my $unsafe = "^\x20-\x39\x3b-\x7e";
860 return uri_escape(Encode::encode("utf8", $text), $unsafe);
861 }
862
863 sub decode_text {
864 my ($data) = @_;
865
866 return Encode::decode("utf8", uri_unescape($data));
867 }
868
869 sub decode_utf8_parameters {
870 my ($param) = @_;
871
872 foreach my $p (qw(comment description firstname lastname)) {
873 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
874 }
875
876 return $param;
877 }
878
879 sub random_ether_addr {
880
881 my $rand = Digest::SHA::sha1_hex(rand(), time());
882
883 my $mac = '';
884 for (my $i = 0; $i < 6; $i++) {
885 my $ss = hex(substr($rand, $i*2, 2));
886 if (!$i) {
887 $ss &= 0xfe; # clear multicast
888 $ss |= 2; # set local id
889 }
890 $ss = sprintf("%02X", $ss);
891
892 if (!$i) {
893 $mac .= "$ss";
894 } else {
895 $mac .= ":$ss";
896 }
897 }
898
899 return $mac;
900 }
901
902 sub shellquote {
903 my $str = shift;
904
905 return String::ShellQuote::shell_quote($str);
906 }
907
908 sub cmd2string {
909 my ($cmd) = @_;
910
911 die "no arguments" if !$cmd;
912
913 return $cmd if !ref($cmd);
914
915 my @qa = ();
916 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
917
918 return join (' ', @qa);
919 }
920
921 # split an shell argument string into an array,
922 sub split_args {
923 my ($str) = @_;
924
925 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
926 }
927
928 sub dump_logfile {
929 my ($filename, $start, $limit) = @_;
930
931 my $lines = [];
932 my $count = 0;
933
934 my $fh = IO::File->new($filename, "r");
935 if (!$fh) {
936 $count++;
937 push @$lines, { n => $count, t => "unable to open file - $!"};
938 return ($count, $lines);
939 }
940
941 $start = 0 if !$start;
942 $limit = 50 if !$limit;
943
944 my $line;
945 while (defined($line = <$fh>)) {
946 next if $count++ < $start;
947 next if $limit <= 0;
948 chomp $line;
949 push @$lines, { n => $count, t => $line};
950 $limit--;
951 }
952
953 close($fh);
954
955 # HACK: ExtJS store.guaranteeRange() does not like empty array
956 # so we add a line
957 if (!$count) {
958 $count++;
959 push @$lines, { n => $count, t => "no content"};
960 }
961
962 return ($count, $lines);
963 }
964
965 sub dir_glob_regex {
966 my ($dir, $regex) = @_;
967
968 my $dh = IO::Dir->new ($dir);
969 return wantarray ? () : undef if !$dh;
970
971 while (defined(my $tmp = $dh->read)) {
972 if (my @res = $tmp =~ m/^($regex)$/) {
973 $dh->close;
974 return wantarray ? @res : $tmp;
975 }
976 }
977 $dh->close;
978
979 return wantarray ? () : undef;
980 }
981
982 sub dir_glob_foreach {
983 my ($dir, $regex, $func) = @_;
984
985 my $dh = IO::Dir->new ($dir);
986 if (defined $dh) {
987 while (defined(my $tmp = $dh->read)) {
988 if (my @res = $tmp =~ m/^($regex)$/) {
989 &$func (@res);
990 }
991 }
992 }
993 }
994
995 1;