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