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
8 from sfa.util.plxrn import slicename_to_hrn, hostname_to_hrn, hrn_to_pl_slicename, hrn_to_pl_login_base
10 from sfa.plc.plshell import PlShell
12 def list_to_dict(recs, key):
14 convert a list of dictionaries into a dictionary keyed on the
15 specified dictionary key
17 keys = [rec[key] for rec in recs]
18 return dict(zip(keys, recs))
20 class PlDriver (PlShell):
22 def __init__ (self, config):
23 PlShell.__init__ (self, config)
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')
35 # Convert SFA fields to PLC fields for use when registering up updating
36 # registry record in the PLC database
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)
43 def sfa_fields_to_pl_fields(self, type, hrn, record):
45 def convert_ints(tmpdict, int_fields):
46 for field in int_fields:
48 tmpdict[field] = int(tmpdict[field])
52 # pl_record[field] = record[field]
55 if not "instantiation" in pl_record:
56 pl_record["instantiation"] = "plc-instantiated"
57 pl_record["name"] = hrn_to_pl_slicename(hrn)
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"])
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"
73 elif type == "authority":
74 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
76 if not "name" in pl_record:
77 pl_record["name"] = hrn
79 if not "abbreviated_name" in pl_record:
80 pl_record["abbreviated_name"] = hrn
82 if not "enabled" in pl_record:
83 pl_record["enabled"] = True
85 if not "is_public" in pl_record:
86 pl_record["is_public"] = True
90 def fill_record_pl_info(self, records):
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.
96 PLC data is filled into the pl_info field of the record.
98 @param record: record to fill in field (in/out param)
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}
106 for record in records:
107 for type in type_map:
108 if type == record['type']:
109 type_map[type].append(record['pointer'])
112 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
114 node_list = self.GetNodes(node_ids)
115 nodes = list_to_dict(node_list, 'node_id')
117 site_list = self.GetSites(site_ids)
118 sites = list_to_dict(site_list, 'site_id')
120 slice_list = self.GetSlices(slice_ids)
121 slices = list_to_dict(slice_list, 'slice_id')
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'])
128 pl_records = {'node': nodes, 'authority': sites,
129 'slice': slices, 'user': persons}
132 key_list = self.GetKeys(key_ids)
133 keys = list_to_dict(key_list, 'key_id')
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:
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']])
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 ?")
153 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
154 record['keys'] = pubkeys
156 # fill in record hrns
157 records = self.fill_record_hrns(records)
161 def fill_record_hrns(self, records):
163 convert pl ids to hrns
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'])
181 slices, persons, sites, nodes = {}, {}, {}, {}
183 site_list = self.GetSites(site_ids, ['site_id', 'login_base'])
184 sites = list_to_dict(site_list, 'site_id')
186 person_list = self.GetPersons(person_ids, ['person_id', 'email'])
187 persons = list_to_dict(person_list, 'person_id')
189 slice_list = self.GetSlices(slice_ids, ['slice_id', 'name'])
190 slices = list_to_dict(slice_list, 'slice_id')
192 node_list = self.GetNodes(node_ids, ['node_id', 'hostname'])
193 nodes = list_to_dict(node_list, 'node_id')
195 # convert ids to hrns
196 for record in records:
197 # get all relevant data
198 type = record['type']
199 pointer = record['pointer']
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'] \
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'] \
228 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
229 record['sites'] = site_hrns
233 # aggregates is basically api.aggregates
234 def fill_record_sfa_info(self, records, aggregates):
236 def startswith(prefix, values):
237 return [value for value in values if value.startswith(prefix)]
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'])
248 # get all pis from the sites we've encountered
249 # and store them in a dictionary keyed on site_id
252 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
253 pi_list = self.GetPersons(pi_filter, ['person_id', 'site_ids'])
255 # we will need the pi's hrns also
256 person_ids.append(pi['person_id'])
258 # we also need to keep track of the sites these pis
260 for site_id in pi['site_ids']:
261 if site_id in site_pis:
262 site_pis[site_id].append(pi)
264 site_pis[site_id] = [pi]
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
270 # get the sfa records
271 # xxx thgen fixme - use SfaTable hardwired for now
272 # table = self.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)
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')
289 for record in records:
290 # skip records with no pl info (top level authorities)
291 #if record['pointer'] == -1:
294 type = record['type']
295 if (type == "slice"):
296 # all slice users are researchers
297 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
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)
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']
313 elif (type.startswith("authority")):
315 if record['hrn'] in aggregates:
317 record['url'] = aggregates[record['hrn']].get_url()
319 if record['pointer'] != -1:
321 record['operator'] = []
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
327 hrns = [person['hrn'] for person in persons[pointer]]
328 roles = pl_persons[pointer]['roles']
330 record['PI'].extend(hrns)
332 record['operator'].extend(hrns)
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
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)
347 def fill_record_info(self, records, aggregates):
349 Given a SFA record, fill in the PLC specific and SFA specific
350 fields in the record.
352 if not isinstance(records, list):
355 self.fill_record_pl_info(records)
356 self.fill_record_sfa_info(records, aggregates)
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
361 oldList = oldRecord.get(listName, [])
364 newList = record.get(listName, [])
366 # if the lists are the same, then we don't have to update anything
367 if (oldList == newList):
370 # build a list of the new person ids, by looking up each person to get
373 # xxx thgen fixme - use SfaTable hardwired for now
374 #table = self.SfaTable()
376 records = table.find({'type': 'user', 'hrn': newList})
378 newIdList.append(rec['pointer'])
380 # build a list of the old person ids from the person_ids field
382 oldIdList = oldRecord.get("person_ids", [])
383 containerId = oldRecord.get_pointer()
385 # if oldRecord==None, then we are doing a Register, instead of an
388 containerId = record.get_pointer()
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)
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)
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":