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