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