| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005 |
- // Package updater — actualizador (paridad src/updater.js, SPEC §9): chequea
- // el último commit de main en la API de GitHub al arrancar y cada 24 h, y
- // aplica la actualización lanzando deploy/update.sh (copiado antes a /tmp:
- // el propio update hace git reset --hard y reescribiría el script). El
- // binario Go se actualiza por el mismo mecanismo de script externo.
- package updater
- import (
- "context"
- "database/sql"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "os"
- "os/exec"
- "path/filepath"
- "regexp"
- "strconv"
- "strings"
- "sync"
- "time"
- )
- const (
- checkInterval = 24 * time.Hour
- httpTimeout = 8 * time.Second
- logTail = 4000
- statusLogTail = 800
- // maxChangelogCommits: tope de commits del compare que se exponen en el
- // estado (issue #490); el enlace compareUrl lleva la lista completa.
- maxChangelogCommits = 30
- )
- // APIBase es la base de la API de GitHub (inyectable en tests).
- var APIBase = "https://api.github.com"
- // BuildCommit se fija en compilación con -ldflags "-X ...". Si está definido,
- // el updater lo usa en vez de ejecutar git rev-parse (permite builds fuera de un
- // repo git, p.ej. despliegues manuales sin working tree).
- var BuildCommit string
- type progress struct {
- Step string `json:"step"`
- Progress int `json:"progress"` // 0-100
- }
- // CommitRef: un commit entre la versión actual y la disponible, para el
- // changelog humano del asistente de actualización (issue #490).
- type CommitRef struct {
- SHA string `json:"sha"` // corto (7 chars), solo display
- Subject string `json:"subject"` // primera línea del mensaje
- }
- // stepWeight: porcentaje mostrado MIENTRAS el paso está en ejecución
- // (issue #280). Pasos del update.sh actual + los legados (binary,
- // server-deps, frontend-build) para compatibilidad con scripts viejos.
- var stepWeight = map[string]int{
- "start": 3,
- "fetch": 12,
- "binary": 40, // legado: download+install juntos
- "download": 40,
- "verify": 68,
- "install": 84,
- "restart": 94,
- "done": 100,
- "server-deps": 30, // legado flujo Node
- "frontend-build": 60, // legado flujo Node
- }
- const stepDefaultWeight = 50
- // Status es la respuesta de /api/update/status (extiende el shape histórico
- // updater.js): updating es false | {step, progress 0-100}; lastLog son los
- // últimos 800 chars.
- type Status struct {
- Current string `json:"current"`
- Latest *string `json:"latest"`
- // CurrentVersion/LatestVersion (#1222): semver legible (sin prefijo v)
- // para la tarjeta de versión de la UI. LatestVersion puede ir vacío en
- // rolling si la consulta del último release falló.
- CurrentVersion string `json:"currentVersion"`
- LatestVersion string `json:"latestVersion,omitempty"`
- LatestMsg *string `json:"latestMsg"`
- UpdateAvailable bool `json:"updateAvailable"`
- CanApply bool `json:"canApply"`
- Mode string `json:"mode"`
- LastCheck *int64 `json:"lastCheck"`
- // LatestBody: cuerpo del commit (rolling) o notas del release (estable)
- // mostrado como changelog en el asistente (issue #280).
- LatestBody *string `json:"latestBody,omitempty"`
- // Commits: commits entre current y latest (compare de GitHub), newest
- // first, cap maxChangelogCommits (issue #490). Vacío cuando no hay
- // actualización o el compare falló: la UI cae a latestBody.
- Commits []CommitRef `json:"commits,omitempty"`
- // CompareURL: enlace web al compare completo current...latest (#490).
- CompareURL string `json:"compareUrl,omitempty"`
- Updating any `json:"updating"` // false | {"step": ...}
- Error *string `json:"error"`
- LastLog *string `json:"lastLog"`
- Repo string `json:"repo"`
- HasToken bool `json:"hasToken"`
- // CheckFailed (#743): el último Check no pudo completar el fetch a
- // GitHub (rate limit anónimo, red, timeout). UpdateAvailable refleja
- // entonces el último estado CONOCIDO, no una comprobación fresca: la UI
- // debe mostrar "no se pudo comprobar" en vez de "estás en la última".
- CheckFailed bool `json:"checkFailed,omitempty"`
- CheckErr string `json:"checkErr,omitempty"`
- // Readiness: pre-flight checks del apply (issue #160). Null en layout
- // estable (sin auto-apply) o hasta el primer Status().
- Readiness *Readiness `json:"readiness,omitempty"`
- // PendingApply: confirmación de que el último update aplicó y el servicio
- // arrancó con el commit nuevo (issue #161). Null sin confirmación.
- PendingApply *PendingApply `json:"pendingApply,omitempty"`
- }
- // Updater mantiene el estado y los timers (como createUpdater).
- type Updater struct {
- repoRoot string
- repo string
- token string
- version string // semver embebido (httpapi.Version) para comparar en estable
- canApply bool // rolling: deploy/update.sh; estable: unidad root de swap (#480)
- mode string // "rolling" (git layout) | "stable" (install.sh)
- // dataDir: ruta real resuelta de DATA_DIR (WithDataDir). En estable es
- // donde el auto-apply (#480) deja el staging y los marcadores.
- dataDir string
- // db: SQLite para historial (#159) y marcador pendingApply (#161). nil →
- // persistencia deshabilitada (tests sin BD).
- db *sql.DB
- mu sync.Mutex
- checkMu sync.Mutex
- current string
- latest *string
- latestMsg *string
- latestBody *string // cuerpo del commit/notas del release (changelog #280)
- // currentVersion/latestVersion (#1222): semver legible del binario en
- // marcha y del último release publicado. En rolling current es el hash
- // corto (gitShort) y latest el sha de main: la UI muestra estos semver
- // en la tarjeta de versión con el hash como detalle secundario.
- currentVersion string
- latestVersion string
- // compare de GitHub cacheado (issue #490): commits current→latest y
- // clave "current|latest" del último fetch para no repetir la consulta.
- commits []CommitRef
- compareURL string
- compareKey string
- updateAvail bool
- lastCheck *int64
- checkFailed bool // #743: el último Check no llegó a completarse
- checkErr string // #743: errCode del último Check fallido
- updatingStep *string // nil = no actualizando
- updatingPct int // 0-100 (issue #280); peso del paso o PROGRESS explícito
- updatingLog string
- lastLog *string
- err *string
- // Suscriptores del stream /api/update/stream (issue #280). Notificados
- // en cada cambio de paso/porcentaje o fin de actualización.
- subs map[chan Status]struct{}
- // readiness cacheado (issue #160): el network check toca red y no debe
- // bloquear el polling de status.
- readiness *Readiness
- readinessAt time.Time
- // pendingApply en memoria (issue #161): confirmación post-update.
- pendingApply *PendingApply
- stopCh chan struct{}
- wg sync.WaitGroup
- }
- // New crea el updater. version es el semver embebido (httpapi.Version) usado
- // para comparar contra el último release tag en modo estable. La detección
- // de layout es automática: si existe deploy/update.sh junto a repoRoot, el
- // modo es "rolling" (compara contra main HEAD y aplica vía update.sh); si
- // no, es "stable" (compara contra release tags). En estable, con la unidad
- // root de swap instalada por install.sh, el auto-apply también está
- // disponible (#480). db puede ser nil (persistencia deshabilitada).
- func New(repoRoot, repo, token, version string, db *sql.DB) *Updater {
- canApply := fileExists(filepath.Join(repoRoot, "deploy", "update.sh"))
- mode := "stable"
- if canApply {
- mode = "rolling"
- } else if stableUnitInstalled() {
- canApply = true
- }
- u := &Updater{
- repoRoot: repoRoot,
- repo: repo,
- token: token,
- version: version,
- canApply: canApply,
- mode: mode,
- db: db,
- current: "desconocido",
- subs: make(map[chan Status]struct{}),
- stopCh: make(chan struct{}),
- }
- // Issue #161: procesar el marcador pendiente (confirmación post-update)
- // y finalizar historial interrumpido en cada arranque.
- u.loadPendingApply()
- return u
- }
- // CanApply indica si el updater puede auto-aplicar en este layout.
- func (u *Updater) CanApply() bool { return u.canApply }
- func fileExists(path string) bool {
- _, err := os.Stat(path)
- return err == nil
- }
- func gitShort(repoRoot string) string {
- if BuildCommit != "" {
- return BuildCommit
- }
- out, err := exec.Command("git", "-C", repoRoot, "rev-parse", "--short", "HEAD").Output()
- if err != nil {
- return ""
- }
- return strings.TrimSpace(string(out))
- }
- // fetchLatestCommit consulta el último commit de main (modo rolling).
- // Errores → {error: ...}. El body (líneas tras el subject) se devuelve como
- // changelog del asistente. También devuelve el SHA completo para poder buscar
- // las notas del release asociado (#404).
- func (u *Updater) fetchLatestCommit(ctx context.Context) (sha, fullSHA, msg, body, errCode string) {
- req, err := http.NewRequestWithContext(ctx, "GET",
- fmt.Sprintf("%s/repos/%s/commits/main", APIBase, u.repo), nil)
- if err != nil {
- return "", "", "", "", "network"
- }
- req.Header.Set("Accept", "application/vnd.github+json")
- req.Header.Set("User-Agent", "netpulse-updater")
- req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
- if u.token != "" {
- req.Header.Set("Authorization", "Bearer "+u.token)
- }
- client := &http.Client{Timeout: httpTimeout}
- res, err := client.Do(req)
- if err != nil {
- if ctx.Err() != nil {
- return "", "", "", "", "timeout"
- }
- return "", "", "", "", "network"
- }
- defer res.Body.Close()
- if res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 404 {
- if u.token != "" {
- return "", "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
- }
- return "", "", "", "", "no_token"
- }
- if res.StatusCode != 200 {
- return "", "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
- }
- var data struct {
- SHA string `json:"sha"`
- Commit struct {
- Message string `json:"message"`
- } `json:"commit"`
- }
- if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&data); err != nil {
- return "", "", "", "", "network"
- }
- fullSHA = data.SHA
- sha = fullSHA
- if len(sha) > 7 {
- sha = sha[:7]
- }
- msg = strings.Split(data.Commit.Message, "\n")[0]
- body = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(data.Commit.Message), msg))
- // JS slice(0, 80) corta por UNIDADES UTF-16 (un astral = 2 unidades),
- // no por bytes: replicar ese cómputo (sin dejar surrogates partidos).
- units, cut := 0, len(msg)
- for i, r := range msg {
- w := 1
- if r > 0xFFFF {
- w = 2
- }
- if units+w > 80 {
- cut = i
- break
- }
- units += w
- }
- msg = msg[:cut]
- return sha, fullSHA, msg, body, ""
- }
- // fetchLatestRelease consulta el último release tag (modo stable). Devuelve
- // tag_name (ej. "v2.7.3"), el nombre del release y sus notas (body) para el
- // changelog del asistente. Errores → {error: ...}.
- func (u *Updater) fetchLatestRelease(ctx context.Context) (tag, name, body, errCode string) {
- req, err := http.NewRequestWithContext(ctx, "GET",
- fmt.Sprintf("%s/repos/%s/releases/latest", APIBase, u.repo), nil)
- if err != nil {
- return "", "", "", "network"
- }
- req.Header.Set("Accept", "application/vnd.github+json")
- req.Header.Set("User-Agent", "netpulse-updater")
- req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
- if u.token != "" {
- req.Header.Set("Authorization", "Bearer "+u.token)
- }
- client := &http.Client{Timeout: httpTimeout}
- res, err := client.Do(req)
- if err != nil {
- if ctx.Err() != nil {
- return "", "", "", "timeout"
- }
- return "", "", "", "network"
- }
- defer res.Body.Close()
- if res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 404 {
- if u.token != "" {
- return "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
- }
- return "", "", "", "no_token"
- }
- if res.StatusCode != 200 {
- return "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
- }
- var data struct {
- TagName string `json:"tag_name"`
- Name string `json:"name"`
- Body string `json:"body"`
- }
- if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&data); err != nil {
- return "", "", "", "network"
- }
- tag = data.TagName
- name = data.Name
- if name == "" {
- name = tag
- }
- return tag, name, strings.TrimSpace(data.Body), ""
- }
- // fetchReleaseBody busca las notas del release asociado al commit dado. Si no
- // encuentra coincidencia o falla la red, devuelve cadena vacía (el asistente
- // usará el body del commit o el fallback a enlace).
- func (u *Updater) fetchReleaseBody(ctx context.Context, sha string) string {
- if sha == "" {
- return ""
- }
- req, err := http.NewRequestWithContext(ctx, "GET",
- fmt.Sprintf("%s/repos/%s/releases?per_page=10", APIBase, u.repo), nil)
- if err != nil {
- return ""
- }
- req.Header.Set("Accept", "application/vnd.github+json")
- req.Header.Set("User-Agent", "netpulse-updater")
- req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
- if u.token != "" {
- req.Header.Set("Authorization", "Bearer "+u.token)
- }
- client := &http.Client{Timeout: httpTimeout}
- res, err := client.Do(req)
- if err != nil {
- return ""
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- return ""
- }
- var releases []struct {
- Body string `json:"body"`
- TargetCommitish string `json:"target_commitish"`
- }
- if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&releases); err != nil {
- return ""
- }
- for _, r := range releases {
- if strings.EqualFold(r.TargetCommitish, sha) || strings.HasPrefix(strings.ToLower(r.TargetCommitish), strings.ToLower(sha)) {
- return strings.TrimSpace(r.Body)
- }
- }
- return ""
- }
- // fetchCompare consulta los commits entre base y head (compare de GitHub,
- // issue #490). base/head aceptan SHAs (rolling) o tags (estable); GitHub
- // devuelve los commits oldest→newest y aquí se invierten para que el
- // changelog se lea newest-first. Cualquier error → (nil, ""): el changelog
- // no aparece y el flujo de actualización queda intacto.
- func (u *Updater) fetchCompare(ctx context.Context, base, head string) ([]CommitRef, string) {
- req, err := http.NewRequestWithContext(ctx, "GET",
- fmt.Sprintf("%s/repos/%s/compare/%s...%s", APIBase, u.repo, base, head), nil)
- if err != nil {
- return nil, ""
- }
- req.Header.Set("Accept", "application/vnd.github+json")
- req.Header.Set("User-Agent", "netpulse-updater")
- req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
- if u.token != "" {
- req.Header.Set("Authorization", "Bearer "+u.token)
- }
- client := &http.Client{Timeout: httpTimeout}
- res, err := client.Do(req)
- if err != nil {
- return nil, ""
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- return nil, ""
- }
- var data struct {
- Commits []struct {
- SHA string `json:"sha"`
- Commit struct {
- Message string `json:"message"`
- } `json:"commit"`
- } `json:"commits"`
- }
- if err := json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(&data); err != nil {
- return nil, ""
- }
- out := make([]CommitRef, 0, len(data.Commits))
- for i := len(data.Commits) - 1; i >= 0; i-- {
- c := data.Commits[i]
- subject := strings.Split(c.Commit.Message, "\n")[0]
- if subject == "" {
- continue
- }
- sha := c.SHA
- if len(sha) > 7 {
- sha = sha[:7]
- }
- out = append(out, CommitRef{SHA: sha, Subject: subject})
- if len(out) >= maxChangelogCommits {
- break
- }
- }
- return out, fmt.Sprintf("https://github.com/%s/compare/%s...%s", u.repo, base, head)
- }
- // compareTagRef normaliza un semver a ref de tag ("2.26.2" → "v2.26.2")
- // para el compare en modo estable; los tags del repo llevan prefijo "v".
- func compareTagRef(s string) string {
- if !strings.HasPrefix(s, "v") {
- return "v" + s
- }
- return s
- }
- // compareSemver compara dos strings semver (con o sin prefijo "v").
- // Devuelve >0 si a > b, 0 si iguales, <0 si a < b. No-parseable → 0.
- func compareSemver(a, b string) int {
- av := parseSemver(a)
- bv := parseSemver(b)
- for i := 0; i < 3; i++ {
- if av[i] != bv[i] {
- return av[i] - bv[i]
- }
- }
- return 0
- }
- func parseSemver(s string) [3]int {
- s = strings.TrimPrefix(s, "v")
- parts := strings.SplitN(s, ".", 3)
- var out [3]int
- for i := 0; i < len(parts) && i < 3; i++ {
- p := parts[i]
- // descartar sufijos pre-release/build (-rc1, +build, etc.)
- if idx := strings.IndexAny(p, "-+"); idx >= 0 {
- p = p[:idx]
- }
- n, _ := strconv.Atoi(p)
- out[i] = n
- }
- return out
- }
- // Check fuerza un chequeo contra GitHub y devuelve el estado. En modo
- // rolling compara contra el último commit de main; en modo estable contra
- // el último release tag (semver).
- func (u *Updater) Check(ctx context.Context) Status {
- u.checkMu.Lock()
- defer u.checkMu.Unlock()
- var current, latest, latestMsg, latestBody, errCode string
- var latestSHA string
- currentVersion := u.version
- var latestVersion string
- if u.mode == "stable" {
- current = u.version
- if current == "" {
- current = "desconocido"
- }
- latest, latestMsg, latestBody, errCode = u.fetchLatestRelease(ctx)
- latestVersion = strings.TrimPrefix(latest, "v")
- } else {
- current = shortSHA(gitShort(u.repoRoot))
- if current == "" {
- current = "desconocido"
- }
- latest, latestSHA, latestMsg, latestBody, errCode = u.fetchLatestCommit(ctx)
- // #1222: el versionado real público en rolling es el tag del último
- // release (main puede ir por delante). Fallo -> se queda vacío y la
- // UI cae al sha.
- if tag, _, _, relErr := u.fetchLatestRelease(ctx); relErr == "" {
- latestVersion = strings.TrimPrefix(tag, "v")
- }
- // Issue #404: si el body del commit está vacío, intentar usar las
- // notas del release asociado a ese commit (rolling en CTs reales).
- if errCode == "" && latestBody == "" && latestSHA != "" {
- if releaseBody := u.fetchReleaseBody(ctx, latestSHA); releaseBody != "" {
- latestBody = releaseBody
- }
- }
- }
- now := time.Now().UnixMilli()
- // Disponibilidad calculada fuera del lock (lógica pura de strings).
- avail := false
- if latest != "" && current != "desconocido" {
- if u.mode == "stable" {
- avail = compareSemver(latest, current) > 0
- } else {
- avail = latest != current
- }
- }
- // Changelog humano (issue #490): commits current→latest vía compare,
- // solo con novedades y solo si el par (current, latest) cambió desde el
- // último fetch (el check corre cada 24 h; no repetir la misma consulta).
- key := current + "|" + latest
- var commits []CommitRef
- var compareURL string
- if avail && key != u.compareKey {
- base, head := current, latestSHA
- if u.mode == "stable" {
- base = compareTagRef(current)
- head = compareTagRef(latest)
- }
- commits, compareURL = u.fetchCompare(ctx, base, head)
- }
- u.mu.Lock()
- defer u.mu.Unlock()
- u.current = current
- u.currentVersion = currentVersion
- u.latestVersion = latestVersion
- u.lastCheck = &now
- if errCode != "" {
- u.err = &errCode
- u.checkFailed = true
- u.checkErr = errCode // no_token no lanza el banner (#743): solo marca el check como fallido
- return u.statusLocked()
- }
- u.err = nil
- u.checkFailed = false
- u.checkErr = ""
- u.latest = &latest
- u.latestMsg = &latestMsg
- u.latestBody = &latestBody
- u.updateAvail = avail
- if avail {
- if key != u.compareKey {
- u.compareKey = key
- u.commits = commits
- u.compareURL = compareURL
- }
- } else {
- // Sin novedades: caduca cualquier changelog anterior.
- u.compareKey = ""
- u.commits = nil
- u.compareURL = ""
- }
- if u.updateAvail {
- fmt.Printf("[netpulse] new version available: %s → %s (%s)\n", current, latest, latestMsg)
- }
- return u.statusLocked()
- }
- var (
- stepRe = regexp.MustCompile(`STEP:(\w+)`)
- progressRe = regexp.MustCompile(`PROGRESS:(\d{1,3})`)
- )
- // setStepLocked fija el paso activo y su porcentaje base (issue #280).
- func (u *Updater) setStepLocked(step string) {
- u.updatingStep = &step
- if w, ok := stepWeight[step]; ok {
- u.updatingPct = w
- } else {
- u.updatingPct = stepDefaultWeight
- }
- }
- // Subscribe registra un canal para recibir el Status en cada cambio del
- // update en curso (issue #280). El cancel devuelto lo retira.
- func (u *Updater) Subscribe() (<-chan Status, func()) {
- ch := make(chan Status, 8)
- u.mu.Lock()
- u.subs[ch] = struct{}{}
- u.mu.Unlock()
- cancel := func() {
- u.mu.Lock()
- delete(u.subs, ch)
- u.mu.Unlock()
- }
- return ch, cancel
- }
- // broadcastLocked emite el estado a todos los suscriptores sin bloquear
- // (un cliente lento pierde el evento; el siguiente lo corrige). Llamar con mu.
- func (u *Updater) broadcastLocked() {
- st := u.statusLocked()
- for ch := range u.subs {
- select {
- case ch <- st:
- default:
- }
- }
- }
- // Apply lanza update.sh en segundo plano (iniciado manualmente desde la UI,
- // rol admin). Devuelve false si ya hay una actualización en curso (→ 409
- // already_updating) o si no se pudo copiar.
- func (u *Updater) Apply() bool { return u.ApplyBy("admin") }
- // applyFreshCheckAge: antigüedad máxima del chequeo que se acepta como
- // objetivo de un apply (#1881). Con checkInterval a 24 h, un apply manual con
- // el estado del último chequeo descargaba una release ya superada y costaba un
- // segundo reinicio.
- const applyFreshCheckAge = 10 * time.Minute
- // needsFreshCheck indica si el objetivo guardado es demasiado viejo para
- // aplicarlo sin volver a preguntar a GitHub.
- func (u *Updater) needsFreshCheck() bool {
- u.mu.Lock()
- defer u.mu.Unlock()
- return u.lastCheck == nil || time.Since(time.UnixMilli(*u.lastCheck)) > applyFreshCheckAge
- }
- // ApplyBy lanza update.sh en segundo plano con el iniciador dado ("admin"
- // manual o "auto" para el rolling main). Antes de lanzar registra la entrada
- // 'running' del historial (#159) y persiste el marcador pendingApply (#161);
- // la goroutine finaliza ambos según el resultado del script.
- func (u *Updater) ApplyBy(initiatedBy string) bool {
- // #1881: el objetivo es el último chequeo, que puede tener hasta 24 h
- // (checkInterval). Aplicar con ese estado instala una release ya superada
- // y obliga a un segundo reinicio; refrescamos antes de elegir target. Si
- // el chequeo falla, Check conserva el anterior: aplicar nunca depende de
- // que GitHub responda.
- if u.needsFreshCheck() {
- ctx, cancel := context.WithTimeout(context.Background(), 2*httpTimeout+2*time.Second)
- u.Check(ctx)
- cancel()
- }
- u.mu.Lock()
- if u.updatingStep != nil {
- u.mu.Unlock()
- return false
- }
- u.setStepLocked("start")
- u.updatingPct = 0
- u.updatingLog = ""
- u.broadcastLocked()
- u.mu.Unlock()
- // Historial + marcador: version_from es el commit actual, version_to el
- // objetivo (latest de GitHub si ya se consultó).
- u.mu.Lock()
- from := u.current
- var to *string
- if u.latest != nil {
- c := *u.latest
- to = &c
- }
- u.mu.Unlock()
- if from == "" || from == "desconocido" {
- from = gitShort(u.repoRoot)
- }
- historyID := u.recordStart(from, to, initiatedBy)
- u.persistPendingApply(from, to)
- startedAt := time.Now()
- if u.mode == "stable" {
- // Issue #480: layout single-binary con unidad root de swap. Nada
- // de update.sh: descargar release estable, verificar y dejar el
- // binario en escena para el helper root (applyStable). El éxito se
- // confirma en el arranque siguiente (#444 vía loadPendingApply).
- if to == nil || strings.TrimSpace(*to) == "" {
- u.mu.Lock()
- u.updatingStep = nil
- code := "stable_no_target"
- u.err = &code
- u.broadcastLocked()
- u.mu.Unlock()
- u.finishHistory(historyID, "failed", code, time.Since(startedAt))
- u.clearPendingApply()
- return false
- }
- // Marcador de un apply previo: fuera antes de empezar (#444).
- _ = os.Remove(u.appliedMarkerPath())
- u.wg.Add(1)
- go func() {
- defer u.wg.Done()
- u.applyStable(historyID, strings.TrimSpace(*to), startedAt)
- }()
- return true
- }
- tmpScript := filepath.Join(os.TempDir(), fmt.Sprintf("netpulse-update-%d.sh", time.Now().UnixMilli()))
- src, err := os.ReadFile(filepath.Join(u.repoRoot, "deploy", "update.sh"))
- if err == nil {
- err = os.WriteFile(tmpScript, src, 0o755)
- }
- // Marcador de un apply previo: fuera antes de empezar (#444).
- _ = os.Remove(u.appliedMarkerPath())
- if err != nil {
- u.mu.Lock()
- u.updatingStep = nil
- code := "update_copy_failed"
- u.err = &code
- u.broadcastLocked()
- u.mu.Unlock()
- u.finishHistory(historyID, "failed", code, time.Since(startedAt))
- fmt.Printf("[netpulse] could not copy update.sh: %v\n", err)
- return false
- }
- cmd := exec.Command("bash", tmpScript)
- cmd.Dir = u.repoRoot
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- u.mu.Lock()
- u.updatingStep = nil
- u.broadcastLocked()
- u.mu.Unlock()
- u.finishHistory(historyID, "failed", "update_pipe_failed", time.Since(startedAt))
- return false
- }
- cmd.Stderr = &tailWriter{u: u}
- if err := cmd.Start(); err != nil {
- u.mu.Lock()
- u.updatingStep = nil
- u.broadcastLocked()
- u.mu.Unlock()
- u.finishHistory(historyID, "failed", "update_start_failed", time.Since(startedAt))
- return false
- }
- u.wg.Add(1)
- go func() {
- defer u.wg.Done()
- buf := make([]byte, 4096)
- for {
- n, err := stdout.Read(buf)
- if n > 0 {
- u.appendLog(string(buf[:n]), true)
- }
- if err != nil {
- break
- }
- }
- waitErr := cmd.Wait()
- dur := time.Since(startedAt)
- u.mu.Lock()
- defer u.mu.Unlock()
- if waitErr == nil {
- u.setStepLocked("done")
- log := u.updatingLog
- u.lastLog = &log
- u.updateAvail = false
- u.finishHistory(historyID, "success", "", dur)
- } else if marker := readAppliedMarker(u.appliedMarkerPath()); marker != "" {
- // #444/#512: el reinicio diferido (systemd.path) mata el script
- // justo después del swap. Si el marcador pre-reinicio existe, el
- // swap se hizo y pidió el reinicio: es el camino de éxito, no un
- // fallo. update.sh escribe el SHA COMPLETO (git rev-parse) y el
- // check guarda el corto, así que se compara por prefijo (#512).
- // Si además el SHA no casa con el target registrado, main avanzó
- // entre el check y el fetch: el marcador es la verdad del terreno
- // y se rectifican historial y pendingApply al SHA instalado.
- if to != nil && !markerMatchesTarget(marker, *to) {
- short := shortSHA(marker)
- u.updateHistoryTarget(historyID, short)
- u.retargetPendingApply(short)
- }
- u.setStepLocked("done")
- log := u.updatingLog
- u.lastLog = &log
- u.updateAvail = false
- u.finishHistory(historyID, "success", "restarted_by_update", dur)
- } else {
- code := "update_exit_-1"
- if ee, ok := waitErr.(*exec.ExitError); ok {
- log := u.updatingLog
- u.lastLog = &log
- u.updatingStep = nil
- code = fmt.Sprintf("update_exit_%d", ee.ExitCode())
- u.err = &code
- } else {
- u.updatingStep = nil
- u.err = &code
- }
- u.finishHistory(historyID, "failed", code, dur)
- // Issue #161: el apply falló → sin confirmación post-update.
- u.clearPendingApply()
- }
- u.broadcastLocked()
- }()
- return true
- }
- // appendLog acumula el log (tail 4000) y extrae STEP:xxx y PROGRESS:nn del
- // stdout. Solo hace broadcast cuando el paso o el porcentaje CAMBIAN (no en
- // cada línea de log) para no saturar el stream (issue #280).
- func (u *Updater) appendLog(text string, parseStep bool) {
- u.mu.Lock()
- defer u.mu.Unlock()
- u.updatingLog = tail(u.updatingLog+text, logTail)
- if parseStep {
- before := ""
- if u.updatingStep != nil {
- before = *u.updatingStep
- }
- beforePct := u.updatingPct
- if m := stepRe.FindStringSubmatch(text); m != nil {
- u.setStepLocked(m[1])
- }
- if m := progressRe.FindStringSubmatch(text); m != nil && u.updatingStep != nil {
- // El progreso explícito no puede bajar del peso del paso activo
- // ni superar el 99 (done se reserva al final del script).
- n, err := strconv.Atoi(m[1])
- if err == nil {
- if n < u.updatingPct {
- n = u.updatingPct
- }
- if n > 99 {
- n = 99
- }
- u.updatingPct = n
- }
- }
- after := ""
- if u.updatingStep != nil {
- after = *u.updatingStep
- }
- if after != before || u.updatingPct != beforePct {
- u.broadcastLocked()
- }
- fmt.Printf("[netpulse:update] %s\n", strings.TrimSpace(text))
- }
- }
- func tail(s string, n int) string {
- if len(s) > n {
- return s[len(s)-n:]
- }
- return s
- }
- // tailWriter captura stderr al log.
- type tailWriter struct{ u *Updater }
- func (w *tailWriter) Write(p []byte) (int, error) {
- w.u.appendLog(string(p), false)
- return len(p), nil
- }
- // Status devuelve el estado actual (shape de la API), incluyendo readiness
- // (issue #160) y la confirmación pendingApply (issue #161).
- func (u *Updater) Status() Status {
- u.mu.Lock()
- st := u.statusLocked()
- u.mu.Unlock()
- st.Readiness = u.Readiness()
- return st
- }
- func (u *Updater) statusLocked() Status {
- var updating any = false
- if u.updatingStep != nil {
- pct := u.updatingPct
- if *u.updatingStep == "done" {
- pct = 100
- }
- updating = progress{Step: *u.updatingStep, Progress: pct}
- }
- var lastLog *string
- if u.updatingStep != nil {
- // JS: state.updating?.log?.slice(-800) ?? state.lastLog ?? null
- l := tail(u.updatingLog, statusLogTail)
- lastLog = &l
- } else {
- lastLog = u.lastLog
- }
- return Status{
- Current: u.current,
- Latest: u.latest,
- CurrentVersion: u.currentVersion,
- LatestVersion: u.latestVersion,
- LatestMsg: u.latestMsg,
- LatestBody: u.latestBody,
- Commits: u.commits,
- CompareURL: u.compareURL,
- UpdateAvailable: u.updateAvail,
- CanApply: u.canApply,
- Mode: u.mode,
- LastCheck: u.lastCheck,
- Updating: updating,
- Error: u.err,
- LastLog: lastLog,
- Repo: u.repo,
- HasToken: u.token != "",
- CheckFailed: u.checkFailed,
- CheckErr: u.checkErr,
- PendingApply: u.pendingApply,
- }
- }
- // Start lanza el chequeo inicial y el timer de 6 h (paridad start()).
- // El contexto cubre las llamadas de red del Check: latest + compare (#490).
- func (u *Updater) Start() {
- u.wg.Add(1)
- go func() {
- defer u.wg.Done()
- ctx, cancel := context.WithTimeout(context.Background(), 2*httpTimeout+2*time.Second)
- u.Check(ctx)
- cancel()
- t := time.NewTicker(checkInterval)
- defer t.Stop()
- for {
- select {
- case <-u.stopCh:
- return
- case <-t.C:
- ctx, cancel := context.WithTimeout(context.Background(), 2*httpTimeout+2*time.Second)
- u.Check(ctx)
- cancel()
- }
- }
- }()
- }
- // Stop para el timer y espera a los procesos en curso (paridad stop()).
- func (u *Updater) Stop() {
- select {
- case <-u.stopCh:
- default:
- close(u.stopCh)
- }
- u.wg.Wait()
- }
- // appliedMarkerPath: fichero que update.sh (rolling) o el helper root
- // (estable, #480) escriben justo antes de tocar el flag de reinicio (#444).
- func (u *Updater) appliedMarkerPath() string {
- if u.mode == "stable" && u.dataDir != "" {
- // En estable el repoRoot (padre del working dir, p.ej. /var/lib)
- // no es escribible por el servicio: el marcador vive en el dataDir.
- return filepath.Join(u.dataDir, stableAppliedName)
- }
- return filepath.Join(u.repoRoot, ".update-applied")
- }
- // readAppliedMarker devuelve el SHA objetivo escrito por update.sh ("" si no
- // existe o no es legible).
- func readAppliedMarker(path string) string {
- b, err := os.ReadFile(path)
- if err != nil {
- return ""
- }
- return strings.TrimSpace(string(b))
- }
- // markerMatchesTarget compara el SHA del marcador (completo, 40 chars, lo
- // que escribe `git rev-parse HEAD` en update.sh) con el target registrado
- // (corto, 7 chars, lo que guarda el check) por PREFIJO y sin distinguir
- // mayúsculas (#512: la igualdad literal hacía imposible el camino de éxito
- // de #444 y todo apply con reinicio registraba "update_exit_-1").
- func markerMatchesTarget(marker, target string) bool {
- m := strings.ToLower(strings.TrimSpace(marker))
- t := strings.ToLower(strings.TrimSpace(target))
- if m == "" || t == "" {
- return false
- }
- n := len(m)
- if len(t) < n {
- n = len(t)
- }
- return m[:n] == t[:n]
- }
- // shortSHA trunca un SHA al formato corto de display (7 chars), aceptando
- // ambos formatos como entrada.
- func shortSHA(sha string) string {
- s := strings.TrimSpace(sha)
- if len(s) > 7 {
- return s[:7]
- }
- return s
- }
|