merging with geni-api branch
[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 geni_am_port=12348
38 import os, os.path
39 import sys
40 from optparse import OptionParser
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.util.report import trace
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/sfa.daemon', 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     subject = config.SFA_INTERFACE_HRN
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             trace("server's public key not found in %s" % key_file)
87             trace("generating a random server key pair")
88             key = Keypair(create=True)
89             key.save_to_file(server_key_file)
90             cert = Certificate(subject=subject)
91             cert.set_issuer(key=key, subject=subject)
92             cert.set_pubkey(key)
93             cert.sign()
94             cert.save_to_file(server_cert_file, save_parents=True)
95
96         else:
97             # the pkey was found in the authorites directory. lets 
98             # copy it to where the server key should be and generate
99             # the cert
100             key = Keypair(filename=key_file)
101             key.save_to_file(server_key_file)
102             cert = Certificate(subject=subject)
103             cert.set_issuer(key=key, subject=subject)
104             cert.set_pubkey(key)
105             cert.sign()
106             cert.save_to_file(server_cert_file, save_parents=True)
107
108
109     # If private key exists and cert doesnt, recreate cert
110     if (os.path.exists(server_key_file)) and (not os.path.exists(server_cert_file)):
111         key = Keypair(filename=server_key_file)
112         cert = Certificate(subject=subject)
113         cert.set_issuer(key=key, subject=subject)
114         cert.set_pubkey(key)
115         cert.sign()
116         cert.save_to_file(server_cert_file)
117
118 def init_server(options, config):
119     """
120     Execute the init method defined in the manager file 
121     """
122     manager_base = 'sfa.managers'
123     if options.registry:
124         mgr_type = config.SFA_REGISTRY_TYPE
125         manager_module = manager_base + ".registry_manager_%s" % mgr_type
126         try: manager = __import__(manager_module, fromlist=[manager_base])
127         except: manager = None
128         if manager and hasattr(manager, 'init_server'): 
129             manager.init_server()    
130     if options.am:
131         mgr_type = config.SFA_AGGREGATE_TYPE
132         manager_module = manager_base + ".aggregate_manager_%s" % mgr_type
133         try: manager = __import__(manager_module, fromlist=[manager_base])
134         except: manager = None
135         if manager and hasattr(manager, 'init_server'):
136             manager.init_server()    
137     if options.sm:
138         mgr_type = config.SFA_SM_TYPE
139         manager_module = manager_base + ".slice_manager_%s" % mgr_type
140         try: manager = __import__(manager_module, fromlist=[manager_base])
141         except: manager = None
142         if manager and hasattr(manager, 'init_server'):
143             manager.init_server()    
144     if options.cm:
145         mgr_type = config.SFA_CM_TYPE
146         manager_module = manager_base + ".component_manager_%s" % mgr_type
147         try: manager = __import__(manager_module, fromlist=[manager_base])
148         except: manager = None
149         if manager and hasattr(manager, 'init_server'):
150             manager.init_server()
151     if options.gam:
152         mgr_type = config.SFA_GENI_AGGREGATE_TYPE
153         manager_module = manager_base + ".geni_am_%s" % mgr_type
154         try: manager = __import__(manager_module, fromlist=[manager_base])
155         except: manager = None
156         if manager and hasattr(manager, 'init_server'):
157             manager.init_server()
158             
159
160 def sync_interfaces(server_key_file, server_cert_file):
161     """
162     Attempt to install missing trusted gids and db records for 
163     our federated interfaces
164     """
165     api = SfaAPI(key_file = server_key_file, cert_file = server_cert_file)
166     registries = Registries(api)
167     aggregates = Aggregates(api)
168     registries.sync_interfaces()
169     aggregates.sync_interfaces()
170
171 def main():
172     # xxx get rid of globals - name consistently CamelCase or under_score
173     global AuthHierarchy
174     global TrustedRoots
175     global registry_port
176     global aggregate_port
177     global slicemgr_port
178
179     # Generate command line parser
180     parser = OptionParser(usage="sfa-server [options]")
181     parser.add_option("-r", "--registry", dest="registry", action="store_true",
182          help="run registry server", default=False)
183     parser.add_option("-s", "--slicemgr", dest="sm", action="store_true",
184          help="run slice manager", default=False)
185     parser.add_option("-a", "--aggregate", dest="am", action="store_true",
186          help="run aggregate manager", default=False)
187     parser.add_option("-c", "--component", dest="cm", action="store_true",
188          help="run component server", default=False)
189     parser.add_option("-g", "--geniam", dest="gam", action="store_true",
190          help="run GENI aggregate manager", default=False)
191     parser.add_option("-v", "--verbose", dest="verbose", action="store_true", 
192          help="verbose mode", default=False)
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
197
198     config = Config()
199     hierarchy = Hierarchy()
200     server_key_file = os.path.join(hierarchy.basedir, "server.key")
201     server_cert_file = os.path.join(hierarchy.basedir, "server.cert")
202
203     init_server_key(server_key_file, server_cert_file, config, hierarchy)
204     init_server(options, config)
205     sync_interfaces(server_key_file, server_cert_file)   
206  
207     if (options.daemon):  daemon()
208     # start registry server
209     if (options.registry):
210         from sfa.server.registry import Registry
211         r = Registry("", registry_port, server_key_file, server_cert_file)
212         r.start()
213
214     # start aggregate manager
215     if (options.am):
216         from sfa.server.aggregate import Aggregate
217         a = Aggregate("", aggregate_port, server_key_file, server_cert_file)
218         a.start()
219
220     # start slice manager
221     if (options.sm):
222         from sfa.server.slicemgr import SliceMgr
223         s = SliceMgr("", slicemgr_port, server_key_file, server_cert_file)
224         s.start()
225
226     if (options.cm):
227         from sfa.server.component import Component
228         c = Component("", component_port, server_key_file, server_cert_file)
229         c.start()
230
231     # start GENI aggregate manager
232     if (options.gam):
233         from sfa.server.geni_aggregate import GENIAggregate
234         g = GENIAggregate("", geni_am_port, server_key_file, server_cert_file)
235         g.start()
236
237 if __name__ == "__main__":
238     main()