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