156219303e38e6af72f3773e9fedcdbf9e10e014
[sfa.git] / sfa / server / sfa-server.py
1 #!/usr/bin/python
2 #
3 # SFA PLC Wrapper
4 #
5 # This wrapper implements the SFA Registry and Slice Interfaces on PLC.
6 # Depending on command line options, it starts some combination of a
7 # Registry, an Aggregate Manager, and a Slice Manager.
8 #
9 # There are several items that need to be done before starting the wrapper
10 # server.
11 #
12 # NOTE:  Many configuration settings, including the PLC maintenance account
13 # credentials, URI of the PLCAPI, and PLC DB URI and admin credentials are initialized
14 # from your MyPLC configuration (/etc/planetlab/plc_config*).  Please make sure this information
15 # is up to date and accurate.
16 #
17 # 1) Import the existing planetlab database, creating the
18 #    appropriate SFA records. This is done by running the "sfa-import-plc.py" tool.
19 #
20 # 2) Create a "trusted_roots" directory and place the certificate of the root
21 #    authority in that directory. Given the defaults in sfa-import-plc.py, this
22 #    certificate would be named "planetlab.gid". For example,
23 #
24 #    mkdir trusted_roots; cp authorities/planetlab.gid trusted_roots/
25 #
26 # TODO: Can all three servers use the same "registry" certificate?
27 ##
28
29 # TCP ports for the three servers
30 #registry_port=12345
31 #aggregate_port=12346
32 #slicemgr_port=12347
33 ### xxx todo not in the config yet
34 component_port=12346
35 import os, os.path
36 import traceback
37 import sys
38 from optparse import OptionParser
39
40 from sfa.util.sfalogging import sfa_logger
41 from sfa.trust.trustedroot import TrustedRootList
42 from sfa.trust.certificate import Keypair, Certificate
43 from sfa.trust.hierarchy import Hierarchy
44 from sfa.trust.gid import GID
45 from sfa.util.config import Config
46 from sfa.plc.api import SfaAPI
47 from sfa.server.registry import Registries
48 from sfa.server.aggregate import Aggregates
49
50 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
51 def daemon():
52     """Daemonize the current process."""
53     if os.fork() != 0: os._exit(0)
54     os.setsid()
55     if os.fork() != 0: os._exit(0)
56     os.umask(0)
57     devnull = os.open(os.devnull, os.O_RDWR)
58     os.dup2(devnull, 0)
59     # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
60     crashlog = os.open('/var/log/httpd/sfa_access_log', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
61     os.dup2(crashlog, 1)
62     os.dup2(crashlog, 2)
63
64 def init_server_key(server_key_file, server_cert_file, config, hierarchy):
65
66     hrn = config.SFA_INTERFACE_HRN.lower()
67     # check if the server's private key exists. If it doesnt,
68     # get the right one from the authorities directory. If it cant be
69     # found in the authorities directory, generate a random one
70     if not os.path.exists(server_key_file):
71         hrn = config.SFA_INTERFACE_HRN.lower()
72         hrn_parts = hrn.split(".")
73         rel_key_path = hrn
74         pkey_filename = hrn+".pkey"
75
76         # sub authority's have "." in their hrn. This must
77         # be converted to os.path separator
78         if len(hrn_parts) > 0:
79             rel_key_path = hrn.replace(".", os.sep)
80             pkey_filename= hrn_parts[-1]+".pkey"
81
82         key_file = os.sep.join([hierarchy.basedir, rel_key_path, pkey_filename])
83         if not os.path.exists(key_file):
84             # if it doesnt exist then this is probably a fresh interface
85             # with no records. Generate a random keypair for now
86             sfa_logger().debug("server's public key not found in %s" % key_file)
87             sfa_logger().debug("generating a random server key pair")
88             key = Keypair(create=True)
89             key.save_to_file(server_key_file)
90             init_server_cert(hrn, key, server_cert_file, self_signed=True)    
91
92         else:
93             # the pkey was found in the authorites directory. lets 
94             # copy it to where the server key should be and generate
95             # the cert
96             key = Keypair(filename=key_file)
97             key.save_to_file(server_key_file)
98             init_server_cert(hrn, key, server_cert_file)    
99
100     # If private key exists and cert doesnt, recreate cert
101     if (os.path.exists(server_key_file)) and (not os.path.exists(server_cert_file)):
102         key = Keypair(filename=server_key_file)
103         init_server_cert(hrn, key, server_cert_file)    
104
105
106 def init_server_cert(hrn, key, server_cert_file, self_signed=False):
107     """
108     Setup the certificate for this server. Attempt to use gid before 
109     creating a self signed cert 
110     """
111     if self_signed:
112         init_self_signed_cert(hrn, key, server_cert_file)
113     else:
114         try:
115             # look for gid file
116             sfa_logger().debug("generating server cert from gid: %s"% hrn)
117             hierarchy = Hierarchy()
118             auth_info = hierarchy.get_auth_info(hrn)
119             gid = GID(filename=auth_info.gid_filename)
120             gid.save_to_file(filename=server_cert_file)
121         except:
122             # fall back to self signed cert
123             sfa_logger().debug("gid for %s not found" % hrn)
124             init_self_signed_cert(hrn, key, server_cert_file)        
125         
126 def init_self_signed_cert(hrn, key, server_cert_file):
127     sfa_logger().debug("generating self signed cert")
128     # generate self signed certificate
129     cert = Certificate(subject=hrn)
130     cert.set_issuer(key=key, subject=hrn)
131     cert.set_pubkey(key)
132     cert.sign()
133     cert.save_to_file(server_cert_file)
134
135 def init_server(options, config):
136     """
137     Execute the init method defined in the manager file 
138     """
139     manager_base = 'sfa.managers'
140     if options.registry:
141         mgr_type = config.SFA_REGISTRY_TYPE
142         manager_module = manager_base + ".registry_manager_%s" % mgr_type
143         try: manager = __import__(manager_module, fromlist=[manager_base])
144         except: manager = None
145         if manager and hasattr(manager, 'init_server'): 
146             manager.init_server()    
147     if options.am:
148         mgr_type = config.SFA_AGGREGATE_TYPE
149         manager_module = manager_base + ".aggregate_manager_%s" % mgr_type
150         try: manager = __import__(manager_module, fromlist=[manager_base])
151         except: manager = None
152         if manager and hasattr(manager, 'init_server'):
153             manager.init_server()    
154     if options.sm:
155         mgr_type = config.SFA_SM_TYPE
156         manager_module = manager_base + ".slice_manager_%s" % mgr_type
157         try: manager = __import__(manager_module, fromlist=[manager_base])
158         except: manager = None
159         if manager and hasattr(manager, 'init_server'):
160             manager.init_server()    
161     if options.cm:
162         mgr_type = config.SFA_CM_TYPE
163         manager_module = manager_base + ".component_manager_%s" % mgr_type
164         try: manager = __import__(manager_module, fromlist=[manager_base])
165         except: manager = None
166         if manager and hasattr(manager, 'init_server'):
167             manager.init_server()
168
169 def sync_interfaces(server_key_file, server_cert_file):
170     """
171     Attempt to install missing trusted gids and db records for 
172     our federated interfaces
173     """
174     api = SfaAPI(key_file = server_key_file, cert_file = server_cert_file)
175     registries = Registries(api)
176     aggregates = Aggregates(api)
177     registries.sync_interfaces()
178     aggregates.sync_interfaces()
179
180 def main():
181     # Generate command line parser
182     parser = OptionParser(usage="sfa-server [options]")
183     parser.add_option("-r", "--registry", dest="registry", action="store_true",
184          help="run registry server", default=False)
185     parser.add_option("-s", "--slicemgr", dest="sm", action="store_true",
186          help="run slice manager", default=False)
187     parser.add_option("-a", "--aggregate", dest="am", action="store_true",
188          help="run aggregate manager", default=False)
189     parser.add_option("-c", "--component", dest="cm", action="store_true",
190          help="run component server", default=False)
191     parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0,
192          help="verbose mode - cumulative")
193     parser.add_option("-d", "--daemon", dest="daemon", action="store_true",
194          help="Run as daemon.", default=False)
195     (options, args) = parser.parse_args()
196     sfa_logger().setLevelFromOptVerbose(options.verbose)
197
198     config = Config()
199     if config.SFA_API_DEBUG: sfa_logger().setLevelDebug()
200     hierarchy = Hierarchy()
201     server_key_file = os.path.join(hierarchy.basedir, "server.key")
202     server_cert_file = os.path.join(hierarchy.basedir, "server.cert")
203
204     init_server_key(server_key_file, server_cert_file, config, hierarchy)
205     init_server(options, config)
206     sync_interfaces(server_key_file, server_cert_file)   
207  
208     if (options.daemon):  daemon()
209     # start registry server
210     if (options.registry):
211         from sfa.server.registry import Registry
212         r = Registry("", config.SFA_REGISTRY_PORT, server_key_file, server_cert_file)
213         r.start()
214
215     # start aggregate manager
216     if (options.am):
217         from sfa.server.aggregate import Aggregate
218         a = Aggregate("", config.SFA_AGGREGATE_PORT, server_key_file, server_cert_file)
219         a.start()
220
221     # start slice manager
222     if (options.sm):
223         from sfa.server.slicemgr import SliceMgr
224         s = SliceMgr("", config.SFA_SM_PORT, server_key_file, server_cert_file)
225         s.start()
226
227     if (options.cm):
228         from sfa.server.component import Component
229         c = Component("", config.component_port, server_key_file, server_cert_file)
230 #        c = Component("", config.SFA_COMPONENT_PORT, server_key_file, server_cert_file)
231         c.start()
232
233 if __name__ == "__main__":
234     try:
235         main()
236     except:
237         sfa_logger().log_exc_critical("SFA server is exiting")