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