fix issue at install-openvim.sh
[osm/openvim.git] / openvimd
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 ##
5 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
6 # This file is part of openvim
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 import osm_openvim.httpserver as httpserver
32 import osm_openvim.auxiliary_functions as af
33 import sys
34 import getopt
35 import time
36 import yaml
37 import os
38 from jsonschema import validate as js_v, exceptions as js_e
39 from osm_openvim.vim_schema import config_schema
40 import logging
41 import logging.handlers as log_handlers
42 import socket
43 import osm_openvim.ovim as ovim
44
45 __author__ = "Alfonso Tierno"
46 __date__ = "$10-jul-2014 12:07:15$"
47
48 global config_dic
49 global logger
50 logger = logging.getLogger('vim')
51
52
53 class LoadConfigurationException(Exception):
54     pass
55
56
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,
63                      'log_level': "DEBUG",
64                      'log_level_db': "ERROR",
65                      'log_level_of': 'ERROR',
66                      'bridge_ifaces': {},
67                      'network_type': 'ovs',
68                      'ovs_controller_user': 'osm_dhcp',
69                      'ovs_controller_file_path': '/var/lib/',
70             }
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
110 def usage():
111     print "Usage: ", sys.argv[0], "[options]"
112     print "      -v|--version: prints current version"
113     print "      -c|--config FILE: loads the configuration file (default: osm_openvim/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")
121     return
122
123
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',
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')
133     logging.basicConfig(format=log_format_simple, level=logging.DEBUG)
134     logger = logging.getLogger('openvim')
135     logger.setLevel(logging.DEBUG)
136     try:
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"
141         #usage()
142         sys.exit(-2)
143
144     port=None
145     port_admin = None
146     config_file = 'osm_openvim/openvimd.cfg'
147     log_file = None
148     db_name = None
149
150     for o, a in opts:
151         if o in ("-v", "--version"):
152             print "openvimd version", ovim.ovim.get_version(), ovim.ovim.get_version_date()
153             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
164         elif o in ("-P", "--dbname"):
165             db_name = a
166         elif o == "--log-file":
167             log_file = a
168         else:
169             assert False, "Unhandled option"
170
171     
172     engine = None
173     http_thread = None
174     http_thread_admin = None
175
176     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)
184         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
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
199         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
205         
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' 
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)
215             exit(-1)
216
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"
223
224         engine = ovim.ovim(config_dic)
225         engine.start_service()
226
227         
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)
230         http_thread.start()
231         
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()
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
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)
265     except ovim.ovimException as e:
266         logger.critical(str(e))
267         exit(-1)
268
269     logger.info('Exiting openvimd')
270     if engine:
271         engine.stop_service()
272     if http_thread:
273         http_thread.join(1)
274     if http_thread_admin:
275         http_thread_admin.join(1)
276
277     logger.debug( "bye!")
278     exit()
279