| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # -*- coding: utf-8 -*- |
| 3 | |
| 4 | ## |
| 5 | # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U. |
| tierno | 9a61c6b | 2016-09-08 10:57:02 +0200 | [diff] [blame] | 6 | # This file is part of openvim |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 7 | # 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 | ''' |
| 26 | This is the main program of openvim, it reads the configuration |
| 27 | and launches the rest of threads: http clients, openflow controller |
| 28 | and host controllers |
| 29 | ''' |
| 30 | |
| 31 | __author__="Alfonso Tierno" |
| 32 | __date__ ="$10-jul-2014 12:07:15$" |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 33 | __version__="0.5.3-r520" |
| tierno | 4a8f0df | 2017-01-19 18:59:59 +0100 | [diff] [blame] | 34 | version_date="Jan 2017" |
| tierno | c1d1d47 | 2017-02-08 14:21:28 +0100 | [diff] [blame] | 35 | database_version="0.10" #expected database schema version |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 36 | |
| 37 | import httpserver |
| tierno | f053737 | 2016-09-08 08:17:37 +0200 | [diff] [blame] | 38 | import auxiliary_functions as af |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 39 | import sys |
| 40 | import getopt |
| 41 | import time |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 42 | import yaml |
| 43 | import os |
| 44 | from jsonschema import validate as js_v, exceptions as js_e |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 45 | from vim_schema import config_schema |
| 46 | import logging |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 47 | import logging.handlers as log_handlers |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 48 | import socket |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 49 | import ovim |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 50 | |
| 51 | global config_dic |
| 52 | global logger |
| 53 | logger = logging.getLogger('vim') |
| 54 | |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 55 | class LoadConfigurationException(Exception): |
| 56 | pass |
| 57 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 58 | def 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', |
| Mirabal | 7256d6b | 2016-12-15 10:51:19 +0000 | [diff] [blame] | 67 | 'bridge_ifaces': {}, |
| 68 | 'network_type': 'ovs', |
| Mirabal | e9317ff | 2017-01-18 16:10:58 +0000 | [diff] [blame] | 69 | 'ovs_controller_user': 'osm_dhcp', |
| 70 | 'ovs_controller_file_path': '/var/lib/', |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 71 | } |
| 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 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 111 | def usage(): |
| 112 | print "Usage: ", sys.argv[0], "[options]" |
| 113 | print " -v|--version: prints current version" |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 114 | print " -c|--config FILE: loads the configuration file (default: openvimd.cfg)" |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 115 | print " -h|--help: shows this help" |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 116 | 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" |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 119 | #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") |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 122 | return |
| 123 | |
| 124 | |
| 125 | if __name__=="__main__": |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 126 | hostname = socket.gethostname() |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 127 | #streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s" |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 128 | 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) |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 135 | logger = logging.getLogger('openvim') |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 136 | logger.setLevel(logging.DEBUG) |
| 137 | try: |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 138 | opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:", ["config=", "help", "version", "port=", "adminport=", "log-file=", "dbname="]) |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 139 | 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' |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 148 | log_file = None |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 149 | db_name = None |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 150 | |
| 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 |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 165 | elif o in ("-P", "--dbname"): |
| 166 | db_name = a |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 167 | elif o == "--log-file": |
| 168 | log_file = a |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 169 | else: |
| 170 | assert False, "Unhandled option" |
| 171 | |
| 172 | |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 173 | engine = None |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 174 | try: |
| 175 | #Load configuration file |
| 176 | r, config_dic = load_configuration(config_file) |
| 177 | #print config_dic |
| 178 | if not r: |
| 179 | logger.error(config_dic) |
| 180 | config_dic={} |
| 181 | exit(-1) |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 182 | if log_file: |
| 183 | try: |
| 184 | file_handler= logging.handlers.RotatingFileHandler(log_file, maxBytes=100e6, backupCount=9, delay=0) |
| 185 | file_handler.setFormatter(log_formatter_simple) |
| 186 | logger.addHandler(file_handler) |
| 187 | #logger.debug("moving logs to '%s'", global_config["log_file"]) |
| 188 | #remove initial stream handler |
| 189 | logging.root.removeHandler(logging.root.handlers[0]) |
| 190 | print ("logging on '{}'".format(log_file)) |
| 191 | except IOError as e: |
| 192 | raise LoadConfigurationException("Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, str(e)) ) |
| 193 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 194 | logger.setLevel(getattr(logging, config_dic['log_level'])) |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 195 | logger.critical("Starting openvim server command: '%s'", sys.argv[0]) |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 196 | #override parameters obtained by command line |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 197 | if port: |
| 198 | config_dic['http_port'] = port |
| 199 | if port_admin: |
| 200 | config_dic['http_admin_port'] = port_admin |
| 201 | if db_name: |
| 202 | config_dic['db_name'] = db_name |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 203 | |
| 204 | #check mode |
| 205 | if 'mode' not in config_dic: |
| 206 | config_dic['mode'] = 'normal' |
| 207 | #allow backward compatibility of test_mode option |
| 208 | if 'test_mode' in config_dic and config_dic['test_mode']==True: |
| 209 | config_dic['mode'] = 'test' |
| Mirabal | 7256d6b | 2016-12-15 10:51:19 +0000 | [diff] [blame] | 210 | if config_dic['mode'] == 'development' and config_dic['network_type'] == 'bridge' and \ |
| 211 | ( 'development_bridge' not in config_dic or config_dic['development_bridge'] not in config_dic.get("bridge_ifaces",None) ): |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 212 | logger.error("'%s' is not a valid 'development_bridge', not one of the 'bridge_ifaces'", config_file) |
| 213 | exit(-1) |
| Mirabal | e9317ff | 2017-01-18 16:10:58 +0000 | [diff] [blame] | 214 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 215 | if config_dic['mode'] != 'normal': |
| 216 | print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' |
| 217 | print "!! Warning, openvimd in TEST mode '%s'" % config_dic['mode'] |
| 218 | print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' |
| 219 | config_dic['version'] = __version__ |
| 220 | |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 221 | config_dic["database_version"] = database_version |
| 222 | config_dic["logger_name"] = "openvim" |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 223 | |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 224 | engine = ovim.ovim(config_dic) |
| 225 | engine.start_service() |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 226 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 227 | |
| 228 | #Create thread to listen to web requests |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 229 | http_thread = httpserver.httpserver(engine, 'http', config_dic['http_host'], config_dic['http_port'], False, config_dic) |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 230 | http_thread.start() |
| 231 | |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 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) |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 235 | 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 |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 256 | 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) |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 265 | except ovim.ovimException as e: |
| 266 | logger.critical(str(e)) |
| 267 | exit(-1) |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 268 | |
| 269 | logger.info('Exiting openvimd') |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame^] | 270 | if engine: |
| 271 | engine.stop_service() |
| 272 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 273 | logger.debug( "bye!") |
| 274 | exit() |
| 275 | |