integrations_boot_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. // integrations_boot_test.go - #1696: reanudación al arrancar de las
  2. // integraciones locales habilitadas, detección de hijos muertos (la fila pasa
  3. // a estado error con su motivo) y conciliación de estado running huérfano
  4. // (sin push en varios intervalos la vista lo reporta como "stale", no sano).
  5. package httpapi_test
  6. import (
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "testing"
  13. "time"
  14. "github.com/gnacho/netpulse/server-go/internal/adapters"
  15. "github.com/gnacho/netpulse/server-go/internal/apitoken"
  16. "github.com/gnacho/netpulse/server-go/internal/auth"
  17. "github.com/gnacho/netpulse/server-go/internal/channelplan"
  18. "github.com/gnacho/netpulse/server-go/internal/config"
  19. "github.com/gnacho/netpulse/server-go/internal/configbackup"
  20. "github.com/gnacho/netpulse/server-go/internal/db"
  21. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  22. "github.com/gnacho/netpulse/server-go/internal/orchestr"
  23. "github.com/gnacho/netpulse/server-go/internal/rintegration"
  24. "github.com/gnacho/netpulse/server-go/internal/sse"
  25. "net/http/httptest"
  26. )
  27. // makeIntegrationsTestServerSeeded replica makeTestServerWithMode pero con el
  28. // supervisor de integraciones cableado (como en producción). seed corre antes
  29. // de construir el handler: las filas de router_integrations deben existir al
  30. // "arrancar" para que el resume del boot las vea.
  31. func makeIntegrationsTestServerSeeded(t *testing.T, seed func(d *db.DB, mgr *rintegration.Manager)) (*testServer, *rintegration.Manager) {
  32. return makeIntegrationsTestServerFull(t, seed, nil)
  33. }
  34. // makeIntegrationsTestServerFull es la variante con catálogo de vendors
  35. // inyectable (#1697): catFn construye el VendorCatalog con la base ya abierta
  36. // (nil → fallback de NewHandler: semilla embebida sin red).
  37. func makeIntegrationsTestServerFull(t *testing.T, seed func(d *db.DB, mgr *rintegration.Manager), catFn func(d *db.DB) *rintegration.Catalog) (*testServer, *rintegration.Manager) {
  38. t.Helper()
  39. auth.SetTrustProxy(true)
  40. t.Cleanup(func() { auth.SetTrustProxy(false) })
  41. dataDir := t.TempDir()
  42. cfg, err := config.Load(map[string]string{
  43. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  44. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  45. }, dataDir)
  46. if err != nil {
  47. t.Fatalf("config: %v", err)
  48. }
  49. d, err := db.Open(dataDir)
  50. if err != nil {
  51. t.Fatalf("db: %v", err)
  52. }
  53. secret, err := auth.EnsureSessionSecret(d, cfg)
  54. if err != nil {
  55. t.Fatalf("secret: %v", err)
  56. }
  57. if err := auth.EnsureUsers(d, cfg); err != nil {
  58. t.Fatalf("users: %v", err)
  59. }
  60. if err := apitoken.EnsureSchema(d); err != nil {
  61. t.Fatalf("api_tokens schema: %v", err)
  62. }
  63. configBackup, err := configbackup.NewStore(d)
  64. if err != nil {
  65. t.Fatalf("config backup store: %v", err)
  66. }
  67. hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
  68. mgr := rintegration.NewManager(filepath.Join(cfg.DataDir, "integrations"))
  69. if seed != nil {
  70. seed(d, mgr)
  71. }
  72. var cat *rintegration.Catalog
  73. if catFn != nil {
  74. cat = catFn(d)
  75. }
  76. handler := httpapi.NewHandler(httpapi.Deps{
  77. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
  78. Started: time.Now(),
  79. TokenStore: apitoken.NewStore(d, secret),
  80. ConfigBackup: configBackup,
  81. Orchestr: orchestr.New(d),
  82. Agents: adapters.NewAgentRegistry(0),
  83. ChannelPlan: channelplan.NewStore(d.DB),
  84. Integrations: mgr,
  85. VendorCatalog: cat,
  86. })
  87. srv := httptest.NewServer(handler)
  88. ts := &testServer{Server: srv, db: d, secret: secret}
  89. t.Cleanup(func() {
  90. srv.Close()
  91. d.Close()
  92. })
  93. return ts, mgr
  94. }
  95. func makeIntegrationsTestServer(t *testing.T) (*testServer, *rintegration.Manager) {
  96. t.Helper()
  97. return makeIntegrationsTestServerSeeded(t, nil)
  98. }
  99. func bootIntegrationRow(slug, vendor, mode string, enabled bool, state string) rintegration.Row {
  100. return rintegration.Row{
  101. Slug: slug, Vendor: vendor, Mode: mode, Host: "10.0.0.1", Username: "admin",
  102. Version: "0.1.1", Asset: vendor + ".tar.gz",
  103. Arch: "amd64", IntervalS: 45, Enabled: enabled, State: state,
  104. }
  105. }
  106. // installFakePusher escribe el "binario" instalado del pusher (script sh)
  107. // dentro del directorio de la integración y su fichero de entorno 0600, el
  108. // mismo layout que deja un alta real en disco.
  109. func installFakePusher(t *testing.T, mgr *rintegration.Manager, slug, binary, body string) string {
  110. t.Helper()
  111. installDir := filepath.Join(mgr.Dir(), slug)
  112. if err := os.MkdirAll(installDir, 0o755); err != nil {
  113. t.Fatalf("mkdir %s: %v", installDir, err)
  114. }
  115. bin := filepath.Join(installDir, binary)
  116. if err := os.WriteFile(bin, []byte("#!/bin/sh\n"+body), 0o755); err != nil {
  117. t.Fatalf("write %s: %v", bin, err)
  118. }
  119. if err := mgr.WriteEnv(slug, map[string]string{"NETPULSE_SLUG": slug}); err != nil {
  120. t.Fatalf("write env %s: %v", slug, err)
  121. }
  122. return bin
  123. }
  124. func integrationsBySlug(t *testing.T, ts *testServer) map[string]map[string]any {
  125. t.Helper()
  126. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  127. res := get(t, ts.URL, "/api/integrations", cookie)
  128. if res.StatusCode != http.StatusOK {
  129. t.Fatalf("GET /api/integrations: status %d", res.StatusCode)
  130. }
  131. body := readJSON(t, res)
  132. rawItems, ok := body["integrations"].([]any)
  133. if !ok {
  134. t.Fatalf("GET /api/integrations: integrations missing: %v", body)
  135. }
  136. out := map[string]map[string]any{}
  137. for _, raw := range rawItems {
  138. it, ok := raw.(map[string]any)
  139. if !ok {
  140. t.Fatalf("integration item no es un objeto: %v", raw)
  141. }
  142. slug, _ := it["slug"].(string)
  143. out[slug] = it
  144. }
  145. return out
  146. }
  147. func waitIntegrationState(t *testing.T, store *rintegration.Store, slug, state string) rintegration.Row {
  148. t.Helper()
  149. deadline := time.Now().Add(5 * time.Second)
  150. for {
  151. row, ok := store.Get(slug)
  152. if ok && row.State == state {
  153. return row
  154. }
  155. if time.Now().After(deadline) {
  156. row, _ = store.Get(slug)
  157. t.Fatalf("la fila %s no llegó a estado %q a tiempo (estado %q, lastError %q)", slug, state, row.State, row.LastError)
  158. }
  159. time.Sleep(5 * time.Millisecond)
  160. }
  161. }
  162. // TestIntegrationsResumeOnBoot: al arrancar el servidor, la integración local
  163. // habilitada se reanuda sola con el binario y el env ya en disco; la que no
  164. // tiene binario queda en error sin tirar el arranque; la deshabilitada no se
  165. // toca; la de modo ssh deja de decir running (no verificada desde aquí).
  166. func TestIntegrationsResumeOnBoot(t *testing.T) {
  167. v := seedVendor(t, "routeros")
  168. ts, mgr := makeIntegrationsTestServerSeeded(t, func(d *db.DB, mgr *rintegration.Manager) {
  169. store := rintegration.NewStore(d.DB)
  170. installFakePusher(t, mgr, "lab", v.Binary, "sleep 30")
  171. _ = store.Upsert(bootIntegrationRow("lab", "routeros", "local", true, "running"))
  172. _ = mgr.WriteEnv("broken", map[string]string{"NETPULSE_SLUG": "broken"})
  173. _ = store.Upsert(bootIntegrationRow("broken", "routeros", "local", true, "running"))
  174. _ = store.Upsert(bootIntegrationRow("off", "routeros", "local", false, "stopped"))
  175. _ = store.Upsert(bootIntegrationRow("wrt", "asuswrt", "ssh", true, "running"))
  176. })
  177. store := rintegration.NewStore(ts.db.DB)
  178. deadline := time.Now().Add(5 * time.Second)
  179. for !mgr.Running("lab") {
  180. if time.Now().After(deadline) {
  181. t.Fatal("la integración local habilitada no se reanudó al arrancar")
  182. }
  183. time.Sleep(5 * time.Millisecond)
  184. }
  185. t.Cleanup(func() { _ = mgr.Stop("lab") })
  186. row := waitIntegrationState(t, store, "lab", "running")
  187. if row.LastStartMs == 0 {
  188. t.Fatalf("lab reanudada sin last_start_ms: %+v", row)
  189. }
  190. if row.LastError != "" {
  191. t.Fatalf("lab reanudada con lastError %q", row.LastError)
  192. }
  193. broken := waitIntegrationState(t, store, "broken", "error")
  194. if broken.LastError == "" {
  195. t.Fatal("broken quedó en error sin lastError")
  196. }
  197. if mgr.Running("broken") {
  198. t.Fatal("broken no debe tener proceso")
  199. }
  200. if row, _ := store.Get("off"); row.State != "stopped" || mgr.Running("off") {
  201. t.Fatalf("la deshabilitada no se debe tocar: state=%q running=%v", row.State, mgr.Running("off"))
  202. }
  203. if row, _ := store.Get("wrt"); row.State != "unverified" {
  204. t.Fatalf("la ssh habilitada debe dejar running tras el arranque, state=%q", row.State)
  205. }
  206. if mgr.Running("wrt") {
  207. t.Fatal("la ssh no debe arrancar en el servidor")
  208. }
  209. items := integrationsBySlug(t, ts)
  210. if it := items["lab"]; it == nil || it["state"] != "running" {
  211. t.Fatalf("API lab: %v", items["lab"])
  212. }
  213. if it := items["broken"]; it == nil || it["state"] != "error" || it["lastError"] == "" {
  214. t.Fatalf("API broken: %v", items["broken"])
  215. }
  216. if it := items["wrt"]; it == nil || it["state"] != "unverified" {
  217. t.Fatalf("API wrt: %v", items["wrt"])
  218. }
  219. }
  220. // TestIntegrationsDeadChildFlipsToError: un pusher que muere solo (código de
  221. // error, salida limpia o un kill externo) deja la fila en estado error con su
  222. // motivo y deja de reportarse como running.
  223. func TestIntegrationsDeadChildFlipsToError(t *testing.T) {
  224. for _, tc := range []struct {
  225. name, script, wantErr string
  226. }{
  227. {"crash", "exit 3", "exit status 3"},
  228. {"clean-exit", "exit 0", "exit code 0"},
  229. {"killed", `kill -9 $$`, "signal: killed"},
  230. } {
  231. t.Run(tc.name, func(t *testing.T) {
  232. v := seedVendor(t, "routeros")
  233. slug := "dead-" + tc.name
  234. ts, mgr := makeIntegrationsTestServer(t)
  235. store := rintegration.NewStore(ts.db.DB)
  236. bin := installFakePusher(t, mgr, slug, v.Binary, tc.script)
  237. if err := store.Upsert(bootIntegrationRow(slug, "routeros", "local", true, "running")); err != nil {
  238. t.Fatal(err)
  239. }
  240. if err := mgr.Start(slug, nil, bin); err != nil {
  241. t.Fatalf("start: %v", err)
  242. }
  243. row := waitIntegrationState(t, store, slug, "error")
  244. if row.LastError == "" || !strings.Contains(row.LastError, tc.wantErr) {
  245. t.Fatalf("lastError = %q, want contener %q", row.LastError, tc.wantErr)
  246. }
  247. if mgr.Running(slug) {
  248. t.Fatal("el hijo muerto sigue reportándose como running")
  249. }
  250. items := integrationsBySlug(t, ts)
  251. if it := items[slug]; it == nil || it["state"] != "error" {
  252. t.Fatalf("API %s: %v", slug, items[slug])
  253. }
  254. })
  255. }
  256. }
  257. // TestIntegrationsIntentionalStopDoesNotError: parar por API es un paro
  258. // intencional: la fila queda stopped y el callback de muerte no la marca error.
  259. func TestIntegrationsIntentionalStopDoesNotError(t *testing.T) {
  260. v := seedVendor(t, "routeros")
  261. ts, mgr := makeIntegrationsTestServer(t)
  262. store := rintegration.NewStore(ts.db.DB)
  263. bin := installFakePusher(t, mgr, "manual", v.Binary, "sleep 30")
  264. if err := store.Upsert(bootIntegrationRow("manual", "routeros", "local", true, "running")); err != nil {
  265. t.Fatal(err)
  266. }
  267. if err := mgr.Start("manual", nil, bin); err != nil {
  268. t.Fatalf("start: %v", err)
  269. }
  270. t.Cleanup(func() { _ = mgr.Stop("manual") })
  271. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  272. res, body := wanSpeedRequest(t, "POST", ts.URL, "/api/integrations/manual/stop", cookie, "")
  273. if res.StatusCode != http.StatusOK {
  274. t.Fatalf("POST stop: status %d (%v)", res.StatusCode, body)
  275. }
  276. if it := body["integration"].(map[string]any); it["state"] != "stopped" {
  277. t.Fatalf("estado tras stop: %v", it["state"])
  278. }
  279. // Ventana corta de ausencia: ningún callback tardío debe convertir el
  280. // paro intencional en error.
  281. deadline := time.Now().Add(300 * time.Millisecond)
  282. for time.Now().Before(deadline) {
  283. if row, _ := store.Get("manual"); row.State == "error" {
  284. t.Fatal("el paro intencional acabó en estado error")
  285. }
  286. time.Sleep(20 * time.Millisecond)
  287. }
  288. }
  289. // TestIntegrationsCheckReconcilesState: un check con el proceso
  290. // demostradamente vivo saca la fila de un estado desfasado (unverified tras un
  291. // reinicio del servidor) y la devuelve a running; sin proceso, la fila no se
  292. // toca (el error sigue siendo error).
  293. func TestIntegrationsCheckReconcilesState(t *testing.T) {
  294. v := seedVendor(t, "routeros")
  295. ts, mgr := makeIntegrationsTestServer(t)
  296. store := rintegration.NewStore(ts.db.DB)
  297. bin := installFakePusher(t, mgr, "verify", v.Binary, "sleep 30")
  298. if err := store.Upsert(bootIntegrationRow("verify", "routeros", "local", true, "unverified")); err != nil {
  299. t.Fatal(err)
  300. }
  301. if err := store.Upsert(bootIntegrationRow("dead-check", "routeros", "local", true, "error")); err != nil {
  302. t.Fatal(err)
  303. }
  304. if err := mgr.Start("verify", nil, bin); err != nil {
  305. t.Fatalf("start: %v", err)
  306. }
  307. t.Cleanup(func() { _ = mgr.Stop("verify") })
  308. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  309. res, body := wanSpeedRequest(t, "POST", ts.URL, "/api/integrations/verify/check", cookie, "")
  310. if res.StatusCode != http.StatusOK {
  311. t.Fatalf("POST check: status %d (%v)", res.StatusCode, body)
  312. }
  313. if body["running"] != true {
  314. t.Fatalf("check running: %v", body["running"])
  315. }
  316. if it := body["integration"].(map[string]any); it["state"] != "running" {
  317. t.Fatalf("estado tras check: %v", it["state"])
  318. }
  319. if row, _ := store.Get("verify"); row.State != "running" {
  320. t.Fatalf("la fila no se reconcilió con el check: %q", row.State)
  321. }
  322. res, body = wanSpeedRequest(t, "POST", ts.URL, "/api/integrations/dead-check/check", cookie, "")
  323. if res.StatusCode != http.StatusOK {
  324. t.Fatalf("POST check dead: status %d (%v)", res.StatusCode, body)
  325. }
  326. if body["running"] != false {
  327. t.Fatalf("check running dead: %v", body["running"])
  328. }
  329. if row, _ := store.Get("dead-check"); row.State != "error" {
  330. t.Fatalf("el check sin proceso no debe tocar la fila: %q", row.State)
  331. }
  332. }
  333. // TestIntegrationsStaleNotReportedRunning: conciliación al leer. Una fila en
  334. // running cuyo último push es más viejo que 3 intervalos se reporta como
  335. // "stale" en la API (y no fresh), sin tocar la fila; con push reciente sigue
  336. // siendo running/fresh; sin push nunca no se puede juzgar y sigue running.
  337. func TestIntegrationsStaleNotReportedRunning(t *testing.T) {
  338. ts, _ := makeIntegrationsTestServer(t)
  339. store := rintegration.NewStore(ts.db.DB)
  340. now := time.Now().Unix()
  341. rows := []struct {
  342. slug, vendor, mode, state string
  343. pushSec int64
  344. }{
  345. {"fresh-push", "routeros", "local", "running", now - 10},
  346. {"old-push", "routeros", "local", "running", now - 200},
  347. {"no-push", "routeros", "local", "running", 0},
  348. {"errored", "routeros", "local", "error", now - 200},
  349. {"stale-ssh", "asuswrt", "ssh", "running", now - 200},
  350. }
  351. for _, r := range rows {
  352. if err := store.Upsert(bootIntegrationRow(r.slug, r.vendor, r.mode, true, r.state)); err != nil {
  353. t.Fatal(err)
  354. }
  355. if r.pushSec > 0 {
  356. if _, err := ts.db.Exec(
  357. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
  358. "agent.last_push_ts."+r.slug, strconv.FormatInt(r.pushSec, 10),
  359. ); err != nil {
  360. t.Fatal(err)
  361. }
  362. }
  363. }
  364. items := integrationsBySlug(t, ts)
  365. if it := items["fresh-push"]; it == nil || it["state"] != "running" || it["fresh"] != true {
  366. t.Fatalf("fresh-push: %v", items["fresh-push"])
  367. }
  368. if it := items["old-push"]; it == nil || it["state"] != "stale" || it["fresh"] != false {
  369. t.Fatalf("old-push debe salir stale sin fresh: %v", items["old-push"])
  370. }
  371. if it := items["no-push"]; it == nil || it["state"] != "running" {
  372. t.Fatalf("no-push (sin push aún) no se puede juzgar: %v", items["no-push"])
  373. }
  374. if it := items["errored"]; it == nil || it["state"] != "error" {
  375. t.Fatalf("errored: %v", items["errored"])
  376. }
  377. if it := items["stale-ssh"]; it == nil || it["state"] != "stale" {
  378. t.Fatalf("stale-ssh: %v", items["stale-ssh"])
  379. }
  380. // La conciliación es de vista: la fila sigue en running en la base de
  381. // datos y el propio cálculo la devuelve a running cuando vuelva a empujar.
  382. if row, _ := store.Get("old-push"); row.State != "running" {
  383. t.Fatalf("la fila no se debe tocar: state=%q", row.State)
  384. }
  385. }