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 project_name = Xrn(slice_urn).get_leaf()
247 project = self.shell.auth_manager.get_project(project_name)
248 instances = self.shell.db.instance_get_all_by_project(project_name)
249 if len(instances) == 0:
250 raise SliverDoesNotExist("You have not allocated any slivers here")
253 top_level_status = 'unknown'
255 top_level_status = 'ready'
256 result['geni_urn'] = slice_urn
257 result['plos_login'] = 'root'
258 result['plos_expires'] = None
261 for instance in instances:
263 # instances are accessed by ip, not hostname. We need to report the ip
264 # somewhere so users know where to ssh to.
265 res['plos_hostname'] = instance.hostname
266 res['plos_created_at'] = datetime_to_string(utcparse(instance.created_at))
267 res['plos_boot_state'] = instance.vm_state
268 res['plos_sliver_type'] = instance.instance_type.name
269 sliver_id = Xrn(slice_urn).get_sliver_id(instance.project_id, \
270 instance.hostname, instance.id)
271 res['geni_urn'] = sliver_id
273 if instance.vm_state == 'running':
274 res['boot_state'] = 'ready';
276 res['boot_state'] = 'unknown'
277 resources.append(res)
279 result['geni_status'] = top_level_status
280 result['geni_resources'] = resources
283 def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
285 aggregate = OSAggregate(self)
286 slicename = get_leaf(slice_hrn)
289 rspec = RSpec(rspec_string)
290 requested_attributes = rspec.version.get_slice_attributes()
293 pubkeys.extend(user['keys'])
294 # assume that there is a key whos nane matches the caller's username.
295 project_key = Xrn(users[0]['urn']).get_leaf()
298 # ensure slice record exists
299 aggregate.create_project(slicename, users, options=options)
300 # ensure person records exists
301 aggregate.create_project_users(slicename, users, options=options)
302 # add/remove slice from nodes
303 aggregate.run_instances(slicename, rspec, project_key, pubkeys)
305 return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
307 def delete_sliver (self, slice_urn, slice_hrn, creds, options):
308 name = OSXrn(xrn=slice_urn).name
309 slice = self.shell.project_get(name)
312 instances = self.shell.db.instance_get_all_by_project(name)
313 for instance in instances:
314 self.shell.db.instance_destroy(instance.instance_id)
317 def renew_sliver (self, slice_urn, slice_hrn, creds, expiration_time, options):
320 def start_slice (self, slice_urn, slice_hrn, creds):
323 def stop_slice (self, slice_urn, slice_hrn, creds):
324 name = OSXrn(xrn=slice_urn).name
325 slice = self.shell.get_project(name)
326 instances = self.shell.db.instance_get_all_by_project(name)
327 for instance in instances:
328 self.shell.db.instance_stop(instance.instance_id)
331 def reset_slice (self, slice_urn, slice_hrn, creds):
332 raise SfaNotImplemented ("reset_slice not available at this interface")
334 # xxx this code is quite old and has not run for ages
335 # it is obviously totally broken and needs a rewrite
336 def get_ticket (self, slice_urn, slice_hrn, creds, rspec_string, options):
337 raise SfaNotImplemented,"OpenStackDriver.get_ticket needs a rewrite"
338 # please keep this code for future reference
339 # slices = PlSlices(self)
340 # peer = slices.get_peer(slice_hrn)
341 # sfa_peer = slices.get_sfa_peer(slice_hrn)
343 # # get the slice record
344 # credential = api.getCredential()
345 # interface = api.registries[api.hrn]
346 # registry = api.server_proxy(interface, credential)
347 # records = registry.Resolve(xrn, credential)
349 # # make sure we get a local slice record
351 # for tmp_record in records:
352 # if tmp_record['type'] == 'slice' and \
353 # not tmp_record['peer_authority']:
354 # #Error (E0602, GetTicket): Undefined variable 'SliceRecord'
355 # slice_record = SliceRecord(dict=tmp_record)
357 # raise RecordNotFound(slice_hrn)
359 # # similar to CreateSliver, we must verify that the required records exist
360 # # at this aggregate before we can issue a ticket
362 # rspec = RSpec(rspec_string)
363 # requested_attributes = rspec.version.get_slice_attributes()
365 # # ensure site record exists
366 # site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer)
367 # # ensure slice record exists
368 # slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer)
369 # # ensure person records exists
370 # # xxx users is undefined in this context
371 # persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer)
372 # # ensure slice attributes exists
373 # slices.verify_slice_attributes(slice, requested_attributes)
376 # slivers = slices.get_slivers(slice_hrn)
379 # raise SliverDoesNotExist(slice_hrn)
384 # 'timestamp': int(time.time()),
385 # 'initscripts': initscripts,
389 # # create the ticket
390 # object_gid = record.get_gid_object()
391 # new_ticket = SfaTicket(subject = object_gid.get_subject())
392 # new_ticket.set_gid_caller(api.auth.client_gid)
393 # new_ticket.set_gid_object(object_gid)
394 # new_ticket.set_issuer(key=api.key, subject=self.hrn)
395 # new_ticket.set_pubkey(object_gid.get_pubkey())
396 # new_ticket.set_attributes(data)
397 # new_ticket.set_rspec(rspec)
398 # #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
399 # new_ticket.encode()
402 # return new_ticket.save_to_string(save_parents=True)