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