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 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("Error at configuration file '{}'. Invalid network_vlan_range less than 10 elements".format)
92 except yaml.YAMLError as exc:
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:
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))
108 # except Exception as e:
109 # raise LoadConfigurationException("Error loading configuration file '{}': {}".format(configuration_file, e))
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 "
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")
128 def set_logging_file(log_file):
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))
138 raise LoadConfigurationException(
139 "Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, e))
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(
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)
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"
165 config_file = 'osm_openvim/openvimd.cfg'
170 if o in ("-v", "--version"):
171 print ("openvimd version", ovim.ovim.get_version(), ovim.ovim.get_version_date())
172 print ("(c) Copyright Telefonica")
174 elif o in ("-h", "--help"):
177 elif o in ("-c", "--config"):
179 elif o in ("-p", "--port"):
181 elif o in ("-P", "--adminport"):
183 elif o in ("-P", "--dbname"):
185 elif o == "--log-file":
188 assert False, "Unhandled option"
192 http_thread_admin = None
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
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
212 config_dic['http_port'] = port
214 config_dic['http_admin_port'] = port_admin
216 config_dic['db_name'] = db_name
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)
229 logger.error(error_msg)
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"
239 engine = ovim.ovim(config_dic)
240 engine.start_service()
243 # Create thread to listen to web requests
244 http_thread = httpserver.httpserver(engine, 'http', config_dic['http_host'], config_dic['http_port'],
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()
254 http_thread_admin = None
256 logger.info('Waiting for http clients')
257 print ('openvimd ready')
258 print ('====================')
261 #TODO: Interactive console would be nice here instead of join or sleep
268 print "type 'exit' for terminate"
274 except (KeyboardInterrupt, SystemExit):
276 except (getopt.GetoptError, LoadConfigurationException, ovim.ovimException) as e:
277 logger.critical(str(e)) # will print something like "option -a not recognized"
280 logger.info('Exiting openvimd')
282 engine.stop_service()
285 if http_thread_admin:
286 http_thread_admin.join(1)