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