#!/bin/bash

#    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.

# devstack/plugin.sh
# Functions to control the configuration and operation of the OVN service

# Dependencies:
#
# ``functions`` file
# ``DEST`` must be defined
# ``STACK_USER`` must be defined

# ``stack.sh`` calls the entry points in this order:
#
# - install_ovn
# - configure_ovn
# - configure_ovn_plugin
# - init_ovn
# - start_ovn
# - stop_ovn
# - cleanup_ovn

# Save trace setting
_XTRACE_NETWORKING_OVN=$(set +o | grep xtrace)
set +o xtrace

# Libraries that could be installed from source

GITREPO["ovsdbapp"]=${OVSDBAPP_REPO:-${GIT_BASE}/openstack/ovsdbapp.git}
GITBRANCH["ovsdbapp"]=${OVSDBAPP_BRANCH:-master}
GITDIR["ovsdbapp"]=$DEST/ovsdbapp

# Defaults
# --------

# The git repo to use
OVN_REPO=${OVN_REPO:-https://github.com/openvswitch/ovs.git}
OVN_REPO_NAME=$(basename ${OVN_REPO} | cut -f1 -d'.')

# The project directory
NETWORKING_OVN_DIR=$DEST/networking-ovn

# The branch to use from $OVN_REPO
OVN_BRANCH=${OVN_BRANCH:-master}

# How to connect to ovsdb-server hosting the OVN SB database.
OVN_SB_REMOTE=${OVN_SB_REMOTE:-tcp:$SERVICE_HOST:6642}

# How to connect to ovsdb-server hosting the OVN NB database
OVN_NB_REMOTE=${OVN_NB_REMOTE:-tcp:$SERVICE_HOST:6641}

# A UUID to uniquely identify this system.  If one is not specified, a random
# one will be generated.  A randomly generated UUID will be saved in a file
# 'ovn-uuid' so that the same one will be re-used if you re-run DevStack.
OVN_UUID=${OVN_UUID:-}

# Whether or not to build the openvswitch kernel module from ovs.  This is required
# unless the distro kernel includes ovs+conntrack support.
OVN_BUILD_MODULES=$(trueorfalse True OVN_BUILD_MODULES)

# Whether or not to install the ovs python module from ovs source.  This can be
# used to test and validate new ovs python features.  This should only be used
# for development purposes since the ovs python version is controlled by OpenStack
# requirements.
OVN_INSTALL_OVS_PYTHON_MODULE=$(trueorfalse False OVN_INSTALL_OVS_PYTHON_MODULE)

# GENEVE overlay protocol overhead. Defaults to 38 bytes plus the IP version
# overhead (20 bytes for IPv4 (default) or 40 bytes for IPv6) which is determined
# based on the ML2 overlay_ip_version option. The ML2 framework will use this to
# configure the MTU DHCP option.
OVN_GENEVE_OVERHEAD=${OVN_GENEVE_OVERHEAD:-38}

# This sets whether to create a public network and bridge.
# If set to True, a public network and subnet(s) will be created, and a router
# will be created to route the default private network to the public one.
OVN_L3_CREATE_PUBLIC_NETWORK=$(trueorfalse False OVN_L3_CREATE_PUBLIC_NETWORK)

# ml2/config for neutron_sync_mode
OVN_NEUTRON_SYNC_MODE=${OVN_NEUTRON_SYNC_MODE:-log}

# The type of OVN L3 Scheduler to use. The OVN L3 Scheduler determines the
# hypervisor/chassis where a routers gateway should be hosted in OVN. The
# default OVN L3 scheduler is leastloaded
OVN_L3_SCHEDULER=${OVN_L3_SCHEDULER:-leastloaded}

# Neutron directory
NEUTRON_DIR=$DEST/neutron

OVN_META_CONF=$NEUTRON_CONF_DIR/networking_ovn_metadata_agent.ini

# Set variables for building OVS from source
OVS_REPO=$OVN_REPO
OVS_REPO_NAME=$OVN_REPO_NAME
OVS_BRANCH=$OVN_BRANCH

OVS_PREFIX=/usr/local
OVS_SBINDIR=$OVS_PREFIX/sbin
OVS_BINDIR=$OVS_PREFIX/bin
OVS_RUNDIR=$OVS_PREFIX/var/run/openvswitch
OVS_SHAREDIR=$OVS_PREFIX/share/openvswitch
OVS_SCRIPTDIR=$OVS_SHAREDIR/scripts
OVS_DATADIR=$DATA_DIR/ovs

NETWORKING_OVN_BIN_DIR=$(get_python_exec_prefix)
NETWORKING_OVN_METADATA_BINARY="networking-ovn-metadata-agent"

# Utility Functions
# -----------------

# There are some ovs functions OVN depends on that must be sourced from
# the ovs neutron plugins. After doing this, the OVN overrides must be
# re-sourced.
source $TOP_DIR/lib/neutron_plugins/ovs_base
source $TOP_DIR/lib/neutron_plugins/openvswitch_agent
source $NETWORKING_OVN_DIR/devstack/override-defaults
source $NETWORKING_OVN_DIR/devstack/network_utils.sh

# NOTE(rtheis): Function copied from DevStack _neutron_ovs_base_setup_bridge
# and _neutron_ovs_base_add_bridge with the call to neutron-ovs-cleanup
# removed. The call is not relevant for OVN, as it is specific to the use
# of Neutron's OVS agent and hangs when running stack.sh because
# neutron-ovs-cleanup uses the OVSDB native interface.
function ovn_base_setup_bridge {
    local bridge=$1
    local addbr_cmd="ovs-vsctl --no-wait -- --may-exist add-br $bridge"

    if [ "$OVS_DATAPATH_TYPE" != "system" ] ; then
        addbr_cmd="$addbr_cmd -- set Bridge $bridge datapath_type=${OVS_DATAPATH_TYPE}"
    fi

    $addbr_cmd
    ovs-vsctl --no-wait br-set-external-id $bridge bridge-id $bridge
}

function _ovn_run_process {
    local service=$1
    local cmd="$2"
    local group=$3
    local user=${4:-$STACK_USER}

    local systemd_service="devstack@$service.service"
    local unit_file="$SYSTEMD_DIR/$systemd_service"
    local environment="OVS_RUNDIR=$OVS_RUNDIR OVS_DBDIR=$OVS_DATADIR OVS_LOGDIR=$LOGDIR"

    echo "Starting $service executed command": $cmd

    write_user_unit_file $systemd_service "$cmd" "$group" "$user"
    iniset -sudo $unit_file "Service" "Type" "forking"
    iniset -sudo $unit_file "Service" "RemainAfterExit" "yes"
    iniset -sudo $unit_file "Service" "KillMode" "mixed"
    iniset -sudo $unit_file "Service" "LimitNOFILE" "65536"
    iniset -sudo $unit_file "Service" "Environment" "$environment"

    $SYSTEMCTL daemon-reload
    $SYSTEMCTL enable $systemd_service
    $SYSTEMCTL restart $systemd_service

    local testcmd="test -e $OVS_RUNDIR/$service.pid"
    test_with_retry "$testcmd" "$service did not start" $SERVICE_TIMEOUT 1
    sudo ovs-appctl -t $service vlog/set console:off syslog:info file:info
}


# Entry Points
# ------------

# cleanup_ovn() - Remove residual data files, anything left over from previous
# runs that a clean run would need to clean up
function cleanup_ovn {
    local _pwd=$(pwd)
    cd $DEST/$OVN_REPO_NAME
    sudo make uninstall
    sudo make distclean
    cd $_pwd
}

# configure_ovn() - Set config files, create data dirs, etc
function configure_ovn {
    echo "Configuring OVN"

    if [ -z "$OVN_UUID" ] ; then
        if [ -f ./ovn-uuid ] ; then
            OVN_UUID=$(cat ovn-uuid)
        else
            OVN_UUID=$(uuidgen)
            echo $OVN_UUID > ovn-uuid
        fi
    fi

    # Metadata
    if is_service_enabled networking-ovn-metadata-agent; then
        sudo install -d -o $STACK_USER $NEUTRON_CONF_DIR

        configure_neutron_rootwrap

        mkdir -p $NETWORKING_OVN_DIR/etc/neutron/plugins/ml2
        (cd $NETWORKING_OVN_DIR && exec ./tools/generate_config_file_samples.sh)

        cp $NETWORKING_OVN_DIR/etc/networking_ovn_metadata_agent.ini.sample $OVN_META_CONF
        configure_root_helper_options $OVN_META_CONF

        iniset $OVN_META_CONF DEFAULT debug $ENABLE_DEBUG_LOG_LEVEL
        iniset $OVN_META_CONF DEFAULT nova_metadata_host $SERVICE_HOST
        iniset $OVN_META_CONF DEFAULT metadata_workers $API_WORKERS
        iniset $OVN_META_CONF DEFAULT state_path $NEUTRON_STATE_PATH
        iniset $OVN_META_CONF ovs ovsdb_connection unix:$OVS_RUNDIR/db.sock
        iniset $OVN_META_CONF ovn ovn_sb_connection $OVN_SB_REMOTE
    fi
}

function configure_ovn_plugin {
    echo "Configuring Neutron for OVN"

    if is_service_enabled q-svc ; then
        # NOTE(arosen) needed for tempest
        export NETWORK_API_EXTENSIONS=$(python -c \
            'from networking_ovn.common import extensions ;\
             print ",".join(extensions.ML2_SUPPORTED_API_EXTENSIONS)')
        export NETWORK_API_EXTENSIONS=$NETWORK_API_EXTENSIONS,$(python -c \
            'from networking_ovn.common import extensions ;\
             print ",".join(extensions.ML2_SUPPORTED_API_EXTENSIONS_OVN_L3)')
        populate_ml2_config /$Q_PLUGIN_CONF_FILE ml2_type_geneve max_header_size=$OVN_GENEVE_OVERHEAD
        populate_ml2_config /$Q_PLUGIN_CONF_FILE ovn ovn_nb_connection="$OVN_NB_REMOTE"
        populate_ml2_config /$Q_PLUGIN_CONF_FILE ovn ovn_sb_connection="$OVN_SB_REMOTE"
        populate_ml2_config /$Q_PLUGIN_CONF_FILE ovn neutron_sync_mode="$OVN_NEUTRON_SYNC_MODE"
        populate_ml2_config /$Q_PLUGIN_CONF_FILE ovn ovn_l3_scheduler="$OVN_L3_SCHEDULER"
        populate_ml2_config /$Q_PLUGIN_CONF_FILE securitygroup enable_security_group="$Q_USE_SECGROUP"
        inicomment /$Q_PLUGIN_CONF_FILE securitygroup firewall_driver

        if is_service_enabled networking-ovn-metadata-agent; then
            populate_ml2_config /$Q_PLUGIN_CONF_FILE ovn ovn_metadata_enabled=True
        else
            populate_ml2_config /$Q_PLUGIN_CONF_FILE ovn ovn_metadata_enabled=False
        fi
    fi

    if is_service_enabled q-dhcp ; then
        die $LINENO "The q-dhcp service must be disabled with OVN."
    fi
    iniset $NEUTRON_CONF DEFAULT dhcp_agent_notification False

    if is_service_enabled q-l3 ; then
        die $LINENO "The q-l3 service must be disabled with OVN."
    fi

    # NOTE(rtheis): OVN currently lacks support for metadata so enabling
    # config drive is required to provide metadata to instances.
    if is_service_enabled n-api-meta ; then
        if is_service_enabled networking-ovn-metadata-agent ; then
            iniset $NOVA_CONF neutron service_metadata_proxy True
        else
            iniset $NOVA_CONF DEFAULT force_config_drive True
        fi
    fi
}

# init_ovn() - Initialize databases, etc.
function init_ovn {
    # clean up from previous (possibly aborted) runs
    # create required data files

    # Assumption: this is a dedicated test system and there is nothing important
    # in the ovn, ovn-nb, or ovs databases.  We're going to trash them and
    # create new ones on each devstack run.

    mkdir -p $OVS_DATADIR

    rm -f $OVS_DATADIR/*.db
    rm -f $OVS_DATADIR/.*.db.~lock~
}

# install_ovn() - Collect source and prepare
function install_ovn {
    echo "Installing OVN and dependent packages"

    # If OVS is already installed, remove it, because we're about to re-install
    # it from source.
    for package in openvswitch openvswitch-switch openvswitch-common; do
        if is_package_installed $package ; then
            uninstall_package $package
        fi
    done

    if ! is_neutron_enabled ; then
        # NOTE(rtheis): networking-ovn depends on neutron, so ensure it at
        # least gets installed and its configuration directory exists (which
        # is needed by the multinode job).
        install_neutron
        sudo install -d -o $STACK_USER $NEUTRON_CONF_DIR
    fi

    # Install tox, used to generate the config (see devstack/override-defaults)
    pip_install tox
    source $NEUTRON_DIR/devstack/lib/ovs
    remove_ovs_packages
    sudo rm -f $OVS_RUNDIR/*

    compile_ovs $OVN_BUILD_MODULES

    sudo mkdir -p $OVS_RUNDIR
    sudo chown $(whoami) $OVS_RUNDIR
    sudo mkdir -p $OVS_PREFIX/var/log/openvswitch
    sudo chown $(whoami) $OVS_PREFIX/var/log/openvswitch

    # Archive log files and create new
    local log_archive_dir=$LOGDIR/archive
    mkdir -p $log_archive_dir
    for logfile in ovs-vswitchd.log ovn-northd.log ovn-controller.log ovn-controller-vtep.log ovs-vtep.log ovsdb-server.log ovsdb-server-nb.log ovsdb-server-sb.log; do
        if [ -f "$LOGDIR/$logfile" ] ; then
            mv "$LOGDIR/$logfile"  "$log_archive_dir/$logfile.${CURRENT_LOG_TIME}"
        fi
    done

    # Install ovsdbapp from source if requested
    if use_library_from_git "ovsdbapp"; then
        git_clone_by_name "ovsdbapp"
        setup_dev_lib "ovsdbapp"
    fi

    setup_develop $DEST/networking-ovn

    # Install ovs python module from ovs source.
    if [[ "$OVN_INSTALL_OVS_PYTHON_MODULE" == "True" ]]; then
        sudo pip uninstall -y ovs
        sudo pip install -e $DEST/$OVS_REPO_NAME/python
    fi
}

function start_ovs {
    echo "Starting OVS"
    if is_service_enabled ovn-controller || is_service_enabled ovn-controller-vtep ; then
        # ovsdb-server and ovs-vswitchd are used privately in OVN as openvswitch service names.
        enable_service ovsdb-server
        enable_service ovs-vswitchd

        ovsdb-tool create $OVS_DATADIR/conf.db $OVS_SHAREDIR/vswitch.ovsschema
        if is_service_enabled ovn-controller-vtep; then
            ovsdb-tool create $OVS_DATADIR/vtep.db $OVS_SHAREDIR/vtep.ovsschema
        fi

        local dbcmd="$OVS_SBINDIR/ovsdb-server --remote=punix:$OVS_RUNDIR/db.sock --pidfile --detach --log-file"
        dbcmd+=" --remote=db:Open_vSwitch,Open_vSwitch,manager_options"
        if is_service_enabled ovn-controller-vtep; then
            dbcmd+=" --remote=db:hardware_vtep,Global,managers $OVS_DATADIR/vtep.db"
        fi
        dbcmd+=" $OVS_DATADIR/conf.db"
        _ovn_run_process ovsdb-server "$dbcmd"

        echo "Configuring OVSDB"
        ovs-vsctl --no-wait set open_vswitch . system-type="devstack"
        ovs-vsctl --no-wait set open_vswitch . external-ids:system-id="$OVN_UUID"
        ovs-vsctl --no-wait set open_vswitch . external-ids:ovn-remote="$OVN_SB_REMOTE"
        ovs-vsctl --no-wait set open_vswitch . external-ids:ovn-bridge="br-int"
        ovs-vsctl --no-wait set open_vswitch . external-ids:ovn-encap-type="geneve,vxlan"
        ovs-vsctl --no-wait set open_vswitch . external-ids:ovn-encap-ip="$HOST_IP"
        # Select this chassis to host gateway routers
        if [[ "$ENABLE_CHASSIS_AS_GW" == "True" ]]; then
            ovs-vsctl --no-wait set open_vswitch . external-ids:ovn-cms-options="enable-chassis-as-gw"
        fi

        ovn_base_setup_bridge br-int
        ovs-vsctl --no-wait set bridge br-int fail-mode=secure other-config:disable-in-band=true

        local ovscmd="$OVS_SBINDIR/ovs-vswitchd --log-file --pidfile --detach"
        _ovn_run_process ovs-vswitchd "$ovscmd" "$STACK_USER" "root"

        if is_provider_network || [[ $Q_USE_PROVIDERNET_FOR_PUBLIC == "True" ]]; then
            ovn_base_setup_bridge $OVS_PHYSICAL_BRIDGE
            ovs-vsctl set open . external-ids:ovn-bridge-mappings=${PHYSICAL_NETWORK}:${OVS_PHYSICAL_BRIDGE}
        fi

        if is_service_enabled ovn-controller-vtep ; then
            ovn_base_setup_bridge br-v
            vtep-ctl add-ps br-v
            vtep-ctl set Physical_Switch br-v tunnel_ips=$HOST_IP

            enable_service ovs-vtep
            local vtepcmd="$OVS_SCRIPTDIR/ovs-vtep --log-file --pidfile --detach br-v"
            _ovn_run_process ovs-vtep "$vtepcmd" "$STACK_USER" "root"

            vtep-ctl set-manager tcp:$HOST_IP:6640
        fi
    fi

    cd $_pwd
}

# start_ovn() - Start running processes, including screen
function start_ovn {
    echo "Starting OVN"

    if is_service_enabled ovn-northd ; then
        local cmd="/bin/bash $OVS_SCRIPTDIR/ovn-ctl --no-monitor start_northd"

        _ovn_run_process ovn-northd "$cmd"
        ovn-nbctl --db=unix:$OVS_RUNDIR/ovnnb_db.sock set-connection ptcp:6641:0.0.0.0 -- set connection . inactivity_probe=60000
        ovn-sbctl --db=unix:$OVS_RUNDIR/ovnsb_db.sock set-connection ptcp:6642:0.0.0.0 -- set connection . inactivity_probe=60000
        sudo ovs-appctl -t $OVS_RUNDIR/ovnnb_db.ctl vlog/set console:off syslog:info file:info
        sudo ovs-appctl -t $OVS_RUNDIR/ovnsb_db.ctl vlog/set console:off syslog:info file:info
    fi

    if is_service_enabled ovn-controller ; then
        local cmd="/bin/bash $OVS_SCRIPTDIR/ovn-ctl --no-monitor start_controller"

        _ovn_run_process ovn-controller "$cmd" "$STACK_USER" "root"
    fi

    if is_service_enabled ovn-controller-vtep ; then
        local cmd="$OVS_BINDIR/ovn-controller-vtep --log-file --pidfile --detach --ovnsb-db=$OVN_SB_REMOTE"

        _ovn_run_process ovn-controller-vtep "$cmd" "$STACK_USER" "root"
    fi

    if is_service_enabled networking-ovn-metadata-agent; then
        run_process networking-ovn-metadata-agent "$NETWORKING_OVN_BIN_DIR/$NETWORKING_OVN_METADATA_BINARY --config-file $OVN_META_CONF"
        # Format logging
        setup_logging $OVN_META_CONF
    fi

    if is_service_enabled br-ex-tcpdump ; then
        # tcpdump monitor on br-ex for ARP, reverse ARP and ICMP v4 / v6 packets
        sudo ip link set dev $PUBLIC_BRIDGE up
        run_process br-ex-tcpdump "/usr/sbin/tcpdump -i $PUBLIC_BRIDGE arp or rarp or icmp or icmp6 -enlX" $STACK_USER root
    fi

    if is_service_enabled br-int-flows ; then
        run_process br-int-flows "/bin/sh -c \"set +e; while true; do echo ovs-ofctl dump-flows br-int; ovs-ofctl dump-flows br-int ; sleep 30; done; \"" $STACK_USER root
    fi
}

# stop_ovn() - Stop running processes (non-screen)
function stop_ovn {
    if is_service_enabled networking-ovn-metadata-agent; then
        sudo pkill -9 -f haproxy || :
        stop_process networking-ovn-metadata-agent
    fi
    if is_service_enabled ovn-controller-vtep ; then
        stop_process ovn-controller-vtep
    fi
    if is_service_enabled ovn-controller ; then
        stop_process ovn-controller
    fi
    if is_service_enabled ovn-northd ; then
        stop_process ovn-northd
    fi
    if is_service_enabled ovs-vtep ; then
        stop_process ovs-vtep
    fi
    if is_service_enabled ovs-vswitchd ; then
        stop_process ovs-vswitchd
    fi
    if is_service_enabled ovsdb-server ; then
        stop_process ovsdb-server
    fi
}

# stop_ovs_dp() - Stop OVS datapath
function stop_ovs_dp {
    sudo ovs-dpctl dump-dps | sudo xargs -n1 ovs-dpctl del-dp
    sudo rmmod vport_geneve
    sudo rmmod vport_vxlan
    sudo rmmod openvswitch
}

function disable_libvirt_apparmor {
    if ! sudo aa-status --enabled ; then
        return 0
    fi
    # NOTE(arosen): This is used as a work around to allow newer versions
    # of libvirt to work with ovs configured ports. See LP#1466631.
    # requires the apparmor-utils
    install_package apparmor-utils
    # disables apparmor for libvirtd
    sudo aa-complain /etc/apparmor.d/usr.sbin.libvirtd
}

function create_public_bridge {
    # Create the public bridge that OVN will use
    # This logic is based on the devstack neutron-legacy _neutron_configure_router_v4 and _v6
    local ext_gw_ifc
    ext_gw_ifc=$(get_ext_gw_interface)

    ovs-vsctl --may-exist add-br $ext_gw_ifc -- set bridge $ext_gw_ifc protocols=OpenFlow13
    ovs-vsctl set open . external-ids:ovn-bridge-mappings=$PHYSICAL_NETWORK:$ext_gw_ifc
    if [ -n "$FLOATING_RANGE" ]; then
        local cidr_len=${FLOATING_RANGE#*/}
        sudo ip addr add $PUBLIC_NETWORK_GATEWAY/$cidr_len dev $ext_gw_ifc
    fi

    # Ensure IPv6 RAs are accepted on the interface with the default route.
    # This is needed for neutron-based devstack clouds to work in
    # IPv6-only clouds in the gate. Please do not remove this without
    # talking to folks in Infra. This fix is based on a devstack fix for
    # neutron L3 agent: https://review.openstack.org/#/c/359490/.
    default_route_dev=$(ip route | grep ^default | awk '{print $5}')
    sudo sysctl -w net.ipv6.conf.$default_route_dev.accept_ra=2

    sudo sysctl -w net.ipv6.conf.all.forwarding=1
    if [ -n "$IPV6_PUBLIC_RANGE" ]; then
        local ipv6_cidr_len=${IPV6_PUBLIC_RANGE#*/}
        sudo ip -6 addr add $IPV6_PUBLIC_NETWORK_GATEWAY/$ipv6_cidr_len dev $ext_gw_ifc
        # NOTE(numans): Commenting the below code for now as this is breaking
        # the CI after xenial upgrade.
        # https://bugs.launchpad.net/networking-ovn/+bug/1648670
        # sudo ip -6 route replace $FIXED_RANGE_V6 via $IPV6_PUBLIC_NETWORK_GATEWAY dev $ext_gw_ifc
    fi

    sudo ip link set $ext_gw_ifc up
}

# Restore xtrace
$_XTRACE_NETWORKING_OVN
