return only the rspec for the slice
[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         self.primary = iface['is_primary']
32
33     """
34     Just print out bwlimit right now
35     """
36     def toxml(self, xml):
37         if self.bwlimit:
38             with xml.bw_limit(units="kbps"):
39                 xml << str(self.bwlimit / 1000)
40
41
42 class Node:
43     def __init__(self, network, node):
44         self.network = network
45         self.id = node['node_id']
46         self.idtag = "n%s" % self.id
47         self.hostname = node['hostname']
48         self.site_id = node['site_id']
49         self.iface_ids = node['interface_ids']
50         self.sliver = None
51         self.whitelist = node['slice_ids_whitelist']
52
53     def get_primary_iface(self):
54         for id in self.iface_ids:
55             iface = self.network.lookupIface(id)
56             if iface.primary:
57                 return iface
58         return None
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             iface = self.get_primary_iface()
76             if iface:
77                 iface.toxml(xml)
78             if self.sliver:
79                 self.sliver.toxml(xml)
80     
81
82 class Site:
83     def __init__(self, network, site):
84         self.network = network
85         self.id = site['site_id']
86         self.idtag = "s%s" % self.id
87         self.node_ids = site['node_ids']
88         self.node_ids.sort()
89         self.name = site['abbreviated_name']
90         self.tag = site['login_base']
91         self.public = site['is_public']
92         self.enabled = site['enabled']
93         self.links = set()
94         self.whitelist = False
95
96     def get_sitenodes(self):
97         n = []
98         for i in self.node_ids:
99             n.append(self.network.lookupNode(i))
100         return n
101     
102     def toxml(self, xml):
103         if not (self.public and self.enabled and self.node_ids):
104             return
105         with xml.site(id = self.idtag):
106             with xml.name:
107                 xml << self.name
108             for node in self.get_sitenodes():
109                 node.toxml(xml)
110    
111     
112 class Slice:
113     def __init__(self, network, hrn, slice):
114         self.hrn = hrn
115         self.network = network
116         self.id = slice['slice_id']
117         self.name = slice['name']
118         self.peer_id = slice['peer_id']
119         self.node_ids = set(slice['node_ids'])
120         self.slice_tag_ids = slice['slice_tag_ids']
121     
122     """
123     Use with tags that can have more than one instance
124     """
125     def get_multi_tag(self, tagname, node = None):
126         tags = []
127         for i in self.slice_tag_ids:
128             tag = self.network.lookupSliceTag(i)
129             if tag.tagname == tagname:
130                 if not (node and node.id != tag.node_id):
131                     tags.append(tag)
132         return tags
133         
134     """
135     Use with tags that have only one instance
136     """
137     def get_tag(self, tagname, node = None):
138         for i in self.slice_tag_ids:
139             tag = self.network.lookupSliceTag(i)
140             if tag.tagname == tagname:
141                 if (not node) or (node.id == tag.node_id):
142                     return tag
143         return None
144         
145     def get_nodes(self):
146         n = []
147         for id in self.node_ids:
148             if id in self.network.nodes:
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, role_id = 40):
154         tt = self.network.lookupTagType(tagname)
155         if not tt.permit_update(role_id):
156             raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
157         tag = Slicetag()
158         tag.initialize(tagname, value, node, self.network)
159         self.network.tags[tag.id] = tag
160         self.slice_tag_ids.append(tag.id)
161         return tag
162     
163     # Update a slice tag if it exists, else add it             
164     def update_tag(self, tagname, value, node = None, role_id = 40):
165         tag = self.get_tag(tagname, node)
166         if tag:
167             if not tag.permit_update(role_id, value):
168                 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
169             tag.change(value)
170         else:
171             tag = self.add_tag(tagname, value, node, role_id)
172         return tag
173             
174     def update_multi_tag(self, tagname, value, node = None, role_id = 40):
175         tags = self.get_multi_tag(tagname, node)
176         for tag in tags:
177             if tag and tag.value == value:
178                 break
179         else:
180             tag = self.add_tag(tagname, value, node, role_id)
181         return tag
182             
183     def tags_to_xml(self, xml, node = None):
184         tagtypes = self.network.getTagTypes()
185         for tt in tagtypes:
186             if tt.in_rspec:
187                 if tt.multi:
188                     tags = self.get_multi_tag(tt.tagname, node)
189                     for tag in tags:
190                         if not tag.was_deleted():  ### Debugging
191                             xml << (tag.tagname, tag.value)
192                 else:
193                     tag = self.get_tag(tt.tagname, node)
194                     if tag:
195                         if not tag.was_deleted():   ### Debugging
196                             xml << (tag.tagname, 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 = None):
206         if not tag:
207             return
208         self.id = tag['slice_tag_id']
209         self.slice_id = tag['slice_id']
210         self.tagname = tag['tagname']
211         self.value = tag['value']
212         self.node_id = tag['node_id']
213         self.category = tag['category']
214         self.min_role_id = tag['min_role_id']
215         self.status = None
216
217     # Create a new slicetag that will be written to the DB later
218     def initialize(self, tagname, value, node, network):
219         tt = network.lookupTagType(tagname)
220         self.id = Slicetag.newid
221         Slicetag.newid -=1
222         self.slice_id = network.slice.id
223         self.tagname = tagname
224         self.value = value
225         if node:
226             self.node_id = node.id
227         else:
228             self.node_id = None
229         self.category = tt.category
230         self.min_role_id = tt.min_role_id
231         self.status = "new"
232
233     def permit_update(self, role_id, value = None):
234         if value and self.value == value:
235             return True
236         if role_id > self.min_role_id:
237             return False
238         return True
239         
240     def change(self, value):
241         if self.value != value:
242             self.value = value
243             self.status = "change"
244         else:
245             self.status = "updated"
246         
247     # Mark a tag as deleted
248     def delete(self):
249         self.status = "delete"
250
251     def was_added(self):
252         return (self.id < 0)
253
254     def was_changed(self):
255         return (self.status == "change")
256
257     def was_deleted(self):
258         return (self.status == "delete")
259
260     def was_updated(self):
261         return (self.status != None)
262     
263     def write(self, api):
264         if self.was_added():
265             api.plshell.AddSliceTag(api.plauth, self.slice_id, 
266                                     self.tagname, self.value, self.node_id)
267         elif self.was_changed():
268             api.plshell.UpdateSliceTag(api.plauth, self.id, self.value)
269         elif self.was_deleted():
270             api.plshell.DeleteSliceTag(api.plauth, self.id)
271
272
273 class TagType:
274     def __init__(self, tagtype):
275         self.id = tagtype['tag_type_id']
276         self.category = tagtype['category']
277         self.tagname = tagtype['tagname']
278         self.min_role_id = tagtype['min_role_id']
279         self.multi = False
280         self.in_rspec = False
281         if self.category == 'slice/rspec':
282             self.in_rspec = True
283         if self.tagname in ['codemux', 'ip_addresses', 'vsys']:
284             self.multi = True
285
286     def permit_update(self, role_id):
287         if role_id > self.min_role_id:
288             return False
289         return True
290         
291
292 """
293 A Network is a compound object consisting of:
294 * a dictionary mapping site IDs to Site objects
295 * a dictionary mapping node IDs to Node objects
296 * a dictionary mapping interface IDs to Iface objects
297 """
298 class Network:
299     def __init__(self, api, type = "SFA"):
300         self.api = api
301         self.type = type
302         self.sites = self.get_sites(api)
303         self.nodes = self.get_nodes(api)
304         self.ifaces = self.get_ifaces(api)
305         self.tags = self.get_slice_tags(api)
306         self.tagtypes = self.get_tag_types(api)
307         self.slice = None
308     
309     """ Lookup site based on id or idtag value """
310     def lookupSite(self, id):
311         val = None
312         if isinstance(id, basestring):
313             id = int(id.lstrip('s'))
314         try:
315             val = self.sites[id]
316         except:
317             raise InvalidRSpec("site ID %s not found" % id)
318         return val
319     
320     def getSites(self):
321         sites = []
322         for s in self.sites:
323             sites.append(self.sites[s])
324         return sites
325         
326     """ Lookup node based on id or idtag value """
327     def lookupNode(self, id):
328         val = None
329         if isinstance(id, basestring):
330             id = int(id.lstrip('n'))
331         try:
332             val = self.nodes[id]
333         except:
334             raise InvalidRSpec("node ID %s not found" % id)
335         return val
336     
337     def getNodes(self):
338         nodes = []
339         for n in self.nodes:
340             nodes.append(self.nodes[n])
341         return nodes
342     
343     """ Lookup iface based on id or idtag value """
344     def lookupIface(self, id):
345         val = None
346         if isinstance(id, basestring):
347             id = int(id.lstrip('i'))
348         try:
349             val = self.ifaces[id]
350         except:
351             raise InvalidRSpec("interface ID %s not found" % id)
352         return val
353     
354     def getIfaces(self):
355         ifaces = []
356         for i in self.ifaces:
357             ifaces.append(self.ifaces[i])
358         return ifaces
359     
360     def nodesWithSlivers(self):
361         nodes = []
362         for n in self.nodes:
363             node = self.nodes[n]
364             if node.sliver:
365                 nodes.append(node)
366         return nodes
367             
368     def lookupSliceTag(self, id):
369         val = None
370         try:
371             val = self.tags[id]
372         except:
373             raise InvalidRSpec("slicetag ID %s not found" % id)
374         return val
375     
376     def getSliceTags(self):
377         tags = []
378         for t in self.tags:
379             tags.append(self.tags[t])
380         return tags
381     
382     def lookupTagType(self, name):
383         val = None
384         try:
385             val = self.tagtypes[name]
386         except:
387             raise InvalidRSpec("tag %s not found" % name)
388         return val
389     
390     def getTagTypes(self):
391         tags = []
392         for t in self.tagtypes:
393             tags.append(self.tagtypes[t])
394         return tags
395     
396     """
397     Process the elements under <sliver_defaults> or <sliver>
398     """
399     def __process_attributes(self, element, node=None):
400         if element is None:
401             return 
402
403         tagtypes = self.getTagTypes()
404         for tt in tagtypes:
405             if tt.in_rspec:
406                 if tt.multi:
407                     for e in element.iterfind("./" + tt.tagname):
408                         self.slice.update_multi_tag(tt.tagname, e.text, node)
409                 else:
410                     e = element.find("./" + tt.tagname)
411                     if e is not None:
412                         self.slice.update_tag(tt.tagname, e.text, node)
413
414     """
415     Annotate the objects in the Network with information from the RSpec
416     """
417     def addRSpec(self, xml, schema=None):
418         try:
419             tree = etree.parse(StringIO(xml))
420         except etree.XMLSyntaxError:
421             message = str(sys.exc_info()[1])
422             raise InvalidRSpec(message)
423
424         # Filter out stuff that's not for us
425         rspec = tree.getroot()
426         for network in rspec.iterfind("./network"):
427             if network.get("name") != self.api.hrn:
428                 rspec.remove(network)
429         for request in rspec.iterfind("./request"):
430             if request.get("name") != self.api.hrn:
431                 rspec.remove(request)
432
433         if schema:
434             # Validate the incoming request against the RelaxNG schema
435             relaxng_doc = etree.parse(schema)
436             relaxng = etree.RelaxNG(relaxng_doc)
437         
438             if not relaxng(tree):
439                 error = relaxng.error_log.last_error
440                 message = "%s (line %s)" % (error.message, error.line)
441                 raise InvalidRSpec(message)
442
443         self.rspec = rspec
444
445         defaults = rspec.find(".//sliver_defaults")
446         self.__process_attributes(defaults)
447
448         # Find slivers under node elements
449         for sliver in rspec.iterfind("./network/site/node/sliver"):
450             elem = sliver.getparent()
451             try:
452                 node = self.lookupNode(elem.get("id"))
453             except:
454                 # Don't worry about nodes from other aggregates
455                 pass
456             else:
457                 node.add_sliver()
458                 self.__process_attributes(sliver, node)
459
460         # Find slivers that specify nodeid
461         for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
462             try:
463                 node = self.lookupNode(sliver.get("nodeid"))
464             except:
465                 # Don't worry about nodes from other aggregates
466                 pass
467             else:
468                 node.add_sliver()
469                 self.__process_attributes(sliver, node)
470
471         return
472
473     """
474     Annotate the objects in the Network with information from the slice
475     """
476     def addSlice(self):
477         slice = self.slice
478         if not slice:
479             raise InvalidRSpec("no slice associated with network")
480
481         for node in slice.get_nodes():
482             node.add_sliver()
483
484     """
485     Write any slice tags that have been added or modified back to the DB
486     """
487     def updateSliceTags(self):
488         for tag in self.getSliceTags():
489             if tag.category == 'slice/rspec' and not tag.was_updated() and tag.permit_update(None, 40):
490                 # The user wants to delete this tag
491                 tag.delete()
492
493         # Update slice tags in database
494         for tag in self.getSliceTags():
495             if tag.slice_id == self.slice.id:
496                 tag.write(self.api) 
497
498     """
499     Produce XML directly from the topology specification.
500     """
501     def toxml(self):
502         xml = XMLBuilder(format = True, tab_step = "  ")
503         with xml.RSpec(type=self.type):
504             if self.slice:
505                 element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
506             else:
507                 element = xml.network(name=self.api.hrn)
508                 
509             with element:
510                 if self.slice:
511                     self.slice.toxml(xml)
512                 else:
513                     for site in self.getSites():
514                         site.toxml(xml)
515
516         header = '<?xml version="1.0"?>\n'
517         return header + str(xml)
518
519     """
520     Create a dictionary of site objects keyed by site ID
521     """
522     def get_sites(self, api):
523         tmp = []
524         for site in api.plshell.GetSites(api.plauth, {'peer_id': None}):
525             t = site['site_id'], Site(self, site)
526             tmp.append(t)
527         return dict(tmp)
528
529
530     """
531     Create a dictionary of node objects keyed by node ID
532     """
533     def get_nodes(self, api):
534         tmp = []
535         for node in api.plshell.GetNodes(api.plauth, {'peer_id': None}):
536             t = node['node_id'], Node(self, node)
537             tmp.append(t)
538         return dict(tmp)
539
540     """
541     Create a dictionary of node objects keyed by node ID
542     """
543     def get_ifaces(self, api):
544         tmp = []
545         for iface in api.plshell.GetInterfaces(api.plauth):
546             t = iface['interface_id'], Iface(self, iface)
547             tmp.append(t)
548         return dict(tmp)
549
550     """
551     Create a dictionary of slicetag objects keyed by slice tag ID
552     """
553     def get_slice_tags(self, api):
554         tmp = []
555         for tag in api.plshell.GetSliceTags(api.plauth):
556             t = tag['slice_tag_id'], Slicetag(tag)
557             tmp.append(t)
558         return dict(tmp)
559     
560     """
561     Create a list of tagtype obects keyed by tag name
562     """
563     def get_tag_types(self, api):
564         tmp = []
565         for tag in api.plshell.GetTagTypes(api.plauth):
566             t = tag['tagname'], TagType(tag)
567             tmp.append(t)
568         return dict(tmp)
569     
570     """
571     Return a Slice object for a single slice
572     """
573     def get_slice(self, api, hrn):
574         slicename = hrn_to_pl_slicename(hrn)
575         slice = api.plshell.GetSlices(api.plauth, [slicename])
576         if len(slice):
577             self.slice = Slice(self, slicename, slice[0])
578             return self.slice
579         else:
580             return None
581     
582