From f13617a350092613d22a39997fb00afda7da209c Mon Sep 17 00:00:00 2001 From: tierno Date: Thu, 8 Sep 2016 11:42:10 +0200 Subject: [PATCH] v0.4.8 insert option --log-file to prepare to be a service Signed-off-by: tierno --- openvimd.py | 49 +++++++++- scripts/install-openvim-service.sh | 152 +++++++++++++++++++++++++++++ 2 files changed, 196 insertions(+), 5 deletions(-) create mode 100755 scripts/install-openvim-service.sh diff --git a/openvimd.py b/openvimd.py index cc2ae59..5dad98b 100755 --- a/openvimd.py +++ b/openvimd.py @@ -30,7 +30,7 @@ and host controllers __author__="Alfonso Tierno" __date__ ="$10-jul-2014 12:07:15$" -__version__="0.4.7-r494" +__version__="0.4.8-r495" version_date="Sep 2016" database_version="0.7" #expected database schema version @@ -49,12 +49,17 @@ import openflow_thread as oft import threading from vim_schema import config_schema import logging +import logging.handlers as log_handlers import imp +import socket global config_dic global logger logger = logging.getLogger('vim') +class LoadConfigurationException(Exception): + pass + def load_configuration(configuration_file): default_tokens ={'http_port':9080, 'http_host':'localhost', 'of_controller_nets_with_same_vlan':True, @@ -118,16 +123,26 @@ def usage(): print " -h|--help: shows this help" print " -p|--port [port_number]: changes port number and overrides the port number in the configuration file (default: 9090)" print " -P|--adminport [port_number]: changes admin port number and overrides the port number in the configuration file (default: 9095)" + #print( " --log-socket-host HOST: send logs to this host") + #print( " --log-socket-port PORT: send logs using this port (default: 9022)") + print( " --log-file FILE: send logs to this file") return if __name__=="__main__": + hostname = socket.gethostname() #streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s" - streamformat = "%(asctime)s %(name)s %(levelname)s: %(message)s" - logging.basicConfig(format=streamformat, level= logging.DEBUG) + log_formatter_complete = logging.Formatter( + '%(asctime)s.%(msecs)03d00Z[{host}@openmanod] %(filename)s:%(lineno)s severity:%(levelname)s logger:%(name)s log:%(message)s'.format(host=hostname), + datefmt='%Y-%m-%dT%H:%M:%S', + ) + log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s" + log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S') + logging.basicConfig(format=log_format_simple, level= logging.DEBUG) + logger = logging.getLogger('openmano') logger.setLevel(logging.DEBUG) try: - opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:", ["config", "help", "version", "port", "adminport"]) + opts, args = getopt.getopt(sys.argv[1:], "hvc:p:P:", ["config=", "help", "version", "port=", "adminport=", "log-file="]) except getopt.GetoptError, err: # print help information and exit: logger.error("%s. Type -h for help", err) # will print something like "option -a not recognized" @@ -137,6 +152,7 @@ if __name__=="__main__": port=None port_admin = None config_file = 'openvimd.cfg' + log_file = None for o, a in opts: if o in ("-v", "--version"): @@ -152,6 +168,8 @@ if __name__=="__main__": port = a elif o in ("-P", "--adminport"): port_admin = a + elif o == "--log-file": + log_file = a else: assert False, "Unhandled option" @@ -164,8 +182,20 @@ if __name__=="__main__": logger.error(config_dic) config_dic={} exit(-1) - logging.basicConfig(level = getattr(logging, config_dic['log_level'])) + if log_file: + try: + file_handler= logging.handlers.RotatingFileHandler(log_file, maxBytes=100e6, backupCount=9, delay=0) + file_handler.setFormatter(log_formatter_simple) + logger.addHandler(file_handler) + #logger.debug("moving logs to '%s'", global_config["log_file"]) + #remove initial stream handler + logging.root.removeHandler(logging.root.handlers[0]) + print ("logging on '{}'".format(log_file)) + except IOError as e: + raise LoadConfigurationException("Cannot open logging file '{}': {}. Check folder exist and permissions".format(log_file, str(e)) ) + logger.setLevel(getattr(logging, config_dic['log_level'])) + logger.critical("Starting openvim server command: '%s'", sys.argv[0]) #override parameters obtained by command line if port is not None: config_dic['http_port'] = port if port_admin is not None: config_dic['http_admin_port'] = port_admin @@ -337,6 +367,15 @@ if __name__=="__main__": except (KeyboardInterrupt, SystemExit): pass + except SystemExit: + pass + except getopt.GetoptError as e: + logger.critical(str(e)) # will print something like "option -a not recognized" + #usage() + exit(-1) + except LoadConfigurationException as e: + logger.critical(str(e)) + exit(-1) logger.info('Exiting openvimd') threads = config_dic.get('host_threads', {}) diff --git a/scripts/install-openvim-service.sh b/scripts/install-openvim-service.sh new file mode 100755 index 0000000..f673502 --- /dev/null +++ b/scripts/install-openvim-service.sh @@ -0,0 +1,152 @@ +#!/bin/bash + +## +# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U. +# This file is part of openvim +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +# For those usages not covered by the Apache License, Version 2.0 please +# contact with: nfvlabs@tid.es +## + +#ONLY TESTED for Ubuntu 16.04 +#it configures openvim to run as a service + +function usage(){ + echo -e "usage: sudo $0 [OPTIONS]" + echo -e "Configures openvim to run as a service" + echo -e " OPTIONS" + echo -e " -u USER_OWNER user owner of the service, 'root' by default" + echo -e " -f PATH path where openvim source is located. If missing it is downloaded from git" + #echo -e " -q: install in an unattended mode" + echo -e " -h: show this help" + echo -e " --uninstall: remove created service and files" +} + +function uninstall(){ + service openvim stop + for file in /opt/openvim /etc/default/openvimd.cfg /var/log/openvim /etc/systemd/system/openvim.service + do + rm -rf $file || ! echo "Can not delete '$file'. Needed root privileges?" >&2 || exit 1 + done + echo "Done" +} + +BAD_PATH_ERROR="Path '$FILE' does not contain a valid openvim distribution" +GIT_URL=https://osm.etsi.org/gerrit/osm/RO.git +USER_OWNER="root" +QUIET_MODE="" +FILE="" +DELETE="" +while getopts ":u:f:hq-:" o; do + case "${o}" in + u) + export USER_OWNER="$OPTARG" + ;; + f) + export FILE="$OPTARG" + ;; + q) + export QUIET_MODE=yes + ;; + h) + usage && exit 0 + ;; + -) + [ "${OPTARG}" == "help" ] && usage && exit 0 + [ "${OPTARG}" == "uninstall" ] && uninstall && exit 0 + echo -e "Invalid option: '--$OPTARG'\nTry $0 --help for more information" >&2 + exit 1 + ;; + \?) + echo -e "Invalid option: '-$OPTARG'\nTry $0 --help for more information" >&2 + exit 1 + ;; + :) + echo -e "Option '-$OPTARG' requires an argument\nTry $0 --help for more information" >&2 + exit 1 + ;; + *) + usage >&2 + exit -1 + ;; + esac +done + +#check root privileges +[ "$USER" != "root" ] && echo "Needed root privileges" >&2 && exit 1 + +#Discover Linux distribution +#try redhat type +if [[ -f /etc/redhat-release ]] +then + _DISTRO=$(cat /etc/redhat-release 2>/dev/null | cut -d" " -f1) +else + #if not assuming ubuntu type + _DISTRO=$(lsb_release -is 2>/dev/null) +fi +if [[ "$_DISTRO" == "Ubuntu" ]] +then + _RELEASE=$(lsb_release -rs) + if [[ ${_RELEASE%%.*} != 16 ]] + then + echo "Only tested in Ubuntu Server 16.04" >&2 && exit 1 + fi +else + echo "Only tested in Ubuntu Server 16.04" >&2 && exit 1 +fi + + +if [[ -z $FILE ]] +then + git clone $GIT_URL __temp__ || ! echo "Cannot get openvim source code from $GIT_URL" >&2 || exit 1 + #git checkout + FILE=./__temp__ + DELETE=y +fi + +#make idenpotent +rm -rf /opt/openvim +rm -f /etc/default/openvimd.cfg +rm -f /var/log/openvim +cp -r $FILE /opt/openvim || ! echo $BAD_PATH_ERROR >&2 || exit 1 +mkdir -p /opt/openvim/logs +#cp ${FILE}/openvim /usr/sbin/ || ! echo $BAD_PATH_ERROR >&2 || exit 1 +ln -s /opt/openvim/openvimd.cfg /etc/default/openvimd.cfg || echo "warning cannot create link '/etc/default/openvimd.cfg'" +ln -s /opt/openvim/logs /var/log/openvim || echo "warning cannot create link '/var/log/openvim'" + +chown $USER_OWNER /opt/openvim/openvimd.cfg +chown -R $USER_OWNER /opt/openvim + +mkdir -p etc/systemd/system/ +cat > /etc/systemd/system/openvim.service << EOF +[Unit] +Description=openvim server + +[Service] +User=${USER_OWNER} +ExecStart=/opt/openvim/openvimd.py -c /opt/openvim/openvimd.cfg --log-file=/opt/openvim/logs/openvim.log +Restart=always + +[Install] +WantedBy=multi-user.target +EOF + +[[ -n $DELETE ]] && rm -rf $FILE + +service openvim start + +echo Done +exit -- 2.25.1