| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404 |
- // 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"`
- // PollError (#2039): último fallo de poll del pusher, tal cual lo escribió
- // en su log. Es el dato que se pide en cada reporte y no llegaba a la UI,
- // así que el usuario solo veía una pista clasificada.
- PollError string `json:"pollError,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"
- }
- reason, pollErr := s.integrationOffline(row, fresh)
- 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: reason,
- PollError: pollErr,
- }
- }
- // integrationOffline (#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.
- //
- // Devuelve además el último fallo de poll en crudo (#2039): la UI lo muestra
- // para que un reporte pueda traer el mensaje real en vez de solo la pista
- // clasificada.
- func (s *server) integrationOffline(row rintegration.Row, fresh bool) (code, pollErr string) {
- if !row.Enabled {
- return "", ""
- }
- if row.State == "stopped" {
- return rintegration.ReasonStopped, ""
- }
- if fresh {
- return "", ""
- }
- if s.integrations != nil {
- pollErr = s.integrations.LastPollError(row.Slug)
- }
- if row.State == "error" && row.LastError != "" {
- code = rintegration.ClassifyPollError(row.LastError)
- }
- if (code == "" || code == rintegration.ReasonError) && pollErr != "" {
- code = rintegration.ClassifyPollError(pollErr)
- }
- return code, pollErr
- }
- 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] warning: integrations: could not read table at startup (%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] warning: integration %s has unknown vendor %q at startup", 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] warning: integration %s could not be resumed at startup (%v)", row.Slug, err)
- continue
- }
- _ = store.SetState(row.Slug, "running", "")
- _ = store.SetLastStart(row.Slug, time.Now().UnixMilli())
- log.Printf("[netpulse] integration %s resumed at startup", row.Slug)
- }
- s.broadcastIntegrations()
- }
- // unmanagedItem es un pusher externo que alimenta la flota sin fila en
- // router_integrations: se instaló a mano, antes de que la app supiera
- // instalarlos (#1743). Solo se describe; la app no puede arrancarlo, pararlo
- // ni rotarle el token.
- type unmanagedItem struct {
- Slug string `json:"slug"`
- Kind string `json:"kind"`
- Version string `json:"version,omitempty"`
- IntervalS int `json:"intervalS,omitempty"`
- LastPushMs int64 `json:"lastPushMs"`
- Fresh bool `json:"fresh"`
- }
- // unmanagedIntegrations lista los pushers externos vivos que la app no
- // gestiona (#1743). Sin esto la página de Integraciones sale vacía mientras
- // /api/agents muestra unidades alimentadas por ellos, y el operador no tiene
- // ni una pista de que el pusher existe.
- //
- // El kind solo vive en memoria (AgentRegistry), así que justo después de un
- // reinicio la lista queda vacía hasta el primer push de cada unidad (~30 s).
- func (s *server) unmanagedIntegrations() []unmanagedItem {
- out := []unmanagedItem{}
- if s.db == nil || s.agents == nil {
- return out
- }
- // Los slugs viven en kv como agent.token.<slug>. El cursor se cierra ANTES
- // de consultar la tienda de integraciones: con SetMaxOpenConns(1), un
- // QueryRow con las filas abiertas espera la única conexión y bloquea.
- slugs := []string{}
- rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
- if err != nil {
- return out
- }
- for rows.Next() {
- var key string
- if rows.Scan(&key) == nil {
- slugs = append(slugs, strings.TrimPrefix(key, agentTokenKeyPrefix))
- }
- }
- rows.Close()
- if err := rows.Err(); err != nil {
- return out
- }
- store := s.integrationsStore()
- for _, slug := range slugs {
- if slug == "" {
- continue
- }
- _, version, kind, interval, ok := s.agents.Info(slug)
- if !ok || kind != "external" {
- continue
- }
- if _, managed := store.Get(slug); managed {
- continue
- }
- lastPush := s.integrationLastPushMs(slug)
- fresh := lastPush > 0 && interval > 0 && time.Now().UnixMilli()-lastPush <= int64(interval)*3*1000
- out = append(out, unmanagedItem{
- Slug: slug,
- Kind: kind,
- Version: version,
- IntervalS: interval,
- LastPushMs: lastPush,
- Fresh: fresh,
- })
- }
- return out
- }
- func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
- writeJSON(w, http.StatusOK, map[string]any{
- "integrations": s.integrationList(),
- "unmanaged": s.unmanagedIntegrations(),
- })
- }
- 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) {
- // #2112: en modo ssh el instalador corre en el router antes de responder.
- setLongWriteDeadline(w, integrationWriteCeiling)
- 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] warning: integration %s: could not read SSH password file (%v), connecting with key", 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) {
- // #2112: en modo ssh reinstala el pusher en el router antes de responder.
- setLongWriteDeadline(w, integrationWriteCeiling)
- 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
- `
- }
|