bugfix
[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, get_leaf
8 from sfa.util.plxrn import slicename_to_hrn, hostname_to_hrn, hrn_to_pl_slicename, hrn_to_pl_login_base
9
10 # the driver interface, mostly provides default behaviours
11 from sfa.managers.driver import Driver
12
13 from sfa.plc.plshell import PlShell
14
15 def list_to_dict(recs, key):
16     """
17     convert a list of dictionaries into a dictionary keyed on the 
18     specified dictionary key 
19     """
20     keys = [rec[key] for rec in recs]
21     return dict(zip(keys, recs))
22
23 #
24 # inheriting Driver is not very helpful in the PL case but
25 # makes sense in the general case
26
27 # PlShell is just an xmlrpc serverproxy where methods
28 # can be sent as-is; it takes care of authentication
29 # from the global config
30
31 # so OTOH we inherit PlShell just so one can do driver.GetNodes
32 # which would not make much sense in the context of other testbeds
33 # so ultimately PlDriver might just as well drop the PlShell inheritance
34
35 class PlDriver (Driver, PlShell):
36
37     def __init__ (self, config):
38         PlShell.__init__ (self, config)
39  
40         self.hrn = config.SFA_INTERFACE_HRN
41         # xxx thgen fixme - use SfaTable hardwired for now 
42         # will need to extend generic to support multiple storage systems
43         #self.SfaTable = SfaTable
44         # Initialize the PLC shell only if SFA wraps a myPLC
45         rspec_type = config.get_aggregate_type()
46         assert (rspec_type == 'pl' or rspec_type == 'vini' or \
47                     rspec_type == 'eucalyptus' or rspec_type == 'max')
48
49     ########## disabled users 
50     def is_enabled_entity (self, record, aggregates):
51         self.fill_record_info(record, aggregates)
52         if record['type'] == 'user':
53             return record['enabled']
54         # only users can be disabled
55         return True
56
57     ########## 
58     def register (self, hrn, sfa_record, pub_key):
59         type = sfa_record['type']
60         pl_record = self.sfa_fields_to_pl_fields(type, hrn, sfa_record)
61
62         if type == 'authority':
63             sites = self.GetSites([pl_record['login_base']])
64             if not sites:
65                 pointer = self.AddSite(pl_record)
66             else:
67                 pointer = sites[0]['site_id']
68
69         elif type == 'slice':
70             acceptable_fields=['url', 'instantiation', 'name', 'description']
71             for key in pl_record.keys():
72                 if key not in acceptable_fields:
73                     pl_record.pop(key)
74             slices = self.GetSlices([pl_record['name']])
75             if not slices:
76                  pointer = self.AddSlice(pl_record)
77             else:
78                  pointer = slices[0]['slice_id']
79
80         elif type == 'user':
81             persons = self.GetPersons([sfa_record['email']])
82             if not persons:
83                 pointer = self.AddPerson(dict(sfa_record))
84             else:
85                 pointer = persons[0]['person_id']
86     
87             if 'enabled' in sfa_record and sfa_record['enabled']:
88                 self.UpdatePerson(pointer, {'enabled': sfa_record['enabled']})
89             # add this person to the site only if she is being added for the first
90             # time by sfa and doesont already exist in plc
91             if not persons or not persons[0]['site_ids']:
92                 login_base = get_leaf(sfa_record['authority'])
93                 self.AddPersonToSite(pointer, login_base)
94     
95             # What roles should this user have?
96             self.AddRoleToPerson('user', pointer)
97             # Add the user's key
98             if pub_key:
99                 self.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
100
101         elif type == 'node':
102             login_base = hrn_to_pl_login_base(sfa_record['authority'])
103             nodes = api.driver.GetNodes([pl_record['hostname']])
104             if not nodes:
105                 pointer = api.driver.AddNode(login_base, pl_record)
106             else:
107                 pointer = nodes[0]['node_id']
108     
109         return pointer
110         
111
112     ##
113     # Convert SFA fields to PLC fields for use when registering up updating
114     # registry record in the PLC database
115     #
116
117     def sfa_fields_to_pl_fields(self, type, hrn, sfa_record):
118
119         pl_record = {}
120  
121         if type == "slice":
122             pl_record["name"] = hrn_to_pl_slicename(hrn)
123             if "instantiation" in sfa_record:
124                 pl_record['instantiation']=sfa_record['instantiation']
125             else:
126                 pl_record["instantiation"] = "plc-instantiated"
127             if "url" in sfa_record:
128                pl_record["url"] = sfa_record["url"]
129             if "description" in sfa_record:
130                 pl_record["description"] = sfa_record["description"]
131             if "expires" in sfa_record:
132                 pl_record["expires"] = int(sfa_record["expires"])
133
134         elif type == "node":
135             if not "hostname" in pl_record:
136                 # fetch from sfa_record
137                 if "hostname" not in sfa_record:
138                     raise MissingSfaInfo("hostname")
139                 pl_record["hostname"] = sfa_record["hostname"]
140             if "model" in sfa_record: 
141                 pl_record["model"] = sfa_record["model"]
142             else:
143                 pl_record["model"] = "geni"
144
145         elif type == "authority":
146             pl_record["login_base"] = hrn_to_pl_login_base(hrn)
147             if "name" not in sfa_record:
148                 pl_record["name"] = hrn
149             if "abbreviated_name" not in sfa_record:
150                 pl_record["abbreviated_name"] = hrn
151             if "enabled" not in sfa_record:
152                 pl_record["enabled"] = True
153             if "is_public" not in sfa_record:
154                 pl_record["is_public"] = True
155
156         return pl_record
157
158     ####################
159     def fill_record_info(self, records, aggregates):
160         """
161         Given a (list of) SFA record, fill in the PLC specific 
162         and SFA specific fields in the record. 
163         """
164         if not isinstance(records, list):
165             records = [records]
166
167         self.fill_record_pl_info(records)
168         self.fill_record_sfa_info(records, aggregates)
169
170     def fill_record_pl_info(self, records):
171         """
172         Fill in the planetlab specific fields of a SFA record. This
173         involves calling the appropriate PLC method to retrieve the 
174         database record for the object.
175         
176         PLC data is filled into the pl_info field of the record.
177     
178         @param record: record to fill in field (in/out param)     
179         """
180         # get ids by type
181         node_ids, site_ids, slice_ids = [], [], [] 
182         person_ids, key_ids = [], []
183         type_map = {'node': node_ids, 'authority': site_ids,
184                     'slice': slice_ids, 'user': person_ids}
185                   
186         for record in records:
187             for type in type_map:
188                 if type == record['type']:
189                     type_map[type].append(record['pointer'])
190
191         # get pl records
192         nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
193         if node_ids:
194             node_list = self.GetNodes(node_ids)
195             nodes = list_to_dict(node_list, 'node_id')
196         if site_ids:
197             site_list = self.GetSites(site_ids)
198             sites = list_to_dict(site_list, 'site_id')
199         if slice_ids:
200             slice_list = self.GetSlices(slice_ids)
201             slices = list_to_dict(slice_list, 'slice_id')
202         if person_ids:
203             person_list = self.GetPersons(person_ids)
204             persons = list_to_dict(person_list, 'person_id')
205             for person in persons:
206                 key_ids.extend(persons[person]['key_ids'])
207
208         pl_records = {'node': nodes, 'authority': sites,
209                       'slice': slices, 'user': persons}
210
211         if key_ids:
212             key_list = self.GetKeys(key_ids)
213             keys = list_to_dict(key_list, 'key_id')
214
215         # fill record info
216         for record in records:
217             # records with pointer==-1 do not have plc info.
218             # for example, the top level authority records which are
219             # authorities, but not PL "sites"
220             if record['pointer'] == -1:
221                 continue
222            
223             for type in pl_records:
224                 if record['type'] == type:
225                     if record['pointer'] in pl_records[type]:
226                         record.update(pl_records[type][record['pointer']])
227                         break
228             # fill in key info
229             if record['type'] == 'user':
230                 if 'key_ids' not in record:
231                     logger.info("user record has no 'key_ids' - need to import from myplc ?")
232                 else:
233                     pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys] 
234                     record['keys'] = pubkeys
235
236         # fill in record hrns
237         records = self.fill_record_hrns(records)   
238  
239         return records
240
241     def fill_record_hrns(self, records):
242         """
243         convert pl ids to hrns
244         """
245
246         # get ids
247         slice_ids, person_ids, site_ids, node_ids = [], [], [], []
248         for record in records:
249             if 'site_id' in record:
250                 site_ids.append(record['site_id'])
251             if 'site_ids' in record:
252                 site_ids.extend(record['site_ids'])
253             if 'person_ids' in record:
254                 person_ids.extend(record['person_ids'])
255             if 'slice_ids' in record:
256                 slice_ids.extend(record['slice_ids'])
257             if 'node_ids' in record:
258                 node_ids.extend(record['node_ids'])
259
260         # get pl records
261         slices, persons, sites, nodes = {}, {}, {}, {}
262         if site_ids:
263             site_list = self.GetSites(site_ids, ['site_id', 'login_base'])
264             sites = list_to_dict(site_list, 'site_id')
265         if person_ids:
266             person_list = self.GetPersons(person_ids, ['person_id', 'email'])
267             persons = list_to_dict(person_list, 'person_id')
268         if slice_ids:
269             slice_list = self.GetSlices(slice_ids, ['slice_id', 'name'])
270             slices = list_to_dict(slice_list, 'slice_id')       
271         if node_ids:
272             node_list = self.GetNodes(node_ids, ['node_id', 'hostname'])
273             nodes = list_to_dict(node_list, 'node_id')
274        
275         # convert ids to hrns
276         for record in records:
277             # get all relevant data
278             type = record['type']
279             pointer = record['pointer']
280             auth_hrn = self.hrn
281             login_base = ''
282             if pointer == -1:
283                 continue
284
285             if 'site_id' in record:
286                 site = sites[record['site_id']]
287                 login_base = site['login_base']
288                 record['site'] = ".".join([auth_hrn, login_base])
289             if 'person_ids' in record:
290                 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
291                           if person_id in  persons]
292                 usernames = [email.split('@')[0] for email in emails]
293                 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
294                 record['persons'] = person_hrns 
295             if 'slice_ids' in record:
296                 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
297                               if slice_id in slices]
298                 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
299                 record['slices'] = slice_hrns
300             if 'node_ids' in record:
301                 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
302                              if node_id in nodes]
303                 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
304                 record['nodes'] = node_hrns
305             if 'site_ids' in record:
306                 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
307                                if site_id in sites]
308                 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
309                 record['sites'] = site_hrns
310             
311         return records   
312
313     # aggregates is basically api.aggregates
314     def fill_record_sfa_info(self, records, aggregates):
315
316         def startswith(prefix, values):
317             return [value for value in values if value.startswith(prefix)]
318
319         # get person ids
320         person_ids = []
321         site_ids = []
322         for record in records:
323             person_ids.extend(record.get("person_ids", []))
324             site_ids.extend(record.get("site_ids", [])) 
325             if 'site_id' in record:
326                 site_ids.append(record['site_id']) 
327         
328         # get all pis from the sites we've encountered
329         # and store them in a dictionary keyed on site_id 
330         site_pis = {}
331         if site_ids:
332             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
333             pi_list = self.GetPersons(pi_filter, ['person_id', 'site_ids'])
334             for pi in pi_list:
335                 # we will need the pi's hrns also
336                 person_ids.append(pi['person_id'])
337                 
338                 # we also need to keep track of the sites these pis
339                 # belong to
340                 for site_id in pi['site_ids']:
341                     if site_id in site_pis:
342                         site_pis[site_id].append(pi)
343                     else:
344                         site_pis[site_id] = [pi]
345                  
346         # get sfa records for all records associated with these records.   
347         # we'll replace pl ids (person_ids) with hrns from the sfa records
348         # we obtain
349         
350         # get the sfa records
351         # xxx thgen fixme - use SfaTable hardwired for now 
352         # table = self.SfaTable()
353         table = SfaTable()
354         person_list, persons = [], {}
355         person_list = table.find({'type': 'user', 'pointer': person_ids})
356         # create a hrns keyed on the sfa record's pointer.
357         # Its possible for multiple records to have the same pointer so
358         # the dict's value will be a list of hrns.
359         persons = defaultdict(list)
360         for person in person_list:
361             persons[person['pointer']].append(person)
362
363         # get the pl records
364         pl_person_list, pl_persons = [], {}
365         pl_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
366         pl_persons = list_to_dict(pl_person_list, 'person_id')
367
368         # fill sfa info
369         for record in records:
370             # skip records with no pl info (top level authorities)
371             #if record['pointer'] == -1:
372             #    continue 
373             sfa_info = {}
374             type = record['type']
375             if (type == "slice"):
376                 # all slice users are researchers
377                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
378                 record['PI'] = []
379                 record['researcher'] = []
380                 for person_id in record.get('person_ids', []):
381                     hrns = [person['hrn'] for person in persons[person_id]]
382                     record['researcher'].extend(hrns)                
383
384                 # pis at the slice's site
385                 if 'site_id' in record and record['site_id'] in site_pis:
386                     pl_pis = site_pis[record['site_id']]
387                     pi_ids = [pi['person_id'] for pi in pl_pis]
388                     for person_id in pi_ids:
389                         hrns = [person['hrn'] for person in persons[person_id]]
390                         record['PI'].extend(hrns)
391                         record['geni_creator'] = record['PI'] 
392                 
393             elif (type.startswith("authority")):
394                 record['url'] = None
395                 if record['hrn'] in aggregates:
396                     
397                     record['url'] = aggregates[record['hrn']].get_url()
398
399                 if record['pointer'] != -1:
400                     record['PI'] = []
401                     record['operator'] = []
402                     record['owner'] = []
403                     for pointer in record.get('person_ids', []):
404                         if pointer not in persons or pointer not in pl_persons:
405                             # this means there is not sfa or pl record for this user
406                             continue   
407                         hrns = [person['hrn'] for person in persons[pointer]] 
408                         roles = pl_persons[pointer]['roles']   
409                         if 'pi' in roles:
410                             record['PI'].extend(hrns)
411                         if 'tech' in roles:
412                             record['operator'].extend(hrns)
413                         if 'admin' in roles:
414                             record['owner'].extend(hrns)
415                         # xxx TODO: OrganizationName
416             elif (type == "node"):
417                 sfa_info['dns'] = record.get("hostname", "")
418                 # xxx TODO: URI, LatLong, IP, DNS
419     
420             elif (type == "user"):
421                 sfa_info['email'] = record.get("email", "")
422                 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
423                 sfa_info['geni_certificate'] = record['gid'] 
424                 # xxx TODO: PostalAddress, Phone
425             record.update(sfa_info)
426
427     ####################
428     def update_membership(self, oldRecord, record):
429         if record.type == "slice":
430             self.update_membership_list(oldRecord, record, 'researcher',
431                                         self.AddPersonToSlice,
432                                         self.DeletePersonFromSlice)
433         elif record.type == "authority":
434             # xxx TODO
435             pass
436
437     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
438         # get a list of the HRNs that are members of the old and new records
439         if oldRecord:
440             oldList = oldRecord.get(listName, [])
441         else:
442             oldList = []     
443         newList = record.get(listName, [])
444
445         # if the lists are the same, then we don't have to update anything
446         if (oldList == newList):
447             return
448
449         # build a list of the new person ids, by looking up each person to get
450         # their pointer
451         newIdList = []
452         # xxx thgen fixme - use SfaTable hardwired for now 
453         #table = self.SfaTable()
454         table = SfaTable()
455         records = table.find({'type': 'user', 'hrn': newList})
456         for rec in records:
457             newIdList.append(rec['pointer'])
458
459         # build a list of the old person ids from the person_ids field 
460         if oldRecord:
461             oldIdList = oldRecord.get("person_ids", [])
462             containerId = oldRecord.get_pointer()
463         else:
464             # if oldRecord==None, then we are doing a Register, instead of an
465             # update.
466             oldIdList = []
467             containerId = record.get_pointer()
468
469     # add people who are in the new list, but not the oldList
470         for personId in newIdList:
471             if not (personId in oldIdList):
472                 addFunc(personId, containerId)
473
474         # remove people who are in the old list, but not the new list
475         for personId in oldIdList:
476             if not (personId in newIdList):
477                 delFunc(personId, containerId)