2 Implements what a driver should provide for SFA to work.
4 from sfa.util.faults import SliverDoesNotExist, UnknownSfaType
5 from sfa.util.sfalogging import logger
6 from sfa.storage.alchemy import dbsession
7 from sfa.storage.model import RegRecord
9 from sfa.managers.driver import Driver
10 from sfa.rspecs.version_manager import VersionManager
11 from sfa.rspecs.rspec import RSpec
13 from sfa.util.xrn import Xrn, hrn_to_urn, get_authority
15 from sfa.iotlab.iotlabaggregate import IotlabAggregate, iotlab_xrn_to_hostname
16 from sfa.iotlab.iotlabslices import IotlabSlices
19 from sfa.iotlab.iotlabapi import IotlabTestbedAPI
22 class IotlabDriver(Driver):
23 """ Iotlab Driver class inherited from Driver generic class.
25 Contains methods compliant with the SFA standard and the testbed
26 infrastructure (calls to LDAP and OAR).
28 .. seealso::: Driver class
31 def __init__(self, config):
34 Sets the iotlab SFA config parameters,
35 instanciates the testbed api and the iotlab database.
37 :param config: iotlab SFA configuration object
38 :type config: Config object
41 Driver.__init__(self, config)
43 self.iotlab_api = IotlabTestbedAPI(config)
46 def augment_records_with_testbed_info(self, record_list):
49 Adds specific testbed info to the records.
51 :param record_list: list of sfa dictionaries records
52 :type record_list: list
53 :returns: list of records with extended information in each record
57 return self.fill_record_info(record_list)
59 def fill_record_info(self, record_list):
62 For each SFA record, fill in the iotlab specific and SFA specific
65 :param record_list: list of sfa dictionaries records
66 :type record_list: list
67 :returns: list of records with extended information in each record
70 .. warning:: Should not be modifying record_list directly because modi
71 fication are kept outside the method's scope. Howerver, there is no
72 other way to do it given the way it's called in registry manager.
76 logger.debug("IOTLABDRIVER \tfill_record_info records %s "
78 if not isinstance(record_list, list):
79 record_list = [record_list]
82 for record in record_list:
84 if str(record['type']) == 'node':
85 # look for node info using GetNodes
86 # the record is about one node only
87 filter_dict = {'hrn': [record['hrn']]}
88 node_info = self.iotlab_api.GetNodes(filter_dict)
89 # the node_info is about one node only, but it is formatted
91 record.update(node_info[0])
92 logger.debug("IOTLABDRIVER.PY \t \
93 fill_record_info NODE" % (record))
95 #If the record is a SFA slice record, then add information
96 #about the user of this slice. This kind of
97 #information is in the Iotlab's DB.
98 if str(record['type']) == 'slice':
99 if 'reg_researchers' in record and isinstance(record
102 record['reg_researchers'] = \
103 record['reg_researchers'][0].__dict__
105 {'PI': [record['reg_researchers']['hrn']],
106 'researcher': [record['reg_researchers']['hrn']],
107 'name': record['hrn'],
110 'person_ids': [record['reg_researchers']
112 # For client_helper.py compatibility
114 # For client_helper.py compatibility
116 # For client_helper.py compatibility
119 #Get iotlab slice record and oar job id if any.
120 recslice_list = self.iotlab_api.GetSlices(
121 slice_filter=str(record['hrn']),
122 slice_filter_type='slice_hrn')
124 logger.debug("IOTLABDRIVER \tfill_record_info \
125 TYPE SLICE RECUSER record['hrn'] %s record['oar_job_id']\
126 %s " % (record['hrn'], record['oar_job_id']))
127 del record['reg_researchers']
129 for rec in recslice_list:
130 logger.debug("IOTLABDRIVER\r\n \t \
131 fill_record_info oar_job_id %s "
132 % (rec['oar_job_id']))
134 record['node_ids'] = [self.iotlab_api.root_auth +
135 '.' + hostname for hostname
140 logger.debug("IOTLABDRIVER.PY \t fill_record_info SLICE \
141 recslice_list %s \r\n \t RECORD %s \r\n \
142 \r\n" % (recslice_list, record))
144 if str(record['type']) == 'user':
145 #The record is a SFA user record.
146 #Get the information about his slice from Iotlab's DB
147 #and add it to the user record.
148 recslice_list = self.iotlab_api.GetSlices(
149 slice_filter=record['record_id'],
150 slice_filter_type='record_id_user')
152 logger.debug("IOTLABDRIVER.PY \t fill_record_info \
153 TYPE USER recslice_list %s \r\n \t RECORD %s \r\n"
154 % (recslice_list, record))
155 #Append slice record in records list,
156 #therefore fetches user and slice info again(one more loop)
157 #Will update PIs and researcher for the slice
159 recuser = recslice_list[0]['reg_researchers']
160 logger.debug("IOTLABDRIVER.PY \t fill_record_info USER \
161 recuser %s \r\n \r\n" % (recuser))
163 recslice = recslice_list[0]
165 {'PI': [recuser['hrn']],
166 'researcher': [recuser['hrn']],
167 'name': record['hrn'],
170 'person_ids': [recuser['record_id']]})
172 for rec in recslice_list:
173 recslice['oar_job_id'].append(rec['oar_job_id'])
177 recslice.update({'type': 'slice',
178 'hrn': recslice_list[0]['hrn']})
180 #GetPersons takes [] as filters
181 user_iotlab = self.iotlab_api.GetPersons([record])
183 record.update(user_iotlab[0])
184 #For client_helper.py compatibility
189 record_list.append(recslice)
191 logger.debug("IOTLABDRIVER.PY \t \
192 fill_record_info ADDING SLICE\
193 INFO TO USER records %s" % (record_list))
195 except TypeError, error:
196 logger.log_exc("IOTLABDRIVER \t fill_record_info EXCEPTION %s"
201 def sliver_status(self, slice_urn, slice_hrn):
203 Receive a status request for slice named urn/hrn
204 urn:publicid:IDN+iotlab+nturro_slice hrn iotlab.nturro_slice
205 shall return a structure as described in
206 http://groups.geni.net/geni/wiki/GAPI_AM_API_V2#SliverStatus
207 NT : not sure if we should implement this or not, but used by sface.
209 :param slice_urn: slice urn
210 :type slice_urn: string
211 :param slice_hrn: slice hrn
212 :type slice_hrn: string
216 #First get the slice with the slice hrn
217 slice_list = self.iotlab_api.GetSlices(slice_filter=slice_hrn,
218 slice_filter_type='slice_hrn')
220 if len(slice_list) == 0:
221 raise SliverDoesNotExist("%s slice_hrn" % (slice_hrn))
223 #Used for fetching the user info witch comes along the slice info
224 one_slice = slice_list[0]
226 #Make a list of all the nodes hostnames in use for this slice
227 slice_nodes_list = []
228 slice_nodes_list = one_slice['node_ids']
229 #Get all the corresponding nodes details
230 nodes_all = self.iotlab_api.GetNodes(
231 {'hostname': slice_nodes_list},
232 ['node_id', 'hostname', 'site', 'boot_state'])
233 nodeall_byhostname = dict([(one_node['hostname'], one_node)
234 for one_node in nodes_all])
236 for single_slice in slice_list:
238 top_level_status = 'empty'
241 ['geni_urn', 'geni_error', 'iotlab_login', 'geni_status',
242 'geni_resources'], None)
244 # ['geni_urn','geni_error', 'pl_login','geni_status',
245 # 'geni_resources'], None)
246 # result['pl_login'] = one_slice['reg_researchers'][0].hrn
247 result['iotlab_login'] = one_slice['user']
248 logger.debug("Slabdriver - sliver_status Sliver status \
249 urn %s hrn %s single_slice %s \r\n "
250 % (slice_urn, slice_hrn, single_slice))
252 if 'node_ids' not in single_slice:
254 result['geni_status'] = top_level_status
255 result['geni_resources'] = []
258 top_level_status = 'ready'
260 #A job is running on Iotlab for this slice
261 # report about the local nodes that are in the slice only
263 result['geni_urn'] = slice_urn
266 for node_hostname in single_slice['node_ids']:
268 res['iotlab_hostname'] = node_hostname
269 res['iotlab_boot_state'] = \
270 nodeall_byhostname[node_hostname]['boot_state']
272 #res['pl_hostname'] = node['hostname']
273 #res['pl_boot_state'] = \
274 #nodeall_byhostname[node['hostname']]['boot_state']
275 #res['pl_last_contact'] = strftime(self.time_format, \
276 #gmtime(float(timestamp)))
278 slice_urn, type='slice',
279 id=nodeall_byhostname[node_hostname]['node_id']).urn
281 res['geni_urn'] = sliver_id
282 #node_name = node['hostname']
283 if nodeall_byhostname[node_hostname]['boot_state'] == 'Alive':
285 res['geni_status'] = 'ready'
287 res['geni_status'] = 'failed'
288 top_level_status = 'failed'
290 res['geni_error'] = ''
292 resources.append(res)
294 result['geni_status'] = top_level_status
295 result['geni_resources'] = resources
296 logger.debug("IOTLABDRIVER \tsliver_statusresources %s res %s "
301 def get_user_record(hrn):
304 Returns the user record based on the hrn from the SFA DB .
306 :param hrn: user's hrn
308 :returns: user record from SFA database
312 return dbsession.query(RegRecord).filter_by(hrn=hrn).first()
314 def testbed_name(self):
317 Returns testbed's name.
318 :returns: testbed authority name.
324 # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
325 def aggregate_version(self):
328 Returns the testbed's supported rspec advertisement and request
330 :returns: rspec versions supported ad a dictionary.
334 version_manager = VersionManager()
335 ad_rspec_versions = []
336 request_rspec_versions = []
337 for rspec_version in version_manager.versions:
338 if rspec_version.content_type in ['*', 'ad']:
339 ad_rspec_versions.append(rspec_version.to_dict())
340 if rspec_version.content_type in ['*', 'request']:
341 request_rspec_versions.append(rspec_version.to_dict())
343 'testbed': self.testbed_name(),
344 'geni_request_rspec_versions': request_rspec_versions,
345 'geni_ad_rspec_versions': ad_rspec_versions}
347 def _get_requested_leases_list(self, rspec):
349 Process leases in rspec depending on the rspec version (format)
350 type. Find the lease requests in the rspec and creates
351 a lease request list with the mandatory information ( nodes,
352 start time and duration) of the valid leases (duration above or
353 equal to the iotlab experiment minimum duration).
355 :param rspec: rspec request received.
357 :returns: list of lease requests found in the rspec
360 requested_lease_list = []
361 for lease in rspec.version.get_leases():
362 single_requested_lease = {}
363 logger.debug("IOTLABDRIVER.PY \t \
364 _get_requested_leases_list lease %s " % (lease))
366 if not lease.get('lease_id'):
367 if get_authority(lease['component_id']) == \
368 self.iotlab_api.root_auth:
369 single_requested_lease['hostname'] = \
370 iotlab_xrn_to_hostname(\
371 lease.get('component_id').strip())
372 single_requested_lease['start_time'] = \
373 lease.get('start_time')
374 single_requested_lease['duration'] = lease.get('duration')
375 #Check the experiment's duration is valid before adding
376 #the lease to the requested leases list
377 duration_in_seconds = \
378 int(single_requested_lease['duration'])
379 if duration_in_seconds >= self.iotlab_api.GetMinExperimentDurationInSec():
380 requested_lease_list.append(single_requested_lease)
382 return requested_lease_list
385 def _group_leases_by_start_time(requested_lease_list):
387 Create dict of leases by start_time, regrouping nodes reserved
388 at the same time, for the same amount of time so as to
389 define one job on OAR.
391 :param requested_lease_list: list of leases
392 :type requested_lease_list: list
393 :returns: Dictionary with key = start time, value = list of leases
394 with the same start time.
399 requested_job_dict = {}
400 for lease in requested_lease_list:
402 #In case it is an asap experiment start_time is empty
403 if lease['start_time'] == '':
404 lease['start_time'] = '0'
406 if lease['start_time'] not in requested_job_dict:
407 if isinstance(lease['hostname'], str):
408 lease['hostname'] = [lease['hostname']]
410 requested_job_dict[lease['start_time']] = lease
413 job_lease = requested_job_dict[lease['start_time']]
414 if lease['duration'] == job_lease['duration']:
415 job_lease['hostname'].append(lease['hostname'])
417 return requested_job_dict
419 def _process_requested_jobs(self, rspec):
421 Turns the requested leases and information into a dictionary
422 of requested jobs, grouped by starting time.
424 :param rspec: RSpec received
429 requested_lease_list = self._get_requested_leases_list(rspec)
430 logger.debug("IOTLABDRIVER _process_requested_jobs \
431 requested_lease_list %s" % (requested_lease_list))
432 job_dict = self._group_leases_by_start_time(requested_lease_list)
433 logger.debug("IOTLABDRIVER _process_requested_jobs job_dict\
438 def create_sliver(self, slice_urn, slice_hrn, creds, rspec_string,
440 """Answer to CreateSliver.
442 Creates the leases and slivers for the users from the information
443 found in the rspec string.
444 Launch experiment on OAR if the requested leases is valid. Delete
445 no longer requested leases.
448 :param creds: user's credentials
450 :param users: user record list
455 :returns: a valid Rspec for the slice which has just been
461 aggregate = IotlabAggregate(self)
463 slices = IotlabSlices(self)
464 peer = slices.get_peer(slice_hrn)
465 sfa_peer = slices.get_sfa_peer(slice_hrn)
468 if not isinstance(creds, list):
472 slice_record = users[0].get('slice_record', {})
473 logger.debug("IOTLABDRIVER.PY \t ===============create_sliver \t\
474 creds %s \r\n \r\n users %s"
476 slice_record['user'] = {'keys': users[0]['keys'],
477 'email': users[0]['email'],
478 'hrn': slice_record['reg-researchers'][0]}
480 rspec = RSpec(rspec_string)
481 logger.debug("IOTLABDRIVER.PY \t create_sliver \trspec.version \
482 %s slice_record %s users %s"
483 % (rspec.version, slice_record, users))
485 # ensure site record exists?
486 # ensure slice record exists
487 #Removed options in verify_slice SA 14/08/12
488 #Removed peer record in verify_slice SA 18/07/13
489 sfa_slice = slices.verify_slice(slice_hrn, slice_record, sfa_peer)
491 # ensure person records exists
492 #verify_persons returns added persons but the return value
494 #Removed peer record and sfa_peer in verify_persons SA 18/07/13
495 slices.verify_persons(slice_hrn, sfa_slice, users, options=options)
496 #requested_attributes returned by rspec.version.get_slice_attributes()
497 #unused, removed SA 13/08/12
498 #rspec.version.get_slice_attributes()
500 logger.debug("IOTLABDRIVER.PY create_sliver slice %s " % (sfa_slice))
502 # add/remove slice from nodes
504 #requested_slivers = [node.get('component_id') \
505 #for node in rspec.version.get_nodes_with_slivers()\
506 #if node.get('authority_id') is self.iotlab_api.root_auth]
507 #l = [ node for node in rspec.version.get_nodes_with_slivers() ]
508 #logger.debug("SLADRIVER \tcreate_sliver requested_slivers \
509 #requested_slivers %s listnodes %s" \
510 #%(requested_slivers,l))
511 #verify_slice_nodes returns nodes, but unused here. Removed SA 13/08/12.
512 #slices.verify_slice_nodes(sfa_slice, requested_slivers, peer)
514 requested_job_dict = self._process_requested_jobs(rspec)
516 logger.debug("IOTLABDRIVER.PY \tcreate_sliver requested_job_dict %s "
517 % (requested_job_dict))
518 #verify_slice_leases returns the leases , but the return value is unused
519 #here. Removed SA 13/08/12
520 slices.verify_slice_leases(sfa_slice,
521 requested_job_dict, peer)
523 return aggregate.get_rspec(slice_xrn=slice_urn,
524 login=sfa_slice['login'],
525 version=rspec.version)
527 def delete_sliver(self, slice_urn, slice_hrn, creds, options):
529 Deletes the lease associated with the slice hrn and the credentials
530 if the slice belongs to iotlab. Answer to DeleteSliver.
532 :param slice_urn: urn of the slice
533 :param slice_hrn: name of the slice
534 :param creds: slice credenials
535 :type slice_urn: string
536 :type slice_hrn: string
537 :type creds: ? unused
539 :returns: 1 if the slice to delete was not found on iotlab,
540 True if the deletion was successful, False otherwise otherwise.
542 .. note:: Should really be named delete_leases because iotlab does
543 not have any slivers, but only deals with leases. However,
544 SFA api only have delete_sliver define so far. SA 13/05/2013
545 .. note:: creds are unused, and are not used either in the dummy driver
549 sfa_slice_list = self.iotlab_api.GetSlices(
550 slice_filter=slice_hrn,
551 slice_filter_type='slice_hrn')
553 if not sfa_slice_list:
556 #Delete all leases in the slice
557 for sfa_slice in sfa_slice_list:
558 logger.debug("IOTLABDRIVER.PY delete_sliver slice %s" % (sfa_slice))
559 slices = IotlabSlices(self)
560 # determine if this is a peer slice
562 peer = slices.get_peer(slice_hrn)
564 logger.debug("IOTLABDRIVER.PY delete_sliver peer %s \
565 \r\n \t sfa_slice %s " % (peer, sfa_slice))
567 self.iotlab_api.DeleteSliceFromNodes(sfa_slice)
572 def list_resources (self, slice_urn, slice_hrn, creds, options):
575 List resources from the iotlab aggregate and returns a Rspec
576 advertisement with resources found when slice_urn and slice_hrn are
577 None (in case of resource discovery).
578 If a slice hrn and urn are provided, list experiment's slice
579 nodes in a rspec format. Answer to ListResources.
582 :param slice_urn: urn of the slice
583 :param slice_hrn: name of the slice
584 :param creds: slice credenials
585 :type slice_urn: string
586 :type slice_hrn: string
587 :type creds: ? unused
588 :param options: options used when listing resources (list_leases, info,
590 :returns: rspec string in xml
593 .. note:: creds are unused
596 #cached_requested = options.get('cached', True)
598 version_manager = VersionManager()
599 # get the rspec's return format from options
601 version_manager.get_version(options.get('geni_rspec_version'))
602 version_string = "rspec_%s" % (rspec_version)
604 #panos adding the info option to the caching key (can be improved)
605 if options.get('info'):
606 version_string = version_string + "_" + \
607 options.get('info', 'default')
609 # Adding the list_leases option to the caching key
610 if options.get('list_leases'):
611 version_string = version_string + "_" + \
612 options.get('list_leases', 'default')
614 # Adding geni_available to caching key
615 if options.get('geni_available'):
616 version_string = version_string + "_" + \
617 str(options.get('geni_available'))
619 # look in cache first
620 #if cached_requested and self.cache and not slice_hrn:
621 #rspec = self.cache.get(version_string)
623 #logger.debug("IotlabDriver.ListResources: \
624 #returning cached advertisement")
627 #panos: passing user-defined options
628 aggregate = IotlabAggregate(self)
630 rspec = aggregate.get_rspec(slice_xrn=slice_urn,
631 version=rspec_version, options=options)
634 #if self.cache and not slice_hrn:
635 #logger.debug("Iotlab.ListResources: stores advertisement in cache")
636 #self.cache.add(version_string, rspec)
641 def list_slices(self, creds, options):
642 """Answer to ListSlices.
644 List slices belonging to iotlab, returns slice urns list.
645 No caching used. Options unused but are defined in the SFA method
648 :returns: slice urns list
651 .. note:: creds are unused
653 # look in cache first
655 #slices = self.cache.get('slices')
657 #logger.debug("PlDriver.list_slices returns from cache")
662 slices = self.iotlab_api.GetSlices()
663 logger.debug("IOTLABDRIVER.PY \tlist_slices hrn %s \r\n \r\n"
665 slice_hrns = [iotlab_slice['hrn'] for iotlab_slice in slices]
667 slice_urns = [hrn_to_urn(slice_hrn, 'slice')
668 for slice_hrn in slice_hrns]
672 #logger.debug ("IotlabDriver.list_slices stores value in cache")
673 #self.cache.add('slices', slice_urns)
678 def register(self, sfa_record, hrn, pub_key):
680 Adding new user, slice, node or site should not be handled
683 ..warnings:: should not be used. Different components are in charge of
684 doing this task. Adding nodes = OAR
685 Adding users = LDAP Iotlab
686 Adding slice = Import from LDAP users
689 :param sfa_record: record provided by the client of the
691 :type sfa_record: dict
692 :param pub_key: public key of the user
693 :type pub_key: string
695 .. note:: DOES NOTHING. Returns -1.
701 def update(self, old_sfa_record, new_sfa_record, hrn, new_key):
703 No site or node record update allowed in Iotlab.
704 The only modifications authorized here are key deletion/addition
705 on an existing user and password change.
706 On an existing user, CAN NOT BE MODIFIED:
707 'first_name', 'last_name', 'email'
708 DOES NOT EXIST IN SENSLAB:
709 'phone', 'url', 'bio','title', 'accepted_aup',
710 A slice is bound to its user, so modifying the user's ssh key should
711 modify the slice's GID after an import procedure.
713 :param old_sfa_record: what is in the db for this hrn
714 :param new_sfa_record: what was passed to the Update call
715 :param new_key: the new user's public key
716 :param hrn: the user's sfa hrn
717 :type old_sfa_record: dictionary
718 :type new_sfa_record: dictionary
719 :type pub_key: string
723 .. seealso::: update in driver.py.
726 pointer = old_sfa_record['pointer']
727 old_sfa_record_type = old_sfa_record['type']
729 # new_key implemented for users only
730 if new_key and old_sfa_record_type not in ['user']:
731 raise UnknownSfaType(old_sfa_record_type)
733 if old_sfa_record_type == "user":
735 all_fields = new_sfa_record
736 for key in all_fields.keys():
737 if key in ['key', 'password']:
738 update_fields[key] = all_fields[key]
741 # must check this key against the previous one if it exists
742 persons = self.iotlab_api.GetPersons([old_sfa_record])
744 keys = [person['pkey']]
745 #Get all the person's keys
746 keys_dict = self.iotlab_api.GetKeys(keys)
748 # Delete all stale keys, meaning the user has only one key
750 #TODO: do we really want to delete all the other keys?
751 #Is this a problem with the GID generation to have multiple
757 #remove all the other keys
758 for key in keys_dict:
759 self.iotlab_api.DeleteKey(person, key)
760 self.iotlab_api.AddPersonKey(
761 person, {'sshPublicKey': person['pkey']},
762 {'sshPublicKey': new_key})
765 def remove(self, sfa_record):
768 Removes users only. Mark the user as disabled in
769 LDAP. The user and his slice are then deleted from the
770 db by running an import on the registry.
772 :param sfa_record: record is the existing sfa record in the db
773 :type sfa_record: dict
775 ..warning::As fas as the slice is concerned, here only the leases are
776 removed from the slice. The slice is record itself is not removed
780 TODO : REMOVE SLICE FROM THE DB AS WELL? SA 14/05/2013,
782 TODO: return boolean for the slice part
784 sfa_record_type = sfa_record['type']
785 hrn = sfa_record['hrn']
786 if sfa_record_type == 'user':
788 #get user from iotlab ldap
789 person = self.iotlab_api.GetPersons(sfa_record)
790 #No registering at a given site in Iotlab.
791 #Once registered to the LDAP, all iotlab sites are
794 #Mark account as disabled in ldap
795 return self.iotlab_api.DeletePerson(sfa_record)
797 elif sfa_record_type == 'slice':
798 if self.iotlab_api.GetSlices(slice_filter=hrn,
799 slice_filter_type='slice_hrn'):
800 ret = self.iotlab_api.DeleteSlice(sfa_record)