stable_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // stable_test.go — auto-apply en layout estable (#480): capacidad (unidad
  2. // root instalada), flujo de staging feliz (download+verify+marcador),
  3. // confirmación en el arranque siguiente (patrón #444) y fallos (checksum).
  4. package updater
  5. import (
  6. "archive/tar"
  7. "compress/gzip"
  8. "context"
  9. "crypto/sha256"
  10. "encoding/hex"
  11. "fmt"
  12. "net/http"
  13. "net/http/httptest"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. "strings"
  18. "testing"
  19. "time"
  20. )
  21. // overrideStableUnit fuerza el resultado de la detección de la unidad root
  22. // durante el test.
  23. func overrideStableUnit(t *testing.T, installed bool) {
  24. t.Helper()
  25. old := stableUnitInstalled
  26. stableUnitInstalled = func() bool { return installed }
  27. t.Cleanup(func() { stableUnitInstalled = old })
  28. }
  29. // fakeReleaseAsset construye un tarball con un binario "netpulse" dentro y
  30. // devuelve (bytes del tarball, sha256 hex del tarball).
  31. func fakeReleaseAsset(t *testing.T, binContent string) ([]byte, string) {
  32. t.Helper()
  33. var buf strings.Builder
  34. gz := gzip.NewWriter(&bufWriter{&buf})
  35. tw := tar.NewWriter(gz)
  36. if err := tw.WriteHeader(&tar.Header{Name: "netpulse", Mode: 0o755, Size: int64(len(binContent))}); err != nil {
  37. t.Fatal(err)
  38. }
  39. if _, err := tw.Write([]byte(binContent)); err != nil {
  40. t.Fatal(err)
  41. }
  42. if err := tw.Close(); err != nil {
  43. t.Fatal(err)
  44. }
  45. if err := gz.Close(); err != nil {
  46. t.Fatal(err)
  47. }
  48. raw := []byte(buf.String())
  49. sum := sha256.Sum256(raw)
  50. return raw, hex.EncodeToString(sum[:])
  51. }
  52. // bufWriter adapta strings.Builder a io.Writer sin copiar el contenido dos
  53. // veces (Write recibe la porción, no el builder entero).
  54. type bufWriter struct{ b *strings.Builder }
  55. func (w *bufWriter) Write(p []byte) (int, error) { return w.b.Write(p) }
  56. // serveStableRelease monta un httptest que hace de GitHub: APIBase para
  57. // /releases/latest y downloadBase para los assets del tag dado.
  58. func serveStableRelease(t *testing.T, tag, asset, tgzSum string, tgzBytes []byte, sumLine string) {
  59. t.Helper()
  60. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  61. if r.URL.Path == "/" {
  62. return // probe de readiness: solo comprueba conectividad
  63. }
  64. // Compare del changelog (issue #490): se tolera sin fallar el test.
  65. if strings.Contains(r.URL.Path, "/compare/") {
  66. fmt.Fprint(w, `{"commits":[]}`)
  67. return
  68. }
  69. if r.URL.Path != "/repos/owner/netpulse/releases/latest" {
  70. t.Errorf("API path inesperado: %s", r.URL.Path)
  71. w.WriteHeader(404)
  72. return
  73. }
  74. w.Header().Set("Content-Type", "application/json")
  75. fmt.Fprintf(w, `{"tag_name":%q,"name":%q,"body":"notas de %s"}`, tag, tag, tag)
  76. })
  77. dl := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  78. want := "/owner/netpulse/releases/download/" + tag
  79. if !strings.HasPrefix(r.URL.Path, want+"/") {
  80. t.Errorf("download path inesperado: %s", r.URL.Path)
  81. w.WriteHeader(404)
  82. return
  83. }
  84. switch filepath.Base(r.URL.Path) {
  85. case asset:
  86. w.Header().Set("Content-Type", "application/gzip")
  87. _, _ = w.Write(tgzBytes)
  88. case "checksums.txt":
  89. fmt.Fprintf(w, "%s %s\n", sumLine, asset)
  90. default:
  91. w.WriteHeader(404)
  92. }
  93. }))
  94. t.Cleanup(dl.Close)
  95. old := downloadBase
  96. downloadBase = dl.URL
  97. t.Cleanup(func() { downloadBase = old })
  98. }
  99. func waitStableMarker(t *testing.T, dataDir string) string {
  100. t.Helper()
  101. marker := filepath.Join(dataDir, stableMarkerName)
  102. deadline := time.Now().Add(15 * time.Second)
  103. for {
  104. if _, err := os.Stat(marker); err == nil {
  105. b, err := os.ReadFile(marker)
  106. if err != nil {
  107. t.Fatal(err)
  108. }
  109. return string(b)
  110. }
  111. if time.Now().After(deadline) {
  112. t.Fatalf("timeout esperando el marcador %s (status: %+v)", marker, func() any {
  113. u := marker
  114. return u
  115. }())
  116. }
  117. time.Sleep(25 * time.Millisecond)
  118. }
  119. }
  120. // Camino feliz: capacidad estable → Check (updateAvailable) → Apply →
  121. // marcador con sha256 y binario en escena → "arranque siguiente" con la
  122. // versión nueva y el marcador de éxito del helper → pendingApply + historial
  123. // success (patrón #444 extendido a boot-time).
  124. func TestStableApplyHappyPath(t *testing.T) {
  125. overrideStableUnit(t, true)
  126. bin := "#!/bin/sh\necho netpulse-9.9.9\n"
  127. tgz, tgzSum := fakeReleaseAsset(t, bin)
  128. asset := fmt.Sprintf("%s_9.9.9_linux_%s.tar.gz", stableBinName, runtime.GOARCH)
  129. serveStableRelease(t, "v9.9.9", asset, tgzSum, tgz, tgzSum)
  130. dataDir := t.TempDir()
  131. dbh := openDB(t)
  132. u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", dbh).WithDataDir(dataDir)
  133. st := u.Check(context.Background())
  134. if st.Error != nil || !st.UpdateAvailable || !st.CanApply {
  135. t.Fatalf("check: %+v", st)
  136. }
  137. if st.Mode != "stable" {
  138. t.Fatalf("mode: %s", st.Mode)
  139. }
  140. if !u.Apply() {
  141. t.Fatal("apply debería arrancar")
  142. }
  143. marker := waitStableMarker(t, dataDir)
  144. if !strings.Contains(marker, "target=v9.9.9") {
  145. t.Fatalf("marcador sin target: %q", marker)
  146. }
  147. stagedPath := fieldOf(marker, "staged")
  148. wantSHA := fieldOf(marker, "sha256")
  149. gotSHA, err := fileSHA256(stagedPath)
  150. if err != nil {
  151. t.Fatalf("binario en escena no accesible: %v", err)
  152. }
  153. if gotSHA != wantSHA {
  154. t.Fatalf("sha del binario en escena: got %s want %s", gotSHA, wantSHA)
  155. }
  156. // Simular al helper: swap OK → marcador de éxito con el objetivo y
  157. // limpieza del marcador disparador (el proceso muere con el restart).
  158. if err := os.WriteFile(filepath.Join(dataDir, stableAppliedName), []byte("v9.9.9\n"), 0o644); err != nil {
  159. t.Fatal(err)
  160. }
  161. _ = os.Remove(filepath.Join(dataDir, stableMarkerName))
  162. // "Arranque siguiente": updater nuevo con la versión ya actualizada.
  163. u.Stop() // libera la goroutine del apply (sigue esperando el restart)
  164. u2 := New(t.TempDir(), "owner/netpulse", "", "9.9.9", dbh).WithDataDir(dataDir)
  165. st2 := u2.Status()
  166. if st2.PendingApply == nil {
  167. t.Fatal("pendingApply debería confirmarse en el arranque con marcador de éxito")
  168. }
  169. if st2.PendingApply.From != "2.0.0" || st2.PendingApply.To != "9.9.9" {
  170. t.Fatalf("pendingApply: %+v", st2.PendingApply)
  171. }
  172. hist, err := ListHistory(dbh, 10)
  173. if err != nil {
  174. t.Fatal(err)
  175. }
  176. if len(hist) == 0 || hist[0].Status != "success" {
  177. t.Fatalf("historial: esperaba success re-marcado, got %+v", hist)
  178. }
  179. }
  180. // Sin el marcador de éxito del helper (apply murió a medias): el arranque
  181. // NO confirma y el historial queda fallido.
  182. func TestStableApplyWithoutHelperMarkerIsSilent(t *testing.T) {
  183. overrideStableUnit(t, true)
  184. bin := "x"
  185. tgz, tgzSum := fakeReleaseAsset(t, bin)
  186. asset := fmt.Sprintf("%s_9.9.9_linux_%s.tar.gz", stableBinName, runtime.GOARCH)
  187. serveStableRelease(t, "v9.9.9", asset, tgzSum, tgz, tgzSum)
  188. dataDir := t.TempDir()
  189. dbh := openDB(t)
  190. u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", dbh).WithDataDir(dataDir)
  191. if st := u.Check(context.Background()); !st.UpdateAvailable {
  192. t.Fatalf("check: %+v", st)
  193. }
  194. if !u.Apply() {
  195. t.Fatal("apply debería arrancar")
  196. }
  197. _ = waitStableMarker(t, dataDir)
  198. // El helper NO llega a escribir .update-applied (p.ej. sha mismatch).
  199. u.Stop()
  200. u2 := New(t.TempDir(), "owner/netpulse", "", "9.9.9", dbh).WithDataDir(dataDir)
  201. if u2.Status().PendingApply != nil {
  202. t.Fatal("sin marcador del helper no debería confirmarse")
  203. }
  204. hist, err := ListHistory(dbh, 10)
  205. if err != nil {
  206. t.Fatal(err)
  207. }
  208. if len(hist) == 0 || hist[0].Status != "failed" {
  209. t.Fatalf("historial: esperaba failed, got %+v", hist)
  210. }
  211. }
  212. // Checksum del tarball incorrecto: el apply falla, no hay marcador y el
  213. // pending se limpia (#161).
  214. func TestStableApplyChecksumMismatch(t *testing.T) {
  215. overrideStableUnit(t, true)
  216. bin := "x"
  217. tgz, _ := fakeReleaseAsset(t, bin)
  218. asset := fmt.Sprintf("%s_9.9.9_linux_%s.tar.gz", stableBinName, runtime.GOARCH)
  219. serveStableRelease(t, "v9.9.9", asset, "deadbeef", tgz, strings.Repeat("0", 64))
  220. dataDir := t.TempDir()
  221. dbh := openDB(t)
  222. u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", dbh).WithDataDir(dataDir)
  223. if st := u.Check(context.Background()); !st.UpdateAvailable {
  224. t.Fatalf("check: %+v", st)
  225. }
  226. if !u.Apply() {
  227. t.Fatal("apply debería arrancar")
  228. }
  229. deadline := time.Now().Add(15 * time.Second)
  230. for {
  231. if st := u.Status(); st.Error != nil && *st.Error == "stable_checksum_mismatch" {
  232. break
  233. }
  234. if time.Now().After(deadline) {
  235. t.Fatalf("timeout esperando stable_checksum_mismatch: %+v", u.Status())
  236. }
  237. time.Sleep(25 * time.Millisecond)
  238. }
  239. if _, err := os.Stat(filepath.Join(dataDir, stableMarkerName)); !os.IsNotExist(err) {
  240. t.Fatal("no debería quedar marcador tras un mismatch")
  241. }
  242. if _, ok := readPendingApply(dbh); ok {
  243. t.Fatal("pendingApply debe limpiarse en un fallo (#161)")
  244. }
  245. hist, err := ListHistory(dbh, 10)
  246. if err != nil {
  247. t.Fatal(err)
  248. }
  249. if len(hist) == 0 || hist[0].Status != "failed" || hist[0].Error == nil || *hist[0].Error != "stable_checksum_mismatch" {
  250. t.Fatalf("historial: %+v", hist[0])
  251. }
  252. }
  253. // Con la unidad root instalada, el layout estable pasa a canApply (#480);
  254. // sin ella, sigue !canApply (comportamiento previo intacto).
  255. func TestStableCapabilityWithUnit(t *testing.T) {
  256. overrideStableUnit(t, true)
  257. u := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil).WithDataDir(t.TempDir())
  258. if !u.CanApply() || u.mode != "stable" {
  259. t.Fatalf("estable+unidad debería ser stable/canApply: %+v", u.Status())
  260. }
  261. overrideStableUnit(t, false)
  262. u2 := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil).WithDataDir(t.TempDir())
  263. if u2.CanApply() || u2.mode != "stable" {
  264. t.Fatalf("estable sin unidad debería ser stable/!canApply")
  265. }
  266. }
  267. // El marcador .update-applied vive en el dataDir en estable y en el
  268. // repoRoot en rolling.
  269. func TestAppliedMarkerPathByMode(t *testing.T) {
  270. uRolling := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil)
  271. writeDeployScript(t, uRolling.repoRoot)
  272. // recrear para que la detección pille el update.sh
  273. uRolling = New(uRolling.repoRoot, "owner/netpulse", "", "1.0.0", nil)
  274. if !strings.HasSuffix(uRolling.appliedMarkerPath(), filepath.Join(uRolling.repoRoot, ".update-applied")) {
  275. t.Fatalf("rolling: %s", uRolling.appliedMarkerPath())
  276. }
  277. dataDir := t.TempDir()
  278. uStable := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil).WithDataDir(dataDir)
  279. if uStable.appliedMarkerPath() != filepath.Join(dataDir, stableAppliedName) {
  280. t.Fatalf("estable: %s", uStable.appliedMarkerPath())
  281. }
  282. }
  283. func fieldOf(marker, key string) string {
  284. for _, line := range strings.Split(marker, "\n") {
  285. if strings.HasPrefix(line, key+"=") {
  286. return strings.TrimPrefix(line, key+"=")
  287. }
  288. }
  289. return ""
  290. }