v0.4.8 insert option --log-file to prepare to be a service
[osm/openvim.git] / openvimd.py
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 __author__="Alfonso Tierno"
32 __date__ ="$10-jul-2014 12:07:15$"
33 __version__="0.4.8-r495"
34 version_date="Sep 2016"
35 database_version="0.7" #expected database schema version
36
37 import httpserver
38 import auxiliary_functions as af
39 import sys
40 import getopt
41 import time
42 import vim_db
43 import yaml
44 import os
45 from jsonschema import validate as js_v, exceptions as js_e
46 import host_thread as ht
47 import dhcp_thread as dt
48 import openflow_thread as oft
49 import threading
50 from vim_schema import config_schema
51 import logging
52 import logging.handlers as log_handlers
53 import imp
54 import socket
55
56 global config_dic
57 global logger
58 logger = logging.getLogger('vim')
59
60 class LoadConfigurationException(Exception):
61 pass
62
63 def load_configuration(configuration_file):
64 default_tokens ={'http_port':9080, 'http_host':'localhost',
65 'of_controller_nets_with_same_vlan':True,
66 'image_path':'/opt/VNF/images',
67 'network_vlan_range_start':1000,
68 'network_vlan_range_end': 4096,
69 'log_level': "DEBUG",
70 'log_level_db': "ERROR",
71 'log_level_of': 'ERROR',
72 }
73 try:
74 #First load configuration from configuration file
75 #Check config file exists
76 if not os.path.isfile(configuration_file):
77 return (False, "Configuration file '"+configuration_file+"' does not exists")
78
79 #Read and parse file
80 (return_status, code) = af.read_file(configuration_file)
81 if not return_status:
82 return (return_status, "Error loading configuration file '"+configuration_file+"': "+code)
83 try:
84 config = yaml.load(code)
85 except yaml.YAMLError, exc:
86 error_pos = ""
87 if hasattr(exc, 'problem_mark'):
88 mark = exc.problem_mark
89 error_pos = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
90 return (False, "Error loading configuration file '"+configuration_file+"'"+error_pos+": content format error: Failed to parse yaml format")
91
92
93 try:
94 js_v(config, config_schema)
95 except js_e.ValidationError, exc:
96 error_pos = ""
97 if len(exc.path)>0: error_pos=" at '" + ":".join(map(str, exc.path))+"'"
98 return False, "Error loading configuration file '"+configuration_file+"'"+error_pos+": "+exc.message
99
100
101 #Check default values tokens
102 for k,v in default_tokens.items():
103 if k not in config: config[k]=v
104 #Check vlan ranges
105 if config["network_vlan_range_start"]+10 >= config["network_vlan_range_end"]:
106 return False, "Error invalid network_vlan_range less than 10 elements"
107
108 except Exception,e:
109 return (False, "Error loading configuration file '"+configuration_file+"': "+str(e))
110 return (True, config)
111
112 def create_database_connection(config_dic):
113 db = vim_db.vim_db( (config_dic["network_vlan_range_start"],config_dic["network_vlan_range_end"]), config_dic['log_level_db'] );
114 if db.connect(config_dic['db_host'], config_dic['db_user'], config_dic['db_passwd'], config_dic['db_name']) == -1:
115 logger.error("Cannot connect to database %s at %s@%s", config_dic['db_name'], config_dic['db_user'], config_dic['db_host'])
116 exit(-1)
117 return db
118
119 def usage():
120 print "Usage: ", sys.argv[0], "[options]"
121 print " -v|--version: prints current version"
122 print " -c|--config [configuration_file]: loads the configuration file (default: openvimd.cfg)"
123 print " -h|--help: shows this help"
124 print " -p|--port [port_number]: changes port number and overrides the port number in the configuration file (default: 9090)"
125 print " -P|--adminport [port_number]: changes admin port number and overrides the port number in the configuration file (default: 9095)"
126 #print( " --log-socket-host HOST: send logs to this host")
127 #print( " --log-socket-port PORT: send logs using this port (default: 9022)")
128 print( " --log-file FILE: send logs to this file")
129 return
130
131
132 if __name__=="__main__":
133 hostname = socket.gethostname()
134 #streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
135 log_formatter_complete = logging.Formatter(
136 '%(asctime)s.%(msecs)03d00Z[{host}@openmanod] %(filename)s:%(lineno)s severity:%(levelname)s logger:%(name)s log:%(message)s'.format(host=hostname),
137 datefmt='%Y-%m-%dT%H:%M:%S',
138 )
139 log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
140 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
141 logging.basicConfig(format=log_format_simple, level= logging.DEBUG)
142 logger = logging.getLogger('openmano')
143 logger.setLevel(logging.DEBUG)
144 try:
145 opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:", ["config=", "help", "version", "port=", "adminport=", "log-file="])
146 except getopt.GetoptError, err:
147 # print help information and exit:
148 logger.error("%s. Type -h for help", err) # will print something like "option -a not recognized"
149 #usage()
150 sys.exit(-2)
151
152 port=None
153 port_admin = None
154 config_file = 'openvimd.cfg'
155 log_file = None
156
157 for o, a in opts:
158 if o in ("-v", "--version"):
159 print "openvimd version", __version__, version_date
160 print "(c) Copyright Telefonica"
161 sys.exit(0)
162 elif o in ("-h", "--help"):
163 usage()
164 sys.exit(0)
165 elif o in ("-c", "--config"):
166 config_file = a
167 elif o in ("-p", "--port"):
168 port = a
169 elif o in ("-P", "--adminport"):
170 port_admin = a
171 elif o == "--log-file":
172 log_file = a
173 else:
174 assert False, "Unhandled option"
175
176
177 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)
185 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
197 logger.setLevel(getattr(logging, config_dic['log_level']))
198 logger.critical("Starting openvim server command: '%s'", sys.argv[0])
199 #override parameters obtained by command line
200 if port is not None: config_dic['http_port'] = port
201 if port_admin is not None: config_dic['http_admin_port'] = port_admin
202
203 #check mode
204 if 'mode' not in config_dic:
205 config_dic['mode'] = 'normal'
206 #allow backward compatibility of test_mode option
207 if 'test_mode' in config_dic and config_dic['test_mode']==True:
208 config_dic['mode'] = 'test'
209 if config_dic['mode'] == 'development' and ( 'development_bridge' not in config_dic or config_dic['development_bridge'] not in config_dic.get("bridge_ifaces",None) ):
210 logger.error("'%s' is not a valid 'development_bridge', not one of the 'bridge_ifaces'", config_file)
211 exit(-1)
212
213 if config_dic['mode'] != 'normal':
214 print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
215 print "!! Warning, openvimd in TEST mode '%s'" % config_dic['mode']
216 print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
217 config_dic['version'] = __version__
218
219 #Connect to database
220 db_http = create_database_connection(config_dic)
221 r = db_http.get_db_version()
222 if r[0]<0:
223 logger.error("DATABASE is not a VIM one or it is a '0.0' version. Try to upgrade to version '%s' with './database_utils/migrate_vim_db.sh'", database_version)
224 exit(-1)
225 elif r[1]!=database_version:
226 logger.error("DATABASE wrong version '%s'. Try to upgrade/downgrade to version '%s' with './database_utils/migrate_vim_db.sh'", r[1], database_version)
227 exit(-1)
228 db_of = create_database_connection(config_dic)
229 db_lock= threading.Lock()
230 config_dic['db'] = db_of
231 config_dic['db_lock'] = db_lock
232
233 #precreate interfaces; [bridge:<host_bridge_name>, VLAN used at Host, uuid of network camping in this bridge, speed in Gbit/s
234 config_dic['dhcp_nets']=[]
235 config_dic['bridge_nets']=[]
236 for bridge,vlan_speed in config_dic["bridge_ifaces"].items():
237 #skip 'development_bridge'
238 if config_dic['mode'] == 'development' and config_dic['development_bridge'] == bridge:
239 continue
240 config_dic['bridge_nets'].append( [bridge, vlan_speed[0], vlan_speed[1], None] )
241 del config_dic["bridge_ifaces"]
242
243 #check if this bridge is already used (present at database) for a network)
244 used_bridge_nets=[]
245 for brnet in config_dic['bridge_nets']:
246 r,nets = db_of.get_table(SELECT=('uuid',), FROM='nets',WHERE={'provider': "bridge:"+brnet[0]})
247 if r>0:
248 brnet[3] = nets[0]['uuid']
249 used_bridge_nets.append(brnet[0])
250 if config_dic.get("dhcp_server"):
251 if brnet[0] in config_dic["dhcp_server"]["bridge_ifaces"]:
252 config_dic['dhcp_nets'].append(nets[0]['uuid'])
253 if len(used_bridge_nets) > 0 :
254 logger.info("found used bridge nets: " + ",".join(used_bridge_nets))
255 #get nets used by dhcp
256 if config_dic.get("dhcp_server"):
257 for net in config_dic["dhcp_server"].get("nets", () ):
258 r,nets = db_of.get_table(SELECT=('uuid',), FROM='nets',WHERE={'name': net})
259 if r>0:
260 config_dic['dhcp_nets'].append(nets[0]['uuid'])
261
262 # get host list from data base before starting threads
263 r,hosts = db_of.get_table(SELECT=('name','ip_name','user','uuid'), FROM='hosts', WHERE={'status':'ok'})
264 if r<0:
265 logger.error("Cannot get hosts from database %s", hosts)
266 exit(-1)
267 # create connector to the openflow controller
268 of_test_mode = False if config_dic['mode']=='normal' or config_dic['mode']=="OF only" else True
269
270 if of_test_mode:
271 OF_conn = oft.of_test_connector({"of_debug": config_dic['log_level_of']} )
272 else:
273 #load other parameters starting by of_ from config dict in a temporal dict
274 temp_dict={ "of_ip": config_dic['of_controller_ip'],
275 "of_port": config_dic['of_controller_port'],
276 "of_dpid": config_dic['of_controller_dpid'],
277 "of_debug": config_dic['log_level_of']
278 }
279 for k,v in config_dic.iteritems():
280 if type(k) is str and k[0:3]=="of_" and k[0:13] != "of_controller":
281 temp_dict[k]=v
282 if config_dic['of_controller']=='opendaylight':
283 module = "ODL"
284 elif "of_controller_module" in config_dic:
285 module = config_dic["of_controller_module"]
286 else:
287 module = config_dic['of_controller']
288 module_info=None
289 try:
290 module_info = imp.find_module(module)
291
292 OF_conn = imp.load_module("OF_conn", *module_info)
293 try:
294 OF_conn = OF_conn.OF_conn(temp_dict)
295 except Exception as e:
296 logger.error("Cannot open the Openflow controller '%s': %s", type(e).__name__, str(e))
297 if module_info and module_info[0]:
298 file.close(module_info[0])
299 exit(-1)
300 except (IOError, ImportError) as e:
301 if module_info and module_info[0]:
302 file.close(module_info[0])
303 logger.error("Cannot open openflow controller module '%s'; %s: %s; revise 'of_controller' field of configuration file.", module, type(e).__name__, str(e))
304 exit(-1)
305
306
307 #create openflow thread
308 thread = oft.openflow_thread(OF_conn, of_test=of_test_mode, db=db_of, db_lock=db_lock,
309 pmp_with_same_vlan=config_dic['of_controller_nets_with_same_vlan'],
310 debug=config_dic['log_level_of'])
311 r,c = thread.OF_connector.obtain_port_correspondence()
312 if r<0:
313 logger.error("Cannot get openflow information %s", c)
314 exit()
315 thread.start()
316 config_dic['of_thread'] = thread
317
318 #create dhcp_server thread
319 host_test_mode = True if config_dic['mode']=='test' or config_dic['mode']=="OF only" else False
320 dhcp_params = config_dic.get("dhcp_server")
321 if dhcp_params:
322 thread = dt.dhcp_thread(dhcp_params=dhcp_params, test=host_test_mode, dhcp_nets=config_dic["dhcp_nets"], db=db_of, db_lock=db_lock, debug=config_dic['log_level_of'])
323 thread.start()
324 config_dic['dhcp_thread'] = thread
325
326
327 #Create one thread for each host
328 host_test_mode = True if config_dic['mode']=='test' or config_dic['mode']=="OF only" else False
329 host_develop_mode = True if config_dic['mode']=='development' else False
330 host_develop_bridge_iface = config_dic.get('development_bridge', None)
331 config_dic['host_threads'] = {}
332 for host in hosts:
333 host['image_path'] = '/opt/VNF/images/openvim'
334 thread = ht.host_thread(name=host['name'], user=host['user'], host=host['ip_name'], db=db_of, db_lock=db_lock,
335 test=host_test_mode, image_path=config_dic['image_path'], version=config_dic['version'],
336 host_id=host['uuid'], develop_mode=host_develop_mode, develop_bridge_iface=host_develop_bridge_iface )
337 thread.start()
338 config_dic['host_threads'][ host['uuid'] ] = thread
339
340
341
342 #Create thread to listen to web requests
343 http_thread = httpserver.httpserver(db_http, 'http', config_dic['http_host'], config_dic['http_port'], False, config_dic)
344 http_thread.start()
345
346 if 'http_admin_port' in config_dic:
347 db_http = create_database_connection(config_dic)
348 http_thread_admin = httpserver.httpserver(db_http, 'http-admin', config_dic['http_host'], config_dic['http_admin_port'], True)
349 http_thread_admin.start()
350 else:
351 http_thread_admin = None
352 time.sleep(1)
353 logger.info('Waiting for http clients')
354 print ('openvimd ready')
355 print ('====================')
356 sys.stdout.flush()
357
358 #TODO: Interactive console would be nice here instead of join or sleep
359
360 r="help" #force print help at the beginning
361 while True:
362 if r=='exit':
363 break
364 elif r!='':
365 print "type 'exit' for terminate"
366 r = raw_input('> ')
367
368 except (KeyboardInterrupt, SystemExit):
369 pass
370 except SystemExit:
371 pass
372 except getopt.GetoptError as e:
373 logger.critical(str(e)) # will print something like "option -a not recognized"
374 #usage()
375 exit(-1)
376 except LoadConfigurationException as e:
377 logger.critical(str(e))
378 exit(-1)
379
380 logger.info('Exiting openvimd')
381 threads = config_dic.get('host_threads', {})
382 if 'of_thread' in config_dic:
383 threads['of'] = (config_dic['of_thread'])
384 if 'dhcp_thread' in config_dic:
385 threads['dhcp'] = (config_dic['dhcp_thread'])
386
387 for thread in threads.values():
388 thread.insert_task("exit")
389 for thread in threads.values():
390 thread.join()
391 #http_thread.join()
392 #if http_thread_admin is not None:
393 #http_thread_admin.join()
394 logger.debug( "bye!")
395 exit()
396