finish cleaning with util.report
[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 component_port=12346
37 import os, os.path
38 import sys
39 from optparse import OptionParser
40 import logging
41
42 from sfa.util.sfalogging import sfa_logger
43 from sfa.trust.trustedroot import TrustedRootList
44 from sfa.trust.certificate import Keypair, Certificate
45 from sfa.trust.hierarchy import Hierarchy
46 from sfa.util.config import Config
47 from sfa.plc.api import SfaAPI
48 from sfa.server.registry import Registries
49 from sfa.server.aggregate import Aggregates
50
51 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
52 def daemon():
53     """Daemonize the current process."""
54     if os.fork() != 0: os._exit(0)
55     os.setsid()
56     if os.fork() != 0: os._exit(0)
57     os.umask(0)
58     devnull = os.open(os.devnull, os.O_RDWR)
59     os.dup2(devnull, 0)
60     # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
61     crashlog = os.open('/var/log/httpd/sfa_access_log', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
62     os.dup2(crashlog, 1)
63     os.dup2(crashlog, 2)
64
65 def init_server_key(server_key_file, server_cert_file, config, hierarchy):
66
67     subject = config.SFA_INTERFACE_HRN
68     # check if the server's private key exists. If it doesnt,
69     # get the right one from the authorities directory. If it cant be
70     # found in the authorities directory, generate a random one
71     if not os.path.exists(server_key_file):
72         hrn = config.SFA_INTERFACE_HRN.lower()
73         hrn_parts = hrn.split(".")
74         rel_key_path = hrn
75         pkey_filename = hrn+".pkey"
76
77         # sub authority's have "." in their hrn. This must
78         # be converted to os.path separator
79         if len(hrn_parts) > 0:
80             rel_key_path = hrn.replace(".", os.sep)
81             pkey_filename= hrn_parts[-1]+".pkey"
82
83         key_file = os.sep.join([hierarchy.basedir, rel_key_path, pkey_filename])
84         if not os.path.exists(key_file):
85             # if it doesnt exist then this is probably a fresh interface
86             # with no records. Generate a random keypair for now
87             sfa_logger.debug("server's public key not found in %s" % key_file)
88             sfa_logger.debug("generating a random server key pair")
89             key = Keypair(create=True)
90             key.save_to_file(server_key_file)
91             cert = Certificate(subject=subject)
92             cert.set_issuer(key=key, subject=subject)
93             cert.set_pubkey(key)
94             cert.sign()
95             cert.save_to_file(server_cert_file, save_parents=True)
96
97         else:
98             # the pkey was found in the authorites directory. lets 
99             # copy it to where the server key should be and generate
100             # the cert
101             key = Keypair(filename=key_file)
102             key.save_to_file(server_key_file)
103             cert = Certificate(subject=subject)
104             cert.set_issuer(key=key, subject=subject)
105             cert.set_pubkey(key)
106             cert.sign()
107             cert.save_to_file(server_cert_file, save_parents=True)
108
109
110     # If private key exists and cert doesnt, recreate cert
111     if (os.path.exists(server_key_file)) and (not os.path.exists(server_cert_file)):
112         key = Keypair(filename=server_key_file)
113         cert = Certificate(subject=subject)
114         cert.set_issuer(key=key, subject=subject)
115         cert.set_pubkey(key)
116         cert.sign()
117         cert.save_to_file(server_cert_file)
118
119 def init_server(options, config):
120     """
121     Execute the init method defined in the manager file 
122     """
123     manager_base = 'sfa.managers'
124     if options.registry:
125         mgr_type = config.SFA_REGISTRY_TYPE
126         manager_module = manager_base + ".registry_manager_%s" % mgr_type
127         try: manager = __import__(manager_module, fromlist=[manager_base])
128         except: manager = None
129         if manager and hasattr(manager, 'init_server'): 
130             manager.init_server()    
131     if options.am:
132         mgr_type = config.SFA_AGGREGATE_TYPE
133         manager_module = manager_base + ".aggregate_manager_%s" % mgr_type
134         try: manager = __import__(manager_module, fromlist=[manager_base])
135         except: manager = None
136         if manager and hasattr(manager, 'init_server'):
137             manager.init_server()    
138     if options.sm:
139         mgr_type = config.SFA_SM_TYPE
140         manager_module = manager_base + ".slice_manager_%s" % mgr_type
141         try: manager = __import__(manager_module, fromlist=[manager_base])
142         except: manager = None
143         if manager and hasattr(manager, 'init_server'):
144             manager.init_server()    
145     if options.cm:
146         mgr_type = config.SFA_CM_TYPE
147         manager_module = manager_base + ".component_manager_%s" % mgr_type
148         try: manager = __import__(manager_module, fromlist=[manager_base])
149         except: manager = None
150         if manager and hasattr(manager, 'init_server'):
151             manager.init_server()
152
153 def sync_interfaces(server_key_file, server_cert_file):
154     """
155     Attempt to install missing trusted gids and db records for 
156     our federated interfaces
157     """
158     api = SfaAPI(key_file = server_key_file, cert_file = server_cert_file)
159     registries = Registries(api)
160     aggregates = Aggregates(api)
161     registries.sync_interfaces()
162     aggregates.sync_interfaces()
163
164 def main():
165     # xxx get rid of globals - name consistently CamelCase or under_score
166     global AuthHierarchy
167     global TrustedRoots
168     global registry_port
169     global aggregate_port
170     global slicemgr_port
171
172     # Generate command line parser
173     parser = OptionParser(usage="sfa-server [options]")
174     parser.add_option("-r", "--registry", dest="registry", action="store_true",
175          help="run registry server", default=False)
176     parser.add_option("-s", "--slicemgr", dest="sm", action="store_true",
177          help="run slice manager", default=False)
178     parser.add_option("-a", "--aggregate", dest="am", action="store_true",
179          help="run aggregate manager", default=False)
180     parser.add_option("-c", "--component", dest="cm", action="store_true",
181          help="run component server", default=False)
182     parser.add_option("-v", "--verbose", dest="verbose", action="store_true", 
183          help="verbose mode", default=False)
184     parser.add_option("-d", "--daemon", dest="daemon", action="store_true",
185          help="Run as daemon.", default=False)
186     (options, args) = parser.parse_args()
187     if options.verbose: sfa_logger.setLevel(logging.DEBUG)
188
189     config = Config()
190     if config.SFA_API_DEBUG: sfa_logger.setLevel(logging.DEBUG)
191     hierarchy = Hierarchy()
192     server_key_file = os.path.join(hierarchy.basedir, "server.key")
193     server_cert_file = os.path.join(hierarchy.basedir, "server.cert")
194
195     init_server_key(server_key_file, server_cert_file, config, hierarchy)
196     init_server(options, config)
197     sync_interfaces(server_key_file, server_cert_file)   
198  
199     if (options.daemon):  daemon()
200     # start registry server
201     if (options.registry):
202         from sfa.server.registry import Registry
203         r = Registry("", registry_port, server_key_file, server_cert_file)
204         r.start()
205
206     # start aggregate manager
207     if (options.am):
208         from sfa.server.aggregate import Aggregate
209         a = Aggregate("", aggregate_port, server_key_file, server_cert_file)
210         a.start()
211
212     # start slice manager
213     if (options.sm):
214         from sfa.server.slicemgr import SliceMgr
215         s = SliceMgr("", slicemgr_port, server_key_file, server_cert_file)
216         s.start()
217
218     if (options.cm):
219         from sfa.server.component import Component
220         c = Component("", component_port, server_key_file, server_cert_file)
221         c.start()
222
223 if __name__ == "__main__":
224     try:
225         main()
226     except:
227         sfa_logger.log_exc_critical("SFA server is exiting")