Setting tag sfa-2.0-10
[sfa.git] / sfa / openstack / openstack_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 # one would think the driver should not need to mess with the SFA db, but..
12 from sfa.storage.table import SfaTable
13 # used to be used in get_ticket
14 #from sfa.trust.sfaticket import SfaTicket
15 from sfa.rspecs.version_manager import VersionManager
16 from sfa.rspecs.rspec import RSpec
17 # the driver interface, mostly provides default behaviours
18 from sfa.managers.driver import Driver
19 from sfa.openstack.openstack_shell import OpenstackShell
20 import sfa.plc.peers as peers
21 from sfa.plc.plaggregate import PlAggregate
22 from sfa.plc.plslices import PlSlices
23 from sfa.util.plxrn import slicename_to_hrn, hostname_to_hrn, hrn_to_pl_slicename, hrn_to_pl_login_base
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 OpenstackDriver (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 = OpenstackShell (config)
46         self.cache=None
47         if config.SFA_AGGREGATE_CACHING:
48             if OpenstackDriver.cache is None:
49                 OpenstackDriver.cache = Cache()
50             self.cache = OpenstackDriver.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.user_get(name)
125                 record['slices'] = [self.hrn + "." + proj.name for \
126                                     proj in os_record.projects]
127                 record['roles'] = [role for role in os_record.roles]
128                 keys = self.shell.key_pair_get_all_by_user(name)
129                 record['keys'] = [key.public_key for key in keys]     
130             elif record['type'] == 'slice': 
131                 os_record = self.shell.project_get(name)
132                 record['description'] = os_record.description
133                 record['PI'] = self.hrn + "." + os_record.project_manager
134                 record['geni_creator'] = record['PI'] 
135                 record['researcher'] = [self.hrn + "." + user.name for \
136                                          user in os_record.members]
137             else:
138                 continue
139             record['geni_urn'] = hrn_to_urn(record['hrn'], record['type'])
140             record['geni_certificate'] = record['gid'] 
141             record['name'] = os_record.name
142             if os_record.created_at is not None:    
143                 record['date_created'] = datetime_to_string(utcparse(os_record.created_at))
144             if os_record.updated_at is not None:
145                 record['last_updated'] = datetime_to_string(utcparse(os_record.updated_at))
146  
147         return records
148
149
150     ####################
151     # plcapi works by changes, compute what needs to be added/deleted
152     def update_relation (self, subject_type, target_type, subject_id, target_ids):
153         # hard-wire the code for slice/user for now, could be smarter if needed
154         if subject_type =='slice' and target_type == 'user':
155             subject=self.shell.project_get(subject_id)[0]
156             current_target_ids = [user.name for user in subject.members]
157             add_target_ids = list ( set (target_ids).difference(current_target_ids))
158             del_target_ids = list ( set (current_target_ids).difference(target_ids))
159             logger.debug ("subject_id = %s (type=%s)"%(subject_id,type(subject_id)))
160             for target_id in add_target_ids:
161                 self.shell.project_add_member(target_id,subject_id)
162                 logger.debug ("add_target_id = %s (type=%s)"%(target_id,type(target_id)))
163             for target_id in del_target_ids:
164                 logger.debug ("del_target_id = %s (type=%s)"%(target_id,type(target_id)))
165                 self.shell.project_remove_member(target_id, subject_id)
166         else:
167             logger.info('unexpected relation to maintain, %s -> %s'%(subject_type,target_type))
168
169         
170     ########################################
171     ########## aggregate oriented
172     ########################################
173
174     def testbed_name (self): return "openstack"
175
176     # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
177     def aggregate_version (self):
178         version_manager = VersionManager()
179         ad_rspec_versions = []
180         request_rspec_versions = []
181         for rspec_version in version_manager.versions:
182             if rspec_version.content_type in ['*', 'ad']:
183                 ad_rspec_versions.append(rspec_version.to_dict())
184             if rspec_version.content_type in ['*', 'request']:
185                 request_rspec_versions.append(rspec_version.to_dict()) 
186         return {
187             'testbed':self.testbed_name(),
188             'geni_request_rspec_versions': request_rspec_versions,
189             'geni_ad_rspec_versions': ad_rspec_versions,
190             }
191
192     def list_slices (self, creds, options):
193         # look in cache first
194         if self.cache:
195             slices = self.cache.get('slices')
196             if slices:
197                 logger.debug("PlDriver.list_slices returns from cache")
198                 return slices
199     
200         # get data from db 
201         slices = self.shell.GetSlices({'peer_id': None}, ['name'])
202         slice_hrns = [slicename_to_hrn(self.hrn, slice['name']) for slice in slices]
203         slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
204     
205         # cache the result
206         if self.cache:
207             logger.debug ("PlDriver.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("PlDriver.ListResources: returning cached advertisement")
230                 return rspec 
231     
232         #panos: passing user-defined options
233         #print "manager options = ",options
234         aggregate = PlAggregate(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("PlDriver.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 = PlAggregate(self)
299         slices = PlSlices(self)
300         peer = slices.get_peer(slice_hrn)
301         sfa_peer = slices.get_sfa_peer(slice_hrn)
302         slice_record=None    
303         if users:
304             slice_record = users[0].get('slice_record', {})
305     
306         # parse rspec
307         rspec = RSpec(rspec_string)
308         requested_attributes = rspec.version.get_slice_attributes()
309         
310         # ensure site record exists
311         site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer, options=options)
312         # ensure slice record exists
313         slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer, options=options)
314         # ensure person records exists
315         persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer, options=options)
316         # ensure slice attributes exists
317         slices.verify_slice_attributes(slice, requested_attributes, options=options)
318         
319         # add/remove slice from nodes
320         requested_slivers = [node.get('component_name') for node in rspec.version.get_nodes_with_slivers()]
321         nodes = slices.verify_slice_nodes(slice, requested_slivers, peer) 
322    
323         # add/remove links links 
324         slices.verify_slice_links(slice, rspec.version.get_link_requests(), nodes)
325     
326         # handle MyPLC peer association.
327         # only used by plc and ple.
328         slices.handle_peer(site, slice, persons, peer)
329         
330         return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
331
332     def delete_sliver (self, slice_urn, slice_hrn, creds, options):
333         slicename = hrn_to_pl_slicename(slice_hrn)
334         slices = self.shell.GetSlices({'name': slicename})
335         if not slices:
336             return 1
337         slice = slices[0]
338     
339         # determine if this is a peer slice
340         # xxx I wonder if this would not need to use PlSlices.get_peer instead 
341         # in which case plc.peers could be deprecated as this here
342         # is the only/last call to this last method in plc.peers
343         peer = peers.get_peer(self, slice_hrn)
344         try:
345             if peer:
346                 self.shell.UnBindObjectFromPeer('slice', slice['slice_id'], peer)
347             self.shell.DeleteSliceFromNodes(slicename, slice['node_ids'])
348         finally:
349             if peer:
350                 self.shell.BindObjectToPeer('slice', slice['slice_id'], peer, slice['peer_slice_id'])
351         return 1
352     
353     def renew_sliver (self, slice_urn, slice_hrn, creds, expiration_time, options):
354         slicename = hrn_to_pl_slicename(slice_hrn)
355         slices = self.shell.GetSlices({'name': slicename}, ['slice_id'])
356         if not slices:
357             raise RecordNotFound(slice_hrn)
358         slice = slices[0]
359         requested_time = utcparse(expiration_time)
360         record = {'expires': int(datetime_to_epoch(requested_time))}
361         try:
362             self.shell.UpdateSlice(slice['slice_id'], record)
363             return True
364         except:
365             return False
366
367     # remove the 'enabled' tag 
368     def start_slice (self, slice_urn, slice_hrn, creds):
369         slicename = hrn_to_pl_slicename(slice_hrn)
370         slices = self.shell.GetSlices({'name': slicename}, ['slice_id'])
371         if not slices:
372             raise RecordNotFound(slice_hrn)
373         slice_id = slices[0]['slice_id']
374         slice_tags = self.shell.GetSliceTags({'slice_id': slice_id, 'tagname': 'enabled'}, ['slice_tag_id'])
375         # just remove the tag if it exists
376         if slice_tags:
377             self.shell.DeleteSliceTag(slice_tags[0]['slice_tag_id'])
378         return 1
379
380     # set the 'enabled' tag to 0
381     def stop_slice (self, slice_urn, slice_hrn, creds):
382         slicename = hrn_to_pl_slicename(slice_hrn)
383         slices = self.shell.GetSlices({'name': slicename}, ['slice_id'])
384         if not slices:
385             raise RecordNotFound(slice_hrn)
386         slice_id = slices[0]['slice_id']
387         slice_tags = self.shell.GetSliceTags({'slice_id': slice_id, 'tagname': 'enabled'})
388         if not slice_tags:
389             self.shell.AddSliceTag(slice_id, 'enabled', '0')
390         elif slice_tags[0]['value'] != "0":
391             tag_id = slice_tags[0]['slice_tag_id']
392             self.shell.UpdateSliceTag(tag_id, '0')
393         return 1
394     
395     def reset_slice (self, slice_urn, slice_hrn, creds):
396         raise SfaNotImplemented ("reset_slice not available at this interface")
397     
398     # xxx this code is quite old and has not run for ages
399     # it is obviously totally broken and needs a rewrite
400     def get_ticket (self, slice_urn, slice_hrn, creds, rspec_string, options):
401         raise SfaNotImplemented,"PlDriver.get_ticket needs a rewrite"
402 # please keep this code for future reference
403 #        slices = PlSlices(self)
404 #        peer = slices.get_peer(slice_hrn)
405 #        sfa_peer = slices.get_sfa_peer(slice_hrn)
406 #    
407 #        # get the slice record
408 #        credential = api.getCredential()
409 #        interface = api.registries[api.hrn]
410 #        registry = api.server_proxy(interface, credential)
411 #        records = registry.Resolve(xrn, credential)
412 #    
413 #        # make sure we get a local slice record
414 #        record = None
415 #        for tmp_record in records:
416 #            if tmp_record['type'] == 'slice' and \
417 #               not tmp_record['peer_authority']:
418 #    #Error (E0602, GetTicket): Undefined variable 'SliceRecord'
419 #                slice_record = SliceRecord(dict=tmp_record)
420 #        if not record:
421 #            raise RecordNotFound(slice_hrn)
422 #        
423 #        # similar to CreateSliver, we must verify that the required records exist
424 #        # at this aggregate before we can issue a ticket
425 #        # parse rspec
426 #        rspec = RSpec(rspec_string)
427 #        requested_attributes = rspec.version.get_slice_attributes()
428 #    
429 #        # ensure site record exists
430 #        site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer)
431 #        # ensure slice record exists
432 #        slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer)
433 #        # ensure person records exists
434 #    # xxx users is undefined in this context
435 #        persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer)
436 #        # ensure slice attributes exists
437 #        slices.verify_slice_attributes(slice, requested_attributes)
438 #        
439 #        # get sliver info
440 #        slivers = slices.get_slivers(slice_hrn)
441 #    
442 #        if not slivers:
443 #            raise SliverDoesNotExist(slice_hrn)
444 #    
445 #        # get initscripts
446 #        initscripts = []
447 #        data = {
448 #            'timestamp': int(time.time()),
449 #            'initscripts': initscripts,
450 #            'slivers': slivers
451 #        }
452 #    
453 #        # create the ticket
454 #        object_gid = record.get_gid_object()
455 #        new_ticket = SfaTicket(subject = object_gid.get_subject())
456 #        new_ticket.set_gid_caller(api.auth.client_gid)
457 #        new_ticket.set_gid_object(object_gid)
458 #        new_ticket.set_issuer(key=api.key, subject=self.hrn)
459 #        new_ticket.set_pubkey(object_gid.get_pubkey())
460 #        new_ticket.set_attributes(data)
461 #        new_ticket.set_rspec(rspec)
462 #        #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
463 #        new_ticket.encode()
464 #        new_ticket.sign()
465 #    
466 #        return new_ticket.save_to_string(save_parents=True)