Convert RSpec sliver attributes to slice tags
[sfa.git] / sfa / plc / network.py
1 from __future__ import with_statement
2 import re
3 import socket
4 from sfa.util.namespace import *
5 from sfa.util.faults import *
6 from xmlbuilder import XMLBuilder
7 from lxml import etree
8 import sys
9 from StringIO import StringIO
10
11
12 class Sliver:
13     def __init__(self, node):
14         self.node = node
15         self.network = node.network
16         self.slice = node.network.slice
17         
18     def toxml(self, xml):
19         with xml.sliver:
20             self.slice.tags_to_xml(xml, self.node)
21
22         
23 class Iface:
24     def __init__(self, network, iface):
25         self.network = network
26         self.id = iface['interface_id']
27         self.idtag = "i%s" % self.id
28         self.ipv4 = iface['ip']
29         self.bwlimit = iface['bwlimit']
30         self.hostname = iface['hostname']
31
32     """
33     Just print out bwlimit right now
34     """
35     def toxml(self, xml):
36         if self.bwlimit:
37             with xml.bw_limit(units="kbps"):
38                 xml << str(self.bwlimit / 1000)
39
40
41 class Node:
42     def __init__(self, network, node, bps = 1000 * 1000000):
43         self.network = network
44         self.id = node['node_id']
45         self.idtag = "n%s" % self.id
46         self.hostname = node['hostname']
47         self.site_id = node['site_id']
48         self.iface_ids = node['interface_ids']
49         self.sliver = None
50         self.whitelist = node['slice_ids_whitelist']
51
52     def get_ifaces(self):
53         i = []
54         for id in self.iface_ids:
55             i.append(self.network.lookupIface(id))
56             # Only return the first interface
57             break
58         return i
59         
60     def get_site(self):
61         return self.network.lookupSite(self.site_id)
62     
63     def add_sliver(self):
64         self.sliver = Sliver(self)
65
66     def toxml(self, xml):
67         slice = self.network.slice
68         if self.whitelist and not self.sliver:
69             if not slice or slice.id not in self.whitelist:
70                 return
71
72         with xml.node(id = self.idtag):
73             with xml.hostname:
74                 xml << self.hostname
75             if self.network.type == "VINI":
76                 with xml.kbps:
77                     xml << str(int(self.bps/1000))
78             for iface in self.get_ifaces():
79                 iface.toxml(xml)
80             if self.sliver:
81                 self.sliver.toxml(xml)
82     
83
84 class Site:
85     def __init__(self, network, site):
86         self.network = network
87         self.id = site['site_id']
88         self.idtag = "s%s" % self.id
89         self.node_ids = site['node_ids']
90         self.node_ids.sort()
91         self.name = site['abbreviated_name']
92         self.tag = site['login_base']
93         self.public = site['is_public']
94         self.enabled = site['enabled']
95         self.links = set()
96         self.whitelist = False
97
98     def get_sitenodes(self):
99         n = []
100         for i in self.node_ids:
101             n.append(self.network.lookupNode(i))
102         return n
103     
104     def toxml(self, xml):
105         if not (self.public and self.enabled and self.node_ids):
106             return
107         with xml.site(id = self.idtag):
108             with xml.name:
109                 xml << self.name
110             for node in self.get_sitenodes():
111                 node.toxml(xml)
112    
113     
114 class Slice:
115     def __init__(self, network, hrn, slice):
116         self.hrn = hrn
117         self.network = network
118         self.id = slice['slice_id']
119         self.name = slice['name']
120         self.node_ids = set(slice['node_ids'])
121         self.slice_tag_ids = slice['slice_tag_ids']
122     
123     """
124     Use with tags that can have more than one instance
125     """
126     def get_multi_tag(self, tagname, node = None):
127         tags = []
128         for i in self.slice_tag_ids:
129             tag = self.network.lookupSliceTag(i)
130             if tag.tagname == tagname:
131                 if not (node and node.id != tag.node_id):
132                     tags.append(tag)
133         return tags
134         
135     """
136     Use with tags that have only one instance
137     """
138     def get_tag(self, tagname, node = None):
139         for i in self.slice_tag_ids:
140             tag = self.network.lookupSliceTag(i)
141             if tag.tagname == tagname:
142                 if (not node) or (node.id == tag.node_id):
143                     return tag
144         return None
145         
146     def get_nodes(self):
147         n = []
148         for id in self.node_ids:
149             n.append(self.network.nodes[id])
150         return n
151   
152     # Add a new slice tag   
153     def add_tag(self, tagname, value, node = None):
154         record = {'slice_tag_id':None, 'slice_id':self.id, 'tagname':tagname, 'value':value}
155         if node:
156             record['node_id'] = node.id
157         else:
158             record['node_id'] = None
159         tag = Slicetag(record)
160         self.network.tags[tag.id] = tag
161         self.slice_tag_ids.append(tag.id)
162         tag.changed = True       
163         tag.updated = True
164         return tag
165     
166     # Update a slice tag if it exists, else add it             
167     def update_tag(self, tagname, value, node = None):
168         tag = self.get_tag(tagname, node)
169         if tag and tag.value == value:
170             value = "no change"
171         elif tag:
172             tag.value = value
173             tag.changed = True
174         else:
175             tag = self.add_tag(tagname, value, node)
176         tag.updated = True
177             
178     def update_multi_tag(self, tagname, value, node = None):
179         tags = self.get_multi_tag(tagname, node)
180         for tag in tags:
181             if tag and tag.value == value:
182                 value = "no change"
183                 break
184         else:
185             tag = self.add_tag(tagname, value, node)
186         tag.updated = True
187             
188     def tags_to_xml(self, xml, node = None):
189         tagtypes = self.network.getTagTypes()
190         for tt in tagtypes:
191             if tt.multi:
192                 tags = self.get_multi_tag(tt.tagname, node)
193                 for tag in tags:
194                     xml << (tag.tagname, tag.value)
195             else:
196                 tag = self.get_tag(tt.tagname, node)
197                 if tag:
198                     xml << (tag.tagname, tag.value)
199
200     def toxml(self, xml):
201         with xml.sliver_defaults:
202             self.tags_to_xml(xml)
203
204
205 class Slicetag:
206     newid = -1 
207     def __init__(self, tag):
208         self.id = tag['slice_tag_id']
209         if not self.id:
210             # Make one up for the time being...
211             self.id = Slicetag.newid
212             Slicetag.newid -= 1
213         self.slice_id = tag['slice_id']
214         self.tagname = tag['tagname']
215         self.value = tag['value']
216         self.node_id = tag['node_id']
217         self.updated = False
218         self.changed = False
219         self.deleted = False
220     
221     # Mark a tag as deleted
222     def delete(self):
223         self.deleted = True
224         self.updated = True
225     
226     def write(self, api):
227         if self.changed:
228             if int(self.id) > 0:
229                 api.plshell.UpdateSliceTag(api.plauth, self.id, self.value)
230             else:
231                 api.plshell.AddSliceTag(api.plauth, self.slice_id, 
232                                         self.tagname, self.value, self.node_id)
233         elif self.deleted and int(self.id) > 0:
234             api.plshell.DeleteSliceTag(api.plauth, self.id)
235
236
237 class TagType:
238     def __init__(self, tagtype):
239         self.id = tagtype['tag_type_id']
240         self.tagname = tagtype['tagname']
241         if self.tagname in ['codemux', 'vsys']:
242             self.multi = True
243         else:
244             self.multi = False
245
246
247 """
248 A Network is a compound object consisting of:
249 * a dictionary mapping site IDs to Site objects
250 * a dictionary mapping node IDs to Node objects
251 * a dictionary mapping interface IDs to Iface objects
252 """
253 class Network:
254     def __init__(self, api, type = "PlanetLab"):
255         self.api = api
256         self.type = type
257         self.sites = self.get_sites(api)
258         self.nodes = self.get_nodes(api)
259         self.ifaces = self.get_ifaces(api)
260         self.tags = self.get_slice_tags(api)
261         self.tagtypes = self.get_tag_types(api)
262         self.slice = None
263     
264     """ Lookup site based on id or idtag value """
265     def lookupSite(self, id):
266         val = None
267         if isinstance(id, basestring):
268             id = int(id.lstrip('s'))
269         try:
270             val = self.sites[id]
271         except:
272             raise KeyError("site ID %s not found" % id)
273         return val
274     
275     def getSites(self):
276         sites = []
277         for s in self.sites:
278             sites.append(self.sites[s])
279         return sites
280         
281     """ Lookup node based on id or idtag value """
282     def lookupNode(self, id):
283         val = None
284         if isinstance(id, basestring):
285             id = int(id.lstrip('n'))
286         try:
287             val = self.nodes[id]
288         except:
289             raise KeyError("node ID %s not found" % id)
290         return val
291     
292     def getNodes(self):
293         nodes = []
294         for n in self.nodes:
295             nodes.append(self.nodes[n])
296         return nodes
297     
298     """ Lookup iface based on id or idtag value """
299     def lookupIface(self, id):
300         val = None
301         if isinstance(id, basestring):
302             id = int(id.lstrip('i'))
303         try:
304             val = self.ifaces[id]
305         except:
306             raise KeyError("interface ID %s not found" % id)
307         return val
308     
309     def getIfaces(self):
310         ifaces = []
311         for i in self.ifaces:
312             ifaces.append(self.ifaces[i])
313         return ifaces
314     
315     def nodesWithSlivers(self):
316         nodes = []
317         for n in self.nodes:
318             node = self.nodes[n]
319             if node.sliver:
320                 nodes.append(node)
321         return nodes
322             
323     def lookupSliceTag(self, id):
324         val = None
325         try:
326             val = self.tags[id]
327         except:
328             raise KeyError("slicetag ID %s not found" % id)
329         return val
330     
331     def getSliceTags(self):
332         tags = []
333         for t in self.tags:
334             tags.append(self.tags[t])
335         return tags
336     
337     def lookupTagType(self, name):
338         val = None
339         try:
340             val = self.tagstypes[name]
341         except:
342             raise KeyError("tag %s not found" % name)
343         return val
344     
345     def getTagTypes(self):
346         tags = []
347         for t in self.tagtypes:
348             tags.append(self.tagtypes[t])
349         return tags
350     
351     def __process_attributes(self, element, node=None):
352         # Do we need to check caller's role before update???
353         tagtypes = self.GetTagTypes()
354         for tt in tagtypes:
355             if tt.multi:
356                 for e in element.iterfind("./" + tt.tagname):
357                     self.slice.update_multi_tag(tt.tagname, e.text, node)
358             else:
359                 e = element.find("./" + tt.tagname)
360                 if e:
361                     self.slice.update_tag(tt.tagname, e.text, node)
362
363     """
364     Annotate the objects in the Network with information from the RSpec
365     """
366     def addRSpec(self, xml, schema=None):
367         nodedict = {}
368         for node in self.getNodes():
369             nodedict[node.idtag] = node
370             
371         slicenodes = {}
372
373         tree = etree.parse(StringIO(xml))
374
375         if schema:
376             # Validate the incoming request against the RelaxNG schema
377             relaxng_doc = etree.parse(schema)
378             relaxng = etree.RelaxNG(relaxng_doc)
379         
380             if not relaxng(tree):
381                 error = relaxng.error_log.last_error
382                 message = "%s (line %s)" % (error.message, error.line)
383                 raise InvalidRSpec(message)
384
385         rspec = tree.getroot()
386
387         defaults = rspec.find("./network/sliver_defaults")
388         self.__process_attributes(defaults)
389
390         # Find slivers under node elements
391         for sliver in rspec.iterfind("./network/site/node/sliver"):
392             elem = sliver.getparent()
393             node = nodedict[elem.get("id")]
394             slicenodes[node.id] = node
395             node.add_sliver()
396             self.__process_attributes(sliver, node)
397
398         # Find slivers that specify nodeid
399         for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
400             node = nodedict[sliver.get("nodeid")]
401             slicenodes[node.id] = node
402             node.add_sliver()
403             self.__process_attributes(sliver, node)
404
405         return
406
407     """
408     Annotate the objects in the Network with information from the slice
409     """
410     def addSlice(self):
411         slice = self.slice
412         if not slice:
413             raise Error("no slice associated with network")
414
415         for node in slice.get_nodes():
416             node.add_sliver()
417
418     """
419     Write any slice tags that have been added or modified back to the DB
420     """
421     def updateSliceTags(self):
422         # Update slice tags in database
423         for tag in self.getSliceTags():
424             if tag.slice_id == self.slice.id:
425                 if not tag.updated:
426                     tag.delete()
427                 #tag.write(self.api)
428
429     """
430     Produce XML directly from the topology specification.
431     """
432     def toxml(self):
433         xml = XMLBuilder(format = True, tab_step = "  ")
434         with xml.RSpec(type=self.type):
435             name = "Public_" + self.type
436             if self.slice:
437                 element = xml.network(name=name, slice=self.slice.hrn)
438             else:
439                 element = xml.network(name=name)
440                 
441             with element:
442                 if self.slice:
443                     self.slice.toxml(xml)
444                 for site in self.getSites():
445                     site.toxml(xml)
446
447         header = '<?xml version="1.0"?>\n'
448         return header + str(xml)
449
450     """
451     Create a dictionary of site objects keyed by site ID
452     """
453     def get_sites(self, api):
454         tmp = []
455         for site in api.plshell.GetSites(api.plauth):
456             t = site['site_id'], Site(self, site)
457             tmp.append(t)
458         return dict(tmp)
459
460
461     """
462     Create a dictionary of node objects keyed by node ID
463     """
464     def get_nodes(self, api):
465         tmp = []
466         for node in api.plshell.GetNodes(api.plauth):
467             t = node['node_id'], Node(self, node)
468             tmp.append(t)
469         return dict(tmp)
470
471     """
472     Create a dictionary of node objects keyed by node ID
473     """
474     def get_ifaces(self, api):
475         tmp = []
476         for iface in api.plshell.GetInterfaces(api.plauth):
477             t = iface['interface_id'], Iface(self, iface)
478             tmp.append(t)
479         return dict(tmp)
480
481     """
482     Create a dictionary of slicetag objects keyed by slice tag ID
483     """
484     def get_slice_tags(self, api):
485         tmp = []
486         for tag in api.plshell.GetSliceTags(api.plauth):
487             t = tag['slice_tag_id'], Slicetag(tag)
488             tmp.append(t)
489         return dict(tmp)
490     
491     """
492     Create a list of tagtype obects keyed by tag name
493     """
494     def get_tag_types(self, api):
495         tmp = []
496         for tag in api.plshell.GetTagTypes(api.plauth):
497             t = tag['tagname'], TagType(tag)
498             tmp.append(t)
499         return dict(tmp)
500     
501     """
502     Return a Slice object for a single slice
503     """
504     def get_slice(self, api, hrn):
505         slicename = hrn_to_pl_slicename(hrn)
506         slice = api.plshell.GetSlices(api.plauth, [slicename])
507         if slice:
508             self.slice = Slice(self, slicename, slice[0])
509             return self.slice
510         else:
511             return None
512     
513