Files
nmon/internal/app/integration_test.go

242 lines
6.8 KiB
Go

//go:build integration
package app_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/v10networks/nmon/internal/app"
"github.com/v10networks/nmon/internal/config"
"github.com/v10networks/nmon/internal/simagent"
"github.com/v10networks/nmon/internal/snmprec"
"github.com/v10networks/nmon/internal/testutil"
"github.com/v10networks/nmon/internal/vmsup"
)
type series struct {
Metric map[string]string `json:"metric"`
Value [2]any `json:"value"`
}
func query(t *testing.T, base, q string) []series {
t.Helper()
resp, err := http.Get(base + "/api/v1/query?q=" + q)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != 200 {
t.Fatalf("query %s: %d %s", q, resp.StatusCode, body)
}
var r struct {
Data struct{ Result []series } `json:"data"`
}
if err := json.Unmarshal(body, &r); err != nil {
t.Fatal(err)
}
return r.Data.Result
}
func TestServeCollectsCountersEndToEnd(t *testing.T) {
rec, err := snmprec.Load("../../testdata/snmprec/counters.snmprec")
if err != nil {
t.Fatal(err)
}
agent := testutil.StartAgent(t, simagent.Config{Recording: rec, Community: "public"})
root := t.TempDir()
data := filepath.Join(root, "data")
a, err := app.Start(context.Background(), config.Flags{
DataDir: data, SecretKeyFile: filepath.Join(root, "keys", "secret.key"), Listen: "[::1]:0", InsecureHTTP: true,
PollInterval: 5 * time.Second, SNMPPort: int(agent.Addr().Port()),
})
if errors.Is(err, vmsup.ErrNoBinary) {
t.Skip("built without the vmembed tag")
}
if err != nil {
t.Fatal(err)
}
stopped := false
stop := func() {
if stopped {
return
}
stopped = true
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
if err := a.Stop(ctx); err != nil {
t.Errorf("stop: %v", err)
}
}
t.Cleanup(stop)
base := "http://" + a.Addr()
resp, err := http.Post(base+"/api/v1/devices", "application/json", strings.NewReader(
`{"name":"counters","addresses":["::1"],"snmp":{"version":"v2c","community":"public"}}`))
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 201 {
t.Fatalf("add device: %d %s", resp.StatusCode, body)
}
var dev struct {
Slug string
Interfaces []struct{ ID string }
}
if err := json.Unmarshal(body, &dev); err != nil || len(dev.Interfaces) != 8 {
t.Fatalf("device: %s (%v)", body, err)
}
// Instant queries return the newest point, so collect values of one counter
// across polls until three distinct ones have been seen.
var vals []float64
deadline := time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) && len(distinct(vals)) < 3 {
time.Sleep(2 * time.Second)
if r, err := http.Post(a.HotURL()+"/internal/force_flush", "", nil); err == nil {
r.Body.Close()
}
for _, s := range query(t, base, "ifHCInOctets") {
if s.Metric["iface"] == dev.Interfaces[0].ID {
v, _ := strconv.ParseFloat(s.Value[1].(string), 64)
vals = append(vals, v)
}
}
}
d := distinct(vals)
if len(d) < 3 {
t.Fatalf("saw only %v for ifHCInOctets after 60s", d)
}
for i := 1; i < len(d); i++ {
if d[i] <= d[i-1] {
t.Fatalf("not rising: %v", d)
}
}
for _, s := range query(t, base, "ifHCInOctets") {
keys := make([]string, 0, len(s.Metric))
for k := range s.Metric {
keys = append(keys, k)
}
sort.Strings(keys)
if fmt.Sprint(keys) != "[__name__ device iface]" || s.Metric["device"] != dev.Slug {
t.Fatalf("labels %v", s.Metric)
}
}
if up := query(t, base, "nmon_snmp_up"); len(up) != 1 || up[0].Value[1] != "1" {
t.Errorf("nmon_snmp_up = %+v", up)
}
// the poller stores nmon_ internals every 15 s
stored := false
for end := time.Now().Add(30 * time.Second); time.Now().Before(end) && !stored; time.Sleep(2 * time.Second) {
if r, err := http.Post(a.HotURL()+"/internal/force_flush", "", nil); err == nil {
r.Body.Close()
}
stored = len(query(t, base, "nmon_pdus_total")) > 0
}
if !stored {
t.Error("nmon_ internals are not stored")
}
if r, err := http.Get(base + "/metrics"); err != nil || r.StatusCode != 200 {
t.Errorf("/metrics: %v %v", r, err)
} else {
b, _ := io.ReadAll(r.Body)
r.Body.Close()
if !bytes.Contains(b, []byte("nmon_pdus_total")) {
t.Error("/metrics lacks nmon_pdus_total")
}
}
stop()
}
func distinct(v []float64) []float64 {
s := append([]float64(nil), v...)
sort.Float64s(s)
out := s[:0]
for i, x := range s {
if i == 0 || x != s[i-1] {
out = append(out, x)
}
}
return out
}
// TestServeDiscoverEndpointHealthAndTraps: the wiring added in M2: the discover
// endpoint, the poller health page and a trap receiver that binds.
func TestServeDiscoverEndpointHealthAndTraps(t *testing.T) {
rec, err := snmprec.Load("../../testdata/snmprec/juniper-junos.snmprec")
if err != nil {
t.Fatal(err)
}
agent := testutil.StartAgent(t, simagent.Config{Recording: rec, Community: "public"})
root := t.TempDir()
a, err := app.Start(context.Background(), config.Flags{
DataDir: filepath.Join(root, "data"), SecretKeyFile: filepath.Join(root, "keys", "secret.key"), Listen: "[::1]:0",
InsecureHTTP: true, PollInterval: 5 * time.Second, SNMPPort: int(agent.Addr().Port()), TrapListen: "[::1]:0",
})
if errors.Is(err, vmsup.ErrNoBinary) {
t.Skip("built without the vmembed tag")
}
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
if err := a.Stop(ctx); err != nil {
t.Errorf("stop: %v", err)
}
})
base := "http://" + a.Addr()
resp, err := http.Post(base+"/api/v1/devices", "application/json", strings.NewReader(
`{"name":"mx","addresses":["::1"],"snmp":{"version":"v2c","community":"public"}}`))
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
var dev struct{ Slug, Profile string }
if resp.StatusCode != 201 || json.Unmarshal(body, &dev) != nil || dev.Profile != "juniper-junos" {
t.Fatalf("add device: %d %s", resp.StatusCode, body)
}
resp, err = http.Post(base+"/api/v1/devices/"+dev.Slug+"/discover", "application/json", nil)
if err != nil {
t.Fatal(err)
}
body, _ = io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 || !strings.Contains(string(body), `"interfaces_matched":9`) {
t.Fatalf("discover: %d %s", resp.StatusCode, body)
}
deadline := time.Now().Add(30 * time.Second)
for {
resp, err = http.Get(base + "/api/v1/poller/health")
if err != nil {
t.Fatal(err)
}
body, _ = io.ReadAll(resp.Body)
resp.Body.Close()
if strings.Contains(string(body), `"slug":"`+dev.Slug+`"`) && strings.Contains(string(body), `"profile":"juniper-junos"`) {
break
}
if time.Now().After(deadline) {
t.Fatalf("poller health never listed the device: %s", body)
}
time.Sleep(200 * time.Millisecond)
}
}