Documenting and cleaning test scripts in /testbeds/iotlab/tests.
[sfa.git] / sfa / iotlab / iotlabslices.py
1 """
2 This file defines the IotlabSlices class by which all the slice checkings
3 upon lease creation are done.
4 """
5 from sfa.util.xrn import get_authority, urn_to_hrn
6 from sfa.util.sfalogging import logger
7
8 MAXINT = 2L**31-1
9
10
11 class IotlabSlices:
12     """
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
17     accordingly).
18     """
19     rspec_to_slice_tag = {'max_rate': 'net_max_rate'}
20
21     def __init__(self, driver):
22         """
23         Get the reference to the driver here.
24         """
25         self.driver = driver
26
27     def get_peer(self, xrn):
28         """
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.
33
34         :param xrn: resource's xrn
35         :type xrn: string
36         :returns: peer record
37         :rtype: dict
38
39         """
40         hrn, hrn_type = urn_to_hrn(xrn)
41         #Does this slice belong to a local site or a peer iotlab site?
42         peer = None
43
44         # get this slice's authority (site)
45         slice_authority = get_authority(hrn)
46         #Iotlab stuff
47         #This slice belongs to the current site
48         if slice_authority == self.driver.testbed_shell.root_auth:
49             site_authority = slice_authority
50             return None
51
52         site_authority = get_authority(slice_authority).lower()
53         # get this site's authority (sfa root authority or sub authority)
54
55         logger.debug("IOTLABSLICES \t get_peer slice_authority  %s \
56                     site_authority %s hrn %s"
57                      % (slice_authority, site_authority, hrn))
58
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:
64                 peer = peer_record
65         logger.debug(" IOTLABSLICES \tget_peer peer  %s " % (peer))
66         return peer
67
68     def get_sfa_peer(self, xrn):
69         """Returns the authority name for the xrn or None if the local site
70         is the authority.
71
72         :param xrn: the xrn of the resource we are looking the authority for.
73         :type xrn: string
74         :returns: the resources's authority name.
75         :rtype: string
76
77         """
78         hrn, hrn_type = urn_to_hrn(xrn)
79
80         # return the authority for this hrn or None if we are the authority
81         sfa_peer = None
82         slice_authority = get_authority(hrn)
83         site_authority = get_authority(slice_authority)
84
85         if site_authority != self.driver.hrn:
86             sfa_peer = site_authority
87
88         return sfa_peer
89
90     def verify_slice_leases(self, sfa_slice, requested_jobs_dict, peer):
91         """
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.
95
96         :param sfa_slice: sfa slice record
97         :param requested_jobs_dict: dictionary of requested leases
98         :param peer: sfa peer record
99
100         :type sfa_slice: dict
101         :type requested_jobs_dict: dict
102         :type peer: dict
103         :returns: leases list of dictionary
104         :rtype: list
105
106         """
107
108         logger.debug("IOTLABSLICES verify_slice_leases sfa_slice %s "
109                      % (sfa_slice))
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))
114
115         current_nodes_reserved_by_start_time = {}
116         requested_nodes_by_start_time = {}
117         leases_by_start_time = {}
118         reschedule_jobs_dict = {}
119
120         #Create reduced dictionary with key start_time and value
121         # the list of nodes
122         #-for the leases already registered by OAR first
123         # then for the new leases requested by the user
124
125         #Leases already scheduled/running in OAR
126         for lease in leases:
127             current_nodes_reserved_by_start_time[lease['t_from']] = \
128                     lease['reserved_nodes']
129             leases_by_start_time[lease['t_from']] = lease
130
131         #First remove job whose duration is too short
132         for job in requested_jobs_dict.values():
133             job['duration'] = \
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']]
139
140         #Requested jobs
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
149         #-Newly added lease
150
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
155         start_time_list = \
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]
160
161
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 \
165                          "%( start_time))
166             if start_time in current_nodes_reserved_by_start_time:
167
168                 if requested_nodes_by_start_time[start_time] == \
169                     current_nodes_reserved_by_start_time[start_time]:
170                     continue
171
172                 else:
173                     update_node_set = \
174                             set(requested_nodes_by_start_time[start_time])
175                     added_nodes = \
176                         update_node_set.difference(\
177                         current_nodes_reserved_by_start_time[start_time])
178                     shared_nodes = \
179                         update_node_set.intersection(\
180                         current_nodes_reserved_by_start_time[start_time])
181                     old_nodes_set = \
182                         set(\
183                         current_nodes_reserved_by_start_time[start_time])
184                     removed_nodes = \
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
191                     #creating it again.
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'])
199                         #Reschedule the job
200                         if added_nodes or shared_nodes:
201                             reschedule_jobs_dict[str(start_time)] = \
202                                         requested_jobs_dict[str(start_time)]
203
204             else:
205                     #New lease
206
207                 job = requested_jobs_dict[str(start_time)]
208                 logger.debug("IOTLABSLICES \
209                               NEWLEASE slice %s  job %s"
210                              % (sfa_slice, job))
211                 job_id = self.driver.AddLeases(
212                     job['hostname'],
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=
217                         sfa_slice['login'])
218                     for new_lease in new_leases:
219                         leases.append(new_lease)
220
221         #Deleted leases are the ones with lease id not declared in the Rspec
222         if deleted_leases:
223             self.driver.testbed_shell.DeleteLeases(deleted_leases,
224                                                 sfa_slice['user']['uid'])
225             logger.debug("IOTLABSLICES \
226                           verify_slice_leases slice %s deleted_leases %s"
227                          % (sfa_slice, deleted_leases))
228
229         if reschedule_jobs_dict:
230             for start_time in reschedule_jobs_dict:
231                 job = reschedule_jobs_dict[start_time]
232                 self.driver.AddLeases(
233                     job['hostname'],
234                     sfa_slice, int(job['start_time']),
235                     int(job['duration']))
236         return leases
237
238     def verify_slice_nodes(self, sfa_slice, requested_slivers, peer):
239         """Check for wanted and unwanted nodes in the slice.
240
241         Removes nodes and associated leases that the user does not want anymore
242         by deleteing the associated job in OAR (DeleteSliceFromNodes).
243         Returns the nodes' hostnames that are going to be in the slice.
244
245         :param sfa_slice: slice record. Must contain node_ids and list_node_ids.
246
247         :param requested_slivers: list of requested nodes' hostnames.
248         :param peer: unused so far.
249
250         :type sfa_slice: dict
251         :type requested_slivers: list
252         :type peer: string
253
254         :returns: list requested nodes hostnames
255         :rtype: list
256
257         .. warning:: UNUSED SQA 24/07/13
258         .. seealso:: DeleteSliceFromNodes
259         .. todo:: check what to do with the peer? Can not remove peer nodes from
260             slice here. Anyway, in this case, the peer should have gotten the
261             remove request too.
262
263         """
264         current_slivers = []
265         deleted_nodes = []
266
267         if 'node_ids' in sfa_slice:
268             nodes = self.driver.testbed_shell.GetNodes(
269                 sfa_slice['list_node_ids'],
270                 ['hostname'])
271             current_slivers = [node['hostname'] for node in nodes]
272
273             # remove nodes not in rspec
274             deleted_nodes = list(set(current_slivers).
275                                  difference(requested_slivers))
276
277             logger.debug("IOTLABSLICES \tverify_slice_nodes slice %s\
278                                          \r\n \r\n deleted_nodes %s"
279                          % (sfa_slice, deleted_nodes))
280
281             if deleted_nodes:
282                 #Delete the entire experience
283                 self.driver.testbed_shell.DeleteSliceFromNodes(sfa_slice)
284             return nodes
285
286     def verify_slice(self, slice_hrn, slice_record, sfa_peer):
287         """Ensures slice record exists.
288
289         The slice record must exist either in Iotlab or in the other
290         federated testbed (sfa_peer). If the slice does not belong to Iotlab,
291         check if the user already exists in LDAP. In this case, adds the slice
292         to the sfa DB and associates its LDAP user.
293
294         :param slice_hrn: slice's name
295         :param slice_record: sfa record of the slice
296         :param sfa_peer: name of the peer authority if any.(not Iotlab).
297
298         :type slice_hrn: string
299         :type slice_record: dictionary
300         :type sfa_peer: string
301
302         .. seealso:: AddSlice
303
304
305         """
306
307         slicename = slice_hrn
308         # check if slice belongs to Iotlab
309         slices_list = self.driver.GetSlices(slice_filter=slicename,
310                                             slice_filter_type='slice_hrn')
311
312         sfa_slice = None
313
314         if slices_list:
315             for sl in slices_list:
316
317                 logger.debug("IOTLABSLICES \t verify_slice slicename %s \
318                                 slices_list %s sl %s \r slice_record %s"
319                              % (slicename, slices_list, sl, slice_record))
320                 sfa_slice = sl
321                 sfa_slice.update(slice_record)
322
323         else:
324             #Search for user in ldap based on email SA 14/11/12
325             ldap_user = self.driver.testbed_shell.ldap.LdapFindUser(\
326                                                     slice_record['user'])
327             logger.debug(" IOTLABSLICES \tverify_slice Oups \
328                         slice_record %s sfa_peer %s ldap_user %s"
329                         % (slice_record, sfa_peer, ldap_user))
330             #User already registered in ldap, meaning user should be in SFA db
331             #and hrn = sfa_auth+ uid
332             sfa_slice = {'hrn': slicename,
333                          'node_list': [],
334                          'authority': slice_record['authority'],
335                          'gid': slice_record['gid'],
336                          'slice_id': slice_record['record_id'],
337                          'reg-researchers': slice_record['reg-researchers'],
338                          'peer_authority': str(sfa_peer)
339                          }
340
341             if ldap_user:
342                 hrn = self.driver.testbed_shell.root_auth + '.' \
343                                                 + ldap_user['uid']
344                 user = self.driver.get_user_record(hrn)
345
346                 logger.debug(" IOTLABSLICES \tverify_slice hrn %s USER %s"
347                              % (hrn, user))
348
349                  # add the external slice to the local SFA iotlab DB
350                 if sfa_slice:
351                     self.driver.AddSlice(sfa_slice, user)
352
353             logger.debug("IOTLABSLICES \tverify_slice ADDSLICE OK")
354         return sfa_slice
355
356
357     def verify_persons(self, slice_hrn, slice_record, users, options={}):
358         """Ensures the users in users list exist and are enabled in LDAP. Adds
359         person if needed (AddPerson).
360
361         Checking that a user exist is based on the user's email. If the user is
362         still not found in the LDAP, it means that the user comes from another
363         federated testbed. In this case an account has to be created in LDAP
364         so as to enable the user to use the testbed, since we trust the testbed
365         he comes from. This is done by calling AddPerson.
366
367         :param slice_hrn: slice name
368         :param slice_record: record of the slice_hrn
369         :param users: users is a record list. Records can either be
370             local records or users records from known and trusted federated
371             sites.If the user is from another site that iotlab doesn't trust
372             yet, then Resolve will raise an error before getting to allocate.
373
374         :type slice_hrn: string
375         :type slice_record: string
376         :type users: list
377
378         .. seealso:: AddPerson
379         .. note:: Removed unused peer and sfa_peer parameters. SA 18/07/13.
380
381
382         """
383
384         logger.debug("IOTLABSLICES \tverify_persons \tslice_hrn  %s  \
385                     \t slice_record %s\r\n users %s \t  "
386                      % (slice_hrn, slice_record, users))
387
388         users_by_email = {}
389         #users_dict : dict whose keys can either be the user's hrn or its id.
390         #Values contains only id and hrn
391         users_dict = {}
392
393         #First create dicts by hrn and id for each user in the user record list:
394         for info in users:
395             # if 'slice_record' in info:
396             #     slice_rec = info['slice_record']
397                 # if 'user' in slice_rec :
398                 #     user = slice_rec['user']
399
400             if 'email' in info:
401                 users_by_email[info['email']] = info
402                 users_dict[info['email']] = info
403
404         logger.debug("IOTLABSLICES.PY \t verify_person  \
405                         users_dict %s \r\n user_by_email %s \r\n  "
406                      % (users_dict, users_by_email))
407
408         existing_user_ids = []
409         existing_user_emails = []
410         existing_users = []
411         # Check if user is in Iotlab LDAP using its hrn.
412         # Assuming Iotlab is centralised :  one LDAP for all sites,
413         # user's record_id unknown from LDAP
414         # LDAP does not provide users id, therefore we rely on email to find the
415         # user in LDAP
416
417         if users_by_email:
418             #Construct the list of filters (list of dicts) for GetPersons
419             filter_user = [users_by_email[email] for email in users_by_email]
420             #Check user i in LDAP with GetPersons
421             #Needed because what if the user has been deleted in LDAP but
422             #is still in SFA?
423             existing_users = self.driver.testbed_shell.GetPersons(filter_user)
424             logger.debug(" \r\n IOTLABSLICES.PY \tverify_person  filter_user %s\
425                        existing_users %s  "
426                         % (filter_user, existing_users))
427             #User is in iotlab LDAP
428             if existing_users:
429                 for user in existing_users:
430                     user['login'] = user['uid']
431                     users_dict[user['email']].update(user)
432                     existing_user_emails.append(
433                         users_dict[user['email']]['email'])
434
435
436             # User from another known trusted federated site. Check
437             # if a iotlab account matching the email has already been created.
438             else:
439                 req = 'mail='
440                 if isinstance(users, list):
441                     req += users[0]['email']
442                 else:
443                     req += users['email']
444                 ldap_reslt = self.driver.testbed_shell.ldap.LdapSearch(req)
445
446                 if ldap_reslt:
447                     logger.debug(" IOTLABSLICES.PY \tverify_person users \
448                                 USER already in Iotlab \t ldap_reslt %s \
449                                 " % (ldap_reslt))
450                     existing_users.append(ldap_reslt[1])
451
452                 else:
453                     #User not existing in LDAP
454                     logger.debug("IOTLABSLICES.PY \tverify_person users \
455                                 not in ldap ...NEW ACCOUNT NEEDED %s \r\n \t \
456                                 ldap_reslt %s " % (users, ldap_reslt))
457
458         requested_user_emails = users_by_email.keys()
459         requested_user_hrns = \
460             [users_by_email[user]['hrn'] for user in users_by_email]
461         logger.debug("IOTLABSLICES.PY \tverify_person  \
462                        users_by_email  %s " % (users_by_email))
463
464         #Check that the user of the slice in the slice record
465         #matches one of the existing users
466         try:
467             if slice_record['reg-researchers'][0] in requested_user_hrns:
468                 logger.debug(" IOTLABSLICES  \tverify_person ['PI']\
469                                 slice_record %s" % (slice_record))
470
471         except KeyError:
472             pass
473
474         # users to be added, removed or updated
475         #One user in one iotlab slice : there should be no need
476         #to remove/ add any user from/to a slice.
477         #However a user from SFA which is not registered in Iotlab yet
478         #should be added to the LDAP.
479         added_user_emails = set(requested_user_emails).\
480                                         difference(set(existing_user_emails))
481
482
483         #self.verify_keys(existing_slice_users, updated_users_list, \
484                                                             #peer, append)
485
486         added_persons = []
487         # add new users
488         #requested_user_email is in existing_user_emails
489         if len(added_user_emails) == 0:
490             slice_record['login'] = users_dict[requested_user_emails[0]]['uid']
491             logger.debug(" IOTLABSLICES  \tverify_person QUICK DIRTY %s"
492                          % (slice_record))
493
494         for added_user_email in added_user_emails:
495             added_user = users_dict[added_user_email]
496             logger.debug(" IOTLABSLICES \r\n \r\n  \t  verify_person \
497                          added_user %s" % (added_user))
498             person = {}
499             person['peer_person_id'] = None
500             k_list = ['first_name', 'last_name', 'person_id']
501             for k in k_list:
502                 if k in added_user:
503                     person[k] = added_user[k]
504
505             person['pkey'] = added_user['keys'][0]
506             person['mail'] = added_user['email']
507             person['email'] = added_user['email']
508             person['key_ids'] = added_user.get('key_ids', [])
509
510             ret = self.driver.testbed_shell.AddPerson(person)
511             if 'uid' in ret:
512                 # meaning bool is True and the AddPerson was successful
513                 person['uid'] = ret['uid']
514                 slice_record['login'] = person['uid']
515             else:
516                 # error message in ret
517                 logger.debug(" IOTLABSLICES ret message %s" %(ret))
518
519             logger.debug(" IOTLABSLICES \r\n \r\n  \t THE SECOND verify_person\
520                            person %s" % (person))
521             #Update slice_Record with the id now known to LDAP
522
523
524             added_persons.append(person)
525         return added_persons
526
527
528     def verify_keys(self, persons, users, peer, options={}):
529         """
530         .. warning:: unused
531         """
532         # existing keys
533         key_ids = []
534         for person in persons:
535             key_ids.extend(person['key_ids'])
536         keylist = self.driver.GetKeys(key_ids, ['key_id', 'key'])
537
538         keydict = {}
539         for key in keylist:
540             keydict[key['key']] = key['key_id']
541         existing_keys = keydict.keys()
542
543         persondict = {}
544         for person in persons:
545             persondict[person['email']] = person
546
547         # add new keys
548         requested_keys = []
549         updated_persons = []
550         users_by_key_string = {}
551         for user in users:
552             user_keys = user.get('keys', [])
553             updated_persons.append(user)
554             for key_string in user_keys:
555                 users_by_key_string[key_string] = user
556                 requested_keys.append(key_string)
557                 if key_string not in existing_keys:
558                     key = {'key': key_string, 'key_type': 'ssh'}
559                     #try:
560                         ##if peer:
561                             #person = persondict[user['email']]
562                             #self.driver.testbed_shell.UnBindObjectFromPeer(
563                                 # 'person',person['person_id'],
564                                 # peer['shortname'])
565                     ret = self.driver.testbed_shell.AddPersonKey(
566                         user['email'], key)
567                         #if peer:
568                             #key_index = user_keys.index(key['key'])
569                             #remote_key_id = user['key_ids'][key_index]
570                             #self.driver.testbed_shell.BindObjectToPeer('key', \
571                                             #key['key_id'], peer['shortname'], \
572                                             #remote_key_id)
573
574         # remove old keys (only if we are not appending)
575         append = options.get('append', True)
576         if append is False:
577             removed_keys = set(existing_keys).difference(requested_keys)
578             for key in removed_keys:
579                     #if peer:
580                         #self.driver.testbed_shell.UnBindObjectFromPeer('key', \
581                                         #key, peer['shortname'])
582
583                 user = users_by_key_string[key]
584                 self.driver.testbed_shell.DeleteKey(user, key)
585
586         return