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 ## thierry: everything that is API-related (i.e. handling incoming requests)
13 # SlabDriver should be really only about talking to the senslab testbed
15 ## thierry : please avoid wildcard imports :)
16 from sfa.senslab.OARrestapi import OARapi
17 from sfa.senslab.LDAPapi import LDAPapi
18 from sfa.senslab.SenslabImportUsers import SenslabImportUsers
19 from sfa.senslab.parsing import parse_filter
20 from sfa.senslab.slabpostgres import SlabDB
22 def list_to_dict(recs, key):
24 convert a list of dictionaries into a dictionary keyed on the
25 specified dictionary key
27 # print>>sys.stderr, " \r\n \t\t 1list_to_dict : rec %s \r\n \t\t list_to_dict key %s" %(recs,key)
28 keys = [rec[key] for rec in recs]
29 #print>>sys.stderr, " \r\n \t\t list_to_dict : rec %s \r\n \t\t list_to_dict keys %s" %(recs,keys)
30 return dict(zip(keys, recs))
33 # this inheritance scheme is so that the driver object can receive
34 # GetNodes or GetSites sorts of calls directly
35 # and thus minimize the differences in the managers with the pl version
38 def __init__(self, config):
41 self.hrn = config.SFA_INTERFACE_HRN
43 self.root_auth = config.SFA_REGISTRY_ROOT_AUTH
46 print >>sys.stderr, "\r\n_____________ SFA SENSLAB DRIVER \r\n"
47 # thierry - just to not break the rest of this code
49 #self.users = SenslabImportUsers()
52 self.users = SenslabImportUsers()
53 self.time_format = "%Y-%m-%d %H:%M:%S"
54 #self.logger=sfa_logger()
57 def GetPersons(self, person_filter=None, return_fields=None):
59 person_list = self.ldap.ldapFind({'authority': self.root_auth })
60 return_person_list = parse_filter(person_list,person_filter ,'persons', return_fields)
61 return return_person_list
63 def GetNodes(self,node_filter= None, return_fields=None):
65 self.oar.parser.SendRequest("GET_resources_full")
66 node_dict = self.oar.parser.GetNodesFromOARParse()
69 if not (node_filter or return_fields):
70 return_node_list = node_dict.values()
71 return return_node_list
73 return_node_list= parse_filter(node_dict.values(),node_filter ,'node', return_fields)
74 return return_node_list
77 # Convert SFA fields to PLC fields for use when registering up updating
78 # registry record in the PLC database
80 # @param type type of record (user, slice, ...)
81 # @param hrn human readable name
82 # @param sfa_fields dictionary of SFA fields
83 # @param pl_fields dictionary of PLC fields (output)
85 def sfa_fields_to_pl_fields(self, type, hrn, record):
87 def convert_ints(tmpdict, int_fields):
88 for field in int_fields:
90 tmpdict[field] = int(tmpdict[field])
94 # pl_record[field] = record[field]
97 if not "instantiation" in pl_record:
98 pl_record["instantiation"] = "plc-instantiated"
99 pl_record["name"] = hrn_to_pl_slicename(hrn)
101 pl_record["url"] = record["url"]
102 if "description" in record:
103 pl_record["description"] = record["description"]
104 if "expires" in record:
105 pl_record["expires"] = int(record["expires"])
108 if not "hostname" in pl_record:
109 if not "hostname" in record:
110 raise MissingSfaInfo("hostname")
111 pl_record["hostname"] = record["hostname"]
112 if not "model" in pl_record:
113 pl_record["model"] = "geni"
115 elif type == "authority":
116 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
118 if not "name" in pl_record:
119 pl_record["name"] = hrn
121 if not "abbreviated_name" in pl_record:
122 pl_record["abbreviated_name"] = hrn
124 if not "enabled" in pl_record:
125 pl_record["enabled"] = True
127 if not "is_public" in pl_record:
128 pl_record["is_public"] = True
132 def fill_record_pl_info(self, records):
134 Fill in the planetlab specific fields of a SFA record. This
135 involves calling the appropriate PLC method to retrieve the
136 database record for the object.
138 PLC data is filled into the pl_info field of the record.
140 @param record: record to fill in field (in/out param)
143 #print>>sys.stderr, "\r\n \r\rn \t\t >>>>>>>>>>fill_record_pl_info records %s : "%(records)
144 node_ids, site_ids, slice_ids = [], [], []
145 person_ids, key_ids = [], []
146 type_map = {'node': node_ids, 'authority': site_ids,
147 'slice': slice_ids, 'user': person_ids}
149 for record in records:
150 for type in type_map:
151 #print>>sys.stderr, "\r\n \t\t \t fill_record_pl_info : type %s. record['pointer'] %s "%(type,record['pointer'])
152 if type == record['type']:
153 type_map[type].append(record['pointer'])
154 #print>>sys.stderr, "\r\n \t\t \t fill_record_pl_info : records %s... \r\n \t\t \t fill_record_pl_info : type_map %s"%(records,type_map)
156 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
158 node_list = self.GetNodes( node_ids)
159 #print>>sys.stderr, " \r\n \t\t\t BEFORE LIST_TO_DICT_NODES node_ids : %s" %(node_ids)
160 nodes = list_to_dict(node_list, 'node_id')
162 site_list = self.oar.GetSites( site_ids)
163 sites = list_to_dict(site_list, 'site_id')
164 #print>>sys.stderr, " \r\n \t\t\t site_ids %s sites : %s" %(site_ids,sites)
166 slice_list = self.users.GetSlices( slice_ids)
167 slices = list_to_dict(slice_list, 'slice_id')
169 #print>>sys.stderr, " \r\n \t\t \t fill_record_pl_info BEFORE GetPersons person_ids: %s" %(person_ids)
170 person_list = self.GetPersons( person_ids)
171 persons = list_to_dict(person_list, 'person_id')
172 #print>>sys.stderr, "\r\n fill_record_pl_info persons %s \r\n \t\t person_ids %s " %(persons, person_ids)
173 for person in persons:
174 key_ids.extend(persons[person]['key_ids'])
175 #print>>sys.stderr, "\r\n key_ids %s " %(key_ids)
177 pl_records = {'node': nodes, 'authority': sites,
178 'slice': slices, 'user': persons}
181 key_list = self.users.GetKeys( key_ids)
182 keys = list_to_dict(key_list, 'key_id')
183 # print>>sys.stderr, "\r\n fill_record_pl_info persons %s \r\n \t\t keys %s " %(keys)
185 for record in records:
186 # records with pointer==-1 do not have plc info.
187 # for example, the top level authority records which are
188 # authorities, but not PL "sites"
189 if record['pointer'] == -1:
192 for type in pl_records:
193 if record['type'] == type:
194 if record['pointer'] in pl_records[type]:
195 record.update(pl_records[type][record['pointer']])
198 if record['type'] == 'user':
199 if 'key_ids' not in record:
200 #print>>sys.stderr, " NO_KEY_IDS fill_record_pl_info key_ids record: %s" %(record)
201 logger.info("user record has no 'key_ids' - need to import ?")
203 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
204 record['keys'] = pubkeys
206 #print>>sys.stderr, "\r\n \r\rn \t\t <<<<<<<<<<<<<<<<<< fill_record_pl_info records %s : "%(records)
207 # fill in record hrns
208 records = self.fill_record_hrns(records)
212 def fill_record_hrns(self, records):
214 convert pl ids to hrns
216 #print>>sys.stderr, "\r\n \r\rn \t\t \t >>>>>>>>>>>>>>>>>>>>>> fill_record_hrns records %s : "%(records)
218 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
219 for record in records:
220 #print>>sys.stderr, "\r\n \r\rn \t\t \t record %s : "%(record)
221 if 'site_id' in record:
222 site_ids.append(record['site_id'])
223 if 'site_ids' in records:
224 site_ids.extend(record['site_ids'])
225 if 'person_ids' in record:
226 person_ids.extend(record['person_ids'])
227 if 'slice_ids' in record:
228 slice_ids.extend(record['slice_ids'])
229 if 'node_ids' in record:
230 node_ids.extend(record['node_ids'])
233 slices, persons, sites, nodes = {}, {}, {}, {}
235 site_list = self.oar.GetSites( site_ids, ['site_id', 'login_base'])
236 sites = list_to_dict(site_list, 'site_id')
237 #print>>sys.stderr, " \r\n \r\n \t\t ____ site_list %s \r\n \t\t____ sites %s " % (site_list,sites)
239 person_list = self.GetPersons( person_ids, ['person_id', 'email'])
240 #print>>sys.stderr, " \r\n \r\n \t\t____ person_lists %s " %(person_list)
241 persons = list_to_dict(person_list, 'person_id')
243 slice_list = self.users.GetSlices( slice_ids, ['slice_id', 'name'])
244 slices = list_to_dict(slice_list, 'slice_id')
246 node_list = self.GetNodes( node_ids, ['node_id', 'hostname'])
247 nodes = list_to_dict(node_list, 'node_id')
249 # convert ids to hrns
250 for record in records:
252 # get all relevant data
253 type = record['type']
254 pointer = record['pointer']
260 #print>>sys.stderr, " \r\n \r\n \t\t fill_record_hrns : sites %s \r\n \t\t record %s " %(sites, record)
261 if 'site_id' in record:
262 site = sites[record['site_id']]
263 #print>>sys.stderr, " \r\n \r\n \t\t \t fill_record_hrns : sites %s \r\n \t\t\t site sites[record['site_id']] %s " %(sites,site)
264 login_base = site['login_base']
265 record['site'] = ".".join([auth_hrn, login_base])
266 if 'person_ids' in record:
267 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
268 if person_id in persons]
269 usernames = [email.split('@')[0] for email in emails]
270 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
271 #print>>sys.stderr, " \r\n \r\n \t\t ____ person_hrns : %s " %(person_hrns)
272 record['persons'] = person_hrns
273 if 'slice_ids' in record:
274 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
275 if slice_id in slices]
276 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
277 record['slices'] = slice_hrns
278 if 'node_ids' in record:
279 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
281 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
282 record['nodes'] = node_hrns
283 if 'site_ids' in record:
284 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
286 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
287 record['sites'] = site_hrns
288 #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<< fill_record_hrns records %s : "%(records)
291 def fill_record_sfa_info(self, records):
293 def startswith(prefix, values):
294 return [value for value in values if value.startswith(prefix)]
299 for record in records:
300 person_ids.extend(record.get("person_ids", []))
301 site_ids.extend(record.get("site_ids", []))
302 if 'site_id' in record:
303 site_ids.append(record['site_id'])
305 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___person_ids %s \r\n \t\t site_ids %s " %(person_ids, site_ids)
307 # get all pis from the sites we've encountered
308 # and store them in a dictionary keyed on site_id
311 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
312 pi_list = self.GetPersons( pi_filter, ['person_id', 'site_ids'])
313 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ GetPersons ['person_id', 'site_ids'] pi_ilist %s" %(pi_list)
316 # we will need the pi's hrns also
317 person_ids.append(pi['person_id'])
319 # we also need to keep track of the sites these pis
321 for site_id in pi['site_ids']:
322 if site_id in site_pis:
323 site_pis[site_id].append(pi)
325 site_pis[site_id] = [pi]
327 # get sfa records for all records associated with these records.
328 # we'll replace pl ids (person_ids) with hrns from the sfa records
331 # get the sfa records
333 person_list, persons = [], {}
334 person_list = table.find({'type': 'user', 'pointer': person_ids})
335 # create a hrns keyed on the sfa record's pointer.
336 # Its possible for multiple records to have the same pointer so
337 # the dict's value will be a list of hrns.
338 persons = defaultdict(list)
339 for person in person_list:
340 persons[person['pointer']].append(person)
343 pl_person_list, pl_persons = [], {}
344 pl_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
345 pl_persons = list_to_dict(pl_person_list, 'person_id')
346 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ _list %s \r\n \t\t SenslabUsers.GetPersons ['person_id', 'roles'] pl_persons %s \r\n records %s" %(pl_person_list, pl_persons,records)
349 for record in records:
350 # skip records with no pl info (top level authorities)
351 #Sandrine 24 oct 11 2 lines
352 #if record['pointer'] == -1:
355 type = record['type']
356 if (type == "slice"):
357 # all slice users are researchers
358 #record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice') ? besoin ou pas ?
360 record['researcher'] = []
361 for person_id in record.get('person_ids', []):
362 #Sandrine 24 oct 11 line
363 #for person_id in record['person_ids']:
364 hrns = [person['hrn'] for person in persons[person_id]]
365 record['researcher'].extend(hrns)
367 # pis at the slice's site
368 pl_pis = site_pis[record['site_id']]
369 pi_ids = [pi['person_id'] for pi in pl_pis]
370 for person_id in pi_ids:
371 hrns = [person['hrn'] for person in persons[person_id]]
372 record['PI'].extend(hrns)
373 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
374 record['geni_creator'] = record['PI']
376 elif (type == "authority"):
378 record['operator'] = []
380 for pointer in record['person_ids']:
381 if pointer not in persons or pointer not in pl_persons:
382 # this means there is not sfa or pl record for this user
384 hrns = [person['hrn'] for person in persons[pointer]]
385 roles = pl_persons[pointer]['roles']
387 record['PI'].extend(hrns)
389 record['operator'].extend(hrns)
391 record['owner'].extend(hrns)
392 # xxx TODO: OrganizationName
393 elif (type == "node"):
394 sfa_info['dns'] = record.get("hostname", "")
395 # xxx TODO: URI, LatLong, IP, DNS
397 elif (type == "user"):
398 sfa_info['email'] = record.get("email", "")
399 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
400 sfa_info['geni_certificate'] = record['gid']
401 # xxx TODO: PostalAddress, Phone
403 #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<< fill_record_sfa_info sfa_info %s \r\n record %s : "%(sfa_info,record)
404 record.update(sfa_info)
406 def fill_record_info(self, records):
408 Given a SFA record, fill in the senslab specific and SFA specific
409 fields in the record.
412 if isinstance(records, list):
414 print >>sys.stderr, "\r\n \t\t BEFORE fill_record_pl_info %s" %(records)
417 if records['type'] == 'slice':
419 sfatable = SfaTable()
420 recslice = db.find('slice',str(records['hrn']))
421 if isinstance(recslice,list) and len(recslice) == 1:
422 recslice = recslice[0]
423 recuser = sfatable.find( recslice['record_id_user'], ['hrn'])
425 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info %s" %(recuser)
427 if isinstance(recuser,list) and len(recuser) == 1:
429 records.update({'PI':[recuser['hrn']],
430 'researcher': [recuser['hrn']],
431 'name':records['hrn'], 'oar_job_id':recslice['oar_job_id'],
432 'person_ids':[recslice['record_id_user']]})
434 #self.fill_record_pl_info(records)
435 ##print >>sys.stderr, "\r\n \t\t after fill_record_pl_info %s" %(records)
436 #self.fill_record_sfa_info(records)
437 #print >>sys.stderr, "\r\n \t\t after fill_record_sfa_info"
439 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
440 # get a list of the HRNs tht are members of the old and new records
442 oldList = oldRecord.get(listName, [])
445 newList = record.get(listName, [])
447 # if the lists are the same, then we don't have to update anything
448 if (oldList == newList):
451 # build a list of the new person ids, by looking up each person to get
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(self.plauth, 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(self.plauth, personId, containerId)
479 def update_membership(self, oldRecord, record):
480 print >>sys.stderr, " \r\n \r\n ***SLABDRIVER.PY update_membership record ", record
481 if record.type == "slice":
482 self.update_membership_list(oldRecord, record, 'researcher',
483 self.users.AddPersonToSlice,
484 self.users.DeletePersonFromSlice)
485 elif record.type == "authority":
490 # I don't think you plan on running a component manager at this point
491 # let me clean up the mess of ComponentAPI that is deprecated anyways