2 # -*- coding: utf-8 -*-
5 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
6 # This file is part of openvim
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
13 # http://www.apache.org/licenses/LICENSE-2.0
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
21 # For those usages not covered by the Apache License, Version 2.0 please
22 # contact with: nfvlabs@tid.es
26 This is the main program of openvim, it reads the configuration
27 and launches the rest of threads: http clients, openflow controllers
28 and host controllers, network controller
31 import osm_openvim.httpserver as httpserver
32 import osm_openvim.auxiliary_functions as af
38 from jsonschema import validate as js_v, exceptions as js_e
39 from osm_openvim.vim_schema import config_schema
41 import logging.handlers as log_handlers
43 import osm_openvim.ovim as ovim
45 __author__ = "Alfonso Tierno"
46 __date__ = "$10-jul-2014 12:07:15$"
50 logger = logging.getLogger('vim')
53 class LoadConfigurationException(Exception):
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,
64 'log_level_db': "ERROR",
65 'log_level_of': 'ERROR',
67 'network_type': 'ovs',
68 'ovs_controller_user': 'osm_dhcp',
69 'ovs_controller_file_path': '/var/lib/',
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))
78 (return_status, code) = af.read_file(configuration_file)
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():
89 if config["network_vlan_range_start"] + 10 >= config["network_vlan_range_end"]:
90 raise LoadConfigurationException(
91 "Error at configuration file '{}'. Invalid network_vlan_range less than 10 elements".format(
94 except yaml.YAMLError as exc:
96 if hasattr(exc, 'problem_mark'):
97 mark = exc.problem_mark
98 error_pos = " at position: ({}:{})".format(mark.line + 1, mark.column + 1)
99 raise LoadConfigurationException("Bad YAML format at configuration file '{}'{}: {}\n"
100 "Use a valid yaml format. Indentation matters, "
101 "and tabs characters are not valid".format(
102 configuration_file, error_pos, exc))
103 except js_e.ValidationError as exc:
105 if len(exc.path) > 0:
106 error_pos = " at '{}'".format(":".join(map(str, exc.path)))
107 raise LoadConfigurationException("Invalid field at configuration file '{}'{}: {}".format(
108 configuration_file, error_pos, exc))
110 # except Exception as e:
111 # raise LoadConfigurationException("Error loading configuration file '{}': {}".format(configuration_file, e))
115 print ("Usage: {} [options]".format(sys.argv[0]))
116 print (" -v|--version: prints current version")
117 print (" -c|--config FILE: loads the configuration file (default: osm_openvim/openvimd.cfg)")
118 print (" -h|--help: shows this help")
119 print (" -p|--port PORT: changes port number and overrides the port number in the configuration file "
121 print (" -P|--adminport PORT: changes admin port number and overrides the port number in the configuration "
122 "file (default: not listen)")
123 print (" --dbname NAME: changes db_name and overrides the db_name in the configuration file")
124 # print( " --log-socket-host HOST: send logs to this host")
125 # print( " --log-socket-port PORT: send logs using this port (default: 9022)")
126 print (" --log-file FILE: send logs to this file")
130 def set_logging_file(log_file):
132 file_handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=100e6, backupCount=9, delay=0)
133 file_handler.setFormatter(log_formatter_simple)
134 logger.addHandler(file_handler)
135 # logger.debug("moving logs to '%s'", global_config["log_file"])
136 # remove initial stream handler
137 logging.root.removeHandler(logging.root.handlers[0])
138 print ("logging on '{}'".format(log_file))
140 raise LoadConfigurationException(
141 "Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, e))
144 if __name__ == "__main__":
145 hostname = socket.gethostname()
146 # streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
147 log_formatter_complete = logging.Formatter('%(asctime)s.%(msecs)03d00Z[{host}@openmanod] %(filename)s:%(lineno)s '
148 'severity:%(levelname)s logger:%(name)s log:%(message)s'.format(
150 datefmt='%Y-%m-%dT%H:%M:%S')
151 log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
152 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
153 logging.basicConfig(format=log_format_simple, level=logging.DEBUG)
154 logger = logging.getLogger('openvim')
155 logger.setLevel(logging.DEBUG)
157 opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:",
158 ["config=", "help", "version", "port=", "adminport=", "log-file=", "dbname="])
159 except getopt.GetoptError as err:
160 # print help information and exit:
161 logger.error("%s. Type -h for help", err) # will print something like "option -a not recognized"
167 config_file = 'osm_openvim/openvimd.cfg'
172 if o in ("-v", "--version"):
173 print ("openvimd version {} {}".format(ovim.ovim.get_version(), ovim.ovim.get_version_date()))
174 print ("(c) Copyright Telefonica")
176 elif o in ("-h", "--help"):
179 elif o in ("-c", "--config"):
181 elif o in ("-p", "--port"):
183 elif o in ("-P", "--adminport"):
185 elif o in ("-P", "--dbname"):
187 elif o == "--log-file":
190 assert False, "Unhandled option"
194 http_thread_admin = None
198 set_logging_file(log_file)
199 # Load configuration file
200 config_dic = load_configuration(config_file)
201 if config_dic.get("dhcp_server"):
202 if config_dic["dhcp_server"].get("key"):
203 config_dic["dhcp_server"]["keyfile"] = config_dic["dhcp_server"].pop("key")
204 if config_dic.get("image_path"):
205 config_dic["host_image_path"] = config_dic.pop("image_path")
206 elif not config_dic.get("host_image_path"):
207 config_dic["host_image_path"] = '/opt/VNF/images' # default value
210 logger.setLevel(getattr(logging, config_dic['log_level']))
211 logger.critical("Starting openvim server command: '%s'", sys.argv[0])
212 # override parameters obtained by command line
214 config_dic['http_port'] = port
216 config_dic['http_admin_port'] = port_admin
218 config_dic['db_name'] = db_name
221 if 'mode' not in config_dic:
222 config_dic['mode'] = 'normal'
223 # allow backward compatibility of test_mode option
224 if 'test_mode' in config_dic and config_dic['test_mode'] == True:
225 config_dic['mode'] = 'test'
226 if config_dic['mode'] == 'development' and config_dic['network_type'] == 'bridge' and \
227 ('development_bridge' not in config_dic or
228 config_dic['development_bridge'] not in config_dic.get("bridge_ifaces", None)):
229 error_msg = "'{}' is not a valid 'development_bridge', not one of the 'bridge_ifaces'".format(config_file)
231 logger.error(error_msg)
234 if config_dic['network_type'] == 'ovs' \
235 and config_dic['ovs_controller_ip'] == 'localhost' \
236 and not (config_dic['mode'] == 'test' or config_dic['mode'] == "OF only"):
238 error_msg = "Error: invalid value '{}' for ovs_controller_ip at {}. " \
239 "Use a valid IP address".format(config_dic['ovs_controller_ip'], config_file)
241 print ("!! {} ".format(error_msg))
242 logger.error(error_msg)
245 if config_dic['mode'] != 'normal':
246 print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
247 print ("!! Warning, openvimd in TEST mode '{}'".format(config_dic['mode']))
248 print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
250 config_dic['version'] = ovim.ovim.get_version()
251 config_dic["logger_name"] = "openvim"
253 engine = ovim.ovim(config_dic)
254 engine.start_service()
256 # Create thread to listen to web requests
257 http_thread = httpserver.httpserver(engine, 'http', config_dic['http_host'], config_dic['http_port'],
261 if 'http_admin_port' in config_dic:
262 engine2 = ovim.ovim(config_dic)
263 http_thread_admin = httpserver.httpserver(engine2, 'http-admin', config_dic['http_host'],
264 config_dic['http_admin_port'], True)
265 http_thread_admin.start()
267 http_thread_admin = None
269 logger.info('Waiting for http clients')
270 print ('openvimd ready')
271 print ('====================')
274 # TODO: Interactive console would be nice here instead of join or sleep
281 print "type 'exit' for terminate"
287 except (KeyboardInterrupt, SystemExit):
289 except (getopt.GetoptError, LoadConfigurationException, ovim.ovimException) as e:
290 logger.critical(str(e)) # will print something like "option -a not recognized"
293 logger.info('Exiting openvimd')
295 engine.stop_service()
298 if http_thread_admin:
299 http_thread_admin.join(1)