Merge branch 'master' of ssh://git.onelab.eu/git/sfa
[sfa.git] / sfa / plc / pldriver.py
1 #
2 from sfa.util.faults import MissingSfaInfo, UnknownSfaType
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     return dict ( [ (rec[key],rec) for rec in recs ] )
21
22 #
23 # PlShell is just an xmlrpc serverproxy where methods
24 # can be sent as-is; it takes care of authentication
25 # from the global config
26
27 # so we inherit PlShell just so one can do driver.GetNodes
28 # which would not make much sense in the context of other testbeds
29 # so ultimately PlDriver should drop the PlShell inheritance
30 # and would have a driver.shell reference to a PlShell instead
31
32 class PlDriver (Driver, PlShell):
33
34     def __init__ (self, config):
35         PlShell.__init__ (self, config)
36  
37         self.hrn = config.SFA_INTERFACE_HRN
38         # xxx thgen fixme - use SfaTable hardwired for now 
39         # will need to extend generic to support multiple storage systems
40         #self.SfaTable = SfaTable
41         # Initialize the PLC shell only if SFA wraps a myPLC
42         rspec_type = config.get_aggregate_type()
43         assert (rspec_type == 'pl' or rspec_type == 'vini' or \
44                     rspec_type == 'eucalyptus' or rspec_type == 'max')
45
46     ########## disabled users 
47     def is_enabled (self, record):
48         self.fill_record_info(record, deep=False)
49         if record['type'] == 'user':
50             return record['enabled']
51         # only users can be disabled
52         return True
53
54     def augment_records_with_testbed_info (self, sfa_records):
55         return self.fill_record_info (sfa_records, deep=True)
56
57     ########## 
58     def register (self, sfa_record, hrn, 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     # xxx actually old_sfa_record comes filled with plc stuff as well in the original code
113     def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
114         pointer = old_sfa_record['pointer']
115         type = old_sfa_record['type']
116
117         # new_key implemented for users only
118         if new_key and type not in [ 'user' ]:
119             raise UnknownSfaType(type)
120
121         if (type == "authority"):
122             self.UpdateSite(pointer, new_sfa_record)
123     
124         elif type == "slice":
125             pl_record=self.sfa_fields_to_pl_fields(type, hrn, new_sfa_record)
126             if 'name' in pl_record:
127                 pl_record.pop('name')
128                 self.UpdateSlice(pointer, pl_record)
129     
130         elif type == "user":
131             # SMBAKER: UpdatePerson only allows a limited set of fields to be
132             #    updated. Ideally we should have a more generic way of doing
133             #    this. I copied the field names from UpdatePerson.py...
134             update_fields = {}
135             all_fields = new_sfa_record
136             for key in all_fields.keys():
137                 if key in ['first_name', 'last_name', 'title', 'email',
138                            'password', 'phone', 'url', 'bio', 'accepted_aup',
139                            'enabled']:
140                     update_fields[key] = all_fields[key]
141             self.UpdatePerson(pointer, update_fields)
142     
143             if new_key:
144                 # must check this key against the previous one if it exists
145                 persons = self.GetPersons([pointer], ['key_ids'])
146                 person = persons[0]
147                 keys = person['key_ids']
148                 keys = self.GetKeys(person['key_ids'])
149                 
150                 # Delete all stale keys
151                 key_exists = False
152                 for key in keys:
153                     if new_key != key['key']:
154                         self.DeleteKey(key['key_id'])
155                     else:
156                         key_exists = True
157                 if not key_exists:
158                     self.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
159     
160         elif type == "node":
161             self.UpdateNode(pointer, new_sfa_record)
162
163         return True
164         
165
166     ##########
167     def remove (self, sfa_record):
168         type=sfa_record['type']
169         pointer=sfa_record['pointer']
170         if type == 'user':
171             persons = self.GetPersons(pointer)
172             # only delete this person if he has site ids. if he doesnt, it probably means
173             # he was just removed from a site, not actually deleted
174             if persons and persons[0]['site_ids']:
175                 self.DeletePerson(pointer)
176         elif type == 'slice':
177             if self.GetSlices(pointer):
178                 self.DeleteSlice(pointer)
179         elif type == 'node':
180             if self.GetNodes(pointer):
181                 self.DeleteNode(pointer)
182         elif type == 'authority':
183             if self.GetSites(pointer):
184                 self.DeleteSite(pointer)
185
186         return True
187
188
189
190
191
192     ##
193     # Convert SFA fields to PLC fields for use when registering up updating
194     # registry record in the PLC database
195     #
196
197     def sfa_fields_to_pl_fields(self, type, hrn, sfa_record):
198
199         pl_record = {}
200  
201         if type == "slice":
202             pl_record["name"] = hrn_to_pl_slicename(hrn)
203             if "instantiation" in sfa_record:
204                 pl_record['instantiation']=sfa_record['instantiation']
205             else:
206                 pl_record["instantiation"] = "plc-instantiated"
207             if "url" in sfa_record:
208                pl_record["url"] = sfa_record["url"]
209             if "description" in sfa_record:
210                 pl_record["description"] = sfa_record["description"]
211             if "expires" in sfa_record:
212                 pl_record["expires"] = int(sfa_record["expires"])
213
214         elif type == "node":
215             if not "hostname" in pl_record:
216                 # fetch from sfa_record
217                 if "hostname" not in sfa_record:
218                     raise MissingSfaInfo("hostname")
219                 pl_record["hostname"] = sfa_record["hostname"]
220             if "model" in sfa_record: 
221                 pl_record["model"] = sfa_record["model"]
222             else:
223                 pl_record["model"] = "geni"
224
225         elif type == "authority":
226             pl_record["login_base"] = hrn_to_pl_login_base(hrn)
227             if "name" not in sfa_record:
228                 pl_record["name"] = hrn
229             if "abbreviated_name" not in sfa_record:
230                 pl_record["abbreviated_name"] = hrn
231             if "enabled" not in sfa_record:
232                 pl_record["enabled"] = True
233             if "is_public" not in sfa_record:
234                 pl_record["is_public"] = True
235
236         return pl_record
237
238     ####################
239     def fill_record_info(self, records, deep=False):
240         """
241         Given a (list of) SFA record, fill in the PLC specific 
242         and SFA specific fields in the record. 
243         """
244         if not isinstance(records, list):
245             records = [records]
246
247         self.fill_record_pl_info(records)
248         if deep:
249             self.fill_record_hrns(records)
250             self.fill_record_sfa_info(records)
251         return records
252
253     def fill_record_pl_info(self, records):
254         """
255         Fill in the planetlab specific fields of a SFA record. This
256         involves calling the appropriate PLC method to retrieve the 
257         database record for the object.
258             
259         @param record: record to fill in field (in/out param)     
260         """
261         # get ids by type
262         node_ids, site_ids, slice_ids = [], [], [] 
263         person_ids, key_ids = [], []
264         type_map = {'node': node_ids, 'authority': site_ids,
265                     'slice': slice_ids, 'user': person_ids}
266                   
267         for record in records:
268             for type in type_map:
269                 if type == record['type']:
270                     type_map[type].append(record['pointer'])
271
272         # get pl records
273         nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
274         if node_ids:
275             node_list = self.GetNodes(node_ids)
276             nodes = list_to_dict(node_list, 'node_id')
277         if site_ids:
278             site_list = self.GetSites(site_ids)
279             sites = list_to_dict(site_list, 'site_id')
280         if slice_ids:
281             slice_list = self.GetSlices(slice_ids)
282             slices = list_to_dict(slice_list, 'slice_id')
283         if person_ids:
284             person_list = self.GetPersons(person_ids)
285             persons = list_to_dict(person_list, 'person_id')
286             for person in persons:
287                 key_ids.extend(persons[person]['key_ids'])
288
289         pl_records = {'node': nodes, 'authority': sites,
290                       'slice': slices, 'user': persons}
291
292         if key_ids:
293             key_list = self.GetKeys(key_ids)
294             keys = list_to_dict(key_list, 'key_id')
295
296         # fill record info
297         for record in records:
298             # records with pointer==-1 do not have plc info.
299             # for example, the top level authority records which are
300             # authorities, but not PL "sites"
301             if record['pointer'] == -1:
302                 continue
303            
304             for type in pl_records:
305                 if record['type'] == type:
306                     if record['pointer'] in pl_records[type]:
307                         record.update(pl_records[type][record['pointer']])
308                         break
309             # fill in key info
310             if record['type'] == 'user':
311                 if 'key_ids' not in record:
312                     logger.info("user record has no 'key_ids' - need to import from myplc ?")
313                 else:
314                     pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys] 
315                     record['keys'] = pubkeys
316
317         return records
318
319     def fill_record_hrns(self, records):
320         """
321         convert pl ids to hrns
322         """
323
324         # get ids
325         slice_ids, person_ids, site_ids, node_ids = [], [], [], []
326         for record in records:
327             if 'site_id' in record:
328                 site_ids.append(record['site_id'])
329             if 'site_ids' in record:
330                 site_ids.extend(record['site_ids'])
331             if 'person_ids' in record:
332                 person_ids.extend(record['person_ids'])
333             if 'slice_ids' in record:
334                 slice_ids.extend(record['slice_ids'])
335             if 'node_ids' in record:
336                 node_ids.extend(record['node_ids'])
337
338         # get pl records
339         slices, persons, sites, nodes = {}, {}, {}, {}
340         if site_ids:
341             site_list = self.GetSites(site_ids, ['site_id', 'login_base'])
342             sites = list_to_dict(site_list, 'site_id')
343         if person_ids:
344             person_list = self.GetPersons(person_ids, ['person_id', 'email'])
345             persons = list_to_dict(person_list, 'person_id')
346         if slice_ids:
347             slice_list = self.GetSlices(slice_ids, ['slice_id', 'name'])
348             slices = list_to_dict(slice_list, 'slice_id')       
349         if node_ids:
350             node_list = self.GetNodes(node_ids, ['node_id', 'hostname'])
351             nodes = list_to_dict(node_list, 'node_id')
352        
353         # convert ids to hrns
354         for record in records:
355             # get all relevant data
356             type = record['type']
357             pointer = record['pointer']
358             auth_hrn = self.hrn
359             login_base = ''
360             if pointer == -1:
361                 continue
362
363             if 'site_id' in record:
364                 site = sites[record['site_id']]
365                 login_base = site['login_base']
366                 record['site'] = ".".join([auth_hrn, login_base])
367             if 'person_ids' in record:
368                 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
369                           if person_id in  persons]
370                 usernames = [email.split('@')[0] for email in emails]
371                 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
372                 record['persons'] = person_hrns 
373             if 'slice_ids' in record:
374                 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
375                               if slice_id in slices]
376                 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
377                 record['slices'] = slice_hrns
378             if 'node_ids' in record:
379                 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
380                              if node_id in nodes]
381                 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
382                 record['nodes'] = node_hrns
383             if 'site_ids' in record:
384                 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
385                                if site_id in sites]
386                 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
387                 record['sites'] = site_hrns
388             
389         return records   
390
391     # aggregates is basically api.aggregates
392     def fill_record_sfa_info(self, records):
393
394         def startswith(prefix, values):
395             return [value for value in values if value.startswith(prefix)]
396
397         # get person ids
398         person_ids = []
399         site_ids = []
400         for record in records:
401             person_ids.extend(record.get("person_ids", []))
402             site_ids.extend(record.get("site_ids", [])) 
403             if 'site_id' in record:
404                 site_ids.append(record['site_id']) 
405         
406         # get all pis from the sites we've encountered
407         # and store them in a dictionary keyed on site_id 
408         site_pis = {}
409         if site_ids:
410             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
411             pi_list = self.GetPersons(pi_filter, ['person_id', 'site_ids'])
412             for pi in pi_list:
413                 # we will need the pi's hrns also
414                 person_ids.append(pi['person_id'])
415                 
416                 # we also need to keep track of the sites these pis
417                 # belong to
418                 for site_id in pi['site_ids']:
419                     if site_id in site_pis:
420                         site_pis[site_id].append(pi)
421                     else:
422                         site_pis[site_id] = [pi]
423                  
424         # get sfa records for all records associated with these records.   
425         # we'll replace pl ids (person_ids) with hrns from the sfa records
426         # we obtain
427         
428         # get the sfa records
429         # xxx thgen fixme - use SfaTable hardwired for now 
430         # table = self.SfaTable()
431         table = SfaTable()
432         person_list, persons = [], {}
433         person_list = table.find({'type': 'user', 'pointer': person_ids})
434         # create a hrns keyed on the sfa record's pointer.
435         # Its possible for multiple records to have the same pointer so
436         # the dict's value will be a list of hrns.
437         persons = defaultdict(list)
438         for person in person_list:
439             persons[person['pointer']].append(person)
440
441         # get the pl records
442         pl_person_list, pl_persons = [], {}
443         pl_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
444         pl_persons = list_to_dict(pl_person_list, 'person_id')
445
446         # fill sfa info
447         for record in records:
448             # skip records with no pl info (top level authorities)
449             #if record['pointer'] == -1:
450             #    continue 
451             sfa_info = {}
452             type = record['type']
453             if (type == "slice"):
454                 # all slice users are researchers
455                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
456                 record['PI'] = []
457                 record['researcher'] = []
458                 for person_id in record.get('person_ids', []):
459                     hrns = [person['hrn'] for person in persons[person_id]]
460                     record['researcher'].extend(hrns)                
461
462                 # pis at the slice's site
463                 if 'site_id' in record and record['site_id'] in site_pis:
464                     pl_pis = site_pis[record['site_id']]
465                     pi_ids = [pi['person_id'] for pi in pl_pis]
466                     for person_id in pi_ids:
467                         hrns = [person['hrn'] for person in persons[person_id]]
468                         record['PI'].extend(hrns)
469                         record['geni_creator'] = record['PI'] 
470                 
471             elif (type.startswith("authority")):
472                 record['url'] = None
473                 if record['pointer'] != -1:
474                     record['PI'] = []
475                     record['operator'] = []
476                     record['owner'] = []
477                     for pointer in record.get('person_ids', []):
478                         if pointer not in persons or pointer not in pl_persons:
479                             # this means there is not sfa or pl record for this user
480                             continue   
481                         hrns = [person['hrn'] for person in persons[pointer]] 
482                         roles = pl_persons[pointer]['roles']   
483                         if 'pi' in roles:
484                             record['PI'].extend(hrns)
485                         if 'tech' in roles:
486                             record['operator'].extend(hrns)
487                         if 'admin' in roles:
488                             record['owner'].extend(hrns)
489                         # xxx TODO: OrganizationName
490             elif (type == "node"):
491                 sfa_info['dns'] = record.get("hostname", "")
492                 # xxx TODO: URI, LatLong, IP, DNS
493     
494             elif (type == "user"):
495                 sfa_info['email'] = record.get("email", "")
496                 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
497                 sfa_info['geni_certificate'] = record['gid'] 
498                 # xxx TODO: PostalAddress, Phone
499             record.update(sfa_info)
500
501
502     ####################
503     # plcapi works by changes, compute what needs to be added/deleted
504     def update_relation (self, subject_type, target_type, subject_id, target_ids):
505         # hard-wire the code for slice/user for now
506         if subject_type =='slice' and target_type == 'user':
507             subject=self.GetSlices (subject_id)[0]
508             current_target_ids = subject['person_ids']
509             add_target_ids = list ( set (target_ids).difference(current_target_ids))
510             del_target_ids = list ( set (current_target_ids).difference(target_ids))
511             logger.info ("subject_id = %s (type=%s)"%(subject_id,type(subject_id)))
512             for target_id in add_target_ids:
513                 self.AddPersonToSlice (target_id,subject_id)
514                 logger.info ("add_target_id = %s (type=%s)"%(target_id,type(target_id)))
515             for target_id in del_target_ids:
516                 logger.info ("del_target_id = %s (type=%s)"%(target_id,type(target_id)))
517                 self.DeletePersonFromSlice (target_id, subject_id)
518         else:
519             logger.info('unexpected relation to maintain, %s -> %s'%(subject_type,target_type))
520
521