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