4 from StringIO import StringIO
5 from types import StringTypes
6 from copy import deepcopy
10 from sfa.util.sfalogging import sfa_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_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
35 # we have specialized xmlrpclib.ServerProxy to remember the input url
36 # OTOH it's not clear if we're only dealing with XMLRPCServerProxy instances
37 def get_serverproxy_url (server):
41 sfa_logger().warning("GetVersion, falling back to xmlrpclib.ServerProxy internals")
42 return server._ServerProxy__host + server._ServerProxy__handler
45 # peers explicitly in aggregates.xml
46 peers =dict ([ (peername,get_serverproxy_url(v)) for (peername,v) in api.aggregates.iteritems()
47 if peername != api.hrn])
49 supported_rspecs = [dict(pg_rspec_version), dict(sfa_rspec_version)]
50 version_more = {'interface':'slicemgr',
51 'hrn' : xrn.get_hrn(),
52 'urn' : xrn.get_urn(),
54 'request_rspec_versions': supported_rspecs,
55 'ad_rspec_versions': supported_rspecs,
56 'default_ad_rspec': dict(sfa_rspec_version)
58 sm_version=version_core(version_more)
59 # local aggregate if present needs to have localhost resolved
60 if api.hrn in api.aggregates:
61 local_am_url=get_serverproxy_url(api.aggregates[api.hrn])
62 sm_version['peers'][api.hrn]=local_am_url.replace('localhost',sm_version['hostname'])
65 def CreateSliver(api, xrn, creds, rspec_str, users, call_id):
67 def _CreateSliver(aggregate, xrn, credential, rspec, users, call_id):
68 # Need to call GetVersion at an aggregate to determine the supported
69 # rspec type/format beofre calling CreateSliver at an Aggregate.
70 # The Aggregate's verion info is cached
71 server = api.aggregates[aggregate]
72 # get cached aggregate version
73 aggregate_version_key = 'version_'+ aggregate
74 aggregate_version = api.cache.get(aggregate_version_key)
75 if not aggregate_version:
76 # get current aggregate version anc cache it for 24 hours
77 aggregate_version = server.GetVersion()
78 api.cache.add(aggregate_version_key, aggregate_version, 60 * 60 * 24)
80 if 'sfa' not in aggregate_version and 'geni_api' in aggregate_version:
81 # sfa aggregtes support both sfa and pg rspecs, no need to convert
82 # if aggregate supports sfa rspecs. othewise convert to pg rspec
83 rspec = RSpecConverter.to_pg_rspec(rspec)
85 return server.CreateSliver(xrn, credential, rspec, users, call_id)
88 if Callids().already_handled(call_id): return ""
90 # Validate the RSpec against PlanetLab's schema --disabled for now
91 # The schema used here needs to aggregate the PL and VINI schemas
92 # schema = "/var/www/html/schemas/pl.rng"
93 rspec = parse_rspec(rspec_str)
96 rspec.validate(schema)
98 # attempt to use delegated credential first
99 credential = api.getDelegatedCredential(creds)
101 credential = api.getCredential()
103 # get the callers hrn
104 hrn, type = urn_to_hrn(xrn)
105 valid_cred = api.auth.checkCredentials(creds, 'createsliver', hrn)[0]
106 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
107 threads = ThreadManager()
108 for aggregate in api.aggregates:
109 # prevent infinite loop. Dont send request back to caller
110 # unless the caller is the aggregate's SM
111 if caller_hrn == aggregate and aggregate != api.hrn:
114 # Just send entire RSpec to each aggregate
115 threads.run(_CreateSliver, aggregate, xrn, credential, rspec.toxml(), users, call_id)
117 results = threads.get_results()
119 for result in results:
123 def RenewSliver(api, xrn, creds, expiration_time, call_id):
124 if Callids().already_handled(call_id): return True
126 (hrn, type) = urn_to_hrn(xrn)
127 # get the callers hrn
128 valid_cred = api.auth.checkCredentials(creds, 'renewsliver', hrn)[0]
129 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
131 # attempt to use delegated credential first
132 credential = api.getDelegatedCredential(creds)
134 credential = api.getCredential()
135 threads = ThreadManager()
136 for aggregate in api.aggregates:
137 # prevent infinite loop. Dont send request back to caller
138 # unless the caller is the aggregate's SM
139 if caller_hrn == aggregate and aggregate != api.hrn:
142 server = api.aggregates[aggregate]
143 threads.run(server.RenewSliver, xrn, [credential], expiration_time, call_id)
145 return reduce (lambda x,y: x and y, threads.get_results() , True)
147 def get_ticket(api, xrn, creds, rspec, users):
148 slice_hrn, type = urn_to_hrn(xrn)
149 # get the netspecs contained within the clients rspec
150 aggregate_rspecs = {}
151 tree= etree.parse(StringIO(rspec))
152 elements = tree.findall('./network')
153 for element in elements:
154 aggregate_hrn = element.values()[0]
155 aggregate_rspecs[aggregate_hrn] = rspec
157 # get the callers hrn
158 valid_cred = api.auth.checkCredentials(creds, 'getticket', slice_hrn)[0]
159 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
161 # attempt to use delegated credential first
162 credential = api.getDelegatedCredential(creds)
164 credential = api.getCredential()
165 threads = ThreadManager()
166 for (aggregate, aggregate_rspec) in aggregate_rspecs.iteritems():
167 # prevent infinite loop. Dont send request back to caller
168 # unless the caller is the aggregate's SM
169 if caller_hrn == aggregate and aggregate != api.hrn:
172 if aggregate in api.aggregates:
173 server = api.aggregates[aggregate]
175 net_urn = hrn_to_urn(aggregate, 'authority')
176 # we may have a peer that knows about this aggregate
177 for agg in api.aggregates:
178 target_aggs = api.aggregates[agg].get_aggregates(credential, net_urn)
179 if not target_aggs or not 'hrn' in target_aggs[0]:
181 # send the request to this address
182 url = target_aggs[0]['url']
183 server = xmlrpcprotocol.get_server(url, api.key_file, api.cert_file)
184 # aggregate found, no need to keep looping
188 threads.run(server.GetTicket, xrn, credential, aggregate_rspec, users)
190 results = threads.get_results()
192 # gather information from each ticket
197 for result in results:
198 agg_ticket = SfaTicket(string=result)
199 attrs = agg_ticket.get_attributes()
201 object_gid = agg_ticket.get_gid_object()
202 rspecs.append(agg_ticket.get_rspec())
203 initscripts.extend(attrs.get('initscripts', []))
204 slivers.extend(attrs.get('slivers', []))
207 attributes = {'initscripts': initscripts,
209 merged_rspec = merge_rspecs(rspecs)
211 # create a new ticket
212 ticket = SfaTicket(subject = slice_hrn)
213 ticket.set_gid_caller(api.auth.client_gid)
214 ticket.set_issuer(key=api.key, subject=api.hrn)
215 ticket.set_gid_object(object_gid)
216 ticket.set_pubkey(object_gid.get_pubkey())
217 #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
218 ticket.set_attributes(attributes)
219 ticket.set_rspec(merged_rspec)
222 return ticket.save_to_string(save_parents=True)
225 def DeleteSliver(api, xrn, creds, call_id):
226 if Callids().already_handled(call_id): return ""
227 (hrn, type) = urn_to_hrn(xrn)
228 # get the callers hrn
229 valid_cred = api.auth.checkCredentials(creds, 'deletesliver', hrn)[0]
230 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
232 # attempt to use delegated credential first
233 credential = api.getDelegatedCredential(creds)
235 credential = api.getCredential()
236 threads = ThreadManager()
237 for aggregate in api.aggregates:
238 # prevent infinite loop. Dont send request back to caller
239 # unless the caller is the aggregate's SM
240 if caller_hrn == aggregate and aggregate != api.hrn:
242 server = api.aggregates[aggregate]
243 threads.run(server.DeleteSliver, xrn, credential, call_id)
244 threads.get_results()
247 def start_slice(api, xrn, creds):
248 hrn, type = urn_to_hrn(xrn)
250 # get the callers hrn
251 valid_cred = api.auth.checkCredentials(creds, 'startslice', hrn)[0]
252 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
254 # attempt to use delegated credential first
255 credential = api.getDelegatedCredential(creds)
257 credential = api.getCredential()
258 threads = ThreadManager()
259 for aggregate in api.aggregates:
260 # prevent infinite loop. Dont send request back to caller
261 # unless the caller is the aggregate's SM
262 if caller_hrn == aggregate and aggregate != api.hrn:
264 server = api.aggregates[aggregate]
265 threads.run(server.Start, xrn, credential)
266 threads.get_results()
269 def stop_slice(api, xrn, creds):
270 hrn, type = urn_to_hrn(xrn)
272 # get the callers hrn
273 valid_cred = api.auth.checkCredentials(creds, 'stopslice', hrn)[0]
274 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
276 # attempt to use delegated credential first
277 credential = api.getDelegatedCredential(creds)
279 credential = api.getCredential()
280 threads = ThreadManager()
281 for aggregate in api.aggregates:
282 # prevent infinite loop. Dont send request back to caller
283 # unless the caller is the aggregate's SM
284 if caller_hrn == aggregate and aggregate != api.hrn:
286 server = api.aggregates[aggregate]
287 threads.run(server.Stop, xrn, credential)
288 threads.get_results()
291 def reset_slice(api, xrn):
297 def shutdown(api, xrn, creds):
303 def status(api, xrn, creds):
309 # Thierry : caching at the slicemgr level makes sense to some extent
312 def ListSlices(api, creds, call_id):
314 if Callids().already_handled(call_id): return []
316 # look in cache first
317 if caching and api.cache:
318 slices = api.cache.get('slices')
322 # get the callers hrn
323 valid_cred = api.auth.checkCredentials(creds, 'listslices', None)[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 # fetch from aggregates
332 for aggregate in api.aggregates:
333 # prevent infinite loop. Dont send request back to caller
334 # unless the caller is the aggregate's SM
335 if caller_hrn == aggregate and aggregate != api.hrn:
337 server = api.aggregates[aggregate]
338 threads.run(server.ListSlices, credential, call_id)
341 results = threads.get_results()
343 for result in results:
344 slices.extend(result)
347 if caching and api.cache:
348 api.cache.add('slices', slices)
353 def ListResources(api, creds, options, call_id):
355 if Callids().already_handled(call_id): return ""
357 # get slice's hrn from options
358 xrn = options.get('geni_slice_urn', '')
359 (hrn, type) = urn_to_hrn(xrn)
361 # get the rspec's return format from options
362 rspec_version = RSpecVersion(options.get('rspec_version'))
363 version_string = "rspec_%s" % (rspec_version.get_version_name())
365 #panos adding the info option to the caching key (can be improved)
366 if options.get('info'):
367 version_string = version_string + "_"+options.get('info')
369 print "version string = ",version_string
371 # look in cache first
372 if caching and api.cache and not xrn:
373 rspec = api.cache.get(version_string)
377 # get the callers hrn
378 valid_cred = api.auth.checkCredentials(creds, 'listnodes', hrn)[0]
379 caller_hrn = Credential(string=valid_cred).get_gid_caller().get_hrn()
381 # attempt to use delegated credential first
382 credential = api.getDelegatedCredential(creds)
384 credential = api.getCredential()
385 threads = ThreadManager()
386 for aggregate in api.aggregates:
387 # prevent infinite loop. Dont send request back to caller
388 # unless the caller is the aggregate's SM
389 if caller_hrn == aggregate and aggregate != api.hrn:
391 # get the rspec from the aggregate
392 server = api.aggregates[aggregate]
393 my_opts = copy(options)
394 my_opts['geni_compressed'] = False
395 threads.run(server.ListResources, credential, my_opts, call_id)
397 results = threads.get_results()
398 #results.append(open('/root/protogeni.rspec', 'r').read())
399 rspec_version = RSpecVersion(my_opts.get('rspec_version'))
400 if rspec_version['type'].lower() == 'protogeni':
405 for result in results:
411 api.logger.info("SM.ListResources: Failed to merge aggregate rspec")
414 if caching and api.cache and not xrn:
415 api.cache.add(version_string, rspec.toxml())
419 # first draft at a merging SliverStatus
420 def SliverStatus(api, slice_xrn, creds, call_id):
421 if Callids().already_handled(call_id): return {}
422 # attempt to use delegated credential first
423 credential = api.getDelegatedCredential(creds)
425 credential = api.getCredential()
426 threads = ThreadManager()
427 for aggregate in api.aggregates:
428 server = api.aggregates[aggregate]
429 threads.run (server.SliverStatus, slice_xrn, credential, call_id)
430 results = threads.get_results()
432 # get rid of any void result - e.g. when call_id was hit where by convention we return {}
433 results = [ result for result in results if result and result['geni_resources']]
435 # do not try to combine if there's no result
436 if not results : return {}
438 # otherwise let's merge stuff
441 # mmh, it is expected that all results carry the same urn
442 overall['geni_urn'] = results[0]['geni_urn']
444 # consolidate geni_status - simple model using max on a total order
445 states = [ 'ready', 'configuring', 'failed', 'unknown' ]
447 shash = dict ( zip ( states, range(len(states)) ) )
448 def combine_status (x,y):
449 return shash [ max (shash(x),shash(y)) ]
450 overall['geni_status'] = reduce (combine_status, [ result['geni_status'] for result in results], 'ready' )
452 # {'ready':0,'configuring':1,'failed':2,'unknown':3}
453 # append all geni_resources
454 overall['geni_resources'] = \
455 reduce (lambda x,y: x+y, [ result['geni_resources'] for result in results] , [])
461 r.parseFile(sys.argv[1])
463 CreateSliver(None,'plc.princeton.tmacktestslice',rspec,'create-slice-tmacktestslice')
465 if __name__ == "__main__":