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 from collections import defaultdict
27 class defaultdict(dict):
28 def __init__(self, default_factory=None, *a, **kw):
29 if (default_factory is not None and
30 not hasattr(default_factory, '__call__')):
31 raise TypeError('first argument must be callable')
32 dict.__init__(self, *a, **kw)
33 self.default_factory = default_factory
34 def __getitem__(self, key):
36 return dict.__getitem__(self, key)
38 return self.__missing__(key)
39 def __missing__(self, key):
40 if self.default_factory is None:
42 self[key] = value = self.default_factory()
45 if self.default_factory is None:
48 args = self.default_factory,
49 return type(self), args, None, None, self.items()
51 return self.__copy__()
53 return type(self)(self.default_factory, self)
54 def __deepcopy__(self, memo):
56 return type(self)(self.default_factory,
57 copy.deepcopy(self.items()))
59 return 'defaultdict(%s, %s)' % (self.default_factory,
61 ## end of http://code.activestate.com/recipes/523034/ }}}
63 def list_to_dict(recs, key):
65 convert a list of dictionaries into a dictionary keyed on the
66 specified dictionary key
68 keys = [rec[key] for rec in recs]
69 return dict(zip(keys, recs))
71 class SfaAPI(BaseAPI):
73 # flat list of method names
75 methods = sfa.methods.all
77 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8",
78 methods='sfa.methods', peer_cert = None, interface = None,
79 key_file = None, cert_file = None, cache = None):
80 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
81 peer_cert=peer_cert, interface=interface, key_file=key_file, \
82 cert_file=cert_file, cache=cache)
84 self.encoding = encoding
85 from sfa.util.table import SfaTable
86 self.SfaTable = SfaTable
87 # Better just be documenting the API
92 self.config = Config(config)
93 self.auth = Auth(peer_cert)
94 self.interface = interface
95 self.key_file = key_file
96 self.key = Keypair(filename=self.key_file)
97 self.cert_file = cert_file
98 self.cert = Certificate(filename=self.cert_file)
99 self.credential = None
100 # Initialize the PLC shell only if SFA wraps a myPLC
101 rspec_type = self.config.get_aggregate_type()
102 if (rspec_type == 'pl' or rspec_type == 'vini' or rspec_type == 'eucalyptus'):
103 self.plshell = self.getPLCShell()
104 self.plshell_version = "4.3"
106 self.hrn = self.config.SFA_INTERFACE_HRN
107 self.time_format = "%Y-%m-%d %H:%M:%S"
108 self.logger=get_sfa_logger()
110 def getPLCShell(self):
111 self.plauth = {'Username': self.config.SFA_PLC_USER,
112 'AuthMethod': 'password',
113 'AuthString': self.config.SFA_PLC_PASSWORD}
115 sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
116 self.plshell_type = 'direct'
118 shell = PLC.Shell.Shell(globals = globals())
120 self.plshell_type = 'xmlrpc'
121 url = self.config.SFA_PLC_URL
122 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
126 def getCredential(self):
128 Retrun a valid credential for this interface.
130 if self.interface in ['registry']:
131 return self.getCredentialFromLocalRegistry()
133 return self.getCredentialFromRegistry()
135 def getDelegatedCredential(self, creds):
137 Attempt to find a credential delegated to us in
138 the specified list of creds.
140 if creds and not isinstance(creds, list): creds = [creds]
141 return filter_creds_by_caller(creds,self.hrn)
143 def getCredentialFromRegistry(self):
145 Get our credential from a remote registry
148 path = self.config.SFA_DATA_DIR
149 filename = ".".join([self.interface, self.hrn, type, "cred"])
150 cred_filename = path + os.sep + filename
152 credential = Credential(filename = cred_filename)
153 return credential.save_to_string(save_parents=True)
155 from sfa.server.registry import Registries
156 registries = Registries(self)
157 registry = registries[self.hrn]
158 cert_string=self.cert.save_to_string(save_parents=True)
159 # get self credential
160 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
162 cred = registry.get_credential(self_cred, type, self.hrn)
165 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
168 def getCredentialFromLocalRegistry(self):
170 Get our current credential directly from the local registry.
174 auth_hrn = self.auth.get_authority(hrn)
176 # is this a root or sub authority
177 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
179 auth_info = self.auth.get_auth_info(auth_hrn)
180 table = self.SfaTable()
181 records = table.findObjects(hrn)
185 type = record['type']
186 object_gid = record.get_gid_object()
187 new_cred = Credential(subject = object_gid.get_subject())
188 new_cred.set_gid_caller(object_gid)
189 new_cred.set_gid_object(object_gid)
190 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
192 r1 = determine_rights(type, hrn)
193 new_cred.set_privileges(r1)
195 auth_kind = "authority,ma,sa"
197 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
202 return new_cred.save_to_string(save_parents=True)
205 def loadCredential (self):
207 Attempt to load credential from file if it exists. If it doesnt get
208 credential from registry.
211 # see if this file exists
212 # XX This is really the aggregate's credential. Using this is easier than getting
213 # the registry's credential from iteslf (ssl errors).
214 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
216 self.credential = Credential(filename = ma_cred_filename)
218 self.credential = self.getCredentialFromRegistry()
221 # Convert SFA fields to PLC fields for use when registering up updating
222 # registry record in the PLC database
224 # @param type type of record (user, slice, ...)
225 # @param hrn human readable name
226 # @param sfa_fields dictionary of SFA fields
227 # @param pl_fields dictionary of PLC fields (output)
229 def sfa_fields_to_pl_fields(self, type, hrn, record):
231 def convert_ints(tmpdict, int_fields):
232 for field in int_fields:
234 tmpdict[field] = int(tmpdict[field])
237 #for field in record:
238 # pl_record[field] = record[field]
241 if not "instantiation" in pl_record:
242 pl_record["instantiation"] = "plc-instantiated"
243 pl_record["name"] = hrn_to_pl_slicename(hrn)
245 pl_record["url"] = record["url"]
246 if "description" in record:
247 pl_record["description"] = record["description"]
248 if "expires" in record:
249 pl_record["expires"] = int(record["expires"])
252 if not "hostname" in pl_record:
253 if not "hostname" in record:
254 raise MissingSfaInfo("hostname")
255 pl_record["hostname"] = record["hostname"]
256 if not "model" in pl_record:
257 pl_record["model"] = "geni"
259 elif type == "authority":
260 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
262 if not "name" in pl_record:
263 pl_record["name"] = hrn
265 if not "abbreviated_name" in pl_record:
266 pl_record["abbreviated_name"] = hrn
268 if not "enabled" in pl_record:
269 pl_record["enabled"] = True
271 if not "is_public" in pl_record:
272 pl_record["is_public"] = True
276 def fill_record_pl_info(self, records):
278 Fill in the planetlab specific fields of a SFA record. This
279 involves calling the appropriate PLC method to retrieve the
280 database record for the object.
282 PLC data is filled into the pl_info field of the record.
284 @param record: record to fill in field (in/out param)
287 node_ids, site_ids, slice_ids = [], [], []
288 person_ids, key_ids = [], []
289 type_map = {'node': node_ids, 'authority': site_ids,
290 'slice': slice_ids, 'user': person_ids}
292 for record in records:
293 for type in type_map:
294 if type == record['type']:
295 type_map[type].append(record['pointer'])
298 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
300 node_list = self.plshell.GetNodes(self.plauth, node_ids)
301 nodes = list_to_dict(node_list, 'node_id')
303 site_list = self.plshell.GetSites(self.plauth, site_ids)
304 sites = list_to_dict(site_list, 'site_id')
306 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
307 slices = list_to_dict(slice_list, 'slice_id')
309 person_list = self.plshell.GetPersons(self.plauth, person_ids)
310 persons = list_to_dict(person_list, 'person_id')
311 for person in persons:
312 key_ids.extend(persons[person]['key_ids'])
314 pl_records = {'node': nodes, 'authority': sites,
315 'slice': slices, 'user': persons}
318 key_list = self.plshell.GetKeys(self.plauth, key_ids)
319 keys = list_to_dict(key_list, 'key_id')
322 for record in records:
323 # records with pointer==-1 do not have plc info.
324 # for example, the top level authority records which are
325 # authorities, but not PL "sites"
326 if record['pointer'] == -1:
329 for type in pl_records:
330 if record['type'] == type:
331 if record['pointer'] in pl_records[type]:
332 record.update(pl_records[type][record['pointer']])
335 if record['type'] == 'user':
336 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
337 record['keys'] = pubkeys
339 # fill in record hrns
340 records = self.fill_record_hrns(records)
344 def fill_record_hrns(self, records):
346 convert pl ids to hrns
350 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
351 for record in records:
352 if 'site_id' in record:
353 site_ids.append(record['site_id'])
354 if 'site_ids' in records:
355 site_ids.extend(record['site_ids'])
356 if 'person_ids' in record:
357 person_ids.extend(record['person_ids'])
358 if 'slice_ids' in record:
359 slice_ids.extend(record['slice_ids'])
360 if 'node_ids' in record:
361 node_ids.extend(record['node_ids'])
364 slices, persons, sites, nodes = {}, {}, {}, {}
366 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
367 sites = list_to_dict(site_list, 'site_id')
369 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
370 persons = list_to_dict(person_list, 'person_id')
372 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
373 slices = list_to_dict(slice_list, 'slice_id')
375 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
376 nodes = list_to_dict(node_list, 'node_id')
378 # convert ids to hrns
379 for record in records:
381 # get all relevant data
382 type = record['type']
383 pointer = record['pointer']
389 if 'site_id' in record:
390 site = sites[record['site_id']]
391 login_base = site['login_base']
392 record['site'] = ".".join([auth_hrn, login_base])
393 if 'person_ids' in record:
394 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
395 if person_id in persons]
396 usernames = [email.split('@')[0] for email in emails]
397 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
398 record['persons'] = person_hrns
399 if 'slice_ids' in record:
400 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
401 if slice_id in slices]
402 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
403 record['slices'] = slice_hrns
404 if 'node_ids' in record:
405 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
407 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
408 record['nodes'] = node_hrns
409 if 'site_ids' in record:
410 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
412 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
413 record['sites'] = site_hrns
417 def fill_record_sfa_info(self, records):
419 def startswith(prefix, values):
420 return [value for value in values if value.startswith(prefix)]
425 for record in records:
426 person_ids.extend(record.get("person_ids", []))
427 site_ids.extend(record.get("site_ids", []))
428 if 'site_id' in record:
429 site_ids.append(record['site_id'])
431 # get all pis from the sites we've encountered
432 # and store them in a dictionary keyed on site_id
435 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
436 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
438 # we will need the pi's hrns also
439 person_ids.append(pi['person_id'])
441 # we also need to keep track of the sites these pis
443 for site_id in pi['site_ids']:
444 if site_id in site_pis:
445 site_pis[site_id].append(pi)
447 site_pis[site_id] = [pi]
449 # get sfa records for all records associated with these records.
450 # we'll replace pl ids (person_ids) with hrns from the sfa records
453 # get the sfa records
454 table = self.SfaTable()
455 person_list, persons = [], {}
456 person_list = table.find({'type': 'user', 'pointer': person_ids})
457 # create a hrns keyed on the sfa record's pointer.
458 # Its possible for multiple records to have the same pointer so
459 # the dict's value will be a list of hrns.
460 persons = defaultdict(list)
461 for person in person_list:
462 persons[person['pointer']].append(person)
465 pl_person_list, pl_persons = [], {}
466 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
467 pl_persons = list_to_dict(pl_person_list, 'person_id')
470 for record in records:
471 # skip records with no pl info (top level authorities)
472 if record['pointer'] == -1:
475 type = record['type']
476 if (type == "slice"):
477 # all slice users are researchers
479 record['researcher'] = []
480 for person_id in record['person_ids']:
481 hrns = [person['hrn'] for person in persons[person_id]]
482 record['researcher'].extend(hrns)
484 # pis at the slice's site
485 pl_pis = site_pis[record['site_id']]
486 pi_ids = [pi['person_id'] for pi in pl_pis]
487 for person_id in pi_ids:
488 hrns = [person['hrn'] for person in persons[person_id]]
489 record['PI'].extend(hrns)
490 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
491 record['geni_creator'] = record['PI']
493 elif (type == "authority"):
495 record['operator'] = []
497 for pointer in record['person_ids']:
498 if pointer not in persons or pointer not in pl_persons:
499 # this means there is not sfa or pl record for this user
501 hrns = [person['hrn'] for person in persons[pointer]]
502 roles = pl_persons[pointer]['roles']
504 record['PI'].extend(hrns)
506 record['operator'].extend(hrns)
508 record['owner'].extend(hrns)
509 # xxx TODO: OrganizationName
510 elif (type == "node"):
511 sfa_info['dns'] = record.get("hostname", "")
512 # xxx TODO: URI, LatLong, IP, DNS
514 elif (type == "user"):
515 sfa_info['email'] = record.get("email", "")
516 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
517 sfa_info['geni_certificate'] = record['gid']
518 # xxx TODO: PostalAddress, Phone
519 record.update(sfa_info)
521 def fill_record_info(self, records):
523 Given a SFA record, fill in the PLC specific and SFA specific
524 fields in the record.
526 if not isinstance(records, list):
529 self.fill_record_pl_info(records)
530 self.fill_record_sfa_info(records)
532 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
533 # get a list of the HRNs tht are members of the old and new records
535 oldList = oldRecord.get(listName, [])
538 newList = record.get(listName, [])
540 # if the lists are the same, then we don't have to update anything
541 if (oldList == newList):
544 # build a list of the new person ids, by looking up each person to get
547 table = self.SfaTable()
548 records = table.find({'type': 'user', 'hrn': newList})
550 newIdList.append(rec['pointer'])
552 # build a list of the old person ids from the person_ids field
554 oldIdList = oldRecord.get("person_ids", [])
555 containerId = oldRecord.get_pointer()
557 # if oldRecord==None, then we are doing a Register, instead of an
560 containerId = record.get_pointer()
562 # add people who are in the new list, but not the oldList
563 for personId in newIdList:
564 if not (personId in oldIdList):
565 addFunc(self.plauth, personId, containerId)
567 # remove people who are in the old list, but not the new list
568 for personId in oldIdList:
569 if not (personId in newIdList):
570 delFunc(self.plauth, personId, containerId)
572 def update_membership(self, oldRecord, record):
573 if record.type == "slice":
574 self.update_membership_list(oldRecord, record, 'researcher',
575 self.plshell.AddPersonToSlice,
576 self.plshell.DeletePersonFromSlice)
577 elif record.type == "authority":
583 class ComponentAPI(BaseAPI):
585 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
586 peer_cert = None, interface = None, key_file = None, cert_file = None):
588 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
589 interface=interface, key_file=key_file, cert_file=cert_file)
590 self.encoding = encoding
592 # Better just be documenting the API
596 self.nodemanager = NodeManager(self.config)
598 def sliver_exists(self):
599 sliver_dict = self.nodemanager.GetXIDs()
600 if slicename in sliver_dict.keys():
605 def get_registry(self):
606 addr, port = self.config.SFA_REGISTRY_HOST, self.config.SFA_REGISTRY_PORT
607 url = "http://%(addr)s:%(port)s" % locals()
608 server = xmlrpcprotocol.get_server(url, self.key_file, self.cert_file)
611 def get_node_key(self):
612 # this call requires no authentication,
613 # so we can generate a random keypair here
615 (kfd, keyfile) = tempfile.mkstemp()
616 (cfd, certfile) = tempfile.mkstemp()
617 key = Keypair(create=True)
618 key.save_to_file(keyfile)
619 cert = Certificate(subject=subject)
620 cert.set_issuer(key=key, subject=subject)
623 cert.save_to_file(certfile)
624 registry = self.get_registry()
625 # the registry will scp the key onto the node
628 def getCredential(self):
630 Get our credential from a remote registry
632 path = self.config.SFA_DATA_DIR
633 config_dir = self.config.config_path
634 credfile = path + os.sep + 'node.cred'
636 credential = Credential(filename = cred_filename)
637 return credential.save_to_string(save_parents=True)
639 node_pkey_file = config_dir + os.sep + "node.key"
640 node_gid_file = config_dir + os.sep + "node.gid"
641 if not os.path.exists(node_pkey_file) or \
642 not os.path.exists(node_gid_file):
646 gid = GID(filename=node_gid_file)
648 # get credential from registry
649 registry = self.get_registry()
650 cred = registry.get_self_credential(cert_str, 'node', hrn)
651 Credential(string=cred).save_to_file(credfile, save_parents=True)
655 def clean_key_cred(self):
657 remove the existing keypair and cred and generate new ones
659 files = ["server.key", "server.cert", "node.cred"]
661 filepath = KEYDIR + os.sep + f
662 if os.path.isfile(filepath):
665 # install the new key pair
666 # get_credential will take care of generating the new keypair