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