stable.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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] stable apply failed: %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] stable: downloading %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, 0o770); err != nil {
  122. fail("stable_staging_failed")
  123. return
  124. }
  125. if err := os.Chmod(staging, 0o770); err != nil {
  126. fail("stable_staging_failed")
  127. return
  128. }
  129. tgz := filepath.Join(staging, asset)
  130. base := fmt.Sprintf("%s/%s/releases/download/%s", downloadBase, u.repo, tag)
  131. if err := downloadToFile(base+"/"+asset, tgz); err != nil {
  132. fmt.Printf("[netpulse:update] download of %s failed: %v\n", asset, err)
  133. fail("stable_download_failed")
  134. return
  135. }
  136. if err := downloadToFile(base+"/checksums.txt", filepath.Join(staging, "checksums.txt")); err != nil {
  137. fmt.Printf("[netpulse:update] download of checksums.txt failed: %v\n", err)
  138. fail("stable_download_failed")
  139. return
  140. }
  141. u.mu.Lock()
  142. u.setStepLocked("verify")
  143. u.broadcastLocked()
  144. u.mu.Unlock()
  145. want, err := checksumFor(filepath.Join(staging, "checksums.txt"), asset)
  146. if err != nil {
  147. fail("stable_checksum_missing")
  148. return
  149. }
  150. got, err := fileSHA256(tgz)
  151. if err != nil {
  152. fail("stable_checksum_missing")
  153. return
  154. }
  155. if !strings.EqualFold(want, got) {
  156. fmt.Printf("[netpulse:update] tarball sha256 mismatch: want %s got %s\n", want, got)
  157. fail("stable_checksum_mismatch")
  158. return
  159. }
  160. binNew, err := extractBinary(tgz, staging)
  161. if err != nil {
  162. fail("stable_extract_failed")
  163. return
  164. }
  165. // sha256 del binario YA extraído: el helper lo re-verifica antes del
  166. // swap (defensa en profundidad: el marcador vive en disco).
  167. binSHA, err := fileSHA256(binNew)
  168. if err != nil {
  169. fail("stable_extract_failed")
  170. return
  171. }
  172. u.mu.Lock()
  173. u.setStepLocked("install")
  174. u.broadcastLocked()
  175. u.mu.Unlock()
  176. marker := filepath.Join(u.dataDir, stableMarkerName)
  177. tmp := marker + ".tmp"
  178. content := fmt.Sprintf("target=%s\nsha256=%s\nstaged=%s\n", tag, binSHA, binNew)
  179. if err := os.WriteFile(tmp, []byte(content), 0o640); err != nil {
  180. fail("stable_marker_failed")
  181. return
  182. }
  183. if err := os.Rename(tmp, marker); err != nil {
  184. fail("stable_marker_failed")
  185. return
  186. }
  187. u.mu.Lock()
  188. u.setStepLocked("restart")
  189. u.broadcastLocked()
  190. u.mu.Unlock()
  191. fmt.Printf("[netpulse:update] stable %s staged, waiting for swap+restart (root unit)\n", tag)
  192. // En producción el helper reinicia el servicio y el proceso muere aquí
  193. // con el binario nuevo. En tests, Stop() desbloquea sin marcar nada
  194. // (el éxito se confirma en el "arranque siguiente", ver loadPendingApply).
  195. select {
  196. case <-u.stopCh:
  197. return
  198. case <-time.After(stableRestartWait):
  199. _ = os.Remove(marker)
  200. fail("stable_restart_timeout")
  201. }
  202. }
  203. func downloadToFile(url, dst string) error {
  204. resp, err := downloadClient.Get(url)
  205. if err != nil {
  206. return err
  207. }
  208. defer resp.Body.Close()
  209. if resp.StatusCode != http.StatusOK {
  210. return fmt.Errorf("http %d para %s", resp.StatusCode, url)
  211. }
  212. f, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o640)
  213. if err != nil {
  214. return err
  215. }
  216. if err := f.Chmod(0o640); err != nil {
  217. f.Close()
  218. return err
  219. }
  220. defer f.Close()
  221. _, err = io.Copy(f, io.LimitReader(resp.Body, stableMaxBinSize))
  222. return err
  223. }
  224. func fileSHA256(path string) (string, error) {
  225. f, err := os.Open(path)
  226. if err != nil {
  227. return "", err
  228. }
  229. defer f.Close()
  230. h := sha256.New()
  231. if _, err := io.Copy(h, f); err != nil {
  232. return "", err
  233. }
  234. return hex.EncodeToString(h.Sum(nil)), nil
  235. }
  236. // checksumFor extrae de checksums.txt el sha256 del asset dado (líneas
  237. // "<hex> <nombre>", mismo formato que grepea install.sh).
  238. func checksumFor(sumsFile, asset string) (string, error) {
  239. data, err := os.ReadFile(sumsFile)
  240. if err != nil {
  241. return "", err
  242. }
  243. for _, line := range strings.Split(string(data), "\n") {
  244. fields := strings.Fields(line)
  245. if len(fields) == 2 && fields[1] == asset {
  246. return fields[0], nil
  247. }
  248. }
  249. return "", fmt.Errorf("%s not found in %s", asset, sumsFile)
  250. }
  251. // extractBinary extrae la entrada "netpulse" (posible prefijo ./) del
  252. // tarball a staging como netpulse.new con 0755. Rechaza entradas raras.
  253. func extractBinary(tgz, staging string) (string, error) {
  254. f, err := os.Open(tgz)
  255. if err != nil {
  256. return "", err
  257. }
  258. defer f.Close()
  259. gz, err := gzip.NewReader(f)
  260. if err != nil {
  261. return "", err
  262. }
  263. defer gz.Close()
  264. tr := tar.NewReader(gz)
  265. for {
  266. hdr, err := tr.Next()
  267. if err == io.EOF {
  268. return "", fmt.Errorf("tarball has no entry %s", stableBinName)
  269. }
  270. if err != nil {
  271. return "", err
  272. }
  273. name := strings.TrimPrefix(hdr.Name, "./")
  274. if name != stableBinName || hdr.Typeflag != tar.TypeReg {
  275. continue
  276. }
  277. if hdr.Size > stableMaxBinSize {
  278. return "", fmt.Errorf("entry %s too large (%d)", name, hdr.Size)
  279. }
  280. dst := filepath.Join(staging, "netpulse.new")
  281. out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o750)
  282. if err != nil {
  283. return "", err
  284. }
  285. if _, err := io.Copy(out, io.LimitReader(tr, stableMaxBinSize)); err != nil {
  286. out.Close()
  287. return "", err
  288. }
  289. if err := out.Close(); err != nil {
  290. return "", err
  291. }
  292. return dst, nil
  293. }
  294. }