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