updater.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. // Package updater — actualizador (paridad src/updater.js, SPEC §9): chequea
  2. // el último commit de main en la API de GitHub al arrancar y cada 24 h, y
  3. // aplica la actualización lanzando deploy/update.sh (copiado antes a /tmp:
  4. // el propio update hace git reset --hard y reescribiría el script). El
  5. // binario Go se actualiza por el mismo mecanismo de script externo.
  6. package updater
  7. import (
  8. "context"
  9. "database/sql"
  10. "encoding/json"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. const (
  24. checkInterval = 24 * time.Hour
  25. httpTimeout = 8 * time.Second
  26. logTail = 4000
  27. statusLogTail = 800
  28. // maxChangelogCommits: tope de commits del compare que se exponen en el
  29. // estado (issue #490); el enlace compareUrl lleva la lista completa.
  30. maxChangelogCommits = 30
  31. )
  32. // APIBase es la base de la API de GitHub (inyectable en tests).
  33. var APIBase = "https://api.github.com"
  34. // BuildCommit se fija en compilación con -ldflags "-X ...". Si está definido,
  35. // el updater lo usa en vez de ejecutar git rev-parse (permite builds fuera de un
  36. // repo git, p.ej. despliegues manuales sin working tree).
  37. var BuildCommit string
  38. type progress struct {
  39. Step string `json:"step"`
  40. Progress int `json:"progress"` // 0-100
  41. }
  42. // CommitRef: un commit entre la versión actual y la disponible, para el
  43. // changelog humano del asistente de actualización (issue #490).
  44. type CommitRef struct {
  45. SHA string `json:"sha"` // corto (7 chars), solo display
  46. Subject string `json:"subject"` // primera línea del mensaje
  47. }
  48. // stepWeight: porcentaje mostrado MIENTRAS el paso está en ejecución
  49. // (issue #280). Pasos del update.sh actual + los legados (binary,
  50. // server-deps, frontend-build) para compatibilidad con scripts viejos.
  51. var stepWeight = map[string]int{
  52. "start": 3,
  53. "fetch": 12,
  54. "binary": 40, // legado: download+install juntos
  55. "download": 40,
  56. "verify": 68,
  57. "install": 84,
  58. "restart": 94,
  59. "done": 100,
  60. "server-deps": 30, // legado flujo Node
  61. "frontend-build": 60, // legado flujo Node
  62. }
  63. const stepDefaultWeight = 50
  64. // Status es la respuesta de /api/update/status (extiende el shape histórico
  65. // updater.js): updating es false | {step, progress 0-100}; lastLog son los
  66. // últimos 800 chars.
  67. type Status struct {
  68. Current string `json:"current"`
  69. Latest *string `json:"latest"`
  70. // CurrentVersion/LatestVersion (#1222): semver legible (sin prefijo v)
  71. // para la tarjeta de versión de la UI. LatestVersion puede ir vacío en
  72. // rolling si la consulta del último release falló.
  73. CurrentVersion string `json:"currentVersion"`
  74. LatestVersion string `json:"latestVersion,omitempty"`
  75. LatestMsg *string `json:"latestMsg"`
  76. UpdateAvailable bool `json:"updateAvailable"`
  77. CanApply bool `json:"canApply"`
  78. Mode string `json:"mode"`
  79. LastCheck *int64 `json:"lastCheck"`
  80. // LatestBody: cuerpo del commit (rolling) o notas del release (estable)
  81. // mostrado como changelog en el asistente (issue #280).
  82. LatestBody *string `json:"latestBody,omitempty"`
  83. // Commits: commits entre current y latest (compare de GitHub), newest
  84. // first, cap maxChangelogCommits (issue #490). Vacío cuando no hay
  85. // actualización o el compare falló: la UI cae a latestBody.
  86. Commits []CommitRef `json:"commits,omitempty"`
  87. // CompareURL: enlace web al compare completo current...latest (#490).
  88. CompareURL string `json:"compareUrl,omitempty"`
  89. Updating any `json:"updating"` // false | {"step": ...}
  90. Error *string `json:"error"`
  91. LastLog *string `json:"lastLog"`
  92. Repo string `json:"repo"`
  93. HasToken bool `json:"hasToken"`
  94. // CheckFailed (#743): el último Check no pudo completar el fetch a
  95. // GitHub (rate limit anónimo, red, timeout). UpdateAvailable refleja
  96. // entonces el último estado CONOCIDO, no una comprobación fresca: la UI
  97. // debe mostrar "no se pudo comprobar" en vez de "estás en la última".
  98. CheckFailed bool `json:"checkFailed,omitempty"`
  99. CheckErr string `json:"checkErr,omitempty"`
  100. // Readiness: pre-flight checks del apply (issue #160). Null en layout
  101. // estable (sin auto-apply) o hasta el primer Status().
  102. Readiness *Readiness `json:"readiness,omitempty"`
  103. // PendingApply: confirmación de que el último update aplicó y el servicio
  104. // arrancó con el commit nuevo (issue #161). Null sin confirmación.
  105. PendingApply *PendingApply `json:"pendingApply,omitempty"`
  106. }
  107. // Updater mantiene el estado y los timers (como createUpdater).
  108. type Updater struct {
  109. repoRoot string
  110. repo string
  111. token string
  112. version string // semver embebido (httpapi.Version) para comparar en estable
  113. canApply bool // rolling: deploy/update.sh; estable: unidad root de swap (#480)
  114. mode string // "rolling" (git layout) | "stable" (install.sh)
  115. // dataDir: ruta real resuelta de DATA_DIR (WithDataDir). En estable es
  116. // donde el auto-apply (#480) deja el staging y los marcadores.
  117. dataDir string
  118. // db: SQLite para historial (#159) y marcador pendingApply (#161). nil →
  119. // persistencia deshabilitada (tests sin BD).
  120. db *sql.DB
  121. mu sync.Mutex
  122. checkMu sync.Mutex
  123. current string
  124. latest *string
  125. latestMsg *string
  126. latestBody *string // cuerpo del commit/notas del release (changelog #280)
  127. // currentVersion/latestVersion (#1222): semver legible del binario en
  128. // marcha y del último release publicado. En rolling current es el hash
  129. // corto (gitShort) y latest el sha de main: la UI muestra estos semver
  130. // en la tarjeta de versión con el hash como detalle secundario.
  131. currentVersion string
  132. latestVersion string
  133. // compare de GitHub cacheado (issue #490): commits current→latest y
  134. // clave "current|latest" del último fetch para no repetir la consulta.
  135. commits []CommitRef
  136. compareURL string
  137. compareKey string
  138. updateAvail bool
  139. lastCheck *int64
  140. checkFailed bool // #743: el último Check no llegó a completarse
  141. checkErr string // #743: errCode del último Check fallido
  142. updatingStep *string // nil = no actualizando
  143. updatingPct int // 0-100 (issue #280); peso del paso o PROGRESS explícito
  144. updatingLog string
  145. lastLog *string
  146. err *string
  147. // Suscriptores del stream /api/update/stream (issue #280). Notificados
  148. // en cada cambio de paso/porcentaje o fin de actualización.
  149. subs map[chan Status]struct{}
  150. // readiness cacheado (issue #160): el network check toca red y no debe
  151. // bloquear el polling de status.
  152. readiness *Readiness
  153. readinessAt time.Time
  154. // pendingApply en memoria (issue #161): confirmación post-update.
  155. pendingApply *PendingApply
  156. stopCh chan struct{}
  157. wg sync.WaitGroup
  158. }
  159. // New crea el updater. version es el semver embebido (httpapi.Version) usado
  160. // para comparar contra el último release tag en modo estable. La detección
  161. // de layout es automática: si existe deploy/update.sh junto a repoRoot, el
  162. // modo es "rolling" (compara contra main HEAD y aplica vía update.sh); si
  163. // no, es "stable" (compara contra release tags). En estable, con la unidad
  164. // root de swap instalada por install.sh, el auto-apply también está
  165. // disponible (#480). db puede ser nil (persistencia deshabilitada).
  166. func New(repoRoot, repo, token, version string, db *sql.DB) *Updater {
  167. canApply := fileExists(filepath.Join(repoRoot, "deploy", "update.sh"))
  168. mode := "stable"
  169. if canApply {
  170. mode = "rolling"
  171. } else if stableUnitInstalled() {
  172. canApply = true
  173. }
  174. u := &Updater{
  175. repoRoot: repoRoot,
  176. repo: repo,
  177. token: token,
  178. version: version,
  179. canApply: canApply,
  180. mode: mode,
  181. db: db,
  182. current: "desconocido",
  183. subs: make(map[chan Status]struct{}),
  184. stopCh: make(chan struct{}),
  185. }
  186. // Issue #161: procesar el marcador pendiente (confirmación post-update)
  187. // y finalizar historial interrumpido en cada arranque.
  188. u.loadPendingApply()
  189. return u
  190. }
  191. // CanApply indica si el updater puede auto-aplicar en este layout.
  192. func (u *Updater) CanApply() bool { return u.canApply }
  193. func fileExists(path string) bool {
  194. _, err := os.Stat(path)
  195. return err == nil
  196. }
  197. func gitShort(repoRoot string) string {
  198. if BuildCommit != "" {
  199. return BuildCommit
  200. }
  201. out, err := exec.Command("git", "-C", repoRoot, "rev-parse", "--short", "HEAD").Output()
  202. if err != nil {
  203. return ""
  204. }
  205. return strings.TrimSpace(string(out))
  206. }
  207. // fetchLatestCommit consulta el último commit de main (modo rolling).
  208. // Errores → {error: ...}. El body (líneas tras el subject) se devuelve como
  209. // changelog del asistente. También devuelve el SHA completo para poder buscar
  210. // las notas del release asociado (#404).
  211. func (u *Updater) fetchLatestCommit(ctx context.Context) (sha, fullSHA, msg, body, errCode string) {
  212. req, err := http.NewRequestWithContext(ctx, "GET",
  213. fmt.Sprintf("%s/repos/%s/commits/main", APIBase, u.repo), nil)
  214. if err != nil {
  215. return "", "", "", "", "network"
  216. }
  217. req.Header.Set("Accept", "application/vnd.github+json")
  218. req.Header.Set("User-Agent", "netpulse-updater")
  219. req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
  220. if u.token != "" {
  221. req.Header.Set("Authorization", "Bearer "+u.token)
  222. }
  223. client := &http.Client{Timeout: httpTimeout}
  224. res, err := client.Do(req)
  225. if err != nil {
  226. if ctx.Err() != nil {
  227. return "", "", "", "", "timeout"
  228. }
  229. return "", "", "", "", "network"
  230. }
  231. defer res.Body.Close()
  232. if res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 404 {
  233. if u.token != "" {
  234. return "", "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
  235. }
  236. return "", "", "", "", "no_token"
  237. }
  238. if res.StatusCode != 200 {
  239. return "", "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
  240. }
  241. var data struct {
  242. SHA string `json:"sha"`
  243. Commit struct {
  244. Message string `json:"message"`
  245. } `json:"commit"`
  246. }
  247. if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&data); err != nil {
  248. return "", "", "", "", "network"
  249. }
  250. fullSHA = data.SHA
  251. sha = fullSHA
  252. if len(sha) > 7 {
  253. sha = sha[:7]
  254. }
  255. msg = strings.Split(data.Commit.Message, "\n")[0]
  256. body = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(data.Commit.Message), msg))
  257. // JS slice(0, 80) corta por UNIDADES UTF-16 (un astral = 2 unidades),
  258. // no por bytes: replicar ese cómputo (sin dejar surrogates partidos).
  259. units, cut := 0, len(msg)
  260. for i, r := range msg {
  261. w := 1
  262. if r > 0xFFFF {
  263. w = 2
  264. }
  265. if units+w > 80 {
  266. cut = i
  267. break
  268. }
  269. units += w
  270. }
  271. msg = msg[:cut]
  272. return sha, fullSHA, msg, body, ""
  273. }
  274. // fetchLatestRelease consulta el último release tag (modo stable). Devuelve
  275. // tag_name (ej. "v2.7.3"), el nombre del release y sus notas (body) para el
  276. // changelog del asistente. Errores → {error: ...}.
  277. func (u *Updater) fetchLatestRelease(ctx context.Context) (tag, name, body, errCode string) {
  278. req, err := http.NewRequestWithContext(ctx, "GET",
  279. fmt.Sprintf("%s/repos/%s/releases/latest", APIBase, u.repo), nil)
  280. if err != nil {
  281. return "", "", "", "network"
  282. }
  283. req.Header.Set("Accept", "application/vnd.github+json")
  284. req.Header.Set("User-Agent", "netpulse-updater")
  285. req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
  286. if u.token != "" {
  287. req.Header.Set("Authorization", "Bearer "+u.token)
  288. }
  289. client := &http.Client{Timeout: httpTimeout}
  290. res, err := client.Do(req)
  291. if err != nil {
  292. if ctx.Err() != nil {
  293. return "", "", "", "timeout"
  294. }
  295. return "", "", "", "network"
  296. }
  297. defer res.Body.Close()
  298. if res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 404 {
  299. if u.token != "" {
  300. return "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
  301. }
  302. return "", "", "", "no_token"
  303. }
  304. if res.StatusCode != 200 {
  305. return "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
  306. }
  307. var data struct {
  308. TagName string `json:"tag_name"`
  309. Name string `json:"name"`
  310. Body string `json:"body"`
  311. }
  312. if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&data); err != nil {
  313. return "", "", "", "network"
  314. }
  315. tag = data.TagName
  316. name = data.Name
  317. if name == "" {
  318. name = tag
  319. }
  320. return tag, name, strings.TrimSpace(data.Body), ""
  321. }
  322. // fetchReleaseBody busca las notas del release asociado al commit dado. Si no
  323. // encuentra coincidencia o falla la red, devuelve cadena vacía (el asistente
  324. // usará el body del commit o el fallback a enlace).
  325. func (u *Updater) fetchReleaseBody(ctx context.Context, sha string) string {
  326. if sha == "" {
  327. return ""
  328. }
  329. req, err := http.NewRequestWithContext(ctx, "GET",
  330. fmt.Sprintf("%s/repos/%s/releases?per_page=10", APIBase, u.repo), nil)
  331. if err != nil {
  332. return ""
  333. }
  334. req.Header.Set("Accept", "application/vnd.github+json")
  335. req.Header.Set("User-Agent", "netpulse-updater")
  336. req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
  337. if u.token != "" {
  338. req.Header.Set("Authorization", "Bearer "+u.token)
  339. }
  340. client := &http.Client{Timeout: httpTimeout}
  341. res, err := client.Do(req)
  342. if err != nil {
  343. return ""
  344. }
  345. defer res.Body.Close()
  346. if res.StatusCode != 200 {
  347. return ""
  348. }
  349. var releases []struct {
  350. Body string `json:"body"`
  351. TargetCommitish string `json:"target_commitish"`
  352. }
  353. if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&releases); err != nil {
  354. return ""
  355. }
  356. for _, r := range releases {
  357. if strings.EqualFold(r.TargetCommitish, sha) || strings.HasPrefix(strings.ToLower(r.TargetCommitish), strings.ToLower(sha)) {
  358. return strings.TrimSpace(r.Body)
  359. }
  360. }
  361. return ""
  362. }
  363. // fetchCompare consulta los commits entre base y head (compare de GitHub,
  364. // issue #490). base/head aceptan SHAs (rolling) o tags (estable); GitHub
  365. // devuelve los commits oldest→newest y aquí se invierten para que el
  366. // changelog se lea newest-first. Cualquier error → (nil, ""): el changelog
  367. // no aparece y el flujo de actualización queda intacto.
  368. func (u *Updater) fetchCompare(ctx context.Context, base, head string) ([]CommitRef, string) {
  369. req, err := http.NewRequestWithContext(ctx, "GET",
  370. fmt.Sprintf("%s/repos/%s/compare/%s...%s", APIBase, u.repo, base, head), nil)
  371. if err != nil {
  372. return nil, ""
  373. }
  374. req.Header.Set("Accept", "application/vnd.github+json")
  375. req.Header.Set("User-Agent", "netpulse-updater")
  376. req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
  377. if u.token != "" {
  378. req.Header.Set("Authorization", "Bearer "+u.token)
  379. }
  380. client := &http.Client{Timeout: httpTimeout}
  381. res, err := client.Do(req)
  382. if err != nil {
  383. return nil, ""
  384. }
  385. defer res.Body.Close()
  386. if res.StatusCode != 200 {
  387. return nil, ""
  388. }
  389. var data struct {
  390. Commits []struct {
  391. SHA string `json:"sha"`
  392. Commit struct {
  393. Message string `json:"message"`
  394. } `json:"commit"`
  395. } `json:"commits"`
  396. }
  397. if err := json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(&data); err != nil {
  398. return nil, ""
  399. }
  400. out := make([]CommitRef, 0, len(data.Commits))
  401. for i := len(data.Commits) - 1; i >= 0; i-- {
  402. c := data.Commits[i]
  403. subject := strings.Split(c.Commit.Message, "\n")[0]
  404. if subject == "" {
  405. continue
  406. }
  407. sha := c.SHA
  408. if len(sha) > 7 {
  409. sha = sha[:7]
  410. }
  411. out = append(out, CommitRef{SHA: sha, Subject: subject})
  412. if len(out) >= maxChangelogCommits {
  413. break
  414. }
  415. }
  416. return out, fmt.Sprintf("https://github.com/%s/compare/%s...%s", u.repo, base, head)
  417. }
  418. // compareTagRef normaliza un semver a ref de tag ("2.26.2" → "v2.26.2")
  419. // para el compare en modo estable; los tags del repo llevan prefijo "v".
  420. func compareTagRef(s string) string {
  421. if !strings.HasPrefix(s, "v") {
  422. return "v" + s
  423. }
  424. return s
  425. }
  426. // compareSemver compara dos strings semver (con o sin prefijo "v").
  427. // Devuelve >0 si a > b, 0 si iguales, <0 si a < b. No-parseable → 0.
  428. func compareSemver(a, b string) int {
  429. av := parseSemver(a)
  430. bv := parseSemver(b)
  431. for i := 0; i < 3; i++ {
  432. if av[i] != bv[i] {
  433. return av[i] - bv[i]
  434. }
  435. }
  436. return 0
  437. }
  438. func parseSemver(s string) [3]int {
  439. s = strings.TrimPrefix(s, "v")
  440. parts := strings.SplitN(s, ".", 3)
  441. var out [3]int
  442. for i := 0; i < len(parts) && i < 3; i++ {
  443. p := parts[i]
  444. // descartar sufijos pre-release/build (-rc1, +build, etc.)
  445. if idx := strings.IndexAny(p, "-+"); idx >= 0 {
  446. p = p[:idx]
  447. }
  448. n, _ := strconv.Atoi(p)
  449. out[i] = n
  450. }
  451. return out
  452. }
  453. // Check fuerza un chequeo contra GitHub y devuelve el estado. En modo
  454. // rolling compara contra el último commit de main; en modo estable contra
  455. // el último release tag (semver).
  456. func (u *Updater) Check(ctx context.Context) Status {
  457. u.checkMu.Lock()
  458. defer u.checkMu.Unlock()
  459. var current, latest, latestMsg, latestBody, errCode string
  460. var latestSHA string
  461. currentVersion := u.version
  462. var latestVersion string
  463. if u.mode == "stable" {
  464. current = u.version
  465. if current == "" {
  466. current = "desconocido"
  467. }
  468. latest, latestMsg, latestBody, errCode = u.fetchLatestRelease(ctx)
  469. latestVersion = strings.TrimPrefix(latest, "v")
  470. } else {
  471. current = shortSHA(gitShort(u.repoRoot))
  472. if current == "" {
  473. current = "desconocido"
  474. }
  475. latest, latestSHA, latestMsg, latestBody, errCode = u.fetchLatestCommit(ctx)
  476. // #1222: el versionado real público en rolling es el tag del último
  477. // release (main puede ir por delante). Fallo -> se queda vacío y la
  478. // UI cae al sha.
  479. if tag, _, _, relErr := u.fetchLatestRelease(ctx); relErr == "" {
  480. latestVersion = strings.TrimPrefix(tag, "v")
  481. }
  482. // Issue #404: si el body del commit está vacío, intentar usar las
  483. // notas del release asociado a ese commit (rolling en CTs reales).
  484. if errCode == "" && latestBody == "" && latestSHA != "" {
  485. if releaseBody := u.fetchReleaseBody(ctx, latestSHA); releaseBody != "" {
  486. latestBody = releaseBody
  487. }
  488. }
  489. }
  490. now := time.Now().UnixMilli()
  491. // Disponibilidad calculada fuera del lock (lógica pura de strings).
  492. avail := false
  493. if latest != "" && current != "desconocido" {
  494. if u.mode == "stable" {
  495. avail = compareSemver(latest, current) > 0
  496. } else {
  497. avail = latest != current
  498. }
  499. }
  500. // Changelog humano (issue #490): commits current→latest vía compare,
  501. // solo con novedades y solo si el par (current, latest) cambió desde el
  502. // último fetch (el check corre cada 24 h; no repetir la misma consulta).
  503. key := current + "|" + latest
  504. var commits []CommitRef
  505. var compareURL string
  506. if avail && key != u.compareKey {
  507. base, head := current, latestSHA
  508. if u.mode == "stable" {
  509. base = compareTagRef(current)
  510. head = compareTagRef(latest)
  511. }
  512. commits, compareURL = u.fetchCompare(ctx, base, head)
  513. }
  514. u.mu.Lock()
  515. defer u.mu.Unlock()
  516. u.current = current
  517. u.currentVersion = currentVersion
  518. u.latestVersion = latestVersion
  519. u.lastCheck = &now
  520. if errCode != "" {
  521. u.err = &errCode
  522. u.checkFailed = true
  523. u.checkErr = errCode // no_token no lanza el banner (#743): solo marca el check como fallido
  524. return u.statusLocked()
  525. }
  526. u.err = nil
  527. u.checkFailed = false
  528. u.checkErr = ""
  529. u.latest = &latest
  530. u.latestMsg = &latestMsg
  531. u.latestBody = &latestBody
  532. u.updateAvail = avail
  533. if avail {
  534. if key != u.compareKey {
  535. u.compareKey = key
  536. u.commits = commits
  537. u.compareURL = compareURL
  538. }
  539. } else {
  540. // Sin novedades: caduca cualquier changelog anterior.
  541. u.compareKey = ""
  542. u.commits = nil
  543. u.compareURL = ""
  544. }
  545. if u.updateAvail {
  546. fmt.Printf("[netpulse] new version available: %s → %s (%s)\n", current, latest, latestMsg)
  547. }
  548. return u.statusLocked()
  549. }
  550. var (
  551. stepRe = regexp.MustCompile(`STEP:(\w+)`)
  552. progressRe = regexp.MustCompile(`PROGRESS:(\d{1,3})`)
  553. )
  554. // setStepLocked fija el paso activo y su porcentaje base (issue #280).
  555. func (u *Updater) setStepLocked(step string) {
  556. u.updatingStep = &step
  557. if w, ok := stepWeight[step]; ok {
  558. u.updatingPct = w
  559. } else {
  560. u.updatingPct = stepDefaultWeight
  561. }
  562. }
  563. // Subscribe registra un canal para recibir el Status en cada cambio del
  564. // update en curso (issue #280). El cancel devuelto lo retira.
  565. func (u *Updater) Subscribe() (<-chan Status, func()) {
  566. ch := make(chan Status, 8)
  567. u.mu.Lock()
  568. u.subs[ch] = struct{}{}
  569. u.mu.Unlock()
  570. cancel := func() {
  571. u.mu.Lock()
  572. delete(u.subs, ch)
  573. u.mu.Unlock()
  574. }
  575. return ch, cancel
  576. }
  577. // broadcastLocked emite el estado a todos los suscriptores sin bloquear
  578. // (un cliente lento pierde el evento; el siguiente lo corrige). Llamar con mu.
  579. func (u *Updater) broadcastLocked() {
  580. st := u.statusLocked()
  581. for ch := range u.subs {
  582. select {
  583. case ch <- st:
  584. default:
  585. }
  586. }
  587. }
  588. // Apply lanza update.sh en segundo plano (iniciado manualmente desde la UI,
  589. // rol admin). Devuelve false si ya hay una actualización en curso (→ 409
  590. // already_updating) o si no se pudo copiar.
  591. func (u *Updater) Apply() bool { return u.ApplyBy("admin") }
  592. // applyFreshCheckAge: antigüedad máxima del chequeo que se acepta como
  593. // objetivo de un apply (#1881). Con checkInterval a 24 h, un apply manual con
  594. // el estado del último chequeo descargaba una release ya superada y costaba un
  595. // segundo reinicio.
  596. const applyFreshCheckAge = 10 * time.Minute
  597. // needsFreshCheck indica si el objetivo guardado es demasiado viejo para
  598. // aplicarlo sin volver a preguntar a GitHub.
  599. func (u *Updater) needsFreshCheck() bool {
  600. u.mu.Lock()
  601. defer u.mu.Unlock()
  602. return u.lastCheck == nil || time.Since(time.UnixMilli(*u.lastCheck)) > applyFreshCheckAge
  603. }
  604. // ApplyBy lanza update.sh en segundo plano con el iniciador dado ("admin"
  605. // manual o "auto" para el rolling main). Antes de lanzar registra la entrada
  606. // 'running' del historial (#159) y persiste el marcador pendingApply (#161);
  607. // la goroutine finaliza ambos según el resultado del script.
  608. func (u *Updater) ApplyBy(initiatedBy string) bool {
  609. // #1881: el objetivo es el último chequeo, que puede tener hasta 24 h
  610. // (checkInterval). Aplicar con ese estado instala una release ya superada
  611. // y obliga a un segundo reinicio; refrescamos antes de elegir target. Si
  612. // el chequeo falla, Check conserva el anterior: aplicar nunca depende de
  613. // que GitHub responda.
  614. if u.needsFreshCheck() {
  615. ctx, cancel := context.WithTimeout(context.Background(), 2*httpTimeout+2*time.Second)
  616. u.Check(ctx)
  617. cancel()
  618. }
  619. u.mu.Lock()
  620. if u.updatingStep != nil {
  621. u.mu.Unlock()
  622. return false
  623. }
  624. u.setStepLocked("start")
  625. u.updatingPct = 0
  626. u.updatingLog = ""
  627. u.broadcastLocked()
  628. u.mu.Unlock()
  629. // Historial + marcador: version_from es el commit actual, version_to el
  630. // objetivo (latest de GitHub si ya se consultó).
  631. u.mu.Lock()
  632. from := u.current
  633. var to *string
  634. if u.latest != nil {
  635. c := *u.latest
  636. to = &c
  637. }
  638. u.mu.Unlock()
  639. if from == "" || from == "desconocido" {
  640. from = gitShort(u.repoRoot)
  641. }
  642. historyID := u.recordStart(from, to, initiatedBy)
  643. u.persistPendingApply(from, to)
  644. startedAt := time.Now()
  645. if u.mode == "stable" {
  646. // Issue #480: layout single-binary con unidad root de swap. Nada
  647. // de update.sh: descargar release estable, verificar y dejar el
  648. // binario en escena para el helper root (applyStable). El éxito se
  649. // confirma en el arranque siguiente (#444 vía loadPendingApply).
  650. if to == nil || strings.TrimSpace(*to) == "" {
  651. u.mu.Lock()
  652. u.updatingStep = nil
  653. code := "stable_no_target"
  654. u.err = &code
  655. u.broadcastLocked()
  656. u.mu.Unlock()
  657. u.finishHistory(historyID, "failed", code, time.Since(startedAt))
  658. u.clearPendingApply()
  659. return false
  660. }
  661. // Marcador de un apply previo: fuera antes de empezar (#444).
  662. _ = os.Remove(u.appliedMarkerPath())
  663. u.wg.Add(1)
  664. go func() {
  665. defer u.wg.Done()
  666. u.applyStable(historyID, strings.TrimSpace(*to), startedAt)
  667. }()
  668. return true
  669. }
  670. tmpScript := filepath.Join(os.TempDir(), fmt.Sprintf("netpulse-update-%d.sh", time.Now().UnixMilli()))
  671. src, err := os.ReadFile(filepath.Join(u.repoRoot, "deploy", "update.sh"))
  672. if err == nil {
  673. err = os.WriteFile(tmpScript, src, 0o755)
  674. }
  675. // Marcador de un apply previo: fuera antes de empezar (#444).
  676. _ = os.Remove(u.appliedMarkerPath())
  677. if err != nil {
  678. u.mu.Lock()
  679. u.updatingStep = nil
  680. code := "update_copy_failed"
  681. u.err = &code
  682. u.broadcastLocked()
  683. u.mu.Unlock()
  684. u.finishHistory(historyID, "failed", code, time.Since(startedAt))
  685. fmt.Printf("[netpulse] could not copy update.sh: %v\n", err)
  686. return false
  687. }
  688. cmd := exec.Command("bash", tmpScript)
  689. cmd.Dir = u.repoRoot
  690. stdout, err := cmd.StdoutPipe()
  691. if err != nil {
  692. u.mu.Lock()
  693. u.updatingStep = nil
  694. u.broadcastLocked()
  695. u.mu.Unlock()
  696. u.finishHistory(historyID, "failed", "update_pipe_failed", time.Since(startedAt))
  697. return false
  698. }
  699. cmd.Stderr = &tailWriter{u: u}
  700. if err := cmd.Start(); err != nil {
  701. u.mu.Lock()
  702. u.updatingStep = nil
  703. u.broadcastLocked()
  704. u.mu.Unlock()
  705. u.finishHistory(historyID, "failed", "update_start_failed", time.Since(startedAt))
  706. return false
  707. }
  708. u.wg.Add(1)
  709. go func() {
  710. defer u.wg.Done()
  711. buf := make([]byte, 4096)
  712. for {
  713. n, err := stdout.Read(buf)
  714. if n > 0 {
  715. u.appendLog(string(buf[:n]), true)
  716. }
  717. if err != nil {
  718. break
  719. }
  720. }
  721. waitErr := cmd.Wait()
  722. dur := time.Since(startedAt)
  723. u.mu.Lock()
  724. defer u.mu.Unlock()
  725. if waitErr == nil {
  726. u.setStepLocked("done")
  727. log := u.updatingLog
  728. u.lastLog = &log
  729. u.updateAvail = false
  730. u.finishHistory(historyID, "success", "", dur)
  731. } else if marker := readAppliedMarker(u.appliedMarkerPath()); marker != "" {
  732. // #444/#512: el reinicio diferido (systemd.path) mata el script
  733. // justo después del swap. Si el marcador pre-reinicio existe, el
  734. // swap se hizo y pidió el reinicio: es el camino de éxito, no un
  735. // fallo. update.sh escribe el SHA COMPLETO (git rev-parse) y el
  736. // check guarda el corto, así que se compara por prefijo (#512).
  737. // Si además el SHA no casa con el target registrado, main avanzó
  738. // entre el check y el fetch: el marcador es la verdad del terreno
  739. // y se rectifican historial y pendingApply al SHA instalado.
  740. if to != nil && !markerMatchesTarget(marker, *to) {
  741. short := shortSHA(marker)
  742. u.updateHistoryTarget(historyID, short)
  743. u.retargetPendingApply(short)
  744. }
  745. u.setStepLocked("done")
  746. log := u.updatingLog
  747. u.lastLog = &log
  748. u.updateAvail = false
  749. u.finishHistory(historyID, "success", "restarted_by_update", dur)
  750. } else {
  751. code := "update_exit_-1"
  752. if ee, ok := waitErr.(*exec.ExitError); ok {
  753. log := u.updatingLog
  754. u.lastLog = &log
  755. u.updatingStep = nil
  756. code = fmt.Sprintf("update_exit_%d", ee.ExitCode())
  757. u.err = &code
  758. } else {
  759. u.updatingStep = nil
  760. u.err = &code
  761. }
  762. u.finishHistory(historyID, "failed", code, dur)
  763. // Issue #161: el apply falló → sin confirmación post-update.
  764. u.clearPendingApply()
  765. }
  766. u.broadcastLocked()
  767. }()
  768. return true
  769. }
  770. // appendLog acumula el log (tail 4000) y extrae STEP:xxx y PROGRESS:nn del
  771. // stdout. Solo hace broadcast cuando el paso o el porcentaje CAMBIAN (no en
  772. // cada línea de log) para no saturar el stream (issue #280).
  773. func (u *Updater) appendLog(text string, parseStep bool) {
  774. u.mu.Lock()
  775. defer u.mu.Unlock()
  776. u.updatingLog = tail(u.updatingLog+text, logTail)
  777. if parseStep {
  778. before := ""
  779. if u.updatingStep != nil {
  780. before = *u.updatingStep
  781. }
  782. beforePct := u.updatingPct
  783. if m := stepRe.FindStringSubmatch(text); m != nil {
  784. u.setStepLocked(m[1])
  785. }
  786. if m := progressRe.FindStringSubmatch(text); m != nil && u.updatingStep != nil {
  787. // El progreso explícito no puede bajar del peso del paso activo
  788. // ni superar el 99 (done se reserva al final del script).
  789. n, err := strconv.Atoi(m[1])
  790. if err == nil {
  791. if n < u.updatingPct {
  792. n = u.updatingPct
  793. }
  794. if n > 99 {
  795. n = 99
  796. }
  797. u.updatingPct = n
  798. }
  799. }
  800. after := ""
  801. if u.updatingStep != nil {
  802. after = *u.updatingStep
  803. }
  804. if after != before || u.updatingPct != beforePct {
  805. u.broadcastLocked()
  806. }
  807. fmt.Printf("[netpulse:update] %s\n", strings.TrimSpace(text))
  808. }
  809. }
  810. func tail(s string, n int) string {
  811. if len(s) > n {
  812. return s[len(s)-n:]
  813. }
  814. return s
  815. }
  816. // tailWriter captura stderr al log.
  817. type tailWriter struct{ u *Updater }
  818. func (w *tailWriter) Write(p []byte) (int, error) {
  819. w.u.appendLog(string(p), false)
  820. return len(p), nil
  821. }
  822. // Status devuelve el estado actual (shape de la API), incluyendo readiness
  823. // (issue #160) y la confirmación pendingApply (issue #161).
  824. func (u *Updater) Status() Status {
  825. u.mu.Lock()
  826. st := u.statusLocked()
  827. u.mu.Unlock()
  828. st.Readiness = u.Readiness()
  829. return st
  830. }
  831. func (u *Updater) statusLocked() Status {
  832. var updating any = false
  833. if u.updatingStep != nil {
  834. pct := u.updatingPct
  835. if *u.updatingStep == "done" {
  836. pct = 100
  837. }
  838. updating = progress{Step: *u.updatingStep, Progress: pct}
  839. }
  840. var lastLog *string
  841. if u.updatingStep != nil {
  842. // JS: state.updating?.log?.slice(-800) ?? state.lastLog ?? null
  843. l := tail(u.updatingLog, statusLogTail)
  844. lastLog = &l
  845. } else {
  846. lastLog = u.lastLog
  847. }
  848. return Status{
  849. Current: u.current,
  850. Latest: u.latest,
  851. CurrentVersion: u.currentVersion,
  852. LatestVersion: u.latestVersion,
  853. LatestMsg: u.latestMsg,
  854. LatestBody: u.latestBody,
  855. Commits: u.commits,
  856. CompareURL: u.compareURL,
  857. UpdateAvailable: u.updateAvail,
  858. CanApply: u.canApply,
  859. Mode: u.mode,
  860. LastCheck: u.lastCheck,
  861. Updating: updating,
  862. Error: u.err,
  863. LastLog: lastLog,
  864. Repo: u.repo,
  865. HasToken: u.token != "",
  866. CheckFailed: u.checkFailed,
  867. CheckErr: u.checkErr,
  868. PendingApply: u.pendingApply,
  869. }
  870. }
  871. // Start lanza el chequeo inicial y el timer de 6 h (paridad start()).
  872. // El contexto cubre las llamadas de red del Check: latest + compare (#490).
  873. func (u *Updater) Start() {
  874. u.wg.Add(1)
  875. go func() {
  876. defer u.wg.Done()
  877. ctx, cancel := context.WithTimeout(context.Background(), 2*httpTimeout+2*time.Second)
  878. u.Check(ctx)
  879. cancel()
  880. t := time.NewTicker(checkInterval)
  881. defer t.Stop()
  882. for {
  883. select {
  884. case <-u.stopCh:
  885. return
  886. case <-t.C:
  887. ctx, cancel := context.WithTimeout(context.Background(), 2*httpTimeout+2*time.Second)
  888. u.Check(ctx)
  889. cancel()
  890. }
  891. }
  892. }()
  893. }
  894. // Stop para el timer y espera a los procesos en curso (paridad stop()).
  895. func (u *Updater) Stop() {
  896. select {
  897. case <-u.stopCh:
  898. default:
  899. close(u.stopCh)
  900. }
  901. u.wg.Wait()
  902. }
  903. // appliedMarkerPath: fichero que update.sh (rolling) o el helper root
  904. // (estable, #480) escriben justo antes de tocar el flag de reinicio (#444).
  905. func (u *Updater) appliedMarkerPath() string {
  906. if u.mode == "stable" && u.dataDir != "" {
  907. // En estable el repoRoot (padre del working dir, p.ej. /var/lib)
  908. // no es escribible por el servicio: el marcador vive en el dataDir.
  909. return filepath.Join(u.dataDir, stableAppliedName)
  910. }
  911. return filepath.Join(u.repoRoot, ".update-applied")
  912. }
  913. // readAppliedMarker devuelve el SHA objetivo escrito por update.sh ("" si no
  914. // existe o no es legible).
  915. func readAppliedMarker(path string) string {
  916. b, err := os.ReadFile(path)
  917. if err != nil {
  918. return ""
  919. }
  920. return strings.TrimSpace(string(b))
  921. }
  922. // markerMatchesTarget compara el SHA del marcador (completo, 40 chars, lo
  923. // que escribe `git rev-parse HEAD` en update.sh) con el target registrado
  924. // (corto, 7 chars, lo que guarda el check) por PREFIJO y sin distinguir
  925. // mayúsculas (#512: la igualdad literal hacía imposible el camino de éxito
  926. // de #444 y todo apply con reinicio registraba "update_exit_-1").
  927. func markerMatchesTarget(marker, target string) bool {
  928. m := strings.ToLower(strings.TrimSpace(marker))
  929. t := strings.ToLower(strings.TrimSpace(target))
  930. if m == "" || t == "" {
  931. return false
  932. }
  933. n := len(m)
  934. if len(t) < n {
  935. n = len(t)
  936. }
  937. return m[:n] == t[:n]
  938. }
  939. // shortSHA trunca un SHA al formato corto de display (7 chars), aceptando
  940. // ambos formatos como entrada.
  941. func shortSHA(sha string) string {
  942. s := strings.TrimSpace(sha)
  943. if len(s) > 7 {
  944. return s[:7]
  945. }
  946. return s
  947. }