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