Files
nmon/internal/app/app.go

150 lines
4.0 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"
"time"
"github.com/v10networks/nmon/internal/config"
"github.com/v10networks/nmon/internal/discovery"
"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
)
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
profiles *profile.Set
sched *discovery.Scheduler
traps *traps.Listener // nil when the trap receiver is disabled
serveErr chan error // the HTTP server stopped on its own
// 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 {
a, err := Start(ctx, f)
if err != nil {
return err
}
var runErr error
select {
case <-ctx.Done():
case runErr = <-a.serveErr:
}
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, write queues, profiles, poller,
// discovery scheduler, trap receiver, HTTP API. 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)}
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.startMetricStores(ctx, s); err != nil {
return nil, err
}
a.startQueues()
if err = a.loadProfiles(s); err != nil {
return nil, err
}
a.startPoller(s)
a.newScheduler(s)
a.newTraps(s)
a.startScheduler()
a.startTraps(s)
if err = a.startAPI(s); err != nil {
return nil, err
}
return a, nil
}
// Addr is the address the API listens on.
func (a *App) Addr() string { return a.ln.Addr().String() }
// 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, 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...)
}