mqttpub.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Package mqttpub publishes the NetPulse fleet state to an MQTT broker with
  2. // Home Assistant MQTT Discovery (#825).
  3. //
  4. // It is opt-in (NETPULSE_MQTT_ENABLED=1 plus a broker host), disabled in demo
  5. // mode and fail-silent: a broker that is down never affects the server. Only
  6. // publishing is used, so there is no subscription and no command surface.
  7. package mqttpub
  8. import (
  9. "context"
  10. "crypto/tls"
  11. "encoding/json"
  12. "fmt"
  13. "log"
  14. "os"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/gonzalop/mq"
  20. "github.com/gnacho/netpulse/server-go/internal/adapters"
  21. )
  22. const (
  23. defaultPort = 1883
  24. defaultInterval = 30 * time.Second
  25. initialBackoff = 5 * time.Second
  26. maxBackoff = 2 * time.Minute
  27. publishTimeout = 10 * time.Second
  28. )
  29. // Config is the publisher configuration.
  30. type Config struct {
  31. Enabled bool
  32. Host string
  33. Port int
  34. User string
  35. Pass string
  36. Instance string
  37. Interval time.Duration
  38. TLS bool
  39. TLSInsecure bool
  40. }
  41. // ConfigFromEnv reads the configuration from the environment. lookup follows
  42. // the os.LookupEnv shape so it can be injected in tests. Missing values fall
  43. // back to defaults; an enabled config without a host is disabled.
  44. func ConfigFromEnv(lookup func(string) (string, bool)) Config {
  45. cfg := Config{Port: defaultPort, Interval: defaultInterval, Instance: "default"}
  46. if v, ok := lookup("NETPULSE_MQTT_ENABLED"); ok {
  47. cfg.Enabled = isTrue(v)
  48. }
  49. if v, ok := lookup("NETPULSE_MQTT_HOST"); ok {
  50. cfg.Host = strings.TrimSpace(v)
  51. }
  52. if v, ok := lookup("NETPULSE_MQTT_PORT"); ok {
  53. if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && n > 0 {
  54. cfg.Port = n
  55. }
  56. }
  57. if v, ok := lookup("NETPULSE_MQTT_USER"); ok {
  58. cfg.User = strings.TrimSpace(v)
  59. }
  60. if v, ok := lookup("NETPULSE_MQTT_PASS"); ok {
  61. cfg.Pass = v
  62. }
  63. if v, ok := lookup("NETPULSE_MQTT_INSTANCE"); ok && strings.TrimSpace(v) != "" {
  64. cfg.Instance = strings.TrimSpace(v)
  65. }
  66. if v, ok := lookup("NETPULSE_MQTT_INTERVAL"); ok {
  67. if sec, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && sec > 0 {
  68. cfg.Interval = time.Duration(sec) * time.Second
  69. }
  70. }
  71. if v, ok := lookup("NETPULSE_MQTT_TLS"); ok {
  72. cfg.TLS = isTrue(v)
  73. }
  74. if v, ok := lookup("NETPULSE_MQTT_TLS_INSECURE"); ok {
  75. cfg.TLSInsecure = isTrue(v)
  76. }
  77. cfg.Instance = sanitize(cfg.Instance)
  78. if cfg.Host == "" {
  79. cfg.Enabled = false
  80. }
  81. return cfg
  82. }
  83. func isTrue(v string) bool {
  84. switch strings.ToLower(strings.TrimSpace(v)) {
  85. case "1", "true", "on", "yes":
  86. return true
  87. }
  88. return false
  89. }
  90. // brokerURL builds the dial URL. TLS keeps the configured port and only
  91. // changes the scheme: the broker listens on 8883 by convention, but the port
  92. // in Settings always wins.
  93. func brokerURL(cfg Config) string {
  94. scheme := "tcp"
  95. if cfg.TLS {
  96. scheme = "tls"
  97. }
  98. return fmt.Sprintf("%s://%s:%d", scheme, cfg.Host, cfg.Port)
  99. }
  100. // tlsOption returns the TLS client config when TLS is enabled. Certificates
  101. // are verified against the system roots; TLSInsecure is the explicit opt-in
  102. // for self-signed brokers, the same trade-off as mosquitto_sub --insecure.
  103. func tlsOption(cfg Config) (mq.Option, bool) {
  104. if !cfg.TLS {
  105. return nil, false
  106. }
  107. tc := &tls.Config{MinVersion: tls.VersionTLS12}
  108. if cfg.TLSInsecure {
  109. // #nosec G402 -- opted in from Settings for a self-signed broker.
  110. tc.InsecureSkipVerify = true
  111. }
  112. return mq.WithTLS(tc), true
  113. }
  114. // Publisher keeps the broker connection and publishes the state periodically.
  115. type Publisher struct {
  116. cfg Config
  117. version string
  118. snapshot func() *adapters.Overview
  119. demo bool
  120. // mu guards the fields below: publishCycle runs on the publisher
  121. // goroutine AND from the client's OnConnect hook (initial connect and
  122. // every reconnect), so the alert/router state must not be touched
  123. // without the lock.
  124. mu sync.Mutex
  125. seenAlerts map[string]struct{}
  126. seenInit bool
  127. lastRouters string
  128. }
  129. // New builds a publisher. snapshot returns the latest overview (nil allowed
  130. // before the first poll).
  131. func New(cfg Config, version string, snapshot func() *adapters.Overview, demo bool) *Publisher {
  132. return &Publisher{
  133. cfg: cfg,
  134. version: version,
  135. snapshot: snapshot,
  136. demo: demo,
  137. seenAlerts: map[string]struct{}{},
  138. }
  139. }
  140. // Enabled reports whether the publisher will run.
  141. func (p *Publisher) Enabled() bool { return p.cfg.Enabled && !p.demo && p.snapshot != nil }
  142. // Start runs the publisher until ctx is cancelled. It is a no-op when not
  143. // enabled, so callers can start it unconditionally.
  144. func (p *Publisher) Start(ctx context.Context) {
  145. if !p.Enabled() {
  146. if p.cfg.Enabled && p.demo {
  147. log.Printf("[netpulse:mqtt] disabled in demo mode")
  148. }
  149. return
  150. }
  151. go p.Run(ctx)
  152. }
  153. // Run es el bucle del publisher; los callers que necesitan saber cuándo ha
  154. // terminado (Manager, #1158) lo invocan en su propio goroutine.
  155. func (p *Publisher) Run(ctx context.Context) {
  156. backoff := initialBackoff
  157. for {
  158. if ctx.Err() != nil {
  159. return
  160. }
  161. client, err := p.dial(ctx)
  162. if err != nil {
  163. log.Printf("[netpulse:mqtt] connect to %s:%d failed: %v", p.cfg.Host, p.cfg.Port, err)
  164. if !sleepCtx(ctx, backoff) {
  165. return
  166. }
  167. backoff *= 2
  168. if backoff > maxBackoff {
  169. backoff = maxBackoff
  170. }
  171. continue
  172. }
  173. backoff = initialBackoff
  174. log.Printf("[netpulse:mqtt] connected to %s:%d as instance %q", p.cfg.Host, p.cfg.Port, p.cfg.Instance)
  175. p.loop(ctx, client)
  176. // The retained availability must not stay "online" after an
  177. // intentional stop (a graceful DISCONNECT suppresses the will).
  178. p.publishAvailabilityWithTimeout(client, "offline", shutdownWait-time.Second)
  179. _ = client.Disconnect(context.Background())
  180. return
  181. }
  182. }
  183. func (p *Publisher) dial(ctx context.Context) (*mq.Client, error) {
  184. addr := brokerURL(p.cfg)
  185. opts := []mq.Option{
  186. mq.WithProtocolVersion(mq.ProtocolV311),
  187. mq.WithClientID("netpulse-" + p.cfg.Instance),
  188. mq.WithKeepAlive(60 * time.Second),
  189. mq.WithAutoReconnect(true),
  190. mq.WithReconnectBackoff(2*time.Second, maxBackoff, true),
  191. mq.WithConnectTimeout(15 * time.Second),
  192. mq.WithWill(availabilityTopic(p.cfg.Instance), []byte("offline"), 1, true),
  193. mq.WithOnConnect(func(c *mq.Client) {
  194. // Fires on the initial connect and on every reconnect.
  195. p.publishAvailability(c, "online")
  196. p.publishDiscovery(c)
  197. p.publishCycle(c)
  198. }),
  199. mq.WithOnConnectionLost(func(_ *mq.Client, err error) {
  200. log.Printf("[netpulse:mqtt] connection lost: %v", err)
  201. }),
  202. }
  203. if opt, ok := tlsOption(p.cfg); ok {
  204. opts = append(opts, opt)
  205. }
  206. if p.cfg.User != "" {
  207. opts = append(opts, mq.WithCredentials(p.cfg.User, p.cfg.Pass))
  208. }
  209. dctx, cancel := context.WithTimeout(ctx, 15*time.Second)
  210. defer cancel()
  211. return mq.DialContext(dctx, addr, opts...)
  212. }
  213. // loop publishes on the configured interval until ctx ends.
  214. func (p *Publisher) loop(ctx context.Context, client *mq.Client) {
  215. interval := p.cfg.Interval
  216. if interval <= 0 {
  217. interval = defaultInterval
  218. }
  219. t := time.NewTicker(interval)
  220. defer t.Stop()
  221. // Log reconnect bursts once each so an unstable broker connection is
  222. // visible in the journal instead of only in broker-side logs (#1153).
  223. var loggedReconnects uint64
  224. for {
  225. select {
  226. case <-ctx.Done():
  227. return
  228. case <-t.C:
  229. if n := client.GetStats().ReconnectCount; n > loggedReconnects {
  230. log.Printf("[netpulse:mqtt] client reconnected %d time(s): broker connection unstable", n)
  231. loggedReconnects = n
  232. }
  233. if client.IsConnected() {
  234. p.publishCycle(client)
  235. }
  236. }
  237. }
  238. }
  239. // publishCycle publishes the instance status, every router state and any new
  240. // alert. It also republishes discovery when the set of routers changes.
  241. func (p *Publisher) publishCycle(client *mq.Client) {
  242. ov := p.snapshot()
  243. if ov == nil {
  244. return
  245. }
  246. p.publishStatus(client, ov)
  247. p.publishRouters(client, ov)
  248. p.publishNewAlerts(client, ov)
  249. newKey := routerSetKey(ov)
  250. p.mu.Lock()
  251. changed := newKey != p.lastRouters
  252. if changed {
  253. p.lastRouters = newKey
  254. }
  255. p.mu.Unlock()
  256. if changed {
  257. p.publishDiscovery(client)
  258. }
  259. }
  260. // publishNewAlerts emits an event per unseen alert. The first overview only
  261. // seeds the set, so a fresh server start does not replay the whole backlog.
  262. func (p *Publisher) publishNewAlerts(client *mq.Client, ov *adapters.Overview) {
  263. p.mu.Lock()
  264. if !p.seenInit {
  265. for _, a := range ov.Alerts {
  266. if a.ID != "" {
  267. p.seenAlerts[a.ID] = struct{}{}
  268. }
  269. }
  270. p.seenInit = true
  271. p.mu.Unlock()
  272. return
  273. }
  274. var fresh []alertEvent
  275. for _, a := range ov.Alerts {
  276. if a.ID == "" {
  277. continue
  278. }
  279. if _, ok := p.seenAlerts[a.ID]; ok {
  280. continue
  281. }
  282. p.seenAlerts[a.ID] = struct{}{}
  283. fresh = append(fresh, alertEvent{
  284. ID: a.ID, Severity: a.Severity, Title: a.Title, Description: a.Description,
  285. RouterID: a.RouterID, Urgent: a.Urgent, Ts: a.Ts,
  286. })
  287. }
  288. p.mu.Unlock()
  289. for _, ev := range fresh {
  290. payload, err := json.Marshal(ev)
  291. if err != nil {
  292. continue
  293. }
  294. publish(client, eventTopic(p.cfg.Instance, "alert"), payload, false)
  295. }
  296. }
  297. func (p *Publisher) publishAvailability(client *mq.Client, value string) {
  298. p.publishAvailabilityWithTimeout(client, value, publishTimeout)
  299. }
  300. func (p *Publisher) publishAvailabilityWithTimeout(client *mq.Client, value string, timeout time.Duration) {
  301. publishWithTimeout(client, availabilityTopic(p.cfg.Instance), []byte(value), true, timeout)
  302. }
  303. // publish sends one payload at QoS 1 (retained when retain is true).
  304. func publish(client *mq.Client, topic string, payload []byte, retain bool) {
  305. publishWithTimeout(client, topic, payload, retain, publishTimeout)
  306. }
  307. func publishWithTimeout(client *mq.Client, topic string, payload []byte, retain bool, timeout time.Duration) {
  308. if !client.IsConnected() {
  309. return
  310. }
  311. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  312. defer cancel()
  313. opts := []mq.PublishOption{mq.WithQoS(mq.AtLeastOnce)}
  314. if retain {
  315. opts = append(opts, mq.WithRetain(true))
  316. }
  317. if err := client.Publish(ctx, topic, payload, opts...).Wait(ctx); err != nil {
  318. log.Printf("[netpulse:mqtt] publish %s: %v", topic, err)
  319. }
  320. }
  321. // sanitize makes a string safe for use as an MQTT topic level.
  322. func sanitize(s string) string {
  323. s = strings.TrimSpace(s)
  324. if s == "" {
  325. return "default"
  326. }
  327. return strings.NewReplacer("/", "-", "+", "-", "#", "-", " ", "-").Replace(s)
  328. }
  329. // sleepCtx sleeps for d, returning false when ctx ends first.
  330. func sleepCtx(ctx context.Context, d time.Duration) bool {
  331. t := time.NewTimer(d)
  332. defer t.Stop()
  333. select {
  334. case <-ctx.Done():
  335. return false
  336. case <-t.C:
  337. return true
  338. }
  339. }
  340. // envLookup is the production lookup (os.LookupEnv), used by main.
  341. func envLookup(k string) (string, bool) { return os.LookupEnv(k) }
  342. // ConfigFromProcessEnv reads the configuration from the process environment.
  343. func ConfigFromProcessEnv() Config { return ConfigFromEnv(envLookup) }