GetSlices fix 1.
[sfa.git] / sfa / senslab / slabdriver.py
1 import sys
2
3 from sfa.util.faults import MissingSfaInfo
4 from sfa.util.sfalogging import logger
5 from sfa.storage.table import SfaTable
6 from sfa.util.defaultdict import defaultdict
7
8 from sfa.trust.certificate import *
9 from sfa.trust.credential import *
10 from sfa.trust.gid import GID
11
12 from sfa.managers.driver import Driver
13 from sfa.rspecs.version_manager import VersionManager
14 from sfa.rspecs.rspec import RSpec
15
16 from sfa.util.xrn import hrn_to_urn
17 from sfa.util.plxrn import slicename_to_hrn, hostname_to_hrn, hrn_to_pl_slicename, hrn_to_pl_login_base
18
19 ## thierry: everything that is API-related (i.e. handling incoming requests) 
20 # is taken care of 
21 # SlabDriver should be really only about talking to the senslab testbed
22
23 ## thierry : please avoid wildcard imports :)
24 from sfa.senslab.OARrestapi import  OARrestapi
25 from sfa.senslab.LDAPapi import LDAPapi
26 from sfa.senslab.SenslabImportUsers import SenslabImportUsers
27 from sfa.senslab.parsing import parse_filter
28 from sfa.senslab.slabpostgres import SlabDB
29 from sfa.senslab.slabaggregate import SlabAggregate
30 from sfa.senslab.slabslices import SlabSlices
31
32 def list_to_dict(recs, key):
33     """
34     convert a list of dictionaries into a dictionary keyed on the 
35     specified dictionary key 
36     """
37    # print>>sys.stderr, " \r\n \t\t 1list_to_dict : rec %s  \r\n \t\t list_to_dict key %s" %(recs,key)   
38     keys = [rec[key] for rec in recs]
39     #print>>sys.stderr, " \r\n \t\t list_to_dict : rec %s  \r\n \t\t list_to_dict keys %s" %(recs,keys)   
40     return dict(zip(keys, recs))
41
42 # thierry : note
43 # this inheritance scheme is so that the driver object can receive
44 # GetNodes or GetSites sorts of calls directly
45 # and thus minimize the differences in the managers with the pl version
46 class SlabDriver(Driver):
47
48     def __init__(self, config):
49         Driver.__init__ (self, config)
50         self.config=config
51         self.hrn = config.SFA_INTERFACE_HRN
52     
53         self.root_auth = config.SFA_REGISTRY_ROOT_AUTH
54
55         
56         print >>sys.stderr, "\r\n_____________ SFA SENSLAB DRIVER \r\n" 
57         # thierry - just to not break the rest of this code
58
59
60         #self.oar = OARapi()
61         self.oar = OARrestapi()
62         self.ldap = LDAPapi()
63         self.users = SenslabImportUsers()
64         self.time_format = "%Y-%m-%d %H:%M:%S"
65         self.db = SlabDB()
66         #self.logger=sfa_logger()
67         self.cache=None
68         
69
70             
71     def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
72         aggregate = SlabAggregate(self)
73         #aggregate = SlabAggregate(self)
74         slices = SlabSlices(self)
75         peer = slices.get_peer(slice_hrn)
76         sfa_peer = slices.get_sfa_peer(slice_hrn)
77         slice_record=None 
78         #print>>sys.stderr, " \r\n \r\n   create_sliver  creds %s \r\n \r\n users %s " %(creds,users)
79        
80         if not isinstance(creds, list):
81             creds = [creds]
82
83         #for cred in creds:
84             #cred_obj=Credential(string=cred)
85             #print >>sys.stderr," \r\n \r\n   create_sliver cred  %s  " %(cred)
86             #GIDcall = cred_obj.get_gid_caller()
87             #GIDobj = cred_obj.get_gid_object() 
88             #print >>sys.stderr," \r\n \r\n   create_sliver GIDobj pubkey %s hrn %s " %(GIDobj.get_pubkey().get_pubkey_string(), GIDobj.get_hrn())
89             #print >>sys.stderr," \r\n \r\n   create_sliver GIDcall pubkey %s  hrn %s" %(GIDcall.get_pubkey().get_pubkey_string(),GIDobj.get_hrn())
90
91         
92         #tmpcert = GID(string = users[0]['gid'])
93         #print >>sys.stderr," \r\n \r\n   create_sliver  tmpcer pubkey %s hrn %s " %(tmpcert.get_pubkey().get_pubkey_string(), tmpcert.get_hrn())
94            
95         if users:
96             slice_record = users[0].get('slice_record', {})
97     
98         # parse rspec
99         rspec = RSpec(rspec_string)
100         requested_attributes = rspec.version.get_slice_attributes()
101         
102         # ensure site record exists
103         #site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer, options=options)
104         # ensure slice record exists
105         slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer, options=options)
106         # ensure person records exists
107         persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer, options=options)
108         # ensure slice attributes exists
109         #slices.verify_slice_attributes(slice, requested_attributes, options=options)
110         
111         # add/remove slice from nodes
112         requested_slivers = [node.get('component_name') for node in rspec.version.get_nodes_with_slivers()]
113         nodes = slices.verify_slice_nodes(slice, requested_slivers, peer) 
114     
115       
116     
117         # handle MyPLC peer association.
118         # only used by plc and ple.
119         #slices.handle_peer(site, slice, persons, peer)
120         
121         return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
122         
123         
124     def delete_sliver (self, slice_urn, slice_hrn, creds, options):
125         
126         slices = self.GetSlices({'slice_hrn': slice_hrn})
127         if not slices:
128             return 1
129         slice = slices[0]
130     
131         # determine if this is a peer slice
132         # xxx I wonder if this would not need to use PlSlices.get_peer instead 
133         # in which case plc.peers could be deprecated as this here
134         # is the only/last call to this last method in plc.peers
135         peer = peers.get_peer(self, slice_hrn)
136         try:
137             if peer:
138                 self.UnBindObjectFromPeer('slice', slice['slice_id'], peer)
139             self.DeleteSliceFromNodes(slice_hrn, slice['node_ids'])
140         finally:
141             if peer:
142                 self.BindObjectToPeer('slice', slice['slice_id'], peer, slice['peer_slice_id'])
143         return 1
144             
145             
146             
147             
148     # first 2 args are None in case of resource discovery
149     def list_resources (self, slice_urn, slice_hrn, creds, options):
150         #cached_requested = options.get('cached', True) 
151     
152         version_manager = VersionManager()
153         # get the rspec's return format from options
154         rspec_version = version_manager.get_version(options.get('geni_rspec_version'))
155         version_string = "rspec_%s" % (rspec_version)
156     
157         #panos adding the info option to the caching key (can be improved)
158         if options.get('info'):
159             version_string = version_string + "_"+options.get('info', 'default')
160     
161         # look in cache first
162         #if cached_requested and self.cache and not slice_hrn:
163             #rspec = self.cache.get(version_string)
164             #if rspec:
165                 #logger.debug("SlabDriver.ListResources: returning cached advertisement")
166                 #return rspec 
167     
168         #panos: passing user-defined options
169         #print "manager options = ",options
170         aggregate = SlabAggregate(self)
171         rspec =  aggregate.get_rspec(slice_xrn=slice_urn, version=rspec_version, 
172                                      options=options)
173     
174         # cache the result
175         #if self.cache and not slice_hrn:
176             #logger.debug("Slab.ListResources: stores advertisement in cache")
177             #self.cache.add(version_string, rspec)
178     
179         return rspec
180         
181         
182     def list_slices (self, creds, options):
183         # look in cache first
184         #if self.cache:
185             #slices = self.cache.get('slices')
186             #if slices:
187                 #logger.debug("PlDriver.list_slices returns from cache")
188                 #return slices
189     
190         # get data from db 
191         print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY list_slices"
192         slices = self.GetSlices()
193         slice_hrns = [slicename_to_hrn(self.hrn, slice['slice_hrn']) for slice in slices]
194         slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
195     
196         # cache the result
197         #if self.cache:
198             #logger.debug ("SlabDriver.list_slices stores value in cache")
199             #self.cache.add('slices', slice_urns) 
200     
201         return slice_urns
202     
203     #No site or node register supported
204     def register (self, sfa_record, hrn, pub_key):
205         type = sfa_record['type']
206         pl_record = self.sfa_fields_to_pl_fields(type, hrn, sfa_record)
207     
208         #if type == 'authority':
209             #sites = self.shell.GetSites([pl_record['login_base']])
210             #if not sites:
211                 #pointer = self.shell.AddSite(pl_record)
212             #else:
213                 #pointer = sites[0]['site_id']
214     
215         if type == 'slice':
216             acceptable_fields=['url', 'instantiation', 'name', 'description']
217             for key in pl_record.keys():
218                 if key not in acceptable_fields:
219                     pl_record.pop(key) 
220             print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY register"
221             slices = self.GetSlices([pl_record['hrn']])
222             if not slices:
223                     pointer = self.AddSlice(pl_record)
224             else:
225                     pointer = slices[0]['slice_id']
226     
227         elif type == 'user':
228             persons = self.GetPersons([sfa_record['hrn']])
229             if not persons:
230                 pointer = self.AddPerson(dict(sfa_record))
231                 #add in LDAP 
232             else:
233                 pointer = persons[0]['person_id']
234                 
235             #Does this make sense to senslab ?
236             #if 'enabled' in sfa_record and sfa_record['enabled']:
237                 #self.UpdatePerson(pointer, {'enabled': sfa_record['enabled']})
238                 
239             # add this person to the site only if she is being added for the first
240             # time by sfa and doesont already exist in plc
241             if not persons or not persons[0]['site_ids']:
242                 login_base = get_leaf(sfa_record['authority'])
243                 self.AddPersonToSite(pointer, login_base)
244     
245             # What roles should this user have?
246             self.AddRoleToPerson('user', pointer)
247             # Add the user's key
248             if pub_key:
249                 self.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
250                 
251         #No node adding outside OAR
252         #elif type == 'node':
253             #login_base = hrn_to_pl_login_base(sfa_record['authority'])
254             #nodes = self.GetNodes([pl_record['hostname']])
255             #if not nodes:
256                 #pointer = self.AddNode(login_base, pl_record)
257             #else:
258                 #pointer = nodes[0]['node_id']
259     
260         return pointer
261             
262     #No site or node record update allowed       
263     def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
264         pointer = old_sfa_record['pointer']
265         type = old_sfa_record['type']
266
267         # new_key implemented for users only
268         if new_key and type not in [ 'user' ]:
269             raise UnknownSfaType(type)
270         
271         #if (type == "authority"):
272             #self.shell.UpdateSite(pointer, new_sfa_record)
273     
274         if type == "slice":
275             pl_record=self.sfa_fields_to_pl_fields(type, hrn, new_sfa_record)
276             if 'name' in pl_record:
277                 pl_record.pop('name')
278                 self.UpdateSlice(pointer, pl_record)
279     
280         elif type == "user":
281             update_fields = {}
282             all_fields = new_sfa_record
283             for key in all_fields.keys():
284                 if key in ['first_name', 'last_name', 'title', 'email',
285                            'password', 'phone', 'url', 'bio', 'accepted_aup',
286                            'enabled']:
287                     update_fields[key] = all_fields[key]
288             self.UpdatePerson(pointer, update_fields)
289     
290             if new_key:
291                 # must check this key against the previous one if it exists
292                 persons = self.GetPersons([pointer], ['key_ids'])
293                 person = persons[0]
294                 keys = person['key_ids']
295                 keys = self.GetKeys(person['key_ids'])
296                 
297                 # Delete all stale keys
298                 key_exists = False
299                 for key in keys:
300                     if new_key != key['key']:
301                         self.DeleteKey(key['key_id'])
302                     else:
303                         key_exists = True
304                 if not key_exists:
305                     self.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
306     
307         #elif type == "node":
308             #self.UpdateNode(pointer, new_sfa_record)
309
310         return True
311         
312
313     def remove (self, sfa_record):
314         type=sfa_record['type']
315         hrn=sfa_record['hrn']
316         record_id= sfa_record['record_id']
317         if type == 'user':
318             username = hrn.split(".")[len(hrn.split(".")) -1]
319             #get user in ldap
320             persons = self.GetPersons(username)
321             # only delete this person if he has site ids. if he doesnt, it probably means
322             # he was just removed from a site, not actually deleted
323             if persons and persons[0]['site_ids']:
324                 self.DeletePerson(username)
325         elif type == 'slice':
326             if self.GetSlices(hrn):
327                 self.DeleteSlice(hrn)
328
329         #elif type == 'authority':
330             #if self.GetSites(pointer):
331                 #self.DeleteSite(pointer)
332
333         return True
334             
335     def GetPeers (self,auth = None, peer_filter=None, return_fields=None):
336         table = SfaTable()
337         return_records = [] 
338         records_list =  table.findObjects({'type':'authority+sa'})   
339         if not peer_filter and not return_fields:
340             return records_list
341         return_records = parse_filter(records_list,peer_filter, 'peers', return_fields) 
342  
343         return return_records
344         
345      
346             
347     def GetPersons(self, person_filter=None, return_fields=None):
348         
349         person_list = self.ldap.ldapFind({'authority': self.root_auth })
350         
351         #check = False
352         #if person_filter and isinstance(person_filter, dict):
353             #for k in  person_filter.keys():
354                 #if k in person_list[0].keys():
355                     #check = True
356                     
357         return_person_list = parse_filter(person_list,person_filter ,'persons', return_fields)
358         if return_person_list:
359             print>>sys.stderr, " \r\n GetPersons person_filter %s return_fields %s return_person_list %s " %(person_filter,return_fields,return_person_list)
360             return return_person_list
361
362
363     def GetJobs(self,job_id= None, resources=True,return_fields=None, details = None):
364         #job_resources=['reserved_resources', 'assigned_resources','job_id', 'job_uri', 'assigned_nodes',\
365         #'api_timestamp']
366         #assigned_res = ['resource_id', 'resource_uri']
367         #assigned_n = ['node', 'node_uri']
368       
369                 
370         if job_id and resources is False:
371             job_info = self.oar.parser.SendRequest("GET_jobs_id", job_id)
372             print>>sys.stderr, "\r\n \r\n \t\t GetJobs resources is False job_info %s" %(job_info)
373
374         if job_id and resources :       
375             job_info = self.oar.parser.SendRequest("GET_jobs_id_resources", job_id)
376             print>>sys.stderr, "\r\n \r\n \t\t GetJobs job_info %s" %(job_info)
377             
378         if job_info['state'] == 'Terminated':
379             print>>sys.stderr, "\r\n \r\n \t\t GetJobs TERMINELEBOUSIN "
380             return None
381         else:
382             return job_info
383      
384        
385      
386     def GetNodes(self,node_filter= None, return_fields=None):
387                 
388         node_dict =self.oar.parser.SendRequest("GET_resources_full")
389
390         return_node_list = []
391         if not (node_filter or return_fields):
392                 return_node_list = node_dict.values()
393                 return return_node_list
394     
395         return_node_list= parse_filter(node_dict.values(),node_filter ,'node', return_fields)
396         return return_node_list
397     
398     #def GetSites(self, auth, site_filter = None, return_fields=None):
399         #self.oar.parser.SendRequest("GET_resources_full")
400         #site_dict = self.oar.parser.GetSitesFromOARParse()
401         #return_site_list = []
402         #site = site_dict.values()[0]
403         #if not (site_filter or return_fields):
404                 #return_site_list = site_dict.values()
405                 #return return_site_list
406         
407         #return_site_list = parse_filter(site_dict.values(),site_filter ,'site', return_fields)
408         #return return_site_list
409     
410     def GetSlices(self,slice_filter = None, return_fields=None):
411         
412         return_slice_list =[]
413         sliceslist = self.db.find('slice',columns = ['oar_job_id', 'slice_hrn', 'record_id_slice','record_id_user'], record_filter=slice_filter)
414         
415         print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  slices %s slice_filter %s " %(sliceslist,slice_filter)
416       
417        
418                     
419         if not (slice_filter or return_fields) and sliceslist:
420             for sl in sliceslist:
421                 if sl['oar_job_id'] is not -1: 
422                     rslt = self.GetJobs( sl['oar_job_id'],resources=False)
423                     print >>sys.stderr, " \r\n \r\n \tSLABRIVER.PY  GetSlices  rslt   %s" %(rslt)
424                     
425                     if rslt :
426                         sl.update(rslt)
427                         sl.update({'hrn':str(sl['slice_hrn'])}) 
428                         print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  slice SL  %s" %(sl)
429                     #If GetJobs is empty, this means the job is now in the 'Terminated' state
430                     #Update the slice record
431                     else :
432                         sl['oar_job_id'] = '-1'
433                        
434                         sl.update({'hrn':str(sl['slice_hrn'])})
435                         print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  TERMINATEDDFDDDDD  %s" %(sl)
436                         self.db.update_senslab_slice(sl)
437                                  
438                                  
439             return_slice_list = sliceslist
440             print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  return_slice_list  %s" %(return_slice_list)  
441             return  return_slice_list
442         
443         return_slice_list  = parse_filter(sliceslist, slice_filter,'slice', return_fields)
444         
445         
446         for sl in return_slice_list:
447                 if sl['oar_job_id'] is not -1: 
448                     print >>sys.stderr, " \r\n \r\n SLABDRIVER.PY  GetSlices  sl  %s" %(sl)
449                     rslt =self.GetJobs( sl['oar_job_id'],resources=False)
450                     print >>sys.stderr, " \r\n \r\n SLABRIVER.PY  GetSlices  rslt   %s" %(rslt)
451                     if rslt :
452                         sl.update(rslt)
453                         sl.update({'hrn':str(sl['slice_hrn'])}) 
454                         print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  slice SL  %s" %(sl)
455                     #If GetJobs is empty, this means the job is now in the 'Terminated' state
456                     #Update the slice record
457                     else :
458                         sl['oar_job_id'] = '-1'
459                        
460                         sl.update({'hrn':str(sl['slice_hrn'])})
461                         print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  TERMINATEDDFDDDDD  %s" %(sl)
462                         self.db.update_senslab_slice(sl)
463                        
464                    
465         #print >>sys.stderr, " \r\n \r\n SLABDRIVER.PY  GetSlices  return_slice_list %s" %(return_slice_list)
466         return return_slice_list
467     
468     def testbed_name (self): return "senslab2" 
469          
470     # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
471     def aggregate_version (self):
472         version_manager = VersionManager()
473         ad_rspec_versions = []
474         request_rspec_versions = []
475         for rspec_version in version_manager.versions:
476             if rspec_version.content_type in ['*', 'ad']:
477                 ad_rspec_versions.append(rspec_version.to_dict())
478             if rspec_version.content_type in ['*', 'request']:
479                 request_rspec_versions.append(rspec_version.to_dict()) 
480         return {
481             'testbed':self.testbed_name(),
482             'geni_request_rspec_versions': request_rspec_versions,
483             'geni_ad_rspec_versions': ad_rspec_versions,
484             }
485           
486           
487           
488           
489           
490           
491     ##
492     # Convert SFA fields to PLC fields for use when registering up updating
493     # registry record in the PLC database
494     #
495     # @param type type of record (user, slice, ...)
496     # @param hrn human readable name
497     # @param sfa_fields dictionary of SFA fields
498     # @param pl_fields dictionary of PLC fields (output)
499
500     def sfa_fields_to_pl_fields(self, type, hrn, record):
501
502         def convert_ints(tmpdict, int_fields):
503             for field in int_fields:
504                 if field in tmpdict:
505                     tmpdict[field] = int(tmpdict[field])
506
507         pl_record = {}
508         #for field in record:
509         #    pl_record[field] = record[field]
510  
511         if type == "slice":
512             #instantion used in get_slivers ? 
513             if not "instantiation" in pl_record:
514                 pl_record["instantiation"] = "senslab-instantiated"
515             pl_record["hrn"] = hrn_to_pl_slicename(hrn)
516             if "url" in record:
517                pl_record["url"] = record["url"]
518             if "description" in record:
519                 pl_record["description"] = record["description"]
520             if "expires" in record:
521                 pl_record["expires"] = int(record["expires"])
522                 
523         #nodes added by OAR only and then imported to SFA
524         #elif type == "node":
525             #if not "hostname" in pl_record:
526                 #if not "hostname" in record:
527                     #raise MissingSfaInfo("hostname")
528                 #pl_record["hostname"] = record["hostname"]
529             #if not "model" in pl_record:
530                 #pl_record["model"] = "geni"
531                 
532         #One authority only 
533         #elif type == "authority":
534             #pl_record["login_base"] = hrn_to_pl_login_base(hrn)
535
536             #if not "name" in pl_record:
537                 #pl_record["name"] = hrn
538
539             #if not "abbreviated_name" in pl_record:
540                 #pl_record["abbreviated_name"] = hrn
541
542             #if not "enabled" in pl_record:
543                 #pl_record["enabled"] = True
544
545             #if not "is_public" in pl_record:
546                 #pl_record["is_public"] = True
547
548         return pl_record
549
550   
551                  
552                  
553     def AddSliceToNodes(self,  slice_name, added_nodes, slice_user=None):
554         print>>sys.stderr, "\r\n \r\n AddSliceToNodes  slice_name %s added_nodes %s username %s" %(slice_name,added_nodes,slice_user )
555         site_list = []
556         nodeid_list =[]
557         resource = ""
558         reqdict = {}
559         reqdict['property'] ="network_address in ("
560         for node in added_nodes:
561             #Get the ID of the node : remove the root auth and put the site in a separate list
562             tmp = node.strip(self.root_auth+".")
563             l = tmp.split("_")
564              
565             nodeid= (l[len(l)-1]) 
566             reqdict['property'] += "'"+ nodeid +"', "
567             nodeid_list.append(nodeid)
568             site_list.append( l[0] )
569             
570         reqdict['property'] =  reqdict['property'][0: len( reqdict['property'])-2] +")"
571         reqdict['resource'] ="network_address="+ str(len(nodeid_list))
572         reqdict['resource']+= ",walltime=" + str(00) + ":" + str(05) + ":" + str(00)
573         reqdict['script_path'] = "/bin/sleep 320"
574         #reqdict['type'] = "deploy"
575         print>>sys.stderr, "\r\n \r\n AddSliceToNodes reqdict   %s \r\n site_list   %s"  %(reqdict,site_list)   
576         OAR = OARrestapi()
577         answer = OAR.POSTRequestToOARRestAPI('POST_job',reqdict,slice_user)
578         print>>sys.stderr, "\r\n \r\n AddSliceToNodes jobid   %s "  %(answer)
579         self.db.update('slice',['oar_job_id'], [answer['id']], 'slice_hrn', slice_name)
580         return 
581     
582
583         
584         
585     def DeleteSliceFromNodes(self, slice_name, deleted_nodes):
586         return   
587     
588  
589
590     def fill_record_sfa_info(self, records):
591
592         def startswith(prefix, values):
593             return [value for value in values if value.startswith(prefix)]
594
595         # get person ids
596         person_ids = []
597         site_ids = []
598         for record in records:
599             person_ids.extend(record.get("person_ids", []))
600             site_ids.extend(record.get("site_ids", [])) 
601             if 'site_id' in record:
602                 site_ids.append(record['site_id']) 
603                 
604         #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___person_ids %s \r\n \t\t site_ids %s " %(person_ids, site_ids)
605         
606         # get all pis from the sites we've encountered
607         # and store them in a dictionary keyed on site_id 
608         site_pis = {}
609         if site_ids:
610             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
611             pi_list = self.GetPersons( pi_filter, ['person_id', 'site_ids'])
612             #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ GetPersons ['person_id', 'site_ids'] pi_ilist %s" %(pi_list)
613
614             for pi in pi_list:
615                 # we will need the pi's hrns also
616                 person_ids.append(pi['person_id'])
617                 
618                 # we also need to keep track of the sites these pis
619                 # belong to
620                 for site_id in pi['site_ids']:
621                     if site_id in site_pis:
622                         site_pis[site_id].append(pi)
623                     else:
624                         site_pis[site_id] = [pi]
625                  
626         # get sfa records for all records associated with these records.   
627         # we'll replace pl ids (person_ids) with hrns from the sfa records
628         # we obtain
629         
630         # get the sfa records
631         table = SfaTable()
632         person_list, persons = [], {}
633         person_list = table.find({'type': 'user', 'pointer': person_ids})
634         # create a hrns keyed on the sfa record's pointer.
635         # Its possible for  multiple records to have the same pointer so
636         # the dict's value will be a list of hrns.
637         persons = defaultdict(list)
638         for person in person_list:
639             persons[person['pointer']].append(person)
640
641         # get the pl records
642         pl_person_list, pl_persons = [], {}
643         pl_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
644         pl_persons = list_to_dict(pl_person_list, 'person_id')
645         #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___  _list %s \r\n \t\t SenslabUsers.GetPersons ['person_id', 'roles'] pl_persons %s \r\n records %s" %(pl_person_list, pl_persons,records) 
646         # fill sfa info
647         
648         for record in records:
649             # skip records with no pl info (top level authorities)
650             #Sandrine 24 oct 11 2 lines
651             #if record['pointer'] == -1:
652                 #continue 
653             sfa_info = {}
654             type = record['type']
655             if (type == "slice"):
656                 # all slice users are researchers
657                 #record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')  ? besoin ou pas ?
658                 record['PI'] = []
659                 record['researcher'] = []
660                 for person_id in record.get('person_ids', []):
661                          #Sandrine 24 oct 11 line
662                 #for person_id in record['person_ids']:
663                     hrns = [person['hrn'] for person in persons[person_id]]
664                     record['researcher'].extend(hrns)                
665
666                 # pis at the slice's site
667                 pl_pis = site_pis[record['site_id']]
668                 pi_ids = [pi['person_id'] for pi in pl_pis]
669                 for person_id in pi_ids:
670                     hrns = [person['hrn'] for person in persons[person_id]]
671                     record['PI'].extend(hrns)
672                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
673                 record['geni_creator'] = record['PI'] 
674                 
675             elif (type == "authority"):
676                 record['PI'] = []
677                 record['operator'] = []
678                 record['owner'] = []
679                 for pointer in record['person_ids']:
680                     if pointer not in persons or pointer not in pl_persons:
681                         # this means there is not sfa or pl record for this user
682                         continue   
683                     hrns = [person['hrn'] for person in persons[pointer]] 
684                     roles = pl_persons[pointer]['roles']   
685                     if 'pi' in roles:
686                         record['PI'].extend(hrns)
687                     if 'tech' in roles:
688                         record['operator'].extend(hrns)
689                     if 'admin' in roles:
690                         record['owner'].extend(hrns)
691                     # xxx TODO: OrganizationName
692             elif (type == "node"):
693                 sfa_info['dns'] = record.get("hostname", "")
694                 # xxx TODO: URI, LatLong, IP, DNS
695     
696             elif (type == "user"):
697                  sfa_info['email'] = record.get("email", "")
698                  sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
699                  sfa_info['geni_certificate'] = record['gid'] 
700                 # xxx TODO: PostalAddress, Phone
701                 
702             #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<<  fill_record_sfa_info sfa_info %s  \r\n record %s : "%(sfa_info,record)  
703             record.update(sfa_info)
704             
705     def augment_records_with_testbed_info (self, sfa_records):
706         return self.fill_record_info (sfa_records)
707     
708     def fill_record_info(self, records):
709         """
710         Given a SFA record, fill in the senslab specific and SFA specific
711         fields in the record. 
712         """
713         print >>sys.stderr, "\r\n \t\t BEFORE fill_record_info %s" %(records)   
714         if not isinstance(records, list):
715             records = [records]
716         #print >>sys.stderr, "\r\n \t\t BEFORE fill_record_pl_info %s" %(records)       
717         parkour = records 
718         try:
719             for record in parkour:
720                     
721                 if str(record['type']) == 'slice':
722                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info record %s" %(record)
723                     sfatable = SfaTable()
724                     recslice = self.db.find('slice',str(record['hrn']))
725                     if isinstance(recslice,list) and len(recslice) == 1:
726                         recslice = recslice[0]
727                     recuser = sfatable.find(  recslice['record_id_user'], ['hrn'])
728                     
729                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info %s" %(recuser)
730                     
731                     if isinstance(recuser,list) and len(recuser) == 1:
732                         recuser = recuser[0]              
733                     record.update({'PI':[recuser['hrn']],
734                     'researcher': [recuser['hrn']],
735                     'name':record['hrn'], 
736                     'oar_job_id':recslice['oar_job_id'],
737                     'node_ids': [],
738                     'person_ids':[recslice['record_id_user']]})
739                     
740                 elif str(record['type']) == 'user':  
741                     recslice = self.db.find('slice', record_filter={'record_id_user':record['record_id']})
742                     for rec in recslice:
743                         rec.update({'type':'slice'})
744                         rec.update({'hrn':rec['slice_hrn'], 'record_id':rec['record_id_slice']})
745                         records.append(rec)
746                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info ADDING SLIC EINFO recslice %s" %(recslice) 
747                     
748         
749         except TypeError:
750             print >>sys.stderr, "\r\n \t\t SLABDRIVER fill_record_info  EXCEPTION RECORDS : %s" %(records)      
751             return
752         
753         #self.fill_record_pl_info(records)
754         ##print >>sys.stderr, "\r\n \t\t after fill_record_pl_info %s" %(records)       
755         #self.fill_record_sfa_info(records)
756         #print >>sys.stderr, "\r\n \t\t after fill_record_sfa_info"
757         
758     #def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
759         ## get a list of the HRNs tht are members of the old and new records
760         #if oldRecord:
761             #oldList = oldRecord.get(listName, [])
762         #else:
763             #oldList = []     
764         #newList = record.get(listName, [])
765
766         ## if the lists are the same, then we don't have to update anything
767         #if (oldList == newList):
768             #return
769
770         ## build a list of the new person ids, by looking up each person to get
771         ## their pointer
772         #newIdList = []
773         #table = SfaTable()
774         #records = table.find({'type': 'user', 'hrn': newList})
775         #for rec in records:
776             #newIdList.append(rec['pointer'])
777
778         ## build a list of the old person ids from the person_ids field 
779         #if oldRecord:
780             #oldIdList = oldRecord.get("person_ids", [])
781             #containerId = oldRecord.get_pointer()
782         #else:
783             ## if oldRecord==None, then we are doing a Register, instead of an
784             ## update.
785             #oldIdList = []
786             #containerId = record.get_pointer()
787
788     ## add people who are in the new list, but not the oldList
789         #for personId in newIdList:
790             #if not (personId in oldIdList):
791                 #addFunc(self.plauth, personId, containerId)
792
793         ## remove people who are in the old list, but not the new list
794         #for personId in oldIdList:
795             #if not (personId in newIdList):
796                 #delFunc(self.plauth, personId, containerId)
797
798     #def update_membership(self, oldRecord, record):
799         #print >>sys.stderr, " \r\n \r\n ***SLABDRIVER.PY update_membership record ", record
800         #if record.type == "slice":
801             #self.update_membership_list(oldRecord, record, 'researcher',
802                                         #self.users.AddPersonToSlice,
803                                         #self.users.DeletePersonFromSlice)
804         #elif record.type == "authority":
805             ## xxx TODO
806             #pass
807
808 ### thierry
809 # I don't think you plan on running a component manager at this point
810 # let me clean up the mess of ComponentAPI that is deprecated anyways