defaultdict in sfa.util + minor/cosmetic
[sfa.git] / sfa / plc / plcsfaapi.py
1 import xmlrpclib
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 from sfa.server.sfaapi import SfaApi
12
13 def list_to_dict(recs, key):
14     """
15     convert a list of dictionaries into a dictionary keyed on the 
16     specified dictionary key 
17     """
18     keys = [rec[key] for rec in recs]
19     return dict(zip(keys, recs))
20
21 class PlcSfaApi(SfaApi):
22
23     def __init__ (self, encoding="utf-8", methods='sfa.methods', 
24                   config = "/etc/sfa/sfa_config.py", 
25                   peer_cert = None, interface = None, 
26                   key_file = None, cert_file = None, cache = None):
27         SfaApi.__init__(self, encoding=encoding, methods=methods, 
28                         config=config, 
29                         peer_cert=peer_cert, interface=interface, 
30                         key_file=key_file, 
31                         cert_file=cert_file, cache=cache)
32  
33         self.SfaTable = SfaTable
34         # Initialize the PLC shell only if SFA wraps a myPLC
35         rspec_type = self.config.get_aggregate_type()
36         if (rspec_type == 'pl' or rspec_type == 'vini' or \
37             rspec_type == 'eucalyptus' or rspec_type == 'max'):
38             self.plshell = self.getPLCShell()
39             self.plshell_version = "4.3"
40
41     def getPLCShell(self):
42         self.plauth = {'Username': self.config.SFA_PLC_USER,
43                        'AuthMethod': 'password',
44                        'AuthString': self.config.SFA_PLC_PASSWORD}
45
46         # The native shell (PLC.Shell.Shell) is more efficient than xmlrpc,
47         # but it leaves idle db connections open. use xmlrpc until we can figure
48         # out why PLC.Shell.Shell doesn't close db connection properly     
49         #try:
50         #    sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
51         #    self.plshell_type = 'direct'
52         #    import PLC.Shell
53         #    shell = PLC.Shell.Shell(globals = globals())
54         #except:
55         
56         self.plshell_type = 'xmlrpc' 
57         url = self.config.SFA_PLC_URL
58         shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
59         return shell
60
61     ##
62     # Convert SFA fields to PLC fields for use when registering up updating
63     # registry record in the PLC database
64     #
65     # @param type type of record (user, slice, ...)
66     # @param hrn human readable name
67     # @param sfa_fields dictionary of SFA fields
68     # @param pl_fields dictionary of PLC fields (output)
69
70     def sfa_fields_to_pl_fields(self, type, hrn, record):
71
72         def convert_ints(tmpdict, int_fields):
73             for field in int_fields:
74                 if field in tmpdict:
75                     tmpdict[field] = int(tmpdict[field])
76
77         pl_record = {}
78         #for field in record:
79         #    pl_record[field] = record[field]
80  
81         if type == "slice":
82             if not "instantiation" in pl_record:
83                 pl_record["instantiation"] = "plc-instantiated"
84             pl_record["name"] = hrn_to_pl_slicename(hrn)
85             if "url" in record:
86                pl_record["url"] = record["url"]
87             if "description" in record:
88                 pl_record["description"] = record["description"]
89             if "expires" in record:
90                 pl_record["expires"] = int(record["expires"])
91
92         elif type == "node":
93             if not "hostname" in pl_record:
94                 if not "hostname" in record:
95                     raise MissingSfaInfo("hostname")
96                 pl_record["hostname"] = record["hostname"]
97             if not "model" in pl_record:
98                 pl_record["model"] = "geni"
99
100         elif type == "authority":
101             pl_record["login_base"] = hrn_to_pl_login_base(hrn)
102
103             if not "name" in pl_record:
104                 pl_record["name"] = hrn
105
106             if not "abbreviated_name" in pl_record:
107                 pl_record["abbreviated_name"] = hrn
108
109             if not "enabled" in pl_record:
110                 pl_record["enabled"] = True
111
112             if not "is_public" in pl_record:
113                 pl_record["is_public"] = True
114
115         return pl_record
116
117     def fill_record_pl_info(self, records):
118         """
119         Fill in the planetlab specific fields of a SFA record. This
120         involves calling the appropriate PLC method to retrieve the 
121         database record for the object.
122         
123         PLC data is filled into the pl_info field of the record.
124     
125         @param record: record to fill in field (in/out param)     
126         """
127         # get ids by type
128         node_ids, site_ids, slice_ids = [], [], [] 
129         person_ids, key_ids = [], []
130         type_map = {'node': node_ids, 'authority': site_ids,
131                     'slice': slice_ids, 'user': person_ids}
132                   
133         for record in records:
134             for type in type_map:
135                 if type == record['type']:
136                     type_map[type].append(record['pointer'])
137
138         # get pl records
139         nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
140         if node_ids:
141             node_list = self.plshell.GetNodes(self.plauth, node_ids)
142             nodes = list_to_dict(node_list, 'node_id')
143         if site_ids:
144             site_list = self.plshell.GetSites(self.plauth, site_ids)
145             sites = list_to_dict(site_list, 'site_id')
146         if slice_ids:
147             slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
148             slices = list_to_dict(slice_list, 'slice_id')
149         if person_ids:
150             person_list = self.plshell.GetPersons(self.plauth, person_ids)
151             persons = list_to_dict(person_list, 'person_id')
152             for person in persons:
153                 key_ids.extend(persons[person]['key_ids'])
154
155         pl_records = {'node': nodes, 'authority': sites,
156                       'slice': slices, 'user': persons}
157
158         if key_ids:
159             key_list = self.plshell.GetKeys(self.plauth, key_ids)
160             keys = list_to_dict(key_list, 'key_id')
161
162         # fill record info
163         for record in records:
164             # records with pointer==-1 do not have plc info.
165             # for example, the top level authority records which are
166             # authorities, but not PL "sites"
167             if record['pointer'] == -1:
168                 continue
169            
170             for type in pl_records:
171                 if record['type'] == type:
172                     if record['pointer'] in pl_records[type]:
173                         record.update(pl_records[type][record['pointer']])
174                         break
175             # fill in key info
176             if record['type'] == 'user':
177                 if 'key_ids' not in record:
178                     logger.info("user record has no 'key_ids' - need to import from myplc ?")
179                 else:
180                     pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys] 
181                     record['keys'] = pubkeys
182
183         # fill in record hrns
184         records = self.fill_record_hrns(records)   
185  
186         return records
187
188     def fill_record_hrns(self, records):
189         """
190         convert pl ids to hrns
191         """
192
193         # get ids
194         slice_ids, person_ids, site_ids, node_ids = [], [], [], []
195         for record in records:
196             if 'site_id' in record:
197                 site_ids.append(record['site_id'])
198             if 'site_ids' in record:
199                 site_ids.extend(record['site_ids'])
200             if 'person_ids' in record:
201                 person_ids.extend(record['person_ids'])
202             if 'slice_ids' in record:
203                 slice_ids.extend(record['slice_ids'])
204             if 'node_ids' in record:
205                 node_ids.extend(record['node_ids'])
206
207         # get pl records
208         slices, persons, sites, nodes = {}, {}, {}, {}
209         if site_ids:
210             site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
211             sites = list_to_dict(site_list, 'site_id')
212         if person_ids:
213             person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
214             persons = list_to_dict(person_list, 'person_id')
215         if slice_ids:
216             slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
217             slices = list_to_dict(slice_list, 'slice_id')       
218         if node_ids:
219             node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
220             nodes = list_to_dict(node_list, 'node_id')
221        
222         # convert ids to hrns
223         for record in records:
224             # get all relevant data
225             type = record['type']
226             pointer = record['pointer']
227             auth_hrn = self.hrn
228             login_base = ''
229             if pointer == -1:
230                 continue
231
232             if 'site_id' in record:
233                 site = sites[record['site_id']]
234                 login_base = site['login_base']
235                 record['site'] = ".".join([auth_hrn, login_base])
236             if 'person_ids' in record:
237                 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
238                           if person_id in  persons]
239                 usernames = [email.split('@')[0] for email in emails]
240                 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
241                 record['persons'] = person_hrns 
242             if 'slice_ids' in record:
243                 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
244                               if slice_id in slices]
245                 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
246                 record['slices'] = slice_hrns
247             if 'node_ids' in record:
248                 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
249                              if node_id in nodes]
250                 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
251                 record['nodes'] = node_hrns
252             if 'site_ids' in record:
253                 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
254                                if site_id in sites]
255                 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
256                 record['sites'] = site_hrns
257             
258         return records   
259
260     def fill_record_sfa_info(self, records):
261
262         def startswith(prefix, values):
263             return [value for value in values if value.startswith(prefix)]
264
265         # get person ids
266         person_ids = []
267         site_ids = []
268         for record in records:
269             person_ids.extend(record.get("person_ids", []))
270             site_ids.extend(record.get("site_ids", [])) 
271             if 'site_id' in record:
272                 site_ids.append(record['site_id']) 
273         
274         # get all pis from the sites we've encountered
275         # and store them in a dictionary keyed on site_id 
276         site_pis = {}
277         if site_ids:
278             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
279             pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
280             for pi in pi_list:
281                 # we will need the pi's hrns also
282                 person_ids.append(pi['person_id'])
283                 
284                 # we also need to keep track of the sites these pis
285                 # belong to
286                 for site_id in pi['site_ids']:
287                     if site_id in site_pis:
288                         site_pis[site_id].append(pi)
289                     else:
290                         site_pis[site_id] = [pi]
291                  
292         # get sfa records for all records associated with these records.   
293         # we'll replace pl ids (person_ids) with hrns from the sfa records
294         # we obtain
295         
296         # get the sfa records
297         table = self.SfaTable()
298         person_list, persons = [], {}
299         person_list = table.find({'type': 'user', 'pointer': person_ids})
300         # create a hrns keyed on the sfa record's pointer.
301         # Its possible for  multiple records to have the same pointer so
302         # the dict's value will be a list of hrns.
303         persons = defaultdict(list)
304         for person in person_list:
305             persons[person['pointer']].append(person)
306
307         # get the pl records
308         pl_person_list, pl_persons = [], {}
309         pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
310         pl_persons = list_to_dict(pl_person_list, 'person_id')
311
312         # fill sfa info
313         for record in records:
314             # skip records with no pl info (top level authorities)
315             #if record['pointer'] == -1:
316             #    continue 
317             sfa_info = {}
318             type = record['type']
319             if (type == "slice"):
320                 # all slice users are researchers
321                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
322                 record['PI'] = []
323                 record['researcher'] = []
324                 for person_id in record.get('person_ids', []):
325                     hrns = [person['hrn'] for person in persons[person_id]]
326                     record['researcher'].extend(hrns)                
327
328                 # pis at the slice's site
329                 if 'site_id' in record and record['site_id'] in site_pis:
330                     pl_pis = site_pis[record['site_id']]
331                     pi_ids = [pi['person_id'] for pi in pl_pis]
332                     for person_id in pi_ids:
333                         hrns = [person['hrn'] for person in persons[person_id]]
334                         record['PI'].extend(hrns)
335                         record['geni_creator'] = record['PI'] 
336                 
337             elif (type.startswith("authority")):
338                 record['url'] = None
339                 if record['hrn'] in self.aggregates:
340                     
341                     record['url'] = self.aggregates[record['hrn']].get_url()
342
343                 if record['pointer'] != -1:
344                     record['PI'] = []
345                     record['operator'] = []
346                     record['owner'] = []
347                     for pointer in record.get('person_ids', []):
348                         if pointer not in persons or pointer not in pl_persons:
349                             # this means there is not sfa or pl record for this user
350                             continue   
351                         hrns = [person['hrn'] for person in persons[pointer]] 
352                         roles = pl_persons[pointer]['roles']   
353                         if 'pi' in roles:
354                             record['PI'].extend(hrns)
355                         if 'tech' in roles:
356                             record['operator'].extend(hrns)
357                         if 'admin' in roles:
358                             record['owner'].extend(hrns)
359                         # xxx TODO: OrganizationName
360             elif (type == "node"):
361                 sfa_info['dns'] = record.get("hostname", "")
362                 # xxx TODO: URI, LatLong, IP, DNS
363     
364             elif (type == "user"):
365                 sfa_info['email'] = record.get("email", "")
366                 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
367                 sfa_info['geni_certificate'] = record['gid'] 
368                 # xxx TODO: PostalAddress, Phone
369             record.update(sfa_info)
370
371     def fill_record_info(self, records):
372         """
373         Given a SFA record, fill in the PLC specific and SFA specific
374         fields in the record. 
375         """
376         if not isinstance(records, list):
377             records = [records]
378
379         self.fill_record_pl_info(records)
380         self.fill_record_sfa_info(records)
381
382     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
383         # get a list of the HRNs that are members of the old and new records
384         if oldRecord:
385             oldList = oldRecord.get(listName, [])
386         else:
387             oldList = []     
388         newList = record.get(listName, [])
389
390         # if the lists are the same, then we don't have to update anything
391         if (oldList == newList):
392             return
393
394         # build a list of the new person ids, by looking up each person to get
395         # their pointer
396         newIdList = []
397         table = self.SfaTable()
398         records = table.find({'type': 'user', 'hrn': newList})
399         for rec in records:
400             newIdList.append(rec['pointer'])
401
402         # build a list of the old person ids from the person_ids field 
403         if oldRecord:
404             oldIdList = oldRecord.get("person_ids", [])
405             containerId = oldRecord.get_pointer()
406         else:
407             # if oldRecord==None, then we are doing a Register, instead of an
408             # update.
409             oldIdList = []
410             containerId = record.get_pointer()
411
412     # add people who are in the new list, but not the oldList
413         for personId in newIdList:
414             if not (personId in oldIdList):
415                 addFunc(self.plauth, personId, containerId)
416
417         # remove people who are in the old list, but not the new list
418         for personId in oldIdList:
419             if not (personId in newIdList):
420                 delFunc(self.plauth, personId, containerId)
421
422     def update_membership(self, oldRecord, record):
423         if record.type == "slice":
424             self.update_membership_list(oldRecord, record, 'researcher',
425                                         self.plshell.AddPersonToSlice,
426                                         self.plshell.DeletePersonFromSlice)
427         elif record.type == "authority":
428             # xxx TODO
429             pass