readiness.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // readiness.go — pre-flight checks del apply (issue #160): espacio en disco
  2. // para descarga+backup, working tree de git limpio, red hacia GitHub y sin
  3. // update concurrente. Se expone en /api/update/status (campo `readiness`) y
  4. // el frontend bloquea el botón de aplicar si algo falla.
  5. //
  6. // El cómputo se cachea readinessTTL: el network check hace una petición HTTP
  7. // y no debe bloquear el polling de status (2,5 s durante el apply).
  8. package updater
  9. import (
  10. "context"
  11. "fmt"
  12. "net/http"
  13. "os/exec"
  14. "path/filepath"
  15. "strings"
  16. "syscall"
  17. "time"
  18. )
  19. const (
  20. // readinessTTL: cuánto tiempo se sirve el readiness cacheado (el network
  21. // check toca red; no recalcular en cada poll de status).
  22. readinessTTL = 30 * time.Second
  23. // readinessNetTimeout: tope para el check de red hacia GitHub.
  24. readinessNetTimeout = 5 * time.Second
  25. )
  26. // probeURL es el endpoint del check de conectividad. Es github.com (HTML) y
  27. // NO api.github.com a propósito (issue #956): la API anónima tiene cuota de
  28. // 60 req/h por IP y el readiness se recomputa cada readinessTTL mientras la
  29. // UI de actualización está abierta, lo que agotaba la cuota y luego impedía
  30. // al apply descargar los metadatos de la release. La web pública no cuenta
  31. // contra esa cuota y un 4xx también prueba conectividad.
  32. // Var de paquete para apuntarlo al httptest de los tests.
  33. var probeURL = "https://github.com"
  34. // SetProbeURL cambia el destino del check de conectividad y devuelve la
  35. // funcion para restaurarlo. Solo para tests: el check no debe depender de que
  36. // el runner de CI alcance internet (#160).
  37. func SetProbeURL(u string) (restore func()) {
  38. old := probeURL
  39. probeURL = u
  40. return func() { probeURL = old }
  41. }
  42. // minDiskFreeBytes es el espacio libre mínimo exigido en repoRoot (descarga
  43. // del binario de CI ~40 MB + backup del binario actual + margen de build).
  44. // Var de paquete para poder bajarlo en tests.
  45. var minDiskFreeBytes int64 = 500 * 1024 * 1024
  46. // CheckResult es el resultado de un check individual.
  47. //
  48. // Detail lo escribe el servidor en castellano y se mantiene como respaldo para
  49. // clientes antiguos. La UI actual usa Code y Vars: el servidor no pre-formatea
  50. // texto traducible (#1036), así que cada check publica un slug estable y sus
  51. // números, y el idioma lo pone el frontend (#1811).
  52. type CheckResult struct {
  53. OK bool `json:"ok"`
  54. Detail string `json:"detail,omitempty"`
  55. Code string `json:"code,omitempty"`
  56. Vars map[string]string `json:"vars,omitempty"`
  57. }
  58. // Readiness agrupa los pre-flight checks del apply (issue #160).
  59. type Readiness struct {
  60. Disk CheckResult `json:"disk"`
  61. Git CheckResult `json:"git"`
  62. Network CheckResult `json:"network"`
  63. Concurrent CheckResult `json:"concurrent"`
  64. Ready bool `json:"ready"`
  65. }
  66. // Readiness devuelve los checks (cacheados readinessTTL). Nil si el layout no
  67. // permite auto-apply (modo estable install.sh): el frontend ya muestra el
  68. // enlace a releases en vez del botón de aplicar.
  69. func (u *Updater) Readiness() *Readiness {
  70. if !u.canApply {
  71. return nil
  72. }
  73. u.mu.Lock()
  74. if u.readiness != nil && time.Since(u.readinessAt) < readinessTTL {
  75. r := u.readiness
  76. u.mu.Unlock()
  77. return r
  78. }
  79. u.mu.Unlock()
  80. r := u.computeReadiness()
  81. u.mu.Lock()
  82. u.readiness = &r
  83. u.readinessAt = time.Now()
  84. u.mu.Unlock()
  85. return &r
  86. }
  87. // computeReadiness ejecuta los 4 checks sin cache.
  88. func (u *Updater) computeReadiness() Readiness {
  89. r := Readiness{
  90. Disk: u.checkDisk(),
  91. Git: u.checkGit(),
  92. Network: u.checkNetwork(),
  93. Concurrent: u.checkConcurrent(),
  94. }
  95. r.Ready = u.canApply && r.Disk.OK && r.Git.OK && r.Network.OK && r.Concurrent.OK
  96. return r
  97. }
  98. // checkDisk verifica espacio libre en repoRoot (donde se backupa el binario
  99. // y se trabaja durante el update).
  100. func (u *Updater) checkDisk() CheckResult {
  101. path := u.repoRoot
  102. if path == "" {
  103. path = "."
  104. }
  105. var st syscall.Statfs_t
  106. if err := syscall.Statfs(path, &st); err != nil {
  107. return CheckResult{OK: false, Detail: "no se pudo leer el espacio en disco", Code: "diskError"}
  108. }
  109. free := int64(st.Bavail) * int64(st.Bsize)
  110. if free < minDiskFreeBytes {
  111. return CheckResult{
  112. OK: false,
  113. Detail: fmt.Sprintf("%d MB libres, se necesitan %d", free/(1<<20), minDiskFreeBytes/(1<<20)),
  114. Code: "diskLow",
  115. Vars: map[string]string{
  116. "free": fmt.Sprintf("%d", free/(1<<20)),
  117. "need": fmt.Sprintf("%d", minDiskFreeBytes/(1<<20)),
  118. },
  119. }
  120. }
  121. return CheckResult{
  122. OK: true,
  123. Detail: fmt.Sprintf("%d MB libres", free/(1<<20)),
  124. Code: "diskOk",
  125. Vars: map[string]string{"free": fmt.Sprintf("%d", free/(1<<20))},
  126. }
  127. }
  128. // checkGit verifica que el working tree está limpio (update.sh hace
  129. // git reset --hard: cualquier cambio sin commitear se perdería). Se ignoran
  130. // los untracked (--untracked-files=no): artefactos runtime del servidor
  131. // (.env, data/, binarios, backups) viven fuera de git y un reset --hard no
  132. // los toca — de otro modo el apply quedaría bloqueado para siempre.
  133. func (u *Updater) checkGit() CheckResult {
  134. if u.mode != "rolling" {
  135. return CheckResult{OK: true, Detail: "no aplica (layout estable)", Code: "gitStable"}
  136. }
  137. // Rolling sin clone (.git ausente, p.ej. el layout estable actualizado
  138. // in place con deploy/update.sh copiado): update.sh resuelve el SHA de
  139. // main vía ls-remote y NO hace git reset --hard (issue #897), así que no
  140. // hay working tree que proteger. Sin este skip el check fallaba con "no
  141. // se pudo leer el estado de git" y bloqueaba el apply para siempre
  142. // (issue #955).
  143. if !fileExists(filepath.Join(u.repoRoot, ".git")) {
  144. return CheckResult{OK: true, Detail: "no aplica (sin clone git)", Code: "gitNoClone"}
  145. }
  146. out, err := exec.Command("git", "-C", u.repoRoot, "status", "--porcelain", "--untracked-files=no").Output()
  147. if err != nil {
  148. return CheckResult{OK: false, Detail: "no se pudo leer el estado de git", Code: "gitError"}
  149. }
  150. if len(strings.TrimSpace(string(out))) > 0 {
  151. return CheckResult{OK: false, Detail: "hay cambios sin commitear", Code: "gitDirty"}
  152. }
  153. return CheckResult{OK: true}
  154. }
  155. // checkNetwork comprueba que GitHub es alcanzable (cualquier respuesta HTTP
  156. // cuenta: un 4xx también significa que hay conectividad). Usa probeURL (web
  157. // pública, sin cuota de API; #956).
  158. func (u *Updater) checkNetwork() CheckResult {
  159. ctx, cancel := context.WithTimeout(context.Background(), readinessNetTimeout)
  160. defer cancel()
  161. req, err := http.NewRequestWithContext(ctx, "GET", probeURL, nil)
  162. if err != nil {
  163. return CheckResult{OK: false, Detail: "URL de API inválida", Code: "netUrl"}
  164. }
  165. req.Header.Set("User-Agent", "netpulse-updater")
  166. client := &http.Client{Timeout: readinessNetTimeout}
  167. res, err := client.Do(req)
  168. if err != nil {
  169. return CheckResult{OK: false, Detail: "no se pudo contactar con GitHub", Code: "netUnreachable"}
  170. }
  171. res.Body.Close()
  172. return CheckResult{OK: true}
  173. }
  174. // checkConcurrent verifica que no hay ya un update en curso (mismo flag que
  175. // Apply usa para devolver 409 already_updating).
  176. func (u *Updater) checkConcurrent() CheckResult {
  177. u.mu.Lock()
  178. defer u.mu.Unlock()
  179. if u.updatingStep != nil {
  180. return CheckResult{OK: false, Detail: "hay una actualización en curso", Code: "busy"}
  181. }
  182. return CheckResult{OK: true}
  183. }