]> git.proxmox.com Git - pve-common.git/blame - data/PVE/Tools.pm
split out run_with_timeout()
[pve-common.git] / data / PVE / Tools.pm
CommitLineData
e143e9d8
DM
1package PVE::Tools;
2
3use strict;
4use POSIX;
5use IO::Socket::INET;
6use IO::Select;
7use File::Basename;
8use File::Path qw(make_path);
9use IO::File;
10use IPC::Open3;
11use Fcntl qw(:DEFAULT :flock);
12use base 'Exporter';
13use URI::Escape;
14use Encode;
a413a515 15use Digest::SHA1;
e38bcd35 16use Text::ParseWords;
7514b23a 17use String::ShellQuote;
e143e9d8
DM
18
19our @EXPORT_OK = qw(
20lock_file
21run_command
22file_set_contents
23file_get_contents
24file_read_firstline
25split_list
26template_replace
27safe_print
28trim
29extract_param
30);
31
32my $pvelogdir = "/var/log/pve";
33my $pvetaskdir = "$pvelogdir/tasks";
34
35mkdir $pvelogdir;
36mkdir $pvetaskdir;
37
0f0990f1
DM
38sub run_with_timeout {
39 my ($timeout, $code, @param) = @_;
e143e9d8 40
0f0990f1 41 die "got timeout\n" if $timeout <= 0;
e143e9d8 42
0f0990f1
DM
43 my $prev_alarm;
44
45 my $sigcount = 0;
e143e9d8
DM
46
47 my $res;
48
0f0990f1 49 local $SIG{ALRM} = sub { $sigcount++; }; # catch alarm outside eval
e143e9d8
DM
50
51 eval {
0f0990f1
DM
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
e143e9d8 55
0f0990f1 56 $prev_alarm = alarm($timeout);
e143e9d8 57
0f0990f1
DM
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}
e143e9d8 73
0f0990f1
DM
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
77my $lock_handles = {};
78
79sub lock_file {
80 my ($filename, $timeout, $code, @param) = @_;
81
82 $timeout = 10 if !$timeout;
83
84 my $lock_func = sub {
e143e9d8
DM
85 if (!$lock_handles->{$$}->{$filename}) {
86 $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") ||
0f0990f1 87 die "can't open file - $!\n";
e143e9d8
DM
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";
0f0990f1 94 die "can't aquire lock - $!\n";
e143e9d8
DM
95 }
96 print STDERR " OK\n";
97 }
e143e9d8
DM
98 };
99
0f0990f1 100 my $res;
e143e9d8 101
0f0990f1
DM
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 }
e143e9d8
DM
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
127sub 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
154sub 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
167sub 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
178sub 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
199sub run_command {
200 my ($cmd, %param) = @_;
201
202 my $old_umask;
203
204 $cmd = [ $cmd ] if !ref($cmd);
205
65e1d3fc 206 my $cmdstr = cmd2string($cmd);
e143e9d8
DM
207
208 my $errmsg;
209 my $laststderr;
210 my $timeout;
211 my $oldtimeout;
212 my $pid;
213
4630cb95
DM
214 my $outfunc;
215 my $errfunc;
216 my $logfunc;
217 my $input;
218 my $output;
219
e143e9d8 220 eval {
e143e9d8
DM
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};
e143e9d8
DM
229 } elsif ($p eq 'input') {
230 $input = $param{$p};
1c50a24a
DM
231 } elsif ($p eq 'output') {
232 $output = $param{$p};
e143e9d8
DM
233 } elsif ($p eq 'outfunc') {
234 $outfunc = $param{$p};
235 } elsif ($p eq 'errfunc') {
236 $errfunc = $param{$p};
776fbfa8
DM
237 } elsif ($p eq 'logfunc') {
238 $logfunc = $param{$p};
e143e9d8
DM
239 } else {
240 die "got unknown parameter '$p' for run_command\n";
241 }
242 }
243
4630cb95
DM
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
1c50a24a
DM
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
e143e9d8
DM
262 # try to avoid locale related issues/warnings
263 my $lang = $param{lang} || 'C';
264
265 my $orig_pid = $$;
266
267 eval {
329351e2 268 local $ENV{LC_ALL} = $lang;
e143e9d8
DM
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 $!;
f38995ab
DM
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 }
e143e9d8
DM
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
f38995ab
DM
299 if (ref($writer)) {
300 print $writer $input if defined $input;
301 close $writer;
302 }
e143e9d8
DM
303
304 my $select = new IO::Select;
f38995ab 305 $select->add($reader) if ref($reader);
e143e9d8
DM
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) {
776fbfa8 327 if ($outfunc || $logfunc) {
e143e9d8
DM
328 eval {
329 $outlog .= $buf;
330 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
331 my $line = $1;
776fbfa8
DM
332 &$outfunc($line) if $outfunc;
333 &$logfunc($line) if $logfunc;
e143e9d8
DM
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) {
776fbfa8 347 if ($errfunc || $logfunc) {
e143e9d8
DM
348 eval {
349 $errlog .= $buf;
350 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
351 my $line = $1;
776fbfa8
DM
352 &$errfunc($line) if $errfunc;
353 &$logfunc($line) if $logfunc;
e143e9d8
DM
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;
776fbfa8
DM
371 &$logfunc($outlog) if $logfunc && $outlog;
372
e143e9d8 373 &$errfunc($errlog) if $errfunc && $errlog;
776fbfa8 374 &$logfunc($errlog) if $logfunc && $errlog;
e143e9d8
DM
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)) {
1c50a24a
DM
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";
e143e9d8 390 }
e143e9d8
DM
391 }
392
393 alarm(0);
394 };
395
396 my $err = $@;
397
398 alarm(0);
399
4630cb95
DM
400 if ($errmsg && $laststderr) {
401 &$errfunc(undef); # flush laststderr
402 }
e143e9d8
DM
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 }
1c50a24a
DM
421
422 return undef;
e143e9d8
DM
423}
424
425sub split_list {
426 my $listtxt = shift || '';
427
d2b0374d
DM
428 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
429
430 $listtxt =~ s/[,;]/ /g;
e143e9d8
DM
431 $listtxt =~ s/^\s+//;
432
433 my @data = split (/\s+/, $listtxt);
434
435 return @data;
436}
437
438sub 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}"
450sub 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
461sub 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
471sub 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
516sub kvmkeymaps {
517 return {
518 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
519 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
520 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
521 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
522 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
523 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
524 #'et' => [], # Ethopia or Estonia ??
525 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
526 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
527 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
528 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
529 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
530 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
531 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
532 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
533 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
534 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
535 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
536 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
537 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
538 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
539 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
540 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
541 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
542 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
543 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
544 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
545 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
546 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
547 #'sv' => [], Swedish ?
548 #'th' => [],
549 #'tr' => [],
550 };
551}
552
553sub extract_param {
554 my ($param, $key) = @_;
555
556 my $res = $param->{$key};
557 delete $param->{$key};
558
559 return $res;
560}
561
562sub next_vnc_port {
563
564 for (my $p = 5900; $p < 6000; $p++) {
565
566 my $sock = IO::Socket::INET->new (Listen => 5,
567 LocalAddr => 'localhost',
568 LocalPort => $p,
569 ReuseAddr => 1,
570 Proto => 0);
571
572 if ($sock) {
573 close ($sock);
574 return $p;
575 }
576 }
577
578 die "unable to find free vnc port";
579};
580
581# NOTE: NFS syscall can't be interrupted, so alarm does
582# not work to provide timeouts.
583# from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
584# So the spawn external 'df' process instead of using
585# Filesys::Df (which uses statfs syscall)
586sub df {
587 my ($path, $timeout) = @_;
588
589 my $cmd = [ 'df', '-P', '-B', '1', $path];
590
591 my $res = {
592 total => 0,
593 used => 0,
594 avail => 0,
595 };
596
597 my $parser = sub {
598 my $line = shift;
599 if (my ($fsid, $total, $used, $avail) = $line =~
600 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
601 $res = {
602 total => $total,
603 used => $used,
604 avail => $avail,
605 };
606 }
607 };
608 eval { run_command($cmd, timeout => $timeout, outfunc => $parser); };
609 warn $@ if $@;
610
611 return $res;
612}
613
614# UPID helper
615# We use this to uniquely identify a process.
616# An 'Unique Process ID' has the following format:
617# "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
618
619sub upid_encode {
620 my $d = shift;
621
622 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
623 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
624 $d->{user});
625}
626
627sub upid_decode {
628 my ($upid, $noerr) = @_;
629
630 my $res;
631 my $filename;
632
633 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
634 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]+):$/) {
635 $res->{node} = $1;
636 $res->{pid} = hex($2);
637 $res->{pstart} = hex($3);
638 $res->{starttime} = hex($4);
639 $res->{type} = $5;
640 $res->{id} = $6;
641 $res->{user} = $7;
642
643 my $subdir = substr($4, 7, 8);
644 $filename = "$pvetaskdir/$subdir/$upid";
645
646 } else {
647 return undef if $noerr;
648 die "unable to parse worker upid '$upid'\n";
649 }
650
651 return wantarray ? ($res, $filename) : $res;
652}
653
654sub upid_open {
655 my ($upid) = @_;
656
657 my ($task, $filename) = upid_decode($upid);
658
659 my $dirname = dirname($filename);
660 make_path($dirname);
661
662 my $wwwid = getpwnam('www-data') ||
663 die "getpwnam failed";
664
665 my $perm = 0640;
666
667 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
668 die "unable to create output file '$filename' - $!\n";
2b8e0f12 669 chown $wwwid, -1, $outfh;
e143e9d8
DM
670
671 return $outfh;
672};
673
674sub upid_read_status {
675 my ($upid) = @_;
676
677 my ($task, $filename) = upid_decode($upid);
678 my $fh = IO::File->new($filename, "r");
679 return "unable to open file - $!" if !$fh;
680 my $maxlen = 1024;
681 sysseek($fh, -$maxlen, 2);
682 my $readbuf = '';
683 my $br = sysread($fh, $readbuf, $maxlen);
684 close($fh);
685 if ($br) {
686 return "unable to extract last line"
687 if $readbuf !~ m/\n?(.+)$/;
688 my $line = $1;
689 if ($line =~ m/^TASK OK$/) {
690 return 'OK';
691 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
692 return $1;
693 } else {
694 return "unexpected status";
695 }
696 }
697 return "unable to read tail (got $br bytes)";
698}
699
700# useful functions to store comments in config files
701sub encode_text {
702 my ($text) = @_;
703
704 # all control and hi-bit characters, and ':'
705 my $unsafe = "^\x20-\x39\x3b-\x7e";
706 return uri_escape(Encode::encode("utf8", $text), $unsafe);
707}
708
709sub decode_text {
710 my ($data) = @_;
711
712 return Encode::decode("utf8", uri_unescape($data));
713}
714
a413a515
DM
715sub random_ether_addr {
716
717 my $rand = Digest::SHA1::sha1_hex(rand(), time());
718
719 my $mac = '';
720 for (my $i = 0; $i < 6; $i++) {
721 my $ss = hex(substr($rand, $i*2, 2));
722 if (!$i) {
723 $ss &= 0xfe; # clear multicast
724 $ss |= 2; # set local id
725 }
726 $ss = sprintf("%02X", $ss);
727
728 if (!$i) {
729 $mac .= "$ss";
730 } else {
731 $mac .= ":$ss";
732 }
733 }
734
735 return $mac;
736}
e143e9d8 737
762e3223
DM
738sub shellquote {
739 my $str = shift;
740
7514b23a 741 return String::ShellQuote::shell_quote($str);
762e3223
DM
742}
743
65e1d3fc
DM
744sub cmd2string {
745 my ($cmd) = @_;
746
747 die "no arguments" if !$cmd;
748
749 return $cmd if !ref($cmd);
750
751 my @qa = ();
752 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
753
754 return join (' ', @qa);
755}
756
e38bcd35 757# split an shell argument string into an array,
f9125663
DM
758sub split_args {
759 my ($str) = @_;
760
e38bcd35 761 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
f9125663
DM
762}
763
804b1041
DM
764sub dump_logfile {
765 my ($filename, $start, $limit) = @_;
766
767 my $lines = [];
768 my $count = 0;
769
770 my $fh = IO::File->new($filename, "r");
771 if (!$fh) {
772 $count++;
773 push @$lines, { n => $count, t => "unable to open file - $!"};
774 return ($count, $lines);
775 }
776
777 $start = 0 if !$start;
778 $limit = 50 if !$limit;
779
780 my $line;
781 while (defined($line = <$fh>)) {
782 next if $count++ < $start;
783 next if $limit <= 0;
784 chomp $line;
785 push @$lines, { n => $count, t => $line};
786 $limit--;
787 }
788
789 close($fh);
790
791 # HACK: ExtJS store.guaranteeRange() does not like empty array
792 # so we add a line
793 if (!$count) {
794 $count++;
795 push @$lines, { n => $count, t => "no content"};
796 }
797
798 return ($count, $lines);
799}
800
e143e9d8 8011;