integrations.go 47 KB

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