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
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 keys = [rec[key] for rec in recs]
21 return dict(zip(keys, recs))
24 # inheriting Driver is not very helpful in the PL case but
25 # makes sense in the general case
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
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
35 class PlDriver (Driver, PlShell):
37 def __init__ (self, config):
38 PlShell.__init__ (self, config)
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')
49 ########## disabled users
50 def is_enabled_entity (self, record, aggregates):
51 self.fill_record_info(record, api.aggregates)
52 if record['type'] == 'user':
53 return record['enabled']
54 # only users can be disabled
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)
62 if type == 'authority':
63 sites = self.GetSites([pl_record['login_base']])
65 pointer = self.AddSite(pl_record)
67 pointer = sites[0]['site_id']
70 acceptable_fields=['url', 'instantiation', 'name', 'description']
71 for key in pl_record.keys():
72 if key not in acceptable_fields:
74 slices = self.GetSlices([pl_record['name']])
76 pointer = self.AddSlice(pl_record)
78 pointer = slices[0]['slice_id']
81 persons = self.GetPersons([sfa_record['email']])
83 pointer = self.AddPerson(dict(sfa_record))
85 pointer = persons[0]['person_id']
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)
95 # What roles should this user have?
96 self.AddRoleToPerson('user', pointer)
99 self.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
102 login_base = hrn_to_pl_login_base(sfa_record['authority'])
103 nodes = api.driver.GetNodes([pl_record['hostname']])
105 pointer = api.driver.AddNode(login_base, pl_record)
107 pointer = nodes[0]['node_id']
113 # Convert SFA fields to PLC fields for use when registering up updating
114 # registry record in the PLC database
117 def sfa_fields_to_pl_fields(self, type, hrn, sfa_record):
122 pl_record["name"] = hrn_to_pl_slicename(hrn)
123 if "instantiation" in sfa_record:
124 pl_record['instantiation']=sfa_record['instantiation']
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"])
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"]
143 pl_record["model"] = "geni"
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
159 def fill_record_info(self, records, aggregates):
161 Given a (list of) SFA record, fill in the PLC specific
162 and SFA specific fields in the record.
164 if not isinstance(records, list):
167 self.fill_record_pl_info(records)
168 self.fill_record_sfa_info(records, aggregates)
170 def fill_record_pl_info(self, records):
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.
176 PLC data is filled into the pl_info field of the record.
178 @param record: record to fill in field (in/out param)
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}
186 for record in records:
187 for type in type_map:
188 if type == record['type']:
189 type_map[type].append(record['pointer'])
192 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
194 node_list = self.GetNodes(node_ids)
195 nodes = list_to_dict(node_list, 'node_id')
197 site_list = self.GetSites(site_ids)
198 sites = list_to_dict(site_list, 'site_id')
200 slice_list = self.GetSlices(slice_ids)
201 slices = list_to_dict(slice_list, 'slice_id')
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'])
208 pl_records = {'node': nodes, 'authority': sites,
209 'slice': slices, 'user': persons}
212 key_list = self.GetKeys(key_ids)
213 keys = list_to_dict(key_list, 'key_id')
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:
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']])
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 ?")
233 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
234 record['keys'] = pubkeys
236 # fill in record hrns
237 records = self.fill_record_hrns(records)
241 def fill_record_hrns(self, records):
243 convert pl ids to hrns
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'])
261 slices, persons, sites, nodes = {}, {}, {}, {}
263 site_list = self.GetSites(site_ids, ['site_id', 'login_base'])
264 sites = list_to_dict(site_list, 'site_id')
266 person_list = self.GetPersons(person_ids, ['person_id', 'email'])
267 persons = list_to_dict(person_list, 'person_id')
269 slice_list = self.GetSlices(slice_ids, ['slice_id', 'name'])
270 slices = list_to_dict(slice_list, 'slice_id')
272 node_list = self.GetNodes(node_ids, ['node_id', 'hostname'])
273 nodes = list_to_dict(node_list, 'node_id')
275 # convert ids to hrns
276 for record in records:
277 # get all relevant data
278 type = record['type']
279 pointer = record['pointer']
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'] \
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'] \
308 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
309 record['sites'] = site_hrns
313 # aggregates is basically api.aggregates
314 def fill_record_sfa_info(self, records, aggregates):
316 def startswith(prefix, values):
317 return [value for value in values if value.startswith(prefix)]
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'])
328 # get all pis from the sites we've encountered
329 # and store them in a dictionary keyed on site_id
332 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
333 pi_list = self.GetPersons(pi_filter, ['person_id', 'site_ids'])
335 # we will need the pi's hrns also
336 person_ids.append(pi['person_id'])
338 # we also need to keep track of the sites these pis
340 for site_id in pi['site_ids']:
341 if site_id in site_pis:
342 site_pis[site_id].append(pi)
344 site_pis[site_id] = [pi]
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
350 # get the sfa records
351 # xxx thgen fixme - use SfaTable hardwired for now
352 # table = self.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)
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')
369 for record in records:
370 # skip records with no pl info (top level authorities)
371 #if record['pointer'] == -1:
374 type = record['type']
375 if (type == "slice"):
376 # all slice users are researchers
377 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
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)
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']
393 elif (type.startswith("authority")):
395 if record['hrn'] in aggregates:
397 record['url'] = aggregates[record['hrn']].get_url()
399 if record['pointer'] != -1:
401 record['operator'] = []
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
407 hrns = [person['hrn'] for person in persons[pointer]]
408 roles = pl_persons[pointer]['roles']
410 record['PI'].extend(hrns)
412 record['operator'].extend(hrns)
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
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)
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":
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
440 oldList = oldRecord.get(listName, [])
443 newList = record.get(listName, [])
445 # if the lists are the same, then we don't have to update anything
446 if (oldList == newList):
449 # build a list of the new person ids, by looking up each person to get
452 # xxx thgen fixme - use SfaTable hardwired for now
453 #table = self.SfaTable()
455 records = table.find({'type': 'user', 'hrn': newList})
457 newIdList.append(rec['pointer'])
459 # build a list of the old person ids from the person_ids field
461 oldIdList = oldRecord.get("person_ids", [])
462 containerId = oldRecord.get_pointer()
464 # if oldRecord==None, then we are doing a Register, instead of an
467 containerId = record.get_pointer()
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)
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)