1 from __future__ import with_statement
4 from sfa.util.namespace import *
5 from sfa.util.faults import *
6 from xmlbuilder import XMLBuilder
9 from StringIO import StringIO
13 def __init__(self, node):
15 self.network = node.network
16 self.slice = node.network.slice
20 self.slice.tags_to_xml(xml, self.node)
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']
34 Just print out bwlimit right now
38 with xml.bw_limit(units="kbps"):
39 xml << str(self.bwlimit / 1000)
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']
51 self.whitelist = node['slice_ids_whitelist']
53 def get_primary_iface(self):
54 for id in self.iface_ids:
55 iface = self.network.lookupIface(id)
61 return self.network.lookupSite(self.site_id)
64 self.sliver = Sliver(self)
67 slice = self.network.slice
68 if self.whitelist and not self.sliver:
69 if not slice or slice.id not in self.whitelist:
72 with xml.node(id = self.idtag):
75 iface = self.get_primary_iface()
79 self.sliver.toxml(xml)
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']
89 self.name = site['abbreviated_name']
90 self.tag = site['login_base']
91 self.public = site['is_public']
92 self.enabled = site['enabled']
94 self.whitelist = False
96 def get_sitenodes(self):
98 for i in self.node_ids:
99 n.append(self.network.lookupNode(i))
102 def toxml(self, xml):
103 if not (self.public and self.enabled and self.node_ids):
105 with xml.site(id = self.idtag):
108 for node in self.get_sitenodes():
113 def __init__(self, network, hrn, slice):
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']
123 Use with tags that can have more than one instance
125 def get_multi_tag(self, tagname, node = None):
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):
135 Use with tags that have only one instance
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):
147 for id in self.node_ids:
148 if id in self.network.nodes:
149 n.append(self.network.nodes[id])
152 # Add a new slice tag
153 def add_tag(self, tagname, value, node = None):
154 tt = self.network.lookupTagType(tagname)
156 tag.initialize(tagname, value, node, self.network)
157 self.network.tags[tag.id] = tag
158 self.slice_tag_ids.append(tag.id)
161 # Update a slice tag if it exists, else add it
162 def update_tag(self, tagname, value, node = None):
163 tag = self.get_tag(tagname, node)
167 tag = self.add_tag(tagname, value, node)
170 def update_multi_tag(self, tagname, value, node = None):
171 tags = self.get_multi_tag(tagname, node)
173 if tag and tag.value == value:
176 tag = self.add_tag(tagname, value, node)
179 def tags_to_xml(self, xml, node = None):
180 tagtypes = self.network.getTagTypes()
184 tags = self.get_multi_tag(tt.tagname, node)
186 if not tag.was_deleted(): ### Debugging
187 xml << (tag.tagname, tag.value)
189 tag = self.get_tag(tt.tagname, node)
191 if not tag.was_deleted(): ### Debugging
192 xml << (tag.tagname, tag.value)
194 def toxml(self, xml):
195 with xml.sliver_defaults:
196 self.tags_to_xml(xml)
201 filter_fields = ['slice_tag_id','slice_id','tagname','value','node_id','category','min_role_id']
202 ignore_tags = ['hmac','ssh_key']
204 def __init__(self, tag = None):
207 self.id = tag['slice_tag_id']
208 self.slice_id = tag['slice_id']
209 self.tagname = tag['tagname']
210 self.value = tag['value']
211 self.node_id = tag['node_id']
212 self.category = tag['category']
215 # Create a new slicetag that will be written to the DB later
216 def initialize(self, tagname, value, node, network):
217 tt = network.lookupTagType(tagname)
218 self.id = Slicetag.newid
220 self.slice_id = network.slice.id
221 self.tagname = tagname
224 self.node_id = node.id
227 self.category = tt.category
230 def change(self, value):
231 if self.value != value:
233 self.status = "change"
235 self.status = "updated"
237 # Mark a tag as deleted
239 self.status = "delete"
244 def was_changed(self):
245 return (self.status == "change")
247 def was_deleted(self):
248 return (self.status == "delete")
250 def was_updated(self):
251 return (self.status != None)
253 def write(self, api, user_plauth):
256 api.plshell.AddSliceTag(user_plauth, self.slice_id,
257 self.tagname, self.value, self.node_id)
258 elif self.was_changed():
259 api.plshell.UpdateSliceTag(user_plauth, self.id, self.value)
260 elif self.was_deleted():
261 api.plshell.DeleteSliceTag(user_plauth, self.id)
263 raise InvalidRSpec("user cannot modify '%s' tag" % self.tagname)
268 def __init__(self, tagtype):
269 self.id = tagtype['tag_type_id']
270 self.category = tagtype['category']
271 self.tagname = tagtype['tagname']
273 self.in_rspec = False
274 if self.category == 'slice/rspec':
276 if self.tagname in ['codemux', 'ip_addresses', 'vsys']:
282 A Network is a compound object consisting of:
283 * a dictionary mapping site IDs to Site objects
284 * a dictionary mapping node IDs to Node objects
285 * a dictionary mapping interface IDs to Iface objects
287 def __init__(self, api, user_plauth, type = "SFA"):
289 self.user_plauth = user_plauth
291 self.sites = self.get_sites(api)
292 self.nodes = self.get_nodes(api)
293 self.ifaces = self.get_ifaces(api)
294 self.tags = self.get_slice_tags(api)
295 self.tagtypes = self.get_tag_types(api)
298 def lookupSite(self, id):
299 """ Lookup site based on id or idtag value """
301 if isinstance(id, basestring):
302 id = int(id.lstrip('s'))
306 raise InvalidRSpec("site ID %s not found" % id)
312 sites.append(self.sites[s])
315 def lookupNode(self, id):
316 """ Lookup node based on id or idtag value """
318 if isinstance(id, basestring):
319 id = int(id.lstrip('n'))
323 raise InvalidRSpec("node ID %s not found" % id)
329 nodes.append(self.nodes[n])
332 def lookupIface(self, id):
333 """ Lookup iface based on id or idtag value """
335 if isinstance(id, basestring):
336 id = int(id.lstrip('i'))
338 val = self.ifaces[id]
340 raise InvalidRSpec("interface ID %s not found" % id)
345 for i in self.ifaces:
346 ifaces.append(self.ifaces[i])
349 def nodesWithSlivers(self):
357 def lookupSliceTag(self, id):
362 raise InvalidRSpec("slicetag ID %s not found" % id)
365 def getSliceTags(self):
368 tags.append(self.tags[t])
371 def lookupTagType(self, name):
374 val = self.tagtypes[name]
376 raise InvalidRSpec("tag %s not found" % name)
379 def getTagTypes(self):
381 for t in self.tagtypes:
382 tags.append(self.tagtypes[t])
385 def __process_attributes(self, element, node=None):
387 Process the elements under <sliver_defaults> or <sliver>
392 tagtypes = self.getTagTypes()
396 for e in element.iterfind("./" + tt.tagname):
397 self.slice.update_multi_tag(tt.tagname, e.text, node)
399 e = element.find("./" + tt.tagname)
401 self.slice.update_tag(tt.tagname, e.text, node)
403 def addRSpec(self, xml, schema=None):
405 Annotate the objects in the Network with information from the RSpec
408 tree = etree.parse(StringIO(xml))
409 except etree.XMLSyntaxError:
410 message = str(sys.exc_info()[1])
411 raise InvalidRSpec(message)
413 # Filter out stuff that's not for us
414 rspec = tree.getroot()
415 for network in rspec.iterfind("./network"):
416 if network.get("name") != self.api.hrn:
417 rspec.remove(network)
418 for request in rspec.iterfind("./request"):
419 if request.get("name") != self.api.hrn:
420 rspec.remove(request)
423 # Validate the incoming request against the RelaxNG schema
424 relaxng_doc = etree.parse(schema)
425 relaxng = etree.RelaxNG(relaxng_doc)
427 if not relaxng(tree):
428 error = relaxng.error_log.last_error
429 message = "%s (line %s)" % (error.message, error.line)
430 raise InvalidRSpec(message)
434 defaults = rspec.find(".//sliver_defaults")
435 self.__process_attributes(defaults)
437 # Find slivers under node elements
438 for sliver in rspec.iterfind("./network/site/node/sliver"):
439 elem = sliver.getparent()
441 node = self.lookupNode(elem.get("id"))
443 # Don't worry about nodes from other aggregates
447 self.__process_attributes(sliver, node)
449 # Find slivers that specify nodeid
450 for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
452 node = self.lookupNode(sliver.get("nodeid"))
454 # Don't worry about nodes from other aggregates
458 self.__process_attributes(sliver, node)
464 Annotate the objects in the Network with information from the slice
468 raise InvalidRSpec("no slice associated with network")
470 for node in slice.get_nodes():
473 def updateSliceTags(self):
475 Write any slice tags that have been added or modified back to the DB
477 for tag in self.getSliceTags():
478 if tag.category == 'slice/rspec' and not tag.was_updated():
479 # The user wants to delete this tag
482 # Update slice tags in database
483 for tag in self.getSliceTags():
484 if tag.slice_id == self.slice.id:
485 tag.write(self.api, self.user_plauth)
489 Produce XML directly from the topology specification.
491 xml = XMLBuilder(format = True, tab_step = " ")
492 with xml.RSpec(type=self.type):
494 element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
496 element = xml.network(name=self.api.hrn)
500 self.slice.toxml(xml)
501 for site in self.getSites():
504 header = '<?xml version="1.0"?>\n'
505 return header + str(xml)
507 def get_sites(self, api):
509 Create a dictionary of site objects keyed by site ID
512 for site in api.plshell.GetSites(self.user_plauth, {'peer_id': None}):
513 t = site['site_id'], Site(self, site)
519 def get_nodes(self, api):
521 Create a dictionary of node objects keyed by node ID
524 for node in api.plshell.GetNodes(self.user_plauth, {'peer_id': None}):
525 t = node['node_id'], Node(self, node)
529 def get_ifaces(self, api):
531 Create a dictionary of node objects keyed by node ID
534 for iface in api.plshell.GetInterfaces(self.user_plauth):
535 t = iface['interface_id'], Iface(self, iface)
539 def get_slice_tags(self, api):
541 Create a dictionary of slicetag objects keyed by slice tag ID
544 for tag in api.plshell.GetSliceTags(self.user_plauth, {'~tagname':Slicetag.ignore_tags}, Slicetag.filter_fields):
545 t = tag['slice_tag_id'], Slicetag(tag)
549 def get_tag_types(self, api):
551 Create a list of tagtype obects keyed by tag name
554 for tag in api.plshell.GetTagTypes(self.user_plauth):
555 t = tag['tagname'], TagType(tag)
559 def get_slice(self, api, hrn):
561 Return a Slice object for a single slice
563 slicename = hrn_to_pl_slicename(hrn)
564 slice = api.plshell.GetSlices(self.user_plauth, [slicename])
566 self.slice = Slice(self, slicename, slice[0])