blob: 923ad16bf66ceb72eaccd19ab79cf75bf7fb885e [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
25'''
26This is the main program of openvim, it reads the configuration
27and launches the rest of threads: http clients, openflow controller
28and host controllers
29'''
30
mirabal9e194592017-02-17 11:03:25 +010031__author__ = "Alfonso Tierno"
32__date__ = "$10-jul-2014 12:07:15$"
33__version__ = "0.5.5-r522"
34version_date = "Feb 2017"
35database_version = "0.12" #expected database schema version
tiernof7aa8c42016-09-06 16:43:04 +020036
37import httpserver
tiernof0537372016-09-08 08:17:37 +020038import auxiliary_functions as af
tiernof7aa8c42016-09-06 16:43:04 +020039import sys
40import getopt
41import time
tiernof7aa8c42016-09-06 16:43:04 +020042import yaml
43import os
44from jsonschema import validate as js_v, exceptions as js_e
tiernof7aa8c42016-09-06 16:43:04 +020045from vim_schema import config_schema
46import logging
tiernof13617a2016-09-08 11:42:10 +020047import logging.handlers as log_handlers
tiernof13617a2016-09-08 11:42:10 +020048import socket
tierno57f7bda2017-02-09 12:01:55 +010049import ovim
tiernof7aa8c42016-09-06 16:43:04 +020050
51global config_dic
52global logger
53logger = logging.getLogger('vim')
54
tiernof13617a2016-09-08 11:42:10 +020055class LoadConfigurationException(Exception):
56 pass
57
tiernof7aa8c42016-09-06 16:43:04 +020058def load_configuration(configuration_file):
59 default_tokens ={'http_port':9080, 'http_host':'localhost',
60 'of_controller_nets_with_same_vlan':True,
61 'image_path':'/opt/VNF/images',
62 'network_vlan_range_start':1000,
63 'network_vlan_range_end': 4096,
64 'log_level': "DEBUG",
65 'log_level_db': "ERROR",
66 'log_level_of': 'ERROR',
Mirabal7256d6b2016-12-15 10:51:19 +000067 'bridge_ifaces': {},
68 'network_type': 'ovs',
Mirabale9317ff2017-01-18 16:10:58 +000069 'ovs_controller_user': 'osm_dhcp',
70 'ovs_controller_file_path': '/var/lib/',
tiernof7aa8c42016-09-06 16:43:04 +020071 }
72 try:
73 #First load configuration from configuration file
74 #Check config file exists
75 if not os.path.isfile(configuration_file):
76 return (False, "Configuration file '"+configuration_file+"' does not exists")
77
78 #Read and parse file
79 (return_status, code) = af.read_file(configuration_file)
80 if not return_status:
81 return (return_status, "Error loading configuration file '"+configuration_file+"': "+code)
82 try:
83 config = yaml.load(code)
84 except yaml.YAMLError, exc:
85 error_pos = ""
86 if hasattr(exc, 'problem_mark'):
87 mark = exc.problem_mark
88 error_pos = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
89 return (False, "Error loading configuration file '"+configuration_file+"'"+error_pos+": content format error: Failed to parse yaml format")
90
91
92 try:
93 js_v(config, config_schema)
94 except js_e.ValidationError, exc:
95 error_pos = ""
96 if len(exc.path)>0: error_pos=" at '" + ":".join(map(str, exc.path))+"'"
97 return False, "Error loading configuration file '"+configuration_file+"'"+error_pos+": "+exc.message
98
99
100 #Check default values tokens
101 for k,v in default_tokens.items():
102 if k not in config: config[k]=v
103 #Check vlan ranges
104 if config["network_vlan_range_start"]+10 >= config["network_vlan_range_end"]:
105 return False, "Error invalid network_vlan_range less than 10 elements"
106
107 except Exception,e:
108 return (False, "Error loading configuration file '"+configuration_file+"': "+str(e))
109 return (True, config)
110
tiernof7aa8c42016-09-06 16:43:04 +0200111def usage():
112 print "Usage: ", sys.argv[0], "[options]"
113 print " -v|--version: prints current version"
tiernoa36d64d2016-09-14 15:58:40 +0200114 print " -c|--config FILE: loads the configuration file (default: openvimd.cfg)"
tiernof7aa8c42016-09-06 16:43:04 +0200115 print " -h|--help: shows this help"
tiernoa36d64d2016-09-14 15:58:40 +0200116 print " -p|--port PORT: changes port number and overrides the port number in the configuration file (default: 908)"
117 print " -P|--adminport PORT: changes admin port number and overrides the port number in the configuration file (default: not listen)"
118 print " --dbname NAME: changes db_name and overrides the db_name in the configuration file"
tiernof13617a2016-09-08 11:42:10 +0200119 #print( " --log-socket-host HOST: send logs to this host")
120 #print( " --log-socket-port PORT: send logs using this port (default: 9022)")
121 print( " --log-file FILE: send logs to this file")
tiernof7aa8c42016-09-06 16:43:04 +0200122 return
123
124
125if __name__=="__main__":
tiernof13617a2016-09-08 11:42:10 +0200126 hostname = socket.gethostname()
tiernof7aa8c42016-09-06 16:43:04 +0200127 #streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
tiernof13617a2016-09-08 11:42:10 +0200128 log_formatter_complete = logging.Formatter(
129 '%(asctime)s.%(msecs)03d00Z[{host}@openmanod] %(filename)s:%(lineno)s severity:%(levelname)s logger:%(name)s log:%(message)s'.format(host=hostname),
130 datefmt='%Y-%m-%dT%H:%M:%S',
131 )
132 log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
133 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
134 logging.basicConfig(format=log_format_simple, level= logging.DEBUG)
tierno57f7bda2017-02-09 12:01:55 +0100135 logger = logging.getLogger('openvim')
tiernof7aa8c42016-09-06 16:43:04 +0200136 logger.setLevel(logging.DEBUG)
137 try:
tiernoa36d64d2016-09-14 15:58:40 +0200138 opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:", ["config=", "help", "version", "port=", "adminport=", "log-file=", "dbname="])
tiernof7aa8c42016-09-06 16:43:04 +0200139 except getopt.GetoptError, err:
140 # print help information and exit:
141 logger.error("%s. Type -h for help", err) # will print something like "option -a not recognized"
142 #usage()
143 sys.exit(-2)
144
145 port=None
146 port_admin = None
147 config_file = 'openvimd.cfg'
tiernof13617a2016-09-08 11:42:10 +0200148 log_file = None
tiernoa36d64d2016-09-14 15:58:40 +0200149 db_name = None
tiernof7aa8c42016-09-06 16:43:04 +0200150
151 for o, a in opts:
152 if o in ("-v", "--version"):
153 print "openvimd version", __version__, version_date
154 print "(c) Copyright Telefonica"
155 sys.exit(0)
156 elif o in ("-h", "--help"):
157 usage()
158 sys.exit(0)
159 elif o in ("-c", "--config"):
160 config_file = a
161 elif o in ("-p", "--port"):
162 port = a
163 elif o in ("-P", "--adminport"):
164 port_admin = a
tiernoa36d64d2016-09-14 15:58:40 +0200165 elif o in ("-P", "--dbname"):
166 db_name = a
tiernof13617a2016-09-08 11:42:10 +0200167 elif o == "--log-file":
168 log_file = a
tiernof7aa8c42016-09-06 16:43:04 +0200169 else:
170 assert False, "Unhandled option"
171
172
tierno57f7bda2017-02-09 12:01:55 +0100173 engine = None
tierno56c0c282017-02-10 14:52:55 +0100174 http_thread = None
175 http_thread_admin = None
176
tiernof7aa8c42016-09-06 16:43:04 +0200177 try:
178 #Load configuration file
179 r, config_dic = load_configuration(config_file)
180 #print config_dic
181 if not r:
182 logger.error(config_dic)
183 config_dic={}
184 exit(-1)
tiernof13617a2016-09-08 11:42:10 +0200185 if log_file:
186 try:
187 file_handler= logging.handlers.RotatingFileHandler(log_file, maxBytes=100e6, backupCount=9, delay=0)
188 file_handler.setFormatter(log_formatter_simple)
189 logger.addHandler(file_handler)
190 #logger.debug("moving logs to '%s'", global_config["log_file"])
191 #remove initial stream handler
192 logging.root.removeHandler(logging.root.handlers[0])
193 print ("logging on '{}'".format(log_file))
194 except IOError as e:
195 raise LoadConfigurationException("Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, str(e)) )
196
tiernof7aa8c42016-09-06 16:43:04 +0200197 logger.setLevel(getattr(logging, config_dic['log_level']))
tiernof13617a2016-09-08 11:42:10 +0200198 logger.critical("Starting openvim server command: '%s'", sys.argv[0])
tiernof7aa8c42016-09-06 16:43:04 +0200199 #override parameters obtained by command line
tiernoa36d64d2016-09-14 15:58:40 +0200200 if port:
201 config_dic['http_port'] = port
202 if port_admin:
203 config_dic['http_admin_port'] = port_admin
204 if db_name:
205 config_dic['db_name'] = db_name
tiernof7aa8c42016-09-06 16:43:04 +0200206
207 #check mode
208 if 'mode' not in config_dic:
209 config_dic['mode'] = 'normal'
210 #allow backward compatibility of test_mode option
211 if 'test_mode' in config_dic and config_dic['test_mode']==True:
212 config_dic['mode'] = 'test'
Mirabal7256d6b2016-12-15 10:51:19 +0000213 if config_dic['mode'] == 'development' and config_dic['network_type'] == 'bridge' and \
214 ( '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 +0200215 logger.error("'%s' is not a valid 'development_bridge', not one of the 'bridge_ifaces'", config_file)
216 exit(-1)
Mirabale9317ff2017-01-18 16:10:58 +0000217
tiernof7aa8c42016-09-06 16:43:04 +0200218 if config_dic['mode'] != 'normal':
219 print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
220 print "!! Warning, openvimd in TEST mode '%s'" % config_dic['mode']
221 print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
222 config_dic['version'] = __version__
223
tierno57f7bda2017-02-09 12:01:55 +0100224 config_dic["database_version"] = database_version
225 config_dic["logger_name"] = "openvim"
tiernof7aa8c42016-09-06 16:43:04 +0200226
tierno57f7bda2017-02-09 12:01:55 +0100227 engine = ovim.ovim(config_dic)
228 engine.start_service()
tiernof7aa8c42016-09-06 16:43:04 +0200229
tiernof7aa8c42016-09-06 16:43:04 +0200230
231 #Create thread to listen to web requests
tierno57f7bda2017-02-09 12:01:55 +0100232 http_thread = httpserver.httpserver(engine, 'http', config_dic['http_host'], config_dic['http_port'], False, config_dic)
tiernof7aa8c42016-09-06 16:43:04 +0200233 http_thread.start()
234
tierno57f7bda2017-02-09 12:01:55 +0100235 if 'http_admin_port' in config_dic:
236 engine2 = ovim.ovim(config_dic)
237 http_thread_admin = httpserver.httpserver(engine2, 'http-admin', config_dic['http_host'], config_dic['http_admin_port'], True)
tiernof7aa8c42016-09-06 16:43:04 +0200238 http_thread_admin.start()
239 else:
240 http_thread_admin = None
241 time.sleep(1)
242 logger.info('Waiting for http clients')
243 print ('openvimd ready')
244 print ('====================')
245 sys.stdout.flush()
246
247 #TODO: Interactive console would be nice here instead of join or sleep
248
249 r="help" #force print help at the beginning
250 while True:
251 if r=='exit':
252 break
253 elif r!='':
254 print "type 'exit' for terminate"
255 r = raw_input('> ')
256
257 except (KeyboardInterrupt, SystemExit):
258 pass
tiernof13617a2016-09-08 11:42:10 +0200259 except SystemExit:
260 pass
261 except getopt.GetoptError as e:
262 logger.critical(str(e)) # will print something like "option -a not recognized"
263 #usage()
264 exit(-1)
265 except LoadConfigurationException as e:
266 logger.critical(str(e))
267 exit(-1)
tierno57f7bda2017-02-09 12:01:55 +0100268 except ovim.ovimException as e:
269 logger.critical(str(e))
270 exit(-1)
tiernof7aa8c42016-09-06 16:43:04 +0200271
272 logger.info('Exiting openvimd')
tierno57f7bda2017-02-09 12:01:55 +0100273 if engine:
274 engine.stop_service()
tierno56c0c282017-02-10 14:52:55 +0100275 if http_thread:
276 http_thread.join(1)
277 if http_thread_admin:
278 http_thread_admin.join(1)
tierno57f7bda2017-02-09 12:01:55 +0100279
tiernof7aa8c42016-09-06 16:43:04 +0200280 logger.debug( "bye!")
281 exit()
282