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