Removed unused import from planetlab.plxrn in slab files.
[sfa.git] / sfa / senslab / slabdriver.py
1 import subprocess
2
3 from datetime import datetime
4 from dateutil import tz 
5 from time import strftime, gmtime
6
7 from sfa.util.faults import SliverDoesNotExist, UnknownSfaType
8 from sfa.util.sfalogging import logger
9
10 from sfa.storage.alchemy import dbsession
11 from sfa.storage.model import RegRecord, RegUser
12
13 from sfa.trust.credential import Credential
14
15
16 from sfa.managers.driver import Driver
17 from sfa.rspecs.version_manager import VersionManager
18 from sfa.rspecs.rspec import RSpec
19
20 from sfa.util.xrn import hrn_to_urn, urn_to_sliver_id, get_leaf
21 from sfa.planetlab.plxrn import slicename_to_hrn, \
22                                         hostname_to_urn, \
23                                         xrn_to_hostname
24
25 ## thierry: everything that is API-related (i.e. handling incoming requests) 
26 # is taken care of 
27 # SlabDriver should be really only about talking to the senslab testbed
28
29
30 from sfa.senslab.OARrestapi import  OARrestapi
31 from sfa.senslab.LDAPapi import LDAPapi
32
33 from sfa.senslab.slabpostgres import SlabDB, slab_dbsession, SliceSenslab
34 from sfa.senslab.slabaggregate import SlabAggregate
35 from sfa.senslab.slabslices import SlabSlices
36
37
38
39
40
41 # thierry : note
42 # this inheritance scheme is so that the driver object can receive
43 # GetNodes or GetSites sorts of calls directly
44 # and thus minimize the differences in the managers with the pl version
45 class SlabDriver(Driver):
46
47     def __init__(self, config):
48         Driver.__init__ (self, config)
49         self.config = config
50         self.hrn = config.SFA_INTERFACE_HRN
51
52         self.root_auth = config.SFA_REGISTRY_ROOT_AUTH
53
54         self.oar = OARrestapi()
55         self.ldap = LDAPapi()
56         self.time_format = "%Y-%m-%d %H:%M:%S"
57         self.db = SlabDB(config,debug = True)
58         self.cache = None
59         
60     
61     def sliver_status(self, slice_urn, slice_hrn):
62         """Receive a status request for slice named urn/hrn 
63         urn:publicid:IDN+senslab+nturro_slice hrn senslab.nturro_slice
64         shall return a structure as described in
65         http://groups.geni.net/geni/wiki/GAPI_AM_API_V2#SliverStatus
66         NT : not sure if we should implement this or not, but used by sface.
67         
68         """
69         
70         #First get the slice with the slice hrn
71         sl = self.GetSlices(slice_filter = slice_hrn, \
72                                     slice_filter_type = 'slice_hrn')
73         if len(sl) is 0:
74             raise SliverDoesNotExist("%s  slice_hrn" % (slice_hrn))
75         
76         top_level_status = 'unknown'
77         nodes_in_slice = sl['node_ids']
78         
79         if len(nodes_in_slice) is 0:
80             raise SliverDoesNotExist("No slivers allocated ") 
81         else:
82             top_level_status = 'ready' 
83         
84         logger.debug("Slabdriver - sliver_status Sliver status urn %s hrn %s sl\
85                              %s \r\n " %(slice_urn, slice_hrn, sl))
86                              
87         if sl['oar_job_id'] is not -1:
88             #A job is running on Senslab for this slice
89             # report about the local nodes that are in the slice only
90             
91             nodes_all = self.GetNodes({'hostname':nodes_in_slice},
92                             ['node_id', 'hostname','site','boot_state'])
93             nodeall_byhostname = dict([(n['hostname'], n) for n in nodes_all])
94             
95
96             result = {}
97             result['geni_urn'] = slice_urn
98             result['pl_login'] = sl['job_user'] #For compatibility
99
100             
101             timestamp = float(sl['startTime']) + float(sl['walltime']) 
102             result['pl_expires'] = strftime(self.time_format, \
103                                                     gmtime(float(timestamp)))
104             #result['slab_expires'] = strftime(self.time_format,\
105                                                      #gmtime(float(timestamp)))
106             
107             resources = []
108             for node in nodeall_byhostname:
109                 res = {}
110                 #res['slab_hostname'] = node['hostname']
111                 #res['slab_boot_state'] = node['boot_state']
112                 
113                 res['pl_hostname'] = nodeall_byhostname[node]['hostname']
114                 res['pl_boot_state'] = nodeall_byhostname[node]['boot_state']
115                 res['pl_last_contact'] = strftime(self.time_format, \
116                                                     gmtime(float(timestamp)))
117                 sliver_id = urn_to_sliver_id(slice_urn, sl['record_id_slice'], \
118                                             nodeall_byhostname[node]['node_id']) 
119                 res['geni_urn'] = sliver_id 
120                 if nodeall_byhostname[node]['boot_state'] == 'Alive':
121
122                     res['geni_status'] = 'ready'
123                 else:
124                     res['geni_status'] = 'failed'
125                     top_level_status = 'failed' 
126                     
127                 res['geni_error'] = ''
128         
129                 resources.append(res)
130                 
131             result['geni_status'] = top_level_status
132             result['geni_resources'] = resources 
133             logger.debug("SLABDRIVER \tsliver_statusresources %s res %s "\
134                                                      %(resources,res))
135             return result        
136         
137         
138     def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, \
139                                                              users, options):
140         logger.debug("SLABDRIVER.PY \tcreate_sliver ")
141         aggregate = SlabAggregate(self)
142         
143         slices = SlabSlices(self)
144         peer = slices.get_peer(slice_hrn)
145         sfa_peer = slices.get_sfa_peer(slice_hrn)
146         slice_record = None 
147  
148         if not isinstance(creds, list):
149             creds = [creds]
150     
151         if users:
152             slice_record = users[0].get('slice_record', {})
153     
154         # parse rspec
155         rspec = RSpec(rspec_string)
156         logger.debug("SLABDRIVER.PY \tcreate_sliver \trspec.version %s " \
157                                                             %(rspec.version))
158         
159         
160         # ensure site record exists?
161         # ensure slice record exists
162         sfa_slice = slices.verify_slice(slice_hrn, slice_record, peer, \
163                                                     sfa_peer, options=options)
164         requested_attributes = rspec.version.get_slice_attributes()
165         
166         if requested_attributes:
167             for attrib_dict in requested_attributes:
168                 if 'timeslot' in attrib_dict and attrib_dict['timeslot'] \
169                                                                 is not None:
170                     sfa_slice.update({'timeslot':attrib_dict['timeslot']})
171         logger.debug("SLABDRIVER.PY create_sliver slice %s " %(sfa_slice))
172         
173         # ensure person records exists
174         persons = slices.verify_persons(slice_hrn, sfa_slice, users, peer, \
175                                                     sfa_peer, options=options)
176         
177         # ensure slice attributes exists?
178
179         
180         # add/remove slice from nodes 
181        
182         requested_slivers = [node.get('component_name') \
183                             for node in rspec.version.get_nodes_with_slivers()]
184         logger.debug("SLADRIVER \tcreate_sliver requested_slivers \
185                                     requested_slivers %s " %(requested_slivers))
186         
187         nodes = slices.verify_slice_nodes(sfa_slice, requested_slivers, peer) 
188         
189         # add/remove leases
190         requested_leases = []
191         kept_leases = []
192         for lease in rspec.version.get_leases():
193             requested_lease = {}
194             if not lease.get('lease_id'):
195                 requested_lease['hostname'] = \
196                             xrn_to_hostname(lease.get('component_id').strip())
197                 requested_lease['start_time'] = lease.get('start_time')
198                 requested_lease['duration'] = lease.get('duration')
199             else:
200                 kept_leases.append(int(lease['lease_id']))
201             if requested_lease.get('hostname'):
202                 requested_leases.append(requested_lease)
203                 
204         leases = slices.verify_slice_leases(sfa_slice, \
205                                     requested_leases, kept_leases, peer)
206         
207         return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
208         
209         
210     def delete_sliver (self, slice_urn, slice_hrn, creds, options):
211         
212         sfa_slice = self.GetSlices(slice_filter = slice_hrn, \
213                                             slice_filter_type = 'slice_hrn')
214         logger.debug("SLABDRIVER.PY delete_sliver slice %s" %(sfa_slice))
215         if not sfa_slice:
216             return 1
217        
218         slices = SlabSlices(self)
219         # determine if this is a peer slice
220       
221         peer = slices.get_peer(slice_hrn)
222         try:
223             if peer:
224                 self.UnBindObjectFromPeer('slice', \
225                                         sfa_slice['record_id_slice'], peer)
226             self.DeleteSliceFromNodes(sfa_slice)
227         finally:
228             if peer:
229                 self.BindObjectToPeer('slice', sfa_slice['slice_id'], \
230                                             peer, sfa_slice['peer_slice_id'])
231         return 1
232             
233             
234     def AddSlice(self, slice_record):
235         slab_slice = SliceSenslab( slice_hrn = slice_record['slice_hrn'], \
236                         record_id_slice= slice_record['record_id_slice'] , \
237                         record_id_user= slice_record['record_id_user'], \
238                         peer_authority = slice_record['peer_authority'])
239         logger.debug("SLABDRIVER.PY \tAddSlice slice_record %s slab_slice %s" \
240                                             %(slice_record,slab_slice))
241         slab_dbsession.add(slab_slice)
242         slab_dbsession.commit()
243         return
244         
245     # first 2 args are None in case of resource discovery
246     def list_resources (self, slice_urn, slice_hrn, creds, options):
247         #cached_requested = options.get('cached', True) 
248     
249         version_manager = VersionManager()
250         # get the rspec's return format from options
251         rspec_version = \
252                 version_manager.get_version(options.get('geni_rspec_version'))
253         version_string = "rspec_%s" % (rspec_version)
254     
255         #panos adding the info option to the caching key (can be improved)
256         if options.get('info'):
257             version_string = version_string + "_" + \
258                                         options.get('info', 'default')
259     
260         # look in cache first
261         #if cached_requested and self.cache and not slice_hrn:
262             #rspec = self.cache.get(version_string)
263             #if rspec:
264                 #logger.debug("SlabDriver.ListResources: \
265                                     #returning cached advertisement")
266                 #return rspec 
267     
268         #panos: passing user-defined options
269         aggregate = SlabAggregate(self)
270         origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
271         options.update({'origin_hrn':origin_hrn})
272         rspec =  aggregate.get_rspec(slice_xrn=slice_urn, \
273                                         version=rspec_version, options=options)
274        
275         # cache the result
276         #if self.cache and not slice_hrn:
277             #logger.debug("Slab.ListResources: stores advertisement in cache")
278             #self.cache.add(version_string, rspec)
279     
280         return rspec
281         
282         
283     def list_slices (self, creds, options):
284         # look in cache first
285         #if self.cache:
286             #slices = self.cache.get('slices')
287             #if slices:
288                 #logger.debug("PlDriver.list_slices returns from cache")
289                 #return slices
290     
291         # get data from db 
292         logger.debug("SLABDRIVER.PY \tlist_slices")
293         slices = self.GetSlices()
294         slice_hrns = [slicename_to_hrn(self.hrn, slab_slice['slice_hrn']) \
295                                                     for slab_slice in slices]
296         slice_urns = [hrn_to_urn(slice_hrn, 'slice') \
297                                                 for slice_hrn in slice_hrns]
298     
299         # cache the result
300         #if self.cache:
301             #logger.debug ("SlabDriver.list_slices stores value in cache")
302             #self.cache.add('slices', slice_urns) 
303     
304         return slice_urns
305     
306     #No site or node register supported
307     def register (self, sfa_record, hrn, pub_key):
308         record_type = sfa_record['type']
309         slab_record = self.sfa_fields_to_slab_fields(record_type, hrn, \
310                                                             sfa_record)
311     
312
313         if record_type == 'slice':
314             acceptable_fields = ['url', 'instantiation', 'name', 'description']
315             for key in slab_record.keys():
316                 if key not in acceptable_fields:
317                     slab_record.pop(key) 
318             logger.debug("SLABDRIVER.PY register")
319             slices = self.GetSlices(slice_filter =slab_record['hrn'], \
320                                             slice_filter_type = 'slice_hrn')
321             if not slices:
322                 pointer = self.AddSlice(slab_record)
323             else:
324                 pointer = slices[0]['slice_id']
325     
326         elif record_type == 'user':  
327             persons = self.GetPersons([sfa_record])
328             #persons = self.GetPersons([sfa_record['hrn']])
329             if not persons:
330                 pointer = self.AddPerson(dict(sfa_record))
331                 #add in LDAP 
332             else:
333                 pointer = persons[0]['person_id']
334                 
335             #Does this make sense to senslab ?
336             #if 'enabled' in sfa_record and sfa_record['enabled']:
337                 #self.UpdatePerson(pointer, \
338                                     #{'enabled': sfa_record['enabled']})
339                 
340             #TODO register Change this AddPersonToSite stuff 05/07/2012 SA   
341             # add this person to the site only if 
342             # she is being added for the first
343             # time by sfa and doesnt already exist in plc
344             if not persons or not persons[0]['site_ids']:
345                 login_base = get_leaf(sfa_record['authority'])
346                 self.AddPersonToSite(pointer, login_base)
347     
348             # What roles should this user have?
349             #TODO : DElete this AddRoleToPerson 04/07/2012 SA
350             #Function prototype is :
351             #AddRoleToPerson(self, auth, role_id_or_name, person_id_or_email)
352             #what's the pointer doing here?
353             self.AddRoleToPerson('user', pointer)
354             # Add the user's key
355             if pub_key:
356                 self.AddPersonKey(pointer, {'key_type' : 'ssh', \
357                                                 'key' : pub_key})
358                 
359         #No node adding outside OAR
360
361         return pointer
362             
363     #No site or node record update allowed       
364     def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
365         pointer = old_sfa_record['pointer']
366         old_sfa_record_type = old_sfa_record['type']
367
368         # new_key implemented for users only
369         if new_key and old_sfa_record_type not in [ 'user' ]:
370             raise UnknownSfaType(old_sfa_record_type)
371         
372         #if (type == "authority"):
373             #self.shell.UpdateSite(pointer, new_sfa_record)
374     
375         if old_sfa_record_type == "slice":
376             slab_record = self.sfa_fields_to_slab_fields(old_sfa_record_type, \
377                                                 hrn, new_sfa_record)
378             if 'name' in slab_record:
379                 slab_record.pop('name')
380                 #Prototype should be UpdateSlice(self,
381                 #auth, slice_id_or_name, slice_fields)
382                 #Senslab cannot update slice since slice = job
383                 #so we must delete and create another job
384                 self.UpdateSlice(pointer, slab_record)
385     
386         elif old_sfa_record_type == "user":
387             update_fields = {}
388             all_fields = new_sfa_record
389             for key in all_fields.keys():
390                 if key in ['first_name', 'last_name', 'title', 'email',
391                            'password', 'phone', 'url', 'bio', 'accepted_aup',
392                            'enabled']:
393                     update_fields[key] = all_fields[key]
394             self.UpdatePerson(pointer, update_fields)
395     
396             if new_key:
397                 # must check this key against the previous one if it exists
398                 persons = self.GetPersons([pointer], ['key_ids'])
399                 person = persons[0]
400                 keys = person['key_ids']
401                 keys = self.GetKeys(person['key_ids'])
402                 
403                 # Delete all stale keys
404                 key_exists = False
405                 for key in keys:
406                     if new_key != key['key']:
407                         self.DeleteKey(key['key_id'])
408                     else:
409                         key_exists = True
410                 if not key_exists:
411                     self.AddPersonKey(pointer, {'key_type': 'ssh', \
412                                                     'key': new_key})
413
414
415         return True
416         
417
418     def remove (self, sfa_record):
419         sfa_record_type = sfa_record['type']
420         hrn = sfa_record['hrn']
421         record_id = sfa_record['record_id']
422         if sfa_record_type == 'user':
423
424             #get user from senslab ldap  
425             person = self.GetPersons(sfa_record)
426             #No registering at a given site in Senslab.
427             #Once registered to the LDAP, all senslab sites are
428             #accesible.
429             if person :
430                 #Mark account as disabled in ldap
431                 self.DeletePerson(sfa_record)
432         elif sfa_record_type == 'slice':
433             if self.GetSlices(slice_filter = hrn, \
434                                     slice_filter_type = 'slice_hrn'):
435                 self.DeleteSlice(sfa_record_type)
436
437         #elif type == 'authority':
438             #if self.GetSites(pointer):
439                 #self.DeleteSite(pointer)
440
441         return True
442             
443             
444             
445     #TODO clean GetPeers. 05/07/12SA        
446     def GetPeers (self, auth = None, peer_filter=None, return_fields_list=None):
447
448         existing_records = {}
449         existing_hrns_by_types = {}
450         logger.debug("SLABDRIVER \tGetPeers auth = %s, peer_filter %s, \
451                     return_field %s " %(auth , peer_filter, return_fields_list))
452         all_records = dbsession.query(RegRecord).filter(RegRecord.type.like('%authority%')).all()
453         for record in all_records:
454             existing_records[(record.hrn, record.type)] = record
455             if record.type not in existing_hrns_by_types:
456                 existing_hrns_by_types[record.type] = [record.hrn]
457                 logger.debug("SLABDRIVER \tGetPeer\t NOT IN \
458                     existing_hrns_by_types %s " %( existing_hrns_by_types))
459             else:
460                 
461                 logger.debug("SLABDRIVER \tGetPeer\t \INNN  type %s hrn %s " \
462                                                 %(record.type,record.hrn))
463                 existing_hrns_by_types[record.type].append(record.hrn)
464
465                         
466         logger.debug("SLABDRIVER \tGetPeer\texisting_hrns_by_types %s "\
467                                              %( existing_hrns_by_types))
468         records_list = [] 
469       
470         try: 
471             if peer_filter:
472                 records_list.append(existing_records[(peer_filter,'authority')])
473             else :
474                 for hrn in existing_hrns_by_types['authority']:
475                     records_list.append(existing_records[(hrn,'authority')])
476                     
477             logger.debug("SLABDRIVER \tGetPeer \trecords_list  %s " \
478                                             %(records_list))
479
480         except:
481             pass
482                 
483         return_records = records_list
484         if not peer_filter and not return_fields_list:
485             return records_list
486
487        
488         logger.debug("SLABDRIVER \tGetPeer return_records %s " \
489                                                     %(return_records))
490         return return_records
491         
492      
493     #TODO  : Handling OR request in make_ldap_filters_from_records 
494     #instead of the for loop 
495     #over the records' list
496     def GetPersons(self, person_filter=None, return_fields_list=None):
497         """
498         person_filter should be a list of dictionnaries when not set to None.
499         Returns a list of users whose accounts are enabled found in ldap.
500        
501         """
502         logger.debug("SLABDRIVER \tGetPersons person_filter %s" \
503                                                     %(person_filter))
504         person_list = []
505         if person_filter and isinstance(person_filter, list):
506         #If we are looking for a list of users (list of dict records)
507         #Usually the list contains only one user record
508             for searched_attributes in person_filter:
509                 
510                 #Get only enabled user accounts in senslab LDAP : 
511                 #add a filter for make_ldap_filters_from_record
512                 person = self.ldap.LdapFindUser(searched_attributes, \
513                                 is_user_enabled=True)
514                 person_list.append(person)
515           
516         else:
517             #Get only enabled user accounts in senslab LDAP : 
518             #add a filter for make_ldap_filters_from_record
519             person_list  = self.ldap.LdapFindUser(is_user_enabled=True)  
520
521         return person_list
522
523     def GetTimezone(self):
524         server_timestamp, server_tz = self.oar.parser.\
525                                             SendRequest("GET_timezone")
526         return server_timestamp, server_tz
527     
528
529     def DeleteJobs(self, job_id, slice_hrn):
530         if not job_id or job_id is -1:
531             return
532         username  = slice_hrn.split(".")[-1].rstrip("_slice")
533         reqdict = {}
534         reqdict['method'] = "delete"
535         reqdict['strval'] = str(job_id)
536        
537         answer = self.oar.POSTRequestToOARRestAPI('DELETE_jobs_id', \
538                                                     reqdict,username)
539         logger.debug("SLABDRIVER \tDeleteJobs jobid  %s \r\n answer %s username %s"  \
540                                                 %(job_id,answer, username))
541         return answer
542
543             
544         
545         ##TODO : Unused GetJobsId ? SA 05/07/12
546     #def GetJobsId(self, job_id, username = None ):
547         #"""
548         #Details about a specific job. 
549         #Includes details about submission time, jot type, state, events, 
550         #owner, assigned ressources, walltime etc...
551             
552         #"""
553         #req = "GET_jobs_id"
554         #node_list_k = 'assigned_network_address'
555         ##Get job info from OAR    
556         #job_info = self.oar.parser.SendRequest(req, job_id, username)
557
558         #logger.debug("SLABDRIVER \t GetJobsId  %s " %(job_info))
559         #try:
560             #if job_info['state'] == 'Terminated':
561                 #logger.debug("SLABDRIVER \t GetJobsId job %s TERMINATED"\
562                                                             #%(job_id))
563                 #return None
564             #if job_info['state'] == 'Error':
565                 #logger.debug("SLABDRIVER \t GetJobsId ERROR message %s "\
566                                                             #%(job_info))
567                 #return None
568                                                             
569         #except KeyError:
570             #logger.error("SLABDRIVER \tGetJobsId KeyError")
571             #return None 
572         
573         #parsed_job_info  = self.get_info_on_reserved_nodes(job_info, \
574                                                             #node_list_k)
575         ##Replaces the previous entry 
576         ##"assigned_network_address" / "reserved_resources"
577         ##with "node_ids"
578         #job_info.update({'node_ids':parsed_job_info[node_list_k]})
579         #del job_info[node_list_k]
580         #logger.debug(" \r\nSLABDRIVER \t GetJobsId job_info %s " %(job_info))
581         #return job_info
582
583         
584     def GetJobsResources(self, job_id, username = None):
585         #job_resources=['reserved_resources', 'assigned_resources',\
586                             #'job_id', 'job_uri', 'assigned_nodes',\
587                              #'api_timestamp']
588         #assigned_res = ['resource_id', 'resource_uri']
589         #assigned_n = ['node', 'node_uri']
590
591         req = "GET_jobs_id_resources"
592         node_list_k = 'reserved_resources' 
593                
594         #Get job resources list from OAR    
595         node_id_list = self.oar.parser.SendRequest(req, job_id, username)
596         logger.debug("SLABDRIVER \t GetJobsResources  %s " %(node_id_list))
597         
598         hostname_list = \
599             self.__get_hostnames_from_oar_node_ids(node_id_list)
600         
601         #parsed_job_info  = self.get_info_on_reserved_nodes(job_info, \
602                                                         #node_list_k)
603         #Replaces the previous entry "assigned_network_address" / 
604         #"reserved_resources"
605         #with "node_ids"
606         job_info = {'node_ids': hostname_list}
607
608         return job_info
609
610             
611     def get_info_on_reserved_nodes(self, job_info, node_list_name):
612         #Get the list of the testbed nodes records and make a 
613         #dictionnary keyed on the hostname out of it
614         node_list_dict = self.GetNodes() 
615         #node_hostname_list = []
616         node_hostname_list = [node['hostname'] for node in node_list_dict] 
617         #for node in node_list_dict:
618             #node_hostname_list.append(node['hostname'])
619         node_dict = dict(zip(node_hostname_list, node_list_dict))
620         try :
621             reserved_node_hostname_list = []
622             for index in range(len(job_info[node_list_name])):
623                #job_info[node_list_name][k] = 
624                 reserved_node_hostname_list[index] = \
625                         node_dict[job_info[node_list_name][index]]['hostname']
626                             
627             logger.debug("SLABDRIVER \t get_info_on_reserved_nodes \
628                         reserved_node_hostname_list %s" \
629                         %(reserved_node_hostname_list))
630         except KeyError:
631             logger.error("SLABDRIVER \t get_info_on_reserved_nodes KEYERROR " )
632             
633         return reserved_node_hostname_list  
634             
635     def GetNodesCurrentlyInUse(self):
636         """Returns a list of all the nodes already involved in an oar job"""
637         return self.oar.parser.SendRequest("GET_running_jobs") 
638     
639     def __get_hostnames_from_oar_node_ids(self, resource_id_list ):
640         full_nodes_dict_list = self.GetNodes()
641         #Put the full node list into a dictionary keyed by oar node id
642         oar_id_node_dict = {}
643         for node in full_nodes_dict_list:
644             oar_id_node_dict[node['oar_id']] = node
645             
646         logger.debug("SLABDRIVER \t  __get_hostnames_from_oar_node_ids\
647                         oar_id_node_dict %s" %(oar_id_node_dict))
648         hostname_list = []
649         hostname_dict_list = [] 
650         for resource_id in resource_id_list:
651             hostname_dict_list.append({'hostname' : \
652                     oar_id_node_dict[resource_id]['hostname'], 
653                     'site_id' :  oar_id_node_dict[resource_id]['site']})
654             
655             #hostname_list.append(oar_id_node_dict[resource_id]['hostname'])
656         return hostname_dict_list 
657         
658     def GetReservedNodes(self):
659         #Get the nodes in use and the reserved nodes
660         reservation_dict_list = \
661                         self.oar.parser.SendRequest("GET_reserved_nodes")
662         
663         
664         for resa in reservation_dict_list:
665             logger.debug ("GetReservedNodes resa %s"%(resa))
666             #dict list of hostnames and their site
667             resa['reserved_nodes'] = \
668                 self.__get_hostnames_from_oar_node_ids(resa['resource_ids'])
669                 
670         #del resa['resource_ids']
671         return reservation_dict_list
672      
673     def GetNodes(self, node_filter_dict = None, return_fields_list = None):
674         """
675         node_filter_dict : dictionnary of lists
676         
677         """
678         node_dict_by_id = self.oar.parser.SendRequest("GET_resources_full")
679         node_dict_list = node_dict_by_id.values()
680         
681         #No  filtering needed return the list directly
682         if not (node_filter_dict or return_fields_list):
683             return node_dict_list
684         
685         return_node_list = []
686         if node_filter_dict:
687             for filter_key in node_filter_dict:
688                 try:
689                     #Filter the node_dict_list by each value contained in the 
690                     #list node_filter_dict[filter_key]
691                     for value in node_filter_dict[filter_key]:
692                         for node in node_dict_list:
693                             if node[filter_key] == value:
694                                 if return_fields_list :
695                                     tmp = {}
696                                     for k in return_fields_list:
697                                         tmp[k] = node[k]     
698                                     return_node_list.append(tmp)
699                                 else:
700                                     return_node_list.append(node)
701                 except KeyError:
702                     logger.log_exc("GetNodes KeyError")
703                     return
704
705
706         return return_node_list
707     
708   
709     def GetSites(self, site_filter_name_list = None, return_fields_list = None):
710         site_dict = self.oar.parser.SendRequest("GET_sites")
711         #site_dict : dict where the key is the sit ename
712         return_site_list = []
713         if not ( site_filter_name_list or return_fields_list):
714             return_site_list = site_dict.values()
715             return return_site_list
716         
717         for site_filter_name in site_filter_name_list:
718             if site_filter_name in site_dict:
719                 if return_fields_list:
720                     for field in return_fields_list:
721                         tmp = {}
722                         try:
723                             tmp[field] = site_dict[site_filter_name][field]
724                         except KeyError:
725                             logger.error("GetSites KeyError %s "%(field))
726                             return None
727                     return_site_list.append(tmp)
728                 else:
729                     return_site_list.append( site_dict[site_filter_name])
730             
731
732         return return_site_list
733     #warning return_fields_list paramr emoved  (Not used)     
734     def GetSlices(self, slice_filter = None, slice_filter_type = None):
735     #def GetSlices(self, slice_filter = None, slice_filter_type = None, \
736                                             #return_fields_list = None):
737         """ Get the slice records from the slab db. 
738         Returns a slice ditc if slice_filter  and slice_filter_type 
739         are specified.
740         Returns a list of slice dictionnaries if there are no filters
741         specified. 
742        
743         """
744         return_slice_list = []
745         slicerec  = {}
746         slicerec_dict = {}
747         authorized_filter_types_list = ['slice_hrn', 'record_id_user']
748         logger.debug("SLABDRIVER \tGetSlices authorized_filter_types_list %s"\
749                                                 %(authorized_filter_types_list))
750         if slice_filter_type in authorized_filter_types_list:
751             if slice_filter_type == 'slice_hrn':
752                 slicerec = slab_dbsession.query(SliceSenslab).filter_by(slice_hrn = slice_filter).first()
753                                         
754             if slice_filter_type == 'record_id_user':
755                 slicerec = slab_dbsession.query(SliceSenslab).filter_by(record_id_user = slice_filter).first()
756                 
757             if slicerec:
758                 #warning pylint OK
759                 slicerec_dict = slicerec.dump_sqlalchemyobj_to_dict() 
760                 logger.debug("SLABDRIVER \tGetSlices slicerec_dict %s" \
761                                                         %(slicerec_dict))
762                 #Get login 
763                 login = slicerec_dict['slice_hrn'].split(".")[1].split("_")[0]
764                 logger.debug("\r\n SLABDRIVER \tGetSlices login %s \
765                                                 slice record %s" \
766                                                 %(login, slicerec_dict))
767                 if slicerec_dict['oar_job_id'] is not -1:
768                     #Check with OAR the status of the job if a job id is in 
769                     #the slice record 
770                     rslt = self.GetJobsResources(slicerec_dict['oar_job_id'], \
771                                                             username = login)
772
773                     if rslt :
774                         slicerec_dict.update(rslt)
775                         slicerec_dict.update({'hrn':\
776                                             str(slicerec_dict['slice_hrn'])})
777                         #If GetJobsResources is empty, this means the job is 
778                         #now in the 'Terminated' state
779                         #Update the slice record
780                     else :
781                         self.db.update_job(slice_filter, job_id = -1)
782                         slicerec_dict['oar_job_id'] = -1
783                         slicerec_dict.\
784                                 update({'hrn':str(slicerec_dict['slice_hrn'])})
785             
786                 try:
787                     slicerec_dict['node_ids'] = slicerec_dict['node_list']
788                 except KeyError:
789                     pass
790                 
791                 logger.debug("SLABDRIVER.PY  \tGetSlices  slicerec_dict  %s"\
792                                                             %(slicerec_dict))
793                               
794             return slicerec_dict
795                 
796                 
797         else:
798             return_slice_list = slab_dbsession.query(SliceSenslab).all()
799
800             logger.debug("SLABDRIVER.PY  \tGetSlices slices %s \
801                         slice_filter %s " %(return_slice_list, slice_filter))
802         
803         #if return_fields_list:
804             #return_slice_list  = parse_filter(sliceslist, \
805                                 #slice_filter,'slice', return_fields_list)
806
807         return return_slice_list
808
809             
810
811         
812     
813     def testbed_name (self): return self.hrn
814          
815     # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
816     def aggregate_version (self):
817         version_manager = VersionManager()
818         ad_rspec_versions = []
819         request_rspec_versions = []
820         for rspec_version in version_manager.versions:
821             if rspec_version.content_type in ['*', 'ad']:
822                 ad_rspec_versions.append(rspec_version.to_dict())
823             if rspec_version.content_type in ['*', 'request']:
824                 request_rspec_versions.append(rspec_version.to_dict()) 
825         return {
826             'testbed':self.testbed_name(),
827             'geni_request_rspec_versions': request_rspec_versions,
828             'geni_ad_rspec_versions': ad_rspec_versions,
829             }
830           
831           
832           
833           
834           
835           
836     ##
837     # Convert SFA fields to PLC fields for use when registering up updating
838     # registry record in the PLC database
839     #
840     # @param type type of record (user, slice, ...)
841     # @param hrn human readable name
842     # @param sfa_fields dictionary of SFA fields
843     # @param slab_fields dictionary of PLC fields (output)
844
845     def sfa_fields_to_slab_fields(self, sfa_type, hrn, record):
846
847         def convert_ints(tmpdict, int_fields):
848             for field in int_fields:
849                 if field in tmpdict:
850                     tmpdict[field] = int(tmpdict[field])
851
852         slab_record = {}
853         #for field in record:
854         #    slab_record[field] = record[field]
855  
856         if sfa_type == "slice":
857             #instantion used in get_slivers ? 
858             if not "instantiation" in slab_record:
859                 slab_record["instantiation"] = "senslab-instantiated"
860             #slab_record["hrn"] = hrn_to_pl_slicename(hrn)     
861             #Unused hrn_to_pl_slicename because Slab's hrn already in the appropriate form SA 23/07/12
862             slab_record["hrn"] = hrn 
863             logger.debug("SLABDRIVER.PY sfa_fields_to_slab_fields \
864                         slab_record %s  " %(slab_record['hrn']))
865             if "url" in record:
866                 slab_record["url"] = record["url"]
867             if "description" in record:
868                 slab_record["description"] = record["description"]
869             if "expires" in record:
870                 slab_record["expires"] = int(record["expires"])
871                 
872         #nodes added by OAR only and then imported to SFA
873         #elif type == "node":
874             #if not "hostname" in slab_record:
875                 #if not "hostname" in record:
876                     #raise MissingSfaInfo("hostname")
877                 #slab_record["hostname"] = record["hostname"]
878             #if not "model" in slab_record:
879                 #slab_record["model"] = "geni"
880                 
881         #One authority only 
882         #elif type == "authority":
883             #slab_record["login_base"] = hrn_to_slab_login_base(hrn)
884
885             #if not "name" in slab_record:
886                 #slab_record["name"] = hrn
887
888             #if not "abbreviated_name" in slab_record:
889                 #slab_record["abbreviated_name"] = hrn
890
891             #if not "enabled" in slab_record:
892                 #slab_record["enabled"] = True
893
894             #if not "is_public" in slab_record:
895                 #slab_record["is_public"] = True
896
897         return slab_record
898
899     
900
901             
902     def __transforms_timestamp_into_date(self, xp_utc_timestamp = None):
903         """ Transforms unix timestamp into valid OAR date format """
904         
905         #Used in case of a scheduled experiment (not immediate)
906         #To run an XP immediately, don't specify date and time in RSpec 
907         #They will be set to None. 
908         if xp_utc_timestamp:
909             #transform the xp_utc_timestamp into server readable time  
910             xp_server_readable_date = datetime.fromtimestamp(int(\
911                                 xp_utc_timestamp)).strftime(self.time_format)
912
913             return xp_server_readable_date
914             
915         else:
916             return None
917                                
918     def LaunchExperimentOnOAR(self, slice_dict, added_nodes, slice_user=None):
919         """ Creates the structure needed for a correct POST on OAR.
920         Makes the timestamp transformation into the appropriate format.
921         Sends the POST request to create the job with the resources in 
922         added_nodes.
923         
924         """
925         site_list = []
926         nodeid_list = []
927         resource = ""
928         reqdict = {}
929         slice_name = slice_dict['name']
930         try:
931             slot = slice_dict['timeslot'] 
932             logger.debug("SLABDRIVER.PY \tLaunchExperimentOnOAR \
933                                                     slot %s" %(slot))
934         except KeyError:
935             #Running on default parameters
936             #XP immediate , 10 mins
937             slot = {    'date':None, 'start_time':None,
938                         'timezone':None, 'duration':None }#10 min 
939         
940         reqdict['workdir'] = '/tmp'   
941         reqdict['resource'] = "{network_address in ("   
942
943         for node in added_nodes: 
944             logger.debug("OARrestapi \tLaunchExperimentOnOAR \
945                                                             node %s" %(node))
946
947             #Get the ID of the node : remove the root auth and put 
948             # the site in a separate list.
949             # NT: it's not clear for me if the nodenames will have the senslab 
950             #prefix so lets take the last part only, for now.
951
952             # Again here it's not clear if nodes will be prefixed with <site>_, 
953             #lets split and tanke the last part for now.
954             #s=lastpart.split("_")
955
956             nodeid = node
957             reqdict['resource'] += "'" + nodeid + "', "
958             nodeid_list.append(nodeid)
959
960         custom_length = len(reqdict['resource'])- 2
961         reqdict['resource'] = reqdict['resource'][0:custom_length] + \
962                                             ")}/nodes=" + str(len(nodeid_list))
963                                             
964         def __process_walltime(duration=None):
965             """ Calculates the walltime in seconds from the duration in H:M:S
966                 specified in the RSpec.
967                 
968             """
969             if duration:
970                 walltime = duration.split(":")
971                 # Fixing the walltime by adding a few delays. First put the walltime 
972                 # in seconds oarAdditionalDelay = 20; additional delay for 
973                 # /bin/sleep command to
974                 # take in account  prologue and epilogue scripts execution
975                 # int walltimeAdditionalDelay = 120;  additional delay
976         
977                 desired_walltime = int(walltime[0])*3600 + int(walltime[1]) * 60 +\
978                                                                     int(walltime[2])
979                 total_walltime = desired_walltime + 140 #+2 min 20
980                 sleep_walltime = desired_walltime + 20 #+20 sec
981                 logger.debug("SLABDRIVER \t__process_walltime desired_walltime %s\
982                                         total_walltime %s sleep_walltime %s  "\
983                                             %(desired_walltime, total_walltime, \
984                                                             sleep_walltime))
985                 #Put the walltime back in str form
986                 #First get the hours
987                 walltime[0] = str(total_walltime / 3600)
988                 total_walltime = total_walltime - 3600 * int(walltime[0])
989                 #Get the remaining minutes
990                 walltime[1] = str(total_walltime / 60)
991                 total_walltime = total_walltime - 60 * int(walltime[1])
992                 #Get the seconds
993                 walltime[2] = str(total_walltime)
994                 logger.debug("SLABDRIVER \t__process_walltime walltime %s "\
995                                                 %(walltime))
996             else:
997                 #automatically set 10min  +2 min 20
998                 walltime[0] = '0'
999                 walltime[1] = '12' 
1000                 walltime[2] = '20'
1001                 sleep_walltime = '620'
1002                 
1003             return walltime, sleep_walltime
1004                 
1005         #if slot['duration']:
1006         walltime, sleep_walltime = __process_walltime(duration = \
1007                                                             slot['duration'])
1008         #else: 
1009             #walltime, sleep_walltime = self.__process_walltime(duration = None)
1010             
1011         reqdict['resource'] += ",walltime=" + str(walltime[0]) + \
1012                             ":" + str(walltime[1]) + ":" + str(walltime[2])
1013         reqdict['script_path'] = "/bin/sleep " + str(sleep_walltime)
1014        
1015                 
1016                 
1017         #In case of a scheduled experiment (not immediate)
1018         #To run an XP immediately, don't specify date and time in RSpec 
1019         #They will be set to None. 
1020         server_timestamp, server_tz = self.GetTimezone()
1021         if slot['date'] and slot['start_time']:
1022             if slot['timezone'] is '' or slot['timezone'] is None:
1023                 #assume it is server timezone
1024                 from_zone = tz.gettz(server_tz) 
1025                 logger.warning("SLABDRIVER \tLaunchExperimentOnOAR  timezone \
1026                 not specified  server_tz %s from_zone  %s" \
1027                 %(server_tz, from_zone)) 
1028             else:
1029                 #Get zone of the user from the reservation time given 
1030                 #in the rspec
1031                 from_zone = tz.gettz(slot['timezone'])  
1032                    
1033             date = str(slot['date']) + " " + str(slot['start_time'])
1034             user_datetime = datetime.strptime(date, self.time_format)
1035             user_datetime = user_datetime.replace(tzinfo = from_zone)
1036             
1037             #Convert to server zone
1038
1039             to_zone = tz.gettz(server_tz)
1040             reservation_date = user_datetime.astimezone(to_zone)
1041             #Readable time accpeted by OAR
1042             reqdict['reservation'] = reservation_date.strftime(self.time_format)
1043         
1044             logger.debug("SLABDRIVER \tLaunchExperimentOnOAR \
1045                         reqdict['reservation'] %s " %(reqdict['reservation']))
1046             
1047         else:
1048             # Immediate XP. Not need to add special parameters.
1049             # normally not used in SFA
1050        
1051             pass
1052         
1053
1054         reqdict['type'] = "deploy" 
1055         reqdict['directory'] = ""
1056         reqdict['name'] = "TestSandrine"
1057        
1058          
1059         # first step : start the OAR job and update the job 
1060         logger.debug("SLABDRIVER.PY \tLaunchExperimentOnOAR reqdict %s\
1061                              \r\n site_list   %s"  %(reqdict, site_list))  
1062        
1063         answer = self.oar.POSTRequestToOARRestAPI('POST_job', \
1064                                                             reqdict, slice_user)
1065         logger.debug("SLABDRIVER \tLaunchExperimentOnOAR jobid   %s " %(answer))
1066         try:       
1067             jobid = answer['id']
1068         except KeyError:
1069             logger.log_exc("SLABDRIVER \tLaunchExperimentOnOAR \
1070                                 Impossible to create job  %s "  %(answer))
1071             return
1072         
1073         logger.debug("SLABDRIVER \tLaunchExperimentOnOAR jobid %s \
1074                 added_nodes %s slice_user %s" %(jobid, added_nodes, slice_user))
1075         self.db.update_job( slice_name, jobid, added_nodes)
1076         
1077           
1078         # second step : configure the experiment
1079         # we need to store the nodes in a yaml (well...) file like this :
1080         # [1,56,23,14,45,75] with name /tmp/sfa<jobid>.json
1081         job_file = open('/tmp/sfa/'+ str(jobid) + '.json', 'w')
1082         job_file.write('[')
1083         job_file.write(str(added_nodes[0].strip('node')))
1084         for node in added_nodes[1:len(added_nodes)] :
1085             job_file.write(', '+ node.strip('node'))
1086         job_file.write(']')
1087         job_file.close()
1088         
1089         # third step : call the senslab-experiment wrapper
1090         #command= "java -jar target/sfa-1.0-jar-with-dependencies.jar 
1091         # "+str(jobid)+" "+slice_user
1092         javacmdline = "/usr/bin/java"
1093         jarname = \
1094             "/opt/senslabexperimentwrapper/sfa-1.0-jar-with-dependencies.jar"
1095         #ret=subprocess.check_output(["/usr/bin/java", "-jar", ", \
1096                                                     #str(jobid), slice_user])
1097         output = subprocess.Popen([javacmdline, "-jar", jarname, str(jobid), \
1098                             slice_user],stdout=subprocess.PIPE).communicate()[0]
1099
1100         logger.debug("SLABDRIVER \tLaunchExperimentOnOAR wrapper returns%s " \
1101                                                                  %(output))
1102         return 
1103                  
1104  
1105     #Delete the jobs and updates the job id in the senslab table
1106     #to set it to -1  
1107     #Does not clear the node list 
1108     def DeleteSliceFromNodes(self, slice_record):
1109          # Get user information
1110        
1111         self.DeleteJobs(slice_record['oar_job_id'], slice_record['hrn'])
1112         self.db.update_job(slice_record['hrn'], job_id = -1)
1113         return   
1114     
1115  
1116     def GetLeaseGranularity(self):
1117         """ Returns the granularity of Senslab testbed.
1118         Defined in seconds. """
1119         
1120         grain = 60 
1121         return grain
1122     
1123     def GetLeases(self, lease_filter_dict=None, return_fields_list=None):
1124         unfiltered_reservation_list = self.GetReservedNodes()
1125         reservation_list = []
1126         #Find the slice associated with this user senslab ldap uid
1127         logger.debug(" SLABDRIVER.PY \tGetLeases ")
1128         for resa in unfiltered_reservation_list:
1129             ldap_info = self.ldap.LdapSearch('(uid='+resa['user']+')')
1130             ldap_info = ldap_info[0][1]
1131
1132             user = dbsession.query(RegUser).filter_by(email = \
1133                                                 ldap_info['mail'][0]).first()
1134             #Separated in case user not in database : record_id not defined SA 17/07//12
1135             query_slice_info = slab_dbsession.query(SliceSenslab).filter_by(record_id_user = user.record_id)
1136             if query_slice_info:
1137                 slice_info = query_slice_info.first()
1138                 
1139             #Put the slice_urn 
1140             resa['slice_id'] = hrn_to_urn(slice_info.slice_hrn, 'slice')
1141             resa['component_id_list'] = []
1142             #Transform the hostnames into urns (component ids)
1143             for node in resa['reserved_nodes']:
1144                 resa['component_id_list'].append(hostname_to_urn(self.hrn, \
1145                          self.root_auth, node['hostname']))
1146
1147         
1148         #Filter the reservation list if necessary
1149         #Returns all the leases associated with a given slice
1150         if lease_filter_dict:
1151             logger.debug("SLABDRIVER \tGetLeases lease_filter_dict %s"\
1152                                             %(lease_filter_dict))
1153             for resa in unfiltered_reservation_list:
1154                 if lease_filter_dict['name'] == resa['slice_id']:
1155                     reservation_list.append(resa)
1156         else:
1157             reservation_list = unfiltered_reservation_list
1158             
1159         logger.debug(" SLABDRIVER.PY \tGetLeases reservation_list %s"\
1160                                                     %(reservation_list))
1161         return reservation_list
1162             
1163     def augment_records_with_testbed_info (self, sfa_records):
1164         return self.fill_record_info (sfa_records)
1165     
1166     def fill_record_info(self, record_list):
1167         """
1168         Given a SFA record, fill in the senslab specific and SFA specific
1169         fields in the record. 
1170         """
1171                     
1172         logger.debug("SLABDRIVER \tfill_record_info records %s " %(record_list))
1173         if not isinstance(record_list, list):
1174             record_list = [record_list]
1175             
1176         try:
1177             for record in record_list:
1178                 #If the record is a SFA slice record, then add information 
1179                 #about the user of this slice. This kind of 
1180                 #information is in the Senslab's DB.
1181                 if str(record['type']) == 'slice':
1182                     #Get slab slice record.
1183                     recslice = self.GetSlices(slice_filter = \
1184                                                 str(record['hrn']),\
1185                                                 slice_filter_type = 'slice_hrn')
1186                     recuser = dbsession.query(RegRecord).filter_by(record_id = \
1187                                             recslice['record_id_user']).first()
1188                     logger.debug( "SLABDRIVER.PY \t fill_record_info SLICE \
1189                                                 rec %s \r\n \r\n" %(recslice)) 
1190                     record.update({'PI':[recuser.hrn],
1191                             'researcher': [recuser.hrn],
1192                             'name':record['hrn'], 
1193                             'oar_job_id':recslice['oar_job_id'],
1194                             'node_ids': [],
1195                             'person_ids':[recslice['record_id_user']],
1196                             'geni_urn':'',  #For client_helper.py compatibility
1197                             'keys':'',  #For client_helper.py compatibility
1198                             'key_ids':''})  #For client_helper.py compatibility
1199                     
1200                 elif str(record['type']) == 'user':
1201                     #The record is a SFA user record.
1202                     #Get the information about his slice from Senslab's DB
1203                     #and add it to the user record.
1204                     recslice = self.GetSlices(\
1205                             slice_filter = record['record_id'],\
1206                             slice_filter_type = 'record_id_user')
1207                                             
1208                     logger.debug( "SLABDRIVER.PY \t fill_record_info user \
1209                                                 rec %s \r\n \r\n" %(recslice)) 
1210                     #Append slice record in records list, 
1211                     #therefore fetches user and slice info again(one more loop)
1212                     #Will update PIs and researcher for the slice
1213                     recuser = dbsession.query(RegRecord).filter_by(record_id = \
1214                                                 recslice['record_id_user']).first()
1215                     recslice.update({'PI':[recuser.hrn],
1216                     'researcher': [recuser.hrn],
1217                     'name':record['hrn'], 
1218                     'oar_job_id':recslice['oar_job_id'],
1219                     'node_ids': [],
1220                     'person_ids':[recslice['record_id_user']]})
1221
1222                     #GetPersons takes [] as filters 
1223                     #user_slab = self.GetPersons([{'hrn':recuser.hrn}])
1224                     user_slab = self.GetPersons([record])
1225     
1226                     recslice.update({'type':'slice', \
1227                                                 'hrn':recslice['slice_hrn']})
1228                     record.update(user_slab[0])
1229                     #For client_helper.py compatibility
1230                     record.update( { 'geni_urn':'',
1231                     'keys':'',
1232                     'key_ids':'' })                
1233                     record_list.append(recslice)
1234                     
1235                     logger.debug("SLABDRIVER.PY \tfill_record_info ADDING SLICE\
1236                                 INFO TO USER records %s" %(record_list)) 
1237                         
1238
1239         except TypeError, error:
1240             logger.log_exc("SLABDRIVER \t fill_record_info  EXCEPTION %s"\
1241                                                                      %(error))
1242         
1243         return
1244         
1245         #self.fill_record_slab_info(records)
1246         
1247         
1248         
1249
1250     
1251     #TODO Update membership?    update_membership_list SA 05/07/12
1252     #def update_membership_list(self, oldRecord, record, listName, addFunc, \
1253                                                                 #delFunc):
1254         ## get a list of the HRNs tht are members of the old and new records
1255         #if oldRecord:
1256             #oldList = oldRecord.get(listName, [])
1257         #else:
1258             #oldList = []     
1259         #newList = record.get(listName, [])
1260
1261         ## if the lists are the same, then we don't have to update anything
1262         #if (oldList == newList):
1263             #return
1264
1265         ## build a list of the new person ids, by looking up each person to get
1266         ## their pointer
1267         #newIdList = []
1268         #table = SfaTable()
1269         #records = table.find({'type': 'user', 'hrn': newList})
1270         #for rec in records:
1271             #newIdList.append(rec['pointer'])
1272
1273         ## build a list of the old person ids from the person_ids field 
1274         #if oldRecord:
1275             #oldIdList = oldRecord.get("person_ids", [])
1276             #containerId = oldRecord.get_pointer()
1277         #else:
1278             ## if oldRecord==None, then we are doing a Register, instead of an
1279             ## update.
1280             #oldIdList = []
1281             #containerId = record.get_pointer()
1282
1283     ## add people who are in the new list, but not the oldList
1284         #for personId in newIdList:
1285             #if not (personId in oldIdList):
1286                 #addFunc(self.plauth, personId, containerId)
1287
1288         ## remove people who are in the old list, but not the new list
1289         #for personId in oldIdList:
1290             #if not (personId in newIdList):
1291                 #delFunc(self.plauth, personId, containerId)
1292
1293     #def update_membership(self, oldRecord, record):
1294        
1295         #if record.type == "slice":
1296             #self.update_membership_list(oldRecord, record, 'researcher',
1297                                         #self.users.AddPersonToSlice,
1298                                         #self.users.DeletePersonFromSlice)
1299         #elif record.type == "authority":
1300             ## xxx TODO
1301             #pass
1302
1303 ### thierry
1304 # I don't think you plan on running a component manager at this point
1305 # let me clean up the mess of ComponentAPI that is deprecated anyways
1306
1307
1308 #TODO FUNCTIONS SECTION 04/07/2012 SA
1309
1310     #TODO : Is UnBindObjectFromPeer still necessary ? Currently does nothing
1311     #04/07/2012 SA
1312     def UnBindObjectFromPeer(self, auth, object_type, object_id, shortname):
1313         """ This method is a hopefully temporary hack to let the sfa correctly
1314         detach the objects it creates from a remote peer object. This is 
1315         needed so that the sfa federation link can work in parallel with 
1316         RefreshPeer, as RefreshPeer depends on remote objects being correctly 
1317         marked.
1318         Parameters:
1319         auth : struct, API authentication structure
1320             AuthMethod : string, Authentication method to use 
1321         object_type : string, Object type, among 'site','person','slice',
1322         'node','key'
1323         object_id : int, object_id
1324         shortname : string, peer shortname 
1325         FROM PLC DOC
1326         
1327         """
1328         logger.warning("SLABDRIVER \tUnBindObjectFromPeer EMPTY-\
1329                         DO NOTHING \r\n ")
1330         return 
1331     
1332     #TODO Is BindObjectToPeer still necessary ? Currently does nothing 
1333     #04/07/2012 SA
1334     def BindObjectToPeer(self, auth, object_type, object_id, shortname=None, \
1335                                                     remote_object_id=None):
1336         """This method is a hopefully temporary hack to let the sfa correctly 
1337         attach the objects it creates to a remote peer object. This is needed 
1338         so that the sfa federation link can work in parallel with RefreshPeer, 
1339         as RefreshPeer depends on remote objects being correctly marked.
1340         Parameters:
1341         shortname : string, peer shortname 
1342         remote_object_id : int, remote object_id, set to 0 if unknown 
1343         FROM PLC API DOC
1344         
1345         """
1346         logger.warning("SLABDRIVER \tBindObjectToPeer EMPTY - DO NOTHING \r\n ")
1347         return
1348     
1349     #TODO UpdateSlice 04/07/2012 SA
1350     #Funciton should delete and create another job since oin senslab slice=job
1351     def UpdateSlice(self, auth, slice_id_or_name, slice_fields=None):    
1352         """Updates the parameters of an existing slice with the values in 
1353         slice_fields.
1354         Users may only update slices of which they are members. 
1355         PIs may update any of the slices at their sites, or any slices of 
1356         which they are members. Admins may update any slice.
1357         Only PIs and admins may update max_nodes. Slices cannot be renewed
1358         (by updating the expires parameter) more than 8 weeks into the future.
1359          Returns 1 if successful, faults otherwise.
1360         FROM PLC API DOC
1361         
1362         """  
1363         logger.warning("SLABDRIVER UpdateSlice EMPTY - DO NOTHING \r\n ")
1364         return
1365     
1366     #TODO UpdatePerson 04/07/2012 SA
1367     def UpdatePerson(self, auth, person_id_or_email, person_fields=None):
1368         """Updates a person. Only the fields specified in person_fields 
1369         are updated, all other fields are left untouched.
1370         Users and techs can only update themselves. PIs can only update
1371         themselves and other non-PIs at their sites.
1372         Returns 1 if successful, faults otherwise.
1373         FROM PLC API DOC
1374          
1375         """
1376         logger.warning("SLABDRIVER UpdatePerson EMPTY - DO NOTHING \r\n ")
1377         return
1378     
1379     #TODO GetKeys 04/07/2012 SA
1380     def GetKeys(self, auth, key_filter=None, return_fields=None):
1381         """Returns an array of structs containing details about keys. 
1382         If key_filter is specified and is an array of key identifiers, 
1383         or a struct of key attributes, only keys matching the filter 
1384         will be returned. If return_fields is specified, only the 
1385         specified details will be returned.
1386
1387         Admin may query all keys. Non-admins may only query their own keys.
1388         FROM PLC API DOC
1389         
1390         """
1391         logger.warning("SLABDRIVER  GetKeys EMPTY - DO NOTHING \r\n ")
1392         return
1393     
1394     #TODO DeleteKey 04/07/2012 SA
1395     def DeleteKey(self, auth, key_id):
1396         """  Deletes a key.
1397          Non-admins may only delete their own keys.
1398          Returns 1 if successful, faults otherwise.
1399          FROM PLC API DOC
1400          
1401         """
1402         logger.warning("SLABDRIVER  DeleteKey EMPTY - DO NOTHING \r\n ")
1403         return
1404
1405     
1406     #TODO : Check rights to delete person 
1407     def DeletePerson(self, auth, person_record):
1408         """ Disable an existing account in senslab LDAP.
1409         Users and techs can only delete themselves. PIs can only 
1410         delete themselves and other non-PIs at their sites. 
1411         ins can delete anyone.
1412         Returns 1 if successful, faults otherwise.
1413         FROM PLC API DOC
1414         
1415         """
1416         #Disable user account in senslab LDAP
1417         ret = self.ldap.LdapMarkUserAsDeleted(person_record)
1418         logger.warning("SLABDRIVER DeletePerson %s " %(person_record))
1419         return ret
1420     
1421     #TODO Check DeleteSlice, check rights 05/07/2012 SA
1422     def DeleteSlice(self, auth, slice_record):
1423         """ Deletes the specified slice.
1424          Senslab : Kill the job associated with the slice if there is one
1425          using DeleteSliceFromNodes.
1426          Updates the slice record in slab db to remove the slice nodes.
1427          
1428          Users may only delete slices of which they are members. PIs may 
1429          delete any of the slices at their sites, or any slices of which 
1430          they are members. Admins may delete any slice.
1431          Returns 1 if successful, faults otherwise.
1432          FROM PLC API DOC
1433         
1434         """
1435         self.DeleteSliceFromNodes(slice_record)
1436         self.db.update_job(slice_record['hrn'], job_id = -1, nodes = [])
1437         logger.warning("SLABDRIVER DeleteSlice %s "%(slice_record))
1438         return
1439     
1440     #TODO AddPerson 04/07/2012 SA
1441     def AddPerson(self, auth, person_fields=None):
1442         """Adds a new account. Any fields specified in person_fields are used, 
1443         otherwise defaults are used.
1444         Accounts are disabled by default. To enable an account, 
1445         use UpdatePerson().
1446         Returns the new person_id (> 0) if successful, faults otherwise. 
1447         FROM PLC API DOC
1448         
1449         """
1450         logger.warning("SLABDRIVER AddPerson EMPTY - DO NOTHING \r\n ")
1451         return
1452     
1453     #TODO AddPersonToSite 04/07/2012 SA
1454     def AddPersonToSite (self, auth, person_id_or_email, \
1455                                                 site_id_or_login_base=None):
1456         """  Adds the specified person to the specified site. If the person is 
1457         already a member of the site, no errors are returned. Does not change 
1458         the person's primary site.
1459         Returns 1 if successful, faults otherwise.
1460         FROM PLC API DOC
1461         
1462         """
1463         logger.warning("SLABDRIVER AddPersonToSite EMPTY - DO NOTHING \r\n ")
1464         return
1465     
1466     #TODO AddRoleToPerson : Not sure if needed in senslab 04/07/2012 SA
1467     def AddRoleToPerson(self, auth, role_id_or_name, person_id_or_email):
1468         """Grants the specified role to the person.
1469         PIs can only grant the tech and user roles to users and techs at their 
1470         sites. Admins can grant any role to any user.
1471         Returns 1 if successful, faults otherwise.
1472         FROM PLC API DOC
1473         
1474         """
1475         logger.warning("SLABDRIVER AddRoleToPerson EMPTY - DO NOTHING \r\n ")
1476         return
1477     
1478     #TODO AddPersonKey 04/07/2012 SA
1479     def AddPersonKey(self, auth, person_id_or_email, key_fields=None):
1480         """Adds a new key to the specified account.
1481         Non-admins can only modify their own keys.
1482         Returns the new key_id (> 0) if successful, faults otherwise.
1483         FROM PLC API DOC
1484         
1485         """
1486         logger.warning("SLABDRIVER AddPersonKey EMPTY - DO NOTHING \r\n ")
1487         return