Merge branch 'master' into sqlalchemy
[sfa.git] / sfa / openstack / nova_driver.py
1 import time
2 import datetime
3 #
4 from sfa.util.faults import MissingSfaInfo, UnknownSfaType, \
5     RecordNotFound, SfaNotImplemented, SliverDoesNotExist
6
7 from sfa.util.sfalogging import logger
8 from sfa.util.defaultdict import defaultdict
9 from sfa.util.sfatime import utcparse, datetime_to_string, datetime_to_epoch
10 from sfa.util.xrn import Xrn, hrn_to_urn, get_leaf, urn_to_sliver_id
11 from sfa.util.cache import Cache
12 # used to be used in get_ticket
13 #from sfa.trust.sfaticket import SfaTicket
14
15 from sfa.rspecs.version_manager import VersionManager
16 from sfa.rspecs.rspec import RSpec
17
18 # the driver interface, mostly provides default behaviours
19 from sfa.managers.driver import Driver
20 from sfa.openstack.nova_shell import NovaShell
21 from sfa.openstack.osaggregate import OSAggregate
22 from sfa.plc.plslices import PlSlices
23 from sfa.util.osxrn import OSXrn
24
25
26 def list_to_dict(recs, key):
27     """
28     convert a list of dictionaries into a dictionary keyed on the 
29     specified dictionary key 
30     """
31     return dict ( [ (rec[key],rec) for rec in recs ] )
32
33 #
34 # PlShell is just an xmlrpc serverproxy where methods
35 # can be sent as-is; it takes care of authentication
36 # from the global config
37
38 class NovaDriver (Driver):
39
40     # the cache instance is a class member so it survives across incoming requests
41     cache = None
42
43     def __init__ (self, config):
44         Driver.__init__ (self, config)
45         self.shell = NovaShell (config)
46         self.cache=None
47         if config.SFA_AGGREGATE_CACHING:
48             if NovaDriver.cache is None:
49                 NovaDriver.cache = Cache()
50             self.cache = NovaDriver.cache
51  
52     ########################################
53     ########## registry oriented
54     ########################################
55
56     ########## disabled users 
57     def is_enabled (self, record):
58         # all records are enabled
59         return True
60
61     def augment_records_with_testbed_info (self, sfa_records):
62         return self.fill_record_info (sfa_records)
63
64     ########## 
65     def register (self, sfa_record, hrn, pub_key):
66         type = sfa_record['type']
67         pl_record = self.sfa_fields_to_pl_fields(type, hrn, sfa_record)
68
69         if type == 'slice':
70             acceptable_fields=['url', 'instantiation', 'name', 'description']
71             # add slice description, name, researchers, PI 
72             pass
73
74         elif type == 'user':
75             # add person roles, projects and keys
76             pass
77         return pointer
78         
79     ##########
80     # xxx actually old_sfa_record comes filled with plc stuff as well in the original code
81     def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
82         pointer = old_sfa_record['pointer']
83         type = old_sfa_record['type']
84
85         # new_key implemented for users only
86         if new_key and type not in [ 'user' ]:
87             raise UnknownSfaType(type)
88
89         elif type == "slice":
90             # can update description, researchers and PI
91             pass 
92         elif type == "user":
93             # can update  slices, keys and roles
94             pass
95         return True
96         
97
98     ##########
99     def remove (self, sfa_record):
100         type=sfa_record['type']
101         name = Xrn(sfa_record['hrn']).get_leaf()     
102         if type == 'user':
103             if self.shell.user_get(name):
104                 self.shell.user_delete(name)
105         elif type == 'slice':
106             if self.shell.project_get(name):
107                 self.shell.project_delete(name)
108         return True
109
110
111     ####################
112     def fill_record_info(self, records):
113         """
114         Given a (list of) SFA record, fill in the PLC specific 
115         and SFA specific fields in the record. 
116         """
117         if not isinstance(records, list):
118             records = [records]
119
120         for record in records:
121             name = Xrn(record['hrn']).get_leaf()
122             os_record = None
123             if record['type'] == 'user':
124                 os_record = self.shell.auth_manager.get_user(name)
125                 projects = self.shell.db.project_get_by_user(name)
126                 record['slices'] = [self.hrn + "." + proj.name for \
127                                     proj in projects]
128                 record['roles'] = self.shell.db.user_get_roles(name)
129                 keys = self.shell.db.key_pair_get_all_by_user(name)
130                 record['keys'] = [key.public_key for key in keys]     
131             elif record['type'] == 'slice': 
132                 os_record = self.shell.auth_manager.get_project(name)
133                 record['description'] = os_record.description
134                 record['PI'] = [self.hrn + "." + os_record.project_manager.name]
135                 record['geni_creator'] = record['PI'] 
136                 record['researcher'] = [self.hrn + "." + user for \
137                                          user in os_record.member_ids]
138             else:
139                 continue
140             record['geni_urn'] = hrn_to_urn(record['hrn'], record['type'])
141             record['geni_certificate'] = record['gid'] 
142             record['name'] = os_record.name
143             #if os_record.created_at is not None:    
144             #    record['date_created'] = datetime_to_string(utcparse(os_record.created_at))
145             #if os_record.updated_at is not None:
146             #    record['last_updated'] = datetime_to_string(utcparse(os_record.updated_at))
147  
148         return records
149
150
151     ####################
152     # plcapi works by changes, compute what needs to be added/deleted
153     def update_relation (self, subject_type, target_type, subject_id, target_ids):
154         # hard-wire the code for slice/user for now, could be smarter if needed
155         if subject_type =='slice' and target_type == 'user':
156             subject=self.shell.project_get(subject_id)[0]
157             current_target_ids = [user.name for user in subject.members]
158             add_target_ids = list ( set (target_ids).difference(current_target_ids))
159             del_target_ids = list ( set (current_target_ids).difference(target_ids))
160             logger.debug ("subject_id = %s (type=%s)"%(subject_id,type(subject_id)))
161             for target_id in add_target_ids:
162                 self.shell.project_add_member(target_id,subject_id)
163                 logger.debug ("add_target_id = %s (type=%s)"%(target_id,type(target_id)))
164             for target_id in del_target_ids:
165                 logger.debug ("del_target_id = %s (type=%s)"%(target_id,type(target_id)))
166                 self.shell.project_remove_member(target_id, subject_id)
167         else:
168             logger.info('unexpected relation to maintain, %s -> %s'%(subject_type,target_type))
169
170         
171     ########################################
172     ########## aggregate oriented
173     ########################################
174
175     def testbed_name (self): return "openstack"
176
177     # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
178     def aggregate_version (self):
179         version_manager = VersionManager()
180         ad_rspec_versions = []
181         request_rspec_versions = []
182         for rspec_version in version_manager.versions:
183             if rspec_version.content_type in ['*', 'ad']:
184                 ad_rspec_versions.append(rspec_version.to_dict())
185             if rspec_version.content_type in ['*', 'request']:
186                 request_rspec_versions.append(rspec_version.to_dict()) 
187         return {
188             'testbed':self.testbed_name(),
189             'geni_request_rspec_versions': request_rspec_versions,
190             'geni_ad_rspec_versions': ad_rspec_versions,
191             }
192
193     def list_slices (self, creds, options):
194         # look in cache first
195         if self.cache:
196             slices = self.cache.get('slices')
197             if slices:
198                 logger.debug("OpenStackDriver.list_slices returns from cache")
199                 return slices
200     
201         # get data from db
202         projs = self.shell.auth_manager.get_projects()
203         slice_urns = [OSXrn(proj.name, 'slice').urn for proj in projs] 
204     
205         # cache the result
206         if self.cache:
207             logger.debug ("OpenStackDriver.list_slices stores value in cache")
208             self.cache.add('slices', slice_urns) 
209     
210         return slice_urns
211         
212     # first 2 args are None in case of resource discovery
213     def list_resources (self, slice_urn, slice_hrn, creds, options):
214         cached_requested = options.get('cached', True) 
215     
216         version_manager = VersionManager()
217         # get the rspec's return format from options
218         rspec_version = version_manager.get_version(options.get('geni_rspec_version'))
219         version_string = "rspec_%s" % (rspec_version)
220     
221         #panos adding the info option to the caching key (can be improved)
222         if options.get('info'):
223             version_string = version_string + "_"+options.get('info', 'default')
224     
225         # look in cache first
226         if cached_requested and self.cache and not slice_hrn:
227             rspec = self.cache.get(version_string)
228             if rspec:
229                 logger.debug("OpenStackDriver.ListResources: returning cached advertisement")
230                 return rspec 
231     
232         #panos: passing user-defined options
233         #print "manager options = ",options
234         aggregate = OSAggregate(self)
235         rspec =  aggregate.get_rspec(slice_xrn=slice_urn, version=rspec_version, 
236                                      options=options)
237     
238         # cache the result
239         if self.cache and not slice_hrn:
240             logger.debug("OpenStackDriver.ListResources: stores advertisement in cache")
241             self.cache.add(version_string, rspec)
242     
243         return rspec
244     
245     def sliver_status (self, slice_urn, slice_hrn):
246         # find out where this slice is currently running
247         slicename = hrn_to_pl_slicename(slice_hrn)
248         
249         slices = self.shell.GetSlices([slicename], ['slice_id', 'node_ids','person_ids','name','expires'])
250         if len(slices) == 0:        
251             raise SliverDoesNotExist("%s (used %s as slicename internally)" % (slice_hrn, slicename))
252         slice = slices[0]
253         
254         # report about the local nodes only
255         nodes = self.shell.GetNodes({'node_id':slice['node_ids'],'peer_id':None},
256                               ['node_id', 'hostname', 'site_id', 'boot_state', 'last_contact'])
257
258         if len(nodes) == 0:
259             raise SliverDoesNotExist("You have not allocated any slivers here") 
260
261         site_ids = [node['site_id'] for node in nodes]
262     
263         result = {}
264         top_level_status = 'unknown'
265         if nodes:
266             top_level_status = 'ready'
267         result['geni_urn'] = slice_urn
268         result['pl_login'] = slice['name']
269         result['pl_expires'] = datetime_to_string(utcparse(slice['expires']))
270         
271         resources = []
272         for node in nodes:
273             res = {}
274             res['pl_hostname'] = node['hostname']
275             res['pl_boot_state'] = node['boot_state']
276             res['pl_last_contact'] = node['last_contact']
277             if node['last_contact'] is not None:
278                 
279                 res['pl_last_contact'] = datetime_to_string(utcparse(node['last_contact']))
280             sliver_id = urn_to_sliver_id(slice_urn, slice['slice_id'], node['node_id']) 
281             res['geni_urn'] = sliver_id
282             if node['boot_state'] == 'boot':
283                 res['geni_status'] = 'ready'
284             else:
285                 res['geni_status'] = 'failed'
286                 top_level_status = 'failed' 
287                 
288             res['geni_error'] = ''
289     
290             resources.append(res)
291             
292         result['geni_status'] = top_level_status
293         result['geni_resources'] = resources
294         return result
295
296     def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
297
298         aggregate = OSAggregate(self)
299         slicename = get_leaf(slice_hrn)
300         
301         # parse rspec
302         rspec = RSpec(rspec_string)
303         requested_attributes = rspec.version.get_slice_attributes()
304         
305         # ensure slice record exists
306         slice = aggregate.verify_slice(slicename, users, options=options)
307         # ensure person records exists
308         persons = aggregate.verify_slice_users(slicename, users, options=options)
309         # add/remove slice from nodes
310         slices.verify_instances(slicename, rspec)    
311    
312         return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
313
314     def delete_sliver (self, slice_urn, slice_hrn, creds, options):
315         name = OSXrn(xrn=slice_urn).name
316         slice = self.shell.project_get(name)
317         if not slice:
318             return 1
319         
320         self.shell.DeleteSliceFromNodes(slicename, slice['node_ids'])
321         instances = self.shell.db.instance_get_all_by_project(name)
322         for instance in instances:
323             self.shell.db.instance_destroy(instance.instance_id)
324         return 1
325     
326     def renew_sliver (self, slice_urn, slice_hrn, creds, expiration_time, options):
327         return True
328
329     def start_slice (self, slice_urn, slice_hrn, creds):
330         return 1
331
332     def stop_slice (self, slice_urn, slice_hrn, creds):
333         name = OSXrn(xrn=slice_urn).name
334         slice = self.shell.get_project(name)
335         instances = self.shell.db.instance_get_all_by_project(name)
336         for instance in instances:
337             self.shell.db.instance_stop(instance.instance_id)
338         return 1
339     
340     def reset_slice (self, slice_urn, slice_hrn, creds):
341         raise SfaNotImplemented ("reset_slice not available at this interface")
342     
343     # xxx this code is quite old and has not run for ages
344     # it is obviously totally broken and needs a rewrite
345     def get_ticket (self, slice_urn, slice_hrn, creds, rspec_string, options):
346         raise SfaNotImplemented,"OpenStackDriver.get_ticket needs a rewrite"
347 # please keep this code for future reference
348 #        slices = PlSlices(self)
349 #        peer = slices.get_peer(slice_hrn)
350 #        sfa_peer = slices.get_sfa_peer(slice_hrn)
351 #    
352 #        # get the slice record
353 #        credential = api.getCredential()
354 #        interface = api.registries[api.hrn]
355 #        registry = api.server_proxy(interface, credential)
356 #        records = registry.Resolve(xrn, credential)
357 #    
358 #        # make sure we get a local slice record
359 #        record = None
360 #        for tmp_record in records:
361 #            if tmp_record['type'] == 'slice' and \
362 #               not tmp_record['peer_authority']:
363 #    #Error (E0602, GetTicket): Undefined variable 'SliceRecord'
364 #                slice_record = SliceRecord(dict=tmp_record)
365 #        if not record:
366 #            raise RecordNotFound(slice_hrn)
367 #        
368 #        # similar to CreateSliver, we must verify that the required records exist
369 #        # at this aggregate before we can issue a ticket
370 #        # parse rspec
371 #        rspec = RSpec(rspec_string)
372 #        requested_attributes = rspec.version.get_slice_attributes()
373 #    
374 #        # ensure site record exists
375 #        site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer)
376 #        # ensure slice record exists
377 #        slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer)
378 #        # ensure person records exists
379 #    # xxx users is undefined in this context
380 #        persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer)
381 #        # ensure slice attributes exists
382 #        slices.verify_slice_attributes(slice, requested_attributes)
383 #        
384 #        # get sliver info
385 #        slivers = slices.get_slivers(slice_hrn)
386 #    
387 #        if not slivers:
388 #            raise SliverDoesNotExist(slice_hrn)
389 #    
390 #        # get initscripts
391 #        initscripts = []
392 #        data = {
393 #            'timestamp': int(time.time()),
394 #            'initscripts': initscripts,
395 #            'slivers': slivers
396 #        }
397 #    
398 #        # create the ticket
399 #        object_gid = record.get_gid_object()
400 #        new_ticket = SfaTicket(subject = object_gid.get_subject())
401 #        new_ticket.set_gid_caller(api.auth.client_gid)
402 #        new_ticket.set_gid_object(object_gid)
403 #        new_ticket.set_issuer(key=api.key, subject=self.hrn)
404 #        new_ticket.set_pubkey(object_gid.get_pubkey())
405 #        new_ticket.set_attributes(data)
406 #        new_ticket.set_rspec(rspec)
407 #        #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
408 #        new_ticket.encode()
409 #        new_ticket.sign()
410 #    
411 #        return new_ticket.save_to_string(save_parents=True)