integrations.go 20 KB

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