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.rspecHelper import merge_rspecs
12 from sfa.util.xrn import Xrn, urn_to_hrn, hrn_to_urn
13 from sfa.util.plxrn import hrn_to_pl_slicename
14 from sfa.util.rspec import *
15 from sfa.util.specdict import *
16 from sfa.util.faults import *
17 from sfa.util.record import SfaRecord
18 from sfa.rspecs.pg_rspec import PGRSpec
19 from sfa.rspecs.sfa_rspec import SfaRSpec
20 from sfa.rspecs.rspec_converter import RSpecConverter
21 from sfa.rspecs.rspec_parser import parse_rspec
22 from sfa.rspecs.rspec_version import RSpecVersion
23 from sfa.rspecs.sfa_rspec import sfa_rspec_version
24 from sfa.rspecs.pg_rspec import pg_rspec_ad_version, pg_rspec_request_version
25 from sfa.util.policy import Policy
26 from sfa.util.prefixTree import prefixTree
27 from sfa.util.sfaticket import *
28 from sfa.trust.credential import Credential
29 from sfa.util.threadmanager import ThreadManager
30 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
31 import sfa.plc.peers as peers
32 from sfa.util.version import version_core
33 from sfa.util.callids import Callids
36 def _call_id_supported(api, server):
38 Returns true if server support the optional call_id arg, false otherwise.
40 server_version = api.get_cached_server_version(server)
42 if 'sfa' in server_version:
43 code_tag = server_version['code_tag']
44 code_tag_parts = code_tag.split("-")
46 version_parts = code_tag_parts[0].split(".")
47 major, minor = version_parts[0:2]
48 rev = code_tag_parts[1]
50 if int(minor) > 0 or int(rev) > 20:
54 # we have specialized xmlrpclib.ServerProxy to remember the input url
55 # OTOH it's not clear if we're only dealing with XMLRPCServerProxy instances
56 def get_serverproxy_url (server):
60 logger.warning("GetVersion, falling back to xmlrpclib.ServerProxy internals")
61 return server._ServerProxy__host + server._ServerProxy__handler
64 # peers explicitly in aggregates.xml
65 peers =dict ([ (peername,get_serverproxy_url(v)) for (peername,v) in api.aggregates.iteritems()
66 if peername != api.hrn])
68 request_rspec_versions = [dict(pg_rspec_request_version), dict(sfa_rspec_version)]
69 ad_rspec_versions = [dict(pg_rspec_ad_version), dict(sfa_rspec_version)]
70 version_more = {'interface':'slicemgr',
71 'hrn' : xrn.get_hrn(),
72 'urn' : xrn.get_urn(),
74 'request_rspec_versions': request_rspec_versions,
75 'ad_rspec_versions': ad_rspec_versions,
76 'default_ad_rspec': dict(sfa_rspec_version)
78 sm_version=version_core(version_more)
79 # local aggregate if present needs to have localhost resolved
80 if api.hrn in api.aggregates:
81 local_am_url=get_serverproxy_url(api.aggregates[api.hrn])
82 sm_version['peers'][api.hrn]=local_am_url.replace('localhost',sm_version['hostname'])
85 def drop_slicemgr_stats(rspec):
87 stats_elements = rspec.xml.xpath('//statistics')
88 for node in stats_elements:
89 node.getparent().remove(node)
91 api.logger.warn("drop_slicemgr_stats failed: %s " % (str(e)))
93 def add_slicemgr_stat(rspec, callname, aggname, elapsed, status):
95 stats_tags = rspec.xml.xpath('//statistics[@call="%s"]' % callname)
97 stats_tag = stats_tags[0]
99 stats_tag = etree.SubElement(rspec.xml, "statistics", call=callname)
101 etree.SubElement(stats_tag, "aggregate", name=str(aggname), elapsed=str(elapsed), status=str(status))
103 api.logger.warn("add_slicemgr_stat failed on %s: %s" %(aggname, str(e)))
105 def ListResources(api, creds, options, call_id):
106 def _ListResources(aggregate, server, credential, opts, call_id):
109 args = [credential, my_opts]
112 if _call_id_supported(api, server):
114 version = api.get_cached_server_version(server)
115 # force ProtoGENI aggregates to give us a v2 RSpec
116 if 'sfa' not in version.keys():
117 my_opts['rspec_version'] = dict(pg_rspec_ad_version)
118 rspec = server.ListResources(*args)
119 return {"aggregate": aggregate, "rspec": rspec, "elapsed": time.time()-tStart, "status": "success"}
121 api.logger.warn("ListResources failed at %s: %s" %(server.url, str(e)))
122 return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception"}
124 if Callids().already_handled(call_id): return ""
126 # get slice's hrn from options
127 xrn = options.get('geni_slice_urn', '')
128 (hrn, type) = urn_to_hrn(xrn)
129 if 'geni_compressed' in options:
130 del(options['geni_compressed'])
132 # get the rspec's return format from options
133 rspec_version = RSpecVersion(options.get('rspec_version'))
134 version_string = "rspec_%s" % (rspec_version.get_version_name())
136 # look in cache first
137 if caching and api.cache and not xrn:
138 rspec = api.cache.get(version_string)
142 # get the callers hrn
143 valid_cred = api.auth.checkCredentials(creds, 'listnodes', hrn)[0]
144 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
146 # attempt to use delegated credential first
147 credential = api.getDelegatedCredential(creds)
149 credential = api.getCredential()
150 credentials = [credential]
151 threads = ThreadManager()
152 for aggregate in api.aggregates:
153 # prevent infinite loop. Dont send request back to caller
154 # unless the caller is the aggregate's SM
155 if caller_hrn == aggregate and aggregate != api.hrn:
158 # get the rspec from the aggregate
159 server = api.aggregates[aggregate]
160 threads.run(_ListResources, aggregate, server, credentials, options, call_id)
162 results = threads.get_results()
163 rspec_version = RSpecVersion(options.get('rspec_version'))
164 if rspec_version['type'] == pg_rspec_ad_version['type']:
169 for result in results:
170 add_slicemgr_stat(rspec, "ListResources", result["aggregate"], result["elapsed"], result["status"])
171 if result["status"]=="success":
173 rspec.merge(result["rspec"])
175 api.logger.log_exc("SM.ListResources: Failed to merge aggregate rspec")
178 if caching and api.cache and not xrn:
179 api.cache.add(version_string, rspec.toxml())
184 def CreateSliver(api, xrn, creds, rspec_str, users, call_id):
186 def _CreateSliver(aggregate, server, xrn, credential, rspec, users, call_id):
189 # Need to call GetVersion at an aggregate to determine the supported
190 # rspec type/format beofre calling CreateSliver at an Aggregate.
191 server_version = api.get_cached_server_version(server)
192 if 'sfa' not in server_version and 'geni_api' in server_version:
193 # sfa aggregtes support both sfa and pg rspecs, no need to convert
194 # if aggregate supports sfa rspecs. otherwise convert to pg rspec
195 rspec = RSpecConverter.to_pg_rspec(rspec)
196 args = [xrn, credential, rspec, users]
197 if _call_id_supported(api, server):
199 rspec = server.CreateSliver(*args)
200 return {"aggregate": aggregate, "rspec": rspec, "elapsed": time.time()-tStart, "status": "success"}
202 logger.log_exc('Something wrong in _CreateSliver with URL %s'%server.url)
203 return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception"}
205 if Callids().already_handled(call_id): return ""
206 # Validate the RSpec against PlanetLab's schema --disabled for now
207 # The schema used here needs to aggregate the PL and VINI schemas
208 # schema = "/var/www/html/schemas/pl.rng"
209 rspec = parse_rspec(rspec_str)
212 rspec.validate(schema)
214 # if there is a <statistics> section, the aggregates don't care about it,
216 drop_slicemgr_stats(rspec)
218 # attempt to use delegated credential first
219 credential = api.getDelegatedCredential(creds)
221 credential = api.getCredential()
223 # get the callers hrn
224 hrn, type = urn_to_hrn(xrn)
225 valid_cred = api.auth.checkCredentials(creds, 'createsliver', hrn)[0]
226 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
227 threads = ThreadManager()
228 for aggregate in api.aggregates:
229 # prevent infinite loop. Dont send request back to caller
230 # unless the caller is the aggregate's SM
231 if caller_hrn == aggregate and aggregate != api.hrn:
233 server = api.aggregates[aggregate]
234 # Just send entire RSpec to each aggregate
235 threads.run(_CreateSliver, aggregate, server, xrn, credential, rspec.toxml(), users, call_id)
237 results = threads.get_results()
239 for result in results:
240 add_slicemgr_stat(rspec, "CreateSliver", result["aggregate"], result["elapsed"], result["status"])
241 if result["status"]=="success":
243 rspec.merge(result["rspec"])
245 api.logger.log_exc("SM.CreateSliver: Failed to merge aggregate rspec")
248 def RenewSliver(api, xrn, creds, expiration_time, call_id):
249 def _RenewSliver(server, xrn, creds, expiration_time, call_id):
250 server_version = api.get_cached_server_version(server)
251 args = [xrn, creds, expiration_time, call_id]
252 if _call_id_supported(api, server):
254 return server.RenewSliver(*args)
256 if Callids().already_handled(call_id): return True
258 (hrn, type) = urn_to_hrn(xrn)
259 # get the callers hrn
260 valid_cred = api.auth.checkCredentials(creds, 'renewsliver', hrn)[0]
261 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
263 # attempt to use delegated credential first
264 credential = api.getDelegatedCredential(creds)
266 credential = api.getCredential()
267 threads = ThreadManager()
268 for aggregate in api.aggregates:
269 # prevent infinite loop. Dont send request back to caller
270 # unless the caller is the aggregate's SM
271 if caller_hrn == aggregate and aggregate != api.hrn:
273 server = api.aggregates[aggregate]
274 threads.run(_RenewSliver, server, xrn, [credential], expiration_time, call_id)
276 return reduce (lambda x,y: x and y, threads.get_results() , True)
278 def DeleteSliver(api, xrn, creds, call_id):
279 def _DeleteSliver(server, xrn, creds, call_id):
280 server_version = api.get_cached_server_version(server)
282 if _call_id_supported(api, server):
284 return server.DeleteSliver(*args)
286 if Callids().already_handled(call_id): return ""
287 (hrn, type) = urn_to_hrn(xrn)
288 # get the callers hrn
289 valid_cred = api.auth.checkCredentials(creds, 'deletesliver', hrn)[0]
290 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
292 # attempt to use delegated credential first
293 credential = api.getDelegatedCredential(creds)
295 credential = api.getCredential()
296 threads = ThreadManager()
297 for aggregate in api.aggregates:
298 # prevent infinite loop. Dont send request back to caller
299 # unless the caller is the aggregate's SM
300 if caller_hrn == aggregate and aggregate != api.hrn:
302 server = api.aggregates[aggregate]
303 threads.run(_DeleteSliver, server, xrn, credential, call_id)
304 threads.get_results()
308 # first draft at a merging SliverStatus
309 def SliverStatus(api, slice_xrn, creds, call_id):
310 def _SliverStatus(server, xrn, creds, call_id):
311 server_version = api.get_cached_server_version(server)
313 if _call_id_supported(api, server):
315 return server.SliverStatus(*args)
317 if Callids().already_handled(call_id): return {}
318 # attempt to use delegated credential first
319 credential = api.getDelegatedCredential(creds)
321 credential = api.getCredential()
322 threads = ThreadManager()
323 for aggregate in api.aggregates:
324 server = api.aggregates[aggregate]
325 threads.run (_SliverStatus, server, slice_xrn, credential, call_id)
326 results = threads.get_results()
328 # get rid of any void result - e.g. when call_id was hit where by convention we return {}
329 results = [ result for result in results if result and result['geni_resources']]
331 # do not try to combine if there's no result
332 if not results : return {}
334 # otherwise let's merge stuff
337 # mmh, it is expected that all results carry the same urn
338 overall['geni_urn'] = results[0]['geni_urn']
339 overall['pl_login'] = results[0]['pl_login']
340 # append all geni_resources
341 overall['geni_resources'] = \
342 reduce (lambda x,y: x+y, [ result['geni_resources'] for result in results] , [])
343 overall['status'] = 'unknown'
344 if overall['geni_resources']:
345 overall['status'] = 'ready'
351 def ListSlices(api, creds, call_id):
352 def _ListSlices(server, creds, call_id):
353 server_version = api.get_cached_server_version(server)
355 if _call_id_supported(api, server):
357 return server.ListSlices(*args)
359 if Callids().already_handled(call_id): return []
361 # look in cache first
362 if caching and api.cache:
363 slices = api.cache.get('slices')
367 # get the callers hrn
368 valid_cred = api.auth.checkCredentials(creds, 'listslices', None)[0]
369 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
371 # attempt to use delegated credential first
372 credential = api.getDelegatedCredential(creds)
374 credential = api.getCredential()
375 threads = ThreadManager()
376 # fetch from aggregates
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:
382 server = api.aggregates[aggregate]
383 threads.run(_ListSlices, server, credential, call_id)
386 results = threads.get_results()
388 for result in results:
389 slices.extend(result)
392 if caching and api.cache:
393 api.cache.add('slices', slices)
398 def get_ticket(api, xrn, creds, rspec, users):
399 slice_hrn, type = urn_to_hrn(xrn)
400 # get the netspecs contained within the clients rspec
401 aggregate_rspecs = {}
402 tree= etree.parse(StringIO(rspec))
403 elements = tree.findall('./network')
404 for element in elements:
405 aggregate_hrn = element.values()[0]
406 aggregate_rspecs[aggregate_hrn] = rspec
408 # get the callers hrn
409 valid_cred = api.auth.checkCredentials(creds, 'getticket', slice_hrn)[0]
410 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
412 # attempt to use delegated credential first
413 credential = api.getDelegatedCredential(creds)
415 credential = api.getCredential()
416 threads = ThreadManager()
417 for (aggregate, aggregate_rspec) in aggregate_rspecs.iteritems():
418 # prevent infinite loop. Dont send request back to caller
419 # unless the caller is the aggregate's SM
420 if caller_hrn == aggregate and aggregate != api.hrn:
423 if aggregate in api.aggregates:
424 server = api.aggregates[aggregate]
426 net_urn = hrn_to_urn(aggregate, 'authority')
427 # we may have a peer that knows about this aggregate
428 for agg in api.aggregates:
429 target_aggs = api.aggregates[agg].get_aggregates(credential, net_urn)
430 if not target_aggs or not 'hrn' in target_aggs[0]:
432 # send the request to this address
433 url = target_aggs[0]['url']
434 server = xmlrpcprotocol.get_server(url, api.key_file, api.cert_file, timeout=30)
435 # aggregate found, no need to keep looping
439 threads.run(server.GetTicket, xrn, credential, aggregate_rspec, users)
441 results = threads.get_results()
443 # gather information from each ticket
448 for result in results:
449 agg_ticket = SfaTicket(string=result)
450 attrs = agg_ticket.get_attributes()
452 object_gid = agg_ticket.get_gid_object()
453 rspecs.append(agg_ticket.get_rspec())
454 initscripts.extend(attrs.get('initscripts', []))
455 slivers.extend(attrs.get('slivers', []))
458 attributes = {'initscripts': initscripts,
460 merged_rspec = merge_rspecs(rspecs)
462 # create a new ticket
463 ticket = SfaTicket(subject = slice_hrn)
464 ticket.set_gid_caller(api.auth.client_gid)
465 ticket.set_issuer(key=api.key, subject=api.hrn)
466 ticket.set_gid_object(object_gid)
467 ticket.set_pubkey(object_gid.get_pubkey())
468 #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
469 ticket.set_attributes(attributes)
470 ticket.set_rspec(merged_rspec)
473 return ticket.save_to_string(save_parents=True)
475 def start_slice(api, xrn, creds):
476 hrn, type = urn_to_hrn(xrn)
478 # get the callers hrn
479 valid_cred = api.auth.checkCredentials(creds, 'startslice', hrn)[0]
480 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
482 # attempt to use delegated credential first
483 credential = api.getDelegatedCredential(creds)
485 credential = api.getCredential()
486 threads = ThreadManager()
487 for aggregate in api.aggregates:
488 # prevent infinite loop. Dont send request back to caller
489 # unless the caller is the aggregate's SM
490 if caller_hrn == aggregate and aggregate != api.hrn:
492 server = api.aggregates[aggregate]
493 threads.run(server.Start, xrn, credential)
494 threads.get_results()
497 def stop_slice(api, xrn, creds):
498 hrn, type = urn_to_hrn(xrn)
500 # get the callers hrn
501 valid_cred = api.auth.checkCredentials(creds, 'stopslice', hrn)[0]
502 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
504 # attempt to use delegated credential first
505 credential = api.getDelegatedCredential(creds)
507 credential = api.getCredential()
508 threads = ThreadManager()
509 for aggregate in api.aggregates:
510 # prevent infinite loop. Dont send request back to caller
511 # unless the caller is the aggregate's SM
512 if caller_hrn == aggregate and aggregate != api.hrn:
514 server = api.aggregates[aggregate]
515 threads.run(server.Stop, xrn, credential)
516 threads.get_results()
519 def reset_slice(api, xrn):
525 def shutdown(api, xrn, creds):
531 def status(api, xrn, creds):
539 r.parseFile(sys.argv[1])
541 CreateSliver(None,'plc.princeton.tmacktestslice',rspec,'create-slice-tmacktestslice')
543 if __name__ == "__main__":