280bf14ee64919e753d3730f42429721f45e7d4d
[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
14 from sfa.server.xmlrpcapi import XmlrpcApi
15
16 from sfa.client.return_value import ReturnValue
17
18
19 ####################
20 class SfaApi (XmlrpcApi): 
21     
22     """
23     An SfaApi instance is a basic xmlrcp service
24     augmented with the local cryptographic material and hrn
25
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
30
31     Finally it contains a cache instance
32
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
37     """
38
39     def __init__ (self, encoding="utf-8", methods='sfa.methods', 
40                   config = "/etc/sfa/sfa_config.py", 
41                   peer_cert = None, interface = None, 
42                   key_file = None, cert_file = None, cache = None):
43         
44         XmlrpcApi.__init__ (self, encoding)
45         
46         # we may be just be documenting the API
47         if config is None:
48             return
49         # Load configuration
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)
59         self.cache = cache
60         if self.cache is None:
61             self.cache = Cache()
62
63         # load registries
64         from sfa.server.registry import Registries
65         self.registries = Registries() 
66
67         # load aggregates
68         from sfa.server.aggregate import Aggregates
69         self.aggregates = Aggregates()
70         
71         # filled later on by generic/Generic
72         self.manager=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         
94     def getCredential(self, minimumExpiration=0):
95         """
96         Return a valid credential for this interface.
97         """
98         type = 'authority'
99         path = self.config.SFA_DATA_DIR
100         filename = ".".join([self.interface, self.hrn, type, "cred"])
101         cred_filename = os.path.join(path,filename)
102         cred = None
103         if os.path.isfile(cred_filename):
104             cred = Credential(filename = cred_filename)
105             # make sure cred isnt expired
106             if not cred.get_expiration or \
107                datetime.datetime.utcnow() + datetime.timedelta(seconds=minimumExpiration) < cred.get_expiration():
108                 return cred.save_to_string(save_parents=True)
109
110         # get a new credential
111         if self.interface in ['registry']:
112             cred =  self._getCredentialRaw()
113         else:
114             cred =  self._getCredential()
115         cred.save_to_file(cred_filename, save_parents=True)
116
117         return cred.save_to_string(save_parents=True)
118
119
120     def getDelegatedCredential(self, creds):
121         """
122         Attempt to find a credential delegated to us in
123         the specified list of creds.
124         """
125         from sfa.trust.hierarchy import Hierarchy
126         if creds and not isinstance(creds, list): 
127             creds = [creds]
128         hierarchy = Hierarchy()
129                 
130         delegated_cred = None
131         for cred in creds:
132             if hierarchy.auth_exists(Credential(string=cred).get_gid_caller().get_hrn()):
133                 delegated_cred = cred
134                 break
135         return delegated_cred
136  
137     def _getCredential(self):
138         """ 
139         Get our credential from a remote registry 
140         """
141         from sfa.server.registry import Registries
142         registries = Registries()
143         registry = registries.server_proxy(self.hrn, self.key_file, self.cert_file)
144         cert_string=self.cert.save_to_string(save_parents=True)
145         # get self credential
146         self_cred = registry.GetSelfCredential(cert_string, self.hrn, 'authority')
147         # get credential
148         cred = registry.GetCredential(self_cred, self.hrn, 'authority')
149         return Credential(string=cred)
150
151     def _getCredentialRaw(self):
152         """
153         Get our current credential directly from the local registry.
154         """
155
156         hrn = self.hrn
157         auth_hrn = self.auth.get_authority(hrn)
158     
159         # is this a root or sub authority
160         if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
161             auth_hrn = hrn
162         auth_info = self.auth.get_auth_info(auth_hrn)
163         from sfa.storage.alchemy import dbsession
164         from sfa.storage.persistentobjs import RegRecord
165         record = dbsession.query(RegRecord).filter_by(type='authority+sa', hrn=hrn).first()
166         if not record:
167             raise RecordNotFound(hrn)
168         type = record.type
169         object_gid = record.get_gid_object()
170         new_cred = Credential(subject = object_gid.get_subject())
171         new_cred.set_gid_caller(object_gid)
172         new_cred.set_gid_object(object_gid)
173         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
174         
175         r1 = determine_rights(type, hrn)
176         new_cred.set_privileges(r1)
177         new_cred.encode()
178         new_cred.sign()
179
180         return new_cred
181    
182     def loadCredential (self):
183         """
184         Attempt to load credential from file if it exists. If it doesnt get
185         credential from registry.
186         """
187
188         # see if this file exists
189         # XX This is really the aggregate's credential. Using this is easier than getting
190         # the registry's credential from iteslf (ssl errors).
191         filename = self.interface + self.hrn + ".ma.cred"
192         ma_cred_path = os.path.join(self.config.SFA_DATA_DIR,filename)
193         try:
194             self.credential = Credential(filename = ma_cred_path)
195         except IOError:
196             self.credential = self.getCredentialFromRegistry()
197
198     def get_cached_server_version(self, server):
199         cache_key = server.url + "-version"
200         server_version = None
201         if self.cache:
202             server_version = self.cache.get(cache_key)
203         if not server_version:
204             result = server.GetVersion()
205             server_version = ReturnValue.get_value(result)
206             # cache version for 24 hours
207             self.cache.add(cache_key, server_version, ttl= 60*60*24)
208         return server_version
209
210
211     def get_geni_code(self, result):
212         code = {
213             'geni_code': GENICODE.SUCCESS, 
214             'am_type': 'sfa',
215             'am_code': None,
216         }
217         if isinstance(result, SfaFault):
218             code['geni_code'] = result.faultCode
219             code['am_code'] = result.faultCode                        
220                 
221         return code
222
223     def get_geni_value(self, result):
224         value = result
225         if isinstance(result, SfaFault):
226             value = ""
227         return value
228
229     def get_geni_output(self, result):
230         output = ""
231         if isinstance(result, SfaFault):
232             output = result.faultString 
233         return output
234
235     def prepare_response_v2_am(self, result):
236         response = {
237             'geni_api': 2,             
238             'code': self.get_geni_code(result),
239             'value': self.get_geni_value(result),
240             'output': self.get_geni_output(result),
241         }
242         return response
243     
244     def prepare_response(self, result, method=""):
245         """
246         Converts the specified result into a standard GENI compliant 
247         response  
248         """
249         # as of dec 13 2011 we only support API v2
250         if self.interface.lower() in ['aggregate', 'slicemgr']: 
251             result = self.prepare_response_v2_am(result)
252         return XmlrpcApi.prepare_response(self, result, method)
253