namespace module is gone, plxrn provides PL-specific translations
[sfa.git] / sfa / plc / network.py
1 from __future__ import with_statement
2 import re
3 import socket
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
8 from lxml import etree
9 import sys
10 from StringIO import StringIO
11
12
13 class Sliver:
14     def __init__(self, node):
15         self.node = node
16         self.network = node.network
17         self.slice = node.network.slice
18         
19     def toxml(self, xml):
20         with xml.sliver:
21             self.slice.tags_to_xml(xml, self.node)
22
23         
24 class Iface:
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']
33
34     def toxml(self, xml):
35         """
36         Just print out bwlimit right now
37         """
38         if self.bwlimit:
39             with xml.bw_limit(units="kbps"):
40                 xml << str(self.bwlimit / 1000)
41
42
43 class Node:
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']
51         self.sliver = None
52         self.whitelist = node['slice_ids_whitelist']
53
54     def get_primary_iface(self):
55         for id in self.iface_ids:
56             iface = self.network.lookupIface(id)
57             if iface.primary:
58                 return iface
59         return None
60         
61     def get_site(self):
62         return self.network.lookupSite(self.site_id)
63     
64     def add_sliver(self):
65         self.sliver = Sliver(self)
66
67     def toxml(self, xml):
68         slice = self.network.slice
69         if self.whitelist and not self.sliver:
70             if not slice or slice.id not in self.whitelist:
71                 return
72
73         with xml.node(id = self.idtag):
74             with xml.hostname:
75                 xml << self.hostname
76             iface = self.get_primary_iface()
77             if iface:
78                 iface.toxml(xml)
79             if self.sliver:
80                 self.sliver.toxml(xml)
81     
82
83 class Site:
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']
89         self.node_ids.sort()
90         self.name = site['abbreviated_name']
91         self.tag = site['login_base']
92         self.public = site['is_public']
93         self.enabled = site['enabled']
94         self.links = set()
95         self.whitelist = False
96
97     def get_sitenodes(self):
98         n = []
99         for i in self.node_ids:
100             n.append(self.network.lookupNode(i))
101         return n
102     
103     def toxml(self, xml):
104         if not (self.public and self.enabled and self.node_ids):
105             return
106         with xml.site(id = self.idtag):
107             with xml.name:
108                 xml << self.name
109             for node in self.get_sitenodes():
110                 node.toxml(xml)
111    
112     
113 class Slice:
114     def __init__(self, network, hrn, slice):
115         self.hrn = hrn
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']
122     
123     """
124     Use with tags that can have more than one instance
125     """
126     def get_multi_tag(self, tagname, node = None):
127         tags = []
128         for i in self.slice_tag_ids:
129             try: 
130                 tag = self.network.lookupSliceTag(i)                 
131                 if tag.tagname == tagname: 
132                     if not (node and node.id != tag.node_id): 
133                         tags.append(tag) 
134             except InvalidRSpec, e: 
135                 # As they're not needed, we ignore some tag types from 
136                 # GetSliceTags call. See Slicetag.ignore_tags 
137                 pass 
138         return tags
139         
140     """
141     Use with tags that have only one instance
142     """
143     def get_tag(self, tagname, node = None):
144         try: 
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): 
149                         return tag 
150         except InvalidRSpec, e: 
151             # As they're not needed, we ignore some tag types from 
152             # GetSliceTags call. See Slicetag.ignore_tags 
153             pass 
154         return None
155         
156     def get_nodes(self):
157         n = []
158         for id in self.node_ids:
159             if id in self.network.nodes:
160                 n.append(self.network.nodes[id])
161         return n
162
163     # Add a new slice tag   
164     def add_tag(self, tagname, value, node = None, role_id = 40):
165         tt = self.network.lookupTagType(tagname)
166         if not tt.permit_update(role_id):
167             raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
168         tag = Slicetag()
169         tag.initialize(tagname, value, node, self.network)
170         self.network.tags[tag.id] = tag
171         self.slice_tag_ids.append(tag.id)
172         return tag
173     
174     # Update a slice tag if it exists, else add it             
175     def update_tag(self, tagname, value, node = None, role_id = 40):
176         tag = self.get_tag(tagname, node)
177         if tag:
178             if not tag.permit_update(role_id, value):
179                 raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
180             tag.change(value)
181         else:
182             tag = self.add_tag(tagname, value, node, role_id)
183         return tag
184             
185     def update_multi_tag(self, tagname, value, node = None, role_id = 40):
186         tags = self.get_multi_tag(tagname, node)
187         for tag in tags:
188             if tag and tag.value == value:
189                 break
190         else:
191             tag = self.add_tag(tagname, value, node, role_id)
192         return tag
193             
194     def tags_to_xml(self, xml, node = None):
195         tagtypes = self.network.getTagTypes()
196         for tt in tagtypes:
197             if tt.in_rspec:
198                 if tt.multi:
199                     tags = self.get_multi_tag(tt.tagname, node)
200                     for tag in tags:
201                         if not tag.was_deleted():  ### Debugging
202                             xml << (tag.tagname, tag.value)
203                 else:
204                     tag = self.get_tag(tt.tagname, node)
205                     if tag:
206                         if not tag.was_deleted():   ### Debugging
207                             xml << (tag.tagname, tag.value)
208
209     def toxml(self, xml):
210         with xml.sliver_defaults:
211             self.tags_to_xml(xml)
212
213
214 class Slicetag:
215     newid = -1 
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):
219         if not tag:
220             return
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']
228         self.status = None
229
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
234         Slicetag.newid -=1
235         self.slice_id = network.slice.id
236         self.tagname = tagname
237         self.value = value
238         if node:
239             self.node_id = node.id
240         else:
241             self.node_id = None
242         self.category = tt.category
243         self.min_role_id = tt.min_role_id
244         self.status = "new"
245
246     def permit_update(self, role_id, value = None):
247         if value and self.value == value:
248             return True
249         if role_id > self.min_role_id:
250             return False
251         return True
252         
253     def change(self, value):
254         if self.value != value:
255             self.value = value
256             self.status = "change"
257         else:
258             self.status = "updated"
259         
260     # Mark a tag as deleted
261     def delete(self):
262         self.status = "delete"
263
264     def was_added(self):
265         return (self.id < 0)
266
267     def was_changed(self):
268         return (self.status == "change")
269
270     def was_deleted(self):
271         return (self.status == "delete")
272
273     def was_updated(self):
274         return (self.status != None)
275     
276     def write(self, api):
277         if self.was_added():
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)
284
285
286 class TagType:
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']
293         self.multi = False
294         self.in_rspec = False
295         if self.category == 'slice/rspec':
296             self.in_rspec = True
297         if self.tagname in ['codemux', 'ip_addresses', 'vsys']:
298             self.multi = True
299
300     def permit_update(self, role_id):
301         if role_id > self.min_role_id:
302             return False
303         return True
304         
305
306 class Network:
307     """
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
312     """
313     def __init__(self, api, type = "SFA"):
314         self.api = api
315         self.type = type
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)
321         self.slice = None
322     
323     def lookupSite(self, id):
324         """ Lookup site based on id or idtag value """
325         val = None
326         if isinstance(id, basestring):
327             id = int(id.lstrip('s'))
328         try:
329             val = self.sites[id]
330         except:
331             raise InvalidRSpec("site ID %s not found" % id)
332         return val
333     
334     def getSites(self):
335         sites = []
336         for s in self.sites:
337             sites.append(self.sites[s])
338         return sites
339         
340     def lookupNode(self, id):
341         """ Lookup node based on id or idtag value """
342         val = None
343         if isinstance(id, basestring):
344             id = int(id.lstrip('n'))
345         try:
346             val = self.nodes[id]
347         except:
348             raise InvalidRSpec("node ID %s not found" % id)
349         return val
350     
351     def getNodes(self):
352         nodes = []
353         for n in self.nodes:
354             nodes.append(self.nodes[n])
355         return nodes
356     
357     def lookupIface(self, id):
358         """ Lookup iface based on id or idtag value """
359         val = None
360         if isinstance(id, basestring):
361             id = int(id.lstrip('i'))
362         try:
363             val = self.ifaces[id]
364         except:
365             raise InvalidRSpec("interface ID %s not found" % id)
366         return val
367     
368     def getIfaces(self):
369         ifaces = []
370         for i in self.ifaces:
371             ifaces.append(self.ifaces[i])
372         return ifaces
373     
374     def nodesWithSlivers(self):
375         nodes = []
376         for n in self.nodes:
377             node = self.nodes[n]
378             if node.sliver:
379                 nodes.append(node)
380         return nodes
381             
382     def lookupSliceTag(self, id):
383         val = None
384         try:
385             val = self.tags[id]
386         except:
387             raise InvalidRSpec("slicetag ID %s not found" % id)
388         return val
389     
390     def getSliceTags(self):
391         tags = []
392         for t in self.tags:
393             tags.append(self.tags[t])
394         return tags
395     
396     def lookupTagType(self, name):
397         val = None
398         try:
399             val = self.tagtypes[name]
400         except:
401             raise InvalidRSpec("tag %s not found" % name)
402         return val
403     
404     def getTagTypes(self):
405         tags = []
406         for t in self.tagtypes:
407             tags.append(self.tagtypes[t])
408         return tags
409     
410     def __process_attributes(self, element, node=None):
411         """
412         Process the elements under <sliver_defaults> or <sliver>
413         """
414         if element is None:
415             return 
416
417         tagtypes = self.getTagTypes()
418         for tt in tagtypes:
419             if tt.in_rspec:
420                 if tt.multi:
421                     for e in element.iterfind("./" + tt.tagname):
422                         self.slice.update_multi_tag(tt.tagname, e.text, node)
423                 else:
424                     e = element.find("./" + tt.tagname)
425                     if e is not None:
426                         self.slice.update_tag(tt.tagname, e.text, node)
427
428     def addRSpec(self, xml, schema=None):
429         """
430         Annotate the objects in the Network with information from the RSpec
431         """
432         try:
433             tree = etree.parse(StringIO(xml))
434         except etree.XMLSyntaxError:
435             message = str(sys.exc_info()[1])
436             raise InvalidRSpec(message)
437
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)
446
447         if schema:
448             # Validate the incoming request against the RelaxNG schema
449             relaxng_doc = etree.parse(schema)
450             relaxng = etree.RelaxNG(relaxng_doc)
451         
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)
456
457         self.rspec = rspec
458
459         defaults = rspec.find(".//sliver_defaults")
460         self.__process_attributes(defaults)
461
462         # Find slivers under node elements
463         for sliver in rspec.iterfind("./network/site/node/sliver"):
464             elem = sliver.getparent()
465             try:
466                 node = self.lookupNode(elem.get("id"))
467             except:
468                 # Don't worry about nodes from other aggregates
469                 pass
470             else:
471                 node.add_sliver()
472                 self.__process_attributes(sliver, node)
473
474         # Find slivers that specify nodeid
475         for sliver in rspec.iterfind("./request/sliver[@nodeid]"):
476             try:
477                 node = self.lookupNode(sliver.get("nodeid"))
478             except:
479                 # Don't worry about nodes from other aggregates
480                 pass
481             else:
482                 node.add_sliver()
483                 self.__process_attributes(sliver, node)
484
485         return
486
487     def addSlice(self):
488         """
489         Annotate the objects in the Network with information from the slice
490         """
491         slice = self.slice
492         if not slice:
493             raise InvalidRSpec("no slice associated with network")
494
495         for node in slice.get_nodes():
496             node.add_sliver()
497
498     def updateSliceTags(self):
499         """
500         Write any slice tags that have been added or modified back to the DB
501         """
502         for tag in self.getSliceTags():
503             if tag.category == 'slice/rspec' and not tag.was_updated() and tag.permit_update(None, 40):
504                 # The user wants to delete this tag
505                 tag.delete()
506
507         # Update slice tags in database
508         for tag in self.getSliceTags():
509             if tag.slice_id == self.slice.id:
510                 tag.write(self.api) 
511
512     def toxml(self):
513         """
514         Produce XML directly from the topology specification.
515         """
516         xml = XMLBuilder(format = True, tab_step = "  ")
517         with xml.RSpec(type=self.type):
518             if self.slice:
519                 element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
520             else:
521                 element = xml.network(name=self.api.hrn)
522                 
523             with element:
524                 if self.slice:
525                     self.slice.toxml(xml)
526                 for site in self.getSites():
527                     site.toxml(xml)
528
529         header = '<?xml version="1.0"?>\n'
530         return header + str(xml)
531
532     def get_sites(self, api):
533         """
534         Create a dictionary of site objects keyed by site ID
535         """
536         tmp = []
537         for site in api.plshell.GetSites(api.plauth, {'peer_id': None}):
538             t = site['site_id'], Site(self, site)
539             tmp.append(t)
540         return dict(tmp)
541
542
543     def get_nodes(self, api):
544         """
545         Create a dictionary of node objects keyed by node ID
546         """
547         tmp = []
548         for node in api.plshell.GetNodes(api.plauth, {'peer_id': None}):
549             t = node['node_id'], Node(self, node)
550             tmp.append(t)
551         return dict(tmp)
552
553     def get_ifaces(self, api):
554         """
555         Create a dictionary of node objects keyed by node ID
556         """
557         tmp = []
558         for iface in api.plshell.GetInterfaces(api.plauth):
559             t = iface['interface_id'], Iface(self, iface)
560             tmp.append(t)
561         return dict(tmp)
562
563     def get_slice_tags(self, api):
564         """
565         Create a dictionary of slicetag objects keyed by slice tag ID
566         """
567         tmp = []
568         for tag in api.plshell.GetSliceTags(api.plauth, {'~tagname':Slicetag.ignore_tags}, Slicetag.filter_fields): 
569             t = tag['slice_tag_id'], Slicetag(tag)
570             tmp.append(t)
571         return dict(tmp)
572     
573     def get_tag_types(self, api):
574         """
575         Create a list of tagtype obects keyed by tag name
576         """
577         tmp = []
578         for tag in api.plshell.GetTagTypes(api.plauth, {'~tagname':TagType.ignore_tags}):
579             t = tag['tagname'], TagType(tag)
580             tmp.append(t)
581         return dict(tmp)
582     
583     def get_slice(self, api, hrn):
584         """
585         Return a Slice object for a single slice
586         """
587         slicename = hrn_to_pl_slicename(hrn)
588         slice = api.plshell.GetSlices(api.plauth, [slicename])
589         if len(slice):
590             self.slice = Slice(self, slicename, slice[0])
591             return self.slice
592         else:
593             return None
594     
595