# lib/quantum
# functions - funstions specific to quantum

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


# Quantum Networking
# ------------------

# Make sure that quantum is enabled in ``ENABLED_SERVICES``.  If you want
# to run Quantum on this host, make sure that q-svc is also in
# ``ENABLED_SERVICES``.
#
# If you're planning to use the Quantum openvswitch plugin, set
# ``Q_PLUGIN`` to "openvswitch" and make sure the q-agt service is enabled
# in ``ENABLED_SERVICES``.  If you're planning to use the Quantum
# linuxbridge plugin, set ``Q_PLUGIN`` to "linuxbridge" and make sure the
# q-agt service is enabled in ``ENABLED_SERVICES``.
#
# See "Quantum Network Configuration" below for additional variables
# that must be set in localrc for connectivity across hosts with
# Quantum.
#
# With Quantum networking the NET_MAN variable is ignored.


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


# Defaults
# --------

# Set up default directories
QUANTUM_DIR=$DEST/quantum
QUANTUMCLIENT_DIR=$DEST/python-quantumclient
QUANTUM_AUTH_CACHE_DIR=${QUANTUM_AUTH_CACHE_DIR:-/var/cache/quantum}

QUANTUM_CONF_DIR=/etc/quantum
QUANTUM_CONF=$QUANTUM_CONF_DIR/quantum.conf
export QUANTUM_TEST_CONFIG_FILE=${QUANTUM_TEST_CONFIG_FILE:-"$QUANTUM_CONF_DIR/debug.ini"}

# Default Quantum Plugin
Q_PLUGIN=${Q_PLUGIN:-openvswitch}
# Default Quantum Port
Q_PORT=${Q_PORT:-9696}
# Default Quantum Host
Q_HOST=${Q_HOST:-$HOST_IP}
# Which Quantum API nova should use
# Default admin username
Q_ADMIN_USERNAME=${Q_ADMIN_USERNAME:-quantum}
# Default auth strategy
Q_AUTH_STRATEGY=${Q_AUTH_STRATEGY:-keystone}
# Use namespace or not
Q_USE_NAMESPACE=${Q_USE_NAMESPACE:-True}
Q_USE_ROOTWRAP=${Q_USE_ROOTWRAP:-True}
# Meta data IP
Q_META_DATA_IP=${Q_META_DATA_IP:-$HOST_IP}
# Use quantum-debug command
Q_USE_DEBUG_COMMAND=${Q_USE_DEBUG_COMMAND:-False}

if is_service_enabled quantum; then
    Q_RR_CONF_FILE=$QUANTUM_CONF_DIR/rootwrap.conf
    if [[ "$Q_USE_ROOTWRAP" == "False" ]]; then
        Q_RR_COMMAND="sudo"
    else
        QUANTUM_ROOTWRAP=$(get_rootwrap_location quantum)
        Q_RR_COMMAND="sudo $QUANTUM_ROOTWRAP $Q_RR_CONF_FILE"
    fi
fi


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

# configure_quantum_rootwrap() - configure Quantum's rootwrap
function configure_quantum_rootwrap() {
    if [[ "$Q_USE_ROOTWRAP" == "False" ]]; then
        return
    fi
    # Deploy new rootwrap filters files (owned by root).
    # Wipe any existing rootwrap.d files first
    Q_CONF_ROOTWRAP_D=$QUANTUM_CONF_DIR/rootwrap.d
    if [[ -d $Q_CONF_ROOTWRAP_D ]]; then
        sudo rm -rf $Q_CONF_ROOTWRAP_D
    fi
    # Deploy filters to $QUANTUM_CONF_DIR/rootwrap.d
    mkdir -p -m 755 $Q_CONF_ROOTWRAP_D
    cp -pr $QUANTUM_DIR/etc/quantum/rootwrap.d/* $Q_CONF_ROOTWRAP_D/
    sudo chown -R root:root $Q_CONF_ROOTWRAP_D
    sudo chmod 644 $Q_CONF_ROOTWRAP_D/*
    # Set up rootwrap.conf, pointing to $QUANTUM_CONF_DIR/rootwrap.d
    sudo cp -p $QUANTUM_DIR/etc/rootwrap.conf $Q_RR_CONF_FILE
    sudo sed -e "s:^filters_path=.*$:filters_path=$Q_CONF_ROOTWRAP_D:" -i $Q_RR_CONF_FILE
    sudo chown root:root $Q_RR_CONF_FILE
    sudo chmod 0644 $Q_RR_CONF_FILE
    # Specify rootwrap.conf as first parameter to quantum-rootwrap
    ROOTWRAP_SUDOER_CMD="$QUANTUM_ROOTWRAP $Q_RR_CONF_FILE *"

    # Set up the rootwrap sudoers for quantum
    TEMPFILE=`mktemp`
    echo "$USER ALL=(root) NOPASSWD: $ROOTWRAP_SUDOER_CMD" >$TEMPFILE
    chmod 0440 $TEMPFILE
    sudo chown root:root $TEMPFILE
    sudo mv $TEMPFILE /etc/sudoers.d/quantum-rootwrap
}

# Configures keystone integration for quantum service and agents
function quantum_setup_keystone() {
    local conf_file=$1
    local section=$2
    local use_auth_url=$3
    if [[ -n $use_auth_url ]]; then
        iniset $conf_file $section auth_url "$KEYSTONE_SERVICE_PROTOCOL://$KEYSTONE_AUTH_HOST:$KEYSTONE_AUTH_PORT/v2.0"
    else
        iniset $conf_file $section auth_host $KEYSTONE_SERVICE_HOST
        iniset $conf_file $section auth_port $KEYSTONE_AUTH_PORT
        iniset $conf_file $section auth_protocol $KEYSTONE_SERVICE_PROTOCOL
    fi
    iniset $conf_file $section admin_tenant_name $SERVICE_TENANT_NAME
    iniset $conf_file $section admin_user $Q_ADMIN_USERNAME
    iniset $conf_file $section admin_password $SERVICE_PASSWORD
    iniset $conf_file $section signing_dir $QUANTUM_AUTH_CACHE_DIR
    # Create cache dir
    sudo mkdir -p $QUANTUM_AUTH_CACHE_DIR
    sudo chown `whoami` $QUANTUM_AUTH_CACHE_DIR
}

function quantum_setup_ovs_bridge() {
    local bridge=$1
    for PORT in `sudo ovs-vsctl --no-wait list-ports $bridge`; do
        if [[ "$PORT" =~ tap* ]]; then echo `sudo ip link delete $PORT` > /dev/null; fi
        sudo ovs-vsctl --no-wait del-port $bridge $PORT
    done
    sudo ovs-vsctl --no-wait -- --if-exists del-br $bridge
    sudo ovs-vsctl --no-wait add-br $bridge
    sudo ovs-vsctl --no-wait br-set-external-id $bridge bridge-id $bridge
}

function quantum_setup_external_bridge() {
    local bridge=$1
    # Create it if it does not exist
    sudo ovs-vsctl --no-wait -- --may-exist add-br $bridge
    # remove internal ports
    for PORT in `sudo ovs-vsctl --no-wait list-ports $bridge`; do
        TYPE=$(sudo ovs-vsctl get interface $PORT type)
        if [[ "$TYPE" == "internal" ]]; then
            echo `sudo ip link delete $PORT` > /dev/null
            sudo ovs-vsctl --no-wait del-port $bridge $PORT
        fi
    done
    # ensure no IP is configured on the public bridge
    sudo ip addr flush dev $bridge
}

function is_quantum_ovs_base_plugin() {
    local plugin=$1
    if [[ ",openvswitch,ryu," =~ ,${plugin}, ]]; then
        return 0
    fi
    return 1
}

function _get_net_id() {
    quantum --os-tenant-name admin --os-username admin --os-password $ADMIN_PASSWORD net-list | grep $1 | awk '{print $2}'
}

function _get_probe_cmd_prefix() {
    local from_net="$1"
    net_id=`_get_net_id $from_net`
    probe_id=`quantum-debug --os-tenant-name admin --os-username admin --os-password $ADMIN_PASSWORD probe-list -c id -c network_id | grep $net_id | awk '{print $2}' | head -n 1`
    echo "$Q_RR_COMMAND ip netns exec qprobe-$probe_id"
}

function delete_probe() {
    local from_net="$1"
    net_id=`_get_net_id $from_net`
    probe_id=`quantum-debug --os-tenant-name admin --os-username admin --os-password $ADMIN_PASSWORD probe-list -c id -c network_id | grep $net_id | awk '{print $2}'`
    quantum-debug --os-tenant-name admin --os-username admin probe-delete $probe_id
}

function _ping_check_quantum() {
    local from_net=$1
    local ip=$2
    local timeout_sec=$3
    local expected=${4:-"True"}
    local check_command=""
    probe_cmd=`_get_probe_cmd_prefix $from_net`
    if [[ "$expected" = "True" ]]; then
        check_command="while ! $probe_cmd ping -w 1 -c 1 $ip; do sleep 1; done"
    else
        check_command="while $probe_cmd ping -w 1 -c 1 $ip; do sleep 1; done"
    fi
    if ! timeout $timeout_sec sh -c "$check_command"; then
        if [[ "$expected" = "True" ]]; then
            echo "[Fail] Couldn't ping server"
        else
            echo "[Fail] Could ping server"
        fi
        exit 1
    fi
}

# ssh check
function _ssh_check_quantum() {
    local from_net=$1
    local key_file=$2
    local ip=$3
    local user=$4
    local timeout_sec=$5
    local probe_cmd = ""
    probe_cmd=`_get_probe_cmd_prefix $from_net`
    if ! timeout $timeout_sec sh -c "while ! $probe_cmd ssh -o StrictHostKeyChecking=no -i $key_file ${user}@$ip echo success ; do sleep 1; done"; then
        echo "server didn't become ssh-able!"
        exit 1
    fi
}

function setup_quantum() {
    public_net_id=`_get_net_id $PUBLIC_NETWORK_NAME`
    quantum-debug --os-tenant-name admin --os-username admin --os-password $ADMIN_PASSWORD probe-create $public_net_id
    private_net_id=`_get_net_id $PRIVATE_NETWORK_NAME`
    quantum-debug --os-tenant-name admin --os-username admin --os-password $ADMIN_PASSWORD probe-create $private_net_id
}

function teardown_quantum() {
    delete_probe $PUBLIC_NETWORK_NAME
    delete_probe $PRIVATE_NETWORK_NAME
}

# Restore xtrace
$XTRACE