Compare commits
9 Commits
m3
...
m6-integra
| Author | SHA1 | Date | |
|---|---|---|---|
| 0754268e9e | |||
| a768a15fb6 | |||
| d7df853a35 | |||
| 81162b57b5 | |||
| fe4db76a6e | |||
| b3aae800bf | |||
| ba960474bc | |||
| d3ec85a19c | |||
| b740611136 |
@@ -108,13 +108,18 @@ linters:
|
||||
- pkg: github.com/v10networks/nmon/internal/traps
|
||||
desc: collection paths share code via a lower package, not each other
|
||||
devtools-not-in-nmon:
|
||||
# profile_record.go (`nmon profile record`, M2) already uses the recording types and writer; nothing else may.
|
||||
files: ["**/cmd/nmon/**", "!**/cmd/nmon/profile_record.go", "!$test"]
|
||||
# The product binary never links dev/test machinery. `nmon profile record` needs only the
|
||||
# .snmprec format, which lives in internal/snmprec.
|
||||
files: ["**/cmd/nmon/**", "!$test"]
|
||||
deny:
|
||||
- pkg: github.com/v10networks/nmon/internal/simagent
|
||||
desc: the simulator belongs to cmd/nmon-devtools and tests, never the shipped binary
|
||||
- pkg: github.com/v10networks/nmon/internal/fixturegen
|
||||
desc: the fixture generator belongs to cmd/nmon-devtools and tests, never the shipped binary
|
||||
- pkg: github.com/v10networks/nmon/internal/fixtures
|
||||
desc: fixtures are test data, never the shipped binary
|
||||
- pkg: github.com/v10networks/nmon/internal/testutil
|
||||
desc: test helpers are never in the shipped binary
|
||||
devtools-no-core:
|
||||
files: ["**/cmd/nmon-devtools/**"]
|
||||
deny:
|
||||
|
||||
80
cmd/nmon-devtools/backfilllong.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/v10networks/nmon/internal/longq"
|
||||
"github.com/v10networks/nmon/internal/metrics"
|
||||
"github.com/v10networks/nmon/internal/rollup"
|
||||
)
|
||||
|
||||
// backfillLongCmd writes rollup series straight into the long store, as if the rollup job had been running
|
||||
// for years: hourly average and maximum rates for --months months and 5-minute rates for --days days, flat
|
||||
// at the given rates so a gate can assert exact values. The data ends --end-offset ago, leaving the recent
|
||||
// hours to the real rollup job (its repair writes higher versions, which win).
|
||||
func backfillLongCmd(ctx context.Context, args []string) error {
|
||||
fs := devFlagSet("backfill-long")
|
||||
var ifaces stringList
|
||||
long := fs.String("long-url", "", "base URL of the long VictoriaMetrics (see \"metric stores up\" in the serve log)")
|
||||
device := fs.String("device", "", "device slug (the series' device label)")
|
||||
fs.Var(&ifaces, "iface", "interface ULID; repeat the flag or separate with commas")
|
||||
months := fs.Int("months", 25, "months of hourly rollups to write")
|
||||
days := fs.Int("days", 70, "days of 5-minute rates to write")
|
||||
offset := fs.Duration("end-offset", 3*time.Hour, "stop this long before now")
|
||||
in := fs.Float64("in-bps", 8e6, "constant inbound rate")
|
||||
out := fs.Float64("out-bps", 2e6, "constant outbound rate")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if *long == "" || *device == "" || len(ifaces) == 0 {
|
||||
return fmt.Errorf("backfill-long needs --long-url, --device and --iface: %w", errUsage)
|
||||
}
|
||||
c := &backfillConfig{hotURL: strings.TrimRight(*long, "/"), hc: &http.Client{Timeout: 5 * time.Minute}}
|
||||
end := time.Now().Add(-*offset).Truncate(time.Hour)
|
||||
for _, id := range ifaces {
|
||||
s := longSamples(*device, id, end, *months, *days, map[string]float64{"in": *in, "out": *out})
|
||||
if err := c.send(ctx, s); err != nil {
|
||||
return errors.Join(fmt.Errorf("iface %s", id), err)
|
||||
}
|
||||
fmt.Printf("backfilled long %s/%s: %d months hourly, %d days 5m (%d samples)\n", *device, id, *months, *days, len(s))
|
||||
}
|
||||
return c.flush(ctx)
|
||||
}
|
||||
|
||||
// flush makes what was just imported searchable at once: VictoriaMetrics shows new rows only after its
|
||||
// buffers flush, and a gate that queries right after the import would otherwise see a partial history.
|
||||
func (c *backfillConfig) flush(ctx context.Context) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.hotURL+"/internal/force_flush", http.NoBody)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = resp.Body.Close() // nothing in the reply matters
|
||||
return nil
|
||||
}
|
||||
|
||||
// longSamples builds the hourly series from end back months months and the 5-minute series from end back days.
|
||||
func longSamples(device, iface string, end time.Time, months, days int, rate map[string]float64) []metrics.Sample {
|
||||
var out []metrics.Sample
|
||||
labels := func(dir string, ws time.Time) []string {
|
||||
return []string{"device", device, "iface", iface, "dir", dir, "v", rollup.VersionLabel(ws, 1)}
|
||||
}
|
||||
for dir, bps := range rate {
|
||||
for h := end; h.After(end.AddDate(0, -months, 0)); h = h.Add(-time.Hour) {
|
||||
out = append(out, metrics.New(longq.MetricRateAvg1h, bps, h, labels(dir, h)...),
|
||||
metrics.New(longq.MetricRateMax1h, bps*1.25, h, labels(dir, h)...))
|
||||
}
|
||||
for t := end; t.After(end.AddDate(0, 0, -days)); t = t.Add(-5 * time.Minute) {
|
||||
out = append(out, metrics.New(longq.MetricRate5m, bps, t, labels(dir, t)...))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -9,14 +9,14 @@ import (
|
||||
|
||||
"github.com/v10networks/nmon/internal/fixturegen"
|
||||
"github.com/v10networks/nmon/internal/profile"
|
||||
"github.com/v10networks/nmon/internal/simagent"
|
||||
"github.com/v10networks/nmon/internal/snmprec"
|
||||
)
|
||||
|
||||
// demoDevice is one simulated device of `devtools seed-demo`.
|
||||
type demoDevice struct {
|
||||
name, site, role string
|
||||
kind string // counters, big, router, ups, v1, down: what the gate and screenshots look for
|
||||
rec *simagent.Recording
|
||||
rec *snmprec.Recording
|
||||
community string
|
||||
version string // v2c unless set
|
||||
hc bool // 64-bit counters, so history can be back-filled
|
||||
@@ -36,8 +36,8 @@ const (
|
||||
// animate returns a copy of rec whose 64-bit octet counters advance at a steady
|
||||
// per-port rate from counterBase and whose uptime ticks, so successive polls see
|
||||
// traffic. Counters that already advance keep their rate and only gain the base.
|
||||
func animate(rec *simagent.Recording) *simagent.Recording {
|
||||
recs := append([]simagent.Record(nil), rec.Records()...)
|
||||
func animate(rec *snmprec.Recording) *snmprec.Recording {
|
||||
recs := append([]snmprec.Record(nil), rec.Records()...)
|
||||
for i := range recs {
|
||||
r := &recs[i]
|
||||
switch {
|
||||
@@ -45,14 +45,14 @@ func animate(rec *simagent.Recording) *simagent.Recording {
|
||||
recs[i] = animateCounter(*r)
|
||||
case r.OID == oidUp && r.Dyn == nil:
|
||||
if v, ok := r.Value.(uint32); ok {
|
||||
r.Dyn, r.Value = &simagent.Dynamic{Rate: 100, Initial: uint64(v)}, nil
|
||||
r.Dyn, r.Value = &snmprec.Dynamic{Rate: 100, Initial: uint64(v)}, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return simagent.NewRecording(recs)
|
||||
return snmprec.NewRecording(recs)
|
||||
}
|
||||
|
||||
func animateCounter(r simagent.Record) simagent.Record {
|
||||
func animateCounter(r snmprec.Record) snmprec.Record {
|
||||
if r.Dyn != nil {
|
||||
d := *r.Dyn
|
||||
d.Initial += counterBase
|
||||
@@ -65,7 +65,7 @@ func animateCounter(r simagent.Record) simagent.Record {
|
||||
dir = 2
|
||||
}
|
||||
mbps := 1 + (k*(31+7*dir))%90
|
||||
r.Dyn = &simagent.Dynamic{Rate: float64(mbps) * 125_000, Initial: counterBase + uint64(k)*1_000_000_000}
|
||||
r.Dyn = &snmprec.Dynamic{Rate: float64(mbps) * 125_000, Initial: counterBase + uint64(k)*1_000_000_000}
|
||||
r.Value = nil
|
||||
return r
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func profileDevice(set *profile.Set, prof, name, site, role, kind string, ports
|
||||
// routers, a firewall, a UPS, one 32-bit device, the counters fixture and one
|
||||
// device whose agent is stopped after seeding, so it reads as down.
|
||||
func buildFleet(set *profile.Set, countersRec string) ([]demoDevice, error) {
|
||||
counters, err := simagent.LoadRecording(countersRec)
|
||||
counters, err := snmprec.Load(countersRec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
163
cmd/nmon-devtools/gatedump.go
Normal file
@@ -0,0 +1,163 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// gateDumpCmd prints what the M4 gate asserts on, one line per item, so the shell
|
||||
// script can count and match lines instead of parsing JSON.
|
||||
//
|
||||
// gate-dump sink --file F what the webhook sink received, in arrival order
|
||||
// gate-dump alerts --api URL every alert, newest first
|
||||
// gate-dump devices --api URL every device's reachability
|
||||
func gateDumpCmd(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("gate-dump sink|alerts|devices")
|
||||
}
|
||||
fs := devFlagSet("gate-dump " + args[0])
|
||||
file := fs.String("file", "", "sink file (sink)")
|
||||
api := fs.String("api", "", "nmon API base URL (alerts, devices)")
|
||||
mapFile := fs.String("map", "", "slug map written by topology-add; slugs are printed as topology names")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
names, err := readSlugMap(*mapFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch args[0] {
|
||||
case "sink":
|
||||
return dumpSink(*file, names)
|
||||
case "alerts":
|
||||
return dumpAlerts(ctx, *api, names)
|
||||
case "devices":
|
||||
return dumpDevices(ctx, *api, names)
|
||||
}
|
||||
return fmt.Errorf("gate-dump: unknown %q", args[0])
|
||||
}
|
||||
|
||||
func orDash(s []string) string {
|
||||
if len(s) == 0 {
|
||||
return "-"
|
||||
}
|
||||
return strings.Join(s, ",")
|
||||
}
|
||||
|
||||
// dumpSink prints "rule state device parents=a,b children=N incident=ID" per request received.
|
||||
func dumpSink(file string, names slugNames) error {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = f.Close() }() // read only
|
||||
sc := bufio.NewScanner(f)
|
||||
sc.Buffer(make([]byte, 1<<20), 1<<20)
|
||||
for sc.Scan() {
|
||||
var l sinkLine
|
||||
var n struct {
|
||||
Rule, State string
|
||||
IncidentID string `json:"incident_id"`
|
||||
Device struct{ Slug string }
|
||||
Parents []string
|
||||
SuppressedChildren int `json:"suppressed_children"`
|
||||
}
|
||||
if json.Unmarshal(sc.Bytes(), &l) != nil || json.Unmarshal(l.Body, &n) != nil {
|
||||
fmt.Println("unparsable - - parents=- children=0 incident=-")
|
||||
continue
|
||||
}
|
||||
fmt.Printf("%s %s %s parents=%s children=%d incident=%s\n", n.Rule, n.State, names.one(n.Device.Slug), orDash(names.of(n.Parents)),
|
||||
n.SuppressedChildren, n.IncidentID)
|
||||
}
|
||||
return sc.Err()
|
||||
}
|
||||
|
||||
func getJSON(ctx context.Context, api, path string, out any) error {
|
||||
hc := &http.Client{Timeout: 30 * time.Second}
|
||||
return httpJSON(ctx, hc, http.MethodGet, api+path, nil, out)
|
||||
}
|
||||
|
||||
// dumpAlerts prints "id rule state device suppressed_by=a,b incident=ID acked=yes|no" per alert.
|
||||
func dumpAlerts(ctx context.Context, api string, names slugNames) error {
|
||||
var page struct {
|
||||
Items []struct {
|
||||
ID, Rule, State string
|
||||
Device struct{ Slug string }
|
||||
SuppressedBy []string `json:"suppressed_by"`
|
||||
IncidentID string `json:"incident_id"`
|
||||
Ack *struct{} `json:"ack"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := getJSON(ctx, api, "/api/v1/alerts?per_page=1000", &page); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, a := range page.Items {
|
||||
acked := "no"
|
||||
if a.Ack != nil {
|
||||
acked = "yes"
|
||||
}
|
||||
fmt.Printf("%s %s %s %s suppressed_by=%s incident=%s acked=%s\n", a.ID, a.Rule, a.State, names.one(a.Device.Slug),
|
||||
orDash(names.of(a.SuppressedBy)), orDash([]string{a.IncidentID}), acked)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// dumpDevices prints "slug reachability poll_state warnings=a,b" per device.
|
||||
func dumpDevices(ctx context.Context, api string, names slugNames) error {
|
||||
var page struct {
|
||||
Items []struct {
|
||||
Slug, Reachability string
|
||||
PollState string `json:"poll_state"`
|
||||
Warnings []string `json:"warnings"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := getJSON(ctx, api, "/api/v1/devices?per_page=1000", &page); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, d := range page.Items {
|
||||
fmt.Printf("%s %s %s warnings=%s\n", url.PathEscape(names.one(d.Slug)), d.Reachability, d.PollState, orDash(d.Warnings))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// slugNames maps nmon slugs back to the names in the topology file.
|
||||
type slugNames map[string]string
|
||||
|
||||
func readSlugMap(path string) (slugNames, error) {
|
||||
m := slugNames{}
|
||||
if path == "" {
|
||||
return m, nil
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
if f := strings.Fields(l); len(f) == 2 {
|
||||
m[f[0]] = f[1]
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m slugNames) one(slug string) string {
|
||||
if n, ok := m[slug]; ok {
|
||||
return n
|
||||
}
|
||||
return slug
|
||||
}
|
||||
|
||||
func (m slugNames) of(slugs []string) []string {
|
||||
out := make([]string, len(slugs))
|
||||
for i, s := range slugs {
|
||||
out[i] = m.one(s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
59
cmd/nmon-devtools/m5_test.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRebaseInfluxMakesTheNewestLineNowAndKeepsSpacing(t *testing.T) {
|
||||
in := "m,host=a v=1 1000000000000000000\n# c\nm,host=a v=2 1000000060000000000\n"
|
||||
now := time.Unix(2_000_000_000, 0)
|
||||
out, n, err := rebaseInflux(in, now)
|
||||
if err != nil || n != 2 {
|
||||
t.Fatalf("n=%d err=%v", n, err)
|
||||
}
|
||||
want := "m,host=a v=1 1999999940000000000\nm,host=a v=2 2000000000000000000\n"
|
||||
if out != want {
|
||||
t.Fatalf("got %q want %q", out, want)
|
||||
}
|
||||
if _, _, err := rebaseInflux("\n# only comments\n", now); err == nil {
|
||||
t.Fatal("empty input accepted")
|
||||
}
|
||||
if !strings.Contains(out, "host=a") {
|
||||
t.Fatal("tags lost")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxmoxMockAuthShape(t *testing.T) {
|
||||
for h, want := range map[string]bool{
|
||||
"PVEAPIToken=root@pam!nmon=s3cret": true, "PVEAPIToken=root@pam!nmon=": false, "Bearer x": false, "": false,
|
||||
} {
|
||||
if validPVEAuth(h, "") != want {
|
||||
t.Errorf("%q: want %v", h, want)
|
||||
}
|
||||
}
|
||||
if validPVEAuth("PVEAPIToken=a@b!c=other", "s3cret") {
|
||||
t.Error("wrong secret accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongSamplesCarryVersionedHourlyAndFiveMinuteSeries(t *testing.T) {
|
||||
end := time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)
|
||||
s := longSamples("d", "I", end, 1, 1, map[string]float64{"in": 8e6})
|
||||
var h, f int
|
||||
for _, x := range s {
|
||||
switch x.Name {
|
||||
case "nmon_if_rate_bps_5m":
|
||||
f++
|
||||
default:
|
||||
h++
|
||||
}
|
||||
}
|
||||
if f != 288 || h < 2*28*24 {
|
||||
t.Fatalf("5m=%d hourly=%d", f, h)
|
||||
}
|
||||
if s[0].Labels[3].Name != "v" || s[0].Labels[3].Value != "202610001" {
|
||||
t.Fatalf("labels %+v", s[0].Labels)
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,9 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var errUsage = errors.New("usage: nmon-devtools backfill|seed-demo [flags] (see docs/dev.md)")
|
||||
var errUsage = errors.New("usage: nmon-devtools backfill|seed-demo|topology-agents|topology-add|webhook-sink|gate-dump|" +
|
||||
"proxmox-mock|push-replay|backfill-long|oidc-mock|bcrypt [flags]" +
|
||||
" (see docs/dev.md)")
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
@@ -38,6 +40,24 @@ func run(ctx context.Context, args []string) error {
|
||||
return backfillCmd(ctx, args[1:])
|
||||
case "seed-demo":
|
||||
return seedDemoCmd(ctx, args[1:])
|
||||
case "topology-agents":
|
||||
return topologyAgentsCmd(ctx, args[1:])
|
||||
case "topology-add":
|
||||
return topologyAddCmd(ctx, args[1:])
|
||||
case "webhook-sink":
|
||||
return webhookSinkCmd(ctx, args[1:])
|
||||
case "gate-dump":
|
||||
return gateDumpCmd(ctx, args[1:])
|
||||
case "proxmox-mock":
|
||||
return proxmoxMockCmd(ctx, args[1:])
|
||||
case "push-replay":
|
||||
return pushReplayCmd(ctx, args[1:])
|
||||
case "backfill-long":
|
||||
return backfillLongCmd(ctx, args[1:])
|
||||
case "bcrypt":
|
||||
return bcryptCmd(ctx, args[1:])
|
||||
case "oidc-mock":
|
||||
return oidcMockCmd(ctx, args[1:])
|
||||
default:
|
||||
return fmt.Errorf("unknown command %q: %w", args[0], errUsage)
|
||||
}
|
||||
@@ -72,7 +92,7 @@ func devFlagSet(name string) *flag.FlagSet {
|
||||
return fs
|
||||
}
|
||||
|
||||
// httpJSON sends an optional JSON body and decodes a 2xx JSON reply into out (nil to discard it).
|
||||
// httpJSON sends an optional JSON body (with the API token in NMON_TOKEN, if set) and decodes a 2xx reply into out (nil: discard).
|
||||
func httpJSON(ctx context.Context, hc *http.Client, method, url string, in, out any) error {
|
||||
var body io.Reader
|
||||
if in != nil {
|
||||
@@ -89,6 +109,9 @@ func httpJSON(ctx context.Context, hc *http.Client, method, url string, in, out
|
||||
if in != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if tok := os.Getenv("NMON_TOKEN"); tok != "" { // an nmon with authentication on needs an admin API token
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
102
cmd/nmon-devtools/oidcmock.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/v10networks/nmon/internal/auth/oidctest"
|
||||
)
|
||||
|
||||
// devTB lets the test-only mock issuer run outside a test binary: it supplies the three methods oidctest uses
|
||||
// (Helper, Fatal, Cleanup) and leaves the rest of testing.TB nil.
|
||||
type devTB struct {
|
||||
testing.TB
|
||||
cleanups []func()
|
||||
}
|
||||
|
||||
func (*devTB) Helper() {}
|
||||
|
||||
func (*devTB) Fatal(args ...any) { panic(fmt.Sprint(args...)) }
|
||||
|
||||
func (d *devTB) Cleanup(f func()) { d.cleanups = append(d.cleanups, f) }
|
||||
|
||||
func (d *devTB) close() {
|
||||
for i := len(d.cleanups) - 1; i >= 0; i-- {
|
||||
d.cleanups[i]()
|
||||
}
|
||||
}
|
||||
|
||||
// oidcMockCmd runs internal/auth/oidctest as a standalone OpenID Connect issuer for the M6 gate and for
|
||||
// screenshots. The issuer approves every login at once as the "current user"; a control listener changes who
|
||||
// that is: GET /user?sub=ID&name=NAME&groups=a,b on --control. The issuer URL is written to --issuer-file.
|
||||
func oidcMockCmd(ctx context.Context, args []string) error {
|
||||
fs := devFlagSet("oidc-mock")
|
||||
control := fs.String("control", "[::1]:0", "listen address of the control endpoint")
|
||||
clientID := fs.String("client-id", "nmon", "OIDC client id the issuer accepts")
|
||||
clientSecret := fs.String("client-secret", "s3cret", "OIDC client secret the issuer accepts")
|
||||
groupsClaim := fs.String("groups-claim", "groups", "name of the groups claim")
|
||||
issuerFile := fs.String("issuer-file", "", "file that receives the issuer URL")
|
||||
portFile := fs.String("port-file", "", "file that receives the control port")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
tb := &devTB{}
|
||||
defer tb.close()
|
||||
srv := oidctest.New(tb)
|
||||
srv.ClientID, srv.ClientSecret, srv.GroupsClaim = *clientID, *clientSecret, *groupsClaim
|
||||
ln, err := net.Listen("tcp", *control)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writePort(*portFile, ln); err != nil {
|
||||
return err
|
||||
}
|
||||
if *issuerFile != "" {
|
||||
if err := os.WriteFile(*issuerFile, []byte(srv.Issuer()), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /user", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
u := oidctest.User{Sub: q.Get("sub"), Name: q.Get("name"), Email: q.Get("email")}
|
||||
if g := q.Get("groups"); g != "" {
|
||||
u.Groups = strings.Split(g, ",")
|
||||
}
|
||||
if u.Sub == "" {
|
||||
http.Error(w, "sub is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
srv.SetUser(u)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
hs := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}
|
||||
go func() { <-ctx.Done(); _ = hs.Close() }()
|
||||
fmt.Printf("oidc-mock issuer %s control %s\n", srv.Issuer(), ln.Addr())
|
||||
if err := hs.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// bcryptCmd prints the bcrypt hash of its argument: the content of a break-glass password file.
|
||||
func bcryptCmd(_ context.Context, args []string) error {
|
||||
if len(args) != 1 {
|
||||
return errors.New("usage: nmon-devtools bcrypt PASSWORD")
|
||||
}
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(args[0]), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(string(h))
|
||||
return nil
|
||||
}
|
||||
75
cmd/nmon-devtools/proxmoxmock.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// proxmoxMockCmd serves a recorded cluster/resources response the way a Proxmox VE API does, for the M5 gate:
|
||||
// GET /api2/json/cluster/resources with "Authorization: PVEAPIToken=<id>=<secret>". Any other path is a 404 and
|
||||
// a request without that header shape is a 401, so a client that forgot the secret fails like the real thing.
|
||||
func proxmoxMockCmd(ctx context.Context, args []string) error {
|
||||
fs := devFlagSet("proxmox-mock")
|
||||
listen := fs.String("listen", "[::1]:0", "listen address")
|
||||
file := fs.String("file", "", "recorded cluster/resources JSON (testdata/proxmox/cluster-resources.json)")
|
||||
secret := fs.String("secret", "", "token secret to require (empty: any non-empty secret)")
|
||||
portFile := fs.String("port-file", "", "file that receives the bound port")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
body, err := os.ReadFile(*file)
|
||||
if err != nil || *file == "" {
|
||||
return fmt.Errorf("proxmox-mock needs --file: %w", errors.Join(err, errUsage))
|
||||
}
|
||||
ln, err := net.Listen("tcp", *listen)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writePort(*portFile, ln); err != nil {
|
||||
return err
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api2/json/cluster/resources", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !validPVEAuth(r.Header.Get("Authorization"), *secret) {
|
||||
http.Error(w, `{"data":null}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(body) // a client that hung up has nobody to tell
|
||||
})
|
||||
srv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}
|
||||
go func() { <-ctx.Done(); _ = srv.Close() }()
|
||||
fmt.Printf("proxmox-mock listening on %s\n", ln.Addr())
|
||||
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validPVEAuth accepts "PVEAPIToken=user@realm!id=secret" with the wanted secret (or any, when want is empty).
|
||||
func validPVEAuth(h, want string) bool {
|
||||
rest, ok := strings.CutPrefix(h, "PVEAPIToken=")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
_, got, ok := strings.Cut(rest, "=")
|
||||
return ok && got != "" && (want == "" || got == want)
|
||||
}
|
||||
|
||||
// writePort records the bound port for a shell script to read.
|
||||
func writePort(file string, ln net.Listener) error {
|
||||
if file == "" {
|
||||
return nil
|
||||
}
|
||||
tcp, ok := ln.Addr().(*net.TCPAddr)
|
||||
if !ok {
|
||||
return fmt.Errorf("listener is not TCP: %s", ln.Addr())
|
||||
}
|
||||
return os.WriteFile(file, []byte(fmt.Sprint(tcp.Port)), 0o600)
|
||||
}
|
||||
95
cmd/nmon-devtools/pushreplay.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// pushReplayCmd sends a recorded Influx line-protocol file to a running nmon's POST /write, shifting every
|
||||
// timestamp so the newest line is "now": a recording is days old by the time a gate replays it, and ingest
|
||||
// refuses timestamps far from the clock.
|
||||
func pushReplayCmd(ctx context.Context, args []string) error {
|
||||
fs := devFlagSet("push-replay")
|
||||
url := fs.String("url", "", "ingest URL, for example http://127.0.0.1:8443/write")
|
||||
token := fs.String("token", "", "push token secret (omit to test the unauthenticated case)")
|
||||
file := fs.String("file", "", "Influx line-protocol file")
|
||||
extra := fs.String("append", "", "one more line to send after the file (a raw line, rebased like the others)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
raw, err := os.ReadFile(*file)
|
||||
if err != nil || *url == "" {
|
||||
return fmt.Errorf("push-replay needs --url and --file: %w", errors.Join(err, errUsage))
|
||||
}
|
||||
body, n, err := rebaseInflux(string(raw)+"\n"+*extra, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, *url, bytes.NewReader([]byte(body)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+*token)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }() // body read below
|
||||
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 500))
|
||||
fmt.Printf("%d lines -> HTTP %d %s\n", n, resp.StatusCode, strings.TrimSpace(string(msg)))
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("push refused: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rebaseInflux shifts the nanosecond timestamp at the end of every line by the same amount so the newest one
|
||||
// equals now. Lines without a timestamp, blank lines and comments pass through.
|
||||
func rebaseInflux(text string, now time.Time) (string, int, error) {
|
||||
lines := strings.Split(text, "\n")
|
||||
var newest int64
|
||||
for _, l := range lines {
|
||||
if ts, ok := lineTS(l); ok {
|
||||
newest = max(newest, ts)
|
||||
}
|
||||
}
|
||||
shift := now.UnixNano() - newest
|
||||
var out strings.Builder
|
||||
n := 0
|
||||
for _, l := range lines {
|
||||
l = strings.TrimSpace(l)
|
||||
if l == "" || strings.HasPrefix(l, "#") {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
if ts, ok := lineTS(l); ok {
|
||||
l = l[:strings.LastIndexByte(l, ' ')+1] + strconv.FormatInt(ts+shift, 10)
|
||||
}
|
||||
out.WriteString(l + "\n")
|
||||
}
|
||||
if n == 0 {
|
||||
return "", 0, errors.New("no lines to send")
|
||||
}
|
||||
return out.String(), n, nil
|
||||
}
|
||||
|
||||
// lineTS returns the trailing nanosecond timestamp of an Influx line, if it has one.
|
||||
func lineTS(l string) (int64, bool) {
|
||||
l = strings.TrimSpace(l)
|
||||
i := strings.LastIndexByte(l, ' ')
|
||||
if l == "" || strings.HasPrefix(l, "#") || i < 0 {
|
||||
return 0, false
|
||||
}
|
||||
ts, err := strconv.ParseInt(l[i+1:], 10, 64)
|
||||
return ts, err == nil && ts > 1e15
|
||||
}
|
||||
219
cmd/nmon-devtools/topology.go
Normal file
@@ -0,0 +1,219 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/v10networks/nmon/internal/deps"
|
||||
"github.com/v10networks/nmon/internal/fixturegen"
|
||||
"github.com/v10networks/nmon/internal/simagent"
|
||||
)
|
||||
|
||||
// Topology commands for the M4 gate: one simulated SNMP agent per device of a
|
||||
// topology file (deps.Topology), the devices added to a running nmon with their
|
||||
// parents, and a webhook receiver that records what nmon sends.
|
||||
|
||||
const agentCommunity = "public"
|
||||
|
||||
// topologyPort is the UDP port of the i-th device of a topology.
|
||||
func topologyPort(base, i int) int { return base + i }
|
||||
|
||||
// topologyAgentsCmd runs one agent per device on [::1]:port-base+index. The
|
||||
// agent of device X is down while the file <control-dir>/stop-X exists, so a
|
||||
// shell script can take a device away and bring it back on the same port.
|
||||
func topologyAgentsCmd(ctx context.Context, args []string) error {
|
||||
fs := devFlagSet("topology-agents")
|
||||
file := fs.String("topology", "", "topology file (testdata/topologies/*.yaml)")
|
||||
base := fs.Int("port-base", 0, "UDP port of the first device; device i uses port-base+i")
|
||||
ctl := fs.String("control-dir", "", "directory watched for stop-<slug> files")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if *file == "" || *base == 0 || *ctl == "" {
|
||||
return fmt.Errorf("topology-agents needs --topology, --port-base and --control-dir")
|
||||
}
|
||||
topo, err := deps.LoadTopology(*file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f := &agentFleet{topo: topo, base: *base, ctl: *ctl, agents: map[string]*simagent.Agent{}}
|
||||
defer f.closeAll()
|
||||
for {
|
||||
if err := f.reconcile(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if !f.announced {
|
||||
f.announced = true
|
||||
fmt.Printf("agents ready: %d devices on [::1]:%d-%d\n", len(topo.Devices), *base, topologyPort(*base, len(topo.Devices)-1))
|
||||
}
|
||||
if !sleepCtx(ctx, 200*time.Millisecond) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type agentFleet struct {
|
||||
topo *deps.Topology
|
||||
base int
|
||||
ctl string
|
||||
agents map[string]*simagent.Agent
|
||||
announced bool
|
||||
}
|
||||
|
||||
// reconcile starts the agents whose stop file is gone and stops those whose stop file appeared.
|
||||
func (f *agentFleet) reconcile(ctx context.Context) error {
|
||||
for i, d := range f.topo.Devices {
|
||||
_, stopped := os.Stat(filepath.Join(f.ctl, "stop-"+d.Slug))
|
||||
want := stopped != nil // no stop file: the agent should run
|
||||
a := f.agents[d.Slug]
|
||||
switch {
|
||||
case want && a == nil:
|
||||
rec := fixturegen.Generic(fixturegen.Options{Ports: 4, HCCounters: true, Counters: true, SysName: d.Slug})
|
||||
cfg := simagent.Config{Addr: fmt.Sprintf("[::1]:%d", topologyPort(f.base, i)), Recording: rec, Community: agentCommunity}
|
||||
ag, err := simagent.Start(ctx, cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("agent %s: %w", d.Slug, err)
|
||||
}
|
||||
f.agents[d.Slug] = ag
|
||||
case !want && a != nil:
|
||||
_ = a.Close() // best-effort: the port is released either way
|
||||
delete(f.agents, d.Slug)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *agentFleet) closeAll() {
|
||||
for _, a := range f.agents {
|
||||
_ = a.Close() // best-effort at exit
|
||||
}
|
||||
}
|
||||
|
||||
// topologyAddCmd adds every device of a topology to a running nmon, pointing at
|
||||
// its agent, then sets the parents by slug.
|
||||
func topologyAddCmd(ctx context.Context, args []string) error {
|
||||
fs := devFlagSet("topology-add")
|
||||
api := fs.String("api", "", "nmon API base URL")
|
||||
file := fs.String("topology", "", "topology file")
|
||||
base := fs.Int("port-base", 0, "UDP port of the first device's agent")
|
||||
mapOut := fs.String("map-out", "", "file that receives one \"<nmon slug> <topology name>\" line per device")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if *api == "" || *file == "" || *base == 0 {
|
||||
return fmt.Errorf("topology-add needs --api, --topology and --port-base")
|
||||
}
|
||||
topo, err := deps.LoadTopology(*file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hc := &http.Client{Timeout: 90 * time.Second}
|
||||
slugOf := map[string]string{} // topology name -> the slug nmon generated
|
||||
for i, d := range topo.Devices {
|
||||
body := map[string]any{
|
||||
"name": d.Slug, "addresses": []string{"::1"}, "role": d.Role, "kind": d.Kind,
|
||||
"snmp": map[string]any{"version": "v2c", "community": agentCommunity, "port": topologyPort(*base, i)},
|
||||
}
|
||||
var got struct {
|
||||
Slug string `json:"slug"`
|
||||
}
|
||||
if err := httpJSON(ctx, hc, http.MethodPost, *api+"/api/v1/devices", body, &got); err != nil {
|
||||
return fmt.Errorf("add %s: %w", d.Slug, err)
|
||||
}
|
||||
slugOf[d.Slug] = got.Slug // nmon appends a random suffix to the slug it derives from the name
|
||||
}
|
||||
for _, d := range topo.Devices {
|
||||
if len(d.Parents) == 0 {
|
||||
continue
|
||||
}
|
||||
parents := make([]string, len(d.Parents))
|
||||
for i, p := range d.Parents {
|
||||
parents[i] = slugOf[p]
|
||||
}
|
||||
err := httpJSON(ctx, hc, http.MethodPut, *api+"/api/v1/devices/"+url.PathEscape(slugOf[d.Slug]), map[string]any{"parents": parents}, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parents of %s: %w", d.Slug, err)
|
||||
}
|
||||
}
|
||||
fmt.Printf("topology-add ready: %d devices\n", len(topo.Devices))
|
||||
return writeSlugMap(*mapOut, topo, slugOf)
|
||||
}
|
||||
|
||||
// writeSlugMap records which nmon slug belongs to which topology name, for gate-dump --map and the gate script.
|
||||
func writeSlugMap(path string, topo *deps.Topology, slugOf map[string]string) error {
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, d := range topo.Devices {
|
||||
fmt.Fprintf(&b, "%s %s\n", slugOf[d.Slug], d.Slug)
|
||||
}
|
||||
return os.WriteFile(path, []byte(b.String()), 0o600)
|
||||
}
|
||||
|
||||
// sinkLine is one recorded request.
|
||||
type sinkLine struct {
|
||||
At string `json:"at"`
|
||||
Path string `json:"path"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
}
|
||||
|
||||
// webhookSinkCmd records every POST body as one JSON line in --out, answers 200,
|
||||
// and writes the bound port to --port-file once it listens.
|
||||
func webhookSinkCmd(ctx context.Context, args []string) error {
|
||||
fs := devFlagSet("webhook-sink")
|
||||
listen := fs.String("listen", "[::1]:0", "listen address")
|
||||
out := fs.String("out", "", "file that receives one JSON line per request")
|
||||
portFile := fs.String("port-file", "", "file that receives the bound port")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if *out == "" {
|
||||
return fmt.Errorf("webhook-sink needs --out")
|
||||
}
|
||||
f, err := os.OpenFile(*out, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = f.Close() }() // lines are written whole; nothing is buffered
|
||||
ln, err := net.Listen("tcp", *listen)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *portFile != "" {
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
if err := os.WriteFile(*portFile, []byte(fmt.Sprint(port)), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var mu sync.Mutex
|
||||
srv := &http.Server{ReadHeaderTimeout: 10 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
raw := json.RawMessage(b)
|
||||
if !json.Valid(b) {
|
||||
raw, _ = json.Marshal(string(b))
|
||||
}
|
||||
line, _ := json.Marshal(sinkLine{At: time.Now().UTC().Format(time.RFC3339Nano), Path: r.URL.Path, Body: raw})
|
||||
mu.Lock()
|
||||
_, _ = f.Write(append(line, '\n'))
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})}
|
||||
go func() { <-ctx.Done(); _ = srv.Close() }()
|
||||
fmt.Printf("webhook-sink listening on %s\n", ln.Addr())
|
||||
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
90
cmd/nmon/apiclient.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// apiFlags are the flags of every command that talks to a running nmon.
|
||||
type apiFlags struct {
|
||||
URL, Token string
|
||||
SkipVerify bool
|
||||
}
|
||||
|
||||
func (f *apiFlags) register(fs *flag.FlagSet) {
|
||||
fs.StringVar(&f.URL, "api", os.Getenv("NMON_API"), "base URL of the running nmon, such as https://nmon.example.net:8443 (or set NMON_API)")
|
||||
fs.StringVar(&f.Token, "token", os.Getenv("NMON_TOKEN"), "admin API token, nma_... (or set NMON_TOKEN)")
|
||||
fs.BoolVar(&f.SkipVerify, "tls-skip-verify", false,
|
||||
"do not verify the server certificate (a self-signed certificate on a trusted network)")
|
||||
}
|
||||
|
||||
func (f *apiFlags) validate() error {
|
||||
if f.URL == "" {
|
||||
return errors.New("--api is required (the URL of the running nmon)")
|
||||
}
|
||||
if f.Token == "" {
|
||||
return errors.New("--token is required (an admin API token; create one in Settings, or POST /api/v1/tokens)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// client returns an HTTP client without an overall timeout: a backup download can take minutes. ctx bounds each call.
|
||||
func (f *apiFlags) client() *http.Client {
|
||||
tr := http.DefaultTransport.(*http.Transport).Clone()
|
||||
if f.SkipVerify {
|
||||
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS12} // opt-in flag for self-signed certificates
|
||||
}
|
||||
return &http.Client{Transport: tr, Timeout: 0}
|
||||
}
|
||||
|
||||
// call sends one request and returns the open response when the status is 2xx; any other status is an error
|
||||
// carrying the problem detail. The caller closes the body.
|
||||
func (f *apiFlags) call(ctx context.Context, method, path string, body io.Reader) (*http.Response, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
|
||||
req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(f.URL, "/")+path, body)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+f.Token)
|
||||
resp, err := f.client().Do(req)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode/100 != 2 {
|
||||
defer cancel()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
return nil, problemError(resp)
|
||||
}
|
||||
resp.Body = &cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
type cancelOnClose struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (c *cancelOnClose) Close() error { defer c.cancel(); return c.ReadCloser.Close() }
|
||||
|
||||
// problemError turns an RFC 9457 response into an error with the server's explanation.
|
||||
func problemError(resp *http.Response) error {
|
||||
b, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
var p struct {
|
||||
Title, Detail string
|
||||
}
|
||||
if json.Unmarshal(b, &p) == nil && (p.Title != "" || p.Detail != "") {
|
||||
return fmt.Errorf("%s: %s", resp.Status, strings.TrimSpace(p.Title+": "+p.Detail))
|
||||
}
|
||||
return fmt.Errorf("%s", resp.Status)
|
||||
}
|
||||
94
cmd/nmon/backup.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/v10networks/nmon/internal/backup"
|
||||
)
|
||||
|
||||
func init() {
|
||||
register("backup", "write a backup of inventory, metrics, config and profiles from a running nmon", backupCmd)
|
||||
}
|
||||
|
||||
// backupCmd asks the running nmon to take its online backup and saves the stream. A running nmon owns the
|
||||
// stores, so the work happens inside it (POST /api/v1/admin/backup); this command only downloads the result.
|
||||
func backupCmd(ctx context.Context, args []string) error {
|
||||
var af apiFlags
|
||||
var includeKey bool
|
||||
fs := newFlagSet("backup", "backup FILE --api URL --token TOKEN [--include-key]")
|
||||
af.register(fs)
|
||||
fs.BoolVar(&includeKey, "include-key", false, "put the encryption key file in the archive (protect the archive like the key)")
|
||||
file, rest, err := leadingArg(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fs.Parse(rest); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if file == "" && fs.NArg() == 1 {
|
||||
file = fs.Arg(0)
|
||||
}
|
||||
if file == "" || fs.NArg() > 1 {
|
||||
return errors.New("usage: nmon backup FILE --api URL --token TOKEN [--include-key]")
|
||||
}
|
||||
if err := af.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := af.call(ctx, "POST", "/api/v1/admin/backup?"+url.Values{"include_key": {strconv.FormatBool(includeKey)}}.Encode(), nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
included := resp.Header.Get("X-Nmon-Key-Included") == "true"
|
||||
n, err := saveAtomically(file, resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
fmt.Println(backup.KeyNotice(included))
|
||||
fmt.Printf("backup: wrote %s (%d bytes)\n", file, n)
|
||||
return nil
|
||||
}
|
||||
|
||||
// leadingArg splits a positional first argument from the flags after it ("nmon backup FILE --api ...").
|
||||
func leadingArg(args []string) (string, []string, error) {
|
||||
if len(args) > 0 && len(args[0]) > 0 && args[0][0] != '-' {
|
||||
return args[0], args[1:], nil
|
||||
}
|
||||
return "", args, nil
|
||||
}
|
||||
|
||||
// saveAtomically writes r to a temp file beside path, syncs it and renames it, so an interrupted download never
|
||||
// leaves a truncated file under the final name.
|
||||
func saveAtomically(path string, r io.Reader) (n int64, err error) {
|
||||
f, err := os.CreateTemp(filepath.Dir(path), ".nmon-backup-*")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = os.Remove(f.Name()) // best effort: the download error is the one to report
|
||||
}
|
||||
}()
|
||||
if n, err = io.Copy(f, r); err != nil {
|
||||
_ = f.Close() // best effort: the copy error is the one to report
|
||||
return 0, err
|
||||
}
|
||||
if err = f.Sync(); err != nil {
|
||||
_ = f.Close() // best effort: the sync error is the one to report
|
||||
return 0, err
|
||||
}
|
||||
if err = f.Close(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err = os.Chmod(f.Name(), 0o600); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return n, os.Rename(f.Name(), path)
|
||||
}
|
||||
@@ -31,8 +31,6 @@ func init() {
|
||||
for name, summary := range map[string]string{
|
||||
"discover": "run discovery for a device now",
|
||||
"profile": "test, record and draft device profiles",
|
||||
"backup": "write a backup of inventory, metrics, config and profiles",
|
||||
"restore": "restore a backup into a clean data dir",
|
||||
"loadtest": "run the scale test against simulated devices",
|
||||
} {
|
||||
if _, ok := commands[name]; !ok {
|
||||
|
||||
229
cmd/nmon/ops.go
Normal file
@@ -0,0 +1,229 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/v10networks/nmon/internal/app"
|
||||
"github.com/v10networks/nmon/internal/auth"
|
||||
"github.com/v10networks/nmon/internal/clock"
|
||||
"github.com/v10networks/nmon/internal/config"
|
||||
"github.com/v10networks/nmon/internal/keyrotate"
|
||||
"github.com/v10networks/nmon/internal/secrets"
|
||||
"github.com/v10networks/nmon/internal/store"
|
||||
)
|
||||
|
||||
func init() {
|
||||
register("key", "rotate the encryption key: nmon key rotate (nmon stopped)", keyCmd)
|
||||
register("unlock", "clear break-glass lockouts: nmon unlock [IP|all]", unlockCmd)
|
||||
register("secret", "store a named secret before the first start: nmon secret set NAME", secretCmd)
|
||||
register("store", "operate the metric stores of a running nmon: nmon store restart [hot|long]", storeCmd)
|
||||
}
|
||||
|
||||
// openInventory opens the inventory named by the shared store flags. keys may be nil for commands that never
|
||||
// decrypt (unlock).
|
||||
func openInventory(ctx context.Context, f *config.Flags, kr *secrets.Keyring) (store.Store, error) {
|
||||
if f.DataDir == "" {
|
||||
return nil, errors.New("--data-dir is required")
|
||||
}
|
||||
dsn := f.DBDSN
|
||||
if dsn == "" {
|
||||
if f.DBDriver != store.DriverSQLite {
|
||||
return nil, fmt.Errorf("--db-dsn is required for --db-driver %s", f.DBDriver)
|
||||
}
|
||||
dsn = config.InventoryDB(f.DataDir)
|
||||
}
|
||||
return store.Open(ctx, f.DBDriver, dsn, kr, clock.Real())
|
||||
}
|
||||
|
||||
// keyCmd is "nmon key rotate": a new key version for new data, every credential re-sealed under it, the old
|
||||
// key kept in the file so older backups still decrypt. nmon must be stopped: a running process holds the old keys.
|
||||
func keyCmd(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 || args[0] != "rotate" {
|
||||
return errors.New("usage: nmon key rotate --data-dir DIR --secret-key-file FILE (stop nmon first)")
|
||||
}
|
||||
var f config.Flags
|
||||
fs := newFlagSet("key rotate", "key rotate --data-dir DIR --secret-key-file FILE [flags]")
|
||||
storeFlags(fs, &f)
|
||||
fs.StringVar(&f.SecretKeyFile, "secret-key-file", app.DefaultSecretKeyFile, "the key file to rotate")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
res, err := keyrotate.Rotate(ctx, f.SecretKeyFile, func(ctx context.Context, kr *secrets.Keyring) (store.Store, error) {
|
||||
st, err := openInventory(ctx, &f, kr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return st, st.Migrate(ctx)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("key rotate: key version %d -> %d; re-encrypted %d SNMP credentials and %d secrets; "+
|
||||
"the previous key stays in %s so older backups still restore\n",
|
||||
res.OldVersion, res.NewVersion, res.Credentials, res.Secrets, f.SecretKeyFile)
|
||||
return nil
|
||||
}
|
||||
|
||||
// unlockCmd clears the break-glass lockout of one address, or of all. It works on the database, so it takes
|
||||
// effect in a running nmon too.
|
||||
func unlockCmd(ctx context.Context, args []string) error {
|
||||
target, rest, err := leadingArg(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var f config.Flags
|
||||
fs := newFlagSet("unlock", "unlock [IP|all] --data-dir DIR [flags]")
|
||||
storeFlags(fs, &f)
|
||||
if err := fs.Parse(rest); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if target == "" && fs.NArg() == 1 {
|
||||
target = fs.Arg(0)
|
||||
}
|
||||
if target == "" {
|
||||
target = "all"
|
||||
}
|
||||
st, err := openInventory(ctx, &f, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = st.Close() }() // the unlock is committed
|
||||
if err := st.Migrate(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := auth.Unlock(ctx, st, "console", target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("unlock: cleared %d lockout(s) for %s\n", n, target)
|
||||
return nil
|
||||
}
|
||||
|
||||
// storeCmd is "nmon store restart [hot|long]": resume a store the supervisor gave up on.
|
||||
func storeCmd(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 || args[0] != "restart" {
|
||||
return errors.New("usage: nmon store restart [hot|long] --api URL --token TOKEN")
|
||||
}
|
||||
name, rest, err := leadingArg(args[1:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var af apiFlags
|
||||
fs := flag.NewFlagSet("store restart", flag.ContinueOnError)
|
||||
af.register(fs)
|
||||
if err := fs.Parse(rest); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if err := af.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
names := []string{"hot", "long"}
|
||||
if name != "" {
|
||||
names = []string{name}
|
||||
}
|
||||
var errs []error
|
||||
for _, n := range names {
|
||||
resp, err := af.call(ctx, http.MethodPost, "/api/v1/admin/stores/"+n+"/restart", nil)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("%s: %w", n, err))
|
||||
continue
|
||||
}
|
||||
_ = resp.Body.Close() // 204: nothing to read
|
||||
fmt.Printf("store restart: %s store resumed\n", n)
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// secretCmd is "nmon secret set NAME": it stores a named secret (the OIDC client secret, a Proxmox token) in the
|
||||
// inventory without a running nmon, reading the value from --value-file or standard input. It exists because
|
||||
// OIDC needs its client secret at start while the API that stores secrets needs a way to sign in.
|
||||
func secretCmd(ctx context.Context, args []string) error {
|
||||
if len(args) < 2 || args[0] != "set" {
|
||||
return errors.New("usage: nmon secret set NAME --data-dir DIR --secret-key-file FILE [--value-file FILE] (value on stdin otherwise)")
|
||||
}
|
||||
name, rest, err := leadingArg(args[1:])
|
||||
if err != nil || name == "" {
|
||||
return errors.New("usage: nmon secret set NAME --data-dir DIR --secret-key-file FILE")
|
||||
}
|
||||
var f config.Flags
|
||||
var valueFile string
|
||||
fs := newFlagSet("secret set", "secret set NAME --data-dir DIR --secret-key-file FILE [flags]")
|
||||
storeFlags(fs, &f)
|
||||
fs.StringVar(&f.SecretKeyFile, "secret-key-file", app.DefaultSecretKeyFile, "the encryption key file")
|
||||
fs.StringVar(&valueFile, "value-file", "", "read the secret from this file instead of standard input")
|
||||
if err := fs.Parse(rest); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
value, err := readSecretValue(valueFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
kr, err := keyringForSecrets(&f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := openInventory(ctx, &f, kr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = st.Close() }() // the secret is committed
|
||||
if err := st.Migrate(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := st.PutSecret(ctx, name, value); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := st.AppendAudit(ctx, "console", "secret.put", "secret:"+name, nil, nil); err != nil { // the value is never audited
|
||||
return err
|
||||
}
|
||||
fmt.Printf("secret set: stored %q (encrypted with key version %d)\n", name, kr.CurrentVersion())
|
||||
return nil
|
||||
}
|
||||
|
||||
// readSecretValue reads the secret from a file or standard input, without its trailing newline.
|
||||
func readSecretValue(valueFile string) (string, error) {
|
||||
var src io.Reader = os.Stdin
|
||||
if valueFile != "" {
|
||||
vf, err := os.Open(valueFile)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = vf.Close() }() // read-only
|
||||
src = vf
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(src, 4097))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
value := strings.TrimRight(string(raw), "\r\n")
|
||||
if value == "" || len(value) > 4096 {
|
||||
return "", errors.New("the secret must be 1 to 4096 bytes")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// keyringForSecrets loads the key file. On a brand-new install (no key file and no inventory yet) it creates the
|
||||
// key first, as `nmon serve` would, so the OIDC client secret can be stored before the first start.
|
||||
func keyringForSecrets(f *config.Flags) (*secrets.Keyring, error) {
|
||||
if _, err := os.Stat(f.SecretKeyFile); errors.Is(err, os.ErrNotExist) {
|
||||
if _, err := os.Stat(config.InventoryDB(f.DataDir)); err == nil {
|
||||
return nil, fmt.Errorf("secret key file %s is missing but the inventory exists; restore the key file", f.SecretKeyFile)
|
||||
}
|
||||
if err := secrets.GenerateKeyFile(f.SecretKeyFile); err != nil {
|
||||
return nil, fmt.Errorf("generate secret key: %w", err)
|
||||
}
|
||||
fmt.Printf("secret set: created a new encryption key at %s; back it up now\n", f.SecretKeyFile)
|
||||
}
|
||||
kr, err := secrets.LoadKeyring(f.SecretKeyFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("secret key: %w", err)
|
||||
}
|
||||
return kr, nil
|
||||
}
|
||||
@@ -11,9 +11,8 @@ import (
|
||||
|
||||
"github.com/gosnmp/gosnmp"
|
||||
|
||||
"github.com/v10networks/nmon/internal/fixturegen"
|
||||
"github.com/v10networks/nmon/internal/simagent"
|
||||
"github.com/v10networks/nmon/internal/snmp"
|
||||
"github.com/v10networks/nmon/internal/snmprec"
|
||||
)
|
||||
|
||||
// defaultRecordSubtrees is what `profile record` walks when --subtree is not given:
|
||||
@@ -130,7 +129,7 @@ func recordDevice(ctx context.Context, o recordOpts, w io.Writer) (int, error) {
|
||||
return 0, err
|
||||
}
|
||||
defer func() { _ = s.Close() }() // read-only session
|
||||
var recs []simagent.Record
|
||||
var recs []snmprec.Record
|
||||
for _, root := range o.Subtrees {
|
||||
err := s.Walk(ctx, root, o.MaxReps, func(vb snmp.Varbind) error {
|
||||
if vb.Exception() {
|
||||
@@ -146,19 +145,19 @@ func recordDevice(ctx context.Context, o recordOpts, w io.Writer) (int, error) {
|
||||
return 0, fmt.Errorf("walk %s: %w", root, err)
|
||||
}
|
||||
}
|
||||
rec := simagent.NewRecording(recs)
|
||||
rec := snmprec.NewRecording(recs)
|
||||
if rec.Len() == 0 {
|
||||
return 0, fmt.Errorf("the device returned nothing under %v", o.Subtrees)
|
||||
}
|
||||
if err := fixturegen.WriteSnmprec(w, rec); err != nil {
|
||||
if err := snmprec.Write(w, rec); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return rec.Len(), nil
|
||||
}
|
||||
|
||||
// redact turns a varbind into a recording row, replacing secrets with REDACTED.
|
||||
func redact(vb snmp.Varbind, community string) simagent.Record {
|
||||
r := simagent.Record{OID: vb.OID, Type: vb.Type, Value: vb.Value}
|
||||
func redact(vb snmp.Varbind, community string) snmprec.Record {
|
||||
r := snmprec.Record{OID: vb.OID, Type: vb.Type, Value: vb.Value}
|
||||
if redactedOIDs[vb.OID] {
|
||||
r.Type, r.Value = gosnmp.OctetString, []byte(redacted)
|
||||
return r
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/v10networks/nmon/internal/profile"
|
||||
"github.com/v10networks/nmon/internal/simagent"
|
||||
"github.com/v10networks/nmon/internal/snmprec"
|
||||
)
|
||||
|
||||
func bundledMIBs(t *testing.T) string {
|
||||
@@ -121,7 +122,7 @@ const recordSample = `1.3.6.1.2.1.1.1.0|4|Test device
|
||||
`
|
||||
|
||||
func TestProfileRecordRedacts(t *testing.T) {
|
||||
rec, err := simagent.ParseRecording(strings.NewReader(recordSample))
|
||||
rec, err := snmprec.Parse(strings.NewReader(recordSample))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -148,7 +149,7 @@ func TestProfileRecordRedacts(t *testing.T) {
|
||||
if n := strings.Count(s, "REDACTED"); n != 4 {
|
||||
t.Errorf("v%s: want 4 REDACTED values, got %d:\n%s", ver, n, s)
|
||||
}
|
||||
got, err := simagent.ParseRecording(strings.NewReader(s))
|
||||
got, err := snmprec.Parse(strings.NewReader(s))
|
||||
if err != nil {
|
||||
t.Fatalf("v%s: output does not parse: %v", ver, err)
|
||||
}
|
||||
@@ -188,7 +189,7 @@ func TestProfileTestArgs(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestProfileTestPrintsMetrics(t *testing.T) {
|
||||
rec, err := simagent.LoadRecording("../../testdata/snmprec/juniper-junos.snmprec")
|
||||
rec, err := snmprec.Load("../../testdata/snmprec/juniper-junos.snmprec")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -222,3 +223,20 @@ func TestNmonDoesNotImportLibreNMS(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dev and test machinery stays out of the product binary: nmon-devtools and tests own the simulator,
|
||||
// the fixture generator and the fixtures. `nmon profile record` needs only internal/snmprec.
|
||||
func TestNmonDoesNotLinkDevMachinery(t *testing.T) {
|
||||
out, err := exec.Command("go", "list", "-deps", ".").CombinedOutput()
|
||||
if err != nil {
|
||||
t.Skipf("go list unavailable: %v\n%s", err, out)
|
||||
}
|
||||
banned := []string{"internal/simagent", "internal/fixturegen", "internal/fixtures", "internal/librenms", "internal/testutil"}
|
||||
for _, pkg := range strings.Fields(string(out)) {
|
||||
for _, b := range banned {
|
||||
if strings.HasSuffix(pkg, "/"+b) {
|
||||
t.Errorf("cmd/nmon depends on %s", pkg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
55
cmd/nmon/restore.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/v10networks/nmon/internal/app"
|
||||
"github.com/v10networks/nmon/internal/backup"
|
||||
"github.com/v10networks/nmon/internal/config"
|
||||
"github.com/v10networks/nmon/internal/vmsup"
|
||||
)
|
||||
|
||||
func init() {
|
||||
register("restore", "restore a backup into a clean data dir (nmon stopped)", restoreCmd)
|
||||
}
|
||||
|
||||
// restoreCmd unpacks a backup into an empty data directory and verifies it before it reports success. It
|
||||
// runs with nmon stopped, because it starts the restored metric stores itself to compare their series.
|
||||
func restoreCmd(ctx context.Context, args []string) error {
|
||||
var f config.Flags
|
||||
fs := newFlagSet("restore", "restore FILE --data-dir CLEAN_DIR [--secret-key-file PATH]")
|
||||
fs.StringVar(&f.DataDir, "data-dir", "", "the clean (absent or empty) data folder to restore into (required)")
|
||||
fs.StringVar(&f.SecretKeyFile, "secret-key-file", "",
|
||||
"where to write the key file if the backup contains one (default <data-dir>/secret.key; nmon serve wants it outside the data dir)")
|
||||
file, rest, err := leadingArg(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fs.Parse(rest); err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if file == "" && fs.NArg() == 1 {
|
||||
file = fs.Arg(0)
|
||||
}
|
||||
if file == "" || f.DataDir == "" || fs.NArg() > 1 {
|
||||
return errors.New("usage: nmon restore FILE --data-dir CLEAN_DIR")
|
||||
}
|
||||
res, err := backup.Restore(ctx, backup.RestoreOptions{
|
||||
File: file, DataDir: f.DataDir, KeyFile: f.SecretKeyFile, Log: os.Stdout,
|
||||
Verifier: backup.NewVMVerifier(vmsup.Options{DataDir: f.DataDir}),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("restore: done and verified: %d inventory rows and %d series matched the manifest\n", res.RowsVerified, res.SeriesVerified)
|
||||
if res.KeyRestoredTo != "" {
|
||||
fmt.Printf("restore: the encryption key was restored to %s\n", res.KeyRestoredTo)
|
||||
} else {
|
||||
fmt.Printf("restore: this backup has NO key file; start nmon with --secret-key-file pointing at the key that sealed it "+
|
||||
"(default %s)\n", app.DefaultSecretKeyFile)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
108
cmd/nmon/rollup.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/v10networks/nmon/internal/cliout"
|
||||
"github.com/v10networks/nmon/internal/rollup"
|
||||
)
|
||||
|
||||
func init() {
|
||||
register("rollup", "repair rollup windows (asks a running nmon)", rollupCmd)
|
||||
}
|
||||
|
||||
const rollupUsage = "usage: nmon rollup repair <from> <to> [--api URL] [--token TOKEN]\n\n" +
|
||||
"Re-runs every rollup window overlapping [from, to) on the running nmon, writing a new version of\n" +
|
||||
"each. The range must be inside hot retention (default 30 days). Times are RFC 3339 (2026-10-20T08:00:00Z)\n" +
|
||||
"or a UTC date (2026-10-20); to is exclusive."
|
||||
|
||||
func rollupCmd(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 || args[0] != "repair" {
|
||||
return fmt.Errorf("%s", rollupUsage)
|
||||
}
|
||||
fs := profileFlagSet("rollup repair", "rollup repair <from> <to> [--api URL]")
|
||||
var api, token string
|
||||
var timeout time.Duration
|
||||
fs.StringVar(&api, "api", "http://[::1]:8443", "base URL of the running nmon")
|
||||
fs.StringVar(&token, "token", os.Getenv("NMON_TOKEN"), "admin API token (default $NMON_TOKEN)")
|
||||
fs.DurationVar(&timeout, "timeout", 30*time.Minute, "how long to wait for the repair")
|
||||
pos, err := parseInterspersed(fs, args[1:])
|
||||
if err != nil {
|
||||
return flagErr(err)
|
||||
}
|
||||
if len(pos) != 2 {
|
||||
return fmt.Errorf("%s", rollupUsage)
|
||||
}
|
||||
from, err := parseRepairTime(pos[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
to, err := parseRepairTime(pos[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
rep, err := requestRepair(ctx, api, token, rollup.RepairRequest{From: from, To: to})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := cliout.New(os.Stdout)
|
||||
w.Printf("repaired %s to %s: %d five-minute windows, %d hourly windows rewritten\n",
|
||||
rep.From.Format(time.RFC3339), rep.To.Format(time.RFC3339), rep.FiveMinutes, rep.Hours)
|
||||
return w.Err()
|
||||
}
|
||||
|
||||
func parseRepairTime(s string) (time.Time, error) {
|
||||
for _, layout := range []string{time.RFC3339, "2006-01-02T15:04", "2006-01-02"} {
|
||||
if t, err := time.ParseInLocation(layout, s, time.UTC); err == nil {
|
||||
return t.UTC(), nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("cannot parse %q as RFC 3339 or YYYY-MM-DD", s)
|
||||
}
|
||||
|
||||
// requestRepair calls POST /api/v1/rollup/repair, which internal/app mounts on
|
||||
// rollup.Job.Repair.
|
||||
func requestRepair(ctx context.Context, api, token string, rr rollup.RepairRequest) (*rollup.RepairReport, error) {
|
||||
body, err := json.Marshal(rr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(api, "/")+"/api/v1/rollup/repair", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot reach nmon at %s (is it running? use --api): %w", api, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }() // body fully read below; a close error changes nothing
|
||||
out, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var p struct{ Title, Detail string }
|
||||
_ = json.Unmarshal(out, &p)
|
||||
msg := p.Detail
|
||||
if msg == "" {
|
||||
msg = p.Title
|
||||
}
|
||||
return nil, fmt.Errorf("repair refused: %d %s", resp.StatusCode, msg)
|
||||
}
|
||||
var rep rollup.RepairReport
|
||||
if err := json.Unmarshal(out, &rep); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &rep, nil
|
||||
}
|
||||
48
cmd/nmon/rollup_test.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/v10networks/nmon/internal/rollup"
|
||||
)
|
||||
|
||||
func TestRollupRepairSendsRangeAndTokenToRunningNmon(t *testing.T) {
|
||||
var got rollup.RepairRequest
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/rollup/repair" || r.Header.Get("Authorization") != "Bearer tok" {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
_ = json.NewEncoder(w).Encode(rollup.RepairReport{From: got.From, To: got.To, FiveMinutes: 12, Hours: 1})
|
||||
}))
|
||||
defer srv.Close()
|
||||
from, to := time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC), time.Date(2026, 10, 20, 9, 0, 0, 0, time.UTC)
|
||||
rep, err := requestRepair(context.Background(), srv.URL, "tok", rollup.RepairRequest{From: from, To: to})
|
||||
if err != nil || rep.FiveMinutes != 12 || !got.From.Equal(from) || !got.To.Equal(to) {
|
||||
t.Fatalf("rep=%+v got=%+v err=%v", rep, got, err)
|
||||
}
|
||||
if _, err := requestRepair(context.Background(), srv.URL, "wrong", rollup.RepairRequest{}); err == nil {
|
||||
t.Error("a refused repair must be an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRepairTimeAcceptsDatesAndRFC3339(t *testing.T) {
|
||||
for in, want := range map[string]time.Time{
|
||||
"2026-10-20": time.Date(2026, 10, 20, 0, 0, 0, 0, time.UTC),
|
||||
"2026-10-20T08:30": time.Date(2026, 10, 20, 8, 30, 0, 0, time.UTC),
|
||||
"2026-10-20T08:00:00Z": time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC),
|
||||
} {
|
||||
if got, err := parseRepairTime(in); err != nil || !got.Equal(want) {
|
||||
t.Errorf("%s: %v %v", in, got, err)
|
||||
}
|
||||
}
|
||||
if _, err := parseRepairTime("yesterday"); err == nil {
|
||||
t.Error("want error")
|
||||
}
|
||||
}
|
||||
@@ -51,17 +51,31 @@ func storeFlags(fs *flag.FlagSet, f *config.Flags) {
|
||||
|
||||
func serve(ctx context.Context, args []string) error {
|
||||
var f config.Flags
|
||||
fs := newFlagSet("serve", "serve --data-dir DIR --insecure-http [flags]")
|
||||
fs := newFlagSet("serve", "serve --data-dir DIR (--tls-cert F --tls-key F | --acme-host H | --insecure-http) [flags]")
|
||||
storeFlags(fs, &f)
|
||||
fs.StringVar(&f.SecretKeyFile, "secret-key-file", app.DefaultSecretKeyFile,
|
||||
"SNMP credential key file; created on first run; must be outside --data-dir")
|
||||
fs.StringVar(&f.Listen, "listen", app.DefaultListen, "address for the API")
|
||||
fs.BoolVar(&f.InsecureHTTP, "insecure-http", false, "serve plain HTTP with no authentication (required until TLS and auth arrive in M6)")
|
||||
fs.BoolVar(&f.InsecureHTTP, "insecure-http", false,
|
||||
"development only: serve plain HTTP (insecure cookies); with no auth.oidc or auth.break_glass_file configured, "+
|
||||
"authentication is off and every request is an admin")
|
||||
fs.StringVar(&f.TLSCert, "tls-cert", "", "PEM certificate chain for HTTPS (reloaded on SIGHUP); needs --tls-key")
|
||||
fs.StringVar(&f.TLSKey, "tls-key", "", "PEM private key for --tls-cert")
|
||||
fs.Func("acme-host", "obtain a Let's Encrypt certificate for this host name (repeatable); needs port 80 reachable", func(v string) error {
|
||||
f.ACMEHosts = append(f.ACMEHosts, v)
|
||||
return nil
|
||||
})
|
||||
fs.StringVar(&f.ACMEEmail, "acme-email", "", "contact address for the ACME account")
|
||||
fs.StringVar(&f.ACMEListen, "acme-listen", app.DefaultACMEListen, "address of the ACME http-01 challenge listener")
|
||||
fs.StringVar(&f.VMHotURL, "vm-hot-url", "", "use this VictoriaMetrics instance as the hot store instead of the embedded one")
|
||||
fs.StringVar(&f.VMLongURL, "vm-long-url", "", "use this VictoriaMetrics instance as the long store instead of the embedded one")
|
||||
fs.StringVar(&f.TrapListen, "trap-listen", app.DefaultTrapListen,
|
||||
"UDP address for SNMP traps; empty disables the receiver "+
|
||||
"(port 162 needs CAP_NET_BIND_SERVICE; without it traps are off and polling continues)")
|
||||
fs.StringVar(&f.GraphiteListen, "graphite-listen", app.DefaultGraphiteListen,
|
||||
"TCP address for Graphite plaintext push (first line \"token <secret>\"); empty disables the listener")
|
||||
fs.StringVar(&f.ICMP, "icmp", config.ICMPAuto,
|
||||
"ICMP probing: auto, or off for hosts where ICMP is not permitted (SNMP alone then decides if a device is down)")
|
||||
fs.IntVar(&f.MaxInflight, "max-inflight", 512, "most SNMP polls in flight at once")
|
||||
fs.DurationVar(&f.PollInterval, "poll-interval", 0, "dev: SNMP poll interval (default 60s)")
|
||||
fs.IntVar(&f.SNMPPort, "snmp-port", 0, "dev: UDP port of every device's agent (default 161)")
|
||||
|
||||
@@ -16,8 +16,29 @@ conscious, reviewed exception.
|
||||
| 9 | `nmon profile import-librenms <repo-path>` is an nmon subcommand | A separate binary, `nmon-librenms-import` (`cmd/nmon-librenms-import`), run offline before nmon. It writes draft profiles that the operator reviews and copies into `<data-dir>/profiles/`. `nmon` neither links nor exposes it. | User decision (2026-10-22). It keeps the importer out of the product binary and makes "the converter never runs at serve time" structural. | M2 |
|
||||
| 10 | `scripts/openapi-diff` fails on an incompatible change (M3 milestone) | The differ is the Go package `internal/openapidiff` (unit-tested, run with `go run ./internal/openapidiff/cmd/openapidiff`), driven by `scripts/openapi-check.sh`, which `make gate-m3` and the CI `openapi` job call. | A Go package is testable and linted like the rest of the code; the script only fetches the spec at the last `m*`/`v*` tag. No new dependency. | M3 |
|
||||
| 11 | Built assets are embedded from `web/dist` into `internal/webui` | `make web` copies `web/dist` to `internal/webui/dist` (git-ignored, `.gitkeep` tracked); a committed `internal/webui/placeholder/index.html` ("UI not built") is served when `dist` has no `index.html`. | A tracked `dist/index.html` would be overwritten by every build and dirty the tree, and a built UI must never be committed. `go build` still works without node. | M3 |
|
||||
| 12 | (not specified) | Developer tools (`backfill`, `seed-demo`) are a separate executable, `cmd/nmon-devtools` (`make devtools` builds `nmon-devtools`), never shipped. It talks to a running nmon over its HTTP API and to the hot store via `--hot-url`. `nmon` has no `devtools` command; a depguard rule keeps `cmd/nmon` from importing `internal/simagent` or `internal/fixturegen` beyond `profile_record.go`, which already used them for `nmon profile record` in M2. | The gate needs 30 days of history without waiting 30 days, and live screenshots need a simulated network. See `docs/dev.md`. | M3 |
|
||||
| 12 | (not specified) | Developer tools (`backfill`, `seed-demo`) are a separate executable, `cmd/nmon-devtools` (`make devtools` builds `nmon-devtools`), never shipped. It talks to a running nmon over its HTTP API and to the hot store via `--hot-url`. `nmon` has no `devtools` command; depguard and a `go list -deps` test keep `cmd/nmon` from linking `internal/simagent`, `internal/fixturegen`, `internal/fixtures` or `internal/testutil`; `nmon profile record` uses only the `.snmprec` format in `internal/snmprec`. | The gate needs 30 days of history without waiting 30 days, and live screenshots need a simulated network. See `docs/dev.md`. | M3 |
|
||||
| 13 | (not specified) `/docs` API reference | `/docs` serves a vendored, pinned swagger-ui-dist 5.17.14 (Apache-2.0, about 1.6 MB) through `embed.FS`. | huma's built-in renderers load their assets from a CDN, which an offline monitor cannot rely on. | M3 |
|
||||
| 14 | M2 defined provisional `poller/health` and `identity-reviews` responses | Both were reshaped in M3 to the reviewed UI contract, before any `openapi.json` existed, so the route freeze starts at `m3`, the first tag with a checked-in spec. | The M2 shapes had no consumer. `scripts/openapi-check.sh` passes against `m2` with a note and diffs for real from `m3`. | M3 |
|
||||
| 15 | A single-signal failure (ICMP only or SNMP only) is a warning | The warning is held as pending for 5 min before it notifies, and is closed silently if the device goes down meanwhile. | Otherwise a real outage whose second signal fails seconds later sends a spurious warning first. | M4 |
|
||||
| 16 | An unsupported probe is unknown, never failed | When ICMP is unsupported (host can't open unprivileged ICMP, or per device), SNMP alone decides down, as with `icmp_blocked`, and a one-time `icmp_unsupported` device warning is raised. | Otherwise nmon could never declare a device down on such a host, and nobody would notice. | M4 |
|
||||
| 17 | M6 gate: "the 2,000-device loadtest cycle finishes under 40 s"; the loadtest acceptance lines (200k interfaces in 40 s, memory stable over 30 min, peak RSS/disk/ingest/latency report, backup during load) | **Skipped** (approved by the owner, 2026-10-22: "skip the device load test… put this in prod asap"). The M6 gate checks only that a viewer gets 403 on PUT. Backup/restore is verified on a normal-size dataset instead of under load. Scale is unproven beyond the fixture and gate sizes (24 devices). | Time to production. | M6 |
|
||||
| 18 | Push token format not specified | The secret is `nmp_<id>_<base32 of 160 random bits>`; the row stores a salted SHA-256 (`<salt>$<hash>`). | The id selects the row, so authentication is one primary-key lookup and never scans or compares other tokens. | M5 |
|
||||
| 19 | `rollup_windows` status is `done` or `partial` | A third status, `pending`, is written before the long-store write begins. | A crash between the write and the commit still tells the next run which version number is taken, so it writes `v+1`. | M5 |
|
||||
| 20 | `v` is a version number on rollup series | `v` is on `nmon_if_rate_bps_5m`, `_avg_1h`, `_max_1h` and the gauge series, encoded `YYYYMM*1000+n` (UTC month of the window, then the version). | Numeric, so MetricsQL can compare versions; the month prefix lets retention drop whole months of 5 m series. Readers use `internal/longq.LatestVersion`. | M5 |
|
||||
| 21 | Gauge rollups: "a 5 m average, plus a 1 h avg, max and min" | Series are named `<name>_avg_5m`, `<name>_avg_1h`, `<name>_max_1h`, `<name>_min_1h`, with the source labels plus `v`. | The suffix keeps the source name searchable and cannot collide with a polled metric (such names are not rolled up). | M5 |
|
||||
| 22 | 5 m series are deleted past `retention.fiveminute` | Whole calendar months are deleted with `delete_series` once they ended before `now - retention.fiveminute`, so 5 m data lives 4 to 5 months. | Open-source VictoriaMetrics has one retention per process and no time-ranged delete; the `v` prefix makes each 5 m series one month. | M5 |
|
||||
| 23 | Rollup writes go through the write queue | Rollup long writes bypass the queue: a synchronous, acknowledged import, then `force_flush`, then a read-back count. | The queue is fire-and-forget (it can drop after 60 s); a window may be recorded done only once the store has it. | M5 |
|
||||
| 24 | Unreliable (32-bit) interfaces are excluded from p95 and group sums | They are also never rolled up, and a graph of one returns no series. | A rate from a wrapping counter is wrong whichever tier stores it. | M5 |
|
||||
| 25 | `nmon_group_p95_bps{group, dir, month, members_hash}` | Group (and interface) p95 records also carry a `coverage` label. | A figure below 90% coverage must never be shown without it. | M5 |
|
||||
| 26 | Check samples labelled by device | `nmon_check_up`, `nmon_check_latency_seconds` and `nmon_tls_expiry_seconds` also carry `check` (the check id). | A device can have several checks. | M5 |
|
||||
| 27 | Proxmox nodes are devices | A node is the existing SNMP device with that name (or sysName), else a new `check_only` device; its health is the status the API reports. Guests are `vm`/`container` devices keyed by `pve:<cluster>/<vmid>`. | `cluster/resources` has no addresses, so nothing but the name can match a node; a missing SNMP device must not orphan its guests. | M5 |
|
||||
| 28 | Pushed series carry only `device` | Pushed series also carry `push="1"` (senders cannot set it). | The device page lists what a push sender wrote without guessing from metric names. | M5 |
|
||||
| 29 | Ingest caps, late p95 months and a stalled rollup "raise an alert" | They are rows of the alerts table with rules `ingest_<kind>`, `p95_late`, `rollup_stalled` and no device, kept open until cleared (ingest alarms close 20 min after the last trip). | They are not metric rules and have no device; the metric-rule evaluator leaves these rule names alone. | M5 |
|
||||
| 30 | Proxmox cluster config could carry the token secret | Only `secret_name` exists; the secret is stored encrypted via `PUT /api/v1/secrets/{name}` and cannot be read back. | `config.yaml` is plain text. | M5 |
|
||||
| 31 | HTTPS by default; plain HTTP only with `--insecure-http` (Auth: OIDC only) | With `--insecure-http` **and** neither `auth.oidc` nor `auth.break_glass_file` configured, nmon runs in **dev-open mode**: every request is the admin principal `dev`, a loud warning is logged at start and the UI shows "Authentication disabled — development mode". Any start over TLS with no sign-in method configured refuses to start. If either sign-in method is configured, `--insecure-http` only means plain HTTP and cookies without `Secure`; authentication stays on. | The M1-M5 gates (and local development) run `nmon serve --insecure-http` with no IdP; M6 must not break them. The refusal for TLS-without-auth keeps the unsafe mode from ever being a production start. | M6 |
|
||||
| 32 | Settings (retention, alert thresholds, IdP, receivers, outbound allow-list) are edited in the UI and reloaded | `PUT /api/v1/settings` and SIGHUP reload in place: alert receivers, the outbound allow-list, trusted proxies, the nightly backup schedule, disk thresholds and the retired-device purge period. Alert rules and their interval, retention, timezone and sites, Proxmox, checks, `auth.oidc`, break-glass, session lifetimes, listen address, TLS and the data dir are saved but reported as `restart_required`. An invalid document is a 422 and changes nothing; the file is rewritten from the validated structure, so comments in a hand-edited `config.yaml` are lost by a UI save. | Those parts are built once at start (stores, evaluators, the OIDC client); rebuilding them live is a larger change than the risk of a restart warrants for v1. | M6 |
|
||||
| 33 | `nmon backup <file>` takes an online snapshot | `nmon backup` is a client of the running nmon: it calls `POST /api/v1/admin/backup` (admin token), nmon runs the backup in a scratch file under `<data-dir>/backups/.downloads/`, streams it and deletes it, and the client saves it atomically (temp file + rename). The key-included line is printed from the archive's own manifest. `nmon restore` runs offline and starts the restored stores for a moment to verify series. | Only the running process may touch the live stores and the database. | M6 |
|
||||
| 34 | (not specified) | Beyond the spec, additive to the API/CLI: `GET /api/v1/me`, `GET /api/v1/auth/options` (public), `GET /api/v1/audit` (admin), `POST /api/v1/admin/backup`, `POST /api/v1/admin/stores/{name}/restart`, `POST /api/v1/devices/{slug}/purge`, `POST /api/v1/devices/import`, `GET/PUT /api/v1/settings`; `nmon secret set NAME` (stores the OIDC client secret before the first start; it also creates the key on a brand-new install); API tokens (viewer, admin) share `/api/v1/tokens` with push tokens and have ids like `a7` because the two kinds live in different tables. | OIDC needs its client secret at start, while the API that stores secrets needs a way to sign in: the CLI breaks the cycle. The audit list makes "every use is logged" checkable. | M6 |
|
||||
| 35 | Port descriptions imported from CSV | Interfaces have a new operator-owned `description` column (migration 8). The CSV import and the API write it; discovery rewrites `ifalias` from the device on every run and never touches `description`. Interface search `q` matches ifname, ifalias and description. | A description typed into `ifalias` would be overwritten at the next discovery. | M6 |
|
||||
| 36 | OIDC login with a browser flow; break-glass as a local login | **No login UI** (owner decision). Every route except `/auth/*`, `/healthz` and push ingest needs a credential, the SPA's files included: an unauthenticated page load is a 302 to `/auth/login?return=<url>` (the OIDC flow; the return target must be a same-site path), an API call without credentials is a 401 problem+json. Break-glass is `GET /auth/breakglass` with HTTP Basic, so the browser's own prompt appears; success sets a session and redirects to `return` or `/` (`POST /auth/breakglass` with JSON stays for scripts). When no IdP is configured the redirect goes to the break-glass prompt. Logout is `POST /auth/logout`, then `/auth/signedout` (static HTML). `/docs` and `/openapi*` need the viewer role. A missing OIDC client secret at start leaves OIDC off with a warning. | The IdP is the login page; a second one would be a second thing to secure. | M6 |
|
||||
| 37 | Disk guard: "ingest throttled below the reserve" | Throttle answers push ingest with 429 + Retry-After below the 5% reserve; the poller keeps writing (its volume is bounded by the inventory). Above 90% used, new series are dropped on the nmon side (poller, push and checks) while known series continue; disk alarms are re-raised each minute while the condition holds and resolve themselves 3 minutes after it clears. | VictoriaMetrics series limits are start-up flags; the guard is nmon-side admission. | M6 |
|
||||
|
||||
@@ -44,7 +44,16 @@ by the store.
|
||||
|
||||
It starts the simulated SNMP agents in-process on `[::1]`, each on its own port (passed to the API as `snmp.port`), adds the devices through the API (a 48-port switch, access switches, routers, a firewall, a UPS, the counters fixture, a v1 device with 32-bit counters, and one whose agent is stopped after seeding so it reads as down), waits for live polls, back-fills 31 days, writes `NMON_DEVICE`, `NMON_DEVICE_48`, `NMON_DEVICE_32BIT` and `NMON_DEVICE_DOWN` to `--env-out`, and keeps the agents answering until interrupted. The simulated 64-bit counters start at 1e14 so history fits below them.
|
||||
|
||||
**oidc-mock** runs `internal/auth/oidctest` as a standalone OpenID Connect issuer for the M6 gate and for screenshots:
|
||||
|
||||
nmon-devtools oidc-mock --issuer-file F --port-file P [--client-id nmon --client-secret s3cret]
|
||||
curl 'http://[::1]:PORT/user?sub=viewer-1&name=Vera&groups=staff' # who the next login is
|
||||
|
||||
The issuer approves every login at once as the current user (the control endpoint changes it); `--issuer-file` receives the issuer URL for `auth.oidc.issuer`. **bcrypt PASSWORD** prints a bcrypt hash, the content of a break-glass file. Every devtools command that calls the API sends `Authorization: Bearer $NMON_TOKEN` when that variable is set (an nmon with authentication on needs an admin token).
|
||||
|
||||
## Gates
|
||||
|
||||
`make gate-m3` runs everything above end to end and writes live screenshots to `docs/screenshots/M3/`.
|
||||
It needs Playwright's chromium: `cd web && npx playwright install chromium`.
|
||||
|
||||
`make gate-m6` starts nmon with a mock IdP and a break-glass file (authentication ON) and checks roles, tokens, break-glass lock-out, backup/restore, key rotation, settings reload, CSV import and the UI; its live screenshots go to `docs/screenshots/M6/`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# M6: Auth and ops
|
||||
|
||||
**Gate:** a viewer gets 403 on PUT, and the 2,000-device loadtest cycle finishes under 40 s.
|
||||
**Gate:** a viewer gets 403 on PUT. ~~and the 2,000-device loadtest cycle finishes under 40 s~~ (skipped: approved deviation, see `docs/DEVIATIONS.md`; the owner prioritised getting to production).
|
||||
**Gate command:** `make gate-m6`. It runs the viewer-fuzz test (every state-changing route with a viewer session and a viewer token → 403) and then `nmon loadtest --devices 2000 --ports 100 --duration 30m`, which must report cycle p100 < 40 s, zero deadline misses, write-queue high-water < 50%, and stable RSS. It also prints the report metrics (peak RSS, steady and peak disk, ingest samples/s, p95 device-page latency, write-queue high-water, backlog recovery after a 5 min store outage). Finally it runs backup-restore during load.
|
||||
|
||||
## Scope
|
||||
@@ -25,6 +25,11 @@
|
||||
- `nmon loadtest`: in-process simagents (2,000 × 100 ports on `::1` with distinct ports), nmon serve in-process, traps plus push plus rollup running, metrics collected from `nmon_` series and `/proc/self/status`.
|
||||
- Platforms: `make build-arm64` cross-compiles. Non-Linux builds compile without `vmembed` and require `--vm-*-url`.
|
||||
|
||||
### Decisions recorded during M6 (see `docs/DEVIATIONS.md` rows 31-37)
|
||||
- **No login UI** (owner decision): page loads without a session redirect (302) to `/auth/login?return=...` (OIDC); API calls get 401; break-glass is `GET /auth/breakglass` with HTTP Basic; the SPA has a user menu (name, role, sign out) and role-aware controls but no login page. Dev-open mode is unchanged.
|
||||
- Hot reload covers receivers, the outbound allow-list, trusted proxies, backup schedule, disk thresholds and the purge period; the rest is `restart_required`.
|
||||
- Interfaces gained an operator-owned `description` (migration 8) that the CSV port import writes and discovery never overwrites.
|
||||
|
||||
## Work packages
|
||||
|
||||
| WP | Files | Depends on |
|
||||
@@ -32,7 +37,7 @@
|
||||
| WP1 OIDC, sessions, CSRF, tokens, break-glass, proxy, TLS | `internal/auth/**`, API middleware | M3 API |
|
||||
| WP2 Backup, restore, key rotate, disk guard, store restart | `internal/backup/**`, `internal/diskguard/**`, `cmd/nmon/{backup,restore,key,store,unlock}.go` | M1 vmsup, store |
|
||||
| WP3 Config reload, settings API and UI, CSV import, purge | `internal/config/**`, `internal/api/settings*.go`, `internal/importcsv/**`, `web/src/routes/settings*` | M4 deps |
|
||||
| WP4 Loadtest, viewer fuzz, gate | `internal/loadtest/**`, `cmd/nmon/loadtest.go`, `scripts/gate-m6.sh` | all |
|
||||
| WP4 Viewer fuzz, backup/restore check, gate (loadtest skipped, approved deviation) | `internal/loadtest/**`, `cmd/nmon/loadtest.go`, `scripts/gate-m6.sh` | all |
|
||||
|
||||
## Acceptance lines closed
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ its **Gate log** is filled in when the gate passes. A milestone is done only whe
|
||||
| M3 | Graphs and UI | a port's in/out graph renders at 1 h, 24 h and 30 d from the counters fixture | [M3](M3-graphs-and-ui.md) | **passed**, tagged `m3` |
|
||||
| M4 | Alerting | stopping a parent fixture sends one notification naming it and its children | [M4](M4-alerting.md) | in progress (WP1 reach and deps, WP2 rules, WP3 notify done) |
|
||||
| M5 | Push ingest, rollup, checks | a replayed Proxmox sample shows under its node and a 2 y query hits the 1 h tier | [M5](M5-ingest-rollup-checks.md) | planned |
|
||||
| M6 | Auth and ops | a viewer gets 403 on PUT and the 2,000-device loadtest cycle finishes under 40 s | [M6](M6-auth-and-ops.md) | planned |
|
||||
| M6 | Auth and ops | a viewer gets 403 on PUT (2,000-device loadtest skipped, approved deviation) | [M6](M6-auth-and-ops.md) | planned |
|
||||
| M7 | gNMI streaming | after v1; not built in this run | — | out of scope |
|
||||
|
||||
## How the work is run
|
||||
@@ -47,6 +47,8 @@ Departures from the spec are recorded in [`docs/DEVIATIONS.md`](../DEVIATIONS.md
|
||||
|
||||
- **Deployment playbook**: install layout (binary, `/usr/share/nmon/mibs` sidecar, systemd unit granting port 162, key file location), TLS/ACME or proxy setup, IdP configuration, backups, and upgrades. Raised by the user on 2026-10-22; deliberately postponed.
|
||||
|
||||
- **Web push notifications (v2)**: a `webpush` receiver kind in `internal/notify` (RFC 8291 payload encryption, RFC 8292 VAPID, standard-library crypto), per-user subscriptions (needs M6 users), a service worker in the UI, and push endpoints in the outbound allow-list. Out of v1 per the spec's non-goals ("alerts go to webhooks and email only"). Owner deferred it to v2 on 2026-10-22. Until then, a webhook receiver pointed at ntfy or Gotify gives phone push.
|
||||
|
||||
## Review artifacts
|
||||
|
||||
- From M3 on, each UI milestone's gate captures Playwright screenshots of every page into `docs/screenshots/<milestone>/` for the user to review.
|
||||
|
||||
68
docs/operations.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Operating nmon
|
||||
|
||||
How to run, secure, back up and maintain a production nmon. Design background: `docs/spec/spec.md` ("Auth", "Operations").
|
||||
|
||||
## Starting
|
||||
|
||||
nmon serve --data-dir /var/lib/nmon --secret-key-file /etc/nmon/secret.key \
|
||||
--tls-cert /etc/nmon/tls.crt --tls-key /etc/nmon/tls.key
|
||||
|
||||
- **HTTPS is the default.** Pass a certificate pair (`--tls-cert`, `--tls-key`; `SIGHUP` reloads them without dropping connections) or Let's Encrypt (`--acme-host nmon.example.net` repeatable, `--acme-email you@example.net`; nmon answers the http-01 challenge on `--acme-listen`, default `:80`, certificates are cached in `<data-dir>/acme`). Without either, `serve` refuses to start and says so. `--insecure-http` is for development: plain HTTP, cookies without `Secure`.
|
||||
- **A sign-in method is required** over TLS (`auth.oidc` and/or `auth.break_glass_file` in `config.yaml`). With `--insecure-http` and neither configured nmon runs in *dev-open mode* (everyone is admin `dev`; a banner says so); never expose that port.
|
||||
- Behind a reverse proxy, list it in `auth.trusted_proxies`; `X-Forwarded-*` is ignored from anyone else.
|
||||
|
||||
## Sign-in
|
||||
|
||||
`config.yaml`:
|
||||
|
||||
auth:
|
||||
oidc:
|
||||
issuer: https://idp.example.net/realms/net
|
||||
client_id: nmon
|
||||
client_secret_name: oidc-client # the secret itself is never in this file
|
||||
redirect_url: https://nmon.example.net/auth/callback
|
||||
groups_claim: groups
|
||||
admin_group: nmon-admins # members are admins; every other user is a viewer
|
||||
break_glass_file: /etc/nmon/breakglass # bcrypt hash, "hash" or "user:hash", created by you
|
||||
|
||||
Store the client secret before the first start: `printf '%s\n' "$SECRET" | nmon secret set oidc-client --data-dir D --secret-key-file K` (it can also be set later with `PUT /api/v1/secrets/oidc-client`; OIDC stays off until the secret exists). The break-glass file holds one bcrypt hash (`$2a$`/`$2b$`), made with any bcrypt tool (the source tree's `nmon-devtools bcrypt PASSWORD` works); keep it readable by the nmon user only.
|
||||
|
||||
- There is no login page. Opening nmon without a session redirects to the IdP and back; API clients use a token. If the IdP is down, open `/auth/breakglass`: the browser asks for the local admin user and password (HTTP Basic), and a successful sign-in lands on the page you asked for.
|
||||
- Break-glass: five wrong passwords lock the source address for 15 minutes; every use and every lock is audited and raises an alert. `nmon unlock [IP|all] --data-dir D` clears locks, also while nmon runs.
|
||||
- API tokens: an admin mints viewer, admin or push tokens (`POST /api/v1/tokens`, or Settings, API tokens). Use `Authorization: Bearer nma_...`. A push token works for ingest only. Revoking takes effect on the next request.
|
||||
- `GET /api/v1/audit` (admin) lists who did what.
|
||||
|
||||
## Backup and restore
|
||||
|
||||
A running nmon owns the stores, so copying the data folder is **not** a backup.
|
||||
|
||||
nmon backup /backups/nmon.tar --api https://nmon.example.net --token nma_... # key NOT included
|
||||
nmon backup /backups/nmon.tar --include-key --api ... --token ... # key included
|
||||
|
||||
Every run prints whether the key file is in the archive. **Lose the key file and a restore has an inventory with no SNMP credentials.** The nightly schedule is `backup: {at: "02:30", dir: /var/backups/nmon, keep: 7}` (time in the configured timezone, default dir `<data-dir>/backups`); a failed run raises the `backup_failed` alert. A backup is refused when the disk is below its 5% reserve.
|
||||
|
||||
Restore with nmon stopped, into a clean directory:
|
||||
|
||||
nmon restore /backups/nmon.tar --data-dir /var/lib/nmon-restored --secret-key-file /etc/nmon/secret.key
|
||||
|
||||
It verifies inventory row counts and a sample of series before it says done. Then start nmon on that directory. Restore needs the embedded stores (the normal release build).
|
||||
|
||||
## Keys
|
||||
|
||||
`nmon key rotate --data-dir D --secret-key-file K` (nmon stopped) adds a new key version, re-encrypts every SNMP credential and secret under it, and keeps the old key in the file so older backups still restore. Remove old keys only after a release.
|
||||
|
||||
## Configuration
|
||||
|
||||
Edit in Settings (admin) or `config.yaml` + `SIGHUP`. An invalid document is rejected and the running configuration stays. Alert receivers, the outbound allow-list, trusted proxies, the backup schedule, disk thresholds and the purge period apply live; everything else is listed as `restart_required` until the next restart. `disk: {alert_used: 0.8, admit_used: 0.9, reserve_free: 0.05}`: alert at 80% used, no new series at 90%, ingest throttled / rollup paused / backups refused below 5% free.
|
||||
|
||||
## Metric stores
|
||||
|
||||
The supervisor restarts a crashed store; after three restarts in ten minutes it raises `store_failed` and stops. `nmon store restart [hot|long] --api URL --token T` (or `SIGHUP`) resumes it.
|
||||
|
||||
## Retired devices
|
||||
|
||||
`POST /api/v1/devices/{slug}/purge` (admin) deletes a retired device's series from both stores once it has been retired for `retired_purge_after` (default 1y).
|
||||
|
||||
## CSV import
|
||||
|
||||
Devices (`name,address,site,role,credential,parents,...`) and port descriptions (`device,ifname,alias`) from Settings or `POST /api/v1/devices/import`. Port descriptions are stored in the operator-owned `description` field, which discovery never overwrites. A dependency cycle is rejected with its path; nothing is written unless the whole import is valid.
|
||||
|
Before Width: | Height: | Size: 136 KiB After Width: | Height: | Size: 141 KiB |
|
Before Width: | Height: | Size: 581 KiB After Width: | Height: | Size: 603 KiB |
|
Before Width: | Height: | Size: 153 KiB After Width: | Height: | Size: 149 KiB |
|
Before Width: | Height: | Size: 137 KiB After Width: | Height: | Size: 137 KiB |
|
Before Width: | Height: | Size: 138 KiB After Width: | Height: | Size: 161 KiB |
|
Before Width: | Height: | Size: 138 KiB After Width: | Height: | Size: 161 KiB |
|
Before Width: | Height: | Size: 183 KiB After Width: | Height: | Size: 193 KiB |
|
Before Width: | Height: | Size: 184 KiB After Width: | Height: | Size: 194 KiB |
|
Before Width: | Height: | Size: 78 KiB After Width: | Height: | Size: 82 KiB |
|
Before Width: | Height: | Size: 107 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 125 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 196 KiB After Width: | Height: | Size: 202 KiB |
|
Before Width: | Height: | Size: 41 KiB After Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 61 KiB |
|
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 53 KiB |
|
Before Width: | Height: | Size: 120 KiB After Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 568 KiB After Width: | Height: | Size: 594 KiB |
|
Before Width: | Height: | Size: 152 KiB After Width: | Height: | Size: 161 KiB |
|
Before Width: | Height: | Size: 116 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 154 KiB After Width: | Height: | Size: 160 KiB |
|
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 123 KiB |
|
Before Width: | Height: | Size: 82 KiB After Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 82 KiB After Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 112 KiB |
|
Before Width: | Height: | Size: 153 KiB After Width: | Height: | Size: 158 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 105 KiB After Width: | Height: | Size: 110 KiB |
|
Before Width: | Height: | Size: 43 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 49 KiB After Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 53 KiB |
|
Before Width: | Height: | Size: 72 KiB After Width: | Height: | Size: 85 KiB |
BIN
docs/screenshots/M4-mock/ack-dialog-light.png
Normal file
|
After Width: | Height: | Size: 111 KiB |
BIN
docs/screenshots/M4-mock/ack-dialog.png
Normal file
|
After Width: | Height: | Size: 108 KiB |
BIN
docs/screenshots/M4-mock/alerts-acked.png
Normal file
|
After Width: | Height: | Size: 50 KiB |
BIN
docs/screenshots/M4-mock/alerts-active-light.png
Normal file
|
After Width: | Height: | Size: 117 KiB |
BIN
docs/screenshots/M4-mock/alerts-active.png
Normal file
|
After Width: | Height: | Size: 115 KiB |
BIN
docs/screenshots/M4-mock/alerts-history.png
Normal file
|
After Width: | Height: | Size: 58 KiB |
BIN
docs/screenshots/M4-mock/device-suppressed-banner.png
Normal file
|
After Width: | Height: | Size: 149 KiB |
BIN
docs/screenshots/M4-mock/devices-list-down-maintenance.png
Normal file
|
After Width: | Height: | Size: 195 KiB |
BIN
docs/screenshots/M4-mock/maintenance.png
Normal file
|
After Width: | Height: | Size: 69 KiB |
BIN
docs/screenshots/M4/ack-dialog.png
Normal file
|
After Width: | Height: | Size: 189 KiB |
BIN
docs/screenshots/M4/alerts-acked.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
docs/screenshots/M4/alerts-active.png
Normal file
|
After Width: | Height: | Size: 213 KiB |
BIN
docs/screenshots/M4/alerts-history.png
Normal file
|
After Width: | Height: | Size: 58 KiB |
BIN
docs/screenshots/M4/device-down.png
Normal file
|
After Width: | Height: | Size: 80 KiB |
BIN
docs/screenshots/M4/device-suppressed.png
Normal file
|
After Width: | Height: | Size: 88 KiB |
BIN
docs/screenshots/M4/devices-list.png
Normal file
|
After Width: | Height: | Size: 175 KiB |
BIN
docs/screenshots/M4/maintenance.png
Normal file
|
After Width: | Height: | Size: 63 KiB |
BIN
docs/screenshots/M5-mock/check-dialog.png
Normal file
|
After Width: | Height: | Size: 80 KiB |
BIN
docs/screenshots/M5-mock/checks.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
docs/screenshots/M5-mock/device-check-only.png
Normal file
|
After Width: | Height: | Size: 81 KiB |
BIN
docs/screenshots/M5-mock/device-node.png
Normal file
|
After Width: | Height: | Size: 84 KiB |
BIN
docs/screenshots/M5-mock/device-vm.png
Normal file
|
After Width: | Height: | Size: 82 KiB |
BIN
docs/screenshots/M5-mock/group-detail.png
Normal file
|
After Width: | Height: | Size: 186 KiB |
BIN
docs/screenshots/M5-mock/group-dialog.png
Normal file
|
After Width: | Height: | Size: 46 KiB |
BIN
docs/screenshots/M5-mock/group-flags.png
Normal file
|
After Width: | Height: | Size: 151 KiB |
BIN
docs/screenshots/M5-mock/group-p95-partial.png
Normal file
|
After Width: | Height: | Size: 152 KiB |
BIN
docs/screenshots/M5-mock/groups-list.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
BIN
docs/screenshots/M5-mock/p95-legend.png
Normal file
|
After Width: | Height: | Size: 120 KiB |
BIN
docs/screenshots/M5-mock/proxmox-card.png
Normal file
|
After Width: | Height: | Size: 126 KiB |
BIN
docs/screenshots/M5-mock/tokens-list.png
Normal file
|
After Width: | Height: | Size: 48 KiB |
BIN
docs/screenshots/M5-mock/tokens-mint-dialog.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
docs/screenshots/M5-mock/tokens-secret-dialog.png
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
docs/screenshots/M5/checks.png
Normal file
|
After Width: | Height: | Size: 48 KiB |
BIN
docs/screenshots/M5/device-vm.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
docs/screenshots/M5/graph-2y-stitched.png
Normal file
|
After Width: | Height: | Size: 83 KiB |
BIN
docs/screenshots/M5/group-detail.png
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
docs/screenshots/M5/groups-list.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
BIN
docs/screenshots/M5/proxmox-card.png
Normal file
|
After Width: | Height: | Size: 81 KiB |