Added slice table support in slabpostgres.sql.
[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.util.table import SfaTable
6 from sfa.util.defaultdict import defaultdict
7
8 from sfa.util.xrn import hrn_to_urn
9 from sfa.util.plxrn import slicename_to_hrn, hostname_to_hrn, hrn_to_pl_slicename, hrn_to_pl_login_base
10
11 ## thierry: everything that is API-related (i.e. handling incoming requests) 
12 # is taken care of 
13 # SlabDriver should be really only about talking to the senslab testbed
14
15 ## thierry : please avoid wildcard imports :)
16 from sfa.senslab.OARrestapi import OARapi
17 from sfa.senslab.LDAPapi import LDAPapi
18 from sfa.senslab.SenslabImportUsers import SenslabImportUsers
19 from sfa.senslab.parsing import parse_filter
20 from sfa.senslab.slabpostgres import SlabDB
21
22 def list_to_dict(recs, key):
23     """
24     convert a list of dictionaries into a dictionary keyed on the 
25     specified dictionary key 
26     """
27    # print>>sys.stderr, " \r\n \t\t 1list_to_dict : rec %s  \r\n \t\t list_to_dict key %s" %(recs,key)   
28     keys = [rec[key] for rec in recs]
29     #print>>sys.stderr, " \r\n \t\t list_to_dict : rec %s  \r\n \t\t list_to_dict keys %s" %(recs,keys)   
30     return dict(zip(keys, recs))
31
32 # thierry : note
33 # this inheritance scheme is so that the driver object can receive
34 # GetNodes or GetSites sorts of calls directly
35 # and thus minimize the differences in the managers with the pl version
36 class SlabDriver ():
37
38     def __init__(self, config):
39        
40         self.config=config
41         self.hrn = config.SFA_INTERFACE_HRN
42     
43         self.root_auth = config.SFA_REGISTRY_ROOT_AUTH
44
45         
46         print >>sys.stderr, "\r\n_____________ SFA SENSLAB DRIVER \r\n" 
47         # thierry - just to not break the rest of this code
48         #self.oar = OARapi()
49         #self.users = SenslabImportUsers()
50         self.oar = OARapi()
51         self.ldap = LDAPapi()
52         self.users = SenslabImportUsers()
53         self.time_format = "%Y-%m-%d %H:%M:%S"
54         #self.logger=sfa_logger()
55       
56         
57     def GetPersons(self, person_filter=None, return_fields=None):
58
59         person_list = self.ldap.ldapFind({'authority': self.root_auth })
60         return_person_list = parse_filter(person_list,person_filter ,'persons', return_fields)
61         return return_person_list
62     
63     def GetNodes(self,node_filter= None, return_fields=None):
64                 
65         self.oar.parser.SendRequest("GET_resources_full")
66         node_dict = self.oar.parser.GetNodesFromOARParse()
67         return_node_list = []
68
69         if not (node_filter or return_fields):
70                 return_node_list = node_dict.values()
71                 return return_node_list
72     
73         return_node_list= parse_filter(node_dict.values(),node_filter ,'node', return_fields)
74         return return_node_list
75     
76     ##
77     # Convert SFA fields to PLC fields for use when registering up updating
78     # registry record in the PLC database
79     #
80     # @param type type of record (user, slice, ...)
81     # @param hrn human readable name
82     # @param sfa_fields dictionary of SFA fields
83     # @param pl_fields dictionary of PLC fields (output)
84
85     def sfa_fields_to_pl_fields(self, type, hrn, record):
86
87         def convert_ints(tmpdict, int_fields):
88             for field in int_fields:
89                 if field in tmpdict:
90                     tmpdict[field] = int(tmpdict[field])
91
92         pl_record = {}
93         #for field in record:
94         #    pl_record[field] = record[field]
95  
96         if type == "slice":
97             if not "instantiation" in pl_record:
98                 pl_record["instantiation"] = "plc-instantiated"
99             pl_record["name"] = hrn_to_pl_slicename(hrn)
100             if "url" in record:
101                pl_record["url"] = record["url"]
102             if "description" in record:
103                 pl_record["description"] = record["description"]
104             if "expires" in record:
105                 pl_record["expires"] = int(record["expires"])
106
107         elif type == "node":
108             if not "hostname" in pl_record:
109                 if not "hostname" in record:
110                     raise MissingSfaInfo("hostname")
111                 pl_record["hostname"] = record["hostname"]
112             if not "model" in pl_record:
113                 pl_record["model"] = "geni"
114
115         elif type == "authority":
116             pl_record["login_base"] = hrn_to_pl_login_base(hrn)
117
118             if not "name" in pl_record:
119                 pl_record["name"] = hrn
120
121             if not "abbreviated_name" in pl_record:
122                 pl_record["abbreviated_name"] = hrn
123
124             if not "enabled" in pl_record:
125                 pl_record["enabled"] = True
126
127             if not "is_public" in pl_record:
128                 pl_record["is_public"] = True
129
130         return pl_record
131
132     def fill_record_pl_info(self, records):
133         """
134         Fill in the planetlab specific fields of a SFA record. This
135         involves calling the appropriate PLC method to retrieve the 
136         database record for the object.
137         
138         PLC data is filled into the pl_info field of the record.
139     
140         @param record: record to fill in field (in/out param)     
141         """
142         # get ids by type
143         #print>>sys.stderr, "\r\n \r\rn \t\t >>>>>>>>>>fill_record_pl_info  records %s : "%(records)
144         node_ids, site_ids, slice_ids = [], [], [] 
145         person_ids, key_ids = [], []
146         type_map = {'node': node_ids, 'authority': site_ids,
147                     'slice': slice_ids, 'user': person_ids}
148                   
149         for record in records:
150             for type in type_map:
151                 #print>>sys.stderr, "\r\n \t\t \t fill_record_pl_info : type %s. record['pointer'] %s "%(type,record['pointer'])   
152                 if type == record['type']:
153                     type_map[type].append(record['pointer'])
154         #print>>sys.stderr, "\r\n \t\t \t fill_record_pl_info : records %s... \r\n \t\t \t fill_record_pl_info : type_map   %s"%(records,type_map)
155         # get pl records
156         nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
157         if node_ids:
158             node_list = self.GetNodes( node_ids)
159             #print>>sys.stderr, " \r\n \t\t\t BEFORE LIST_TO_DICT_NODES node_ids : %s" %(node_ids)
160             nodes = list_to_dict(node_list, 'node_id')
161         if site_ids:
162             site_list = self.oar.GetSites( site_ids)
163             sites = list_to_dict(site_list, 'site_id')
164             #print>>sys.stderr, " \r\n \t\t\t  site_ids %s sites  : %s" %(site_ids,sites)           
165         if slice_ids:
166             slice_list = self.users.GetSlices( slice_ids)
167             slices = list_to_dict(slice_list, 'slice_id')
168         if person_ids:
169             #print>>sys.stderr, " \r\n \t\t \t fill_record_pl_info BEFORE GetPersons  person_ids: %s" %(person_ids)
170             person_list = self.GetPersons( person_ids)
171             persons = list_to_dict(person_list, 'person_id')
172             #print>>sys.stderr, "\r\n  fill_record_pl_info persons %s \r\n \t\t person_ids %s " %(persons, person_ids) 
173             for person in persons:
174                 key_ids.extend(persons[person]['key_ids'])
175                 #print>>sys.stderr, "\r\n key_ids %s " %(key_ids)
176
177         pl_records = {'node': nodes, 'authority': sites,
178                       'slice': slices, 'user': persons}
179
180         if key_ids:
181             key_list = self.users.GetKeys( key_ids)
182             keys = list_to_dict(key_list, 'key_id')
183            # print>>sys.stderr, "\r\n  fill_record_pl_info persons %s \r\n \t\t keys %s " %(keys) 
184         # fill record info
185         for record in records:
186             # records with pointer==-1 do not have plc info.
187             # for example, the top level authority records which are
188             # authorities, but not PL "sites"
189             if record['pointer'] == -1:
190                 continue
191            
192             for type in pl_records:
193                 if record['type'] == type:
194                     if record['pointer'] in pl_records[type]:
195                         record.update(pl_records[type][record['pointer']])
196                         break
197             # fill in key info 
198             if record['type'] == 'user':
199                  if 'key_ids' not in record:
200                         #print>>sys.stderr, " NO_KEY_IDS fill_record_pl_info key_ids record: %s" %(record)
201                         logger.info("user record has no 'key_ids' - need to import  ?")
202                  else:
203                         pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys] 
204                         record['keys'] = pubkeys
205                         
206         #print>>sys.stderr, "\r\n \r\rn \t\t <<<<<<<<<<<<<<<<<< fill_record_pl_info  records %s : "%(records)
207         # fill in record hrns
208         records = self.fill_record_hrns(records)   
209
210         return records
211
212     def fill_record_hrns(self, records):
213         """
214         convert pl ids to hrns
215         """
216         #print>>sys.stderr, "\r\n \r\rn \t\t \t >>>>>>>>>>>>>>>>>>>>>> fill_record_hrns records %s : "%(records)  
217         # get ids
218         slice_ids, person_ids, site_ids, node_ids = [], [], [], []
219         for record in records:
220             #print>>sys.stderr, "\r\n \r\rn \t\t \t record %s : "%(record)
221             if 'site_id' in record:
222                 site_ids.append(record['site_id'])
223             if 'site_ids' in records:
224                 site_ids.extend(record['site_ids'])
225             if 'person_ids' in record:
226                 person_ids.extend(record['person_ids'])
227             if 'slice_ids' in record:
228                 slice_ids.extend(record['slice_ids'])
229             if 'node_ids' in record:
230                 node_ids.extend(record['node_ids'])
231
232         # get pl records
233         slices, persons, sites, nodes = {}, {}, {}, {}
234         if site_ids:
235             site_list = self.oar.GetSites( site_ids, ['site_id', 'login_base'])
236             sites = list_to_dict(site_list, 'site_id')
237             #print>>sys.stderr, " \r\n \r\n \t\t ____ site_list %s \r\n \t\t____ sites %s " % (site_list,sites)
238         if person_ids:
239             person_list = self.GetPersons( person_ids, ['person_id', 'email'])
240             #print>>sys.stderr, " \r\n \r\n   \t\t____ person_lists %s " %(person_list) 
241             persons = list_to_dict(person_list, 'person_id')
242         if slice_ids:
243             slice_list = self.users.GetSlices( slice_ids, ['slice_id', 'name'])
244             slices = list_to_dict(slice_list, 'slice_id')       
245         if node_ids:
246             node_list = self.GetNodes( node_ids, ['node_id', 'hostname'])
247             nodes = list_to_dict(node_list, 'node_id')
248        
249         # convert ids to hrns
250         for record in records:
251              
252             # get all relevant data
253             type = record['type']
254             pointer = record['pointer']
255             auth_hrn = self.hrn
256             login_base = ''
257             if pointer == -1:
258                 continue
259
260             #print>>sys.stderr, " \r\n \r\n \t\t fill_record_hrns : sites %s \r\n \t\t record %s " %(sites, record)
261             if 'site_id' in record:
262                 site = sites[record['site_id']]
263                 #print>>sys.stderr, " \r\n \r\n \t\t \t fill_record_hrns : sites %s \r\n \t\t\t site sites[record['site_id']] %s " %(sites,site)        
264                 login_base = site['login_base']
265                 record['site'] = ".".join([auth_hrn, login_base])
266             if 'person_ids' in record:
267                 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
268                           if person_id in  persons]
269                 usernames = [email.split('@')[0] for email in emails]
270                 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
271                 #print>>sys.stderr, " \r\n \r\n \t\t ____ person_hrns : %s " %(person_hrns)
272                 record['persons'] = person_hrns 
273             if 'slice_ids' in record:
274                 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
275                               if slice_id in slices]
276                 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
277                 record['slices'] = slice_hrns
278             if 'node_ids' in record:
279                 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
280                              if node_id in nodes]
281                 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
282                 record['nodes'] = node_hrns
283             if 'site_ids' in record:
284                 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
285                                if site_id in sites]
286                 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
287                 record['sites'] = site_hrns
288         #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<<  fill_record_hrns records %s : "%(records)  
289         return records   
290
291     def fill_record_sfa_info(self, records):
292
293         def startswith(prefix, values):
294             return [value for value in values if value.startswith(prefix)]
295
296         # get person ids
297         person_ids = []
298         site_ids = []
299         for record in records:
300             person_ids.extend(record.get("person_ids", []))
301             site_ids.extend(record.get("site_ids", [])) 
302             if 'site_id' in record:
303                 site_ids.append(record['site_id']) 
304                 
305         #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)
306         
307         # get all pis from the sites we've encountered
308         # and store them in a dictionary keyed on site_id 
309         site_pis = {}
310         if site_ids:
311             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
312             pi_list = self.GetPersons( pi_filter, ['person_id', 'site_ids'])
313             #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ GetPersons ['person_id', 'site_ids'] pi_ilist %s" %(pi_list)
314
315             for pi in pi_list:
316                 # we will need the pi's hrns also
317                 person_ids.append(pi['person_id'])
318                 
319                 # we also need to keep track of the sites these pis
320                 # belong to
321                 for site_id in pi['site_ids']:
322                     if site_id in site_pis:
323                         site_pis[site_id].append(pi)
324                     else:
325                         site_pis[site_id] = [pi]
326                  
327         # get sfa records for all records associated with these records.   
328         # we'll replace pl ids (person_ids) with hrns from the sfa records
329         # we obtain
330         
331         # get the sfa records
332         table = SfaTable()
333         person_list, persons = [], {}
334         person_list = table.find({'type': 'user', 'pointer': person_ids})
335         # create a hrns keyed on the sfa record's pointer.
336         # Its possible for  multiple records to have the same pointer so
337         # the dict's value will be a list of hrns.
338         persons = defaultdict(list)
339         for person in person_list:
340             persons[person['pointer']].append(person)
341
342         # get the pl records
343         pl_person_list, pl_persons = [], {}
344         pl_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
345         pl_persons = list_to_dict(pl_person_list, 'person_id')
346         #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) 
347         # fill sfa info
348         
349         for record in records:
350             # skip records with no pl info (top level authorities)
351             #Sandrine 24 oct 11 2 lines
352             #if record['pointer'] == -1:
353                 #continue 
354             sfa_info = {}
355             type = record['type']
356             if (type == "slice"):
357                 # all slice users are researchers
358                 #record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')  ? besoin ou pas ?
359                 record['PI'] = []
360                 record['researcher'] = []
361                 for person_id in record.get('person_ids', []):
362                          #Sandrine 24 oct 11 line
363                 #for person_id in record['person_ids']:
364                     hrns = [person['hrn'] for person in persons[person_id]]
365                     record['researcher'].extend(hrns)                
366
367                 # pis at the slice's site
368                 pl_pis = site_pis[record['site_id']]
369                 pi_ids = [pi['person_id'] for pi in pl_pis]
370                 for person_id in pi_ids:
371                     hrns = [person['hrn'] for person in persons[person_id]]
372                     record['PI'].extend(hrns)
373                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
374                 record['geni_creator'] = record['PI'] 
375                 
376             elif (type == "authority"):
377                 record['PI'] = []
378                 record['operator'] = []
379                 record['owner'] = []
380                 for pointer in record['person_ids']:
381                     if pointer not in persons or pointer not in pl_persons:
382                         # this means there is not sfa or pl record for this user
383                         continue   
384                     hrns = [person['hrn'] for person in persons[pointer]] 
385                     roles = pl_persons[pointer]['roles']   
386                     if 'pi' in roles:
387                         record['PI'].extend(hrns)
388                     if 'tech' in roles:
389                         record['operator'].extend(hrns)
390                     if 'admin' in roles:
391                         record['owner'].extend(hrns)
392                     # xxx TODO: OrganizationName
393             elif (type == "node"):
394                 sfa_info['dns'] = record.get("hostname", "")
395                 # xxx TODO: URI, LatLong, IP, DNS
396     
397             elif (type == "user"):
398                  sfa_info['email'] = record.get("email", "")
399                  sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
400                  sfa_info['geni_certificate'] = record['gid'] 
401                 # xxx TODO: PostalAddress, Phone
402                 
403             #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<<  fill_record_sfa_info sfa_info %s  \r\n record %s : "%(sfa_info,record)  
404             record.update(sfa_info)
405
406     def fill_record_info(self, records):
407         """
408         Given a SFA record, fill in the senslab specific and SFA specific
409         fields in the record. 
410         """
411         
412         if isinstance(records, list):
413             records = records[0]
414         print >>sys.stderr, "\r\n \t\t BEFORE fill_record_pl_info %s" %(records)        
415         
416        
417         if records['type'] == 'slice':
418             db = SlabDB()
419             sfatable = SfaTable()
420             recslice = db.find('slice',str(records['hrn']))
421             if isinstance(recslice,list) and len(recslice) == 1:
422                 recslice = recslice[0]
423             recuser = sfatable.find(  recslice['record_id_user'], ['hrn'])
424             
425             print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info %s" %(recuser)
426             records['type']
427             if isinstance(recuser,list) and len(recuser) == 1:
428                 recuser = recuser[0]              
429             records.update({'PI':[recuser['hrn']],
430             'researcher': [recuser['hrn']],
431             'name':records['hrn'], 'oar_job_id':recslice['oar_job_id'],
432             'person_ids':[recslice['record_id_user']]})
433
434         #self.fill_record_pl_info(records)
435         ##print >>sys.stderr, "\r\n \t\t after fill_record_pl_info %s" %(records)       
436         #self.fill_record_sfa_info(records)
437         #print >>sys.stderr, "\r\n \t\t after fill_record_sfa_info"
438         
439     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
440         # get a list of the HRNs tht are members of the old and new records
441         if oldRecord:
442             oldList = oldRecord.get(listName, [])
443         else:
444             oldList = []     
445         newList = record.get(listName, [])
446
447         # if the lists are the same, then we don't have to update anything
448         if (oldList == newList):
449             return
450
451         # build a list of the new person ids, by looking up each person to get
452         # their pointer
453         newIdList = []
454         table = SfaTable()
455         records = table.find({'type': 'user', 'hrn': newList})
456         for rec in records:
457             newIdList.append(rec['pointer'])
458
459         # build a list of the old person ids from the person_ids field 
460         if oldRecord:
461             oldIdList = oldRecord.get("person_ids", [])
462             containerId = oldRecord.get_pointer()
463         else:
464             # if oldRecord==None, then we are doing a Register, instead of an
465             # update.
466             oldIdList = []
467             containerId = record.get_pointer()
468
469     # add people who are in the new list, but not the oldList
470         for personId in newIdList:
471             if not (personId in oldIdList):
472                 addFunc(self.plauth, personId, containerId)
473
474         # remove people who are in the old list, but not the new list
475         for personId in oldIdList:
476             if not (personId in newIdList):
477                 delFunc(self.plauth, personId, containerId)
478
479     def update_membership(self, oldRecord, record):
480         print >>sys.stderr, " \r\n \r\n ***SLABDRIVER.PY update_membership record ", record
481         if record.type == "slice":
482             self.update_membership_list(oldRecord, record, 'researcher',
483                                         self.users.AddPersonToSlice,
484                                         self.users.DeletePersonFromSlice)
485         elif record.type == "authority":
486             # xxx TODO
487             pass
488
489 ### thierry
490 # I don't think you plan on running a component manager at this point
491 # let me clean up the mess of ComponentAPI that is deprecated anyways