do not use 'intl' variant for en an gb keyboard layouts
[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 lock_file
23 lock_file_full
24 run_command
25 file_set_contents
26 file_get_contents
27 file_read_firstline
28 dir_glob_regex
29 dir_glob_foreach
30 split_list
31 template_replace
32 safe_print
33 trim
34 extract_param
35 );
36
37 my $pvelogdir = "/var/log/pve";
38 my $pvetaskdir = "$pvelogdir/tasks";
39
40 mkdir $pvelogdir;
41 mkdir $pvetaskdir;
42
43 sub run_with_timeout {
44 my ($timeout, $code, @param) = @_;
45
46 die "got timeout\n" if $timeout <= 0;
47
48 my $prev_alarm;
49
50 my $sigcount = 0;
51
52 my $res;
53
54 local $SIG{ALRM} = sub { $sigcount++; }; # catch alarm outside eval
55
56 eval {
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
60
61 $prev_alarm = alarm($timeout);
62
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 }
78
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
82 my $lock_handles = {};
83
84 sub lock_file_full {
85 my ($filename, $timeout, $shared, $code, @param) = @_;
86
87 $timeout = 10 if !$timeout;
88
89 my $mode = $shared ? LOCK_SH : LOCK_EX;
90
91 my $lock_func = sub {
92 if (!$lock_handles->{$$}->{$filename}) {
93 $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") ||
94 die "can't open file - $!\n";
95 }
96
97 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB)) {
98 print STDERR "trying to aquire lock...";
99 my $success;
100 while(1) {
101 $success = flock($lock_handles->{$$}->{$filename}, $mode);
102 # try again on EINTR (see bug #273)
103 if ($success || ($! != EINTR)) {
104 last;
105 }
106 }
107 if (!$success) {
108 print STDERR " failed\n";
109 die "can't aquire lock - $!\n";
110 }
111 print STDERR " OK\n";
112 }
113 };
114
115 my $res;
116
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 }
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
142
143 sub lock_file {
144 my ($filename, $timeout, $code, @param) = @_;
145
146 return lock_file_full($filename, $timeout, 0, $code, @param);
147 }
148
149 sub 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
176 sub 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
189 sub file_read_firstline {
190 my ($filename) = @_;
191
192 my $fh = IO::File->new ($filename, "r");
193 return undef if !$fh;
194 my $res = <$fh>;
195 chomp $res if $res;
196 $fh->close;
197 return $res;
198 }
199
200 sub 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
221 sub run_command {
222 my ($cmd, %param) = @_;
223
224 my $old_umask;
225 my $cmdstr;
226
227 if (!ref($cmd)) {
228 $cmdstr = $cmd;
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 }
235 } else {
236 $cmdstr = cmd2string($cmd);
237 }
238
239 my $errmsg;
240 my $laststderr;
241 my $timeout;
242 my $oldtimeout;
243 my $pid;
244
245 my $outfunc;
246 my $errfunc;
247 my $logfunc;
248 my $input;
249 my $output;
250 my $afterfork;
251
252 eval {
253
254 foreach my $p (keys %param) {
255 if ($p eq 'timeout') {
256 $timeout = $param{$p};
257 } elsif ($p eq 'umask') {
258 $old_umask = umask($param{$p});
259 } elsif ($p eq 'errmsg') {
260 $errmsg = $param{$p};
261 } elsif ($p eq 'input') {
262 $input = $param{$p};
263 } elsif ($p eq 'output') {
264 $output = $param{$p};
265 } elsif ($p eq 'outfunc') {
266 $outfunc = $param{$p};
267 } elsif ($p eq 'errfunc') {
268 $errfunc = $param{$p};
269 } elsif ($p eq 'logfunc') {
270 $logfunc = $param{$p};
271 } elsif ($p eq 'afterfork') {
272 $afterfork = $param{$p};
273 } else {
274 die "got unknown parameter '$p' for run_command\n";
275 }
276 }
277
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
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
296 # try to avoid locale related issues/warnings
297 my $lang = $param{lang} || 'C';
298
299 my $orig_pid = $$;
300
301 eval {
302 local $ENV{LC_ALL} = $lang;
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 $!;
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 }
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
333 &$afterfork() if $afterfork;
334
335 if (ref($writer)) {
336 print $writer $input if defined $input;
337 close $writer;
338 }
339
340 my $select = new IO::Select;
341 $select->add($reader) if ref($reader);
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) {
363 if ($outfunc || $logfunc) {
364 eval {
365 $outlog .= $buf;
366 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
367 my $line = $1;
368 &$outfunc($line) if $outfunc;
369 &$logfunc($line) if $logfunc;
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) {
383 if ($errfunc || $logfunc) {
384 eval {
385 $errlog .= $buf;
386 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
387 my $line = $1;
388 &$errfunc($line) if $errfunc;
389 &$logfunc($line) if $logfunc;
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;
407 &$logfunc($outlog) if $logfunc && $outlog;
408
409 &$errfunc($errlog) if $errfunc && $errlog;
410 &$logfunc($errlog) if $logfunc && $errlog;
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)) {
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";
426 }
427 }
428
429 alarm(0);
430 };
431
432 my $err = $@;
433
434 alarm(0);
435
436 if ($errmsg && $laststderr) {
437 &$errfunc(undef); # flush laststderr
438 }
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) {
452 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
453 die "$errmsg: $err";
454 } else {
455 die "command '$cmdstr' failed: $err";
456 }
457 }
458
459 return undef;
460 }
461
462 sub split_list {
463 my $listtxt = shift || '';
464
465 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
466
467 $listtxt =~ s/[,;]/ /g;
468 $listtxt =~ s/^\s+//;
469
470 my @data = split (/\s+/, $listtxt);
471
472 return @data;
473 }
474
475 sub 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}"
487 sub template_replace {
488 my ($tmpl, $data) = @_;
489
490 return $tmpl if !$tmpl;
491
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
500 sub 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
510 sub 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
555 my $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' ],
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 ],
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],
585 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
586 #'th' => [],
587 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
588 };
589
590 my $kvmkeymaparray = [];
591 foreach my $lc (keys %$keymaphash) {
592 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
593 }
594
595 sub kvmkeymaps {
596 return $keymaphash;
597 }
598
599 sub kvmkeymaplist {
600 return $kvmkeymaparray;
601 }
602
603 sub extract_param {
604 my ($param, $key) = @_;
605
606 my $res = $param->{$key};
607 delete $param->{$key};
608
609 return $res;
610 }
611
612 # Note: we use this to wait until vncterm is ready
613 sub 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
636 sub 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";
645
646 my $code = sub {
647
648 my $expiretime = 5;
649 my $ctime = time();
650
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 }
662 }
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);
689
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
701 sub next_migrate_port {
702 return next_unused_port(60000, 60010);
703 }
704
705 sub next_vnc_port {
706 return next_unused_port(5900, 6000);
707 }
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)
714 sub 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
747 sub 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
755 sub upid_decode {
756 my ($upid, $noerr) = @_;
757
758 my $res;
759 my $filename;
760
761 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
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]+):$/) {
763 $res->{node} = $1;
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);
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
782 sub 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";
797 chown $wwwid, -1, $outfh;
798
799 return $outfh;
800 };
801
802 sub 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;
808 my $maxlen = 4096;
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
829 sub 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
837 sub decode_text {
838 my ($data) = @_;
839
840 return Encode::decode("utf8", uri_unescape($data));
841 }
842
843 sub decode_utf8_parameters {
844 my ($param) = @_;
845
846 foreach my $p (qw(comment description firstname lastname)) {
847 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
848 }
849
850 return $param;
851 }
852
853 sub random_ether_addr {
854
855 my $rand = Digest::SHA::sha1_hex(rand(), time());
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 }
875
876 sub shellquote {
877 my $str = shift;
878
879 return String::ShellQuote::shell_quote($str);
880 }
881
882 sub 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
895 # split an shell argument string into an array,
896 sub split_args {
897 my ($str) = @_;
898
899 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
900 }
901
902 sub 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
939 sub 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
956 sub 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
969 1;