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