integrations.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  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). Un fallo se loga y deja la fila en estado
  239. // error: nunca tira el arranque del servidor.
  240. func (s *server) resumeIntegrations() {
  241. if s.integrations == nil || s.db == nil {
  242. return
  243. }
  244. store := s.integrationsStore()
  245. rows, err := store.List()
  246. if err != nil {
  247. log.Printf("[netpulse] warning: integrations: could not read table at startup (%v)", err)
  248. return
  249. }
  250. for _, row := range rows {
  251. if !row.Enabled {
  252. continue
  253. }
  254. if row.Mode != "local" {
  255. // El proceso vive en el router: sin verificar tras el reinicio
  256. // del servidor; check/start lo reconcilian.
  257. if row.State == "running" {
  258. _ = store.SetState(row.Slug, "unverified", "")
  259. }
  260. continue
  261. }
  262. if s.integrations.Running(row.Slug) {
  263. continue
  264. }
  265. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  266. if !ok {
  267. _ = store.SetState(row.Slug, "error", "unknown vendor "+row.Vendor)
  268. log.Printf("[netpulse] warning: integration %s has unknown vendor %q at startup", row.Slug, row.Vendor)
  269. continue
  270. }
  271. binPath := filepath.Join(s.integrations.Dir(), row.Slug, vendor.Binary)
  272. if err := s.integrations.Start(row.Slug, nil, binPath); err != nil {
  273. _ = store.SetState(row.Slug, "error", err.Error())
  274. log.Printf("[netpulse] warning: integration %s could not be resumed at startup (%v)", row.Slug, err)
  275. continue
  276. }
  277. _ = store.SetState(row.Slug, "running", "")
  278. _ = store.SetLastStart(row.Slug, time.Now().UnixMilli())
  279. log.Printf("[netpulse] integration %s resumed at startup", row.Slug)
  280. }
  281. s.broadcastIntegrations()
  282. }
  283. // unmanagedItem es un pusher externo que alimenta la flota sin fila en
  284. // router_integrations: se instaló a mano, antes de que la app supiera
  285. // instalarlos (#1743). Solo se describe; la app no puede arrancarlo, pararlo
  286. // ni rotarle el token.
  287. type unmanagedItem struct {
  288. Slug string `json:"slug"`
  289. Kind string `json:"kind"`
  290. Version string `json:"version,omitempty"`
  291. IntervalS int `json:"intervalS,omitempty"`
  292. LastPushMs int64 `json:"lastPushMs"`
  293. Fresh bool `json:"fresh"`
  294. }
  295. // unmanagedIntegrations lista los pushers externos vivos que la app no
  296. // gestiona (#1743). Sin esto la página de Integraciones sale vacía mientras
  297. // /api/agents muestra unidades alimentadas por ellos, y el operador no tiene
  298. // ni una pista de que el pusher existe.
  299. //
  300. // El kind solo vive en memoria (AgentRegistry), así que justo después de un
  301. // reinicio la lista queda vacía hasta el primer push de cada unidad (~30 s).
  302. func (s *server) unmanagedIntegrations() []unmanagedItem {
  303. out := []unmanagedItem{}
  304. if s.db == nil || s.agents == nil {
  305. return out
  306. }
  307. // Los slugs viven en kv como agent.token.<slug>. El cursor se cierra ANTES
  308. // de consultar la tienda de integraciones: con SetMaxOpenConns(1), un
  309. // QueryRow con las filas abiertas espera la única conexión y bloquea.
  310. slugs := []string{}
  311. rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
  312. if err != nil {
  313. return out
  314. }
  315. for rows.Next() {
  316. var key string
  317. if rows.Scan(&key) == nil {
  318. slugs = append(slugs, strings.TrimPrefix(key, agentTokenKeyPrefix))
  319. }
  320. }
  321. rows.Close()
  322. if err := rows.Err(); err != nil {
  323. return out
  324. }
  325. store := s.integrationsStore()
  326. for _, slug := range slugs {
  327. if slug == "" {
  328. continue
  329. }
  330. _, version, kind, interval, ok := s.agents.Info(slug)
  331. if !ok || kind != "external" {
  332. continue
  333. }
  334. if _, managed := store.Get(slug); managed {
  335. continue
  336. }
  337. lastPush := s.integrationLastPushMs(slug)
  338. fresh := lastPush > 0 && interval > 0 && time.Now().UnixMilli()-lastPush <= int64(interval)*3*1000
  339. out = append(out, unmanagedItem{
  340. Slug: slug,
  341. Kind: kind,
  342. Version: version,
  343. IntervalS: interval,
  344. LastPushMs: lastPush,
  345. Fresh: fresh,
  346. })
  347. }
  348. return out
  349. }
  350. func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
  351. writeJSON(w, http.StatusOK, map[string]any{
  352. "integrations": s.integrationList(),
  353. "unmanaged": s.unmanagedIntegrations(),
  354. })
  355. }
  356. type integrationCreateBody struct {
  357. Slug string `json:"slug"`
  358. Vendor string `json:"vendor"`
  359. Host string `json:"host"`
  360. Username string `json:"username"`
  361. Password string `json:"password"`
  362. IntervalS int `json:"intervalS"`
  363. Arch string `json:"arch"`
  364. }
  365. func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request) {
  366. // #2112: en modo ssh el instalador corre en el router antes de responder.
  367. setLongWriteDeadline(w, integrationWriteCeiling)
  368. if s.db == nil {
  369. writeError(w, http.StatusInternalServerError, "db_error")
  370. return
  371. }
  372. var body integrationCreateBody
  373. if st := readJSONBody(w, r, &body); st != 0 {
  374. writeBodyError(w, st, "invalid_body", `Se esperaba { "slug", "vendor", "host", "username", "password", "intervalS", "arch"? }`)
  375. return
  376. }
  377. if !agentSlugRe.MatchString(body.Slug) {
  378. writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
  379. return
  380. }
  381. vendor, ok := s.vendorCatalog.Lookup(body.Vendor)
  382. if !ok {
  383. writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
  384. return
  385. }
  386. if body.Host == "" || body.Username == "" || body.Password == "" {
  387. writeError(w, http.StatusBadRequest, "invalid_input", "host, username and password are required")
  388. return
  389. }
  390. if body.IntervalS < 10 || body.IntervalS > 86400 {
  391. writeError(w, http.StatusBadRequest, "invalid_interval", "intervalS must be between 10 and 86400")
  392. return
  393. }
  394. arch := body.Arch
  395. if arch == "" {
  396. arch = vendor.Arches[0]
  397. } else if !vendorSupportsArch(vendor, arch) {
  398. writeError(w, http.StatusBadRequest, "invalid_arch", "unsupported arch "+arch)
  399. return
  400. }
  401. store := s.integrationsStore()
  402. if _, exists := store.Get(body.Slug); exists {
  403. writeError(w, http.StatusConflict, "already_exists", "integration already exists")
  404. return
  405. }
  406. // El env que se va a escribir tiene que poder arrancar: con la URL en https
  407. // el pin dejó de ser opcional (#13 en netpulse-integrations), y derivarlo
  408. // exige que este server alcance su propia URL pública. Mejor un 502 aquí,
  409. // sin tocar nada, que un alta que muere al segundo siguiente.
  410. serverURL := s.agentBaseURL(r)
  411. if err := requirePusherPin(serverURL); err != nil {
  412. writeError(w, http.StatusBadGateway, "fingerprint_unreachable", err.Error())
  413. return
  414. }
  415. // Resolver y descargar el último release verificado. En modo local se
  416. // extrae el binario aquí (corre en este host); en modo ssh solo se
  417. // verifica: el router descarga el asset él mismo.
  418. fetch := s.integrationFetcher()
  419. res, err := fetch.ResolveLatest(vendor, arch)
  420. if err != nil {
  421. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  422. return
  423. }
  424. binPath := ""
  425. if vendor.Mode == "local" {
  426. if s.integrations == nil {
  427. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  428. return
  429. }
  430. installDir := filepath.Join(s.integrations.Dir(), body.Slug)
  431. binPath, err = fetch.Download(res, vendor.Binary, installDir)
  432. if err != nil {
  433. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  434. return
  435. }
  436. } else {
  437. if s.pool == nil {
  438. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  439. return
  440. }
  441. if err := fetch.Verify(res); err != nil {
  442. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  443. return
  444. }
  445. }
  446. now := time.Now().UnixMilli()
  447. row := rintegration.Row{
  448. Slug: body.Slug, Vendor: vendor.ID, Mode: vendor.Mode, Host: body.Host,
  449. Username: body.Username, Version: res.Version, Asset: res.AssetName,
  450. Arch: arch, IntervalS: body.IntervalS, Enabled: true, State: "pending",
  451. CreatedAt: now, UpdatedAt: now,
  452. }
  453. if err := store.Upsert(row); err != nil {
  454. writeError(w, http.StatusInternalServerError, "db_error")
  455. return
  456. }
  457. // #1708: en modo ssh la misma contraseña del formulario es la credencial
  458. // SSH del alta y de las acciones posteriores: se guarda en el fichero
  459. // compañero (0600) antes de conectar, nunca en la base de datos.
  460. if vendor.Mode == "ssh" && s.integrations != nil {
  461. if err := s.integrations.WriteSSHPassword(body.Slug, body.Password); err != nil {
  462. _ = store.Delete(body.Slug)
  463. writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
  464. return
  465. }
  466. }
  467. // Router external cuyo id es el slug (push autenticado por token de
  468. // agente, agent.token.<slug>).
  469. router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  470. Name: body.Slug, Host: body.Host, Type: "external", AgentOnly: true,
  471. })
  472. if err != nil || router.ID != body.Slug {
  473. _ = store.Delete(body.Slug)
  474. writeError(w, http.StatusInternalServerError, "router_error")
  475. return
  476. }
  477. s.syncRouters()
  478. rollback := func() {
  479. if vendor.Mode == "local" && s.integrations != nil {
  480. _ = s.integrations.Stop(body.Slug)
  481. _ = s.integrations.Cleanup(body.Slug)
  482. }
  483. if vendor.Mode == "ssh" && s.integrations != nil {
  484. _ = s.integrations.RemoveSSHPassword(body.Slug)
  485. }
  486. _ = routerstore.RemoveRouter(s.db.DB, body.Slug)
  487. s.syncRouters()
  488. _ = store.Delete(body.Slug)
  489. }
  490. token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
  491. env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
  492. if vendor.Mode == "local" {
  493. return s.integrations.Start(body.Slug, env, binPath)
  494. }
  495. return s.runSSHInstall(vendor, row, env, res.URL, res.SHA256)
  496. })
  497. if err != nil {
  498. rollback()
  499. writeError(w, http.StatusBadGateway, sshErrorOr(err, "start_failed"), err.Error())
  500. return
  501. }
  502. _ = store.SetState(body.Slug, "running", "")
  503. _ = store.SetLastStart(body.Slug, time.Now().UnixMilli())
  504. s.broadcastIntegrations()
  505. item, _ := s.getIntegrationRow(body.Slug)
  506. writeJSON(w, http.StatusCreated, map[string]any{
  507. "integration": s.integrationItemOf(item),
  508. "token": token,
  509. })
  510. }
  511. func vendorSupportsArch(v rintegration.Vendor, arch string) bool {
  512. for _, a := range v.Arches {
  513. if a == arch {
  514. return true
  515. }
  516. }
  517. return false
  518. }
  519. // pusherEnv construye el entorno del pusher. En modo ssh el pusher corre en el
  520. // propio router, así que el host del dispositivo es la propia unidad
  521. // (127.0.0.1) en lugar del host SSH de la tabla.
  522. func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password, serverURL, token string) map[string]string {
  523. prefix := strings.ToUpper(v.ID) + "_"
  524. host := row.Host
  525. if v.Mode == "ssh" {
  526. host = "127.0.0.1"
  527. }
  528. env := map[string]string{
  529. prefix + "HOST": host,
  530. prefix + "USER": row.Username,
  531. prefix + "PASS": password,
  532. prefix + "INSECURE": "1",
  533. "NETPULSE_SERVER": serverURL,
  534. "NETPULSE_TOKEN": token,
  535. "NETPULSE_SLUG": row.Slug,
  536. "NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
  537. }
  538. for k, v := range pusherPinEnv(serverURL) {
  539. env[k] = v
  540. }
  541. return env
  542. }
  543. // healPusherPin merges the current server pin into a pusher environment,
  544. // healing files written before the pin requirement and refreshing the pin
  545. // after a certificate reissue. It is a no-op when the server URL needs no
  546. // pin (plain HTTP).
  547. func healPusherPin(env map[string]string, serverURL string) map[string]string {
  548. for k, v := range pusherPinEnv(serverURL) {
  549. env[k] = v
  550. }
  551. return env
  552. }
  553. func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
  554. _, err := s.runIntegrationSSH(row, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
  555. return err
  556. }
  557. // sshPasswordSetter es la capacidad opcional del pool SSH de conectar por
  558. // contraseña (#1708). adapters.SSHPool la implementa; los fakes de tests que
  559. // solo implementan Run no, y en ese caso el pool queda como esté.
  560. type sshPasswordSetter interface {
  561. SetPassword(host, user, password string)
  562. }
  563. // applyIntegrationSSHAuth aplica al pool la credencial SSH de la
  564. // integración (#1708): si existe el fichero compañero <slug>.sshpass la
  565. // conexión va por contraseña con el usuario de la fila (gana sobre la llave
  566. // del servidor); si no, la credencial se limpia y el dial usa la llave como
  567. // siempre. Un fichero ilegible cae a llave con aviso en el log.
  568. func (s *server) applyIntegrationSSHAuth(row rintegration.Row) {
  569. if s.pool == nil || s.integrations == nil {
  570. return
  571. }
  572. setter, ok := s.pool.(sshPasswordSetter)
  573. if !ok {
  574. return
  575. }
  576. pass, err := s.integrations.ReadSSHPassword(row.Slug)
  577. if err != nil {
  578. log.Printf("[netpulse] warning: integration %s: could not read SSH password file (%v), connecting with key", row.Slug, err)
  579. pass = ""
  580. }
  581. setter.SetPassword(row.Host, row.Username, pass)
  582. }
  583. // runIntegrationSSH ejecuta un comando en el router de la integración
  584. // aplicando antes la credencial SSH del fichero compañero (#1708).
  585. func (s *server) runIntegrationSSH(row rintegration.Row, cmd string, timeout time.Duration) (string, error) {
  586. s.applyIntegrationSSHAuth(row)
  587. return s.pool.Run(row.Host, cmd, timeout)
  588. }
  589. // sshErrorCode clasifica un error SSH para la API (#1708): el rechazo de
  590. // autenticación es su propio código (ssh_auth_failed) frente al fallo
  591. // genérico de conexión (ssh_failed), de modo que la UI puede pedir revisar
  592. // la contraseña.
  593. func sshErrorCode(err error) string {
  594. var ae *adapters.SSHAuthError
  595. if errors.As(err, &ae) {
  596. return "ssh_auth_failed"
  597. }
  598. return "ssh_failed"
  599. }
  600. // sshErrorOr devuelve ssh_auth_failed cuando err es un rechazo de
  601. // autenticación SSH y fallback para cualquier otro error.
  602. func sshErrorOr(err error, fallback string) string {
  603. if sshErrorCode(err) == "ssh_auth_failed" {
  604. return "ssh_auth_failed"
  605. }
  606. return fallback
  607. }
  608. func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
  609. slug := r.PathValue("slug")
  610. row, ok := s.getIntegrationRow(slug)
  611. if !ok {
  612. writeError(w, http.StatusNotFound, "not_found")
  613. return
  614. }
  615. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  616. if !ok {
  617. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  618. return
  619. }
  620. store := s.integrationsStore()
  621. if vendor.Mode == "local" {
  622. if s.integrations == nil {
  623. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  624. return
  625. }
  626. if !s.integrations.Running(slug) {
  627. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  628. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  629. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  630. return
  631. }
  632. }
  633. } else {
  634. if s.pool == nil {
  635. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  636. return
  637. }
  638. if _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
  639. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  640. return
  641. }
  642. }
  643. _ = store.SetState(slug, "running", "")
  644. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  645. s.broadcastIntegrations()
  646. item, _ := s.getIntegrationRow(slug)
  647. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  648. }
  649. func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
  650. slug := r.PathValue("slug")
  651. row, ok := s.getIntegrationRow(slug)
  652. if !ok {
  653. writeError(w, http.StatusNotFound, "not_found")
  654. return
  655. }
  656. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  657. if !ok {
  658. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  659. return
  660. }
  661. if vendor.Mode == "local" {
  662. if s.integrations != nil {
  663. _ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
  664. }
  665. } else if s.pool != nil {
  666. _, _ = s.runIntegrationSSH(row, sshServiceScript(vendor, "stop"), 60*time.Second)
  667. }
  668. _ = s.integrationsStore().SetState(slug, "stopped", "")
  669. s.broadcastIntegrations()
  670. item, _ := s.getIntegrationRow(slug)
  671. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  672. }
  673. func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request) {
  674. slug := r.PathValue("slug")
  675. row, ok := s.getIntegrationRow(slug)
  676. if !ok {
  677. writeError(w, http.StatusNotFound, "not_found")
  678. return
  679. }
  680. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  681. if !ok {
  682. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  683. return
  684. }
  685. running := false
  686. if vendor.Mode == "local" {
  687. running = s.integrations != nil && s.integrations.Running(slug)
  688. } else if s.pool != nil {
  689. _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "check"), 30*time.Second)
  690. running = err == nil
  691. }
  692. // #1696: un check verificado reconcilia el estado guardado: el unverified
  693. // que deja un reinicio del servidor (o una fila desfasada) vuelve a
  694. // running cuando el proceso está demostradamente vivo.
  695. if running && row.State != "running" {
  696. _ = s.integrationsStore().SetState(slug, "running", "")
  697. s.broadcastIntegrations()
  698. if fresh, ok := s.getIntegrationRow(slug); ok {
  699. row = fresh
  700. }
  701. }
  702. writeJSON(w, http.StatusOK, map[string]any{
  703. "integration": s.integrationItemOf(row),
  704. "running": running,
  705. })
  706. }
  707. func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request) {
  708. // #2112: en modo ssh reinstala el pusher en el router antes de responder.
  709. setLongWriteDeadline(w, integrationWriteCeiling)
  710. slug := r.PathValue("slug")
  711. row, ok := s.getIntegrationRow(slug)
  712. if !ok {
  713. writeError(w, http.StatusNotFound, "not_found")
  714. return
  715. }
  716. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  717. if !ok {
  718. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  719. return
  720. }
  721. fetch := s.integrationFetcher()
  722. res, err := fetch.ResolveLatest(vendor, row.Arch)
  723. if err != nil {
  724. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  725. return
  726. }
  727. store := s.integrationsStore()
  728. if vendor.Mode == "local" {
  729. if s.integrations == nil {
  730. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  731. return
  732. }
  733. _ = s.integrations.Stop(slug)
  734. installDir := filepath.Join(s.integrations.Dir(), slug)
  735. if _, err := fetch.Download(res, vendor.Binary, installDir); err != nil {
  736. _ = store.SetState(slug, "error", err.Error())
  737. s.broadcastIntegrations()
  738. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  739. return
  740. }
  741. // Heal environments created before the pin requirement: the
  742. // refreshed binary refuses to start without it. Best effort, on
  743. // error the old file is reused and the start below reports it.
  744. if env, err := s.integrations.Env(slug); err == nil {
  745. _ = s.integrations.WriteEnv(slug, healPusherPin(env, s.agentBaseURL(r)))
  746. }
  747. if err := s.integrations.Start(slug, nil, filepath.Join(installDir, vendor.Binary)); err != nil {
  748. _ = store.SetState(slug, "error", err.Error())
  749. s.broadcastIntegrations()
  750. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  751. return
  752. }
  753. } else {
  754. if s.pool == nil {
  755. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  756. return
  757. }
  758. if err := fetch.Verify(res); err != nil {
  759. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  760. return
  761. }
  762. env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
  763. if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
  764. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  765. return
  766. }
  767. }
  768. _ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
  769. _ = store.SetState(slug, "running", "")
  770. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  771. s.broadcastIntegrations()
  772. item, _ := s.getIntegrationRow(slug)
  773. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  774. }
  775. // handleIntegrationEdit actualiza los ajustes mutables de una integración sin
  776. // recrearla: host, usuario, contraseña e intervalo. El fichero de entorno se
  777. // lee, se cambian solo las claves afectadas y se reescribe, de modo que el
  778. // token y la contraseña omitida se conservan (nunca viven en la base de datos).
  779. func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
  780. slug := r.PathValue("slug")
  781. row, ok := s.getIntegrationRow(slug)
  782. if !ok {
  783. writeError(w, http.StatusNotFound, "not_found")
  784. return
  785. }
  786. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  787. if !ok {
  788. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  789. return
  790. }
  791. var body struct {
  792. Host *string `json:"host"`
  793. Username *string `json:"username"`
  794. Password *string `json:"password"`
  795. IntervalS *int `json:"intervalS"`
  796. }
  797. if st := readJSONBody(w, r, &body); st != 0 {
  798. writeBodyError(w, st, "invalid_body", "")
  799. return
  800. }
  801. changed := false
  802. if body.Host != nil {
  803. h := strings.TrimSpace(*body.Host)
  804. if h == "" {
  805. writeError(w, http.StatusBadRequest, "invalid_input", "host cannot be empty")
  806. return
  807. }
  808. row.Host = h
  809. changed = true
  810. }
  811. if body.Username != nil {
  812. u := strings.TrimSpace(*body.Username)
  813. if u == "" {
  814. writeError(w, http.StatusBadRequest, "invalid_input", "username cannot be empty")
  815. return
  816. }
  817. row.Username = u
  818. changed = true
  819. }
  820. if body.IntervalS != nil {
  821. if *body.IntervalS < 10 || *body.IntervalS > 86400 {
  822. writeError(w, http.StatusBadRequest, "invalid_interval")
  823. return
  824. }
  825. row.IntervalS = *body.IntervalS
  826. changed = true
  827. }
  828. password := ""
  829. if body.Password != nil {
  830. password = *body.Password
  831. changed = true
  832. }
  833. if !changed {
  834. writeError(w, http.StatusBadRequest, "invalid_input", "nothing to update")
  835. return
  836. }
  837. prefix := strings.ToUpper(vendor.ID) + "_"
  838. host := row.Host
  839. if vendor.Mode == "ssh" {
  840. host = "127.0.0.1"
  841. }
  842. store := s.integrationsStore()
  843. if vendor.Mode == "local" {
  844. if s.integrations == nil {
  845. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  846. return
  847. }
  848. env, err := s.integrations.Env(slug)
  849. if err != nil {
  850. _ = store.SetState(slug, "error", err.Error())
  851. s.broadcastIntegrations()
  852. writeError(w, http.StatusConflict, "env_unavailable", err.Error())
  853. return
  854. }
  855. env[prefix+"HOST"] = host
  856. env[prefix+"USER"] = row.Username
  857. if password != "" {
  858. env[prefix+"PASS"] = password
  859. }
  860. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  861. healPusherPin(env, s.agentBaseURL(r))
  862. if err := s.integrations.WriteEnv(slug, env); err != nil {
  863. _ = store.SetState(slug, "error", err.Error())
  864. s.broadcastIntegrations()
  865. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  866. return
  867. }
  868. _ = s.integrations.Stop(slug)
  869. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  870. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  871. _ = store.SetState(slug, "error", err.Error())
  872. s.broadcastIntegrations()
  873. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  874. return
  875. }
  876. } else {
  877. if s.pool == nil {
  878. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  879. return
  880. }
  881. // #1708: la contraseña nueva del formulario es también la credencial
  882. // SSH: guardarla en el fichero compañero ANTES de conectar, porque si
  883. // el usuario ya cambió la contraseña en el router, la conexión de
  884. // este mismo guardado necesita la nueva.
  885. if password != "" && s.integrations != nil {
  886. if err := s.integrations.WriteSSHPassword(slug, password); err != nil {
  887. writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
  888. return
  889. }
  890. }
  891. raw, err := s.runIntegrationSSH(row, sshEnvReadScript(vendor), 30*time.Second)
  892. if err != nil {
  893. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  894. return
  895. }
  896. env := rintegration.ParseEnv(raw)
  897. env[prefix+"HOST"] = host
  898. env[prefix+"USER"] = row.Username
  899. if password != "" {
  900. env[prefix+"PASS"] = password
  901. }
  902. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  903. healPusherPin(env, s.agentBaseURL(r))
  904. if _, err := s.runIntegrationSSH(row, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
  905. _ = store.SetState(slug, "error", err.Error())
  906. s.broadcastIntegrations()
  907. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  908. return
  909. }
  910. }
  911. if err := store.Upsert(row); err != nil {
  912. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  913. return
  914. }
  915. _ = store.SetState(slug, "running", "")
  916. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  917. s.broadcastIntegrations()
  918. item, _ := s.getIntegrationRow(slug)
  919. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  920. }
  921. func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request) {
  922. slug := r.PathValue("slug")
  923. row, ok := s.getIntegrationRow(slug)
  924. if !ok {
  925. writeError(w, http.StatusNotFound, "not_found")
  926. return
  927. }
  928. vendor, _ := s.vendorCatalog.Lookup(row.Vendor)
  929. if vendor.Mode == "local" {
  930. if s.integrations != nil {
  931. _ = s.integrations.Stop(slug)
  932. _ = s.integrations.Cleanup(slug)
  933. }
  934. } else if s.pool != nil {
  935. _, _ = s.runIntegrationSSH(row, sshUninstallScript(vendor), 60*time.Second)
  936. }
  937. // #1708: la contraseña SSH del fichero compañero muere con la
  938. // integración y el pool pierde la credencial (la conexión cacheada se
  939. // tira y el siguiente dial vuelve a la llave).
  940. if s.integrations != nil {
  941. _ = s.integrations.RemoveSSHPassword(slug)
  942. }
  943. if setter, ok := s.pool.(sshPasswordSetter); ok {
  944. setter.SetPassword(row.Host, "", "")
  945. }
  946. _ = s.integrationsStore().Delete(slug)
  947. _ = routerstore.RemoveRouter(s.db.DB, slug)
  948. s.syncRouters()
  949. if s.db != nil {
  950. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
  951. }
  952. s.broadcastIntegrations()
  953. w.WriteHeader(http.StatusNoContent)
  954. }
  955. // ---------------------------------------------------------------------------
  956. // Scripts POSIX de instalación/gestión por SSH (modo ssh, p. ej. asuswrt)
  957. // ---------------------------------------------------------------------------
  958. // envFileBody renders the sorted KEY=value body of an env file, with values
  959. // escaped by EscapeEnvValue for a lossless round-trip through ParseEnv.
  960. func envFileBody(env map[string]string) string {
  961. keys := make([]string, 0, len(env))
  962. for k := range env {
  963. keys = append(keys, k)
  964. }
  965. sort.Strings(keys)
  966. var b strings.Builder
  967. for _, k := range keys {
  968. b.WriteString(k)
  969. b.WriteString("=")
  970. b.WriteString(rintegration.EscapeEnvValue(env[k]))
  971. b.WriteString("\n")
  972. }
  973. return b.String()
  974. }
  975. // sshInstallScript genera el instalador on-router de un vendor en modo ssh.
  976. // Ramifica por el sistema de init del vendor (#1681): procd (layout OpenWrt,
  977. // salida intacta) o merlin (/jffs + bloque gestionado en services-start).
  978. func sshInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  979. if v.InitSystem() == "merlin" {
  980. return sshMerlinInstallScript(v, env, assetURL, sha256)
  981. }
  982. return sshProcdInstallScript(v, env, assetURL, sha256)
  983. }
  984. // sshProcdInstallScript instala el pusher en un vendor OpenWrt: binario en
  985. // /usr/sbin, init procd en /etc/init.d y env en /etc.
  986. func sshProcdInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  987. bin := "/usr/sbin/" + v.Binary
  988. init := "/etc/init.d/" + v.Binary
  989. envFile := "/etc/" + v.Binary + ".env"
  990. envBlock := envFileBody(env)
  991. return `#!/bin/sh
  992. set -e
  993. BIN="` + bin + `"
  994. INIT="` + init + `"
  995. ENV_FILE="` + envFile + `"
  996. SERVER="` + env["NETPULSE_SERVER"] + `"
  997. ASSET_URL="` + assetURL + `"
  998. SHA256="` + sha256 + `"
  999. # Preflight: el router debe alcanzar el server.
  1000. if command -v curl >/dev/null 2>&1; then
  1001. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1002. else
  1003. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1004. fi
  1005. # Parar el servicio previo (el proceso vivo mantiene el binario abierto).
  1006. [ -x "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
  1007. # Descargar el asset desde la URL ya verificada en el server.
  1008. if command -v curl >/dev/null 2>&1; then
  1009. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1010. else
  1011. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1012. fi
  1013. # Verificar sha256 antes de instalar.
  1014. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  1015. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  1016. # Extraer y mover de forma atómica (.new -> rename).
  1017. mkdir -p /tmp/` + v.Binary + `.extract
  1018. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  1019. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  1020. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  1021. cp "$SRC" "$BIN.new"
  1022. chmod 0755 "$BIN.new"
  1023. mv -f "$BIN.new" "$BIN"
  1024. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  1025. # Env (chmod 600): solo se escribe en el alta; los updates preservan el
  1026. # fichero existente (la contraseña y el token solo viven ahí).
  1027. if [ ! -f "$ENV_FILE" ]; then
  1028. cat > "$ENV_FILE" <<'ENVEOF'
  1029. ` + envBlock + `ENVEOF
  1030. chmod 600 "$ENV_FILE"
  1031. fi
  1032. # Init procd.
  1033. cat > "$INIT" <<'INITEOF'
  1034. #!/bin/sh /etc/rc.common
  1035. START=99
  1036. STOP=10
  1037. USE_PROCD=1
  1038. BIN="/usr/sbin/` + v.Binary + `"
  1039. ENV_FILE="/etc/` + v.Binary + `.env"
  1040. start_service() {
  1041. [ -x "$BIN" ] || return 1
  1042. [ -r "$ENV_FILE" ] || { echo "netpulse: missing or unreadable env file $ENV_FILE" >&2; return 1; }
  1043. # Cargar el fichero de entorno y pasarlo entero al proceso en UNA sola
  1044. # llamada env (#1709): cada llamada adicional pisaria a la anterior y al
  1045. # proceso solo le llegaria la ultima variable (OpenWrt 21.02, #1701).
  1046. # Los valores van escapados (salto de linea = \n): printf %b los
  1047. # desescapa igual que ParseEnv en el server y que el control script de
  1048. # Merlin (#1705), sin pasar por . "$ENV_FILE" ni /etc/profile.
  1049. set --
  1050. while IFS= read -r line || [ -n "$line" ]; do
  1051. case "$line" in ""|\#*) continue ;; esac
  1052. k=${line%%=*}
  1053. val=${line#*=}
  1054. val=$(printf '%b' "$val")
  1055. set -- "$@" "$k=$val"
  1056. done < "$ENV_FILE"
  1057. procd_open_instance ` + v.Binary + `
  1058. procd_set_param env "$@"
  1059. procd_set_param command "$BIN"
  1060. procd_set_param respawn 3600 5 5
  1061. procd_set_param stdout 1
  1062. procd_set_param stderr 1
  1063. # Vigila el fichero: un cambio sigue reiniciando el servicio y el
  1064. # arranque vuelve a leer el env, asi que el proceso recoge los valores
  1065. # nuevos.
  1066. procd_set_param file "$ENV_FILE"
  1067. procd_close_instance
  1068. }
  1069. INITEOF
  1070. chmod 0755 "$INIT"
  1071. "$INIT" enable
  1072. "$INIT" restart
  1073. `
  1074. }
  1075. // sshMerlinInstallScript instala el pusher en un vendor Asuswrt-Merlin
  1076. // (#1681): sin procd, todo bajo /jffs/netpulse (binario, env, script de
  1077. // control con pidfile y log) y un bloque gestionado en
  1078. // /jffs/scripts/services-start para el arranque al boot. Re-ejecutarlo es
  1079. // idempotente: el env solo se escribe si falta y el bloque solo se añade una
  1080. // vez; el resto del hook no se toca.
  1081. func sshMerlinInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  1082. dir := "/jffs/netpulse"
  1083. bin := dir + "/" + v.Binary
  1084. ctrl := bin + ".sh"
  1085. envFile := bin + ".env"
  1086. pidFile := bin + ".pid"
  1087. logFile := bin + ".log"
  1088. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1089. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1090. return `#!/bin/sh
  1091. set -e
  1092. BIN="` + bin + `"
  1093. CTRL="` + ctrl + `"
  1094. ENV_FILE="` + envFile + `"
  1095. PID_FILE="` + pidFile + `"
  1096. LOG_FILE="` + logFile + `"
  1097. HOOK="/jffs/scripts/services-start"
  1098. SERVER="` + env["NETPULSE_SERVER"] + `"
  1099. ASSET_URL="` + assetURL + `"
  1100. SHA256="` + sha256 + `"
  1101. # Preflight: el router debe alcanzar el server.
  1102. if command -v curl >/dev/null 2>&1; then
  1103. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1104. else
  1105. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1106. fi
  1107. # Parar el pusher previo (el proceso vivo mantiene el binario abierto).
  1108. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1109. # Descargar el asset desde la URL ya verificada en el server.
  1110. if command -v curl >/dev/null 2>&1; then
  1111. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1112. else
  1113. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1114. fi
  1115. # Verificar sha256 antes de instalar.
  1116. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  1117. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  1118. # Extraer y mover de forma atómica (.new -> rename).
  1119. mkdir -p /tmp/` + v.Binary + `.extract
  1120. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  1121. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  1122. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  1123. mkdir -p "$DIR"
  1124. cp "$SRC" "$BIN.new"
  1125. chmod 0755 "$BIN.new"
  1126. mv -f "$BIN.new" "$BIN"
  1127. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  1128. # Env (chmod 600): solo se escribe si aún no existe; los updates preservan
  1129. # el fichero (la contraseña y el token solo viven ahí).
  1130. if [ ! -f "$ENV_FILE" ]; then
  1131. cat > "$ENV_FILE" <<'ENVEOF'
  1132. ` + envFileBody(env) + `ENVEOF
  1133. chmod 600 "$ENV_FILE"
  1134. fi
  1135. # Script de control con pidfile (start|stop|restart|check). El env guarda
  1136. # los valores escapados (salto de línea = \n): printf %b los desescapa igual
  1137. # que ParseEnv en el server antes de exportarlos al pusher.
  1138. cat > "$CTRL" <<'CTRLEOF'
  1139. #!/bin/sh
  1140. # NetPulse pusher control script (Asuswrt-Merlin).
  1141. BIN="` + bin + `"
  1142. PID_FILE="` + pidFile + `"
  1143. ENV_FILE="` + envFile + `"
  1144. LOG_FILE="` + logFile + `"
  1145. running() {
  1146. [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
  1147. }
  1148. case "$1" in
  1149. start)
  1150. [ -x "$BIN" ] || { echo "netpulse: missing $BIN"; exit 1; }
  1151. if running; then
  1152. exit 0
  1153. fi
  1154. rm -f "$PID_FILE"
  1155. [ -f "$ENV_FILE" ] || { echo "netpulse: missing $ENV_FILE"; exit 1; }
  1156. while IFS= read -r line || [ -n "$line" ]; do
  1157. case "$line" in ""|\#*) continue ;; esac
  1158. k=${line%%=*}
  1159. val=${line#*=}
  1160. val=$(printf '%b' "$val")
  1161. export "$k=$val"
  1162. done < "$ENV_FILE"
  1163. nohup "$BIN" >> "$LOG_FILE" 2>&1 &
  1164. echo $! > "$PID_FILE"
  1165. ;;
  1166. stop)
  1167. if [ -f "$PID_FILE" ]; then
  1168. RUN_PID=$(cat "$PID_FILE")
  1169. kill "$RUN_PID" 2>/dev/null || true
  1170. n=0
  1171. while kill -0 "$RUN_PID" 2>/dev/null && [ "$n" -lt 10 ]; do
  1172. sleep 1
  1173. n=$((n+1))
  1174. done
  1175. if kill -0 "$RUN_PID" 2>/dev/null; then
  1176. kill -9 "$RUN_PID" 2>/dev/null || true
  1177. fi
  1178. rm -f "$PID_FILE"
  1179. fi
  1180. ;;
  1181. restart)
  1182. "$0" stop
  1183. "$0" start
  1184. ;;
  1185. check)
  1186. if running; then
  1187. exit 0
  1188. fi
  1189. exit 1
  1190. ;;
  1191. *)
  1192. echo "usage: $0 {start|stop|restart|check}"
  1193. exit 2
  1194. ;;
  1195. esac
  1196. CTRLEOF
  1197. chmod 0755 "$CTRL"
  1198. # Arranque al boot: bloque gestionado en services-start, delimitado por
  1199. # marcadores únicos para poder quitarlo sin tocar el resto del fichero.
  1200. mkdir -p /jffs/scripts
  1201. if [ ! -f "$HOOK" ]; then
  1202. printf '#!/bin/sh\n' > "$HOOK"
  1203. fi
  1204. chmod 0755 "$HOOK"
  1205. if ! grep -qF '` + blockStart + `' "$HOOK" 2>/dev/null; then
  1206. cat >> "$HOOK" <<'BLOKEOF'
  1207. ` + blockStart + `
  1208. ` + ctrl + ` start
  1209. ` + blockEnd + `
  1210. BLOKEOF
  1211. fi
  1212. "$CTRL" start
  1213. `
  1214. }
  1215. // sshEnvReadScript prints the environment file of an integration running
  1216. // inside the router, so the server can merge changes without ever storing the
  1217. // token or the password. Merlin vendors keep the env under /jffs/netpulse.
  1218. func sshEnvReadScript(v rintegration.Vendor) string {
  1219. if v.InitSystem() == "merlin" {
  1220. return "cat /jffs/netpulse/" + v.Binary + ".env"
  1221. }
  1222. return "cat /etc/" + v.Binary + ".env"
  1223. }
  1224. // sshEnvWriteScript replaces the environment file inside the router and
  1225. // restarts the service. Values come already escaped by EscapeEnvValue and the
  1226. // heredoc is quoted, so the shell does not expand anything.
  1227. func sshEnvWriteScript(v rintegration.Vendor, env map[string]string) string {
  1228. envBlock := envFileBody(env)
  1229. if v.InitSystem() == "merlin" {
  1230. envFile := "/jffs/netpulse/" + v.Binary + ".env"
  1231. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1232. return `#!/bin/sh
  1233. set -e
  1234. ENV_FILE="` + envFile + `"
  1235. CTRL="` + ctrl + `"
  1236. cat > "$ENV_FILE.new" <<'ENVEOF'
  1237. ` + envBlock + `ENVEOF
  1238. chmod 600 "$ENV_FILE.new"
  1239. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1240. if [ -x "$CTRL" ]; then
  1241. "$CTRL" restart >/dev/null 2>&1 || true
  1242. fi
  1243. `
  1244. }
  1245. init := "/etc/init.d/" + v.Binary
  1246. envFile := "/etc/" + v.Binary + ".env"
  1247. return `#!/bin/sh
  1248. set -e
  1249. INIT="` + init + `"
  1250. ENV_FILE="` + envFile + `"
  1251. cat > "$ENV_FILE.new" <<'ENVEOF'
  1252. ` + envBlock + `ENVEOF
  1253. chmod 600 "$ENV_FILE.new"
  1254. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1255. if [ -x "$INIT" ]; then
  1256. "$INIT" stop >/dev/null 2>&1 || true
  1257. "$INIT" start >/dev/null 2>&1 || true
  1258. fi
  1259. `
  1260. }
  1261. func sshServiceScript(v rintegration.Vendor, action string) string {
  1262. if v.InitSystem() == "merlin" {
  1263. // Merlin no tiene procd: las acciones van al script de control
  1264. // con pidfile. check sigue siendo pgrep para no cambiar el camino
  1265. // de salud del handler.
  1266. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1267. switch action {
  1268. case "start":
  1269. return "test -x " + ctrl + " && " + ctrl + " start || true"
  1270. case "stop":
  1271. return "test -x " + ctrl + " && " + ctrl + " stop || true"
  1272. case "restart":
  1273. return "test -x " + ctrl + " && " + ctrl + " restart || true"
  1274. case "check":
  1275. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1276. }
  1277. return "true"
  1278. }
  1279. init := "/etc/init.d/" + v.Binary
  1280. switch action {
  1281. case "start":
  1282. return "test -x " + init + " && " + init + " enable && " + init + " start || true"
  1283. case "stop":
  1284. return "test -x " + init + " && " + init + " stop || true"
  1285. case "restart":
  1286. return "test -x " + init + " && " + init + " restart || true"
  1287. case "check":
  1288. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1289. }
  1290. return "true"
  1291. }
  1292. func sshUninstallScript(v rintegration.Vendor) string {
  1293. if v.InitSystem() == "merlin" {
  1294. return sshMerlinUninstallScript(v)
  1295. }
  1296. init := "/etc/init.d/" + v.Binary
  1297. bin := "/usr/sbin/" + v.Binary
  1298. envFile := "/etc/" + v.Binary + ".env"
  1299. return fmt.Sprintf(
  1300. "test -x %s && %s stop || true; test -x %s && %s disable || true; rm -f %s %s %s",
  1301. init, init, init, init, init, bin, envFile,
  1302. )
  1303. }
  1304. // sshMerlinUninstallScript para el pusher con su script de control, quita el
  1305. // bloque gestionado de services-start (el resto del hook queda intacto) y
  1306. // borra /jffs/netpulse entero.
  1307. func sshMerlinUninstallScript(v rintegration.Vendor) string {
  1308. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1309. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1310. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1311. return `CTRL="` + ctrl + `"
  1312. HOOK="/jffs/scripts/services-start"
  1313. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1314. if [ -f "$HOOK" ]; then
  1315. sed -i '/` + blockStart + `/,/` + blockEnd + `/d' "$HOOK" 2>/dev/null || true
  1316. fi
  1317. rm -rf /jffs/netpulse
  1318. `
  1319. }