Add Docker FV tests for metric gathering (#90)

* initial metric tests

* Add FV tests for metrics

* correct comment in test
This commit is contained in:
Rob Parker
2018-05-25 13:09:48 +01:00
committed by Stephen Marshall
parent 91e20f0f98
commit 531f2710c7
6 changed files with 550 additions and 59 deletions

View File

@@ -0,0 +1,315 @@
/*
© Copyright IBM Corporation 2018
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.
*/
package main
import (
"strings"
"testing"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
)
func TestGoldenPathMetric(t *testing.T) {
t.Parallel()
cli, err := client.NewEnvClient()
if err != nil {
t.Fatal(err)
}
containerConfig := container.Config{
Env: []string{
"LICENSE=accept",
"MQ_QMGR_NAME=qm1",
"MQ_ENABLE_METRICS=true",
},
}
id := runContainer(t, cli, &containerConfig)
defer cleanContainer(t, cli, id)
hostname := getIPAddress(t, cli, id)
port := DEFAULT_METRIC_PORT
// Now the container is ready we prod the prometheus endpoint until it's up.
waitForMetricReady(hostname, port)
// Call once as mq_prometheus 'ignores' the first call and will not return any metrics
_, err = getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
time.Sleep(15 * time.Second)
metrics, err := getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
if len(metrics) <= 0 {
t.Log("Expected some metrics to be returned but had none...")
t.Fail()
}
// Stop the container cleanly
stopContainer(t, cli, id)
}
func TestMetricNames(t *testing.T) {
t.Parallel()
approvedSuffixes := []string{"bytes", "seconds", "percentage", "count", "total"}
cli, err := client.NewEnvClient()
if err != nil {
t.Fatal(err)
}
containerConfig := container.Config{
Env: []string{
"LICENSE=accept",
"MQ_QMGR_NAME=qm1",
"MQ_ENABLE_METRICS=true",
},
}
id := runContainer(t, cli, &containerConfig)
defer cleanContainer(t, cli, id)
hostname := getIPAddress(t, cli, id)
port := DEFAULT_METRIC_PORT
// Now the container is ready we prod the prometheus endpoint until it's up.
waitForMetricReady(hostname, port)
// Call once as mq_prometheus 'ignores' the first call
_, err = getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
time.Sleep(15 * time.Second)
metrics, err := getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
if len(metrics) <= 0 {
t.Log("Expected some metrics to be returned but had none...")
t.Fail()
}
okMetrics := []string{}
badMetrics := []string{}
for _, metric := range metrics {
ok := false
for _, e := range approvedSuffixes {
if strings.HasSuffix(metric.Key, e) {
ok = true
break
}
}
if !ok {
t.Logf("Metric '%s' does not have an approved suffix", metric.Key)
badMetrics = append(badMetrics, metric.Key)
t.Fail()
} else {
okMetrics = append(okMetrics, metric.Key)
}
}
// Stop the container cleanly
stopContainer(t, cli, id)
}
func TestMetricLabels(t *testing.T) {
t.Parallel()
requiredLabels := []string{"qmgr"}
cli, err := client.NewEnvClient()
if err != nil {
t.Fatal(err)
}
containerConfig := container.Config{
Env: []string{
"LICENSE=accept",
"MQ_QMGR_NAME=qm1",
"MQ_ENABLE_METRICS=true",
},
}
id := runContainer(t, cli, &containerConfig)
defer cleanContainer(t, cli, id)
hostname := getIPAddress(t, cli, id)
port := DEFAULT_METRIC_PORT
// Now the container is ready we prod the prometheus endpoint until it's up.
waitForMetricReady(hostname, port)
// Call once as mq_prometheus 'ignores' the first call
_, err = getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
time.Sleep(15 * time.Second)
metrics, err := getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
if len(metrics) <= 0 {
t.Log("Expected some metrics to be returned but had none...")
t.Fail()
}
for _, metric := range metrics {
found := false
for key := range metric.Labels {
for _, e := range requiredLabels {
if key == e {
found = true
break
}
}
if found {
break
}
}
if !found {
t.Logf("Metric '%s' with labels %s does not have one or more required labels - %s", metric.Key, metric.Labels, requiredLabels)
t.Fail()
}
}
// Stop the container cleanly
stopContainer(t, cli, id)
}
func TestRapidFirePrometheus(t *testing.T) {
t.Parallel()
cli, err := client.NewEnvClient()
if err != nil {
t.Fatal(err)
}
containerConfig := container.Config{
Env: []string{
"LICENSE=accept",
"MQ_QMGR_NAME=qm1",
"MQ_ENABLE_METRICS=true",
},
}
id := runContainer(t, cli, &containerConfig)
defer cleanContainer(t, cli, id)
hostname := getIPAddress(t, cli, id)
port := DEFAULT_METRIC_PORT
// Now the container is ready we prod the prometheus endpoint until it's up.
waitForMetricReady(hostname, port)
// Call once as mq_prometheus 'ignores' the first call and will not return any metrics
_, err = getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
// Rapid fire it then check we're still happy
for i := 0; i < 30; i++ {
_, err := getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
time.Sleep(1 * time.Second)
}
time.Sleep(11 * time.Second)
metrics, err := getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
if len(metrics) <= 0 {
t.Log("Expected some metrics to be returned but had none...")
t.Fail()
}
// Stop the container cleanly
stopContainer(t, cli, id)
}
func TestSlowPrometheus(t *testing.T) {
t.Parallel()
cli, err := client.NewEnvClient()
if err != nil {
t.Fatal(err)
}
containerConfig := container.Config{
Env: []string{
"LICENSE=accept",
"MQ_QMGR_NAME=qm1",
"MQ_ENABLE_METRICS=true",
},
}
id := runContainer(t, cli, &containerConfig)
defer cleanContainer(t, cli, id)
hostname := getIPAddress(t, cli, id)
port := DEFAULT_METRIC_PORT
// Now the container is ready we prod the prometheus endpoint until it's up.
waitForMetricReady(hostname, port)
// Call once as mq_prometheus 'ignores' the first call and will not return any metrics
_, err = getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
// Send a request twice over a long period and check we're still happy
for i := 0; i < 2; i++ {
time.Sleep(30 * time.Second)
metrics, err := getMetricsFromEndpoint(hostname, port)
if err != nil {
t.Logf("Failed to call metric endpoint - %v", err)
t.FailNow()
}
if len(metrics) <= 0 {
t.Log("Expected some metrics to be returned but had none...")
t.Fail()
}
}
// Stop the container cleanly
stopContainer(t, cli, id)
}

View File

@@ -0,0 +1,160 @@
/*
© Copyright IBM Corporation 2018
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.
*/
package main
import (
"bufio"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
type MQMETRIC struct {
Key string
Value string
Labels map[string]string
}
const DEFAULT_METRIC_URL = "/metrics"
const DEFAULT_METRIC_PORT = 9157
const DEFAULT_MQ_NAMESPACE = "ibmmq"
func getMetricsFromEndpoint(host string, port int) ([]MQMETRIC, error) {
returned := []MQMETRIC{}
if host == "" {
return returned, fmt.Errorf("Test Error - Host was nil")
}
if port <= 0 {
return returned, fmt.Errorf("Test Error - port was not above 0")
}
urlToUse := fmt.Sprintf("http://%s:%d%s", host, port, DEFAULT_METRIC_URL)
resp, err := http.Get(urlToUse)
if err != nil {
return returned, err
}
defer resp.Body.Close()
metricsRaw, err := ioutil.ReadAll(resp.Body)
if err != nil {
return returned, err
}
return convertRawMetricToMap(string(metricsRaw))
}
// Also filters out all non "ibmmq" metrics
func convertRawMetricToMap(input string) ([]MQMETRIC, error) {
returnList := []MQMETRIC{}
if input == "" {
return returnList, fmt.Errorf("Test Error - Raw metric output was nil")
}
scanner := bufio.NewScanner(strings.NewReader(input))
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "#") {
// Comment line of HELP or TYPE. Ignore
continue
}
if !strings.HasPrefix(line, DEFAULT_MQ_NAMESPACE) {
// Not an ibmmq_ metric. Ignore
continue
}
//It's an IBM MQ metric!
key, value, labelMap, err := convertMetricLineToMetric(line)
if err != nil {
return returnList, fmt.Errorf("ibmmq_ metric could not be deciphered - %v", err)
}
toAdd := MQMETRIC{
Key: key,
Value: value,
Labels: labelMap,
}
returnList = append(returnList, toAdd)
}
return returnList, nil
}
func convertMetricLineToMetric(input string) (string, string, map[string]string, error) {
// Lines are in the form "<key>{<labels>}<value>" or "<key> <value>"
// Get the key and value while skipping the label
var key, value string
labelMap := make(map[string]string)
if strings.Contains(input, "{") {
// Get key
splitted := strings.Split(input, "{")
if len(splitted) != 2 {
return "", "", labelMap, fmt.Errorf("Could not split by { Expected 2 but got %d - %s", len(splitted), input)
}
key = strings.TrimSpace(splitted[0])
// Get value
splitted = strings.Split(splitted[1], "}")
if len(splitted) != 2 {
return "", "", labelMap, fmt.Errorf("Could not split by } Expected 2 but got %d - %s", len(splitted), input)
}
value = strings.TrimSpace(splitted[1])
// Get labels
allLabels := strings.Split(splitted[0], ",")
for _, e := range allLabels {
labelPair := strings.Split(e, "=")
if len(labelPair) != 2 {
return "", "", labelMap, fmt.Errorf("Could not split label by '=' Expected 2 but got %d - %s", len(labelPair), e)
}
lkey := strings.TrimSpace(labelPair[0])
lvalue := strings.TrimSpace(labelPair[1])
lvalue = strings.Trim(lvalue, "\"")
labelMap[lkey] = lvalue
}
} else {
splitted := strings.Split(input, " ")
if len(splitted) != 2 {
return "", "", labelMap, fmt.Errorf("Could not split by ' ' Expected 2 but got %d - %s", len(splitted), input)
}
key = strings.TrimSpace(splitted[0])
value = strings.TrimSpace(splitted[1])
}
return key, value, labelMap, nil
}
func waitForMetricReady(host string, port int) error {
if host == "" {
return fmt.Errorf("Test Error - Host was nil")
}
if port <= 0 {
return fmt.Errorf("Test Error - port was not above 0")
}
timeout := 12 // 12 * 5 = 1 minute
for i := 0; i < timeout; i++ {
urlToUse := fmt.Sprintf("http://%s:%d", host, port)
resp, err := http.Get(urlToUse)
if err == nil {
resp.Body.Close()
return nil
}
time.Sleep(time.Second * 5)
}
return fmt.Errorf("Metric endpoint failed to startup in timely manner")
}