blob: 1b3c7db8321a996628e24310b1c77233ea10f058 [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):
58 default_tokens ={'http_port':9080, 'http_host':'localhost',
59 'of_controller_nets_with_same_vlan':True,
60 'image_path':'/opt/VNF/images',
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',
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:
72 #First load configuration from configuration file
73 #Check config file exists
74 if not os.path.isfile(configuration_file):
75 return (False, "Configuration file '"+configuration_file+"' does not exists")
76
77 #Read and parse file
78 (return_status, code) = af.read_file(configuration_file)
79 if not return_status:
80 return (return_status, "Error loading configuration file '"+configuration_file+"': "+code)
81 try:
82 config = yaml.load(code)
83 except yaml.YAMLError, exc:
84 error_pos = ""
85 if hasattr(exc, 'problem_mark'):
86 mark = exc.problem_mark
87 error_pos = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
88 return (False, "Error loading configuration file '"+configuration_file+"'"+error_pos+": content format error: Failed to parse yaml format")
89
90
91 try:
92 js_v(config, config_schema)
93 except js_e.ValidationError, exc:
94 error_pos = ""
95 if len(exc.path)>0: error_pos=" at '" + ":".join(map(str, exc.path))+"'"
96 return False, "Error loading configuration file '"+configuration_file+"'"+error_pos+": "+exc.message
97
98
99 #Check default values tokens
100 for k,v in default_tokens.items():
101 if k not in config: config[k]=v
102 #Check vlan ranges
103 if config["network_vlan_range_start"]+10 >= config["network_vlan_range_end"]:
104 return False, "Error invalid network_vlan_range less than 10 elements"
105
106 except Exception,e:
107 return (False, "Error loading configuration file '"+configuration_file+"': "+str(e))
108 return (True, config)
109
tiernof7aa8c42016-09-06 16:43:04 +0200110def usage():
111 print "Usage: ", sys.argv[0], "[options]"
112 print " -v|--version: prints current version"
tierno51068952017-04-26 15:09:48 +0200113 print " -c|--config FILE: loads the configuration file (default: osm_openvim/openvimd.cfg)"
tiernof7aa8c42016-09-06 16:43:04 +0200114 print " -h|--help: shows this help"
tiernoa36d64d2016-09-14 15:58:40 +0200115 print " -p|--port PORT: changes port number and overrides the port number in the configuration file (default: 908)"
116 print " -P|--adminport PORT: changes admin port number and overrides the port number in the configuration file (default: not listen)"
117 print " --dbname NAME: changes db_name and overrides the db_name in the configuration file"
tiernof13617a2016-09-08 11:42:10 +0200118 #print( " --log-socket-host HOST: send logs to this host")
119 #print( " --log-socket-port PORT: send logs using this port (default: 9022)")
120 print( " --log-file FILE: send logs to this file")
tiernof7aa8c42016-09-06 16:43:04 +0200121 return
122
123
124if __name__=="__main__":
tiernof13617a2016-09-08 11:42:10 +0200125 hostname = socket.gethostname()
tiernof7aa8c42016-09-06 16:43:04 +0200126 #streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
tiernof13617a2016-09-08 11:42:10 +0200127 log_formatter_complete = logging.Formatter(
128 '%(asctime)s.%(msecs)03d00Z[{host}@openmanod] %(filename)s:%(lineno)s severity:%(levelname)s logger:%(name)s log:%(message)s'.format(host=hostname),
129 datefmt='%Y-%m-%dT%H:%M:%S',
130 )
131 log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
132 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
tierno51068952017-04-26 15:09:48 +0200133 logging.basicConfig(format=log_format_simple, level=logging.DEBUG)
tierno57f7bda2017-02-09 12:01:55 +0100134 logger = logging.getLogger('openvim')
tiernof7aa8c42016-09-06 16:43:04 +0200135 logger.setLevel(logging.DEBUG)
136 try:
tiernoa36d64d2016-09-14 15:58:40 +0200137 opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:", ["config=", "help", "version", "port=", "adminport=", "log-file=", "dbname="])
tiernof7aa8c42016-09-06 16:43:04 +0200138 except getopt.GetoptError, err:
139 # print help information and exit:
140 logger.error("%s. Type -h for help", err) # will print something like "option -a not recognized"
141 #usage()
142 sys.exit(-2)
143
144 port=None
145 port_admin = None
tierno51068952017-04-26 15:09:48 +0200146 config_file = 'osm_openvim/openvimd.cfg'
tiernof13617a2016-09-08 11:42:10 +0200147 log_file = None
tiernoa36d64d2016-09-14 15:58:40 +0200148 db_name = None
tiernof7aa8c42016-09-06 16:43:04 +0200149
150 for o, a in opts:
151 if o in ("-v", "--version"):
mirabal50a052f2017-03-27 18:08:07 +0200152 print "openvimd version", ovim.ovim.get_version(), ovim.ovim.get_version_date()
tiernof7aa8c42016-09-06 16:43:04 +0200153 print "(c) Copyright Telefonica"
154 sys.exit(0)
155 elif o in ("-h", "--help"):
156 usage()
157 sys.exit(0)
158 elif o in ("-c", "--config"):
159 config_file = a
160 elif o in ("-p", "--port"):
161 port = a
162 elif o in ("-P", "--adminport"):
163 port_admin = a
tiernoa36d64d2016-09-14 15:58:40 +0200164 elif o in ("-P", "--dbname"):
165 db_name = a
tiernof13617a2016-09-08 11:42:10 +0200166 elif o == "--log-file":
167 log_file = a
tiernof7aa8c42016-09-06 16:43:04 +0200168 else:
169 assert False, "Unhandled option"
170
171
tierno57f7bda2017-02-09 12:01:55 +0100172 engine = None
tierno56c0c282017-02-10 14:52:55 +0100173 http_thread = None
174 http_thread_admin = None
175
tiernof7aa8c42016-09-06 16:43:04 +0200176 try:
177 #Load configuration file
178 r, config_dic = load_configuration(config_file)
179 #print config_dic
180 if not r:
181 logger.error(config_dic)
182 config_dic={}
183 exit(-1)
tiernof13617a2016-09-08 11:42:10 +0200184 if log_file:
185 try:
186 file_handler= logging.handlers.RotatingFileHandler(log_file, maxBytes=100e6, backupCount=9, delay=0)
187 file_handler.setFormatter(log_formatter_simple)
188 logger.addHandler(file_handler)
189 #logger.debug("moving logs to '%s'", global_config["log_file"])
190 #remove initial stream handler
191 logging.root.removeHandler(logging.root.handlers[0])
192 print ("logging on '{}'".format(log_file))
193 except IOError as e:
194 raise LoadConfigurationException("Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, str(e)) )
195
tiernof7aa8c42016-09-06 16:43:04 +0200196 logger.setLevel(getattr(logging, config_dic['log_level']))
tiernof13617a2016-09-08 11:42:10 +0200197 logger.critical("Starting openvim server command: '%s'", sys.argv[0])
tiernof7aa8c42016-09-06 16:43:04 +0200198 #override parameters obtained by command line
tiernoa36d64d2016-09-14 15:58:40 +0200199 if port:
200 config_dic['http_port'] = port
201 if port_admin:
202 config_dic['http_admin_port'] = port_admin
203 if db_name:
204 config_dic['db_name'] = db_name
tiernof7aa8c42016-09-06 16:43:04 +0200205
206 #check mode
207 if 'mode' not in config_dic:
208 config_dic['mode'] = 'normal'
209 #allow backward compatibility of test_mode option
210 if 'test_mode' in config_dic and config_dic['test_mode']==True:
211 config_dic['mode'] = 'test'
Mirabal7256d6b2016-12-15 10:51:19 +0000212 if config_dic['mode'] == 'development' and config_dic['network_type'] == 'bridge' and \
213 ( 'development_bridge' not in config_dic or config_dic['development_bridge'] not in config_dic.get("bridge_ifaces",None) ):
tiernof7aa8c42016-09-06 16:43:04 +0200214 logger.error("'%s' is not a valid 'development_bridge', not one of the 'bridge_ifaces'", config_file)
215 exit(-1)
Mirabale9317ff2017-01-18 16:10:58 +0000216
tiernof7aa8c42016-09-06 16:43:04 +0200217 if config_dic['mode'] != 'normal':
218 print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
219 print "!! Warning, openvimd in TEST mode '%s'" % config_dic['mode']
220 print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
tierno2db743b2017-03-28 17:23:15 +0200221 config_dic['version'] = ovim.ovim.get_version()
tierno57f7bda2017-02-09 12:01:55 +0100222 config_dic["logger_name"] = "openvim"
tiernof7aa8c42016-09-06 16:43:04 +0200223
tierno57f7bda2017-02-09 12:01:55 +0100224 engine = ovim.ovim(config_dic)
225 engine.start_service()
tiernof7aa8c42016-09-06 16:43:04 +0200226
tiernof7aa8c42016-09-06 16:43:04 +0200227
228 #Create thread to listen to web requests
tierno57f7bda2017-02-09 12:01:55 +0100229 http_thread = httpserver.httpserver(engine, 'http', config_dic['http_host'], config_dic['http_port'], False, config_dic)
tiernof7aa8c42016-09-06 16:43:04 +0200230 http_thread.start()
231
tierno57f7bda2017-02-09 12:01:55 +0100232 if 'http_admin_port' in config_dic:
233 engine2 = ovim.ovim(config_dic)
234 http_thread_admin = httpserver.httpserver(engine2, 'http-admin', config_dic['http_host'], config_dic['http_admin_port'], True)
tiernof7aa8c42016-09-06 16:43:04 +0200235 http_thread_admin.start()
236 else:
237 http_thread_admin = None
238 time.sleep(1)
239 logger.info('Waiting for http clients')
240 print ('openvimd ready')
241 print ('====================')
242 sys.stdout.flush()
243
244 #TODO: Interactive console would be nice here instead of join or sleep
245
246 r="help" #force print help at the beginning
247 while True:
248 if r=='exit':
249 break
250 elif r!='':
251 print "type 'exit' for terminate"
252 r = raw_input('> ')
253
254 except (KeyboardInterrupt, SystemExit):
255 pass
tiernof13617a2016-09-08 11:42:10 +0200256 except SystemExit:
257 pass
258 except getopt.GetoptError as e:
259 logger.critical(str(e)) # will print something like "option -a not recognized"
260 #usage()
261 exit(-1)
262 except LoadConfigurationException as e:
263 logger.critical(str(e))
264 exit(-1)
tierno57f7bda2017-02-09 12:01:55 +0100265 except ovim.ovimException as e:
266 logger.critical(str(e))
267 exit(-1)
tiernof7aa8c42016-09-06 16:43:04 +0200268
269 logger.info('Exiting openvimd')
tierno57f7bda2017-02-09 12:01:55 +0100270 if engine:
271 engine.stop_service()
tierno56c0c282017-02-10 14:52:55 +0100272 if http_thread:
273 http_thread.join(1)
274 if http_thread_admin:
275 http_thread_admin.join(1)
tierno57f7bda2017-02-09 12:01:55 +0100276
tiernof7aa8c42016-09-06 16:43:04 +0200277 logger.debug( "bye!")
278 exit()
279