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
10 from sfa.util.sfalogging import logger
13 def __init__(self, node):
15 self.network = node.network
16 self.slice = node.network.slice
19 logger.info("sliver to xml!")
21 self.slice.tags_to_xml(xml, self.node)
25 def __init__(self, network, iface):
26 self.network = network
27 self.id = iface['interface_id']
28 self.idtag = "i%s" % self.id
29 self.ipv4 = iface['ip']
30 self.bwlimit = iface['bwlimit']
31 self.hostname = iface['hostname']
32 self.primary = iface['is_primary']
35 Just print out bwlimit right now
39 with xml.bw_limit(units="kbps"):
40 xml << str(self.bwlimit / 1000)
44 def __init__(self, network, node):
45 self.network = network
46 self.id = node['node_id']
47 self.idtag = "n%s" % self.id
48 self.hostname = node['hostname']
49 self.site_id = node['site_id']
50 self.iface_ids = node['interface_ids']
52 self.whitelist = node['slice_ids_whitelist']
54 def get_primary_iface(self):
55 for id in self.iface_ids:
56 iface = self.network.lookupIface(id)
62 return self.network.lookupSite(self.site_id)
65 self.sliver = Sliver(self)
68 logger.info("node.toxml(I)")
69 slice = self.network.slice
70 if self.whitelist and not self.sliver:
71 if not slice or slice.id not in self.whitelist:
74 with xml.node(id = self.idtag):
77 iface = self.get_primary_iface()
81 self.sliver.toxml(xml)
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']
91 self.name = site['abbreviated_name']
92 self.tag = site['login_base']
93 self.public = site['is_public']
94 self.enabled = site['enabled']
96 self.whitelist = False
98 def get_sitenodes(self):
100 for i in self.node_ids:
101 n.append(self.network.lookupNode(i))
104 def toxml(self, xml):
105 if not (self.public and self.enabled and self.node_ids):
108 with xml.site(id = self.idtag):
111 for node in self.get_sitenodes():
116 def __init__(self, network, hrn, slice):
118 self.network = network
119 self.id = slice['slice_id']
120 self.name = slice['name']
121 self.peer_id = slice['peer_id']
122 self.node_ids = set(slice['node_ids'])
123 self.slice_tag_ids = slice['slice_tag_ids']
126 Use with tags that can have more than one instance
128 def get_multi_tag(self, tagname, node = None):
130 for i in self.slice_tag_ids:
131 tag = self.network.lookupSliceTag(i)
132 if tag.tagname == tagname:
133 if not (node and node.id != tag.node_id):
138 Use with tags that have only one instance
140 def get_tag(self, tagname, node = None):
141 for i in self.slice_tag_ids:
142 tag = self.network.lookupSliceTag(i)
143 if tag.tagname == tagname:
144 if (not node) or (node.id == tag.node_id):
150 for id in self.node_ids:
151 if id in self.network.nodes:
152 n.append(self.network.nodes[id])
155 # Add a new slice tag
156 def add_tag(self, tagname, value, node = None, role_id = 40):
157 tt = self.network.lookupTagType(tagname)
158 if not tt.permit_update(role_id):
159 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
161 tag.initialize(tagname, value, node, self.network)
162 self.network.tags[tag.id] = tag
163 self.slice_tag_ids.append(tag.id)
166 # Update a slice tag if it exists, else add it
167 def update_tag(self, tagname, value, node = None, role_id = 40):
168 tag = self.get_tag(tagname, node)
170 if not tag.permit_update(role_id, value):
171 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
174 tag = self.add_tag(tagname, value, node, role_id)
177 def update_multi_tag(self, tagname, value, node = None, role_id = 40):
178 tags = self.get_multi_tag(tagname, node)
180 if tag and tag.value == value:
183 tag = self.add_tag(tagname, value, node, role_id)
186 def tags_to_xml(self, xml, node = None):
187 tagtypes = self.network.getTagTypes()
191 tags = self.get_multi_tag(tt.tagname, node)
193 if not tag.was_deleted(): ### Debugging
194 xml << (tag.tagname, tag.value)
196 tag = self.get_tag(tt.tagname, node)
198 if not tag.was_deleted(): ### Debugging
199 xml << (tag.tagname, tag.value)
201 def toxml(self, xml):
202 logger.info("slice to xml!")
204 with xml.sliver_defaults:
205 self.tags_to_xml(xml)
210 def __init__(self, tag = None):
213 self.id = tag['slice_tag_id']
214 self.slice_id = tag['slice_id']
215 self.tagname = tag['tagname']
216 self.value = tag['value']
217 self.node_id = tag['node_id']
218 self.category = tag['category']
219 self.min_role_id = tag['min_role_id']
222 # Create a new slicetag that will be written to the DB later
223 def initialize(self, tagname, value, node, network):
224 tt = network.lookupTagType(tagname)
225 self.id = Slicetag.newid
227 self.slice_id = network.slice.id
228 self.tagname = tagname
231 self.node_id = node.id
234 self.category = tt.category
235 self.min_role_id = tt.min_role_id
238 def permit_update(self, role_id, value = None):
239 if value and self.value == value:
241 if role_id > self.min_role_id:
245 def change(self, value):
246 if self.value != value:
248 self.status = "change"
250 self.status = "updated"
252 # Mark a tag as deleted
254 self.status = "delete"
259 def was_changed(self):
260 return (self.status == "change")
262 def was_deleted(self):
263 return (self.status == "delete")
265 def was_updated(self):
266 return (self.status != None)
268 def write(self, api):
270 api.plshell.AddSliceTag(api.plauth, self.slice_id,
271 self.tagname, self.value, self.node_id)
272 elif self.was_changed():
273 api.plshell.UpdateSliceTag(api.plauth, self.id, self.value)
274 elif self.was_deleted():
275 api.plshell.DeleteSliceTag(api.plauth, self.id)
279 def __init__(self, tagtype):
280 self.id = tagtype['tag_type_id']
281 self.category = tagtype['category']
282 self.tagname = tagtype['tagname']
283 self.min_role_id = tagtype['min_role_id']
285 self.in_rspec = False
286 if self.category == 'slice/rspec':
288 if self.tagname in ['codemux', 'ip_addresses', 'vsys']:
291 def permit_update(self, role_id):
292 if role_id > self.min_role_id:
298 A Network is a compound object consisting of:
299 * a dictionary mapping site IDs to Site objects
300 * a dictionary mapping node IDs to Node objects
301 * a dictionary mapping interface IDs to Iface objects
304 def __init__(self, api, type = "SFA"):
307 self.sites = self.get_sites(api)
308 self.nodes = self.get_nodes(api)
309 self.ifaces = self.get_ifaces(api)
310 self.tags = self.get_slice_tags(api)
311 self.tagtypes = self.get_tag_types(api)
314 """ Lookup site based on id or idtag value """
315 def lookupSite(self, id):
317 if isinstance(id, basestring):
318 id = int(id.lstrip('s'))
322 raise InvalidRSpec("site ID %s not found" % id)
328 sites.append(self.sites[s])
331 """ Lookup node based on id or idtag value """
332 def lookupNode(self, id):
334 if isinstance(id, basestring):
335 id = int(id.lstrip('n'))
339 raise InvalidRSpec("node ID %s not found" % id)
345 nodes.append(self.nodes[n])
348 """ Lookup iface based on id or idtag value """
349 def lookupIface(self, id):
351 if isinstance(id, basestring):
352 id = int(id.lstrip('i'))
354 val = self.ifaces[id]
356 raise InvalidRSpec("interface ID %s not found" % id)
361 for i in self.ifaces:
362 ifaces.append(self.ifaces[i])
365 def nodesWithSlivers(self):
373 def lookupSliceTag(self, id):
378 raise InvalidRSpec("slicetag ID %s not found" % id)
381 def getSliceTags(self):
384 tags.append(self.tags[t])
387 def lookupTagType(self, name):
390 val = self.tagtypes[name]
392 raise InvalidRSpec("tag %s not found" % name)
395 def getTagTypes(self):
397 for t in self.tagtypes:
398 tags.append(self.tagtypes[t])
402 Process the elements under <sliver_defaults> or <sliver>
404 def __process_attributes(self, element, node=None):
408 tagtypes = self.getTagTypes()
412 for e in element.iterfind("./" + tt.tagname):
413 self.slice.update_multi_tag(tt.tagname, e.text, node)
415 e = element.find("./" + tt.tagname)
417 self.slice.update_tag(tt.tagname, e.text, node)
420 Annotate the objects in the Network with information from the RSpec
422 def addRSpec(self, xml, schema=None):
424 tree = etree.parse(StringIO(xml))
425 except etree.XMLSyntaxError:
426 message = str(sys.exc_info()[1])
427 raise InvalidRSpec(message)
429 # Filter out stuff that's not for us
430 rspec = tree.getroot()
431 for network in rspec.iterfind("./network"):
432 if network.get("name") != self.api.hrn:
433 rspec.remove(network)
434 for request in rspec.iterfind("./request"):
435 if request.get("name") != self.api.hrn:
436 rspec.remove(request)
439 # Validate the incoming request against the RelaxNG schema
440 relaxng_doc = etree.parse(schema)
441 relaxng = etree.RelaxNG(relaxng_doc)
443 if not relaxng(tree):
444 error = relaxng.error_log.last_error
445 message = "%s (line %s)" % (error.message, error.line)
446 raise InvalidRSpec(message)
449 defaults = rspec.find(".//sliver_defaults")
450 self.__process_attributes(defaults)
453 # Find slivers under node elements
454 for sliver in rspec.iterfind("./network/site/node/sliver"):
455 elem = sliver.getparent()
457 node = self.lookupNode(elem.get("id"))
459 # Don't worry about nodes from other aggregates
463 self.__process_attributes(sliver, node)
465 # Find slivers that specify nodeid
466 for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
468 node = self.lookupNode(sliver.get("nodeid"))
470 # Don't worry about nodes from other aggregates
474 self.__process_attributes(sliver, node)
479 Annotate the objects in the Network with information from the slice
484 raise InvalidRSpec("no slice associated with network")
486 for node in slice.get_nodes():
490 Write any slice tags that have been added or modified back to the DB
492 def updateSliceTags(self):
493 for tag in self.getSliceTags():
494 if tag.category == 'slice/rspec' and not tag.was_updated() and tag.permit_update(None, 40):
495 # The user wants to delete this tag
498 # Update slice tags in database
499 for tag in self.getSliceTags():
500 if tag.slice_id == self.slice.id:
504 Produce XML directly from the topology specification.
507 xml = XMLBuilder(format = True, tab_step = " ")
508 with xml.RSpec(type=self.type):
510 element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
512 element = xml.network(name=self.api.hrn)
516 self.slice.toxml(xml)
517 for site in self.getSites():
520 header = '<?xml version="1.0"?>\n'
521 return header + str(xml)
524 Create a dictionary of site objects keyed by site ID
526 def get_sites(self, api):
528 for site in api.plshell.GetSites(api.plauth, {'peer_id': None}):
529 t = site['site_id'], Site(self, site)
535 Create a dictionary of node objects keyed by node ID
537 def get_nodes(self, api):
539 for node in api.plshell.GetNodes(api.plauth, {'peer_id': None}):
540 t = node['node_id'], Node(self, node)
545 Create a dictionary of node objects keyed by node ID
547 def get_ifaces(self, api):
549 for iface in api.plshell.GetInterfaces(api.plauth):
550 t = iface['interface_id'], Iface(self, iface)
555 Create a dictionary of slicetag objects keyed by slice tag ID
557 def get_slice_tags(self, api):
559 for tag in api.plshell.GetSliceTags(api.plauth):
560 t = tag['slice_tag_id'], Slicetag(tag)
565 Create a list of tagtype obects keyed by tag name
567 def get_tag_types(self, api):
569 for tag in api.plshell.GetTagTypes(api.plauth):
570 t = tag['tagname'], TagType(tag)
575 Return a Slice object for a single slice
577 def get_slice(self, api, hrn):
578 slicename = hrn_to_pl_slicename(hrn)
579 slice = api.plshell.GetSlices(api.plauth, [slicename])
581 self.slice = Slice(self, slicename, slice[0])