#!/bin/bash

# lib/osprofiler
# Functions to control the configuration and operation of the **OSProfiler**

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


# Defaults
# --------

CONF_FILES=(
    $CINDER_CONF
    $HEAT_CONF
    $KEYSTONE_CONF
    $NOVA_CONF
    $NEUTRON_CONF
    $GLANCE_API_CONF
    $GLANCE_REGISTRY_CONF
    $TROVE_CONF
    $TROVE_CONDUCTOR_CONF
    $TROVE_GUESTAGENT_CONF
    $TROVE_TASKMANAGER_CONF
    $SENLIN_CONF
    $MAGNUM_CONF
    $ZUN_CONF
)

# Add config files of Nova Cells
NOVA_NUM_CELLS=${NOVA_NUM_CELLS:-1}
for i in $(seq 1 ${NOVA_NUM_CELLS}); do
    # call function `conductor_conf` defined in lib/nova to get file name
    conf=$(conductor_conf $i)
    CONF_FILES+=(${conf})
done


# Functions
# ---------

function install_redis() {
    if is_fedora; then
        install_package redis python-redis
    elif is_ubuntu; then
        install_package redis-server python-redis
    elif is_suse; then
        install_package redis python-redis
    else
        exit_distro_not_supported "redis installation"
    fi

    start_service redis
}

function install_osprofiler_collector() {
    if [ -z "$OSPROFILER_COLLECTOR" ]; then
        OSPROFILER_CONNECTION_STRING=${OSPROFILER_CONNECTION_STRING:-"messaging://"}
    elif [ "$OSPROFILER_COLLECTOR" == "redis" ]; then
        install_redis
        OSPROFILER_CONNECTION_STRING=${OSPROFILER_CONNECTION_STRING:-"redis://localhost:6379"}
    else
        die $LINENO "OSProfiler collector $OSPROFILER_COLLECTOR is not supported"
    fi
}

function configure_osprofiler() {

    for conf in ${CONF_FILES[@]}; do
        if [ -f $conf ]
        then
            iniset $conf profiler enabled True
            iniset $conf profiler trace_sqlalchemy True
            iniset $conf profiler hmac_keys $OSPROFILER_HMAC_KEYS
            iniset $conf profiler connection_string $OSPROFILER_CONNECTION_STRING
        fi
    done

    # Insert osprofiler filter into Neutron paste configuration
    if [ -f $Q_API_PASTE_FILE ]; then
        VAL=$(iniget $Q_API_PASTE_FILE composite:neutronapi_v2_0 keystone)
        VAL=${VAL/catch_errors/catch_errors osprofiler}
        iniset $Q_API_PASTE_FILE composite:neutronapi_v2_0 keystone "$VAL"
    fi
}


# Restore xtrace
$XTRACE
