Clean up of Getslices.
[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
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         return_slice_list  = parse_filter(sliceslist, slice_filter,'slice', return_fields)
418                     
419         if return_slice_list:
420             for sl in return_slice_list:
421                 if sl['oar_job_id'] is not -1: 
422                     rslt = self.GetJobs( sl['oar_job_id'],resources=False)
423                     
424                     if rslt :
425                         sl.update(rslt)
426                         sl.update({'hrn':str(sl['slice_hrn'])}) 
427                     #If GetJobs is empty, this means the job is now in the 'Terminated' state
428                     #Update the slice record
429                     else :
430                         sl['oar_job_id'] = '-1'
431                         sl.update({'hrn':str(sl['slice_hrn'])})
432                         self.db.update_senslab_slice(sl)
433                                  
434                                  
435            
436             print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  return_slice_list  %s" %(return_slice_list)  
437             return  return_slice_list
438         
439      
440         
441         
442       
443         return return_slice_list
444     
445     def testbed_name (self): return "senslab2" 
446          
447     # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
448     def aggregate_version (self):
449         version_manager = VersionManager()
450         ad_rspec_versions = []
451         request_rspec_versions = []
452         for rspec_version in version_manager.versions:
453             if rspec_version.content_type in ['*', 'ad']:
454                 ad_rspec_versions.append(rspec_version.to_dict())
455             if rspec_version.content_type in ['*', 'request']:
456                 request_rspec_versions.append(rspec_version.to_dict()) 
457         return {
458             'testbed':self.testbed_name(),
459             'geni_request_rspec_versions': request_rspec_versions,
460             'geni_ad_rspec_versions': ad_rspec_versions,
461             }
462           
463           
464           
465           
466           
467           
468     ##
469     # Convert SFA fields to PLC fields for use when registering up updating
470     # registry record in the PLC database
471     #
472     # @param type type of record (user, slice, ...)
473     # @param hrn human readable name
474     # @param sfa_fields dictionary of SFA fields
475     # @param pl_fields dictionary of PLC fields (output)
476
477     def sfa_fields_to_pl_fields(self, type, hrn, record):
478
479         def convert_ints(tmpdict, int_fields):
480             for field in int_fields:
481                 if field in tmpdict:
482                     tmpdict[field] = int(tmpdict[field])
483
484         pl_record = {}
485         #for field in record:
486         #    pl_record[field] = record[field]
487  
488         if type == "slice":
489             #instantion used in get_slivers ? 
490             if not "instantiation" in pl_record:
491                 pl_record["instantiation"] = "senslab-instantiated"
492             pl_record["hrn"] = hrn_to_pl_slicename(hrn)
493             if "url" in record:
494                pl_record["url"] = record["url"]
495             if "description" in record:
496                 pl_record["description"] = record["description"]
497             if "expires" in record:
498                 pl_record["expires"] = int(record["expires"])
499                 
500         #nodes added by OAR only and then imported to SFA
501         #elif type == "node":
502             #if not "hostname" in pl_record:
503                 #if not "hostname" in record:
504                     #raise MissingSfaInfo("hostname")
505                 #pl_record["hostname"] = record["hostname"]
506             #if not "model" in pl_record:
507                 #pl_record["model"] = "geni"
508                 
509         #One authority only 
510         #elif type == "authority":
511             #pl_record["login_base"] = hrn_to_pl_login_base(hrn)
512
513             #if not "name" in pl_record:
514                 #pl_record["name"] = hrn
515
516             #if not "abbreviated_name" in pl_record:
517                 #pl_record["abbreviated_name"] = hrn
518
519             #if not "enabled" in pl_record:
520                 #pl_record["enabled"] = True
521
522             #if not "is_public" in pl_record:
523                 #pl_record["is_public"] = True
524
525         return pl_record
526
527   
528                  
529                  
530     def AddSliceToNodes(self,  slice_name, added_nodes, slice_user=None):
531         print>>sys.stderr, "\r\n \r\n AddSliceToNodes  slice_name %s added_nodes %s username %s" %(slice_name,added_nodes,slice_user )
532         site_list = []
533         nodeid_list =[]
534         resource = ""
535         reqdict = {}
536         reqdict['property'] ="network_address in ("
537         for node in added_nodes:
538             #Get the ID of the node : remove the root auth and put the site in a separate list
539             tmp = node.strip(self.root_auth+".")
540             l = tmp.split("_")
541              
542             nodeid= (l[len(l)-1]) 
543             reqdict['property'] += "'"+ nodeid +"', "
544             nodeid_list.append(nodeid)
545             site_list.append( l[0] )
546             
547         reqdict['property'] =  reqdict['property'][0: len( reqdict['property'])-2] +")"
548         reqdict['resource'] ="network_address="+ str(len(nodeid_list))
549         reqdict['resource']+= ",walltime=" + str(00) + ":" + str(05) + ":" + str(00)
550         reqdict['script_path'] = "/bin/sleep 320"
551         #reqdict['type'] = "deploy"
552         print>>sys.stderr, "\r\n \r\n AddSliceToNodes reqdict   %s \r\n site_list   %s"  %(reqdict,site_list)   
553         OAR = OARrestapi()
554         answer = OAR.POSTRequestToOARRestAPI('POST_job',reqdict,slice_user)
555         print>>sys.stderr, "\r\n \r\n AddSliceToNodes jobid   %s "  %(answer)
556         self.db.update('slice',['oar_job_id'], [answer['id']], 'slice_hrn', slice_name)
557         return 
558     
559
560         
561         
562     def DeleteSliceFromNodes(self, slice_name, deleted_nodes):
563         return   
564     
565  
566
567     def fill_record_sfa_info(self, records):
568
569         def startswith(prefix, values):
570             return [value for value in values if value.startswith(prefix)]
571
572         # get person ids
573         person_ids = []
574         site_ids = []
575         for record in records:
576             person_ids.extend(record.get("person_ids", []))
577             site_ids.extend(record.get("site_ids", [])) 
578             if 'site_id' in record:
579                 site_ids.append(record['site_id']) 
580                 
581         #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)
582         
583         # get all pis from the sites we've encountered
584         # and store them in a dictionary keyed on site_id 
585         site_pis = {}
586         if site_ids:
587             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
588             pi_list = self.GetPersons( pi_filter, ['person_id', 'site_ids'])
589             #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ GetPersons ['person_id', 'site_ids'] pi_ilist %s" %(pi_list)
590
591             for pi in pi_list:
592                 # we will need the pi's hrns also
593                 person_ids.append(pi['person_id'])
594                 
595                 # we also need to keep track of the sites these pis
596                 # belong to
597                 for site_id in pi['site_ids']:
598                     if site_id in site_pis:
599                         site_pis[site_id].append(pi)
600                     else:
601                         site_pis[site_id] = [pi]
602                  
603         # get sfa records for all records associated with these records.   
604         # we'll replace pl ids (person_ids) with hrns from the sfa records
605         # we obtain
606         
607         # get the sfa records
608         table = SfaTable()
609         person_list, persons = [], {}
610         person_list = table.find({'type': 'user', 'pointer': person_ids})
611         # create a hrns keyed on the sfa record's pointer.
612         # Its possible for  multiple records to have the same pointer so
613         # the dict's value will be a list of hrns.
614         persons = defaultdict(list)
615         for person in person_list:
616             persons[person['pointer']].append(person)
617
618         # get the pl records
619         pl_person_list, pl_persons = [], {}
620         pl_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
621         pl_persons = list_to_dict(pl_person_list, 'person_id')
622         #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) 
623         # fill sfa info
624         
625         for record in records:
626             # skip records with no pl info (top level authorities)
627             #Sandrine 24 oct 11 2 lines
628             #if record['pointer'] == -1:
629                 #continue 
630             sfa_info = {}
631             type = record['type']
632             if (type == "slice"):
633                 # all slice users are researchers
634                 #record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')  ? besoin ou pas ?
635                 record['PI'] = []
636                 record['researcher'] = []
637                 for person_id in record.get('person_ids', []):
638                          #Sandrine 24 oct 11 line
639                 #for person_id in record['person_ids']:
640                     hrns = [person['hrn'] for person in persons[person_id]]
641                     record['researcher'].extend(hrns)                
642
643                 # pis at the slice's site
644                 pl_pis = site_pis[record['site_id']]
645                 pi_ids = [pi['person_id'] for pi in pl_pis]
646                 for person_id in pi_ids:
647                     hrns = [person['hrn'] for person in persons[person_id]]
648                     record['PI'].extend(hrns)
649                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
650                 record['geni_creator'] = record['PI'] 
651                 
652             elif (type == "authority"):
653                 record['PI'] = []
654                 record['operator'] = []
655                 record['owner'] = []
656                 for pointer in record['person_ids']:
657                     if pointer not in persons or pointer not in pl_persons:
658                         # this means there is not sfa or pl record for this user
659                         continue   
660                     hrns = [person['hrn'] for person in persons[pointer]] 
661                     roles = pl_persons[pointer]['roles']   
662                     if 'pi' in roles:
663                         record['PI'].extend(hrns)
664                     if 'tech' in roles:
665                         record['operator'].extend(hrns)
666                     if 'admin' in roles:
667                         record['owner'].extend(hrns)
668                     # xxx TODO: OrganizationName
669             elif (type == "node"):
670                 sfa_info['dns'] = record.get("hostname", "")
671                 # xxx TODO: URI, LatLong, IP, DNS
672     
673             elif (type == "user"):
674                  sfa_info['email'] = record.get("email", "")
675                  sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
676                  sfa_info['geni_certificate'] = record['gid'] 
677                 # xxx TODO: PostalAddress, Phone
678                 
679             #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<<  fill_record_sfa_info sfa_info %s  \r\n record %s : "%(sfa_info,record)  
680             record.update(sfa_info)
681             
682     def augment_records_with_testbed_info (self, sfa_records):
683         return self.fill_record_info (sfa_records)
684     
685     def fill_record_info(self, records):
686         """
687         Given a SFA record, fill in the senslab specific and SFA specific
688         fields in the record. 
689         """
690         print >>sys.stderr, "\r\n \t\t BEFORE fill_record_info %s" %(records)   
691         if not isinstance(records, list):
692             records = [records]
693         #print >>sys.stderr, "\r\n \t\t BEFORE fill_record_pl_info %s" %(records)       
694         parkour = records 
695         try:
696             for record in parkour:
697                     
698                 if str(record['type']) == 'slice':
699                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info record %s" %(record)
700                     sfatable = SfaTable()
701                     recslice = self.db.find('slice',str(record['hrn']))
702                     if isinstance(recslice,list) and len(recslice) == 1:
703                         recslice = recslice[0]
704                     recuser = sfatable.find(  recslice['record_id_user'], ['hrn'])
705                     
706                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info %s" %(recuser)
707                     
708                     if isinstance(recuser,list) and len(recuser) == 1:
709                         recuser = recuser[0]              
710                     record.update({'PI':[recuser['hrn']],
711                     'researcher': [recuser['hrn']],
712                     'name':record['hrn'], 
713                     'oar_job_id':recslice['oar_job_id'],
714                     'node_ids': [],
715                     'person_ids':[recslice['record_id_user']]})
716                     
717                 elif str(record['type']) == 'user':  
718                     recslice = self.db.find('slice', record_filter={'record_id_user':record['record_id']})
719                     for rec in recslice:
720                         rec.update({'type':'slice'})
721                         rec.update({'hrn':rec['slice_hrn'], 'record_id':rec['record_id_slice']})
722                         records.append(rec)
723                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info ADDING SLIC EINFO recslice %s" %(recslice) 
724                     
725         
726         except TypeError:
727             print >>sys.stderr, "\r\n \t\t SLABDRIVER fill_record_info  EXCEPTION RECORDS : %s" %(records)      
728             return
729         
730         #self.fill_record_pl_info(records)
731         ##print >>sys.stderr, "\r\n \t\t after fill_record_pl_info %s" %(records)       
732         #self.fill_record_sfa_info(records)
733         #print >>sys.stderr, "\r\n \t\t after fill_record_sfa_info"
734         
735     #def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
736         ## get a list of the HRNs tht are members of the old and new records
737         #if oldRecord:
738             #oldList = oldRecord.get(listName, [])
739         #else:
740             #oldList = []     
741         #newList = record.get(listName, [])
742
743         ## if the lists are the same, then we don't have to update anything
744         #if (oldList == newList):
745             #return
746
747         ## build a list of the new person ids, by looking up each person to get
748         ## their pointer
749         #newIdList = []
750         #table = SfaTable()
751         #records = table.find({'type': 'user', 'hrn': newList})
752         #for rec in records:
753             #newIdList.append(rec['pointer'])
754
755         ## build a list of the old person ids from the person_ids field 
756         #if oldRecord:
757             #oldIdList = oldRecord.get("person_ids", [])
758             #containerId = oldRecord.get_pointer()
759         #else:
760             ## if oldRecord==None, then we are doing a Register, instead of an
761             ## update.
762             #oldIdList = []
763             #containerId = record.get_pointer()
764
765     ## add people who are in the new list, but not the oldList
766         #for personId in newIdList:
767             #if not (personId in oldIdList):
768                 #addFunc(self.plauth, personId, containerId)
769
770         ## remove people who are in the old list, but not the new list
771         #for personId in oldIdList:
772             #if not (personId in newIdList):
773                 #delFunc(self.plauth, personId, containerId)
774
775     #def update_membership(self, oldRecord, record):
776         #print >>sys.stderr, " \r\n \r\n ***SLABDRIVER.PY update_membership record ", record
777         #if record.type == "slice":
778             #self.update_membership_list(oldRecord, record, 'researcher',
779                                         #self.users.AddPersonToSlice,
780                                         #self.users.DeletePersonFromSlice)
781         #elif record.type == "authority":
782             ## xxx TODO
783             #pass
784
785 ### thierry
786 # I don't think you plan on running a component manager at this point
787 # let me clean up the mess of ComponentAPI that is deprecated anyways