added: enter_systemd_scope
[pve-common.git] / src / PVE / Tools.pm
1 package PVE::Tools;
2
3 use strict;
4 use warnings;
5 use POSIX qw(EINTR);
6 use IO::Socket::IP;
7 use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED);
8 use IO::Select;
9 use File::Basename;
10 use File::Path qw(make_path);
11 use Filesys::Df (); # don't overwrite our df()
12 use IO::Pipe;
13 use IO::File;
14 use IO::Dir;
15 use IO::Handle;
16 use IPC::Open3;
17 use Fcntl qw(:DEFAULT :flock);
18 use base 'Exporter';
19 use URI::Escape;
20 use Encode;
21 use Digest::SHA;
22 use Text::ParseWords;
23 use String::ShellQuote;
24 use Time::HiRes qw(usleep gettimeofday tv_interval alarm);
25 use Net::DBus qw(dbus_uint32 dbus_uint64);
26 use Net::DBus::Callback;
27 use Net::DBus::Reactor;
28
29 # avoid warning when parsing long hex values with hex()
30 no warnings 'portable'; # Support for 64-bit ints required
31
32 our @EXPORT_OK = qw(
33 $IPV6RE
34 $IPV4RE
35 lock_file
36 lock_file_full
37 run_command
38 file_set_contents
39 file_get_contents
40 file_read_firstline
41 dir_glob_regex
42 dir_glob_foreach
43 split_list
44 template_replace
45 safe_print
46 trim
47 extract_param
48 file_copy
49 O_PATH
50 O_TMPFILE
51 );
52
53 my $pvelogdir = "/var/log/pve";
54 my $pvetaskdir = "$pvelogdir/tasks";
55
56 mkdir $pvelogdir;
57 mkdir $pvetaskdir;
58
59 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
60 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
61 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
62 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
63
64 our $IPV6RE = "(?:" .
65 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
66 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
67 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
68 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
69 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
70 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
71 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
72 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
73 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
74
75 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
76
77 use constant {CLONE_NEWNS => 0x00020000,
78 CLONE_NEWUTS => 0x04000000,
79 CLONE_NEWIPC => 0x08000000,
80 CLONE_NEWUSER => 0x10000000,
81 CLONE_NEWPID => 0x20000000,
82 CLONE_NEWNET => 0x40000000};
83
84 use constant {O_PATH => 0x00200000,
85 O_TMPFILE => 0x00410000}; # This includes O_DIRECTORY
86
87 sub run_with_timeout {
88 my ($timeout, $code, @param) = @_;
89
90 die "got timeout\n" if $timeout <= 0;
91
92 my $prev_alarm = alarm 0; # suspend outer alarm early
93
94 my $sigcount = 0;
95
96 my $res;
97
98 eval {
99 local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; };
100 local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" };
101 local $SIG{__DIE__}; # see SA bug 4631
102
103 alarm($timeout);
104
105 eval { $res = &$code(@param); };
106
107 alarm(0); # avoid race conditions
108
109 die $@ if $@;
110 };
111
112 my $err = $@;
113
114 alarm $prev_alarm;
115
116 # this shouldn't happen anymore?
117 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
118
119 die $err if $err;
120
121 return $res;
122 }
123
124 # flock: we use one file handle per process, so lock file
125 # can be called multiple times and succeeds for the same process.
126
127 my $lock_handles = {};
128
129 sub lock_file_full {
130 my ($filename, $timeout, $shared, $code, @param) = @_;
131
132 $timeout = 10 if !$timeout;
133
134 my $mode = $shared ? LOCK_SH : LOCK_EX;
135
136 my $lock_func = sub {
137 if (!$lock_handles->{$$}->{$filename}) {
138 my $fh = new IO::File(">>$filename") ||
139 die "can't open file - $!\n";
140 $lock_handles->{$$}->{$filename} = { fh => $fh, refcount => 0};
141 }
142
143 if (!flock($lock_handles->{$$}->{$filename}->{fh}, $mode|LOCK_NB)) {
144 print STDERR "trying to acquire lock...";
145 my $success;
146 while(1) {
147 $success = flock($lock_handles->{$$}->{$filename}->{fh}, $mode);
148 # try again on EINTR (see bug #273)
149 if ($success || ($! != EINTR)) {
150 last;
151 }
152 }
153 if (!$success) {
154 print STDERR " failed\n";
155 die "can't acquire lock '$filename' - $!\n";
156 }
157 print STDERR " OK\n";
158 }
159 $lock_handles->{$$}->{$filename}->{refcount}++;
160 };
161
162 my $res;
163
164 eval { run_with_timeout($timeout, $lock_func); };
165 my $err = $@;
166 if ($err) {
167 $err = "can't lock file '$filename' - $err";
168 } else {
169 eval { $res = &$code(@param) };
170 $err = $@;
171 }
172
173 if (my $fh = $lock_handles->{$$}->{$filename}->{fh}) {
174 my $refcount = --$lock_handles->{$$}->{$filename}->{refcount};
175 if ($refcount <= 0) {
176 $lock_handles->{$$}->{$filename} = undef;
177 close ($fh);
178 }
179 }
180
181 if ($err) {
182 $@ = $err;
183 return undef;
184 }
185
186 $@ = undef;
187
188 return $res;
189 }
190
191
192 sub lock_file {
193 my ($filename, $timeout, $code, @param) = @_;
194
195 return lock_file_full($filename, $timeout, 0, $code, @param);
196 }
197
198 sub file_set_contents {
199 my ($filename, $data, $perm) = @_;
200
201 $perm = 0644 if !defined($perm);
202
203 my $tmpname = "$filename.tmp.$$";
204
205 eval {
206 my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm);
207 die "unable to open file '$tmpname' - $!\n" if !$fh;
208 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
209 die "closing file '$tmpname' failed - $!\n" unless close $fh;
210 };
211 my $err = $@;
212
213 if ($err) {
214 unlink $tmpname;
215 die $err;
216 }
217
218 if (!rename($tmpname, $filename)) {
219 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
220 unlink $tmpname;
221 die $msg;
222 }
223 }
224
225 sub file_get_contents {
226 my ($filename, $max) = @_;
227
228 my $fh = IO::File->new($filename, "r") ||
229 die "can't open '$filename' - $!\n";
230
231 my $content = safe_read_from($fh, $max);
232
233 close $fh;
234
235 return $content;
236 }
237
238 sub file_copy {
239 my ($filename, $dst, $max, $perm) = @_;
240
241 file_set_contents ($dst, file_get_contents($filename, $max), $perm);
242 }
243
244 sub file_read_firstline {
245 my ($filename) = @_;
246
247 my $fh = IO::File->new ($filename, "r");
248 return undef if !$fh;
249 my $res = <$fh>;
250 chomp $res if $res;
251 $fh->close;
252 return $res;
253 }
254
255 sub safe_read_from {
256 my ($fh, $max, $oneline) = @_;
257
258 $max = 32768 if !$max;
259
260 my $br = 0;
261 my $input = '';
262 my $count;
263 while ($count = sysread($fh, $input, 8192, $br)) {
264 $br += $count;
265 die "input too long - aborting\n" if $br > $max;
266 if ($oneline && $input =~ m/^(.*)\n/) {
267 $input = $1;
268 last;
269 }
270 }
271 die "unable to read input - $!\n" if !defined($count);
272
273 return $input;
274 }
275
276 # The $cmd parameter can be:
277 # -) a string
278 # This is generally executed by passing it to the shell with the -c option.
279 # However, it can be executed in one of two ways, depending on whether
280 # there's a pipe involved:
281 # *) with pipe: passed explicitly to bash -c, prefixed with:
282 # set -o pipefail &&
283 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
284 # (Note that this may result in two different syntax requirements!)
285 # FIXME?
286 # -) an array of arguments (strings)
287 # Will be executed without interference from a shell. (Parameters are passed
288 # as is, no escape sequences of strings will be touched.)
289 # -) an array of arrays
290 # Each array represents a command, and each command's output is piped into
291 # the following command's standard input.
292 # For this a shell command string is created with pipe symbols between each
293 # command.
294 # Each command is a list of strings meant to end up in the final command
295 # unchanged. In order to achieve this, every argument is shell-quoted.
296 # Quoting can be disabled for a particular argument by turning it into a
297 # reference, this allows inserting arbitrary shell options.
298 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
299 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
300 # will literally print: hello >/dev/null
301 sub run_command {
302 my ($cmd, %param) = @_;
303
304 my $old_umask;
305 my $cmdstr;
306
307 if (my $ref = ref($cmd)) {
308 if (ref($cmd->[0])) {
309 $cmdstr = 'set -o pipefail && ';
310 my $pipe = '';
311 foreach my $command (@$cmd) {
312 # concatenate quoted parameters
313 # strings which are passed by reference are NOT shell quoted
314 $cmdstr .= $pipe . join(' ', map { ref($_) ? $$_ : shellquote($_) } @$command);
315 $pipe = ' | ';
316 }
317 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ];
318 } else {
319 $cmdstr = cmd2string($cmd);
320 }
321 } else {
322 $cmdstr = $cmd;
323 if ($cmd =~ m/\|/) {
324 # see 'man bash' for option pipefail
325 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
326 } else {
327 $cmd = [ $cmd ];
328 }
329 }
330
331 my $errmsg;
332 my $laststderr;
333 my $timeout;
334 my $oldtimeout;
335 my $pid;
336 my $exitcode;
337
338 my $outfunc;
339 my $errfunc;
340 my $logfunc;
341 my $input;
342 my $output;
343 my $afterfork;
344 my $noerr;
345
346 eval {
347
348 foreach my $p (keys %param) {
349 if ($p eq 'timeout') {
350 $timeout = $param{$p};
351 } elsif ($p eq 'umask') {
352 $old_umask = umask($param{$p});
353 } elsif ($p eq 'errmsg') {
354 $errmsg = $param{$p};
355 } elsif ($p eq 'input') {
356 $input = $param{$p};
357 } elsif ($p eq 'output') {
358 $output = $param{$p};
359 } elsif ($p eq 'outfunc') {
360 $outfunc = $param{$p};
361 } elsif ($p eq 'errfunc') {
362 $errfunc = $param{$p};
363 } elsif ($p eq 'logfunc') {
364 $logfunc = $param{$p};
365 } elsif ($p eq 'afterfork') {
366 $afterfork = $param{$p};
367 } elsif ($p eq 'noerr') {
368 $noerr = $param{$p};
369 } else {
370 die "got unknown parameter '$p' for run_command\n";
371 }
372 }
373
374 if ($errmsg) {
375 my $origerrfunc = $errfunc;
376 $errfunc = sub {
377 if ($laststderr) {
378 if ($origerrfunc) {
379 &$origerrfunc("$laststderr\n");
380 } else {
381 print STDERR "$laststderr\n" if $laststderr;
382 }
383 }
384 $laststderr = shift;
385 };
386 }
387
388 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
389 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
390 my $error = IO::File->new();
391
392 # try to avoid locale related issues/warnings
393 my $lang = $param{lang} || 'C';
394
395 my $orig_pid = $$;
396
397 eval {
398 local $ENV{LC_ALL} = $lang;
399
400 # suppress LVM warnings like: "File descriptor 3 left open";
401 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
402
403 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
404
405 # if we pipe fron STDIN, open3 closes STDIN, so we we
406 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
407 # as soon as we open a new file.
408 # to avoid that we open /dev/null
409 if (!ref($writer) && !defined(fileno(STDIN))) {
410 POSIX::close(0);
411 open(STDIN, "</dev/null");
412 }
413 };
414
415 my $err = $@;
416
417 # catch exec errors
418 if ($orig_pid != $$) {
419 warn "ERROR: $err";
420 POSIX::_exit (1);
421 kill ('KILL', $$);
422 }
423
424 die $err if $err;
425
426 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
427 $oldtimeout = alarm($timeout) if $timeout;
428
429 &$afterfork() if $afterfork;
430
431 if (ref($writer)) {
432 print $writer $input if defined $input;
433 close $writer;
434 }
435
436 my $select = new IO::Select;
437 $select->add($reader) if ref($reader);
438 $select->add($error);
439
440 my $outlog = '';
441 my $errlog = '';
442
443 my $starttime = time();
444
445 while ($select->count) {
446 my @handles = $select->can_read(1);
447
448 foreach my $h (@handles) {
449 my $buf = '';
450 my $count = sysread ($h, $buf, 4096);
451 if (!defined ($count)) {
452 my $err = $!;
453 kill (9, $pid);
454 waitpid ($pid, 0);
455 die $err;
456 }
457 $select->remove ($h) if !$count;
458 if ($h eq $reader) {
459 if ($outfunc || $logfunc) {
460 eval {
461 $outlog .= $buf;
462 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
463 my $line = $1;
464 &$outfunc($line) if $outfunc;
465 &$logfunc($line) if $logfunc;
466 }
467 };
468 my $err = $@;
469 if ($err) {
470 kill (9, $pid);
471 waitpid ($pid, 0);
472 die $err;
473 }
474 } else {
475 print $buf;
476 *STDOUT->flush();
477 }
478 } elsif ($h eq $error) {
479 if ($errfunc || $logfunc) {
480 eval {
481 $errlog .= $buf;
482 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
483 my $line = $1;
484 &$errfunc($line) if $errfunc;
485 &$logfunc($line) if $logfunc;
486 }
487 };
488 my $err = $@;
489 if ($err) {
490 kill (9, $pid);
491 waitpid ($pid, 0);
492 die $err;
493 }
494 } else {
495 print STDERR $buf;
496 *STDERR->flush();
497 }
498 }
499 }
500 }
501
502 &$outfunc($outlog) if $outfunc && $outlog;
503 &$logfunc($outlog) if $logfunc && $outlog;
504
505 &$errfunc($errlog) if $errfunc && $errlog;
506 &$logfunc($errlog) if $logfunc && $errlog;
507
508 waitpid ($pid, 0);
509
510 if ($? == -1) {
511 die "failed to execute\n";
512 } elsif (my $sig = ($? & 127)) {
513 die "got signal $sig\n";
514 } elsif ($exitcode = ($? >> 8)) {
515 if (!($exitcode == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
516 if ($errmsg && $laststderr) {
517 my $lerr = $laststderr;
518 $laststderr = undef;
519 die "$lerr\n";
520 }
521 die "exit code $exitcode\n";
522 }
523 }
524
525 alarm(0);
526 };
527
528 my $err = $@;
529
530 alarm(0);
531
532 if ($errmsg && $laststderr) {
533 &$errfunc(undef); # flush laststderr
534 }
535
536 umask ($old_umask) if defined($old_umask);
537
538 alarm($oldtimeout) if $oldtimeout;
539
540 if ($err) {
541 if ($pid && ($err eq "got timeout\n")) {
542 kill (9, $pid);
543 waitpid ($pid, 0);
544 die "command '$cmdstr' failed: $err";
545 }
546
547 if ($errmsg) {
548 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
549 die "$errmsg: $err";
550 } elsif(!$noerr) {
551 die "command '$cmdstr' failed: $err";
552 }
553 }
554
555 return $exitcode;
556 }
557
558 sub split_list {
559 my $listtxt = shift || '';
560
561 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
562
563 $listtxt =~ s/[,;]/ /g;
564 $listtxt =~ s/^\s+//;
565
566 my @data = split (/\s+/, $listtxt);
567
568 return @data;
569 }
570
571 sub trim {
572 my $txt = shift;
573
574 return $txt if !defined($txt);
575
576 $txt =~ s/^\s+//;
577 $txt =~ s/\s+$//;
578
579 return $txt;
580 }
581
582 # simple uri templates like "/vms/{vmid}"
583 sub template_replace {
584 my ($tmpl, $data) = @_;
585
586 return $tmpl if !$tmpl;
587
588 my $res = '';
589 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
590 $res .= $1 if $1;
591 $res .= ($data->{$3} || '-') if $2;
592 }
593 return $res;
594 }
595
596 sub safe_print {
597 my ($filename, $fh, $data) = @_;
598
599 return if !$data;
600
601 my $res = print $fh $data;
602
603 die "write to '$filename' failed\n" if !$res;
604 }
605
606 sub debmirrors {
607
608 return {
609 'at' => 'ftp.at.debian.org',
610 'au' => 'ftp.au.debian.org',
611 'be' => 'ftp.be.debian.org',
612 'bg' => 'ftp.bg.debian.org',
613 'br' => 'ftp.br.debian.org',
614 'ca' => 'ftp.ca.debian.org',
615 'ch' => 'ftp.ch.debian.org',
616 'cl' => 'ftp.cl.debian.org',
617 'cz' => 'ftp.cz.debian.org',
618 'de' => 'ftp.de.debian.org',
619 'dk' => 'ftp.dk.debian.org',
620 'ee' => 'ftp.ee.debian.org',
621 'es' => 'ftp.es.debian.org',
622 'fi' => 'ftp.fi.debian.org',
623 'fr' => 'ftp.fr.debian.org',
624 'gr' => 'ftp.gr.debian.org',
625 'hk' => 'ftp.hk.debian.org',
626 'hr' => 'ftp.hr.debian.org',
627 'hu' => 'ftp.hu.debian.org',
628 'ie' => 'ftp.ie.debian.org',
629 'is' => 'ftp.is.debian.org',
630 'it' => 'ftp.it.debian.org',
631 'jp' => 'ftp.jp.debian.org',
632 'kr' => 'ftp.kr.debian.org',
633 'mx' => 'ftp.mx.debian.org',
634 'nl' => 'ftp.nl.debian.org',
635 'no' => 'ftp.no.debian.org',
636 'nz' => 'ftp.nz.debian.org',
637 'pl' => 'ftp.pl.debian.org',
638 'pt' => 'ftp.pt.debian.org',
639 'ro' => 'ftp.ro.debian.org',
640 'ru' => 'ftp.ru.debian.org',
641 'se' => 'ftp.se.debian.org',
642 'si' => 'ftp.si.debian.org',
643 'sk' => 'ftp.sk.debian.org',
644 'tr' => 'ftp.tr.debian.org',
645 'tw' => 'ftp.tw.debian.org',
646 'gb' => 'ftp.uk.debian.org',
647 'us' => 'ftp.us.debian.org',
648 };
649 }
650
651 my $keymaphash = {
652 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
653 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
654 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
655 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
656 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
657 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
658 #'et' => [], # Ethopia or Estonia ??
659 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
660 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
661 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
662 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
663 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
664 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
665 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
666 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
667 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
668 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
669 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
670 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
671 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
672 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
673 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
674 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
675 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
676 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
677 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
678 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
679 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
680 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
681 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
682 #'th' => [],
683 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
684 };
685
686 my $kvmkeymaparray = [];
687 foreach my $lc (sort keys %$keymaphash) {
688 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
689 }
690
691 sub kvmkeymaps {
692 return $keymaphash;
693 }
694
695 sub kvmkeymaplist {
696 return $kvmkeymaparray;
697 }
698
699 sub extract_param {
700 my ($param, $key) = @_;
701
702 my $res = $param->{$key};
703 delete $param->{$key};
704
705 return $res;
706 }
707
708 # Note: we use this to wait until vncterm/spiceterm is ready
709 sub wait_for_vnc_port {
710 my ($port, $timeout) = @_;
711
712 $timeout = 5 if !$timeout;
713 my $sleeptime = 0;
714 my $starttime = [gettimeofday];
715 my $elapsed;
716
717 while (($elapsed = tv_interval($starttime)) < $timeout) {
718 if (my $fh = IO::File->new ("/proc/net/tcp", "r")) {
719 while (defined (my $line = <$fh>)) {
720 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
721 if ($port == hex($2)) {
722 close($fh);
723 return 1;
724 }
725 }
726 }
727 close($fh);
728 }
729 $sleeptime += 100000 if $sleeptime < 1000000;
730 usleep($sleeptime);
731 }
732
733 return undef;
734 }
735
736 sub next_unused_port {
737 my ($range_start, $range_end, $family) = @_;
738
739 # We use a file to register allocated ports.
740 # Those registrations expires after $expiretime.
741 # We use this to avoid race conditions between
742 # allocation and use of ports.
743
744 my $filename = "/var/tmp/pve-reserved-ports";
745
746 my $code = sub {
747
748 my $expiretime = 5;
749 my $ctime = time();
750
751 my $ports = {};
752
753 if (my $fh = IO::File->new ($filename, "r")) {
754 while (my $line = <$fh>) {
755 if ($line =~ m/^(\d+)\s(\d+)$/) {
756 my ($port, $timestamp) = ($1, $2);
757 if (($timestamp + $expiretime) > $ctime) {
758 $ports->{$port} = $timestamp; # not expired
759 }
760 }
761 }
762 }
763
764 my $newport;
765
766 for (my $p = $range_start; $p < $range_end; $p++) {
767 next if $ports->{$p}; # reserved
768
769 my $sock = IO::Socket::IP->new(Listen => 5,
770 LocalPort => $p,
771 ReuseAddr => 1,
772 Family => $family,
773 Proto => 0,
774 GetAddrInfoFlags => 0);
775
776 if ($sock) {
777 close($sock);
778 $newport = $p;
779 $ports->{$p} = $ctime;
780 last;
781 }
782 }
783
784 my $data = "";
785 foreach my $p (keys %$ports) {
786 $data .= "$p $ports->{$p}\n";
787 }
788
789 file_set_contents($filename, $data);
790
791 return $newport;
792 };
793
794 my $p = lock_file($filename, 10, $code);
795 die $@ if $@;
796
797 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
798
799 return $p;
800 }
801
802 sub next_migrate_port {
803 my ($family) = @_;
804 return next_unused_port(60000, 60050, $family);
805 }
806
807 sub next_vnc_port {
808 my ($family) = @_;
809 return next_unused_port(5900, 6000, $family);
810 }
811
812 sub next_spice_port {
813 my ($family) = @_;
814 return next_unused_port(61000, 61099, $family);
815 }
816
817 # NOTE: NFS syscall can't be interrupted, so alarm does
818 # not work to provide timeouts.
819 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
820 # So fork() before using Filesys::Df
821 sub df {
822 my ($path, $timeout) = @_;
823
824 my $res = {
825 total => 0,
826 used => 0,
827 avail => 0,
828 };
829
830 my $pipe = IO::Pipe->new();
831 my $child = fork();
832 if (!defined($child)) {
833 warn "fork failed: $!\n";
834 return $res;
835 }
836
837 if (!$child) {
838 $pipe->writer();
839 eval {
840 my $df = Filesys::Df::df($path, 1);
841 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
842 $pipe->close();
843 };
844 if (my $err = $@) {
845 warn $err;
846 POSIX::_exit(1);
847 }
848 POSIX::_exit(0);
849 }
850
851 $pipe->reader();
852
853 my $readvalues = sub {
854 $res->{total} = int(<$pipe>);
855 $res->{used} = int(<$pipe>);
856 $res->{avail} = int(<$pipe>);
857 };
858 eval {
859 run_with_timeout($timeout, $readvalues);
860 };
861 warn $@ if $@;
862 $pipe->close();
863 kill('KILL', $child);
864 waitpid($child, 0);
865 return $res;
866 }
867
868 # UPID helper
869 # We use this to uniquely identify a process.
870 # An 'Unique Process ID' has the following format:
871 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
872
873 sub upid_encode {
874 my $d = shift;
875
876 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
877 # more that 8 characters for pstart
878 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
879 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
880 $d->{user});
881 }
882
883 sub upid_decode {
884 my ($upid, $noerr) = @_;
885
886 my $res;
887 my $filename;
888
889 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
890 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
891 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]+):$/) {
892 $res->{node} = $1;
893 $res->{pid} = hex($3);
894 $res->{pstart} = hex($4);
895 $res->{starttime} = hex($5);
896 $res->{type} = $6;
897 $res->{id} = $7;
898 $res->{user} = $8;
899
900 my $subdir = substr($5, 7, 8);
901 $filename = "$pvetaskdir/$subdir/$upid";
902
903 } else {
904 return undef if $noerr;
905 die "unable to parse worker upid '$upid'\n";
906 }
907
908 return wantarray ? ($res, $filename) : $res;
909 }
910
911 sub upid_open {
912 my ($upid) = @_;
913
914 my ($task, $filename) = upid_decode($upid);
915
916 my $dirname = dirname($filename);
917 make_path($dirname);
918
919 my $wwwid = getpwnam('www-data') ||
920 die "getpwnam failed";
921
922 my $perm = 0640;
923
924 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
925 die "unable to create output file '$filename' - $!\n";
926 chown $wwwid, -1, $outfh;
927
928 return $outfh;
929 };
930
931 sub upid_read_status {
932 my ($upid) = @_;
933
934 my ($task, $filename) = upid_decode($upid);
935 my $fh = IO::File->new($filename, "r");
936 return "unable to open file - $!" if !$fh;
937 my $maxlen = 4096;
938 sysseek($fh, -$maxlen, 2);
939 my $readbuf = '';
940 my $br = sysread($fh, $readbuf, $maxlen);
941 close($fh);
942 if ($br) {
943 return "unable to extract last line"
944 if $readbuf !~ m/\n?(.+)$/;
945 my $line = $1;
946 if ($line =~ m/^TASK OK$/) {
947 return 'OK';
948 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
949 return $1;
950 } else {
951 return "unexpected status";
952 }
953 }
954 return "unable to read tail (got $br bytes)";
955 }
956
957 # useful functions to store comments in config files
958 sub encode_text {
959 my ($text) = @_;
960
961 # all control and hi-bit characters, and ':'
962 my $unsafe = "^\x20-\x39\x3b-\x7e";
963 return uri_escape(Encode::encode("utf8", $text), $unsafe);
964 }
965
966 sub decode_text {
967 my ($data) = @_;
968
969 return Encode::decode("utf8", uri_unescape($data));
970 }
971
972 sub decode_utf8_parameters {
973 my ($param) = @_;
974
975 foreach my $p (qw(comment description firstname lastname)) {
976 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
977 }
978
979 return $param;
980 }
981
982 sub random_ether_addr {
983
984 my ($seconds, $microseconds) = gettimeofday;
985
986 my $rand = Digest::SHA::sha1_hex($$, rand(), $seconds, $microseconds);
987
988 # clear multicast, set local id
989 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
990
991 return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
992 }
993
994 sub shellquote {
995 my $str = shift;
996
997 return String::ShellQuote::shell_quote($str);
998 }
999
1000 sub cmd2string {
1001 my ($cmd) = @_;
1002
1003 die "no arguments" if !$cmd;
1004
1005 return $cmd if !ref($cmd);
1006
1007 my @qa = ();
1008 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
1009
1010 return join (' ', @qa);
1011 }
1012
1013 # split an shell argument string into an array,
1014 sub split_args {
1015 my ($str) = @_;
1016
1017 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
1018 }
1019
1020 sub dump_logfile {
1021 my ($filename, $start, $limit, $filter) = @_;
1022
1023 my $lines = [];
1024 my $count = 0;
1025
1026 my $fh = IO::File->new($filename, "r");
1027 if (!$fh) {
1028 $count++;
1029 push @$lines, { n => $count, t => "unable to open file - $!"};
1030 return ($count, $lines);
1031 }
1032
1033 $start = 0 if !$start;
1034 $limit = 50 if !$limit;
1035
1036 my $line;
1037
1038 if ($filter) {
1039 # duplicate code, so that we do not slow down normal path
1040 while (defined($line = <$fh>)) {
1041 next if $line !~ m/$filter/;
1042 next if $count++ < $start;
1043 next if $limit <= 0;
1044 chomp $line;
1045 push @$lines, { n => $count, t => $line};
1046 $limit--;
1047 }
1048 } else {
1049 while (defined($line = <$fh>)) {
1050 next if $count++ < $start;
1051 next if $limit <= 0;
1052 chomp $line;
1053 push @$lines, { n => $count, t => $line};
1054 $limit--;
1055 }
1056 }
1057
1058 close($fh);
1059
1060 # HACK: ExtJS store.guaranteeRange() does not like empty array
1061 # so we add a line
1062 if (!$count) {
1063 $count++;
1064 push @$lines, { n => $count, t => "no content"};
1065 }
1066
1067 return ($count, $lines);
1068 }
1069
1070 sub dump_journal {
1071 my ($start, $limit, $since, $until) = @_;
1072
1073 my $lines = [];
1074 my $count = 0;
1075
1076 $start = 0 if !$start;
1077 $limit = 50 if !$limit;
1078
1079 my $parser = sub {
1080 my $line = shift;
1081
1082 return if $count++ < $start;
1083 return if $limit <= 0;
1084 push @$lines, { n => int($count), t => $line};
1085 $limit--;
1086 };
1087
1088 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1089
1090 push @$cmd, '--since', $since if $since;
1091 push @$cmd, '--until', $until if $until;
1092 run_command($cmd, outfunc => $parser);
1093
1094 # HACK: ExtJS store.guaranteeRange() does not like empty array
1095 # so we add a line
1096 if (!$count) {
1097 $count++;
1098 push @$lines, { n => $count, t => "no content"};
1099 }
1100
1101 return ($count, $lines);
1102 }
1103
1104 sub dir_glob_regex {
1105 my ($dir, $regex) = @_;
1106
1107 my $dh = IO::Dir->new ($dir);
1108 return wantarray ? () : undef if !$dh;
1109
1110 while (defined(my $tmp = $dh->read)) {
1111 if (my @res = $tmp =~ m/^($regex)$/) {
1112 $dh->close;
1113 return wantarray ? @res : $tmp;
1114 }
1115 }
1116 $dh->close;
1117
1118 return wantarray ? () : undef;
1119 }
1120
1121 sub dir_glob_foreach {
1122 my ($dir, $regex, $func) = @_;
1123
1124 my $dh = IO::Dir->new ($dir);
1125 if (defined $dh) {
1126 while (defined(my $tmp = $dh->read)) {
1127 if (my @res = $tmp =~ m/^($regex)$/) {
1128 &$func (@res);
1129 }
1130 }
1131 }
1132 }
1133
1134 sub assert_if_modified {
1135 my ($digest1, $digest2) = @_;
1136
1137 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1138 die "detected modified configuration - file changed by other user? Try again.\n";
1139 }
1140 }
1141
1142 # Digest for short strings
1143 # like FNV32a, but we only return 31 bits (positive numbers)
1144 sub fnv31a {
1145 my ($string) = @_;
1146
1147 my $hval = 0x811c9dc5;
1148
1149 foreach my $c (unpack('C*', $string)) {
1150 $hval ^= $c;
1151 $hval += (
1152 (($hval << 1) ) +
1153 (($hval << 4) ) +
1154 (($hval << 7) ) +
1155 (($hval << 8) ) +
1156 (($hval << 24) ) );
1157 $hval = $hval & 0xffffffff;
1158 }
1159 return $hval & 0x7fffffff;
1160 }
1161
1162 sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1163
1164 sub unpack_sockaddr_in46 {
1165 my ($sin) = @_;
1166 my $family = Socket::sockaddr_family($sin);
1167 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1168 : Socket::unpack_sockaddr_in($sin));
1169 return ($family, $port, $host);
1170 }
1171
1172 sub getaddrinfo_all {
1173 my ($hostname, @opts) = @_;
1174 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
1175 @opts );
1176 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
1177 die "failed to get address info for: $hostname: $err\n" if $err;
1178 return @res;
1179 }
1180
1181 sub get_host_address_family {
1182 my ($hostname, $socktype) = @_;
1183 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1184 return $res[0]->{family};
1185 }
1186
1187 # Parses any sane kind of host, or host+port pair:
1188 # The port is always optional and thus may be undef.
1189 sub parse_host_and_port {
1190 my ($address) = @_;
1191 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1192 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1193 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1194 {
1195 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1196 }
1197 return; # nothing
1198 }
1199
1200 sub unshare($) {
1201 my ($flags) = @_;
1202 return 0 == syscall(272, $flags);
1203 }
1204
1205 sub setns($$) {
1206 my ($fileno, $nstype) = @_;
1207 return 0 == syscall(308, $fileno, $nstype);
1208 }
1209
1210 sub syncfs($) {
1211 my ($fileno) = @_;
1212 return 0 == syscall(306, $fileno);
1213 }
1214
1215 sub sync_mountpoint {
1216 my ($path) = @_;
1217 sysopen my $fd, $path, O_PATH or die "failed to open $path: $!\n";
1218 my $result = syncfs(fileno($fd));
1219 close($fd);
1220 return $result;
1221 }
1222
1223 # support sending multi-part mail messages with a text and or a HTML part
1224 # mailto may be a single email string or an array of receivers
1225 sub sendmail {
1226 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1227
1228 $mailto = [ $mailto ] if !ref($mailto);
1229
1230 my $rcvrarg = '';
1231 foreach my $r (@$mailto) {
1232 $rcvrarg .= " '$r'";
1233 }
1234 my $rcvrtxt = join (', ', @$mailto);
1235
1236 $mailfrom = $mailfrom || "root";
1237 $author = $author || 'Proxmox VE';
1238
1239 open (MAIL,"|sendmail -B 8BITMIME -f $mailfrom $rcvrarg") ||
1240 die "unable to open 'sendmail' - $!";
1241
1242 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1243 my $boundary = "----_=_NextPart_001_".int(time).$$;
1244
1245 print MAIL "Content-Type: multipart/alternative;\n";
1246 print MAIL "\tboundary=\"$boundary\"\n";
1247 print MAIL "MIME-Version: 1.0\n";
1248
1249 print MAIL "FROM: $author <$mailfrom>\n";
1250 print MAIL "TO: $rcvrtxt\n";
1251 print MAIL "SUBJECT: $subject\n";
1252 print MAIL "\n";
1253 print MAIL "This is a multi-part message in MIME format.\n\n";
1254 print MAIL "--$boundary\n";
1255
1256 if (defined($text)) {
1257 print MAIL "Content-Type: text/plain;\n";
1258 print MAIL "\tcharset=\"UTF8\"\n";
1259 print MAIL "Content-Transfer-Encoding: 8bit\n";
1260 print MAIL "\n";
1261
1262 # avoid 'remove extra line breaks' issue (MS Outlook)
1263 my $fill = ' ';
1264 $text =~ s/^/$fill/gm;
1265
1266 print MAIL $text;
1267
1268 print MAIL "\n--$boundary\n";
1269 }
1270
1271 if (defined($html)) {
1272 print MAIL "Content-Type: text/html;\n";
1273 print MAIL "\tcharset=\"UTF8\"\n";
1274 print MAIL "Content-Transfer-Encoding: 8bit\n";
1275 print MAIL "\n";
1276
1277 print MAIL $html;
1278
1279 print MAIL "\n--$boundary--\n";
1280 }
1281
1282 close(MAIL);
1283 }
1284
1285 sub tempfile {
1286 my ($perm, %opts) = @_;
1287
1288 # default permissions are stricter than with file_set_contents
1289 $perm = 0600 if !defined($perm);
1290
1291 my $dir = $opts{dir} // '/tmp';
1292 my $mode = $opts{mode} // O_RDWR;
1293 $mode |= O_EXCL if !$opts{allow_links};
1294
1295 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm)
1296 or die "failed to create tempfile: $!\n";
1297 return $fh;
1298 }
1299
1300 sub tempfile_contents {
1301 my ($data, $perm, %opts) = @_;
1302
1303 my $fh = tempfile($perm, %opts);
1304 eval {
1305 die "unable to write to tempfile: $!\n" if !print {$fh} $data;
1306 die "unable to flush to tempfile: $!\n" if !defined($fh->flush());
1307 };
1308 if (my $err = $@) {
1309 close $fh;
1310 die $err;
1311 }
1312
1313 return ("/proc/$$/fd/".$fh->fileno, $fh);
1314 }
1315
1316 sub validate_ssh_public_keys {
1317 my ($raw) = @_;
1318 my @lines = split(/\n/, $raw);
1319
1320 foreach my $line (@lines) {
1321 next if $line =~ m/^\s*$/;
1322 eval {
1323 my ($filename, $handle) = tempfile_contents($line);
1324 run_command(["ssh-keygen", "-l", "-f", $filename],
1325 outfunc => sub {}, errfunc => sub {});
1326 };
1327 die "SSH public key validation error\n" if $@;
1328 }
1329 }
1330
1331 sub openat($$$;$) {
1332 my ($dirfd, $pathname, $flags, $mode) = @_;
1333 my $fd = syscall(257, $dirfd, $pathname, $flags, $mode//0);
1334 return undef if $fd < 0;
1335 # sysopen() doesn't deal with numeric file descriptors apparently
1336 # so we need to convert to a mode string for IO::Handle->new_from_fd
1337 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1338 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1339 return $handle if $handle;
1340 my $err = $!; # save error before closing the raw fd
1341 syscall(3, $fd); # close
1342 $! = $err;
1343 return undef;
1344 }
1345
1346 sub mkdirat($$$) {
1347 my ($dirfd, $name, $mode) = @_;
1348 return syscall(258, $dirfd, $name, $mode) == 0;
1349 }
1350
1351 # NOTE: This calls the dbus main loop and must not be used when another dbus
1352 # main loop is being used as we need to wait for the JobRemoved signal.
1353 # Polling the job status instead doesn't work because this doesn't give us the
1354 # distinction between success and failure.
1355 #
1356 # Note that the description is mandatory for security reasons.
1357 sub enter_systemd_scope {
1358 my ($unit, $description, %extra) = @_;
1359 die "missing description\n" if !defined($description);
1360
1361 my $timeout = delete $extra{timeout};
1362
1363 $unit .= '.scope';
1364 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1365
1366 foreach my $key (keys %extra) {
1367 if ($key eq 'Slice' || $key eq 'KillMode') {
1368 push @$properties, [$key, $extra{$key}];
1369 } elsif ($key eq 'CPUShares') {
1370 push @$properties, [$key, dbus_uint64($extra{$key})];
1371 } elsif ($key eq 'CPUQuota') {
1372 push @$properties, ['CPUQuotaPerSecUSec',
1373 dbus_uint64($extra{$key} * 10000)];
1374 } else {
1375 die "Don't know how to encode $key for systemd scope\n";
1376 }
1377 }
1378
1379 my $job;
1380 my $done = 0;
1381
1382 my $bus = Net::DBus->system();
1383 my $reactor = Net::DBus::Reactor->main();
1384
1385 my $service = $bus->get_service('org.freedesktop.systemd1');
1386 my $if = $service->get_object('/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager');
1387 # Connect to the JobRemoved signal since we want to wait for it to finish
1388 my $sigid;
1389 my $timer;
1390 my $cleanup = sub {
1391 my ($no_shutdown) = @_;
1392 $if->disconnect_from_signal('JobRemoved', $sigid) if defined($if);
1393 $if = undef;
1394 $sigid = undef;
1395 $reactor->remove_timeout($timer) if defined($timer);
1396 $timer = undef;
1397 return if $no_shutdown;
1398 $reactor->shutdown();
1399 };
1400
1401 $sigid = $if->connect_to_signal('JobRemoved', sub {
1402 my ($id, $removed_job, $signaled_unit, $result) = @_;
1403 return if $signaled_unit ne $unit || $removed_job ne $job;
1404 $cleanup->(0);
1405 die "systemd job failed\n" if $result ne 'done';
1406 $done = 1;
1407 });
1408
1409 my $on_timeout = sub {
1410 $cleanup->(0);
1411 die "systemd job timed out\n";
1412 };
1413
1414 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1415 if defined($timeout);
1416 $job = $if->StartTransientUnit($unit, 'fail', $properties, []);
1417 $reactor->run();
1418 $cleanup->(1);
1419 die "systemd job never completed\n" if !$done;
1420 }
1421
1422 1;