Updates for change in sioc.gifconf() semantics
[nodemanager-topo.git] / topo.py
1 # $Id$
2 # $URL$
3
4 """ 
5 VINI/Trellis NodeManager plugin.
6 Create virtual links from the topo_rspec slice attribute. 
7 """
8
9 import logger
10 import subprocess
11 import sioc
12 import re
13 import vserver
14 import os
15 from time import strftime
16 import socket
17
18 dryrun = 0
19 vinidir = "/usr/share/vini/"
20 setup_link_cmd = vinidir + "setup-egre-link"
21 teardown_link_cmd = vinidir + "teardown-egre-link"
22 setup_nat_cmd = vinidir + "setup-nat"
23 teardown_nat_cmd = vinidir + "teardown-nat"
24 ifaces = {}
25 old_ifaces = {}
26
27 def run(cmd):
28     if dryrun:
29         logger.log(cmd)
30         return -1
31     else:
32         return subprocess.call(cmd, shell=True);
33
34 """
35 From old pyplnet, former semantics needed for VINI
36 """
37 def gifconf():
38     try:
39         interfaces = os.listdir("/sys/class/net")
40     except:
41         interfaces = []
42     s = None
43     ret = {}
44     try:
45         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
46         for interface in interfaces:
47             try:
48                 ifreq = fcntl.ioctl(s.fileno(), SIOCGIFADDR,
49                                     struct.pack("16sH14x", interface, socket.AF_INET))
50                 (family, ip) = struct.unpack(SIOCGIFADDR_struct, ifreq)
51                 if family == socket.AF_INET:
52                     ret[interface] = _format_ip(ip)
53                 else:
54                     raise Exception
55             except:
56                 ret[interface] = "0.0.0.0"
57     finally:
58         if s is not None:
59             s.close()
60     return ret
61
62 """
63 Subnet used for virtual interfaces by setup-egre-link script
64 """
65 def iias_network():
66     return "192.168.0.0 255.255.0.0"
67
68
69 """
70 Check for existence of interface d<key>x<nodeid>
71 """
72 def virtual_link(key, nodeid):
73     name = "d%sx%s" % (key, nodeid)
74     if name in ifaces:
75         return True
76     else:
77         return False
78
79 """
80 Create a "virtual link" for slice between here and nodeid.
81 The key is used to create the EGRE tunnel.
82 """
83 def setup_virtual_link(slice, key, rate, myid, nodeid, ipaddr, virtip, vnet):
84     logger.log("%s: Set up virtual link to node %s" % (slice, nodeid))
85     run(setup_link_cmd + " %s %s %s %s %s %s %s" % (slice, nodeid, ipaddr, 
86                                                  key, rate, virtip, vnet))
87     return
88
89
90 """
91 Tear down the "virtual link" for slice between here and nodeid.
92 """
93 def teardown_virtual_link(key, nodeid):
94     logger.log("topo: Tear down virtual link %sx%s" % (key, nodeid))
95     run(teardown_link_cmd + " %s %s" % (nodeid, key))
96     return
97
98
99 """
100 Called for all active virtual link interfaces, so they won't be cleaned up.
101 """
102 def refresh_virtual_link(nodeid, key):
103     name = "d%sx%s" % (key, nodeid)
104     if name in old_ifaces:
105         del old_ifaces[name]
106     return
107
108
109 """
110 IP address of the NAT interface created inside the slice by the
111 setup-nat script.
112 """
113 def nat_inner_ip(key):
114     return "10.0.%s.2" % key
115
116
117 """
118 Check for existence of interface natx<key>
119 """
120 def nat_exists(key):
121     name = "natx%s" % key
122     if name in ifaces:
123         return True
124     else:
125         return False
126
127
128 """
129 Create a NAT interface inside the sliver.  
130 """
131 def setup_nat(slice, myid, key):
132     logger.log("%s: Set up NAT" % slice)
133     run(setup_nat_cmd + " %s %s %s" % (slice, myid, key))
134     return
135
136
137 """
138 Tear down the NAT interface identified by key
139 """
140 def teardown_nat(key):
141     logger.log("topo: Tear down NAT %s" % key)
142     run(teardown_nat_cmd + " %s" % key)
143     return
144
145
146 """
147 Called for all active NAT interfaces, so they won't be cleaned up.
148 """
149 def refresh_nat(key):
150     name = "natx%s" % (key)
151     if name in old_ifaces:
152         del old_ifaces[name]
153     return
154
155
156 """
157 Clean up old virtual links (e.g., to nodes that have been deleted 
158 from the slice).
159 """
160 def clean_up_old_virtual_links():
161     pattern1 = "d(.*)x(.*)"
162     pattern2 = "natx(.*)"
163     for iface in old_ifaces:
164         m = re.match(pattern1, iface)
165         if m:
166             key = m.group(1)
167             node = m.group(2)
168             teardown_virtual_link(key, node)
169
170         m = re.match(pattern2, iface)
171         if m:
172             key = m.group(1)
173             teardown_nat(key)
174     return
175
176
177 """
178 Not the safest thing to do, probably should use pickle() or something.
179 """
180 def convert_topospec_to_list(rspec):
181     return eval(rspec)
182
183
184 """
185 Update virtual links for the slice
186 """
187 def update_links(slice, myid, topospec, key, netns):
188     topolist = convert_topospec_to_list(topospec)
189     for (nodeid, ipaddr, rate, myvirtip, remvirtip, virtnet) in topolist:
190         if not virtual_link(key, nodeid):
191             if netns:
192                 setup_virtual_link(slice, key, rate, myid, nodeid, 
193                                    ipaddr, myvirtip, virtnet)
194         else:
195             logger.log("%s: virtual link to node %s exists" % (slice, nodeid))
196             refresh_virtual_link(nodeid, key)
197
198
199 """
200 Update NAT interface for the slice
201 """
202 def update_nat(slice, myid, key, netns):
203     if not nat_exists(key):
204         if netns:
205             setup_nat(slice, myid, key)
206     else:
207         logger.log("%s: NAT exists" % slice)
208         refresh_nat(key)
209
210
211 """
212 Write /etc/vservers/<slicename>/spaces/net.  
213 Restart the vserver if there are any changes.
214 """
215 def write_spaces_net(slicename, value):
216     SLICEDIR="/etc/vservers/%s/" % slicename
217     SPACESDIR="%s/spaces/" % SLICEDIR
218     FILENAME="%s/net" % SPACESDIR
219     if os.path.exists(SLICEDIR):
220         if not os.path.exists(SPACESDIR):
221             try:
222                 os.mkdir(SPACESDIR)
223             except os.error:
224                 logger.log("topo: could not create %s\n" % SPACESDIR)
225                 return
226             
227         if os.path.exists(FILENAME) != value:
228             sliver = vserver.VServer(slicename)
229             
230             sliver.stop()
231
232             if value:
233                 STATUS="ON"
234                 f = open(FILENAME, "w")
235                 f.close()
236             else:
237                 STATUS="OFF"
238                 os.remove(FILENAME)
239
240             sliver.start()
241
242             logger.log("%s: network namespace %s\n" % (slicename, STATUS))
243
244
245 """
246 Generate information for each interface in the sliver, in order to configure
247 Quagga.
248 """
249 def get_ifaces(hostname, myid, topospec, key):
250     ifaces = {}
251     topolist = convert_topospec_to_list(topospec)
252     for (nodeid, ipaddr, rate, myvirtip, remvirtip, virtnet) in topolist:
253         name = "a%sx%s" % (key, nodeid)
254         ifaces[name] = {}
255         ifaces[name]['remote-ip'] = remvirtip
256         ifaces[name]['local-ip'] = myvirtip
257         ifaces[name]['network'] = virtnet
258         ifaces[name]['short-name'] = hostname.replace('.vini-veritas.net', '')
259     return ifaces
260
261
262 def write_header(f, myname, password):
263     f.write ("""! Configuration for %s
264 ! Generated at %s
265
266 hostname %s
267 password %s
268
269 """ % (myname, strftime("%Y-%m-%d %H:%M:%S"), myname, password))
270     return
271
272
273 """
274 IP address of NAT gateway to outside world
275 """
276 def nat_gw(key):
277     return "10.0.%s.1" %  key
278
279 """
280 IP address of the NAT interface inside the slice
281 """
282 def nat_inner(key):
283     return "10.0.%s.2" % key
284
285
286 """
287 Write zebra.conf file for Quagga
288 """
289 def write_zebra(filename, myname, ifaces, myid, key):
290     f = open(filename, 'w')
291     password = "zebra"
292     write_header(f, myname, password)
293
294     f.write ("enable password %s\n" % password)
295
296     for name in ifaces:
297         f.write ("""!     
298 interface %s
299 link-detect
300 """ %  name)
301
302     f.write ("""!
303 access-list vty permit 127.0.0.1/32
304 !
305 line vty
306 !
307 """)
308     f.close()
309     return
310
311
312 """
313 Write ospfd.conf file for Quagga.  
314 """
315 def write_ospf(filename, myname, ifaces):
316     f = open(filename, 'w')
317     password = "zebra"
318     write_header(f, myname, password)
319     name = None
320
321     for name in ifaces:
322         f.write ("""!
323      interface %s
324      ip ospf cost 10
325      ip ospf hello-interval 5
326      ip ospf dead-interval 10
327      ip ospf network non-broadcast
328 """ % name)
329
330     if name:
331         f.write ("""!
332      router ospf
333      ospf router-id %s
334 """ % ifaces[name]['local-ip'])
335
336     for name in ifaces:
337         f.write ("     neighbor %s\n" % ifaces[name]['remote-ip'])
338
339     for name in ifaces:
340         net = ifaces[name]['network']
341         f.write ("     network %s area 0\n" % net)
342
343     f.write("""     redistribute kernel
344 !
345 access-list vty permit 127.0.0.1/32
346 !
347 line vty
348 """)
349     return
350
351
352 """
353 Write config files directly into the slice's file system.
354 """
355 def update_quagga_configs(slicename, hostname, myid, topo, key, netns):
356     ifaces = get_ifaces(hostname, myid, topo, key)
357
358     quagga_dir = "/vservers/%s/etc/quagga/" % slicename
359     if not os.path.exists(quagga_dir):
360         try:
361             os.mkdir(quagga_dir)
362         except os.error:
363             logger.log("topo: could not create %s\n" % quagga_dir)
364             return
365
366     write_zebra(quagga_dir + "zebra.conf.generated", hostname, ifaces, 
367                 myid, key)
368     write_ospf(quagga_dir + "ospfd.conf.generated", hostname, ifaces)
369
370     return
371
372
373 """
374 Write /etc/hosts in the sliver
375 """
376 def update_hosts(slicename, hosts):
377     hosts_file = "/vservers/%s/etc/hosts" % slicename
378     f = open(hosts_file, 'w')
379     f.write(hosts)
380     f.close()
381     return
382
383 """
384 Write /etc/vini/egre-keys.txt, used by vsys topo scripts
385 """
386 def write_egre_keys(slicekeys):
387     vini_dir = "/etc/vini" 
388     if not os.path.exists(vini_dir):
389         try:
390             os.mkdir(vini_dir)
391         except os.error:
392             logger.log("topo: could not create %s\n" % vini_dir)
393             return
394     keys_file = "%s/egre-keys.txt" % vini_dir
395     f = open(keys_file, 'w')
396     for slice in slicekeys:
397         f.write("%s %s\n" % (slice, slicekeys[slice]))
398     f.close()
399     return
400
401
402 """
403 Executed on NM startup
404 """
405 def start():
406     # Should be taken care of by /etc/sysctl.conf, but it doesn't hurt...
407     run ("echo 1 > /proc/sys/net/ipv4/ip_forward")
408     pass
409
410
411 """
412 Update the virtual links for a sliver if it has a 'netns' attribute,
413 an 'egre_key' attribute, and a 'topo_rspec' attribute.
414
415 Creating the virtual link depends on the contents of 
416 /etc/vservers/<slice>/spaces/net.  Update this first.
417 """
418 def GetSlivers(data, config = None, plc = None):
419     global ifaces, old_ifaces
420     ifaces = old_ifaces = gifconf()
421
422     slicekeys = {}
423     for sliver in data['slivers']:
424         attrs = {}
425         for tag in sliver['attributes']:
426             attrs[tag['tagname']] = tag['value']
427             if tag['tagname'] == 'egre_key':
428                 slicekeys[sliver['name']] = tag['value']
429                 
430
431         if vserver.VServer(sliver['name']).is_running():
432             if 'netns' in attrs:
433                 netns = int(attrs['netns'])
434             else:
435                 netns = 0
436             write_spaces_net(sliver['name'], netns)
437
438         if vserver.VServer(sliver['name']).is_running():
439             if 'egre_key' in attrs:
440                 logger.log("topo: Update slice %s" % sliver['name'])
441                 update_nat(sliver['name'], data['node_id'], attrs['egre_key'],
442                            netns)
443                 if 'topo_rspec' in attrs:
444                     update_links(sliver['name'], data['node_id'], 
445                                 attrs['topo_rspec'], attrs['egre_key'], netns)
446                     update_quagga_configs(sliver['name'], data['hostname'],
447                                 data['node_id'], attrs['topo_rspec'], 
448                                 attrs['egre_key'], netns)
449             if 'hosts' in attrs:
450                 update_hosts(sliver['name'], attrs['hosts'])
451         else:
452             logger.log("topo: sliver %s not running yet. Deferring." % \
453                            sliver['name'])
454
455     clean_up_old_virtual_links()
456     write_egre_keys(slicekeys)
457     return
458
459