2 # SFA XML-RPC and SOAP interfaces
13 from sfa.trust.auth import Auth
14 from sfa.util.config import *
15 from sfa.util.faults import *
16 from sfa.util.debug import *
17 from sfa.trust.rights import *
18 from sfa.trust.credential import *
19 from sfa.trust.certificate import *
20 from sfa.util.namespace import *
21 from sfa.util.api import *
22 from sfa.util.nodemanager import NodeManager
23 from sfa.util.sfalogging import *
25 class SfaAPI(BaseAPI):
27 # flat list of method names
29 methods = sfa.methods.all
31 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods', \
32 peer_cert = None, interface = None, key_file = None, cert_file = None):
33 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
34 peer_cert=peer_cert, interface=interface, key_file=key_file, \
37 self.encoding = encoding
39 from sfa.util.table import SfaTable
40 self.SfaTable = SfaTable
41 # Better just be documenting the API
46 self.config = Config(config)
47 self.auth = Auth(peer_cert)
48 self.interface = interface
49 self.key_file = key_file
50 self.key = Keypair(filename=self.key_file)
51 self.cert_file = cert_file
52 self.cert = Certificate(filename=self.cert_file)
53 self.credential = None
55 # Initialize the PLC shell only if SFA wraps a myPLC
56 rspec_type = self.config.get_aggregate_type()
57 if (rspec_type == 'pl' or rspec_type == 'vini'):
58 self.plshell = self.getPLCShell()
59 self.plshell_version = self.getPLCShellVersion()
61 self.hrn = self.config.SFA_INTERFACE_HRN
62 self.time_format = "%Y-%m-%d %H:%M:%S"
63 self.logger=get_sfa_logger()
65 def getPLCShell(self):
66 self.plauth = {'Username': self.config.SFA_PLC_USER,
67 'AuthMethod': 'password',
68 'AuthString': self.config.SFA_PLC_PASSWORD}
70 sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
71 self.plshell_type = 'direct'
73 shell = PLC.Shell.Shell(globals = globals())
74 shell.AuthCheck(self.plauth)
77 self.plshell_type = 'xmlrpc'
79 url = self.config.SFA_PLC_URL
80 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
81 shell.AuthCheck(self.plauth)
84 def getPLCShellVersion(self):
85 # We need to figure out what version of PLCAPI we are talking to.
86 # Some calls we need to make later will be different depending on
89 # This is probably a bad way to determine api versions
90 # but its easy and will work for now. Lets try to make
91 # a call that only exists is PLCAPI.4.3. If it fails, we
92 # can assume the api version is 4.2
93 self.plshell.GetTagTypes(self.plauth)
99 def getCredential(self):
100 if self.interface in ['registry']:
101 return self.getCredentialFromLocalRegistry()
103 return self.getCredentialFromRegistry()
105 def getCredentialFromRegistry(self):
107 Get our credential from a remote registry
110 path = self.config.SFA_DATA_DIR
111 filename = ".".join([self.interface, self.hrn, type, "cred"])
112 cred_filename = path + os.sep + filename
114 credential = Credential(filename = cred_filename)
115 return credential.save_to_string(save_parents=True)
117 from sfa.server.registry import Registries
118 registries = Registries(self)
119 registry = registries[self.hrn]
120 cert_string=self.cert.save_to_string(save_parents=True)
121 # get self credential
122 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
124 cred = registry.get_credential(self_cred, type, self.hrn)
127 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
130 def getCredentialFromLocalRegistry(self):
132 Get our current credential directly from the local registry.
136 auth_hrn = self.auth.get_authority(hrn)
138 # is this a root or sub authority
139 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
141 auth_info = self.auth.get_auth_info(auth_hrn)
142 table = self.SfaTable()
143 records = table.findObjects(hrn)
147 type = record['type']
148 object_gid = record.get_gid_object()
149 new_cred = Credential(subject = object_gid.get_subject())
150 new_cred.set_gid_caller(object_gid)
151 new_cred.set_gid_object(object_gid)
152 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
153 new_cred.set_pubkey(object_gid.get_pubkey())
154 r1 = determine_rights(type, hrn)
155 new_cred.set_privileges(r1)
157 auth_kind = "authority,ma,sa"
159 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
164 return new_cred.save_to_string(save_parents=True)
167 def loadCredential (self):
169 Attempt to load credential from file if it exists. If it doesnt get
170 credential from registry.
173 # see if this file exists
174 # XX This is really the aggregate's credential. Using this is easier than getting
175 # the registry's credential from iteslf (ssl errors).
176 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
178 self.credential = Credential(filename = ma_cred_filename)
180 self.credential = self.getCredentialFromRegistry()
183 # Convert SFA fields to PLC fields for use when registering up updating
184 # registry record in the PLC database
186 # @param type type of record (user, slice, ...)
187 # @param hrn human readable name
188 # @param sfa_fields dictionary of SFA fields
189 # @param pl_fields dictionary of PLC fields (output)
191 def sfa_fields_to_pl_fields(self, type, hrn, record):
193 def convert_ints(tmpdict, int_fields):
194 for field in int_fields:
196 tmpdict[field] = int(tmpdict[field])
199 #for field in record:
200 # pl_record[field] = record[field]
203 if not "instantiation" in pl_record:
204 pl_record["instantiation"] = "plc-instantiated"
205 pl_record["name"] = hrn_to_pl_slicename(hrn)
207 pl_record["url"] = record["url"]
208 if "description" in record:
209 pl_record["description"] = record["description"]
210 if "expires" in record:
211 pl_record["expires"] = int(record["expires"])
214 if not "hostname" in pl_record:
215 if not "hostname" in record:
216 raise MissingSfaInfo("hostname")
217 pl_record["hostname"] = record["hostname"]
218 if not "model" in pl_record:
219 pl_record["model"] = "geni"
221 elif type == "authority":
222 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
224 if not "name" in pl_record:
225 pl_record["name"] = hrn
227 if not "abbreviated_name" in pl_record:
228 pl_record["abbreviated_name"] = hrn
230 if not "enabled" in pl_record:
231 pl_record["enabled"] = True
233 if not "is_public" in pl_record:
234 pl_record["is_public"] = True
238 def fill_record_pl_info(self, record):
240 Fill in the planetlab specific fields of a SFA record. This
241 involves calling the appropriate PLC method to retrieve the
242 database record for the object.
244 PLC data is filled into the pl_info field of the record.
246 @param record: record to fill in field (in/out param)
248 type = record['type']
249 pointer = record['pointer']
252 # records with pointer==-1 do not have plc info associated with them.
253 # for example, the top level authority records which are
254 # authorities, but not PL "sites"
259 if (type in ["authority"]):
260 pl_res = self.plshell.GetSites(self.plauth, [pointer])
261 elif (type == "slice"):
262 pl_res = self.plshell.GetSlices(self.plauth, [pointer])
263 elif (type == "user"):
264 pl_res = self.plshell.GetPersons(self.plauth, [pointer])
265 elif (type == "node"):
266 pl_res = self.plshell.GetNodes(self.plauth, [pointer])
268 raise UnknownSfaType(type)
271 raise PlanetLabRecordDoesNotExist(record['hrn'])
273 # convert ids to hrns
274 pl_record = pl_res[0]
275 if 'site_id' in pl_record:
276 sites = self.plshell.GetSites(self.plauth, pl_record['site_id'], ['login_base'])
278 login_base = site['login_base']
279 pl_record['site'] = ".".join([auth_hrn, login_base])
280 if 'person_ids' in pl_record:
281 persons = self.plshell.GetPersons(self.plauth, pl_record['person_ids'], ['email'])
282 emails = [person['email'] for person in persons]
283 usernames = [email.split('@')[0] for email in emails]
284 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
285 pl_record['persons'] = person_hrns
286 if 'slice_ids' in pl_record:
287 slices = self.plshell.GetSlices(self.plauth, pl_record['slice_ids'], ['name'])
288 slicenames = [slice['name'] for slice in slices]
289 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
290 pl_record['slices'] = slice_hrns
291 if 'node_ids' in pl_record:
292 nodes = self.plshell.GetNodes(self.plauth, pl_record['node_ids'], ['hostname'])
293 hostnames = [node['hostname'] for node in nodes]
294 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
295 pl_record['nodes'] = node_hrns
296 if 'site_ids' in pl_record:
297 sites = self.plshell.GetSites(self.plauth, pl_record['site_ids'], ['login_base'])
298 login_bases = [site['login_base'] for site in sites]
299 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
300 pl_record['sites'] = site_hrns
301 if 'key_ids' in pl_record:
302 keys = self.plshell.GetKeys(self.plauth, pl_record['key_ids'])
305 pubkeys = [key['key'] for key in keys]
306 pl_record['keys'] = pubkeys
308 record.update(pl_record)
312 def fill_record_sfa_info(self, record):
314 type = record['type']
315 table = self.SfaTable()
316 if (type == "slice"):
317 person_ids = record.get("person_ids", [])
318 persons = table.find({'type': 'user', 'pointer': person_ids})
319 researchers = [person['hrn'] for person in persons]
320 sfa_info['researcher'] = researchers
322 elif (type == "authority"):
323 person_ids = record.get("person_ids", [])
324 persons = table.find({'type': 'user', 'pointer': person_ids})
326 for person in persons:
327 persons_dict[person['pointer']] = person
328 pl_persons = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
329 pis, techs, admins = [], [], []
330 for person in pl_persons:
331 pointer = person['person_id']
333 if pointer not in persons_dict:
334 # this means there is not sfa record for this user
336 hrn = persons_dict[pointer]['hrn']
337 if 'pi' in person['roles']:
339 if 'tech' in person['roles']:
341 if 'admin' in person['roles']:
345 sfa_info['operator'] = techs
346 sfa_info['owner'] = admins
347 # xxx TODO: OrganizationName
349 elif (type == "node"):
350 sfa_info['dns'] = record.get("hostname", "")
351 # xxx TODO: URI, LatLong, IP, DNS
353 elif (type == "user"):
354 sfa_info['email'] = record.get("email", "")
355 # xxx TODO: PostalAddress, Phone
357 record.update(sfa_info)
359 def fill_record_info(self, record):
361 Given a SFA record, fill in the PLC specific and SFA specific
362 fields in the record.
364 self.fill_record_pl_info(record)
365 self.fill_record_sfa_info(record)
367 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
368 # get a list of the HRNs tht are members of the old and new records
370 oldList = oldRecord.get(listName, [])
373 newList = record.get(listName, [])
375 # if the lists are the same, then we don't have to update anything
376 if (oldList == newList):
379 # build a list of the new person ids, by looking up each person to get
382 table = self.SfaTable()
383 records = table.find({'type': 'user', 'hrn': newList})
385 newIdList.append(rec['pointer'])
387 # build a list of the old person ids from the person_ids field
389 oldIdList = oldRecord.get("person_ids", [])
390 containerId = oldRecord.get_pointer()
392 # if oldRecord==None, then we are doing a Register, instead of an
395 containerId = record.get_pointer()
397 # add people who are in the new list, but not the oldList
398 for personId in newIdList:
399 if not (personId in oldIdList):
400 addFunc(self.plauth, personId, containerId)
402 # remove people who are in the old list, but not the new list
403 for personId in oldIdList:
404 if not (personId in newIdList):
405 delFunc(self.plauth, personId, containerId)
407 def update_membership(self, oldRecord, record):
408 if record.type == "slice":
409 self.update_membership_list(oldRecord, record, 'researcher',
410 self.plshell.AddPersonToSlice,
411 self.plshell.DeletePersonFromSlice)
412 elif record.type == "authority":
418 class ComponentAPI(BaseAPI):
420 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
421 peer_cert = None, interface = None, key_file = None, cert_file = None):
423 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
424 interface=interface, key_file=key_file, cert_file=cert_file)
425 self.encoding = encoding
427 # Better just be documenting the API
431 self.nodemanager = NodeManager(self.config)
433 def sliver_exists(self):
434 sliver_dict = self.nodemanager.GetXIDs()
435 if slicename in sliver_dict.keys():