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
26 def list_to_dict(recs, key):
28 convert a list of dictionaries into a dictionary keyed on the
29 specified dictionary key
31 return dict ( [ (rec[key],rec) for rec in recs ] )
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
38 class OpenstackDriver (Driver):
40 # the cache instance is a class member so it survives across incoming requests
43 def __init__ (self, config):
44 Driver.__init__ (self, config)
45 self.shell = OpenstackShell (config)
47 if config.SFA_AGGREGATE_CACHING:
48 if OpenstackDriver.cache is None:
49 OpenstackDriver.cache = Cache()
50 self.cache = OpenstackDriver.cache
52 ########################################
53 ########## registry oriented
54 ########################################
56 ########## disabled users
57 def is_enabled (self, record):
58 # all records are enabled
61 def augment_records_with_testbed_info (self, sfa_records):
62 return self.fill_record_info (sfa_records)
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)
70 acceptable_fields=['url', 'instantiation', 'name', 'description']
71 # add slice description, name, researchers, PI
75 # add person roles, projects and keys
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']
85 # new_key implemented for users only
86 if new_key and type not in [ 'user' ]:
87 raise UnknownSfaType(type)
90 # can update description, researchers and PI
93 # can update slices, keys and roles
99 def remove (self, sfa_record):
100 type=sfa_record['type']
101 name = Xrn(sfa_record['hrn']).get_leaf()
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)
112 def fill_record_info(self, records):
114 Given a (list of) SFA record, fill in the PLC specific
115 and SFA specific fields in the record.
117 if not isinstance(records, list):
120 for record in records:
121 name = Xrn(record['hrn']).get_leaf()
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]
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("PlDriver.list_slices returns from cache")
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]
207 logger.debug ("PlDriver.list_slices stores value in cache")
208 self.cache.add('slices', slice_urns)
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)
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)
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')
225 # look in cache first
226 if cached_requested and self.cache and not slice_hrn:
227 rspec = self.cache.get(version_string)
229 logger.debug("PlDriver.ListResources: returning cached advertisement")
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,
239 if self.cache and not slice_hrn:
240 logger.debug("PlDriver.ListResources: stores advertisement in cache")
241 self.cache.add(version_string, rspec)
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)
249 slices = self.shell.GetSlices([slicename], ['slice_id', 'node_ids','person_ids','name','expires'])
251 raise SliverDoesNotExist("%s (used %s as slicename internally)" % (slice_hrn, slicename))
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'])
259 raise SliverDoesNotExist("You have not allocated any slivers here")
261 site_ids = [node['site_id'] for node in nodes]
264 top_level_status = 'unknown'
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']))
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:
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'
285 res['geni_status'] = 'failed'
286 top_level_status = 'failed'
288 res['geni_error'] = ''
290 resources.append(res)
292 result['geni_status'] = top_level_status
293 result['geni_resources'] = resources
296 def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
298 aggregate = PlAggregate(self)
299 slices = PlSlices(self)
300 peer = slices.get_peer(slice_hrn)
301 sfa_peer = slices.get_sfa_peer(slice_hrn)
304 slice_record = users[0].get('slice_record', {})
307 rspec = RSpec(rspec_string)
308 requested_attributes = rspec.version.get_slice_attributes()
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)
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)
323 # add/remove links links
324 slices.verify_slice_links(slice, rspec.version.get_link_requests(), nodes)
326 # handle MyPLC peer association.
327 # only used by plc and ple.
328 slices.handle_peer(site, slice, persons, peer)
330 return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
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})
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)
346 self.shell.UnBindObjectFromPeer('slice', slice['slice_id'], peer)
347 self.shell.DeleteSliceFromNodes(slicename, slice['node_ids'])
350 self.shell.BindObjectToPeer('slice', slice['slice_id'], peer, slice['peer_slice_id'])
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'])
357 raise RecordNotFound(slice_hrn)
359 requested_time = utcparse(expiration_time)
360 record = {'expires': int(datetime_to_epoch(requested_time))}
362 self.shell.UpdateSlice(slice['slice_id'], record)
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'])
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
377 self.shell.DeleteSliceTag(slice_tags[0]['slice_tag_id'])
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'])
385 raise RecordNotFound(slice_hrn)
386 slice_id = slices[0]['slice_id']
387 slice_tags = self.shell.GetSliceTags({'slice_id': slice_id, 'tagname': 'enabled'})
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')
395 def reset_slice (self, slice_urn, slice_hrn, creds):
396 raise SfaNotImplemented ("reset_slice not available at this interface")
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)
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)
413 # # make sure we get a local slice record
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)
421 # raise RecordNotFound(slice_hrn)
423 # # similar to CreateSliver, we must verify that the required records exist
424 # # at this aggregate before we can issue a ticket
426 # rspec = RSpec(rspec_string)
427 # requested_attributes = rspec.version.get_slice_attributes()
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)
440 # slivers = slices.get_slivers(slice_hrn)
443 # raise SliverDoesNotExist(slice_hrn)
448 # 'timestamp': int(time.time()),
449 # 'initscripts': initscripts,
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()
466 # return new_ticket.save_to_string(save_parents=True)