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