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