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