Unify ssh_command. Allow remote ssh with paramiko and localhost with subprocess
[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 controllers
28 and host controllers, network controller
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                       'host_ssh_keyfile': None,
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             raise LoadConfigurationException("Configuration file '{}' does not exists".format(configuration_file))
76
77         # Read and parse file
78         (return_status, code) = af.read_file(configuration_file)
79         if not return_status:
80             raise LoadConfigurationException("Error loading configuration file '{}': {}".format(
81                 configuration_file, code))
82         config = yaml.load(code)
83         js_v(config, config_schema)
84         # Check default values tokens
85         for k, v in default_tokens.items():
86             if k not in config:
87                 config[k] = v
88         # Check vlan ranges
89         if config["network_vlan_range_start"] + 10 >= config["network_vlan_range_end"]:
90             raise LoadConfigurationException(
91                 "Error at configuration file '{}'. Invalid network_vlan_range less than 10 elements".format(
92                     configuration_file))
93         return config
94     except yaml.YAMLError as exc:
95         error_pos = ""
96         if hasattr(exc, 'problem_mark'):
97             mark = exc.problem_mark
98             error_pos = " at position: ({}:{})".format(mark.line + 1, mark.column + 1)
99         raise LoadConfigurationException("Bad YAML format at configuration file '{}'{}: {}\n"
100                                          "Use a valid yaml format. Indentation matters, "
101                                          "and tabs characters are not valid".format(
102                                                 configuration_file, error_pos, exc))
103     except js_e.ValidationError as exc:
104         error_pos = ""
105         if len(exc.path) > 0:
106             error_pos = " at '{}'".format(":".join(map(str, exc.path)))
107         raise LoadConfigurationException("Invalid field at configuration file '{}'{}: {}".format(
108             configuration_file, error_pos, exc))
109
110         # except Exception as e:
111         #     raise LoadConfigurationException("Error loading configuration file '{}': {}".format(configuration_file, e))
112
113
114 def usage():
115     print ("Usage: {} [options]".format(sys.argv[0]))
116     print ("      -v|--version: prints current version")
117     print ("      -c|--config FILE: loads the configuration file (default: osm_openvim/openvimd.cfg)")
118     print ("      -h|--help: shows this help")
119     print ("      -p|--port PORT: changes port number and overrides the port number in the configuration file "
120            "(default: 908)")
121     print ("      -P|--adminport PORT: changes admin port number and overrides the port number in the configuration "
122            "file (default: not listen)")
123     print ("      --dbname NAME: changes db_name and overrides the db_name in the configuration file")
124     # print( "      --log-socket-host HOST: send logs to this host")
125     # print( "      --log-socket-port PORT: send logs using this port (default: 9022)")
126     print ("      --log-file FILE: send logs to this file")
127     return
128
129
130 def set_logging_file(log_file):
131     try:
132         file_handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=100e6, backupCount=9, delay=0)
133         file_handler.setFormatter(log_formatter_simple)
134         logger.addHandler(file_handler)
135         # logger.debug("moving logs to '%s'", global_config["log_file"])
136         # remove initial stream handler
137         logging.root.removeHandler(logging.root.handlers[0])
138         print ("logging on '{}'".format(log_file))
139     except IOError as e:
140         raise LoadConfigurationException(
141             "Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, e))
142
143
144 if __name__ == "__main__":
145     hostname = socket.gethostname()
146     # streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
147     log_formatter_complete = logging.Formatter('%(asctime)s.%(msecs)03d00Z[{host}@openmanod] %(filename)s:%(lineno)s '
148                                                'severity:%(levelname)s logger:%(name)s log:%(message)s'.format(
149         host=hostname),
150         datefmt='%Y-%m-%dT%H:%M:%S')
151     log_format_simple = "%(asctime)s %(levelname)s  %(name)s %(filename)s:%(lineno)s %(message)s"
152     log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
153     logging.basicConfig(format=log_format_simple, level=logging.DEBUG)
154     logger = logging.getLogger('openvim')
155     logger.setLevel(logging.DEBUG)
156     try:
157         opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:",
158                                    ["config=", "help", "version", "port=", "adminport=", "log-file=", "dbname="])
159     except getopt.GetoptError as err:
160         # print help information and exit:
161         logger.error("%s. Type -h for help", err)  # will print something like "option -a not recognized"
162         # usage()
163         sys.exit(2)
164
165     port = None
166     port_admin = None
167     config_file = 'osm_openvim/openvimd.cfg'
168     log_file = None
169     db_name = None
170
171     for o, a in opts:
172         if o in ("-v", "--version"):
173             print ("openvimd version {} {}".format(ovim.ovim.get_version(), ovim.ovim.get_version_date()))
174             print ("(c) Copyright Telefonica")
175             sys.exit(0)
176         elif o in ("-h", "--help"):
177             usage()
178             sys.exit(0)
179         elif o in ("-c", "--config"):
180             config_file = a
181         elif o in ("-p", "--port"):
182             port = a
183         elif o in ("-P", "--adminport"):
184             port_admin = a
185         elif o in ("-P", "--dbname"):
186             db_name = a
187         elif o == "--log-file":
188             log_file = a
189         else:
190             assert False, "Unhandled option"
191
192     engine = None
193     http_thread = None
194     http_thread_admin = None
195
196     try:
197         if log_file:
198             set_logging_file(log_file)
199         # Load configuration file
200         config_dic = load_configuration(config_file)
201         if config_dic.get("dhcp_server"):
202             if config_dic["dhcp_server"].get("key"):
203                 config_dic["dhcp_server"]["keyfile"] = config_dic["dhcp_server"].pop("key")
204         if config_dic.get("image_path"):
205             config_dic["host_image_path"] = config_dic.pop("image_path")
206         elif not config_dic.get("host_image_path"):
207             config_dic["host_image_path"] = '/opt/VNF/images'  # default value
208         # print config_dic
209
210         logger.setLevel(getattr(logging, config_dic['log_level']))
211         logger.critical("Starting openvim server command: '%s'", sys.argv[0])
212         # override parameters obtained by command line
213         if port:
214             config_dic['http_port'] = port
215         if port_admin:
216             config_dic['http_admin_port'] = port_admin
217         if db_name:
218             config_dic['db_name'] = db_name
219
220         # check mode
221         if 'mode' not in config_dic:
222             config_dic['mode'] = 'normal'
223             # allow backward compatibility of test_mode option
224             if 'test_mode' in config_dic and config_dic['test_mode'] == True:
225                 config_dic['mode'] = 'test'
226         if config_dic['mode'] == 'development' and config_dic['network_type'] == 'bridge' and \
227                 ('development_bridge' not in config_dic or
228                          config_dic['development_bridge'] not in config_dic.get("bridge_ifaces", None)):
229             error_msg = "'{}' is not a valid 'development_bridge', not one of the 'bridge_ifaces'".format(config_file)
230             print (error_msg)
231             logger.error(error_msg)
232             exit(1)
233
234         if config_dic['network_type'] == 'ovs' \
235                 and config_dic['ovs_controller_ip'][:4] == '127.':
236                 # and not (config_dic['mode'] == 'test' or config_dic['mode'] == "OF only"):
237
238             error_msg = "Error: invalid value '{}' for ovs_controller_ip at {}. Use 'localhost' word instead "\
239                         "of a loopback IP address".format(config_dic['ovs_controller_ip'], config_file)
240
241             print ("!! {} ".format(error_msg))
242             logger.error(error_msg)
243             exit(1)
244
245         if config_dic['mode'] != 'normal':
246             print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
247             print ("!! Warning, openvimd in TEST mode '{}'".format(config_dic['mode']))
248             print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
249
250         config_dic['version'] = ovim.ovim.get_version()
251         config_dic["logger_name"] = "openvim"
252
253         engine = ovim.ovim(config_dic)
254         engine.start_service()
255
256         # Create thread to listen to web requests
257         http_thread = httpserver.httpserver(engine, 'http', config_dic['http_host'], config_dic['http_port'],
258                                             False, config_dic)
259         http_thread.start()
260
261         if 'http_admin_port' in config_dic:
262             engine2 = ovim.ovim(config_dic)
263             http_thread_admin = httpserver.httpserver(engine2, 'http-admin', config_dic['http_host'],
264                                                       config_dic['http_admin_port'], True)
265             http_thread_admin.start()
266         else:
267             http_thread_admin = None
268         time.sleep(1)
269         logger.info('Waiting for http clients')
270         print ('openvimd ready')
271         print ('====================')
272         sys.stdout.flush()
273
274         # TODO: Interactive console would be nice here instead of join or sleep
275
276         r = ""
277         while True:
278             if r == 'exit':
279                 break
280             elif r != '':
281                 print "type 'exit' for terminate"
282             try:
283                 r = raw_input('> ')
284             except EOFError:
285                 time.sleep(86400)
286
287     except (KeyboardInterrupt, SystemExit):
288         pass
289     except (getopt.GetoptError, LoadConfigurationException, ovim.ovimException) as e:
290         logger.critical(str(e))  # will print something like "option -a not recognized"
291         exit(1)
292
293     logger.info('Exiting openvimd')
294     if engine:
295         engine.stop_service()
296     if http_thread:
297         http_thread.join(1)
298     if http_thread_admin:
299         http_thread_admin.join(1)
300     logger.debug("bye!")
301     exit()