4
0

yield_test.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // yield_test.go: detección, cedida, idempotencia y garantía de que el sabor
  2. // embebido (runtime) nunca depende de este paquete (#369).
  3. package yield
  4. import (
  5. "context"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "testing"
  11. "time"
  12. )
  13. // fakeProc monta un /proc falso con un proceso por nombre.
  14. func fakeProc(t *testing.T, names map[int]string) string {
  15. t.Helper()
  16. root := t.TempDir()
  17. for pid, name := range names {
  18. dir := filepath.Join(root, strconv.Itoa(pid))
  19. if err := os.MkdirAll(dir, 0o755); err != nil {
  20. t.Fatal(err)
  21. }
  22. if err := os.WriteFile(filepath.Join(dir, "comm"), []byte(name+"\n"), 0o644); err != nil {
  23. t.Fatal(err)
  24. }
  25. }
  26. return root
  27. }
  28. func touch(t *testing.T, path string) {
  29. t.Helper()
  30. if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  31. t.Fatal(err)
  32. }
  33. if err := os.WriteFile(path, []byte("x"), 0o755); err != nil {
  34. t.Fatal(err)
  35. }
  36. }
  37. // TestNetgripPresentFiles: init.d o binario de netgrip cuentan como presencia.
  38. func TestNetgripPresentFiles(t *testing.T) {
  39. dir := t.TempDir()
  40. p := Paths{
  41. NetgripInit: filepath.Join(dir, "init.d", "netgrip"),
  42. NetgripBin: filepath.Join(dir, "sbin", "netgrip"),
  43. ProcRoot: "", // sin /proc: aislado del host de CI
  44. }
  45. if NetgripPresent(p) {
  46. t.Fatal("sin ficheros ni /proc no debería detectar")
  47. }
  48. touch(t, p.NetgripBin)
  49. if !NetgripPresent(p) {
  50. t.Fatal("el binario de netgrip debería detectarse")
  51. }
  52. os.Remove(p.NetgripBin)
  53. touch(t, p.NetgripInit)
  54. if !NetgripPresent(p) {
  55. t.Fatal("el init.d de netgrip debería detectarse")
  56. }
  57. }
  58. // TestNetgripPresentProc: proceso vivo por comm (ficheros ausentes).
  59. func TestNetgripPresentProc(t *testing.T) {
  60. proc := fakeProc(t, map[int]string{1: "procd", 42: "netgrip", 99: "netpulse-agent"})
  61. p := Paths{ProcRoot: proc}
  62. if !NetgripPresent(p) {
  63. t.Fatal("el proceso netgrip debería detectarse por comm")
  64. }
  65. p.ProcRoot = fakeProc(t, map[int]string{1: "procd", 99: "netpulse-agent"})
  66. if NetgripPresent(p) {
  67. t.Fatal("sin netgrip en /proc no debería detectar")
  68. }
  69. }
  70. // TestYieldFull: fichero de estado, orden disable->stop del init propio y
  71. // limpieza de la línea del watchdog del cron.
  72. func TestYieldFull(t *testing.T) {
  73. dir := t.TempDir()
  74. selfInit := filepath.Join(dir, "init.d", "netpulse-agent")
  75. touch(t, selfInit)
  76. cron := filepath.Join(dir, "crontabs", "root")
  77. touch(t, cron)
  78. if err := os.WriteFile(cron, []byte("*/5 * * * * /usr/sbin/algo\n*/2 * * * * /usr/sbin/netpulse-watchdog\n"), 0o600); err != nil {
  79. t.Fatal(err)
  80. }
  81. p := Paths{
  82. SelfInit: selfInit,
  83. StateFile: filepath.Join(dir, "netpulse-agent.yielded"),
  84. ProcRoot: "",
  85. CronFile: cron,
  86. }
  87. var cmds [][]string
  88. origRun := runCmd
  89. runCmd = func(name string, args ...string) error {
  90. cmds = append(cmds, append([]string{name}, args...))
  91. return nil
  92. }
  93. cancelled := false
  94. defer func() { runCmd = origRun }()
  95. Yield(p, "prueba", func() { cancelled = true })
  96. if !cancelled {
  97. t.Fatal("cancel debería invocarse al final de la cedida")
  98. }
  99. data, err := os.ReadFile(p.StateFile)
  100. if err != nil {
  101. t.Fatal("el fichero de estado debería existir tras la cedida")
  102. }
  103. if !strings.HasPrefix(string(data), "yielded=1\n") || !strings.Contains(string(data), "reason=prueba") {
  104. t.Fatalf("contenido inesperado del estado: %q", data)
  105. }
  106. // orden exacto: disable antes que stop (si stop mata el proceso, el
  107. // disable ya quedó aplicado)
  108. if len(cmds) != 2 || cmds[0][1] != "disable" || cmds[1][1] != "stop" {
  109. t.Fatalf("comandos inesperados: %v", cmds)
  110. }
  111. cronData, _ := os.ReadFile(cron)
  112. if strings.Contains(string(cronData), "netpulse-watchdog") {
  113. t.Fatalf("la línea del watchdog debería desaparecer del cron: %q", cronData)
  114. }
  115. if !strings.Contains(string(cronData), "/usr/sbin/algo") {
  116. t.Fatal("el resto del cron debería conservarse")
  117. }
  118. }
  119. // TestYieldIdempotente: una segunda cedida no rompe nada (estado se
  120. // reescribe, comandos se repiten pero todo es mejor esfuerzo).
  121. func TestYieldIdempotente(t *testing.T) {
  122. dir := t.TempDir()
  123. selfInit := filepath.Join(dir, "init.d", "netpulse-agent")
  124. touch(t, selfInit)
  125. p := Paths{SelfInit: selfInit, StateFile: filepath.Join(dir, "y"), ProcRoot: "", CronFile: ""}
  126. var n int
  127. origRun := runCmd
  128. runCmd = func(name string, args ...string) error { n++; return nil }
  129. defer func() { runCmd = origRun }()
  130. Yield(p, "uno", nil)
  131. Yield(p, "dos", nil)
  132. if n != 4 {
  133. t.Fatalf("dos cedidas = 4 comandos, hubo %d", n)
  134. }
  135. data, _ := os.ReadFile(p.StateFile)
  136. if !strings.Contains(string(data), "reason=dos") {
  137. t.Fatal("la segunda cedida debería reescribir el motivo")
  138. }
  139. }
  140. // TestYieldSinInit: agente manual (sin init.d propio): no ejecuta comandos,
  141. // pero sí escribe estado y cancela.
  142. func TestYieldSinInit(t *testing.T) {
  143. dir := t.TempDir()
  144. p := Paths{SelfInit: filepath.Join(dir, "no-existe"), StateFile: filepath.Join(dir, "y"), ProcRoot: "", CronFile: ""}
  145. var n int
  146. origRun := runCmd
  147. runCmd = func(name string, args ...string) error { n++; return nil }
  148. defer func() { runCmd = origRun }()
  149. cancelled := false
  150. Yield(p, "manual", func() { cancelled = true })
  151. if n != 0 {
  152. t.Fatal("sin init.d propio no debería lanzar comandos")
  153. }
  154. if !cancelled || !fileExists(p.StateFile) {
  155. t.Fatal("debería escribir estado y cancelar igualmente")
  156. }
  157. }
  158. // TestWatchSinNetgripNuncaCede: sin señales de netgrip, Watch termina solo
  159. // por ctx y NO ejecuta la cedida.
  160. func TestWatchSinNetgripNuncaCede(t *testing.T) {
  161. dir := t.TempDir()
  162. p := Paths{
  163. NetgripInit: filepath.Join(dir, "ninguna"),
  164. NetgripBin: filepath.Join(dir, "ninguno"),
  165. StateFile: filepath.Join(dir, "y"),
  166. ProcRoot: "",
  167. CronFile: "",
  168. }
  169. ctx, cancel := context.WithCancel(context.Background())
  170. go func() { time.Sleep(150 * time.Millisecond); cancel() }()
  171. start := time.Now()
  172. Watch(ctx, p, 30*time.Millisecond, func() { t.Error("cancel no debería invocarse sin netgrip") })
  173. if elapsed := time.Since(start); elapsed > 2*time.Second {
  174. t.Fatalf("Watch debería terminar con el ctx, tardó %s", elapsed)
  175. }
  176. if fileExists(p.StateFile) {
  177. t.Fatal("sin netgrip no debería escribirse el estado de cedida")
  178. }
  179. }
  180. // TestWatchCedeAlDetectar: netgrip aparece a mitad de ejecución -> cedida.
  181. func TestWatchCedeAlDetectar(t *testing.T) {
  182. dir := t.TempDir()
  183. netgripBin := filepath.Join(dir, "sbin", "netgrip")
  184. p := Paths{
  185. NetgripInit: filepath.Join(dir, "init.d", "netgrip"),
  186. NetgripBin: netgripBin,
  187. StateFile: filepath.Join(dir, "y"),
  188. ProcRoot: "",
  189. CronFile: "",
  190. }
  191. ctx, cancel := context.WithCancel(context.Background())
  192. defer cancel()
  193. done := make(chan struct{})
  194. go func() { Watch(ctx, p, 30*time.Millisecond, cancel); close(done) }()
  195. time.Sleep(60 * time.Millisecond) // un par de ticks sin netgrip
  196. if fileExists(p.StateFile) {
  197. t.Fatal("aún no hay netgrip: no debería haber cedido")
  198. }
  199. touch(t, netgripBin) // netgrip se instala en caliente
  200. select {
  201. case <-done:
  202. case <-time.After(2 * time.Second):
  203. t.Fatal("Watch debería ceder tras detectar netgrip")
  204. }
  205. data, err := os.ReadFile(p.StateFile)
  206. if err != nil {
  207. t.Fatal("el estado de cedida debería existir")
  208. }
  209. if !strings.Contains(string(data), ReasonPeriodic) {
  210. t.Fatalf("motivo inesperado: %q", data)
  211. }
  212. if ctx.Err() == nil {
  213. t.Fatal("el ctx del agente debería quedar cancelado tras la cedida")
  214. }
  215. }