| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373 |
- // Package mqttpub publishes the NetPulse fleet state to an MQTT broker with
- // Home Assistant MQTT Discovery (#825).
- //
- // It is opt-in (NETPULSE_MQTT_ENABLED=1 plus a broker host), disabled in demo
- // mode and fail-silent: a broker that is down never affects the server. Only
- // publishing is used, so there is no subscription and no command surface.
- package mqttpub
- import (
- "context"
- "crypto/tls"
- "encoding/json"
- "fmt"
- "log"
- "os"
- "strconv"
- "strings"
- "sync"
- "time"
- "github.com/gonzalop/mq"
- "github.com/gnacho/netpulse/server-go/internal/adapters"
- )
- const (
- defaultPort = 1883
- defaultInterval = 30 * time.Second
- initialBackoff = 5 * time.Second
- maxBackoff = 2 * time.Minute
- publishTimeout = 10 * time.Second
- )
- // Config is the publisher configuration.
- type Config struct {
- Enabled bool
- Host string
- Port int
- User string
- Pass string
- Instance string
- Interval time.Duration
- TLS bool
- TLSInsecure bool
- }
- // ConfigFromEnv reads the configuration from the environment. lookup follows
- // the os.LookupEnv shape so it can be injected in tests. Missing values fall
- // back to defaults; an enabled config without a host is disabled.
- func ConfigFromEnv(lookup func(string) (string, bool)) Config {
- cfg := Config{Port: defaultPort, Interval: defaultInterval, Instance: "default"}
- if v, ok := lookup("NETPULSE_MQTT_ENABLED"); ok {
- cfg.Enabled = isTrue(v)
- }
- if v, ok := lookup("NETPULSE_MQTT_HOST"); ok {
- cfg.Host = strings.TrimSpace(v)
- }
- if v, ok := lookup("NETPULSE_MQTT_PORT"); ok {
- if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && n > 0 {
- cfg.Port = n
- }
- }
- if v, ok := lookup("NETPULSE_MQTT_USER"); ok {
- cfg.User = strings.TrimSpace(v)
- }
- if v, ok := lookup("NETPULSE_MQTT_PASS"); ok {
- cfg.Pass = v
- }
- if v, ok := lookup("NETPULSE_MQTT_INSTANCE"); ok && strings.TrimSpace(v) != "" {
- cfg.Instance = strings.TrimSpace(v)
- }
- if v, ok := lookup("NETPULSE_MQTT_INTERVAL"); ok {
- if sec, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && sec > 0 {
- cfg.Interval = time.Duration(sec) * time.Second
- }
- }
- if v, ok := lookup("NETPULSE_MQTT_TLS"); ok {
- cfg.TLS = isTrue(v)
- }
- if v, ok := lookup("NETPULSE_MQTT_TLS_INSECURE"); ok {
- cfg.TLSInsecure = isTrue(v)
- }
- cfg.Instance = sanitize(cfg.Instance)
- if cfg.Host == "" {
- cfg.Enabled = false
- }
- return cfg
- }
- func isTrue(v string) bool {
- switch strings.ToLower(strings.TrimSpace(v)) {
- case "1", "true", "on", "yes":
- return true
- }
- return false
- }
- // brokerURL builds the dial URL. TLS keeps the configured port and only
- // changes the scheme: the broker listens on 8883 by convention, but the port
- // in Settings always wins.
- func brokerURL(cfg Config) string {
- scheme := "tcp"
- if cfg.TLS {
- scheme = "tls"
- }
- return fmt.Sprintf("%s://%s:%d", scheme, cfg.Host, cfg.Port)
- }
- // tlsOption returns the TLS client config when TLS is enabled. Certificates
- // are verified against the system roots; TLSInsecure is the explicit opt-in
- // for self-signed brokers, the same trade-off as mosquitto_sub --insecure.
- func tlsOption(cfg Config) (mq.Option, bool) {
- if !cfg.TLS {
- return nil, false
- }
- tc := &tls.Config{MinVersion: tls.VersionTLS12}
- if cfg.TLSInsecure {
- // #nosec G402 -- opted in from Settings for a self-signed broker.
- tc.InsecureSkipVerify = true
- }
- return mq.WithTLS(tc), true
- }
- // Publisher keeps the broker connection and publishes the state periodically.
- type Publisher struct {
- cfg Config
- version string
- snapshot func() *adapters.Overview
- demo bool
- // mu guards the fields below: publishCycle runs on the publisher
- // goroutine AND from the client's OnConnect hook (initial connect and
- // every reconnect), so the alert/router state must not be touched
- // without the lock.
- mu sync.Mutex
- seenAlerts map[string]struct{}
- seenInit bool
- lastRouters string
- }
- // New builds a publisher. snapshot returns the latest overview (nil allowed
- // before the first poll).
- func New(cfg Config, version string, snapshot func() *adapters.Overview, demo bool) *Publisher {
- return &Publisher{
- cfg: cfg,
- version: version,
- snapshot: snapshot,
- demo: demo,
- seenAlerts: map[string]struct{}{},
- }
- }
- // Enabled reports whether the publisher will run.
- func (p *Publisher) Enabled() bool { return p.cfg.Enabled && !p.demo && p.snapshot != nil }
- // Start runs the publisher until ctx is cancelled. It is a no-op when not
- // enabled, so callers can start it unconditionally.
- func (p *Publisher) Start(ctx context.Context) {
- if !p.Enabled() {
- if p.cfg.Enabled && p.demo {
- log.Printf("[netpulse:mqtt] disabled in demo mode")
- }
- return
- }
- go p.Run(ctx)
- }
- // Run es el bucle del publisher; los callers que necesitan saber cuándo ha
- // terminado (Manager, #1158) lo invocan en su propio goroutine.
- func (p *Publisher) Run(ctx context.Context) {
- backoff := initialBackoff
- for {
- if ctx.Err() != nil {
- return
- }
- client, err := p.dial(ctx)
- if err != nil {
- log.Printf("[netpulse:mqtt] connect to %s:%d failed: %v", p.cfg.Host, p.cfg.Port, err)
- if !sleepCtx(ctx, backoff) {
- return
- }
- backoff *= 2
- if backoff > maxBackoff {
- backoff = maxBackoff
- }
- continue
- }
- backoff = initialBackoff
- log.Printf("[netpulse:mqtt] connected to %s:%d as instance %q", p.cfg.Host, p.cfg.Port, p.cfg.Instance)
- p.loop(ctx, client)
- // The retained availability must not stay "online" after an
- // intentional stop (a graceful DISCONNECT suppresses the will).
- p.publishAvailabilityWithTimeout(client, "offline", shutdownWait-time.Second)
- _ = client.Disconnect(context.Background())
- return
- }
- }
- func (p *Publisher) dial(ctx context.Context) (*mq.Client, error) {
- addr := brokerURL(p.cfg)
- opts := []mq.Option{
- mq.WithProtocolVersion(mq.ProtocolV311),
- mq.WithClientID("netpulse-" + p.cfg.Instance),
- mq.WithKeepAlive(60 * time.Second),
- mq.WithAutoReconnect(true),
- mq.WithReconnectBackoff(2*time.Second, maxBackoff, true),
- mq.WithConnectTimeout(15 * time.Second),
- mq.WithWill(availabilityTopic(p.cfg.Instance), []byte("offline"), 1, true),
- mq.WithOnConnect(func(c *mq.Client) {
- // Fires on the initial connect and on every reconnect.
- p.publishAvailability(c, "online")
- p.publishDiscovery(c)
- p.publishCycle(c)
- }),
- mq.WithOnConnectionLost(func(_ *mq.Client, err error) {
- log.Printf("[netpulse:mqtt] connection lost: %v", err)
- }),
- }
- if opt, ok := tlsOption(p.cfg); ok {
- opts = append(opts, opt)
- }
- if p.cfg.User != "" {
- opts = append(opts, mq.WithCredentials(p.cfg.User, p.cfg.Pass))
- }
- dctx, cancel := context.WithTimeout(ctx, 15*time.Second)
- defer cancel()
- return mq.DialContext(dctx, addr, opts...)
- }
- // loop publishes on the configured interval until ctx ends.
- func (p *Publisher) loop(ctx context.Context, client *mq.Client) {
- interval := p.cfg.Interval
- if interval <= 0 {
- interval = defaultInterval
- }
- t := time.NewTicker(interval)
- defer t.Stop()
- // Log reconnect bursts once each so an unstable broker connection is
- // visible in the journal instead of only in broker-side logs (#1153).
- var loggedReconnects uint64
- for {
- select {
- case <-ctx.Done():
- return
- case <-t.C:
- if n := client.GetStats().ReconnectCount; n > loggedReconnects {
- log.Printf("[netpulse:mqtt] client reconnected %d time(s): broker connection unstable", n)
- loggedReconnects = n
- }
- if client.IsConnected() {
- p.publishCycle(client)
- }
- }
- }
- }
- // publishCycle publishes the instance status, every router state and any new
- // alert. It also republishes discovery when the set of routers changes.
- func (p *Publisher) publishCycle(client *mq.Client) {
- ov := p.snapshot()
- if ov == nil {
- return
- }
- p.publishStatus(client, ov)
- p.publishRouters(client, ov)
- p.publishNewAlerts(client, ov)
- newKey := routerSetKey(ov)
- p.mu.Lock()
- changed := newKey != p.lastRouters
- if changed {
- p.lastRouters = newKey
- }
- p.mu.Unlock()
- if changed {
- p.publishDiscovery(client)
- }
- }
- // publishNewAlerts emits an event per unseen alert. The first overview only
- // seeds the set, so a fresh server start does not replay the whole backlog.
- func (p *Publisher) publishNewAlerts(client *mq.Client, ov *adapters.Overview) {
- p.mu.Lock()
- if !p.seenInit {
- for _, a := range ov.Alerts {
- if a.ID != "" {
- p.seenAlerts[a.ID] = struct{}{}
- }
- }
- p.seenInit = true
- p.mu.Unlock()
- return
- }
- var fresh []alertEvent
- for _, a := range ov.Alerts {
- if a.ID == "" {
- continue
- }
- if _, ok := p.seenAlerts[a.ID]; ok {
- continue
- }
- p.seenAlerts[a.ID] = struct{}{}
- fresh = append(fresh, alertEvent{
- ID: a.ID, Severity: a.Severity, Title: a.Title, Description: a.Description,
- RouterID: a.RouterID, Urgent: a.Urgent, Ts: a.Ts,
- })
- }
- p.mu.Unlock()
- for _, ev := range fresh {
- payload, err := json.Marshal(ev)
- if err != nil {
- continue
- }
- publish(client, eventTopic(p.cfg.Instance, "alert"), payload, false)
- }
- }
- func (p *Publisher) publishAvailability(client *mq.Client, value string) {
- p.publishAvailabilityWithTimeout(client, value, publishTimeout)
- }
- func (p *Publisher) publishAvailabilityWithTimeout(client *mq.Client, value string, timeout time.Duration) {
- publishWithTimeout(client, availabilityTopic(p.cfg.Instance), []byte(value), true, timeout)
- }
- // publish sends one payload at QoS 1 (retained when retain is true).
- func publish(client *mq.Client, topic string, payload []byte, retain bool) {
- publishWithTimeout(client, topic, payload, retain, publishTimeout)
- }
- func publishWithTimeout(client *mq.Client, topic string, payload []byte, retain bool, timeout time.Duration) {
- if !client.IsConnected() {
- return
- }
- ctx, cancel := context.WithTimeout(context.Background(), timeout)
- defer cancel()
- opts := []mq.PublishOption{mq.WithQoS(mq.AtLeastOnce)}
- if retain {
- opts = append(opts, mq.WithRetain(true))
- }
- if err := client.Publish(ctx, topic, payload, opts...).Wait(ctx); err != nil {
- log.Printf("[netpulse:mqtt] publish %s: %v", topic, err)
- }
- }
- // sanitize makes a string safe for use as an MQTT topic level.
- func sanitize(s string) string {
- s = strings.TrimSpace(s)
- if s == "" {
- return "default"
- }
- return strings.NewReplacer("/", "-", "+", "-", "#", "-", " ", "-").Replace(s)
- }
- // sleepCtx sleeps for d, returning false when ctx ends first.
- func sleepCtx(ctx context.Context, d time.Duration) bool {
- t := time.NewTimer(d)
- defer t.Stop()
- select {
- case <-ctx.Done():
- return false
- case <-t.C:
- return true
- }
- }
- // envLookup is the production lookup (os.LookupEnv), used by main.
- func envLookup(k string) (string, bool) { return os.LookupEnv(k) }
- // ConfigFromProcessEnv reads the configuration from the process environment.
- func ConfigFromProcessEnv() Config { return ConfigFromEnv(envLookup) }
|