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