4 from StringIO import StringIO
5 from types import StringTypes
6 from copy import deepcopy
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
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
40 # we have specialized xmlrpclib.ServerProxy to remember the input url
41 # OTOH it's not clear if we're only dealing with XMLRPCServerProxy instances
42 def get_serverproxy_url (server):
44 return server.get_url()
46 logger.warning("GetVersion, falling back to xmlrpclib.ServerProxy internals")
47 return server._ServerProxy__host + server._ServerProxy__handler
50 # peers explicitly in aggregates.xml
51 peers =dict ([ (peername,get_serverproxy_url(v)) for (peername,v) in api.aggregates.iteritems()
52 if peername != api.hrn])
53 version_manager = VersionManager()
54 ad_rspec_versions = []
55 request_rspec_versions = []
56 for rspec_version in version_manager.versions:
57 if rspec_version.content_type in ['*', 'ad']:
58 ad_rspec_versions.append(rspec_version.to_dict())
59 if rspec_version.content_type in ['*', 'request']:
60 request_rspec_versions.append(rspec_version.to_dict())
61 default_rspec_version = version_manager.get_version("sfa 1").to_dict()
62 xrn=Xrn(api.hrn, 'authority+sa')
63 version_more = {'interface':'slicemgr',
64 'hrn' : xrn.get_hrn(),
65 'urn' : xrn.get_urn(),
67 'request_rspec_versions': request_rspec_versions,
68 'ad_rspec_versions': ad_rspec_versions,
69 'default_ad_rspec': default_rspec_version
71 sm_version=version_core(version_more)
72 # local aggregate if present needs to have localhost resolved
73 if api.hrn in api.aggregates:
74 local_am_url=get_serverproxy_url(api.aggregates[api.hrn])
75 sm_version['peers'][api.hrn]=local_am_url.replace('localhost',sm_version['hostname'])
80 ## peers explicitly in aggregates.xml
81 #peers =dict ([ (peername,get_serverproxy_url(v)) for (peername,v) in api.aggregates.iteritems()
82 #if peername != api.hrn])
84 #request_rspec_versions = [dict(pg_rspec_request_version), dict(sfa_rspec_version)]
85 #ad_rspec_versions = [dict(pg_rspec_ad_version), dict(sfa_rspec_version)]
86 #version_more = {'interface':'slicemgr',
87 #'hrn' : xrn.get_hrn(),
88 #'urn' : xrn.get_urn(),
90 #'request_rspec_versions': request_rspec_versions,
91 #'ad_rspec_versions': ad_rspec_versions,
92 #'default_ad_rspec': dict(sfa_rspec_version)
94 #sm_version=version_core(version_more)
95 ## local aggregate if present needs to have localhost resolved
96 #if api.hrn in api.aggregates:
97 #local_am_url=get_serverproxy_url(api.aggregates[api.hrn])
98 #sm_version['peers'][api.hrn]=local_am_url.replace('localhost',sm_version['hostname'])
102 def drop_slicemgr_stats(api,rspec):
104 stats_elements = rspec.xml.xpath('//statistics')
105 for node in stats_elements:
106 node.getparent().remove(node)
108 api.logger.warn("drop_slicemgr_stats failed: %s " % (str(e)))
113 def CreateSliver(api, xrn, creds, rspec_str, users, call_id):
114 version_manager = VersionManager()
115 def _CreateSliver(aggregate, xrn, credential, rspec, users, call_id):
116 # Need to call ParseVersion at an aggregate to determine the supported
117 # rspec type/format beofre calling CreateSliver at an Aggregate.
118 # The Aggregate's verion info is cached
122 # Need to call GetVersion at an aggregate to determine the supported
123 # rspec type/format beofre calling CreateSliver at an Aggregate.
124 server_version = api.get_cached_server_version(server)
125 requested_users = users
126 if 'sfa' not in server_version and 'geni_api' in server_version:
127 # sfa aggregtes support both sfa and pg rspecs, no need to convert
128 # if aggregate supports sfa rspecs. otherwise convert to pg rspec
129 rspec = RSpec(RSpecConverter.to_pg_rspec(rspec, 'request'))
130 filter = {'component_manager_id': server_version['urn']}
132 rspec = rspec.toxml()
133 requested_users = sfa_to_pg_users_arg(users)
134 args = [xrn, credential, rspec, requested_users]
135 if _call_id_supported(api, server):
137 rspec = server.CreateSliver(*args)
138 return {"aggregate": aggregate, "rspec": rspec, "elapsed": time.time()-tStart, "status": "success"}
140 logger.log_exc('Something wrong in _CreateSliver with URL %s'%server.url)
141 return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception"}
144 if Callids().already_handled(call_id): return ""
146 # Validate the RSpec against PlanetLab's schema --disabled for now
147 # The schema used here needs to aggregate the PL and VINI schemas
148 # schema = "/var/www/html/schemas/pl.rng"
149 rspec = RSpec(rspec_str)
152 rspec.validate(schema)
154 print>>sys.stderr, " \r\n \r\n \t\t =======SLICE MANAGER _CreateSliver api %s" %(api)
155 # if there is a <statistics> section, the aggregates don't care about it,
157 drop_slicemgr_stats(api,rspec)
159 # attempt to use delegated credential first
160 credential = api.getDelegatedCredential(creds)
162 credential = api.getCredential()
164 # get the callers hrn
165 hrn, type = urn_to_hrn(xrn)
166 valid_cred = api.auth.checkCredentials(creds, 'createsliver', hrn)[0]
167 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
168 threads = ThreadManager()
170 for aggregate in api.aggregates:
171 # prevent infinite loop. Dont send request back to caller
172 # unless the caller is the aggregate's SM
173 if caller_hrn == aggregate and aggregate != api.hrn:
175 interface = api.aggregates[aggregate]
176 server = api.get_server(interface, credential)
177 # Just send entire RSpec to each aggregate
178 threads.run(_CreateSliver, aggregate, xrn, [credential], rspec.toxml(), users, call_id)
180 results = threads.get_results()
181 manifest_version = version_manager._get_version(rspec.version.type, rspec.version.version, 'manifest')
182 result_rspec = RSpec(version=manifest_version)
184 for result in results:
185 add_slicemgr_stat(result_rspec, "CreateSliver", result["aggregate"], result["elapsed"], result["status"])
186 if result["status"]=="success":
188 result_rspec.version.merge(result["rspec"])
190 api.logger.log_exc("SM.CreateSliver: Failed to merge aggregate rspec")
191 return result_rspec.toxml()
193 #return rspec.toxml()
195 def RenewSliver(api, xrn, creds, expiration_time, call_id):
196 if Callids().already_handled(call_id): return True
198 (hrn, type) = urn_to_hrn(xrn)
199 # get the callers hrn
200 valid_cred = api.auth.checkCredentials(creds, 'renewsliver', hrn)[0]
201 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
203 # attempt to use delegated credential first
204 credential = api.getDelegatedCredential(creds)
206 credential = api.getCredential()
207 threads = ThreadManager()
208 for aggregate in api.aggregates:
209 # prevent infinite loop. Dont send request back to caller
210 # unless the caller is the aggregate's SM
211 if caller_hrn == aggregate and aggregate != api.hrn:
214 server = api.aggregates[aggregate]
215 threads.run(server.RenewSliver, xrn, [credential], expiration_time, call_id)
217 return reduce (lambda x,y: x and y, threads.get_results() , True)
219 def get_ticket(api, xrn, creds, rspec, users):
220 slice_hrn, type = urn_to_hrn(xrn)
221 # get the netspecs contained within the clients rspec
222 aggregate_rspecs = {}
223 tree= etree.parse(StringIO(rspec))
224 elements = tree.findall('./network')
225 for element in elements:
226 aggregate_hrn = element.values()[0]
227 aggregate_rspecs[aggregate_hrn] = rspec
229 # get the callers hrn
230 valid_cred = api.auth.checkCredentials(creds, 'getticket', slice_hrn)[0]
231 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
233 # attempt to use delegated credential first
234 credential = api.getDelegatedCredential(creds)
236 credential = api.getCredential()
237 threads = ThreadManager()
238 for (aggregate, aggregate_rspec) in aggregate_rspecs.iteritems():
239 # prevent infinite loop. Dont send request back to caller
240 # unless the caller is the aggregate's SM
241 if caller_hrn == aggregate and aggregate != api.hrn:
244 if aggregate in api.aggregates:
245 server = api.aggregates[aggregate]
247 net_urn = hrn_to_urn(aggregate, 'authority')
248 # we may have a peer that knows about this aggregate
249 for agg in api.aggregates:
250 target_aggs = api.aggregates[agg].get_aggregates(credential, net_urn)
251 if not target_aggs or not 'hrn' in target_aggs[0]:
253 # send the request to this address
254 url = target_aggs[0]['url']
255 server = xmlrpcprotocol.get_server(url, api.key_file, api.cert_file)
256 # aggregate found, no need to keep looping
260 threads.run(server.ParseTicket, xrn, credential, aggregate_rspec, users)
262 results = threads.get_results()
264 # gather information from each ticket
269 for result in results:
270 agg_ticket = SfaTicket(string=result)
271 attrs = agg_ticket.get_attributes()
273 object_gid = agg_ticket.get_gid_object()
274 rspecs.append(agg_ticket.get_rspec())
275 initscripts.extend(attrs.get('initscripts', []))
276 slivers.extend(attrs.get('slivers', []))
279 attributes = {'initscripts': initscripts,
281 merged_rspec = merge_rspecs(rspecs)
283 # create a new ticket
284 ticket = SfaTicket(subject = slice_hrn)
285 ticket.set_gid_caller(api.auth.client_gid)
286 ticket.set_issuer(key=api.key, subject=api.hrn)
287 ticket.set_gid_object(object_gid)
288 ticket.set_pubkey(object_gid.get_pubkey())
289 #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
290 ticket.set_attributes(attributes)
291 ticket.set_rspec(merged_rspec)
294 return ticket.save_to_string(save_parents=True)
297 def DeleteSliver(api, xrn, creds, call_id):
298 if Callids().already_handled(call_id): return ""
299 (hrn, type) = urn_to_hrn(xrn)
300 # get the callers hrn
301 valid_cred = api.auth.checkCredentials(creds, 'deletesliver', hrn)[0]
302 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
304 # attempt to use delegated credential first
305 credential = api.getDelegatedCredential(creds)
307 credential = api.getCredential()
308 threads = ThreadManager()
309 for aggregate in api.aggregates:
310 # prevent infinite loop. Dont send request back to caller
311 # unless the caller is the aggregate's SM
312 if caller_hrn == aggregate and aggregate != api.hrn:
314 server = api.aggregates[aggregate]
315 threads.run(server.DeleteSliver, xrn, credential, call_id)
316 threads.get_results()
319 def start_slice(api, xrn, creds):
320 hrn, type = urn_to_hrn(xrn)
322 # get the callers hrn
323 valid_cred = api.auth.checkCredentials(creds, 'startslice', hrn)[0]
324 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
326 # attempt to use delegated credential first
327 credential = api.getDelegatedCredential(creds)
329 credential = api.getCredential()
330 threads = ThreadManager()
331 for aggregate in api.aggregates:
332 # prevent infinite loop. Dont send request back to caller
333 # unless the caller is the aggregate's SM
334 if caller_hrn == aggregate and aggregate != api.hrn:
336 server = api.aggregates[aggregate]
337 threads.run(server.Start, xrn, credential)
338 threads.get_results()
341 def stop_slice(api, xrn, creds):
342 hrn, type = urn_to_hrn(xrn)
344 # get the callers hrn
345 valid_cred = api.auth.checkCredentials(creds, 'stopslice', hrn)[0]
346 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
348 # attempt to use delegated credential first
349 credential = api.getDelegatedCredential(creds)
351 credential = api.getCredential()
352 threads = ThreadManager()
353 for aggregate in api.aggregates:
354 # prevent infinite loop. Dont send request back to caller
355 # unless the caller is the aggregate's SM
356 if caller_hrn == aggregate and aggregate != api.hrn:
358 server = api.aggregates[aggregate]
359 threads.run(server.Stop, xrn, credential)
360 threads.get_results()
363 def reset_slice(api, xrn):
369 def shutdown(api, xrn, creds):
375 def status(api, xrn, creds):
381 # Thierry : caching at the slicemgr level makes sense to some extent
384 def ListSlices(api, creds, call_id):
386 if Callids().already_handled(call_id): return []
388 # look in cache first
389 if caching and api.cache:
390 slices = api.cache.get('slices')
394 # get the callers hrn
395 valid_cred = api.auth.checkCredentials(creds, 'listslices', None)[0]
396 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
398 # attempt to use delegated credential first
399 credential = api.getDelegatedCredential(creds)
401 credential = api.getCredential()
402 threads = ThreadManager()
403 # fetch from aggregates
404 for aggregate in api.aggregates:
405 # prevent infinite loop. Dont send request back to caller
406 # unless the caller is the aggregate's SM
407 if caller_hrn == aggregate and aggregate != api.hrn:
409 server = api.aggregates[aggregate]
410 threads.run(server.ListSlices, credential, call_id)
413 results = threads.get_results()
415 for result in results:
416 slices.extend(result)
419 if caching and api.cache:
420 api.cache.add('slices', slices)
424 def add_slicemgr_stat(rspec, callname, aggname, elapsed, status):
426 stats_tags = rspec.xml.xpath('//statistics[@call="%s"]' % callname)
428 stats_tag = stats_tags[0]
430 stats_tag = etree.SubElement(rspec.xml.root, "statistics", call=callname)
432 etree.SubElement(stats_tag, "aggregate", name=str(aggname), elapsed=str(elapsed), status=str(status))
434 api.logger.warn("add_slicemgr_stat failed on %s: %s" %(aggname, str(e)))
439 def ListResources(api, creds, options, call_id):
440 version_manager = VersionManager()
441 def _ListResources(aggregate, server, credential, opts, call_id):
444 args = [credential, my_opts]
447 if _call_id_supported(api, server):
449 version = api.get_cached_server_version(server)
450 # force ProtoGENI aggregates to give us a v2 RSpec
451 if 'sfa' not in version.keys():
452 my_opts['rspec_version'] = version_manager.get_version('ProtoGENI 2').to_dict()
453 rspec = server.ListResources(*args)
454 return {"aggregate": aggregate, "rspec": rspec, "elapsed": time.time()-tStart, "status": "success"}
456 api.logger.log_exc("ListResources failed at %s" %(server.url))
457 return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception"}
459 if Callids().already_handled(call_id): return ""
461 # get slice's hrn from options
462 xrn = options.get('geni_slice_urn', '')
463 (hrn, type) = urn_to_hrn(xrn)
464 if 'geni_compressed' in options:
465 del(options['geni_compressed'])
467 # get the rspec's return format from options
468 rspec_version = version_manager.get_version(options.get('rspec_version'))
469 version_string = "rspec_%s" % (rspec_version.to_string())
471 # look in cache first
472 if caching and api.cache and not xrn:
473 rspec = api.cache.get(version_string)
477 # get the callers hrn
478 valid_cred = api.auth.checkCredentials(creds, 'listnodes', hrn)[0]
479 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
481 # attempt to use delegated credential first
482 cred = api.getDelegatedCredential(creds)
484 cred = api.getCredential()
485 threads = ThreadManager()
486 for aggregate in api.aggregates:
487 # prevent infinite loop. Dont send request back to caller
488 # unless the caller is the aggregate's SM
489 if caller_hrn == aggregate and aggregate != api.hrn:
492 # get the rspec from the aggregate
493 interface = api.aggregates[aggregate]
494 server = api.get_server(interface, cred)
495 threads.run(_ListResources, aggregate, server, [cred], options, call_id)
498 results = threads.get_results()
499 rspec_version = version_manager.get_version(options.get('rspec_version'))
501 result_version = version_manager._get_version(rspec_version.type, rspec_version.version, 'manifest')
503 result_version = version_manager._get_version(rspec_version.type, rspec_version.version, 'ad')
504 rspec = RSpec(version=result_version)
505 for result in results:
506 add_slicemgr_stat(rspec, "ListResources", result["aggregate"], result["elapsed"], result["status"])
507 if result["status"]=="success":
509 rspec.version.merge(result["rspec"])
511 api.logger.log_exc("SM.ListResources: Failed to merge aggregate rspec")
514 if caching and api.cache and not xrn:
515 api.cache.add(version_string, rspec.toxml())
517 print >>sys.stderr, "\r\n slice_manager \r\n" , rspec
520 #def ListResources(api, creds, options, call_id):
522 #if Callids().already_handled(call_id): return ""
524 ## get slice's hrn from options
525 #xrn = options.get('geni_slice_urn', '')
526 #(hrn, type) = urn_to_hrn(xrn)
527 #print >>sys.stderr, " SM_ListResources xrn " , xrn
528 ##print >>sys.stderr, " SM ListResources api.__dict__ " , api.__dict__.keys()
529 ##print >>sys.stderr, " SM ListResources dir(api)" , dir(api)
530 #print >>sys.stderr, " \r\n avant RspecVersion \r\n \r\n"
531 ## get the rspec's return format from options
532 #rspec_version = RSpecVersion(options.get('rspec_version'))
533 #print >>sys.stderr, " \r\n \r\n ListResources RSpecVersion ", rspec_version
534 #version_string = "rspec_%s" % (rspec_version.get_version_name())
536 ##panos adding the info option to the caching key (can be improved)
537 #if options.get('info'):
538 #version_string = version_string + "_"+options.get('info')
540 #print>>sys.stderr,"version string = ",version_string
542 ## look in cache first
543 #if caching and api.cache and not xrn:
544 #print>>sys.stderr," \r\n caching %s and api.cache %s and not xrn %s"%(caching , api.cache,xrn)
545 #rspec = api.cache.get(version_string)
549 ## get the callers hrn
550 #print >>sys.stderr, " SM ListResources get the callers hrn "
551 #valid_cred = api.auth.checkCredentials(creds, 'listnodes', hrn)[0]
552 #caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
553 #print >>sys.stderr, " \r\n SM ListResources get the callers caller_hrn hrn %s "%(caller_hrn)
554 ## attempt to use delegated credential first
555 #credential = api.getDelegatedCredential(creds)
556 #print >>sys.stderr, " \r\n SM ListResources get the callers credential %s "%(credential)
558 #credential = api.getCredential()
559 #threads = ThreadManager()
560 #print >>sys.stderr, " \r\n SM ListResources get the callers api.aggregates %s "%(api.aggregates)
561 #for aggregate in api.aggregates:
562 ## prevent infinite loop. Dont send request back to caller
563 ## unless the caller is the aggregate's SM
564 #if caller_hrn == aggregate and aggregate != api.hrn:
566 ## get the rspec from the aggregate
567 #server = api.aggregates[aggregate]
568 #print >>sys.stderr, " Slice Mgr ListResources, server" ,server
569 #my_opts = copy(options)
570 #my_opts['geni_compressed'] = False
571 #threads.run(server.ListResources, credential, my_opts, call_id)
572 #print >>sys.stderr, "\r\n !!!!!!!!!!!!!!!! \r\n"
573 #results = threads.get_results()
574 ##results.append(open('/root/protogeni.rspec', 'r').read())
575 #rspec_version = RSpecVersion(my_opts.get('rspec_version'))
576 #if rspec_version['type'].lower() == 'protogeni':
581 #for result in results:
582 #print >>sys.stderr, "\r\n slice_manager result" , result
584 #print >>sys.stderr, "avant merge" , rspec
586 #print >>sys.stderr, "AFTERMERGE" , rspec
589 #api.logger.info("SM.ListResources: Failed to merge aggregate rspec")
592 #if caching and api.cache and not xrn:
593 #api.cache.add(version_string, rspec.toxml())
595 #print >>sys.stderr, "\r\n slice_manager \r\n" , rspec
596 #return rspec.toxml()
598 # first draft at a merging SliverStatus
599 def SliverStatus(api, slice_xrn, creds, call_id):
600 if Callids().already_handled(call_id): return {}
601 # attempt to use delegated credential first
602 credential = api.getDelegatedCredential(creds)
604 credential = api.getCredential()
605 threads = ThreadManager()
606 for aggregate in api.aggregates:
607 server = api.aggregates[aggregate]
608 threads.run (server.SliverStatus, slice_xrn, credential, call_id)
609 results = threads.get_results()
611 # get rid of any void result - e.g. when call_id was hit where by convention we return {}
612 results = [ result for result in results if result and result['geni_resources']]
614 # do not try to combine if there's no result
615 if not results : return {}
617 # otherwise let's merge stuff
620 # mmh, it is expected that all results carry the same urn
621 overall['geni_urn'] = results[0]['geni_urn']
623 # consolidate geni_status - simple model using max on a total order
624 states = [ 'ready', 'configuring', 'failed', 'unknown' ]
626 shash = dict ( zip ( states, range(len(states)) ) )
627 def combine_status (x,y):
628 return shash [ max (shash(x),shash(y)) ]
629 overall['geni_status'] = reduce (combine_status, [ result['geni_status'] for result in results], 'ready' )
631 # {'ready':0,'configuring':1,'failed':2,'unknown':3}
632 # append all geni_resources
633 overall['geni_resources'] = \
634 reduce (lambda x,y: x+y, [ result['geni_resources'] for result in results] , [])
640 r.parseFile(sys.argv[1])
642 CreateSliver(None,'plc.princeton.tmacktestslice',rspec,'create-slice-tmacktestslice')
644 if __name__ == "__main__":