integrations.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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. "fmt"
  10. "log"
  11. "net/http"
  12. "path/filepath"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/gnacho/netpulse/server-go/internal/auth"
  18. "github.com/gnacho/netpulse/server-go/internal/rintegration"
  19. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  20. )
  21. // integrationItem es la vista HTTP de una integración (nunca la contraseña).
  22. type integrationItem struct {
  23. Slug string `json:"slug"`
  24. Vendor string `json:"vendor"`
  25. Mode string `json:"mode"`
  26. Host string `json:"host"`
  27. Username string `json:"username"`
  28. Version string `json:"version"`
  29. Arch string `json:"arch"`
  30. IntervalS int `json:"intervalS"`
  31. Enabled bool `json:"enabled"`
  32. State string `json:"state"`
  33. LastError string `json:"lastError"`
  34. LastStartMs int64 `json:"lastStartMs"`
  35. LastPushMs int64 `json:"lastPushMs"`
  36. Fresh bool `json:"fresh"`
  37. }
  38. // vendorView es la vista HTTP del manifiesto de un vendor.
  39. type vendorView struct {
  40. ID string `json:"id"`
  41. Mode string `json:"mode"`
  42. Arches []string `json:"arches"`
  43. TagPrefix string `json:"tagPrefix"`
  44. Description string `json:"description"`
  45. }
  46. // registerIntegrationRoutes registra las rutas /api/integrations/*. Todas
  47. // exigen rol admin salvo el GET de vendors (solo sesión).
  48. func (s *server) registerIntegrationRoutes(mux *http.ServeMux) {
  49. mux.HandleFunc("GET /api/integrations/vendors", s.handleIntegrationsVendors)
  50. mux.Handle("POST /api/integrations/vendors/refresh", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsVendorsRefresh)))
  51. mux.Handle("GET /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsList)))
  52. mux.Handle("POST /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsCreate)))
  53. mux.Handle("POST /api/integrations/{slug}/start", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStart)))
  54. mux.Handle("POST /api/integrations/{slug}/stop", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStop)))
  55. mux.Handle("POST /api/integrations/{slug}/check", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationCheck)))
  56. mux.Handle("POST /api/integrations/{slug}/update", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationUpdate)))
  57. mux.Handle("PUT /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationEdit)))
  58. mux.Handle("DELETE /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationDelete)))
  59. }
  60. // vendorCatalogRefreshTimeout acota el fetch forzado del endpoint admin.
  61. const vendorCatalogRefreshTimeout = 15 * time.Second
  62. func (s *server) handleIntegrationsVendors(w http.ResponseWriter, r *http.Request) {
  63. vs := s.vendorCatalog.Vendors(r.Context())
  64. writeJSON(w, http.StatusOK, map[string]any{
  65. "vendors": vendorViews(vs),
  66. "lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
  67. })
  68. }
  69. // handleIntegrationsVendorsRefresh fuerza el descubrimiento del catálogo
  70. // (#1697): fetch inmediato, caché actualizada y catálogo devuelto en la
  71. // misma respuesta para que la UI no encadene un segundo GET. Un fallo de
  72. // fetch o de validación deja el catálogo anterior en su sitio (502).
  73. func (s *server) handleIntegrationsVendorsRefresh(w http.ResponseWriter, r *http.Request) {
  74. if s.db == nil || s.vendorCatalog == nil {
  75. writeError(w, http.StatusServiceUnavailable, "unavailable", "vendor catalog is not available without a database")
  76. return
  77. }
  78. ctx, cancel := context.WithTimeout(r.Context(), vendorCatalogRefreshTimeout)
  79. defer cancel()
  80. if err := s.vendorCatalog.Refresh(ctx); err != nil {
  81. writeError(w, http.StatusBadGateway, "refresh_failed", err.Error())
  82. return
  83. }
  84. writeJSON(w, http.StatusOK, map[string]any{
  85. "vendors": vendorViews(s.vendorCatalog.Current()),
  86. "lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
  87. })
  88. }
  89. // vendorViews es la vista HTTP del catálogo: mismos campos que servía el
  90. // manifiesto estático para no romper el contrato con la UI.
  91. func vendorViews(vs []rintegration.Vendor) []vendorView {
  92. out := make([]vendorView, 0, len(vs))
  93. for _, v := range vs {
  94. out = append(out, vendorView{
  95. ID: v.ID, Mode: v.Mode, Arches: v.Arches,
  96. TagPrefix: v.TagPrefix, Description: v.Description,
  97. })
  98. }
  99. return out
  100. }
  101. func (s *server) integrationsStore() *rintegration.Store {
  102. return rintegration.NewStore(s.db.DB)
  103. }
  104. func (s *server) integrationFetcher() *rintegration.Fetcher {
  105. if s.integrations != nil {
  106. return s.integrations.Fetch()
  107. }
  108. return rintegration.NewFetcher()
  109. }
  110. func (s *server) getIntegrationRow(slug string) (rintegration.Row, bool) {
  111. if s.db == nil {
  112. return rintegration.Row{}, false
  113. }
  114. return s.integrationsStore().Get(slug)
  115. }
  116. // integrationLastPushMs lee agent.last_push_ts.<slug> (segundos unix) y lo
  117. // devuelve en milisegundos, 0 si nunca empujó.
  118. func (s *server) integrationLastPushMs(slug string) int64 {
  119. if s.db == nil {
  120. return 0
  121. }
  122. sec, err := strconv.ParseInt(kvGet(s.db.DB, "agent.last_push_ts."+slug), 10, 64)
  123. if err != nil {
  124. return 0
  125. }
  126. return sec * 1000
  127. }
  128. func (s *server) integrationItemOf(row rintegration.Row) integrationItem {
  129. lastPush := s.integrationLastPushMs(row.Slug)
  130. fresh := false
  131. if lastPush > 0 && row.IntervalS > 0 {
  132. fresh = time.Now().UnixMilli()-lastPush <= int64(row.IntervalS)*3*1000
  133. }
  134. // #1696: reconciliar al leer. Una fila en running cuyo último push es más
  135. // viejo que 3 intervalos no puede ir de sana: la vista la reporta como
  136. // "stale". Es solo vista (la fila no se toca): en cuanto el pusher vuelva
  137. // a empujar, el propio cálculo la devuelve a "running".
  138. state := row.State
  139. if state == "running" && lastPush > 0 && row.IntervalS > 0 && !fresh {
  140. state = "stale"
  141. }
  142. return integrationItem{
  143. Slug: row.Slug, Vendor: row.Vendor, Mode: row.Mode, Host: row.Host,
  144. Username: row.Username, Version: row.Version, Arch: row.Arch,
  145. IntervalS: row.IntervalS, Enabled: row.Enabled, State: state,
  146. LastError: row.LastError, LastStartMs: row.LastStartMs,
  147. LastPushMs: lastPush, Fresh: fresh,
  148. }
  149. }
  150. func (s *server) integrationList() []integrationItem {
  151. if s.db == nil {
  152. return []integrationItem{}
  153. }
  154. rows, err := s.integrationsStore().List()
  155. if err != nil {
  156. return []integrationItem{}
  157. }
  158. out := make([]integrationItem, 0, len(rows))
  159. for _, row := range rows {
  160. out = append(out, s.integrationItemOf(row))
  161. }
  162. return out
  163. }
  164. func (s *server) broadcastIntegrations() {
  165. if s.hub != nil {
  166. s.hub.Broadcast("integrations", map[string]any{"integrations": s.integrationList()})
  167. }
  168. }
  169. // watchIntegrations (#1696) registra el callback de salida inesperada de los
  170. // pushers locales (#1674) y reanuda al arrancar las integraciones habilitadas.
  171. // No-op sin supervisor o sin base de datos (demo). Los paros intencionales no
  172. // pasan por el callback: los gestiona el handler de stop.
  173. func (s *server) watchIntegrations() {
  174. if s.integrations == nil || s.db == nil {
  175. return
  176. }
  177. s.integrations.SetOnExit(func(slug string, exitErr error) {
  178. // Un pusher es un daemon de larga vida: también la salida limpia
  179. // (código 0) es inesperada y deja la fila en estado error con su
  180. // motivo, igual que un arranque fallido.
  181. reason := "pusher exited unexpectedly (exit code 0)"
  182. if exitErr != nil {
  183. reason = exitErr.Error()
  184. }
  185. _ = rintegration.NewStore(s.db.DB).SetState(slug, "error", reason)
  186. s.broadcastIntegrations()
  187. })
  188. s.resumeIntegrations()
  189. }
  190. // resumeIntegrations (#1696) reanuda al arrancar cada integración habilitada.
  191. // En modo local arranca el pusher con el binario ya instalado y el fichero de
  192. // entorno 0600 ya existente (el token y la contraseña solo viven ahí); en
  193. // modo ssh el pusher corre dentro del router y no hay nada que arrancar en el
  194. // servidor, pero el estado guardado deja de decir running (no verificado
  195. // hasta el próximo check/start). Un fallo se loga y deja la fila en estado
  196. // error: nunca tira el arranque del servidor.
  197. func (s *server) resumeIntegrations() {
  198. if s.integrations == nil || s.db == nil {
  199. return
  200. }
  201. store := s.integrationsStore()
  202. rows, err := store.List()
  203. if err != nil {
  204. log.Printf("[netpulse] aviso: integraciones: no se pudo leer la tabla al arrancar (%v)", err)
  205. return
  206. }
  207. for _, row := range rows {
  208. if !row.Enabled {
  209. continue
  210. }
  211. if row.Mode != "local" {
  212. // El proceso vive en el router: sin verificar tras el reinicio
  213. // del servidor; check/start lo reconcilian.
  214. if row.State == "running" {
  215. _ = store.SetState(row.Slug, "unverified", "")
  216. }
  217. continue
  218. }
  219. if s.integrations.Running(row.Slug) {
  220. continue
  221. }
  222. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  223. if !ok {
  224. _ = store.SetState(row.Slug, "error", "unknown vendor "+row.Vendor)
  225. log.Printf("[netpulse] aviso: integración %s con vendor desconocido %q al arrancar", row.Slug, row.Vendor)
  226. continue
  227. }
  228. binPath := filepath.Join(s.integrations.Dir(), row.Slug, vendor.Binary)
  229. if err := s.integrations.Start(row.Slug, nil, binPath); err != nil {
  230. _ = store.SetState(row.Slug, "error", err.Error())
  231. log.Printf("[netpulse] aviso: integración %s no se reanudó al arrancar (%v)", row.Slug, err)
  232. continue
  233. }
  234. _ = store.SetState(row.Slug, "running", "")
  235. _ = store.SetLastStart(row.Slug, time.Now().UnixMilli())
  236. log.Printf("[netpulse] integración %s reanudada al arrancar", row.Slug)
  237. }
  238. s.broadcastIntegrations()
  239. }
  240. func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
  241. writeJSON(w, http.StatusOK, map[string]any{"integrations": s.integrationList()})
  242. }
  243. type integrationCreateBody struct {
  244. Slug string `json:"slug"`
  245. Vendor string `json:"vendor"`
  246. Host string `json:"host"`
  247. Username string `json:"username"`
  248. Password string `json:"password"`
  249. IntervalS int `json:"intervalS"`
  250. Arch string `json:"arch"`
  251. }
  252. func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request) {
  253. if s.db == nil {
  254. writeError(w, http.StatusInternalServerError, "db_error")
  255. return
  256. }
  257. var body integrationCreateBody
  258. if st := readJSONBody(w, r, &body); st != 0 {
  259. writeBodyError(w, st, "invalid_body", `Se esperaba { "slug", "vendor", "host", "username", "password", "intervalS", "arch"? }`)
  260. return
  261. }
  262. if !agentSlugRe.MatchString(body.Slug) {
  263. writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
  264. return
  265. }
  266. vendor, ok := s.vendorCatalog.Lookup(body.Vendor)
  267. if !ok {
  268. writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
  269. return
  270. }
  271. if body.Host == "" || body.Username == "" || body.Password == "" {
  272. writeError(w, http.StatusBadRequest, "invalid_input", "host, username and password are required")
  273. return
  274. }
  275. if body.IntervalS < 10 || body.IntervalS > 86400 {
  276. writeError(w, http.StatusBadRequest, "invalid_interval", "intervalS must be between 10 and 86400")
  277. return
  278. }
  279. arch := body.Arch
  280. if arch == "" {
  281. arch = vendor.Arches[0]
  282. } else if !vendorSupportsArch(vendor, arch) {
  283. writeError(w, http.StatusBadRequest, "invalid_arch", "unsupported arch "+arch)
  284. return
  285. }
  286. store := s.integrationsStore()
  287. if _, exists := store.Get(body.Slug); exists {
  288. writeError(w, http.StatusConflict, "already_exists", "integration already exists")
  289. return
  290. }
  291. // El env que se va a escribir tiene que poder arrancar: con la URL en https
  292. // el pin dejó de ser opcional (#13 en netpulse-integrations), y derivarlo
  293. // exige que este server alcance su propia URL pública. Mejor un 502 aquí,
  294. // sin tocar nada, que un alta que muere al segundo siguiente.
  295. serverURL := s.agentBaseURL(r)
  296. if err := requirePusherPin(serverURL); err != nil {
  297. writeError(w, http.StatusBadGateway, "fingerprint_unreachable", err.Error())
  298. return
  299. }
  300. // Resolver y descargar el último release verificado. En modo local se
  301. // extrae el binario aquí (corre en este host); en modo ssh solo se
  302. // verifica: el router descarga el asset él mismo.
  303. fetch := s.integrationFetcher()
  304. res, err := fetch.ResolveLatest(vendor, arch)
  305. if err != nil {
  306. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  307. return
  308. }
  309. binPath := ""
  310. if vendor.Mode == "local" {
  311. if s.integrations == nil {
  312. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  313. return
  314. }
  315. installDir := filepath.Join(s.integrations.Dir(), body.Slug)
  316. binPath, err = fetch.Download(res, vendor.Binary, installDir)
  317. if err != nil {
  318. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  319. return
  320. }
  321. } else {
  322. if s.pool == nil {
  323. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  324. return
  325. }
  326. if err := fetch.Verify(res); err != nil {
  327. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  328. return
  329. }
  330. }
  331. now := time.Now().UnixMilli()
  332. row := rintegration.Row{
  333. Slug: body.Slug, Vendor: vendor.ID, Mode: vendor.Mode, Host: body.Host,
  334. Username: body.Username, Version: res.Version, Asset: res.AssetName,
  335. Arch: arch, IntervalS: body.IntervalS, Enabled: true, State: "pending",
  336. CreatedAt: now, UpdatedAt: now,
  337. }
  338. if err := store.Upsert(row); err != nil {
  339. writeError(w, http.StatusInternalServerError, "db_error")
  340. return
  341. }
  342. // Router external cuyo id es el slug (push autenticado por token de
  343. // agente, agent.token.<slug>).
  344. router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  345. Name: body.Slug, Host: body.Host, Type: "external", AgentOnly: true,
  346. })
  347. if err != nil || router.ID != body.Slug {
  348. _ = store.Delete(body.Slug)
  349. writeError(w, http.StatusInternalServerError, "router_error")
  350. return
  351. }
  352. s.syncRouters()
  353. rollback := func() {
  354. if vendor.Mode == "local" && s.integrations != nil {
  355. _ = s.integrations.Stop(body.Slug)
  356. _ = s.integrations.Cleanup(body.Slug)
  357. }
  358. _ = routerstore.RemoveRouter(s.db.DB, body.Slug)
  359. s.syncRouters()
  360. _ = store.Delete(body.Slug)
  361. }
  362. token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
  363. env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
  364. if vendor.Mode == "local" {
  365. return s.integrations.Start(body.Slug, env, binPath)
  366. }
  367. return s.runSSHInstall(vendor, row, env, res.URL, res.SHA256)
  368. })
  369. if err != nil {
  370. rollback()
  371. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  372. return
  373. }
  374. _ = store.SetState(body.Slug, "running", "")
  375. _ = store.SetLastStart(body.Slug, time.Now().UnixMilli())
  376. s.broadcastIntegrations()
  377. item, _ := s.getIntegrationRow(body.Slug)
  378. writeJSON(w, http.StatusCreated, map[string]any{
  379. "integration": s.integrationItemOf(item),
  380. "token": token,
  381. })
  382. }
  383. func vendorSupportsArch(v rintegration.Vendor, arch string) bool {
  384. for _, a := range v.Arches {
  385. if a == arch {
  386. return true
  387. }
  388. }
  389. return false
  390. }
  391. // pusherEnv construye el entorno del pusher. En modo ssh el pusher corre en el
  392. // propio router, así que el host del dispositivo es la propia unidad
  393. // (127.0.0.1) en lugar del host SSH de la tabla.
  394. func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password, serverURL, token string) map[string]string {
  395. prefix := strings.ToUpper(v.ID) + "_"
  396. host := row.Host
  397. if v.Mode == "ssh" {
  398. host = "127.0.0.1"
  399. }
  400. env := map[string]string{
  401. prefix + "HOST": host,
  402. prefix + "USER": row.Username,
  403. prefix + "PASS": password,
  404. prefix + "INSECURE": "1",
  405. "NETPULSE_SERVER": serverURL,
  406. "NETPULSE_TOKEN": token,
  407. "NETPULSE_SLUG": row.Slug,
  408. "NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
  409. }
  410. for k, v := range pusherPinEnv(serverURL) {
  411. env[k] = v
  412. }
  413. return env
  414. }
  415. // healPusherPin merges the current server pin into a pusher environment,
  416. // healing files written before the pin requirement and refreshing the pin
  417. // after a certificate reissue. It is a no-op when the server URL needs no
  418. // pin (plain HTTP).
  419. func healPusherPin(env map[string]string, serverURL string) map[string]string {
  420. for k, v := range pusherPinEnv(serverURL) {
  421. env[k] = v
  422. }
  423. return env
  424. }
  425. func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
  426. _, err := s.pool.Run(row.Host, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
  427. return err
  428. }
  429. func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
  430. slug := r.PathValue("slug")
  431. row, ok := s.getIntegrationRow(slug)
  432. if !ok {
  433. writeError(w, http.StatusNotFound, "not_found")
  434. return
  435. }
  436. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  437. if !ok {
  438. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  439. return
  440. }
  441. store := s.integrationsStore()
  442. if vendor.Mode == "local" {
  443. if s.integrations == nil {
  444. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  445. return
  446. }
  447. if !s.integrations.Running(slug) {
  448. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  449. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  450. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  451. return
  452. }
  453. }
  454. } else {
  455. if s.pool == nil {
  456. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  457. return
  458. }
  459. if _, err := s.pool.Run(row.Host, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
  460. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  461. return
  462. }
  463. }
  464. _ = store.SetState(slug, "running", "")
  465. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  466. s.broadcastIntegrations()
  467. item, _ := s.getIntegrationRow(slug)
  468. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  469. }
  470. func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
  471. slug := r.PathValue("slug")
  472. row, ok := s.getIntegrationRow(slug)
  473. if !ok {
  474. writeError(w, http.StatusNotFound, "not_found")
  475. return
  476. }
  477. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  478. if !ok {
  479. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  480. return
  481. }
  482. if vendor.Mode == "local" {
  483. if s.integrations != nil {
  484. _ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
  485. }
  486. } else if s.pool != nil {
  487. _, _ = s.pool.Run(row.Host, sshServiceScript(vendor, "stop"), 60*time.Second)
  488. }
  489. _ = s.integrationsStore().SetState(slug, "stopped", "")
  490. s.broadcastIntegrations()
  491. item, _ := s.getIntegrationRow(slug)
  492. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  493. }
  494. func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request) {
  495. slug := r.PathValue("slug")
  496. row, ok := s.getIntegrationRow(slug)
  497. if !ok {
  498. writeError(w, http.StatusNotFound, "not_found")
  499. return
  500. }
  501. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  502. if !ok {
  503. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  504. return
  505. }
  506. running := false
  507. if vendor.Mode == "local" {
  508. running = s.integrations != nil && s.integrations.Running(slug)
  509. } else if s.pool != nil {
  510. _, err := s.pool.Run(row.Host, sshServiceScript(vendor, "check"), 30*time.Second)
  511. running = err == nil
  512. }
  513. // #1696: un check verificado reconcilia el estado guardado: el unverified
  514. // que deja un reinicio del servidor (o una fila desfasada) vuelve a
  515. // running cuando el proceso está demostradamente vivo.
  516. if running && row.State != "running" {
  517. _ = s.integrationsStore().SetState(slug, "running", "")
  518. s.broadcastIntegrations()
  519. if fresh, ok := s.getIntegrationRow(slug); ok {
  520. row = fresh
  521. }
  522. }
  523. writeJSON(w, http.StatusOK, map[string]any{
  524. "integration": s.integrationItemOf(row),
  525. "running": running,
  526. })
  527. }
  528. func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request) {
  529. slug := r.PathValue("slug")
  530. row, ok := s.getIntegrationRow(slug)
  531. if !ok {
  532. writeError(w, http.StatusNotFound, "not_found")
  533. return
  534. }
  535. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  536. if !ok {
  537. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  538. return
  539. }
  540. fetch := s.integrationFetcher()
  541. res, err := fetch.ResolveLatest(vendor, row.Arch)
  542. if err != nil {
  543. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  544. return
  545. }
  546. store := s.integrationsStore()
  547. if vendor.Mode == "local" {
  548. if s.integrations == nil {
  549. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  550. return
  551. }
  552. _ = s.integrations.Stop(slug)
  553. installDir := filepath.Join(s.integrations.Dir(), slug)
  554. if _, err := fetch.Download(res, vendor.Binary, installDir); err != nil {
  555. _ = store.SetState(slug, "error", err.Error())
  556. s.broadcastIntegrations()
  557. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  558. return
  559. }
  560. // Heal environments created before the pin requirement: the
  561. // refreshed binary refuses to start without it. Best effort, on
  562. // error the old file is reused and the start below reports it.
  563. if env, err := s.integrations.Env(slug); err == nil {
  564. _ = s.integrations.WriteEnv(slug, healPusherPin(env, s.agentBaseURL(r)))
  565. }
  566. if err := s.integrations.Start(slug, nil, filepath.Join(installDir, vendor.Binary)); err != nil {
  567. _ = store.SetState(slug, "error", err.Error())
  568. s.broadcastIntegrations()
  569. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  570. return
  571. }
  572. } else {
  573. if s.pool == nil {
  574. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  575. return
  576. }
  577. if err := fetch.Verify(res); err != nil {
  578. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  579. return
  580. }
  581. env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
  582. if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
  583. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  584. return
  585. }
  586. }
  587. _ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
  588. _ = store.SetState(slug, "running", "")
  589. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  590. s.broadcastIntegrations()
  591. item, _ := s.getIntegrationRow(slug)
  592. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  593. }
  594. // handleIntegrationEdit actualiza los ajustes mutables de una integración sin
  595. // recrearla: host, usuario, contraseña e intervalo. El fichero de entorno se
  596. // lee, se cambian solo las claves afectadas y se reescribe, de modo que el
  597. // token y la contraseña omitida se conservan (nunca viven en la base de datos).
  598. func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
  599. slug := r.PathValue("slug")
  600. row, ok := s.getIntegrationRow(slug)
  601. if !ok {
  602. writeError(w, http.StatusNotFound, "not_found")
  603. return
  604. }
  605. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  606. if !ok {
  607. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  608. return
  609. }
  610. var body struct {
  611. Host *string `json:"host"`
  612. Username *string `json:"username"`
  613. Password *string `json:"password"`
  614. IntervalS *int `json:"intervalS"`
  615. }
  616. if st := readJSONBody(w, r, &body); st != 0 {
  617. writeBodyError(w, st, "invalid_body", "")
  618. return
  619. }
  620. changed := false
  621. if body.Host != nil {
  622. h := strings.TrimSpace(*body.Host)
  623. if h == "" {
  624. writeError(w, http.StatusBadRequest, "invalid_input", "host cannot be empty")
  625. return
  626. }
  627. row.Host = h
  628. changed = true
  629. }
  630. if body.Username != nil {
  631. u := strings.TrimSpace(*body.Username)
  632. if u == "" {
  633. writeError(w, http.StatusBadRequest, "invalid_input", "username cannot be empty")
  634. return
  635. }
  636. row.Username = u
  637. changed = true
  638. }
  639. if body.IntervalS != nil {
  640. if *body.IntervalS < 10 || *body.IntervalS > 86400 {
  641. writeError(w, http.StatusBadRequest, "invalid_interval")
  642. return
  643. }
  644. row.IntervalS = *body.IntervalS
  645. changed = true
  646. }
  647. password := ""
  648. if body.Password != nil {
  649. password = *body.Password
  650. changed = true
  651. }
  652. if !changed {
  653. writeError(w, http.StatusBadRequest, "invalid_input", "nothing to update")
  654. return
  655. }
  656. prefix := strings.ToUpper(vendor.ID) + "_"
  657. host := row.Host
  658. if vendor.Mode == "ssh" {
  659. host = "127.0.0.1"
  660. }
  661. store := s.integrationsStore()
  662. if vendor.Mode == "local" {
  663. if s.integrations == nil {
  664. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  665. return
  666. }
  667. env, err := s.integrations.Env(slug)
  668. if err != nil {
  669. _ = store.SetState(slug, "error", err.Error())
  670. s.broadcastIntegrations()
  671. writeError(w, http.StatusConflict, "env_unavailable", err.Error())
  672. return
  673. }
  674. env[prefix+"HOST"] = host
  675. env[prefix+"USER"] = row.Username
  676. if password != "" {
  677. env[prefix+"PASS"] = password
  678. }
  679. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  680. healPusherPin(env, s.agentBaseURL(r))
  681. if err := s.integrations.WriteEnv(slug, env); err != nil {
  682. _ = store.SetState(slug, "error", err.Error())
  683. s.broadcastIntegrations()
  684. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  685. return
  686. }
  687. _ = s.integrations.Stop(slug)
  688. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  689. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  690. _ = store.SetState(slug, "error", err.Error())
  691. s.broadcastIntegrations()
  692. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  693. return
  694. }
  695. } else {
  696. if s.pool == nil {
  697. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  698. return
  699. }
  700. raw, err := s.pool.Run(row.Host, sshEnvReadScript(vendor), 30*time.Second)
  701. if err != nil {
  702. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  703. return
  704. }
  705. env := rintegration.ParseEnv(raw)
  706. env[prefix+"HOST"] = host
  707. env[prefix+"USER"] = row.Username
  708. if password != "" {
  709. env[prefix+"PASS"] = password
  710. }
  711. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  712. healPusherPin(env, s.agentBaseURL(r))
  713. if _, err := s.pool.Run(row.Host, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
  714. _ = store.SetState(slug, "error", err.Error())
  715. s.broadcastIntegrations()
  716. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  717. return
  718. }
  719. }
  720. if err := store.Upsert(row); err != nil {
  721. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  722. return
  723. }
  724. _ = store.SetState(slug, "running", "")
  725. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  726. s.broadcastIntegrations()
  727. item, _ := s.getIntegrationRow(slug)
  728. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  729. }
  730. func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request) {
  731. slug := r.PathValue("slug")
  732. row, ok := s.getIntegrationRow(slug)
  733. if !ok {
  734. writeError(w, http.StatusNotFound, "not_found")
  735. return
  736. }
  737. vendor, _ := s.vendorCatalog.Lookup(row.Vendor)
  738. if vendor.Mode == "local" {
  739. if s.integrations != nil {
  740. _ = s.integrations.Stop(slug)
  741. _ = s.integrations.Cleanup(slug)
  742. }
  743. } else if s.pool != nil {
  744. _, _ = s.pool.Run(row.Host, sshUninstallScript(vendor), 60*time.Second)
  745. }
  746. _ = s.integrationsStore().Delete(slug)
  747. _ = routerstore.RemoveRouter(s.db.DB, slug)
  748. s.syncRouters()
  749. if s.db != nil {
  750. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
  751. }
  752. s.broadcastIntegrations()
  753. w.WriteHeader(http.StatusNoContent)
  754. }
  755. // ---------------------------------------------------------------------------
  756. // Scripts POSIX de instalación/gestión por SSH (modo ssh, p. ej. asuswrt)
  757. // ---------------------------------------------------------------------------
  758. // envFileBody renders the sorted KEY=value body of an env file, with values
  759. // escaped by EscapeEnvValue for a lossless round-trip through ParseEnv.
  760. func envFileBody(env map[string]string) string {
  761. keys := make([]string, 0, len(env))
  762. for k := range env {
  763. keys = append(keys, k)
  764. }
  765. sort.Strings(keys)
  766. var b strings.Builder
  767. for _, k := range keys {
  768. b.WriteString(k)
  769. b.WriteString("=")
  770. b.WriteString(rintegration.EscapeEnvValue(env[k]))
  771. b.WriteString("\n")
  772. }
  773. return b.String()
  774. }
  775. // sshInstallScript genera el instalador on-router de un vendor en modo ssh.
  776. // Ramifica por el sistema de init del vendor (#1681): procd (layout OpenWrt,
  777. // salida intacta) o merlin (/jffs + bloque gestionado en services-start).
  778. func sshInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  779. if v.InitSystem() == "merlin" {
  780. return sshMerlinInstallScript(v, env, assetURL, sha256)
  781. }
  782. return sshProcdInstallScript(v, env, assetURL, sha256)
  783. }
  784. // sshProcdInstallScript instala el pusher en un vendor OpenWrt: binario en
  785. // /usr/sbin, init procd en /etc/init.d y env en /etc.
  786. func sshProcdInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  787. bin := "/usr/sbin/" + v.Binary
  788. init := "/etc/init.d/" + v.Binary
  789. envFile := "/etc/" + v.Binary + ".env"
  790. envBlock := envFileBody(env)
  791. return `#!/bin/sh
  792. set -e
  793. BIN="` + bin + `"
  794. INIT="` + init + `"
  795. ENV_FILE="` + envFile + `"
  796. SERVER="` + env["NETPULSE_SERVER"] + `"
  797. ASSET_URL="` + assetURL + `"
  798. SHA256="` + sha256 + `"
  799. # Preflight: el router debe alcanzar el server.
  800. if command -v curl >/dev/null 2>&1; then
  801. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  802. else
  803. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  804. fi
  805. # Parar el servicio previo (el proceso vivo mantiene el binario abierto).
  806. [ -x "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
  807. # Descargar el asset desde la URL ya verificada en el server.
  808. if command -v curl >/dev/null 2>&1; then
  809. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  810. else
  811. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  812. fi
  813. # Verificar sha256 antes de instalar.
  814. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  815. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  816. # Extraer y mover de forma atómica (.new -> rename).
  817. mkdir -p /tmp/` + v.Binary + `.extract
  818. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  819. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  820. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  821. cp "$SRC" "$BIN.new"
  822. chmod 0755 "$BIN.new"
  823. mv -f "$BIN.new" "$BIN"
  824. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  825. # Env (chmod 600): solo se escribe en el alta; los updates preservan el
  826. # fichero existente (la contraseña y el token solo viven ahí).
  827. if [ ! -f "$ENV_FILE" ]; then
  828. cat > "$ENV_FILE" <<'ENVEOF'
  829. ` + envBlock + `ENVEOF
  830. chmod 600 "$ENV_FILE"
  831. fi
  832. # Init procd.
  833. cat > "$INIT" <<'INITEOF'
  834. #!/bin/sh /etc/rc.common
  835. START=99
  836. STOP=10
  837. USE_PROCD=1
  838. BIN="/usr/sbin/` + v.Binary + `"
  839. ENV_FILE="/etc/` + v.Binary + `.env"
  840. start_service() {
  841. [ -x "$BIN" ] || return 1
  842. procd_open_instance ` + v.Binary + `
  843. procd_set_param command "$BIN"
  844. procd_set_param respawn 3600 5 5
  845. procd_set_param stdout 1
  846. procd_set_param stderr 1
  847. procd_set_param file "$ENV_FILE"
  848. procd_close_instance
  849. }
  850. INITEOF
  851. chmod 0755 "$INIT"
  852. "$INIT" enable
  853. "$INIT" restart
  854. `
  855. }
  856. // sshMerlinInstallScript instala el pusher en un vendor Asuswrt-Merlin
  857. // (#1681): sin procd, todo bajo /jffs/netpulse (binario, env, script de
  858. // control con pidfile y log) y un bloque gestionado en
  859. // /jffs/scripts/services-start para el arranque al boot. Re-ejecutarlo es
  860. // idempotente: el env solo se escribe si falta y el bloque solo se añade una
  861. // vez; el resto del hook no se toca.
  862. func sshMerlinInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  863. dir := "/jffs/netpulse"
  864. bin := dir + "/" + v.Binary
  865. ctrl := bin + ".sh"
  866. envFile := bin + ".env"
  867. pidFile := bin + ".pid"
  868. logFile := bin + ".log"
  869. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  870. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  871. return `#!/bin/sh
  872. set -e
  873. BIN="` + bin + `"
  874. CTRL="` + ctrl + `"
  875. ENV_FILE="` + envFile + `"
  876. PID_FILE="` + pidFile + `"
  877. LOG_FILE="` + logFile + `"
  878. HOOK="/jffs/scripts/services-start"
  879. SERVER="` + env["NETPULSE_SERVER"] + `"
  880. ASSET_URL="` + assetURL + `"
  881. SHA256="` + sha256 + `"
  882. # Preflight: el router debe alcanzar el server.
  883. if command -v curl >/dev/null 2>&1; then
  884. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  885. else
  886. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  887. fi
  888. # Parar el pusher previo (el proceso vivo mantiene el binario abierto).
  889. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  890. # Descargar el asset desde la URL ya verificada en el server.
  891. if command -v curl >/dev/null 2>&1; then
  892. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  893. else
  894. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  895. fi
  896. # Verificar sha256 antes de instalar.
  897. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  898. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  899. # Extraer y mover de forma atómica (.new -> rename).
  900. mkdir -p /tmp/` + v.Binary + `.extract
  901. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  902. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  903. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  904. mkdir -p "$DIR"
  905. cp "$SRC" "$BIN.new"
  906. chmod 0755 "$BIN.new"
  907. mv -f "$BIN.new" "$BIN"
  908. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  909. # Env (chmod 600): solo se escribe si aún no existe; los updates preservan
  910. # el fichero (la contraseña y el token solo viven ahí).
  911. if [ ! -f "$ENV_FILE" ]; then
  912. cat > "$ENV_FILE" <<'ENVEOF'
  913. ` + envFileBody(env) + `ENVEOF
  914. chmod 600 "$ENV_FILE"
  915. fi
  916. # Script de control con pidfile (start|stop|restart|check). El env guarda
  917. # los valores escapados (salto de línea = \n): printf %b los desescapa igual
  918. # que ParseEnv en el server antes de exportarlos al pusher.
  919. cat > "$CTRL" <<'CTRLEOF'
  920. #!/bin/sh
  921. # NetPulse pusher control script (Asuswrt-Merlin).
  922. BIN="` + bin + `"
  923. PID_FILE="` + pidFile + `"
  924. ENV_FILE="` + envFile + `"
  925. LOG_FILE="` + logFile + `"
  926. running() {
  927. [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
  928. }
  929. case "$1" in
  930. start)
  931. [ -x "$BIN" ] || { echo "netpulse: missing $BIN"; exit 1; }
  932. if running; then
  933. exit 0
  934. fi
  935. rm -f "$PID_FILE"
  936. [ -f "$ENV_FILE" ] || { echo "netpulse: missing $ENV_FILE"; exit 1; }
  937. while IFS= read -r line || [ -n "$line" ]; do
  938. case "$line" in ""|\#*) continue ;; esac
  939. k=${line%%=*}
  940. val=${line#*=}
  941. val=$(printf '%b' "$val")
  942. export "$k=$val"
  943. done < "$ENV_FILE"
  944. nohup "$BIN" >> "$LOG_FILE" 2>&1 &
  945. echo $! > "$PID_FILE"
  946. ;;
  947. stop)
  948. if [ -f "$PID_FILE" ]; then
  949. RUN_PID=$(cat "$PID_FILE")
  950. kill "$RUN_PID" 2>/dev/null || true
  951. n=0
  952. while kill -0 "$RUN_PID" 2>/dev/null && [ "$n" -lt 10 ]; do
  953. sleep 1
  954. n=$((n+1))
  955. done
  956. if kill -0 "$RUN_PID" 2>/dev/null; then
  957. kill -9 "$RUN_PID" 2>/dev/null || true
  958. fi
  959. rm -f "$PID_FILE"
  960. fi
  961. ;;
  962. restart)
  963. "$0" stop
  964. "$0" start
  965. ;;
  966. check)
  967. if running; then
  968. exit 0
  969. fi
  970. exit 1
  971. ;;
  972. *)
  973. echo "usage: $0 {start|stop|restart|check}"
  974. exit 2
  975. ;;
  976. esac
  977. CTRLEOF
  978. chmod 0755 "$CTRL"
  979. # Arranque al boot: bloque gestionado en services-start, delimitado por
  980. # marcadores únicos para poder quitarlo sin tocar el resto del fichero.
  981. mkdir -p /jffs/scripts
  982. if [ ! -f "$HOOK" ]; then
  983. printf '#!/bin/sh\n' > "$HOOK"
  984. fi
  985. chmod 0755 "$HOOK"
  986. if ! grep -qF '` + blockStart + `' "$HOOK" 2>/dev/null; then
  987. cat >> "$HOOK" <<'BLOKEOF'
  988. ` + blockStart + `
  989. ` + ctrl + ` start
  990. ` + blockEnd + `
  991. BLOKEOF
  992. fi
  993. "$CTRL" start
  994. `
  995. }
  996. // sshEnvReadScript prints the environment file of an integration running
  997. // inside the router, so the server can merge changes without ever storing the
  998. // token or the password. Merlin vendors keep the env under /jffs/netpulse.
  999. func sshEnvReadScript(v rintegration.Vendor) string {
  1000. if v.InitSystem() == "merlin" {
  1001. return "cat /jffs/netpulse/" + v.Binary + ".env"
  1002. }
  1003. return "cat /etc/" + v.Binary + ".env"
  1004. }
  1005. // sshEnvWriteScript replaces the environment file inside the router and
  1006. // restarts the service. Values come already escaped by EscapeEnvValue and the
  1007. // heredoc is quoted, so the shell does not expand anything.
  1008. func sshEnvWriteScript(v rintegration.Vendor, env map[string]string) string {
  1009. envBlock := envFileBody(env)
  1010. if v.InitSystem() == "merlin" {
  1011. envFile := "/jffs/netpulse/" + v.Binary + ".env"
  1012. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1013. return `#!/bin/sh
  1014. set -e
  1015. ENV_FILE="` + envFile + `"
  1016. CTRL="` + ctrl + `"
  1017. cat > "$ENV_FILE.new" <<'ENVEOF'
  1018. ` + envBlock + `ENVEOF
  1019. chmod 600 "$ENV_FILE.new"
  1020. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1021. if [ -x "$CTRL" ]; then
  1022. "$CTRL" restart >/dev/null 2>&1 || true
  1023. fi
  1024. `
  1025. }
  1026. init := "/etc/init.d/" + v.Binary
  1027. envFile := "/etc/" + v.Binary + ".env"
  1028. return `#!/bin/sh
  1029. set -e
  1030. INIT="` + init + `"
  1031. ENV_FILE="` + envFile + `"
  1032. cat > "$ENV_FILE.new" <<'ENVEOF'
  1033. ` + envBlock + `ENVEOF
  1034. chmod 600 "$ENV_FILE.new"
  1035. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1036. if [ -x "$INIT" ]; then
  1037. "$INIT" stop >/dev/null 2>&1 || true
  1038. "$INIT" start >/dev/null 2>&1 || true
  1039. fi
  1040. `
  1041. }
  1042. func sshServiceScript(v rintegration.Vendor, action string) string {
  1043. if v.InitSystem() == "merlin" {
  1044. // Merlin no tiene procd: las acciones van al script de control
  1045. // con pidfile. check sigue siendo pgrep para no cambiar el camino
  1046. // de salud del handler.
  1047. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1048. switch action {
  1049. case "start":
  1050. return "test -x " + ctrl + " && " + ctrl + " start || true"
  1051. case "stop":
  1052. return "test -x " + ctrl + " && " + ctrl + " stop || true"
  1053. case "restart":
  1054. return "test -x " + ctrl + " && " + ctrl + " restart || true"
  1055. case "check":
  1056. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1057. }
  1058. return "true"
  1059. }
  1060. init := "/etc/init.d/" + v.Binary
  1061. switch action {
  1062. case "start":
  1063. return "test -x " + init + " && " + init + " enable && " + init + " start || true"
  1064. case "stop":
  1065. return "test -x " + init + " && " + init + " stop || true"
  1066. case "restart":
  1067. return "test -x " + init + " && " + init + " restart || true"
  1068. case "check":
  1069. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1070. }
  1071. return "true"
  1072. }
  1073. func sshUninstallScript(v rintegration.Vendor) string {
  1074. if v.InitSystem() == "merlin" {
  1075. return sshMerlinUninstallScript(v)
  1076. }
  1077. init := "/etc/init.d/" + v.Binary
  1078. bin := "/usr/sbin/" + v.Binary
  1079. envFile := "/etc/" + v.Binary + ".env"
  1080. return fmt.Sprintf(
  1081. "test -x %s && %s stop || true; test -x %s && %s disable || true; rm -f %s %s %s",
  1082. init, init, init, init, init, bin, envFile,
  1083. )
  1084. }
  1085. // sshMerlinUninstallScript para el pusher con su script de control, quita el
  1086. // bloque gestionado de services-start (el resto del hook queda intacto) y
  1087. // borra /jffs/netpulse entero.
  1088. func sshMerlinUninstallScript(v rintegration.Vendor) string {
  1089. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1090. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1091. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1092. return `CTRL="` + ctrl + `"
  1093. HOOK="/jffs/scripts/services-start"
  1094. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1095. if [ -f "$HOOK" ]; then
  1096. sed -i '/` + blockStart + `/,/` + blockEnd + `/d' "$HOOK" 2>/dev/null || true
  1097. fi
  1098. rm -rf /jffs/netpulse
  1099. `
  1100. }