new helper kvmkeymaplist()
[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
204 $cmd = [ $cmd ] if !ref($cmd);
205
206 my $cmdstr = cmd2string($cmd);
207
208 my $errmsg;
209 my $laststderr;
210 my $timeout;
211 my $oldtimeout;
212 my $pid;
213
214 my $outfunc;
215 my $errfunc;
216 my $logfunc;
217 my $input;
218 my $output;
219
220 eval {
221
222 foreach my $p (keys %param) {
223 if ($p eq 'timeout') {
224 $timeout = $param{$p};
225 } elsif ($p eq 'umask') {
226 umask($param{$p});
227 } elsif ($p eq 'errmsg') {
228 $errmsg = $param{$p};
229 } elsif ($p eq 'input') {
230 $input = $param{$p};
231 } elsif ($p eq 'output') {
232 $output = $param{$p};
233 } elsif ($p eq 'outfunc') {
234 $outfunc = $param{$p};
235 } elsif ($p eq 'errfunc') {
236 $errfunc = $param{$p};
237 } elsif ($p eq 'logfunc') {
238 $logfunc = $param{$p};
239 } else {
240 die "got unknown parameter '$p' for run_command\n";
241 }
242 }
243
244 if ($errmsg) {
245 my $origerrfunc = $errfunc;
246 $errfunc = sub {
247 if ($laststderr) {
248 if ($origerrfunc) {
249 &$origerrfunc("$laststderr\n");
250 } else {
251 print STDERR "$laststderr\n" if $laststderr;
252 }
253 }
254 $laststderr = shift;
255 };
256 }
257
258 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
259 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
260 my $error = IO::File->new();
261
262 # try to avoid locale related issues/warnings
263 my $lang = $param{lang} || 'C';
264
265 my $orig_pid = $$;
266
267 eval {
268 local $ENV{LC_ALL} = $lang;
269
270 # suppress LVM warnings like: "File descriptor 3 left open";
271 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
272
273 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
274
275 # if we pipe fron STDIN, open3 closes STDIN, so we we
276 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
277 # as soon as we open a new file.
278 # to avoid that we open /dev/null
279 if (!ref($writer) && !defined(fileno(STDIN))) {
280 POSIX::close(0);
281 open(STDIN, "</dev/null");
282 }
283 };
284
285 my $err = $@;
286
287 # catch exec errors
288 if ($orig_pid != $$) {
289 warn "ERROR: $err";
290 POSIX::_exit (1);
291 kill ('KILL', $$);
292 }
293
294 die $err if $err;
295
296 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
297 $oldtimeout = alarm($timeout) if $timeout;
298
299 if (ref($writer)) {
300 print $writer $input if defined $input;
301 close $writer;
302 }
303
304 my $select = new IO::Select;
305 $select->add($reader) if ref($reader);
306 $select->add($error);
307
308 my $outlog = '';
309 my $errlog = '';
310
311 my $starttime = time();
312
313 while ($select->count) {
314 my @handles = $select->can_read(1);
315
316 foreach my $h (@handles) {
317 my $buf = '';
318 my $count = sysread ($h, $buf, 4096);
319 if (!defined ($count)) {
320 my $err = $!;
321 kill (9, $pid);
322 waitpid ($pid, 0);
323 die $err;
324 }
325 $select->remove ($h) if !$count;
326 if ($h eq $reader) {
327 if ($outfunc || $logfunc) {
328 eval {
329 $outlog .= $buf;
330 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
331 my $line = $1;
332 &$outfunc($line) if $outfunc;
333 &$logfunc($line) if $logfunc;
334 }
335 };
336 my $err = $@;
337 if ($err) {
338 kill (9, $pid);
339 waitpid ($pid, 0);
340 die $err;
341 }
342 } else {
343 print $buf;
344 *STDOUT->flush();
345 }
346 } elsif ($h eq $error) {
347 if ($errfunc || $logfunc) {
348 eval {
349 $errlog .= $buf;
350 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
351 my $line = $1;
352 &$errfunc($line) if $errfunc;
353 &$logfunc($line) if $logfunc;
354 }
355 };
356 my $err = $@;
357 if ($err) {
358 kill (9, $pid);
359 waitpid ($pid, 0);
360 die $err;
361 }
362 } else {
363 print STDERR $buf;
364 *STDERR->flush();
365 }
366 }
367 }
368 }
369
370 &$outfunc($outlog) if $outfunc && $outlog;
371 &$logfunc($outlog) if $logfunc && $outlog;
372
373 &$errfunc($errlog) if $errfunc && $errlog;
374 &$logfunc($errlog) if $logfunc && $errlog;
375
376 waitpid ($pid, 0);
377
378 if ($? == -1) {
379 die "failed to execute\n";
380 } elsif (my $sig = ($? & 127)) {
381 die "got signal $sig\n";
382 } elsif (my $ec = ($? >> 8)) {
383 if (!($ec == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
384 if ($errmsg && $laststderr) {
385 my $lerr = $laststderr;
386 $laststderr = undef;
387 die "$lerr\n";
388 }
389 die "exit code $ec\n";
390 }
391 }
392
393 alarm(0);
394 };
395
396 my $err = $@;
397
398 alarm(0);
399
400 if ($errmsg && $laststderr) {
401 &$errfunc(undef); # flush laststderr
402 }
403
404 umask ($old_umask) if defined($old_umask);
405
406 alarm($oldtimeout) if $oldtimeout;
407
408 if ($err) {
409 if ($pid && ($err eq "got timeout\n")) {
410 kill (9, $pid);
411 waitpid ($pid, 0);
412 die "command '$cmdstr' failed: $err";
413 }
414
415 if ($errmsg) {
416 die "$errmsg: $err";
417 } else {
418 die "command '$cmdstr' failed: $err";
419 }
420 }
421
422 return undef;
423 }
424
425 sub split_list {
426 my $listtxt = shift || '';
427
428 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
429
430 $listtxt =~ s/[,;]/ /g;
431 $listtxt =~ s/^\s+//;
432
433 my @data = split (/\s+/, $listtxt);
434
435 return @data;
436 }
437
438 sub trim {
439 my $txt = shift;
440
441 return $txt if !defined($txt);
442
443 $txt =~ s/^\s+//;
444 $txt =~ s/\s+$//;
445
446 return $txt;
447 }
448
449 # simple uri templates like "/vms/{vmid}"
450 sub template_replace {
451 my ($tmpl, $data) = @_;
452
453 my $res = '';
454 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
455 $res .= $1 if $1;
456 $res .= ($data->{$3} || '-') if $2;
457 }
458 return $res;
459 }
460
461 sub safe_print {
462 my ($filename, $fh, $data) = @_;
463
464 return if !$data;
465
466 my $res = print $fh $data;
467
468 die "write to '$filename' failed\n" if !$res;
469 }
470
471 sub debmirrors {
472
473 return {
474 'at' => 'ftp.at.debian.org',
475 'au' => 'ftp.au.debian.org',
476 'be' => 'ftp.be.debian.org',
477 'bg' => 'ftp.bg.debian.org',
478 'br' => 'ftp.br.debian.org',
479 'ca' => 'ftp.ca.debian.org',
480 'ch' => 'ftp.ch.debian.org',
481 'cl' => 'ftp.cl.debian.org',
482 'cz' => 'ftp.cz.debian.org',
483 'de' => 'ftp.de.debian.org',
484 'dk' => 'ftp.dk.debian.org',
485 'ee' => 'ftp.ee.debian.org',
486 'es' => 'ftp.es.debian.org',
487 'fi' => 'ftp.fi.debian.org',
488 'fr' => 'ftp.fr.debian.org',
489 'gr' => 'ftp.gr.debian.org',
490 'hk' => 'ftp.hk.debian.org',
491 'hr' => 'ftp.hr.debian.org',
492 'hu' => 'ftp.hu.debian.org',
493 'ie' => 'ftp.ie.debian.org',
494 'is' => 'ftp.is.debian.org',
495 'it' => 'ftp.it.debian.org',
496 'jp' => 'ftp.jp.debian.org',
497 'kr' => 'ftp.kr.debian.org',
498 'mx' => 'ftp.mx.debian.org',
499 'nl' => 'ftp.nl.debian.org',
500 'no' => 'ftp.no.debian.org',
501 'nz' => 'ftp.nz.debian.org',
502 'pl' => 'ftp.pl.debian.org',
503 'pt' => 'ftp.pt.debian.org',
504 'ro' => 'ftp.ro.debian.org',
505 'ru' => 'ftp.ru.debian.org',
506 'se' => 'ftp.se.debian.org',
507 'si' => 'ftp.si.debian.org',
508 'sk' => 'ftp.sk.debian.org',
509 'tr' => 'ftp.tr.debian.org',
510 'tw' => 'ftp.tw.debian.org',
511 'gb' => 'ftp.uk.debian.org',
512 'us' => 'ftp.us.debian.org',
513 };
514 }
515
516 my $keymaphash = {
517 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
518 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
519 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
520 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
521 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
522 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
523 #'et' => [], # Ethopia or Estonia ??
524 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
525 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
526 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
527 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
528 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
529 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
530 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
531 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
532 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
533 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
534 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
535 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
536 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
537 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
538 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
539 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
540 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
541 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
542 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
543 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
544 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
545 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
546 #'sv' => [], Swedish ?
547 #'th' => [],
548 #'tr' => [],
549 };
550
551 my $kvmkeymaparray = [];
552 foreach my $lc (keys %$keymaphash) {
553 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
554 }
555
556 sub kvmkeymaps {
557 return $keymaphash;
558 }
559
560 sub kvmkeymaplist {
561 return $kvmkeymaparray;
562 }
563
564 sub extract_param {
565 my ($param, $key) = @_;
566
567 my $res = $param->{$key};
568 delete $param->{$key};
569
570 return $res;
571 }
572
573 sub next_vnc_port {
574
575 for (my $p = 5900; $p < 6000; $p++) {
576
577 my $sock = IO::Socket::INET->new (Listen => 5,
578 LocalAddr => 'localhost',
579 LocalPort => $p,
580 ReuseAddr => 1,
581 Proto => 0);
582
583 if ($sock) {
584 close ($sock);
585 return $p;
586 }
587 }
588
589 die "unable to find free vnc port";
590 };
591
592 # NOTE: NFS syscall can't be interrupted, so alarm does
593 # not work to provide timeouts.
594 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
595 # So the spawn external 'df' process instead of using
596 # Filesys::Df (which uses statfs syscall)
597 sub df {
598 my ($path, $timeout) = @_;
599
600 my $cmd = [ 'df', '-P', '-B', '1', $path];
601
602 my $res = {
603 total => 0,
604 used => 0,
605 avail => 0,
606 };
607
608 my $parser = sub {
609 my $line = shift;
610 if (my ($fsid, $total, $used, $avail) = $line =~
611 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
612 $res = {
613 total => $total,
614 used => $used,
615 avail => $avail,
616 };
617 }
618 };
619 eval { run_command($cmd, timeout => $timeout, outfunc => $parser); };
620 warn $@ if $@;
621
622 return $res;
623 }
624
625 # UPID helper
626 # We use this to uniquely identify a process.
627 # An 'Unique Process ID' has the following format:
628 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
629
630 sub upid_encode {
631 my $d = shift;
632
633 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
634 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
635 $d->{user});
636 }
637
638 sub upid_decode {
639 my ($upid, $noerr) = @_;
640
641 my $res;
642 my $filename;
643
644 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
645 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]+):$/) {
646 $res->{node} = $1;
647 $res->{pid} = hex($2);
648 $res->{pstart} = hex($3);
649 $res->{starttime} = hex($4);
650 $res->{type} = $5;
651 $res->{id} = $6;
652 $res->{user} = $7;
653
654 my $subdir = substr($4, 7, 8);
655 $filename = "$pvetaskdir/$subdir/$upid";
656
657 } else {
658 return undef if $noerr;
659 die "unable to parse worker upid '$upid'\n";
660 }
661
662 return wantarray ? ($res, $filename) : $res;
663 }
664
665 sub upid_open {
666 my ($upid) = @_;
667
668 my ($task, $filename) = upid_decode($upid);
669
670 my $dirname = dirname($filename);
671 make_path($dirname);
672
673 my $wwwid = getpwnam('www-data') ||
674 die "getpwnam failed";
675
676 my $perm = 0640;
677
678 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
679 die "unable to create output file '$filename' - $!\n";
680 chown $wwwid, -1, $outfh;
681
682 return $outfh;
683 };
684
685 sub upid_read_status {
686 my ($upid) = @_;
687
688 my ($task, $filename) = upid_decode($upid);
689 my $fh = IO::File->new($filename, "r");
690 return "unable to open file - $!" if !$fh;
691 my $maxlen = 1024;
692 sysseek($fh, -$maxlen, 2);
693 my $readbuf = '';
694 my $br = sysread($fh, $readbuf, $maxlen);
695 close($fh);
696 if ($br) {
697 return "unable to extract last line"
698 if $readbuf !~ m/\n?(.+)$/;
699 my $line = $1;
700 if ($line =~ m/^TASK OK$/) {
701 return 'OK';
702 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
703 return $1;
704 } else {
705 return "unexpected status";
706 }
707 }
708 return "unable to read tail (got $br bytes)";
709 }
710
711 # useful functions to store comments in config files
712 sub encode_text {
713 my ($text) = @_;
714
715 # all control and hi-bit characters, and ':'
716 my $unsafe = "^\x20-\x39\x3b-\x7e";
717 return uri_escape(Encode::encode("utf8", $text), $unsafe);
718 }
719
720 sub decode_text {
721 my ($data) = @_;
722
723 return Encode::decode("utf8", uri_unescape($data));
724 }
725
726 sub random_ether_addr {
727
728 my $rand = Digest::SHA1::sha1_hex(rand(), time());
729
730 my $mac = '';
731 for (my $i = 0; $i < 6; $i++) {
732 my $ss = hex(substr($rand, $i*2, 2));
733 if (!$i) {
734 $ss &= 0xfe; # clear multicast
735 $ss |= 2; # set local id
736 }
737 $ss = sprintf("%02X", $ss);
738
739 if (!$i) {
740 $mac .= "$ss";
741 } else {
742 $mac .= ":$ss";
743 }
744 }
745
746 return $mac;
747 }
748
749 sub shellquote {
750 my $str = shift;
751
752 return String::ShellQuote::shell_quote($str);
753 }
754
755 sub cmd2string {
756 my ($cmd) = @_;
757
758 die "no arguments" if !$cmd;
759
760 return $cmd if !ref($cmd);
761
762 my @qa = ();
763 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
764
765 return join (' ', @qa);
766 }
767
768 # split an shell argument string into an array,
769 sub split_args {
770 my ($str) = @_;
771
772 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
773 }
774
775 sub dump_logfile {
776 my ($filename, $start, $limit) = @_;
777
778 my $lines = [];
779 my $count = 0;
780
781 my $fh = IO::File->new($filename, "r");
782 if (!$fh) {
783 $count++;
784 push @$lines, { n => $count, t => "unable to open file - $!"};
785 return ($count, $lines);
786 }
787
788 $start = 0 if !$start;
789 $limit = 50 if !$limit;
790
791 my $line;
792 while (defined($line = <$fh>)) {
793 next if $count++ < $start;
794 next if $limit <= 0;
795 chomp $line;
796 push @$lines, { n => $count, t => $line};
797 $limit--;
798 }
799
800 close($fh);
801
802 # HACK: ExtJS store.guaranteeRange() does not like empty array
803 # so we add a line
804 if (!$count) {
805 $count++;
806 push @$lines, { n => $count, t => "no content"};
807 }
808
809 return ($count, $lines);
810 }
811
812 1;