]> git.proxmox.com Git - pve-common.git/blob - src/PVE/INotify.pm
bump version to 8.2.1
[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 nodename);
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 sub nodename {
504 return $cached_nodename if $cached_nodename;
505
506 my ($sysname, $nodename) = POSIX::uname();
507 $nodename =~ s/\..*$//; # strip domain part, if any
508
509 die "unable to read node name\n" if !$nodename;
510
511 $cached_nodename = $nodename;
512
513 return $cached_nodename;
514 }
515
516 sub read_etc_hostname {
517 my ($filename, $fd) = @_;
518
519 my $hostname = <$fd>;
520
521 chomp $hostname;
522
523 $hostname =~ s/\..*$//; # strip domain part, if any
524
525 return $hostname;
526 }
527
528 sub write_etc_hostname {
529 my ($filename, $fh, $hostname) = @_;
530
531 die "write failed: $!" unless print $fh "$hostname\n";
532
533 return $hostname;
534 }
535
536 register_file('hostname', "/etc/hostname",
537 \&read_etc_hostname,
538 \&write_etc_hostname);
539
540 sub read_etc_hosts {
541 my ($filename, $fh) = @_;
542
543 my $raw = '';
544 my $data = '';
545
546 while (my $line = <$fh>) {
547 $raw .= $line;
548 if ($line =~ m/^\s*#/) {
549 $line = decode('UTF-8', $line);
550 }
551 $data .= $line;
552 }
553
554 return {
555 digest => Digest::SHA::sha1_hex($raw),
556 data => $data,
557 }
558 }
559
560 sub write_etc_hosts {
561 my ($filename, $fh, $hosts, @args) = @_;
562
563 # check validity of ips/names
564 for my $line (split("\n", $hosts)) {
565 next if $line =~ m/^\s*#/; # comments
566 next if $line =~ m/^\s*$/; # whitespace/empty lines
567
568 my ($ip, @names) = split(/\s+/, $line);
569
570 raise_param_exc({ 'data' => "Invalid IP '$ip'" })
571 if $ip !~ m/^$PVE::Tools::IPRE$/;
572
573 for my $name (@names) {
574 raise_param_exc({ 'data' => "Invalid Hostname '$name'" })
575 if $name !~ m/^[.\-a-zA-Z0-9]+$/;
576 }
577 }
578
579 die "write failed: $!" if !print $fh encode('UTF-8', $hosts);
580
581 return $hosts;
582 }
583
584 register_file('etchosts', "/etc/hosts",
585 \&read_etc_hosts,
586 \&write_etc_hosts);
587
588 sub read_etc_resolv_conf {
589 my ($filename, $fh) = @_;
590
591 my $res = {};
592
593 my $nscount = 0;
594 while (my $line = <$fh>) {
595 chomp $line;
596 if ($line =~ m/^(search|domain)\s+(\S+)\s*/) {
597 $res->{search} = $2;
598 } elsif ($line =~ m/^\s*nameserver\s+($PVE::Tools::IPRE)\s*/) {
599 $nscount++;
600 if ($nscount <= 3) {
601 $res->{"dns$nscount"} = $1;
602 }
603 }
604 }
605
606 return $res;
607 }
608
609 sub update_etc_resolv_conf {
610 my ($filename, $fh, $resolv, @args) = @_;
611
612 my $data = "";
613
614 $data = "search $resolv->{search}\n"
615 if $resolv->{search};
616
617 my $written = {};
618 foreach my $k ("dns1", "dns2", "dns3") {
619 my $ns = $resolv->{$k};
620 if ($ns && $ns ne '0.0.0.0' && !$written->{$ns}) {
621 $written->{$ns} = 1;
622 $data .= "nameserver $ns\n";
623 }
624 }
625
626 while (my $line = <$fh>) {
627 next if $line =~ m/^(search|domain|nameserver)\s+/;
628 $data .= $line
629 }
630
631 return $data;
632 }
633
634 register_file('resolvconf', "/etc/resolv.conf",
635 \&read_etc_resolv_conf, undef,
636 \&update_etc_resolv_conf);
637
638 sub read_etc_timezone {
639 my ($filename, $fd) = @_;
640
641 my $timezone = <$fd>;
642
643 chomp $timezone;
644
645 return $timezone;
646 }
647
648 sub write_etc_timezone {
649 my ($filename, $fh, $timezone) = @_;
650
651 my $tzinfo = "/usr/share/zoneinfo/$timezone";
652
653 raise_param_exc({ 'timezone' => "No such timezone" })
654 if (! -f $tzinfo);
655
656 ($timezone) = $timezone =~ m/^(.*)$/; # untaint
657
658 print $fh "$timezone\n";
659
660 unlink ("/etc/localtime");
661 symlink ("/usr/share/zoneinfo/$timezone", "/etc/localtime");
662
663 }
664
665 register_file('timezone', "/etc/timezone",
666 \&read_etc_timezone,
667 \&write_etc_timezone);
668
669 sub read_active_workers {
670 my ($filename, $fh) = @_;
671
672 return [] if !$fh;
673
674 my $res = [];
675 while (defined (my $line = <$fh>)) {
676 if ($line =~ m/^(\S+)\s(0|1)(\s([0-9A-Za-z]{8})(\s(\s*\S.*))?)?$/) {
677 my $upid = $1;
678 my $saved = $2;
679 my $endtime = $4;
680 my $status = $6;
681 if ((my $task = PVE::Tools::upid_decode($upid, 1))) {
682 $task->{upid} = $upid;
683 $task->{saved} = $saved;
684 $task->{endtime} = hex($endtime) if $endtime;
685 $task->{status} = $status if $status;
686 push @$res, $task;
687 }
688 } else {
689 warn "unable to parse line: $line";
690 }
691 }
692
693 return $res;
694
695 }
696
697 sub write_active_workers {
698 my ($filename, $fh, $tasklist) = @_;
699
700 my $raw = '';
701 foreach my $task (@$tasklist) {
702 my $upid = $task->{upid};
703 my $saved = $task->{saved} ? 1 : 0;
704 if ($task->{endtime}) {
705 if ($task->{status}) {
706 $raw .= sprintf("%s %s %08X %s\n", $upid, $saved, $task->{endtime}, $task->{status});
707 } else {
708 $raw .= sprintf("%s %s %08X\n", $upid, $saved, $task->{endtime});
709 }
710 } else {
711 $raw .= "$upid $saved\n";
712 }
713 }
714
715 PVE::Tools::safe_print($filename, $fh, $raw) if $raw;
716 }
717
718 register_file('active', "/var/log/pve/tasks/active",
719 \&read_active_workers,
720 \&write_active_workers);
721
722
723 our $bond_modes = {
724 'balance-rr' => 0,
725 'active-backup' => 1,
726 'balance-xor' => 2,
727 'broadcast' => 3,
728 '802.3ad' => 4,
729 'balance-tlb' => 5,
730 'balance-alb' => 6,
731 };
732
733 my $ovs_bond_modes = {
734 'active-backup' => 1,
735 'balance-slb' => 1,
736 'lacp-balance-slb' => 1,
737 'lacp-balance-tcp' => 1,
738 };
739
740 #sub get_bond_modes {
741 # return $bond_modes;
742 #}
743
744 my $parse_ovs_option = sub {
745 my ($data) = @_;
746
747 my $opts = {};
748 foreach my $kv (split (/\s+/, $data || '')) {
749 my ($k, $v) = split('=', $kv, 2);
750 $opts->{$k} = $v if $k && $v;
751 }
752 return $opts;
753 };
754
755 my $set_ovs_option = sub {
756 my ($d, %params) = @_;
757
758 my $opts = &$parse_ovs_option($d->{ovs_options});
759
760 foreach my $k (keys %params) {
761 my $v = $params{$k};
762 if ($v) {
763 $opts->{$k} = $v;
764 } else {
765 delete $opts->{$k};
766 }
767 }
768
769 my $res = [];
770 foreach my $k (keys %$opts) {
771 push @$res, "$k=$opts->{$k}";
772 }
773
774 if (my $new = join(' ', @$res)) {
775 $d->{ovs_options} = $new;
776 return $d->{ovs_options};
777 } else {
778 delete $d->{ovs_options};
779 return undef;
780 }
781 };
782
783 my $extract_ovs_option = sub {
784 my ($d, $name) = @_;
785
786 my $opts = &$parse_ovs_option($d->{ovs_options});
787
788 my $v = delete $opts->{$name};
789
790 my $res = [];
791 foreach my $k (keys %$opts) {
792 push @$res, "$k=$opts->{$k}";
793 }
794
795 if (my $new = join(' ', @$res)) {
796 $d->{ovs_options} = $new;
797 } else {
798 delete $d->{ovs_options};
799 }
800
801 return $v;
802 };
803
804 my $check_mtu = sub {
805 my ($ifaces, $parent, $child) = @_;
806
807 die "check mtu - missing parent interface\n" if !$parent;
808 die "check mtu - missing child interface\n" if !$child;
809
810 my $cmtu = $ifaces->{$child}->{mtu};
811 return if !$cmtu;
812
813 my $parentdata = $ifaces->{$parent};
814 my $pmtu = $parentdata->{mtu};
815 $pmtu = $cmtu if $parentdata->{type} eq 'bond' && !$pmtu;
816 $pmtu = 1500 if !$pmtu;
817
818 die "interface '$parent' - mtu $pmtu is lower than '$child' - mtu $cmtu\n"
819 if $pmtu < $cmtu;
820 };
821
822 # config => {
823 # ifaces => {
824 # $ifname => {
825 # <optional> exists => BOOL,
826 # <optional> active => BOOL,
827 # <optional> autostart => BOOL,
828 # <auto> priority => INT,
829 #
830 # type => "eth" | "bridge" | "bond" | "loopback" | "OVS*" | ... ,
831 #
832 # families => ["inet", "inet6", ...],
833 #
834 # method => "manual" | "static" | "dhcp" | ... ,
835 # address => IP,
836 # netmask => SUBNET,
837 # broadcast => IP,
838 # gateway => IP,
839 # comments => [ "..." ],
840 #
841 # method6 => "manual" | "static" | "dhcp" | ... ,
842 # address6 => IP,
843 # netmask6 => SUBNET,
844 # gateway6 => IP,
845 # comments6 => [ "..." ],
846 #
847 # <known options>, # like bridge_ports, ovs_*
848 #
849 # # extra/unknown options stored by-family:
850 # options => { <inet options>... }
851 # options6 => { <inet6 options>... }
852 # }
853 # },
854 # options => [
855 # # mappings end up here as well, as we don't need to understand them
856 # [priority,line]
857 # ]
858 # }
859 sub read_etc_network_interfaces {
860 my ($filename, $fh) = @_;
861 my $proc_net_dev = IO::File->new('/proc/net/dev', 'r');
862 my $active = PVE::ProcFSTools::get_active_network_interfaces();
863 return __read_etc_network_interfaces($fh, $proc_net_dev, $active);
864 }
865
866 sub __read_etc_network_interfaces {
867 my ($fh, $proc_net_dev, $active_ifaces) = @_;
868
869 my $config = {};
870 my $ifaces = $config->{ifaces} = {};
871 my $options = $config->{options} = [];
872
873 my $options_alternatives = {
874 'ovs_mtu' => 'mtu',
875 'bond-slaves' => 'slaves',
876 'bond_slaves' => 'slaves',
877 'bond-xmit-hash-policy' => 'bond_xmit_hash_policy',
878 'bond-mode' => 'bond_mode',
879 'bond-miimon' =>'bond_miimon',
880 'bridge-vlan-aware' => 'bridge_vlan_aware',
881 'bridge-fd' => 'bridge_fd',
882 'bridge-stp' => 'bridge_stp',
883 'bridge-ports' => 'bridge_ports',
884 'bridge-vids' => 'bridge_vids',
885 };
886
887 my $line;
888
889 if ($proc_net_dev) {
890 while (defined ($line = <$proc_net_dev>)) {
891 if ($line =~ m/^\s*($PVE::Network::PHYSICAL_NIC_RE):.*/) {
892 $ifaces->{$1}->{exists} = 1;
893 }
894 }
895 close($proc_net_dev);
896 }
897
898 # we try to keep order inside the file
899 my $priority = 2; # 1 is reserved for lo
900
901 SECTION: while (defined ($line = <$fh>)) {
902 chomp ($line);
903 next if $line =~ m/^\s*#/;
904
905 if ($line =~ m/^\s*(allow-auto|auto|allow-ovs)\s+(.*)$/) {
906
907 $ifaces->{$_}->{autostart} = 1 for split (/\s+/, $2);
908
909 } elsif ($line =~ m/^\s*(allow-hotplug)\s+(.*)$/) {
910
911 # FIXME: handle those differently? auto makes it required on-boot, vs. best-effort
912 $ifaces->{$_}->{autostart} = 1 for split (/\s+/, $2);
913
914 } elsif ($line =~ m/^\s*iface\s+(\S+)\s+(inet6?)\s+(\S+)\s*$/) {
915 my $i = $1;
916 my $family = $2;
917 my $f = { method => $3 }; # by family, merged to $d with a $suffix
918 (my $suffix = $family) =~ s/^inet//;
919
920 my $d = $ifaces->{$i} ||= {};
921 $d->{priority} = $priority++ if !$d->{priority};
922 push @{$d->{families}}, $family;
923
924 while (defined ($line = <$fh>)) {
925 $line =~ s/\s+$//; # drop trailing whitespaces
926
927 if ($line =~ m/^\s*#(.*?)\s*$/) {
928 $f->{comments} = '' if !$f->{comments};
929 my $comment = decode('UTF-8', $1);
930 $f->{comments} .= "$comment\n";
931 } elsif ($line =~ m/^\s*(?:(?:iface|mapping|auto|source|source-directory)\s|allow-)/) {
932 last;
933 } elsif ($line =~ m/^\s*((\S+)\s+(.+))$/) {
934 my $option = $1;
935 my ($id, $value) = ($2, $3);
936
937 $id = $options_alternatives->{$id} if $options_alternatives->{$id};
938
939 my $simple_options = {
940 'mtu' => 1,
941 'ovs_type' => 1,
942 'ovs_options' => 1,
943 'ovs_bridge' => 1,
944 'ovs_bonds' => 1,
945 'ovs_ports' => 1,
946 'bridge_fd' => 1,
947 'bridge_vids' => 1,
948 'bridge-access' => 1,
949 'bridge-learning' => 1,
950 'bridge-arp-nd-suppress' => 1,
951 'bridge-unicast-flood' => 1,
952 'bridge-multicast-flood' => 1,
953 'bridge-disable-mac-learning' => 1,
954 'bond_miimon' => 1,
955 'bond_xmit_hash_policy' => 1,
956 'bond-primary' => 1,
957 'link-type' => 1,
958 'uplink-id' => 1,
959 'vlan-protocol' => 1,
960 'vlan-raw-device' => 1,
961 'vlan-id' => 1,
962 'vxlan-id' => 1,
963 'vxlan-svcnodeip' => 1,
964 'vxlan-physdev' => 1,
965 'vxlan-local-tunnelip' => 1,
966 };
967
968 if ($id eq 'address' || $id eq 'netmask' || $id eq 'broadcast' || $id eq 'gateway') {
969 $f->{$id} = $value;
970 } elsif ($simple_options->{$id}) {
971 $d->{$id} = $value;
972 } elsif ($id eq 'slaves' || $id eq 'bridge_ports') {
973 my $devs = {};
974 foreach my $p (split (/\s+/, $value)) {
975 next if $p eq 'none';
976 $devs->{$p} = 1;
977 }
978 my $str = join (' ', sort keys %{$devs});
979 if ($d->{$id}) {
980 $d->{$id} .= ' ' . $str if $str;
981 } else {
982 $d->{$id} = $str || '';
983 }
984 } elsif ($id eq 'bridge_stp') {
985 if ($value =~ m/^\s*(on|yes)\s*$/i) {
986 $d->{$id} = 'on';
987 } else {
988 $d->{$id} = 'off';
989 }
990 } elsif ($id eq 'bridge_vlan_aware') {
991 $d->{$id} = 1;
992 } elsif ($id eq 'bond_mode') {
993 # always use names
994 foreach my $bm (keys %$bond_modes) {
995 if ($bond_modes->{$bm} eq $value) {
996 $value = $bm;
997 last;
998 }
999 }
1000 $d->{$id} = $value;
1001 } elsif ($id eq 'vxlan-remoteip') {
1002 push @{$d->{$id}}, $value;
1003 } else {
1004 push @{$f->{options}}, $option;
1005 }
1006 } else {
1007 last;
1008 }
1009 }
1010 $d->{"$_$suffix"} = $f->{$_} for keys $f->%*;
1011 last SECTION if !defined($line);
1012 redo SECTION;
1013 } elsif ($line =~ /\w/) {
1014 push @$options, [$priority++, $line];
1015 }
1016 }
1017
1018 foreach my $ifname (@$active_ifaces) {
1019 if (my $iface = $ifaces->{$ifname}) {
1020 $iface->{active} = 1;
1021 }
1022 }
1023
1024 if (!$ifaces->{lo}) {
1025 $ifaces->{lo} = {
1026 priority => 1,
1027 method => 'loopback',
1028 type => 'loopback',
1029 autostart => 1,
1030 };
1031 }
1032
1033 foreach my $iface (sort keys %$ifaces) {
1034 my $d = $ifaces->{$iface};
1035 $d->{type} = 'unknown';
1036 if ($iface =~ m/^bond\d+$/) {
1037 if (!$d->{ovs_type}) {
1038 $d->{type} = 'bond';
1039 } elsif ($d->{ovs_type} eq 'OVSBond') {
1040 $d->{type} = $d->{ovs_type};
1041 # translate: ovs_options => bond_mode
1042 $d->{'bond_mode'} = &$extract_ovs_option($d, 'bond_mode');
1043 my $lacp = &$extract_ovs_option($d, 'lacp');
1044 if ($lacp && $lacp eq 'active') {
1045 if ($d->{'bond_mode'} eq 'balance-slb') {
1046 $d->{'bond_mode'} = 'lacp-balance-slb';
1047 }
1048 }
1049 # Note: balance-tcp needs lacp
1050 if ($d->{'bond_mode'} eq 'balance-tcp') {
1051 $d->{'bond_mode'} = 'lacp-balance-tcp';
1052 }
1053 my $tag = &$extract_ovs_option($d, 'tag');
1054 $d->{ovs_tag} = $tag if defined($tag);
1055 }
1056 } elsif ($iface =~ m/^vmbr\d+$/) {
1057 if (!$d->{ovs_type}) {
1058 $d->{type} = 'bridge';
1059 if (!defined ($d->{bridge_stp})) {
1060 $d->{bridge_stp} = 'off';
1061 }
1062 if (!defined($d->{bridge_fd}) && $d->{bridge_stp} eq 'off') {
1063 $d->{bridge_fd} = 0;
1064 }
1065 } elsif ($d->{ovs_type} eq 'OVSBridge') {
1066 $d->{type} = $d->{ovs_type};
1067 }
1068 } elsif ($iface =~ m/^(\S+):\d+$/) {
1069 $d->{type} = 'alias';
1070 if (defined ($ifaces->{$1})) {
1071 $d->{exists} = $ifaces->{$1}->{exists};
1072 } else {
1073 $ifaces->{$1}->{exists} = 0;
1074 $d->{exists} = 0;
1075 }
1076 } elsif ($iface =~ m/^(\S+)\.(\d+)$/) {
1077 $d->{type} = 'vlan';
1078
1079 my ($dev, $id) = ($1, $2);
1080 $d->{'vlan-raw-device'} = $dev if defined($dev) && !$d->{'vlan-raw-device'};
1081 $d->{'vlan-id'} = $id if $id; # VLAN id 0 is not valid, so truthy check it is
1082
1083 my $raw_iface = $d->{'vlan-raw-device'};
1084
1085 if (defined ($ifaces->{$raw_iface})) {
1086 $d->{exists} = $ifaces->{$raw_iface}->{exists};
1087 } else {
1088 $ifaces->{$raw_iface}->{exists} = 0;
1089 $d->{exists} = 0;
1090 }
1091 } elsif ($d->{'vlan-raw-device'}) {
1092 $d->{type} = 'vlan';
1093
1094 if ($iface =~ m/^vlan(\d+)$/) {
1095 $d->{'vlan-id'} = $1 if $1; # VLAN id 0 is not valid, so truthy check it is
1096 }
1097
1098 my $raw_iface = $d->{'vlan-raw-device'};
1099
1100 if (defined ($ifaces->{$raw_iface})) {
1101 $d->{exists} = $ifaces->{$raw_iface}->{exists};
1102 } else {
1103 $ifaces->{$raw_iface}->{exists} = 0;
1104 $d->{exists} = 0;
1105 }
1106 } elsif ($iface =~ m/^$PVE::Network::PHYSICAL_NIC_RE$/) {
1107 if (!$d->{ovs_type}) {
1108 $d->{type} = 'eth';
1109 } elsif ($d->{ovs_type} eq 'OVSPort') {
1110 $d->{type} = $d->{ovs_type};
1111 my $tag = &$extract_ovs_option($d, 'tag');
1112 $d->{ovs_tag} = $tag if defined($tag);
1113 }
1114 } elsif ($iface =~ m/^lo$/) {
1115 $d->{type} = 'loopback';
1116 } else {
1117 if ($d->{'vxlan-id'}) {
1118 $d->{type} = 'vxlan';
1119 } elsif (defined($d->{ovs_type})) {
1120 if ($d->{ovs_type} eq 'OVSIntPort') {
1121 $d->{type} = $d->{ovs_type};
1122 my $tag = &$extract_ovs_option($d, 'tag');
1123 $d->{ovs_tag} = $tag if defined($tag);
1124 }
1125 } elsif (defined($d->{'link-type'})) {
1126 $d->{type} = $d->{'link-type'} if $d->{'link-type'} eq 'dummy';
1127 }
1128 }
1129
1130 # map address and netmask to cidr
1131 if (my $addr = $d->{address}) {
1132 if (_address_is_cidr($addr)) {
1133 $d->{cidr} = $addr;
1134 my ($baseaddr, $mask) = _cidr_split($addr);
1135 $d->{address} = $baseaddr;
1136 $d->{netmask} = $mask;
1137 } elsif (my $cidr = _get_cidr($d->{address}, $d->{netmask})) {
1138 $d->{cidr} = $cidr;
1139 (undef, $d->{netmask}) = _cidr_split($cidr);
1140 } else {
1141 # no mask, else we'd got a cidr above
1142 $d->{cidr} = $addr ."/32";
1143 }
1144 }
1145
1146 # map address6 and netmask6 to cidr6
1147 if (my $addr6 = $d->{address6}) {
1148 if (_address_is_cidr($addr6)) {
1149 $d->{cidr6} = $addr6;
1150 my ($baseaddr, $mask) = _cidr_split($addr6);
1151 $d->{address6} = $baseaddr;
1152 $d->{netmask6} = $mask;
1153 } elsif (my $cidr6 = _get_cidr($d->{address6}, $d->{netmask6})) {
1154 $d->{cidr6} = $cidr6;
1155 } else {
1156 # no mask, else we'd got a cidr above
1157 $d->{cidr6} = $addr6 ."/128";
1158 }
1159 }
1160
1161 $d->{method} = 'manual' if !$d->{method};
1162 $d->{method6} = 'manual' if !$d->{method6};
1163
1164 if (my $comments6 = delete $d->{comments6}) {
1165 $d->{comments} = ($d->{comments} // '') . $comments6;
1166 }
1167
1168 $d->{families} ||= ['inet'];
1169 }
1170
1171 # OVS bridges create "allow-$BRIDGE $IFACE" lines which we need to remove
1172 # from the {options} hash for them to be removed correctly.
1173 @$options = grep {defined($_)} map {
1174 my ($pri, $line) = @$_;
1175 if ($line =~ /^allow-ovs\s+(.*)$/) {
1176 undef;
1177 } elsif ($line =~ /^allow-(\S+)\s+(.*)$/) {
1178 my $bridge = $1;
1179 my @ports = split(/\s+/, $2);
1180 if (defined(my $br = $ifaces->{$bridge})) {
1181 # if this port is part of a bridge, remove it
1182 my %in_ovs_ports = map {$_=>1} split(/\s+/, $br->{ovs_ports});
1183 @ports = grep { not $in_ovs_ports{$_} } @ports;
1184 }
1185 # create the allow line for the remaining ports, or delete if empty
1186 if (@ports) {
1187 [$pri, "allow-$bridge " . join(' ', @ports)];
1188 } else {
1189 undef;
1190 }
1191 } else {
1192 # don't modify other lines
1193 $_;
1194 }
1195 } @$options;
1196
1197 return $config;
1198 }
1199
1200 sub _address_is_cidr {
1201 my ($addr) = @_;
1202 return $addr =~ /\/\d+$/ ? 1 : 0;
1203 }
1204
1205 sub _cidr_split {
1206 my ($cidr) = @_;
1207 $cidr =~ /^(.+)\/(\d+)$/;
1208 return ($1, $2); # (address, mask)
1209 }
1210
1211 sub _get_cidr {
1212 my ($addr, $mask) = @_;
1213
1214 return $addr if _address_is_cidr($addr);
1215 return undef if !$mask;
1216
1217 if ($mask =~ m/^\d+$/) { # cidr notation
1218 return $addr . "/" . $mask;
1219 } elsif (my $cidrmask = PVE::JSONSchema::get_netmask_bits($mask)) {
1220 return $addr . "/" . $cidrmask;
1221 }
1222 return undef;
1223 }
1224
1225 sub __interface_to_string {
1226 my ($iface, $d, $family, $first_block, $ifupdown2) = @_;
1227
1228 (my $suffix = $family) =~ s/^inet//;
1229
1230 return '' if !($d && $d->{"method$suffix"});
1231
1232 my $raw = "iface $iface $family " . $d->{"method$suffix"} . "\n";
1233
1234 if (my $addr = $d->{"address$suffix"}) {
1235 if ($addr !~ /\/\d+$/ && $d->{"netmask$suffix"}) {
1236 if ($d->{"netmask$suffix"} =~ m/^\d+$/) {
1237 $addr .= "/" . $d->{"netmask$suffix"};
1238 } elsif (my $mask = PVE::JSONSchema::get_netmask_bits($d->{"netmask$suffix"})) {
1239 $addr .= "/" . $mask;
1240 }
1241 }
1242 $raw .= "\taddress ${addr}\n";
1243 }
1244
1245 $raw .= "\tgateway " . $d->{"gateway$suffix"} . "\n" if $d->{"gateway$suffix"};
1246
1247 my $done = {
1248 type => 1, priority => 1, method => 1, active => 1, exists => 1, comments => 1,
1249 autostart => 1, options => 1, address => 1, netmask => 1, gateway => 1, broadcast => 1,
1250 method6 => 1, families => 1, options6 => 1, comments6 => 1, address6 => 1,
1251 netmask6 => 1, gateway6 => 1, broadcast6 => 1, 'uplink-id' => 1,
1252 };
1253
1254 if (!$first_block) {
1255 # not printing out options
1256 } elsif ($d->{type} eq 'bridge') {
1257
1258 my $ports = $d->{bridge_ports} || 'none';
1259 $ports =~ s/[;,\s]+/ /g;
1260 $raw .= "\tbridge-ports $ports\n";
1261 $done->{bridge_ports} = 1;
1262
1263 my $br_stp = defined($d->{bridge_stp}) ? $d->{bridge_stp} : 'off';
1264 my $no_stp = $br_stp eq 'off';
1265
1266 $raw .= "\tbridge-stp $br_stp\n";
1267 $done->{bridge_stp} = 1;
1268
1269 # NOTE: forwarding delay must be 2 <= FD <= 30 if STP is enabled
1270 if (defined(my $br_fd = $d->{bridge_fd})) {
1271 if ($no_stp || ($br_fd >= 2 && $br_fd <= 30)) {
1272 $raw .= "\tbridge-fd $br_fd\n";
1273 } else {
1274 # only complain if the user actually set a value, but not for default fallback below
1275 warn "'$iface': ignoring 'bridge_fd' value '$br_fd', outside of allowed range 2-30\n";
1276 }
1277 } elsif ($no_stp) {
1278 $raw .= "\tbridge-fd 0\n";
1279 }
1280 $done->{bridge_fd} = 1;
1281
1282 if (defined($d->{bridge_vlan_aware})) {
1283 $raw .= "\tbridge-vlan-aware yes\n";
1284 my $vlans = defined($d->{bridge_vids}) ? $d->{bridge_vids} : "2-4094";
1285 $raw .= "\tbridge-vids $vlans\n";
1286 }
1287 $done->{bridge_vlan_aware} = 1;
1288 $done->{bridge_vids} = 1;
1289
1290 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1291 $done->{mtu} = 1;
1292 $done->{'bridge-disable-mac-learning'} = 1;
1293
1294 } elsif ($d->{type} eq 'bond') {
1295
1296 $d->{slaves} =~ s/[;,\s]+/ /g;
1297 my $slaves = $d->{slaves} || 'none';
1298 $raw .= "\tbond-slaves $slaves\n";
1299 $done->{slaves} = 1;
1300
1301 my $v = defined ($d->{'bond_miimon'}) ? $d->{'bond_miimon'} : 100;
1302 $raw .= "\tbond-miimon $v\n";
1303 $done->{'bond_miimon'} = 1;
1304
1305 $v = defined ($d->{'bond_mode'}) ? $d->{'bond_mode'} : 'balance-rr';
1306 $raw .= "\tbond-mode $v\n";
1307 $done->{'bond_mode'} = 1;
1308
1309 if ($d->{'bond_mode'} && $d->{'bond_xmit_hash_policy'} &&
1310 ($d->{'bond_mode'} eq 'balance-xor' || $d->{'bond_mode'} eq '802.3ad')) {
1311 $raw .= "\tbond-xmit-hash-policy $d->{'bond_xmit_hash_policy'}\n";
1312 }
1313 $done->{'bond_xmit_hash_policy'} = 1;
1314
1315 if ($d->{'bond_mode'} && $d->{'bond_mode'} eq 'active-backup' && $d->{'bond-primary'}) {
1316 $raw .= "\tbond-primary $d->{'bond-primary'}\n";
1317 }
1318 $done->{'bond-primary'} = 1;
1319
1320 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1321 $done->{mtu} = 1;
1322
1323 } elsif ($d->{type} eq 'vlan') {
1324 die "$iface: wrong vlan-protocol $d->{'vlan-protocol'}\n"
1325 if $d->{'vlan-protocol'} && $d->{'vlan-protocol'} ne '802.1ad' && $d->{'vlan-protocol'} ne '802.1q';
1326
1327 } elsif ($d->{type} eq 'vxlan') {
1328
1329 foreach my $k (qw(vxlan-id vxlan-svcnodeip vxlan-physdev vxlan-local-tunnelip)) {
1330 $raw .= "\t$k $d->{$k}\n" if defined $d->{$k};
1331 $done->{$k} = 1;
1332 }
1333
1334 if ($d->{'vxlan-remoteip'}) {
1335 foreach my $remoteip (@{$d->{'vxlan-remoteip'}}) {
1336 $raw .= "\tvxlan-remoteip $remoteip\n";
1337 }
1338 $done->{'vxlan-remoteip'} = 1;
1339 }
1340
1341 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1342 $done->{mtu} = 1;
1343
1344 } elsif ($d->{type} eq 'OVSBridge') {
1345
1346 $raw .= "\tovs_type $d->{type}\n";
1347 $done->{ovs_type} = 1;
1348
1349 $raw .= "\tovs_ports $d->{ovs_ports}\n" if $d->{ovs_ports};
1350 $done->{ovs_ports} = 1;
1351
1352 $raw .= "\tovs_mtu $d->{mtu}\n" if $d->{mtu};
1353 $done->{mtu} = 1;
1354
1355 } elsif ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' || $d->{type} eq 'OVSBond') {
1356
1357 $d->{autostart} = 0; # started by the bridge
1358
1359 if (defined($d->{ovs_tag})) {
1360 &$set_ovs_option($d, tag => $d->{ovs_tag});
1361 }
1362 $done->{ovs_tag} = 1;
1363
1364 if ($d->{type} eq 'OVSBond') {
1365
1366 $d->{bond_mode} = 'active-backup' if !$d->{bond_mode};
1367
1368 $ovs_bond_modes->{$d->{bond_mode}} ||
1369 die "OVS does not support bond mode '$d->{bond_mode}\n";
1370
1371 if ($d->{bond_mode} eq 'lacp-balance-slb') {
1372 &$set_ovs_option($d, lacp => 'active');
1373 &$set_ovs_option($d, bond_mode => 'balance-slb');
1374 } elsif ($d->{bond_mode} eq 'lacp-balance-tcp') {
1375 &$set_ovs_option($d, lacp => 'active');
1376 &$set_ovs_option($d, bond_mode => 'balance-tcp');
1377 } else {
1378 &$set_ovs_option($d, lacp => undef);
1379 &$set_ovs_option($d, bond_mode => $d->{bond_mode});
1380 }
1381 $done->{bond_mode} = 1;
1382
1383 $raw .= "\tovs_bonds $d->{ovs_bonds}\n" if $d->{ovs_bonds};
1384 $done->{ovs_bonds} = 1;
1385 }
1386
1387 $raw .= "\tovs_type $d->{type}\n";
1388 $done->{ovs_type} = 1;
1389
1390 if (my $bridge = $d->{ovs_bridge}) {
1391 if ($ifupdown2) {
1392 $raw = "auto $iface\n$raw";
1393 } else {
1394 $raw = "allow-$bridge $iface\n$raw";
1395 }
1396
1397 $raw .= "\tovs_bridge $bridge\n";
1398 $done->{ovs_bridge} = 1;
1399 }
1400
1401 $raw .= "\tovs_mtu $d->{mtu}\n" if $d->{mtu};
1402 $done->{mtu} = 1;
1403 }
1404
1405 if ($first_block) {
1406 # print other settings
1407 foreach my $k (sort keys %$d) {
1408 next if $done->{$k};
1409 next if !$d->{$k};
1410 $raw .= "\t$k $d->{$k}\n";
1411 }
1412 }
1413
1414 foreach my $option (@{$d->{"options$suffix"}}) {
1415 $raw .= "\t$option\n";
1416 }
1417
1418 # add comments
1419 my $comments = $d->{"comments$suffix"} || '';
1420 foreach my $cl (split(/\n/, $comments)) {
1421 $raw .= "#$cl\n";
1422 }
1423
1424 $raw .= "\n";
1425
1426 return $raw;
1427 }
1428
1429
1430 sub write_etc_network_interfaces {
1431 my ($filename, $fh, $config) = @_;
1432 my $ifupdown2 = -e '/usr/share/ifupdown2/ifupdown2';
1433 my $raw = __write_etc_network_interfaces($config, $ifupdown2);
1434 PVE::Tools::safe_print($filename, $fh, encode('UTF-8', $raw));
1435 }
1436 sub __write_etc_network_interfaces {
1437 my ($config, $ifupdown2) = @_;
1438
1439 my $ifaces = $config->{ifaces};
1440 my @options = @{$config->{options}};
1441
1442 my $used_ports = {};
1443
1444 foreach my $iface (keys %$ifaces) {
1445 my $d = $ifaces->{$iface};
1446
1447 my ($cidr, $cidr6) = (delete $d->{cidr}, delete $d->{cidr6});
1448 $d->{address} //= $cidr;
1449 $d->{address6} //= $cidr6;
1450
1451 my $ports = '';
1452 foreach my $k (qw(bridge_ports ovs_ports slaves ovs_bonds)) {
1453 $ports .= " $d->{$k}" if $d->{$k};
1454 }
1455
1456 foreach my $p (PVE::Tools::split_list($ports)) {
1457 die "port '$p' is already used on interface '$used_ports->{$p}'\n"
1458 if $used_ports->{$p} && $used_ports->{$p} ne $iface;
1459 $used_ports->{$p} = $iface;
1460 }
1461 }
1462
1463 # delete unused OVS ports
1464 foreach my $iface (keys %$ifaces) {
1465 my $d = $ifaces->{$iface};
1466 if ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' || $d->{type} eq 'OVSBond') {
1467 my $brname = $used_ports->{$iface};
1468 if (!$brname || !$ifaces->{$brname}) {
1469 if ($iface =~ /^$PVE::Network::PHYSICAL_NIC_RE/) {
1470 $ifaces->{$iface} = {
1471 type => 'eth',
1472 exists => 1,
1473 method => 'manual',
1474 families => ['inet'],
1475 };
1476 } else {
1477 delete $ifaces->{$iface};
1478 }
1479 next;
1480 }
1481 my $bd = $ifaces->{$brname};
1482 if ($bd->{type} ne 'OVSBridge') {
1483 delete $ifaces->{$iface};
1484 next;
1485 }
1486 }
1487 }
1488
1489 # create OVS bridge ports
1490 foreach my $iface (keys %$ifaces) {
1491 my $d = $ifaces->{$iface};
1492 if ($d->{type} eq 'OVSBridge' && $d->{ovs_ports}) {
1493 foreach my $p (split (/\s+/, $d->{ovs_ports})) {
1494 my $n = $ifaces->{$p};
1495 die "OVS bridge '$iface' - unable to find port '$p'\n" if !$n;
1496 $n->{autostart} = 0;
1497 if ($n->{type} eq 'eth') {
1498 $n->{type} = 'OVSPort';
1499 $n->{ovs_bridge} = $iface;
1500 } elsif ($n->{type} eq 'OVSBond' || $n->{type} eq 'OVSPort' ||
1501 $n->{type} eq 'OVSIntPort') {
1502 $n->{ovs_bridge} = $iface;
1503 } else {
1504 die "interface '$p' is not defined as OVS port/bond\n";
1505 }
1506
1507 &$check_mtu($ifaces, $iface, $p);
1508 }
1509 }
1510 }
1511
1512 # check OVS bond ports
1513 foreach my $iface (keys %$ifaces) {
1514 my $d = $ifaces->{$iface};
1515 if ($d->{type} eq 'OVSBond' && $d->{ovs_bonds}) {
1516 foreach my $p (split (/\s+/, $d->{ovs_bonds})) {
1517 my $n = $ifaces->{$p};
1518 $n->{autostart} = 1;
1519 die "OVS bond '$iface' - unable to find slave '$p'\n" if !$n;
1520 die "OVS bond '$iface' - wrong interface type on slave '$p' ('$n->{type}' != 'eth')\n"
1521 if $n->{type} ne 'eth';
1522 &$check_mtu($ifaces, $iface, $p);
1523 }
1524 }
1525 }
1526
1527 # check bond
1528 foreach my $iface (keys %$ifaces) {
1529 my $d = $ifaces->{$iface};
1530 next if !($d->{type} eq 'bond' && $d->{slaves});
1531
1532 my $bond_primary_is_slave = undef;
1533 foreach my $p (split (/\s+/, $d->{slaves})) {
1534 my $n = $ifaces->{$p};
1535 $n->{autostart} = 1;
1536
1537 die "bond '$iface' - unable to find slave '$p'\n" if !$n;
1538 die "bond '$iface' - wrong interface type on slave '$p' ('$n->{type}' != 'eth or bond')\n"
1539 if ($n->{type} ne 'eth' && $n->{type} ne 'bond');
1540
1541 $check_mtu->($ifaces, $iface, $p);
1542 $bond_primary_is_slave = 1 if $d->{'bond-primary'} && $d->{'bond-primary'} eq $p;
1543 }
1544 die "bond '$iface' - bond-primary interface is not a slave" if $d->{'bond-primary'} && !$bond_primary_is_slave;
1545 }
1546
1547 # check vxlan
1548 my $vxlans = {};
1549 foreach my $iface (keys %$ifaces) {
1550 my $d = $ifaces->{$iface};
1551
1552 if ($d->{type} eq 'vxlan' && $d->{'vxlan-id'}) {
1553 my $vxlanid = $d->{'vxlan-id'};
1554 die "iface $iface - duplicate vxlan-id $vxlanid already used in $vxlans->{$vxlanid}\n" if $vxlans->{$vxlanid};
1555 $vxlans->{$vxlanid} = $iface;
1556 }
1557
1558 my $ips = 0;
1559 ++$ips if defined $d->{'vxlan-svcnodeip'};
1560 ++$ips if defined $d->{'vxlan-remoteip'};
1561 ++$ips if defined $d->{'vxlan-local-tunnelip'};
1562 if ($ips > 1) {
1563 die "iface $iface - vxlan-svcnodeip, vxlan-remoteip and vxlan-localtunnelip are mutually exclusive\n";
1564 }
1565
1566 if (defined($d->{'vxlan-svcnodeip'}) != defined($d->{'vxlan-physdev'})) {
1567 die "iface $iface - vxlan-svcnodeip and vxlan-physdev must be define together\n";
1568 }
1569 #fixme : check if vxlan mtu is lower than 50bytes than physical interface where tunnel is going out
1570 }
1571
1572 # check vlan
1573 foreach my $iface (keys %$ifaces) {
1574 my $d = $ifaces->{$iface};
1575 if ($d->{type} eq 'vlan') {
1576
1577 my $p = undef;
1578 my $vlanid = undef;
1579
1580 if ($iface =~ m/^(\S+)\.(\d+)$/) {
1581 $p = $1;
1582 $vlanid = $2;
1583 delete $d->{'vlan-raw-device'} if $d->{'vlan-raw-device'};
1584 delete $d->{'vlan-id'} if $d->{'vlan-id'};
1585
1586 } else {
1587 die "missing vlan-raw-device option" if !$d->{'vlan-raw-device'};
1588 $p = $d->{'vlan-raw-device'};
1589
1590 if ($iface =~ m/^vlan(\d+)$/) {
1591 $vlanid = $1;
1592 delete $d->{'vlan-id'} if $d->{'vlan-id'};
1593 } else {
1594 die "custom vlan interface name need ifupdown2" if !$ifupdown2;
1595 die "missing vlan-id option" if !$d->{'vlan-id'};
1596 $vlanid = $d->{'vlan-id'};
1597 }
1598 }
1599 my $n = $ifaces->{$p};
1600
1601 die "vlan '$iface' - vlan-id $vlanid should be <= 4094\n" if $vlanid > 4094;
1602 die "vlan '$iface' - unable to find parent '$p'\n"
1603 if !$n;
1604
1605 if ($n->{type} ne 'eth' && $n->{type} ne 'bridge' && $n->{type} ne 'bond' && $n->{type} ne 'vlan') {
1606 die "vlan '$iface' - wrong interface type on parent '$p' " .
1607 "('$n->{type}' != 'eth|bond|bridge|vlan' )\n";
1608 }
1609
1610 &$check_mtu($ifaces, $p, $iface);
1611
1612 }
1613 }
1614
1615 # check uplink
1616 my $uplinks = {};
1617 foreach my $iface (keys %$ifaces) {
1618 my $d = $ifaces->{$iface};
1619 if (my $uplinkid = $d->{'uplink-id'}) {
1620 die "iface '$iface' - uplink-id $uplinkid is only allowed on physical and linux bond interfaces\n"
1621 if $d->{type} ne 'eth' && $d->{type} ne 'bond';
1622
1623 die "iface '$iface' - uplink-id $uplinkid is already assigned on '$uplinks->{$uplinkid}'\n"
1624 if $uplinks->{$uplinkid};
1625
1626 $uplinks->{$uplinkid} = $iface;
1627 }
1628 }
1629
1630 # check bridgeport option
1631 my $bridgeports = {};
1632 my $bridges = {};
1633 my $ifaces_copy = { %$ifaces };
1634 foreach my $iface (keys %$ifaces_copy) {
1635 my $d = $ifaces_copy->{$iface};
1636 if ($d->{type} eq 'bridge') {
1637 foreach my $p (split (/\s+/, $d->{bridge_ports} // '')) {
1638 if($p =~ m/(\S+)\.(\d+)$/) {
1639 my $vlanparent = $1;
1640 if (!defined($ifaces_copy->{$p})) {
1641 $ifaces_copy->{$p}->{type} = 'vlan';
1642 $ifaces_copy->{$p}->{method} = 'manual';
1643 $ifaces_copy->{$p}->{method6} = 'manual';
1644 $ifaces_copy->{$p}->{mtu} = $ifaces_copy->{$vlanparent}->{mtu} if defined($ifaces_copy->{$1}->{mtu});
1645 }
1646 }
1647 my $n = $ifaces_copy->{$p};
1648 die "bridge '$iface' - unable to find bridge port '$p'\n" if !$n;
1649 die "iface $p - ip address can't be set on interface if bridged in $iface\n"
1650 if ($n->{method} && $n->{method} eq 'static' && $n->{address} ne '0.0.0.0') ||
1651 ($n->{method6} && $n->{method6} eq 'static' && $n->{address6} ne '::');
1652 &$check_mtu($ifaces_copy, $p, $iface);
1653 $bridgeports->{$p} = $iface;
1654 }
1655 $bridges->{$iface} = $d;
1656 }
1657 }
1658
1659 foreach my $iface (keys %$ifaces) {
1660 my $d = $ifaces->{$iface};
1661
1662 foreach my $k (qw(bridge-learning bridge-arp-nd-suppress bridge-unicast-flood bridge-multicast-flood bridge-access)) {
1663 die "iface $iface - $k: bridge port specific options can be used only on interfaces attached to a bridge\n"
1664 if $d->{$k} && !$bridgeports->{$iface};
1665 }
1666
1667 if ($d->{'bridge-access'} && !$bridges->{$bridgeports->{$iface}}->{bridge_vlan_aware}) {
1668 die "iface $iface - bridge-access option can be only used if interface is in a vlan aware bridge\n";
1669 }
1670 }
1671
1672 my $raw = <<'NETWORKDOC';
1673 # network interface settings; autogenerated
1674 # Please do NOT modify this file directly, unless you know what
1675 # you're doing.
1676 #
1677 # If you want to manage parts of the network configuration manually,
1678 # please utilize the 'source' or 'source-directory' directives to do
1679 # so.
1680 # PVE will preserve these directives, but will NOT read its network
1681 # configuration from sourced files, so do not attempt to move any of
1682 # the PVE managed interfaces into external files!
1683
1684 NETWORKDOC
1685
1686 my $printed = {};
1687
1688 my $if_type_hash = {
1689 loopback => 100000,
1690 dummy => 100000,
1691 eth => 200000,
1692 OVSPort => 200000,
1693 OVSIntPort => 300000,
1694 OVSBond => 400000,
1695 bond => 400000,
1696 bridge => 500000,
1697 OVSBridge => 500000,
1698 vlan => 600000,
1699 vxlan => 600000,
1700 };
1701
1702 my $lookup_type_prio = sub {
1703 my ($iface, $ifaces) = @_;
1704
1705 my ($rootiface, @rest) = split(/[.:]/, $iface);
1706 my $childlevel = scalar(@rest);
1707 my $type = $ifaces->{$rootiface}->{type};
1708 return if !$type || $type eq 'unknown';
1709
1710 return $if_type_hash->{$type} + $childlevel
1711 };
1712
1713 foreach my $iface (sort {
1714 my $ref1 = $ifaces->{$a};
1715 my $ref2 = $ifaces->{$b};
1716 my $tp1 = &$lookup_type_prio($a, $ifaces);
1717 my $tp2 = &$lookup_type_prio($b, $ifaces);
1718
1719 # Only recognized types are in relation to each other. If one type
1720 # is unknown then only consider the interfaces' priority attributes.
1721 $tp1 = $tp2 = 0 if !defined($tp1) || !defined($tp2);
1722
1723 my $p1 = $tp1 + ($ref1->{priority} // 50000);
1724 my $p2 = $tp2 + ($ref2->{priority} // 50000);
1725
1726 return $p1 <=> $p2 if $p1 != $p2;
1727
1728 return $a cmp $b;
1729 } keys %$ifaces) {
1730 next if $printed->{$iface};
1731 my $d = $ifaces->{$iface};
1732 my $pri = $d->{priority} // 0;
1733 if (@options && $options[0]->[0] < $pri) {
1734 do {
1735 $raw .= (shift @options)->[1] . "\n";
1736 } while (@options && $options[0]->[0] < $pri);
1737 $raw .= "\n";
1738 }
1739
1740 $printed->{$iface} = 1;
1741 if ($d->{autostart}) {
1742 if ($d->{type} eq 'OVSBridge' && !$ifupdown2) {
1743 # cannot use 'auto' for OVS, would add race with systemd ifup@.service
1744 $raw .= "allow-ovs $iface\n";
1745 } else {
1746 $raw .= "auto $iface\n";
1747 }
1748 }
1749
1750 # if 'inet6' is the only family
1751 if (scalar($d->{families}->@*) == 1 && $d->{families}[0] eq 'inet6') {
1752 $d->{comments6} = delete $d->{comments};
1753 }
1754
1755 my $i = 0; # some options should be printed only once
1756 $raw .= __interface_to_string($iface, $d, $_, !$i++, $ifupdown2) foreach @{$d->{families}};
1757 }
1758
1759 $raw .= $_->[1] . "\n" foreach @options;
1760 return $raw;
1761 }
1762
1763 register_file('interfaces', "/etc/network/interfaces",
1764 \&read_etc_network_interfaces,
1765 \&write_etc_network_interfaces);
1766
1767
1768 sub read_iscsi_initiatorname {
1769 my ($filename, $fd) = @_;
1770
1771 while (defined(my $line = <$fd>)) {
1772 if ($line =~ m/^InitiatorName=(\S+)$/) {
1773 return $1;
1774 }
1775 }
1776
1777 return 'undefined';
1778 }
1779
1780 register_file('initiatorname', "/etc/iscsi/initiatorname.iscsi",
1781 \&read_iscsi_initiatorname);
1782
1783 1;