]> git.proxmox.com Git - pve-common.git/blob - src/PVE/INotify.pm
c52d99255c98d93e474e9a93f5e7621d99c25b71
[pve-common.git] / src / PVE / INotify.pm
1 package PVE::INotify;
2
3 # todo: maybe we do not need update_file() ?
4
5 use strict;
6 use warnings;
7
8 use POSIX;
9 use IO::File;
10 use IO::Dir;
11 use File::stat;
12 use File::Basename;
13 use Fcntl qw(:DEFAULT :flock);
14 use PVE::SafeSyslog;
15 use PVE::Exception qw(raise_param_exc);
16 use PVE::Network;
17 use PVE::Tools;
18 use PVE::ProcFSTools;
19 use Clone qw(clone);
20 use Linux::Inotify2;
21 use base 'Exporter';
22 use JSON;
23 use Digest::SHA;
24 use Encode qw(encode decode);
25
26 our @EXPORT_OK = qw(read_file write_file register_file);
27
28 my $ccache;
29 my $ccachemap;
30 my $ccacheregex;
31 my $inotify;
32 my $inotify_pid = 0;
33 my $versions;
34 my $shadowfiles = {
35 '/etc/network/interfaces' => '/etc/network/interfaces.new',
36 };
37
38 # to enable cached operation, you need to call 'inotify_init'
39 # inotify handles are a limited resource, so use with care (only
40 # enable the cache if you really need it)
41
42 # Note: please close the inotify handle after you fork
43
44 sub ccache_default_writer {
45 my ($filename, $data) = @_;
46
47 die "undefined config writer for '$filename' :ERROR";
48 }
49
50 sub ccache_default_parser {
51 my ($filename, $srcfd) = @_;
52
53 die "undefined config reader for '$filename' :ERROR";
54 }
55
56 sub ccache_compute_diff {
57 my ($filename, $shadow) = @_;
58
59 my $diff = '';
60
61 my $cmd = ['/usr/bin/diff', '-b', '-N', '-u', $filename, $shadow];
62 PVE::Tools::run_command($cmd, noerr => 1, outfunc => sub {
63 my ($line) = @_;
64 $diff .= decode('UTF-8', $line) . "\n";
65 });
66
67 $diff = undef if !$diff;
68
69 return $diff;
70 }
71
72 sub ccache_info {
73 my ($filename) = @_;
74
75 foreach my $uid (keys %$ccacheregex) {
76 my $ccinfo = $ccacheregex->{$uid};
77 my $dir = $ccinfo->{dir};
78 my $regex = $ccinfo->{regex};
79 if ($filename =~ m|^$dir/+$regex$|) {
80 if (!$ccache->{$filename}) {
81 my $cp = {};
82 while (my ($k, $v) = each %$ccinfo) {
83 $cp->{$k} = $v;
84 }
85 $ccache->{$filename} = $cp;
86 }
87 return ($ccache->{$filename}, $filename);
88 }
89 }
90
91 $filename = $ccachemap->{$filename} if defined ($ccachemap->{$filename});
92
93 die "file '$filename' not added :ERROR" if !defined ($ccache->{$filename});
94
95 return ($ccache->{$filename}, $filename);
96 }
97
98 sub write_file {
99 my ($fileid, $data, $full) = @_;
100
101 my ($ccinfo, $filename) = ccache_info($fileid);
102
103 my $writer = $ccinfo->{writer};
104
105 my $realname = $filename;
106
107 my $shadow;
108 if ($shadow = $shadowfiles->{$filename}) {
109 $realname = $shadow;
110 }
111
112 my $perm = $ccinfo->{perm} || 0644;
113
114 my $tmpname = "$realname.tmp.$$";
115
116 my $res;
117 eval {
118 my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm);
119 die "unable to open file '$tmpname' - $!\n" if !$fh;
120
121 $res = &$writer($filename, $fh, $data);
122
123 die "closing file '$tmpname' failed - $!\n" unless close $fh;
124 };
125 my $err = $@;
126
127 $ccinfo->{version} = undef;
128
129 if ($err) {
130 unlink $tmpname;
131 die $err;
132 }
133
134 if (!rename($tmpname, $realname)) {
135 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
136 unlink $tmpname;
137 die $msg;
138 }
139
140 my $diff;
141 if ($shadow && $full) {
142 $diff = ccache_compute_diff ($filename, $shadow);
143 }
144
145 if ($full) {
146 return { data => $res, changes => $diff };
147 }
148
149 return $res;
150 }
151
152 sub update_file {
153 my ($fileid, $data, @args) = @_;
154
155 my ($ccinfo, $filename) = ccache_info($fileid);
156
157 my $update = $ccinfo->{update};
158
159 die "unable to update/merge data" if !$update;
160
161 my $lkfn = "$filename.lock";
162
163 my $timeout = 10;
164
165 my $fd;
166
167 my $code = sub {
168
169 $fd = IO::File->new ($filename, "r");
170
171 my $new = &$update($filename, $fd, $data, @args);
172
173 if (defined($new)) {
174 PVE::Tools::file_set_contents($filename, $new, $ccinfo->{perm});
175 } else {
176 unlink $filename;
177 }
178 };
179
180 PVE::Tools::lock_file($lkfn, $timeout, $code);
181 my $err = $@;
182
183 close($fd) if defined($fd);
184
185 die $err if $err;
186
187 return undef;
188 }
189
190 sub discard_changes {
191 my ($fileid, $full) = @_;
192
193 my ($ccinfo, $filename) = ccache_info($fileid);
194
195 if (my $copy = $shadowfiles->{$filename}) {
196 unlink $copy;
197 }
198
199 return read_file ($filename, $full);
200 }
201
202 sub poll_changes {
203 my ($filename) = @_;
204
205 poll() if $inotify; # read new inotify events
206
207 $versions->{$filename} = 0 if !defined ($versions->{$filename});
208
209 return $versions->{$filename};
210 }
211
212 sub read_file {
213 my ($fileid, $full) = @_;
214
215 my $parser;
216
217 my ($ccinfo, $filename) = ccache_info($fileid);
218
219 $parser = $ccinfo->{parser};
220
221 my $fd;
222 my $shadow;
223
224 my $cver = poll_changes($filename);
225
226 if (my $copy = $shadowfiles->{$filename}) {
227 if ($fd = IO::File->new ($copy, "r")) {
228 $shadow = $copy;
229 } else {
230 $fd = IO::File->new ($filename, "r");
231 }
232 } else {
233 $fd = IO::File->new ($filename, "r");
234 }
235
236 my $acp = $ccinfo->{always_call_parser};
237
238 if (!$fd) {
239 $ccinfo->{version} = undef;
240 $ccinfo->{data} = undef;
241 $ccinfo->{diff} = undef;
242 return undef if !$acp;
243 }
244
245 my $noclone = $ccinfo->{noclone};
246
247 # file unchanged?
248 if (!$ccinfo->{nocache} &&
249 $inotify && $cver &&
250 defined ($ccinfo->{data}) &&
251 defined ($ccinfo->{version}) &&
252 ($ccinfo->{readonce} ||
253 ($ccinfo->{version} == $cver))) {
254
255 my $ret;
256 if (!$noclone && ref ($ccinfo->{data})) {
257 $ret->{data} = clone ($ccinfo->{data});
258 } else {
259 $ret->{data} = $ccinfo->{data};
260 }
261 $ret->{changes} = $ccinfo->{diff};
262
263 return $full ? $ret : $ret->{data};
264 }
265
266 my $diff;
267
268 if ($shadow) {
269 $diff = ccache_compute_diff ($filename, $shadow);
270 }
271
272 my $res = &$parser($filename, $fd);
273
274 if (!$ccinfo->{nocache}) {
275 $ccinfo->{version} = $cver;
276 }
277
278 # we cache data with references, so we always need to
279 # clone this data. Else the original data may get
280 # modified.
281 $ccinfo->{data} = $res;
282
283 # also store diff
284 $ccinfo->{diff} = $diff;
285
286 my $ret;
287 if (!$noclone && ref ($ccinfo->{data})) {
288 $ret->{data} = clone ($ccinfo->{data});
289 } else {
290 $ret->{data} = $ccinfo->{data};
291 }
292 $ret->{changes} = $ccinfo->{diff};
293
294 return $full ? $ret : $ret->{data};
295 }
296
297 sub parse_ccache_options {
298 my ($ccinfo, %options) = @_;
299
300 foreach my $opt (keys %options) {
301 my $v = $options{$opt};
302 if ($opt eq 'readonce') {
303 $ccinfo->{$opt} = $v;
304 } elsif ($opt eq 'nocache') {
305 $ccinfo->{$opt} = $v;
306 } elsif ($opt eq 'shadow') {
307 $ccinfo->{$opt} = $v;
308 } elsif ($opt eq 'perm') {
309 $ccinfo->{$opt} = $v;
310 } elsif ($opt eq 'noclone') {
311 # noclone flag for large read-only data chunks like aplinfo
312 $ccinfo->{$opt} = $v;
313 } elsif ($opt eq 'always_call_parser') {
314 # when set, we call parser even when the file does not exists.
315 # this allows the parser to return some default
316 $ccinfo->{$opt} = $v;
317 } else {
318 die "internal error - unsupported option '$opt'";
319 }
320 }
321 }
322
323 sub register_file {
324 my ($id, $filename, $parser, $writer, $update, %options) = @_;
325
326 die "can't register file '$filename' after inotify_init" if $inotify;
327
328 die "file '$filename' already added :ERROR" if defined ($ccache->{$filename});
329 die "ID '$id' already used :ERROR" if defined ($ccachemap->{$id});
330
331 my $ccinfo = {};
332
333 $ccinfo->{id} = $id;
334 $ccinfo->{parser} = $parser || \&ccache_default_parser;
335 $ccinfo->{writer} = $writer || \&ccache_default_writer;
336 $ccinfo->{update} = $update;
337
338 parse_ccache_options($ccinfo, %options);
339
340 if ($options{shadow}) {
341 $shadowfiles->{$filename} = $options{shadow};
342 }
343
344 $ccachemap->{$id} = $filename;
345 $ccache->{$filename} = $ccinfo;
346 }
347
348 sub register_regex {
349 my ($dir, $regex, $parser, $writer, $update, %options) = @_;
350
351 die "can't register regex after inotify_init" if $inotify;
352
353 my $uid = "$dir/$regex";
354 die "regular expression '$uid' already added :ERROR" if defined ($ccacheregex->{$uid});
355
356 my $ccinfo = {};
357
358 $ccinfo->{dir} = $dir;
359 $ccinfo->{regex} = $regex;
360 $ccinfo->{parser} = $parser || \&ccache_default_parser;
361 $ccinfo->{writer} = $writer || \&ccache_default_writer;
362 $ccinfo->{update} = $update;
363
364 parse_ccache_options($ccinfo, %options);
365
366 $ccacheregex->{$uid} = $ccinfo;
367 }
368
369 sub poll {
370 return if !$inotify;
371
372 if ($inotify_pid != $$) {
373 syslog ('err', "got inotify poll request in wrong process - disabling inotify");
374 $inotify = undef;
375 } else {
376 1 while $inotify && $inotify->poll;
377 }
378 }
379
380 sub flushcache {
381 foreach my $filename (keys %$ccache) {
382 $ccache->{$filename}->{version} = undef;
383 $ccache->{$filename}->{data} = undef;
384 $ccache->{$filename}->{diff} = undef;
385 }
386 }
387
388 sub inotify_close {
389 $inotify = undef;
390 }
391
392 sub inotify_init {
393
394 die "only one inotify instance allowed" if $inotify;
395
396 $inotify = Linux::Inotify2->new()
397 || die "Unable to create new inotify object: $!";
398
399 $inotify->blocking (0);
400
401 $versions = {};
402
403 my $dirhash = {};
404 foreach my $fn (keys %$ccache) {
405 my $dir = dirname ($fn);
406 my $base = basename ($fn);
407
408 $dirhash->{$dir}->{$base} = $fn;
409
410 if (my $sf = $shadowfiles->{$fn}) {
411 $base = basename ($sf);
412 $dir = dirname ($sf);
413 $dirhash->{$dir}->{$base} = $fn; # change version of original file!
414 }
415 }
416
417 foreach my $uid (keys %$ccacheregex) {
418 my $ccinfo = $ccacheregex->{$uid};
419 $dirhash->{$ccinfo->{dir}}->{_regex} = 1;
420 }
421
422 $inotify_pid = $$;
423
424 foreach my $dir (keys %$dirhash) {
425
426 my $evlist = IN_MODIFY|IN_ATTRIB|IN_MOVED_FROM|IN_MOVED_TO|IN_DELETE|IN_CREATE;
427 $inotify->watch ($dir, $evlist, sub {
428 my $e = shift;
429 my $name = $e->name;
430
431 if ($inotify_pid != $$) {
432 syslog ('err', "got inotify event in wrong process");
433 }
434
435 if ($e->IN_ISDIR || !$name) {
436 return;
437 }
438
439 if ($e->IN_Q_OVERFLOW) {
440 syslog ('info', "got inotify overflow - flushing cache");
441 flushcache();
442 return;
443 }
444
445 if ($e->IN_UNMOUNT) {
446 syslog ('err', "got 'unmount' event on '$name' - disabling inotify");
447 $inotify = undef;
448 }
449 if ($e->IN_IGNORED) {
450 syslog ('err', "got 'ignored' event on '$name' - disabling inotify");
451 $inotify = undef;
452 }
453
454 if ($dirhash->{$dir}->{_regex}) {
455 foreach my $uid (keys %$ccacheregex) {
456 my $ccinfo = $ccacheregex->{$uid};
457 next if $dir ne $ccinfo->{dir};
458 my $regex = $ccinfo->{regex};
459 if ($regex && ($name =~ m|^$regex$|)) {
460
461 my $fn = "$dir/$name";
462 $versions->{$fn}++;
463 #print "VERSION:$fn:$versions->{$fn}\n";
464 }
465 }
466 } elsif (my $fn = $dirhash->{$dir}->{$name}) {
467
468 $versions->{$fn}++;
469 #print "VERSION:$fn:$versions->{$fn}\n";
470 }
471 });
472 }
473
474 foreach my $dir (keys %$dirhash) {
475 foreach my $name (keys %{$dirhash->{$dir}}) {
476 if ($name eq '_regex') {
477 foreach my $uid (keys %$ccacheregex) {
478 my $ccinfo = $ccacheregex->{$uid};
479 next if $dir ne $ccinfo->{dir};
480 my $re = $ccinfo->{regex};
481 if (my $fd = IO::Dir->new ($dir)) {
482 while (defined(my $de = $fd->read)) {
483 if ($de =~ m/^$re$/) {
484 my $fn = "$dir/$de";
485 $versions->{$fn}++; # init with version
486 #print "init:$fn:$versions->{$fn}\n";
487 }
488 }
489 }
490 }
491 } else {
492 my $fn = $dirhash->{$dir}->{$name};
493 $versions->{$fn}++; # init with version
494 #print "init:$fn:$versions->{$fn}\n";
495 }
496 }
497 }
498 }
499
500 my $cached_nodename;
501
502 sub nodename {
503
504 return $cached_nodename if $cached_nodename;
505
506 my ($sysname, $nodename) = POSIX::uname();
507
508 $nodename =~ s/\..*$//; # strip domain part, if any
509
510 die "unable to read node name\n" if !$nodename;
511
512 $cached_nodename = $nodename;
513
514 return $cached_nodename;
515 }
516
517 sub read_etc_hostname {
518 my ($filename, $fd) = @_;
519
520 my $hostname = <$fd>;
521
522 chomp $hostname;
523
524 $hostname =~ s/\..*$//; # strip domain part, if any
525
526 return $hostname;
527 }
528
529 sub write_etc_hostname {
530 my ($filename, $fh, $hostname) = @_;
531
532 die "write failed: $!" unless print $fh "$hostname\n";
533
534 return $hostname;
535 }
536
537 register_file('hostname', "/etc/hostname",
538 \&read_etc_hostname,
539 \&write_etc_hostname);
540
541 sub read_etc_hosts {
542 my ($filename, $fh) = @_;
543
544 my $raw = '';
545 my $data = '';
546
547 while (my $line = <$fh>) {
548 $raw .= $line;
549 if ($line =~ m/^\s*#/) {
550 $line = decode('UTF-8', $line);
551 }
552 $data .= $line;
553 }
554
555 return {
556 digest => Digest::SHA::sha1_hex($raw),
557 data => $data,
558 }
559 }
560
561 sub write_etc_hosts {
562 my ($filename, $fh, $hosts, @args) = @_;
563
564 # check validity of ips/names
565 for my $line (split("\n", $hosts)) {
566 next if $line =~ m/^\s*#/; # comments
567 next if $line =~ m/^\s*$/; # whitespace/empty lines
568
569 my ($ip, @names) = split(/\s+/, $line);
570
571 raise_param_exc({ 'data' => "Invalid IP '$ip'" })
572 if $ip !~ m/^$PVE::Tools::IPRE$/;
573
574 for my $name (@names) {
575 raise_param_exc({ 'data' => "Invalid Hostname '$name'" })
576 if $name !~ m/^[.\-a-zA-Z0-9]+$/;
577 }
578 }
579
580 die "write failed: $!" if !print $fh encode('UTF-8', $hosts);
581
582 return $hosts;
583 }
584
585 register_file('etchosts', "/etc/hosts",
586 \&read_etc_hosts,
587 \&write_etc_hosts);
588
589 sub read_etc_resolv_conf {
590 my ($filename, $fh) = @_;
591
592 my $res = {};
593
594 my $nscount = 0;
595 while (my $line = <$fh>) {
596 chomp $line;
597 if ($line =~ m/^(search|domain)\s+(\S+)\s*/) {
598 $res->{search} = $2;
599 } elsif ($line =~ m/^\s*nameserver\s+($PVE::Tools::IPRE)\s*/) {
600 $nscount++;
601 if ($nscount <= 3) {
602 $res->{"dns$nscount"} = $1;
603 }
604 }
605 }
606
607 return $res;
608 }
609
610 sub update_etc_resolv_conf {
611 my ($filename, $fh, $resolv, @args) = @_;
612
613 my $data = "";
614
615 $data = "search $resolv->{search}\n"
616 if $resolv->{search};
617
618 my $written = {};
619 foreach my $k ("dns1", "dns2", "dns3") {
620 my $ns = $resolv->{$k};
621 if ($ns && $ns ne '0.0.0.0' && !$written->{$ns}) {
622 $written->{$ns} = 1;
623 $data .= "nameserver $ns\n";
624 }
625 }
626
627 while (my $line = <$fh>) {
628 next if $line =~ m/^(search|domain|nameserver)\s+/;
629 $data .= $line
630 }
631
632 return $data;
633 }
634
635 register_file('resolvconf', "/etc/resolv.conf",
636 \&read_etc_resolv_conf, undef,
637 \&update_etc_resolv_conf);
638
639 sub read_etc_timezone {
640 my ($filename, $fd) = @_;
641
642 my $timezone = <$fd>;
643
644 chomp $timezone;
645
646 return $timezone;
647 }
648
649 sub write_etc_timezone {
650 my ($filename, $fh, $timezone) = @_;
651
652 my $tzinfo = "/usr/share/zoneinfo/$timezone";
653
654 raise_param_exc({ 'timezone' => "No such timezone" })
655 if (! -f $tzinfo);
656
657 ($timezone) = $timezone =~ m/^(.*)$/; # untaint
658
659 print $fh "$timezone\n";
660
661 unlink ("/etc/localtime");
662 symlink ("/usr/share/zoneinfo/$timezone", "/etc/localtime");
663
664 }
665
666 register_file('timezone', "/etc/timezone",
667 \&read_etc_timezone,
668 \&write_etc_timezone);
669
670 sub read_active_workers {
671 my ($filename, $fh) = @_;
672
673 return [] if !$fh;
674
675 my $res = [];
676 while (defined (my $line = <$fh>)) {
677 if ($line =~ m/^(\S+)\s(0|1)(\s([0-9A-Za-z]{8})(\s(\s*\S.*))?)?$/) {
678 my $upid = $1;
679 my $saved = $2;
680 my $endtime = $4;
681 my $status = $6;
682 if ((my $task = PVE::Tools::upid_decode($upid, 1))) {
683 $task->{upid} = $upid;
684 $task->{saved} = $saved;
685 $task->{endtime} = hex($endtime) if $endtime;
686 $task->{status} = $status if $status;
687 push @$res, $task;
688 }
689 } else {
690 warn "unable to parse line: $line";
691 }
692 }
693
694 return $res;
695
696 }
697
698 sub write_active_workers {
699 my ($filename, $fh, $tasklist) = @_;
700
701 my $raw = '';
702 foreach my $task (@$tasklist) {
703 my $upid = $task->{upid};
704 my $saved = $task->{saved} ? 1 : 0;
705 if ($task->{endtime}) {
706 if ($task->{status}) {
707 $raw .= sprintf("%s %s %08X %s\n", $upid, $saved, $task->{endtime}, $task->{status});
708 } else {
709 $raw .= sprintf("%s %s %08X\n", $upid, $saved, $task->{endtime});
710 }
711 } else {
712 $raw .= "$upid $saved\n";
713 }
714 }
715
716 PVE::Tools::safe_print($filename, $fh, $raw) if $raw;
717 }
718
719 register_file('active', "/var/log/pve/tasks/active",
720 \&read_active_workers,
721 \&write_active_workers);
722
723
724 our $bond_modes = { 'balance-rr' => 0,
725 'active-backup' => 1,
726 'balance-xor' => 2,
727 'broadcast' => 3,
728 '802.3ad' => 4,
729 'balance-tlb' => 5,
730 'balance-alb' => 6,
731 };
732
733 my $ovs_bond_modes = {
734 'active-backup' => 1,
735 'balance-slb' => 1,
736 'lacp-balance-slb' => 1,
737 'lacp-balance-tcp' => 1,
738 };
739
740 #sub get_bond_modes {
741 # return $bond_modes;
742 #}
743
744 my $parse_ovs_option = sub {
745 my ($data) = @_;
746
747 my $opts = {};
748 foreach my $kv (split (/\s+/, $data || '')) {
749 my ($k, $v) = split('=', $kv, 2);
750 $opts->{$k} = $v if $k && $v;
751 }
752 return $opts;
753 };
754
755 my $set_ovs_option = sub {
756 my ($d, %params) = @_;
757
758 my $opts = &$parse_ovs_option($d->{ovs_options});
759
760 foreach my $k (keys %params) {
761 my $v = $params{$k};
762 if ($v) {
763 $opts->{$k} = $v;
764 } else {
765 delete $opts->{$k};
766 }
767 }
768
769 my $res = [];
770 foreach my $k (keys %$opts) {
771 push @$res, "$k=$opts->{$k}";
772 }
773
774 if (my $new = join(' ', @$res)) {
775 $d->{ovs_options} = $new;
776 return $d->{ovs_options};
777 } else {
778 delete $d->{ovs_options};
779 return undef;
780 }
781 };
782
783 my $extract_ovs_option = sub {
784 my ($d, $name) = @_;
785
786 my $opts = &$parse_ovs_option($d->{ovs_options});
787
788 my $v = delete $opts->{$name};
789
790 my $res = [];
791 foreach my $k (keys %$opts) {
792 push @$res, "$k=$opts->{$k}";
793 }
794
795 if (my $new = join(' ', @$res)) {
796 $d->{ovs_options} = $new;
797 } else {
798 delete $d->{ovs_options};
799 }
800
801 return $v;
802 };
803
804 my $check_mtu = sub {
805 my ($ifaces, $parent, $child) = @_;
806
807 die "check mtu - missing parent interface\n" if !$parent;
808 die "check mtu - missing child interface\n" if !$child;
809
810 my $cmtu = $ifaces->{$child}->{mtu};
811 return if !$cmtu;
812
813 my $parentdata = $ifaces->{$parent};
814 my $pmtu = $parentdata->{mtu};
815 $pmtu = $cmtu if $parentdata->{type} eq 'bond' && !$pmtu;
816 $pmtu = 1500 if !$pmtu;
817
818 die "interface '$parent' - mtu $pmtu is lower than '$child' - mtu $cmtu\n"
819 if $pmtu < $cmtu;
820 };
821
822 # config => {
823 # ifaces => {
824 # $ifname => {
825 # <optional> exists => BOOL,
826 # <optional> active => BOOL,
827 # <optional> autostart => BOOL,
828 # <auto> priority => INT,
829 #
830 # type => "eth" | "bridge" | "bond" | "loopback" | "OVS*" | ... ,
831 #
832 # families => ["inet", "inet6", ...],
833 #
834 # method => "manual" | "static" | "dhcp" | ... ,
835 # address => IP,
836 # netmask => SUBNET,
837 # broadcast => IP,
838 # gateway => IP,
839 # comments => [ "..." ],
840 #
841 # method6 => "manual" | "static" | "dhcp" | ... ,
842 # address6 => IP,
843 # netmask6 => SUBNET,
844 # gateway6 => IP,
845 # comments6 => [ "..." ],
846 #
847 # <known options>, # like bridge_ports, ovs_*
848 #
849 # # extra/unknown options stored by-family:
850 # options => { <inet options>... }
851 # options6 => { <inet6 options>... }
852 # }
853 # },
854 # options => [
855 # # mappings end up here as well, as we don't need to understand them
856 # [priority,line]
857 # ]
858 # }
859 sub read_etc_network_interfaces {
860 my ($filename, $fh) = @_;
861 my $proc_net_dev = IO::File->new('/proc/net/dev', 'r');
862 my $active = PVE::ProcFSTools::get_active_network_interfaces();
863 return __read_etc_network_interfaces($fh, $proc_net_dev, $active);
864 }
865
866 sub __read_etc_network_interfaces {
867 my ($fh, $proc_net_dev, $active_ifaces) = @_;
868
869 my $config = {};
870 my $ifaces = $config->{ifaces} = {};
871 my $options = $config->{options} = [];
872
873 my $options_alternatives = {
874 'bond-slaves' => 'slaves',
875 'bond_slaves' => 'slaves',
876 'bond-xmit-hash-policy' => 'bond_xmit_hash_policy',
877 'bond-mode' => 'bond_mode',
878 'bond-miimon' =>'bond_miimon',
879 'bridge-vlan-aware' => 'bridge_vlan_aware',
880 'bridge-fd' => 'bridge_fd',
881 'bridge-stp' => 'bridge_stp',
882 'bridge-ports' => 'bridge_ports',
883 'bridge-vids' => 'bridge_vids'
884 };
885
886 my $line;
887
888 if ($proc_net_dev) {
889 while (defined ($line = <$proc_net_dev>)) {
890 if ($line =~ m/^\s*($PVE::Network::PHYSICAL_NIC_RE):.*/) {
891 $ifaces->{$1}->{exists} = 1;
892 }
893 }
894 close($proc_net_dev);
895 }
896
897 # we try to keep order inside the file
898 my $priority = 2; # 1 is reserved for lo
899
900 SECTION: while (defined ($line = <$fh>)) {
901 chomp ($line);
902 next if $line =~ m/^\s*#/;
903
904 if ($line =~ m/^\s*auto\s+(.*)$/) {
905 my @aa = split (/\s+/, $1);
906
907 foreach my $a (@aa) {
908 $ifaces->{$a}->{autostart} = 1;
909 }
910
911 } elsif ($line =~ m/^\s*iface\s+(\S+)\s+(inet6?)\s+(\S+)\s*$/) {
912 my $i = $1;
913 my $family = $2;
914 my $f = { method => $3 }; # by family, merged to $d with a $suffix
915 (my $suffix = $family) =~ s/^inet//;
916
917 my $d = $ifaces->{$i} ||= {};
918 $d->{priority} = $priority++ if !$d->{priority};
919 push @{$d->{families}}, $family;
920
921 while (defined ($line = <$fh>)) {
922 chomp $line;
923 if ($line =~ m/^\s*#(.*?)\s*$/) {
924 $f->{comments} = '' if !$f->{comments};
925 my $comment = decode('UTF-8', $1);
926 $f->{comments} .= "$comment\n";
927 } elsif ($line =~ m/^\s*(?:iface\s
928 |mapping\s
929 |auto\s
930 |allow-
931 |source\s
932 |source-directory\s
933 )/x) {
934 last;
935 } elsif ($line =~ m/^\s*((\S+)\s+(.+))$/) {
936 my $option = $1;
937 my ($id, $value) = ($2, $3);
938
939 $id = $options_alternatives->{$id} if $options_alternatives->{$id};
940
941 my $simple_options = {
942 'mtu' => 1,
943 'ovs_type' => 1,
944 'ovs_options' => 1,
945 'ovs_bridge' => 1,
946 'ovs_bonds' => 1,
947 'ovs_ports' => 1,
948 'bridge_fd' => 1,
949 'bridge_vids' => 1,
950 'bridge-access' => 1,
951 'bridge-learning' => 1,
952 'bridge-arp-nd-suppress' => 1,
953 'bridge-unicast-flood' => 1,
954 'bridge-multicast-flood' => 1,
955 'bond_miimon' => 1,
956 'bond_xmit_hash_policy' => 1,
957 'vlan-protocol' => 1,
958 'vxlan-id' => 1,
959 'vxlan-svcnodeip' => 1,
960 'vxlan-physdev' => 1,
961 'vxlan-local-tunnelip' => 1 };
962
963 if (($id eq 'address') || ($id eq 'netmask') || ($id eq 'broadcast') || ($id eq 'gateway')) {
964 $f->{$id} = $value;
965 } elsif ($simple_options->{$id}) {
966 $d->{$id} = $value;
967 } elsif ($id eq 'slaves' || $id eq 'bridge_ports') {
968 my $devs = {};
969 foreach my $p (split (/\s+/, $value)) {
970 next if $p eq 'none';
971 $devs->{$p} = 1;
972 }
973 my $str = join (' ', sort keys %{$devs});
974 if ($d->{$id}) {
975 $d->{$id} .= ' ' . $str if $str;
976 } else {
977 $d->{$id} = $str || '';
978 }
979 } elsif ($id eq 'bridge_stp') {
980 if ($value =~ m/^\s*(on|yes)\s*$/i) {
981 $d->{$id} = 'on';
982 } else {
983 $d->{$id} = 'off';
984 }
985 } elsif ($id eq 'bridge_vlan_aware') {
986 $d->{$id} = 1;
987 } elsif ($id eq 'bond_mode') {
988 # always use names
989 foreach my $bm (keys %$bond_modes) {
990 my $id = $bond_modes->{$bm};
991 if ($id eq $value) {
992 $value = $bm;
993 last;
994 }
995 }
996 $d->{$id} = $value;
997 } elsif ($id eq 'vxlan-remoteip') {
998 push @{$d->{$id}}, $value;
999 } else {
1000 push @{$f->{options}}, $option;
1001 }
1002 } else {
1003 last;
1004 }
1005 }
1006 $d->{"$_$suffix"} = $f->{$_} foreach (keys %$f);
1007 last SECTION if !defined($line);
1008 redo SECTION;
1009 } elsif ($line =~ /\w/) {
1010 push @$options, [$priority++, $line];
1011 }
1012 }
1013
1014 foreach my $ifname (@$active_ifaces) {
1015 if (my $iface = $ifaces->{$ifname}) {
1016 $iface->{active} = 1;
1017 }
1018 }
1019
1020 if (!$ifaces->{lo}) {
1021 $ifaces->{lo}->{priority} = 1;
1022 $ifaces->{lo}->{method} = 'loopback';
1023 $ifaces->{lo}->{type} = 'loopback';
1024 $ifaces->{lo}->{autostart} = 1;
1025 }
1026
1027 foreach my $iface (keys %$ifaces) {
1028 my $d = $ifaces->{$iface};
1029 if ($iface =~ m/^bond\d+$/) {
1030 if (!$d->{ovs_type}) {
1031 $d->{type} = 'bond';
1032 } elsif ($d->{ovs_type} eq 'OVSBond') {
1033 $d->{type} = $d->{ovs_type};
1034 # translate: ovs_options => bond_mode
1035 $d->{'bond_mode'} = &$extract_ovs_option($d, 'bond_mode');
1036 my $lacp = &$extract_ovs_option($d, 'lacp');
1037 if ($lacp && $lacp eq 'active') {
1038 if ($d->{'bond_mode'} eq 'balance-slb') {
1039 $d->{'bond_mode'} = 'lacp-balance-slb';
1040 }
1041 }
1042 # Note: balance-tcp needs lacp
1043 if ($d->{'bond_mode'} eq 'balance-tcp') {
1044 $d->{'bond_mode'} = 'lacp-balance-tcp';
1045 }
1046 my $tag = &$extract_ovs_option($d, 'tag');
1047 $d->{ovs_tag} = $tag if defined($tag);
1048 } else {
1049 $d->{type} = 'unknown';
1050 }
1051 } elsif ($iface =~ m/^vmbr\d+$/) {
1052 if (!$d->{ovs_type}) {
1053 $d->{type} = 'bridge';
1054
1055 if (!defined ($d->{bridge_fd})) {
1056 $d->{bridge_fd} = 0;
1057 }
1058 if (!defined ($d->{bridge_stp})) {
1059 $d->{bridge_stp} = 'off';
1060 }
1061 } elsif ($d->{ovs_type} eq 'OVSBridge') {
1062 $d->{type} = $d->{ovs_type};
1063 } else {
1064 $d->{type} = 'unknown';
1065 }
1066 } elsif ($iface =~ m/^(\S+):\d+$/) {
1067 $d->{type} = 'alias';
1068 if (defined ($ifaces->{$1})) {
1069 $d->{exists} = $ifaces->{$1}->{exists};
1070 } else {
1071 $ifaces->{$1}->{exists} = 0;
1072 $d->{exists} = 0;
1073 }
1074 } elsif ($iface =~ m/^(\S+)\.\d+$/) {
1075 $d->{type} = 'vlan';
1076 if (defined ($ifaces->{$1})) {
1077 $d->{exists} = $ifaces->{$1}->{exists};
1078 } else {
1079 $ifaces->{$1}->{exists} = 0;
1080 $d->{exists} = 0;
1081 }
1082 } elsif ($iface =~ m/^$PVE::Network::PHYSICAL_NIC_RE$/) {
1083 if (!$d->{ovs_type}) {
1084 $d->{type} = 'eth';
1085 } elsif ($d->{ovs_type} eq 'OVSPort') {
1086 $d->{type} = $d->{ovs_type};
1087 my $tag = &$extract_ovs_option($d, 'tag');
1088 $d->{ovs_tag} = $tag if defined($tag);
1089 } else {
1090 $d->{type} = 'unknown';
1091 }
1092 } elsif ($iface =~ m/^lo$/) {
1093 $d->{type} = 'loopback';
1094 } else {
1095 if ($d->{'vxlan-id'}) {
1096 $d->{type} = 'vxlan';
1097 } elsif (!$d->{ovs_type}) {
1098 $d->{type} = 'unknown';
1099 } elsif ($d->{ovs_type} eq 'OVSIntPort') {
1100 $d->{type} = $d->{ovs_type};
1101 my $tag = &$extract_ovs_option($d, 'tag');
1102 $d->{ovs_tag} = $tag if defined($tag);
1103 }
1104 }
1105
1106 $d->{method} = 'manual' if !$d->{method};
1107 $d->{method6} = 'manual' if !$d->{method6};
1108
1109 $d->{families} ||= ['inet'];
1110 }
1111
1112 # OVS bridges create "allow-$BRIDGE $IFACE" lines which we need to remove
1113 # from the {options} hash for them to be removed correctly.
1114 @$options = grep {defined($_)} map {
1115 my ($pri, $line) = @$_;
1116 if ($line =~ /^allow-(\S+)\s+(.*)$/) {
1117 my $bridge = $1;
1118 my @ports = split(/\s+/, $2);
1119 if (defined(my $br = $ifaces->{$bridge})) {
1120 # if this port is part of a bridge, remove it
1121 my %in_ovs_ports = map {$_=>1} split(/\s+/, $br->{ovs_ports});
1122 @ports = grep { not $in_ovs_ports{$_} } @ports;
1123 }
1124 # create the allow line for the remaining ports, or delete if empty
1125 if (@ports) {
1126 [$pri, "allow-$bridge " . join(' ', @ports)];
1127 } else {
1128 undef;
1129 }
1130 } else {
1131 # don't modify other lines
1132 $_;
1133 }
1134 } @$options;
1135
1136 return $config;
1137 }
1138
1139 sub __interface_to_string {
1140 my ($iface, $d, $family, $first_block, $ifupdown2) = @_;
1141
1142 (my $suffix = $family) =~ s/^inet//;
1143
1144 return '' if !($d && $d->{"method$suffix"});
1145
1146 my $raw = '';
1147
1148 $raw .= "iface $iface $family " . $d->{"method$suffix"} . "\n";
1149 $raw .= "\taddress " . $d->{"address$suffix"} . "\n" if $d->{"address$suffix"};
1150 $raw .= "\tnetmask " . $d->{"netmask$suffix"} . "\n" if $d->{"netmask$suffix"};
1151 $raw .= "\tgateway " . $d->{"gateway$suffix"} . "\n" if $d->{"gateway$suffix"};
1152 $raw .= "\tbroadcast " . $d->{"broadcast$suffix"} . "\n" if $d->{"broadcast$suffix"};
1153
1154 my $done = { type => 1, priority => 1, method => 1, active => 1, exists => 1,
1155 comments => 1, autostart => 1, options => 1,
1156 address => 1, netmask => 1, gateway => 1, broadcast => 1,
1157 method6 => 1, families => 1, options6 => 1,
1158 address6 => 1, netmask6 => 1, gateway6 => 1, broadcast6 => 1 };
1159
1160 if (!$first_block) {
1161 # not printing out options
1162 } elsif ($d->{type} eq 'bridge') {
1163
1164 $d->{bridge_ports} =~ s/[;,\s]+/ /g;
1165 my $ports = $d->{bridge_ports} || 'none';
1166 $raw .= "\tbridge-ports $ports\n";
1167 $done->{bridge_ports} = 1;
1168
1169 my $v = defined($d->{bridge_stp}) ? $d->{bridge_stp} : 'off';
1170 $raw .= "\tbridge-stp $v\n";
1171 $done->{bridge_stp} = 1;
1172
1173 $v = defined($d->{bridge_fd}) ? $d->{bridge_fd} : 0;
1174 $raw .= "\tbridge-fd $v\n";
1175 $done->{bridge_fd} = 1;
1176
1177 if( defined($d->{bridge_vlan_aware})) {
1178 $raw .= "\tbridge-vlan-aware yes\n";
1179 $v = defined($d->{bridge_vids}) ? $d->{bridge_vids} : "2-4094";
1180 $raw .= "\tbridge-vids $v\n";
1181 }
1182 $done->{bridge_vlan_aware} = 1;
1183 $done->{bridge_vids} = 1;
1184
1185 } elsif ($d->{type} eq 'bond') {
1186
1187 $d->{slaves} =~ s/[;,\s]+/ /g;
1188 my $slaves = $d->{slaves} || 'none';
1189 $raw .= "\tbond-slaves $slaves\n";
1190 $done->{slaves} = 1;
1191
1192 my $v = defined ($d->{'bond_miimon'}) ? $d->{'bond_miimon'} : 100;
1193 $raw .= "\tbond-miimon $v\n";
1194 $done->{'bond_miimon'} = 1;
1195
1196 $v = defined ($d->{'bond_mode'}) ? $d->{'bond_mode'} : 'balance-rr';
1197 $raw .= "\tbond-mode $v\n";
1198 $done->{'bond_mode'} = 1;
1199
1200 if ($d->{'bond_mode'} && $d->{'bond_xmit_hash_policy'} &&
1201 ($d->{'bond_mode'} eq 'balance-xor' || $d->{'bond_mode'} eq '802.3ad')) {
1202 $raw .= "\tbond-xmit-hash-policy $d->{'bond_xmit_hash_policy'}\n";
1203 }
1204 $done->{'bond_xmit_hash_policy'} = 1;
1205 } elsif ($d->{type} eq 'vlan') {
1206 die "$iface: wrong vlan-protocol $d->{'vlan-protocol'}\n"
1207 if $d->{'vlan-protocol'} && $d->{'vlan-protocol'} ne '802.1ad' && $d->{'vlan-protocol'} ne '802.1q';
1208
1209 } elsif ($d->{type} eq 'vxlan') {
1210
1211 foreach my $k (qw(vxlan-id vxlan-svcnodeip vxlan-physdev vxlan-local-tunnelip)) {
1212 $raw .= "\t$k $d->{$k}\n" if defined $d->{$k};
1213 $done->{$k} = 1;
1214 }
1215
1216 if ($d->{'vxlan-remoteip'}) {
1217 foreach my $remoteip (@{$d->{'vxlan-remoteip'}}) {
1218 $raw .= "\tvxlan-remoteip $remoteip\n";
1219 }
1220 $done->{'vxlan-remoteip'} = 1;
1221 }
1222 } elsif ($d->{type} eq 'OVSBridge') {
1223
1224 $raw .= "\tovs_type $d->{type}\n";
1225 $done->{ovs_type} = 1;
1226
1227 $raw .= "\tovs_ports $d->{ovs_ports}\n" if $d->{ovs_ports};
1228 $done->{ovs_ports} = 1;
1229 } elsif ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' ||
1230 $d->{type} eq 'OVSBond') {
1231
1232 $d->{autostart} = 0; # started by the bridge
1233
1234 if (defined($d->{ovs_tag})) {
1235 &$set_ovs_option($d, tag => $d->{ovs_tag});
1236 }
1237 $done->{ovs_tag} = 1;
1238
1239 if ($d->{type} eq 'OVSBond') {
1240
1241 $d->{bond_mode} = 'active-backup' if !$d->{bond_mode};
1242
1243 $ovs_bond_modes->{$d->{bond_mode}} ||
1244 die "OVS does not support bond mode '$d->{bond_mode}\n";
1245
1246 if ($d->{bond_mode} eq 'lacp-balance-slb') {
1247 &$set_ovs_option($d, lacp => 'active');
1248 &$set_ovs_option($d, bond_mode => 'balance-slb');
1249 } elsif ($d->{bond_mode} eq 'lacp-balance-tcp') {
1250 &$set_ovs_option($d, lacp => 'active');
1251 &$set_ovs_option($d, bond_mode => 'balance-tcp');
1252 } else {
1253 &$set_ovs_option($d, lacp => undef);
1254 &$set_ovs_option($d, bond_mode => $d->{bond_mode});
1255 }
1256 $done->{bond_mode} = 1;
1257
1258 $raw .= "\tovs_bonds $d->{ovs_bonds}\n" if $d->{ovs_bonds};
1259 $done->{ovs_bonds} = 1;
1260 }
1261
1262 $raw .= "\tovs_type $d->{type}\n";
1263 $done->{ovs_type} = 1;
1264
1265 if ($d->{ovs_bridge}) {
1266
1267 if ($ifupdown2) {
1268 $raw = "auto $iface\n$raw";
1269 } else {
1270 $raw = "allow-$d->{ovs_bridge} $iface\n$raw";
1271 }
1272
1273 $raw .= "\tovs_bridge $d->{ovs_bridge}\n";
1274 $done->{ovs_bridge} = 1;
1275 }
1276 }
1277
1278 if ($first_block) {
1279 # print other settings
1280 foreach my $k (sort keys %$d) {
1281 next if $done->{$k};
1282 next if !$d->{$k};
1283 $raw .= "\t$k $d->{$k}\n";
1284 }
1285 }
1286
1287 foreach my $option (@{$d->{"options$suffix"}}) {
1288 $raw .= "\t$option\n";
1289 }
1290
1291 # add comments
1292 my $comments = $d->{"comments$suffix"} || '';
1293 foreach my $cl (split(/\n/, $comments)) {
1294 $raw .= "#$cl\n";
1295 }
1296
1297 $raw .= "\n";
1298
1299 return $raw;
1300 }
1301
1302
1303 sub write_etc_network_interfaces {
1304 my ($filename, $fh, $config) = @_;
1305 my $ifupdown2 = -e '/usr/share/ifupdown2';
1306 my $raw = __write_etc_network_interfaces($config, $ifupdown2);
1307 PVE::Tools::safe_print($filename, $fh, encode('UTF-8', $raw));
1308 }
1309 sub __write_etc_network_interfaces {
1310 my ($config, $ifupdown2) = @_;
1311
1312 my $ifaces = $config->{ifaces};
1313 my @options = @{$config->{options}};
1314
1315 my $used_ports = {};
1316
1317 foreach my $iface (keys %$ifaces) {
1318 my $d = $ifaces->{$iface};
1319
1320 my $ports = '';
1321 foreach my $k (qw(bridge_ports ovs_ports slaves ovs_bonds)) {
1322 $ports .= " $d->{$k}" if $d->{$k};
1323 }
1324
1325 foreach my $p (PVE::Tools::split_list($ports)) {
1326 die "port '$p' is already used on interface '$used_ports->{$p}'\n"
1327 if $used_ports->{$p} && $used_ports->{$p} ne $iface;
1328 $used_ports->{$p} = $iface;
1329 }
1330 }
1331
1332 # delete unused OVS ports
1333 foreach my $iface (keys %$ifaces) {
1334 my $d = $ifaces->{$iface};
1335 if ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' ||
1336 $d->{type} eq 'OVSBond') {
1337 my $brname = $used_ports->{$iface};
1338 if (!$brname || !$ifaces->{$brname}) {
1339 if ($iface =~ /^$PVE::Network::PHYSICAL_NIC_RE/) {
1340 $ifaces->{$iface} = { type => 'eth',
1341 exists => 1,
1342 method => 'manual',
1343 families => ['inet'] };
1344 } else {
1345 delete $ifaces->{$iface};
1346 }
1347 next;
1348 }
1349 my $bd = $ifaces->{$brname};
1350 if ($bd->{type} ne 'OVSBridge') {
1351 delete $ifaces->{$iface};
1352 next;
1353 }
1354 }
1355 }
1356
1357 # create OVS bridge ports
1358 foreach my $iface (keys %$ifaces) {
1359 my $d = $ifaces->{$iface};
1360 if ($d->{type} eq 'OVSBridge' && $d->{ovs_ports}) {
1361 foreach my $p (split (/\s+/, $d->{ovs_ports})) {
1362 my $n = $ifaces->{$p};
1363 die "OVS bridge '$iface' - unable to find port '$p'\n"
1364 if !$n;
1365 $n->{autostart} = 0;
1366 if ($n->{type} eq 'eth') {
1367 $n->{type} = 'OVSPort';
1368 $n->{ovs_bridge} = $iface;
1369 } elsif ($n->{type} eq 'OVSBond' || $n->{type} eq 'OVSPort' ||
1370 $n->{type} eq 'OVSIntPort') {
1371 $n->{ovs_bridge} = $iface;
1372 } else {
1373 die "interface '$p' is not defined as OVS port/bond\n";
1374 }
1375
1376 &$check_mtu($ifaces, $iface, $p);
1377 }
1378 }
1379 }
1380
1381 # check OVS bond ports
1382 foreach my $iface (keys %$ifaces) {
1383 my $d = $ifaces->{$iface};
1384 if ($d->{type} eq 'OVSBond' && $d->{ovs_bonds}) {
1385 foreach my $p (split (/\s+/, $d->{ovs_bonds})) {
1386 my $n = $ifaces->{$p};
1387 die "OVS bond '$iface' - unable to find slave '$p'\n"
1388 if !$n;
1389 die "OVS bond '$iface' - wrong interface type on slave '$p' " .
1390 "('$n->{type}' != 'eth')\n" if $n->{type} ne 'eth';
1391 &$check_mtu($ifaces, $iface, $p);
1392 }
1393 }
1394 }
1395
1396 # check bond
1397 foreach my $iface (keys %$ifaces) {
1398 my $d = $ifaces->{$iface};
1399 if ($d->{type} eq 'bond' && $d->{slaves}) {
1400 foreach my $p (split (/\s+/, $d->{slaves})) {
1401 my $n = $ifaces->{$p};
1402
1403 die "bond '$iface' - unable to find slave '$p'\n"
1404 if !$n;
1405 die "bond '$iface' - wrong interface type on slave '$p' " .
1406 "('$n->{type}' != 'eth')\n" if $n->{type} ne 'eth';
1407 &$check_mtu($ifaces, $iface, $p);
1408 }
1409 }
1410 }
1411
1412 # check vxlan
1413 my $vxlans = {};
1414 foreach my $iface (keys %$ifaces) {
1415 my $d = $ifaces->{$iface};
1416
1417 if ($d->{type} eq 'vxlan' && $d->{'vxlan-id'}) {
1418 my $vxlanid = $d->{'vxlan-id'};
1419 die "iface $iface - duplicate vxlan-id $vxlanid already used in $vxlans->{$vxlanid}\n" if $vxlans->{$vxlanid};
1420 $vxlans->{$vxlanid} = $iface;
1421 }
1422
1423 my $ips = 0;
1424 ++$ips if defined $d->{'vxlan-svcnodeip'};
1425 ++$ips if defined $d->{'vxlan-remoteip'};
1426 ++$ips if defined $d->{'vxlan-local-tunnelip'};
1427 if ($ips > 1) {
1428 die "iface $iface - vxlan-svcnodeip, vxlan-remoteip and vxlan-localtunnelip are mutually exclusive\n";
1429 }
1430
1431 if (defined($d->{'vxlan-svcnodeip'}) != defined($d->{'vxlan-physdev'})) {
1432 die "iface $iface - vxlan-svcnodeip and vxlan-physdev must be define together\n";
1433 }
1434 #fixme : check if vxlan mtu is lower than 50bytes than physical interface where tunnel is going out
1435 }
1436
1437 # check vlan
1438 foreach my $iface (keys %$ifaces) {
1439 my $d = $ifaces->{$iface};
1440 if ($d->{type} eq 'vlan' && $iface =~ m/^(\S+)\.\d+$/) {
1441 my $p = $1;
1442 my $n = $ifaces->{$p};
1443
1444 die "vlan '$iface' - unable to find parent '$p'\n"
1445 if !$n;
1446
1447 if ($n->{type} eq 'bridge' && !$n->{bridge_vlan_aware}) {
1448 die "vlan '$iface' - bridge vlan aware is not enabled on parent '$p'\n";
1449 } elsif ($n->{type} ne 'eth' && $n->{type} ne 'bridge' && $n->{type} ne 'bond' && $n->{type} ne 'vlan') {
1450 die "vlan '$iface' - wrong interface type on parent '$p' " .
1451 "('$n->{type}' != 'eth|bond|bridge|vlan' )\n";
1452 }
1453
1454 &$check_mtu($ifaces, $p, $iface);
1455
1456 }
1457 }
1458
1459 # check bridgeport option
1460 my $bridgeports = {};
1461 my $bridges = {};
1462 foreach my $iface (keys %$ifaces) {
1463 my $d = $ifaces->{$iface};
1464 if ($d->{type} eq 'bridge') {
1465 foreach my $p (split (/\s+/, $d->{bridge_ports})) {
1466 $p =~ s/\.\d+$//;
1467 my $n = $ifaces->{$p};
1468 die "bridge '$iface' - unable to find bridge port '$p'\n"
1469 if !$n;
1470 &$check_mtu($ifaces, $iface, $p);
1471 $bridgeports->{$p} = $iface;
1472 }
1473 $bridges->{$iface} = $d;
1474 }
1475 }
1476
1477 foreach my $iface (keys %$ifaces) {
1478 my $d = $ifaces->{$iface};
1479
1480 foreach my $k (qw(bridge-learning bridge-arp-nd-suppress bridge-unicast-flood bridge-multicast-flood bridge-access)) {
1481 die "iface $iface - $k: bridge port specific options can be used only on interfaces attached to a bridge\n"
1482 if $d->{$k} && !$bridgeports->{$iface};
1483 }
1484
1485 if ($d->{'bridge-access'} && !$bridges->{$bridgeports->{$iface}}->{bridge_vlan_aware}) {
1486 die "iface $iface - bridge-access option can be only used if interface is in a vlan aware bridge\n";
1487 }
1488 }
1489
1490 my $raw = <<'NETWORKDOC';
1491 # network interface settings; autogenerated
1492 # Please do NOT modify this file directly, unless you know what
1493 # you're doing.
1494 #
1495 # If you want to manage parts of the network configuration manually,
1496 # please utilize the 'source' or 'source-directory' directives to do
1497 # so.
1498 # PVE will preserve these directives, but will NOT read its network
1499 # configuration from sourced files, so do not attempt to move any of
1500 # the PVE managed interfaces into external files!
1501
1502 NETWORKDOC
1503
1504 my $printed = {};
1505
1506 my $if_type_hash = {
1507 loopback => 100000,
1508 eth => 200000,
1509 OVSPort => 200000,
1510 OVSIntPort => 200000,
1511 bond => 300000,
1512 bridge => 400000,
1513 OVSBridge => 400000,
1514 vxlan => 500000,
1515 };
1516
1517 my $lookup_type_prio = sub {
1518 my ($iface, $ifaces) = @_;
1519
1520 my ($rootiface, @rest) = split(/[.:]/, $iface);
1521 my $childlevel = scalar(@rest);
1522 my $n = $ifaces->{$rootiface};
1523
1524 my $pri = $if_type_hash->{$n->{type}} + $childlevel
1525 if $n->{type} && $n->{type} ne 'unknown';
1526
1527 return $pri;
1528 };
1529
1530 foreach my $iface (sort {
1531 my $ref1 = $ifaces->{$a};
1532 my $ref2 = $ifaces->{$b};
1533 my $tp1 = &$lookup_type_prio($a, $ifaces);
1534 my $tp2 = &$lookup_type_prio($b, $ifaces);
1535
1536 # Only recognized types are in relation to each other. If one type
1537 # is unknown then only consider the interfaces' priority attributes.
1538 $tp1 = $tp2 = 0 if !defined($tp1) || !defined($tp2);
1539
1540 my $p1 = $tp1 + ($ref1->{priority} // 50000);
1541 my $p2 = $tp2 + ($ref2->{priority} // 50000);
1542
1543 return $p1 <=> $p2 if $p1 != $p2;
1544
1545 return $a cmp $b;
1546 } keys %$ifaces) {
1547 next if $printed->{$iface};
1548
1549 my $d = $ifaces->{$iface};
1550 my $pri = $d->{priority} // 0;
1551 if (@options && $options[0]->[0] < $pri) {
1552 do {
1553 $raw .= (shift @options)->[1] . "\n";
1554 } while (@options && $options[0]->[0] < $pri);
1555 $raw .= "\n";
1556 }
1557
1558 $printed->{$iface} = 1;
1559 $raw .= "auto $iface\n" if $d->{autostart};
1560 my $i = 0; # some options should be printed only once
1561 $raw .= __interface_to_string($iface, $d, $_, !$i++, $ifupdown2) foreach @{$d->{families}};
1562 }
1563
1564 $raw .= $_->[1] . "\n" foreach @options;
1565 return $raw;
1566 }
1567
1568 register_file('interfaces', "/etc/network/interfaces",
1569 \&read_etc_network_interfaces,
1570 \&write_etc_network_interfaces);
1571
1572
1573 sub read_iscsi_initiatorname {
1574 my ($filename, $fd) = @_;
1575
1576 while (defined(my $line = <$fd>)) {
1577 if ($line =~ m/^InitiatorName=(\S+)$/) {
1578 return $1;
1579 }
1580 }
1581
1582 return 'undefined';
1583 }
1584
1585 register_file('initiatorname', "/etc/iscsi/initiatorname.iscsi",
1586 \&read_iscsi_initiatorname);
1587
1588 sub read_apt_auth {
1589 my ($filename, $fd) = @_;
1590
1591 local $/;
1592
1593 my $raw = defined($fd) ? <$fd> : '';
1594
1595 $raw =~ s/^\s+//;
1596
1597
1598 my @tokens = split(/\s+/, $raw);
1599
1600 my $data = {};
1601
1602 my $machine;
1603 while (defined(my $tok = shift @tokens)) {
1604
1605 $machine = shift @tokens if $tok eq 'machine';
1606 next if !$machine;
1607 $data->{$machine} = {} if !$data->{$machine};
1608
1609 $data->{$machine}->{login} = shift @tokens if $tok eq 'login';
1610 $data->{$machine}->{password} = shift @tokens if $tok eq 'password';
1611 };
1612
1613 return $data;
1614 }
1615
1616 my $format_apt_auth_data = sub {
1617 my $data = shift;
1618
1619 my $raw = '';
1620
1621 foreach my $machine (sort keys %$data) {
1622 my $d = $data->{$machine};
1623 $raw .= "machine $machine\n";
1624 $raw .= " login $d->{login}\n" if $d->{login};
1625 $raw .= " password $d->{password}\n" if $d->{password};
1626 $raw .= "\n";
1627 }
1628
1629 return $raw;
1630 };
1631
1632 sub write_apt_auth {
1633 my ($filename, $fh, $data) = @_;
1634
1635 my $raw = &$format_apt_auth_data($data);
1636
1637 die "write failed: $!" unless print $fh "$raw\n";
1638
1639 return $data;
1640 }
1641
1642 sub update_apt_auth {
1643 my ($filename, $fh, $data) = @_;
1644
1645 my $orig = read_apt_auth($filename, $fh);
1646
1647 foreach my $machine (keys %$data) {
1648 $orig->{$machine} = $data->{$machine};
1649 }
1650
1651 return &$format_apt_auth_data($orig);
1652 }
1653
1654 register_file('apt-auth', "/etc/apt/auth.conf",
1655 \&read_apt_auth, \&write_apt_auth,
1656 \&update_apt_auth, perm => 0640);
1657
1658 1;