blob: 6fbcfe2faa47604b825e0daa5fd808289fc321d5 [file] [log] [blame]
tiernof7aa8c42016-09-06 16:43:04 +02001#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4##
5# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
tierno9a61c6b2016-09-08 10:57:02 +02006# This file is part of openvim
tiernof7aa8c42016-09-06 16:43:04 +02007# 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
tierno51068952017-04-26 15:09:48 +020025"""
tiernof7aa8c42016-09-06 16:43:04 +020026This is the main program of openvim, it reads the configuration
27and launches the rest of threads: http clients, openflow controller
28and host controllers
tierno51068952017-04-26 15:09:48 +020029"""
mirabal50a052f2017-03-27 18:08:07 +020030
mirabal9f657102017-04-10 20:05:40 +020031import osm_openvim.httpserver as httpserver
32import osm_openvim.auxiliary_functions as af
tiernof7aa8c42016-09-06 16:43:04 +020033import sys
34import getopt
35import time
tiernof7aa8c42016-09-06 16:43:04 +020036import yaml
37import os
38from jsonschema import validate as js_v, exceptions as js_e
tierno51068952017-04-26 15:09:48 +020039from osm_openvim.vim_schema import config_schema
tiernof7aa8c42016-09-06 16:43:04 +020040import logging
tiernof13617a2016-09-08 11:42:10 +020041import logging.handlers as log_handlers
tiernof13617a2016-09-08 11:42:10 +020042import socket
mirabal9f657102017-04-10 20:05:40 +020043import osm_openvim.ovim as ovim
tiernof7aa8c42016-09-06 16:43:04 +020044
tierno51068952017-04-26 15:09:48 +020045__author__ = "Alfonso Tierno"
46__date__ = "$10-jul-2014 12:07:15$"
47
tiernof7aa8c42016-09-06 16:43:04 +020048global config_dic
49global logger
50logger = logging.getLogger('vim')
51
mirabal9f657102017-04-10 20:05:40 +020052
tiernof13617a2016-09-08 11:42:10 +020053class LoadConfigurationException(Exception):
54 pass
55
mirabal9f657102017-04-10 20:05:40 +020056
tiernof7aa8c42016-09-06 16:43:04 +020057def load_configuration(configuration_file):
tiernoa6933042017-05-24 16:54:33 +020058 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,
tiernof7aa8c42016-09-06 16:43:04 +020062 'network_vlan_range_end': 4096,
63 'log_level': "DEBUG",
64 'log_level_db': "ERROR",
65 'log_level_of': 'ERROR',
Mirabal7256d6b2016-12-15 10:51:19 +000066 'bridge_ifaces': {},
67 'network_type': 'ovs',
Mirabale9317ff2017-01-18 16:10:58 +000068 'ovs_controller_user': 'osm_dhcp',
69 'ovs_controller_file_path': '/var/lib/',
tiernof7aa8c42016-09-06 16:43:04 +020070 }
71 try:
tiernoa6933042017-05-24 16:54:33 +020072 # First load configuration from configuration file
73 # Check config file exists
tiernof7aa8c42016-09-06 16:43:04 +020074 if not os.path.isfile(configuration_file):
tiernoa6933042017-05-24 16:54:33 +020075 raise LoadConfigurationException("Configuration file '{}' does not exists".format(configuration_file))
tiernof7aa8c42016-09-06 16:43:04 +020076
tiernoa6933042017-05-24 16:54:33 +020077 # Read and parse file
tiernof7aa8c42016-09-06 16:43:04 +020078 (return_status, code) = af.read_file(configuration_file)
79 if not return_status:
tiernoa6933042017-05-24 16:54:33 +020080 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
tiernof7aa8c42016-09-06 16:43:04 +020089 if config["network_vlan_range_start"]+10 >= config["network_vlan_range_end"]:
tiernoa6933042017-05-24 16:54:33 +020090 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
tiernof7aa8c42016-09-06 16:43:04 +0200111
tiernof7aa8c42016-09-06 16:43:04 +0200112def usage():
tiernoa6933042017-05-24 16:54:33 +0200113 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")
tiernof7aa8c42016-09-06 16:43:04 +0200125 return
126
127
tiernoa6933042017-05-24 16:54:33 +0200128def 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
142if __name__ == "__main__":
tiernof13617a2016-09-08 11:42:10 +0200143 hostname = socket.gethostname()
tiernoa6933042017-05-24 16:54:33 +0200144 # 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"
tiernof13617a2016-09-08 11:42:10 +0200150 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
tierno51068952017-04-26 15:09:48 +0200151 logging.basicConfig(format=log_format_simple, level=logging.DEBUG)
tierno57f7bda2017-02-09 12:01:55 +0100152 logger = logging.getLogger('openvim')
tiernof7aa8c42016-09-06 16:43:04 +0200153 logger.setLevel(logging.DEBUG)
154 try:
tiernoa6933042017-05-24 16:54:33 +0200155 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:
tiernof7aa8c42016-09-06 16:43:04 +0200158 # print help information and exit:
tiernoa6933042017-05-24 16:54:33 +0200159 logger.error("%s. Type -h for help", err) # will print something like "option -a not recognized"
160 # usage()
161 sys.exit(2)
tiernof7aa8c42016-09-06 16:43:04 +0200162
tiernoa6933042017-05-24 16:54:33 +0200163 port = None
tiernof7aa8c42016-09-06 16:43:04 +0200164 port_admin = None
tierno51068952017-04-26 15:09:48 +0200165 config_file = 'osm_openvim/openvimd.cfg'
tiernof13617a2016-09-08 11:42:10 +0200166 log_file = None
tiernoa36d64d2016-09-14 15:58:40 +0200167 db_name = None
tiernof7aa8c42016-09-06 16:43:04 +0200168
169 for o, a in opts:
170 if o in ("-v", "--version"):
tiernoa6933042017-05-24 16:54:33 +0200171 print ("openvimd version", ovim.ovim.get_version(), ovim.ovim.get_version_date())
172 print ("(c) Copyright Telefonica")
tiernof7aa8c42016-09-06 16:43:04 +0200173 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
tiernoa36d64d2016-09-14 15:58:40 +0200183 elif o in ("-P", "--dbname"):
184 db_name = a
tiernof13617a2016-09-08 11:42:10 +0200185 elif o == "--log-file":
186 log_file = a
tiernof7aa8c42016-09-06 16:43:04 +0200187 else:
188 assert False, "Unhandled option"
189
tierno57f7bda2017-02-09 12:01:55 +0100190 engine = None
tierno56c0c282017-02-10 14:52:55 +0100191 http_thread = None
192 http_thread_admin = None
193
tiernof7aa8c42016-09-06 16:43:04 +0200194 try:
tiernof13617a2016-09-08 11:42:10 +0200195 if log_file:
tiernoa6933042017-05-24 16:54:33 +0200196 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
tiernof13617a2016-09-08 11:42:10 +0200207
tiernof7aa8c42016-09-06 16:43:04 +0200208 logger.setLevel(getattr(logging, config_dic['log_level']))
tiernof13617a2016-09-08 11:42:10 +0200209 logger.critical("Starting openvim server command: '%s'", sys.argv[0])
tiernoa6933042017-05-24 16:54:33 +0200210 # override parameters obtained by command line
tiernoa36d64d2016-09-14 15:58:40 +0200211 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
tiernof7aa8c42016-09-06 16:43:04 +0200217
tiernoa6933042017-05-24 16:54:33 +0200218 # check mode
tiernof7aa8c42016-09-06 16:43:04 +0200219 if 'mode' not in config_dic:
220 config_dic['mode'] = 'normal'
tiernoa6933042017-05-24 16:54:33 +0200221 # allow backward compatibility of test_mode option
tiernof7aa8c42016-09-06 16:43:04 +0200222 if 'test_mode' in config_dic and config_dic['test_mode']==True:
223 config_dic['mode'] = 'test'
Mirabal7256d6b2016-12-15 10:51:19 +0000224 if config_dic['mode'] == 'development' and config_dic['network_type'] == 'bridge' and \
tiernoa6933042017-05-24 16:54:33 +0200225 ('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)
Mirabale9317ff2017-01-18 16:10:58 +0000231
tiernof7aa8c42016-09-06 16:43:04 +0200232 if config_dic['mode'] != 'normal':
tiernoa6933042017-05-24 16:54:33 +0200233 print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
234 print ("!! Warning, openvimd in TEST mode '{}'".format(config_dic['mode']))
235 print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
tierno2db743b2017-03-28 17:23:15 +0200236 config_dic['version'] = ovim.ovim.get_version()
tierno57f7bda2017-02-09 12:01:55 +0100237 config_dic["logger_name"] = "openvim"
tiernof7aa8c42016-09-06 16:43:04 +0200238
tierno57f7bda2017-02-09 12:01:55 +0100239 engine = ovim.ovim(config_dic)
240 engine.start_service()
tiernof7aa8c42016-09-06 16:43:04 +0200241
tiernof7aa8c42016-09-06 16:43:04 +0200242
tiernoa6933042017-05-24 16:54:33 +0200243 # 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)
tiernof7aa8c42016-09-06 16:43:04 +0200246 http_thread.start()
tiernoa6933042017-05-24 16:54:33 +0200247
tierno57f7bda2017-02-09 12:01:55 +0100248 if 'http_admin_port' in config_dic:
249 engine2 = ovim.ovim(config_dic)
tiernoa6933042017-05-24 16:54:33 +0200250 http_thread_admin = httpserver.httpserver(engine2, 'http-admin', config_dic['http_host'],
251 config_dic['http_admin_port'], True)
tiernof7aa8c42016-09-06 16:43:04 +0200252 http_thread_admin.start()
253 else:
254 http_thread_admin = None
tiernoa6933042017-05-24 16:54:33 +0200255 time.sleep(1)
tiernof7aa8c42016-09-06 16:43:04 +0200256 logger.info('Waiting for http clients')
257 print ('openvimd ready')
258 print ('====================')
259 sys.stdout.flush()
tiernoa6933042017-05-24 16:54:33 +0200260
tiernof7aa8c42016-09-06 16:43:04 +0200261 #TODO: Interactive console would be nice here instead of join or sleep
tiernoa6933042017-05-24 16:54:33 +0200262
263 r = ""
tiernof7aa8c42016-09-06 16:43:04 +0200264 while True:
tiernoa6933042017-05-24 16:54:33 +0200265 if r == 'exit':
266 break
267 elif r != '':
tiernof7aa8c42016-09-06 16:43:04 +0200268 print "type 'exit' for terminate"
tiernoa6933042017-05-24 16:54:33 +0200269 try:
270 r = raw_input('> ')
271 except EOFError:
272 time.sleep(86400)
tiernof7aa8c42016-09-06 16:43:04 +0200273
274 except (KeyboardInterrupt, SystemExit):
275 pass
tiernoa6933042017-05-24 16:54:33 +0200276 except (getopt.GetoptError, LoadConfigurationException, ovim.ovimException) as e:
277 logger.critical(str(e)) # will print something like "option -a not recognized"
278 exit(1)
tiernof7aa8c42016-09-06 16:43:04 +0200279
280 logger.info('Exiting openvimd')
tierno57f7bda2017-02-09 12:01:55 +0100281 if engine:
282 engine.stop_service()
tierno56c0c282017-02-10 14:52:55 +0100283 if http_thread:
284 http_thread.join(1)
285 if http_thread_admin:
286 http_thread_admin.join(1)
tiernoa6933042017-05-24 16:54:33 +0200287 logger.debug("bye!")
tiernof7aa8c42016-09-06 16:43:04 +0200288 exit()