Merge branch 'master' into senslab2
[sfa.git] / sfa / managers / slice_manager_slab.py
1
2 import sys
3 import time,datetime
4 from StringIO import StringIO
5 from types import StringTypes
6 from copy import deepcopy
7 from copy import copy
8 from lxml import etree
9
10 from sfa.util.sfalogging import logger
11 #from sfa.util.sfalogging import sfa_logger
12 #from sfa.util.rspecHelper import merge_rspecs
13 from sfa.util.xrn import Xrn, urn_to_hrn, hrn_to_urn
14 from sfa.util.plxrn import hrn_to_pl_slicename
15 #from sfa.util.rspec import *
16 #from sfa.util.specdict import *
17 from sfa.util.faults import *
18 from sfa.util.record import SfaRecord
19 #from sfa.rspecs.pg_rspec import PGRSpec
20 #from sfa.rspecs.sfa_rspec import SfaRSpec
21 from sfa.rspecs.rspec_converter import RSpecConverter
22 #from sfa.rspecs.rspec_parser import parse_rspec    
23 #from sfa.rspecs.rspec_version import RSpecVersion
24 #from sfa.rspecs.sfa_rspec import sfa_rspec_version
25 #from sfa.rspecs.pg_rspec import pg_rspec_ad_version, pg_rspec_request_version
26 from sfa.client.client_helper import sfa_to_pg_users_arg
27 from sfa.rspecs.version_manager import VersionManager
28
29 #from sfa.rspecs.rspec import RSpec 
30 from sfa.util.policy import Policy
31 from sfa.util.prefixTree import prefixTree
32 #from sfa.util.sfaticket import *
33 from sfa.trust.credential import Credential
34 #from sfa.util.threadmanager import ThreadManager
35 #import sfa.util.xmlrpcprotocol as xmlrpcprotocol     
36 #import sfa.plc.peers as peers
37 from sfa.util.version import version_core
38 from sfa.util.callids import Callids
39 #from sfa.senslab.api import *
40
41
42 #api=SfaAPI(interface='slicemgr')
43
44 def _call_id_supported(api, server):
45     """
46     Returns true if server support the optional call_id arg, false otherwise.
47     """
48     server_version = api.get_cached_server_version(server)
49
50     if 'sfa' in server_version:
51         code_tag = server_version['code_tag']
52         code_tag_parts = code_tag.split("-")
53
54         version_parts = code_tag_parts[0].split(".")
55         major, minor = version_parts[0:2]
56         rev = code_tag_parts[1]
57         if int(major) > 1:
58             if int(minor) > 0 or int(rev) > 20:
59                 return True
60     return False
61
62 # we have specialized xmlrpclib.ServerProxy to remember the input url
63 # OTOH it's not clear if we're only dealing with XMLRPCServerProxy instances
64 def get_serverproxy_url (server):
65     try:
66         return server.get_url()
67     except:
68         logger.warning("GetVersion, falling back to xmlrpclib.ServerProxy internals")
69         return server._ServerProxy__host + server._ServerProxy__handler 
70
71 def GetVersion(api):
72     # peers explicitly in aggregates.xml
73     peers =dict ([ (peername,get_serverproxy_url(v)) for (peername,v) in api.aggregates.iteritems()
74                    if peername != api.hrn])
75     version_manager = VersionManager()
76     ad_rspec_versions = []
77     request_rspec_versions = []
78     for rspec_version in version_manager.versions:
79         if rspec_version.content_type in ['*', 'ad']:
80             ad_rspec_versions.append(rspec_version.to_dict())
81         if rspec_version.content_type in ['*', 'request']:
82             request_rspec_versions.append(rspec_version.to_dict())
83     default_rspec_version = version_manager.get_version("sfa 1").to_dict()
84     xrn=Xrn(api.hrn, 'authority+sa')
85     version_more = {'interface':'slicemgr',
86                     'hrn' : xrn.get_hrn(),
87                     'urn' : xrn.get_urn(),
88                     'peers': peers,
89                     'request_rspec_versions': request_rspec_versions,
90                     'ad_rspec_versions': ad_rspec_versions,
91                     'default_ad_rspec': default_rspec_version
92                     }
93     sm_version=version_core(version_more)
94     # local aggregate if present needs to have localhost resolved
95     if api.hrn in api.aggregates:
96         local_am_url=get_serverproxy_url(api.aggregates[api.hrn])
97         sm_version['peers'][api.hrn]=local_am_url.replace('localhost',sm_version['hostname'])
98     return sm_version
99
100
101 #def GetVersion(api):
102     ## peers explicitly in aggregates.xml
103     #peers =dict ([ (peername,get_serverproxy_url(v)) for (peername,v) in api.aggregates.iteritems() 
104                    #if peername != api.hrn])
105     #xrn=Xrn (api.hrn)
106     #request_rspec_versions = [dict(pg_rspec_request_version), dict(sfa_rspec_version)]
107     #ad_rspec_versions = [dict(pg_rspec_ad_version), dict(sfa_rspec_version)]
108     #version_more = {'interface':'slicemgr',
109                     #'hrn' : xrn.get_hrn(),
110                     #'urn' : xrn.get_urn(),
111                     #'peers': peers,
112                     #'request_rspec_versions': request_rspec_versions,
113                     #'ad_rspec_versions': ad_rspec_versions,
114                     #'default_ad_rspec': dict(sfa_rspec_version)
115                     #}
116     #sm_version=version_core(version_more)
117     ## local aggregate if present needs to have localhost resolved
118     #if api.hrn in api.aggregates:
119         #local_am_url=get_serverproxy_url(api.aggregates[api.hrn])
120         #sm_version['peers'][api.hrn]=local_am_url.replace('localhost',sm_version['hostname'])
121     #return sm_version
122  
123  
124 def drop_slicemgr_stats(api,rspec):
125         try:
126                 stats_elements = rspec.xml.xpath('//statistics')
127                 for node in stats_elements:
128                         node.getparent().remove(node)
129         except Exception, e:
130                 api.logger.warn("drop_slicemgr_stats failed: %s " % (str(e)))
131  
132  
133  
134  
135 def CreateSliver(api, xrn, creds, rspec_str, users, call_id):
136         
137         version_manager = VersionManager()
138         def _CreateSliver(aggregate, server, xrn, credential, rspec, users, call_id):
139                 
140                 tStart = time.time()
141                 try:
142                         # Need to call GetVersion at an aggregate to determine the supported
143                         # rspec type/format beofre calling CreateSliver at an Aggregate.
144                         print>>sys.stderr, " \r\n SLICE MANAGERSLAB _CreateSliver server " 
145                         server_version = api.get_cached_server_version(server)
146                         requested_users = users
147                         if 'sfa' not in server_version and 'geni_api' in server_version:
148                                 # sfa aggregtes support both sfa and pg rspecs, no need to convert
149                                 # if aggregate supports sfa rspecs. otherwise convert to pg rspec
150                                 rspec = RSpec(RSpecConverter.to_pg_rspec(rspec, 'request'))
151                                 filter = {'component_manager_id': server_version['urn']}
152                                 rspec.filter(filter)
153                                 rspec = rspec.toxml()
154                                 requested_users = sfa_to_pg_users_arg(users)
155                         args = [xrn, credential, rspec, requested_users]
156                         if _call_id_supported(api, server):
157                                 args.append(call_id)
158                         rspec = server.CreateSliver(*args)
159                         return {"aggregate": aggregate, "rspec": rspec, "elapsed": time.time()-tStart, "status": "success"}
160                 except: 
161                         logger.log_exc('Something wrong in _CreateSliver with URL %s'%server.url)
162                 return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception"}
163
164         
165         if Callids().already_handled(call_id): return ""
166         
167         # Validate the RSpec against PlanetLab's schema --disabled for now
168         # The schema used here needs to aggregate the PL and VINI schemas
169         # schema = "/var/www/html/schemas/pl.rng"
170         rspec = RSpec(rspec_str)
171         schema = None
172         if schema:
173                 rspec.validate(schema)
174                 
175         print>>sys.stderr, " \r\n \r\n \t\t =======SLICE MANAGER _CreateSliver api %s" %(api)
176         # if there is a <statistics> section, the aggregates don't care about it,
177         # so delete it.
178         drop_slicemgr_stats(api,rspec)
179         
180         # attempt to use delegated credential first
181         credential = api.getDelegatedCredential(creds)
182         if not credential:
183                 credential = api.getCredential()
184
185         # get the callers hrn
186         hrn, type = urn_to_hrn(xrn)
187         valid_cred = api.auth.checkCredentials(creds, 'createsliver', hrn)[0]
188         caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
189         threads = ThreadManager()
190         print>>sys.stderr, " \r\n \r\n \t\t =======SLICE MANAGER _CreateSliver api aggregates  %s \t caller_hrn %s api.hrn %s" %(api.aggregates, caller_hrn, api.hrn)
191         for aggregate in api.aggregates:
192         # prevent infinite loop. Dont send request back to caller
193         # unless the caller is the aggregate's SM 
194                 if caller_hrn == aggregate and aggregate != api.hrn:
195                         continue
196                 interface = api.aggregates[aggregate]
197                 print>>sys.stderr, " \r\n \r\n \t\t =======SLICE MANAGER _CreateSliver aggregate %s interface %s" %(api.aggregates[aggregate],interface)   
198                 server = api.get_server(interface, credential)
199                 if server is None:
200                         print>>sys.stderr, " \r\n \r\n \t\t =======SLICE MANAGER _CreateSliver NOSERVERS "  
201                 # Just send entire RSpec to each aggregate
202                 #threads.run(_CreateSliver, aggregate, xrn, [credential], rspec.toxml(), users, call_id)
203                 threads.run(_CreateSliver, aggregate, server, xrn, [credential], rspec.toxml(), users, call_id)
204         results = threads.get_results()
205         manifest_version = version_manager._get_version(rspec.version.type, rspec.version.version, 'manifest')
206         result_rspec = RSpec(version=manifest_version)
207     #rspec = SfaRSpec()
208         for result in results:
209                 add_slicemgr_stat(result_rspec, "CreateSliver", result["aggregate"], result["elapsed"], result["status"])
210                 if result["status"]=="success":
211                         try:
212                                 result_rspec.version.merge(result["rspec"])
213                         except:
214                                 api.logger.log_exc("SM.CreateSliver: Failed to merge aggregate rspec")
215         return result_rspec.toxml()
216         #rspec.merge(result)     
217     #return rspec.toxml()
218
219 def RenewSliver(api, xrn, creds, expiration_time, call_id):
220     if Callids().already_handled(call_id): return True
221
222     (hrn, type) = urn_to_hrn(xrn)
223     # get the callers hrn
224     valid_cred = api.auth.checkCredentials(creds, 'renewsliver', hrn)[0]
225     caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
226
227     # attempt to use delegated credential first
228     credential = api.getDelegatedCredential(creds)
229     if not credential:
230         credential = api.getCredential()
231     threads = ThreadManager()
232     for aggregate in api.aggregates:
233         # prevent infinite loop. Dont send request back to caller
234         # unless the caller is the aggregate's SM
235         if caller_hrn == aggregate and aggregate != api.hrn:
236             continue
237
238         server = api.aggregates[aggregate]
239         threads.run(server.RenewSliver, xrn, [credential], expiration_time, call_id)
240     # 'and' the results
241     return reduce (lambda x,y: x and y, threads.get_results() , True)
242
243 def get_ticket(api, xrn, creds, rspec, users):
244     slice_hrn, type = urn_to_hrn(xrn)
245     # get the netspecs contained within the clients rspec
246     aggregate_rspecs = {}
247     tree= etree.parse(StringIO(rspec))
248     elements = tree.findall('./network')
249     for element in elements:
250         aggregate_hrn = element.values()[0]
251         aggregate_rspecs[aggregate_hrn] = rspec 
252
253     # get the callers hrn
254     valid_cred = api.auth.checkCredentials(creds, 'getticket', slice_hrn)[0]
255     caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
256
257     # attempt to use delegated credential first
258     credential = api.getDelegatedCredential(creds)
259     if not credential:
260         credential = api.getCredential() 
261     threads = ThreadManager()
262     for (aggregate, aggregate_rspec) in aggregate_rspecs.iteritems():
263         # prevent infinite loop. Dont send request back to caller
264         # unless the caller is the aggregate's SM
265         if caller_hrn == aggregate and aggregate != api.hrn:
266             continue
267         server = None
268         if aggregate in api.aggregates:
269             server = api.aggregates[aggregate]
270         else:
271             net_urn = hrn_to_urn(aggregate, 'authority')     
272             # we may have a peer that knows about this aggregate
273             for agg in api.aggregates:
274                 target_aggs = api.aggregates[agg].get_aggregates(credential, net_urn)
275                 if not target_aggs or not 'hrn' in target_aggs[0]:
276                     continue
277                 # send the request to this address 
278                 url = target_aggs[0]['url']
279                 server = xmlrpcprotocol.get_server(url, api.key_file, api.cert_file)
280                 # aggregate found, no need to keep looping
281                 break   
282         if server is None:
283             continue 
284         threads.run(server.ParseTicket, xrn, credential, aggregate_rspec, users)
285
286     results = threads.get_results()
287     
288     # gather information from each ticket 
289     rspecs = []
290     initscripts = []
291     slivers = [] 
292     object_gid = None  
293     for result in results:
294         agg_ticket = SfaTicket(string=result)
295         attrs = agg_ticket.get_attributes()
296         if not object_gid:
297             object_gid = agg_ticket.get_gid_object()
298         rspecs.append(agg_ticket.get_rspec())
299         initscripts.extend(attrs.get('initscripts', [])) 
300         slivers.extend(attrs.get('slivers', [])) 
301     
302     # merge info
303     attributes = {'initscripts': initscripts,
304                  'slivers': slivers}
305     merged_rspec = merge_rspecs(rspecs) 
306
307     # create a new ticket
308     ticket = SfaTicket(subject = slice_hrn)
309     ticket.set_gid_caller(api.auth.client_gid)
310     ticket.set_issuer(key=api.key, subject=api.hrn)
311     ticket.set_gid_object(object_gid)
312     ticket.set_pubkey(object_gid.get_pubkey())
313     #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
314     ticket.set_attributes(attributes)
315     ticket.set_rspec(merged_rspec)
316     ticket.encode()
317     ticket.sign()          
318     return ticket.save_to_string(save_parents=True)
319
320
321 def DeleteSliver(api, xrn, creds, call_id):
322     if Callids().already_handled(call_id): return ""
323     (hrn, type) = urn_to_hrn(xrn)
324     # get the callers hrn
325     valid_cred = api.auth.checkCredentials(creds, 'deletesliver', hrn)[0]
326     caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
327
328     # attempt to use delegated credential first
329     credential = api.getDelegatedCredential(creds)
330     if not credential:
331         credential = api.getCredential()
332     threads = ThreadManager()
333     for aggregate in api.aggregates:
334         # prevent infinite loop. Dont send request back to caller
335         # unless the caller is the aggregate's SM
336         if caller_hrn == aggregate and aggregate != api.hrn:
337             continue
338         server = api.aggregates[aggregate]
339         threads.run(server.DeleteSliver, xrn, credential, call_id)
340     threads.get_results()
341     return 1
342
343 def start_slice(api, xrn, creds):
344     hrn, type = urn_to_hrn(xrn)
345
346     # get the callers hrn
347     valid_cred = api.auth.checkCredentials(creds, 'startslice', hrn)[0]
348     caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
349
350     # attempt to use delegated credential first
351     credential = api.getDelegatedCredential(creds)
352     if not credential:
353         credential = api.getCredential()
354     threads = ThreadManager()
355     for aggregate in api.aggregates:
356         # prevent infinite loop. Dont send request back to caller
357         # unless the caller is the aggregate's SM
358         if caller_hrn == aggregate and aggregate != api.hrn:
359             continue
360         server = api.aggregates[aggregate]
361         threads.run(server.Start, xrn, credential)
362     threads.get_results()    
363     return 1
364  
365 def stop_slice(api, xrn, creds):
366     hrn, type = urn_to_hrn(xrn)
367
368     # get the callers hrn
369     valid_cred = api.auth.checkCredentials(creds, 'stopslice', hrn)[0]
370     caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
371
372     # attempt to use delegated credential first
373     credential = api.getDelegatedCredential(creds)
374     if not credential:
375         credential = api.getCredential()
376     threads = ThreadManager()
377     for aggregate in api.aggregates:
378         # prevent infinite loop. Dont send request back to caller
379         # unless the caller is the aggregate's SM
380         if caller_hrn == aggregate and aggregate != api.hrn:
381             continue
382         server = api.aggregates[aggregate]
383         threads.run(server.Stop, xrn, credential)
384     threads.get_results()    
385     return 1
386
387 def reset_slice(api, xrn):
388     """
389     Not implemented
390     """
391     return 1
392
393 def shutdown(api, xrn, creds):
394     """
395     Not implemented   
396     """
397     return 1
398
399 def status(api, xrn, creds):
400     """
401     Not implemented 
402     """
403     return 1
404
405 # Thierry : caching at the slicemgr level makes sense to some extent
406 #caching=True
407 caching=False
408 def ListSlices(api, creds, call_id):
409
410     if Callids().already_handled(call_id): return []
411
412     # look in cache first
413     if caching and api.cache:
414         slices = api.cache.get('slices')
415         if slices:
416             return slices    
417
418     # get the callers hrn
419     valid_cred = api.auth.checkCredentials(creds, 'listslices', None)[0]
420     caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
421
422     # attempt to use delegated credential first
423     credential = api.getDelegatedCredential(creds)
424     if not credential:
425         credential = api.getCredential()
426     threads = ThreadManager()
427     # fetch from aggregates
428     for aggregate in api.aggregates:
429         # prevent infinite loop. Dont send request back to caller
430         # unless the caller is the aggregate's SM
431         if caller_hrn == aggregate and aggregate != api.hrn:
432             continue
433         server = api.aggregates[aggregate]
434         threads.run(server.ListSlices, credential, call_id)
435
436     # combime results
437     results = threads.get_results()
438     slices = []
439     for result in results:
440         slices.extend(result)
441     
442     # cache the result
443     if caching and api.cache:
444         api.cache.add('slices', slices)
445
446     return slices
447
448 def add_slicemgr_stat(rspec, callname, aggname, elapsed, status):
449         try:
450                 stats_tags = rspec.xml.xpath('//statistics[@call="%s"]' % callname)
451                 if stats_tags:
452                         stats_tag = stats_tags[0]
453                 else:
454                         stats_tag = etree.SubElement(rspec.xml.root, "statistics", call=callname)
455                         
456                 etree.SubElement(stats_tag, "aggregate", name=str(aggname), elapsed=str(elapsed), status=str(status))
457         except Exception, e:
458                 api.logger.warn("add_slicemgr_stat failed on  %s: %s" %(aggname, str(e)))
459
460
461
462
463 def ListResources(api, creds, options, call_id):
464     version_manager = VersionManager()
465     def _ListResources(aggregate, server, credential, opts, call_id):
466
467         my_opts = copy(opts)
468         args = [credential, my_opts]
469         tStart = time.time()
470         try:
471             if _call_id_supported(api, server):
472                 args.append(call_id)
473             version = api.get_cached_server_version(server)
474             # force ProtoGENI aggregates to give us a v2 RSpec
475             if 'sfa' not in version.keys():
476                 my_opts['rspec_version'] = version_manager.get_version('ProtoGENI 2').to_dict()
477             rspec = server.ListResources(*args)
478             return {"aggregate": aggregate, "rspec": rspec, "elapsed": time.time()-tStart, "status": "success"}
479         except Exception, e:
480             api.logger.log_exc("ListResources failed at %s" %(server.url))
481             return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception"}
482
483     if Callids().already_handled(call_id): return ""
484
485     # get slice's hrn from options
486     xrn = options.get('geni_slice_urn', '')
487     (hrn, type) = urn_to_hrn(xrn)
488     if 'geni_compressed' in options:
489         del(options['geni_compressed'])
490
491     # get the rspec's return format from options
492     rspec_version = version_manager.get_version(options.get('rspec_version'))
493     version_string = "rspec_%s" % (rspec_version.to_string())
494
495     # look in cache first
496     if caching and api.cache and not xrn:
497         rspec =  api.cache.get(version_string)
498         if rspec:
499             return rspec
500
501     # get the callers hrn
502     valid_cred = api.auth.checkCredentials(creds, 'listnodes', hrn)[0]
503     caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
504
505     # attempt to use delegated credential first
506     cred = api.getDelegatedCredential(creds)
507     if not cred:
508         cred = api.getCredential()
509     threads = ThreadManager()
510     for aggregate in api.aggregates:
511         # prevent infinite loop. Dont send request back to caller
512         # unless the caller is the aggregate's SM
513         if caller_hrn == aggregate and aggregate != api.hrn:
514             continue
515
516         # get the rspec from the aggregate
517         interface = api.aggregates[aggregate]
518         server = api.get_server(interface, cred)
519         threads.run(_ListResources, aggregate, server, [cred], options, call_id)
520
521
522     results = threads.get_results()
523     rspec_version = version_manager.get_version(options.get('rspec_version'))
524     if xrn:    
525         result_version = version_manager._get_version(rspec_version.type, rspec_version.version, 'manifest')
526     else: 
527         result_version = version_manager._get_version(rspec_version.type, rspec_version.version, 'ad')
528     rspec = RSpec(version=result_version)
529     for result in results:
530         add_slicemgr_stat(rspec, "ListResources", result["aggregate"], result["elapsed"], result["status"])
531         if result["status"]=="success":
532             try:
533                 rspec.version.merge(result["rspec"])
534             except:
535                 api.logger.log_exc("SM.ListResources: Failed to merge aggregate rspec")
536
537     # cache the result
538     if caching and api.cache and not xrn:
539         api.cache.add(version_string, rspec.toxml())
540         
541     print >>sys.stderr, "\r\n  slice_manager  \r\n"   , rspec
542     return rspec.toxml()
543
544 #def ListResources(api, creds, options, call_id):
545
546     #if Callids().already_handled(call_id): return ""
547
548     ## get slice's hrn from options
549     #xrn = options.get('geni_slice_urn', '')
550     #(hrn, type) = urn_to_hrn(xrn)
551     #print >>sys.stderr, " SM_ListResources xrn " , xrn
552     ##print >>sys.stderr, " SM ListResources api.__dict__ " , api.__dict__.keys()
553     ##print >>sys.stderr, " SM ListResources dir(api)" , dir(api)
554     #print >>sys.stderr, "  \r\n avant RspecVersion \r\n \r\n"
555     ## get the rspec's return format from options
556     #rspec_version = RSpecVersion(options.get('rspec_version'))
557     #print >>sys.stderr, " \r\n \r\n ListResources RSpecVersion ", rspec_version
558     #version_string = "rspec_%s" % (rspec_version.get_version_name())
559
560     ##panos adding the info option to the caching key (can be improved)
561     #if options.get('info'):
562         #version_string = version_string + "_"+options.get('info')
563    
564     #print>>sys.stderr,"version string = ",version_string
565
566     ## look in cache first
567     #if caching and api.cache and not xrn:
568         #print>>sys.stderr," \r\n  caching %s and api.cache %s and not xrn %s"%(caching , api.cache,xrn) 
569         #rspec =  api.cache.get(version_string)
570         #if rspec:
571             #return rspec
572
573     ## get the callers hrn
574     #print >>sys.stderr, " SM ListResources get the callers hrn "
575     #valid_cred = api.auth.checkCredentials(creds, 'listnodes', hrn)[0]
576     #caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
577     #print >>sys.stderr, " \r\n SM ListResources get the callers caller_hrn hrn  %s "%(caller_hrn)
578     ## attempt to use delegated credential first
579     #credential = api.getDelegatedCredential(creds)
580     #print >>sys.stderr, " \r\n SM ListResources get the callers credential  %s "%(credential) 
581     #if not credential:
582         #credential = api.getCredential()
583     #threads = ThreadManager()
584     #print >>sys.stderr, " \r\n SM ListResources get the callers api.aggregates  %s "%(api.aggregates) 
585     #for aggregate in api.aggregates:
586         ## prevent infinite loop. Dont send request back to caller
587         ## unless the caller is the aggregate's SM
588         #if caller_hrn == aggregate and aggregate != api.hrn:
589             #continue
590         ## get the rspec from the aggregate
591         #server = api.aggregates[aggregate]
592         #print >>sys.stderr, " Slice Mgr ListResources, server" ,server
593         #my_opts = copy(options)
594         #my_opts['geni_compressed'] = False
595         #threads.run(server.ListResources, credential, my_opts, call_id)
596         #print >>sys.stderr, "\r\n  !!!!!!!!!!!!!!!! \r\n"       
597     #results = threads.get_results()
598     ##results.append(open('/root/protogeni.rspec', 'r').read())
599     #rspec_version = RSpecVersion(my_opts.get('rspec_version'))
600     #if rspec_version['type'].lower() == 'protogeni':
601         #rspec = PGRSpec()
602     #else:
603         #rspec = SfaRSpec()
604
605     #for result in results:
606         #print >>sys.stderr, "\r\n  slice_manager  result"   , result
607         #try:
608             #print >>sys.stderr, "avant merge"  , rspec         
609             #rspec.merge(result)        
610             #print >>sys.stderr, "AFTERMERGE" , rspec
611         #except:
612             #raise
613             #api.logger.info("SM.ListResources: Failed to merge aggregate rspec")
614
615     ## cache the result
616     #if caching and api.cache and not xrn:
617         #api.cache.add(version_string, rspec.toxml())
618
619     #print >>sys.stderr, "\r\n  slice_manager  \r\n"   , rspec
620     #return rspec.toxml()
621
622 # first draft at a merging SliverStatus
623 def SliverStatus(api, slice_xrn, creds, call_id):
624     if Callids().already_handled(call_id): return {}
625     # attempt to use delegated credential first
626     credential = api.getDelegatedCredential(creds)
627     if not credential:
628         credential = api.getCredential()
629     threads = ThreadManager()
630     for aggregate in api.aggregates:
631         server = api.aggregates[aggregate]
632         threads.run (server.SliverStatus, slice_xrn, credential, call_id)
633     results = threads.get_results()
634
635     # get rid of any void result - e.g. when call_id was hit where by convention we return {}
636     results = [ result for result in results if result and result['geni_resources']]
637
638     # do not try to combine if there's no result
639     if not results : return {}
640
641     # otherwise let's merge stuff
642     overall = {}
643
644     # mmh, it is expected that all results carry the same urn
645     overall['geni_urn'] = results[0]['geni_urn']
646
647     # consolidate geni_status - simple model using max on a total order
648     states = [ 'ready', 'configuring', 'failed', 'unknown' ]
649     # hash name to index
650     shash = dict ( zip ( states, range(len(states)) ) )
651     def combine_status (x,y):
652         return shash [ max (shash(x),shash(y)) ]
653     overall['geni_status'] = reduce (combine_status, [ result['geni_status'] for result in results], 'ready' )
654
655     # {'ready':0,'configuring':1,'failed':2,'unknown':3}
656     # append all geni_resources
657     overall['geni_resources'] = \
658         reduce (lambda x,y: x+y, [ result['geni_resources'] for result in results] , [])
659
660     return overall
661
662 def main():
663     r = RSpec()
664     r.parseFile(sys.argv[1])
665     rspec = r.toDict()
666     CreateSliver(None,'plc.princeton.tmacktestslice',rspec,'create-slice-tmacktestslice')
667
668 if __name__ == "__main__":
669     main()
670