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