]> git.proxmox.com Git - pve-common.git/blame - src/PVE/INotify.pm
bump version to 6.0-13
[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
e143e9d8
DM
7use POSIX;
8use IO::File;
9use IO::Dir;
10use File::stat;
11use File::Basename;
12use Fcntl qw(:DEFAULT :flock);
13use PVE::SafeSyslog;
14use PVE::Exception qw(raise_param_exc);
3dabe28a 15use PVE::Network;
e143e9d8 16use PVE::Tools;
f0d1b04f 17use PVE::ProcFSTools;
2896245e 18use PVE::JSONSchema;
32ef45ae 19use Clone qw(clone);
e143e9d8
DM
20use Linux::Inotify2;
21use base 'Exporter';
69758574 22use JSON;
9194ee06 23use Digest::SHA;
69758574 24use Encode qw(encode decode);
e143e9d8
DM
25
26our @EXPORT_OK = qw(read_file write_file register_file);
27
28my $ccache;
29my $ccachemap;
30my $ccacheregex;
31my $inotify;
32my $inotify_pid = 0;
33my $versions;
34my $shadowfiles = {
35 '/etc/network/interfaces' => '/etc/network/interfaces.new',
36};
37
38# to enable cached operation, you need to call 'inotify_init'
39# inotify handles are a limited resource, so use with care (only
40# enable the cache if you really need it)
41
42# Note: please close the inotify handle after you fork
43
44sub ccache_default_writer {
45 my ($filename, $data) = @_;
46
47 die "undefined config writer for '$filename' :ERROR";
48}
49
50sub ccache_default_parser {
51 my ($filename, $srcfd) = @_;
52
53 die "undefined config reader for '$filename' :ERROR";
54}
55
56sub ccache_compute_diff {
57 my ($filename, $shadow) = @_;
58
59 my $diff = '';
60
69758574
DC
61 my $cmd = ['/usr/bin/diff', '-b', '-N', '-u', $filename, $shadow];
62 PVE::Tools::run_command($cmd, noerr => 1, outfunc => sub {
63 my ($line) = @_;
64 $diff .= decode('UTF-8', $line) . "\n";
65 });
e143e9d8
DM
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;
9bbc4e17 86 }
e143e9d8
DM
87 return ($ccache->{$filename}, $filename);
88 }
89 }
9bbc4e17 90
e143e9d8
DM
91 $filename = $ccachemap->{$filename} if defined ($ccachemap->{$filename});
92
93 die "file '$filename' not added :ERROR" if !defined ($ccache->{$filename});
9bbc4e17 94
e143e9d8
DM
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;
9bbc4e17 137 die $msg;
e143e9d8
DM
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");
9bbc4e17 170
e143e9d8
DM
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);
9bbc4e17 218
e143e9d8 219 $parser = $ccinfo->{parser};
9bbc4e17 220
e143e9d8
DM
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;
9bbc4e17 240 $ccinfo->{data} = undef;
e143e9d8
DM
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};
9bbc4e17 262
e143e9d8
DM
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};
9bbc4e17 295}
e143e9d8
DM
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') {
1f929ade 314 # when set, we call parser even when the file does not exist.
e143e9d8
DM
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);
9bbc4e17 339
e143e9d8
DM
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});
9bbc4e17 355
e143e9d8
DM
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};
9bbc4e17 419 $dirhash->{$ccinfo->{dir}}->{_regex} = 1;
e143e9d8
DM
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 }
9bbc4e17 449 if ($e->IN_IGNORED) {
e143e9d8
DM
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)) {
9bbc4e17 482 while (defined(my $de = $fd->read)) {
e143e9d8
DM
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
9bbc4e17
TL
537register_file('hostname', "/etc/hostname",
538 \&read_etc_hostname,
e143e9d8
DM
539 \&write_etc_hostname);
540
9194ee06
DC
541sub read_etc_hosts {
542 my ($filename, $fh) = @_;
543
544 my $raw = '';
545 my $data = '';
546
547 while (my $line = <$fh>) {
548 $raw .= $line;
549 if ($line =~ m/^\s*#/) {
550 $line = decode('UTF-8', $line);
551 }
552 $data .= $line;
553 }
554
555 return {
556 digest => Digest::SHA::sha1_hex($raw),
557 data => $data,
558 }
559}
560
561sub write_etc_hosts {
562 my ($filename, $fh, $hosts, @args) = @_;
563
564 # check validity of ips/names
565 for my $line (split("\n", $hosts)) {
566 next if $line =~ m/^\s*#/; # comments
567 next if $line =~ m/^\s*$/; # whitespace/empty lines
568
569 my ($ip, @names) = split(/\s+/, $line);
570
571 raise_param_exc({ 'data' => "Invalid IP '$ip'" })
572 if $ip !~ m/^$PVE::Tools::IPRE$/;
573
574 for my $name (@names) {
575 raise_param_exc({ 'data' => "Invalid Hostname '$name'" })
576 if $name !~ m/^[.\-a-zA-Z0-9]+$/;
577 }
578 }
579
580 die "write failed: $!" if !print $fh encode('UTF-8', $hosts);
581
582 return $hosts;
583}
584
585register_file('etchosts', "/etc/hosts",
586 \&read_etc_hosts,
587 \&write_etc_hosts);
588
e143e9d8
DM
589sub read_etc_resolv_conf {
590 my ($filename, $fh) = @_;
591
592 my $res = {};
593
594 my $nscount = 0;
595 while (my $line = <$fh>) {
596 chomp $line;
597 if ($line =~ m/^(search|domain)\s+(\S+)\s*/) {
598 $res->{search} = $2;
176b1186 599 } elsif ($line =~ m/^\s*nameserver\s+($PVE::Tools::IPRE)\s*/) {
e143e9d8
DM
600 $nscount++;
601 if ($nscount <= 3) {
602 $res->{"dns$nscount"} = $1;
603 }
604 }
605 }
606
607 return $res;
608}
609
610sub update_etc_resolv_conf {
611 my ($filename, $fh, $resolv, @args) = @_;
612
613 my $data = "";
614
615 $data = "search $resolv->{search}\n"
616 if $resolv->{search};
617
618 my $written = {};
619 foreach my $k ("dns1", "dns2", "dns3") {
620 my $ns = $resolv->{$k};
621 if ($ns && $ns ne '0.0.0.0' && !$written->{$ns}) {
622 $written->{$ns} = 1;
623 $data .= "nameserver $ns\n";
624 }
625 }
626
627 while (my $line = <$fh>) {
628 next if $line =~ m/^(search|domain|nameserver)\s+/;
629 $data .= $line
630 }
9bbc4e17 631
e143e9d8
DM
632 return $data;
633}
634
9bbc4e17
TL
635register_file('resolvconf', "/etc/resolv.conf",
636 \&read_etc_resolv_conf, undef,
e143e9d8
DM
637 \&update_etc_resolv_conf);
638
639sub read_etc_timezone {
640 my ($filename, $fd) = @_;
641
642 my $timezone = <$fd>;
643
644 chomp $timezone;
645
646 return $timezone;
647}
648
649sub write_etc_timezone {
650 my ($filename, $fh, $timezone) = @_;
651
652 my $tzinfo = "/usr/share/zoneinfo/$timezone";
653
654 raise_param_exc({ 'timezone' => "No such timezone" })
655 if (! -f $tzinfo);
656
657 ($timezone) = $timezone =~ m/^(.*)$/; # untaint
658
659 print $fh "$timezone\n";
660
661 unlink ("/etc/localtime");
662 symlink ("/usr/share/zoneinfo/$timezone", "/etc/localtime");
663
664}
665
9bbc4e17
TL
666register_file('timezone', "/etc/timezone",
667 \&read_etc_timezone,
e143e9d8
DM
668 \&write_etc_timezone);
669
670sub read_active_workers {
671 my ($filename, $fh) = @_;
672
673 return [] if !$fh;
674
9bbc4e17 675 my $res = [];
e143e9d8 676 while (defined (my $line = <$fh>)) {
75ed54f1 677 if ($line =~ m/^(\S+)\s(0|1)(\s([0-9A-Za-z]{8})(\s(\s*\S.*))?)?$/) {
e143e9d8
DM
678 my $upid = $1;
679 my $saved = $2;
680 my $endtime = $4;
681 my $status = $6;
682 if ((my $task = PVE::Tools::upid_decode($upid, 1))) {
683 $task->{upid} = $upid;
684 $task->{saved} = $saved;
685 $task->{endtime} = hex($endtime) if $endtime;
686 $task->{status} = $status if $status;
687 push @$res, $task;
688 }
689 } else {
690 warn "unable to parse line: $line";
691 }
692 }
693
694 return $res;
695
696}
697
698sub write_active_workers {
699 my ($filename, $fh, $tasklist) = @_;
700
701 my $raw = '';
702 foreach my $task (@$tasklist) {
703 my $upid = $task->{upid};
704 my $saved = $task->{saved} ? 1 : 0;
705 if ($task->{endtime}) {
706 if ($task->{status}) {
e34c27f4 707 $raw .= sprintf("%s %s %08X %s\n", $upid, $saved, $task->{endtime}, $task->{status});
e143e9d8 708 } else {
e34c27f4 709 $raw .= sprintf("%s %s %08X\n", $upid, $saved, $task->{endtime});
e143e9d8
DM
710 }
711 } else {
712 $raw .= "$upid $saved\n";
713 }
714 }
715
716 PVE::Tools::safe_print($filename, $fh, $raw) if $raw;
717}
718
9bbc4e17 719register_file('active', "/var/log/pve/tasks/active",
e143e9d8
DM
720 \&read_active_workers,
721 \&write_active_workers);
722
723
c8e5d28e 724our $bond_modes = { 'balance-rr' => 0,
e143e9d8
DM
725 'active-backup' => 1,
726 'balance-xor' => 2,
727 'broadcast' => 3,
728 '802.3ad' => 4,
729 'balance-tlb' => 5,
730 'balance-alb' => 6,
731 };
732
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
AD
883 'bridge-ports' => 'bridge_ports',
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*#/;
c86cfb8b 904 next if $line =~ m/^\s*(allow-hotplug)\s+(.*)$/;
9bbc4e17 905
f48815f8
AD
906 if ($line =~ m/^\s*(auto|allow-ovs)\s+(.*)$/) {
907 my @aa = split (/\s+/, $2);
e143e9d8
DM
908
909 foreach my $a (@aa) {
910 $ifaces->{$a}->{autostart} = 1;
911 }
912
48ab17b3 913 } elsif ($line =~ m/^\s*iface\s+(\S+)\s+(inet6?)\s+(\S+)\s*$/) {
e143e9d8 914 my $i = $1;
48ab17b3
WB
915 my $family = $2;
916 my $f = { method => $3 }; # by family, merged to $d with a $suffix
917 (my $suffix = $family) =~ s/^inet//;
e143e9d8 918
cb07ff78 919 my $d = $ifaces->{$i} ||= {};
48ab17b3
WB
920 $d->{priority} = $priority++ if !$d->{priority};
921 push @{$d->{families}}, $family;
922
72ca6520 923 while (defined ($line = <$fh>)) {
b1d7951f
WB
924 chomp $line;
925 if ($line =~ m/^\s*#(.*?)\s*$/) {
48ab17b3 926 $f->{comments} = '' if !$f->{comments};
1b505ae2
DC
927 my $comment = decode('UTF-8', $1);
928 $f->{comments} .= "$comment\n";
b1d7951f
WB
929 } elsif ($line =~ m/^\s*(?:iface\s
930 |mapping\s
931 |auto\s
932 |allow-
933 |source\s
934 |source-directory\s
935 )/x) {
936 last;
937 } elsif ($line =~ m/^\s*((\S+)\s+(.+))$/) {
72ca6520
DM
938 my $option = $1;
939 my ($id, $value) = ($2, $3);
1b1fb9f7
AD
940
941 $id = $options_alternatives->{$id} if $options_alternatives->{$id};
942
9a052564 943 my $simple_options = {
9b053d70 944 'mtu' => 1,
9a052564
AD
945 'ovs_type' => 1,
946 'ovs_options' => 1,
947 'ovs_bridge' => 1,
948 'ovs_bonds' => 1,
949 'ovs_ports' => 1,
950 'bridge_fd' => 1,
951 'bridge_vids' => 1,
952 'bridge-access' => 1,
953 'bridge-learning' => 1,
954 'bridge-arp-nd-suppress' => 1,
955 'bridge-unicast-flood' => 1,
956 'bridge-multicast-flood' => 1,
957 'bond_miimon' => 1,
958 'bond_xmit_hash_policy' => 1,
b94d05ec 959 'bond-primary' => 1,
d949babe 960 'uplink-id' => 1,
8f5d56bf 961 'vlan-protocol' => 1,
bbe7d3ed
AD
962 'vlan-raw-device' => 1,
963 'vlan-id' => 1,
9a052564
AD
964 'vxlan-id' => 1,
965 'vxlan-svcnodeip' => 1,
966 'vxlan-physdev' => 1,
967 'vxlan-local-tunnelip' => 1 };
968
0541ec90 969 if (($id eq 'address') || ($id eq 'netmask') || ($id eq 'broadcast') || ($id eq 'gateway')) {
48ab17b3 970 $f->{$id} = $value;
9a052564 971 } elsif ($simple_options->{$id}) {
9b7b13a1 972 $d->{$id} = $value;
72ca6520
DM
973 } elsif ($id eq 'slaves' || $id eq 'bridge_ports') {
974 my $devs = {};
975 foreach my $p (split (/\s+/, $value)) {
976 next if $p eq 'none';
977 $devs->{$p} = 1;
e143e9d8 978 }
72ca6520 979 my $str = join (' ', sort keys %{$devs});
48ab17b3
WB
980 if ($d->{$id}) {
981 $d->{$id} .= ' ' . $str if $str;
982 } else {
983 $d->{$id} = $str || '';
984 }
72ca6520
DM
985 } elsif ($id eq 'bridge_stp') {
986 if ($value =~ m/^\s*(on|yes)\s*$/i) {
987 $d->{$id} = 'on';
988 } else {
989 $d->{$id} = 'off';
990 }
685a2528
AD
991 } elsif ($id eq 'bridge_vlan_aware') {
992 $d->{$id} = 1;
72ca6520
DM
993 } elsif ($id eq 'bond_mode') {
994 # always use names
995 foreach my $bm (keys %$bond_modes) {
996 my $id = $bond_modes->{$bm};
997 if ($id eq $value) {
998 $value = $bm;
999 last;
1000 }
1001 }
1002 $d->{$id} = $value;
95aa8788
AD
1003 } elsif ($id eq 'vxlan-remoteip') {
1004 push @{$d->{$id}}, $value;
72ca6520 1005 } else {
48ab17b3 1006 push @{$f->{options}}, $option;
e143e9d8 1007 }
e143e9d8 1008 } else {
72ca6520 1009 last;
e143e9d8
DM
1010 }
1011 }
48ab17b3 1012 $d->{"$_$suffix"} = $f->{$_} foreach (keys %$f);
b1d7951f
WB
1013 last SECTION if !defined($line);
1014 redo SECTION;
48ab17b3
WB
1015 } elsif ($line =~ /\w/) {
1016 push @$options, [$priority++, $line];
e143e9d8
DM
1017 }
1018 }
1019
12a235d6
WB
1020 foreach my $ifname (@$active_ifaces) {
1021 if (my $iface = $ifaces->{$ifname}) {
1022 $iface->{active} = 1;
1023 }
1024 }
e143e9d8
DM
1025
1026 if (!$ifaces->{lo}) {
c9dc8645 1027 $ifaces->{lo}->{priority} = 1;
e143e9d8
DM
1028 $ifaces->{lo}->{method} = 'loopback';
1029 $ifaces->{lo}->{type} = 'loopback';
1030 $ifaces->{lo}->{autostart} = 1;
1031 }
1032
1033 foreach my $iface (keys %$ifaces) {
1034 my $d = $ifaces->{$iface};
1035 if ($iface =~ m/^bond\d+$/) {
9b7b13a1
DM
1036 if (!$d->{ovs_type}) {
1037 $d->{type} = 'bond';
1038 } elsif ($d->{ovs_type} eq 'OVSBond') {
1039 $d->{type} = $d->{ovs_type};
1040 # translate: ovs_options => bond_mode
1041 $d->{'bond_mode'} = &$extract_ovs_option($d, 'bond_mode');
a68760b6
DM
1042 my $lacp = &$extract_ovs_option($d, 'lacp');
1043 if ($lacp && $lacp eq 'active') {
1044 if ($d->{'bond_mode'} eq 'balance-slb') {
1045 $d->{'bond_mode'} = 'lacp-balance-slb';
1046 }
1047 }
1048 # Note: balance-tcp needs lacp
1049 if ($d->{'bond_mode'} eq 'balance-tcp') {
1050 $d->{'bond_mode'} = 'lacp-balance-tcp';
1051 }
2a751938
DM
1052 my $tag = &$extract_ovs_option($d, 'tag');
1053 $d->{ovs_tag} = $tag if defined($tag);
9b7b13a1
DM
1054 } else {
1055 $d->{type} = 'unknown';
e143e9d8 1056 }
9b7b13a1
DM
1057 } elsif ($iface =~ m/^vmbr\d+$/) {
1058 if (!$d->{ovs_type}) {
1059 $d->{type} = 'bridge';
1060
1061 if (!defined ($d->{bridge_fd})) {
1062 $d->{bridge_fd} = 0;
1063 }
1064 if (!defined ($d->{bridge_stp})) {
1065 $d->{bridge_stp} = 'off';
1066 }
1067 } elsif ($d->{ovs_type} eq 'OVSBridge') {
1068 $d->{type} = $d->{ovs_type};
1069 } else {
1070 $d->{type} = 'unknown';
e143e9d8
DM
1071 }
1072 } elsif ($iface =~ m/^(\S+):\d+$/) {
1073 $d->{type} = 'alias';
1074 if (defined ($ifaces->{$1})) {
1075 $d->{exists} = $ifaces->{$1}->{exists};
1076 } else {
1077 $ifaces->{$1}->{exists} = 0;
1078 $d->{exists} = 0;
1079 }
bbe7d3ed 1080 } elsif ($iface =~ m/^(\S+)\.\d+$/ || $d->{'vlan-raw-device'}) {
9c808945 1081 $d->{type} = 'vlan';
bbe7d3ed
AD
1082
1083 my $raw_iface = $d->{'vlan-raw-device'} ? $d->{'vlan-raw-device'} : $1;
1084 if (defined ($ifaces->{$raw_iface})) {
1085 $d->{exists} = $ifaces->{$raw_iface}->{exists};
9c808945 1086 } else {
bbe7d3ed 1087 $ifaces->{$raw_iface}->{exists} = 0;
9c808945
AD
1088 $d->{exists} = 0;
1089 }
3dabe28a 1090 } elsif ($iface =~ m/^$PVE::Network::PHYSICAL_NIC_RE$/) {
9b7b13a1
DM
1091 if (!$d->{ovs_type}) {
1092 $d->{type} = 'eth';
1093 } elsif ($d->{ovs_type} eq 'OVSPort') {
1094 $d->{type} = $d->{ovs_type};
2a751938
DM
1095 my $tag = &$extract_ovs_option($d, 'tag');
1096 $d->{ovs_tag} = $tag if defined($tag);
9b7b13a1
DM
1097 } else {
1098 $d->{type} = 'unknown';
1099 }
e143e9d8
DM
1100 } elsif ($iface =~ m/^lo$/) {
1101 $d->{type} = 'loopback';
1102 } else {
95aa8788
AD
1103 if ($d->{'vxlan-id'}) {
1104 $d->{type} = 'vxlan';
1105 } elsif (!$d->{ovs_type}) {
9b7b13a1
DM
1106 $d->{type} = 'unknown';
1107 } elsif ($d->{ovs_type} eq 'OVSIntPort') {
1108 $d->{type} = $d->{ovs_type};
2a751938
DM
1109 my $tag = &$extract_ovs_option($d, 'tag');
1110 $d->{ovs_tag} = $tag if defined($tag);
9b7b13a1 1111 }
e143e9d8
DM
1112 }
1113
2896245e
DC
1114 # map address and netmask to cidr
1115 if ($d->{address}) {
202eaa47
TL
1116 if ($d->{netmask}) {
1117 if ($d->{netmask} =~ m/^\d+$/) { # e.g. netmask 20
1118 $d->{address} = $d->{address} . "/" . $d->{netmask};
1119 } elsif (my $mask = PVE::JSONSchema::get_netmask_bits($d->{netmask})) {
1120 $d->{address} = $d->{address} . "/" . $mask;
1121 }
2896245e 1122 }
202eaa47
TL
1123 # for api compatibility
1124 $d->{cidr} = $d->{address};
2896245e
DC
1125 }
1126
1127 # map address6 and netmask6 to cidr6
1128 if ($d->{address6}) {
378c6656 1129 $d->{address6} .= "/" . $d->{netmask6} if $d->{address6} !~ m!^(.*)/(\d+)$! && $d->{netmask6};
202eaa47
TL
1130 # for api compatibility
1131 $d->{cidr6} = $d->{address6};
2896245e
DC
1132 }
1133
e143e9d8 1134 $d->{method} = 'manual' if !$d->{method};
48ab17b3 1135 $d->{method6} = 'manual' if !$d->{method6};
78325766
WB
1136
1137 $d->{families} ||= ['inet'];
e143e9d8
DM
1138 }
1139
516a50a4
WB
1140 # OVS bridges create "allow-$BRIDGE $IFACE" lines which we need to remove
1141 # from the {options} hash for them to be removed correctly.
1142 @$options = grep {defined($_)} map {
1143 my ($pri, $line) = @$_;
4ac94c72
AD
1144 if ($line =~ /^allow-ovs\s+(.*)$/) {
1145 undef;
1146 } elsif ($line =~ /^allow-(\S+)\s+(.*)$/) {
516a50a4
WB
1147 my $bridge = $1;
1148 my @ports = split(/\s+/, $2);
1149 if (defined(my $br = $ifaces->{$bridge})) {
1150 # if this port is part of a bridge, remove it
1151 my %in_ovs_ports = map {$_=>1} split(/\s+/, $br->{ovs_ports});
1152 @ports = grep { not $in_ovs_ports{$_} } @ports;
1153 }
1154 # create the allow line for the remaining ports, or delete if empty
1155 if (@ports) {
1156 [$pri, "allow-$bridge " . join(' ', @ports)];
1157 } else {
1158 undef;
1159 }
1160 } else {
1161 # don't modify other lines
1162 $_;
1163 }
1164 } @$options;
1165
48ab17b3 1166 return $config;
e143e9d8
DM
1167}
1168
1169sub __interface_to_string {
b7c4f378 1170 my ($iface, $d, $family, $first_block, $ifupdown2) = @_;
48ab17b3
WB
1171
1172 (my $suffix = $family) =~ s/^inet//;
e143e9d8 1173
48ab17b3 1174 return '' if !($d && $d->{"method$suffix"});
e143e9d8
DM
1175
1176 my $raw = '';
1177
48ab17b3 1178 $raw .= "iface $iface $family " . $d->{"method$suffix"} . "\n";
beedabb4
AD
1179 $raw .= "\taddress " . $d->{"address$suffix"} . "\n" if $d->{"address$suffix"};
1180 $raw .= "\tgateway " . $d->{"gateway$suffix"} . "\n" if $d->{"gateway$suffix"};
e143e9d8 1181
9b7b13a1
DM
1182 my $done = { type => 1, priority => 1, method => 1, active => 1, exists => 1,
1183 comments => 1, autostart => 1, options => 1,
48ab17b3
WB
1184 address => 1, netmask => 1, gateway => 1, broadcast => 1,
1185 method6 => 1, families => 1, options6 => 1,
d949babe 1186 address6 => 1, netmask6 => 1, gateway6 => 1, broadcast6 => 1, 'uplink-id' => 1 };
48ab17b3
WB
1187
1188 if (!$first_block) {
1189 # not printing out options
1190 } elsif ($d->{type} eq 'bridge') {
9b7b13a1 1191
fb3a6db1 1192 $d->{bridge_ports} =~ s/[;,\s]+/ /g;
e143e9d8 1193 my $ports = $d->{bridge_ports} || 'none';
1accc6da 1194 $raw .= "\tbridge-ports $ports\n";
9b7b13a1 1195 $done->{bridge_ports} = 1;
e143e9d8 1196
9b7b13a1 1197 my $v = defined($d->{bridge_stp}) ? $d->{bridge_stp} : 'off';
1accc6da 1198 $raw .= "\tbridge-stp $v\n";
9b7b13a1 1199 $done->{bridge_stp} = 1;
e143e9d8 1200
9b7b13a1 1201 $v = defined($d->{bridge_fd}) ? $d->{bridge_fd} : 0;
1accc6da 1202 $raw .= "\tbridge-fd $v\n";
9b7b13a1 1203 $done->{bridge_fd} = 1;
685a2528
AD
1204
1205 if( defined($d->{bridge_vlan_aware})) {
1accc6da 1206 $raw .= "\tbridge-vlan-aware yes\n";
95d0e633
AD
1207 $v = defined($d->{bridge_vids}) ? $d->{bridge_vids} : "2-4094";
1208 $raw .= "\tbridge-vids $v\n";
685a2528
AD
1209 }
1210 $done->{bridge_vlan_aware} = 1;
f6c4a563 1211 $done->{bridge_vids} = 1;
9bbc4e17 1212
2d1e9a02
AD
1213 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1214 $done->{mtu} = 1;
1215
9b7b13a1 1216 } elsif ($d->{type} eq 'bond') {
e143e9d8 1217
fb3a6db1 1218 $d->{slaves} =~ s/[;,\s]+/ /g;
e143e9d8 1219 my $slaves = $d->{slaves} || 'none';
1accc6da 1220 $raw .= "\tbond-slaves $slaves\n";
9b7b13a1 1221 $done->{slaves} = 1;
e143e9d8 1222
9b7b13a1 1223 my $v = defined ($d->{'bond_miimon'}) ? $d->{'bond_miimon'} : 100;
1accc6da 1224 $raw .= "\tbond-miimon $v\n";
9b7b13a1 1225 $done->{'bond_miimon'} = 1;
e143e9d8 1226
9b7b13a1 1227 $v = defined ($d->{'bond_mode'}) ? $d->{'bond_mode'} : 'balance-rr';
1accc6da 1228 $raw .= "\tbond-mode $v\n";
9b7b13a1
DM
1229 $done->{'bond_mode'} = 1;
1230
40fae2b3
DM
1231 if ($d->{'bond_mode'} && $d->{'bond_xmit_hash_policy'} &&
1232 ($d->{'bond_mode'} eq 'balance-xor' || $d->{'bond_mode'} eq '802.3ad')) {
1accc6da 1233 $raw .= "\tbond-xmit-hash-policy $d->{'bond_xmit_hash_policy'}\n";
40fae2b3
DM
1234 }
1235 $done->{'bond_xmit_hash_policy'} = 1;
b94d05ec
AD
1236
1237 if ($d->{'bond_mode'} && $d->{'bond_mode'} eq 'active-backup' && $d->{'bond-primary'}) {
1238 $raw .= "\tbond-primary $d->{'bond-primary'}\n";
1239 }
1240 $done->{'bond-primary'} = 1;
1241
2d1e9a02
AD
1242 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1243 $done->{mtu} = 1;
1244
8f5d56bf 1245 } elsif ($d->{type} eq 'vlan') {
9bbc4e17 1246 die "$iface: wrong vlan-protocol $d->{'vlan-protocol'}\n"
8f5d56bf 1247 if $d->{'vlan-protocol'} && $d->{'vlan-protocol'} ne '802.1ad' && $d->{'vlan-protocol'} ne '802.1q';
9bbc4e17 1248
95aa8788
AD
1249 } elsif ($d->{type} eq 'vxlan') {
1250
94d786b3
WB
1251 foreach my $k (qw(vxlan-id vxlan-svcnodeip vxlan-physdev vxlan-local-tunnelip)) {
1252 $raw .= "\t$k $d->{$k}\n" if defined $d->{$k};
95aa8788 1253 $done->{$k} = 1;
94d786b3 1254 }
95aa8788
AD
1255
1256 if ($d->{'vxlan-remoteip'}) {
1257 foreach my $remoteip (@{$d->{'vxlan-remoteip'}}) {
1258 $raw .= "\tvxlan-remoteip $remoteip\n";
1259 }
1260 $done->{'vxlan-remoteip'} = 1;
1261 }
2d1e9a02
AD
1262
1263 $raw .= "\tmtu $d->{mtu}\n" if $d->{mtu};
1264 $done->{mtu} = 1;
1265
9b7b13a1
DM
1266 } elsif ($d->{type} eq 'OVSBridge') {
1267
1268 $raw .= "\tovs_type $d->{type}\n";
1269 $done->{ovs_type} = 1;
1270
1271 $raw .= "\tovs_ports $d->{ovs_ports}\n" if $d->{ovs_ports};
1272 $done->{ovs_ports} = 1;
2d1e9a02
AD
1273
1274 $raw .= "\tovs_mtu $d->{mtu}\n" if $d->{mtu};
1275 $done->{mtu} = 1;
1276
9b7b13a1
DM
1277 } elsif ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' ||
1278 $d->{type} eq 'OVSBond') {
1279
1280 $d->{autostart} = 0; # started by the bridge
1281
2a751938
DM
1282 if (defined($d->{ovs_tag})) {
1283 &$set_ovs_option($d, tag => $d->{ovs_tag});
1284 }
1285 $done->{ovs_tag} = 1;
1286
9b7b13a1
DM
1287 if ($d->{type} eq 'OVSBond') {
1288
1289 $d->{bond_mode} = 'active-backup' if !$d->{bond_mode};
1290
1291 $ovs_bond_modes->{$d->{bond_mode}} ||
1292 die "OVS does not support bond mode '$d->{bond_mode}\n";
1293
a68760b6
DM
1294 if ($d->{bond_mode} eq 'lacp-balance-slb') {
1295 &$set_ovs_option($d, lacp => 'active');
1296 &$set_ovs_option($d, bond_mode => 'balance-slb');
1297 } elsif ($d->{bond_mode} eq 'lacp-balance-tcp') {
1298 &$set_ovs_option($d, lacp => 'active');
1299 &$set_ovs_option($d, bond_mode => 'balance-tcp');
1300 } else {
1301 &$set_ovs_option($d, lacp => undef);
1302 &$set_ovs_option($d, bond_mode => $d->{bond_mode});
1303 }
9b7b13a1
DM
1304 $done->{bond_mode} = 1;
1305
1306 $raw .= "\tovs_bonds $d->{ovs_bonds}\n" if $d->{ovs_bonds};
1307 $done->{ovs_bonds} = 1;
1308 }
1309
9b7b13a1
DM
1310 $raw .= "\tovs_type $d->{type}\n";
1311 $done->{ovs_type} = 1;
1312
bd9cc42d
TL
1313 if (my $bridge = $d->{ovs_bridge}) {
1314 $raw = "allow-$bridge $iface\n$raw";
1315 $raw .= "\tovs_bridge $bridge\n";
9b7b13a1
DM
1316 $done->{ovs_bridge} = 1;
1317 }
2d1e9a02
AD
1318
1319 $raw .= "\tovs_mtu $d->{mtu}\n" if $d->{mtu};
1320 $done->{mtu} = 1;
9b7b13a1
DM
1321 }
1322
48ab17b3
WB
1323 if ($first_block) {
1324 # print other settings
9a052564 1325 foreach my $k (sort keys %$d) {
48ab17b3
WB
1326 next if $done->{$k};
1327 next if !$d->{$k};
1328 $raw .= "\t$k $d->{$k}\n";
1329 }
e143e9d8
DM
1330 }
1331
48ab17b3 1332 foreach my $option (@{$d->{"options$suffix"}}) {
e143e9d8
DM
1333 $raw .= "\t$option\n";
1334 }
1335
ed4e6e0c 1336 # add comments
48ab17b3 1337 my $comments = $d->{"comments$suffix"} || '';
ed4e6e0c
DM
1338 foreach my $cl (split(/\n/, $comments)) {
1339 $raw .= "#$cl\n";
72ca6520
DM
1340 }
1341
e143e9d8
DM
1342 $raw .= "\n";
1343
1344 return $raw;
1345}
1346
78325766 1347
e143e9d8 1348sub write_etc_network_interfaces {
48ab17b3 1349 my ($filename, $fh, $config) = @_;
b7c4f378
AD
1350 my $ifupdown2 = -e '/usr/share/ifupdown2';
1351 my $raw = __write_etc_network_interfaces($config, $ifupdown2);
1b505ae2 1352 PVE::Tools::safe_print($filename, $fh, encode('UTF-8', $raw));
78325766
WB
1353}
1354sub __write_etc_network_interfaces {
b7c4f378 1355 my ($config, $ifupdown2) = @_;
48ab17b3
WB
1356
1357 my $ifaces = $config->{ifaces};
1358 my @options = @{$config->{options}};
e143e9d8 1359
9b7b13a1
DM
1360 my $used_ports = {};
1361
1362 foreach my $iface (keys %$ifaces) {
1363 my $d = $ifaces->{$iface};
1364
2896245e
DC
1365 delete $d->{cidr};
1366 delete $d->{cidr6};
1367
9b7b13a1
DM
1368 my $ports = '';
1369 foreach my $k (qw(bridge_ports ovs_ports slaves ovs_bonds)) {
1370 $ports .= " $d->{$k}" if $d->{$k};
1371 }
1372
1373 foreach my $p (PVE::Tools::split_list($ports)) {
1374 die "port '$p' is already used on interface '$used_ports->{$p}'\n"
1375 if $used_ports->{$p} && $used_ports->{$p} ne $iface;
1376 $used_ports->{$p} = $iface;
1377 }
1378 }
1379
1380 # delete unused OVS ports
1381 foreach my $iface (keys %$ifaces) {
1382 my $d = $ifaces->{$iface};
94d786b3 1383 if ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' ||
9b7b13a1
DM
1384 $d->{type} eq 'OVSBond') {
1385 my $brname = $used_ports->{$iface};
94d786b3 1386 if (!$brname || !$ifaces->{$brname}) {
3dabe28a 1387 if ($iface =~ /^$PVE::Network::PHYSICAL_NIC_RE/) {
516a50a4
WB
1388 $ifaces->{$iface} = { type => 'eth',
1389 exists => 1,
1390 method => 'manual',
1391 families => ['inet'] };
1392 } else {
1393 delete $ifaces->{$iface};
1394 }
9b7b13a1
DM
1395 next;
1396 }
1397 my $bd = $ifaces->{$brname};
1398 if ($bd->{type} ne 'OVSBridge') {
1399 delete $ifaces->{$iface};
1400 next;
1401 }
1402 }
1403 }
1404
1405 # create OVS bridge ports
1406 foreach my $iface (keys %$ifaces) {
1407 my $d = $ifaces->{$iface};
1408 if ($d->{type} eq 'OVSBridge' && $d->{ovs_ports}) {
1409 foreach my $p (split (/\s+/, $d->{ovs_ports})) {
1410 my $n = $ifaces->{$p};
1411 die "OVS bridge '$iface' - unable to find port '$p'\n"
1412 if !$n;
21d32c95 1413 $n->{autostart} = 0;
9b7b13a1
DM
1414 if ($n->{type} eq 'eth') {
1415 $n->{type} = 'OVSPort';
94d786b3 1416 $n->{ovs_bridge} = $iface;
9b7b13a1
DM
1417 } elsif ($n->{type} eq 'OVSBond' || $n->{type} eq 'OVSPort' ||
1418 $n->{type} eq 'OVSIntPort') {
1419 $n->{ovs_bridge} = $iface;
1420 } else {
1421 die "interface '$p' is not defined as OVS port/bond\n";
1422 }
9b053d70
AD
1423
1424 &$check_mtu($ifaces, $iface, $p);
9b7b13a1
DM
1425 }
1426 }
1427 }
1428
1429 # check OVS bond ports
1430 foreach my $iface (keys %$ifaces) {
1431 my $d = $ifaces->{$iface};
1432 if ($d->{type} eq 'OVSBond' && $d->{ovs_bonds}) {
1433 foreach my $p (split (/\s+/, $d->{ovs_bonds})) {
1434 my $n = $ifaces->{$p};
1435 die "OVS bond '$iface' - unable to find slave '$p'\n"
1436 if !$n;
1437 die "OVS bond '$iface' - wrong interface type on slave '$p' " .
1438 "('$n->{type}' != 'eth')\n" if $n->{type} ne 'eth';
9b053d70 1439 &$check_mtu($ifaces, $iface, $p);
9b7b13a1
DM
1440 }
1441 }
1442 }
1443
0115696f
AD
1444 # check bond
1445 foreach my $iface (keys %$ifaces) {
1446 my $d = $ifaces->{$iface};
1447 if ($d->{type} eq 'bond' && $d->{slaves}) {
b94d05ec 1448 my $bond_primary_is_slave = undef;
0115696f
AD
1449 foreach my $p (split (/\s+/, $d->{slaves})) {
1450 my $n = $ifaces->{$p};
6f830d1d 1451
0115696f
AD
1452 die "bond '$iface' - unable to find slave '$p'\n"
1453 if !$n;
1454 die "bond '$iface' - wrong interface type on slave '$p' " .
1455 "('$n->{type}' != 'eth')\n" if $n->{type} ne 'eth';
9b053d70 1456 &$check_mtu($ifaces, $iface, $p);
b94d05ec 1457 $bond_primary_is_slave = 1 if $d->{'bond-primary'} && $d->{'bond-primary'} eq $p;
0115696f 1458 }
b94d05ec 1459 die "bond '$iface' - bond-primary interface is not a slave" if $d->{'bond-primary'} && !$bond_primary_is_slave;
0115696f
AD
1460 }
1461 }
1462
95aa8788
AD
1463 # check vxlan
1464 my $vxlans = {};
1465 foreach my $iface (keys %$ifaces) {
1466 my $d = $ifaces->{$iface};
1467
1468 if ($d->{type} eq 'vxlan' && $d->{'vxlan-id'}) {
1469 my $vxlanid = $d->{'vxlan-id'};
94d786b3 1470 die "iface $iface - duplicate vxlan-id $vxlanid already used in $vxlans->{$vxlanid}\n" if $vxlans->{$vxlanid};
95aa8788
AD
1471 $vxlans->{$vxlanid} = $iface;
1472 }
1473
1474 my $ips = 0;
1475 ++$ips if defined $d->{'vxlan-svcnodeip'};
1476 ++$ips if defined $d->{'vxlan-remoteip'};
1477 ++$ips if defined $d->{'vxlan-local-tunnelip'};
1478 if ($ips > 1) {
94d786b3 1479 die "iface $iface - vxlan-svcnodeip, vxlan-remoteip and vxlan-localtunnelip are mutually exclusive\n";
95aa8788
AD
1480 }
1481
1482 if (defined($d->{'vxlan-svcnodeip'}) != defined($d->{'vxlan-physdev'})) {
94d786b3 1483 die "iface $iface - vxlan-svcnodeip and vxlan-physdev must be define together\n";
95aa8788 1484 }
9b053d70 1485 #fixme : check if vxlan mtu is lower than 50bytes than physical interface where tunnel is going out
95aa8788
AD
1486 }
1487
c4e56470
AD
1488 # check vlan
1489 foreach my $iface (keys %$ifaces) {
1490 my $d = $ifaces->{$iface};
bbe7d3ed
AD
1491 if ($d->{type} eq 'vlan') {
1492
1493 my $p = undef;
1494 my $vlanid = undef;
1495
1496 if ($iface =~ m/^(\S+)\.(\d+)$/) {
1497 $p = $1;
1498 $vlanid = $2;
1499 delete $d->{'vlan-raw-device'} if $d->{'vlan-raw-device'};
1500 } else {
1501 die "missing vlan-raw-device option" if !$d->{'vlan-raw-device'};
1502 $p = $d->{'vlan-raw-device'};
1503
1504 if ($iface =~ m/^vlan(\d+)$/) {
1505 $vlanid = $1;
1506 delete $d->{'vlan-id'} if $d->{'vlan-id'};
1507 } else {
1508 die "custom vlan interface name need ifupdown2" if !$ifupdown2;
1509 die "missing vlan-id option" if !$d->{'vlan-id'};
1510 $vlanid = $d->{'vlan-id'};
1511 }
1512 }
c4e56470
AD
1513 my $n = $ifaces->{$p};
1514
bbe7d3ed 1515 die "vlan '$iface' - vlan-id $vlanid should be <= 4094\n" if $vlanid > 4094;
c4e56470 1516 die "vlan '$iface' - unable to find parent '$p'\n"
fc158d0d 1517 if !$n;
c4e56470 1518
c8ff0bdf 1519 if ($n->{type} ne 'eth' && $n->{type} ne 'bridge' && $n->{type} ne 'bond' && $n->{type} ne 'vlan') {
c4e56470 1520 die "vlan '$iface' - wrong interface type on parent '$p' " .
8f5d56bf 1521 "('$n->{type}' != 'eth|bond|bridge|vlan' )\n";
c4e56470 1522 }
8f5d56bf 1523
000e32bc 1524 &$check_mtu($ifaces, $p, $iface);
8f5d56bf 1525
c4e56470
AD
1526 }
1527 }
1528
d949babe
AD
1529 # check uplink
1530 my $uplinks = {};
1531 foreach my $iface (keys %$ifaces) {
1532 my $d = $ifaces->{$iface};
1533 if (my $uplinkid = $d->{'uplink-id'}) {
1534 die "iface '$iface' - uplink-id $uplinkid is only allowed on physical and linux bond interfaces\n"
9bbc4e17 1535 if $d->{type} ne 'eth' && $d->{type} ne 'bond';
d949babe
AD
1536
1537 die "iface '$iface' - uplink-id $uplinkid is already assigned on '$uplinks->{$uplinkid}'\n"
1538 if $uplinks->{$uplinkid};
1539
1540 $uplinks->{$uplinkid} = $iface;
1541 }
1542 }
1543
9a052564
AD
1544 # check bridgeport option
1545 my $bridgeports = {};
1546 my $bridges = {};
a70e9925
AD
1547 my $ifaces_copy = { %$ifaces };
1548 foreach my $iface (keys %$ifaces_copy) {
1549 my $d = $ifaces_copy->{$iface};
9a052564
AD
1550 if ($d->{type} eq 'bridge') {
1551 foreach my $p (split (/\s+/, $d->{bridge_ports})) {
a70e9925
AD
1552 if($p =~ m/(\S+)\.(\d+)$/) {
1553 my $vlanparent = $1;
1554 if (!defined($ifaces_copy->{$p})) {
1555 $ifaces_copy->{$p}->{type} = 'vlan';
1556 $ifaces_copy->{$p}->{method} = 'manual';
1557 $ifaces_copy->{$p}->{method6} = 'manual';
1558 $ifaces_copy->{$p}->{mtu} = $ifaces_copy->{$vlanparent}->{mtu} if defined($ifaces_copy->{$1}->{mtu});
1559 }
1560 }
1561 my $n = $ifaces_copy->{$p};
055f076b 1562 die "bridge '$iface' - unable to find bridge port '$p'\n" if !$n;
6f830d1d 1563 die "iface $p - ip address can't be set on interface if bridged in $iface\n"
dd3004e2
AD
1564 if ($n->{method} && $n->{method} eq 'static' && $n->{address} ne '0.0.0.0') ||
1565 ($n->{method6} && $n->{method6} eq 'static' && $n->{address} ne '::');
a70e9925 1566 &$check_mtu($ifaces_copy, $p, $iface);
9a052564
AD
1567 $bridgeports->{$p} = $iface;
1568 }
1569 $bridges->{$iface} = $d;
1570 }
1571 }
1572
1573 foreach my $iface (keys %$ifaces) {
1574 my $d = $ifaces->{$iface};
1575
1576 foreach my $k (qw(bridge-learning bridge-arp-nd-suppress bridge-unicast-flood bridge-multicast-flood bridge-access)) {
94d786b3 1577 die "iface $iface - $k: bridge port specific options can be used only on interfaces attached to a bridge\n"
9a052564
AD
1578 if $d->{$k} && !$bridgeports->{$iface};
1579 }
1580
1581 if ($d->{'bridge-access'} && !$bridges->{$bridgeports->{$iface}}->{bridge_vlan_aware}) {
94d786b3 1582 die "iface $iface - bridge-access option can be only used if interface is in a vlan aware bridge\n";
9a052564
AD
1583 }
1584 }
1585
9d27ef41
WB
1586 my $raw = <<'NETWORKDOC';
1587# network interface settings; autogenerated
1588# Please do NOT modify this file directly, unless you know what
1589# you're doing.
1590#
b3e3b51b 1591# If you want to manage parts of the network configuration manually,
9d27ef41
WB
1592# please utilize the 'source' or 'source-directory' directives to do
1593# so.
b3e3b51b 1594# PVE will preserve these directives, but will NOT read its network
9d27ef41
WB
1595# configuration from sourced files, so do not attempt to move any of
1596# the PVE managed interfaces into external files!
1597
1598NETWORKDOC
e143e9d8
DM
1599
1600 my $printed = {};
1601
ed4e6e0c 1602 my $if_type_hash = {
562fad0b
WB
1603 loopback => 100000,
1604 eth => 200000,
51eec390
AD
1605 OVSPort => 200000,
1606 OVSIntPort => 200000,
562fad0b
WB
1607 bond => 300000,
1608 bridge => 400000,
51eec390 1609 OVSBridge => 400000,
bbe7d3ed 1610 vlan => 500000,
95aa8788 1611 vxlan => 500000,
9b7b13a1 1612 };
ed4e6e0c
DM
1613
1614 my $lookup_type_prio = sub {
51eec390 1615 my ($iface, $ifaces) = @_;
ed4e6e0c 1616
0c0bcf7c
WB
1617 my ($rootiface, @rest) = split(/[.:]/, $iface);
1618 my $childlevel = scalar(@rest);
1619 my $n = $ifaces->{$rootiface};
ed4e6e0c 1620
0c0bcf7c 1621 my $pri = $if_type_hash->{$n->{type}} + $childlevel
51eec390
AD
1622 if $n->{type} && $n->{type} ne 'unknown';
1623
7a822100 1624 return $pri;
ed4e6e0c
DM
1625 };
1626
c9dc8645
DM
1627 foreach my $iface (sort {
1628 my $ref1 = $ifaces->{$a};
1629 my $ref2 = $ifaces->{$b};
51eec390
AD
1630 my $tp1 = &$lookup_type_prio($a, $ifaces);
1631 my $tp2 = &$lookup_type_prio($b, $ifaces);
e143e9d8 1632
7a822100
WB
1633 # Only recognized types are in relation to each other. If one type
1634 # is unknown then only consider the interfaces' priority attributes.
1635 $tp1 = $tp2 = 0 if !defined($tp1) || !defined($tp2);
1636
1637 my $p1 = $tp1 + ($ref1->{priority} // 50000);
1638 my $p2 = $tp2 + ($ref2->{priority} // 50000);
ed4e6e0c
DM
1639
1640 return $p1 <=> $p2 if $p1 != $p2;
c9dc8645
DM
1641
1642 return $a cmp $b;
11e7facb 1643 } keys %$ifaces) {
c9dc8645 1644 next if $printed->{$iface};
11e7facb 1645 my $d = $ifaces->{$iface};
562fad0b
WB
1646 my $pri = $d->{priority} // 0;
1647 if (@options && $options[0]->[0] < $pri) {
48ab17b3
WB
1648 do {
1649 $raw .= (shift @options)->[1] . "\n";
562fad0b 1650 } while (@options && $options[0]->[0] < $pri);
48ab17b3
WB
1651 $raw .= "\n";
1652 }
1653
c9dc8645 1654 $printed->{$iface} = 1;
f48815f8
AD
1655 if ($d->{autostart}) {
1656 if ($d->{type} eq 'OVSBridge') {
1657 # cannot use 'auto' for OVS, would add race with systemd ifup@.service
1658 $raw .= "allow-ovs $iface\n";
1659 } else {
1660 $raw .= "auto $iface\n";
1661 }
4ac94c72
AD
1662 }
1663
48ab17b3 1664 my $i = 0; # some options should be printed only once
b7c4f378 1665 $raw .= __interface_to_string($iface, $d, $_, !$i++, $ifupdown2) foreach @{$d->{families}};
e143e9d8 1666 }
48ab17b3
WB
1667
1668 $raw .= $_->[1] . "\n" foreach @options;
78325766 1669 return $raw;
e143e9d8
DM
1670}
1671
1672register_file('interfaces', "/etc/network/interfaces",
1673 \&read_etc_network_interfaces,
1674 \&write_etc_network_interfaces);
1675
ddd3d224
DM
1676
1677sub read_iscsi_initiatorname {
1678 my ($filename, $fd) = @_;
1679
1680 while (defined(my $line = <$fd>)) {
1681 if ($line =~ m/^InitiatorName=(\S+)$/) {
1682 return $1;
1683 }
1684 }
1685
1686 return 'undefined';
1687}
1688
9bbc4e17 1689register_file('initiatorname', "/etc/iscsi/initiatorname.iscsi",
ddd3d224
DM
1690 \&read_iscsi_initiatorname);
1691
6c3aef09
DM
1692sub read_apt_auth {
1693 my ($filename, $fd) = @_;
1694
1695 local $/;
1696
b8e02bc2 1697 my $raw = defined($fd) ? <$fd> : '';
6c3aef09
DM
1698
1699 $raw =~ s/^\s+//;
1700
9bbc4e17 1701
6c3aef09
DM
1702 my @tokens = split(/\s+/, $raw);
1703
1704 my $data = {};
1705
1706 my $machine;
1707 while (defined(my $tok = shift @tokens)) {
1708
1709 $machine = shift @tokens if $tok eq 'machine';
1710 next if !$machine;
1711 $data->{$machine} = {} if !$data->{$machine};
1712
1713 $data->{$machine}->{login} = shift @tokens if $tok eq 'login';
1714 $data->{$machine}->{password} = shift @tokens if $tok eq 'password';
1715 };
1716
1717 return $data;
1718}
1719
1720my $format_apt_auth_data = sub {
1721 my $data = shift;
1722
1723 my $raw = '';
1724
1725 foreach my $machine (sort keys %$data) {
1726 my $d = $data->{$machine};
1727 $raw .= "machine $machine\n";
1728 $raw .= " login $d->{login}\n" if $d->{login};
1729 $raw .= " password $d->{password}\n" if $d->{password};
1730 $raw .= "\n";
1731 }
1732
1733 return $raw;
1734};
1735
1736sub write_apt_auth {
1737 my ($filename, $fh, $data) = @_;
1738
1739 my $raw = &$format_apt_auth_data($data);
1740
1741 die "write failed: $!" unless print $fh "$raw\n";
9bbc4e17 1742
6c3aef09
DM
1743 return $data;
1744}
1745
1746sub update_apt_auth {
1747 my ($filename, $fh, $data) = @_;
1748
1749 my $orig = read_apt_auth($filename, $fh);
1750
1751 foreach my $machine (keys %$data) {
1752 $orig->{$machine} = $data->{$machine};
1753 }
1754
1755 return &$format_apt_auth_data($orig);
1756}
1757
9bbc4e17 1758register_file('apt-auth', "/etc/apt/auth.conf",
6c3aef09 1759 \&read_apt_auth, \&write_apt_auth,
b7aae8e5 1760 \&update_apt_auth, perm => 0640);
6c3aef09 1761
e143e9d8 17621;