a2950762388c580c859ef9786db64c4d4959e150
[sfa.git] / sfa / server / sfaapi.py
1 import os
2 import os.path
3 import datetime
4
5 from sfa.util.faults import SfaFault, SfaAPIError, RecordNotFound
6 from sfa.util.genicode import GENICODE
7 from sfa.util.config import Config
8 from sfa.util.cache import Cache
9
10 from sfa.trust.auth import Auth
11 from sfa.trust.certificate import Keypair, Certificate
12 from sfa.trust.credential import Credential
13 from sfa.trust.rights import determine_rights
14 from sfa.util.version import version_core
15 from sfa.server.xmlrpcapi import XmlrpcApi
16 from sfa.client.return_value import ReturnValue
17
18 from sfa.storage.alchemy import alchemy
19
20 ####################
21
22
23 class SfaApi (XmlrpcApi):
24     """
25     An SfaApi instance is a basic xmlrpc service
26     augmented with the local cryptographic material and hrn
27
28     It also has the notion of its own interface (a string describing
29     whether we run a registry, aggregate or slicemgr) and has 
30     the notion of neighbour sfa services as defined 
31     in /etc/sfa/{aggregates,registries}.xml
32
33     Finally it contains a cache instance
34
35     It gets augmented by the generic layer with 
36     (*) an instance of manager (actually a manager module for now)
37         beware that this is shared among all instances of api
38     (*) an instance of a testbed driver
39     """
40
41     def __init__(self, encoding="utf-8", methods='sfa.methods',
42                  config="/etc/sfa/sfa_config",
43                  peer_cert=None, interface=None,
44                  key_file=None, cert_file=None, cache=None):
45
46         XmlrpcApi.__init__(self, encoding)
47
48         # we may be just be documenting the API
49         if config is None:
50             return
51         # Load configuration
52         self.config = Config(config)
53         self.credential = None
54         self.auth = Auth(peer_cert)
55         self.interface = interface
56         self.hrn = self.config.SFA_INTERFACE_HRN
57         self.key_file = key_file
58         self.key = Keypair(filename=self.key_file)
59         self.cert_file = cert_file
60         self.cert = Certificate(filename=self.cert_file)
61         self.cache = cache
62         if self.cache is None:
63             self.cache = Cache()
64
65         # load registries
66         from sfa.server.registry import Registries
67         self.registries = Registries()
68
69         # load aggregates
70         from sfa.server.aggregate import Aggregates
71         self.aggregates = Aggregates()
72
73         # filled later on by generic/Generic
74         self.manager = None
75         self._dbsession = None
76
77     def server_proxy(self, interface, cred, timeout=30):
78         """
79         Returns a connection to the specified interface. Use the specified
80         credential to determine the caller and look for the caller's key/cert 
81         in the registry hierarchy cache. 
82         """
83         from sfa.trust.hierarchy import Hierarchy
84         if not isinstance(cred, Credential):
85             cred_obj = Credential(string=cred)
86         else:
87             cred_obj = cred
88         caller_gid = cred_obj.get_gid_caller()
89         hierarchy = Hierarchy()
90         auth_info = hierarchy.get_auth_info(caller_gid.get_hrn())
91         key_file = auth_info.get_privkey_filename()
92         cert_file = auth_info.get_gid_filename()
93         server = interface.server_proxy(key_file, cert_file, timeout)
94         return server
95
96     def dbsession(self):
97         if self._dbsession is None:
98             self._dbsession = alchemy.session()
99         return self._dbsession
100
101     def close_dbsession(self):
102         if self._dbsession is None:
103             return
104         alchemy.close_session(self._dbsession)
105         self._dbsession = None
106
107     def getCredential(self, minimumExpiration=0):
108         """
109         Return a valid credential for this interface.
110         """
111         type = 'authority'
112         path = self.config.SFA_DATA_DIR
113         filename = ".".join([self.interface, self.hrn, type, "cred"])
114         cred_filename = os.path.join(path, filename)
115         cred = None
116         if os.path.isfile(cred_filename):
117             cred = Credential(filename=cred_filename)
118             # make sure cred isnt expired
119             if not cred.get_expiration or \
120                datetime.datetime.utcnow() + datetime.timedelta(seconds=minimumExpiration) < cred.get_expiration():
121                 return cred.save_to_string(save_parents=True)
122
123         # get a new credential
124         if self.interface in ['registry']:
125             cred = self._getCredentialRaw()
126         else:
127             cred = self._getCredential()
128         cred.save_to_file(cred_filename, save_parents=True)
129
130         return cred.save_to_string(save_parents=True)
131
132     def getDelegatedCredential(self, creds):
133         """
134         Attempt to find a credential delegated to us in
135         the specified list of creds.
136         """
137         from sfa.trust.hierarchy import Hierarchy
138         if creds and not isinstance(creds, list):
139             creds = [creds]
140         hierarchy = Hierarchy()
141
142         delegated_cred = None
143         for cred in creds:
144             if hierarchy.auth_exists(Credential(cred=cred).get_gid_caller().get_hrn()):
145                 delegated_cred = cred
146                 break
147         return delegated_cred
148
149     def _getCredential(self):
150         """ 
151         Get our credential from a remote registry 
152         """
153         from sfa.server.registry import Registries
154         registries = Registries()
155         registry = registries.server_proxy(
156             self.hrn, self.key_file, self.cert_file)
157         cert_string = self.cert.save_to_string(save_parents=True)
158         # get self credential
159         self_cred = registry.GetSelfCredential(
160             cert_string, self.hrn, 'authority')
161         # get credential
162         cred = registry.GetCredential(self_cred, self.hrn, 'authority')
163         return Credential(string=cred)
164
165     def _getCredentialRaw(self):
166         """
167         Get our current credential directly from the local registry.
168         """
169
170         hrn = self.hrn
171         auth_hrn = self.auth.get_authority(hrn)
172
173         # is this a root or sub authority
174         if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
175             auth_hrn = hrn
176         auth_info = self.auth.get_auth_info(auth_hrn)
177         # xxx although unlikely we might want to check for a potential leak
178         dbsession = self.dbsession()
179         from sfa.storage.model import RegRecord
180         record = dbsession.query(RegRecord).filter_by(
181             type='authority+sa', hrn=hrn).first()
182         if not record:
183             raise RecordNotFound(hrn)
184         type = record.type
185         object_gid = record.get_gid_object()
186         new_cred = Credential(subject=object_gid.get_subject())
187         new_cred.set_gid_caller(object_gid)
188         new_cred.set_gid_object(object_gid)
189         new_cred.set_issuer_keys(
190             auth_info.get_privkey_filename(), auth_info.get_gid_filename())
191
192         r1 = determine_rights(type, hrn)
193         new_cred.set_privileges(r1)
194         new_cred.encode()
195         new_cred.sign()
196
197         return new_cred
198
199     def loadCredential(self):
200         """
201         Attempt to load credential from file if it exists. If it doesnt get
202         credential from registry.
203         """
204
205         # see if this file exists
206         # XX This is really the aggregate's credential. Using this is easier than getting
207         # the registry's credential from iteslf (ssl errors).
208         filename = self.interface + self.hrn + ".ma.cred"
209         ma_cred_path = os.path.join(self.config.SFA_DATA_DIR, filename)
210         try:
211             self.credential = Credential(filename=ma_cred_path)
212         except IOError:
213             self.credential = self.getCredentialFromRegistry()
214
215     def get_cached_server_version(self, server):
216         cache_key = server.url + "-version"
217         server_version = None
218         if self.cache:
219             server_version = self.cache.get(cache_key)
220         if not server_version:
221             result = server.GetVersion()
222             server_version = ReturnValue.get_value(result)
223             # cache version for 24 hours
224             self.cache.add(cache_key, server_version, ttl=60 * 60 * 24)
225         return server_version
226
227     def get_geni_code(self, result):
228         code = {
229             'geni_code': GENICODE.SUCCESS,
230             'am_type': 'sfa',
231             'am_code': None,
232         }
233         if isinstance(result, SfaFault):
234             code['geni_code'] = result.faultCode
235             code['am_code'] = result.faultCode
236
237         return code
238
239     def get_geni_value(self, result):
240         value = result
241         if isinstance(result, SfaFault):
242             value = ""
243         return value
244
245     def get_geni_output(self, result):
246         output = ""
247         if isinstance(result, SfaFault):
248             output = result.faultString
249         return output
250
251     def prepare_response_am(self, result):
252         version = version_core()
253         response = {
254             'geni_api': 3,
255             'code': self.get_geni_code(result),
256             'value': self.get_geni_value(result),
257             'output': self.get_geni_output(result),
258         }
259         return response
260
261     def prepare_response(self, result, method=""):
262         """
263         Converts the specified result into a standard GENI compliant 
264         response  
265         """
266         # as of dec 13 2011 we only support API v2
267         if self.interface.lower() in ['aggregate', 'slicemgr']:
268             result = self.prepare_response_am(result)
269         return XmlrpcApi.prepare_response(self, result, method)