#!/bin/sh
# PCP QA Test No. 1194
# Exercise the Prometheus PMDA auto-refresh metadata.
#
# Copyright (c) 2017 Ronak Jain.  All Rights Reserved.
#

seq=`basename $0`
echo "QA output created by $seq"

. ./common.product
. ./common.filter
. ./common.check
. ./common.python

[ -f $PCP_PMDAS_DIR/prometheus/pmdaprometheus.python ] || _notrun "prometheus pmda not installed"

$python -c "import requests"
[ $? -eq 0 ] || _notrun "python requests module not installed"

$python -c "import prometheus_client"
[ $? -eq 0 ] || _notrun "python prometheus_client module not installed"

_cleanup()
{
    if [ -n "$pid" ]
    then
        kill $pid >/dev/null 2>&1
    fi
    $sudo rm -rf $tmp.* $tmp.*
}

pmdaprometheus_remove()
{
    echo
    echo "=== remove prometheus agent ==="
    $sudo ./Remove >$tmp.out 2>&1
    _filter_pmda_remove <$tmp.out
}

pmdaprometheus_install()
{
    # start from known starting points
    cd $PCP_PMDAS_DIR/prometheus
    $sudo ./Remove >/dev/null 2>&1
    _service pmcd stop 2>&1 | _filter_pcp_stop

    echo
    echo "=== prometheus agent installation ==="
    $sudo ./Install </dev/null >$tmp.out 2>&1
    cat $tmp.out >>$here/$seq.full
}

generate_config()
{
    cd $PCP_PMDAS_DIR/prometheus
    $sudo ./pmdaprometheus.python -g -n "test" -u "http://127.0.0.1:9090"
}

status=1    # failure is the default!
$sudo rm -rf $tmp $tmp.* $seq.full
_prepare_pmda prometheus
trap "_cleanup; _cleanup_pmda prometheus; exit \$status" 0 1 2 3 15

_stop_auto_restart pmcd
_save_config $PCP_PMDAS_DIR/prometheus/metadata
_save_config $PCP_VAR_DIR/config/pmda
$sudo rm -f $PCP_PMDAS_DIR/prometheus/metadata/*
$sudo rm -f $PCP_VAR_DIR/config/pmda/*

# real QA test starts here

$python $here/prometheus/prometheus_client_server.python &
pid=$!
sleep 3 #avoid racing
pmdaprometheus_install

if pminfo -v prometheus > $tmp.info 2> $tmp.err
then
    echo "Installation ok"
else
    echo "Installation failed"
    cat $tmp.out
fi

# Change metadata refresh frequency to 1 second
pmstore prometheus.config.metadata_refresh_frequency 1

# Generate config the source
generate_config

# Trigger metadata update
pminfo -f prometheus > $tmp.info 2> $tmp.err

if pminfo -f prometheus.test.queue_size > $tmp.info 2> $tmp.err
then
    echo "Metadata refresh successful"
    echo "Fetch prometheus.test.queue_size: success"
    pminfo -f prometheus.test.queue_size
else
    echo "Fetch prometheus.test.queue_size: failed"
    cat $tmp.err
fi

if pminfo -f prometheus.test.requests_total > $tmp.info 2> $tmp.err
then
    echo "Metadata refresh successful"
    echo "Fetch prometheus.test.requests_total: success"
else
    echo "Fetch prometheus.test.requests_total: failed"
    cat $tmp.err
fi

pmdaprometheus_remove
_restore_config $PCP_PMDAS_DIR/prometheus/metadata
_restore_config $PCP_VAR_DIR/config/pmda
# success, all done
status=0
exit
