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