]> git.proxmox.com Git - pve-common.git/blame - src/PVE/INotify.pm
network parser: iterate deterministically
[pve-common.git] / src / PVE / INotify.pm
CommitLineData
e143e9d8
DM
1package PVE::INotify;
2
3# todo: maybe we do not need update_file() ?
e143e9d8 4use strict;
c36f332e
DM
5use warnings;
6
afd50f0d
TL
7use Clone qw(clone);
8use Digest::SHA;
9use Encode qw(encode decode);
e143e9d8 10use Fcntl qw(:DEFAULT :flock);
afd50f0d
TL
11use File::Basename;
12use File::stat;
13use IO::Dir;
14use IO::File;
15use JSON;
16use Linux::Inotify2;
17use POSIX;
18
e143e9d8 19use PVE::Exception qw(raise_param_exc);
afd50f0d 20use PVE::JSONSchema;
3dabe28a 21use PVE::Network;
f0d1b04f 22use PVE::ProcFSTools;
afd50f0d
TL
23use PVE::SafeSyslog;
24use PVE::Tools;
25
e143e9d8 26use base 'Exporter';
e143e9d8 27
eb6f49f4 28our @EXPORT_OK = qw(read_file write_file register_file nodename);
e143e9d8
DM
29
30my $ccache;
31my $ccachemap;
32my $ccacheregex;
33my $inotify;
34my $inotify_pid = 0;
35my $versions;
36my $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
46sub ccache_default_writer {
47 my ($filename, $data) = @_;
48
49 die "undefined config writer for '$filename' :ERROR";
50}
51
52sub ccache_default_parser {
53 my ($filename, $srcfd) = @_;
54
55 die "undefined config reader for '$filename' :ERROR";
56}
57
58sub ccache_compute_diff {
59 my ($filename, $shadow) = @_;
60
61 my $diff = '';
62
69758574
DC
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 });
e143e9d8
DM
68
69 $diff = undef if !$diff;
70
71 return $diff;
72}
73
74sub 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;
9bbc4e17 88 }
e143e9d8
DM
89 return ($ccache->{$filename}, $filename);
90 }
91 }
9bbc4e17 92
e143e9d8
DM
93 $filename = $ccachemap->{$filename} if defined ($ccachemap->{$filename});
94
95 die "file '$filename' not added :ERROR" if !defined ($ccache->{$filename});
9bbc4e17 96
e143e9d8
DM
97 return ($ccache->{$filename}, $filename);
98}
99
100sub 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;
9bbc4e17 139 die $msg;
e143e9d8
DM
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
154sub 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");
9bbc4e17 172
e143e9d8
DM
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
192sub 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
3b671d82
DM
204sub 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
e143e9d8
DM
214sub read_file {
215 my ($fileid, $full) = @_;
216
217 my $parser;
218
219 my ($ccinfo, $filename) = ccache_info($fileid);
9bbc4e17 220
e143e9d8 221 $parser = $ccinfo->{parser};
9bbc4e17 222
e143e9d8
DM
223 my $fd;
224 my $shadow;
225
3b671d82 226 my $cver = poll_changes($filename);
e143e9d8
DM
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;
9bbc4e17 242 $ccinfo->{data} = undef;
e143e9d8
DM
243 $ccinfo->{diff} = undef;
244 return undef if !$acp;
245 }
246
247 my $noclone = $ccinfo->{noclone};
248
249 # file unchanged?
250 if (!$ccinfo->{nocache} &&
04cba6c8 251 $inotify && $cver &&
e143e9d8
DM
252 defined ($ccinfo->{data}) &&
253 defined ($ccinfo->{version}) &&
254 ($ccinfo->{readonce} ||
04cba6c8 255 ($ccinfo->{version} == $cver))) {
e143e9d8
DM
256
257 my $ret;
258 if (!$noclone && ref ($ccinfo->{data})) {
32ef45ae 259 $ret->{data} = clone ($ccinfo->{data});
e143e9d8
DM
260 } else {
261 $ret->{data} = $ccinfo->{data};
262 }
263 $ret->{changes} = $ccinfo->{diff};
9bbc4e17 264
e143e9d8
DM
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
32ef45ae 281 # clone this data. Else the original data may get
e143e9d8
DM
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})) {
32ef45ae 290 $ret->{data} = clone ($ccinfo->{data});
e143e9d8
DM
291 } else {
292 $ret->{data} = $ccinfo->{data};
293 }
294 $ret->{changes} = $ccinfo->{diff};
295
296 return $full ? $ret : $ret->{data};
9bbc4e17 297}
e143e9d8
DM
298
299sub 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') {
1f929ade 316 # when set, we call parser even when the file does not exist.
e143e9d8
DM
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
325sub register_file {
326 my ($id, $filename, $parser, $writer, $update, %options) = @_;
327
26a8d824 328 die "can't register file '$filename' after inotify_init" if $inotify;
e143e9d8
DM
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);
9bbc4e17 341
e143e9d8
DM
342 if ($options{shadow}) {
343 $shadowfiles->{$filename} = $options{shadow};
344 }
345
346 $ccachemap->{$id} = $filename;
347 $ccache->{$filename} = $ccinfo;
348}
349
350sub register_regex {
351 my ($dir, $regex, $parser, $writer, $update, %options) = @_;
352
b8246bfc 353 die "can't register regex after inotify_init" if $inotify;
e143e9d8
DM
354
355 my $uid = "$dir/$regex";
356 die "regular expression '$uid' already added :ERROR" if defined ($ccacheregex->{$uid});
9bbc4e17 357
e143e9d8
DM
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
371sub 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
382sub 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
390sub inotify_close {
391 $inotify = undef;
392}
393
394sub 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};
9bbc4e17 421 $dirhash->{$ccinfo->{dir}}->{_regex} = 1;
e143e9d8
DM
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 }
9bbc4e17 451 if ($e->IN_IGNORED) {
e143e9d8
DM
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)) {
9bbc4e17 484 while (defined(my $de = $fd->read)) {
e143e9d8
DM
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
502my $cached_nodename;
e143e9d8 503sub nodename {
e143e9d8
DM
504 return $cached_nodename if $cached_nodename;
505
506 my ($sysname, $nodename) = POSIX::uname();
e143e9d8
DM
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
516sub 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
528sub write_etc_hostname {
529 my ($filename, $fh, $hostname) = @_;
530
531 die "write failed: $!" unless print $fh "$hostname\n";
532
533 return $hostname;
534}
535
9bbc4e17
TL
536register_file('hostname', "/etc/hostname",
537 \&read_etc_hostname,
e143e9d8
DM
538 \&write_etc_hostname);
539
9194ee06
DC
540sub 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
560sub 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
584register_file('etchosts', "/etc/hosts",
585 \&read_etc_hosts,
586 \&write_etc_hosts);
587
e143e9d8
DM
588sub 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;
176b1186 598 } elsif ($line =~ m/^\s*nameserver\s+($PVE::Tools::IPRE)\s*/) {
e143e9d8
DM
599 $nscount++;
600 if ($nscount <= 3) {
601 $res->{"dns$nscount"} = $1;
602 }
603 }
604 }
605
606 return $res;
607}
608
609sub 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 }
9bbc4e17 630
e143e9d8
DM
631 return $data;
632}
633
9bbc4e17
TL
634register_file('resolvconf', "/etc/resolv.conf",
635 \&read_etc_resolv_conf, undef,
e143e9d8
DM
636 \&update_etc_resolv_conf);
637
638sub read_etc_timezone {
639 my ($filename, $fd) = @_;
640
641 my $timezone = <$fd>;
642
643 chomp $timezone;
644
645 return $timezone;
646}
647
648sub 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
9bbc4e17
TL
665register_file('timezone', "/etc/timezone",
666 \&read_etc_timezone,
e143e9d8
DM
667 \&write_etc_timezone);
668
669sub read_active_workers {
670 my ($filename, $fh) = @_;
671
672 return [] if !$fh;
673
9bbc4e17 674 my $res = [];
e143e9d8 675 while (defined (my $line = <$fh>)) {
75ed54f1 676 if ($line =~ m/^(\S+)\s(0|1)(\s([0-9A-Za-z]{8})(\s(\s*\S.*))?)?$/) {
e143e9d8
DM
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
697sub 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}) {
e34c27f4 706 $raw .= sprintf("%s %s %08X %s\n", $upid, $saved, $task->{endtime}, $task->{status});
e143e9d8 707 } else {
e34c27f4 708 $raw .= sprintf("%s %s %08X\n", $upid, $saved, $task->{endtime});
e143e9d8
DM
709 }
710 } else {
711 $raw .= "$upid $saved\n";
712 }
713 }
714
715 PVE::Tools::safe_print($filename, $fh, $raw) if $raw;
716}
717
9bbc4e17 718register_file('active', "/var/log/pve/tasks/active",
e143e9d8
DM
719 \&read_active_workers,
720 \&write_active_workers);
721
722
13c77181
TL
723our $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};
e143e9d8 732
9b7b13a1
DM
733my $ovs_bond_modes = {
734 'active-backup' => 1,
9b7b13a1 735 'balance-slb' => 1,
a68760b6 736 'lacp-balance-slb' => 1,
9bbc4e17 737 'lacp-balance-tcp' => 1,
9b7b13a1
DM
738};
739
e143e9d8
DM
740#sub get_bond_modes {
741# return $bond_modes;
742#}
743
9b7b13a1
DM
744my $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
755my $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
783my $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
9b053d70 804my $check_mtu = sub {
cebd1c85 805 my ($ifaces, $parent, $child) = @_;
9b053d70 806
cebd1c85
WB
807 die "check mtu - missing parent interface\n" if !$parent;
808 die "check mtu - missing child interface\n" if !$child;
9b053d70 809
000e32bc
AD
810 my $cmtu = $ifaces->{$child}->{mtu};
811 return if !$cmtu;
9b053d70 812
000e32bc
AD
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;
9b053d70
AD
820};
821
48ab17b3
WB
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# }
e143e9d8
DM
859sub read_etc_network_interfaces {
860 my ($filename, $fh) = @_;
78325766 861 my $proc_net_dev = IO::File->new('/proc/net/dev', 'r');
f0d1b04f 862 my $active = PVE::ProcFSTools::get_active_network_interfaces();
12a235d6 863 return __read_etc_network_interfaces($fh, $proc_net_dev, $active);
78325766
WB
864}
865
866sub __read_etc_network_interfaces {
12a235d6 867 my ($fh, $proc_net_dev, $active_ifaces) = @_;
e143e9d8 868
48ab17b3
WB
869 my $config = {};
870 my $ifaces = $config->{ifaces} = {};
871 my $options = $config->{options} = [];
e143e9d8 872
1b1fb9f7 873 my $options_alternatives = {
2d1e9a02 874 'ovs_mtu' => 'mtu',
1b1fb9f7
AD
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',
95d0e633 883 'bridge-ports' => 'bridge_ports',
25558f13 884 'bridge-vids' => 'bridge_vids',
1b1fb9f7
AD
885 };
886
e143e9d8
DM
887 my $line;
888
78325766
WB
889 if ($proc_net_dev) {
890 while (defined ($line = <$proc_net_dev>)) {
3dabe28a 891 if ($line =~ m/^\s*($PVE::Network::PHYSICAL_NIC_RE):.*/) {
e143e9d8
DM
892 $ifaces->{$1}->{exists} = 1;
893 }
894 }
78325766 895 close($proc_net_dev);
e143e9d8
DM
896 }
897
c9dc8645 898 # we try to keep order inside the file
9bbc4e17 899 my $priority = 2; # 1 is reserved for lo
c9dc8645 900
b1d7951f 901 SECTION: while (defined ($line = <$fh>)) {
e143e9d8 902 chomp ($line);
b1d7951f 903 next if $line =~ m/^\s*#/;
9bbc4e17 904
0dcace5a 905 if ($line =~ m/^\s*(allow-auto|auto|allow-ovs)\s+(.*)$/) {
e143e9d8 906
75a2a1c6 907 $ifaces->{$_}->{autostart} = 1 for split (/\s+/, $2);
e143e9d8 908
0dc7fd7b
TL
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
48ab17b3 914 } elsif ($line =~ m/^\s*iface\s+(\S+)\s+(inet6?)\s+(\S+)\s*$/) {
e143e9d8 915 my $i = $1;
48ab17b3
WB
916 my $family = $2;
917 my $f = { method => $3 }; # by family, merged to $d with a $suffix
918 (my $suffix = $family) =~ s/^inet//;
e143e9d8 919
cb07ff78 920 my $d = $ifaces->{$i} ||= {};
48ab17b3
WB
921 $d->{priority} = $priority++ if !$d->{priority};
922 push @{$d->{families}}, $family;
923
72ca6520 924 while (defined ($line = <$fh>)) {
de906ba3 925 $line =~ s/\s+$//; # drop trailing whitespaces
684e07f2 926
b1d7951f 927 if ($line =~ m/^\s*#(.*?)\s*$/) {
48ab17b3 928 $f->{comments} = '' if !$f->{comments};
1b505ae2
DC
929 my $comment = decode('UTF-8', $1);
930 $f->{comments} .= "$comment\n";
75a2a1c6 931 } elsif ($line =~ m/^\s*(?:(?:iface|mapping|auto|source|source-directory)\s|allow-)/) {
b1d7951f
WB
932 last;
933 } elsif ($line =~ m/^\s*((\S+)\s+(.+))$/) {
72ca6520
DM
934 my $option = $1;
935 my ($id, $value) = ($2, $3);
1b1fb9f7
AD
936
937 $id = $options_alternatives->{$id} if $options_alternatives->{$id};
938
9a052564 939 my $simple_options = {
9b053d70 940 'mtu' => 1,
9a052564
AD
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,
25558f13 953 'bridge-disable-mac-learning' => 1,
9a052564
AD
954 'bond_miimon' => 1,
955 'bond_xmit_hash_policy' => 1,
b94d05ec 956 'bond-primary' => 1,
a85812af 957 'link-type' => 1,
d949babe 958 'uplink-id' => 1,
8f5d56bf 959 'vlan-protocol' => 1,
bbe7d3ed
AD
960 'vlan-raw-device' => 1,
961 'vlan-id' => 1,
9a052564
AD
962 'vxlan-id' => 1,
963 'vxlan-svcnodeip' => 1,
964 'vxlan-physdev' => 1,
75a2a1c6
TL
965 'vxlan-local-tunnelip' => 1,
966 };
9a052564 967
75a2a1c6 968 if ($id eq 'address' || $id eq 'netmask' || $id eq 'broadcast' || $id eq 'gateway') {
48ab17b3 969 $f->{$id} = $value;
9a052564 970 } elsif ($simple_options->{$id}) {
9b7b13a1 971 $d->{$id} = $value;
72ca6520
DM
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;
e143e9d8 977 }
72ca6520 978 my $str = join (' ', sort keys %{$devs});
48ab17b3
WB
979 if ($d->{$id}) {
980 $d->{$id} .= ' ' . $str if $str;
981 } else {
982 $d->{$id} = $str || '';
983 }
72ca6520
DM
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 }
685a2528
AD
990 } elsif ($id eq 'bridge_vlan_aware') {
991 $d->{$id} = 1;
72ca6520
DM
992 } elsif ($id eq 'bond_mode') {
993 # always use names
994 foreach my $bm (keys %$bond_modes) {
75a2a1c6 995 if ($bond_modes->{$bm} eq $value) {
72ca6520
DM
996 $value = $bm;
997 last;
998 }
999 }
1000 $d->{$id} = $value;
95aa8788
AD
1001 } elsif ($id eq 'vxlan-remoteip') {
1002 push @{$d->{$id}}, $value;
72ca6520 1003 } else {
48ab17b3 1004 push @{$f->{options}}, $option;
e143e9d8 1005 }
e143e9d8 1006 } else {
72ca6520 1007 last;
e143e9d8
DM
1008 }
1009 }
75a2a1c6 1010 $d->{"$_$suffix"} = $f->{$_} for keys $f->%*;
b1d7951f
WB
1011 last SECTION if !defined($line);
1012 redo SECTION;
48ab17b3
WB
1013 } elsif ($line =~ /\w/) {
1014 push @$options, [$priority++, $line];
e143e9d8
DM
1015 }
1016 }
1017
12a235d6
WB
1018 foreach my $ifname (@$active_ifaces) {
1019 if (my $iface = $ifaces->{$ifname}) {
1020 $iface->{active} = 1;
1021 }
1022 }
e143e9d8
DM
1023
1024 if (!$ifaces->{lo}) {
75a2a1c6
TL
1025 $ifaces->{lo} = {
1026 priority => 1,
1027 method => 'loopback',
1028 type => 'loopback',
1029 autostart => 1,
1030 };
e143e9d8
DM
1031 }
1032
fcc97ec9 1033 foreach my $iface (sort keys %$ifaces) {
e143e9d8 1034 my $d = $ifaces->{$iface};
c688b8e6 1035 $d->{type} = 'unknown';
e143e9d8 1036 if ($iface =~ m/^bond\d+$/) {
9b7b13a1
DM
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');
a68760b6
DM
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 }
2a751938
DM
1053 my $tag = &$extract_ovs_option($d, 'tag');
1054 $d->{ovs_tag} = $tag if defined($tag);
e143e9d8 1055 }
9b7b13a1
DM
1056 } elsif ($iface =~ m/^vmbr\d+$/) {
1057 if (!$d->{ovs_type}) {
1058 $d->{type} = 'bridge';
9b7b13a1
DM
1059 if (!defined ($d->{bridge_stp})) {
1060 $d->{bridge_stp} = 'off';
1061 }
e960f794
FG
1062 if (!defined($d->{bridge_fd}) && $d->{bridge_stp} eq 'off') {
1063 $d->{bridge_fd} = 0;
1064 }
9b7b13a1
DM
1065 } elsif ($d->{ovs_type} eq 'OVSBridge') {
1066 $d->{type} = $d->{ovs_type};
e143e9d8
DM
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 }
b818066a 1076 } elsif ($iface =~ m/^(\S+)\.(\d+)$/ || $d->{'vlan-raw-device'}) {
9c808945 1077 $d->{type} = 'vlan';
bbe7d3ed 1078
9fffe4bc
TL
1079 my ($dev, $id) = ($1, $2);
1080 $d->{'vlan-raw-device'} = $dev if defined($dev) && !$d->{'vlan-raw-device'};
1081
1082 if (!$id && $iface =~ m/^vlan(\d+)$/) { # VLAN id 0 is not valid, so truthy check it is
1083 $id = $1;
1084 }
1085 $d->{'vlan-id'} = $id if $id;
b818066a
AL
1086
1087 my $raw_iface = $d->{'vlan-raw-device'};
1088
bbe7d3ed
AD
1089 if (defined ($ifaces->{$raw_iface})) {
1090 $d->{exists} = $ifaces->{$raw_iface}->{exists};
9c808945 1091 } else {
bbe7d3ed 1092 $ifaces->{$raw_iface}->{exists} = 0;
9c808945
AD
1093 $d->{exists} = 0;
1094 }
3dabe28a 1095 } elsif ($iface =~ m/^$PVE::Network::PHYSICAL_NIC_RE$/) {
9b7b13a1
DM
1096 if (!$d->{ovs_type}) {
1097 $d->{type} = 'eth';
1098 } elsif ($d->{ovs_type} eq 'OVSPort') {
1099 $d->{type} = $d->{ovs_type};
2a751938
DM
1100 my $tag = &$extract_ovs_option($d, 'tag');
1101 $d->{ovs_tag} = $tag if defined($tag);
9b7b13a1 1102 }
e143e9d8
DM
1103 } elsif ($iface =~ m/^lo$/) {
1104 $d->{type} = 'loopback';
1105 } else {
95aa8788
AD
1106 if ($d->{'vxlan-id'}) {
1107 $d->{type} = 'vxlan';
d2513a84
TL
1108 } elsif (defined($d->{ovs_type})) {
1109 if ($d->{ovs_type} eq 'OVSIntPort') {
1110 $d->{type} = $d->{ovs_type};
1111 my $tag = &$extract_ovs_option($d, 'tag');
1112 $d->{ovs_tag} = $tag if defined($tag);
1113 }
a85812af
AD
1114 } elsif (defined($d->{'link-type'})) {
1115 $d->{type} = $d->{'link-type'} if $d->{'link-type'} eq 'dummy';
9b7b13a1 1116 }
e143e9d8
DM
1117 }
1118
2896245e 1119 # map address and netmask to cidr
fa6e6946
TL
1120 if (my $addr = $d->{address}) {
1121 if (_address_is_cidr($addr)) {
1122 $d->{cidr} = $addr;
1123 my ($baseaddr, $mask) = _cidr_split($addr);
1124 $d->{address} = $baseaddr;
1125 $d->{netmask} = $mask;
1126 } elsif (my $cidr = _get_cidr($d->{address}, $d->{netmask})) {
1127 $d->{cidr} = $cidr;
1128 (undef, $d->{netmask}) = _cidr_split($cidr);
1129 } else {
1130 # no mask, else we'd got a cidr above
1131 $d->{cidr} = $addr ."/32";
2896245e
DC
1132 }
1133 }
1134
1135 # map address6 and netmask6 to cidr6
fa6e6946
TL
1136 if (my $addr6 = $d->{address6}) {
1137 if (_address_is_cidr($addr6)) {
1138 $d->{cidr6} = $addr6;
1139 my ($baseaddr, $mask) = _cidr_split($addr6);
1140 $d->{address6} = $baseaddr;
1141 $d->{netmask6} = $mask;
1142 } elsif (my $cidr6 = _get_cidr($d->{address6}, $d->{netmask6})) {
1143 $d->{cidr6} = $cidr6;
1144 } else {
1145 # no mask, else we'd got a cidr above
1146 $d->{cidr6} = $addr6 ."/128";
1147 }
2896245e
DC
1148 }
1149
e143e9d8 1150 $d->{method} = 'manual' if !$d->{method};
48ab17b3 1151 $d->{method6} = 'manual' if !$d->{method6};
78325766 1152
f2ac9dd3
LS
1153 if (my $comments6 = delete $d->{comments6}) {
1154 $d->{comments} = ($d->{comments} // '') . $comments6;
1155 }
1156
78325766 1157 $d->{families} ||= ['inet'];
e143e9d8
DM
1158 }
1159
516a50a4
WB
1160 # OVS bridges create "allow-$BRIDGE $IFACE" lines which we need to remove
1161 # from the {options} hash for them to be removed correctly.
1162 @$options = grep {defined($_)} map {
1163 my ($pri, $line) = @$_;
4ac94c72
AD
1164 if ($line =~ /^allow-ovs\s+(.*)$/) {
1165 undef;
1166 } elsif ($line =~ /^allow-(\S+)\s+(.*)$/) {
516a50a4
WB
1167 my $bridge = $1;
1168 my @ports = split(/\s+/, $2);
1169 if (defined(my $br = $ifaces->{$bridge})) {
1170 # if this port is part of a bridge, remove it
1171 my %in_ovs_ports = map {$_=>1} split(/\s+/, $br->{ovs_ports});
1172 @ports = grep { not $in_ovs_ports{$_} } @ports;
1173 }
1174 # create the allow line for the remaining ports, or delete if empty
1175 if (@ports) {
1176 [$pri, "allow-$bridge " . join(' ', @ports)];
1177 } else {
1178 undef;
1179 }
1180 } else {
1181 # don't modify other lines
1182 $_;
1183 }
1184 } @$options;
1185
48ab17b3 1186 return $config;
e143e9d8
DM
1187}
1188
fa6e6946
TL
1189sub _address_is_cidr {
1190 my ($addr) = @_;
1191 return $addr =~ /\/\d+$/ ? 1 : 0;
1192}
1193
1194sub _cidr_split {
1195 my ($cidr) = @_;
1196 $cidr =~ /^(.+)\/(\d+)$/;
1197 return ($1, $2); # (address, mask)
1198}
1199
1200sub _get_cidr {
1201 my ($addr, $mask) = @_;
1202
1203 return $addr if _address_is_cidr($addr);
1204 return undef if !$mask;
1205
1206 if ($mask =~ m/^\d+$/) { # cidr notation
1207 return $addr . "/" . $mask;
1208 } elsif (my $cidrmask = PVE::JSONSchema::get_netmask_bits($mask)) {
1209 return $addr . "/" . $cidrmask;
1210 }
1211 return undef;
1212}
1213
e143e9d8 1214sub __interface_to_string {
b7c4f378 1215 my ($iface, $d, $family, $first_block, $ifupdown2) = @_;
48ab17b3
WB
1216
1217 (my $suffix = $family) =~ s/^inet//;
e143e9d8 1218
48ab17b3 1219 return '' if !($d && $d->{"method$suffix"});
e143e9d8 1220
43997e84 1221 my $raw = "iface $iface $family " . $d->{"method$suffix"} . "\n";
f6c9d9a4
TL
1222
1223 if (my $addr = $d->{"address$suffix"}) {
f6c9d9a4
TL
1224 if ($addr !~ /\/\d+$/ && $d->{"netmask$suffix"}) {
1225 if ($d->{"netmask$suffix"} =~ m/^\d+$/) {
1226 $addr .= "/" . $d->{"netmask$suffix"};
1227 } elsif (my $mask = PVE::JSONSchema::get_netmask_bits($d->{"netmask$suffix"})) {
1228 $addr .= "/" . $mask;
1229 }
1230 }
43997e84 1231 $raw .= "\taddress ${addr}\n";
f6c9d9a4
TL
1232 }
1233
beedabb4 1234 $raw .= "\tgateway " . $d->{"gateway$suffix"} . "\n" if $d->{"gateway$suffix"};
e143e9d8 1235
75a2a1c6
TL
1236 my $done = {
1237 type => 1, priority => 1, method => 1, active => 1, exists => 1, comments => 1,
1238 autostart => 1, options => 1, address => 1, netmask => 1, gateway => 1, broadcast => 1,
1239 method6 => 1, families => 1, options6 => 1, comments6 => 1, address6 => 1,
1240 netmask6 => 1, gateway6 => 1, broadcast6 => 1, 'uplink-id' => 1,
1241 };
48ab17b3
WB
1242
1243 if (!$first_block) {
1244 # not printing out options
1245 } elsif ($d->{type} eq 'bridge') {
9b7b13a1 1246
e143e9d8 1247 my $ports = $d->{bridge_ports} || 'none';
8342b610 1248 $ports =~ s/[;,\s]+/ /g;
1accc6da 1249 $raw .= "\tbridge-ports $ports\n";
9b7b13a1 1250 $done->{bridge_ports} = 1;
e143e9d8 1251
43997e84
TL
1252 my $br_stp = defined($d->{bridge_stp}) ? $d->{bridge_stp} : 'off';
1253 my $no_stp = $br_stp eq 'off';
e960f794 1254
43997e84 1255 $raw .= "\tbridge-stp $br_stp\n";
9b7b13a1 1256 $done->{bridge_stp} = 1;
e143e9d8 1257
576dadb1
TL
1258 # NOTE: forwarding delay must be 2 <= FD <= 30 if STP is enabled
1259 if (defined(my $br_fd = $d->{bridge_fd})) {
1260 if ($no_stp || ($br_fd >= 2 && $br_fd <= 30)) {
1261 $raw .= "\tbridge-fd $br_fd\n";
1262 } else {
1263 # only complain if the user actually set a value, but not for default fallback below
1264 warn "'$iface': ignoring 'bridge_fd' value '$br_fd', outside of allowed range 2-30\n";
1265 }
1266 } elsif ($no_stp) {
1267 $raw .= "\tbridge-fd 0\n";
e960f794 1268 }
9b7b13a1 1269 $done->{bridge_fd} = 1;
685a2528 1270
74d28de2 1271 if (defined($d->{bridge_vlan_aware})) {
1accc6da 1272 $raw .= "\tbridge-vlan-aware yes\n";
43997e84
TL
1273 my $vlans = defined($d->{bridge_vids}) ? $d->{bridge_vids} : "2-4094";
1274 $raw .= "\tbridge-vids $vlans\n";
685a2528
AD
1275 }
1276 $done->{bridge_vlan_aware} = 1;
f6c4a563 1277 $done->{bridge_vids} = 1;
9bbc4e17 1278
2d1e9a02
AD
1279 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1280 $done->{mtu} = 1;
25558f13 1281 $done->{'bridge-disable-mac-learning'} = 1;
2d1e9a02 1282
9b7b13a1 1283 } elsif ($d->{type} eq 'bond') {
e143e9d8 1284
fb3a6db1 1285 $d->{slaves} =~ s/[;,\s]+/ /g;
e143e9d8 1286 my $slaves = $d->{slaves} || 'none';
1accc6da 1287 $raw .= "\tbond-slaves $slaves\n";
9b7b13a1 1288 $done->{slaves} = 1;
e143e9d8 1289
9b7b13a1 1290 my $v = defined ($d->{'bond_miimon'}) ? $d->{'bond_miimon'} : 100;
1accc6da 1291 $raw .= "\tbond-miimon $v\n";
9b7b13a1 1292 $done->{'bond_miimon'} = 1;
e143e9d8 1293
9b7b13a1 1294 $v = defined ($d->{'bond_mode'}) ? $d->{'bond_mode'} : 'balance-rr';
1accc6da 1295 $raw .= "\tbond-mode $v\n";
9b7b13a1
DM
1296 $done->{'bond_mode'} = 1;
1297
40fae2b3
DM
1298 if ($d->{'bond_mode'} && $d->{'bond_xmit_hash_policy'} &&
1299 ($d->{'bond_mode'} eq 'balance-xor' || $d->{'bond_mode'} eq '802.3ad')) {
1accc6da 1300 $raw .= "\tbond-xmit-hash-policy $d->{'bond_xmit_hash_policy'}\n";
40fae2b3
DM
1301 }
1302 $done->{'bond_xmit_hash_policy'} = 1;
b94d05ec
AD
1303
1304 if ($d->{'bond_mode'} && $d->{'bond_mode'} eq 'active-backup' && $d->{'bond-primary'}) {
1305 $raw .= "\tbond-primary $d->{'bond-primary'}\n";
1306 }
1307 $done->{'bond-primary'} = 1;
1308
2d1e9a02
AD
1309 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1310 $done->{mtu} = 1;
1311
8f5d56bf 1312 } elsif ($d->{type} eq 'vlan') {
9bbc4e17 1313 die "$iface: wrong vlan-protocol $d->{'vlan-protocol'}\n"
8f5d56bf 1314 if $d->{'vlan-protocol'} && $d->{'vlan-protocol'} ne '802.1ad' && $d->{'vlan-protocol'} ne '802.1q';
9bbc4e17 1315
95aa8788
AD
1316 } elsif ($d->{type} eq 'vxlan') {
1317
94d786b3
WB
1318 foreach my $k (qw(vxlan-id vxlan-svcnodeip vxlan-physdev vxlan-local-tunnelip)) {
1319 $raw .= "\t$k $d->{$k}\n" if defined $d->{$k};
95aa8788 1320 $done->{$k} = 1;
94d786b3 1321 }
95aa8788
AD
1322
1323 if ($d->{'vxlan-remoteip'}) {
1324 foreach my $remoteip (@{$d->{'vxlan-remoteip'}}) {
1325 $raw .= "\tvxlan-remoteip $remoteip\n";
1326 }
1327 $done->{'vxlan-remoteip'} = 1;
1328 }
2d1e9a02
AD
1329
1330 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1331 $done->{mtu} = 1;
1332
9b7b13a1
DM
1333 } elsif ($d->{type} eq 'OVSBridge') {
1334
1335 $raw .= "\tovs_type $d->{type}\n";
1336 $done->{ovs_type} = 1;
1337
1338 $raw .= "\tovs_ports $d->{ovs_ports}\n" if $d->{ovs_ports};
1339 $done->{ovs_ports} = 1;
2d1e9a02
AD
1340
1341 $raw .= "\tovs_mtu $d->{mtu}\n" if $d->{mtu};
1342 $done->{mtu} = 1;
1343
75a2a1c6 1344 } elsif ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' || $d->{type} eq 'OVSBond') {
9b7b13a1
DM
1345
1346 $d->{autostart} = 0; # started by the bridge
1347
2a751938
DM
1348 if (defined($d->{ovs_tag})) {
1349 &$set_ovs_option($d, tag => $d->{ovs_tag});
1350 }
1351 $done->{ovs_tag} = 1;
1352
9b7b13a1
DM
1353 if ($d->{type} eq 'OVSBond') {
1354
1355 $d->{bond_mode} = 'active-backup' if !$d->{bond_mode};
1356
1357 $ovs_bond_modes->{$d->{bond_mode}} ||
1358 die "OVS does not support bond mode '$d->{bond_mode}\n";
1359
a68760b6
DM
1360 if ($d->{bond_mode} eq 'lacp-balance-slb') {
1361 &$set_ovs_option($d, lacp => 'active');
1362 &$set_ovs_option($d, bond_mode => 'balance-slb');
1363 } elsif ($d->{bond_mode} eq 'lacp-balance-tcp') {
1364 &$set_ovs_option($d, lacp => 'active');
1365 &$set_ovs_option($d, bond_mode => 'balance-tcp');
1366 } else {
1367 &$set_ovs_option($d, lacp => undef);
1368 &$set_ovs_option($d, bond_mode => $d->{bond_mode});
1369 }
9b7b13a1
DM
1370 $done->{bond_mode} = 1;
1371
1372 $raw .= "\tovs_bonds $d->{ovs_bonds}\n" if $d->{ovs_bonds};
1373 $done->{ovs_bonds} = 1;
1374 }
1375
9b7b13a1
DM
1376 $raw .= "\tovs_type $d->{type}\n";
1377 $done->{ovs_type} = 1;
1378
bd9cc42d 1379 if (my $bridge = $d->{ovs_bridge}) {
d34d7393
AD
1380 if ($ifupdown2) {
1381 $raw = "auto $iface\n$raw";
1382 } else {
1383 $raw = "allow-$bridge $iface\n$raw";
1384 }
1385
bd9cc42d 1386 $raw .= "\tovs_bridge $bridge\n";
9b7b13a1
DM
1387 $done->{ovs_bridge} = 1;
1388 }
2d1e9a02
AD
1389
1390 $raw .= "\tovs_mtu $d->{mtu}\n" if $d->{mtu};
1391 $done->{mtu} = 1;
9b7b13a1
DM
1392 }
1393
48ab17b3
WB
1394 if ($first_block) {
1395 # print other settings
9a052564 1396 foreach my $k (sort keys %$d) {
48ab17b3
WB
1397 next if $done->{$k};
1398 next if !$d->{$k};
1399 $raw .= "\t$k $d->{$k}\n";
1400 }
e143e9d8
DM
1401 }
1402
48ab17b3 1403 foreach my $option (@{$d->{"options$suffix"}}) {
e143e9d8
DM
1404 $raw .= "\t$option\n";
1405 }
1406
ed4e6e0c 1407 # add comments
48ab17b3 1408 my $comments = $d->{"comments$suffix"} || '';
ed4e6e0c
DM
1409 foreach my $cl (split(/\n/, $comments)) {
1410 $raw .= "#$cl\n";
72ca6520
DM
1411 }
1412
e143e9d8
DM
1413 $raw .= "\n";
1414
1415 return $raw;
1416}
1417
78325766 1418
e143e9d8 1419sub write_etc_network_interfaces {
48ab17b3 1420 my ($filename, $fh, $config) = @_;
bc6713df 1421 my $ifupdown2 = -e '/usr/share/ifupdown2/ifupdown2';
b7c4f378 1422 my $raw = __write_etc_network_interfaces($config, $ifupdown2);
1b505ae2 1423 PVE::Tools::safe_print($filename, $fh, encode('UTF-8', $raw));
78325766
WB
1424}
1425sub __write_etc_network_interfaces {
b7c4f378 1426 my ($config, $ifupdown2) = @_;
48ab17b3
WB
1427
1428 my $ifaces = $config->{ifaces};
1429 my @options = @{$config->{options}};
e143e9d8 1430
9b7b13a1
DM
1431 my $used_ports = {};
1432
1433 foreach my $iface (keys %$ifaces) {
1434 my $d = $ifaces->{$iface};
1435
9197b046
TL
1436 my ($cidr, $cidr6) = (delete $d->{cidr}, delete $d->{cidr6});
1437 $d->{address} //= $cidr;
1438 $d->{address6} //= $cidr6;
2896245e 1439
9b7b13a1
DM
1440 my $ports = '';
1441 foreach my $k (qw(bridge_ports ovs_ports slaves ovs_bonds)) {
1442 $ports .= " $d->{$k}" if $d->{$k};
1443 }
1444
1445 foreach my $p (PVE::Tools::split_list($ports)) {
1446 die "port '$p' is already used on interface '$used_ports->{$p}'\n"
1447 if $used_ports->{$p} && $used_ports->{$p} ne $iface;
1448 $used_ports->{$p} = $iface;
1449 }
1450 }
1451
1452 # delete unused OVS ports
1453 foreach my $iface (keys %$ifaces) {
1454 my $d = $ifaces->{$iface};
75a2a1c6 1455 if ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' || $d->{type} eq 'OVSBond') {
9b7b13a1 1456 my $brname = $used_ports->{$iface};
94d786b3 1457 if (!$brname || !$ifaces->{$brname}) {
3dabe28a 1458 if ($iface =~ /^$PVE::Network::PHYSICAL_NIC_RE/) {
040fc87d
TL
1459 $ifaces->{$iface} = {
1460 type => 'eth',
1461 exists => 1,
1462 method => 'manual',
1463 families => ['inet'],
1464 };
516a50a4
WB
1465 } else {
1466 delete $ifaces->{$iface};
1467 }
9b7b13a1
DM
1468 next;
1469 }
1470 my $bd = $ifaces->{$brname};
1471 if ($bd->{type} ne 'OVSBridge') {
1472 delete $ifaces->{$iface};
1473 next;
1474 }
1475 }
1476 }
1477
1478 # create OVS bridge ports
1479 foreach my $iface (keys %$ifaces) {
1480 my $d = $ifaces->{$iface};
1481 if ($d->{type} eq 'OVSBridge' && $d->{ovs_ports}) {
1482 foreach my $p (split (/\s+/, $d->{ovs_ports})) {
1483 my $n = $ifaces->{$p};
75a2a1c6 1484 die "OVS bridge '$iface' - unable to find port '$p'\n" if !$n;
21d32c95 1485 $n->{autostart} = 0;
9b7b13a1
DM
1486 if ($n->{type} eq 'eth') {
1487 $n->{type} = 'OVSPort';
94d786b3 1488 $n->{ovs_bridge} = $iface;
9b7b13a1
DM
1489 } elsif ($n->{type} eq 'OVSBond' || $n->{type} eq 'OVSPort' ||
1490 $n->{type} eq 'OVSIntPort') {
1491 $n->{ovs_bridge} = $iface;
1492 } else {
1493 die "interface '$p' is not defined as OVS port/bond\n";
1494 }
9b053d70
AD
1495
1496 &$check_mtu($ifaces, $iface, $p);
9b7b13a1
DM
1497 }
1498 }
1499 }
1500
1501 # check OVS bond ports
1502 foreach my $iface (keys %$ifaces) {
1503 my $d = $ifaces->{$iface};
1504 if ($d->{type} eq 'OVSBond' && $d->{ovs_bonds}) {
1505 foreach my $p (split (/\s+/, $d->{ovs_bonds})) {
1506 my $n = $ifaces->{$p};
fe2a773c 1507 $n->{autostart} = 1;
75a2a1c6
TL
1508 die "OVS bond '$iface' - unable to find slave '$p'\n" if !$n;
1509 die "OVS bond '$iface' - wrong interface type on slave '$p' ('$n->{type}' != 'eth')\n"
1510 if $n->{type} ne 'eth';
9b053d70 1511 &$check_mtu($ifaces, $iface, $p);
9b7b13a1
DM
1512 }
1513 }
1514 }
1515
0115696f
AD
1516 # check bond
1517 foreach my $iface (keys %$ifaces) {
1518 my $d = $ifaces->{$iface};
329dfb64 1519 next if !($d->{type} eq 'bond' && $d->{slaves});
6f830d1d 1520
329dfb64
TL
1521 my $bond_primary_is_slave = undef;
1522 foreach my $p (split (/\s+/, $d->{slaves})) {
1523 my $n = $ifaces->{$p};
1524 $n->{autostart} = 1;
1525
1526 die "bond '$iface' - unable to find slave '$p'\n" if !$n;
1527 die "bond '$iface' - wrong interface type on slave '$p' ('$n->{type}' != 'eth or bond')\n"
1528 if ($n->{type} ne 'eth' && $n->{type} ne 'bond');
1529
1530 $check_mtu->($ifaces, $iface, $p);
1531 $bond_primary_is_slave = 1 if $d->{'bond-primary'} && $d->{'bond-primary'} eq $p;
0115696f 1532 }
329dfb64 1533 die "bond '$iface' - bond-primary interface is not a slave" if $d->{'bond-primary'} && !$bond_primary_is_slave;
0115696f
AD
1534 }
1535
95aa8788
AD
1536 # check vxlan
1537 my $vxlans = {};
1538 foreach my $iface (keys %$ifaces) {
1539 my $d = $ifaces->{$iface};
1540
1541 if ($d->{type} eq 'vxlan' && $d->{'vxlan-id'}) {
1542 my $vxlanid = $d->{'vxlan-id'};
94d786b3 1543 die "iface $iface - duplicate vxlan-id $vxlanid already used in $vxlans->{$vxlanid}\n" if $vxlans->{$vxlanid};
95aa8788
AD
1544 $vxlans->{$vxlanid} = $iface;
1545 }
1546
1547 my $ips = 0;
1548 ++$ips if defined $d->{'vxlan-svcnodeip'};
1549 ++$ips if defined $d->{'vxlan-remoteip'};
1550 ++$ips if defined $d->{'vxlan-local-tunnelip'};
1551 if ($ips > 1) {
94d786b3 1552 die "iface $iface - vxlan-svcnodeip, vxlan-remoteip and vxlan-localtunnelip are mutually exclusive\n";
95aa8788
AD
1553 }
1554
1555 if (defined($d->{'vxlan-svcnodeip'}) != defined($d->{'vxlan-physdev'})) {
94d786b3 1556 die "iface $iface - vxlan-svcnodeip and vxlan-physdev must be define together\n";
95aa8788 1557 }
9b053d70 1558 #fixme : check if vxlan mtu is lower than 50bytes than physical interface where tunnel is going out
95aa8788
AD
1559 }
1560
c4e56470
AD
1561 # check vlan
1562 foreach my $iface (keys %$ifaces) {
1563 my $d = $ifaces->{$iface};
bbe7d3ed
AD
1564 if ($d->{type} eq 'vlan') {
1565
1566 my $p = undef;
1567 my $vlanid = undef;
1568
1569 if ($iface =~ m/^(\S+)\.(\d+)$/) {
1570 $p = $1;
1571 $vlanid = $2;
1572 delete $d->{'vlan-raw-device'} if $d->{'vlan-raw-device'};
9ca89b87
AD
1573 delete $d->{'vlan-id'} if $d->{'vlan-id'};
1574
bbe7d3ed
AD
1575 } else {
1576 die "missing vlan-raw-device option" if !$d->{'vlan-raw-device'};
1577 $p = $d->{'vlan-raw-device'};
1578
1579 if ($iface =~ m/^vlan(\d+)$/) {
1580 $vlanid = $1;
1581 delete $d->{'vlan-id'} if $d->{'vlan-id'};
1582 } else {
1583 die "custom vlan interface name need ifupdown2" if !$ifupdown2;
1584 die "missing vlan-id option" if !$d->{'vlan-id'};
1585 $vlanid = $d->{'vlan-id'};
1586 }
1587 }
c4e56470
AD
1588 my $n = $ifaces->{$p};
1589
bbe7d3ed 1590 die "vlan '$iface' - vlan-id $vlanid should be <= 4094\n" if $vlanid > 4094;
c4e56470 1591 die "vlan '$iface' - unable to find parent '$p'\n"
fc158d0d 1592 if !$n;
c4e56470 1593
c8ff0bdf 1594 if ($n->{type} ne 'eth' && $n->{type} ne 'bridge' && $n->{type} ne 'bond' && $n->{type} ne 'vlan') {
c4e56470 1595 die "vlan '$iface' - wrong interface type on parent '$p' " .
8f5d56bf 1596 "('$n->{type}' != 'eth|bond|bridge|vlan' )\n";
c4e56470 1597 }
8f5d56bf 1598
000e32bc 1599 &$check_mtu($ifaces, $p, $iface);
8f5d56bf 1600
c4e56470
AD
1601 }
1602 }
1603
d949babe
AD
1604 # check uplink
1605 my $uplinks = {};
1606 foreach my $iface (keys %$ifaces) {
1607 my $d = $ifaces->{$iface};
1608 if (my $uplinkid = $d->{'uplink-id'}) {
1609 die "iface '$iface' - uplink-id $uplinkid is only allowed on physical and linux bond interfaces\n"
9bbc4e17 1610 if $d->{type} ne 'eth' && $d->{type} ne 'bond';
d949babe
AD
1611
1612 die "iface '$iface' - uplink-id $uplinkid is already assigned on '$uplinks->{$uplinkid}'\n"
1613 if $uplinks->{$uplinkid};
1614
1615 $uplinks->{$uplinkid} = $iface;
1616 }
1617 }
1618
9a052564
AD
1619 # check bridgeport option
1620 my $bridgeports = {};
1621 my $bridges = {};
a70e9925
AD
1622 my $ifaces_copy = { %$ifaces };
1623 foreach my $iface (keys %$ifaces_copy) {
1624 my $d = $ifaces_copy->{$iface};
9a052564 1625 if ($d->{type} eq 'bridge') {
8342b610 1626 foreach my $p (split (/\s+/, $d->{bridge_ports} // '')) {
a70e9925
AD
1627 if($p =~ m/(\S+)\.(\d+)$/) {
1628 my $vlanparent = $1;
1629 if (!defined($ifaces_copy->{$p})) {
1630 $ifaces_copy->{$p}->{type} = 'vlan';
1631 $ifaces_copy->{$p}->{method} = 'manual';
1632 $ifaces_copy->{$p}->{method6} = 'manual';
1633 $ifaces_copy->{$p}->{mtu} = $ifaces_copy->{$vlanparent}->{mtu} if defined($ifaces_copy->{$1}->{mtu});
1634 }
1635 }
1636 my $n = $ifaces_copy->{$p};
055f076b 1637 die "bridge '$iface' - unable to find bridge port '$p'\n" if !$n;
6f830d1d 1638 die "iface $p - ip address can't be set on interface if bridged in $iface\n"
dd3004e2 1639 if ($n->{method} && $n->{method} eq 'static' && $n->{address} ne '0.0.0.0') ||
eeafe02d 1640 ($n->{method6} && $n->{method6} eq 'static' && $n->{address6} ne '::');
a70e9925 1641 &$check_mtu($ifaces_copy, $p, $iface);
9a052564
AD
1642 $bridgeports->{$p} = $iface;
1643 }
1644 $bridges->{$iface} = $d;
1645 }
1646 }
1647
1648 foreach my $iface (keys %$ifaces) {
1649 my $d = $ifaces->{$iface};
1650
1651 foreach my $k (qw(bridge-learning bridge-arp-nd-suppress bridge-unicast-flood bridge-multicast-flood bridge-access)) {
94d786b3 1652 die "iface $iface - $k: bridge port specific options can be used only on interfaces attached to a bridge\n"
9a052564
AD
1653 if $d->{$k} && !$bridgeports->{$iface};
1654 }
1655
1656 if ($d->{'bridge-access'} && !$bridges->{$bridgeports->{$iface}}->{bridge_vlan_aware}) {
94d786b3 1657 die "iface $iface - bridge-access option can be only used if interface is in a vlan aware bridge\n";
9a052564
AD
1658 }
1659 }
1660
9d27ef41
WB
1661 my $raw = <<'NETWORKDOC';
1662# network interface settings; autogenerated
1663# Please do NOT modify this file directly, unless you know what
1664# you're doing.
1665#
b3e3b51b 1666# If you want to manage parts of the network configuration manually,
9d27ef41
WB
1667# please utilize the 'source' or 'source-directory' directives to do
1668# so.
b3e3b51b 1669# PVE will preserve these directives, but will NOT read its network
9d27ef41
WB
1670# configuration from sourced files, so do not attempt to move any of
1671# the PVE managed interfaces into external files!
1672
1673NETWORKDOC
e143e9d8
DM
1674
1675 my $printed = {};
1676
ed4e6e0c 1677 my $if_type_hash = {
562fad0b 1678 loopback => 100000,
a85812af 1679 dummy => 100000,
562fad0b 1680 eth => 200000,
51eec390 1681 OVSPort => 200000,
36bbe29d
AD
1682 OVSIntPort => 300000,
1683 OVSBond => 400000,
1684 bond => 400000,
1685 bridge => 500000,
1686 OVSBridge => 500000,
1687 vlan => 600000,
1688 vxlan => 600000,
9b7b13a1 1689 };
ed4e6e0c
DM
1690
1691 my $lookup_type_prio = sub {
51eec390 1692 my ($iface, $ifaces) = @_;
ed4e6e0c 1693
0c0bcf7c
WB
1694 my ($rootiface, @rest) = split(/[.:]/, $iface);
1695 my $childlevel = scalar(@rest);
87ff065c
TL
1696 my $type = $ifaces->{$rootiface}->{type};
1697 return if !$type || $type eq 'unknown';
ed4e6e0c 1698
87ff065c 1699 return $if_type_hash->{$type} + $childlevel
ed4e6e0c
DM
1700 };
1701
c9dc8645
DM
1702 foreach my $iface (sort {
1703 my $ref1 = $ifaces->{$a};
1704 my $ref2 = $ifaces->{$b};
51eec390
AD
1705 my $tp1 = &$lookup_type_prio($a, $ifaces);
1706 my $tp2 = &$lookup_type_prio($b, $ifaces);
e143e9d8 1707
7a822100
WB
1708 # Only recognized types are in relation to each other. If one type
1709 # is unknown then only consider the interfaces' priority attributes.
1710 $tp1 = $tp2 = 0 if !defined($tp1) || !defined($tp2);
1711
1712 my $p1 = $tp1 + ($ref1->{priority} // 50000);
1713 my $p2 = $tp2 + ($ref2->{priority} // 50000);
ed4e6e0c
DM
1714
1715 return $p1 <=> $p2 if $p1 != $p2;
c9dc8645
DM
1716
1717 return $a cmp $b;
11e7facb 1718 } keys %$ifaces) {
c9dc8645 1719 next if $printed->{$iface};
11e7facb 1720 my $d = $ifaces->{$iface};
562fad0b
WB
1721 my $pri = $d->{priority} // 0;
1722 if (@options && $options[0]->[0] < $pri) {
48ab17b3
WB
1723 do {
1724 $raw .= (shift @options)->[1] . "\n";
562fad0b 1725 } while (@options && $options[0]->[0] < $pri);
48ab17b3
WB
1726 $raw .= "\n";
1727 }
1728
c9dc8645 1729 $printed->{$iface} = 1;
f48815f8 1730 if ($d->{autostart}) {
d34d7393 1731 if ($d->{type} eq 'OVSBridge' && !$ifupdown2) {
f48815f8
AD
1732 # cannot use 'auto' for OVS, would add race with systemd ifup@.service
1733 $raw .= "allow-ovs $iface\n";
1734 } else {
1735 $raw .= "auto $iface\n";
1736 }
4ac94c72
AD
1737 }
1738
f2ac9dd3
LS
1739 # if 'inet6' is the only family
1740 if (scalar($d->{families}->@*) == 1 && $d->{families}[0] eq 'inet6') {
1741 $d->{comments6} = delete $d->{comments};
1742 }
1743
48ab17b3 1744 my $i = 0; # some options should be printed only once
b7c4f378 1745 $raw .= __interface_to_string($iface, $d, $_, !$i++, $ifupdown2) foreach @{$d->{families}};
e143e9d8 1746 }
48ab17b3
WB
1747
1748 $raw .= $_->[1] . "\n" foreach @options;
78325766 1749 return $raw;
e143e9d8
DM
1750}
1751
1752register_file('interfaces', "/etc/network/interfaces",
1753 \&read_etc_network_interfaces,
1754 \&write_etc_network_interfaces);
1755
ddd3d224
DM
1756
1757sub read_iscsi_initiatorname {
1758 my ($filename, $fd) = @_;
1759
1760 while (defined(my $line = <$fd>)) {
1761 if ($line =~ m/^InitiatorName=(\S+)$/) {
1762 return $1;
1763 }
1764 }
1765
1766 return 'undefined';
1767}
1768
9bbc4e17 1769register_file('initiatorname', "/etc/iscsi/initiatorname.iscsi",
ddd3d224
DM
1770 \&read_iscsi_initiatorname);
1771
e143e9d8 17721;