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