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