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
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']
53 auth = self.network.api.hrn
54 login_base = self.get_site().idtag
55 self.urn = hostname_to_urn(auth, login_base, self.hostname)
57 def get_primary_iface(self):
58 for id in self.iface_ids:
59 iface = self.network.lookupIface(id)
65 return self.network.lookupSite(self.site_id)
68 self.sliver = Sliver(self)
71 slice = self.network.slice
72 if self.whitelist and not self.sliver:
73 if not slice or slice.id not in self.whitelist:
76 with xml.node(id = self.idtag):
81 iface = self.get_primary_iface()
85 self.sliver.toxml(xml)
89 def __init__(self, network, site):
90 self.network = network
91 self.id = site['site_id']
92 self.node_ids = site['node_ids']
94 self.name = site['abbreviated_name']
95 self.tag = site['login_base']
96 self.idtag = site['login_base']
97 self.public = site['is_public']
98 self.enabled = site['enabled']
100 self.whitelist = False
102 def get_sitenodes(self):
104 for i in self.node_ids:
105 n.append(self.network.lookupNode(i))
108 def toxml(self, xml):
109 if not (self.public and self.enabled and self.node_ids):
111 with xml.site(id = self.idtag):
114 for node in self.get_sitenodes():
119 def __init__(self, network, hrn, slice):
121 self.network = network
122 self.id = slice['slice_id']
123 self.name = slice['name']
124 self.peer_id = slice['peer_id']
125 self.node_ids = set(slice['node_ids'])
126 self.slice_tag_ids = slice['slice_tag_ids']
129 Use with tags that can have more than one instance
131 def get_multi_tag(self, tagname, node = None):
133 for i in self.slice_tag_ids:
135 tag = self.network.lookupSliceTag(i)
136 if tag.tagname == tagname:
137 if not (node and node.id != tag.node_id):
139 except InvalidRSpec, e:
140 # As they're not needed, we ignore some tag types from
141 # GetSliceTags call. See Slicetag.ignore_tags
146 Use with tags that have only one instance
148 def get_tag(self, tagname, node = None):
150 for i in self.slice_tag_ids:
151 tag = self.network.lookupSliceTag(i)
152 if tag.tagname == tagname:
153 if (not node) or (node.id == tag.node_id):
155 except InvalidRSpec, e:
156 # As they're not needed, we ignore some tag types from
157 # GetSliceTags call. See Slicetag.ignore_tags
163 for id in self.node_ids:
164 if id in self.network.nodes:
165 n.append(self.network.nodes[id])
168 # Add a new slice tag
169 def add_tag(self, tagname, value, node = None, role_id = 30):
170 tt = self.network.lookupTagType(tagname)
171 if not tt.permit_update(role_id):
172 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
174 tag.initialize(tagname, value, node, self.network)
175 self.network.tags[tag.id] = tag
176 self.slice_tag_ids.append(tag.id)
179 # Update a slice tag if it exists, else add it
180 def update_tag(self, tagname, value, node = None, role_id = 30):
181 tag = self.get_tag(tagname, node)
183 if not tag.permit_update(role_id, value):
184 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
187 tag = self.add_tag(tagname, value, node, role_id)
190 def update_multi_tag(self, tagname, value, node = None, role_id = 30):
191 tags = self.get_multi_tag(tagname, node)
193 if tag and tag.value == value:
196 tag = self.add_tag(tagname, value, node, role_id)
199 def tags_to_xml(self, xml, node = None):
200 tagtypes = self.network.getTagTypes()
204 tags = self.get_multi_tag(tt.tagname, node)
206 if not tag.was_deleted(): ### Debugging
207 xml << (tag.tagname, tag.value)
209 tag = self.get_tag(tt.tagname, node)
211 if not tag.was_deleted(): ### Debugging
212 xml << (tag.tagname, tag.value)
214 def toxml(self, xml):
215 with xml.sliver_defaults:
216 self.tags_to_xml(xml)
221 # filter_fields = ['slice_tag_id','slice_id','tagname','value','node_id','category','min_role_id']
222 filter_fields = ['slice_tag_id','slice_id','tagname','value','node_id','category']
223 ignore_tags = ['hmac','ssh_key']
224 def __init__(self, tag = None):
227 self.id = tag['slice_tag_id']
228 self.slice_id = tag['slice_id']
229 self.tagname = tag['tagname']
230 self.value = tag['value']
231 self.node_id = tag['node_id']
232 self.category = tag['category']
233 # self.min_role_id = tag['min_role_id']
236 # Create a new slicetag that will be written to the DB later
237 def initialize(self, tagname, value, node, network):
238 tt = network.lookupTagType(tagname)
239 self.id = Slicetag.newid
241 self.slice_id = network.slice.id
242 self.tagname = tagname
245 self.node_id = node.id
248 self.category = tt.category
249 # self.min_role_id = tt.min_role_id
252 def permit_update(self, role_id, value = None):
253 if value and self.value == value:
255 # xxx FIXME - the new model in PLCAPI has roles and not min_role_id
256 #if role_id > self.min_role_id:
260 def change(self, value):
261 if self.value != value:
263 self.status = "change"
265 self.status = "updated"
267 # Mark a tag as deleted
269 self.status = "delete"
274 def was_changed(self):
275 return (self.status == "change")
277 def was_deleted(self):
278 return (self.status == "delete")
280 def was_updated(self):
281 return (self.status != None)
283 def write(self, api):
285 api.plshell.AddSliceTag(api.plauth, self.slice_id,
286 self.tagname, self.value, self.node_id)
287 elif self.was_changed():
288 api.plshell.UpdateSliceTag(api.plauth, self.id, self.value)
289 elif self.was_deleted():
290 api.plshell.DeleteSliceTag(api.plauth, self.id)
294 ignore_tags = ['hmac','ssh_key']
295 def __init__(self, tagtype):
296 self.id = tagtype['tag_type_id']
297 self.category = tagtype['category']
298 self.tagname = tagtype['tagname']
299 # self.min_role_id = tagtype['min_role_id']
301 self.in_rspec = False
302 if self.category == 'slice/rspec':
304 if self.tagname in ['codemux', 'ip_addresses', 'vsys']:
307 def permit_update(self, role_id):
309 #if role_id > self.min_role_id:
316 A Network is a compound object consisting of:
317 * a dictionary mapping site IDs to Site objects
318 * a dictionary mapping node IDs to Node objects
319 * a dictionary mapping interface IDs to Iface objects
321 def __init__(self, api, type = "SFA"):
324 self.sites = self.get_sites(api)
325 self.nodes = self.get_nodes(api)
326 self.ifaces = self.get_ifaces(api)
327 self.tags = self.get_slice_tags(api)
328 self.tagtypes = self.get_tag_types(api)
333 self.sitemap[site.idtag] = site.id
335 def lookupSiteIdtag(self, name):
336 """ Lookup site id from name """
339 val = self.sitemap[name]
341 raise InvalidRSpec("site name '%s' not found" % name)
344 def lookupSite(self, id):
345 """ Lookup site based on id or idtag value """
347 if isinstance(id, basestring):
348 id = self.lookupSiteIdtag(id)
352 raise InvalidRSpec("site ID %s not found" % id)
358 sites.append(self.sites[s])
361 def lookupNode(self, id):
362 """ Lookup node based on id or idtag value """
364 if isinstance(id, basestring):
365 id = int(id.lstrip('n'))
369 raise InvalidRSpec("node ID %s not found" % id)
375 nodes.append(self.nodes[n])
378 def lookupIface(self, id):
379 """ Lookup iface based on id or idtag value """
381 if isinstance(id, basestring):
382 id = int(id.lstrip('i'))
384 val = self.ifaces[id]
386 raise InvalidRSpec("interface ID %s not found" % id)
391 for i in self.ifaces:
392 ifaces.append(self.ifaces[i])
395 def nodesWithSlivers(self):
403 def lookupSliceTag(self, id):
408 raise InvalidRSpec("slicetag ID %s not found" % id)
411 def getSliceTags(self):
414 tags.append(self.tags[t])
417 def lookupTagType(self, name):
420 val = self.tagtypes[name]
422 raise InvalidRSpec("tag %s not found" % name)
425 def getTagTypes(self):
427 for t in self.tagtypes:
428 tags.append(self.tagtypes[t])
431 def __process_attributes(self, element, node=None):
433 Process the elements under <sliver_defaults> or <sliver>
438 tagtypes = self.getTagTypes()
442 for e in element.iterfind("./" + tt.tagname):
443 self.slice.update_multi_tag(tt.tagname, e.text, node)
445 e = element.find("./" + tt.tagname)
447 self.slice.update_tag(tt.tagname, e.text, node)
449 def addRSpec(self, xml, schema=None):
451 Annotate the objects in the Network with information from the RSpec
454 tree = etree.parse(StringIO(xml))
455 except etree.XMLSyntaxError:
456 message = str(sys.exc_info()[1])
457 raise InvalidRSpec(message)
459 # Filter out stuff that's not for us
460 rspec = tree.getroot()
461 for network in rspec.iterfind("./network"):
462 if network.get("name") != self.api.hrn:
463 rspec.remove(network)
464 for request in rspec.iterfind("./request"):
465 if request.get("name") != self.api.hrn:
466 rspec.remove(request)
469 # Validate the incoming request against the RelaxNG schema
470 relaxng_doc = etree.parse(schema)
471 relaxng = etree.RelaxNG(relaxng_doc)
473 if not relaxng(tree):
474 error = relaxng.error_log.last_error
475 message = "%s (line %s)" % (error.message, error.line)
476 raise InvalidRSpec(message)
480 defaults = rspec.find(".//sliver_defaults")
481 self.__process_attributes(defaults)
483 # Find slivers under node elements
484 for sliver in rspec.iterfind("./network/site/node/sliver"):
485 elem = sliver.getparent()
487 node = self.lookupNode(elem.get("id"))
489 # Don't worry about nodes from other aggregates
493 self.__process_attributes(sliver, node)
495 # Find slivers that specify nodeid
496 for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
498 node = self.lookupNode(sliver.get("nodeid"))
500 # Don't worry about nodes from other aggregates
504 self.__process_attributes(sliver, node)
510 Annotate the objects in the Network with information from the slice
514 raise InvalidRSpec("no slice associated with network")
516 for node in slice.get_nodes():
519 def updateSliceTags(self):
521 Write any slice tags that have been added or modified back to the DB
523 for tag in self.getSliceTags():
524 if tag.category == 'slice/rspec' and not tag.was_updated() and tag.permit_update(None, 30):
525 # The user wants to delete this tag
528 # Update slice tags in database
529 for tag in self.getSliceTags():
530 if tag.slice_id == self.slice.id:
535 Produce XML directly from the topology specification.
537 xml = XMLBuilder(format = True, tab_step = " ")
538 with xml.RSpec(type=self.type):
540 element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
542 element = xml.network(name=self.api.hrn)
546 self.slice.toxml(xml)
547 for site in self.getSites():
550 header = '<?xml version="1.0"?>\n'
551 return header + str(xml)
553 def get_sites(self, api):
555 Create a dictionary of site objects keyed by site ID
558 for site in api.plshell.GetSites(api.plauth, {'peer_id': None}):
559 t = site['site_id'], Site(self, site)
564 def get_nodes(self, api):
566 Create a dictionary of node objects keyed by node ID
569 for node in api.plshell.GetNodes(api.plauth, {'peer_id': None}):
570 t = node['node_id'], Node(self, node)
574 def get_ifaces(self, api):
576 Create a dictionary of node objects keyed by node ID
579 for iface in api.plshell.GetInterfaces(api.plauth):
580 t = iface['interface_id'], Iface(self, iface)
584 def get_slice_tags(self, api):
586 Create a dictionary of slicetag objects keyed by slice tag ID
589 for tag in api.plshell.GetSliceTags(api.plauth, {'~tagname':Slicetag.ignore_tags}, Slicetag.filter_fields):
590 t = tag['slice_tag_id'], Slicetag(tag)
594 def get_tag_types(self, api):
596 Create a list of tagtype obects keyed by tag name
599 for tag in api.plshell.GetTagTypes(api.plauth, {'~tagname':TagType.ignore_tags}):
600 t = tag['tagname'], TagType(tag)
604 def get_slice(self, api, hrn):
606 Return a Slice object for a single slice
608 slicename = hrn_to_pl_slicename(hrn)
609 slice = api.plshell.GetSlices(api.plauth, [slicename])
611 self.slice = Slice(self, slicename, slice[0])