mqtt_settings.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. // mqtt_settings.go - ajustes del publisher MQTT (#838): GET (sin password),
  2. // PUT (password vacío = conservar), test de conexión y propagación a los
  3. // routers NetGrip de la flota.
  4. package httpapi
  5. import (
  6. "net/http"
  7. "strconv"
  8. "time"
  9. "github.com/gnacho/netpulse/agent/executor"
  10. "github.com/gnacho/netpulse/server-go/internal/auth"
  11. "github.com/gnacho/netpulse/server-go/internal/mqttpub"
  12. )
  13. type mqttConfigResponse struct {
  14. Enabled bool `json:"enabled"`
  15. Host string `json:"host"`
  16. Port int `json:"port"`
  17. User string `json:"user"`
  18. PassSet bool `json:"passSet"`
  19. Instance string `json:"instance"`
  20. IntervalSec int `json:"intervalSec"`
  21. Running bool `json:"running"`
  22. }
  23. func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager) {
  24. adapter := &dbKVAdapter{db: s.db.DB}
  25. mux.Handle("GET /api/settings/mqtt", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  26. if mgr == nil {
  27. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  28. return
  29. }
  30. cfg := mgr.Config()
  31. writeJSON(w, http.StatusOK, mqttConfigResponse{
  32. Enabled: cfg.Enabled, Host: cfg.Host, Port: cfg.Port, User: cfg.User,
  33. PassSet: cfg.Pass != "", Instance: cfg.Instance,
  34. IntervalSec: int(cfg.Interval.Seconds()), Running: mgr.Running(),
  35. })
  36. })))
  37. mux.Handle("PUT /api/settings/mqtt", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  38. if mgr == nil {
  39. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  40. return
  41. }
  42. var body struct {
  43. // Enabled es puntero (#968): un PUT parcial que solo toca otro
  44. // campo (p.ej. host) NO debe apagar el publisher por accidente.
  45. Enabled *bool `json:"enabled"`
  46. Host string `json:"host"`
  47. Port int `json:"port"`
  48. User string `json:"user"`
  49. Pass string `json:"pass"`
  50. Instance string `json:"instance"`
  51. IntervalSec int `json:"intervalSec"`
  52. }
  53. if st := readJSONBody(w, r, &body); st != 0 {
  54. return
  55. }
  56. cfg := mgr.Config()
  57. if body.Enabled != nil {
  58. cfg.Enabled = *body.Enabled
  59. }
  60. if body.Host != "" {
  61. cfg.Host = body.Host
  62. }
  63. if body.Port > 0 {
  64. cfg.Port = body.Port
  65. }
  66. if body.User != "" {
  67. cfg.User = body.User
  68. }
  69. if body.Pass != "" {
  70. cfg.Pass = body.Pass
  71. }
  72. if body.Instance != "" {
  73. cfg.Instance = body.Instance
  74. }
  75. if body.IntervalSec > 0 {
  76. cfg.Interval = time.Duration(body.IntervalSec) * time.Second
  77. }
  78. if err := mqttpub.SaveConfig(adapter, cfg); err != nil {
  79. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  80. return
  81. }
  82. mgr.Apply(cfg)
  83. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  84. })))
  85. mux.Handle("POST /api/settings/mqtt/test", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  86. if mgr == nil {
  87. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  88. return
  89. }
  90. var body struct {
  91. Host string `json:"host"`
  92. Port int `json:"port"`
  93. User string `json:"user"`
  94. Pass string `json:"pass"`
  95. }
  96. if st := readJSONBody(w, r, &body); st != 0 {
  97. return
  98. }
  99. cfg := mgr.Config()
  100. if body.Host != "" {
  101. cfg.Host = body.Host
  102. }
  103. if body.Port > 0 {
  104. cfg.Port = body.Port
  105. }
  106. if body.User != "" {
  107. cfg.User = body.User
  108. }
  109. if body.Pass != "" {
  110. cfg.Pass = body.Pass
  111. }
  112. if err := mqttpub.Probe(r.Context(), cfg); err != nil {
  113. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  114. return
  115. }
  116. writeJSON(w, http.StatusOK, map[string]any{"ok": true})
  117. })))
  118. // propagate envía la configuración del broker a cada router NetGrip de la
  119. // flota (op mqtt.configure vía su executor), para no configurarlos a mano.
  120. mux.Handle("POST /api/settings/mqtt/propagate", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  121. if mgr == nil {
  122. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  123. return
  124. }
  125. cfg := mgr.Config()
  126. if !cfg.Enabled {
  127. writeError(w, http.StatusBadRequest, "mqtt_disabled", "MQTT está desactivado en este servidor")
  128. return
  129. }
  130. ov := s.lastOv()
  131. if ov == nil {
  132. writeError(w, http.StatusServiceUnavailable, "no_overview")
  133. return
  134. }
  135. op := executor.Op{
  136. Kind: "mqtt.configure",
  137. Args: map[string]string{
  138. "enabled": "true",
  139. "host": cfg.Host,
  140. "port": strconv.Itoa(cfg.Port),
  141. "user": cfg.User,
  142. "pass": cfg.Pass,
  143. "interval": strconv.Itoa(int(cfg.Interval.Seconds())),
  144. },
  145. Desc: "MQTT: aplicar el broker de NetPulse",
  146. }
  147. planID := "mqtt-propagate-" + strconv.FormatInt(time.Now().Unix(), 10)
  148. results := []map[string]any{}
  149. for _, rt := range ov.Routers {
  150. if s.agentKindOf(rt.ID) != "netgrip" {
  151. continue
  152. }
  153. ok, err := s.applyViaNetGrip(rt.ID, planID, []executor.Op{op})
  154. res := map[string]any{"id": rt.ID, "name": rt.Name, "delegated": ok}
  155. if err != nil {
  156. res["error"] = err.Error()
  157. }
  158. results = append(results, res)
  159. }
  160. writeJSON(w, http.StatusOK, map[string]any{"results": results})
  161. })))
  162. }