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