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