integrations_boot_test.go 15 KB

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