2 This file defines the IotlabSlices class by which all the slice checkings
3 upon lease creation are done.
5 from sfa.util.xrn import get_authority, urn_to_hrn
6 from sfa.util.sfalogging import logger
13 This class is responsible for checking the slice when creating a
14 lease or a sliver. Those checks include verifying that the user is valid,
15 that the slice is known from the testbed or from our peers, that the list
16 of nodes involved has not changed (in this case the lease is modified
19 rspec_to_slice_tag = {'max_rate': 'net_max_rate'}
21 def __init__(self, driver):
23 Get the reference to the driver here.
27 def get_peer(self, xrn):
29 Finds the authority of a resource based on its xrn.
30 If the authority is Iotlab (local) return None,
31 Otherwise, look up in the DB if Iotlab is federated with this site
32 authority and returns its DB record if it is the case.
34 :param xrn: resource's xrn
40 hrn, hrn_type = urn_to_hrn(xrn)
41 #Does this slice belong to a local site or a peer iotlab site?
44 # get this slice's authority (site)
45 slice_authority = get_authority(hrn)
47 #This slice belongs to the current site
48 if slice_authority == self.driver.testbed_shell.root_auth:
49 site_authority = slice_authority
52 site_authority = get_authority(slice_authority).lower()
53 # get this site's authority (sfa root authority or sub authority)
55 logger.debug("IOTLABSLICES \t get_peer slice_authority %s \
56 site_authority %s hrn %s"
57 % (slice_authority, site_authority, hrn))
59 # check if we are already peered with this site_authority
60 #if so find the peer record
61 peers = self.driver.GetPeers(peer_filter=site_authority)
62 for peer_record in peers:
63 if site_authority == peer_record.hrn:
65 logger.debug(" IOTLABSLICES \tget_peer peer %s " % (peer))
68 def get_sfa_peer(self, xrn):
69 """Returns the authority name for the xrn or None if the local site
72 :param xrn: the xrn of the resource we are looking the authority for.
74 :returns: the resources's authority name.
78 hrn, hrn_type = urn_to_hrn(xrn)
80 # return the authority for this hrn or None if we are the authority
82 slice_authority = get_authority(hrn)
83 site_authority = get_authority(slice_authority)
85 if site_authority != self.driver.hrn:
86 sfa_peer = site_authority
90 def verify_slice_leases(self, sfa_slice, requested_jobs_dict, peer):
92 Compare requested leases with the leases already scheduled/
93 running in OAR. If necessary, delete and recreate modified leases,
94 and delete no longer requested ones.
96 :param sfa_slice: sfa slice record
97 :param requested_jobs_dict: dictionary of requested leases
98 :param peer: sfa peer record
100 :type sfa_slice: dict
101 :type requested_jobs_dict: dict
103 :returns: leases list of dictionary
108 logger.debug("IOTLABSLICES verify_slice_leases sfa_slice %s "
110 #First get the list of current leases from OAR
111 leases = self.driver.GetLeases({'slice_hrn': sfa_slice['hrn']})
112 logger.debug("IOTLABSLICES verify_slice_leases requested_jobs_dict %s \
113 leases %s " % (requested_jobs_dict, leases))
115 current_nodes_reserved_by_start_time = {}
116 requested_nodes_by_start_time = {}
117 leases_by_start_time = {}
118 reschedule_jobs_dict = {}
120 #Create reduced dictionary with key start_time and value
122 #-for the leases already registered by OAR first
123 # then for the new leases requested by the user
125 #Leases already scheduled/running in OAR
127 current_nodes_reserved_by_start_time[lease['t_from']] = \
128 lease['reserved_nodes']
129 leases_by_start_time[lease['t_from']] = lease
131 #First remove job whose duration is too short
132 for job in requested_jobs_dict.values():
134 str(int(job['duration']) \
135 * self.driver.testbed_shell.GetLeaseGranularity())
136 if job['duration'] < \
137 self.driver.testbed_shell.GetLeaseGranularity():
138 del requested_jobs_dict[job['start_time']]
141 for start_time in requested_jobs_dict:
142 requested_nodes_by_start_time[int(start_time)] = \
143 requested_jobs_dict[start_time]['hostname']
144 #Check if there is any difference between the leases already
145 #registered in OAR and the requested jobs.
146 #Difference could be:
147 #-Lease deleted in the requested jobs
148 #-Added/removed nodes
151 logger.debug("IOTLABSLICES verify_slice_leases \
152 requested_nodes_by_start_time %s \
153 "% (requested_nodes_by_start_time))
154 #Find all deleted leases
156 list(set(leases_by_start_time.keys()).\
157 difference(requested_nodes_by_start_time.keys()))
158 deleted_leases = [leases_by_start_time[start_time]['lease_id'] \
159 for start_time in start_time_list]
162 #Find added or removed nodes in exisiting leases
163 for start_time in requested_nodes_by_start_time:
164 logger.debug("IOTLABSLICES verify_slice_leases start_time %s \
166 if start_time in current_nodes_reserved_by_start_time:
168 if requested_nodes_by_start_time[start_time] == \
169 current_nodes_reserved_by_start_time[start_time]:
174 set(requested_nodes_by_start_time[start_time])
176 update_node_set.difference(\
177 current_nodes_reserved_by_start_time[start_time])
179 update_node_set.intersection(\
180 current_nodes_reserved_by_start_time[start_time])
183 current_nodes_reserved_by_start_time[start_time])
185 old_nodes_set.difference(\
186 requested_nodes_by_start_time[start_time])
187 logger.debug("IOTLABSLICES verify_slice_leases \
188 shared_nodes %s added_nodes %s removed_nodes %s"\
189 %(shared_nodes, added_nodes,removed_nodes ))
190 #If the lease is modified, delete it before
192 #Add the deleted lease job id in the list
193 #WARNING :rescheduling does not work if there is already
194 # 2 running/scheduled jobs because deleting a job
195 #takes time SA 18/10/2012
196 if added_nodes or removed_nodes:
197 deleted_leases.append(\
198 leases_by_start_time[start_time]['lease_id'])
200 if added_nodes or shared_nodes:
201 reschedule_jobs_dict[str(start_time)] = \
202 requested_jobs_dict[str(start_time)]
207 job = requested_jobs_dict[str(start_time)]
208 logger.debug("IOTLABSLICES \
209 NEWLEASE slice %s job %s"
211 job_id = self.driver.AddLeases(
213 sfa_slice, int(job['start_time']),
214 int(job['duration']))
215 if job_id is not None:
216 new_leases = self.driver.GetLeases(login=
218 for new_lease in new_leases:
219 leases.append(new_lease)
221 #Deleted leases are the ones with lease id not declared in the Rspec
223 self.driver.testbed_shell.DeleteLeases(deleted_leases,
225 #self.driver.testbed_shell.DeleteLeases(deleted_leases,
226 # sfa_slice['user']['uid'])
227 logger.debug("IOTLABSLICES \
228 verify_slice_leases slice %s deleted_leases %s"
229 % (sfa_slice, deleted_leases))
231 if reschedule_jobs_dict:
232 for start_time in reschedule_jobs_dict:
233 job = reschedule_jobs_dict[start_time]
234 self.driver.AddLeases(
236 sfa_slice, int(job['start_time']),
237 int(job['duration']))
240 def verify_slice_nodes(self, sfa_slice, requested_slivers, peer):
241 """Check for wanted and unwanted nodes in the slice.
243 Removes nodes and associated leases that the user does not want anymore
244 by deleteing the associated job in OAR (DeleteSliceFromNodes).
245 Returns the nodes' hostnames that are going to be in the slice.
247 :param sfa_slice: slice record. Must contain node_ids and list_node_ids.
249 :param requested_slivers: list of requested nodes' hostnames.
250 :param peer: unused so far.
252 :type sfa_slice: dict
253 :type requested_slivers: list
256 :returns: list requested nodes hostnames
259 .. warning:: UNUSED SQA 24/07/13
260 .. seealso:: DeleteSliceFromNodes
261 .. todo:: check what to do with the peer? Can not remove peer nodes from
262 slice here. Anyway, in this case, the peer should have gotten the
269 if 'node_ids' in sfa_slice:
270 nodes = self.driver.testbed_shell.GetNodes(
271 sfa_slice['list_node_ids'],
273 current_slivers = [node['hostname'] for node in nodes]
275 # remove nodes not in rspec
276 deleted_nodes = list(set(current_slivers).
277 difference(requested_slivers))
279 logger.debug("IOTLABSLICES \tverify_slice_nodes slice %s\
280 \r\n \r\n deleted_nodes %s"
281 % (sfa_slice, deleted_nodes))
284 #Delete the entire experience
285 self.driver.testbed_shell.DeleteSliceFromNodes(sfa_slice)
288 def verify_slice(self, slice_hrn, slice_record, sfa_peer):
289 """Ensures slice record exists.
291 The slice record must exist either in Iotlab or in the other
292 federated testbed (sfa_peer). If the slice does not belong to Iotlab,
293 check if the user already exists in LDAP. In this case, adds the slice
294 to the sfa DB and associates its LDAP user.
296 :param slice_hrn: slice's name
297 :param slice_record: sfa record of the slice
298 :param sfa_peer: name of the peer authority if any.(not Iotlab).
300 :type slice_hrn: string
301 :type slice_record: dictionary
302 :type sfa_peer: string
304 .. seealso:: AddSlice
309 slicename = slice_hrn
310 # check if slice belongs to Iotlab
311 slices_list = self.driver.GetSlices(slice_filter=slicename,
312 slice_filter_type='slice_hrn')
317 for sl in slices_list:
319 logger.debug("IOTLABSLICES \t verify_slice slicename %s \
320 slices_list %s sl %s \r slice_record %s"
321 % (slicename, slices_list, sl, slice_record))
323 sfa_slice.update(slice_record)
326 #Search for user in ldap based on email SA 14/11/12
327 ldap_user = self.driver.testbed_shell.ldap.LdapFindUser(\
328 slice_record['user'])
329 logger.debug(" IOTLABSLICES \tverify_slice Oups \
330 slice_record %s sfa_peer %s ldap_user %s"
331 % (slice_record, sfa_peer, ldap_user))
332 #User already registered in ldap, meaning user should be in SFA db
333 #and hrn = sfa_auth+ uid
334 sfa_slice = {'hrn': slicename,
336 'authority': slice_record['authority'],
337 'gid': slice_record['gid'],
338 'slice_id': slice_record['record_id'],
339 'reg-researchers': slice_record['reg-researchers'],
340 'peer_authority': str(sfa_peer)
344 hrn = self.driver.testbed_shell.root_auth + '.' \
346 user = self.driver.get_user_record(hrn)
348 logger.debug(" IOTLABSLICES \tverify_slice hrn %s USER %s"
351 # add the external slice to the local SFA iotlab DB
353 self.driver.AddSlice(sfa_slice, user)
355 logger.debug("IOTLABSLICES \tverify_slice ADDSLICE OK")
359 def verify_persons(self, slice_hrn, slice_record, users, options={}):
360 """Ensures the users in users list exist and are enabled in LDAP. Adds
361 person if needed (AddPerson).
363 Checking that a user exist is based on the user's email. If the user is
364 still not found in the LDAP, it means that the user comes from another
365 federated testbed. In this case an account has to be created in LDAP
366 so as to enable the user to use the testbed, since we trust the testbed
367 he comes from. This is done by calling AddPerson.
369 :param slice_hrn: slice name
370 :param slice_record: record of the slice_hrn
371 :param users: users is a record list. Records can either be
372 local records or users records from known and trusted federated
373 sites.If the user is from another site that iotlab doesn't trust
374 yet, then Resolve will raise an error before getting to allocate.
376 :type slice_hrn: string
377 :type slice_record: string
380 .. seealso:: AddPerson
381 .. note:: Removed unused peer and sfa_peer parameters. SA 18/07/13.
386 logger.debug("IOTLABSLICES \tverify_persons \tslice_hrn %s \
387 \t slice_record %s\r\n users %s \t "
388 % (slice_hrn, slice_record, users))
391 #users_dict : dict whose keys can either be the user's hrn or its id.
392 #Values contains only id and hrn
395 #First create dicts by hrn and id for each user in the user record list:
397 # if 'slice_record' in info:
398 # slice_rec = info['slice_record']
399 # if 'user' in slice_rec :
400 # user = slice_rec['user']
403 users_by_email[info['email']] = info
404 users_dict[info['email']] = info
406 logger.debug("IOTLABSLICES.PY \t verify_person \
407 users_dict %s \r\n user_by_email %s \r\n "
408 % (users_dict, users_by_email))
410 existing_user_ids = []
411 existing_user_emails = []
413 # Check if user is in Iotlab LDAP using its hrn.
414 # Assuming Iotlab is centralised : one LDAP for all sites,
415 # user's record_id unknown from LDAP
416 # LDAP does not provide users id, therefore we rely on email to find the
420 #Construct the list of filters (list of dicts) for GetPersons
421 filter_user = [users_by_email[email] for email in users_by_email]
422 #Check user i in LDAP with GetPersons
423 #Needed because what if the user has been deleted in LDAP but
425 existing_users = self.driver.testbed_shell.GetPersons(filter_user)
426 logger.debug(" \r\n IOTLABSLICES.PY \tverify_person filter_user %s\
428 % (filter_user, existing_users))
429 #User is in iotlab LDAP
431 for user in existing_users:
432 user['login'] = user['uid']
433 users_dict[user['email']].update(user)
434 existing_user_emails.append(
435 users_dict[user['email']]['email'])
438 # User from another known trusted federated site. Check
439 # if a iotlab account matching the email has already been created.
442 if isinstance(users, list):
443 req += users[0]['email']
445 req += users['email']
446 ldap_reslt = self.driver.testbed_shell.ldap.LdapSearch(req)
449 logger.debug(" IOTLABSLICES.PY \tverify_person users \
450 USER already in Iotlab \t ldap_reslt %s \
452 existing_users.append(ldap_reslt[1])
455 #User not existing in LDAP
456 logger.debug("IOTLABSLICES.PY \tverify_person users \
457 not in ldap ...NEW ACCOUNT NEEDED %s \r\n \t \
458 ldap_reslt %s " % (users, ldap_reslt))
460 requested_user_emails = users_by_email.keys()
461 # requested_user_hrns = \
462 # [users_by_email[user]['hrn'] for user in users_by_email]
463 # logger.debug("IOTLABSLICES.PY \tverify_person \
464 # users_by_email %s " % (users_by_email))
466 # #Check that the user of the slice in the slice record
467 # #matches one of the existing users
469 # if slice_record['reg-researchers'][0] in requested_user_hrns:
470 # logger.debug(" IOTLABSLICES \tverify_person ['PI']\
471 # slice_record %s" % (slice_record))
476 # users to be added, removed or updated
477 #One user in one iotlab slice : there should be no need
478 #to remove/ add any user from/to a slice.
479 #However a user from SFA which is not registered in Iotlab yet
480 #should be added to the LDAP.
481 added_user_emails = set(requested_user_emails).\
482 difference(set(existing_user_emails))
485 #self.verify_keys(existing_slice_users, updated_users_list, \
490 #requested_user_email is in existing_user_emails
491 if len(added_user_emails) == 0:
492 slice_record['login'] = users_dict[requested_user_emails[0]]['uid']
493 logger.debug(" IOTLABSLICES \tverify_person QUICK DIRTY %s"
496 for added_user_email in added_user_emails:
497 added_user = users_dict[added_user_email]
498 logger.debug(" IOTLABSLICES \r\n \r\n \t verify_person \
499 added_user %s" % (added_user))
501 person['peer_person_id'] = None
502 k_list = ['first_name', 'last_name', 'person_id']
505 person[k] = added_user[k]
506 # bug user without key
507 if added_user['keys']:
508 person['pkey'] = added_user['keys'][0]
509 person['mail'] = added_user['email']
510 person['email'] = added_user['email']
511 person['key_ids'] = added_user.get('key_ids', [])
513 ret = self.driver.AddPerson(person)
515 # meaning bool is True and the AddPerson was successful
516 person['uid'] = ret['uid']
517 slice_record['login'] = person['uid']
519 # error message in ret
520 logger.debug(" IOTLABSLICES ret message %s" %(ret))
522 logger.debug(" IOTLABSLICES \r\n \r\n \t THE SECOND verify_person\
523 person %s" % (person))
524 #Update slice_Record with the id now known to LDAP
527 added_persons.append(person)
531 def verify_keys(self, persons, users, peer, options={}):
537 for person in persons:
538 key_ids.extend(person['key_ids'])
539 keylist = self.driver.GetKeys(key_ids, ['key_id', 'key'])
543 keydict[key['key']] = key['key_id']
544 existing_keys = keydict.keys()
547 for person in persons:
548 persondict[person['email']] = person
553 users_by_key_string = {}
555 user_keys = user.get('keys', [])
556 updated_persons.append(user)
557 for key_string in user_keys:
558 users_by_key_string[key_string] = user
559 requested_keys.append(key_string)
560 if key_string not in existing_keys:
561 key = {'key': key_string, 'key_type': 'ssh'}
564 #person = persondict[user['email']]
565 #self.driver.testbed_shell.UnBindObjectFromPeer(
566 # 'person',person['person_id'],
568 ret = self.driver.testbed_shell.AddPersonKey(
571 #key_index = user_keys.index(key['key'])
572 #remote_key_id = user['key_ids'][key_index]
573 #self.driver.testbed_shell.BindObjectToPeer('key', \
574 #key['key_id'], peer['shortname'], \
577 # remove old keys (only if we are not appending)
578 append = options.get('append', True)
580 removed_keys = set(existing_keys).difference(requested_keys)
581 for key in removed_keys:
583 #self.driver.testbed_shell.UnBindObjectFromPeer('key', \
584 #key, peer['shortname'])
586 user = users_by_key_string[key]
587 self.driver.testbed_shell.DeleteKey(user, key)