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 filter_fields = ['slice_tag_id','slice_id','tagname','value','node_id','category']
218 ignore_tags = ['hmac','ssh_key']
219 def __init__(self, tag = None):
222 self.id = tag['slice_tag_id']
223 self.slice_id = tag['slice_id']
224 self.tagname = tag['tagname']
225 self.value = tag['value']
226 self.node_id = tag['node_id']
227 self.category = tag['category']
228 # self.min_role_id = tag['min_role_id']
231 # Create a new slicetag that will be written to the DB later
232 def initialize(self, tagname, value, node, network):
233 tt = network.lookupTagType(tagname)
234 self.id = Slicetag.newid
236 self.slice_id = network.slice.id
237 self.tagname = tagname
240 self.node_id = node.id
243 self.category = tt.category
244 # self.min_role_id = tt.min_role_id
247 def permit_update(self, role_id, value = None):
248 if value and self.value == value:
250 # xxx FIXME - the new model in PLCAPI has roles and not min_role_id
251 #if role_id > self.min_role_id:
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.min_role_id = tagtype['min_role_id']
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_id):
304 #if role_id > self.min_role_id:
311 A Network is a compound object consisting of:
312 * a dictionary mapping site IDs to Site objects
313 * a dictionary mapping node IDs to Node objects
314 * a dictionary mapping interface IDs to Iface objects
316 def __init__(self, api, type = "SFA"):
319 self.sites = self.get_sites(api)
320 self.nodes = self.get_nodes(api)
321 self.ifaces = self.get_ifaces(api)
322 self.tags = self.get_slice_tags(api)
323 self.tagtypes = self.get_tag_types(api)
326 def lookupSite(self, id):
327 """ Lookup site based on id or idtag value """
329 if isinstance(id, basestring):
330 id = int(id.lstrip('s'))
334 raise InvalidRSpec("site ID %s not found" % id)
340 sites.append(self.sites[s])
343 def lookupNode(self, id):
344 """ Lookup node based on id or idtag value """
346 if isinstance(id, basestring):
347 id = int(id.lstrip('n'))
351 raise InvalidRSpec("node ID %s not found" % id)
357 nodes.append(self.nodes[n])
360 def lookupIface(self, id):
361 """ Lookup iface based on id or idtag value """
363 if isinstance(id, basestring):
364 id = int(id.lstrip('i'))
366 val = self.ifaces[id]
368 raise InvalidRSpec("interface ID %s not found" % id)
373 for i in self.ifaces:
374 ifaces.append(self.ifaces[i])
377 def nodesWithSlivers(self):
385 def lookupSliceTag(self, id):
390 raise InvalidRSpec("slicetag ID %s not found" % id)
393 def getSliceTags(self):
396 tags.append(self.tags[t])
399 def lookupTagType(self, name):
402 val = self.tagtypes[name]
404 raise InvalidRSpec("tag %s not found" % name)
407 def getTagTypes(self):
409 for t in self.tagtypes:
410 tags.append(self.tagtypes[t])
413 def __process_attributes(self, element, node=None):
415 Process the elements under <sliver_defaults> or <sliver>
420 tagtypes = self.getTagTypes()
424 for e in element.iterfind("./" + tt.tagname):
425 self.slice.update_multi_tag(tt.tagname, e.text, node)
427 e = element.find("./" + tt.tagname)
429 self.slice.update_tag(tt.tagname, e.text, node)
431 def addRSpec(self, xml, schema=None):
433 Annotate the objects in the Network with information from the RSpec
436 tree = etree.parse(StringIO(xml))
437 except etree.XMLSyntaxError:
438 message = str(sys.exc_info()[1])
439 raise InvalidRSpec(message)
441 # Filter out stuff that's not for us
442 rspec = tree.getroot()
443 for network in rspec.iterfind("./network"):
444 if network.get("name") != self.api.hrn:
445 rspec.remove(network)
446 for request in rspec.iterfind("./request"):
447 if request.get("name") != self.api.hrn:
448 rspec.remove(request)
451 # Validate the incoming request against the RelaxNG schema
452 relaxng_doc = etree.parse(schema)
453 relaxng = etree.RelaxNG(relaxng_doc)
455 if not relaxng(tree):
456 error = relaxng.error_log.last_error
457 message = "%s (line %s)" % (error.message, error.line)
458 raise InvalidRSpec(message)
462 defaults = rspec.find(".//sliver_defaults")
463 self.__process_attributes(defaults)
465 # Find slivers under node elements
466 for sliver in rspec.iterfind("./network/site/node/sliver"):
467 elem = sliver.getparent()
469 node = self.lookupNode(elem.get("id"))
471 # Don't worry about nodes from other aggregates
475 self.__process_attributes(sliver, node)
477 # Find slivers that specify nodeid
478 for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
480 node = self.lookupNode(sliver.get("nodeid"))
482 # Don't worry about nodes from other aggregates
486 self.__process_attributes(sliver, node)
492 Annotate the objects in the Network with information from the slice
496 raise InvalidRSpec("no slice associated with network")
498 for node in slice.get_nodes():
501 def updateSliceTags(self):
503 Write any slice tags that have been added or modified back to the DB
505 for tag in self.getSliceTags():
506 if tag.category == 'slice/rspec' and not tag.was_updated() and tag.permit_update(None, 30):
507 # The user wants to delete this tag
510 # Update slice tags in database
511 for tag in self.getSliceTags():
512 if tag.slice_id == self.slice.id:
517 Produce XML directly from the topology specification.
519 xml = XMLBuilder(format = True, tab_step = " ")
520 with xml.RSpec(type=self.type):
522 element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
524 element = xml.network(name=self.api.hrn)
528 self.slice.toxml(xml)
529 for site in self.getSites():
532 header = '<?xml version="1.0"?>\n'
533 return header + str(xml)
535 def get_sites(self, api):
537 Create a dictionary of site objects keyed by site ID
540 for site in api.plshell.GetSites(api.plauth, {'peer_id': None}):
541 t = site['site_id'], Site(self, site)
546 def get_nodes(self, api):
548 Create a dictionary of node objects keyed by node ID
551 for node in api.plshell.GetNodes(api.plauth, {'peer_id': None}):
552 t = node['node_id'], Node(self, node)
556 def get_ifaces(self, api):
558 Create a dictionary of node objects keyed by node ID
561 for iface in api.plshell.GetInterfaces(api.plauth):
562 t = iface['interface_id'], Iface(self, iface)
566 def get_slice_tags(self, api):
568 Create a dictionary of slicetag objects keyed by slice tag ID
571 for tag in api.plshell.GetSliceTags(api.plauth, {'~tagname':Slicetag.ignore_tags}, Slicetag.filter_fields):
572 t = tag['slice_tag_id'], Slicetag(tag)
576 def get_tag_types(self, api):
578 Create a list of tagtype obects keyed by tag name
581 for tag in api.plshell.GetTagTypes(api.plauth, {'~tagname':TagType.ignore_tags}):
582 t = tag['tagname'], TagType(tag)
586 def get_slice(self, api, hrn):
588 Return a Slice object for a single slice
590 slicename = hrn_to_pl_slicename(hrn)
591 slice = api.plshell.GetSlices(api.plauth, [slicename])
593 self.slice = Slice(self, slicename, slice[0])