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