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 self.SfaTable = SfaTable
27 # Initialize the PLC shell only if SFA wraps a myPLC
28 rspec_type = config.get_aggregate_type()
29 assert (rspec_type == 'pl' or rspec_type == 'vini' or \
30 rspec_type == 'eucalyptus' or rspec_type == 'max')
33 # Convert SFA fields to PLC fields for use when registering up updating
34 # registry record in the PLC database
36 # @param type type of record (user, slice, ...)
37 # @param hrn human readable name
38 # @param sfa_fields dictionary of SFA fields
39 # @param pl_fields dictionary of PLC fields (output)
41 def sfa_fields_to_pl_fields(self, type, hrn, record):
43 def convert_ints(tmpdict, int_fields):
44 for field in int_fields:
46 tmpdict[field] = int(tmpdict[field])
50 # pl_record[field] = record[field]
53 if not "instantiation" in pl_record:
54 pl_record["instantiation"] = "plc-instantiated"
55 pl_record["name"] = hrn_to_pl_slicename(hrn)
57 pl_record["url"] = record["url"]
58 if "description" in record:
59 pl_record["description"] = record["description"]
60 if "expires" in record:
61 pl_record["expires"] = int(record["expires"])
64 if not "hostname" in pl_record:
65 if not "hostname" in record:
66 raise MissingSfaInfo("hostname")
67 pl_record["hostname"] = record["hostname"]
68 if not "model" in pl_record:
69 pl_record["model"] = "geni"
71 elif type == "authority":
72 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
74 if not "name" in pl_record:
75 pl_record["name"] = hrn
77 if not "abbreviated_name" in pl_record:
78 pl_record["abbreviated_name"] = hrn
80 if not "enabled" in pl_record:
81 pl_record["enabled"] = True
83 if not "is_public" in pl_record:
84 pl_record["is_public"] = True
88 def fill_record_pl_info(self, records):
90 Fill in the planetlab specific fields of a SFA record. This
91 involves calling the appropriate PLC method to retrieve the
92 database record for the object.
94 PLC data is filled into the pl_info field of the record.
96 @param record: record to fill in field (in/out param)
99 node_ids, site_ids, slice_ids = [], [], []
100 person_ids, key_ids = [], []
101 type_map = {'node': node_ids, 'authority': site_ids,
102 'slice': slice_ids, 'user': person_ids}
104 for record in records:
105 for type in type_map:
106 if type == record['type']:
107 type_map[type].append(record['pointer'])
110 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
112 node_list = self.GetNodes(node_ids)
113 nodes = list_to_dict(node_list, 'node_id')
115 site_list = self.GetSites(site_ids)
116 sites = list_to_dict(site_list, 'site_id')
118 slice_list = self.GetSlices(slice_ids)
119 slices = list_to_dict(slice_list, 'slice_id')
121 person_list = self.GetPersons(person_ids)
122 persons = list_to_dict(person_list, 'person_id')
123 for person in persons:
124 key_ids.extend(persons[person]['key_ids'])
126 pl_records = {'node': nodes, 'authority': sites,
127 'slice': slices, 'user': persons}
130 key_list = self.GetKeys(key_ids)
131 keys = list_to_dict(key_list, 'key_id')
134 for record in records:
135 # records with pointer==-1 do not have plc info.
136 # for example, the top level authority records which are
137 # authorities, but not PL "sites"
138 if record['pointer'] == -1:
141 for type in pl_records:
142 if record['type'] == type:
143 if record['pointer'] in pl_records[type]:
144 record.update(pl_records[type][record['pointer']])
147 if record['type'] == 'user':
148 if 'key_ids' not in record:
149 logger.info("user record has no 'key_ids' - need to import from myplc ?")
151 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
152 record['keys'] = pubkeys
154 # fill in record hrns
155 records = self.fill_record_hrns(records)
159 def fill_record_hrns(self, records):
161 convert pl ids to hrns
165 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
166 for record in records:
167 if 'site_id' in record:
168 site_ids.append(record['site_id'])
169 if 'site_ids' in record:
170 site_ids.extend(record['site_ids'])
171 if 'person_ids' in record:
172 person_ids.extend(record['person_ids'])
173 if 'slice_ids' in record:
174 slice_ids.extend(record['slice_ids'])
175 if 'node_ids' in record:
176 node_ids.extend(record['node_ids'])
179 slices, persons, sites, nodes = {}, {}, {}, {}
181 site_list = self.GetSites(site_ids, ['site_id', 'login_base'])
182 sites = list_to_dict(site_list, 'site_id')
184 person_list = self.GetPersons(person_ids, ['person_id', 'email'])
185 persons = list_to_dict(person_list, 'person_id')
187 slice_list = self.GetSlices(slice_ids, ['slice_id', 'name'])
188 slices = list_to_dict(slice_list, 'slice_id')
190 node_list = self.GetNodes(node_ids, ['node_id', 'hostname'])
191 nodes = list_to_dict(node_list, 'node_id')
193 # convert ids to hrns
194 for record in records:
195 # get all relevant data
196 type = record['type']
197 pointer = record['pointer']
203 if 'site_id' in record:
204 site = sites[record['site_id']]
205 login_base = site['login_base']
206 record['site'] = ".".join([auth_hrn, login_base])
207 if 'person_ids' in record:
208 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
209 if person_id in persons]
210 usernames = [email.split('@')[0] for email in emails]
211 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
212 record['persons'] = person_hrns
213 if 'slice_ids' in record:
214 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
215 if slice_id in slices]
216 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
217 record['slices'] = slice_hrns
218 if 'node_ids' in record:
219 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
221 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
222 record['nodes'] = node_hrns
223 if 'site_ids' in record:
224 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
226 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
227 record['sites'] = site_hrns
231 # aggregates is basically api.aggregates
232 def fill_record_sfa_info(self, records, aggregates):
234 def startswith(prefix, values):
235 return [value for value in values if value.startswith(prefix)]
240 for record in records:
241 person_ids.extend(record.get("person_ids", []))
242 site_ids.extend(record.get("site_ids", []))
243 if 'site_id' in record:
244 site_ids.append(record['site_id'])
246 # get all pis from the sites we've encountered
247 # and store them in a dictionary keyed on site_id
250 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
251 pi_list = self.GetPersons(pi_filter, ['person_id', 'site_ids'])
253 # we will need the pi's hrns also
254 person_ids.append(pi['person_id'])
256 # we also need to keep track of the sites these pis
258 for site_id in pi['site_ids']:
259 if site_id in site_pis:
260 site_pis[site_id].append(pi)
262 site_pis[site_id] = [pi]
264 # get sfa records for all records associated with these records.
265 # we'll replace pl ids (person_ids) with hrns from the sfa records
268 # get the sfa records
269 table = self.SfaTable()
270 person_list, persons = [], {}
271 person_list = table.find({'type': 'user', 'pointer': person_ids})
272 # create a hrns keyed on the sfa record's pointer.
273 # Its possible for multiple records to have the same pointer so
274 # the dict's value will be a list of hrns.
275 persons = defaultdict(list)
276 for person in person_list:
277 persons[person['pointer']].append(person)
280 pl_person_list, pl_persons = [], {}
281 pl_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
282 pl_persons = list_to_dict(pl_person_list, 'person_id')
285 for record in records:
286 # skip records with no pl info (top level authorities)
287 #if record['pointer'] == -1:
290 type = record['type']
291 if (type == "slice"):
292 # all slice users are researchers
293 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
295 record['researcher'] = []
296 for person_id in record.get('person_ids', []):
297 hrns = [person['hrn'] for person in persons[person_id]]
298 record['researcher'].extend(hrns)
300 # pis at the slice's site
301 if 'site_id' in record and record['site_id'] in site_pis:
302 pl_pis = site_pis[record['site_id']]
303 pi_ids = [pi['person_id'] for pi in pl_pis]
304 for person_id in pi_ids:
305 hrns = [person['hrn'] for person in persons[person_id]]
306 record['PI'].extend(hrns)
307 record['geni_creator'] = record['PI']
309 elif (type.startswith("authority")):
311 if record['hrn'] in aggregates:
313 record['url'] = aggregates[record['hrn']].get_url()
315 if record['pointer'] != -1:
317 record['operator'] = []
319 for pointer in record.get('person_ids', []):
320 if pointer not in persons or pointer not in pl_persons:
321 # this means there is not sfa or pl record for this user
323 hrns = [person['hrn'] for person in persons[pointer]]
324 roles = pl_persons[pointer]['roles']
326 record['PI'].extend(hrns)
328 record['operator'].extend(hrns)
330 record['owner'].extend(hrns)
331 # xxx TODO: OrganizationName
332 elif (type == "node"):
333 sfa_info['dns'] = record.get("hostname", "")
334 # xxx TODO: URI, LatLong, IP, DNS
336 elif (type == "user"):
337 sfa_info['email'] = record.get("email", "")
338 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
339 sfa_info['geni_certificate'] = record['gid']
340 # xxx TODO: PostalAddress, Phone
341 record.update(sfa_info)
343 def fill_record_info(self, records, aggregates):
345 Given a SFA record, fill in the PLC specific and SFA specific
346 fields in the record.
348 if not isinstance(records, list):
351 self.fill_record_pl_info(records)
352 self.fill_record_sfa_info(records, aggregates)
354 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
355 # get a list of the HRNs that are members of the old and new records
357 oldList = oldRecord.get(listName, [])
360 newList = record.get(listName, [])
362 # if the lists are the same, then we don't have to update anything
363 if (oldList == newList):
366 # build a list of the new person ids, by looking up each person to get
369 table = self.SfaTable()
370 records = table.find({'type': 'user', 'hrn': newList})
372 newIdList.append(rec['pointer'])
374 # build a list of the old person ids from the person_ids field
376 oldIdList = oldRecord.get("person_ids", [])
377 containerId = oldRecord.get_pointer()
379 # if oldRecord==None, then we are doing a Register, instead of an
382 containerId = record.get_pointer()
384 # add people who are in the new list, but not the oldList
385 for personId in newIdList:
386 if not (personId in oldIdList):
387 addFunc(personId, containerId)
389 # remove people who are in the old list, but not the new list
390 for personId in oldIdList:
391 if not (personId in newIdList):
392 delFunc(personId, containerId)
394 def update_membership(self, oldRecord, record):
395 if record.type == "slice":
396 self.update_membership_list(oldRecord, record, 'researcher',
397 self.AddPersonToSlice,
398 self.DeletePersonFromSlice)
399 elif record.type == "authority":