generic to handle the manager instance in the api too
[sfa.git] / sfa / server / sfaapi.py
1 import os.path
2 import datetime
3
4 from sfa.util.faults import SfaAPIError
5 from sfa.util.config import Config
6 from sfa.util.cache import Cache
7 from sfa.trust.auth import Auth
8 from sfa.trust.certificate import Keypair, Certificate
9 from sfa.trust.credential import Credential
10 from sfa.trust.rights import determine_rights
11
12 # this is wrong all right, but temporary, will use generic
13 from sfa.server.xmlrpcapi import XmlrpcApi
14 import os
15 import datetime
16
17 ####################
18 class SfaApi (XmlrpcApi): 
19     
20     """
21     An SfaApi instance is a basic xmlrcp service
22     augmented with the local cryptographic material and hrn
23     It also has the notion of neighbour sfa services 
24     as defined in /etc/sfa/{aggregates,registries}.xml
25     Finally it contains a cache instance
26     It gets augmented by the generic layer with 
27     (*) an instance of manager (actually a manager module for now)
28     (*) which in turn holds an instance of a testbed driver
29     """
30
31     def __init__ (self, encoding="utf-8", methods='sfa.methods', 
32                   config = "/etc/sfa/sfa_config.py", 
33                   peer_cert = None, interface = None, 
34                   key_file = None, cert_file = None, cache = None):
35         
36         XmlrpcApi.__init__ (self, encoding)
37         
38         # we may be just be documenting the API
39         if config is None:
40             return
41         # Load configuration
42         self.config = Config(config)
43         self.credential = None
44         self.auth = Auth(peer_cert)
45         self.interface = interface
46         self.hrn = self.config.SFA_INTERFACE_HRN
47         self.key_file = key_file
48         self.key = Keypair(filename=self.key_file)
49         self.cert_file = cert_file
50         self.cert = Certificate(filename=self.cert_file)
51         self.cache = cache
52         if self.cache is None:
53             self.cache = Cache()
54
55         # load registries
56         from sfa.server.registry import Registries
57         self.registries = Registries() 
58
59         # load aggregates
60         from sfa.server.aggregate import Aggregates
61         self.aggregates = Aggregates()
62         
63         # filled later on by generic/Generic
64         self.manager=None
65
66     # tmp
67     def get_interface_manager(self, manager_base = 'sfa.managers'):
68         return self.manager
69
70     def get_server(self, interface, cred, timeout=30):
71         """
72         Returns a connection to the specified interface. Use the specified
73         credential to determine the caller and look for the caller's key/cert 
74         in the registry hierarchy cache. 
75         """       
76         from sfa.trust.hierarchy import Hierarchy
77         if not isinstance(cred, Credential):
78             cred_obj = Credential(string=cred)
79         else:
80             cred_obj = cred
81         caller_gid = cred_obj.get_gid_caller()
82         hierarchy = Hierarchy()
83         auth_info = hierarchy.get_auth_info(caller_gid.get_hrn())
84         key_file = auth_info.get_privkey_filename()
85         cert_file = auth_info.get_gid_filename()
86         server = interface.get_server(key_file, cert_file, timeout)
87         return server
88                
89         
90     def getCredential(self):
91         """
92         Return a valid credential for this interface. 
93         """
94         type = 'authority'
95         path = self.config.SFA_DATA_DIR
96         filename = ".".join([self.interface, self.hrn, type, "cred"])
97         cred_filename = os.path.join(path,filename)
98         cred = None
99         if os.path.isfile(cred_filename):
100             cred = Credential(filename = cred_filename)
101             # make sure cred isnt expired
102             if not cred.get_expiration or \
103                datetime.datetime.utcnow() < cred.get_expiration():    
104                 return cred.save_to_string(save_parents=True)
105
106         # get a new credential
107         if self.interface in ['registry']:
108             cred =  self.__getCredentialRaw()
109         else:
110             cred =  self.__getCredential()
111         cred.save_to_file(cred_filename, save_parents=True)
112
113         return cred.save_to_string(save_parents=True)
114
115
116     def getDelegatedCredential(self, creds):
117         """
118         Attempt to find a credential delegated to us in
119         the specified list of creds.
120         """
121         from sfa.trust.hierarchy import Hierarchy
122         if creds and not isinstance(creds, list): 
123             creds = [creds]
124         hierarchy = Hierarchy()
125                 
126         delegated_cred = None
127         for cred in creds:
128             if hierarchy.auth_exists(Credential(string=cred).get_gid_caller().get_hrn()):
129                 delegated_cred = cred
130                 break
131         return delegated_cred
132  
133     def __getCredential(self):
134         """ 
135         Get our credential from a remote registry 
136         """
137         from sfa.server.registry import Registries
138         registries = Registries()
139         registry = registries.get_server(self.hrn, self.key_file, self.cert_file)
140         cert_string=self.cert.save_to_string(save_parents=True)
141         # get self credential
142         self_cred = registry.GetSelfCredential(cert_string, self.hrn, 'authority')
143         # get credential
144         cred = registry.GetCredential(self_cred, self.hrn, 'authority')
145         return Credential(string=cred)
146
147     def __getCredentialRaw(self):
148         """
149         Get our current credential directly from the local registry.
150         """
151
152         hrn = self.hrn
153         auth_hrn = self.auth.get_authority(hrn)
154     
155         # is this a root or sub authority
156         if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
157             auth_hrn = hrn
158         auth_info = self.auth.get_auth_info(auth_hrn)
159         table = self.SfaTable()
160         records = table.findObjects({'hrn': hrn, 'type': 'authority+sa'})
161         if not records:
162             raise RecordNotFound
163         record = records[0]
164         type = record['type']
165         object_gid = record.get_gid_object()
166         new_cred = Credential(subject = object_gid.get_subject())
167         new_cred.set_gid_caller(object_gid)
168         new_cred.set_gid_object(object_gid)
169         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
170         
171         r1 = determine_rights(type, hrn)
172         new_cred.set_privileges(r1)
173         new_cred.encode()
174         new_cred.sign()
175
176         return new_cred
177    
178     def loadCredential (self):
179         """
180         Attempt to load credential from file if it exists. If it doesnt get
181         credential from registry.
182         """
183
184         # see if this file exists
185         # XX This is really the aggregate's credential. Using this is easier than getting
186         # the registry's credential from iteslf (ssl errors).
187         filename = self.interface + self.hrn + ".ma.cred"
188         ma_cred_path = os.path.join(self.config.SFA_DATA_DIR,filename)
189         try:
190             self.credential = Credential(filename = ma_cred_path)
191         except IOError:
192             self.credential = self.getCredentialFromRegistry()
193
194     def get_cached_server_version(self, server):
195         cache_key = server.url + "-version"
196         server_version = None
197         if self.cache:
198             server_version = self.cache.get(cache_key)
199         if not server_version:
200             server_version = server.GetVersion()
201             # cache version for 24 hours
202             self.cache.add(cache_key, server_version, ttl= 60*60*24)
203         return server_version