integrations.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. // integrations.go — API de integraciones externas de routers (#1674):
  2. // pushers de routers externos (MikroTik RouterOS, Asuswrt) gestionados desde
  3. // la app con el contrato de agente externo. El slug de la integración es el
  4. // id del router external asociado, así el push del pusher (POST
  5. // /api/ingest/agent con Bearer token) se atribuye a la misma unidad.
  6. package httpapi
  7. import (
  8. "fmt"
  9. "net/http"
  10. "path/filepath"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/gnacho/netpulse/server-go/internal/auth"
  16. "github.com/gnacho/netpulse/server-go/internal/rintegration"
  17. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  18. )
  19. // integrationItem es la vista HTTP de una integración (nunca la contraseña).
  20. type integrationItem struct {
  21. Slug string `json:"slug"`
  22. Vendor string `json:"vendor"`
  23. Mode string `json:"mode"`
  24. Host string `json:"host"`
  25. Username string `json:"username"`
  26. Version string `json:"version"`
  27. Arch string `json:"arch"`
  28. IntervalS int `json:"intervalS"`
  29. Enabled bool `json:"enabled"`
  30. State string `json:"state"`
  31. LastError string `json:"lastError"`
  32. LastStartMs int64 `json:"lastStartMs"`
  33. LastPushMs int64 `json:"lastPushMs"`
  34. Fresh bool `json:"fresh"`
  35. }
  36. // vendorView es la vista HTTP del manifiesto de un vendor.
  37. type vendorView struct {
  38. ID string `json:"id"`
  39. Mode string `json:"mode"`
  40. Arches []string `json:"arches"`
  41. TagPrefix string `json:"tagPrefix"`
  42. Description string `json:"description"`
  43. }
  44. // registerIntegrationRoutes registra las rutas /api/integrations/*. Todas
  45. // exigen rol admin salvo el GET de vendors (solo sesión).
  46. func (s *server) registerIntegrationRoutes(mux *http.ServeMux) {
  47. mux.HandleFunc("GET /api/integrations/vendors", s.handleIntegrationsVendors)
  48. mux.Handle("GET /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsList)))
  49. mux.Handle("POST /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsCreate)))
  50. mux.Handle("POST /api/integrations/{slug}/start", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStart)))
  51. mux.Handle("POST /api/integrations/{slug}/stop", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStop)))
  52. mux.Handle("POST /api/integrations/{slug}/check", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationCheck)))
  53. mux.Handle("POST /api/integrations/{slug}/update", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationUpdate)))
  54. mux.Handle("PUT /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationEdit)))
  55. mux.Handle("DELETE /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationDelete)))
  56. }
  57. func (s *server) handleIntegrationsVendors(w http.ResponseWriter, _ *http.Request) {
  58. vs := rintegration.Vendors()
  59. out := make([]vendorView, 0, len(vs))
  60. for _, v := range vs {
  61. out = append(out, vendorView{
  62. ID: v.ID, Mode: v.Mode, Arches: v.Arches,
  63. TagPrefix: v.TagPrefix, Description: v.Description,
  64. })
  65. }
  66. writeJSON(w, http.StatusOK, map[string]any{"vendors": out})
  67. }
  68. func (s *server) integrationsStore() *rintegration.Store {
  69. return rintegration.NewStore(s.db.DB)
  70. }
  71. func (s *server) integrationFetcher() *rintegration.Fetcher {
  72. if s.integrations != nil {
  73. return s.integrations.Fetch()
  74. }
  75. return rintegration.NewFetcher()
  76. }
  77. func (s *server) getIntegrationRow(slug string) (rintegration.Row, bool) {
  78. if s.db == nil {
  79. return rintegration.Row{}, false
  80. }
  81. return s.integrationsStore().Get(slug)
  82. }
  83. // integrationLastPushMs lee agent.last_push_ts.<slug> (segundos unix) y lo
  84. // devuelve en milisegundos, 0 si nunca empujó.
  85. func (s *server) integrationLastPushMs(slug string) int64 {
  86. if s.db == nil {
  87. return 0
  88. }
  89. sec, err := strconv.ParseInt(kvGet(s.db.DB, "agent.last_push_ts."+slug), 10, 64)
  90. if err != nil {
  91. return 0
  92. }
  93. return sec * 1000
  94. }
  95. func (s *server) integrationItemOf(row rintegration.Row) integrationItem {
  96. lastPush := s.integrationLastPushMs(row.Slug)
  97. fresh := false
  98. if lastPush > 0 && row.IntervalS > 0 {
  99. fresh = time.Now().UnixMilli()-lastPush <= int64(row.IntervalS)*3*1000
  100. }
  101. return integrationItem{
  102. Slug: row.Slug, Vendor: row.Vendor, Mode: row.Mode, Host: row.Host,
  103. Username: row.Username, Version: row.Version, Arch: row.Arch,
  104. IntervalS: row.IntervalS, Enabled: row.Enabled, State: row.State,
  105. LastError: row.LastError, LastStartMs: row.LastStartMs,
  106. LastPushMs: lastPush, Fresh: fresh,
  107. }
  108. }
  109. func (s *server) integrationList() []integrationItem {
  110. if s.db == nil {
  111. return []integrationItem{}
  112. }
  113. rows, err := s.integrationsStore().List()
  114. if err != nil {
  115. return []integrationItem{}
  116. }
  117. out := make([]integrationItem, 0, len(rows))
  118. for _, row := range rows {
  119. out = append(out, s.integrationItemOf(row))
  120. }
  121. return out
  122. }
  123. func (s *server) broadcastIntegrations() {
  124. if s.hub != nil {
  125. s.hub.Broadcast("integrations", map[string]any{"integrations": s.integrationList()})
  126. }
  127. }
  128. func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
  129. writeJSON(w, http.StatusOK, map[string]any{"integrations": s.integrationList()})
  130. }
  131. type integrationCreateBody struct {
  132. Slug string `json:"slug"`
  133. Vendor string `json:"vendor"`
  134. Host string `json:"host"`
  135. Username string `json:"username"`
  136. Password string `json:"password"`
  137. IntervalS int `json:"intervalS"`
  138. Arch string `json:"arch"`
  139. }
  140. func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request) {
  141. if s.db == nil {
  142. writeError(w, http.StatusInternalServerError, "db_error")
  143. return
  144. }
  145. var body integrationCreateBody
  146. if st := readJSONBody(w, r, &body); st != 0 {
  147. writeBodyError(w, st, "invalid_body", `Se esperaba { "slug", "vendor", "host", "username", "password", "intervalS", "arch"? }`)
  148. return
  149. }
  150. if !agentSlugRe.MatchString(body.Slug) {
  151. writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
  152. return
  153. }
  154. vendor, ok := rintegration.LookupVendor(body.Vendor)
  155. if !ok {
  156. writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
  157. return
  158. }
  159. if body.Host == "" || body.Username == "" || body.Password == "" {
  160. writeError(w, http.StatusBadRequest, "invalid_input", "host, username and password are required")
  161. return
  162. }
  163. if body.IntervalS < 10 || body.IntervalS > 86400 {
  164. writeError(w, http.StatusBadRequest, "invalid_interval", "intervalS must be between 10 and 86400")
  165. return
  166. }
  167. arch := body.Arch
  168. if arch == "" {
  169. arch = vendor.Arches[0]
  170. } else if !vendorSupportsArch(vendor, arch) {
  171. writeError(w, http.StatusBadRequest, "invalid_arch", "unsupported arch "+arch)
  172. return
  173. }
  174. store := s.integrationsStore()
  175. if _, exists := store.Get(body.Slug); exists {
  176. writeError(w, http.StatusConflict, "already_exists", "integration already exists")
  177. return
  178. }
  179. // Resolver y descargar el último release verificado. En modo local se
  180. // extrae el binario aquí (corre en este host); en modo ssh solo se
  181. // verifica: el router descarga el asset él mismo.
  182. fetch := s.integrationFetcher()
  183. res, err := fetch.ResolveLatest(vendor, arch)
  184. if err != nil {
  185. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  186. return
  187. }
  188. binPath := ""
  189. if vendor.Mode == "local" {
  190. if s.integrations == nil {
  191. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  192. return
  193. }
  194. installDir := filepath.Join(s.integrations.Dir(), body.Slug)
  195. binPath, err = fetch.Download(res, vendor.Binary, installDir)
  196. if err != nil {
  197. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  198. return
  199. }
  200. } else {
  201. if s.pool == nil {
  202. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  203. return
  204. }
  205. if err := fetch.Verify(res); err != nil {
  206. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  207. return
  208. }
  209. }
  210. now := time.Now().UnixMilli()
  211. row := rintegration.Row{
  212. Slug: body.Slug, Vendor: vendor.ID, Mode: vendor.Mode, Host: body.Host,
  213. Username: body.Username, Version: res.Version, Asset: res.AssetName,
  214. Arch: arch, IntervalS: body.IntervalS, Enabled: true, State: "pending",
  215. CreatedAt: now, UpdatedAt: now,
  216. }
  217. if err := store.Upsert(row); err != nil {
  218. writeError(w, http.StatusInternalServerError, "db_error")
  219. return
  220. }
  221. // Router external cuyo id es el slug (push autenticado por token de
  222. // agente, agent.token.<slug>).
  223. router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  224. Name: body.Slug, Host: body.Host, Type: "external", AgentOnly: true,
  225. })
  226. if err != nil || router.ID != body.Slug {
  227. _ = store.Delete(body.Slug)
  228. writeError(w, http.StatusInternalServerError, "router_error")
  229. return
  230. }
  231. s.syncRouters()
  232. rollback := func() {
  233. if vendor.Mode == "local" && s.integrations != nil {
  234. _ = s.integrations.Stop(body.Slug)
  235. _ = s.integrations.Cleanup(body.Slug)
  236. }
  237. _ = routerstore.RemoveRouter(s.db.DB, body.Slug)
  238. s.syncRouters()
  239. _ = store.Delete(body.Slug)
  240. }
  241. serverURL := s.agentBaseURL(r)
  242. token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
  243. env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
  244. if vendor.Mode == "local" {
  245. return s.integrations.Start(body.Slug, env, binPath)
  246. }
  247. return s.runSSHInstall(vendor, row, env, res.URL, res.SHA256)
  248. })
  249. if err != nil {
  250. rollback()
  251. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  252. return
  253. }
  254. _ = store.SetState(body.Slug, "running", "")
  255. _ = store.SetLastStart(body.Slug, time.Now().UnixMilli())
  256. s.broadcastIntegrations()
  257. item, _ := s.getIntegrationRow(body.Slug)
  258. writeJSON(w, http.StatusCreated, map[string]any{
  259. "integration": s.integrationItemOf(item),
  260. "token": token,
  261. })
  262. }
  263. func vendorSupportsArch(v rintegration.Vendor, arch string) bool {
  264. for _, a := range v.Arches {
  265. if a == arch {
  266. return true
  267. }
  268. }
  269. return false
  270. }
  271. // pusherEnv construye el entorno del pusher. En modo ssh el pusher corre en el
  272. // propio router, así que el host del dispositivo es la propia unidad
  273. // (127.0.0.1) en lugar del host SSH de la tabla.
  274. func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password, serverURL, token string) map[string]string {
  275. prefix := strings.ToUpper(v.ID) + "_"
  276. host := row.Host
  277. if v.Mode == "ssh" {
  278. host = "127.0.0.1"
  279. }
  280. return map[string]string{
  281. prefix + "HOST": host,
  282. prefix + "USER": row.Username,
  283. prefix + "PASS": password,
  284. prefix + "INSECURE": "1",
  285. "NETPULSE_SERVER": serverURL,
  286. "NETPULSE_TOKEN": token,
  287. "NETPULSE_SLUG": row.Slug,
  288. "NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
  289. }
  290. }
  291. func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
  292. _, err := s.pool.Run(row.Host, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
  293. return err
  294. }
  295. func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
  296. slug := r.PathValue("slug")
  297. row, ok := s.getIntegrationRow(slug)
  298. if !ok {
  299. writeError(w, http.StatusNotFound, "not_found")
  300. return
  301. }
  302. vendor, ok := rintegration.LookupVendor(row.Vendor)
  303. if !ok {
  304. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  305. return
  306. }
  307. store := s.integrationsStore()
  308. if vendor.Mode == "local" {
  309. if s.integrations == nil {
  310. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  311. return
  312. }
  313. if !s.integrations.Running(slug) {
  314. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  315. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  316. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  317. return
  318. }
  319. }
  320. } else {
  321. if s.pool == nil {
  322. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  323. return
  324. }
  325. if _, err := s.pool.Run(row.Host, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
  326. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  327. return
  328. }
  329. }
  330. _ = store.SetState(slug, "running", "")
  331. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  332. s.broadcastIntegrations()
  333. item, _ := s.getIntegrationRow(slug)
  334. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  335. }
  336. func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
  337. slug := r.PathValue("slug")
  338. row, ok := s.getIntegrationRow(slug)
  339. if !ok {
  340. writeError(w, http.StatusNotFound, "not_found")
  341. return
  342. }
  343. vendor, ok := rintegration.LookupVendor(row.Vendor)
  344. if !ok {
  345. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  346. return
  347. }
  348. if vendor.Mode == "local" {
  349. if s.integrations != nil {
  350. _ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
  351. }
  352. } else if s.pool != nil {
  353. _, _ = s.pool.Run(row.Host, sshServiceScript(vendor, "stop"), 60*time.Second)
  354. }
  355. _ = s.integrationsStore().SetState(slug, "stopped", "")
  356. s.broadcastIntegrations()
  357. item, _ := s.getIntegrationRow(slug)
  358. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  359. }
  360. func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request) {
  361. slug := r.PathValue("slug")
  362. row, ok := s.getIntegrationRow(slug)
  363. if !ok {
  364. writeError(w, http.StatusNotFound, "not_found")
  365. return
  366. }
  367. vendor, ok := rintegration.LookupVendor(row.Vendor)
  368. if !ok {
  369. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  370. return
  371. }
  372. running := false
  373. if vendor.Mode == "local" {
  374. running = s.integrations != nil && s.integrations.Running(slug)
  375. } else if s.pool != nil {
  376. _, err := s.pool.Run(row.Host, sshServiceScript(vendor, "check"), 30*time.Second)
  377. running = err == nil
  378. }
  379. writeJSON(w, http.StatusOK, map[string]any{
  380. "integration": s.integrationItemOf(row),
  381. "running": running,
  382. })
  383. }
  384. func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request) {
  385. slug := r.PathValue("slug")
  386. row, ok := s.getIntegrationRow(slug)
  387. if !ok {
  388. writeError(w, http.StatusNotFound, "not_found")
  389. return
  390. }
  391. vendor, ok := rintegration.LookupVendor(row.Vendor)
  392. if !ok {
  393. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  394. return
  395. }
  396. fetch := s.integrationFetcher()
  397. res, err := fetch.ResolveLatest(vendor, row.Arch)
  398. if err != nil {
  399. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  400. return
  401. }
  402. store := s.integrationsStore()
  403. if vendor.Mode == "local" {
  404. if s.integrations == nil {
  405. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  406. return
  407. }
  408. _ = s.integrations.Stop(slug)
  409. installDir := filepath.Join(s.integrations.Dir(), slug)
  410. if _, err := fetch.Download(res, vendor.Binary, installDir); err != nil {
  411. _ = store.SetState(slug, "error", err.Error())
  412. s.broadcastIntegrations()
  413. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  414. return
  415. }
  416. if err := s.integrations.Start(slug, nil, filepath.Join(installDir, vendor.Binary)); err != nil {
  417. _ = store.SetState(slug, "error", err.Error())
  418. s.broadcastIntegrations()
  419. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  420. return
  421. }
  422. } else {
  423. if s.pool == nil {
  424. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  425. return
  426. }
  427. if err := fetch.Verify(res); err != nil {
  428. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  429. return
  430. }
  431. env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
  432. if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
  433. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  434. return
  435. }
  436. }
  437. _ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
  438. _ = store.SetState(slug, "running", "")
  439. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  440. s.broadcastIntegrations()
  441. item, _ := s.getIntegrationRow(slug)
  442. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  443. }
  444. // handleIntegrationEdit actualiza los ajustes mutables de una integración sin
  445. // recrearla: host, usuario, contraseña e intervalo. El fichero de entorno se
  446. // lee, se cambian solo las claves afectadas y se reescribe, de modo que el
  447. // token y la contraseña omitida se conservan (nunca viven en la base de datos).
  448. func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
  449. slug := r.PathValue("slug")
  450. row, ok := s.getIntegrationRow(slug)
  451. if !ok {
  452. writeError(w, http.StatusNotFound, "not_found")
  453. return
  454. }
  455. vendor, ok := rintegration.LookupVendor(row.Vendor)
  456. if !ok {
  457. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  458. return
  459. }
  460. var body struct {
  461. Host *string `json:"host"`
  462. Username *string `json:"username"`
  463. Password *string `json:"password"`
  464. IntervalS *int `json:"intervalS"`
  465. }
  466. if st := readJSONBody(w, r, &body); st != 0 {
  467. writeBodyError(w, st, "invalid_body", "")
  468. return
  469. }
  470. changed := false
  471. if body.Host != nil {
  472. h := strings.TrimSpace(*body.Host)
  473. if h == "" {
  474. writeError(w, http.StatusBadRequest, "invalid_input", "host cannot be empty")
  475. return
  476. }
  477. row.Host = h
  478. changed = true
  479. }
  480. if body.Username != nil {
  481. u := strings.TrimSpace(*body.Username)
  482. if u == "" {
  483. writeError(w, http.StatusBadRequest, "invalid_input", "username cannot be empty")
  484. return
  485. }
  486. row.Username = u
  487. changed = true
  488. }
  489. if body.IntervalS != nil {
  490. if *body.IntervalS < 10 || *body.IntervalS > 86400 {
  491. writeError(w, http.StatusBadRequest, "invalid_interval")
  492. return
  493. }
  494. row.IntervalS = *body.IntervalS
  495. changed = true
  496. }
  497. password := ""
  498. if body.Password != nil {
  499. password = *body.Password
  500. changed = true
  501. }
  502. if !changed {
  503. writeError(w, http.StatusBadRequest, "invalid_input", "nothing to update")
  504. return
  505. }
  506. prefix := strings.ToUpper(vendor.ID) + "_"
  507. host := row.Host
  508. if vendor.Mode == "ssh" {
  509. host = "127.0.0.1"
  510. }
  511. store := s.integrationsStore()
  512. if vendor.Mode == "local" {
  513. if s.integrations == nil {
  514. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  515. return
  516. }
  517. env, err := s.integrations.Env(slug)
  518. if err != nil {
  519. _ = store.SetState(slug, "error", err.Error())
  520. s.broadcastIntegrations()
  521. writeError(w, http.StatusConflict, "env_unavailable", err.Error())
  522. return
  523. }
  524. env[prefix+"HOST"] = host
  525. env[prefix+"USER"] = row.Username
  526. if password != "" {
  527. env[prefix+"PASS"] = password
  528. }
  529. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  530. if err := s.integrations.WriteEnv(slug, env); err != nil {
  531. _ = store.SetState(slug, "error", err.Error())
  532. s.broadcastIntegrations()
  533. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  534. return
  535. }
  536. _ = s.integrations.Stop(slug)
  537. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  538. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  539. _ = store.SetState(slug, "error", err.Error())
  540. s.broadcastIntegrations()
  541. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  542. return
  543. }
  544. } else {
  545. if s.pool == nil {
  546. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  547. return
  548. }
  549. raw, err := s.pool.Run(row.Host, sshEnvReadScript(vendor), 30*time.Second)
  550. if err != nil {
  551. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  552. return
  553. }
  554. env := rintegration.ParseEnv(raw)
  555. env[prefix+"HOST"] = host
  556. env[prefix+"USER"] = row.Username
  557. if password != "" {
  558. env[prefix+"PASS"] = password
  559. }
  560. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  561. if _, err := s.pool.Run(row.Host, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
  562. _ = store.SetState(slug, "error", err.Error())
  563. s.broadcastIntegrations()
  564. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  565. return
  566. }
  567. }
  568. if err := store.Upsert(row); err != nil {
  569. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  570. return
  571. }
  572. _ = store.SetState(slug, "running", "")
  573. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  574. s.broadcastIntegrations()
  575. item, _ := s.getIntegrationRow(slug)
  576. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  577. }
  578. func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request) {
  579. slug := r.PathValue("slug")
  580. row, ok := s.getIntegrationRow(slug)
  581. if !ok {
  582. writeError(w, http.StatusNotFound, "not_found")
  583. return
  584. }
  585. vendor, _ := rintegration.LookupVendor(row.Vendor)
  586. if vendor.Mode == "local" {
  587. if s.integrations != nil {
  588. _ = s.integrations.Stop(slug)
  589. _ = s.integrations.Cleanup(slug)
  590. }
  591. } else if s.pool != nil {
  592. _, _ = s.pool.Run(row.Host, sshUninstallScript(vendor), 60*time.Second)
  593. }
  594. _ = s.integrationsStore().Delete(slug)
  595. _ = routerstore.RemoveRouter(s.db.DB, slug)
  596. s.syncRouters()
  597. if s.db != nil {
  598. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
  599. }
  600. s.broadcastIntegrations()
  601. w.WriteHeader(http.StatusNoContent)
  602. }
  603. // ---------------------------------------------------------------------------
  604. // Scripts POSIX de instalación/gestión por SSH (modo ssh, p. ej. asuswrt)
  605. // ---------------------------------------------------------------------------
  606. func sshInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  607. bin := "/usr/sbin/" + v.Binary
  608. init := "/etc/init.d/" + v.Binary
  609. envFile := "/etc/" + v.Binary + ".env"
  610. keys := make([]string, 0, len(env))
  611. for k := range env {
  612. keys = append(keys, k)
  613. }
  614. sort.Strings(keys)
  615. var envBlock strings.Builder
  616. for _, k := range keys {
  617. envBlock.WriteString(k)
  618. envBlock.WriteString("=")
  619. envBlock.WriteString(rintegration.EscapeEnvValue(env[k]))
  620. envBlock.WriteString("\n")
  621. }
  622. return `#!/bin/sh
  623. set -e
  624. BIN="` + bin + `"
  625. INIT="` + init + `"
  626. ENV_FILE="` + envFile + `"
  627. SERVER="` + env["NETPULSE_SERVER"] + `"
  628. ASSET_URL="` + assetURL + `"
  629. SHA256="` + sha256 + `"
  630. # Preflight: el router debe alcanzar el server.
  631. if command -v curl >/dev/null 2>&1; then
  632. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  633. else
  634. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  635. fi
  636. # Parar el servicio previo (el proceso vivo mantiene el binario abierto).
  637. [ -x "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
  638. # Descargar el asset desde la URL ya verificada en el server.
  639. if command -v curl >/dev/null 2>&1; then
  640. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  641. else
  642. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  643. fi
  644. # Verificar sha256 antes de instalar.
  645. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  646. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  647. # Extraer y mover de forma atómica (.new -> rename).
  648. mkdir -p /tmp/` + v.Binary + `.extract
  649. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  650. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  651. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  652. cp "$SRC" "$BIN.new"
  653. chmod 0755 "$BIN.new"
  654. mv -f "$BIN.new" "$BIN"
  655. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  656. # Env (chmod 600): solo se escribe en el alta; los updates preservan el
  657. # fichero existente (la contraseña y el token solo viven ahí).
  658. if [ ! -f "$ENV_FILE" ]; then
  659. cat > "$ENV_FILE" <<'ENVEOF'
  660. ` + envBlock.String() + `ENVEOF
  661. chmod 600 "$ENV_FILE"
  662. fi
  663. # Init procd.
  664. cat > "$INIT" <<'INITEOF'
  665. #!/bin/sh /etc/rc.common
  666. START=99
  667. STOP=10
  668. USE_PROCD=1
  669. BIN="/usr/sbin/` + v.Binary + `"
  670. ENV_FILE="/etc/` + v.Binary + `.env"
  671. start_service() {
  672. [ -x "$BIN" ] || return 1
  673. procd_open_instance ` + v.Binary + `
  674. procd_set_param command "$BIN"
  675. procd_set_param respawn 3600 5 5
  676. procd_set_param stdout 1
  677. procd_set_param stderr 1
  678. procd_set_param file "$ENV_FILE"
  679. procd_close_instance
  680. }
  681. INITEOF
  682. chmod 0755 "$INIT"
  683. "$INIT" enable
  684. "$INIT" restart
  685. `
  686. }
  687. // sshEnvReadScript prints the environment file of an integration running
  688. // inside the router, so the server can merge changes without ever storing the
  689. // token or the password.
  690. func sshEnvReadScript(v rintegration.Vendor) string {
  691. return "cat /etc/" + v.Binary + ".env"
  692. }
  693. // sshEnvWriteScript replaces the environment file inside the router and
  694. // restarts the service. Values come already escaped by EscapeEnvValue and the
  695. // heredoc is quoted, so the shell does not expand anything.
  696. func sshEnvWriteScript(v rintegration.Vendor, env map[string]string) string {
  697. init := "/etc/init.d/" + v.Binary
  698. envFile := "/etc/" + v.Binary + ".env"
  699. keys := make([]string, 0, len(env))
  700. for k := range env {
  701. keys = append(keys, k)
  702. }
  703. sort.Strings(keys)
  704. var envBlock strings.Builder
  705. for _, k := range keys {
  706. envBlock.WriteString(k)
  707. envBlock.WriteString("=")
  708. envBlock.WriteString(rintegration.EscapeEnvValue(env[k]))
  709. envBlock.WriteString("\n")
  710. }
  711. return `#!/bin/sh
  712. set -e
  713. INIT="` + init + `"
  714. ENV_FILE="` + envFile + `"
  715. cat > "$ENV_FILE.new" <<'ENVEOF'
  716. ` + envBlock.String() + `ENVEOF
  717. chmod 600 "$ENV_FILE.new"
  718. mv -f "$ENV_FILE.new" "$ENV_FILE"
  719. if [ -x "$INIT" ]; then
  720. "$INIT" stop >/dev/null 2>&1 || true
  721. "$INIT" start >/dev/null 2>&1 || true
  722. fi
  723. `
  724. }
  725. func sshServiceScript(v rintegration.Vendor, action string) string {
  726. init := "/etc/init.d/" + v.Binary
  727. switch action {
  728. case "start":
  729. return "test -x " + init + " && " + init + " enable && " + init + " start || true"
  730. case "stop":
  731. return "test -x " + init + " && " + init + " stop || true"
  732. case "restart":
  733. return "test -x " + init + " && " + init + " restart || true"
  734. case "check":
  735. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  736. }
  737. return "true"
  738. }
  739. func sshUninstallScript(v rintegration.Vendor) string {
  740. init := "/etc/init.d/" + v.Binary
  741. bin := "/usr/sbin/" + v.Binary
  742. envFile := "/etc/" + v.Binary + ".env"
  743. return fmt.Sprintf(
  744. "test -x %s && %s stop || true; test -x %s && %s disable || true; rm -f %s %s %s",
  745. init, init, init, init, init, bin, envFile,
  746. )
  747. }