Files
nmon/internal/app/app.go
Vibe Coder f31fb3712a
Some checks failed
ci / lint (push) Successful in 4m19s
ci / openapi (push) Successful in 29s
ci / postgres (push) Successful in 4m55s
ci / test (push) Failing after 19m48s
Add settings forms, first-install wizard, webhook presets, help and poll tools
Make nmon easier to install and run without editing YAML by hand:

- Settings: point-and-click forms over config.yaml (GET/PUT
  /api/v1/settings/form); the YAML editor moves to /settings/yaml.
- First install: with no sign-in configured nmon starts in install
  mode, serves only the setup wizard (sign-in, basics, devices,
  alerting) and closes it for good once sign-in is saved. A
  self-signed certificate is generated when no TLS source is given.
  poller.interval becomes a config setting.
- Reverse proxies: opt-in --http-listen plain-HTTP listener beside
  HTTPS; sign-in stays required.
- Webhooks: Generic, Teams Adaptive Card, Slack and Discord presets,
  template preview and test send.
- Help: the operations, coverage and profile docs served at /help.
- Polling: per-device "Poll now", a dry-run test poll returning an
  SNMP trace, and time-limited in-memory SNMP debug recording, in the
  UI and as `nmon device poll`.
- Ansible: deploys into install mode when no sign-in is set, and no
  longer overwrites the config.yaml the wizard wrote.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w
2026-10-25 06:31:12 +00:00

250 lines
7.8 KiB
Go

// Package app wires nmon serve: config, secret key, inventory, metric stores,
// write queues, poller and HTTP API, and shuts them down in order.
package app
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/v10networks/nmon/internal/auth"
"github.com/v10networks/nmon/internal/config"
"github.com/v10networks/nmon/internal/discovery"
"github.com/v10networks/nmon/internal/diskguard"
"github.com/v10networks/nmon/internal/ingest"
"github.com/v10networks/nmon/internal/l2"
"github.com/v10networks/nmon/internal/metrics"
"github.com/v10networks/nmon/internal/netpolicy"
"github.com/v10networks/nmon/internal/oui"
"github.com/v10networks/nmon/internal/poller"
"github.com/v10networks/nmon/internal/profile"
"github.com/v10networks/nmon/internal/store"
"github.com/v10networks/nmon/internal/traps"
"github.com/v10networks/nmon/internal/vmsup"
)
// Defaults for flags left empty.
const (
DefaultListen = "[::]:8443"
DefaultSecretKeyFile = "/etc/nmon/secret.key"
DefaultTrapListen = traps.DefaultAddr
DefaultGraphiteListen = "[::]:2003"
)
const (
startTimeout = 60 * time.Second
shutdownTimeout = 30 * time.Second
)
// App is a running nmon server.
type App struct {
log *slog.Logger
st store.Store
sup *vmsup.Supervisor
hot *vmsup.Queue
long *vmsup.Queue
poller *poller.Poller
srv *http.Server
ln net.Listener
httpLn net.Listener // the --http-listen listener when it runs beside HTTPS; nil otherwise
profiles *profile.Set
sched *discovery.Scheduler
traps *traps.Listener // nil when the trap receiver is disabled
alerting *alerting
policy *netpolicy.Policy
svc services
l2 *l2.Job // the MAC/ARP/FDB table job
oui *oui.Service // the optional IEEE vendor registry
ingester *ingest.Ingester
serveErr chan error // the HTTP server stopped on its own
dataDir, keyFile string
live *liveConfig // the configuration as running; see reload.go
settingsMu sync.Mutex // serialises settings writes (YAML, typed form, SIGHUP) so none overwrites another's read
tr *transport
flags config.Flags // the process flags, kept for settings that a flag overrides (poller.interval)
cadence *store.PollCadence // the live default poll interval
authp atomic.Pointer[auth.Auth] // the live authentication; setup completion swaps it (install.go)
authMu sync.Mutex
authRunning *authRun
install atomic.Bool // install mode is on
setupMu sync.Mutex // serialises the setup steps
guard *diskguard.Guard
hotW metrics.Writer // a.hot behind the disk guard's new-series admission
backups *backupService
schedMu sync.Mutex
stopBackup func() // ends the nightly backup schedule; nil when none
// stops holds one step per subsystem that came up, in start order. Stop runs
// them in reverse, so a subsystem goes down before the ones it depends on.
stops []stopStep
}
// stopStep shuts one subsystem down.
type stopStep struct {
name string
fn func(ctx context.Context) error
}
// onStop registers how to shut down the subsystem that was just started.
func (a *App) onStop(name string, fn func(ctx context.Context) error) {
a.stops = append(a.stops, stopStep{name, fn})
}
// Run starts nmon and blocks until ctx is cancelled or the HTTP server fails,
// then shuts everything down gracefully.
func Run(ctx context.Context, f config.Flags) error {
// Catch SIGHUP before starting: Go's default action is to exit, and startup takes
// seconds (metric stores), so a `systemctl reload` then would kill nmon. A SIGHUP
// that arrives during startup is queued and applied once Start returns.
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
defer signal.Stop(hup)
a, err := Start(ctx, f)
if err != nil {
return err
}
var runErr error
wait:
for {
select {
case <-ctx.Done():
break wait
case runErr = <-a.serveErr:
break wait
case <-hup:
a.OnSIGHUP()
}
}
sctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
return errors.Join(runErr, a.Stop(sctx))
}
// Start brings every component up and returns once the API is listening. ctx
// bounds startup only; call Stop to shut down. A failed Start stops whatever
// had already come up.
//
// Startup order: inventory, metric stores, alerting (built), write queues and the
// disk guard, profiles, poller, alerting (started), discovery scheduler, trap receiver,
// rollup, p95 and group jobs, the MAC/ARP table job and vendor registry, Proxmox sync and checks, push ingest (HTTP and Graphite),
// authentication, HTTP API, the nightly backup schedule.
// Stop reverses it.
func Start(ctx context.Context, f config.Flags) (_ *App, err error) {
log := slog.Default()
s, err := resolveSettings(f)
if err != nil {
return nil, err
}
kr, err := loadKeyring(log, s)
if err != nil {
return nil, err
}
a := &App{log: log, serveErr: make(chan error, 1), dataDir: s.DataDir, keyFile: s.keyFile, live: newLiveConfig(s.cfg), tr: s.tr,
flags: s.Flags, cadence: store.NewPollCadence(config.EffectivePollInterval(s.Flags, s.cfg))}
a.backups = &backupService{a: a}
defer func() {
if err != nil {
sctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
_ = a.Stop(sctx) // the startup error is the one to report
}
}()
if err = a.startStore(ctx, s, kr); err != nil {
return nil, err
}
if err = a.decideAuth(ctx, s); err != nil {
return nil, err
}
if err = a.startMetricStores(ctx, s); err != nil {
return nil, err
}
if err = a.newAlerting(s); err != nil {
return nil, err
}
a.startQueues()
if err = a.startDisk(s); err != nil {
return nil, err
}
if err = a.loadProfiles(s); err != nil {
return nil, err
}
a.startPoller(s)
if err = a.startAlerting(s); err != nil {
return nil, err
}
a.newScheduler(s)
a.newTraps(s)
a.startScheduler()
a.startTraps(s)
if err = a.startJobs(s); err != nil {
return nil, err
}
if err = a.startIngest(s); err != nil {
return nil, err
}
if err = a.startAuth(ctx, s); err != nil {
return nil, err
}
if err = a.startAPI(s); err != nil {
return nil, err
}
a.setBackupSchedule(s.cfg)
a.onStop("backup schedule", func(context.Context) error { a.stopSchedule(); return nil })
return a, nil
}
// startJobs starts the storage and collection jobs that follow the poller: rollup with the p95 jobs, the MAC/ARP
// table job with the vendor registry, then Proxmox sync and service checks.
func (a *App) startJobs(s *settings) error {
for _, start := range []func(*settings) error{a.startRollup, a.startL2, a.startCollectors} {
if err := start(s); err != nil {
return err
}
}
return nil
}
// Addr is the address the API listens on.
func (a *App) Addr() string { return a.ln.Addr().String() }
// HTTPAddr is the address of the --http-listen listener, or "" when it is off. With plain HTTP only it equals Addr.
func (a *App) HTTPAddr() string {
switch {
case a.httpLn != nil:
return a.httpLn.Addr().String()
case a.tr.httpOnly:
return a.ln.Addr().String()
}
return ""
}
// HotURL is the base URL of the hot metric store.
func (a *App) HotURL() string { return a.sup.HotURL() }
// Stop shuts the subsystems down in reverse start order: HTTP, trap receiver,
// discovery scheduler, alerting, poller, write queues, metric stores (which flush the
// queues) and the inventory. It is safe after a failed Start and idempotent.
func (a *App) Stop(ctx context.Context) error {
var errs []error
for i := len(a.stops) - 1; i >= 0; i-- {
if err := a.stops[i].fn(ctx); err != nil {
errs = append(errs, fmt.Errorf("stop %s: %w", a.stops[i].name, err))
}
}
a.stops = nil
a.log.Info("stopped")
return errors.Join(errs...)
}