| 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 | |
| mirabal | 9e19459 | 2017-02-17 11:03:25 +0100 | [diff] [blame] | 31 | __author__ = "Alfonso Tierno" |
| 32 | __date__ = "$10-jul-2014 12:07:15$" |
| mirabal | 50a052f | 2017-03-27 18:08:07 +0200 | [diff] [blame] | 33 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 34 | |
| 35 | import httpserver |
| tierno | f053737 | 2016-09-08 08:17:37 +0200 | [diff] [blame] | 36 | import auxiliary_functions as af |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 37 | import sys |
| 38 | import getopt |
| 39 | import time |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 40 | import yaml |
| 41 | import os |
| 42 | from jsonschema import validate as js_v, exceptions as js_e |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 43 | from vim_schema import config_schema |
| 44 | import logging |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 45 | import logging.handlers as log_handlers |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 46 | import socket |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 47 | import ovim |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 48 | |
| 49 | global config_dic |
| 50 | global logger |
| 51 | logger = logging.getLogger('vim') |
| 52 | |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 53 | class LoadConfigurationException(Exception): |
| 54 | pass |
| 55 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 56 | def load_configuration(configuration_file): |
| 57 | default_tokens ={'http_port':9080, 'http_host':'localhost', |
| 58 | 'of_controller_nets_with_same_vlan':True, |
| 59 | 'image_path':'/opt/VNF/images', |
| 60 | 'network_vlan_range_start':1000, |
| 61 | 'network_vlan_range_end': 4096, |
| 62 | 'log_level': "DEBUG", |
| 63 | 'log_level_db': "ERROR", |
| 64 | 'log_level_of': 'ERROR', |
| Mirabal | 7256d6b | 2016-12-15 10:51:19 +0000 | [diff] [blame] | 65 | 'bridge_ifaces': {}, |
| 66 | 'network_type': 'ovs', |
| Mirabal | e9317ff | 2017-01-18 16:10:58 +0000 | [diff] [blame] | 67 | 'ovs_controller_user': 'osm_dhcp', |
| 68 | 'ovs_controller_file_path': '/var/lib/', |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 69 | } |
| 70 | try: |
| 71 | #First load configuration from configuration file |
| 72 | #Check config file exists |
| 73 | if not os.path.isfile(configuration_file): |
| 74 | return (False, "Configuration file '"+configuration_file+"' does not exists") |
| 75 | |
| 76 | #Read and parse file |
| 77 | (return_status, code) = af.read_file(configuration_file) |
| 78 | if not return_status: |
| 79 | return (return_status, "Error loading configuration file '"+configuration_file+"': "+code) |
| 80 | try: |
| 81 | config = yaml.load(code) |
| 82 | except yaml.YAMLError, exc: |
| 83 | error_pos = "" |
| 84 | if hasattr(exc, 'problem_mark'): |
| 85 | mark = exc.problem_mark |
| 86 | error_pos = " at position: (%s:%s)" % (mark.line+1, mark.column+1) |
| 87 | return (False, "Error loading configuration file '"+configuration_file+"'"+error_pos+": content format error: Failed to parse yaml format") |
| 88 | |
| 89 | |
| 90 | try: |
| 91 | js_v(config, config_schema) |
| 92 | except js_e.ValidationError, exc: |
| 93 | error_pos = "" |
| 94 | if len(exc.path)>0: error_pos=" at '" + ":".join(map(str, exc.path))+"'" |
| 95 | return False, "Error loading configuration file '"+configuration_file+"'"+error_pos+": "+exc.message |
| 96 | |
| 97 | |
| 98 | #Check default values tokens |
| 99 | for k,v in default_tokens.items(): |
| 100 | if k not in config: config[k]=v |
| 101 | #Check vlan ranges |
| 102 | if config["network_vlan_range_start"]+10 >= config["network_vlan_range_end"]: |
| 103 | return False, "Error invalid network_vlan_range less than 10 elements" |
| 104 | |
| 105 | except Exception,e: |
| 106 | return (False, "Error loading configuration file '"+configuration_file+"': "+str(e)) |
| 107 | return (True, config) |
| 108 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 109 | def usage(): |
| 110 | print "Usage: ", sys.argv[0], "[options]" |
| 111 | print " -v|--version: prints current version" |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 112 | print " -c|--config FILE: loads the configuration file (default: openvimd.cfg)" |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 113 | print " -h|--help: shows this help" |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 114 | print " -p|--port PORT: changes port number and overrides the port number in the configuration file (default: 908)" |
| 115 | print " -P|--adminport PORT: changes admin port number and overrides the port number in the configuration file (default: not listen)" |
| 116 | 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] | 117 | #print( " --log-socket-host HOST: send logs to this host") |
| 118 | #print( " --log-socket-port PORT: send logs using this port (default: 9022)") |
| 119 | print( " --log-file FILE: send logs to this file") |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 120 | return |
| 121 | |
| 122 | |
| 123 | if __name__=="__main__": |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 124 | hostname = socket.gethostname() |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 125 | #streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s" |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 126 | log_formatter_complete = logging.Formatter( |
| 127 | '%(asctime)s.%(msecs)03d00Z[{host}@openmanod] %(filename)s:%(lineno)s severity:%(levelname)s logger:%(name)s log:%(message)s'.format(host=hostname), |
| 128 | datefmt='%Y-%m-%dT%H:%M:%S', |
| 129 | ) |
| 130 | log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s" |
| 131 | log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S') |
| 132 | logging.basicConfig(format=log_format_simple, level= logging.DEBUG) |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 133 | logger = logging.getLogger('openvim') |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 134 | logger.setLevel(logging.DEBUG) |
| 135 | try: |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 136 | 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] | 137 | except getopt.GetoptError, err: |
| 138 | # print help information and exit: |
| 139 | logger.error("%s. Type -h for help", err) # will print something like "option -a not recognized" |
| 140 | #usage() |
| 141 | sys.exit(-2) |
| 142 | |
| 143 | port=None |
| 144 | port_admin = None |
| 145 | config_file = 'openvimd.cfg' |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 146 | log_file = None |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 147 | db_name = None |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 148 | |
| 149 | for o, a in opts: |
| 150 | if o in ("-v", "--version"): |
| mirabal | 50a052f | 2017-03-27 18:08:07 +0200 | [diff] [blame] | 151 | print "openvimd version", ovim.ovim.get_version(), ovim.ovim.get_version_date() |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 152 | print "(c) Copyright Telefonica" |
| 153 | sys.exit(0) |
| 154 | elif o in ("-h", "--help"): |
| 155 | usage() |
| 156 | sys.exit(0) |
| 157 | elif o in ("-c", "--config"): |
| 158 | config_file = a |
| 159 | elif o in ("-p", "--port"): |
| 160 | port = a |
| 161 | elif o in ("-P", "--adminport"): |
| 162 | port_admin = a |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 163 | elif o in ("-P", "--dbname"): |
| 164 | db_name = a |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 165 | elif o == "--log-file": |
| 166 | log_file = a |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 167 | else: |
| 168 | assert False, "Unhandled option" |
| 169 | |
| 170 | |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 171 | engine = None |
| tierno | 56c0c28 | 2017-02-10 14:52:55 +0100 | [diff] [blame] | 172 | http_thread = None |
| 173 | http_thread_admin = None |
| 174 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 175 | try: |
| 176 | #Load configuration file |
| 177 | r, config_dic = load_configuration(config_file) |
| 178 | #print config_dic |
| 179 | if not r: |
| 180 | logger.error(config_dic) |
| 181 | config_dic={} |
| 182 | exit(-1) |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 183 | if log_file: |
| 184 | try: |
| 185 | file_handler= logging.handlers.RotatingFileHandler(log_file, maxBytes=100e6, backupCount=9, delay=0) |
| 186 | file_handler.setFormatter(log_formatter_simple) |
| 187 | logger.addHandler(file_handler) |
| 188 | #logger.debug("moving logs to '%s'", global_config["log_file"]) |
| 189 | #remove initial stream handler |
| 190 | logging.root.removeHandler(logging.root.handlers[0]) |
| 191 | print ("logging on '{}'".format(log_file)) |
| 192 | except IOError as e: |
| 193 | raise LoadConfigurationException("Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, str(e)) ) |
| 194 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 195 | logger.setLevel(getattr(logging, config_dic['log_level'])) |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 196 | logger.critical("Starting openvim server command: '%s'", sys.argv[0]) |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 197 | #override parameters obtained by command line |
| tierno | a36d64d | 2016-09-14 15:58:40 +0200 | [diff] [blame] | 198 | if port: |
| 199 | config_dic['http_port'] = port |
| 200 | if port_admin: |
| 201 | config_dic['http_admin_port'] = port_admin |
| 202 | if db_name: |
| 203 | config_dic['db_name'] = db_name |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 204 | |
| 205 | #check mode |
| 206 | if 'mode' not in config_dic: |
| 207 | config_dic['mode'] = 'normal' |
| 208 | #allow backward compatibility of test_mode option |
| 209 | if 'test_mode' in config_dic and config_dic['test_mode']==True: |
| 210 | config_dic['mode'] = 'test' |
| Mirabal | 7256d6b | 2016-12-15 10:51:19 +0000 | [diff] [blame] | 211 | if config_dic['mode'] == 'development' and config_dic['network_type'] == 'bridge' and \ |
| 212 | ( '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] | 213 | logger.error("'%s' is not a valid 'development_bridge', not one of the 'bridge_ifaces'", config_file) |
| 214 | exit(-1) |
| Mirabal | e9317ff | 2017-01-18 16:10:58 +0000 | [diff] [blame] | 215 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 216 | if config_dic['mode'] != 'normal': |
| 217 | print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' |
| 218 | print "!! Warning, openvimd in TEST mode '%s'" % config_dic['mode'] |
| 219 | print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' |
| tierno | 2db743b | 2017-03-28 17:23:15 +0200 | [diff] [blame^] | 220 | config_dic['version'] = ovim.ovim.get_version() |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 221 | config_dic["logger_name"] = "openvim" |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 222 | |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 223 | engine = ovim.ovim(config_dic) |
| 224 | engine.start_service() |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 225 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 226 | |
| 227 | #Create thread to listen to web requests |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 228 | 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] | 229 | http_thread.start() |
| 230 | |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 231 | if 'http_admin_port' in config_dic: |
| 232 | engine2 = ovim.ovim(config_dic) |
| 233 | 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] | 234 | http_thread_admin.start() |
| 235 | else: |
| 236 | http_thread_admin = None |
| 237 | time.sleep(1) |
| 238 | logger.info('Waiting for http clients') |
| 239 | print ('openvimd ready') |
| 240 | print ('====================') |
| 241 | sys.stdout.flush() |
| 242 | |
| 243 | #TODO: Interactive console would be nice here instead of join or sleep |
| 244 | |
| 245 | r="help" #force print help at the beginning |
| 246 | while True: |
| 247 | if r=='exit': |
| 248 | break |
| 249 | elif r!='': |
| 250 | print "type 'exit' for terminate" |
| 251 | r = raw_input('> ') |
| 252 | |
| 253 | except (KeyboardInterrupt, SystemExit): |
| 254 | pass |
| tierno | f13617a | 2016-09-08 11:42:10 +0200 | [diff] [blame] | 255 | except SystemExit: |
| 256 | pass |
| 257 | except getopt.GetoptError as e: |
| 258 | logger.critical(str(e)) # will print something like "option -a not recognized" |
| 259 | #usage() |
| 260 | exit(-1) |
| 261 | except LoadConfigurationException as e: |
| 262 | logger.critical(str(e)) |
| 263 | exit(-1) |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 264 | except ovim.ovimException as e: |
| 265 | logger.critical(str(e)) |
| 266 | exit(-1) |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 267 | |
| 268 | logger.info('Exiting openvimd') |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 269 | if engine: |
| 270 | engine.stop_service() |
| tierno | 56c0c28 | 2017-02-10 14:52:55 +0100 | [diff] [blame] | 271 | if http_thread: |
| 272 | http_thread.join(1) |
| 273 | if http_thread_admin: |
| 274 | http_thread_admin.join(1) |
| tierno | 57f7bda | 2017-02-09 12:01:55 +0100 | [diff] [blame] | 275 | |
| tierno | f7aa8c4 | 2016-09-06 16:43:04 +0200 | [diff] [blame] | 276 | logger.debug( "bye!") |
| 277 | exit() |
| 278 | |