rtlconsole.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. // rtlconsole.go — #639: sondeo HTTP de la consola de switches RTLPlayground
  2. // (Keephome KP-9000 con firmware FreeSwitchOS/RTLPlayground) para poblar
  3. // firmware + uptime en routers cuyo agente es external (beacon UDP, #291).
  4. //
  5. // El datagrama del beacon no puede crecer (el banco de código del 8051 está
  6. // lleno), así que el server consulta la consola web del propio switch con
  7. // cadencia lenta. La web sirve UNA petición a la vez (uIP/8051), por eso el
  8. // poll es serial por switch y nunca en paralelo (InFlight).
  9. //
  10. // El resultado se cachea por slug con {firmware, bootUnix}: a partir del
  11. // bootUnix el uptime se deriva del reloj del server entre polls (no hace
  12. // falta re-consultar cada 30 s), y el poll solo re-sincroniza bootUnix con
  13. // la cadencia configurada (NETPULSE_RTL_POLL_S, default 300).
  14. package httpapi
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io"
  19. "log"
  20. "net/http"
  21. "net/url"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. "github.com/gnacho/netpulse/agent/probe"
  27. )
  28. // rtlConsoleEntry: resultado del último poll OK de la consola del switch.
  29. type rtlConsoleEntry struct {
  30. Firmware string // sw_ver de /information.json ("v0.1.0-e1fa080-dirty")
  31. Model string // hw_ver ("keepLink KP-9000-9XHML-X V3.1")
  32. MAC string // mac_address (la que el switch usa en runtime)
  33. BootUnix time.Time // now - uptimeSec del poll; el uptime se deriva de aquí
  34. PolledAt time.Time // cuándo se hizo el poll (para la cadencia)
  35. InFlight bool // hay un poll en curso (serial por slug)
  36. FailedAt time.Time // último fallo (backoff para no martillear un host no-RTL)
  37. FailCount int
  38. }
  39. // rtlConsoleInfo es la respuesta de /information.json del firmware (solo los
  40. // campos que necesitamos; el JSON tiene más).
  41. type rtlConsoleInfo struct {
  42. SwVer string `json:"sw_ver"`
  43. HwVer string `json:"hw_ver"`
  44. Mac string `json:"mac_address"`
  45. }
  46. // rtlConsoleCache: estado del sondeo por slug. Protegido por su mutex.
  47. type rtlConsoleCache struct {
  48. mu sync.Mutex
  49. pass string
  50. sec int // cadencia en segundos
  51. byID map[string]*rtlConsoleEntry
  52. }
  53. func newRtlConsoleCache(pass string, pollSec int) *rtlConsoleCache {
  54. if pollSec <= 0 {
  55. pollSec = 300
  56. }
  57. if pass == "" {
  58. pass = "1234"
  59. }
  60. return &rtlConsoleCache{pass: pass, sec: pollSec, byID: map[string]*rtlConsoleEntry{}}
  61. }
  62. // snapshot devuelve la entrada cacheada para adjuntar System al payload del
  63. // beacon. Si la entrada es vieja o no existe y no hay poll en curso, lanza el
  64. // poll en background (no bloquea el handler del beacon). Devuelve nil hasta
  65. // que el primer poll tenga éxito (el beacon de turno no lleva System).
  66. func (c *rtlConsoleCache) snapshot(slug, host string) *rtlConsoleEntry {
  67. now := time.Now()
  68. c.mu.Lock()
  69. e := c.byID[slug]
  70. if e == nil {
  71. e = &rtlConsoleEntry{}
  72. c.byID[slug] = e
  73. }
  74. needPoll := e.Firmware == "" || now.Sub(e.PolledAt) >= time.Duration(c.sec)*time.Second
  75. // Backoff tras fallos: reintentar como mucho cada max(sec, 15 min) si el
  76. // host no habla el protocolo (login fallido), para no martillearlo.
  77. if needPoll && e.FailCount > 0 && now.Sub(e.FailedAt) < 15*time.Minute {
  78. needPoll = false
  79. }
  80. if needPoll && !e.InFlight {
  81. e.InFlight = true
  82. c.mu.Unlock()
  83. go c.poll(slug, host)
  84. c.mu.Lock()
  85. }
  86. out := e
  87. c.mu.Unlock()
  88. if out.Firmware == "" {
  89. return nil
  90. }
  91. return out
  92. }
  93. // invalidate marca la entrada para re-poll inmediato (reboot detectado por el
  94. // seq del beacon: el bootUnix cacheado ya no es válido).
  95. func (c *rtlConsoleCache) invalidate(slug string) {
  96. c.mu.Lock()
  97. defer c.mu.Unlock()
  98. if e := c.byID[slug]; e != nil {
  99. e.PolledAt = time.Time{}
  100. }
  101. }
  102. // poll consulta la consola del switch (login + /information.json + /cmd time)
  103. // y guarda el resultado. Serial por slug (InFlight) y con timeouts cortos:
  104. // la web del firmware atiende una conexión cada vez.
  105. func (c *rtlConsoleCache) poll(slug, host string) {
  106. entry, err := c.fetch(host)
  107. c.mu.Lock()
  108. e := c.byID[slug]
  109. if e == nil {
  110. e = &rtlConsoleEntry{}
  111. c.byID[slug] = e
  112. }
  113. e.InFlight = false
  114. if err != nil {
  115. e.FailCount++
  116. e.FailedAt = time.Now()
  117. c.mu.Unlock()
  118. log.Printf("[netpulse:rtl] poll %s (%s) falló: %v", slug, host, err)
  119. return
  120. }
  121. e.Firmware = entry.Firmware
  122. e.Model = entry.Model
  123. e.MAC = entry.MAC
  124. e.BootUnix = entry.BootUnix
  125. e.PolledAt = time.Now()
  126. e.FailCount = 0
  127. c.mu.Unlock()
  128. }
  129. // fetch hace login en la consola y lee /information.json (sw_ver/hw_ver) y el
  130. // uptime por POST /cmd "time". Devuelve bootUnix = now - uptimeSec.
  131. func (c *rtlConsoleCache) fetch(host string) (*rtlConsoleEntry, error) {
  132. base := "http://" + host
  133. // No seguir el 302 del login (Location: index.html): necesitamos la
  134. // cookie del Set-Cookie y la respuesta es el propio redirect.
  135. client := &http.Client{
  136. Timeout: 8 * time.Second,
  137. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  138. return http.ErrUseLastResponse
  139. },
  140. }
  141. // 1) login: POST /login pwd=<pass> → 302 + Set-Cookie: session=...
  142. form := url.Values{"pwd": {c.pass}}
  143. req, err := http.NewRequest(http.MethodPost, base+"/login", strings.NewReader(form.Encode()))
  144. if err != nil {
  145. return nil, err
  146. }
  147. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  148. resp, err := client.Do(req)
  149. if err != nil {
  150. return nil, err
  151. }
  152. cookie := ""
  153. for _, ck := range resp.Cookies() {
  154. if ck.Name == "session" && ck.Value != "" {
  155. cookie = ck.Name + "=" + ck.Value
  156. break
  157. }
  158. }
  159. _, _ = io.Copy(io.Discard, resp.Body)
  160. resp.Body.Close()
  161. if resp.StatusCode != http.StatusFound && resp.StatusCode != http.StatusOK {
  162. return nil, fmt.Errorf("login HTTP %d", resp.StatusCode)
  163. }
  164. if cookie == "" {
  165. return nil, fmt.Errorf("login sin cookie de sesión")
  166. }
  167. // 2) /information.json → sw_ver + hw_ver
  168. infoReq, err := http.NewRequest(http.MethodGet, base+"/information.json", nil)
  169. if err != nil {
  170. return nil, err
  171. }
  172. infoReq.Header.Set("Cookie", cookie)
  173. infoResp, err := client.Do(infoReq)
  174. if err != nil {
  175. return nil, err
  176. }
  177. infoBody, _ := io.ReadAll(io.LimitReader(infoResp.Body, 4096))
  178. infoResp.Body.Close()
  179. if infoResp.StatusCode != http.StatusOK {
  180. return nil, fmt.Errorf("information.json HTTP %d", infoResp.StatusCode)
  181. }
  182. var info rtlConsoleInfo
  183. if err := json.Unmarshal(infoBody, &info); err != nil {
  184. return nil, fmt.Errorf("information.json inválido: %w", err)
  185. }
  186. // 3) POST /cmd "time" → uptime en segundos (hex, p. ej. "0x00028e9d").
  187. // El firmware exige Content-Type en todo POST (sin él responde 404).
  188. cmdReq, err := http.NewRequest(http.MethodPost, base+"/cmd", strings.NewReader("time"))
  189. if err != nil {
  190. return nil, err
  191. }
  192. cmdReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  193. cmdReq.Header.Set("Cookie", cookie)
  194. cmdResp, err := client.Do(cmdReq)
  195. if err != nil {
  196. return nil, err
  197. }
  198. cmdBody, _ := io.ReadAll(io.LimitReader(cmdResp.Body, 256))
  199. cmdResp.Body.Close()
  200. if cmdResp.StatusCode != http.StatusOK {
  201. return nil, fmt.Errorf("/cmd time HTTP %d", cmdResp.StatusCode)
  202. }
  203. upHex := strings.TrimSpace(string(cmdBody))
  204. upHex = strings.TrimPrefix(upHex, "0x")
  205. upHex = strings.TrimPrefix(upHex, "0X")
  206. upSec, err := strconv.ParseUint(upHex, 16, 32)
  207. if err != nil {
  208. return nil, fmt.Errorf("/cmd time no es un contador hex (%q): %w", strings.TrimSpace(string(cmdBody)), err)
  209. }
  210. now := time.Now()
  211. return &rtlConsoleEntry{
  212. Firmware: info.SwVer, Model: info.HwVer, MAC: info.Mac,
  213. BootUnix: now.Add(-time.Duration(upSec) * time.Second),
  214. }, nil
  215. }
  216. // attachSystem adjunta la sección System (board + uptime + MAC) al payload de
  217. // un beacon periódico si hay datos de consola cacheados. Es el punto de
  218. // inyección: polledFromAgent mapea System.Board→board, SysInfo.Uptime→
  219. // uptimeSec y BridgeMAC→brMac, y buildRouter pinta Firmware/Uptime/MAC sin
  220. // cambios en el front.
  221. func (s *server) attachRTLConsole(slug, host string, pl *probe.Payload) {
  222. if s.rtlConsole == nil || pl == nil {
  223. return
  224. }
  225. e := s.rtlConsole.snapshot(slug, host)
  226. if e == nil {
  227. return
  228. }
  229. // Board.Release es un struct anónimo; se rellena campo a campo igual que
  230. // boardWithDesc en los tests de buildRouter.
  231. b := &probe.BoardInfo{}
  232. b.Model = e.Model
  233. b.Release.Description = "RTLPlayground " + e.Firmware
  234. sd := &probe.SystemData{
  235. Board: b,
  236. SysInfo: &probe.SysInfo{Uptime: time.Since(e.BootUnix).Seconds()},
  237. BridgeMAC: strings.ToUpper(e.MAC),
  238. }
  239. pl.Data.System = sd
  240. }