merge the vs and lxc nodemanagers
[nodemanager.git] / net.py
1 """network configuration"""
2
3 # system provided modules
4 import os, string, time, socket
5
6 # PlanetLab system modules
7 import sioc, plnet
8
9 # local modules
10 try:    import bwlimit as bwlimit
11 except: import bwlimitlxc as bwlimit
12 import logger, iptables, tools
13
14 # we can't do anything without a network
15 priority=1
16
17 dev_default = tools.get_default_if()
18
19
20 def start():
21     logger.log("net: plugin starting up...")
22
23 def GetSlivers(data, config, plc):
24     # added by caglar
25     # band-aid for short period as old API returns networks instead of interfaces
26     global KEY_NAME
27     KEY_NAME = "interfaces"
28     #################
29
30     logger.verbose("net: GetSlivers called.")
31     if not 'interfaces' in data:
32         # added by caglar
33         # band-aid for short period as old API returns networks instead of interfaces
34         # logger.log_missing_data('net.GetSlivers','interfaces')
35         # return
36         if not 'networks' in data:
37             logger.log_missing_data('net.GetSlivers','interfaces')
38             return
39         else:
40             KEY_NAME = "networks"
41         ##################
42
43     plnet.InitInterfaces(logger, plc, data)
44     if 'OVERRIDES' in dir(config):
45         if config.OVERRIDES.get('net_max_rate') == '-1':
46             logger.log("net: Slice and node BW Limits disabled.")
47             if len(bwlimit.tc("class show dev %s" % dev_default)):
48                 logger.verbose("net: *** DISABLING NODE BW LIMITS ***")
49                 bwlimit.stop()
50         else:
51             InitNodeLimit(data)
52             InitI2(plc, data)
53     else:
54         InitNodeLimit(data)
55         InitI2(plc, data)
56     InitNAT(plc, data)
57
58
59 def InitNodeLimit(data):
60
61     # query running network interfaces
62     devs = sioc.gifconf()
63     ips = dict(zip(devs.values(), devs.keys()))
64     macs = {}
65     for dev in devs:
66         macs[sioc.gifhwaddr(dev).lower()] = dev
67
68     for interface in data[KEY_NAME]:
69         # Get interface name preferably from MAC address, falling
70         # back on IP address.
71         hwaddr=interface['mac']
72         if hwaddr <> None: hwaddr=hwaddr.lower()
73         if hwaddr in macs:
74             dev = macs[interface['mac']]
75         elif interface['ip'] in ips:
76             dev = ips[interface['ip']]
77         else:
78             logger.log('net: %s: no such interface with address %s/%s' % (interface['hostname'], interface['ip'], interface['mac']))
79             continue
80
81         # Get current node cap
82         try:
83             old_bwlimit = bwlimit.get_bwcap(dev)
84         except:
85             old_bwlimit = None
86
87         # Get desired node cap
88         if interface['bwlimit'] is None or interface['bwlimit'] < 0:
89             new_bwlimit = bwlimit.bwmax
90         else:
91             new_bwlimit = interface['bwlimit']
92
93         if old_bwlimit != new_bwlimit:
94             # Reinitialize bandwidth limits
95             bwlimit.init(dev, new_bwlimit)
96
97             # XXX This should trigger an rspec refresh in case
98             # some previously invalid sliver bwlimit is now valid
99             # again, or vice-versa.
100
101 def InitI2(plc, data):
102     if not 'groups' in data: return
103
104     if "Internet2" in data['groups']:
105         logger.log("net: This is an Internet2 node.  Setting rules.")
106         i2nodes = []
107         i2nodeids = plc.GetNodeGroups(["Internet2"])[0]['node_ids']
108         for node in plc.GetInterfaces({"node_id": i2nodeids}, ["ip"]):
109             # Get the IPs
110             i2nodes.append(node['ip'])
111         # this will create the set if it doesn't already exist
112         # and add IPs that don't exist in the set rather than
113         # just recreateing the set.
114         bwlimit.exempt_init('Internet2', i2nodes)
115
116         # set the iptables classification rule if it doesnt exist.
117         cmd = '-A POSTROUTING -m set --set Internet2 dst -j CLASSIFY --set-class 0001:2000 --add-mark'
118         rules = []
119         ipt = os.popen("/sbin/iptables-save")
120         for line in ipt.readlines(): rules.append(line.strip(" \n"))
121         ipt.close()
122         if cmd not in rules:
123             logger.verbose("net:  Adding iptables rule for Internet2")
124             os.popen("/sbin/iptables -t mangle " + cmd)
125
126 def InitNAT(plc, data):
127
128     # query running network interfaces
129     devs = sioc.gifconf()
130     ips = dict(zip(devs.values(), devs.keys()))
131     macs = {}
132     for dev in devs:
133         macs[sioc.gifhwaddr(dev).lower()] = dev
134
135     ipt = iptables.IPTables()
136     for interface in data[KEY_NAME]:
137         # Get interface name preferably from MAC address, falling
138         # back on IP address.
139         hwaddr=interface['mac']
140         if hwaddr <> None: hwaddr=hwaddr.lower()
141         if hwaddr in macs:
142             dev = macs[interface['mac']]
143         elif interface['ip'] in ips:
144             dev = ips[interface['ip']]
145         else:
146             logger.log('net: %s: no such interface with address %s/%s' % (interface['hostname'], interface['ip'], interface['mac']))
147             continue
148
149         try:
150             settings = plc.GetInterfaceTags({'interface_tag_id': interface['interface_tag_ids']})
151         except:
152             continue
153
154         for setting in settings:
155             if setting['category'].upper() != 'FIREWALL':
156                 continue
157             if setting['name'].upper() == 'EXTERNAL':
158                 # Enable NAT for this interface
159                 ipt.add_ext(dev)
160             elif setting['name'].upper() == 'INTERNAL':
161                 ipt.add_int(dev)
162             elif setting['name'].upper() == 'PF': # XXX Uglier code is hard to find...
163                 for pf in setting['value'].split("\n"):
164                     fields = {}
165                     for field in pf.split(","):
166                         (key, val) = field.split("=", 2)
167                         fields[key] = val
168                     if 'new_dport' not in fields:
169                         fields['new_dport'] = fields['dport']
170                     if 'source' not in fields:
171                         fields['source'] = "0.0.0.0/0"
172                     ipt.add_pf(fields)
173     ipt.commit()