Restart the veserver if spaces/net changes
[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 = m.group(1)
139             node = m.group(2)
140             teardown_virtual_link(key, node)
141
142         m = re.match(pattern2, iface)
143         if m:
144             key = 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
171 """
172 Update NAT interface for the slice
173 """
174 def update_nat(slice, myid, key, netns):
175     if not nat_exists(key):
176         if netns:
177             setup_nat(slice, myid, key)
178     else:
179         logger.log("%s: NAT exists" % slice)
180         refresh_nat(key)
181
182
183 """
184 Write /etc/vservers/<slicename>/spaces/net.  
185 Restart the vserver if there are any changes.
186 """
187 def write_spaces_net(slicename, value):
188     SLICEDIR="/etc/vservers/%s/" % slicename
189     SPACESDIR="%s/spaces/" % SLICEDIR
190     FILENAME="%s/net" % SPACESDIR
191     if os.path.exists(SLICEDIR):
192         if not os.path.exists(SPACESDIR):
193             try:
194                 os.mkdir(SPACESDIR)
195             except os.error:
196                 logger.log("topo: could not create %s\n" % SPACESDIR)
197                 return
198             
199         if os.path.exists(FILENAME) != value:
200             sliver = vserver.VServer(slicename)
201             
202             sliver.stop()
203
204             if value:
205                 STATUS="ON"
206                 f = open(FILENAME, "w")
207                 f.close()
208             else:
209                 STATUS="OFF"
210                 os.remove(FILENAME)
211
212             sliver.start()
213
214             logger.log("%s: network namespace %s\n" % (slicename, STATUS))
215
216
217 """
218 Generate information for each interface in the sliver, in order to configure
219 Quagga.
220 """
221 def get_ifaces(hostname, myid, topospec, key):
222     ifaces = {}
223     topolist = convert_topospec_to_list(topospec)
224     for (nodeid, ipaddr, rate, myvirtip, remvirtip, virtnet) in topolist:
225         name = "a%sx%s" % (key, nodeid)
226         ifaces[name] = {}
227         ifaces[name]['remote-ip'] = remvirtip
228         ifaces[name]['local-ip'] = myvirtip
229         ifaces[name]['network'] = virtnet
230         ifaces[name]['short-name'] = hostname.replace('.vini-veritas.net', '')
231     return ifaces
232
233
234 def write_header(f, myname, password):
235     f.write ("""! Configuration for %s
236 ! Generated at %s
237
238 hostname %s
239 password %s
240
241 """ % (myname, strftime("%Y-%m-%d %H:%M:%S"), myname, password))
242     return
243
244
245 """
246 IP address of NAT gateway to outside world
247 """
248 def nat_gw(key):
249     return "10.0.%s.1" %  key
250
251 """
252 IP address of the NAT interface inside the slice
253 """
254 def nat_inner(key):
255     return "10.0.%s.2" % key
256
257
258 """
259 Write zebra.conf file for Quagga
260 """
261 def write_zebra(filename, myname, ifaces, myid, key):
262     f = open(filename, 'w')
263     password = "zebra"
264     write_header(f, myname, password)
265
266     f.write ("enable password %s\n" % password)
267
268     for name in ifaces:
269         f.write ("""!     
270 interface %s
271 link-detect
272 """ %  name)
273
274     f.write ("""!
275 access-list vty permit 127.0.0.1/32
276 !
277 line vty
278 !
279 """)
280     f.close()
281     return
282
283
284 """
285 Write ospfd.conf file for Quagga.  
286 """
287 def write_ospf(filename, myname, ifaces):
288     f = open(filename, 'w')
289     password = "zebra"
290     write_header(f, myname, password)
291     name = None
292
293     for name in ifaces:
294         f.write ("""!
295      interface %s
296      ip ospf cost 10
297      ip ospf hello-interval 5
298      ip ospf dead-interval 10
299      ip ospf network non-broadcast
300 """ % name)
301
302     if name:
303         f.write ("""!
304      router ospf
305      ospf router-id %s
306 """ % ifaces[name]['local-ip'])
307
308     for name in ifaces:
309         f.write ("     neighbor %s\n" % ifaces[name]['remote-ip'])
310
311     for name in ifaces:
312         net = ifaces[name]['network']
313         f.write ("     network %s area 0\n" % net)
314
315     f.write("""     redistribute kernel
316 !
317 access-list vty permit 127.0.0.1/32
318 !
319 line vty
320 """)
321     return
322
323
324 """
325 Write config files directly into the slice's file system.
326 """
327 def update_quagga_configs(slicename, hostname, myid, topo, key, netns):
328     ifaces = get_ifaces(hostname, myid, topo, key)
329
330     quagga_dir = "/vservers/%s/etc/quagga/" % slicename
331     if not os.path.exists(quagga_dir):
332         try:
333             os.mkdir(quagga_dir)
334         except os.error:
335             logger.log("topo: could not create %s\n" % quagga_dir)
336             return
337
338     write_zebra(quagga_dir + "zebra.conf.generated", hostname, ifaces, 
339                 myid, key)
340     write_ospf(quagga_dir + "ospfd.conf.generated", hostname, ifaces)
341
342     return
343
344
345 """
346 Write /etc/hosts in the sliver
347 """
348 def update_hosts(slicename, hosts):
349     hosts_file = "/vservers/%s/etc/hosts" % slicename
350     f = open(hosts_file, 'w')
351     f.write(hosts)
352     f.close()
353     return
354
355 """
356 Write /etc/vini/egre-keys.txt, used by vsys topo scripts
357 """
358 def write_egre_keys(slicekeys):
359     vini_dir = "/etc/vini" 
360     if not os.path.exists(vini_dir):
361         try:
362             os.mkdir(vini_dir)
363         except os.error:
364             logger.log("topo: could not create %s\n" % vini_dir)
365             return
366     keys_file = "%s/egre-keys.txt" % vini_dir
367     f = open(keys_file, 'w')
368     for slice in slicekeys:
369         f.write("%s %s\n" % (slice, slicekeys[slice]))
370     f.close()
371     return
372
373
374 """
375 Executed on NM startup
376 """
377 def start(options, config):
378     # Should be taken care of by /etc/sysctl.conf, but it doesn't hurt...
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, config = None, plc = None):
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 vserver.VServer(sliver['name']).is_running():
404             if 'netns' in attrs:
405                 netns = int(attrs['netns'])
406             else:
407                 netns = 0
408             write_spaces_net(sliver['name'], netns)
409
410         if vserver.VServer(sliver['name']).is_running():
411             if 'egre_key' in attrs:
412                 logger.log("topo: Update slice %s" % sliver['name'])
413                 update_nat(sliver['name'], data['node_id'], attrs['egre_key'],
414                            netns)
415                 if 'topo_rspec' in attrs:
416                     update_links(sliver['name'], data['node_id'], 
417                                 attrs['topo_rspec'], attrs['egre_key'], netns)
418                     update_quagga_configs(sliver['name'], data['hostname'],
419                                 data['node_id'], attrs['topo_rspec'], 
420                                 attrs['egre_key'], netns)
421             if 'hosts' in attrs:
422                 update_hosts(sliver['name'], attrs['hosts'])
423         else:
424             logger.log("topo: sliver %s not running yet. Deferring." % \
425                            sliver['name'])
426
427     clean_up_old_virtual_links()
428     write_egre_keys(slicekeys)
429     return
430
431