]> git.proxmox.com Git - pve-common.git/blob - data/PVE/Tools.pm
20fc1ea3ad0f73c1ee4f03b8d6b93586833b6e5b
[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 run_command
23 file_set_contents
24 file_get_contents
25 file_read_firstline
26 dir_glob_regex
27 dir_glob_foreach
28 split_list
29 template_replace
30 safe_print
31 trim
32 extract_param
33 );
34
35 my $pvelogdir = "/var/log/pve";
36 my $pvetaskdir = "$pvelogdir/tasks";
37
38 mkdir $pvelogdir;
39 mkdir $pvetaskdir;
40
41 sub run_with_timeout {
42 my ($timeout, $code, @param) = @_;
43
44 die "got timeout\n" if $timeout <= 0;
45
46 my $prev_alarm;
47
48 my $sigcount = 0;
49
50 my $res;
51
52 local $SIG{ALRM} = sub { $sigcount++; }; # catch alarm outside eval
53
54 eval {
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
58
59 $prev_alarm = alarm($timeout);
60
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 }
76
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
80 my $lock_handles = {};
81
82 sub lock_file {
83 my ($filename, $timeout, $code, @param) = @_;
84
85 $timeout = 10 if !$timeout;
86
87 my $lock_func = sub {
88 if (!$lock_handles->{$$}->{$filename}) {
89 $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") ||
90 die "can't open file - $!\n";
91 }
92
93 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX|LOCK_NB)) {
94 print STDERR "trying to aquire lock...";
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) {
104 print STDERR " failed\n";
105 die "can't aquire lock - $!\n";
106 }
107 print STDERR " OK\n";
108 }
109 };
110
111 my $res;
112
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 }
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
138 sub 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
165 sub 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
178 sub file_read_firstline {
179 my ($filename) = @_;
180
181 my $fh = IO::File->new ($filename, "r");
182 return undef if !$fh;
183 my $res = <$fh>;
184 chomp $res if $res;
185 $fh->close;
186 return $res;
187 }
188
189 sub 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
210 sub run_command {
211 my ($cmd, %param) = @_;
212
213 my $old_umask;
214 my $cmdstr;
215
216 if (!ref($cmd)) {
217 $cmdstr = $cmd;
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 }
224 } else {
225 $cmdstr = cmd2string($cmd);
226 }
227
228 my $errmsg;
229 my $laststderr;
230 my $timeout;
231 my $oldtimeout;
232 my $pid;
233
234 my $outfunc;
235 my $errfunc;
236 my $logfunc;
237 my $input;
238 my $output;
239 my $afterfork;
240
241 eval {
242
243 foreach my $p (keys %param) {
244 if ($p eq 'timeout') {
245 $timeout = $param{$p};
246 } elsif ($p eq 'umask') {
247 $old_umask = umask($param{$p});
248 } elsif ($p eq 'errmsg') {
249 $errmsg = $param{$p};
250 } elsif ($p eq 'input') {
251 $input = $param{$p};
252 } elsif ($p eq 'output') {
253 $output = $param{$p};
254 } elsif ($p eq 'outfunc') {
255 $outfunc = $param{$p};
256 } elsif ($p eq 'errfunc') {
257 $errfunc = $param{$p};
258 } elsif ($p eq 'logfunc') {
259 $logfunc = $param{$p};
260 } elsif ($p eq 'afterfork') {
261 $afterfork = $param{$p};
262 } else {
263 die "got unknown parameter '$p' for run_command\n";
264 }
265 }
266
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
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
285 # try to avoid locale related issues/warnings
286 my $lang = $param{lang} || 'C';
287
288 my $orig_pid = $$;
289
290 eval {
291 local $ENV{LC_ALL} = $lang;
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 $!;
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 }
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
322 &$afterfork() if $afterfork;
323
324 if (ref($writer)) {
325 print $writer $input if defined $input;
326 close $writer;
327 }
328
329 my $select = new IO::Select;
330 $select->add($reader) if ref($reader);
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) {
352 if ($outfunc || $logfunc) {
353 eval {
354 $outlog .= $buf;
355 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
356 my $line = $1;
357 &$outfunc($line) if $outfunc;
358 &$logfunc($line) if $logfunc;
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) {
372 if ($errfunc || $logfunc) {
373 eval {
374 $errlog .= $buf;
375 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
376 my $line = $1;
377 &$errfunc($line) if $errfunc;
378 &$logfunc($line) if $logfunc;
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;
396 &$logfunc($outlog) if $logfunc && $outlog;
397
398 &$errfunc($errlog) if $errfunc && $errlog;
399 &$logfunc($errlog) if $logfunc && $errlog;
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)) {
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";
415 }
416 }
417
418 alarm(0);
419 };
420
421 my $err = $@;
422
423 alarm(0);
424
425 if ($errmsg && $laststderr) {
426 &$errfunc(undef); # flush laststderr
427 }
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) {
441 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
442 die "$errmsg: $err";
443 } else {
444 die "command '$cmdstr' failed: $err";
445 }
446 }
447
448 return undef;
449 }
450
451 sub split_list {
452 my $listtxt = shift || '';
453
454 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
455
456 $listtxt =~ s/[,;]/ /g;
457 $listtxt =~ s/^\s+//;
458
459 my @data = split (/\s+/, $listtxt);
460
461 return @data;
462 }
463
464 sub 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}"
476 sub template_replace {
477 my ($tmpl, $data) = @_;
478
479 return $tmpl if !$tmpl;
480
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
489 sub 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
499 sub 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
544 my $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],
574 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
575 #'th' => [],
576 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
577 };
578
579 my $kvmkeymaparray = [];
580 foreach my $lc (keys %$keymaphash) {
581 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
582 }
583
584 sub kvmkeymaps {
585 return $keymaphash;
586 }
587
588 sub kvmkeymaplist {
589 return $kvmkeymaparray;
590 }
591
592 sub extract_param {
593 my ($param, $key) = @_;
594
595 my $res = $param->{$key};
596 delete $param->{$key};
597
598 return $res;
599 }
600
601 # Note: we use this to wait until vncterm is ready
602 sub 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
625 sub 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)
649 sub 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
682 sub 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
690 sub upid_decode {
691 my ($upid, $noerr) = @_;
692
693 my $res;
694 my $filename;
695
696 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
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]+):$/) {
698 $res->{node} = $1;
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);
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
717 sub 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";
732 chown $wwwid, -1, $outfh;
733
734 return $outfh;
735 };
736
737 sub 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
764 sub 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
772 sub decode_text {
773 my ($data) = @_;
774
775 return Encode::decode("utf8", uri_unescape($data));
776 }
777
778 sub decode_utf8_parameters {
779 my ($param) = @_;
780
781 foreach my $p (qw(comment description firstname lastname)) {
782 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
783 }
784
785 return $param;
786 }
787
788 sub random_ether_addr {
789
790 my $rand = Digest::SHA::sha1_hex(rand(), time());
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 }
810
811 sub shellquote {
812 my $str = shift;
813
814 return String::ShellQuote::shell_quote($str);
815 }
816
817 sub 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
830 # split an shell argument string into an array,
831 sub split_args {
832 my ($str) = @_;
833
834 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
835 }
836
837 sub 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
874 sub 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
891 sub 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
904 1;