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         tag = self.get_tag("cpu_pct", node)
190         if tag:
191             with xml.cpu_percent:
192                 xml << tag.value
193         tags = self.get_multi_tag("vsys", node)
194         for tag in tags:
195             with xml.vsys:
196                 xml << tag.value
197
198     def toxml(self, xml):
199         with xml.sliver_defaults:
200             self.tags_to_xml(xml)
201
202
203 class Slicetag:
204     newid = -1 
205     def __init__(self, tag):
206         self.id = tag['slice_tag_id']
207         if not self.id:
208             # Make one up for the time being...
209             self.id = Slicetag.newid
210             Slicetag.newid -= 1
211         self.slice_id = tag['slice_id']
212         self.tagname = tag['tagname']
213         self.value = tag['value']
214         self.node_id = tag['node_id']
215         self.updated = False
216         self.changed = False
217         self.deleted = False
218     
219     # Mark a tag as deleted
220     def delete(self):
221         self.deleted = True
222         self.updated = True
223     
224     def write(self, api):
225         if self.changed:
226             if int(self.id) > 0:
227                 api.plshell.UpdateSliceTag(api.plauth, self.id, self.value)
228             else:
229                 api.plshell.AddSliceTag(api.plauth, self.slice_id, 
230                                         self.tagname, self.value, self.node_id)
231         elif self.deleted and int(self.id) > 0:
232             api.plshell.DeleteSliceTag(api.plauth, self.id)
233
234
235 """
236 A Network is a compound object consisting of:
237 * a dictionary mapping site IDs to Site objects
238 * a dictionary mapping node IDs to Node objects
239 * a dictionary mapping interface IDs to Iface objects
240 """
241 class Network:
242     def __init__(self, api, type = "PlanetLab"):
243         self.api = api
244         self.type = type
245         self.sites = self.get_sites(api)
246         self.nodes = self.get_nodes(api)
247         self.ifaces = self.get_ifaces(api)
248         self.tags = self.get_slice_tags(api)
249         self.slice = None
250     
251     """ Lookup site based on id or idtag value """
252     def lookupSite(self, id):
253         val = None
254         if isinstance(id, basestring):
255             id = int(id.lstrip('s'))
256         try:
257             val = self.sites[id]
258         except:
259             raise KeyError("site ID %s not found" % id)
260         return val
261     
262     def getSites(self):
263         sites = []
264         for s in self.sites:
265             sites.append(self.sites[s])
266         return sites
267         
268     """ Lookup node based on id or idtag value """
269     def lookupNode(self, id):
270         val = None
271         if isinstance(id, basestring):
272             id = int(id.lstrip('n'))
273         try:
274             val = self.nodes[id]
275         except:
276             raise KeyError("node ID %s not found" % id)
277         return val
278     
279     def getNodes(self):
280         nodes = []
281         for n in self.nodes:
282             nodes.append(self.nodes[n])
283         return nodes
284     
285     """ Lookup iface based on id or idtag value """
286     def lookupIface(self, id):
287         val = None
288         if isinstance(id, basestring):
289             id = int(id.lstrip('i'))
290         try:
291             val = self.ifaces[id]
292         except:
293             raise KeyError("interface ID %s not found" % id)
294         return val
295     
296     def getIfaces(self):
297         ifaces = []
298         for i in self.ifaces:
299             ifaces.append(self.ifaces[i])
300         return ifaces
301     
302     def nodesWithSlivers(self):
303         nodes = []
304         for n in self.nodes:
305             node = self.nodes[n]
306             if node.sliver:
307                 nodes.append(node)
308         return nodes
309             
310     def lookupSliceTag(self, id):
311         val = None
312         try:
313             val = self.tags[id]
314         except:
315             raise KeyError("slicetag ID %s not found" % id)
316         return val
317     
318     def getSliceTags(self):
319         tags = []
320         for t in self.tags:
321             tags.append(self.tags[t])
322         return tags
323     
324
325     def __process_attributes(self, element, node=None):
326         for e in element.iterfind("./vsys"):
327             self.slice.update_multi_tag("vsys", e.text, node)
328             
329
330     """
331     Annotate the objects in the Network with information from the RSpec
332     """
333     def addRSpec(self, xml, schema=None):
334         nodedict = {}
335         for node in self.getNodes():
336             nodedict[node.idtag] = node
337             
338         slicenodes = {}
339
340         tree = etree.parse(StringIO(xml))
341
342         if schema:
343             # Validate the incoming request against the RelaxNG schema
344             relaxng_doc = etree.parse(schema)
345             relaxng = etree.RelaxNG(relaxng_doc)
346         
347             if not relaxng(tree):
348                 error = relaxng.error_log.last_error
349                 message = "%s (line %s)" % (error.message, error.line)
350                 raise InvalidRSpec(message)
351
352         rspec = tree.getroot()
353
354         defaults = rspec.find("./network/sliver_defaults")
355         self.__process_attributes(defaults)
356
357         # Find slivers under node elements
358         for sliver in rspec.iterfind("./network/site/node/sliver"):
359             elem = sliver.getparent()
360             node = nodedict[elem.get("id")]
361             slicenodes[node.id] = node
362             node.add_sliver()
363             self.__process_attributes(sliver, node)
364
365         # Find slivers that specify nodeid
366         for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
367             node = nodedict[sliver.get("nodeid")]
368             slicenodes[node.id] = node
369             node.add_sliver()
370             self.__process_attributes(sliver, node)
371
372         return
373
374     """
375     Annotate the objects in the Network with information from the slice
376     """
377     def addSlice(self):
378         slice = self.slice
379         if not slice:
380             raise Error("no slice associated with network")
381
382         for node in slice.get_nodes():
383             node.add_sliver()
384
385     """
386     Write any slice tags that have been added or modified back to the DB
387     """
388     def updateSliceTags(self):
389         # Update slice tags in database
390         for tag in self.getSliceTags():
391             if tag.slice_id == self.slice.id:
392                 if not tag.updated:
393                     tag.delete()
394                 #tag.write(self.api)
395
396     """
397     Produce XML directly from the topology specification.
398     """
399     def toxml(self):
400         xml = XMLBuilder(format = True, tab_step = "  ")
401         with xml.RSpec(type=self.type):
402             name = "Public_" + self.type
403             if self.slice:
404                 element = xml.network(name=name, slice=self.slice.hrn)
405             else:
406                 element = xml.network(name=name)
407                 
408             with element:
409                 if self.slice:
410                     self.slice.toxml(xml)
411                 for site in self.getSites():
412                     site.toxml(xml)
413
414         header = '<?xml version="1.0"?>\n'
415         return header + str(xml)
416
417     """
418     Create a dictionary of site objects keyed by site ID
419     """
420     def get_sites(self, api):
421         tmp = []
422         for site in api.plshell.GetSites(api.plauth):
423             t = site['site_id'], Site(self, site)
424             tmp.append(t)
425         return dict(tmp)
426
427
428     """
429     Create a dictionary of node objects keyed by node ID
430     """
431     def get_nodes(self, api):
432         tmp = []
433         for node in api.plshell.GetNodes(api.plauth):
434             t = node['node_id'], Node(self, node)
435             tmp.append(t)
436         return dict(tmp)
437
438     """
439     Create a dictionary of node objects keyed by node ID
440     """
441     def get_ifaces(self, api):
442         tmp = []
443         for iface in api.plshell.GetInterfaces(api.plauth):
444             t = iface['interface_id'], Iface(self, iface)
445             tmp.append(t)
446         return dict(tmp)
447
448     """
449     Create a dictionary of slicetag objects keyed by slice tag ID
450     """
451     def get_slice_tags(self, api):
452         tmp = []
453         for tag in api.plshell.GetSliceTags(api.plauth):
454             t = tag['slice_tag_id'], Slicetag(tag)
455             tmp.append(t)
456         return dict(tmp)
457     
458     """
459     Return a Slice object for a single slice
460     """
461     def get_slice(self, api, hrn):
462         slicename = hrn_to_pl_slicename(hrn)
463         slice = api.plshell.GetSlices(api.plauth, [slicename])
464         if slice:
465             self.slice = Slice(self, slicename, slice[0])
466             return self.slice
467         else:
468             return None
469     
470