Setting tag sfa-1.1-3
[sfa.git] / sfa / plc / network.py
index 41bae48..e97565c 100644 (file)
@@ -1,14 +1,14 @@
 from __future__ import with_statement
+import sys
 import re
 import socket
-from sfa.util.xrn import get_authority
-from sfa.util.plxrn import hrn_to_pl_slicename, hostname_to_urn
-from sfa.util.faults import *
-from xmlbuilder import XMLBuilder
-from lxml import etree
-import sys
 from StringIO import StringIO
+from lxml import etree
+from xmlbuilder import XMLBuilder
 
+from sfa.util.faults import InvalidRSpec
+from sfa.util.xrn import get_authority
+from sfa.util.plxrn import hrn_to_pl_slicename, hostname_to_urn
 
 class Sliver:
     def __init__(self, node):
@@ -133,9 +133,12 @@ class Slice:
         for i in self.slice_tag_ids:
             try: 
                 tag = self.network.lookupSliceTag(i)                 
-                if tag.tagname == tagname: 
-                    if not (node and node.id != tag.node_id): 
-                        tags.append(tag) 
+                if tag.tagname == tagname:
+                    if node:
+                        if node.id == tag.node_id:
+                            tags.append(tag)
+                    elif not tag.node_id:
+                        tags.append(tag)
             except InvalidRSpec, e: 
                 # As they're not needed, we ignore some tag types from 
                 # GetSliceTags call. See Slicetag.ignore_tags 
@@ -146,16 +149,19 @@ class Slice:
     Use with tags that have only one instance
     """
     def get_tag(self, tagname, node = None):
-        try: 
-            for i in self.slice_tag_ids: 
+        for i in self.slice_tag_ids:
+            try:
                 tag = self.network.lookupSliceTag(i) 
                 if tag.tagname == tagname: 
-                    if (not node) or (node.id == tag.node_id): 
+                    if node:
+                        if node.id == tag.node_id:
+                            return tag
+                    elif not tag.node_id:
                         return tag 
-        except InvalidRSpec, e: 
-            # As they're not needed, we ignore some tag types from 
-            # GetSliceTags call. See Slicetag.ignore_tags 
-            pass 
+            except InvalidRSpec, e:
+                # As they're not needed, we ignore some tag types from
+                # GetSliceTags call. See Slicetag.ignore_tags
+                pass
         return None
         
     def get_nodes(self):
@@ -166,9 +172,9 @@ class Slice:
         return n
 
     # Add a new slice tag   
-    def add_tag(self, tagname, value, node = None, role_id = 30):
+    def add_tag(self, tagname, value, node = None, role = "user"):
         tt = self.network.lookupTagType(tagname)
-        if not tt.permit_update(role_id):
+        if not tt.permit_update(role):
             raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
         tag = Slicetag()
         tag.initialize(tagname, value, node, self.network)
@@ -177,23 +183,28 @@ class Slice:
         return tag
     
     # Update a slice tag if it exists, else add it             
-    def update_tag(self, tagname, value, node = None, role_id = 30):
+    def update_tag(self, tagname, value, node = None, role = "user"):
         tag = self.get_tag(tagname, node)
+        if tag and tag.value == value:
+            return tag
+
+        tt = self.network.lookupTagType(tagname)
+        if not tt.permit_update(role):
+            raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
+
         if tag:
-            if not tag.permit_update(role_id, value):
-                raise InvalidRSpec("permission denied to modify '%s' tag" % tagname)
             tag.change(value)
         else:
-            tag = self.add_tag(tagname, value, node, role_id)
+            tag = self.add_tag(tagname, value, node, role)
         return tag
             
-    def update_multi_tag(self, tagname, value, node = None, role_id = 30):
+    def update_multi_tag(self, tagname, value, node = None, role = "user"):
         tags = self.get_multi_tag(tagname, node)
         for tag in tags:
             if tag and tag.value == value:
                 break
         else:
-            tag = self.add_tag(tagname, value, node, role_id)
+            tag = self.add_tag(tagname, value, node, role)
         return tag
             
     def tags_to_xml(self, xml, node = None):
@@ -218,7 +229,6 @@ class Slice:
 
 class Slicetag:
     newid = -1 
-#    filter_fields = ['slice_tag_id','slice_id','tagname','value','node_id','category','min_role_id'] 
     filter_fields = ['slice_tag_id','slice_id','tagname','value','node_id','category'] 
     ignore_tags = ['hmac','ssh_key']
     def __init__(self, tag = None):
@@ -230,7 +240,6 @@ class Slicetag:
         self.value = tag['value']
         self.node_id = tag['node_id']
         self.category = tag['category']
-#        self.min_role_id = tag['min_role_id']
         self.status = None
 
     # Create a new slicetag that will be written to the DB later
@@ -246,17 +255,8 @@ class Slicetag:
         else:
             self.node_id = None
         self.category = tt.category
-#        self.min_role_id = tt.min_role_id
         self.status = "new"
 
-    def permit_update(self, role_id, value = None):
-        if value and self.value == value:
-            return True
-        # xxx FIXME - the new model in PLCAPI has roles and not min_role_id
-        #if role_id > self.min_role_id:
-        #    return False
-        return False
-        
     def change(self, value):
         if self.value != value:
             self.value = value
@@ -282,12 +282,11 @@ class Slicetag:
     
     def write(self, api):
         if self.was_added():
-            api.plshell.AddSliceTag(api.plauth, self.slice_id, 
-                                    self.tagname, self.value, self.node_id)
+            api.driver.AddSliceTag(self.slice_id, self.tagname, self.value, self.node_id)
         elif self.was_changed():
-            api.plshell.UpdateSliceTag(api.plauth, self.id, self.value)
+            api.driver.UpdateSliceTag(self.id, self.value)
         elif self.was_deleted():
-            api.plshell.DeleteSliceTag(api.plauth, self.id)
+            api.driver.DeleteSliceTag(self.id)
 
 
 class TagType:
@@ -296,7 +295,7 @@ class TagType:
         self.id = tagtype['tag_type_id']
         self.category = tagtype['category']
         self.tagname = tagtype['tagname']
-#        self.min_role_id = tagtype['min_role_id']
+        self.roles = tagtype['roles']
         self.multi = False
         self.in_rspec = False
         if self.category == 'slice/rspec':
@@ -304,10 +303,9 @@ class TagType:
         if self.tagname in ['codemux', 'ip_addresses', 'vsys']:
             self.multi = True
 
-    def permit_update(self, role_id):
-        # XXX FIXME ditto
-        #if role_id > self.min_role_id:
-        #    return False
+    def permit_update(self, role):
+        if role in self.roles:
+            return True
         return False
         
 
@@ -327,15 +325,29 @@ class Network:
         self.tags = self.get_slice_tags(api)
         self.tagtypes = self.get_tag_types(api)
         self.slice = None
+        self.sitemap = {}
+        for s in self.sites:
+            site = self.sites[s]
+            self.sitemap[site.idtag] = site.id
+
+    def lookupSiteIdtag(self, name):
+        """ Lookup site id from name """
+        val = None
+        try:
+            val = self.sitemap[name]
+        except:
+            raise InvalidRSpec("site name '%s' not found" % name)
+        return val
     
     def lookupSite(self, id):
         """ Lookup site based on id or idtag value """
         val = None
         if isinstance(id, basestring):
-            id = int(id.lstrip('s'))
+            id = self.lookupSiteIdtag(id)
         try:
             val = self.sites[id]
         except:
+            self.api.logger.error("Invalid RSpec: site ID %s not found" % id )
             raise InvalidRSpec("site ID %s not found" % id)
         return val
     
@@ -460,6 +472,10 @@ class Network:
             if not relaxng(tree):
                 error = relaxng.error_log.last_error
                 message = "%s (line %s)" % (error.message, error.line)
+                self.api.logger.error("failed to validate rspec %r"%message)
+                self.api.logger.debug("---------- XML input BEG")
+                self.api.logger.debug(xml)
+                self.api.logger.debug("---------- XML input END")
                 raise InvalidRSpec(message)
 
         self.rspec = rspec
@@ -508,9 +524,10 @@ class Network:
         Write any slice tags that have been added or modified back to the DB
         """
         for tag in self.getSliceTags():
-            if tag.category == 'slice/rspec' and not tag.was_updated() and tag.permit_update(None, 30):
-                # The user wants to delete this tag
-                tag.delete()
+            if tag.category == 'slice/rspec' and not tag.was_updated():
+                tt = self.lookupTagType(tag.tagname)
+                if tt.permit_update("user"):
+                    tag.delete()
 
         # Update slice tags in database
         for tag in self.getSliceTags():
@@ -542,7 +559,7 @@ class Network:
         Create a dictionary of site objects keyed by site ID
         """
         tmp = []
-        for site in api.plshell.GetSites(api.plauth, {'peer_id': None}):
+        for site in api.driver.GetSites({'peer_id': None}):
             t = site['site_id'], Site(self, site)
             tmp.append(t)
         return dict(tmp)
@@ -553,9 +570,13 @@ class Network:
         Create a dictionary of node objects keyed by node ID
         """
         tmp = []
-        for node in api.plshell.GetNodes(api.plauth, {'peer_id': None}):
-            t = node['node_id'], Node(self, node)
-            tmp.append(t)
+        for node in api.driver.GetNodes({'peer_id': None}):
+            try:
+                t = node['node_id'], Node(self, node)
+                tmp.append(t)
+            except:
+                self.api.logger.error("Failed to add node %s (%s) to RSpec" % (node['hostname'], node['node_id']))
+                 
         return dict(tmp)
 
     def get_ifaces(self, api):
@@ -563,7 +584,7 @@ class Network:
         Create a dictionary of node objects keyed by node ID
         """
         tmp = []
-        for iface in api.plshell.GetInterfaces(api.plauth):
+        for iface in api.driver.GetInterfaces():
             t = iface['interface_id'], Iface(self, iface)
             tmp.append(t)
         return dict(tmp)
@@ -573,7 +594,7 @@ class Network:
         Create a dictionary of slicetag objects keyed by slice tag ID
         """
         tmp = []
-        for tag in api.plshell.GetSliceTags(api.plauth, {'~tagname':Slicetag.ignore_tags}, Slicetag.filter_fields): 
+        for tag in api.driver.GetSliceTags({'~tagname':Slicetag.ignore_tags}, Slicetag.filter_fields): 
             t = tag['slice_tag_id'], Slicetag(tag)
             tmp.append(t)
         return dict(tmp)
@@ -583,7 +604,7 @@ class Network:
         Create a list of tagtype obects keyed by tag name
         """
         tmp = []
-        for tag in api.plshell.GetTagTypes(api.plauth, {'~tagname':TagType.ignore_tags}):
+        for tag in api.driver.GetTagTypes({'~tagname':TagType.ignore_tags}):
             t = tag['tagname'], TagType(tag)
             tmp.append(t)
         return dict(tmp)
@@ -593,7 +614,7 @@ class Network:
         Return a Slice object for a single slice
         """
         slicename = hrn_to_pl_slicename(hrn)
-        slice = api.plshell.GetSlices(api.plauth, [slicename])
+        slice = api.driver.GetSlices([slicename])
         if len(slice):
             self.slice = Slice(self, slicename, slice[0])
             return self.slice