stable.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // stable.go — auto-apply en layout estable (single-binary de install.sh,
  2. // issue #480). El server corre como usuario netpulse con sandbox
  3. // ProtectSystem=strict: NO puede reemplazar /usr/local/bin/netpulse. Flujo:
  4. //
  5. // 1. El updater descarga el asset de la release estable (tarball +
  6. // checksums.txt) a <dataDir>/updates/ y verifica el sha256 del tarball
  7. // contra checksums.txt (mismo formato que usa install.sh).
  8. // 2. Extrae el binario a <dataDir>/updates/netpulse.new, le calcula su
  9. // sha256 y escribe el marcador <dataDir>/.stable-update (atómico, vía
  10. // rename) con target/sha256/ruta del binario en escena.
  11. // 3. La unidad root netpulse-stable-update.path (instalada por install.sh,
  12. // detectada por stableUnitInstalled) reacciona al marcador y lanza el
  13. // helper netpulse-stable-apply, que RE-VERIFICA el sha256, respalda el
  14. // binario actual, hace swap, escribe el marcador de éxito
  15. // .update-applied con el objetivo (patrón #444), reinicia el servicio y
  16. // comprueba health; ante cualquier fallo restaura el binario anterior.
  17. // 4. El restart mata este proceso, así que el éxito se confirma en el
  18. // arranque siguiente: loadPendingApply compara la versión embebida con
  19. // el marcador persistido (#161) y marca el historial (patrón #444
  20. // extendido a boot-time).
  21. package updater
  22. import (
  23. "archive/tar"
  24. "compress/gzip"
  25. "crypto/sha256"
  26. "encoding/hex"
  27. "fmt"
  28. "io"
  29. "net/http"
  30. "os"
  31. "path/filepath"
  32. "runtime"
  33. "strings"
  34. "time"
  35. )
  36. const (
  37. // stableMarkerName dispara la unidad root (PathChanged). Se escribe de
  38. // forma atómica (tmp + rename) para que el helper nunca lea a medias.
  39. stableMarkerName = ".stable-update"
  40. // stableAppliedName: objetivo escrito por el helper justo antes de
  41. // reiniciar (mismo papel que el .update-applied de update.sh en rolling,
  42. // issue #444).
  43. stableAppliedName = ".update-applied"
  44. // stableErrorName: código de fallo del helper (verificación, swap o
  45. // healthcheck con rollback). Informativo; el historial manda.
  46. stableErrorName = ".stable-update.error"
  47. // stableBinName: nombre del binario dentro del tarball de release y
  48. // base del nombre de asset (netpulse_<ver>_linux_<GOARCH>.tar.gz).
  49. stableBinName = "netpulse"
  50. // stableMaxBinSize cota el tamaño del binario extraído (defensa).
  51. stableMaxBinSize = 256 << 20
  52. // stableRestartWait: espera máxima al swap+restart. En producción el
  53. // proceso muere en segundos; si vence, el apply se marca fallido y se
  54. // retira el marcador para que no dispare un swap tardío.
  55. stableRestartWait = 3 * time.Minute
  56. )
  57. // downloadBase es la base de los assets de release (inyectable en tests).
  58. var downloadBase = "https://github.com"
  59. // downloadClient: el tarball ronda los 20 MB; el timeout de la API (8 s)
  60. // no aplica aquí.
  61. var downloadClient = &http.Client{Timeout: 10 * time.Minute}
  62. // stableUnitInstalled detecta la unidad root que hace el swap: busca
  63. // /etc/systemd/system/<binario>-stable-update.path (install.sh la nombra a
  64. // partir del binario, igual que las unidades -restart). Var de paquete para
  65. // poder sobreescribirla en tests.
  66. var stableUnitInstalled = func() bool {
  67. exe, err := os.Executable()
  68. if err != nil {
  69. return false
  70. }
  71. unit := filepath.Join("/etc/systemd/system", filepath.Base(exe)+"-stable-update.path")
  72. _, err = os.Stat(unit)
  73. return err == nil
  74. }
  75. // WithDataDir fija el dataDir real (ruta resuelta de DATA_DIR). Necesario
  76. // para el auto-apply estable (#480): staging y marcadores viven ahí. Sin
  77. // dataDir el apply estable falla con stable_no_datadir. Encadenable tras
  78. // New(); debe llamarse antes de servir tráfico. Como New() ya lanzó
  79. // loadPendingApply sin dataDir, aquí corre la confirmación estable
  80. // pendiente (loadStablePending): es el "arranque siguiente" de un apply
  81. // que murió con el restart.
  82. func (u *Updater) WithDataDir(path string) *Updater {
  83. // Sin u.mu a propósito: dataDir es boot-time e inmutable tras la
  84. // construcción (paridad repoRoot/version en New), y loadStablePending
  85. // toma u.mu al confirmar (mutex no reentrante).
  86. u.dataDir = path
  87. if path != "" {
  88. u.loadStablePending()
  89. }
  90. return u
  91. }
  92. // applyStable ejecuta el flujo completo de staging (download → verify →
  93. // install → restart) emitiendo los mismos pasos del contrato #280. Al final
  94. // espera la muerte del proceso (el restart de la unidad root); si no llega,
  95. // aborta limpio.
  96. func (u *Updater) applyStable(historyID int64, tag string, startedAt time.Time) {
  97. fail := func(code string) {
  98. u.mu.Lock()
  99. u.updatingStep = nil
  100. u.err = &code
  101. u.broadcastLocked()
  102. u.mu.Unlock()
  103. u.finishHistory(historyID, "failed", code, time.Since(startedAt))
  104. u.clearPendingApply()
  105. fmt.Printf("[netpulse:update] apply estable fallido: %s\n", code)
  106. }
  107. if u.dataDir == "" {
  108. fail("stable_no_datadir")
  109. return
  110. }
  111. ver := strings.TrimPrefix(tag, "v")
  112. asset := fmt.Sprintf("%s_%s_linux_%s.tar.gz", stableBinName, ver, runtime.GOARCH)
  113. u.mu.Lock()
  114. u.setStepLocked("download")
  115. u.broadcastLocked()
  116. u.mu.Unlock()
  117. fmt.Printf("[netpulse:update] estable: descargando %s (%s)\n", asset, tag)
  118. staging := filepath.Join(u.dataDir, "updates")
  119. _ = os.RemoveAll(staging) // restos de intentos previos
  120. _ = os.Remove(filepath.Join(u.dataDir, stableErrorName))
  121. if err := os.MkdirAll(staging, 0o755); err != nil {
  122. fail("stable_staging_failed")
  123. return
  124. }
  125. tgz := filepath.Join(staging, asset)
  126. base := fmt.Sprintf("%s/%s/releases/download/%s", downloadBase, u.repo, tag)
  127. if err := downloadToFile(base+"/"+asset, tgz); err != nil {
  128. fmt.Printf("[netpulse:update] descarga de %s falló: %v\n", asset, err)
  129. fail("stable_download_failed")
  130. return
  131. }
  132. if err := downloadToFile(base+"/checksums.txt", filepath.Join(staging, "checksums.txt")); err != nil {
  133. fmt.Printf("[netpulse:update] descarga de checksums.txt falló: %v\n", err)
  134. fail("stable_download_failed")
  135. return
  136. }
  137. u.mu.Lock()
  138. u.setStepLocked("verify")
  139. u.broadcastLocked()
  140. u.mu.Unlock()
  141. want, err := checksumFor(filepath.Join(staging, "checksums.txt"), asset)
  142. if err != nil {
  143. fail("stable_checksum_missing")
  144. return
  145. }
  146. got, err := fileSHA256(tgz)
  147. if err != nil {
  148. fail("stable_checksum_missing")
  149. return
  150. }
  151. if !strings.EqualFold(want, got) {
  152. fmt.Printf("[netpulse:update] sha256 mismatch del tarball: want %s got %s\n", want, got)
  153. fail("stable_checksum_mismatch")
  154. return
  155. }
  156. binNew, err := extractBinary(tgz, staging)
  157. if err != nil {
  158. fail("stable_extract_failed")
  159. return
  160. }
  161. // sha256 del binario YA extraído: el helper lo re-verifica antes del
  162. // swap (defensa en profundidad: el marcador vive en disco).
  163. binSHA, err := fileSHA256(binNew)
  164. if err != nil {
  165. fail("stable_extract_failed")
  166. return
  167. }
  168. u.mu.Lock()
  169. u.setStepLocked("install")
  170. u.broadcastLocked()
  171. u.mu.Unlock()
  172. marker := filepath.Join(u.dataDir, stableMarkerName)
  173. tmp := marker + ".tmp"
  174. content := fmt.Sprintf("target=%s\nsha256=%s\nstaged=%s\n", tag, binSHA, binNew)
  175. if err := os.WriteFile(tmp, []byte(content), 0o644); err != nil {
  176. fail("stable_marker_failed")
  177. return
  178. }
  179. if err := os.Rename(tmp, marker); err != nil {
  180. fail("stable_marker_failed")
  181. return
  182. }
  183. u.mu.Lock()
  184. u.setStepLocked("restart")
  185. u.broadcastLocked()
  186. u.mu.Unlock()
  187. fmt.Printf("[netpulse:update] estable %s en escena; esperando swap+restart (unidad root)\n", tag)
  188. // En producción el helper reinicia el servicio y el proceso muere aquí
  189. // con el binario nuevo. En tests, Stop() desbloquea sin marcar nada
  190. // (el éxito se confirma en el "arranque siguiente", ver loadPendingApply).
  191. select {
  192. case <-u.stopCh:
  193. return
  194. case <-time.After(stableRestartWait):
  195. _ = os.Remove(marker)
  196. fail("stable_restart_timeout")
  197. }
  198. }
  199. func downloadToFile(url, dst string) error {
  200. resp, err := downloadClient.Get(url)
  201. if err != nil {
  202. return err
  203. }
  204. defer resp.Body.Close()
  205. if resp.StatusCode != http.StatusOK {
  206. return fmt.Errorf("http %d para %s", resp.StatusCode, url)
  207. }
  208. f, err := os.Create(dst)
  209. if err != nil {
  210. return err
  211. }
  212. defer f.Close()
  213. _, err = io.Copy(f, io.LimitReader(resp.Body, stableMaxBinSize))
  214. return err
  215. }
  216. func fileSHA256(path string) (string, error) {
  217. f, err := os.Open(path)
  218. if err != nil {
  219. return "", err
  220. }
  221. defer f.Close()
  222. h := sha256.New()
  223. if _, err := io.Copy(h, f); err != nil {
  224. return "", err
  225. }
  226. return hex.EncodeToString(h.Sum(nil)), nil
  227. }
  228. // checksumFor extrae de checksums.txt el sha256 del asset dado (líneas
  229. // "<hex> <nombre>", mismo formato que grepea install.sh).
  230. func checksumFor(sumsFile, asset string) (string, error) {
  231. data, err := os.ReadFile(sumsFile)
  232. if err != nil {
  233. return "", err
  234. }
  235. for _, line := range strings.Split(string(data), "\n") {
  236. fields := strings.Fields(line)
  237. if len(fields) == 2 && fields[1] == asset {
  238. return fields[0], nil
  239. }
  240. }
  241. return "", fmt.Errorf("%s no está en %s", asset, sumsFile)
  242. }
  243. // extractBinary extrae la entrada "netpulse" (posible prefijo ./) del
  244. // tarball a staging como netpulse.new con 0755. Rechaza entradas raras.
  245. func extractBinary(tgz, staging string) (string, error) {
  246. f, err := os.Open(tgz)
  247. if err != nil {
  248. return "", err
  249. }
  250. defer f.Close()
  251. gz, err := gzip.NewReader(f)
  252. if err != nil {
  253. return "", err
  254. }
  255. defer gz.Close()
  256. tr := tar.NewReader(gz)
  257. for {
  258. hdr, err := tr.Next()
  259. if err == io.EOF {
  260. return "", fmt.Errorf("tarball sin entrada %s", stableBinName)
  261. }
  262. if err != nil {
  263. return "", err
  264. }
  265. name := strings.TrimPrefix(hdr.Name, "./")
  266. if name != stableBinName || hdr.Typeflag != tar.TypeReg {
  267. continue
  268. }
  269. if hdr.Size > stableMaxBinSize {
  270. return "", fmt.Errorf("entrada %s demasiado grande (%d)", name, hdr.Size)
  271. }
  272. dst := filepath.Join(staging, "netpulse.new")
  273. out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
  274. if err != nil {
  275. return "", err
  276. }
  277. if _, err := io.Copy(out, io.LimitReader(tr, stableMaxBinSize)); err != nil {
  278. out.Close()
  279. return "", err
  280. }
  281. if err := out.Close(); err != nil {
  282. return "", err
  283. }
  284. return dst, nil
  285. }
  286. }