3 from sfa.util.faults import MissingSfaInfo
4 from sfa.util.sfalogging import logger
5 from sfa.util.table import SfaTable
6 from sfa.util.defaultdict import defaultdict
8 from sfa.util.xrn import hrn_to_urn
9 from sfa.util.plxrn import slicename_to_hrn, hostname_to_hrn, hrn_to_pl_slicename, hrn_to_pl_login_base
11 from sfa.server.sfaapi import SfaApi
13 def list_to_dict(recs, key):
15 convert a list of dictionaries into a dictionary keyed on the
16 specified dictionary key
18 keys = [rec[key] for rec in recs]
19 return dict(zip(keys, recs))
21 class PlcSfaApi(SfaApi):
23 def __init__ (self, encoding="utf-8", methods='sfa.methods',
24 config = "/etc/sfa/sfa_config.py",
25 peer_cert = None, interface = None,
26 key_file = None, cert_file = None, cache = None):
27 SfaApi.__init__(self, encoding=encoding, methods=methods,
29 peer_cert=peer_cert, interface=interface,
31 cert_file=cert_file, cache=cache)
33 self.SfaTable = SfaTable
34 # Initialize the PLC shell only if SFA wraps a myPLC
35 rspec_type = self.config.get_aggregate_type()
36 if (rspec_type == 'pl' or rspec_type == 'vini' or \
37 rspec_type == 'eucalyptus' or rspec_type == 'max'):
38 self.plshell = self.getPLCShell()
39 self.plshell_version = "4.3"
41 def getPLCShell(self):
42 self.plauth = {'Username': self.config.SFA_PLC_USER,
43 'AuthMethod': 'password',
44 'AuthString': self.config.SFA_PLC_PASSWORD}
46 # The native shell (PLC.Shell.Shell) is more efficient than xmlrpc,
47 # but it leaves idle db connections open. use xmlrpc until we can figure
48 # out why PLC.Shell.Shell doesn't close db connection properly
50 # sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
51 # self.plshell_type = 'direct'
53 # shell = PLC.Shell.Shell(globals = globals())
56 self.plshell_type = 'xmlrpc'
57 url = self.config.SFA_PLC_URL
58 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
62 # Convert SFA fields to PLC fields for use when registering up updating
63 # registry record in the PLC database
65 # @param type type of record (user, slice, ...)
66 # @param hrn human readable name
67 # @param sfa_fields dictionary of SFA fields
68 # @param pl_fields dictionary of PLC fields (output)
70 def sfa_fields_to_pl_fields(self, type, hrn, record):
72 def convert_ints(tmpdict, int_fields):
73 for field in int_fields:
75 tmpdict[field] = int(tmpdict[field])
79 # pl_record[field] = record[field]
82 if not "instantiation" in pl_record:
83 pl_record["instantiation"] = "plc-instantiated"
84 pl_record["name"] = hrn_to_pl_slicename(hrn)
86 pl_record["url"] = record["url"]
87 if "description" in record:
88 pl_record["description"] = record["description"]
89 if "expires" in record:
90 pl_record["expires"] = int(record["expires"])
93 if not "hostname" in pl_record:
94 if not "hostname" in record:
95 raise MissingSfaInfo("hostname")
96 pl_record["hostname"] = record["hostname"]
97 if not "model" in pl_record:
98 pl_record["model"] = "geni"
100 elif type == "authority":
101 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
103 if not "name" in pl_record:
104 pl_record["name"] = hrn
106 if not "abbreviated_name" in pl_record:
107 pl_record["abbreviated_name"] = hrn
109 if not "enabled" in pl_record:
110 pl_record["enabled"] = True
112 if not "is_public" in pl_record:
113 pl_record["is_public"] = True
117 def fill_record_pl_info(self, records):
119 Fill in the planetlab specific fields of a SFA record. This
120 involves calling the appropriate PLC method to retrieve the
121 database record for the object.
123 PLC data is filled into the pl_info field of the record.
125 @param record: record to fill in field (in/out param)
128 node_ids, site_ids, slice_ids = [], [], []
129 person_ids, key_ids = [], []
130 type_map = {'node': node_ids, 'authority': site_ids,
131 'slice': slice_ids, 'user': person_ids}
133 for record in records:
134 for type in type_map:
135 if type == record['type']:
136 type_map[type].append(record['pointer'])
139 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
141 node_list = self.plshell.GetNodes(self.plauth, node_ids)
142 nodes = list_to_dict(node_list, 'node_id')
144 site_list = self.plshell.GetSites(self.plauth, site_ids)
145 sites = list_to_dict(site_list, 'site_id')
147 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
148 slices = list_to_dict(slice_list, 'slice_id')
150 person_list = self.plshell.GetPersons(self.plauth, person_ids)
151 persons = list_to_dict(person_list, 'person_id')
152 for person in persons:
153 key_ids.extend(persons[person]['key_ids'])
155 pl_records = {'node': nodes, 'authority': sites,
156 'slice': slices, 'user': persons}
159 key_list = self.plshell.GetKeys(self.plauth, key_ids)
160 keys = list_to_dict(key_list, 'key_id')
163 for record in records:
164 # records with pointer==-1 do not have plc info.
165 # for example, the top level authority records which are
166 # authorities, but not PL "sites"
167 if record['pointer'] == -1:
170 for type in pl_records:
171 if record['type'] == type:
172 if record['pointer'] in pl_records[type]:
173 record.update(pl_records[type][record['pointer']])
176 if record['type'] == 'user':
177 if 'key_ids' not in record:
178 logger.info("user record has no 'key_ids' - need to import from myplc ?")
180 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
181 record['keys'] = pubkeys
183 # fill in record hrns
184 records = self.fill_record_hrns(records)
188 def fill_record_hrns(self, records):
190 convert pl ids to hrns
194 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
195 for record in records:
196 if 'site_id' in record:
197 site_ids.append(record['site_id'])
198 if 'site_ids' in record:
199 site_ids.extend(record['site_ids'])
200 if 'person_ids' in record:
201 person_ids.extend(record['person_ids'])
202 if 'slice_ids' in record:
203 slice_ids.extend(record['slice_ids'])
204 if 'node_ids' in record:
205 node_ids.extend(record['node_ids'])
208 slices, persons, sites, nodes = {}, {}, {}, {}
210 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
211 sites = list_to_dict(site_list, 'site_id')
213 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
214 persons = list_to_dict(person_list, 'person_id')
216 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
217 slices = list_to_dict(slice_list, 'slice_id')
219 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
220 nodes = list_to_dict(node_list, 'node_id')
222 # convert ids to hrns
223 for record in records:
224 # get all relevant data
225 type = record['type']
226 pointer = record['pointer']
232 if 'site_id' in record:
233 site = sites[record['site_id']]
234 login_base = site['login_base']
235 record['site'] = ".".join([auth_hrn, login_base])
236 if 'person_ids' in record:
237 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
238 if person_id in persons]
239 usernames = [email.split('@')[0] for email in emails]
240 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
241 record['persons'] = person_hrns
242 if 'slice_ids' in record:
243 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
244 if slice_id in slices]
245 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
246 record['slices'] = slice_hrns
247 if 'node_ids' in record:
248 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
250 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
251 record['nodes'] = node_hrns
252 if 'site_ids' in record:
253 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
255 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
256 record['sites'] = site_hrns
260 def fill_record_sfa_info(self, records):
262 def startswith(prefix, values):
263 return [value for value in values if value.startswith(prefix)]
268 for record in records:
269 person_ids.extend(record.get("person_ids", []))
270 site_ids.extend(record.get("site_ids", []))
271 if 'site_id' in record:
272 site_ids.append(record['site_id'])
274 # get all pis from the sites we've encountered
275 # and store them in a dictionary keyed on site_id
278 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
279 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
281 # we will need the pi's hrns also
282 person_ids.append(pi['person_id'])
284 # we also need to keep track of the sites these pis
286 for site_id in pi['site_ids']:
287 if site_id in site_pis:
288 site_pis[site_id].append(pi)
290 site_pis[site_id] = [pi]
292 # get sfa records for all records associated with these records.
293 # we'll replace pl ids (person_ids) with hrns from the sfa records
296 # get the sfa records
297 table = self.SfaTable()
298 person_list, persons = [], {}
299 person_list = table.find({'type': 'user', 'pointer': person_ids})
300 # create a hrns keyed on the sfa record's pointer.
301 # Its possible for multiple records to have the same pointer so
302 # the dict's value will be a list of hrns.
303 persons = defaultdict(list)
304 for person in person_list:
305 persons[person['pointer']].append(person)
308 pl_person_list, pl_persons = [], {}
309 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
310 pl_persons = list_to_dict(pl_person_list, 'person_id')
313 for record in records:
314 # skip records with no pl info (top level authorities)
315 #if record['pointer'] == -1:
318 type = record['type']
319 if (type == "slice"):
320 # all slice users are researchers
321 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
323 record['researcher'] = []
324 for person_id in record.get('person_ids', []):
325 hrns = [person['hrn'] for person in persons[person_id]]
326 record['researcher'].extend(hrns)
328 # pis at the slice's site
329 if 'site_id' in record and record['site_id'] in site_pis:
330 pl_pis = site_pis[record['site_id']]
331 pi_ids = [pi['person_id'] for pi in pl_pis]
332 for person_id in pi_ids:
333 hrns = [person['hrn'] for person in persons[person_id]]
334 record['PI'].extend(hrns)
335 record['geni_creator'] = record['PI']
337 elif (type.startswith("authority")):
339 if record['hrn'] in self.aggregates:
341 record['url'] = self.aggregates[record['hrn']].get_url()
343 if record['pointer'] != -1:
345 record['operator'] = []
347 for pointer in record.get('person_ids', []):
348 if pointer not in persons or pointer not in pl_persons:
349 # this means there is not sfa or pl record for this user
351 hrns = [person['hrn'] for person in persons[pointer]]
352 roles = pl_persons[pointer]['roles']
354 record['PI'].extend(hrns)
356 record['operator'].extend(hrns)
358 record['owner'].extend(hrns)
359 # xxx TODO: OrganizationName
360 elif (type == "node"):
361 sfa_info['dns'] = record.get("hostname", "")
362 # xxx TODO: URI, LatLong, IP, DNS
364 elif (type == "user"):
365 sfa_info['email'] = record.get("email", "")
366 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
367 sfa_info['geni_certificate'] = record['gid']
368 # xxx TODO: PostalAddress, Phone
369 record.update(sfa_info)
371 def fill_record_info(self, records):
373 Given a SFA record, fill in the PLC specific and SFA specific
374 fields in the record.
376 if not isinstance(records, list):
379 self.fill_record_pl_info(records)
380 self.fill_record_sfa_info(records)
382 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
383 # get a list of the HRNs that are members of the old and new records
385 oldList = oldRecord.get(listName, [])
388 newList = record.get(listName, [])
390 # if the lists are the same, then we don't have to update anything
391 if (oldList == newList):
394 # build a list of the new person ids, by looking up each person to get
397 table = self.SfaTable()
398 records = table.find({'type': 'user', 'hrn': newList})
400 newIdList.append(rec['pointer'])
402 # build a list of the old person ids from the person_ids field
404 oldIdList = oldRecord.get("person_ids", [])
405 containerId = oldRecord.get_pointer()
407 # if oldRecord==None, then we are doing a Register, instead of an
410 containerId = record.get_pointer()
412 # add people who are in the new list, but not the oldList
413 for personId in newIdList:
414 if not (personId in oldIdList):
415 addFunc(self.plauth, personId, containerId)
417 # remove people who are in the old list, but not the new list
418 for personId in oldIdList:
419 if not (personId in newIdList):
420 delFunc(self.plauth, personId, containerId)
422 def update_membership(self, oldRecord, record):
423 if record.type == "slice":
424 self.update_membership_list(oldRecord, record, 'researcher',
425 self.plshell.AddPersonToSlice,
426 self.plshell.DeletePersonFromSlice)
427 elif record.type == "authority":