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