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