fix slices geni_urn in SliverStatus
[sfa.git] / sfa / managers / aggregate_manager_pl.py
index 11c90a9..b6ac34d 100644 (file)
@@ -1,3 +1,5 @@
+
+
 import datetime
 import time
 import traceback
@@ -6,7 +8,7 @@ import re
 from types import StringTypes
 
 from sfa.util.faults import *
-from sfa.util.xrn import get_authority, hrn_to_urn, urn_to_hrn, Xrn
+from sfa.util.xrn import get_authority, hrn_to_urn, urn_to_hrn, Xrn, urn_to_sliver_id
 from sfa.util.plxrn import slicename_to_hrn, hrn_to_pl_slicename, hostname_to_urn
 from sfa.util.rspec import *
 from sfa.util.specdict import *
@@ -23,19 +25,24 @@ from sfa.plc.aggregate import Aggregate
 from sfa.plc.slices import *
 from sfa.util.version import version_core
 from sfa.rspecs.rspec_version import RSpecVersion
+from sfa.rspecs.sfa_rspec import sfa_rspec_version
+from sfa.rspecs.pg_rspec import pg_rspec_ad_version, pg_rspec_request_version
 from sfa.rspecs.rspec_parser import parse_rspec 
 from sfa.util.sfatime import utcparse
 from sfa.util.callids import Callids
 
 def GetVersion(api):
     xrn=Xrn(api.hrn)
-    return version_core({'interface':'aggregate',
-                         'testbed':'myplc',
-                         'hrn':xrn.get_hrn(),
-                         'input_rspec' : ['PG 2', 'SFA 1'],
-                         'output_rspec' : ["SFA 1"],
-                         'ad_rspec' : ["PG 2", "SFA 1"],
-                         })
+    request_rspec_versions = [dict(pg_rspec_request_version), dict(sfa_rspec_version)]
+    ad_rspec_versions = [dict(pg_rspec_ad_version), dict(sfa_rspec_version)]
+    version_more = {'interface':'aggregate',
+                    'testbed':'myplc',
+                    'hrn':xrn.get_hrn(),
+                    'request_rspec_versions': request_rspec_versions,
+                    'ad_rspec_versions': ad_rspec_versions,
+                    'default_ad_rspec': dict(sfa_rspec_version)
+                    }
+    return version_core(version_more)
 
 def __get_registry_objects(slice_xrn, creds, users):
     """
@@ -72,6 +79,7 @@ def __get_registry_objects(slice_xrn, creds, users):
 
         slice = {}
         
+        # get_expiration always returns a normalized datetime - no need to utcparse
         extime = Credential(string=creds[0]).get_expiration()
         # If the expiration time is > 60 days from now, set the expiration time to 60 days from now
         if extime > datetime.datetime.utcnow() + datetime.timedelta(days=60):
@@ -109,14 +117,14 @@ def SliverStatus(api, slice_xrn, creds, call_id):
     api.logger.info(hrn)
     slicename = hrn_to_pl_slicename(hrn)
     
-    slices = api.plshell.GetSlices(api.plauth, [slicename], ['node_ids','person_ids','name','expires'])
+    slices = api.plshell.GetSlices(api.plauth, [slicename], ['slice_id', 'node_ids','person_ids','name','expires'])
     if len(slices) == 0:        
-        raise Exception("Slice %s not found (used %s as slicename internally)" % slice_xrn, slicename)
+        raise Exception("Slice %s not found (used %s as slicename internally)" % (slice_xrn, slicename))
     slice = slices[0]
     
     # report about the local nodes only
     nodes = api.plshell.GetNodes(api.plauth, {'node_id':slice['node_ids'],'peer_id':None},
-                                 ['hostname', 'site_id', 'boot_state', 'last_contact'])
+                                 ['node_id', 'hostname', 'site_id', 'boot_state', 'last_contact'])
     site_ids = [node['site_id'] for node in nodes]
     sites = api.plshell.GetSites(api.plauth, site_ids, ['site_id', 'login_base'])
     sites_dict = dict ( [ (site['site_id'],site['login_base'] ) for site in sites ] )
@@ -125,7 +133,8 @@ def SliverStatus(api, slice_xrn, creds, call_id):
     top_level_status = 'unknown'
     if nodes:
         top_level_status = 'ready'
-    result['geni_urn'] = Xrn(slice_xrn, 'slice').get_urn()
+    slice_urn = Xrn(slice_xrn, 'slice').get_urn()
+    result['geni_urn'] = slice_urn
     result['pl_login'] = slice['name']
     result['pl_expires'] = datetime.datetime.fromtimestamp(slice['expires']).ctime()
     
@@ -137,7 +146,8 @@ def SliverStatus(api, slice_xrn, creds, call_id):
         res['pl_last_contact'] = node['last_contact']
         if node['last_contact'] is not None:
             res['pl_last_contact'] = datetime.datetime.fromtimestamp(node['last_contact']).ctime()
-        res['geni_urn'] = hostname_to_urn(api.hrn, sites_dict[node['site_id']], node['hostname'])
+        sliver_id = urn_to_sliver_id(slice_urn, slice['slice_id'], node['node_id']) 
+        res['geni_urn'] = sliver_id
         if node['boot_state'] == 'boot':
             res['geni_status'] = 'ready'
         else:
@@ -181,30 +191,58 @@ def CreateSliver(api, slice_xrn, creds, rspec_string, users, call_id):
     nodes = api.plshell.GetNodes(api.plauth, slice['node_ids'], ['hostname'])
     current_slivers = [node['hostname'] for node in nodes] 
     rspec = parse_rspec(rspec_string)
-    requested_slivers = rspec.get_nodes_with_slivers()
-     
+    requested_slivers = [str(host) for host in rspec.get_nodes_with_slivers()]
     # remove nodes not in rspec
     deleted_nodes = list(set(current_slivers).difference(requested_slivers))
 
     # add nodes from rspec
     added_nodes = list(set(requested_slivers).difference(current_slivers))
 
+    # get sliver attributes
+    requested_slice_attributes = rspec.get_slice_attributes()
+    removed_slice_attributes = []
+    existing_slice_attributes = []    
+    for slice_tag in api.plshell.GetSliceTags(api.plauth, {'slice_id': slice['slice_id']}):
+        attribute_found=False
+        for requested_attribute in requested_slice_attributes:
+            if requested_attribute['name'] == slice_tag['tagname'] and \
+               requested_attribute['value'] == slice_tag['value']:
+                attribute_found=True
+
+        if not attribute_found: 
+            removed_slice_attributes.append(slice_tag)
+        else:
+            existing_slice_attributes.append(slice_tag)  
+         
     try:
         if peer:
             api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice['slice_id'], peer)
 
         api.plshell.AddSliceToNodes(api.plauth, slice['name'], added_nodes) 
         api.plshell.DeleteSliceFromNodes(api.plauth, slice['name'], deleted_nodes)
-
-        # TODO: update slice tags
-        #network.updateSliceTags()
+        # remove stale attributes
+        for attribute in removed_slice_attributes:
+            try:
+                api.plshell.DeleteSliceTag(api.plauth, attribute['slice_tag_id'])
+            except Exception, e:
+                api.logger.warn('Failed to remove sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
+                                % (name, value,  node_id, str(e)))
+
+        # add requested_attributes
+        for attribute in requested_slice_attributes:
+            try:
+                name, value, node_id = attribute['name'], attribute['value'], attribute.get('node_id', None)
+                api.plshell.AddSliceTag(api.plauth, slice['name'], name, value, node_id)
+            except Exception, e:
+                api.logger.warn('Failed to add sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
+                                % (name, value,  node_id, str(e)))
 
     finally:
         if peer:
             api.plshell.BindObjectToPeer(api.plauth, 'slice', slice.id, peer, 
                                          slice.peer_id)
 
-    return aggregate.get_rspec(slice_xrn=slice_xrn)
+    return aggregate.get_rspec(slice_xrn=slice_xrn, version=rspec.version)
 
 
 def RenewSliver(api, xrn, creds, expiration_time, call_id):
@@ -277,8 +315,8 @@ def DeleteSliver(api, xrn, creds, call_id):
     return 1
 
 # xxx Thierry : caching at the aggregate level sounds wrong...
-caching=True
-#caching=False
+#caching=True
+caching=False
 def ListSlices(api, creds, call_id):
     if Callids().already_handled(call_id): return []
     # look in cache first
@@ -305,9 +343,13 @@ def ListResources(api, creds, options,call_id):
     (hrn, type) = urn_to_hrn(xrn)
 
     # get the rspec's return format from options
-    rspec_version = RSpecVersion(options.get('rspec_version', 'SFA 1'))
-    version_string = "rspec_%s_%s" % (rspec_version.format, rspec_version.version)
-    
+    rspec_version = RSpecVersion(options.get('rspec_version'))
+    version_string = "rspec_%s" % (rspec_version.get_version_name())
+
+    #panos adding the info option to the caching key (can be improved)
+    if options.get('info'):
+       version_string = version_string + "_"+options.get('info', 'default')
+
     # look in cache first
     if caching and api.cache and not xrn:
         rspec = api.cache.get(version_string)
@@ -315,14 +357,12 @@ def ListResources(api, creds, options,call_id):
             api.logger.info("aggregate.ListResources: returning cached value for hrn %s"%hrn)
             return rspec 
 
-    aggregate = Aggregate(api)
+    #aggregate = Aggregate(api)
+    #panos: passing user-defined options
+    #print "manager options = ",options
+    aggregate = Aggregate(api, options)
 
-    if xrn:
-        # get this rspec for the specified slice 
-        rspec =  aggregate.get_rspec(slice_xrn=hrn, version=rspec_version)
-    else:
-        # generate rspec in both pg and sfa formats
-        rspec = aggregate.get_rspec(version=rspec_version)
+    rspec =  aggregate.get_rspec(slice_xrn=xrn, version=rspec_version)
 
     # cache the result
     if caching and api.cache and not xrn: