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