1 from __future__ import with_statement
4 from sfa.util.xrn import get_authority
5 from sfa.util.plxrn import hrn_to_pl_slicename, hostname_to_urn
6 from sfa.util.faults import *
7 from xmlbuilder import XMLBuilder
10 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']
35 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']
52 auth = self.network.api.hrn
53 login_base = self.get_site().idtag
54 self.urn = hostname_to_urn(auth, login_base, self.hostname)
56 def get_primary_iface(self):
57 for id in self.iface_ids:
58 iface = self.network.lookupIface(id)
64 return self.network.lookupSite(self.site_id)
67 self.sliver = Sliver(self)
70 slice = self.network.slice
71 if self.whitelist and not self.sliver:
72 if not slice or slice.id not in self.whitelist:
75 with xml.node(id = self.idtag):
80 iface = self.get_primary_iface()
84 self.sliver.toxml(xml)
88 def __init__(self, network, site):
89 self.network = network
90 self.id = site['site_id']
91 self.node_ids = site['node_ids']
93 self.name = site['abbreviated_name']
94 self.tag = site['login_base']
95 self.idtag = site['login_base']
96 self.public = site['is_public']
97 self.enabled = site['enabled']
99 self.whitelist = False
101 def get_sitenodes(self):
103 for i in self.node_ids:
104 n.append(self.network.lookupNode(i))
107 def toxml(self, xml):
108 if not (self.public and self.enabled and self.node_ids):
110 with xml.site(id = self.idtag):
113 for node in self.get_sitenodes():
118 def __init__(self, network, hrn, slice):
120 self.network = network
121 self.id = slice['slice_id']
122 self.name = slice['name']
123 self.peer_id = slice['peer_id']
124 self.node_ids = set(slice['node_ids'])
125 self.slice_tag_ids = slice['slice_tag_ids']
128 Use with tags that can have more than one instance
130 def get_multi_tag(self, tagname, node = None):
132 for i in self.slice_tag_ids:
134 tag = self.network.lookupSliceTag(i)
135 if tag.tagname == tagname:
137 if node.id == tag.node_id:
139 elif not tag.node_id:
141 except InvalidRSpec, e:
142 # As they're not needed, we ignore some tag types from
143 # GetSliceTags call. See Slicetag.ignore_tags
148 Use with tags that have only one instance
150 def get_tag(self, tagname, node = None):
151 for i in self.slice_tag_ids:
153 tag = self.network.lookupSliceTag(i)
154 if tag.tagname == tagname:
156 if node.id == tag.node_id:
158 elif not tag.node_id:
160 except InvalidRSpec, e:
161 # As they're not needed, we ignore some tag types from
162 # GetSliceTags call. See Slicetag.ignore_tags
168 for id in self.node_ids:
169 if id in self.network.nodes:
170 n.append(self.network.nodes[id])
173 # Add a new slice tag
174 def add_tag(self, tagname, value, node = None, role = "user"):
175 tt = self.network.lookupTagType(tagname)
176 if not tt.permit_update(role):
177 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
179 tag.initialize(tagname, value, node, self.network)
180 self.network.tags[tag.id] = tag
181 self.slice_tag_ids.append(tag.id)
184 # Update a slice tag if it exists, else add it
185 def update_tag(self, tagname, value, node = None, role = "user"):
186 tt = self.network.lookupTagType(tagname)
187 if not tt.permit_update(role):
188 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
189 tag = self.get_tag(tagname, node)
193 tag = self.add_tag(tagname, value, node, role)
196 def update_multi_tag(self, tagname, value, node = None, role = "user"):
197 tags = self.get_multi_tag(tagname, node)
199 if tag and tag.value == value:
202 tag = self.add_tag(tagname, value, node, role)
205 def tags_to_xml(self, xml, node = None):
206 tagtypes = self.network.getTagTypes()
210 tags = self.get_multi_tag(tt.tagname, node)
212 if not tag.was_deleted(): ### Debugging
213 xml << (tag.tagname, tag.value)
215 tag = self.get_tag(tt.tagname, node)
217 if not tag.was_deleted(): ### Debugging
218 xml << (tag.tagname, tag.value)
220 def toxml(self, xml):
221 with xml.sliver_defaults:
222 self.tags_to_xml(xml)
227 filter_fields = ['slice_tag_id','slice_id','tagname','value','node_id','category']
228 ignore_tags = ['hmac','ssh_key']
229 def __init__(self, tag = None):
232 self.id = tag['slice_tag_id']
233 self.slice_id = tag['slice_id']
234 self.tagname = tag['tagname']
235 self.value = tag['value']
236 self.node_id = tag['node_id']
237 self.category = tag['category']
240 # Create a new slicetag that will be written to the DB later
241 def initialize(self, tagname, value, node, network):
242 tt = network.lookupTagType(tagname)
243 self.id = Slicetag.newid
245 self.slice_id = network.slice.id
246 self.tagname = tagname
249 self.node_id = node.id
252 self.category = tt.category
255 def change(self, value):
256 if self.value != value:
258 self.status = "change"
260 self.status = "updated"
262 # Mark a tag as deleted
264 self.status = "delete"
269 def was_changed(self):
270 return (self.status == "change")
272 def was_deleted(self):
273 return (self.status == "delete")
275 def was_updated(self):
276 return (self.status != None)
278 def write(self, api):
280 api.plshell.AddSliceTag(api.plauth, self.slice_id,
281 self.tagname, self.value, self.node_id)
282 elif self.was_changed():
283 api.plshell.UpdateSliceTag(api.plauth, self.id, self.value)
284 elif self.was_deleted():
285 api.plshell.DeleteSliceTag(api.plauth, self.id)
289 ignore_tags = ['hmac','ssh_key']
290 def __init__(self, tagtype):
291 self.id = tagtype['tag_type_id']
292 self.category = tagtype['category']
293 self.tagname = tagtype['tagname']
294 self.roles = tagtype['roles']
296 self.in_rspec = False
297 if self.category == 'slice/rspec':
299 if self.tagname in ['codemux', 'ip_addresses', 'vsys']:
302 def permit_update(self, role):
303 if role in self.roles:
310 A Network is a compound object consisting of:
311 * a dictionary mapping site IDs to Site objects
312 * a dictionary mapping node IDs to Node objects
313 * a dictionary mapping interface IDs to Iface objects
315 def __init__(self, api, type = "SFA"):
318 self.sites = self.get_sites(api)
319 self.nodes = self.get_nodes(api)
320 self.ifaces = self.get_ifaces(api)
321 self.tags = self.get_slice_tags(api)
322 self.tagtypes = self.get_tag_types(api)
327 self.sitemap[site.idtag] = site.id
329 def lookupSiteIdtag(self, name):
330 """ Lookup site id from name """
333 val = self.sitemap[name]
335 raise InvalidRSpec("site name '%s' not found" % name)
338 def lookupSite(self, id):
339 """ Lookup site based on id or idtag value """
341 if isinstance(id, basestring):
342 id = self.lookupSiteIdtag(id)
346 raise InvalidRSpec("site ID %s not found" % id)
352 sites.append(self.sites[s])
355 def lookupNode(self, id):
356 """ Lookup node based on id or idtag value """
358 if isinstance(id, basestring):
359 id = int(id.lstrip('n'))
363 raise InvalidRSpec("node ID %s not found" % id)
369 nodes.append(self.nodes[n])
372 def lookupIface(self, id):
373 """ Lookup iface based on id or idtag value """
375 if isinstance(id, basestring):
376 id = int(id.lstrip('i'))
378 val = self.ifaces[id]
380 raise InvalidRSpec("interface ID %s not found" % id)
385 for i in self.ifaces:
386 ifaces.append(self.ifaces[i])
389 def nodesWithSlivers(self):
397 def lookupSliceTag(self, id):
402 raise InvalidRSpec("slicetag ID %s not found" % id)
405 def getSliceTags(self):
408 tags.append(self.tags[t])
411 def lookupTagType(self, name):
414 val = self.tagtypes[name]
416 raise InvalidRSpec("tag %s not found" % name)
419 def getTagTypes(self):
421 for t in self.tagtypes:
422 tags.append(self.tagtypes[t])
425 def __process_attributes(self, element, node=None):
427 Process the elements under <sliver_defaults> or <sliver>
432 tagtypes = self.getTagTypes()
436 for e in element.iterfind("./" + tt.tagname):
437 self.slice.update_multi_tag(tt.tagname, e.text, node)
439 e = element.find("./" + tt.tagname)
441 self.slice.update_tag(tt.tagname, e.text, node)
443 def addRSpec(self, xml, schema=None):
445 Annotate the objects in the Network with information from the RSpec
448 tree = etree.parse(StringIO(xml))
449 except etree.XMLSyntaxError:
450 message = str(sys.exc_info()[1])
451 raise InvalidRSpec(message)
453 # Filter out stuff that's not for us
454 rspec = tree.getroot()
455 for network in rspec.iterfind("./network"):
456 if network.get("name") != self.api.hrn:
457 rspec.remove(network)
458 for request in rspec.iterfind("./request"):
459 if request.get("name") != self.api.hrn:
460 rspec.remove(request)
463 # Validate the incoming request against the RelaxNG schema
464 relaxng_doc = etree.parse(schema)
465 relaxng = etree.RelaxNG(relaxng_doc)
467 if not relaxng(tree):
468 error = relaxng.error_log.last_error
469 message = "%s (line %s)" % (error.message, error.line)
470 raise InvalidRSpec(message)
474 defaults = rspec.find(".//sliver_defaults")
475 self.__process_attributes(defaults)
477 # Find slivers under node elements
478 for sliver in rspec.iterfind("./network/site/node/sliver"):
479 elem = sliver.getparent()
481 node = self.lookupNode(elem.get("id"))
483 # Don't worry about nodes from other aggregates
487 self.__process_attributes(sliver, node)
489 # Find slivers that specify nodeid
490 for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
492 node = self.lookupNode(sliver.get("nodeid"))
494 # Don't worry about nodes from other aggregates
498 self.__process_attributes(sliver, node)
504 Annotate the objects in the Network with information from the slice
508 raise InvalidRSpec("no slice associated with network")
510 for node in slice.get_nodes():
513 def updateSliceTags(self):
515 Write any slice tags that have been added or modified back to the DB
517 for tag in self.getSliceTags():
518 if tag.category == 'slice/rspec' and not tag.was_updated():
519 tt = self.lookupTagType(tag.tagname)
520 if tt.permit_update("user"):
523 # Update slice tags in database
524 for tag in self.getSliceTags():
525 if tag.slice_id == self.slice.id:
530 Produce XML directly from the topology specification.
532 xml = XMLBuilder(format = True, tab_step = " ")
533 with xml.RSpec(type=self.type):
535 element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
537 element = xml.network(name=self.api.hrn)
541 self.slice.toxml(xml)
542 for site in self.getSites():
545 header = '<?xml version="1.0"?>\n'
546 return header + str(xml)
548 def get_sites(self, api):
550 Create a dictionary of site objects keyed by site ID
553 for site in api.plshell.GetSites(api.plauth, {'peer_id': None}):
554 t = site['site_id'], Site(self, site)
559 def get_nodes(self, api):
561 Create a dictionary of node objects keyed by node ID
564 for node in api.plshell.GetNodes(api.plauth, {'peer_id': None}):
565 t = node['node_id'], Node(self, node)
569 def get_ifaces(self, api):
571 Create a dictionary of node objects keyed by node ID
574 for iface in api.plshell.GetInterfaces(api.plauth):
575 t = iface['interface_id'], Iface(self, iface)
579 def get_slice_tags(self, api):
581 Create a dictionary of slicetag objects keyed by slice tag ID
584 for tag in api.plshell.GetSliceTags(api.plauth, {'~tagname':Slicetag.ignore_tags}, Slicetag.filter_fields):
585 t = tag['slice_tag_id'], Slicetag(tag)
589 def get_tag_types(self, api):
591 Create a list of tagtype obects keyed by tag name
594 for tag in api.plshell.GetTagTypes(api.plauth, {'~tagname':TagType.ignore_tags}):
595 t = tag['tagname'], TagType(tag)
599 def get_slice(self, api, hrn):
601 Return a Slice object for a single slice
603 slicename = hrn_to_pl_slicename(hrn)
604 slice = api.plshell.GetSlices(api.plauth, [slicename])
606 self.slice = Slice(self, slicename, slice[0])