4
0

integrations.go 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  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. "context"
  9. "errors"
  10. "fmt"
  11. "log"
  12. "net/http"
  13. "path/filepath"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/gnacho/netpulse/server-go/internal/adapters"
  19. "github.com/gnacho/netpulse/server-go/internal/auth"
  20. "github.com/gnacho/netpulse/server-go/internal/rintegration"
  21. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  22. )
  23. // integrationItem es la vista HTTP de una integración (nunca la contraseña).
  24. type integrationItem struct {
  25. Slug string `json:"slug"`
  26. Vendor string `json:"vendor"`
  27. Mode string `json:"mode"`
  28. Host string `json:"host"`
  29. Username string `json:"username"`
  30. Version string `json:"version"`
  31. Arch string `json:"arch"`
  32. IntervalS int `json:"intervalS"`
  33. Enabled bool `json:"enabled"`
  34. State string `json:"state"`
  35. LastError string `json:"lastError"`
  36. // OfflineReason (#1718): código estable del motivo por el que la unidad
  37. // no está empujando (mismos códigos que la tarjeta y el detalle desde
  38. // #1714). Vacío si está empujando, pausada o sin señal clara.
  39. OfflineReason string `json:"offlineReason,omitempty"`
  40. // PollError (#2039): último fallo de poll del pusher, tal cual lo escribió
  41. // en su log. Es el dato que se pide en cada reporte y no llegaba a la UI,
  42. // así que el usuario solo veía una pista clasificada.
  43. PollError string `json:"pollError,omitempty"`
  44. LastStartMs int64 `json:"lastStartMs"`
  45. LastPushMs int64 `json:"lastPushMs"`
  46. Fresh bool `json:"fresh"`
  47. }
  48. // vendorView es la vista HTTP del manifiesto de un vendor.
  49. type vendorView struct {
  50. ID string `json:"id"`
  51. Mode string `json:"mode"`
  52. Arches []string `json:"arches"`
  53. TagPrefix string `json:"tagPrefix"`
  54. Description string `json:"description"`
  55. }
  56. // registerIntegrationRoutes registra las rutas /api/integrations/*. Todas
  57. // exigen rol admin salvo el GET de vendors (solo sesión).
  58. func (s *server) registerIntegrationRoutes(mux *http.ServeMux) {
  59. mux.HandleFunc("GET /api/integrations/vendors", s.handleIntegrationsVendors)
  60. mux.Handle("POST /api/integrations/vendors/refresh", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsVendorsRefresh)))
  61. mux.Handle("GET /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsList)))
  62. mux.Handle("POST /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsCreate)))
  63. mux.Handle("POST /api/integrations/{slug}/start", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStart)))
  64. mux.Handle("POST /api/integrations/{slug}/stop", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStop)))
  65. mux.Handle("POST /api/integrations/{slug}/check", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationCheck)))
  66. mux.Handle("POST /api/integrations/{slug}/update", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationUpdate)))
  67. mux.Handle("PUT /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationEdit)))
  68. mux.Handle("DELETE /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationDelete)))
  69. }
  70. // vendorCatalogRefreshTimeout acota el fetch forzado del endpoint admin.
  71. const vendorCatalogRefreshTimeout = 15 * time.Second
  72. func (s *server) handleIntegrationsVendors(w http.ResponseWriter, r *http.Request) {
  73. vs := s.vendorCatalog.Vendors(r.Context())
  74. writeJSON(w, http.StatusOK, map[string]any{
  75. "vendors": vendorViews(vs),
  76. "lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
  77. })
  78. }
  79. // handleIntegrationsVendorsRefresh fuerza el descubrimiento del catálogo
  80. // (#1697): fetch inmediato, caché actualizada y catálogo devuelto en la
  81. // misma respuesta para que la UI no encadene un segundo GET. Un fallo de
  82. // fetch o de validación deja el catálogo anterior en su sitio (502).
  83. func (s *server) handleIntegrationsVendorsRefresh(w http.ResponseWriter, r *http.Request) {
  84. if s.db == nil || s.vendorCatalog == nil {
  85. writeError(w, http.StatusServiceUnavailable, "unavailable", "vendor catalog is not available without a database")
  86. return
  87. }
  88. ctx, cancel := context.WithTimeout(r.Context(), vendorCatalogRefreshTimeout)
  89. defer cancel()
  90. if err := s.vendorCatalog.Refresh(ctx); err != nil {
  91. writeError(w, http.StatusBadGateway, "refresh_failed", err.Error())
  92. return
  93. }
  94. writeJSON(w, http.StatusOK, map[string]any{
  95. "vendors": vendorViews(s.vendorCatalog.Current()),
  96. "lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
  97. })
  98. }
  99. // vendorViews es la vista HTTP del catálogo: mismos campos que servía el
  100. // manifiesto estático para no romper el contrato con la UI.
  101. func vendorViews(vs []rintegration.Vendor) []vendorView {
  102. out := make([]vendorView, 0, len(vs))
  103. for _, v := range vs {
  104. out = append(out, vendorView{
  105. ID: v.ID, Mode: v.Mode, Arches: v.Arches,
  106. TagPrefix: v.TagPrefix, Description: v.Description,
  107. })
  108. }
  109. return out
  110. }
  111. func (s *server) integrationsStore() *rintegration.Store {
  112. return rintegration.NewStore(s.db.DB)
  113. }
  114. func (s *server) integrationFetcher() *rintegration.Fetcher {
  115. if s.integrations != nil {
  116. return s.integrations.Fetch()
  117. }
  118. return rintegration.NewFetcher()
  119. }
  120. func (s *server) getIntegrationRow(slug string) (rintegration.Row, bool) {
  121. if s.db == nil {
  122. return rintegration.Row{}, false
  123. }
  124. return s.integrationsStore().Get(slug)
  125. }
  126. // integrationLastPushMs lee agent.last_push_ts.<slug> (segundos unix) y lo
  127. // devuelve en milisegundos, 0 si nunca empujó.
  128. func (s *server) integrationLastPushMs(slug string) int64 {
  129. if s.db == nil {
  130. return 0
  131. }
  132. sec, err := strconv.ParseInt(kvGet(s.db.DB, "agent.last_push_ts."+slug), 10, 64)
  133. if err != nil {
  134. return 0
  135. }
  136. return sec * 1000
  137. }
  138. func (s *server) integrationItemOf(row rintegration.Row) integrationItem {
  139. lastPush := s.integrationLastPushMs(row.Slug)
  140. fresh := false
  141. if lastPush > 0 && row.IntervalS > 0 {
  142. fresh = time.Now().UnixMilli()-lastPush <= int64(row.IntervalS)*3*1000
  143. }
  144. // #1696: reconciliar al leer. Una fila en running cuyo último push es más
  145. // viejo que 3 intervalos no puede ir de sana: la vista la reporta como
  146. // "stale". Es solo vista (la fila no se toca): en cuanto el pusher vuelva
  147. // a empujar, el propio cálculo la devuelve a "running".
  148. state := row.State
  149. if state == "running" && lastPush > 0 && row.IntervalS > 0 && !fresh {
  150. state = "stale"
  151. }
  152. reason, pollErr := s.integrationOffline(row, fresh)
  153. return integrationItem{
  154. Slug: row.Slug, Vendor: row.Vendor, Mode: row.Mode, Host: row.Host,
  155. Username: row.Username, Version: row.Version, Arch: row.Arch,
  156. IntervalS: row.IntervalS, Enabled: row.Enabled, State: state,
  157. LastError: row.LastError, LastStartMs: row.LastStartMs,
  158. LastPushMs: lastPush, Fresh: fresh,
  159. OfflineReason: reason,
  160. PollError: pollErr,
  161. }
  162. }
  163. // integrationOffline (#1718) clasifica por qué una integración no está
  164. // empujando, con los mismos códigos y la misma precedencia que StatusReasons
  165. // en el paquete rintegration (que alimenta la tarjeta y el detalle): parada
  166. // explícita, último error de instalación, o el log del pusher para fallos de
  167. // poll. Pausada o fresca no tienen motivo.
  168. //
  169. // Devuelve además el último fallo de poll en crudo (#2039): la UI lo muestra
  170. // para que un reporte pueda traer el mensaje real en vez de solo la pista
  171. // clasificada.
  172. func (s *server) integrationOffline(row rintegration.Row, fresh bool) (code, pollErr string) {
  173. if !row.Enabled {
  174. return "", ""
  175. }
  176. if row.State == "stopped" {
  177. return rintegration.ReasonStopped, ""
  178. }
  179. if fresh {
  180. return "", ""
  181. }
  182. if s.integrations != nil {
  183. pollErr = s.integrations.LastPollError(row.Slug)
  184. }
  185. if row.State == "error" && row.LastError != "" {
  186. code = rintegration.ClassifyPollError(row.LastError)
  187. }
  188. if (code == "" || code == rintegration.ReasonError) && pollErr != "" {
  189. code = rintegration.ClassifyPollError(pollErr)
  190. }
  191. return code, pollErr
  192. }
  193. func (s *server) integrationList() []integrationItem {
  194. if s.db == nil {
  195. return []integrationItem{}
  196. }
  197. rows, err := s.integrationsStore().List()
  198. if err != nil {
  199. return []integrationItem{}
  200. }
  201. out := make([]integrationItem, 0, len(rows))
  202. for _, row := range rows {
  203. out = append(out, s.integrationItemOf(row))
  204. }
  205. return out
  206. }
  207. func (s *server) broadcastIntegrations() {
  208. if s.hub != nil {
  209. s.hub.Broadcast("integrations", map[string]any{"integrations": s.integrationList()})
  210. }
  211. }
  212. // watchIntegrations (#1696) registra el callback de salida inesperada de los
  213. // pushers locales (#1674) y reanuda al arrancar las integraciones habilitadas.
  214. // No-op sin supervisor o sin base de datos (demo). Los paros intencionales no
  215. // pasan por el callback: los gestiona el handler de stop.
  216. func (s *server) watchIntegrations() {
  217. if s.integrations == nil || s.db == nil {
  218. return
  219. }
  220. s.integrations.SetOnExit(func(slug string, exitErr error) {
  221. // Un pusher es un daemon de larga vida: también la salida limpia
  222. // (código 0) es inesperada y deja la fila en estado error con su
  223. // motivo, igual que un arranque fallido.
  224. reason := "pusher exited unexpectedly (exit code 0)"
  225. if exitErr != nil {
  226. reason = exitErr.Error()
  227. }
  228. _ = rintegration.NewStore(s.db.DB).SetState(slug, "error", reason)
  229. s.broadcastIntegrations()
  230. })
  231. s.resumeIntegrations()
  232. }
  233. // resumeIntegrations (#1696) reanuda al arrancar cada integración habilitada.
  234. // En modo local arranca el pusher con el binario ya instalado y el fichero de
  235. // entorno 0600 ya existente (el token y la contraseña solo viven ahí); en
  236. // modo ssh el pusher corre dentro del router y no hay nada que arrancar en el
  237. // servidor, pero el estado guardado deja de decir running (no verificado
  238. // hasta el próximo check/start). En modo node el pusher corre en el host
  239. // monitorizado: la fila vuelve a pending y el primer push la pone viva. Un
  240. // fallo se loga y deja la fila en estado error: nunca tira el arranque del
  241. // servidor.
  242. func (s *server) resumeIntegrations() {
  243. if s.integrations == nil || s.db == nil {
  244. return
  245. }
  246. store := s.integrationsStore()
  247. rows, err := store.List()
  248. if err != nil {
  249. log.Printf("[netpulse] warning: integrations: could not read table at startup (%v)", err)
  250. return
  251. }
  252. for _, row := range rows {
  253. if !row.Enabled {
  254. continue
  255. }
  256. if row.Mode == rintegration.ModeNode {
  257. // Nadie en el servidor instala ni arranca esto (#2272): lo
  258. // supervisa el operador en el host monitorizado.
  259. if row.State != "pending" {
  260. _ = store.SetState(row.Slug, "pending", "")
  261. }
  262. continue
  263. }
  264. if row.Mode != rintegration.ModeLocal {
  265. // El proceso vive en el router: sin verificar tras el reinicio
  266. // del servidor; check/start lo reconcilian.
  267. if row.State == "running" {
  268. _ = store.SetState(row.Slug, "unverified", "")
  269. }
  270. continue
  271. }
  272. if s.integrations.Running(row.Slug) {
  273. continue
  274. }
  275. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  276. if !ok {
  277. _ = store.SetState(row.Slug, "error", "unknown vendor "+row.Vendor)
  278. log.Printf("[netpulse] warning: integration %s has unknown vendor %q at startup", row.Slug, row.Vendor)
  279. continue
  280. }
  281. binPath := filepath.Join(s.integrations.Dir(), row.Slug, vendor.Binary)
  282. if err := s.integrations.Start(row.Slug, nil, binPath); err != nil {
  283. _ = store.SetState(row.Slug, "error", err.Error())
  284. log.Printf("[netpulse] warning: integration %s could not be resumed at startup (%v)", row.Slug, err)
  285. continue
  286. }
  287. _ = store.SetState(row.Slug, "running", "")
  288. _ = store.SetLastStart(row.Slug, time.Now().UnixMilli())
  289. log.Printf("[netpulse] integration %s resumed at startup", row.Slug)
  290. }
  291. s.broadcastIntegrations()
  292. }
  293. // unmanagedItem es un pusher externo que alimenta la flota sin fila en
  294. // router_integrations: se instaló a mano, antes de que la app supiera
  295. // instalarlos (#1743). Solo se describe; la app no puede arrancarlo, pararlo
  296. // ni rotarle el token.
  297. type unmanagedItem struct {
  298. Slug string `json:"slug"`
  299. Kind string `json:"kind"`
  300. Version string `json:"version,omitempty"`
  301. IntervalS int `json:"intervalS,omitempty"`
  302. LastPushMs int64 `json:"lastPushMs"`
  303. Fresh bool `json:"fresh"`
  304. }
  305. // unmanagedIntegrations lista los pushers externos vivos que la app no
  306. // gestiona (#1743). Sin esto la página de Integraciones sale vacía mientras
  307. // /api/agents muestra unidades alimentadas por ellos, y el operador no tiene
  308. // ni una pista de que el pusher existe.
  309. //
  310. // El kind solo vive en memoria (AgentRegistry), así que justo después de un
  311. // reinicio la lista queda vacía hasta el primer push de cada unidad (~30 s).
  312. func (s *server) unmanagedIntegrations() []unmanagedItem {
  313. out := []unmanagedItem{}
  314. if s.db == nil || s.agents == nil {
  315. return out
  316. }
  317. // Los slugs viven en kv como agent.token.<slug>. El cursor se cierra ANTES
  318. // de consultar la tienda de integraciones: con SetMaxOpenConns(1), un
  319. // QueryRow con las filas abiertas espera la única conexión y bloquea.
  320. slugs := []string{}
  321. rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
  322. if err != nil {
  323. return out
  324. }
  325. for rows.Next() {
  326. var key string
  327. if rows.Scan(&key) == nil {
  328. slugs = append(slugs, strings.TrimPrefix(key, agentTokenKeyPrefix))
  329. }
  330. }
  331. rows.Close()
  332. if err := rows.Err(); err != nil {
  333. return out
  334. }
  335. store := s.integrationsStore()
  336. for _, slug := range slugs {
  337. if slug == "" {
  338. continue
  339. }
  340. _, version, kind, interval, ok := s.agents.Info(slug)
  341. if !ok || kind != "external" {
  342. continue
  343. }
  344. if _, managed := store.Get(slug); managed {
  345. continue
  346. }
  347. lastPush := s.integrationLastPushMs(slug)
  348. fresh := lastPush > 0 && interval > 0 && time.Now().UnixMilli()-lastPush <= int64(interval)*3*1000
  349. out = append(out, unmanagedItem{
  350. Slug: slug,
  351. Kind: kind,
  352. Version: version,
  353. IntervalS: interval,
  354. LastPushMs: lastPush,
  355. Fresh: fresh,
  356. })
  357. }
  358. return out
  359. }
  360. func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
  361. writeJSON(w, http.StatusOK, map[string]any{
  362. "integrations": s.integrationList(),
  363. "unmanaged": s.unmanagedIntegrations(),
  364. })
  365. }
  366. type integrationCreateBody struct {
  367. Slug string `json:"slug"`
  368. Vendor string `json:"vendor"`
  369. Host string `json:"host"`
  370. Username string `json:"username"`
  371. Password string `json:"password"`
  372. IntervalS int `json:"intervalS"`
  373. Arch string `json:"arch"`
  374. }
  375. func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request) {
  376. // #2112: en modo ssh el instalador corre en el router antes de responder.
  377. setLongWriteDeadline(w, integrationWriteCeiling)
  378. if s.db == nil {
  379. writeError(w, http.StatusInternalServerError, "db_error")
  380. return
  381. }
  382. var body integrationCreateBody
  383. if st := readJSONBody(w, r, &body); st != 0 {
  384. writeBodyError(w, st, "invalid_body", `Se esperaba { "slug", "vendor", "host", "username", "password", "intervalS", "arch"? }`)
  385. return
  386. }
  387. if !agentSlugRe.MatchString(body.Slug) {
  388. writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
  389. return
  390. }
  391. vendor, ok := s.vendorCatalog.Lookup(body.Vendor)
  392. if !ok {
  393. writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
  394. return
  395. }
  396. if vendor.OperatorInstalled() {
  397. // #2272: en modo node el host es solo la etiqueta de la fila. La
  398. // conexión del pusher (token del apiserver, kubelet, rutas) la
  399. // configura el operador en el propio nodo, así que el alta no pide
  400. // usuario ni contraseña.
  401. if body.Host == "" {
  402. body.Host = body.Slug
  403. }
  404. } else if body.Host == "" || body.Username == "" || body.Password == "" {
  405. writeError(w, http.StatusBadRequest, "invalid_input", "host, username and password are required")
  406. return
  407. }
  408. if body.IntervalS < 10 || body.IntervalS > 86400 {
  409. writeError(w, http.StatusBadRequest, "invalid_interval", "intervalS must be between 10 and 86400")
  410. return
  411. }
  412. arch := body.Arch
  413. if arch == "" {
  414. arch = vendor.Arches[0]
  415. } else if !vendorSupportsArch(vendor, arch) {
  416. writeError(w, http.StatusBadRequest, "invalid_arch", "unsupported arch "+arch)
  417. return
  418. }
  419. store := s.integrationsStore()
  420. if _, exists := store.Get(body.Slug); exists {
  421. writeError(w, http.StatusConflict, "already_exists", "integration already exists")
  422. return
  423. }
  424. // El env que se va a escribir tiene que poder arrancar: con la URL en https
  425. // el pin dejó de ser opcional (#13 en netpulse-integrations), y derivarlo
  426. // exige que este server alcance su propia URL pública. Mejor un 502 aquí,
  427. // sin tocar nada, que un alta que muere al segundo siguiente.
  428. serverURL := s.agentBaseURL(r)
  429. if err := requirePusherPin(serverURL); err != nil {
  430. writeError(w, http.StatusBadGateway, "fingerprint_unreachable", err.Error())
  431. return
  432. }
  433. // Resolver el último release verificado. En modo local se extrae el
  434. // binario aquí (corre en este host); en modo ssh solo se verifica: el
  435. // router descarga el asset él mismo; en modo node no se descarga ni se
  436. // verifica nada, porque instala el operador (#2272) y la fila solo
  437. // conserva versión y nombre del asset para que la UI apunte a la descarga.
  438. fetch := s.integrationFetcher()
  439. res, err := fetch.ResolveLatest(vendor, arch)
  440. if err != nil {
  441. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  442. return
  443. }
  444. binPath := ""
  445. if vendor.ServerManaged() {
  446. if s.integrations == nil {
  447. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  448. return
  449. }
  450. installDir := filepath.Join(s.integrations.Dir(), body.Slug)
  451. binPath, err = fetch.Download(res, vendor.Binary, installDir)
  452. if err != nil {
  453. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  454. return
  455. }
  456. } else if vendor.Mode == rintegration.ModeSSH {
  457. if s.pool == nil {
  458. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  459. return
  460. }
  461. if err := fetch.Verify(res); err != nil {
  462. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  463. return
  464. }
  465. }
  466. now := time.Now().UnixMilli()
  467. row := rintegration.Row{
  468. Slug: body.Slug, Vendor: vendor.ID, Mode: vendor.Mode, Host: body.Host,
  469. Username: body.Username, Version: res.Version, Asset: res.AssetName,
  470. Arch: arch, IntervalS: body.IntervalS, Enabled: true, State: "pending",
  471. CreatedAt: now, UpdatedAt: now,
  472. }
  473. if err := store.Upsert(row); err != nil {
  474. writeError(w, http.StatusInternalServerError, "db_error")
  475. return
  476. }
  477. // #1708: en modo ssh la misma contraseña del formulario es la credencial
  478. // SSH del alta y de las acciones posteriores: se guarda en el fichero
  479. // compañero (0600) antes de conectar, nunca en la base de datos.
  480. if vendor.Mode == rintegration.ModeSSH && s.integrations != nil {
  481. if err := s.integrations.WriteSSHPassword(body.Slug, body.Password); err != nil {
  482. _ = store.Delete(body.Slug)
  483. writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
  484. return
  485. }
  486. }
  487. // Router external cuyo id es el slug (push autenticado por token de
  488. // agente, agent.token.<slug>).
  489. router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  490. Name: body.Slug, Host: body.Host, Type: "external", AgentOnly: true,
  491. })
  492. if err != nil || router.ID != body.Slug {
  493. _ = store.Delete(body.Slug)
  494. writeError(w, http.StatusInternalServerError, "router_error")
  495. return
  496. }
  497. s.syncRouters()
  498. rollback := func() {
  499. if vendor.ServerManaged() && s.integrations != nil {
  500. _ = s.integrations.Stop(body.Slug)
  501. _ = s.integrations.Cleanup(body.Slug)
  502. }
  503. if vendor.Mode == rintegration.ModeSSH && s.integrations != nil {
  504. _ = s.integrations.RemoveSSHPassword(body.Slug)
  505. }
  506. _ = routerstore.RemoveRouter(s.db.DB, body.Slug)
  507. s.syncRouters()
  508. _ = store.Delete(body.Slug)
  509. }
  510. // #2272: en modo node la rotación de token no arranca ni instala nada; el
  511. // env que el operador debe copiar en el nodo sale en la respuesta una sola
  512. // vez, como el token.
  513. var nodeEnv map[string]string
  514. token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
  515. if vendor.OperatorInstalled() {
  516. nodeEnv = s.operatorEnv(row, serverURL, tok)
  517. return nil
  518. }
  519. env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
  520. if vendor.ServerManaged() {
  521. return s.integrations.Start(body.Slug, env, binPath)
  522. }
  523. return s.runSSHInstall(vendor, row, env, res.URL, res.SHA256)
  524. })
  525. if err != nil {
  526. rollback()
  527. writeError(w, http.StatusBadGateway, sshErrorOr(err, "start_failed"), err.Error())
  528. return
  529. }
  530. if !vendor.OperatorInstalled() {
  531. _ = store.SetState(body.Slug, "running", "")
  532. _ = store.SetLastStart(body.Slug, time.Now().UnixMilli())
  533. }
  534. s.broadcastIntegrations()
  535. item, _ := s.getIntegrationRow(body.Slug)
  536. out := map[string]any{
  537. "integration": s.integrationItemOf(item),
  538. "token": token,
  539. }
  540. if nodeEnv != nil {
  541. out["env"] = nodeEnv
  542. }
  543. writeJSON(w, http.StatusCreated, out)
  544. }
  545. func vendorSupportsArch(v rintegration.Vendor, arch string) bool {
  546. for _, a := range v.Arches {
  547. if a == arch {
  548. return true
  549. }
  550. }
  551. return false
  552. }
  553. // operatorEnv builds the environment an operator has to set on a mode "node"
  554. // pusher (#2272): only the ingest side, because the vendor-specific knobs
  555. // (credentials, endpoints, file paths) live on the monitored host and the
  556. // server never learns them. Mirrors pusherEnv for the shared keys so a pusher
  557. // that speaks the standard contract needs no translation.
  558. func (s *server) operatorEnv(row rintegration.Row, serverURL, token string) map[string]string {
  559. env := map[string]string{
  560. "NETPULSE_SERVER": serverURL,
  561. "NETPULSE_TOKEN": token,
  562. "NETPULSE_SLUG": row.Slug,
  563. "NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
  564. }
  565. for k, v := range pusherPinEnv(serverURL) {
  566. env[k] = v
  567. }
  568. return env
  569. }
  570. // pusherEnv construye el entorno del pusher. En modo ssh el pusher corre en el
  571. // propio router, así que el host del dispositivo es la propia unidad
  572. // (127.0.0.1) en lugar del host SSH de la tabla.
  573. func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password, serverURL, token string) map[string]string {
  574. prefix := strings.ToUpper(v.ID) + "_"
  575. host := row.Host
  576. if v.Mode == rintegration.ModeSSH {
  577. host = "127.0.0.1"
  578. }
  579. env := map[string]string{
  580. prefix + "HOST": host,
  581. prefix + "USER": row.Username,
  582. prefix + "PASS": password,
  583. prefix + "INSECURE": "1",
  584. "NETPULSE_SERVER": serverURL,
  585. "NETPULSE_TOKEN": token,
  586. "NETPULSE_SLUG": row.Slug,
  587. "NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
  588. }
  589. for k, v := range pusherPinEnv(serverURL) {
  590. env[k] = v
  591. }
  592. return env
  593. }
  594. // healPusherPin merges the current server pin into a pusher environment,
  595. // healing files written before the pin requirement and refreshing the pin
  596. // after a certificate reissue. It is a no-op when the server URL needs no
  597. // pin (plain HTTP).
  598. func healPusherPin(env map[string]string, serverURL string) map[string]string {
  599. for k, v := range pusherPinEnv(serverURL) {
  600. env[k] = v
  601. }
  602. return env
  603. }
  604. func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
  605. _, err := s.runIntegrationSSH(row, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
  606. return err
  607. }
  608. // sshPasswordSetter es la capacidad opcional del pool SSH de conectar por
  609. // contraseña (#1708). adapters.SSHPool la implementa; los fakes de tests que
  610. // solo implementan Run no, y en ese caso el pool queda como esté.
  611. type sshPasswordSetter interface {
  612. SetPassword(host, user, password string)
  613. }
  614. // applyIntegrationSSHAuth aplica al pool la credencial SSH de la
  615. // integración (#1708): si existe el fichero compañero <slug>.sshpass la
  616. // conexión va por contraseña con el usuario de la fila (gana sobre la llave
  617. // del servidor); si no, la credencial se limpia y el dial usa la llave como
  618. // siempre. Un fichero ilegible cae a llave con aviso en el log.
  619. func (s *server) applyIntegrationSSHAuth(row rintegration.Row) {
  620. if s.pool == nil || s.integrations == nil {
  621. return
  622. }
  623. setter, ok := s.pool.(sshPasswordSetter)
  624. if !ok {
  625. return
  626. }
  627. pass, err := s.integrations.ReadSSHPassword(row.Slug)
  628. if err != nil {
  629. log.Printf("[netpulse] warning: integration %s: could not read SSH password file (%v), connecting with key", row.Slug, err)
  630. pass = ""
  631. }
  632. setter.SetPassword(row.Host, row.Username, pass)
  633. }
  634. // runIntegrationSSH ejecuta un comando en el router de la integración
  635. // aplicando antes la credencial SSH del fichero compañero (#1708).
  636. func (s *server) runIntegrationSSH(row rintegration.Row, cmd string, timeout time.Duration) (string, error) {
  637. s.applyIntegrationSSHAuth(row)
  638. return s.pool.Run(row.Host, cmd, timeout)
  639. }
  640. // sshErrorCode clasifica un error SSH para la API (#1708): el rechazo de
  641. // autenticación es su propio código (ssh_auth_failed) frente al fallo
  642. // genérico de conexión (ssh_failed), de modo que la UI puede pedir revisar
  643. // la contraseña.
  644. func sshErrorCode(err error) string {
  645. var ae *adapters.SSHAuthError
  646. if errors.As(err, &ae) {
  647. return "ssh_auth_failed"
  648. }
  649. return "ssh_failed"
  650. }
  651. // sshErrorOr devuelve ssh_auth_failed cuando err es un rechazo de
  652. // autenticación SSH y fallback para cualquier otro error.
  653. func sshErrorOr(err error, fallback string) string {
  654. if sshErrorCode(err) == "ssh_auth_failed" {
  655. return "ssh_auth_failed"
  656. }
  657. return fallback
  658. }
  659. func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
  660. slug := r.PathValue("slug")
  661. row, ok := s.getIntegrationRow(slug)
  662. if !ok {
  663. writeError(w, http.StatusNotFound, "not_found")
  664. return
  665. }
  666. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  667. if !ok {
  668. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  669. return
  670. }
  671. if vendor.OperatorInstalled() {
  672. // #2272: no hay proceso en el servidor que arrancar. Lo supervisa el
  673. // operador en el host monitorizado.
  674. writeError(w, http.StatusConflict, "not_managed", "this pusher runs on the monitored host: start it there")
  675. return
  676. }
  677. store := s.integrationsStore()
  678. if vendor.ServerManaged() {
  679. if s.integrations == nil {
  680. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  681. return
  682. }
  683. if !s.integrations.Running(slug) {
  684. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  685. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  686. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  687. return
  688. }
  689. }
  690. } else {
  691. if s.pool == nil {
  692. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  693. return
  694. }
  695. if _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
  696. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  697. return
  698. }
  699. }
  700. _ = store.SetState(slug, "running", "")
  701. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  702. s.broadcastIntegrations()
  703. item, _ := s.getIntegrationRow(slug)
  704. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  705. }
  706. func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
  707. slug := r.PathValue("slug")
  708. row, ok := s.getIntegrationRow(slug)
  709. if !ok {
  710. writeError(w, http.StatusNotFound, "not_found")
  711. return
  712. }
  713. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  714. if !ok {
  715. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  716. return
  717. }
  718. if vendor.OperatorInstalled() {
  719. // #2272: nada que parar desde el servidor.
  720. writeError(w, http.StatusConflict, "not_managed", "this pusher runs on the monitored host: stop it there")
  721. return
  722. }
  723. if vendor.ServerManaged() {
  724. if s.integrations != nil {
  725. _ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
  726. }
  727. } else if s.pool != nil {
  728. _, _ = s.runIntegrationSSH(row, sshServiceScript(vendor, "stop"), 60*time.Second)
  729. }
  730. _ = s.integrationsStore().SetState(slug, "stopped", "")
  731. s.broadcastIntegrations()
  732. item, _ := s.getIntegrationRow(slug)
  733. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  734. }
  735. func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request) {
  736. slug := r.PathValue("slug")
  737. row, ok := s.getIntegrationRow(slug)
  738. if !ok {
  739. writeError(w, http.StatusNotFound, "not_found")
  740. return
  741. }
  742. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  743. if !ok {
  744. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  745. return
  746. }
  747. if vendor.OperatorInstalled() {
  748. // #2272: no hay proceso en el servidor que comprobar. La vida la dice
  749. // el push (frescura y motivo de offline de la fila), así que el check
  750. // no toca el estado guardado y lo declara por lo que es: no gestionado.
  751. writeJSON(w, http.StatusOK, map[string]any{
  752. "integration": s.integrationItemOf(row),
  753. "running": false,
  754. "managed": false,
  755. })
  756. return
  757. }
  758. running := false
  759. if vendor.ServerManaged() {
  760. running = s.integrations != nil && s.integrations.Running(slug)
  761. } else if s.pool != nil {
  762. _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "check"), 30*time.Second)
  763. running = err == nil
  764. }
  765. // #1696: un check verificado reconcilia el estado guardado: el unverified
  766. // que deja un reinicio del servidor (o una fila desfasada) vuelve a
  767. // running cuando el proceso está demostradamente vivo.
  768. if running && row.State != "running" {
  769. _ = s.integrationsStore().SetState(slug, "running", "")
  770. s.broadcastIntegrations()
  771. if fresh, ok := s.getIntegrationRow(slug); ok {
  772. row = fresh
  773. }
  774. }
  775. writeJSON(w, http.StatusOK, map[string]any{
  776. "integration": s.integrationItemOf(row),
  777. "running": running,
  778. "managed": true,
  779. })
  780. }
  781. func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request) {
  782. // #2112: en modo ssh reinstala el pusher en el router antes de responder.
  783. setLongWriteDeadline(w, integrationWriteCeiling)
  784. slug := r.PathValue("slug")
  785. row, ok := s.getIntegrationRow(slug)
  786. if !ok {
  787. writeError(w, http.StatusNotFound, "not_found")
  788. return
  789. }
  790. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  791. if !ok {
  792. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  793. return
  794. }
  795. fetch := s.integrationFetcher()
  796. res, err := fetch.ResolveLatest(vendor, row.Arch)
  797. if err != nil {
  798. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  799. return
  800. }
  801. store := s.integrationsStore()
  802. if vendor.OperatorInstalled() {
  803. // #2272: el servidor no instala ni reinicia nada en el nodo. Lo único
  804. // que puede hacer es refrescar la versión publicada para que la UI
  805. // ofrezca la descarga; el operador decide cuándo subirla.
  806. _ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
  807. s.broadcastIntegrations()
  808. item, _ := s.getIntegrationRow(slug)
  809. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  810. return
  811. }
  812. if vendor.ServerManaged() {
  813. if s.integrations == nil {
  814. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  815. return
  816. }
  817. _ = s.integrations.Stop(slug)
  818. installDir := filepath.Join(s.integrations.Dir(), slug)
  819. if _, err := fetch.Download(res, vendor.Binary, installDir); err != nil {
  820. _ = store.SetState(slug, "error", err.Error())
  821. s.broadcastIntegrations()
  822. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  823. return
  824. }
  825. // Heal environments created before the pin requirement: the
  826. // refreshed binary refuses to start without it. Best effort, on
  827. // error the old file is reused and the start below reports it.
  828. if env, err := s.integrations.Env(slug); err == nil {
  829. _ = s.integrations.WriteEnv(slug, healPusherPin(env, s.agentBaseURL(r)))
  830. }
  831. if err := s.integrations.Start(slug, nil, filepath.Join(installDir, vendor.Binary)); err != nil {
  832. _ = store.SetState(slug, "error", err.Error())
  833. s.broadcastIntegrations()
  834. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  835. return
  836. }
  837. } else {
  838. if s.pool == nil {
  839. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  840. return
  841. }
  842. if err := fetch.Verify(res); err != nil {
  843. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  844. return
  845. }
  846. env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
  847. if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
  848. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  849. return
  850. }
  851. }
  852. _ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
  853. _ = store.SetState(slug, "running", "")
  854. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  855. s.broadcastIntegrations()
  856. item, _ := s.getIntegrationRow(slug)
  857. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  858. }
  859. // handleIntegrationEdit actualiza los ajustes mutables de una integración sin
  860. // recrearla: host, usuario, contraseña e intervalo. El fichero de entorno se
  861. // lee, se cambian solo las claves afectadas y se reescribe, de modo que el
  862. // token y la contraseña omitida se conservan (nunca viven en la base de datos).
  863. func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
  864. slug := r.PathValue("slug")
  865. row, ok := s.getIntegrationRow(slug)
  866. if !ok {
  867. writeError(w, http.StatusNotFound, "not_found")
  868. return
  869. }
  870. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  871. if !ok {
  872. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  873. return
  874. }
  875. var body struct {
  876. Host *string `json:"host"`
  877. Username *string `json:"username"`
  878. Password *string `json:"password"`
  879. IntervalS *int `json:"intervalS"`
  880. }
  881. if st := readJSONBody(w, r, &body); st != 0 {
  882. writeBodyError(w, st, "invalid_body", "")
  883. return
  884. }
  885. changed := false
  886. if body.Host != nil {
  887. h := strings.TrimSpace(*body.Host)
  888. if h == "" {
  889. writeError(w, http.StatusBadRequest, "invalid_input", "host cannot be empty")
  890. return
  891. }
  892. row.Host = h
  893. changed = true
  894. }
  895. if body.Username != nil {
  896. if vendor.OperatorInstalled() {
  897. writeError(w, http.StatusBadRequest, "invalid_input", "username is set on the monitored host, not here")
  898. return
  899. }
  900. u := strings.TrimSpace(*body.Username)
  901. if u == "" {
  902. writeError(w, http.StatusBadRequest, "invalid_input", "username cannot be empty")
  903. return
  904. }
  905. row.Username = u
  906. changed = true
  907. }
  908. if body.IntervalS != nil {
  909. if *body.IntervalS < 10 || *body.IntervalS > 86400 {
  910. writeError(w, http.StatusBadRequest, "invalid_interval")
  911. return
  912. }
  913. row.IntervalS = *body.IntervalS
  914. changed = true
  915. }
  916. password := ""
  917. if body.Password != nil {
  918. if vendor.OperatorInstalled() {
  919. writeError(w, http.StatusBadRequest, "invalid_input", "credentials are set on the monitored host, not here")
  920. return
  921. }
  922. password = *body.Password
  923. changed = true
  924. }
  925. if !changed {
  926. writeError(w, http.StatusBadRequest, "invalid_input", "nothing to update")
  927. return
  928. }
  929. store := s.integrationsStore()
  930. if vendor.OperatorInstalled() {
  931. // #2272: no hay fichero de entorno en el servidor que reescribir ni
  932. // proceso que reiniciar. Host es la etiqueta de la fila e intervalo lo
  933. // aplica el operador en el nodo; la fila solo guarda ambos.
  934. if err := store.Upsert(row); err != nil {
  935. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  936. return
  937. }
  938. s.broadcastIntegrations()
  939. item, _ := s.getIntegrationRow(slug)
  940. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  941. return
  942. }
  943. prefix := strings.ToUpper(vendor.ID) + "_"
  944. host := row.Host
  945. if vendor.Mode == rintegration.ModeSSH {
  946. host = "127.0.0.1"
  947. }
  948. if vendor.ServerManaged() {
  949. if s.integrations == nil {
  950. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  951. return
  952. }
  953. env, err := s.integrations.Env(slug)
  954. if err != nil {
  955. _ = store.SetState(slug, "error", err.Error())
  956. s.broadcastIntegrations()
  957. writeError(w, http.StatusConflict, "env_unavailable", err.Error())
  958. return
  959. }
  960. env[prefix+"HOST"] = host
  961. env[prefix+"USER"] = row.Username
  962. if password != "" {
  963. env[prefix+"PASS"] = password
  964. }
  965. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  966. healPusherPin(env, s.agentBaseURL(r))
  967. if err := s.integrations.WriteEnv(slug, env); err != nil {
  968. _ = store.SetState(slug, "error", err.Error())
  969. s.broadcastIntegrations()
  970. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  971. return
  972. }
  973. _ = s.integrations.Stop(slug)
  974. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  975. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  976. _ = store.SetState(slug, "error", err.Error())
  977. s.broadcastIntegrations()
  978. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  979. return
  980. }
  981. } else {
  982. if s.pool == nil {
  983. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  984. return
  985. }
  986. // #1708: la contraseña nueva del formulario es también la credencial
  987. // SSH: guardarla en el fichero compañero ANTES de conectar, porque si
  988. // el usuario ya cambió la contraseña en el router, la conexión de
  989. // este mismo guardado necesita la nueva.
  990. if password != "" && s.integrations != nil {
  991. if err := s.integrations.WriteSSHPassword(slug, password); err != nil {
  992. writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
  993. return
  994. }
  995. }
  996. raw, err := s.runIntegrationSSH(row, sshEnvReadScript(vendor), 30*time.Second)
  997. if err != nil {
  998. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  999. return
  1000. }
  1001. env := rintegration.ParseEnv(raw)
  1002. env[prefix+"HOST"] = host
  1003. env[prefix+"USER"] = row.Username
  1004. if password != "" {
  1005. env[prefix+"PASS"] = password
  1006. }
  1007. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  1008. healPusherPin(env, s.agentBaseURL(r))
  1009. if _, err := s.runIntegrationSSH(row, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
  1010. _ = store.SetState(slug, "error", err.Error())
  1011. s.broadcastIntegrations()
  1012. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  1013. return
  1014. }
  1015. }
  1016. if err := store.Upsert(row); err != nil {
  1017. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  1018. return
  1019. }
  1020. _ = store.SetState(slug, "running", "")
  1021. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  1022. s.broadcastIntegrations()
  1023. item, _ := s.getIntegrationRow(slug)
  1024. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  1025. }
  1026. func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request) {
  1027. slug := r.PathValue("slug")
  1028. row, ok := s.getIntegrationRow(slug)
  1029. if !ok {
  1030. writeError(w, http.StatusNotFound, "not_found")
  1031. return
  1032. }
  1033. vendor, _ := s.vendorCatalog.Lookup(row.Vendor)
  1034. if vendor.ServerManaged() {
  1035. if s.integrations != nil {
  1036. _ = s.integrations.Stop(slug)
  1037. _ = s.integrations.Cleanup(slug)
  1038. }
  1039. } else if vendor.Mode == rintegration.ModeSSH && s.pool != nil {
  1040. _, _ = s.runIntegrationSSH(row, sshUninstallScript(vendor), 60*time.Second)
  1041. }
  1042. // #1708: la contraseña SSH del fichero compañero muere con la
  1043. // integración y el pool pierde la credencial (la conexión cacheada se
  1044. // tira y el siguiente dial vuelve a la llave).
  1045. if s.integrations != nil {
  1046. _ = s.integrations.RemoveSSHPassword(slug)
  1047. }
  1048. if setter, ok := s.pool.(sshPasswordSetter); ok {
  1049. setter.SetPassword(row.Host, "", "")
  1050. }
  1051. _ = s.integrationsStore().Delete(slug)
  1052. _ = routerstore.RemoveRouter(s.db.DB, slug)
  1053. s.syncRouters()
  1054. if s.db != nil {
  1055. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
  1056. }
  1057. s.broadcastIntegrations()
  1058. w.WriteHeader(http.StatusNoContent)
  1059. }
  1060. // ---------------------------------------------------------------------------
  1061. // Scripts POSIX de instalación/gestión por SSH (modo ssh, p. ej. asuswrt)
  1062. // ---------------------------------------------------------------------------
  1063. // envFileBody renders the sorted KEY=value body of an env file, with values
  1064. // escaped by EscapeEnvValue for a lossless round-trip through ParseEnv.
  1065. func envFileBody(env map[string]string) string {
  1066. keys := make([]string, 0, len(env))
  1067. for k := range env {
  1068. keys = append(keys, k)
  1069. }
  1070. sort.Strings(keys)
  1071. var b strings.Builder
  1072. for _, k := range keys {
  1073. b.WriteString(k)
  1074. b.WriteString("=")
  1075. b.WriteString(rintegration.EscapeEnvValue(env[k]))
  1076. b.WriteString("\n")
  1077. }
  1078. return b.String()
  1079. }
  1080. // sshInstallScript genera el instalador on-router de un vendor en modo ssh.
  1081. // Ramifica por el sistema de init del vendor (#1681): procd (layout OpenWrt,
  1082. // salida intacta) o merlin (/jffs + bloque gestionado en services-start).
  1083. func sshInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  1084. if v.InitSystem() == "merlin" {
  1085. return sshMerlinInstallScript(v, env, assetURL, sha256)
  1086. }
  1087. return sshProcdInstallScript(v, env, assetURL, sha256)
  1088. }
  1089. // sshProcdInstallScript instala el pusher en un vendor OpenWrt: binario en
  1090. // /usr/sbin, init procd en /etc/init.d y env en /etc.
  1091. func sshProcdInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  1092. bin := "/usr/sbin/" + v.Binary
  1093. init := "/etc/init.d/" + v.Binary
  1094. envFile := "/etc/" + v.Binary + ".env"
  1095. envBlock := envFileBody(env)
  1096. return `#!/bin/sh
  1097. set -e
  1098. BIN="` + bin + `"
  1099. INIT="` + init + `"
  1100. ENV_FILE="` + envFile + `"
  1101. SERVER="` + env["NETPULSE_SERVER"] + `"
  1102. ASSET_URL="` + assetURL + `"
  1103. SHA256="` + sha256 + `"
  1104. # Preflight: el router debe alcanzar el server.
  1105. if command -v curl >/dev/null 2>&1; then
  1106. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1107. else
  1108. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1109. fi
  1110. # Parar el servicio previo (el proceso vivo mantiene el binario abierto).
  1111. [ -x "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
  1112. # Descargar el asset desde la URL ya verificada en el server.
  1113. if command -v curl >/dev/null 2>&1; then
  1114. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1115. else
  1116. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1117. fi
  1118. # Verificar sha256 antes de instalar.
  1119. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  1120. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  1121. # Extraer y mover de forma atómica (.new -> rename).
  1122. mkdir -p /tmp/` + v.Binary + `.extract
  1123. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  1124. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  1125. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  1126. cp "$SRC" "$BIN.new"
  1127. chmod 0755 "$BIN.new"
  1128. mv -f "$BIN.new" "$BIN"
  1129. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  1130. # Env (chmod 600): solo se escribe en el alta; los updates preservan el
  1131. # fichero existente (la contraseña y el token solo viven ahí).
  1132. if [ ! -f "$ENV_FILE" ]; then
  1133. cat > "$ENV_FILE" <<'ENVEOF'
  1134. ` + envBlock + `ENVEOF
  1135. chmod 600 "$ENV_FILE"
  1136. fi
  1137. # Init procd.
  1138. cat > "$INIT" <<'INITEOF'
  1139. #!/bin/sh /etc/rc.common
  1140. START=99
  1141. STOP=10
  1142. USE_PROCD=1
  1143. BIN="/usr/sbin/` + v.Binary + `"
  1144. ENV_FILE="/etc/` + v.Binary + `.env"
  1145. start_service() {
  1146. [ -x "$BIN" ] || return 1
  1147. [ -r "$ENV_FILE" ] || { echo "netpulse: missing or unreadable env file $ENV_FILE" >&2; return 1; }
  1148. # Cargar el fichero de entorno y pasarlo entero al proceso en UNA sola
  1149. # llamada env (#1709): cada llamada adicional pisaria a la anterior y al
  1150. # proceso solo le llegaria la ultima variable (OpenWrt 21.02, #1701).
  1151. # Los valores van escapados (salto de linea = \n): printf %b los
  1152. # desescapa igual que ParseEnv en el server y que el control script de
  1153. # Merlin (#1705), sin pasar por . "$ENV_FILE" ni /etc/profile.
  1154. set --
  1155. while IFS= read -r line || [ -n "$line" ]; do
  1156. case "$line" in ""|\#*) continue ;; esac
  1157. k=${line%%=*}
  1158. val=${line#*=}
  1159. val=$(printf '%b' "$val")
  1160. set -- "$@" "$k=$val"
  1161. done < "$ENV_FILE"
  1162. procd_open_instance ` + v.Binary + `
  1163. procd_set_param env "$@"
  1164. procd_set_param command "$BIN"
  1165. procd_set_param respawn 3600 5 5
  1166. procd_set_param stdout 1
  1167. procd_set_param stderr 1
  1168. # Vigila el fichero: un cambio sigue reiniciando el servicio y el
  1169. # arranque vuelve a leer el env, asi que el proceso recoge los valores
  1170. # nuevos.
  1171. procd_set_param file "$ENV_FILE"
  1172. procd_close_instance
  1173. }
  1174. INITEOF
  1175. chmod 0755 "$INIT"
  1176. "$INIT" enable
  1177. "$INIT" restart
  1178. `
  1179. }
  1180. // sshMerlinInstallScript instala el pusher en un vendor Asuswrt-Merlin
  1181. // (#1681): sin procd, todo bajo /jffs/netpulse (binario, env, script de
  1182. // control con pidfile y log) y un bloque gestionado en
  1183. // /jffs/scripts/services-start para el arranque al boot. Re-ejecutarlo es
  1184. // idempotente: el env solo se escribe si falta y el bloque solo se añade una
  1185. // vez; el resto del hook no se toca.
  1186. func sshMerlinInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  1187. dir := "/jffs/netpulse"
  1188. bin := dir + "/" + v.Binary
  1189. ctrl := bin + ".sh"
  1190. envFile := bin + ".env"
  1191. pidFile := bin + ".pid"
  1192. logFile := bin + ".log"
  1193. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1194. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1195. return `#!/bin/sh
  1196. set -e
  1197. BIN="` + bin + `"
  1198. CTRL="` + ctrl + `"
  1199. ENV_FILE="` + envFile + `"
  1200. PID_FILE="` + pidFile + `"
  1201. LOG_FILE="` + logFile + `"
  1202. HOOK="/jffs/scripts/services-start"
  1203. SERVER="` + env["NETPULSE_SERVER"] + `"
  1204. ASSET_URL="` + assetURL + `"
  1205. SHA256="` + sha256 + `"
  1206. # Preflight: el router debe alcanzar el server.
  1207. if command -v curl >/dev/null 2>&1; then
  1208. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1209. else
  1210. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1211. fi
  1212. # Parar el pusher previo (el proceso vivo mantiene el binario abierto).
  1213. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1214. # Descargar el asset desde la URL ya verificada en el server.
  1215. if command -v curl >/dev/null 2>&1; then
  1216. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1217. else
  1218. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1219. fi
  1220. # Verificar sha256 antes de instalar.
  1221. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  1222. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  1223. # Extraer y mover de forma atómica (.new -> rename).
  1224. mkdir -p /tmp/` + v.Binary + `.extract
  1225. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  1226. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  1227. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  1228. mkdir -p "$DIR"
  1229. cp "$SRC" "$BIN.new"
  1230. chmod 0755 "$BIN.new"
  1231. mv -f "$BIN.new" "$BIN"
  1232. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  1233. # Env (chmod 600): solo se escribe si aún no existe; los updates preservan
  1234. # el fichero (la contraseña y el token solo viven ahí).
  1235. if [ ! -f "$ENV_FILE" ]; then
  1236. cat > "$ENV_FILE" <<'ENVEOF'
  1237. ` + envFileBody(env) + `ENVEOF
  1238. chmod 600 "$ENV_FILE"
  1239. fi
  1240. # Script de control con pidfile (start|stop|restart|check). El env guarda
  1241. # los valores escapados (salto de línea = \n): printf %b los desescapa igual
  1242. # que ParseEnv en el server antes de exportarlos al pusher.
  1243. cat > "$CTRL" <<'CTRLEOF'
  1244. #!/bin/sh
  1245. # NetPulse pusher control script (Asuswrt-Merlin).
  1246. BIN="` + bin + `"
  1247. PID_FILE="` + pidFile + `"
  1248. ENV_FILE="` + envFile + `"
  1249. LOG_FILE="` + logFile + `"
  1250. running() {
  1251. [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
  1252. }
  1253. case "$1" in
  1254. start)
  1255. [ -x "$BIN" ] || { echo "netpulse: missing $BIN"; exit 1; }
  1256. if running; then
  1257. exit 0
  1258. fi
  1259. rm -f "$PID_FILE"
  1260. [ -f "$ENV_FILE" ] || { echo "netpulse: missing $ENV_FILE"; exit 1; }
  1261. while IFS= read -r line || [ -n "$line" ]; do
  1262. case "$line" in ""|\#*) continue ;; esac
  1263. k=${line%%=*}
  1264. val=${line#*=}
  1265. val=$(printf '%b' "$val")
  1266. export "$k=$val"
  1267. done < "$ENV_FILE"
  1268. nohup "$BIN" >> "$LOG_FILE" 2>&1 &
  1269. echo $! > "$PID_FILE"
  1270. ;;
  1271. stop)
  1272. if [ -f "$PID_FILE" ]; then
  1273. RUN_PID=$(cat "$PID_FILE")
  1274. kill "$RUN_PID" 2>/dev/null || true
  1275. n=0
  1276. while kill -0 "$RUN_PID" 2>/dev/null && [ "$n" -lt 10 ]; do
  1277. sleep 1
  1278. n=$((n+1))
  1279. done
  1280. if kill -0 "$RUN_PID" 2>/dev/null; then
  1281. kill -9 "$RUN_PID" 2>/dev/null || true
  1282. fi
  1283. rm -f "$PID_FILE"
  1284. fi
  1285. ;;
  1286. restart)
  1287. "$0" stop
  1288. "$0" start
  1289. ;;
  1290. check)
  1291. if running; then
  1292. exit 0
  1293. fi
  1294. exit 1
  1295. ;;
  1296. *)
  1297. echo "usage: $0 {start|stop|restart|check}"
  1298. exit 2
  1299. ;;
  1300. esac
  1301. CTRLEOF
  1302. chmod 0755 "$CTRL"
  1303. # Arranque al boot: bloque gestionado en services-start, delimitado por
  1304. # marcadores únicos para poder quitarlo sin tocar el resto del fichero.
  1305. mkdir -p /jffs/scripts
  1306. if [ ! -f "$HOOK" ]; then
  1307. printf '#!/bin/sh\n' > "$HOOK"
  1308. fi
  1309. chmod 0755 "$HOOK"
  1310. if ! grep -qF '` + blockStart + `' "$HOOK" 2>/dev/null; then
  1311. cat >> "$HOOK" <<'BLOKEOF'
  1312. ` + blockStart + `
  1313. ` + ctrl + ` start
  1314. ` + blockEnd + `
  1315. BLOKEOF
  1316. fi
  1317. "$CTRL" start
  1318. `
  1319. }
  1320. // sshEnvReadScript prints the environment file of an integration running
  1321. // inside the router, so the server can merge changes without ever storing the
  1322. // token or the password. Merlin vendors keep the env under /jffs/netpulse.
  1323. func sshEnvReadScript(v rintegration.Vendor) string {
  1324. if v.InitSystem() == "merlin" {
  1325. return "cat /jffs/netpulse/" + v.Binary + ".env"
  1326. }
  1327. return "cat /etc/" + v.Binary + ".env"
  1328. }
  1329. // sshEnvWriteScript replaces the environment file inside the router and
  1330. // restarts the service. Values come already escaped by EscapeEnvValue and the
  1331. // heredoc is quoted, so the shell does not expand anything.
  1332. func sshEnvWriteScript(v rintegration.Vendor, env map[string]string) string {
  1333. envBlock := envFileBody(env)
  1334. if v.InitSystem() == "merlin" {
  1335. envFile := "/jffs/netpulse/" + v.Binary + ".env"
  1336. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1337. return `#!/bin/sh
  1338. set -e
  1339. ENV_FILE="` + envFile + `"
  1340. CTRL="` + ctrl + `"
  1341. cat > "$ENV_FILE.new" <<'ENVEOF'
  1342. ` + envBlock + `ENVEOF
  1343. chmod 600 "$ENV_FILE.new"
  1344. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1345. if [ -x "$CTRL" ]; then
  1346. "$CTRL" restart >/dev/null 2>&1 || true
  1347. fi
  1348. `
  1349. }
  1350. init := "/etc/init.d/" + v.Binary
  1351. envFile := "/etc/" + v.Binary + ".env"
  1352. return `#!/bin/sh
  1353. set -e
  1354. INIT="` + init + `"
  1355. ENV_FILE="` + envFile + `"
  1356. cat > "$ENV_FILE.new" <<'ENVEOF'
  1357. ` + envBlock + `ENVEOF
  1358. chmod 600 "$ENV_FILE.new"
  1359. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1360. if [ -x "$INIT" ]; then
  1361. "$INIT" stop >/dev/null 2>&1 || true
  1362. "$INIT" start >/dev/null 2>&1 || true
  1363. fi
  1364. `
  1365. }
  1366. func sshServiceScript(v rintegration.Vendor, action string) string {
  1367. if v.InitSystem() == "merlin" {
  1368. // Merlin no tiene procd: las acciones van al script de control
  1369. // con pidfile. check sigue siendo pgrep para no cambiar el camino
  1370. // de salud del handler.
  1371. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1372. switch action {
  1373. case "start":
  1374. return "test -x " + ctrl + " && " + ctrl + " start || true"
  1375. case "stop":
  1376. return "test -x " + ctrl + " && " + ctrl + " stop || true"
  1377. case "restart":
  1378. return "test -x " + ctrl + " && " + ctrl + " restart || true"
  1379. case "check":
  1380. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1381. }
  1382. return "true"
  1383. }
  1384. init := "/etc/init.d/" + v.Binary
  1385. switch action {
  1386. case "start":
  1387. return "test -x " + init + " && " + init + " enable && " + init + " start || true"
  1388. case "stop":
  1389. return "test -x " + init + " && " + init + " stop || true"
  1390. case "restart":
  1391. return "test -x " + init + " && " + init + " restart || true"
  1392. case "check":
  1393. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1394. }
  1395. return "true"
  1396. }
  1397. func sshUninstallScript(v rintegration.Vendor) string {
  1398. if v.InitSystem() == "merlin" {
  1399. return sshMerlinUninstallScript(v)
  1400. }
  1401. init := "/etc/init.d/" + v.Binary
  1402. bin := "/usr/sbin/" + v.Binary
  1403. envFile := "/etc/" + v.Binary + ".env"
  1404. return fmt.Sprintf(
  1405. "test -x %s && %s stop || true; test -x %s && %s disable || true; rm -f %s %s %s",
  1406. init, init, init, init, init, bin, envFile,
  1407. )
  1408. }
  1409. // sshMerlinUninstallScript para el pusher con su script de control, quita el
  1410. // bloque gestionado de services-start (el resto del hook queda intacto) y
  1411. // borra /jffs/netpulse entero.
  1412. func sshMerlinUninstallScript(v rintegration.Vendor) string {
  1413. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1414. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1415. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1416. return `CTRL="` + ctrl + `"
  1417. HOOK="/jffs/scripts/services-start"
  1418. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1419. if [ -f "$HOOK" ]; then
  1420. sed -i '/` + blockStart + `/,/` + blockEnd + `/d' "$HOOK" 2>/dev/null || true
  1421. fi
  1422. rm -rf /jffs/netpulse
  1423. `
  1424. }