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 __author__ = "Alfonso Tierno"
32 __date__ = "$10-jul-2014 12:07:15$"
34 import osm_openvim.httpserver as httpserver
35 import osm_openvim.auxiliary_functions as af
41 from jsonschema import validate as js_v, exceptions as js_e
42 from vim_schema import config_schema
44 import logging.handlers as log_handlers
46 import osm_openvim.ovim as ovim
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 'image_path':'/opt/VNF/images',
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 return (False, "Configuration file '"+configuration_file+"' does not exists")
78 (return_status, code) = af.read_file(configuration_file)
80 return (return_status, "Error loading configuration file '"+configuration_file+"': "+code)
82 config = yaml.load(code)
83 except yaml.YAMLError, exc:
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")
92 js_v(config, config_schema)
93 except js_e.ValidationError, exc:
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
99 #Check default values tokens
100 for k,v in default_tokens.items():
101 if k not in config: config[k]=v
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"
107 return (False, "Error loading configuration file '"+configuration_file+"': "+str(e))
108 return (True, config)
111 print "Usage: ", sys.argv[0], "[options]"
112 print " -v|--version: prints current version"
113 print " -c|--config FILE: loads the configuration file (default: openvimd.cfg)"
114 print " -h|--help: shows this help"
115 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"
118 #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")
124 if __name__=="__main__":
125 hostname = socket.gethostname()
126 #streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
127 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',
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')
133 logging.basicConfig(format=log_format_simple, level= logging.DEBUG)
134 logger = logging.getLogger('openvim')
135 logger.setLevel(logging.DEBUG)
137 opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:", ["config=", "help", "version", "port=", "adminport=", "log-file=", "dbname="])
138 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"
146 config_file = 'openvimd.cfg'
151 if o in ("-v", "--version"):
152 print "openvimd version", ovim.ovim.get_version(), ovim.ovim.get_version_date()
153 print "(c) Copyright Telefonica"
155 elif o in ("-h", "--help"):
158 elif o in ("-c", "--config"):
160 elif o in ("-p", "--port"):
162 elif o in ("-P", "--adminport"):
164 elif o in ("-P", "--dbname"):
166 elif o == "--log-file":
169 assert False, "Unhandled option"
174 http_thread_admin = None
177 #Load configuration file
178 r, config_dic = load_configuration(config_file)
181 logger.error(config_dic)
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))
194 raise LoadConfigurationException("Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, str(e)) )
196 logger.setLevel(getattr(logging, config_dic['log_level']))
197 logger.critical("Starting openvim server command: '%s'", sys.argv[0])
198 #override parameters obtained by command line
200 config_dic['http_port'] = port
202 config_dic['http_admin_port'] = port_admin
204 config_dic['db_name'] = db_name
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'
212 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) ):
214 logger.error("'%s' is not a valid 'development_bridge', not one of the 'bridge_ifaces'", config_file)
217 if config_dic['mode'] != 'normal':
218 print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
219 print "!! Warning, openvimd in TEST mode '%s'" % config_dic['mode']
220 print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
221 config_dic['version'] = ovim.ovim.get_version()
222 config_dic["logger_name"] = "openvim"
224 engine = ovim.ovim(config_dic)
225 engine.start_service()
228 #Create thread to listen to web requests
229 http_thread = httpserver.httpserver(engine, 'http', config_dic['http_host'], config_dic['http_port'], False, config_dic)
232 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)
235 http_thread_admin.start()
237 http_thread_admin = None
239 logger.info('Waiting for http clients')
240 print ('openvimd ready')
241 print ('====================')
244 #TODO: Interactive console would be nice here instead of join or sleep
246 r="help" #force print help at the beginning
251 print "type 'exit' for terminate"
254 except (KeyboardInterrupt, SystemExit):
258 except getopt.GetoptError as e:
259 logger.critical(str(e)) # will print something like "option -a not recognized"
262 except LoadConfigurationException as e:
263 logger.critical(str(e))
265 except ovim.ovimException as e:
266 logger.critical(str(e))
269 logger.info('Exiting openvimd')
271 engine.stop_service()
274 if http_thread_admin:
275 http_thread_admin.join(1)
277 logger.debug( "bye!")