bda355e55dba0d06de72d0efaeefb289e9c4d447
[sfa.git] / sfa / managers / slice_manager_pl.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.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
34
35
36 def _call_id_supported(api, server):
37     """
38     Returns true if server support the optional call_id arg, false otherwise.
39     """
40     server_version = api.get_cached_server_version(server)
41
42     if 'sfa' in server_version:
43         code_tag = server_version['code_tag']
44         code_tag_parts = code_tag.split("-")
45
46         version_parts = code_tag_parts[0].split(".")
47         major, minor = version_parts[0:2]
48         rev = code_tag_parts[1]
49         if int(major) > 1:
50             if int(minor) > 0 or int(rev) > 20:
51                 return True
52     return False
53
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):
57     try:
58         return server.url
59     except:
60         logger.warning("GetVersion, falling back to xmlrpclib.ServerProxy internals")
61         return server._ServerProxy__host + server._ServerProxy__handler
62
63 def GetVersion(api):
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])
67     xrn=Xrn (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(),
73                     'peers': peers,
74                     'request_rspec_versions': request_rspec_versions,
75                     'ad_rspec_versions': ad_rspec_versions,
76                     'default_ad_rspec': dict(sfa_rspec_version)
77                     }
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'])
83     return sm_version
84
85 def drop_slicemgr_stats(rspec):
86     try:
87         stats_elements = rspec.xml.xpath('//statistics')
88         for node in stats_elements:
89             node.getparent().remove(node)
90     except Exception, e:
91         api.logger.warn("drop_slicemgr_stats failed: %s " % (str(e)))
92
93 def add_slicemgr_stat(rspec, callname, aggname, elapsed, status):
94     try:
95         stats_tags = rspec.xml.xpath('//statistics[@call="%s"]' % callname)
96         if stats_tags:
97             stats_tag = stats_tags[0]
98         else:
99             stats_tag = etree.SubElement(rspec.xml, "statistics", call="ListResources")
100
101         etree.SubElement(stats_tag, "aggregate", name=str(aggname), elapsed=str(elapsed), status=str(status))
102     except Exception, e:
103         api.logger.warn("add_slicemgr_stat failed on  %s: %s" %(aggname, str(e)))
104
105 def ListResources(api, creds, options, call_id):
106     def _ListResources(aggregate, server, credential, opts, call_id):
107
108         my_opts = copy(opts)
109         args = [credential, my_opts]
110         tStart = time.time()
111         try:
112             if _call_id_supported(api, server):
113                 args.append(call_id)
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'] = pg_rspec_ad_version
118             rspec = server.ListResources(*args)
119             return {"aggregate": aggregate, "rspec": rspec, "elapsed": time.time()-tStart, "status": "success"}
120         except Exception, e:
121             api.logger.warn("ListResources failed at %s: %s" %(server.url, str(e)))
122             return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception"}
123
124     if Callids().already_handled(call_id): return ""
125
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'])
131
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())
135
136     # look in cache first
137     if caching and api.cache and not xrn:
138         rspec =  api.cache.get(version_string)
139         if rspec:
140             return rspec
141
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()
145
146     # attempt to use delegated credential first
147     credential = api.getDelegatedCredential(creds)
148     if not credential:
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:
156             continue
157
158         # get the rspec from the aggregate
159         server = api.aggregates[aggregate]
160         threads.run(_ListResources, aggregate, server, credentials, options, call_id)
161
162     results = threads.get_results()
163     rspec_version = RSpecVersion(options.get('rspec_version'))
164     if rspec_version['type'] == pg_rspec_ad_version['type']:
165         rspec = PGRSpec()
166     else:
167         rspec = SfaRSpec()
168
169     for result in results:
170         add_slicemgr_stat(rspec, "ListResources", result["aggregate"], result["elapsed"], result["status"])
171         if result["status"]=="success":
172             try:
173                 rspec.merge(result["rspec"])
174             except:
175                 api.logger.log_exc("SM.ListResources: Failed to merge aggregate rspec")
176
177     # cache the result
178     if caching and api.cache and not xrn:
179         api.cache.add(version_string, rspec.toxml())
180
181     return rspec.toxml()
182
183
184 def CreateSliver(api, xrn, creds, rspec_str, users, call_id):
185
186     def _CreateSliver(aggregate, server, xrn, credential, rspec, users, call_id):
187         tStart = time.time()
188         try:
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):
198                 args.append(call_id)
199             rspec = server.CreateSliver(*args)
200             return {"aggregate": aggregate, "rspec": rspec, "elapsed": time.time()-tStart, "status": "success"}
201         except: 
202             logger.log_exc('Something wrong in _CreateSliver with URL %s'%server.url)
203             return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception"}
204
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)
210     schema = None
211     if schema:
212         rspec.validate(schema)
213
214     # if there is a <statistics> section, the aggregates don't care about it,
215     # so delete it.
216     drop_slicemgr_stats(rspec)
217
218     # attempt to use delegated credential first
219     credential = api.getDelegatedCredential(creds)
220     if not credential:
221         credential = api.getCredential()
222
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:
232             continue
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)
236             
237     results = threads.get_results()
238     rspec = SfaRSpec()
239     for result in results:
240         add_slicemgr_stat(rspec, "CreateSliver", result["aggregate"], result["elapsed"], result["status"])
241         if result["status"]=="success":
242             try:
243                 rspec.merge(result["rspec"])
244             except:
245                 api.logger.log_exc("SM.CreateSliver: Failed to merge aggregate rspec")
246     return rspec.toxml()
247
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):
253             args.append(call_id)
254         return server.RenewSliver(*args)
255
256     if Callids().already_handled(call_id): return True
257
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()
262
263     # attempt to use delegated credential first
264     credential = api.getDelegatedCredential(creds)
265     if not credential:
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:
272             continue
273         server = api.aggregates[aggregate]
274         threads.run(_RenewSliver, server, xrn, [credential], expiration_time, call_id)
275     # 'and' the results
276     return reduce (lambda x,y: x and y, threads.get_results() , True)
277
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)
281         args =  [xrn, creds]
282         if _call_id_supported(api, server):
283             args.append(call_id)
284         return server.DeleteSliver(*args)
285
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()
291
292     # attempt to use delegated credential first
293     credential = api.getDelegatedCredential(creds)
294     if not credential:
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:
301             continue
302         server = api.aggregates[aggregate]
303         threads.run(_DeleteSliver, server, xrn, credential, call_id)
304     threads.get_results()
305     return 1
306
307
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)
312         args =  [xrn, creds]
313         if _call_id_supported(api, server):
314             args.append(call_id)
315         return server.SliverStatus(*args)
316     
317     if Callids().already_handled(call_id): return {}
318     # attempt to use delegated credential first
319     credential = api.getDelegatedCredential(creds)
320     if not credential:
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()
327
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']]
330
331     # do not try to combine if there's no result
332     if not results : return {}
333
334     # otherwise let's merge stuff
335     overall = {}
336
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'
346
347     return overall
348
349 caching=True
350 #caching=False
351 def ListSlices(api, creds, call_id):
352     def _ListSlices(server, creds, call_id):
353         server_version = api.get_cached_server_version(api, server)
354         args =  [creds]
355         if _call_id_supported(api, server):
356             args.append(call_id)
357         return server.ListSlices(*args)
358
359     if Callids().already_handled(call_id): return []
360
361     # look in cache first
362     if caching and api.cache:
363         slices = api.cache.get('slices')
364         if slices:
365             return slices
366
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()
370
371     # attempt to use delegated credential first
372     credential = api.getDelegatedCredential(creds)
373     if not credential:
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:
381             continue
382         server = api.aggregates[aggregate]
383         threads.run(_ListSlices, server, credential, call_id)
384
385     # combime results
386     results = threads.get_results()
387     slices = []
388     for result in results:
389         slices.extend(result)
390
391     # cache the result
392     if caching and api.cache:
393         api.cache.add('slices', slices)
394
395     return slices
396
397
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 
407
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()
411
412     # attempt to use delegated credential first
413     credential = api.getDelegatedCredential(creds)
414     if not credential:
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:
421             continue
422         server = None
423         if aggregate in api.aggregates:
424             server = api.aggregates[aggregate]
425         else:
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]:
431                     continue
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
436                 break   
437         if server is None:
438             continue 
439         threads.run(server.GetTicket, xrn, credential, aggregate_rspec, users)
440
441     results = threads.get_results()
442     
443     # gather information from each ticket 
444     rspecs = []
445     initscripts = []
446     slivers = [] 
447     object_gid = None  
448     for result in results:
449         agg_ticket = SfaTicket(string=result)
450         attrs = agg_ticket.get_attributes()
451         if not object_gid:
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', [])) 
456     
457     # merge info
458     attributes = {'initscripts': initscripts,
459                  'slivers': slivers}
460     merged_rspec = merge_rspecs(rspecs) 
461
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)
471     ticket.encode()
472     ticket.sign()          
473     return ticket.save_to_string(save_parents=True)
474
475 def start_slice(api, xrn, creds):
476     hrn, type = urn_to_hrn(xrn)
477
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()
481
482     # attempt to use delegated credential first
483     credential = api.getDelegatedCredential(creds)
484     if not credential:
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:
491             continue
492         server = api.aggregates[aggregate]
493         threads.run(server.Start, xrn, credential)
494     threads.get_results()    
495     return 1
496  
497 def stop_slice(api, xrn, creds):
498     hrn, type = urn_to_hrn(xrn)
499
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()
503
504     # attempt to use delegated credential first
505     credential = api.getDelegatedCredential(creds)
506     if not credential:
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:
513             continue
514         server = api.aggregates[aggregate]
515         threads.run(server.Stop, xrn, credential)
516     threads.get_results()    
517     return 1
518
519 def reset_slice(api, xrn):
520     """
521     Not implemented
522     """
523     return 1
524
525 def shutdown(api, xrn, creds):
526     """
527     Not implemented   
528     """
529     return 1
530
531 def status(api, xrn, creds):
532     """
533     Not implemented 
534     """
535     return 1
536
537 def main():
538     r = RSpec()
539     r.parseFile(sys.argv[1])
540     rspec = r.toDict()
541     CreateSliver(None,'plc.princeton.tmacktestslice',rspec,'create-slice-tmacktestslice')
542
543 if __name__ == "__main__":
544     main()
545