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
23 def list_to_dict(recs, key):
25 convert a list of dictionaries into a dictionary keyed on the
26 specified dictionary key
28 return dict ( [ (rec[key],rec) for rec in recs ] )
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
35 class NovaDriver (Driver):
37 # the cache instance is a class member so it survives across incoming requests
40 def __init__ (self, config):
41 Driver.__init__ (self, config)
42 self.shell = NovaShell (config)
44 if config.SFA_AGGREGATE_CACHING:
45 if NovaDriver.cache is None:
46 NovaDriver.cache = Cache()
47 self.cache = NovaDriver.cache
49 ########################################
50 ########## registry oriented
51 ########################################
53 ########## disabled users
54 def is_enabled (self, record):
55 # all records are enabled
58 def augment_records_with_testbed_info (self, sfa_records):
59 return self.fill_record_info (sfa_records)
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)
67 acceptable_fields=['url', 'instantiation', 'name', 'description']
68 # add slice description, name, researchers, PI
72 # add person roles, projects and keys
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']
82 # new_key implemented for users only
83 if new_key and type not in [ 'user' ]:
84 raise UnknownSfaType(type)
87 # can update description, researchers and PI
90 # can update slices, keys and roles
96 def remove (self, sfa_record):
97 type=sfa_record['type']
98 name = Xrn(sfa_record['hrn']).get_leaf()
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)
109 def fill_record_info(self, records):
111 Given a (list of) SFA record, fill in the PLC specific
112 and SFA specific fields in the record.
114 if not isinstance(records, list):
117 for record in records:
118 name = Xrn(record['hrn']).get_leaf()
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]
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))
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)
164 logger.info('unexpected relation to maintain, %s -> %s'%(subject_type,target_type))
167 ########################################
168 ########## aggregate oriented
169 ########################################
171 def testbed_name (self): return "openstack"
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())
184 'testbed':self.testbed_name(),
185 'geni_request_rspec_versions': request_rspec_versions,
186 'geni_ad_rspec_versions': ad_rspec_versions,
189 def list_slices (self, creds, options):
190 # look in cache first
192 slices = self.cache.get('slices')
194 logger.debug("OpenStackDriver.list_slices returns from cache")
198 projs = self.shell.auth_manager.get_projects()
199 slice_urns = [OSXrn(proj.name, 'slice').urn for proj in projs]
203 logger.debug ("OpenStackDriver.list_slices stores value in cache")
204 self.cache.add('slices', slice_urns)
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)
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)
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')
221 # look in cache first
222 if cached_requested and self.cache and not slice_hrn:
223 rspec = self.cache.get(version_string)
225 logger.debug("OpenStackDriver.ListResources: returning cached advertisement")
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,
235 if self.cache and not slice_hrn:
236 logger.debug("OpenStackDriver.ListResources: stores advertisement in cache")
237 self.cache.add(version_string, rspec)
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)
245 slices = self.shell.GetSlices([slicename], ['slice_id', 'node_ids','person_ids','name','expires'])
247 raise SliverDoesNotExist("%s (used %s as slicename internally)" % (slice_hrn, slicename))
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'])
255 raise SliverDoesNotExist("You have not allocated any slivers here")
257 site_ids = [node['site_id'] for node in nodes]
260 top_level_status = 'unknown'
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']))
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:
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'
281 res['geni_status'] = 'failed'
282 top_level_status = 'failed'
284 res['geni_error'] = ''
286 resources.append(res)
288 result['geni_status'] = top_level_status
289 result['geni_resources'] = resources
292 def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
294 aggregate = OSAggregate(self)
295 slicename = get_leaf(slice_hrn)
298 rspec = RSpec(rspec_string)
299 requested_attributes = rspec.version.get_slice_attributes()
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)
308 return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
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)
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)
322 def renew_sliver (self, slice_urn, slice_hrn, creds, expiration_time, options):
325 def start_slice (self, slice_urn, slice_hrn, creds):
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)
336 def reset_slice (self, slice_urn, slice_hrn, creds):
337 raise SfaNotImplemented ("reset_slice not available at this interface")
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)
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)
354 # # make sure we get a local slice record
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)
362 # raise RecordNotFound(slice_hrn)
364 # # similar to CreateSliver, we must verify that the required records exist
365 # # at this aggregate before we can issue a ticket
367 # rspec = RSpec(rspec_string)
368 # requested_attributes = rspec.version.get_slice_attributes()
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)
381 # slivers = slices.get_slivers(slice_hrn)
384 # raise SliverDoesNotExist(slice_hrn)
389 # 'timestamp': int(time.time()),
390 # 'initscripts': initscripts,
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()
407 # return new_ticket.save_to_string(save_parents=True)