call utcparse before exiting get_expiration istead of calling it when timestamp is...
[sfa.git] / sfa / rspecs / rspec.py
index d35fb78..f2fa662 100755 (executable)
@@ -4,24 +4,26 @@ from StringIO import StringIO
 from datetime import datetime, timedelta
 from sfa.util.xrn import *
 from sfa.util.plxrn import hostname_to_urn
-from sfa.util.config import Config  
 from sfa.util.faults import SfaNotImplemented, InvalidRSpec
 
 class RSpec:
     header = '<?xml version="1.0"?>\n'
     template = """<RSpec></RSpec>"""
-    namespaces = {}
-    config = Config()
     xml = None
     type = None
+    version = None
+    namespaces = None
+    user_options = {}
   
-    def __init__(self, rspec="", namespaces={}):
+    def __init__(self, rspec="", namespaces={}, type=None, user_options={}):
+        self.type = type
+        self.user_options = user_options
         if rspec:
             self.parse_rspec(rspec, namespaces)
         else:
             self.create()
 
-    def create(self, type="advertisement"):
+    def create(self):
         """
         Create root element
         """
@@ -31,7 +33,7 @@ class RSpec:
         generated_ts = now.strftime(date_format)
         expires_ts = (now + timedelta(hours=1)).strftime(date_format) 
         self.parse_rspec(self.template, self.namespaces)
-        self.xml.set('valid_until', expires_ts)
+        self.xml.set('expires', expires_ts)
         self.xml.set('generated', generated_ts)
     
     def parse_rspec(self, rspec, namespaces={}):
@@ -45,13 +47,15 @@ class RSpec:
             # 'rspec' file doesnt exist. 'rspec' is proably an xml string
             try:
                 tree = etree.parse(StringIO(rspec), parser)
-            except:
-                raise InvalidRSpec('Must specify a xml file or xml string. Received: ' + rspec )
-
+            except Exception, e:
+                raise InvalidRSpec(str(e))
         self.xml = tree.getroot()  
         if namespaces:
            self.namespaces = namespaces
 
+    def xpath(self, xpath):
+        return this.xml.xpath(xpath, namespaces=self.namespaces)
+
     def add_attribute(self, elem, name, value):
         """
         Add attribute to specified etree element    
@@ -86,6 +90,25 @@ class RSpec:
                     if opt.text == value:
                         elem.remove(opt)
 
+    def remove_element(self, element_name, root_node = None):
+        """
+        Removes all occurences of an element from the tree. Start at 
+        specified root_node if specified, otherwise start at tree's root.   
+        """
+        if not root_node:
+            root_node = self.xml
+
+        if not element_name.startswith('//'):
+            element_name = '//' + element_name
+
+        elements = root_node.xpath('%s ' % element_name, namespaces=self.namespaces)
+        for element in elements:
+            parent = element.getparent()
+            parent.remove(element)
+         
+
+    def merge(self, in_rspec):
+        pass
 
     def validate(self, schema):
         """
@@ -100,11 +123,35 @@ class RSpec:
             raise InvalidRSpec(message)
         return True
         
+    def cleanup(self):
+        """
+        Optional method which inheriting classes can choose to implent. 
+        """
+        pass 
+
+    def _process_slivers(self, slivers):
+        """
+        Creates a dict of sliver details for each sliver host
+        
+        @param slivers a single hostname, list of hostanmes or list of dicts keys on hostname,
+        Returns a list of dicts 
+        """
+        if not isinstance(slivers, list):
+            slivers = [slivers]
+        dicts = []
+        for sliver in slivers:
+            if isinstance(sliver, dict):
+                dicts.append(sliver)
+            elif isinstance(sliver, basestring):
+                dicts.append({'hostname': sliver}) 
+        return dicts
 
     def __str__(self):
         return self.toxml()
 
-    def toxml(self):
+    def toxml(self, cleanup=False):
+        if cleanup:
+            self.cleanup()
         return self.header + etree.tostring(self.xml, pretty_print=True)  
         
     def save(self, filename):