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