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