]> git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
export regular expressions for IPv4 and IPv6 addresses
[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
21 our @EXPORT_OK = qw(
22 $IPV6RE
23 $IPV4RE
24 lock_file
25 lock_file_full
26 run_command
27 file_set_contents
28 file_get_contents
29 file_read_firstline
30 dir_glob_regex
31 dir_glob_foreach
32 split_list
33 template_replace
34 safe_print
35 trim
36 extract_param
37 );
38
39 my $pvelogdir = "/var/log/pve";
40 my $pvetaskdir = "$pvelogdir/tasks";
41
42 mkdir $pvelogdir;
43 mkdir $pvetaskdir;
44
45 my $IPV4OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
46 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
47 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
48 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
49
50 our $IPV6RE = "(?:" .
51 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
52 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
53 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
54 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
55 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
56 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
57 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
58 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
59 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
60
61 sub run_with_timeout {
62 my ($timeout, $code, @param) = @_;
63
64 die "got timeout\n" if $timeout <= 0;
65
66 my $prev_alarm;
67
68 my $sigcount = 0;
69
70 my $res;
71
72 local $SIG{ALRM} = sub { $sigcount++; }; # catch alarm outside eval
73
74 eval {
75 local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; };
76 local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" };
77 local $SIG{__DIE__}; # see SA bug 4631
78
79 $prev_alarm = alarm($timeout);
80
81 $res = &$code(@param);
82
83 alarm(0); # avoid race conditions
84 };
85
86 my $err = $@;
87
88 alarm($prev_alarm) if defined($prev_alarm);
89
90 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
91
92 die $err if $err;
93
94 return $res;
95 }
96
97 # flock: we use one file handle per process, so lock file
98 # can be called multiple times and succeeds for the same process.
99
100 my $lock_handles = {};
101
102 sub lock_file_full {
103 my ($filename, $timeout, $shared, $code, @param) = @_;
104
105 $timeout = 10 if !$timeout;
106
107 my $mode = $shared ? LOCK_SH : LOCK_EX;
108
109 my $lock_func = sub {
110 if (!$lock_handles->{$$}->{$filename}) {
111 $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") ||
112 die "can't open file - $!\n";
113 }
114
115 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB)) {
116 print STDERR "trying to aquire lock...";
117 my $success;
118 while(1) {
119 $success = flock($lock_handles->{$$}->{$filename}, $mode);
120 # try again on EINTR (see bug #273)
121 if ($success || ($! != EINTR)) {
122 last;
123 }
124 }
125 if (!$success) {
126 print STDERR " failed\n";
127 die "can't aquire lock - $!\n";
128 }
129 print STDERR " OK\n";
130 }
131 };
132
133 my $res;
134
135 eval { run_with_timeout($timeout, $lock_func); };
136 my $err = $@;
137 if ($err) {
138 $err = "can't lock file '$filename' - $err";
139 } else {
140 eval { $res = &$code(@param) };
141 $err = $@;
142 }
143
144 if ($lock_handles->{$$}->{$filename}) {
145 my $fh = $lock_handles->{$$}->{$filename};
146 $lock_handles->{$$}->{$filename} = undef;
147 close ($fh);
148 }
149
150 if ($err) {
151 $@ = $err;
152 return undef;
153 }
154
155 $@ = undef;
156
157 return $res;
158 }
159
160
161 sub lock_file {
162 my ($filename, $timeout, $code, @param) = @_;
163
164 return lock_file_full($filename, $timeout, 0, $code, @param);
165 }
166
167 sub file_set_contents {
168 my ($filename, $data, $perm) = @_;
169
170 $perm = 0644 if !defined($perm);
171
172 my $tmpname = "$filename.tmp.$$";
173
174 eval {
175 my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm);
176 die "unable to open file '$tmpname' - $!\n" if !$fh;
177 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
178 die "closing file '$tmpname' failed - $!\n" unless close $fh;
179 };
180 my $err = $@;
181
182 if ($err) {
183 unlink $tmpname;
184 die $err;
185 }
186
187 if (!rename($tmpname, $filename)) {
188 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
189 unlink $tmpname;
190 die $msg;
191 }
192 }
193
194 sub file_get_contents {
195 my ($filename, $max) = @_;
196
197 my $fh = IO::File->new($filename, "r") ||
198 die "can't open '$filename' - $!\n";
199
200 my $content = safe_read_from($fh, $max);
201
202 close $fh;
203
204 return $content;
205 }
206
207 sub file_read_firstline {
208 my ($filename) = @_;
209
210 my $fh = IO::File->new ($filename, "r");
211 return undef if !$fh;
212 my $res = <$fh>;
213 chomp $res if $res;
214 $fh->close;
215 return $res;
216 }
217
218 sub safe_read_from {
219 my ($fh, $max, $oneline) = @_;
220
221 $max = 32768 if !$max;
222
223 my $br = 0;
224 my $input = '';
225 my $count;
226 while ($count = sysread($fh, $input, 8192, $br)) {
227 $br += $count;
228 die "input too long - aborting\n" if $br > $max;
229 if ($oneline && $input =~ m/^(.*)\n/) {
230 $input = $1;
231 last;
232 }
233 }
234 die "unable to read input - $!\n" if !defined($count);
235
236 return $input;
237 }
238
239 sub run_command {
240 my ($cmd, %param) = @_;
241
242 my $old_umask;
243 my $cmdstr;
244
245 if (!ref($cmd)) {
246 $cmdstr = $cmd;
247 if ($cmd =~ m/|/) {
248 # see 'man bash' for option pipefail
249 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
250 } else {
251 $cmd = [ $cmd ];
252 }
253 } else {
254 $cmdstr = cmd2string($cmd);
255 }
256
257 my $errmsg;
258 my $laststderr;
259 my $timeout;
260 my $oldtimeout;
261 my $pid;
262
263 my $outfunc;
264 my $errfunc;
265 my $logfunc;
266 my $input;
267 my $output;
268 my $afterfork;
269
270 eval {
271
272 foreach my $p (keys %param) {
273 if ($p eq 'timeout') {
274 $timeout = $param{$p};
275 } elsif ($p eq 'umask') {
276 $old_umask = umask($param{$p});
277 } elsif ($p eq 'errmsg') {
278 $errmsg = $param{$p};
279 } elsif ($p eq 'input') {
280 $input = $param{$p};
281 } elsif ($p eq 'output') {
282 $output = $param{$p};
283 } elsif ($p eq 'outfunc') {
284 $outfunc = $param{$p};
285 } elsif ($p eq 'errfunc') {
286 $errfunc = $param{$p};
287 } elsif ($p eq 'logfunc') {
288 $logfunc = $param{$p};
289 } elsif ($p eq 'afterfork') {
290 $afterfork = $param{$p};
291 } else {
292 die "got unknown parameter '$p' for run_command\n";
293 }
294 }
295
296 if ($errmsg) {
297 my $origerrfunc = $errfunc;
298 $errfunc = sub {
299 if ($laststderr) {
300 if ($origerrfunc) {
301 &$origerrfunc("$laststderr\n");
302 } else {
303 print STDERR "$laststderr\n" if $laststderr;
304 }
305 }
306 $laststderr = shift;
307 };
308 }
309
310 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
311 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
312 my $error = IO::File->new();
313
314 # try to avoid locale related issues/warnings
315 my $lang = $param{lang} || 'C';
316
317 my $orig_pid = $$;
318
319 eval {
320 local $ENV{LC_ALL} = $lang;
321
322 # suppress LVM warnings like: "File descriptor 3 left open";
323 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
324
325 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
326
327 # if we pipe fron STDIN, open3 closes STDIN, so we we
328 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
329 # as soon as we open a new file.
330 # to avoid that we open /dev/null
331 if (!ref($writer) && !defined(fileno(STDIN))) {
332 POSIX::close(0);
333 open(STDIN, "</dev/null");
334 }
335 };
336
337 my $err = $@;
338
339 # catch exec errors
340 if ($orig_pid != $$) {
341 warn "ERROR: $err";
342 POSIX::_exit (1);
343 kill ('KILL', $$);
344 }
345
346 die $err if $err;
347
348 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
349 $oldtimeout = alarm($timeout) if $timeout;
350
351 &$afterfork() if $afterfork;
352
353 if (ref($writer)) {
354 print $writer $input if defined $input;
355 close $writer;
356 }
357
358 my $select = new IO::Select;
359 $select->add($reader) if ref($reader);
360 $select->add($error);
361
362 my $outlog = '';
363 my $errlog = '';
364
365 my $starttime = time();
366
367 while ($select->count) {
368 my @handles = $select->can_read(1);
369
370 foreach my $h (@handles) {
371 my $buf = '';
372 my $count = sysread ($h, $buf, 4096);
373 if (!defined ($count)) {
374 my $err = $!;
375 kill (9, $pid);
376 waitpid ($pid, 0);
377 die $err;
378 }
379 $select->remove ($h) if !$count;
380 if ($h eq $reader) {
381 if ($outfunc || $logfunc) {
382 eval {
383 $outlog .= $buf;
384 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
385 my $line = $1;
386 &$outfunc($line) if $outfunc;
387 &$logfunc($line) if $logfunc;
388 }
389 };
390 my $err = $@;
391 if ($err) {
392 kill (9, $pid);
393 waitpid ($pid, 0);
394 die $err;
395 }
396 } else {
397 print $buf;
398 *STDOUT->flush();
399 }
400 } elsif ($h eq $error) {
401 if ($errfunc || $logfunc) {
402 eval {
403 $errlog .= $buf;
404 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
405 my $line = $1;
406 &$errfunc($line) if $errfunc;
407 &$logfunc($line) if $logfunc;
408 }
409 };
410 my $err = $@;
411 if ($err) {
412 kill (9, $pid);
413 waitpid ($pid, 0);
414 die $err;
415 }
416 } else {
417 print STDERR $buf;
418 *STDERR->flush();
419 }
420 }
421 }
422 }
423
424 &$outfunc($outlog) if $outfunc && $outlog;
425 &$logfunc($outlog) if $logfunc && $outlog;
426
427 &$errfunc($errlog) if $errfunc && $errlog;
428 &$logfunc($errlog) if $logfunc && $errlog;
429
430 waitpid ($pid, 0);
431
432 if ($? == -1) {
433 die "failed to execute\n";
434 } elsif (my $sig = ($? & 127)) {
435 die "got signal $sig\n";
436 } elsif (my $ec = ($? >> 8)) {
437 if (!($ec == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
438 if ($errmsg && $laststderr) {
439 my $lerr = $laststderr;
440 $laststderr = undef;
441 die "$lerr\n";
442 }
443 die "exit code $ec\n";
444 }
445 }
446
447 alarm(0);
448 };
449
450 my $err = $@;
451
452 alarm(0);
453
454 if ($errmsg && $laststderr) {
455 &$errfunc(undef); # flush laststderr
456 }
457
458 umask ($old_umask) if defined($old_umask);
459
460 alarm($oldtimeout) if $oldtimeout;
461
462 if ($err) {
463 if ($pid && ($err eq "got timeout\n")) {
464 kill (9, $pid);
465 waitpid ($pid, 0);
466 die "command '$cmdstr' failed: $err";
467 }
468
469 if ($errmsg) {
470 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
471 die "$errmsg: $err";
472 } else {
473 die "command '$cmdstr' failed: $err";
474 }
475 }
476
477 return undef;
478 }
479
480 sub split_list {
481 my $listtxt = shift || '';
482
483 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
484
485 $listtxt =~ s/[,;]/ /g;
486 $listtxt =~ s/^\s+//;
487
488 my @data = split (/\s+/, $listtxt);
489
490 return @data;
491 }
492
493 sub trim {
494 my $txt = shift;
495
496 return $txt if !defined($txt);
497
498 $txt =~ s/^\s+//;
499 $txt =~ s/\s+$//;
500
501 return $txt;
502 }
503
504 # simple uri templates like "/vms/{vmid}"
505 sub template_replace {
506 my ($tmpl, $data) = @_;
507
508 return $tmpl if !$tmpl;
509
510 my $res = '';
511 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
512 $res .= $1 if $1;
513 $res .= ($data->{$3} || '-') if $2;
514 }
515 return $res;
516 }
517
518 sub safe_print {
519 my ($filename, $fh, $data) = @_;
520
521 return if !$data;
522
523 my $res = print $fh $data;
524
525 die "write to '$filename' failed\n" if !$res;
526 }
527
528 sub debmirrors {
529
530 return {
531 'at' => 'ftp.at.debian.org',
532 'au' => 'ftp.au.debian.org',
533 'be' => 'ftp.be.debian.org',
534 'bg' => 'ftp.bg.debian.org',
535 'br' => 'ftp.br.debian.org',
536 'ca' => 'ftp.ca.debian.org',
537 'ch' => 'ftp.ch.debian.org',
538 'cl' => 'ftp.cl.debian.org',
539 'cz' => 'ftp.cz.debian.org',
540 'de' => 'ftp.de.debian.org',
541 'dk' => 'ftp.dk.debian.org',
542 'ee' => 'ftp.ee.debian.org',
543 'es' => 'ftp.es.debian.org',
544 'fi' => 'ftp.fi.debian.org',
545 'fr' => 'ftp.fr.debian.org',
546 'gr' => 'ftp.gr.debian.org',
547 'hk' => 'ftp.hk.debian.org',
548 'hr' => 'ftp.hr.debian.org',
549 'hu' => 'ftp.hu.debian.org',
550 'ie' => 'ftp.ie.debian.org',
551 'is' => 'ftp.is.debian.org',
552 'it' => 'ftp.it.debian.org',
553 'jp' => 'ftp.jp.debian.org',
554 'kr' => 'ftp.kr.debian.org',
555 'mx' => 'ftp.mx.debian.org',
556 'nl' => 'ftp.nl.debian.org',
557 'no' => 'ftp.no.debian.org',
558 'nz' => 'ftp.nz.debian.org',
559 'pl' => 'ftp.pl.debian.org',
560 'pt' => 'ftp.pt.debian.org',
561 'ro' => 'ftp.ro.debian.org',
562 'ru' => 'ftp.ru.debian.org',
563 'se' => 'ftp.se.debian.org',
564 'si' => 'ftp.si.debian.org',
565 'sk' => 'ftp.sk.debian.org',
566 'tr' => 'ftp.tr.debian.org',
567 'tw' => 'ftp.tw.debian.org',
568 'gb' => 'ftp.uk.debian.org',
569 'us' => 'ftp.us.debian.org',
570 };
571 }
572
573 my $keymaphash = {
574 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
575 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
576 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
577 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
578 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
579 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
580 #'et' => [], # Ethopia or Estonia ??
581 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
582 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
583 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
584 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
585 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
586 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
587 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
588 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
589 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
590 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
591 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
592 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
593 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
594 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
595 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
596 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
597 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
598 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
599 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
600 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
601 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
602 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
603 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
604 #'th' => [],
605 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
606 };
607
608 my $kvmkeymaparray = [];
609 foreach my $lc (keys %$keymaphash) {
610 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
611 }
612
613 sub kvmkeymaps {
614 return $keymaphash;
615 }
616
617 sub kvmkeymaplist {
618 return $kvmkeymaparray;
619 }
620
621 sub extract_param {
622 my ($param, $key) = @_;
623
624 my $res = $param->{$key};
625 delete $param->{$key};
626
627 return $res;
628 }
629
630 # Note: we use this to wait until vncterm is ready
631 sub wait_for_vnc_port {
632 my ($port, $timeout) = @_;
633
634 $timeout = 5 if !$timeout;
635
636 for (my $i = 0; $i < $timeout; $i++) {
637 if (my $fh = IO::File->new ("/proc/net/tcp", "r")) {
638 while (defined (my $line = <$fh>)) {
639 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
640 if ($port == hex($2)) {
641 close($fh);
642 return 1;
643 }
644 }
645 }
646 close($fh);
647 }
648 sleep(1);
649 }
650
651 return undef;
652 }
653
654 sub next_unused_port {
655 my ($range_start, $range_end) = @_;
656
657 # We use a file to register allocated ports.
658 # Those registrations expires after $expiretime.
659 # We use this to avoid race conditions between
660 # allocation and use of ports.
661
662 my $filename = "/var/tmp/pve-reserved-ports";
663
664 my $code = sub {
665
666 my $expiretime = 5;
667 my $ctime = time();
668
669 my $ports = {};
670
671 if (my $fh = IO::File->new ($filename, "r")) {
672 while (my $line = <$fh>) {
673 if ($line =~ m/^(\d+)\s(\d+)$/) {
674 my ($port, $timestamp) = ($1, $2);
675 if (($timestamp + $expiretime) > $ctime) {
676 $ports->{$port} = $timestamp; # not expired
677 }
678 }
679 }
680 }
681
682 my $newport;
683
684 for (my $p = $range_start; $p < $range_end; $p++) {
685 next if $ports->{$p}; # reserved
686
687 my $sock = IO::Socket::INET->new(Listen => 5,
688 LocalAddr => 'localhost',
689 LocalPort => $p,
690 ReuseAddr => 1,
691 Proto => 0);
692
693 if ($sock) {
694 close($sock);
695 $newport = $p;
696 $ports->{$p} = $ctime;
697 last;
698 }
699 }
700
701 my $data = "";
702 foreach my $p (keys %$ports) {
703 $data .= "$p $ports->{$p}\n";
704 }
705
706 file_set_contents($filename, $data);
707
708 return $newport;
709 };
710
711 my $p = lock_file($filename, 10, $code);
712 die $@ if $@;
713
714 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
715
716 return $p;
717 }
718
719 sub next_migrate_port {
720 return next_unused_port(60000, 60010);
721 }
722
723 sub next_vnc_port {
724 return next_unused_port(5900, 6000);
725 }
726
727 # NOTE: NFS syscall can't be interrupted, so alarm does
728 # not work to provide timeouts.
729 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
730 # So the spawn external 'df' process instead of using
731 # Filesys::Df (which uses statfs syscall)
732 sub df {
733 my ($path, $timeout) = @_;
734
735 my $cmd = [ 'df', '-P', '-B', '1', $path];
736
737 my $res = {
738 total => 0,
739 used => 0,
740 avail => 0,
741 };
742
743 my $parser = sub {
744 my $line = shift;
745 if (my ($fsid, $total, $used, $avail) = $line =~
746 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
747 $res = {
748 total => $total,
749 used => $used,
750 avail => $avail,
751 };
752 }
753 };
754 eval { run_command($cmd, timeout => $timeout, outfunc => $parser); };
755 warn $@ if $@;
756
757 return $res;
758 }
759
760 # UPID helper
761 # We use this to uniquely identify a process.
762 # An 'Unique Process ID' has the following format:
763 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
764
765 sub upid_encode {
766 my $d = shift;
767
768 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
769 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
770 $d->{user});
771 }
772
773 sub upid_decode {
774 my ($upid, $noerr) = @_;
775
776 my $res;
777 my $filename;
778
779 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
780 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}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/) {
781 $res->{node} = $1;
782 $res->{pid} = hex($3);
783 $res->{pstart} = hex($4);
784 $res->{starttime} = hex($5);
785 $res->{type} = $6;
786 $res->{id} = $7;
787 $res->{user} = $8;
788
789 my $subdir = substr($5, 7, 8);
790 $filename = "$pvetaskdir/$subdir/$upid";
791
792 } else {
793 return undef if $noerr;
794 die "unable to parse worker upid '$upid'\n";
795 }
796
797 return wantarray ? ($res, $filename) : $res;
798 }
799
800 sub upid_open {
801 my ($upid) = @_;
802
803 my ($task, $filename) = upid_decode($upid);
804
805 my $dirname = dirname($filename);
806 make_path($dirname);
807
808 my $wwwid = getpwnam('www-data') ||
809 die "getpwnam failed";
810
811 my $perm = 0640;
812
813 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
814 die "unable to create output file '$filename' - $!\n";
815 chown $wwwid, -1, $outfh;
816
817 return $outfh;
818 };
819
820 sub upid_read_status {
821 my ($upid) = @_;
822
823 my ($task, $filename) = upid_decode($upid);
824 my $fh = IO::File->new($filename, "r");
825 return "unable to open file - $!" if !$fh;
826 my $maxlen = 4096;
827 sysseek($fh, -$maxlen, 2);
828 my $readbuf = '';
829 my $br = sysread($fh, $readbuf, $maxlen);
830 close($fh);
831 if ($br) {
832 return "unable to extract last line"
833 if $readbuf !~ m/\n?(.+)$/;
834 my $line = $1;
835 if ($line =~ m/^TASK OK$/) {
836 return 'OK';
837 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
838 return $1;
839 } else {
840 return "unexpected status";
841 }
842 }
843 return "unable to read tail (got $br bytes)";
844 }
845
846 # useful functions to store comments in config files
847 sub encode_text {
848 my ($text) = @_;
849
850 # all control and hi-bit characters, and ':'
851 my $unsafe = "^\x20-\x39\x3b-\x7e";
852 return uri_escape(Encode::encode("utf8", $text), $unsafe);
853 }
854
855 sub decode_text {
856 my ($data) = @_;
857
858 return Encode::decode("utf8", uri_unescape($data));
859 }
860
861 sub decode_utf8_parameters {
862 my ($param) = @_;
863
864 foreach my $p (qw(comment description firstname lastname)) {
865 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
866 }
867
868 return $param;
869 }
870
871 sub random_ether_addr {
872
873 my $rand = Digest::SHA::sha1_hex(rand(), time());
874
875 my $mac = '';
876 for (my $i = 0; $i < 6; $i++) {
877 my $ss = hex(substr($rand, $i*2, 2));
878 if (!$i) {
879 $ss &= 0xfe; # clear multicast
880 $ss |= 2; # set local id
881 }
882 $ss = sprintf("%02X", $ss);
883
884 if (!$i) {
885 $mac .= "$ss";
886 } else {
887 $mac .= ":$ss";
888 }
889 }
890
891 return $mac;
892 }
893
894 sub shellquote {
895 my $str = shift;
896
897 return String::ShellQuote::shell_quote($str);
898 }
899
900 sub cmd2string {
901 my ($cmd) = @_;
902
903 die "no arguments" if !$cmd;
904
905 return $cmd if !ref($cmd);
906
907 my @qa = ();
908 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
909
910 return join (' ', @qa);
911 }
912
913 # split an shell argument string into an array,
914 sub split_args {
915 my ($str) = @_;
916
917 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
918 }
919
920 sub dump_logfile {
921 my ($filename, $start, $limit) = @_;
922
923 my $lines = [];
924 my $count = 0;
925
926 my $fh = IO::File->new($filename, "r");
927 if (!$fh) {
928 $count++;
929 push @$lines, { n => $count, t => "unable to open file - $!"};
930 return ($count, $lines);
931 }
932
933 $start = 0 if !$start;
934 $limit = 50 if !$limit;
935
936 my $line;
937 while (defined($line = <$fh>)) {
938 next if $count++ < $start;
939 next if $limit <= 0;
940 chomp $line;
941 push @$lines, { n => $count, t => $line};
942 $limit--;
943 }
944
945 close($fh);
946
947 # HACK: ExtJS store.guaranteeRange() does not like empty array
948 # so we add a line
949 if (!$count) {
950 $count++;
951 push @$lines, { n => $count, t => "no content"};
952 }
953
954 return ($count, $lines);
955 }
956
957 sub dir_glob_regex {
958 my ($dir, $regex) = @_;
959
960 my $dh = IO::Dir->new ($dir);
961 return wantarray ? () : undef if !$dh;
962
963 while (defined(my $tmp = $dh->read)) {
964 if (my @res = $tmp =~ m/^($regex)$/) {
965 $dh->close;
966 return wantarray ? @res : $tmp;
967 }
968 }
969 $dh->close;
970
971 return wantarray ? () : undef;
972 }
973
974 sub dir_glob_foreach {
975 my ($dir, $regex, $func) = @_;
976
977 my $dh = IO::Dir->new ($dir);
978 if (defined $dh) {
979 while (defined(my $tmp = $dh->read)) {
980 if (my @res = $tmp =~ m/^($regex)$/) {
981 &$func (@res);
982 }
983 }
984 }
985 }
986
987 1;