Allow specifying ssh key file for compute nodes and network controller
[osm/openvim.git] / openvimd
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 ##
5 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
6 # This file is part of openvim
7 # All Rights Reserved.
8 #
9 # Licensed under the Apache License, Version 2.0 (the "License"); you may
10 # not use this file except in compliance with the License. You may obtain
11 # a copy of the License at
12 #
13 #         http://www.apache.org/licenses/LICENSE-2.0
14 #
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18 # License for the specific language governing permissions and limitations
19 # under the License.
20 #
21 # For those usages not covered by the Apache License, Version 2.0 please
22 # contact with: nfvlabs@tid.es
23 ##
24
25 """
26 This is the main program of openvim, it reads the configuration 
27 and launches the rest of threads: http clients, openflow controller
28 and host controllers  
29 """
30
31 import osm_openvim.httpserver as httpserver
32 import osm_openvim.auxiliary_functions as af
33 import sys
34 import getopt
35 import time
36 import yaml
37 import os
38 from jsonschema import validate as js_v, exceptions as js_e
39 from osm_openvim.vim_schema import config_schema
40 import logging
41 import logging.handlers as log_handlers
42 import socket
43 import osm_openvim.ovim as ovim
44
45 __author__ = "Alfonso Tierno"
46 __date__ = "$10-jul-2014 12:07:15$"
47
48 global config_dic
49 global logger
50 logger = logging.getLogger('vim')
51
52
53 class LoadConfigurationException(Exception):
54     pass
55
56
57 def load_configuration(configuration_file):
58     default_tokens ={'http_port': 9080, 'http_host': 'localhost',
59                      'of_controller_nets_with_same_vlan': True,
60                      'host_ssh_keyfile': None,
61                      'network_vlan_range_start': 1000,
62                      'network_vlan_range_end': 4096,
63                      'log_level': "DEBUG",
64                      'log_level_db': "ERROR",
65                      'log_level_of': 'ERROR',
66                      'bridge_ifaces': {},
67                      'network_type': 'ovs',
68                      'ovs_controller_user': 'osm_dhcp',
69                      'ovs_controller_file_path': '/var/lib/',
70             }
71     try:
72         # First load configuration from configuration file
73         # Check config file exists
74         if not os.path.isfile(configuration_file):
75             raise LoadConfigurationException("Configuration file '{}' does not exists".format(configuration_file))
76             
77         # Read and parse file
78         (return_status, code) = af.read_file(configuration_file)
79         if not return_status:
80             raise LoadConfigurationException("Error loading configuration file '{}': {}".format(
81                 configuration_file, code))
82         config = yaml.load(code)
83         js_v(config, config_schema)
84         # Check default values tokens
85         for k, v in default_tokens.items():
86             if k not in config:
87                 config[k] = v
88         # Check vlan ranges
89         if config["network_vlan_range_start"]+10 >= config["network_vlan_range_end"]:
90             raise LoadConfigurationException("Error at configuration file '{}'. Invalid network_vlan_range less than 10 elements".format)
91         return config
92     except yaml.YAMLError as exc:
93         error_pos = ""
94         if hasattr(exc, 'problem_mark'):
95             mark = exc.problem_mark
96             error_pos = " at position: ({}:{})".format(mark.line + 1, mark.column + 1)
97         raise LoadConfigurationException("Error loading configuration file '{}'{}: {}\n"
98                                          "Use a valid yaml format. Indentation matters, "
99                                          "and tabs characters are not valid".format(
100                                              configuration_file, error_pos, exc))
101     except js_e.ValidationError as exc:
102         error_pos = ""
103         if len(exc.path) > 0:
104             error_pos = " at '{}'".format(":".join(map(str, exc.path)))
105         raise LoadConfigurationException("Error loading configuration file '{}'{}: {}".format(
106             configuration_file, error_pos, exc))
107
108     # except Exception as e:
109     #     raise LoadConfigurationException("Error loading configuration file '{}': {}".format(configuration_file, e))
110
111
112 def usage():
113     print ("Usage: ", sys.argv[0], "[options]")
114     print ("      -v|--version: prints current version")
115     print ("      -c|--config FILE: loads the configuration file (default: osm_openvim/openvimd.cfg)")
116     print ("      -h|--help: shows this help")
117     print ("      -p|--port PORT: changes port number and overrides the port number in the configuration file "
118            "(default: 908)")
119     print ("      -P|--adminport PORT: changes admin port number and overrides the port number in the configuration "
120            "file (default: not listen)")
121     print ("      --dbname NAME: changes db_name and overrides the db_name in the configuration file")
122     # print( "      --log-socket-host HOST: send logs to this host")
123     # print( "      --log-socket-port PORT: send logs using this port (default: 9022)")
124     print ("      --log-file FILE: send logs to this file")
125     return
126
127
128 def set_logging_file(log_file):
129     try:
130         file_handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=100e6, backupCount=9, delay=0)
131         file_handler.setFormatter(log_formatter_simple)
132         logger.addHandler(file_handler)
133         # logger.debug("moving logs to '%s'", global_config["log_file"])
134         # remove initial stream handler
135         logging.root.removeHandler(logging.root.handlers[0])
136         print ("logging on '{}'".format(log_file))
137     except IOError as e:
138         raise LoadConfigurationException(
139             "Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, e))
140
141
142 if __name__ == "__main__":
143     hostname = socket.gethostname()
144     # streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
145     log_formatter_complete = logging.Formatter('%(asctime)s.%(msecs)03d00Z[{host}@openmanod] %(filename)s:%(lineno)s '
146                                                'severity:%(levelname)s logger:%(name)s log:%(message)s'.format(
147                                                     host=hostname),
148                                 datefmt='%Y-%m-%dT%H:%M:%S')
149     log_format_simple = "%(asctime)s %(levelname)s  %(name)s %(filename)s:%(lineno)s %(message)s"
150     log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
151     logging.basicConfig(format=log_format_simple, level=logging.DEBUG)
152     logger = logging.getLogger('openvim')
153     logger.setLevel(logging.DEBUG)
154     try:
155         opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:",
156                                    ["config=", "help", "version", "port=", "adminport=", "log-file=", "dbname="])
157     except getopt.GetoptError as err:
158         # print help information and exit:
159         logger.error("%s. Type -h for help", err)  # will print something like "option -a not recognized"
160         # usage()
161         sys.exit(2)
162
163     port = None
164     port_admin = None
165     config_file = 'osm_openvim/openvimd.cfg'
166     log_file = None
167     db_name = None
168
169     for o, a in opts:
170         if o in ("-v", "--version"):
171             print ("openvimd version", ovim.ovim.get_version(), ovim.ovim.get_version_date())
172             print ("(c) Copyright Telefonica")
173             sys.exit(0)
174         elif o in ("-h", "--help"):
175             usage()
176             sys.exit(0)
177         elif o in ("-c", "--config"):
178             config_file = a
179         elif o in ("-p", "--port"):
180             port = a
181         elif o in ("-P", "--adminport"):
182             port_admin = a
183         elif o in ("-P", "--dbname"):
184             db_name = a
185         elif o == "--log-file":
186             log_file = a
187         else:
188             assert False, "Unhandled option"
189
190     engine = None
191     http_thread = None
192     http_thread_admin = None
193
194     try:
195         if log_file:
196             set_logging_file(log_file)
197         # Load configuration file
198         config_dic = load_configuration(config_file)
199         if config_dic.get("dhcp_server"):
200             if config_dic["dhcp_server"].get("key"):
201                 config_dic["dhcp_server"]["keyfile"] = config_dic["dhcp_server"].pop("key")
202         if config_dic.get("image_path"):
203             config_dic["host_image_path"] = config_dic.pop("image_path")
204         elif not config_dic.get("host_image_path"):
205             config_dic["host_image_path"] = '/opt/VNF/images'   # default value
206         # print config_dic
207
208         logger.setLevel(getattr(logging, config_dic['log_level']))
209         logger.critical("Starting openvim server command: '%s'", sys.argv[0])
210         # override parameters obtained by command line
211         if port: 
212             config_dic['http_port'] = port
213         if port_admin:
214             config_dic['http_admin_port'] = port_admin
215         if db_name: 
216             config_dic['db_name'] = db_name
217         
218         # check mode
219         if 'mode' not in config_dic:
220             config_dic['mode'] = 'normal'
221             # allow backward compatibility of test_mode option
222             if 'test_mode' in config_dic and config_dic['test_mode']==True:
223                 config_dic['mode'] = 'test' 
224         if config_dic['mode'] == 'development' and config_dic['network_type'] == 'bridge' and \
225                 ('development_bridge' not in config_dic or
226                              config_dic['development_bridge'] not in config_dic.get("bridge_ifaces",None)):
227             error_msg = "'{}' is not a valid 'development_bridge', not one of the 'bridge_ifaces'".format(config_file)
228             print (error_msg)
229             logger.error(error_msg)
230             exit(1)
231
232         if config_dic['mode'] != 'normal':
233             print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
234             print ("!! Warning, openvimd in TEST mode '{}'".format(config_dic['mode']))
235             print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
236         config_dic['version'] = ovim.ovim.get_version()
237         config_dic["logger_name"] = "openvim"
238
239         engine = ovim.ovim(config_dic)
240         engine.start_service()
241
242         
243     # Create thread to listen to web requests
244         http_thread = httpserver.httpserver(engine, 'http', config_dic['http_host'], config_dic['http_port'],
245                                             False, config_dic)
246         http_thread.start()
247
248         if 'http_admin_port' in config_dic:
249             engine2 = ovim.ovim(config_dic)
250             http_thread_admin = httpserver.httpserver(engine2, 'http-admin', config_dic['http_host'],
251                                                       config_dic['http_admin_port'], True)
252             http_thread_admin.start()
253         else:
254             http_thread_admin = None
255         time.sleep(1)
256         logger.info('Waiting for http clients')
257         print ('openvimd ready')
258         print ('====================')
259         sys.stdout.flush()
260
261         #TODO: Interactive console would be nice here instead of join or sleep
262
263         r = ""
264         while True:
265             if r == 'exit':
266                 break
267             elif r != '':
268                 print "type 'exit' for terminate"
269             try:
270                 r = raw_input('> ')
271             except EOFError:
272                 time.sleep(86400)
273
274     except (KeyboardInterrupt, SystemExit):
275         pass
276     except (getopt.GetoptError, LoadConfigurationException, ovim.ovimException) as e:
277         logger.critical(str(e))   # will print something like "option -a not recognized"
278         exit(1)
279
280     logger.info('Exiting openvimd')
281     if engine:
282         engine.stop_service()
283     if http_thread:
284         http_thread.join(1)
285     if http_thread_admin:
286         http_thread_admin.join(1)
287     logger.debug("bye!")
288     exit()