#! /bin/sh
# PCP QA Test No. 662
# Exercises REST API functionality using python requests module
#
# Copyright (c) 2013-2015,2019 Red Hat.
#
# Debugging note:
# 1. touch 662.wait
# 2. ./662
# 3. when pmproxy is setup, the test will wait for 662.wait to be
#    removed, giving time to poke pmproxy, attach gdb, whatever
#    before the test resumes
#
seq=`basename $0`
echo "QA output created by $seq"

. ./common.python

_check_series

signal=$PCP_BINADM_DIR/pmsignal
status=1	# failure is the default!
hostname=`hostname`
machineid=`_machine_id`
domainname=`_domain_name`
need_restore=true

# only stop pmproxy if it was not running before the QA test starts
if [ -n "`_get_pids_by_name pmproxy`" ]
then
    pmproxy_was_running=true
else
    pmproxy_was_running=false
fi
echo "pmproxy_was_running=$pmproxy_was_running" >>$seq_full

_cleanup()
{
    cd $here
    if $need_restore
    then
	need_restore=false
	$sudo rm -rf $PCP_ETC_DIR/pcp/labels/*
	_restore_config $PCP_ETC_DIR/pcp/labels
	_sighup_pmcd
    fi
    _restore_auto_restart pmproxy
    $pmproxy_was_running && _service pmproxy restart >>$seq_full 2>&1
    $sudo rm -f $tmp.*
}

trap "_cleanup; exit \$status" 0 1 2 3 15

_filter_labels()
{
    sed \
	-e "s/domainname=.${domainname}./domainname=\"DOMAIN\"/g" \
	-e "s/machineid=.${machineid}./machineid=\"MACHINE\"/g" \
	-e "s/hostname=.${hostname}./hostname=\"HOSTNAME\"/g" \
    #end
}

# real test starts here
_save_config $PCP_ETC_DIR/pcp/labels
$sudo rm -rf $PCP_ETC_DIR/pcp/labels/*
_sighup_pmcd || _exit 1

# make the same derived metrics available between the processes
# being compared (pminfo is run within test_webapi.py, which is
# affected by this (qa/common unsets this).
#
PCP_DERIVED_CONFIG="$PCP_VAR_DIR/config/derived"; export PCP_DERIVED_CONFIG

if ! _service pmproxy restart >/dev/null 2>&1; then _exit 1; fi
_wait_for_pmproxy || _exit 1

echo "+++ pmproxy before test_webapi.py ..." >>$seq_full
_ps_full_by_name pmproxy >>$seq_full

_triage_wait_point "pmproxy PID `_get_pids_by_name pmproxy` started."

$python $here/src/test_webapi.py | _webapi_response_filter | _filter_labels
echo "+++ pmproxy after test_webapi.py ..." >>$seq_full
_ps_full_by_name pmproxy >>$seq_full

# metrics from src/test_webapi.py are enumerated in these files
# webapi-host and webapi-pmcd-host, and
# webapi-host-kernel and webapi-pmcd-host-kernel
#
# help triage by checking lists of metrics ...
#
LC_COLLATE=POSIX; export LC_COLLATE
echo "+++ webapi-host vs webapi-pmcd-host diffs ..." >>$seq_full
sed -e 's/ \[.*//' <webapi-pmcd-host | sort >$tmp.tmp
sort webapi-host | diff $tmp.tmp - >>$seq_full
echo "+++ webapi-host-kernel vs webapi-pmcd-host-kernel diffs ..." >>$seq_full
sed -e 's/ \[.*//' <webapi-pmcd-host-kernel | sort >$tmp.tmp
sort webapi-host-kernel | diff $tmp.tmp - >>$seq_full

echo >>$seq_full
echo "=== pmproxy log ===" >>$seq_full
cat $PCP_LOG_DIR/pmproxy/pmproxy.log >>$seq_full

status=0
exit
