add vlan setup code to PVE::Network
[pve-common.git] / data / PVE / Network.pm
1 package PVE::Network;
2
3 use strict;
4 use PVE::Tools;
5 use PVE::ProcFSTools;
6 use PVE::INotify;
7 use File::Basename;
8
9 # host network related utility functions
10
11 sub copy_bridge_config {
12 my ($br0, $br1) = @_;
13
14 return if $br0 eq $br1;
15
16 my $br_configs = [ 'ageing_time', 'stp_state', 'priority', 'forward_delay',
17 'hello_time', 'max_age'];
18
19 foreach my $sysname (@$br_configs) {
20 eval {
21 my $v0 = PVE::Tools::file_read_firstline("/sys/class/net/$br0/bridge/$sysname");
22 my $v1 = PVE::Tools::file_read_firstline("/sys/class/net/$br1/bridge/$sysname");
23 if ($v0 ne $v1) {
24 system("echo \"$v0\" > /sys/class/net/$br1/bridge/$sysname") == 0 ||
25 warn "unable to set bridge config '$sysname'\n";
26 }
27 };
28 warn $@ if $@;
29 }
30 }
31
32 sub activate_bridge_vlan {
33 my ($bridge, $tag_param) = @_;
34
35 die "bridge '$bridge' is not active\n" if ! -d "/sys/class/net/$bridge";
36
37 return $bridge if !defined($tag_param); # no vlan, simply return
38
39 my $tag = int($tag_param);
40
41 die "got strange vlan tag '$tag_param'\n" if $tag < 1 || $tag > 4094;
42
43 my $bridgevlan = "${bridge}v$tag";
44
45 my $dir = "/sys/class/net/$bridge/brif";
46
47 #check if we have an only one ethX or bondX interface in the bridge
48
49 my $iface;
50 PVE::Tools::dir_glob_foreach($dir, '((eth|bond)\d+)', sub {
51 my ($slave) = @_;
52
53 die "more then one physical interfaces on bridge '$bridge'\n" if $iface;
54 $iface = $slave;
55
56 });
57
58 die "no physical interface on bridge '$bridge'\n" if !$iface;
59
60 my $ifacevlan = "${iface}.$tag";
61
62 # create vlan on $iface is not already exist
63 if (! -d "/sys/class/net/$ifacevlan") {
64 system("/sbin/vconfig add $iface $tag") == 0 ||
65 die "can't add vlan tag $tag to interface $iface\n";
66 }
67
68 # be sure to have the $ifacevlan up
69 system("/sbin/ip link set $ifacevlan up") == 0 ||
70 die "can't up interface $ifacevlan\n";
71
72 # test if $vlaniface is already enslaved in another bridge
73 my $path= "/sys/class/net/$ifacevlan/brport/bridge";
74 if (-l $path) {
75 my $tbridge = basename(readlink($path));
76 if ($tbridge eq $bridgevlan) {
77 # already member of bridge - assume setup is already done
78 return $bridgevlan;
79 } else {
80 die "interface $ifacevlan already exist in bridge $tbridge\n";
81 }
82 }
83
84 # add bridgevlan if it doesn't already exist
85 if (! -d "/sys/class/net/$bridgevlan") {
86 system("/usr/sbin/brctl addbr $bridgevlan") == 0 ||
87 die "can't add bridge $bridgevlan\n";
88 }
89
90 #fixme: set other bridge flags
91
92 # be sure to have the bridge up
93 system("/sbin/ip link set $bridgevlan up") == 0 ||
94 die "can't up bridge $bridgevlan\n";
95
96 # add $ifacevlan to the bridge
97 system("/usr/sbin/brctl addif $bridgevlan $ifacevlan") == 0 ||
98 die "can't add interface $ifacevlan to bridge $bridgevlan\n";
99
100 return $bridgevlan;
101 }
102
103 1;