1 from __future__ import with_statement
4 from sfa.util.xrn import get_authority
5 from sfa.util.plxrn import hrn_to_pl_slicename
6 from sfa.util.faults import *
7 from xmlbuilder import XMLBuilder
10 from StringIO import StringIO
14 def __init__(self, node):
16 self.network = node.network
17 self.slice = node.network.slice
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']
36 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 slice = self.network.slice
69 if self.whitelist and not self.sliver:
70 if not slice or slice.id not in self.whitelist:
73 with xml.node(id = self.idtag):
76 iface = self.get_primary_iface()
80 self.sliver.toxml(xml)
84 def __init__(self, network, site):
85 self.network = network
86 self.id = site['site_id']
87 self.idtag = "s%s" % self.id
88 self.node_ids = site['node_ids']
90 self.name = site['abbreviated_name']
91 self.tag = site['login_base']
92 self.public = site['is_public']
93 self.enabled = site['enabled']
95 self.whitelist = False
97 def get_sitenodes(self):
99 for i in self.node_ids:
100 n.append(self.network.lookupNode(i))
103 def toxml(self, xml):
104 if not (self.public and self.enabled and self.node_ids):
106 with xml.site(id = self.idtag):
109 for node in self.get_sitenodes():
114 def __init__(self, network, hrn, slice):
116 self.network = network
117 self.id = slice['slice_id']
118 self.name = slice['name']
119 self.peer_id = slice['peer_id']
120 self.node_ids = set(slice['node_ids'])
121 self.slice_tag_ids = slice['slice_tag_ids']
124 Use with tags that can have more than one instance
126 def get_multi_tag(self, tagname, node = None):
128 for i in self.slice_tag_ids:
130 tag = self.network.lookupSliceTag(i)
131 if tag.tagname == tagname:
132 if not (node and node.id != tag.node_id):
134 except InvalidRSpec, e:
135 # As they're not needed, we ignore some tag types from
136 # GetSliceTags call. See Slicetag.ignore_tags
141 Use with tags that have only one instance
143 def get_tag(self, tagname, node = None):
145 for i in self.slice_tag_ids:
146 tag = self.network.lookupSliceTag(i)
147 if tag.tagname == tagname:
148 if (not node) or (node.id == tag.node_id):
150 except InvalidRSpec, e:
151 # As they're not needed, we ignore some tag types from
152 # GetSliceTags call. See Slicetag.ignore_tags
158 for id in self.node_ids:
159 if id in self.network.nodes:
160 n.append(self.network.nodes[id])
163 # Add a new slice tag
164 def add_tag(self, tagname, value, node = None, role_id = 30):
165 tt = self.network.lookupTagType(tagname)
166 if not tt.permit_update(role_id):
167 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
169 tag.initialize(tagname, value, node, self.network)
170 self.network.tags[tag.id] = tag
171 self.slice_tag_ids.append(tag.id)
174 # Update a slice tag if it exists, else add it
175 def update_tag(self, tagname, value, node = None, role_id = 30):
176 tag = self.get_tag(tagname, node)
178 if not tag.permit_update(role_id, value):
179 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
182 tag = self.add_tag(tagname, value, node, role_id)
185 def update_multi_tag(self, tagname, value, node = None, role_id = 30):
186 tags = self.get_multi_tag(tagname, node)
188 if tag and tag.value == value:
191 tag = self.add_tag(tagname, value, node, role_id)
194 def tags_to_xml(self, xml, node = None):
195 tagtypes = self.network.getTagTypes()
199 tags = self.get_multi_tag(tt.tagname, node)
201 if not tag.was_deleted(): ### Debugging
202 xml << (tag.tagname, tag.value)
204 tag = self.get_tag(tt.tagname, node)
206 if not tag.was_deleted(): ### Debugging
207 xml << (tag.tagname, tag.value)
209 def toxml(self, xml):
210 with xml.sliver_defaults:
211 self.tags_to_xml(xml)
216 filter_fields = ['slice_tag_id','slice_id','tagname','value','node_id','category','min_role_id']
217 ignore_tags = ['hmac','ssh_key']
218 def __init__(self, tag = None):
221 self.id = tag['slice_tag_id']
222 self.slice_id = tag['slice_id']
223 self.tagname = tag['tagname']
224 self.value = tag['value']
225 self.node_id = tag['node_id']
226 self.category = tag['category']
227 self.min_role_id = tag['min_role_id']
230 # Create a new slicetag that will be written to the DB later
231 def initialize(self, tagname, value, node, network):
232 tt = network.lookupTagType(tagname)
233 self.id = Slicetag.newid
235 self.slice_id = network.slice.id
236 self.tagname = tagname
239 self.node_id = node.id
242 self.category = tt.category
243 self.min_role_id = tt.min_role_id
246 def permit_update(self, role_id, value = None):
247 if value and self.value == value:
249 if role_id > self.min_role_id:
253 def change(self, value):
254 if self.value != value:
256 self.status = "change"
258 self.status = "updated"
260 # Mark a tag as deleted
262 self.status = "delete"
267 def was_changed(self):
268 return (self.status == "change")
270 def was_deleted(self):
271 return (self.status == "delete")
273 def was_updated(self):
274 return (self.status != None)
276 def write(self, api):
278 api.plshell.AddSliceTag(api.plauth, self.slice_id,
279 self.tagname, self.value, self.node_id)
280 elif self.was_changed():
281 api.plshell.UpdateSliceTag(api.plauth, self.id, self.value)
282 elif self.was_deleted():
283 api.plshell.DeleteSliceTag(api.plauth, self.id)
287 ignore_tags = ['hmac','ssh_key']
288 def __init__(self, tagtype):
289 self.id = tagtype['tag_type_id']
290 self.category = tagtype['category']
291 self.tagname = tagtype['tagname']
292 self.min_role_id = tagtype['min_role_id']
294 self.in_rspec = False
295 if self.category == 'slice/rspec':
297 if self.tagname in ['codemux', 'ip_addresses', 'vsys']:
300 def permit_update(self, role_id):
301 if role_id > self.min_role_id:
308 A Network is a compound object consisting of:
309 * a dictionary mapping site IDs to Site objects
310 * a dictionary mapping node IDs to Node objects
311 * a dictionary mapping interface IDs to Iface objects
313 def __init__(self, api, type = "SFA"):
316 self.sites = self.get_sites(api)
317 self.nodes = self.get_nodes(api)
318 self.ifaces = self.get_ifaces(api)
319 self.tags = self.get_slice_tags(api)
320 self.tagtypes = self.get_tag_types(api)
323 def lookupSite(self, id):
324 """ Lookup site based on id or idtag value """
326 if isinstance(id, basestring):
327 id = int(id.lstrip('s'))
331 raise InvalidRSpec("site ID %s not found" % id)
337 sites.append(self.sites[s])
340 def lookupNode(self, id):
341 """ Lookup node based on id or idtag value """
343 if isinstance(id, basestring):
344 id = int(id.lstrip('n'))
348 raise InvalidRSpec("node ID %s not found" % id)
354 nodes.append(self.nodes[n])
357 def lookupIface(self, id):
358 """ Lookup iface based on id or idtag value """
360 if isinstance(id, basestring):
361 id = int(id.lstrip('i'))
363 val = self.ifaces[id]
365 raise InvalidRSpec("interface ID %s not found" % id)
370 for i in self.ifaces:
371 ifaces.append(self.ifaces[i])
374 def nodesWithSlivers(self):
382 def lookupSliceTag(self, id):
387 raise InvalidRSpec("slicetag ID %s not found" % id)
390 def getSliceTags(self):
393 tags.append(self.tags[t])
396 def lookupTagType(self, name):
399 val = self.tagtypes[name]
401 raise InvalidRSpec("tag %s not found" % name)
404 def getTagTypes(self):
406 for t in self.tagtypes:
407 tags.append(self.tagtypes[t])
410 def __process_attributes(self, element, node=None):
412 Process the elements under <sliver_defaults> or <sliver>
417 tagtypes = self.getTagTypes()
421 for e in element.iterfind("./" + tt.tagname):
422 self.slice.update_multi_tag(tt.tagname, e.text, node)
424 e = element.find("./" + tt.tagname)
426 self.slice.update_tag(tt.tagname, e.text, node)
428 def addRSpec(self, xml, schema=None):
430 Annotate the objects in the Network with information from the RSpec
433 tree = etree.parse(StringIO(xml))
434 except etree.XMLSyntaxError:
435 message = str(sys.exc_info()[1])
436 raise InvalidRSpec(message)
438 # Filter out stuff that's not for us
439 rspec = tree.getroot()
440 for network in rspec.iterfind("./network"):
441 if network.get("name") != self.api.hrn:
442 rspec.remove(network)
443 for request in rspec.iterfind("./request"):
444 if request.get("name") != self.api.hrn:
445 rspec.remove(request)
448 # Validate the incoming request against the RelaxNG schema
449 relaxng_doc = etree.parse(schema)
450 relaxng = etree.RelaxNG(relaxng_doc)
452 if not relaxng(tree):
453 error = relaxng.error_log.last_error
454 message = "%s (line %s)" % (error.message, error.line)
455 raise InvalidRSpec(message)
459 defaults = rspec.find(".//sliver_defaults")
460 self.__process_attributes(defaults)
462 # Find slivers under node elements
463 for sliver in rspec.iterfind("./network/site/node/sliver"):
464 elem = sliver.getparent()
466 node = self.lookupNode(elem.get("id"))
468 # Don't worry about nodes from other aggregates
472 self.__process_attributes(sliver, node)
474 # Find slivers that specify nodeid
475 for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
477 node = self.lookupNode(sliver.get("nodeid"))
479 # Don't worry about nodes from other aggregates
483 self.__process_attributes(sliver, node)
489 Annotate the objects in the Network with information from the slice
493 raise InvalidRSpec("no slice associated with network")
495 for node in slice.get_nodes():
498 def updateSliceTags(self):
500 Write any slice tags that have been added or modified back to the DB
502 for tag in self.getSliceTags():
503 if tag.category == 'slice/rspec' and not tag.was_updated() and tag.permit_update(None, 30):
504 # The user wants to delete this tag
507 # Update slice tags in database
508 for tag in self.getSliceTags():
509 if tag.slice_id == self.slice.id:
514 Produce XML directly from the topology specification.
516 xml = XMLBuilder(format = True, tab_step = " ")
517 with xml.RSpec(type=self.type):
519 element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
521 element = xml.network(name=self.api.hrn)
525 self.slice.toxml(xml)
526 for site in self.getSites():
529 header = '<?xml version="1.0"?>\n'
530 return header + str(xml)
532 def get_sites(self, api):
534 Create a dictionary of site objects keyed by site ID
537 for site in api.plshell.GetSites(api.plauth, {'peer_id': None}):
538 t = site['site_id'], Site(self, site)
543 def get_nodes(self, api):
545 Create a dictionary of node objects keyed by node ID
548 for node in api.plshell.GetNodes(api.plauth, {'peer_id': None}):
549 t = node['node_id'], Node(self, node)
553 def get_ifaces(self, api):
555 Create a dictionary of node objects keyed by node ID
558 for iface in api.plshell.GetInterfaces(api.plauth):
559 t = iface['interface_id'], Iface(self, iface)
563 def get_slice_tags(self, api):
565 Create a dictionary of slicetag objects keyed by slice tag ID
568 for tag in api.plshell.GetSliceTags(api.plauth, {'~tagname':Slicetag.ignore_tags}, Slicetag.filter_fields):
569 t = tag['slice_tag_id'], Slicetag(tag)
573 def get_tag_types(self, api):
575 Create a list of tagtype obects keyed by tag name
578 for tag in api.plshell.GetTagTypes(api.plauth, {'~tagname':TagType.ignore_tags}):
579 t = tag['tagname'], TagType(tag)
583 def get_slice(self, api, hrn):
585 Return a Slice object for a single slice
587 slicename = hrn_to_pl_slicename(hrn)
588 slice = api.plshell.GetSlices(api.plauth, [slicename])
590 self.slice = Slice(self, slicename, slice[0])