| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318 |
- // integrations.go — API de integraciones externas de routers (#1674):
- // pushers de routers externos (MikroTik RouterOS, Asuswrt) gestionados desde
- // la app con el contrato de agente externo. El slug de la integración es el
- // id del router external asociado, así el push del pusher (POST
- // /api/ingest/agent con Bearer token) se atribuye a la misma unidad.
- package httpapi
- import (
- "context"
- "errors"
- "fmt"
- "log"
- "net/http"
- "path/filepath"
- "sort"
- "strconv"
- "strings"
- "time"
- "github.com/gnacho/netpulse/server-go/internal/adapters"
- "github.com/gnacho/netpulse/server-go/internal/auth"
- "github.com/gnacho/netpulse/server-go/internal/rintegration"
- "github.com/gnacho/netpulse/server-go/internal/routerstore"
- )
- // integrationItem es la vista HTTP de una integración (nunca la contraseña).
- type integrationItem struct {
- Slug string `json:"slug"`
- Vendor string `json:"vendor"`
- Mode string `json:"mode"`
- Host string `json:"host"`
- Username string `json:"username"`
- Version string `json:"version"`
- Arch string `json:"arch"`
- IntervalS int `json:"intervalS"`
- Enabled bool `json:"enabled"`
- State string `json:"state"`
- LastError string `json:"lastError"`
- // OfflineReason (#1718): código estable del motivo por el que la unidad
- // no está empujando (mismos códigos que la tarjeta y el detalle desde
- // #1714). Vacío si está empujando, pausada o sin señal clara.
- OfflineReason string `json:"offlineReason,omitempty"`
- LastStartMs int64 `json:"lastStartMs"`
- LastPushMs int64 `json:"lastPushMs"`
- Fresh bool `json:"fresh"`
- }
- // vendorView es la vista HTTP del manifiesto de un vendor.
- type vendorView struct {
- ID string `json:"id"`
- Mode string `json:"mode"`
- Arches []string `json:"arches"`
- TagPrefix string `json:"tagPrefix"`
- Description string `json:"description"`
- }
- // registerIntegrationRoutes registra las rutas /api/integrations/*. Todas
- // exigen rol admin salvo el GET de vendors (solo sesión).
- func (s *server) registerIntegrationRoutes(mux *http.ServeMux) {
- mux.HandleFunc("GET /api/integrations/vendors", s.handleIntegrationsVendors)
- mux.Handle("POST /api/integrations/vendors/refresh", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsVendorsRefresh)))
- mux.Handle("GET /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsList)))
- mux.Handle("POST /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsCreate)))
- mux.Handle("POST /api/integrations/{slug}/start", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStart)))
- mux.Handle("POST /api/integrations/{slug}/stop", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStop)))
- mux.Handle("POST /api/integrations/{slug}/check", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationCheck)))
- mux.Handle("POST /api/integrations/{slug}/update", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationUpdate)))
- mux.Handle("PUT /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationEdit)))
- mux.Handle("DELETE /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationDelete)))
- }
- // vendorCatalogRefreshTimeout acota el fetch forzado del endpoint admin.
- const vendorCatalogRefreshTimeout = 15 * time.Second
- func (s *server) handleIntegrationsVendors(w http.ResponseWriter, r *http.Request) {
- vs := s.vendorCatalog.Vendors(r.Context())
- writeJSON(w, http.StatusOK, map[string]any{
- "vendors": vendorViews(vs),
- "lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
- })
- }
- // handleIntegrationsVendorsRefresh fuerza el descubrimiento del catálogo
- // (#1697): fetch inmediato, caché actualizada y catálogo devuelto en la
- // misma respuesta para que la UI no encadene un segundo GET. Un fallo de
- // fetch o de validación deja el catálogo anterior en su sitio (502).
- func (s *server) handleIntegrationsVendorsRefresh(w http.ResponseWriter, r *http.Request) {
- if s.db == nil || s.vendorCatalog == nil {
- writeError(w, http.StatusServiceUnavailable, "unavailable", "vendor catalog is not available without a database")
- return
- }
- ctx, cancel := context.WithTimeout(r.Context(), vendorCatalogRefreshTimeout)
- defer cancel()
- if err := s.vendorCatalog.Refresh(ctx); err != nil {
- writeError(w, http.StatusBadGateway, "refresh_failed", err.Error())
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "vendors": vendorViews(s.vendorCatalog.Current()),
- "lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
- })
- }
- // vendorViews es la vista HTTP del catálogo: mismos campos que servía el
- // manifiesto estático para no romper el contrato con la UI.
- func vendorViews(vs []rintegration.Vendor) []vendorView {
- out := make([]vendorView, 0, len(vs))
- for _, v := range vs {
- out = append(out, vendorView{
- ID: v.ID, Mode: v.Mode, Arches: v.Arches,
- TagPrefix: v.TagPrefix, Description: v.Description,
- })
- }
- return out
- }
- func (s *server) integrationsStore() *rintegration.Store {
- return rintegration.NewStore(s.db.DB)
- }
- func (s *server) integrationFetcher() *rintegration.Fetcher {
- if s.integrations != nil {
- return s.integrations.Fetch()
- }
- return rintegration.NewFetcher()
- }
- func (s *server) getIntegrationRow(slug string) (rintegration.Row, bool) {
- if s.db == nil {
- return rintegration.Row{}, false
- }
- return s.integrationsStore().Get(slug)
- }
- // integrationLastPushMs lee agent.last_push_ts.<slug> (segundos unix) y lo
- // devuelve en milisegundos, 0 si nunca empujó.
- func (s *server) integrationLastPushMs(slug string) int64 {
- if s.db == nil {
- return 0
- }
- sec, err := strconv.ParseInt(kvGet(s.db.DB, "agent.last_push_ts."+slug), 10, 64)
- if err != nil {
- return 0
- }
- return sec * 1000
- }
- func (s *server) integrationItemOf(row rintegration.Row) integrationItem {
- lastPush := s.integrationLastPushMs(row.Slug)
- fresh := false
- if lastPush > 0 && row.IntervalS > 0 {
- fresh = time.Now().UnixMilli()-lastPush <= int64(row.IntervalS)*3*1000
- }
- // #1696: reconciliar al leer. Una fila en running cuyo último push es más
- // viejo que 3 intervalos no puede ir de sana: la vista la reporta como
- // "stale". Es solo vista (la fila no se toca): en cuanto el pusher vuelva
- // a empujar, el propio cálculo la devuelve a "running".
- state := row.State
- if state == "running" && lastPush > 0 && row.IntervalS > 0 && !fresh {
- state = "stale"
- }
- return integrationItem{
- Slug: row.Slug, Vendor: row.Vendor, Mode: row.Mode, Host: row.Host,
- Username: row.Username, Version: row.Version, Arch: row.Arch,
- IntervalS: row.IntervalS, Enabled: row.Enabled, State: state,
- LastError: row.LastError, LastStartMs: row.LastStartMs,
- LastPushMs: lastPush, Fresh: fresh,
- OfflineReason: s.integrationOfflineReason(row, fresh),
- }
- }
- // integrationOfflineReason (#1718) clasifica por qué una integración no está
- // empujando, con los mismos códigos y la misma precedencia que StatusReasons
- // en el paquete rintegration (que alimenta la tarjeta y el detalle): parada
- // explícita, último error de instalación, o el log del pusher para fallos de
- // poll. Pausada o fresca no tienen motivo.
- func (s *server) integrationOfflineReason(row rintegration.Row, fresh bool) string {
- if !row.Enabled {
- return ""
- }
- if row.State == "stopped" {
- return rintegration.ReasonStopped
- }
- if fresh {
- return ""
- }
- code := ""
- if row.State == "error" && row.LastError != "" {
- code = rintegration.ClassifyPollError(row.LastError)
- }
- if (code == "" || code == rintegration.ReasonError) && s.integrations != nil {
- if msg := s.integrations.LastPollError(row.Slug); msg != "" {
- code = rintegration.ClassifyPollError(msg)
- }
- }
- return code
- }
- func (s *server) integrationList() []integrationItem {
- if s.db == nil {
- return []integrationItem{}
- }
- rows, err := s.integrationsStore().List()
- if err != nil {
- return []integrationItem{}
- }
- out := make([]integrationItem, 0, len(rows))
- for _, row := range rows {
- out = append(out, s.integrationItemOf(row))
- }
- return out
- }
- func (s *server) broadcastIntegrations() {
- if s.hub != nil {
- s.hub.Broadcast("integrations", map[string]any{"integrations": s.integrationList()})
- }
- }
- // watchIntegrations (#1696) registra el callback de salida inesperada de los
- // pushers locales (#1674) y reanuda al arrancar las integraciones habilitadas.
- // No-op sin supervisor o sin base de datos (demo). Los paros intencionales no
- // pasan por el callback: los gestiona el handler de stop.
- func (s *server) watchIntegrations() {
- if s.integrations == nil || s.db == nil {
- return
- }
- s.integrations.SetOnExit(func(slug string, exitErr error) {
- // Un pusher es un daemon de larga vida: también la salida limpia
- // (código 0) es inesperada y deja la fila en estado error con su
- // motivo, igual que un arranque fallido.
- reason := "pusher exited unexpectedly (exit code 0)"
- if exitErr != nil {
- reason = exitErr.Error()
- }
- _ = rintegration.NewStore(s.db.DB).SetState(slug, "error", reason)
- s.broadcastIntegrations()
- })
- s.resumeIntegrations()
- }
- // resumeIntegrations (#1696) reanuda al arrancar cada integración habilitada.
- // En modo local arranca el pusher con el binario ya instalado y el fichero de
- // entorno 0600 ya existente (el token y la contraseña solo viven ahí); en
- // modo ssh el pusher corre dentro del router y no hay nada que arrancar en el
- // servidor, pero el estado guardado deja de decir running (no verificado
- // hasta el próximo check/start). Un fallo se loga y deja la fila en estado
- // error: nunca tira el arranque del servidor.
- func (s *server) resumeIntegrations() {
- if s.integrations == nil || s.db == nil {
- return
- }
- store := s.integrationsStore()
- rows, err := store.List()
- if err != nil {
- log.Printf("[netpulse] aviso: integraciones: no se pudo leer la tabla al arrancar (%v)", err)
- return
- }
- for _, row := range rows {
- if !row.Enabled {
- continue
- }
- if row.Mode != "local" {
- // El proceso vive en el router: sin verificar tras el reinicio
- // del servidor; check/start lo reconcilian.
- if row.State == "running" {
- _ = store.SetState(row.Slug, "unverified", "")
- }
- continue
- }
- if s.integrations.Running(row.Slug) {
- continue
- }
- vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
- if !ok {
- _ = store.SetState(row.Slug, "error", "unknown vendor "+row.Vendor)
- log.Printf("[netpulse] aviso: integración %s con vendor desconocido %q al arrancar", row.Slug, row.Vendor)
- continue
- }
- binPath := filepath.Join(s.integrations.Dir(), row.Slug, vendor.Binary)
- if err := s.integrations.Start(row.Slug, nil, binPath); err != nil {
- _ = store.SetState(row.Slug, "error", err.Error())
- log.Printf("[netpulse] aviso: integración %s no se reanudó al arrancar (%v)", row.Slug, err)
- continue
- }
- _ = store.SetState(row.Slug, "running", "")
- _ = store.SetLastStart(row.Slug, time.Now().UnixMilli())
- log.Printf("[netpulse] integración %s reanudada al arrancar", row.Slug)
- }
- s.broadcastIntegrations()
- }
- func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
- writeJSON(w, http.StatusOK, map[string]any{"integrations": s.integrationList()})
- }
- type integrationCreateBody struct {
- Slug string `json:"slug"`
- Vendor string `json:"vendor"`
- Host string `json:"host"`
- Username string `json:"username"`
- Password string `json:"password"`
- IntervalS int `json:"intervalS"`
- Arch string `json:"arch"`
- }
- func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request) {
- if s.db == nil {
- writeError(w, http.StatusInternalServerError, "db_error")
- return
- }
- var body integrationCreateBody
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", `Se esperaba { "slug", "vendor", "host", "username", "password", "intervalS", "arch"? }`)
- return
- }
- if !agentSlugRe.MatchString(body.Slug) {
- writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
- return
- }
- vendor, ok := s.vendorCatalog.Lookup(body.Vendor)
- if !ok {
- writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
- return
- }
- if body.Host == "" || body.Username == "" || body.Password == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "host, username and password are required")
- return
- }
- if body.IntervalS < 10 || body.IntervalS > 86400 {
- writeError(w, http.StatusBadRequest, "invalid_interval", "intervalS must be between 10 and 86400")
- return
- }
- arch := body.Arch
- if arch == "" {
- arch = vendor.Arches[0]
- } else if !vendorSupportsArch(vendor, arch) {
- writeError(w, http.StatusBadRequest, "invalid_arch", "unsupported arch "+arch)
- return
- }
- store := s.integrationsStore()
- if _, exists := store.Get(body.Slug); exists {
- writeError(w, http.StatusConflict, "already_exists", "integration already exists")
- return
- }
- // El env que se va a escribir tiene que poder arrancar: con la URL en https
- // el pin dejó de ser opcional (#13 en netpulse-integrations), y derivarlo
- // exige que este server alcance su propia URL pública. Mejor un 502 aquí,
- // sin tocar nada, que un alta que muere al segundo siguiente.
- serverURL := s.agentBaseURL(r)
- if err := requirePusherPin(serverURL); err != nil {
- writeError(w, http.StatusBadGateway, "fingerprint_unreachable", err.Error())
- return
- }
- // Resolver y descargar el último release verificado. En modo local se
- // extrae el binario aquí (corre en este host); en modo ssh solo se
- // verifica: el router descarga el asset él mismo.
- fetch := s.integrationFetcher()
- res, err := fetch.ResolveLatest(vendor, arch)
- if err != nil {
- writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
- return
- }
- binPath := ""
- if vendor.Mode == "local" {
- if s.integrations == nil {
- writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
- return
- }
- installDir := filepath.Join(s.integrations.Dir(), body.Slug)
- binPath, err = fetch.Download(res, vendor.Binary, installDir)
- if err != nil {
- writeError(w, http.StatusBadGateway, "download_failed", err.Error())
- return
- }
- } else {
- if s.pool == nil {
- writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
- return
- }
- if err := fetch.Verify(res); err != nil {
- writeError(w, http.StatusBadGateway, "download_failed", err.Error())
- return
- }
- }
- now := time.Now().UnixMilli()
- row := rintegration.Row{
- Slug: body.Slug, Vendor: vendor.ID, Mode: vendor.Mode, Host: body.Host,
- Username: body.Username, Version: res.Version, Asset: res.AssetName,
- Arch: arch, IntervalS: body.IntervalS, Enabled: true, State: "pending",
- CreatedAt: now, UpdatedAt: now,
- }
- if err := store.Upsert(row); err != nil {
- writeError(w, http.StatusInternalServerError, "db_error")
- return
- }
- // #1708: en modo ssh la misma contraseña del formulario es la credencial
- // SSH del alta y de las acciones posteriores: se guarda en el fichero
- // compañero (0600) antes de conectar, nunca en la base de datos.
- if vendor.Mode == "ssh" && s.integrations != nil {
- if err := s.integrations.WriteSSHPassword(body.Slug, body.Password); err != nil {
- _ = store.Delete(body.Slug)
- writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
- return
- }
- }
- // Router external cuyo id es el slug (push autenticado por token de
- // agente, agent.token.<slug>).
- router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
- Name: body.Slug, Host: body.Host, Type: "external", AgentOnly: true,
- })
- if err != nil || router.ID != body.Slug {
- _ = store.Delete(body.Slug)
- writeError(w, http.StatusInternalServerError, "router_error")
- return
- }
- s.syncRouters()
- rollback := func() {
- if vendor.Mode == "local" && s.integrations != nil {
- _ = s.integrations.Stop(body.Slug)
- _ = s.integrations.Cleanup(body.Slug)
- }
- if vendor.Mode == "ssh" && s.integrations != nil {
- _ = s.integrations.RemoveSSHPassword(body.Slug)
- }
- _ = routerstore.RemoveRouter(s.db.DB, body.Slug)
- s.syncRouters()
- _ = store.Delete(body.Slug)
- }
- token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
- env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
- if vendor.Mode == "local" {
- return s.integrations.Start(body.Slug, env, binPath)
- }
- return s.runSSHInstall(vendor, row, env, res.URL, res.SHA256)
- })
- if err != nil {
- rollback()
- writeError(w, http.StatusBadGateway, sshErrorOr(err, "start_failed"), err.Error())
- return
- }
- _ = store.SetState(body.Slug, "running", "")
- _ = store.SetLastStart(body.Slug, time.Now().UnixMilli())
- s.broadcastIntegrations()
- item, _ := s.getIntegrationRow(body.Slug)
- writeJSON(w, http.StatusCreated, map[string]any{
- "integration": s.integrationItemOf(item),
- "token": token,
- })
- }
- func vendorSupportsArch(v rintegration.Vendor, arch string) bool {
- for _, a := range v.Arches {
- if a == arch {
- return true
- }
- }
- return false
- }
- // pusherEnv construye el entorno del pusher. En modo ssh el pusher corre en el
- // propio router, así que el host del dispositivo es la propia unidad
- // (127.0.0.1) en lugar del host SSH de la tabla.
- func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password, serverURL, token string) map[string]string {
- prefix := strings.ToUpper(v.ID) + "_"
- host := row.Host
- if v.Mode == "ssh" {
- host = "127.0.0.1"
- }
- env := map[string]string{
- prefix + "HOST": host,
- prefix + "USER": row.Username,
- prefix + "PASS": password,
- prefix + "INSECURE": "1",
- "NETPULSE_SERVER": serverURL,
- "NETPULSE_TOKEN": token,
- "NETPULSE_SLUG": row.Slug,
- "NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
- }
- for k, v := range pusherPinEnv(serverURL) {
- env[k] = v
- }
- return env
- }
- // healPusherPin merges the current server pin into a pusher environment,
- // healing files written before the pin requirement and refreshing the pin
- // after a certificate reissue. It is a no-op when the server URL needs no
- // pin (plain HTTP).
- func healPusherPin(env map[string]string, serverURL string) map[string]string {
- for k, v := range pusherPinEnv(serverURL) {
- env[k] = v
- }
- return env
- }
- func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
- _, err := s.runIntegrationSSH(row, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
- return err
- }
- // sshPasswordSetter es la capacidad opcional del pool SSH de conectar por
- // contraseña (#1708). adapters.SSHPool la implementa; los fakes de tests que
- // solo implementan Run no, y en ese caso el pool queda como esté.
- type sshPasswordSetter interface {
- SetPassword(host, user, password string)
- }
- // applyIntegrationSSHAuth aplica al pool la credencial SSH de la
- // integración (#1708): si existe el fichero compañero <slug>.sshpass la
- // conexión va por contraseña con el usuario de la fila (gana sobre la llave
- // del servidor); si no, la credencial se limpia y el dial usa la llave como
- // siempre. Un fichero ilegible cae a llave con aviso en el log.
- func (s *server) applyIntegrationSSHAuth(row rintegration.Row) {
- if s.pool == nil || s.integrations == nil {
- return
- }
- setter, ok := s.pool.(sshPasswordSetter)
- if !ok {
- return
- }
- pass, err := s.integrations.ReadSSHPassword(row.Slug)
- if err != nil {
- log.Printf("[netpulse] aviso: integración %s: no se pudo leer el fichero de contraseña SSH (%v); conecto con llave", row.Slug, err)
- pass = ""
- }
- setter.SetPassword(row.Host, row.Username, pass)
- }
- // runIntegrationSSH ejecuta un comando en el router de la integración
- // aplicando antes la credencial SSH del fichero compañero (#1708).
- func (s *server) runIntegrationSSH(row rintegration.Row, cmd string, timeout time.Duration) (string, error) {
- s.applyIntegrationSSHAuth(row)
- return s.pool.Run(row.Host, cmd, timeout)
- }
- // sshErrorCode clasifica un error SSH para la API (#1708): el rechazo de
- // autenticación es su propio código (ssh_auth_failed) frente al fallo
- // genérico de conexión (ssh_failed), de modo que la UI puede pedir revisar
- // la contraseña.
- func sshErrorCode(err error) string {
- var ae *adapters.SSHAuthError
- if errors.As(err, &ae) {
- return "ssh_auth_failed"
- }
- return "ssh_failed"
- }
- // sshErrorOr devuelve ssh_auth_failed cuando err es un rechazo de
- // autenticación SSH y fallback para cualquier otro error.
- func sshErrorOr(err error, fallback string) string {
- if sshErrorCode(err) == "ssh_auth_failed" {
- return "ssh_auth_failed"
- }
- return fallback
- }
- func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
- slug := r.PathValue("slug")
- row, ok := s.getIntegrationRow(slug)
- if !ok {
- writeError(w, http.StatusNotFound, "not_found")
- return
- }
- vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
- if !ok {
- writeError(w, http.StatusInternalServerError, "invalid_vendor")
- return
- }
- store := s.integrationsStore()
- if vendor.Mode == "local" {
- if s.integrations == nil {
- writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
- return
- }
- if !s.integrations.Running(slug) {
- binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
- if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
- writeError(w, http.StatusBadGateway, "start_failed", err.Error())
- return
- }
- }
- } else {
- if s.pool == nil {
- writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
- return
- }
- if _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
- writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
- return
- }
- }
- _ = store.SetState(slug, "running", "")
- _ = store.SetLastStart(slug, time.Now().UnixMilli())
- s.broadcastIntegrations()
- item, _ := s.getIntegrationRow(slug)
- writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
- }
- func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
- slug := r.PathValue("slug")
- row, ok := s.getIntegrationRow(slug)
- if !ok {
- writeError(w, http.StatusNotFound, "not_found")
- return
- }
- vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
- if !ok {
- writeError(w, http.StatusInternalServerError, "invalid_vendor")
- return
- }
- if vendor.Mode == "local" {
- if s.integrations != nil {
- _ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
- }
- } else if s.pool != nil {
- _, _ = s.runIntegrationSSH(row, sshServiceScript(vendor, "stop"), 60*time.Second)
- }
- _ = s.integrationsStore().SetState(slug, "stopped", "")
- s.broadcastIntegrations()
- item, _ := s.getIntegrationRow(slug)
- writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
- }
- func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request) {
- slug := r.PathValue("slug")
- row, ok := s.getIntegrationRow(slug)
- if !ok {
- writeError(w, http.StatusNotFound, "not_found")
- return
- }
- vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
- if !ok {
- writeError(w, http.StatusInternalServerError, "invalid_vendor")
- return
- }
- running := false
- if vendor.Mode == "local" {
- running = s.integrations != nil && s.integrations.Running(slug)
- } else if s.pool != nil {
- _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "check"), 30*time.Second)
- running = err == nil
- }
- // #1696: un check verificado reconcilia el estado guardado: el unverified
- // que deja un reinicio del servidor (o una fila desfasada) vuelve a
- // running cuando el proceso está demostradamente vivo.
- if running && row.State != "running" {
- _ = s.integrationsStore().SetState(slug, "running", "")
- s.broadcastIntegrations()
- if fresh, ok := s.getIntegrationRow(slug); ok {
- row = fresh
- }
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "integration": s.integrationItemOf(row),
- "running": running,
- })
- }
- func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request) {
- slug := r.PathValue("slug")
- row, ok := s.getIntegrationRow(slug)
- if !ok {
- writeError(w, http.StatusNotFound, "not_found")
- return
- }
- vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
- if !ok {
- writeError(w, http.StatusInternalServerError, "invalid_vendor")
- return
- }
- fetch := s.integrationFetcher()
- res, err := fetch.ResolveLatest(vendor, row.Arch)
- if err != nil {
- writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
- return
- }
- store := s.integrationsStore()
- if vendor.Mode == "local" {
- if s.integrations == nil {
- writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
- return
- }
- _ = s.integrations.Stop(slug)
- installDir := filepath.Join(s.integrations.Dir(), slug)
- if _, err := fetch.Download(res, vendor.Binary, installDir); err != nil {
- _ = store.SetState(slug, "error", err.Error())
- s.broadcastIntegrations()
- writeError(w, http.StatusBadGateway, "download_failed", err.Error())
- return
- }
- // Heal environments created before the pin requirement: the
- // refreshed binary refuses to start without it. Best effort, on
- // error the old file is reused and the start below reports it.
- if env, err := s.integrations.Env(slug); err == nil {
- _ = s.integrations.WriteEnv(slug, healPusherPin(env, s.agentBaseURL(r)))
- }
- if err := s.integrations.Start(slug, nil, filepath.Join(installDir, vendor.Binary)); err != nil {
- _ = store.SetState(slug, "error", err.Error())
- s.broadcastIntegrations()
- writeError(w, http.StatusBadGateway, "start_failed", err.Error())
- return
- }
- } else {
- if s.pool == nil {
- writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
- return
- }
- if err := fetch.Verify(res); err != nil {
- writeError(w, http.StatusBadGateway, "download_failed", err.Error())
- return
- }
- env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
- if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
- writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
- return
- }
- }
- _ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
- _ = store.SetState(slug, "running", "")
- _ = store.SetLastStart(slug, time.Now().UnixMilli())
- s.broadcastIntegrations()
- item, _ := s.getIntegrationRow(slug)
- writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
- }
- // handleIntegrationEdit actualiza los ajustes mutables de una integración sin
- // recrearla: host, usuario, contraseña e intervalo. El fichero de entorno se
- // lee, se cambian solo las claves afectadas y se reescribe, de modo que el
- // token y la contraseña omitida se conservan (nunca viven en la base de datos).
- func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
- slug := r.PathValue("slug")
- row, ok := s.getIntegrationRow(slug)
- if !ok {
- writeError(w, http.StatusNotFound, "not_found")
- return
- }
- vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
- if !ok {
- writeError(w, http.StatusInternalServerError, "invalid_vendor")
- return
- }
- var body struct {
- Host *string `json:"host"`
- Username *string `json:"username"`
- Password *string `json:"password"`
- IntervalS *int `json:"intervalS"`
- }
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "")
- return
- }
- changed := false
- if body.Host != nil {
- h := strings.TrimSpace(*body.Host)
- if h == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "host cannot be empty")
- return
- }
- row.Host = h
- changed = true
- }
- if body.Username != nil {
- u := strings.TrimSpace(*body.Username)
- if u == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "username cannot be empty")
- return
- }
- row.Username = u
- changed = true
- }
- if body.IntervalS != nil {
- if *body.IntervalS < 10 || *body.IntervalS > 86400 {
- writeError(w, http.StatusBadRequest, "invalid_interval")
- return
- }
- row.IntervalS = *body.IntervalS
- changed = true
- }
- password := ""
- if body.Password != nil {
- password = *body.Password
- changed = true
- }
- if !changed {
- writeError(w, http.StatusBadRequest, "invalid_input", "nothing to update")
- return
- }
- prefix := strings.ToUpper(vendor.ID) + "_"
- host := row.Host
- if vendor.Mode == "ssh" {
- host = "127.0.0.1"
- }
- store := s.integrationsStore()
- if vendor.Mode == "local" {
- if s.integrations == nil {
- writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
- return
- }
- env, err := s.integrations.Env(slug)
- if err != nil {
- _ = store.SetState(slug, "error", err.Error())
- s.broadcastIntegrations()
- writeError(w, http.StatusConflict, "env_unavailable", err.Error())
- return
- }
- env[prefix+"HOST"] = host
- env[prefix+"USER"] = row.Username
- if password != "" {
- env[prefix+"PASS"] = password
- }
- env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
- healPusherPin(env, s.agentBaseURL(r))
- if err := s.integrations.WriteEnv(slug, env); err != nil {
- _ = store.SetState(slug, "error", err.Error())
- s.broadcastIntegrations()
- writeError(w, http.StatusInternalServerError, "db_error", err.Error())
- return
- }
- _ = s.integrations.Stop(slug)
- binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
- if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
- _ = store.SetState(slug, "error", err.Error())
- s.broadcastIntegrations()
- writeError(w, http.StatusBadGateway, "start_failed", err.Error())
- return
- }
- } else {
- if s.pool == nil {
- writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
- return
- }
- // #1708: la contraseña nueva del formulario es también la credencial
- // SSH: guardarla en el fichero compañero ANTES de conectar, porque si
- // el usuario ya cambió la contraseña en el router, la conexión de
- // este mismo guardado necesita la nueva.
- if password != "" && s.integrations != nil {
- if err := s.integrations.WriteSSHPassword(slug, password); err != nil {
- writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
- return
- }
- }
- raw, err := s.runIntegrationSSH(row, sshEnvReadScript(vendor), 30*time.Second)
- if err != nil {
- writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
- return
- }
- env := rintegration.ParseEnv(raw)
- env[prefix+"HOST"] = host
- env[prefix+"USER"] = row.Username
- if password != "" {
- env[prefix+"PASS"] = password
- }
- env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
- healPusherPin(env, s.agentBaseURL(r))
- if _, err := s.runIntegrationSSH(row, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
- _ = store.SetState(slug, "error", err.Error())
- s.broadcastIntegrations()
- writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
- return
- }
- }
- if err := store.Upsert(row); err != nil {
- writeError(w, http.StatusInternalServerError, "db_error", err.Error())
- return
- }
- _ = store.SetState(slug, "running", "")
- _ = store.SetLastStart(slug, time.Now().UnixMilli())
- s.broadcastIntegrations()
- item, _ := s.getIntegrationRow(slug)
- writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
- }
- func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request) {
- slug := r.PathValue("slug")
- row, ok := s.getIntegrationRow(slug)
- if !ok {
- writeError(w, http.StatusNotFound, "not_found")
- return
- }
- vendor, _ := s.vendorCatalog.Lookup(row.Vendor)
- if vendor.Mode == "local" {
- if s.integrations != nil {
- _ = s.integrations.Stop(slug)
- _ = s.integrations.Cleanup(slug)
- }
- } else if s.pool != nil {
- _, _ = s.runIntegrationSSH(row, sshUninstallScript(vendor), 60*time.Second)
- }
- // #1708: la contraseña SSH del fichero compañero muere con la
- // integración y el pool pierde la credencial (la conexión cacheada se
- // tira y el siguiente dial vuelve a la llave).
- if s.integrations != nil {
- _ = s.integrations.RemoveSSHPassword(slug)
- }
- if setter, ok := s.pool.(sshPasswordSetter); ok {
- setter.SetPassword(row.Host, "", "")
- }
- _ = s.integrationsStore().Delete(slug)
- _ = routerstore.RemoveRouter(s.db.DB, slug)
- s.syncRouters()
- if s.db != nil {
- _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
- }
- s.broadcastIntegrations()
- w.WriteHeader(http.StatusNoContent)
- }
- // ---------------------------------------------------------------------------
- // Scripts POSIX de instalación/gestión por SSH (modo ssh, p. ej. asuswrt)
- // ---------------------------------------------------------------------------
- // envFileBody renders the sorted KEY=value body of an env file, with values
- // escaped by EscapeEnvValue for a lossless round-trip through ParseEnv.
- func envFileBody(env map[string]string) string {
- keys := make([]string, 0, len(env))
- for k := range env {
- keys = append(keys, k)
- }
- sort.Strings(keys)
- var b strings.Builder
- for _, k := range keys {
- b.WriteString(k)
- b.WriteString("=")
- b.WriteString(rintegration.EscapeEnvValue(env[k]))
- b.WriteString("\n")
- }
- return b.String()
- }
- // sshInstallScript genera el instalador on-router de un vendor en modo ssh.
- // Ramifica por el sistema de init del vendor (#1681): procd (layout OpenWrt,
- // salida intacta) o merlin (/jffs + bloque gestionado en services-start).
- func sshInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
- if v.InitSystem() == "merlin" {
- return sshMerlinInstallScript(v, env, assetURL, sha256)
- }
- return sshProcdInstallScript(v, env, assetURL, sha256)
- }
- // sshProcdInstallScript instala el pusher en un vendor OpenWrt: binario en
- // /usr/sbin, init procd en /etc/init.d y env en /etc.
- func sshProcdInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
- bin := "/usr/sbin/" + v.Binary
- init := "/etc/init.d/" + v.Binary
- envFile := "/etc/" + v.Binary + ".env"
- envBlock := envFileBody(env)
- return `#!/bin/sh
- set -e
- BIN="` + bin + `"
- INIT="` + init + `"
- ENV_FILE="` + envFile + `"
- SERVER="` + env["NETPULSE_SERVER"] + `"
- ASSET_URL="` + assetURL + `"
- SHA256="` + sha256 + `"
- # Preflight: el router debe alcanzar el server.
- if command -v curl >/dev/null 2>&1; then
- curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
- else
- wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
- fi
- # Parar el servicio previo (el proceso vivo mantiene el binario abierto).
- [ -x "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
- # Descargar el asset desde la URL ya verificada en el server.
- if command -v curl >/dev/null 2>&1; then
- curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
- else
- wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
- fi
- # Verificar sha256 antes de instalar.
- GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
- [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
- # Extraer y mover de forma atómica (.new -> rename).
- mkdir -p /tmp/` + v.Binary + `.extract
- tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
- SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
- [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
- cp "$SRC" "$BIN.new"
- chmod 0755 "$BIN.new"
- mv -f "$BIN.new" "$BIN"
- rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
- # Env (chmod 600): solo se escribe en el alta; los updates preservan el
- # fichero existente (la contraseña y el token solo viven ahí).
- if [ ! -f "$ENV_FILE" ]; then
- cat > "$ENV_FILE" <<'ENVEOF'
- ` + envBlock + `ENVEOF
- chmod 600 "$ENV_FILE"
- fi
- # Init procd.
- cat > "$INIT" <<'INITEOF'
- #!/bin/sh /etc/rc.common
- START=99
- STOP=10
- USE_PROCD=1
- BIN="/usr/sbin/` + v.Binary + `"
- ENV_FILE="/etc/` + v.Binary + `.env"
- start_service() {
- [ -x "$BIN" ] || return 1
- [ -r "$ENV_FILE" ] || { echo "netpulse: missing or unreadable env file $ENV_FILE" >&2; return 1; }
- # Cargar el fichero de entorno y pasarlo entero al proceso en UNA sola
- # llamada env (#1709): cada llamada adicional pisaria a la anterior y al
- # proceso solo le llegaria la ultima variable (OpenWrt 21.02, #1701).
- # Los valores van escapados (salto de linea = \n): printf %b los
- # desescapa igual que ParseEnv en el server y que el control script de
- # Merlin (#1705), sin pasar por . "$ENV_FILE" ni /etc/profile.
- set --
- while IFS= read -r line || [ -n "$line" ]; do
- case "$line" in ""|\#*) continue ;; esac
- k=${line%%=*}
- val=${line#*=}
- val=$(printf '%b' "$val")
- set -- "$@" "$k=$val"
- done < "$ENV_FILE"
- procd_open_instance ` + v.Binary + `
- procd_set_param env "$@"
- procd_set_param command "$BIN"
- procd_set_param respawn 3600 5 5
- procd_set_param stdout 1
- procd_set_param stderr 1
- # Vigila el fichero: un cambio sigue reiniciando el servicio y el
- # arranque vuelve a leer el env, asi que el proceso recoge los valores
- # nuevos.
- procd_set_param file "$ENV_FILE"
- procd_close_instance
- }
- INITEOF
- chmod 0755 "$INIT"
- "$INIT" enable
- "$INIT" restart
- `
- }
- // sshMerlinInstallScript instala el pusher en un vendor Asuswrt-Merlin
- // (#1681): sin procd, todo bajo /jffs/netpulse (binario, env, script de
- // control con pidfile y log) y un bloque gestionado en
- // /jffs/scripts/services-start para el arranque al boot. Re-ejecutarlo es
- // idempotente: el env solo se escribe si falta y el bloque solo se añade una
- // vez; el resto del hook no se toca.
- func sshMerlinInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
- dir := "/jffs/netpulse"
- bin := dir + "/" + v.Binary
- ctrl := bin + ".sh"
- envFile := bin + ".env"
- pidFile := bin + ".pid"
- logFile := bin + ".log"
- blockStart := "# >>> netpulse " + v.Binary + " >>>"
- blockEnd := "# <<< netpulse " + v.Binary + " <<<"
- return `#!/bin/sh
- set -e
- BIN="` + bin + `"
- CTRL="` + ctrl + `"
- ENV_FILE="` + envFile + `"
- PID_FILE="` + pidFile + `"
- LOG_FILE="` + logFile + `"
- HOOK="/jffs/scripts/services-start"
- SERVER="` + env["NETPULSE_SERVER"] + `"
- ASSET_URL="` + assetURL + `"
- SHA256="` + sha256 + `"
- # Preflight: el router debe alcanzar el server.
- if command -v curl >/dev/null 2>&1; then
- curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
- else
- wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
- fi
- # Parar el pusher previo (el proceso vivo mantiene el binario abierto).
- [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
- # Descargar el asset desde la URL ya verificada en el server.
- if command -v curl >/dev/null 2>&1; then
- curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
- else
- wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
- fi
- # Verificar sha256 antes de instalar.
- GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
- [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
- # Extraer y mover de forma atómica (.new -> rename).
- mkdir -p /tmp/` + v.Binary + `.extract
- tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
- SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
- [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
- mkdir -p "$DIR"
- cp "$SRC" "$BIN.new"
- chmod 0755 "$BIN.new"
- mv -f "$BIN.new" "$BIN"
- rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
- # Env (chmod 600): solo se escribe si aún no existe; los updates preservan
- # el fichero (la contraseña y el token solo viven ahí).
- if [ ! -f "$ENV_FILE" ]; then
- cat > "$ENV_FILE" <<'ENVEOF'
- ` + envFileBody(env) + `ENVEOF
- chmod 600 "$ENV_FILE"
- fi
- # Script de control con pidfile (start|stop|restart|check). El env guarda
- # los valores escapados (salto de línea = \n): printf %b los desescapa igual
- # que ParseEnv en el server antes de exportarlos al pusher.
- cat > "$CTRL" <<'CTRLEOF'
- #!/bin/sh
- # NetPulse pusher control script (Asuswrt-Merlin).
- BIN="` + bin + `"
- PID_FILE="` + pidFile + `"
- ENV_FILE="` + envFile + `"
- LOG_FILE="` + logFile + `"
- running() {
- [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
- }
- case "$1" in
- start)
- [ -x "$BIN" ] || { echo "netpulse: missing $BIN"; exit 1; }
- if running; then
- exit 0
- fi
- rm -f "$PID_FILE"
- [ -f "$ENV_FILE" ] || { echo "netpulse: missing $ENV_FILE"; exit 1; }
- while IFS= read -r line || [ -n "$line" ]; do
- case "$line" in ""|\#*) continue ;; esac
- k=${line%%=*}
- val=${line#*=}
- val=$(printf '%b' "$val")
- export "$k=$val"
- done < "$ENV_FILE"
- nohup "$BIN" >> "$LOG_FILE" 2>&1 &
- echo $! > "$PID_FILE"
- ;;
- stop)
- if [ -f "$PID_FILE" ]; then
- RUN_PID=$(cat "$PID_FILE")
- kill "$RUN_PID" 2>/dev/null || true
- n=0
- while kill -0 "$RUN_PID" 2>/dev/null && [ "$n" -lt 10 ]; do
- sleep 1
- n=$((n+1))
- done
- if kill -0 "$RUN_PID" 2>/dev/null; then
- kill -9 "$RUN_PID" 2>/dev/null || true
- fi
- rm -f "$PID_FILE"
- fi
- ;;
- restart)
- "$0" stop
- "$0" start
- ;;
- check)
- if running; then
- exit 0
- fi
- exit 1
- ;;
- *)
- echo "usage: $0 {start|stop|restart|check}"
- exit 2
- ;;
- esac
- CTRLEOF
- chmod 0755 "$CTRL"
- # Arranque al boot: bloque gestionado en services-start, delimitado por
- # marcadores únicos para poder quitarlo sin tocar el resto del fichero.
- mkdir -p /jffs/scripts
- if [ ! -f "$HOOK" ]; then
- printf '#!/bin/sh\n' > "$HOOK"
- fi
- chmod 0755 "$HOOK"
- if ! grep -qF '` + blockStart + `' "$HOOK" 2>/dev/null; then
- cat >> "$HOOK" <<'BLOKEOF'
- ` + blockStart + `
- ` + ctrl + ` start
- ` + blockEnd + `
- BLOKEOF
- fi
- "$CTRL" start
- `
- }
- // sshEnvReadScript prints the environment file of an integration running
- // inside the router, so the server can merge changes without ever storing the
- // token or the password. Merlin vendors keep the env under /jffs/netpulse.
- func sshEnvReadScript(v rintegration.Vendor) string {
- if v.InitSystem() == "merlin" {
- return "cat /jffs/netpulse/" + v.Binary + ".env"
- }
- return "cat /etc/" + v.Binary + ".env"
- }
- // sshEnvWriteScript replaces the environment file inside the router and
- // restarts the service. Values come already escaped by EscapeEnvValue and the
- // heredoc is quoted, so the shell does not expand anything.
- func sshEnvWriteScript(v rintegration.Vendor, env map[string]string) string {
- envBlock := envFileBody(env)
- if v.InitSystem() == "merlin" {
- envFile := "/jffs/netpulse/" + v.Binary + ".env"
- ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
- return `#!/bin/sh
- set -e
- ENV_FILE="` + envFile + `"
- CTRL="` + ctrl + `"
- cat > "$ENV_FILE.new" <<'ENVEOF'
- ` + envBlock + `ENVEOF
- chmod 600 "$ENV_FILE.new"
- mv -f "$ENV_FILE.new" "$ENV_FILE"
- if [ -x "$CTRL" ]; then
- "$CTRL" restart >/dev/null 2>&1 || true
- fi
- `
- }
- init := "/etc/init.d/" + v.Binary
- envFile := "/etc/" + v.Binary + ".env"
- return `#!/bin/sh
- set -e
- INIT="` + init + `"
- ENV_FILE="` + envFile + `"
- cat > "$ENV_FILE.new" <<'ENVEOF'
- ` + envBlock + `ENVEOF
- chmod 600 "$ENV_FILE.new"
- mv -f "$ENV_FILE.new" "$ENV_FILE"
- if [ -x "$INIT" ]; then
- "$INIT" stop >/dev/null 2>&1 || true
- "$INIT" start >/dev/null 2>&1 || true
- fi
- `
- }
- func sshServiceScript(v rintegration.Vendor, action string) string {
- if v.InitSystem() == "merlin" {
- // Merlin no tiene procd: las acciones van al script de control
- // con pidfile. check sigue siendo pgrep para no cambiar el camino
- // de salud del handler.
- ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
- switch action {
- case "start":
- return "test -x " + ctrl + " && " + ctrl + " start || true"
- case "stop":
- return "test -x " + ctrl + " && " + ctrl + " stop || true"
- case "restart":
- return "test -x " + ctrl + " && " + ctrl + " restart || true"
- case "check":
- return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
- }
- return "true"
- }
- init := "/etc/init.d/" + v.Binary
- switch action {
- case "start":
- return "test -x " + init + " && " + init + " enable && " + init + " start || true"
- case "stop":
- return "test -x " + init + " && " + init + " stop || true"
- case "restart":
- return "test -x " + init + " && " + init + " restart || true"
- case "check":
- return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
- }
- return "true"
- }
- func sshUninstallScript(v rintegration.Vendor) string {
- if v.InitSystem() == "merlin" {
- return sshMerlinUninstallScript(v)
- }
- init := "/etc/init.d/" + v.Binary
- bin := "/usr/sbin/" + v.Binary
- envFile := "/etc/" + v.Binary + ".env"
- return fmt.Sprintf(
- "test -x %s && %s stop || true; test -x %s && %s disable || true; rm -f %s %s %s",
- init, init, init, init, init, bin, envFile,
- )
- }
- // sshMerlinUninstallScript para el pusher con su script de control, quita el
- // bloque gestionado de services-start (el resto del hook queda intacto) y
- // borra /jffs/netpulse entero.
- func sshMerlinUninstallScript(v rintegration.Vendor) string {
- ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
- blockStart := "# >>> netpulse " + v.Binary + " >>>"
- blockEnd := "# <<< netpulse " + v.Binary + " <<<"
- return `CTRL="` + ctrl + `"
- HOOK="/jffs/scripts/services-start"
- [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
- if [ -f "$HOOK" ]; then
- sed -i '/` + blockStart + `/,/` + blockEnd + `/d' "$HOOK" 2>/dev/null || true
- fi
- rm -rf /jffs/netpulse
- `
- }
|