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