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
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
10 # the driver interface, mostly provides default behaviours
11 from sfa.managers.driver import Driver
13 from sfa.plc.plshell import PlShell
15 def list_to_dict(recs, key):
17 convert a list of dictionaries into a dictionary keyed on the
18 specified dictionary key
20 return dict ( [ (rec[key],rec) for rec in recs ] )
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
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
32 class PlDriver (Driver, PlShell):
34 def __init__ (self, config):
35 PlShell.__init__ (self, config)
37 self.hrn = config.SFA_INTERFACE_HRN
39 ########## disabled users
40 def is_enabled (self, record):
41 # the incoming record was augmented already, so 'enabled' should be set
42 if record['type'] == 'user':
43 return record['enabled']
44 # only users can be disabled
47 def augment_records_with_testbed_info (self, sfa_records):
48 return self.fill_record_info (sfa_records)
51 def register (self, sfa_record, hrn, pub_key):
52 type = sfa_record['type']
53 pl_record = self.sfa_fields_to_pl_fields(type, hrn, sfa_record)
55 if type == 'authority':
56 sites = self.GetSites([pl_record['login_base']])
58 pointer = self.AddSite(pl_record)
60 pointer = sites[0]['site_id']
63 acceptable_fields=['url', 'instantiation', 'name', 'description']
64 for key in pl_record.keys():
65 if key not in acceptable_fields:
67 slices = self.GetSlices([pl_record['name']])
69 pointer = self.AddSlice(pl_record)
71 pointer = slices[0]['slice_id']
74 persons = self.GetPersons([sfa_record['email']])
76 pointer = self.AddPerson(dict(sfa_record))
78 pointer = persons[0]['person_id']
80 if 'enabled' in sfa_record and sfa_record['enabled']:
81 self.UpdatePerson(pointer, {'enabled': sfa_record['enabled']})
82 # add this person to the site only if she is being added for the first
83 # time by sfa and doesont already exist in plc
84 if not persons or not persons[0]['site_ids']:
85 login_base = get_leaf(sfa_record['authority'])
86 self.AddPersonToSite(pointer, login_base)
88 # What roles should this user have?
89 self.AddRoleToPerson('user', pointer)
92 self.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
95 login_base = hrn_to_pl_login_base(sfa_record['authority'])
96 nodes = api.driver.GetNodes([pl_record['hostname']])
98 pointer = api.driver.AddNode(login_base, pl_record)
100 pointer = nodes[0]['node_id']
105 # xxx actually old_sfa_record comes filled with plc stuff as well in the original code
106 def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
107 pointer = old_sfa_record['pointer']
108 type = old_sfa_record['type']
110 # new_key implemented for users only
111 if new_key and type not in [ 'user' ]:
112 raise UnknownSfaType(type)
114 if (type == "authority"):
115 self.UpdateSite(pointer, new_sfa_record)
117 elif type == "slice":
118 pl_record=self.sfa_fields_to_pl_fields(type, hrn, new_sfa_record)
119 if 'name' in pl_record:
120 pl_record.pop('name')
121 self.UpdateSlice(pointer, pl_record)
124 # SMBAKER: UpdatePerson only allows a limited set of fields to be
125 # updated. Ideally we should have a more generic way of doing
126 # this. I copied the field names from UpdatePerson.py...
128 all_fields = new_sfa_record
129 for key in all_fields.keys():
130 if key in ['first_name', 'last_name', 'title', 'email',
131 'password', 'phone', 'url', 'bio', 'accepted_aup',
133 update_fields[key] = all_fields[key]
134 self.UpdatePerson(pointer, update_fields)
137 # must check this key against the previous one if it exists
138 persons = self.GetPersons([pointer], ['key_ids'])
140 keys = person['key_ids']
141 keys = self.GetKeys(person['key_ids'])
143 # Delete all stale keys
146 if new_key != key['key']:
147 self.DeleteKey(key['key_id'])
151 self.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
154 self.UpdateNode(pointer, new_sfa_record)
160 def remove (self, sfa_record):
161 type=sfa_record['type']
162 pointer=sfa_record['pointer']
164 persons = self.GetPersons(pointer)
165 # only delete this person if he has site ids. if he doesnt, it probably means
166 # he was just removed from a site, not actually deleted
167 if persons and persons[0]['site_ids']:
168 self.DeletePerson(pointer)
169 elif type == 'slice':
170 if self.GetSlices(pointer):
171 self.DeleteSlice(pointer)
173 if self.GetNodes(pointer):
174 self.DeleteNode(pointer)
175 elif type == 'authority':
176 if self.GetSites(pointer):
177 self.DeleteSite(pointer)
186 # Convert SFA fields to PLC fields for use when registering up updating
187 # registry record in the PLC database
190 def sfa_fields_to_pl_fields(self, type, hrn, sfa_record):
195 pl_record["name"] = hrn_to_pl_slicename(hrn)
196 if "instantiation" in sfa_record:
197 pl_record['instantiation']=sfa_record['instantiation']
199 pl_record["instantiation"] = "plc-instantiated"
200 if "url" in sfa_record:
201 pl_record["url"] = sfa_record["url"]
202 if "description" in sfa_record:
203 pl_record["description"] = sfa_record["description"]
204 if "expires" in sfa_record:
205 pl_record["expires"] = int(sfa_record["expires"])
208 if not "hostname" in pl_record:
209 # fetch from sfa_record
210 if "hostname" not in sfa_record:
211 raise MissingSfaInfo("hostname")
212 pl_record["hostname"] = sfa_record["hostname"]
213 if "model" in sfa_record:
214 pl_record["model"] = sfa_record["model"]
216 pl_record["model"] = "geni"
218 elif type == "authority":
219 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
220 if "name" not in sfa_record:
221 pl_record["name"] = hrn
222 if "abbreviated_name" not in sfa_record:
223 pl_record["abbreviated_name"] = hrn
224 if "enabled" not in sfa_record:
225 pl_record["enabled"] = True
226 if "is_public" not in sfa_record:
227 pl_record["is_public"] = True
232 def fill_record_info(self, records):
234 Given a (list of) SFA record, fill in the PLC specific
235 and SFA specific fields in the record.
237 if not isinstance(records, list):
240 self.fill_record_pl_info(records)
241 self.fill_record_hrns(records)
242 self.fill_record_sfa_info(records)
245 def fill_record_pl_info(self, records):
247 Fill in the planetlab specific fields of a SFA record. This
248 involves calling the appropriate PLC method to retrieve the
249 database record for the object.
251 @param record: record to fill in field (in/out param)
254 node_ids, site_ids, slice_ids = [], [], []
255 person_ids, key_ids = [], []
256 type_map = {'node': node_ids, 'authority': site_ids,
257 'slice': slice_ids, 'user': person_ids}
259 for record in records:
260 for type in type_map:
261 if type == record['type']:
262 type_map[type].append(record['pointer'])
265 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
267 node_list = self.GetNodes(node_ids)
268 nodes = list_to_dict(node_list, 'node_id')
270 site_list = self.GetSites(site_ids)
271 sites = list_to_dict(site_list, 'site_id')
273 slice_list = self.GetSlices(slice_ids)
274 slices = list_to_dict(slice_list, 'slice_id')
276 person_list = self.GetPersons(person_ids)
277 persons = list_to_dict(person_list, 'person_id')
278 for person in persons:
279 key_ids.extend(persons[person]['key_ids'])
281 pl_records = {'node': nodes, 'authority': sites,
282 'slice': slices, 'user': persons}
285 key_list = self.GetKeys(key_ids)
286 keys = list_to_dict(key_list, 'key_id')
289 for record in records:
290 # records with pointer==-1 do not have plc info.
291 # for example, the top level authority records which are
292 # authorities, but not PL "sites"
293 if record['pointer'] == -1:
296 for type in pl_records:
297 if record['type'] == type:
298 if record['pointer'] in pl_records[type]:
299 record.update(pl_records[type][record['pointer']])
302 if record['type'] == 'user':
303 if 'key_ids' not in record:
304 logger.info("user record has no 'key_ids' - need to import from myplc ?")
306 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
307 record['keys'] = pubkeys
311 def fill_record_hrns(self, records):
313 convert pl ids to hrns
317 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
318 for record in records:
319 if 'site_id' in record:
320 site_ids.append(record['site_id'])
321 if 'site_ids' in record:
322 site_ids.extend(record['site_ids'])
323 if 'person_ids' in record:
324 person_ids.extend(record['person_ids'])
325 if 'slice_ids' in record:
326 slice_ids.extend(record['slice_ids'])
327 if 'node_ids' in record:
328 node_ids.extend(record['node_ids'])
331 slices, persons, sites, nodes = {}, {}, {}, {}
333 site_list = self.GetSites(site_ids, ['site_id', 'login_base'])
334 sites = list_to_dict(site_list, 'site_id')
336 person_list = self.GetPersons(person_ids, ['person_id', 'email'])
337 persons = list_to_dict(person_list, 'person_id')
339 slice_list = self.GetSlices(slice_ids, ['slice_id', 'name'])
340 slices = list_to_dict(slice_list, 'slice_id')
342 node_list = self.GetNodes(node_ids, ['node_id', 'hostname'])
343 nodes = list_to_dict(node_list, 'node_id')
345 # convert ids to hrns
346 for record in records:
347 # get all relevant data
348 type = record['type']
349 pointer = record['pointer']
355 if 'site_id' in record:
356 site = sites[record['site_id']]
357 login_base = site['login_base']
358 record['site'] = ".".join([auth_hrn, login_base])
359 if 'person_ids' in record:
360 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
361 if person_id in persons]
362 usernames = [email.split('@')[0] for email in emails]
363 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
364 record['persons'] = person_hrns
365 if 'slice_ids' in record:
366 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
367 if slice_id in slices]
368 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
369 record['slices'] = slice_hrns
370 if 'node_ids' in record:
371 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
373 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
374 record['nodes'] = node_hrns
375 if 'site_ids' in record:
376 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
378 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
379 record['sites'] = site_hrns
383 # aggregates is basically api.aggregates
384 def fill_record_sfa_info(self, records):
386 def startswith(prefix, values):
387 return [value for value in values if value.startswith(prefix)]
392 for record in records:
393 person_ids.extend(record.get("person_ids", []))
394 site_ids.extend(record.get("site_ids", []))
395 if 'site_id' in record:
396 site_ids.append(record['site_id'])
398 # get all pis from the sites we've encountered
399 # and store them in a dictionary keyed on site_id
402 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
403 pi_list = self.GetPersons(pi_filter, ['person_id', 'site_ids'])
405 # we will need the pi's hrns also
406 person_ids.append(pi['person_id'])
408 # we also need to keep track of the sites these pis
410 for site_id in pi['site_ids']:
411 if site_id in site_pis:
412 site_pis[site_id].append(pi)
414 site_pis[site_id] = [pi]
416 # get sfa records for all records associated with these records.
417 # we'll replace pl ids (person_ids) with hrns from the sfa records
420 # get the sfa records
421 # xxx thgen fixme - use SfaTable hardwired for now
422 # table = self.SfaTable()
424 person_list, persons = [], {}
425 person_list = table.find({'type': 'user', 'pointer': person_ids})
426 # create a hrns keyed on the sfa record's pointer.
427 # Its possible for multiple records to have the same pointer so
428 # the dict's value will be a list of hrns.
429 persons = defaultdict(list)
430 for person in person_list:
431 persons[person['pointer']].append(person)
434 pl_person_list, pl_persons = [], {}
435 pl_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
436 pl_persons = list_to_dict(pl_person_list, 'person_id')
439 for record in records:
440 # skip records with no pl info (top level authorities)
441 #if record['pointer'] == -1:
444 type = record['type']
445 if (type == "slice"):
446 # all slice users are researchers
447 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
449 record['researcher'] = []
450 for person_id in record.get('person_ids', []):
451 hrns = [person['hrn'] for person in persons[person_id]]
452 record['researcher'].extend(hrns)
454 # pis at the slice's site
455 if 'site_id' in record and record['site_id'] in site_pis:
456 pl_pis = site_pis[record['site_id']]
457 pi_ids = [pi['person_id'] for pi in pl_pis]
458 for person_id in pi_ids:
459 hrns = [person['hrn'] for person in persons[person_id]]
460 record['PI'].extend(hrns)
461 record['geni_creator'] = record['PI']
463 elif (type.startswith("authority")):
465 if record['pointer'] != -1:
467 record['operator'] = []
469 for pointer in record.get('person_ids', []):
470 if pointer not in persons or pointer not in pl_persons:
471 # this means there is not sfa or pl record for this user
473 hrns = [person['hrn'] for person in persons[pointer]]
474 roles = pl_persons[pointer]['roles']
476 record['PI'].extend(hrns)
478 record['operator'].extend(hrns)
480 record['owner'].extend(hrns)
481 # xxx TODO: OrganizationName
482 elif (type == "node"):
483 sfa_info['dns'] = record.get("hostname", "")
484 # xxx TODO: URI, LatLong, IP, DNS
486 elif (type == "user"):
487 sfa_info['email'] = record.get("email", "")
488 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
489 sfa_info['geni_certificate'] = record['gid']
490 # xxx TODO: PostalAddress, Phone
491 record.update(sfa_info)
495 # plcapi works by changes, compute what needs to be added/deleted
496 def update_relation (self, subject_type, target_type, subject_id, target_ids):
497 # hard-wire the code for slice/user for now, could be smarter if needed
498 if subject_type =='slice' and target_type == 'user':
499 subject=self.GetSlices (subject_id)[0]
500 current_target_ids = subject['person_ids']
501 add_target_ids = list ( set (target_ids).difference(current_target_ids))
502 del_target_ids = list ( set (current_target_ids).difference(target_ids))
503 logger.info ("subject_id = %s (type=%s)"%(subject_id,type(subject_id)))
504 for target_id in add_target_ids:
505 self.AddPersonToSlice (target_id,subject_id)
506 logger.info ("add_target_id = %s (type=%s)"%(target_id,type(target_id)))
507 for target_id in del_target_ids:
508 logger.info ("del_target_id = %s (type=%s)"%(target_id,type(target_id)))
509 self.DeletePersonFromSlice (target_id, subject_id)
511 logger.info('unexpected relation to maintain, %s -> %s'%(subject_type,target_type))