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