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.euca_shell import EucaShell
19 from sfa.openstack.osaggregate import OSAggregate
20 from sfa.plc.plslices import PlSlices
21 from sfa.util.osxrn import OSXrn
24 def list_to_dict(recs, key):
26 convert a list of dictionaries into a dictionary keyed on the
27 specified dictionary key
29 return dict ( [ (rec[key],rec) for rec in recs ] )
32 # PlShell is just an xmlrpc serverproxy where methods
33 # can be sent as-is; it takes care of authentication
34 # from the global config
36 class NovaDriver (Driver):
38 # the cache instance is a class member so it survives across incoming requests
41 def __init__ (self, config):
42 Driver.__init__ (self, config)
43 self.shell = NovaShell (config)
44 self.euca_shell = EucaShell(config)
46 if config.SFA_AGGREGATE_CACHING:
47 if NovaDriver.cache is None:
48 NovaDriver.cache = Cache()
49 self.cache = NovaDriver.cache
51 ########################################
52 ########## registry oriented
53 ########################################
55 ########## disabled users
56 def is_enabled (self, record):
57 # all records are enabled
60 def augment_records_with_testbed_info (self, sfa_records):
61 return self.fill_record_info (sfa_records)
64 def register (self, sfa_record, hrn, pub_key):
65 type = sfa_record['type']
66 pl_record = self.sfa_fields_to_pl_fields(type, hrn, sfa_record)
69 acceptable_fields=['url', 'instantiation', 'name', 'description']
70 # add slice description, name, researchers, PI
74 # add person roles, projects and keys
79 # xxx actually old_sfa_record comes filled with plc stuff as well in the original code
80 def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
81 pointer = old_sfa_record['pointer']
82 type = old_sfa_record['type']
84 # new_key implemented for users only
85 if new_key and type not in [ 'user' ]:
86 raise UnknownSfaType(type)
89 # can update description, researchers and PI
92 # can update slices, keys and roles
98 def remove (self, sfa_record):
99 type=sfa_record['type']
100 name = Xrn(sfa_record['hrn']).get_leaf()
102 if self.shell.user_get(name):
103 self.shell.user_delete(name)
104 elif type == 'slice':
105 if self.shell.project_get(name):
106 self.shell.project_delete(name)
111 def fill_record_info(self, records):
113 Given a (list of) SFA record, fill in the PLC specific
114 and SFA specific fields in the record.
116 if not isinstance(records, list):
119 for record in records:
120 name = Xrn(record['hrn']).get_leaf()
122 if record['type'] == 'user':
123 os_record = self.shell.auth_manager.get_user(name)
124 projects = self.shell.db.project_get_by_user(name)
125 record['slices'] = [self.hrn + "." + proj.name for \
127 record['roles'] = self.shell.db.user_get_roles(name)
128 keys = self.shell.db.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.auth_manager.get_project(name)
132 record['description'] = os_record.description
133 record['PI'] = [self.hrn + "." + os_record.project_manager.name]
134 record['geni_creator'] = record['PI']
135 record['researcher'] = [self.hrn + "." + user for \
136 user in os_record.member_ids]
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))
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)
167 logger.info('unexpected relation to maintain, %s -> %s'%(subject_type,target_type))
170 ########################################
171 ########## aggregate oriented
172 ########################################
174 def testbed_name (self): return "openstack"
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())
187 'testbed':self.testbed_name(),
188 'geni_request_rspec_versions': request_rspec_versions,
189 'geni_ad_rspec_versions': ad_rspec_versions,
192 def list_slices (self, creds, options):
193 # look in cache first
195 slices = self.cache.get('slices')
197 logger.debug("OpenStackDriver.list_slices returns from cache")
201 projs = self.shell.auth_manager.get_projects()
202 slice_urns = [OSXrn(proj.name, 'slice').urn for proj in projs]
206 logger.debug ("OpenStackDriver.list_slices stores value in cache")
207 self.cache.add('slices', slice_urns)
211 # first 2 args are None in case of resource discovery
212 def list_resources (self, slice_urn, slice_hrn, creds, options):
213 cached_requested = options.get('cached', True)
215 version_manager = VersionManager()
216 # get the rspec's return format from options
217 rspec_version = version_manager.get_version(options.get('geni_rspec_version'))
218 version_string = "rspec_%s" % (rspec_version)
220 #panos adding the info option to the caching key (can be improved)
221 if options.get('info'):
222 version_string = version_string + "_"+options.get('info', 'default')
224 # look in cache first
225 if cached_requested and self.cache and not slice_hrn:
226 rspec = self.cache.get(version_string)
228 logger.debug("OpenStackDriver.ListResources: returning cached advertisement")
231 #panos: passing user-defined options
232 #print "manager options = ",options
233 aggregate = OSAggregate(self)
234 rspec = aggregate.get_rspec(slice_xrn=slice_urn, version=rspec_version,
238 if self.cache and not slice_hrn:
239 logger.debug("OpenStackDriver.ListResources: stores advertisement in cache")
240 self.cache.add(version_string, rspec)
244 def sliver_status (self, slice_urn, slice_hrn):
245 # find out where this slice is currently running
246 slicename = hrn_to_pl_slicename(slice_hrn)
248 slices = self.shell.GetSlices([slicename], ['slice_id', 'node_ids','person_ids','name','expires'])
250 raise SliverDoesNotExist("%s (used %s as slicename internally)" % (slice_hrn, slicename))
253 # report about the local nodes only
254 nodes = self.shell.GetNodes({'node_id':slice['node_ids'],'peer_id':None},
255 ['node_id', 'hostname', 'site_id', 'boot_state', 'last_contact'])
258 raise SliverDoesNotExist("You have not allocated any slivers here")
260 site_ids = [node['site_id'] for node in nodes]
263 top_level_status = 'unknown'
265 top_level_status = 'ready'
266 result['geni_urn'] = slice_urn
267 result['pl_login'] = slice['name']
268 result['pl_expires'] = datetime_to_string(utcparse(slice['expires']))
273 res['pl_hostname'] = node['hostname']
274 res['pl_boot_state'] = node['boot_state']
275 res['pl_last_contact'] = node['last_contact']
276 if node['last_contact'] is not None:
278 res['pl_last_contact'] = datetime_to_string(utcparse(node['last_contact']))
279 sliver_id = urn_to_sliver_id(slice_urn, slice['slice_id'], node['node_id'])
280 res['geni_urn'] = sliver_id
281 if node['boot_state'] == 'boot':
282 res['geni_status'] = 'ready'
284 res['geni_status'] = 'failed'
285 top_level_status = 'failed'
287 res['geni_error'] = ''
289 resources.append(res)
291 result['geni_status'] = top_level_status
292 result['geni_resources'] = resources
295 def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
297 aggregate = OSAggregate(self)
298 slicename = get_leaf(slice_hrn)
301 rspec = RSpec(rspec_string)
302 requested_attributes = rspec.version.get_slice_attributes()
305 pubkeys.extend(user['keys'])
306 # assume that there is a key whos nane matches the caller's username.
307 project_key = Xrn(users[0]['urn']).get_leaf()
310 # ensure slice record exists
311 aggregate.create_project(slicename, users, options=options)
312 # ensure person records exists
313 aggregate.create_project_users(slicename, users, options=options)
314 # add/remove slice from nodes
315 aggregate.run_instances(slicename, rspec, project_key, pubkeys)
317 return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
319 def delete_sliver (self, slice_urn, slice_hrn, creds, options):
320 name = OSXrn(xrn=slice_urn).name
321 slice = self.shell.project_get(name)
324 instances = self.shell.db.instance_get_all_by_project(name)
325 for instance in instances:
326 self.shell.db.instance_destroy(instance.instance_id)
329 def renew_sliver (self, slice_urn, slice_hrn, creds, expiration_time, options):
332 def start_slice (self, slice_urn, slice_hrn, creds):
335 def stop_slice (self, slice_urn, slice_hrn, creds):
336 name = OSXrn(xrn=slice_urn).name
337 slice = self.shell.get_project(name)
338 instances = self.shell.db.instance_get_all_by_project(name)
339 for instance in instances:
340 self.shell.db.instance_stop(instance.instance_id)
343 def reset_slice (self, slice_urn, slice_hrn, creds):
344 raise SfaNotImplemented ("reset_slice not available at this interface")
346 # xxx this code is quite old and has not run for ages
347 # it is obviously totally broken and needs a rewrite
348 def get_ticket (self, slice_urn, slice_hrn, creds, rspec_string, options):
349 raise SfaNotImplemented,"OpenStackDriver.get_ticket needs a rewrite"
350 # please keep this code for future reference
351 # slices = PlSlices(self)
352 # peer = slices.get_peer(slice_hrn)
353 # sfa_peer = slices.get_sfa_peer(slice_hrn)
355 # # get the slice record
356 # credential = api.getCredential()
357 # interface = api.registries[api.hrn]
358 # registry = api.server_proxy(interface, credential)
359 # records = registry.Resolve(xrn, credential)
361 # # make sure we get a local slice record
363 # for tmp_record in records:
364 # if tmp_record['type'] == 'slice' and \
365 # not tmp_record['peer_authority']:
366 # #Error (E0602, GetTicket): Undefined variable 'SliceRecord'
367 # slice_record = SliceRecord(dict=tmp_record)
369 # raise RecordNotFound(slice_hrn)
371 # # similar to CreateSliver, we must verify that the required records exist
372 # # at this aggregate before we can issue a ticket
374 # rspec = RSpec(rspec_string)
375 # requested_attributes = rspec.version.get_slice_attributes()
377 # # ensure site record exists
378 # site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer)
379 # # ensure slice record exists
380 # slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer)
381 # # ensure person records exists
382 # # xxx users is undefined in this context
383 # persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer)
384 # # ensure slice attributes exists
385 # slices.verify_slice_attributes(slice, requested_attributes)
388 # slivers = slices.get_slivers(slice_hrn)
391 # raise SliverDoesNotExist(slice_hrn)
396 # 'timestamp': int(time.time()),
397 # 'initscripts': initscripts,
401 # # create the ticket
402 # object_gid = record.get_gid_object()
403 # new_ticket = SfaTicket(subject = object_gid.get_subject())
404 # new_ticket.set_gid_caller(api.auth.client_gid)
405 # new_ticket.set_gid_object(object_gid)
406 # new_ticket.set_issuer(key=api.key, subject=self.hrn)
407 # new_ticket.set_pubkey(object_gid.get_pubkey())
408 # new_ticket.set_attributes(data)
409 # new_ticket.set_rspec(rspec)
410 # #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
411 # new_ticket.encode()
414 # return new_ticket.save_to_string(save_parents=True)