4 from sfa.util.faults import SfaFault, SfaAPIError, RecordNotFound
5 from sfa.util.genicode import GENICODE
6 from sfa.util.config import Config
7 from sfa.util.cache import Cache
9 from sfa.trust.auth import Auth
10 from sfa.trust.certificate import Keypair, Certificate
11 from sfa.trust.credential import Credential
12 from sfa.trust.rights import determine_rights
13 from sfa.util.version import version_core
14 from sfa.server.xmlrpcapi import XmlrpcApi
15 from sfa.client.return_value import ReturnValue
17 from sfa.storage.alchemy import alchemy
20 class SfaApi (XmlrpcApi):
23 An SfaApi instance is a basic xmlrcp service
24 augmented with the local cryptographic material and hrn
26 It also has the notion of its own interface (a string describing
27 whether we run a registry, aggregate or slicemgr) and has
28 the notion of neighbour sfa services as defined
29 in /etc/sfa/{aggregates,registries}.xml
31 Finally it contains a cache instance
33 It gets augmented by the generic layer with
34 (*) an instance of manager (actually a manager module for now)
35 (*) which in turn holds an instance of a testbed driver
36 For convenience api.manager.driver == api.driver
39 def __init__ (self, encoding="utf-8", methods='sfa.methods',
40 config = "/etc/sfa/sfa_config",
41 peer_cert = None, interface = None,
42 key_file = None, cert_file = None, cache = None):
44 XmlrpcApi.__init__ (self, encoding)
46 # we may be just be documenting the API
50 self.config = Config(config)
51 self.credential = None
52 self.auth = Auth(peer_cert)
53 self.interface = interface
54 self.hrn = self.config.SFA_INTERFACE_HRN
55 self.key_file = key_file
56 self.key = Keypair(filename=self.key_file)
57 self.cert_file = cert_file
58 self.cert = Certificate(filename=self.cert_file)
60 if self.cache is None:
64 from sfa.server.registry import Registries
65 self.registries = Registries()
68 from sfa.server.aggregate import Aggregates
69 self.aggregates = Aggregates()
71 # filled later on by generic/Generic
75 def server_proxy(self, interface, cred, timeout=30):
77 Returns a connection to the specified interface. Use the specified
78 credential to determine the caller and look for the caller's key/cert
79 in the registry hierarchy cache.
81 from sfa.trust.hierarchy import Hierarchy
82 if not isinstance(cred, Credential):
83 cred_obj = Credential(string=cred)
86 caller_gid = cred_obj.get_gid_caller()
87 hierarchy = Hierarchy()
88 auth_info = hierarchy.get_auth_info(caller_gid.get_hrn())
89 key_file = auth_info.get_privkey_filename()
90 cert_file = auth_info.get_gid_filename()
91 server = interface.server_proxy(key_file, cert_file, timeout)
95 if self._dbsession is None:
96 self._dbsession=alchemy.session()
97 return self._dbsession
99 def close_dbsession(self):
100 if self._dbsession is None: return
101 alchemy.close_session(self._dbsession)
104 def getCredential(self, minimumExpiration=0):
106 Return a valid credential for this interface.
109 path = self.config.SFA_DATA_DIR
110 filename = ".".join([self.interface, self.hrn, type, "cred"])
111 cred_filename = os.path.join(path,filename)
113 if os.path.isfile(cred_filename):
114 cred = Credential(filename = cred_filename)
115 # make sure cred isnt expired
116 if not cred.get_expiration or \
117 datetime.datetime.utcnow() + datetime.timedelta(seconds=minimumExpiration) < cred.get_expiration():
118 return cred.save_to_string(save_parents=True)
120 # get a new credential
121 if self.interface in ['registry']:
122 cred = self._getCredentialRaw()
124 cred = self._getCredential()
125 cred.save_to_file(cred_filename, save_parents=True)
127 return cred.save_to_string(save_parents=True)
130 def getDelegatedCredential(self, creds):
132 Attempt to find a credential delegated to us in
133 the specified list of creds.
135 from sfa.trust.hierarchy import Hierarchy
136 if creds and not isinstance(creds, list):
138 hierarchy = Hierarchy()
140 delegated_cred = None
142 if hierarchy.auth_exists(Credential(cred=cred).get_gid_caller().get_hrn()):
143 delegated_cred = cred
145 return delegated_cred
147 def _getCredential(self):
149 Get our credential from a remote registry
151 from sfa.server.registry import Registries
152 registries = Registries()
153 registry = registries.server_proxy(self.hrn, self.key_file, self.cert_file)
154 cert_string=self.cert.save_to_string(save_parents=True)
155 # get self credential
156 self_cred = registry.GetSelfCredential(cert_string, self.hrn, 'authority')
158 cred = registry.GetCredential(self_cred, self.hrn, 'authority')
159 return Credential(string=cred)
161 def _getCredentialRaw(self):
163 Get our current credential directly from the local registry.
167 auth_hrn = self.auth.get_authority(hrn)
169 # is this a root or sub authority
170 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
172 auth_info = self.auth.get_auth_info(auth_hrn)
173 # xxx although unlikely we might want to check for a potential leak
174 dbsession=self.dbsession()
175 from sfa.storage.model import RegRecord
176 record = dbsession.query(RegRecord).filter_by(type='authority+sa', hrn=hrn).first()
178 raise RecordNotFound(hrn)
180 object_gid = record.get_gid_object()
181 new_cred = Credential(subject = object_gid.get_subject())
182 new_cred.set_gid_caller(object_gid)
183 new_cred.set_gid_object(object_gid)
184 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
186 r1 = determine_rights(type, hrn)
187 new_cred.set_privileges(r1)
193 def loadCredential (self):
195 Attempt to load credential from file if it exists. If it doesnt get
196 credential from registry.
199 # see if this file exists
200 # XX This is really the aggregate's credential. Using this is easier than getting
201 # the registry's credential from iteslf (ssl errors).
202 filename = self.interface + self.hrn + ".ma.cred"
203 ma_cred_path = os.path.join(self.config.SFA_DATA_DIR,filename)
205 self.credential = Credential(filename = ma_cred_path)
207 self.credential = self.getCredentialFromRegistry()
209 def get_cached_server_version(self, server):
210 cache_key = server.url + "-version"
211 server_version = None
213 server_version = self.cache.get(cache_key)
214 if not server_version:
215 result = server.GetVersion()
216 server_version = ReturnValue.get_value(result)
217 # cache version for 24 hours
218 self.cache.add(cache_key, server_version, ttl= 60*60*24)
219 return server_version
222 def get_geni_code(self, result):
224 'geni_code': GENICODE.SUCCESS,
228 if isinstance(result, SfaFault):
229 code['geni_code'] = result.faultCode
230 code['am_code'] = result.faultCode
234 def get_geni_value(self, result):
236 if isinstance(result, SfaFault):
240 def get_geni_output(self, result):
242 if isinstance(result, SfaFault):
243 output = result.faultString
246 def prepare_response_am(self, result):
247 version = version_core()
250 'code': self.get_geni_code(result),
251 'value': self.get_geni_value(result),
252 'output': self.get_geni_output(result),
256 def prepare_response(self, result, method=""):
258 Converts the specified result into a standard GENI compliant
261 # as of dec 13 2011 we only support API v2
262 if self.interface.lower() in ['aggregate', 'slicemgr']:
263 result = self.prepare_response_am(result)
264 return XmlrpcApi.prepare_response(self, result, method)