3 # todo: maybe we do not need update_file() ?
13 use Fcntl
qw(:DEFAULT :flock);
15 use PVE
::Exception
qw(raise_param_exc);
25 use Encode
qw(encode decode);
27 our @EXPORT_OK = qw(read_file write_file register_file);
36 '/etc/network/interfaces' => '/etc/network/interfaces.new',
39 # to enable cached operation, you need to call 'inotify_init'
40 # inotify handles are a limited resource, so use with care (only
41 # enable the cache if you really need it)
43 # Note: please close the inotify handle after you fork
45 sub ccache_default_writer
{
46 my ($filename, $data) = @_;
48 die "undefined config writer for '$filename' :ERROR";
51 sub ccache_default_parser
{
52 my ($filename, $srcfd) = @_;
54 die "undefined config reader for '$filename' :ERROR";
57 sub ccache_compute_diff
{
58 my ($filename, $shadow) = @_;
62 my $cmd = ['/usr/bin/diff', '-b', '-N', '-u', $filename, $shadow];
63 PVE
::Tools
::run_command
($cmd, noerr
=> 1, outfunc
=> sub {
65 $diff .= decode
('UTF-8', $line) . "\n";
68 $diff = undef if !$diff;
76 foreach my $uid (keys %$ccacheregex) {
77 my $ccinfo = $ccacheregex->{$uid};
78 my $dir = $ccinfo->{dir
};
79 my $regex = $ccinfo->{regex
};
80 if ($filename =~ m
|^$dir/+$regex$|) {
81 if (!$ccache->{$filename}) {
83 while (my ($k, $v) = each %$ccinfo) {
86 $ccache->{$filename} = $cp;
88 return ($ccache->{$filename}, $filename);
92 $filename = $ccachemap->{$filename} if defined ($ccachemap->{$filename});
94 die "file '$filename' not added :ERROR" if !defined ($ccache->{$filename});
96 return ($ccache->{$filename}, $filename);
100 my ($fileid, $data, $full) = @_;
102 my ($ccinfo, $filename) = ccache_info
($fileid);
104 my $writer = $ccinfo->{writer
};
106 my $realname = $filename;
109 if ($shadow = $shadowfiles->{$filename}) {
113 my $perm = $ccinfo->{perm
} || 0644;
115 my $tmpname = "$realname.tmp.$$";
119 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
120 die "unable to open file '$tmpname' - $!\n" if !$fh;
122 $res = &$writer($filename, $fh, $data);
124 die "closing file '$tmpname' failed - $!\n" unless close $fh;
128 $ccinfo->{version
} = undef;
135 if (!rename($tmpname, $realname)) {
136 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
142 if ($shadow && $full) {
143 $diff = ccache_compute_diff
($filename, $shadow);
147 return { data
=> $res, changes
=> $diff };
154 my ($fileid, $data, @args) = @_;
156 my ($ccinfo, $filename) = ccache_info
($fileid);
158 my $update = $ccinfo->{update
};
160 die "unable to update/merge data" if !$update;
162 my $lkfn = "$filename.lock";
170 $fd = IO
::File-
>new ($filename, "r");
172 my $new = &$update($filename, $fd, $data, @args);
175 PVE
::Tools
::file_set_contents
($filename, $new, $ccinfo->{perm
});
181 PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
184 close($fd) if defined($fd);
191 sub discard_changes
{
192 my ($fileid, $full) = @_;
194 my ($ccinfo, $filename) = ccache_info
($fileid);
196 if (my $copy = $shadowfiles->{$filename}) {
200 return read_file
($filename, $full);
206 poll
() if $inotify; # read new inotify events
208 $versions->{$filename} = 0 if !defined ($versions->{$filename});
210 return $versions->{$filename};
214 my ($fileid, $full) = @_;
218 my ($ccinfo, $filename) = ccache_info
($fileid);
220 $parser = $ccinfo->{parser
};
225 my $cver = poll_changes
($filename);
227 if (my $copy = $shadowfiles->{$filename}) {
228 if ($fd = IO
::File-
>new ($copy, "r")) {
231 $fd = IO
::File-
>new ($filename, "r");
234 $fd = IO
::File-
>new ($filename, "r");
237 my $acp = $ccinfo->{always_call_parser
};
240 $ccinfo->{version
} = undef;
241 $ccinfo->{data
} = undef;
242 $ccinfo->{diff
} = undef;
243 return undef if !$acp;
246 my $noclone = $ccinfo->{noclone
};
249 if (!$ccinfo->{nocache
} &&
251 defined ($ccinfo->{data
}) &&
252 defined ($ccinfo->{version
}) &&
253 ($ccinfo->{readonce
} ||
254 ($ccinfo->{version
} == $cver))) {
257 if (!$noclone && ref ($ccinfo->{data
})) {
258 $ret->{data
} = clone
($ccinfo->{data
});
260 $ret->{data
} = $ccinfo->{data
};
262 $ret->{changes
} = $ccinfo->{diff
};
264 return $full ?
$ret : $ret->{data
};
270 $diff = ccache_compute_diff
($filename, $shadow);
273 my $res = &$parser($filename, $fd);
275 if (!$ccinfo->{nocache
}) {
276 $ccinfo->{version
} = $cver;
279 # we cache data with references, so we always need to
280 # clone this data. Else the original data may get
282 $ccinfo->{data
} = $res;
285 $ccinfo->{diff
} = $diff;
288 if (!$noclone && ref ($ccinfo->{data
})) {
289 $ret->{data
} = clone
($ccinfo->{data
});
291 $ret->{data
} = $ccinfo->{data
};
293 $ret->{changes
} = $ccinfo->{diff
};
295 return $full ?
$ret : $ret->{data
};
298 sub parse_ccache_options
{
299 my ($ccinfo, %options) = @_;
301 foreach my $opt (keys %options) {
302 my $v = $options{$opt};
303 if ($opt eq 'readonce') {
304 $ccinfo->{$opt} = $v;
305 } elsif ($opt eq 'nocache') {
306 $ccinfo->{$opt} = $v;
307 } elsif ($opt eq 'shadow') {
308 $ccinfo->{$opt} = $v;
309 } elsif ($opt eq 'perm') {
310 $ccinfo->{$opt} = $v;
311 } elsif ($opt eq 'noclone') {
312 # noclone flag for large read-only data chunks like aplinfo
313 $ccinfo->{$opt} = $v;
314 } elsif ($opt eq 'always_call_parser') {
315 # when set, we call parser even when the file does not exist.
316 # this allows the parser to return some default
317 $ccinfo->{$opt} = $v;
319 die "internal error - unsupported option '$opt'";
325 my ($id, $filename, $parser, $writer, $update, %options) = @_;
327 die "can't register file '$filename' after inotify_init" if $inotify;
329 die "file '$filename' already added :ERROR" if defined ($ccache->{$filename});
330 die "ID '$id' already used :ERROR" if defined ($ccachemap->{$id});
335 $ccinfo->{parser
} = $parser || \
&ccache_default_parser
;
336 $ccinfo->{writer
} = $writer || \
&ccache_default_writer
;
337 $ccinfo->{update
} = $update;
339 parse_ccache_options
($ccinfo, %options);
341 if ($options{shadow
}) {
342 $shadowfiles->{$filename} = $options{shadow
};
345 $ccachemap->{$id} = $filename;
346 $ccache->{$filename} = $ccinfo;
350 my ($dir, $regex, $parser, $writer, $update, %options) = @_;
352 die "can't register regex after inotify_init" if $inotify;
354 my $uid = "$dir/$regex";
355 die "regular expression '$uid' already added :ERROR" if defined ($ccacheregex->{$uid});
359 $ccinfo->{dir
} = $dir;
360 $ccinfo->{regex
} = $regex;
361 $ccinfo->{parser
} = $parser || \
&ccache_default_parser
;
362 $ccinfo->{writer
} = $writer || \
&ccache_default_writer
;
363 $ccinfo->{update
} = $update;
365 parse_ccache_options
($ccinfo, %options);
367 $ccacheregex->{$uid} = $ccinfo;
373 if ($inotify_pid != $$) {
374 syslog
('err', "got inotify poll request in wrong process - disabling inotify");
377 1 while $inotify && $inotify->poll;
382 foreach my $filename (keys %$ccache) {
383 $ccache->{$filename}->{version
} = undef;
384 $ccache->{$filename}->{data
} = undef;
385 $ccache->{$filename}->{diff
} = undef;
395 die "only one inotify instance allowed" if $inotify;
397 $inotify = Linux
::Inotify2-
>new()
398 || die "Unable to create new inotify object: $!";
400 $inotify->blocking (0);
405 foreach my $fn (keys %$ccache) {
406 my $dir = dirname
($fn);
407 my $base = basename
($fn);
409 $dirhash->{$dir}->{$base} = $fn;
411 if (my $sf = $shadowfiles->{$fn}) {
412 $base = basename
($sf);
413 $dir = dirname
($sf);
414 $dirhash->{$dir}->{$base} = $fn; # change version of original file!
418 foreach my $uid (keys %$ccacheregex) {
419 my $ccinfo = $ccacheregex->{$uid};
420 $dirhash->{$ccinfo->{dir
}}->{_regex
} = 1;
425 foreach my $dir (keys %$dirhash) {
427 my $evlist = IN_MODIFY
|IN_ATTRIB
|IN_MOVED_FROM
|IN_MOVED_TO
|IN_DELETE
|IN_CREATE
;
428 $inotify->watch ($dir, $evlist, sub {
432 if ($inotify_pid != $$) {
433 syslog
('err', "got inotify event in wrong process");
436 if ($e->IN_ISDIR || !$name) {
440 if ($e->IN_Q_OVERFLOW) {
441 syslog
('info', "got inotify overflow - flushing cache");
446 if ($e->IN_UNMOUNT) {
447 syslog
('err', "got 'unmount' event on '$name' - disabling inotify");
450 if ($e->IN_IGNORED) {
451 syslog
('err', "got 'ignored' event on '$name' - disabling inotify");
455 if ($dirhash->{$dir}->{_regex
}) {
456 foreach my $uid (keys %$ccacheregex) {
457 my $ccinfo = $ccacheregex->{$uid};
458 next if $dir ne $ccinfo->{dir
};
459 my $regex = $ccinfo->{regex
};
460 if ($regex && ($name =~ m
|^$regex$|)) {
462 my $fn = "$dir/$name";
464 #print "VERSION:$fn:$versions->{$fn}\n";
467 } elsif (my $fn = $dirhash->{$dir}->{$name}) {
470 #print "VERSION:$fn:$versions->{$fn}\n";
475 foreach my $dir (keys %$dirhash) {
476 foreach my $name (keys %{$dirhash->{$dir}}) {
477 if ($name eq '_regex') {
478 foreach my $uid (keys %$ccacheregex) {
479 my $ccinfo = $ccacheregex->{$uid};
480 next if $dir ne $ccinfo->{dir
};
481 my $re = $ccinfo->{regex
};
482 if (my $fd = IO
::Dir-
>new ($dir)) {
483 while (defined(my $de = $fd->read)) {
484 if ($de =~ m/^$re$/) {
486 $versions->{$fn}++; # init with version
487 #print "init:$fn:$versions->{$fn}\n";
493 my $fn = $dirhash->{$dir}->{$name};
494 $versions->{$fn}++; # init with version
495 #print "init:$fn:$versions->{$fn}\n";
505 return $cached_nodename if $cached_nodename;
507 my ($sysname, $nodename) = POSIX
::uname
();
509 $nodename =~ s/\..*$//; # strip domain part, if any
511 die "unable to read node name\n" if !$nodename;
513 $cached_nodename = $nodename;
515 return $cached_nodename;
518 sub read_etc_hostname
{
519 my ($filename, $fd) = @_;
521 my $hostname = <$fd>;
525 $hostname =~ s/\..*$//; # strip domain part, if any
530 sub write_etc_hostname
{
531 my ($filename, $fh, $hostname) = @_;
533 die "write failed: $!" unless print $fh "$hostname\n";
538 register_file
('hostname', "/etc/hostname",
540 \
&write_etc_hostname
);
543 my ($filename, $fh) = @_;
548 while (my $line = <$fh>) {
550 if ($line =~ m/^\s*#/) {
551 $line = decode
('UTF-8', $line);
557 digest
=> Digest
::SHA
::sha1_hex
($raw),
562 sub write_etc_hosts
{
563 my ($filename, $fh, $hosts, @args) = @_;
565 # check validity of ips/names
566 for my $line (split("\n", $hosts)) {
567 next if $line =~ m/^\s*#/; # comments
568 next if $line =~ m/^\s*$/; # whitespace/empty lines
570 my ($ip, @names) = split(/\s+/, $line);
572 raise_param_exc
({ 'data' => "Invalid IP '$ip'" })
573 if $ip !~ m/^$PVE::Tools::IPRE$/;
575 for my $name (@names) {
576 raise_param_exc
({ 'data' => "Invalid Hostname '$name'" })
577 if $name !~ m/^[.\-a-zA-Z0-9]+$/;
581 die "write failed: $!" if !print $fh encode
('UTF-8', $hosts);
586 register_file
('etchosts', "/etc/hosts",
590 sub read_etc_resolv_conf
{
591 my ($filename, $fh) = @_;
596 while (my $line = <$fh>) {
598 if ($line =~ m/^(search|domain)\s+(\S+)\s*/) {
600 } elsif ($line =~ m/^\s*nameserver\s+($PVE::Tools::IPRE)\s*/) {
603 $res->{"dns$nscount"} = $1;
611 sub update_etc_resolv_conf
{
612 my ($filename, $fh, $resolv, @args) = @_;
616 $data = "search $resolv->{search}\n"
617 if $resolv->{search
};
620 foreach my $k ("dns1", "dns2", "dns3") {
621 my $ns = $resolv->{$k};
622 if ($ns && $ns ne '0.0.0.0' && !$written->{$ns}) {
624 $data .= "nameserver $ns\n";
628 while (my $line = <$fh>) {
629 next if $line =~ m/^(search|domain|nameserver)\s+/;
636 register_file
('resolvconf', "/etc/resolv.conf",
637 \
&read_etc_resolv_conf
, undef,
638 \
&update_etc_resolv_conf
);
640 sub read_etc_timezone
{
641 my ($filename, $fd) = @_;
643 my $timezone = <$fd>;
650 sub write_etc_timezone
{
651 my ($filename, $fh, $timezone) = @_;
653 my $tzinfo = "/usr/share/zoneinfo/$timezone";
655 raise_param_exc
({ 'timezone' => "No such timezone" })
658 ($timezone) = $timezone =~ m/^(.*)$/; # untaint
660 print $fh "$timezone\n";
662 unlink ("/etc/localtime");
663 symlink ("/usr/share/zoneinfo/$timezone", "/etc/localtime");
667 register_file
('timezone', "/etc/timezone",
669 \
&write_etc_timezone
);
671 sub read_active_workers
{
672 my ($filename, $fh) = @_;
677 while (defined (my $line = <$fh>)) {
678 if ($line =~ m/^(\S+)\s(0|1)(\s([0-9A-Za-z]{8})(\s(\s*\S.*))?)?$/) {
683 if ((my $task = PVE
::Tools
::upid_decode
($upid, 1))) {
684 $task->{upid
} = $upid;
685 $task->{saved
} = $saved;
686 $task->{endtime
} = hex($endtime) if $endtime;
687 $task->{status
} = $status if $status;
691 warn "unable to parse line: $line";
699 sub write_active_workers
{
700 my ($filename, $fh, $tasklist) = @_;
703 foreach my $task (@$tasklist) {
704 my $upid = $task->{upid
};
705 my $saved = $task->{saved
} ?
1 : 0;
706 if ($task->{endtime
}) {
707 if ($task->{status
}) {
708 $raw .= sprintf("%s %s %08X %s\n", $upid, $saved, $task->{endtime
}, $task->{status
});
710 $raw .= sprintf("%s %s %08X\n", $upid, $saved, $task->{endtime
});
713 $raw .= "$upid $saved\n";
717 PVE
::Tools
::safe_print
($filename, $fh, $raw) if $raw;
720 register_file
('active', "/var/log/pve/tasks/active",
721 \
&read_active_workers
,
722 \
&write_active_workers
);
725 our $bond_modes = { 'balance-rr' => 0,
726 'active-backup' => 1,
734 my $ovs_bond_modes = {
735 'active-backup' => 1,
737 'lacp-balance-slb' => 1,
738 'lacp-balance-tcp' => 1,
741 #sub get_bond_modes {
742 # return $bond_modes;
745 my $parse_ovs_option = sub {
749 foreach my $kv (split (/\s+/, $data || '')) {
750 my ($k, $v) = split('=', $kv, 2);
751 $opts->{$k} = $v if $k && $v;
756 my $set_ovs_option = sub {
757 my ($d, %params) = @_;
759 my $opts = &$parse_ovs_option($d->{ovs_options
});
761 foreach my $k (keys %params) {
771 foreach my $k (keys %$opts) {
772 push @$res, "$k=$opts->{$k}";
775 if (my $new = join(' ', @$res)) {
776 $d->{ovs_options
} = $new;
777 return $d->{ovs_options
};
779 delete $d->{ovs_options
};
784 my $extract_ovs_option = sub {
787 my $opts = &$parse_ovs_option($d->{ovs_options
});
789 my $v = delete $opts->{$name};
792 foreach my $k (keys %$opts) {
793 push @$res, "$k=$opts->{$k}";
796 if (my $new = join(' ', @$res)) {
797 $d->{ovs_options
} = $new;
799 delete $d->{ovs_options
};
805 my $check_mtu = sub {
806 my ($ifaces, $parent, $child) = @_;
808 die "check mtu - missing parent interface\n" if !$parent;
809 die "check mtu - missing child interface\n" if !$child;
811 my $cmtu = $ifaces->{$child}->{mtu
};
814 my $parentdata = $ifaces->{$parent};
815 my $pmtu = $parentdata->{mtu
};
816 $pmtu = $cmtu if $parentdata->{type
} eq 'bond' && !$pmtu;
817 $pmtu = 1500 if !$pmtu;
819 die "interface '$parent' - mtu $pmtu is lower than '$child' - mtu $cmtu\n"
826 # <optional> exists => BOOL,
827 # <optional> active => BOOL,
828 # <optional> autostart => BOOL,
829 # <auto> priority => INT,
831 # type => "eth" | "bridge" | "bond" | "loopback" | "OVS*" | ... ,
833 # families => ["inet", "inet6", ...],
835 # method => "manual" | "static" | "dhcp" | ... ,
840 # comments => [ "..." ],
842 # method6 => "manual" | "static" | "dhcp" | ... ,
844 # netmask6 => SUBNET,
846 # comments6 => [ "..." ],
848 # <known options>, # like bridge_ports, ovs_*
850 # # extra/unknown options stored by-family:
851 # options => { <inet options>... }
852 # options6 => { <inet6 options>... }
856 # # mappings end up here as well, as we don't need to understand them
860 sub read_etc_network_interfaces
{
861 my ($filename, $fh) = @_;
862 my $proc_net_dev = IO
::File-
>new('/proc/net/dev', 'r');
863 my $active = PVE
::ProcFSTools
::get_active_network_interfaces
();
864 return __read_etc_network_interfaces
($fh, $proc_net_dev, $active);
867 sub __read_etc_network_interfaces
{
868 my ($fh, $proc_net_dev, $active_ifaces) = @_;
871 my $ifaces = $config->{ifaces
} = {};
872 my $options = $config->{options
} = [];
874 my $options_alternatives = {
875 'bond-slaves' => 'slaves',
876 'bond_slaves' => 'slaves',
877 'bond-xmit-hash-policy' => 'bond_xmit_hash_policy',
878 'bond-mode' => 'bond_mode',
879 'bond-miimon' =>'bond_miimon',
880 'bridge-vlan-aware' => 'bridge_vlan_aware',
881 'bridge-fd' => 'bridge_fd',
882 'bridge-stp' => 'bridge_stp',
883 'bridge-ports' => 'bridge_ports',
884 'bridge-vids' => 'bridge_vids'
890 while (defined ($line = <$proc_net_dev>)) {
891 if ($line =~ m/^\s*($PVE::Network::PHYSICAL_NIC_RE):.*/) {
892 $ifaces->{$1}->{exists} = 1;
895 close($proc_net_dev);
898 # we try to keep order inside the file
899 my $priority = 2; # 1 is reserved for lo
901 SECTION
: while (defined ($line = <$fh>)) {
903 next if $line =~ m/^\s*#/;
904 next if $line =~ m/^\s*(allow-hotplug)\s+(.*)$/;
906 if ($line =~ m/^\s*(auto|allow-ovs)\s+(.*)$/) {
907 my @aa = split (/\s+/, $2);
909 foreach my $a (@aa) {
910 $ifaces->{$a}->{autostart
} = 1;
913 } elsif ($line =~ m/^\s*iface\s+(\S+)\s+(inet6?)\s+(\S+)\s*$/) {
916 my $f = { method => $3 }; # by family, merged to $d with a $suffix
917 (my $suffix = $family) =~ s/^inet//;
919 my $d = $ifaces->{$i} ||= {};
920 $d->{priority
} = $priority++ if !$d->{priority
};
921 push @{$d->{families
}}, $family;
923 while (defined ($line = <$fh>)) {
925 if ($line =~ m/^\s*#(.*?)\s*$/) {
926 $f->{comments
} = '' if !$f->{comments
};
927 my $comment = decode
('UTF-8', $1);
928 $f->{comments
} .= "$comment\n";
929 } elsif ($line =~ m
/^\s
*(?
:iface\s
937 } elsif ($line =~ m/^\s*((\S+)\s+(.+))$/) {
939 my ($id, $value) = ($2, $3);
941 $id = $options_alternatives->{$id} if $options_alternatives->{$id};
943 my $simple_options = {
952 'bridge-access' => 1,
953 'bridge-learning' => 1,
954 'bridge-arp-nd-suppress' => 1,
955 'bridge-unicast-flood' => 1,
956 'bridge-multicast-flood' => 1,
958 'bond_xmit_hash_policy' => 1,
961 'vlan-protocol' => 1,
963 'vxlan-svcnodeip' => 1,
964 'vxlan-physdev' => 1,
965 'vxlan-local-tunnelip' => 1 };
967 if (($id eq 'address') || ($id eq 'netmask') || ($id eq 'broadcast') || ($id eq 'gateway')) {
969 } elsif ($simple_options->{$id}) {
971 } elsif ($id eq 'slaves' || $id eq 'bridge_ports') {
973 foreach my $p (split (/\s+/, $value)) {
974 next if $p eq 'none';
977 my $str = join (' ', sort keys %{$devs});
979 $d->{$id} .= ' ' . $str if $str;
981 $d->{$id} = $str || '';
983 } elsif ($id eq 'bridge_stp') {
984 if ($value =~ m/^\s*(on|yes)\s*$/i) {
989 } elsif ($id eq 'bridge_vlan_aware') {
991 } elsif ($id eq 'bond_mode') {
993 foreach my $bm (keys %$bond_modes) {
994 my $id = $bond_modes->{$bm};
1001 } elsif ($id eq 'vxlan-remoteip') {
1002 push @{$d->{$id}}, $value;
1004 push @{$f->{options
}}, $option;
1010 $d->{"$_$suffix"} = $f->{$_} foreach (keys %$f);
1011 last SECTION
if !defined($line);
1013 } elsif ($line =~ /\w/) {
1014 push @$options, [$priority++, $line];
1018 foreach my $ifname (@$active_ifaces) {
1019 if (my $iface = $ifaces->{$ifname}) {
1020 $iface->{active
} = 1;
1024 if (!$ifaces->{lo
}) {
1025 $ifaces->{lo
}->{priority
} = 1;
1026 $ifaces->{lo
}->{method} = 'loopback';
1027 $ifaces->{lo
}->{type
} = 'loopback';
1028 $ifaces->{lo
}->{autostart
} = 1;
1031 foreach my $iface (keys %$ifaces) {
1032 my $d = $ifaces->{$iface};
1033 if ($iface =~ m/^bond\d+$/) {
1034 if (!$d->{ovs_type
}) {
1035 $d->{type
} = 'bond';
1036 } elsif ($d->{ovs_type
} eq 'OVSBond') {
1037 $d->{type
} = $d->{ovs_type
};
1038 # translate: ovs_options => bond_mode
1039 $d->{'bond_mode'} = &$extract_ovs_option($d, 'bond_mode');
1040 my $lacp = &$extract_ovs_option($d, 'lacp');
1041 if ($lacp && $lacp eq 'active') {
1042 if ($d->{'bond_mode'} eq 'balance-slb') {
1043 $d->{'bond_mode'} = 'lacp-balance-slb';
1046 # Note: balance-tcp needs lacp
1047 if ($d->{'bond_mode'} eq 'balance-tcp') {
1048 $d->{'bond_mode'} = 'lacp-balance-tcp';
1050 my $tag = &$extract_ovs_option($d, 'tag');
1051 $d->{ovs_tag
} = $tag if defined($tag);
1053 $d->{type
} = 'unknown';
1055 } elsif ($iface =~ m/^vmbr\d+$/) {
1056 if (!$d->{ovs_type
}) {
1057 $d->{type
} = 'bridge';
1059 if (!defined ($d->{bridge_fd
})) {
1060 $d->{bridge_fd
} = 0;
1062 if (!defined ($d->{bridge_stp
})) {
1063 $d->{bridge_stp
} = 'off';
1065 } elsif ($d->{ovs_type
} eq 'OVSBridge') {
1066 $d->{type
} = $d->{ovs_type
};
1068 $d->{type
} = 'unknown';
1070 } elsif ($iface =~ m/^(\S+):\d+$/) {
1071 $d->{type
} = 'alias';
1072 if (defined ($ifaces->{$1})) {
1073 $d->{exists} = $ifaces->{$1}->{exists};
1075 $ifaces->{$1}->{exists} = 0;
1078 } elsif ($iface =~ m/^(\S+)\.\d+$/) {
1079 $d->{type
} = 'vlan';
1080 if (defined ($ifaces->{$1})) {
1081 $d->{exists} = $ifaces->{$1}->{exists};
1083 $ifaces->{$1}->{exists} = 0;
1086 } elsif ($iface =~ m/^$PVE::Network::PHYSICAL_NIC_RE$/) {
1087 if (!$d->{ovs_type
}) {
1089 } elsif ($d->{ovs_type
} eq 'OVSPort') {
1090 $d->{type
} = $d->{ovs_type
};
1091 my $tag = &$extract_ovs_option($d, 'tag');
1092 $d->{ovs_tag
} = $tag if defined($tag);
1094 $d->{type
} = 'unknown';
1096 } elsif ($iface =~ m/^lo$/) {
1097 $d->{type
} = 'loopback';
1099 if ($d->{'vxlan-id'}) {
1100 $d->{type
} = 'vxlan';
1101 } elsif (!$d->{ovs_type
}) {
1102 $d->{type
} = 'unknown';
1103 } elsif ($d->{ovs_type
} eq 'OVSIntPort') {
1104 $d->{type
} = $d->{ovs_type
};
1105 my $tag = &$extract_ovs_option($d, 'tag');
1106 $d->{ovs_tag
} = $tag if defined($tag);
1110 # map address and netmask to cidr
1111 if ($d->{address
}) {
1112 if ($d->{netmask
} && $d->{netmask
} =~ m/^\d+$/) { # e.g. netmask 20
1113 $d->{cidr
} = $d->{address
} . "/" . $d->{netmask
};
1114 } elsif ($d->{netmask
} &&
1115 (my $cidr = PVE
::JSONSchema
::get_netmask_bits
($d->{netmask
}))) { # e.g. netmask 255.255.255.0
1116 $d->{cidr
} = $d->{address
} . "/" . $cidr;
1117 } elsif ($d->{address
} =~ m!^(.*)/(\d+)$!) {
1118 $d->{cidr
} = $d->{address
};
1122 $d->{cidr
} = $d->{address
};
1126 # map address6 and netmask6 to cidr6
1127 if ($d->{address6
}) {
1128 $d->{cidr6
} = $d->{address6
};
1129 if ($d->{netmask6
}) {
1130 $d->{cidr6
} .= "/" . $d->{netmask6
};
1131 } elsif ($d->{address6
} =~ m!^(.*)/(\d+)$!) {
1132 $d->{address6
} = $1;
1133 $d->{netmask6
} = $2;
1137 $d->{method} = 'manual' if !$d->{method};
1138 $d->{method6
} = 'manual' if !$d->{method6
};
1140 $d->{families
} ||= ['inet'];
1143 # OVS bridges create "allow-$BRIDGE $IFACE" lines which we need to remove
1144 # from the {options} hash for them to be removed correctly.
1145 @$options = grep {defined($_)} map {
1146 my ($pri, $line) = @$_;
1147 if ($line =~ /^allow-ovs\s+(.*)$/) {
1149 } elsif ($line =~ /^allow-(\S+)\s+(.*)$/) {
1151 my @ports = split(/\s+/, $2);
1152 if (defined(my $br = $ifaces->{$bridge})) {
1153 # if this port is part of a bridge, remove it
1154 my %in_ovs_ports = map {$_=>1} split(/\s+/, $br->{ovs_ports
});
1155 @ports = grep { not $in_ovs_ports{$_} } @ports;
1157 # create the allow line for the remaining ports, or delete if empty
1159 [$pri, "allow-$bridge " . join(' ', @ports)];
1164 # don't modify other lines
1172 sub __interface_to_string
{
1173 my ($iface, $d, $family, $first_block, $ifupdown2) = @_;
1175 (my $suffix = $family) =~ s/^inet//;
1177 return '' if !($d && $d->{"method$suffix"});
1181 $raw .= "iface $iface $family " . $d->{"method$suffix"} . "\n";
1182 $raw .= "\taddress " . $d->{"address$suffix"} . "\n" if $d->{"address$suffix"};
1183 $raw .= "\tnetmask " . $d->{"netmask$suffix"} . "\n" if $d->{"netmask$suffix"};
1184 $raw .= "\tgateway " . $d->{"gateway$suffix"} . "\n" if $d->{"gateway$suffix"};
1185 $raw .= "\tbroadcast " . $d->{"broadcast$suffix"} . "\n" if $d->{"broadcast$suffix"};
1187 my $done = { type
=> 1, priority
=> 1, method => 1, active
=> 1, exists => 1,
1188 comments
=> 1, autostart
=> 1, options
=> 1,
1189 address
=> 1, netmask
=> 1, gateway
=> 1, broadcast
=> 1,
1190 method6
=> 1, families
=> 1, options6
=> 1,
1191 address6
=> 1, netmask6
=> 1, gateway6
=> 1, broadcast6
=> 1, 'uplink-id' => 1 };
1193 if (!$first_block) {
1194 # not printing out options
1195 } elsif ($d->{type
} eq 'bridge') {
1197 $d->{bridge_ports
} =~ s/[;,\s]+/ /g;
1198 my $ports = $d->{bridge_ports
} || 'none';
1199 $raw .= "\tbridge-ports $ports\n";
1200 $done->{bridge_ports
} = 1;
1202 my $v = defined($d->{bridge_stp
}) ?
$d->{bridge_stp
} : 'off';
1203 $raw .= "\tbridge-stp $v\n";
1204 $done->{bridge_stp
} = 1;
1206 $v = defined($d->{bridge_fd
}) ?
$d->{bridge_fd
} : 0;
1207 $raw .= "\tbridge-fd $v\n";
1208 $done->{bridge_fd
} = 1;
1210 if( defined($d->{bridge_vlan_aware
})) {
1211 $raw .= "\tbridge-vlan-aware yes\n";
1212 $v = defined($d->{bridge_vids
}) ?
$d->{bridge_vids
} : "2-4094";
1213 $raw .= "\tbridge-vids $v\n";
1215 $done->{bridge_vlan_aware
} = 1;
1216 $done->{bridge_vids
} = 1;
1218 } elsif ($d->{type
} eq 'bond') {
1220 $d->{slaves
} =~ s/[;,\s]+/ /g;
1221 my $slaves = $d->{slaves
} || 'none';
1222 $raw .= "\tbond-slaves $slaves\n";
1223 $done->{slaves
} = 1;
1225 my $v = defined ($d->{'bond_miimon'}) ?
$d->{'bond_miimon'} : 100;
1226 $raw .= "\tbond-miimon $v\n";
1227 $done->{'bond_miimon'} = 1;
1229 $v = defined ($d->{'bond_mode'}) ?
$d->{'bond_mode'} : 'balance-rr';
1230 $raw .= "\tbond-mode $v\n";
1231 $done->{'bond_mode'} = 1;
1233 if ($d->{'bond_mode'} && $d->{'bond_xmit_hash_policy'} &&
1234 ($d->{'bond_mode'} eq 'balance-xor' || $d->{'bond_mode'} eq '802.3ad')) {
1235 $raw .= "\tbond-xmit-hash-policy $d->{'bond_xmit_hash_policy'}\n";
1237 $done->{'bond_xmit_hash_policy'} = 1;
1239 if ($d->{'bond_mode'} && $d->{'bond_mode'} eq 'active-backup' && $d->{'bond-primary'}) {
1240 $raw .= "\tbond-primary $d->{'bond-primary'}\n";
1242 $done->{'bond-primary'} = 1;
1244 } elsif ($d->{type
} eq 'vlan') {
1245 die "$iface: wrong vlan-protocol $d->{'vlan-protocol'}\n"
1246 if $d->{'vlan-protocol'} && $d->{'vlan-protocol'} ne '802.1ad' && $d->{'vlan-protocol'} ne '802.1q';
1248 } elsif ($d->{type
} eq 'vxlan') {
1250 foreach my $k (qw(vxlan-id vxlan-svcnodeip vxlan-physdev vxlan-local-tunnelip)) {
1251 $raw .= "\t$k $d->{$k}\n" if defined $d->{$k};
1255 if ($d->{'vxlan-remoteip'}) {
1256 foreach my $remoteip (@{$d->{'vxlan-remoteip'}}) {
1257 $raw .= "\tvxlan-remoteip $remoteip\n";
1259 $done->{'vxlan-remoteip'} = 1;
1261 } elsif ($d->{type
} eq 'OVSBridge') {
1263 $raw .= "\tovs_type $d->{type}\n";
1264 $done->{ovs_type
} = 1;
1266 $raw .= "\tovs_ports $d->{ovs_ports}\n" if $d->{ovs_ports
};
1268 $done->{ovs_ports
} = 1;
1269 } elsif ($d->{type
} eq 'OVSPort' || $d->{type
} eq 'OVSIntPort' ||
1270 $d->{type
} eq 'OVSBond') {
1272 $d->{autostart
} = 0; # started by the bridge
1274 if (defined($d->{ovs_tag
})) {
1275 &$set_ovs_option($d, tag
=> $d->{ovs_tag
});
1277 $done->{ovs_tag
} = 1;
1279 if ($d->{type
} eq 'OVSBond') {
1281 $d->{bond_mode
} = 'active-backup' if !$d->{bond_mode
};
1283 $ovs_bond_modes->{$d->{bond_mode
}} ||
1284 die "OVS does not support bond mode '$d->{bond_mode}\n";
1286 if ($d->{bond_mode
} eq 'lacp-balance-slb') {
1287 &$set_ovs_option($d, lacp
=> 'active');
1288 &$set_ovs_option($d, bond_mode
=> 'balance-slb');
1289 } elsif ($d->{bond_mode
} eq 'lacp-balance-tcp') {
1290 &$set_ovs_option($d, lacp
=> 'active');
1291 &$set_ovs_option($d, bond_mode
=> 'balance-tcp');
1293 &$set_ovs_option($d, lacp
=> undef);
1294 &$set_ovs_option($d, bond_mode
=> $d->{bond_mode
});
1296 $done->{bond_mode
} = 1;
1298 $raw .= "\tovs_bonds $d->{ovs_bonds}\n" if $d->{ovs_bonds
};
1299 $done->{ovs_bonds
} = 1;
1302 $raw .= "\tovs_type $d->{type}\n";
1303 $done->{ovs_type
} = 1;
1305 if (my $bridge = $d->{ovs_bridge
}) {
1306 $raw = "allow-$bridge $iface\n$raw";
1307 $raw .= "\tovs_bridge $bridge\n";
1308 $done->{ovs_bridge
} = 1;
1313 # print other settings
1314 foreach my $k (sort keys %$d) {
1315 next if $done->{$k};
1317 $raw .= "\t$k $d->{$k}\n";
1321 foreach my $option (@{$d->{"options$suffix"}}) {
1322 $raw .= "\t$option\n";
1326 my $comments = $d->{"comments$suffix"} || '';
1327 foreach my $cl (split(/\n/, $comments)) {
1337 sub write_etc_network_interfaces
{
1338 my ($filename, $fh, $config) = @_;
1339 my $ifupdown2 = -e
'/usr/share/ifupdown2';
1340 my $raw = __write_etc_network_interfaces
($config, $ifupdown2);
1341 PVE
::Tools
::safe_print
($filename, $fh, encode
('UTF-8', $raw));
1343 sub __write_etc_network_interfaces
{
1344 my ($config, $ifupdown2) = @_;
1346 my $ifaces = $config->{ifaces
};
1347 my @options = @{$config->{options
}};
1349 my $used_ports = {};
1351 foreach my $iface (keys %$ifaces) {
1352 my $d = $ifaces->{$iface};
1358 foreach my $k (qw(bridge_ports ovs_ports slaves ovs_bonds)) {
1359 $ports .= " $d->{$k}" if $d->{$k};
1362 foreach my $p (PVE
::Tools
::split_list
($ports)) {
1363 die "port '$p' is already used on interface '$used_ports->{$p}'\n"
1364 if $used_ports->{$p} && $used_ports->{$p} ne $iface;
1365 $used_ports->{$p} = $iface;
1369 # delete unused OVS ports
1370 foreach my $iface (keys %$ifaces) {
1371 my $d = $ifaces->{$iface};
1372 if ($d->{type
} eq 'OVSPort' || $d->{type
} eq 'OVSIntPort' ||
1373 $d->{type
} eq 'OVSBond') {
1374 my $brname = $used_ports->{$iface};
1375 if (!$brname || !$ifaces->{$brname}) {
1376 if ($iface =~ /^$PVE::Network::PHYSICAL_NIC_RE/) {
1377 $ifaces->{$iface} = { type
=> 'eth',
1380 families
=> ['inet'] };
1382 delete $ifaces->{$iface};
1386 my $bd = $ifaces->{$brname};
1387 if ($bd->{type
} ne 'OVSBridge') {
1388 delete $ifaces->{$iface};
1394 # create OVS bridge ports
1395 foreach my $iface (keys %$ifaces) {
1396 my $d = $ifaces->{$iface};
1397 if ($d->{type
} eq 'OVSBridge' && $d->{ovs_ports
}) {
1398 foreach my $p (split (/\s+/, $d->{ovs_ports
})) {
1399 my $n = $ifaces->{$p};
1400 die "OVS bridge '$iface' - unable to find port '$p'\n"
1402 $n->{autostart
} = 0;
1403 if ($n->{type
} eq 'eth') {
1404 $n->{type
} = 'OVSPort';
1405 $n->{ovs_bridge
} = $iface;
1406 } elsif ($n->{type
} eq 'OVSBond' || $n->{type
} eq 'OVSPort' ||
1407 $n->{type
} eq 'OVSIntPort') {
1408 $n->{ovs_bridge
} = $iface;
1410 die "interface '$p' is not defined as OVS port/bond\n";
1413 &$check_mtu($ifaces, $iface, $p);
1418 # check OVS bond ports
1419 foreach my $iface (keys %$ifaces) {
1420 my $d = $ifaces->{$iface};
1421 if ($d->{type
} eq 'OVSBond' && $d->{ovs_bonds
}) {
1422 foreach my $p (split (/\s+/, $d->{ovs_bonds
})) {
1423 my $n = $ifaces->{$p};
1424 die "OVS bond '$iface' - unable to find slave '$p'\n"
1426 die "OVS bond '$iface' - wrong interface type on slave '$p' " .
1427 "('$n->{type}' != 'eth')\n" if $n->{type
} ne 'eth';
1428 &$check_mtu($ifaces, $iface, $p);
1434 foreach my $iface (keys %$ifaces) {
1435 my $d = $ifaces->{$iface};
1436 if ($d->{type
} eq 'bond' && $d->{slaves
}) {
1437 my $bond_primary_is_slave = undef;
1438 foreach my $p (split (/\s+/, $d->{slaves
})) {
1439 my $n = $ifaces->{$p};
1441 die "bond '$iface' - unable to find slave '$p'\n"
1443 die "bond '$iface' - wrong interface type on slave '$p' " .
1444 "('$n->{type}' != 'eth')\n" if $n->{type
} ne 'eth';
1445 &$check_mtu($ifaces, $iface, $p);
1446 $bond_primary_is_slave = 1 if $d->{'bond-primary'} && $d->{'bond-primary'} eq $p;
1448 die "bond '$iface' - bond-primary interface is not a slave" if $d->{'bond-primary'} && !$bond_primary_is_slave;
1454 foreach my $iface (keys %$ifaces) {
1455 my $d = $ifaces->{$iface};
1457 if ($d->{type
} eq 'vxlan' && $d->{'vxlan-id'}) {
1458 my $vxlanid = $d->{'vxlan-id'};
1459 die "iface $iface - duplicate vxlan-id $vxlanid already used in $vxlans->{$vxlanid}\n" if $vxlans->{$vxlanid};
1460 $vxlans->{$vxlanid} = $iface;
1464 ++$ips if defined $d->{'vxlan-svcnodeip'};
1465 ++$ips if defined $d->{'vxlan-remoteip'};
1466 ++$ips if defined $d->{'vxlan-local-tunnelip'};
1468 die "iface $iface - vxlan-svcnodeip, vxlan-remoteip and vxlan-localtunnelip are mutually exclusive\n";
1471 if (defined($d->{'vxlan-svcnodeip'}) != defined($d->{'vxlan-physdev'})) {
1472 die "iface $iface - vxlan-svcnodeip and vxlan-physdev must be define together\n";
1474 #fixme : check if vxlan mtu is lower than 50bytes than physical interface where tunnel is going out
1478 foreach my $iface (keys %$ifaces) {
1479 my $d = $ifaces->{$iface};
1480 if ($d->{type
} eq 'vlan' && $iface =~ m/^(\S+)\.\d+$/) {
1482 my $n = $ifaces->{$p};
1484 die "vlan '$iface' - unable to find parent '$p'\n"
1487 if ($n->{type
} ne 'eth' && $n->{type
} ne 'bridge' && $n->{type
} ne 'bond' && $n->{type
} ne 'vlan') {
1488 die "vlan '$iface' - wrong interface type on parent '$p' " .
1489 "('$n->{type}' != 'eth|bond|bridge|vlan' )\n";
1492 &$check_mtu($ifaces, $p, $iface);
1499 foreach my $iface (keys %$ifaces) {
1500 my $d = $ifaces->{$iface};
1501 if (my $uplinkid = $d->{'uplink-id'}) {
1502 die "iface '$iface' - uplink-id $uplinkid is only allowed on physical and linux bond interfaces\n"
1503 if $d->{type
} ne 'eth' && $d->{type
} ne 'bond';
1505 die "iface '$iface' - uplink-id $uplinkid is already assigned on '$uplinks->{$uplinkid}'\n"
1506 if $uplinks->{$uplinkid};
1508 $uplinks->{$uplinkid} = $iface;
1512 # check bridgeport option
1513 my $bridgeports = {};
1515 foreach my $iface (keys %$ifaces) {
1516 my $d = $ifaces->{$iface};
1517 if ($d->{type
} eq 'bridge') {
1518 foreach my $p (split (/\s+/, $d->{bridge_ports
})) {
1520 my $n = $ifaces->{$p};
1521 die "bridge '$iface' - unable to find bridge port '$p'\n"
1523 die "iface $p - ip address can't be set on interface if bridged in $iface\n"
1524 if ($n->{method} eq 'static' && $n->{address
} ne '0.0.0.0') ||
1525 ($n->{method6
} eq 'static' && $n->{address
} ne "\:\:");
1527 &$check_mtu($ifaces, $iface, $p);
1528 $bridgeports->{$p} = $iface;
1530 $bridges->{$iface} = $d;
1534 foreach my $iface (keys %$ifaces) {
1535 my $d = $ifaces->{$iface};
1537 foreach my $k (qw(bridge-learning bridge-arp-nd-suppress bridge-unicast-flood bridge-multicast-flood bridge-access)) {
1538 die "iface $iface - $k: bridge port specific options can be used only on interfaces attached to a bridge\n"
1539 if $d->{$k} && !$bridgeports->{$iface};
1542 if ($d->{'bridge-access'} && !$bridges->{$bridgeports->{$iface}}->{bridge_vlan_aware
}) {
1543 die "iface $iface - bridge-access option can be only used if interface is in a vlan aware bridge\n";
1547 my $raw = <<'NETWORKDOC';
1548 # network interface settings; autogenerated
1549 # Please do NOT modify this file directly, unless you know what
1552 # If you want to manage parts of the network configuration manually,
1553 # please utilize the 'source' or 'source-directory' directives to do
1555 # PVE will preserve these directives, but will NOT read its network
1556 # configuration from sourced files, so do not attempt to move any of
1557 # the PVE managed interfaces into external files!
1563 my $if_type_hash = {
1567 OVSIntPort
=> 200000,
1570 OVSBridge
=> 400000,
1574 my $lookup_type_prio = sub {
1575 my ($iface, $ifaces) = @_;
1577 my ($rootiface, @rest) = split(/[.:]/, $iface);
1578 my $childlevel = scalar(@rest);
1579 my $n = $ifaces->{$rootiface};
1581 my $pri = $if_type_hash->{$n->{type
}} + $childlevel
1582 if $n->{type
} && $n->{type
} ne 'unknown';
1587 foreach my $iface (sort {
1588 my $ref1 = $ifaces->{$a};
1589 my $ref2 = $ifaces->{$b};
1590 my $tp1 = &$lookup_type_prio($a, $ifaces);
1591 my $tp2 = &$lookup_type_prio($b, $ifaces);
1593 # Only recognized types are in relation to each other. If one type
1594 # is unknown then only consider the interfaces' priority attributes.
1595 $tp1 = $tp2 = 0 if !defined($tp1) || !defined($tp2);
1597 my $p1 = $tp1 + ($ref1->{priority
} // 50000);
1598 my $p2 = $tp2 + ($ref2->{priority
} // 50000);
1600 return $p1 <=> $p2 if $p1 != $p2;
1604 next if $printed->{$iface};
1605 my $d = $ifaces->{$iface};
1606 my $pri = $d->{priority
} // 0;
1607 if (@options && $options[0]->[0] < $pri) {
1609 $raw .= (shift @options)->[1] . "\n";
1610 } while (@options && $options[0]->[0] < $pri);
1614 $printed->{$iface} = 1;
1615 if ($d->{autostart
}) {
1616 if ($d->{type
} eq 'OVSBridge') {
1617 # cannot use 'auto' for OVS, would add race with systemd ifup@.service
1618 $raw .= "allow-ovs $iface\n";
1620 $raw .= "auto $iface\n";
1624 my $i = 0; # some options should be printed only once
1625 $raw .= __interface_to_string
($iface, $d, $_, !$i++, $ifupdown2) foreach @{$d->{families
}};
1628 $raw .= $_->[1] . "\n" foreach @options;
1632 register_file
('interfaces', "/etc/network/interfaces",
1633 \
&read_etc_network_interfaces
,
1634 \
&write_etc_network_interfaces
);
1637 sub read_iscsi_initiatorname
{
1638 my ($filename, $fd) = @_;
1640 while (defined(my $line = <$fd>)) {
1641 if ($line =~ m/^InitiatorName=(\S+)$/) {
1649 register_file
('initiatorname', "/etc/iscsi/initiatorname.iscsi",
1650 \
&read_iscsi_initiatorname
);
1653 my ($filename, $fd) = @_;
1657 my $raw = defined($fd) ?
<$fd> : '';
1662 my @tokens = split(/\s+/, $raw);
1667 while (defined(my $tok = shift @tokens)) {
1669 $machine = shift @tokens if $tok eq 'machine';
1671 $data->{$machine} = {} if !$data->{$machine};
1673 $data->{$machine}->{login
} = shift @tokens if $tok eq 'login';
1674 $data->{$machine}->{password
} = shift @tokens if $tok eq 'password';
1680 my $format_apt_auth_data = sub {
1685 foreach my $machine (sort keys %$data) {
1686 my $d = $data->{$machine};
1687 $raw .= "machine $machine\n";
1688 $raw .= " login $d->{login}\n" if $d->{login
};
1689 $raw .= " password $d->{password}\n" if $d->{password
};
1696 sub write_apt_auth
{
1697 my ($filename, $fh, $data) = @_;
1699 my $raw = &$format_apt_auth_data($data);
1701 die "write failed: $!" unless print $fh "$raw\n";
1706 sub update_apt_auth
{
1707 my ($filename, $fh, $data) = @_;
1709 my $orig = read_apt_auth
($filename, $fh);
1711 foreach my $machine (keys %$data) {
1712 $orig->{$machine} = $data->{$machine};
1715 return &$format_apt_auth_data($orig);
1718 register_file
('apt-auth', "/etc/apt/auth.conf",
1719 \
&read_apt_auth
, \
&write_apt_auth
,
1720 \
&update_apt_auth
, perm
=> 0640);