| 1 | //go:build !windows |
| 2 | |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "syscall" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/gorilla/websocket" |
| 18 | ) |
| 19 | |
| 20 | // vivo: ¿existe todavía el proceso? (un zombi cuenta hasta que lo recogen) |
| 21 | func vivo(pid int) bool { return syscall.Kill(pid, 0) == nil } |
| 22 | |
| 23 | func esperaMuerto(t *testing.T, pid int) bool { |
| 24 | t.Helper() |
| 25 | for i := 0; i < 100; i++ { |
| 26 | if !vivo(pid) { |
| 27 | return true |
| 28 | } |
| 29 | time.Sleep(50 * time.Millisecond) |
| 30 | } |
| 31 | return false |
| 32 | } |
| 33 | |
| 34 | // Parar un comando mata también lo que el sh lanzó, no solo el sh. |
| 35 | func TestKillTreeKillsWhatTheShellStarted(t *testing.T) { |
| 36 | c := shellFor("sleep 30 & echo $!; wait") |
| 37 | out, err := c.StdoutPipe() |
| 38 | if err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | if err := c.Start(); err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | line, err := bufio.NewReader(out).ReadString('\n') |
| 45 | if err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | hijo, err := strconv.Atoi(strings.TrimSpace(line)) |
| 49 | if err != nil || !vivo(hijo) { |
| 50 | t.Fatalf("no hay hijo vivo que parar: %q", line) |
| 51 | } |
| 52 | killTree(c) |
| 53 | _ = c.Wait() |
| 54 | if !esperaMuerto(t, hijo) { |
| 55 | _ = syscall.Kill(hijo, syscall.SIGKILL) |
| 56 | t.Fatalf("el hijo del sh (%d) sigue vivo tras parar", hijo) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | const tokenPrueba = "token-de-prueba-del-bridge-0123456789" |
| 61 | |
| 62 | type cliente struct { |
| 63 | t *testing.T |
| 64 | conn *websocket.Conn |
| 65 | } |
| 66 | |
| 67 | func conecta(t *testing.T, root string) (*cliente, func()) { |
| 68 | t.Helper() |
| 69 | srv := httptest.NewServer(serveWS(tokenPrueba, root)) |
| 70 | url := "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws" |
| 71 | conn, _, err := websocket.DefaultDialer.Dial(url, http.Header{"Origin": {"http://localhost:8799"}}) |
| 72 | if err != nil { |
| 73 | srv.Close() |
| 74 | t.Fatal(err) |
| 75 | } |
| 76 | cl := &cliente{t: t, conn: conn} |
| 77 | cl.manda(inMsg{Type: "auth", Token: tokenPrueba}) |
| 78 | if m := cl.lee(); m.Type != "auth-ok" { |
| 79 | t.Fatalf("sin auth-ok: %+v", m) |
| 80 | } |
| 81 | return cl, func() { conn.Close(); srv.Close() } |
| 82 | } |
| 83 | |
| 84 | func (c *cliente) manda(m inMsg) { |
| 85 | if err := c.conn.WriteJSON(m); err != nil { |
| 86 | c.t.Fatal(err) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | func (c *cliente) lee() outMsg { |
| 91 | c.t.Helper() |
| 92 | var m outMsg |
| 93 | _ = c.conn.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| 94 | if err := c.conn.ReadJSON(&m); err != nil { |
| 95 | c.t.Fatal(err) |
| 96 | } |
| 97 | return m |
| 98 | } |
| 99 | |
| 100 | // lee hasta el «exit» de ese id |
| 101 | func (c *cliente) salida(id string) outMsg { |
| 102 | c.t.Helper() |
| 103 | for { |
| 104 | m := c.lee() |
| 105 | if m.ID == id && (m.Type == "exit" || m.Type == "error") { |
| 106 | return m |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | // Un «stop» que llega antes de que el proceso haya arrancado no se pierde: antes |
| 112 | // el bridge no encontraba el id y el comando corría hasta el final. |
| 113 | func TestStopRightAfterExecIsNotLost(t *testing.T) { |
| 114 | root := t.TempDir() |
| 115 | cl, cerrar := conecta(t, root) |
| 116 | defer cerrar() |
| 117 | for i := 0; i < 10; i++ { |
| 118 | id := "pronto-" + strconv.Itoa(i) |
| 119 | marca := filepath.Join(root, id) |
| 120 | cl.manda(inMsg{Type: "exec", ID: id, Cmd: "sleep 1; touch '" + marca + "'"}) |
| 121 | cl.manda(inMsg{Type: "stop", ID: id}) |
| 122 | cl.salida(id) |
| 123 | } |
| 124 | time.Sleep(1500 * time.Millisecond) |
| 125 | for i := 0; i < 10; i++ { |
| 126 | if _, err := os.Stat(filepath.Join(root, "pronto-"+strconv.Itoa(i))); err == nil { |
| 127 | t.Errorf("el comando %d se paró nada más mandarlo y aun así terminó", i) |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // Y un «stop» de un id que todavía no ha llegado se recuerda para cuando llegue. |
| 133 | func TestStopBeforeExecIsRemembered(t *testing.T) { |
| 134 | root := t.TempDir() |
| 135 | cl, cerrar := conecta(t, root) |
| 136 | defer cerrar() |
| 137 | marca := filepath.Join(root, "antes") |
| 138 | cl.manda(inMsg{Type: "stop", ID: "x"}) |
| 139 | cl.manda(inMsg{Type: "exec", ID: "x", Cmd: "touch '" + marca + "'"}) |
| 140 | if m := cl.salida("x"); m.Type != "exit" || m.Code != exitStopped { |
| 141 | t.Errorf("esperaba exit %d sin arrancar, llegó %+v", exitStopped, m) |
| 142 | } |
| 143 | time.Sleep(300 * time.Millisecond) |
| 144 | if _, err := os.Stat(marca); err == nil { |
| 145 | t.Error("el comando corrió aunque su «stop» llegó antes") |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // Cerrar el socket con un comando en marcha mata el comando y lo que lanzó. |
| 150 | func TestSocketCloseKillsTheTree(t *testing.T) { |
| 151 | root := t.TempDir() |
| 152 | cl, cerrar := conecta(t, root) |
| 153 | defer cerrar() |
| 154 | cl.manda(inMsg{Type: "exec", ID: "largo", Cmd: "sleep 30 & echo $!; wait"}) |
| 155 | var hijo int |
| 156 | for hijo == 0 { |
| 157 | m := cl.lee() |
| 158 | if m.ID == "largo" && m.Type == "stdout" { |
| 159 | hijo, _ = strconv.Atoi(strings.TrimSpace(m.Data)) |
| 160 | } |
| 161 | } |
| 162 | if !vivo(hijo) { |
| 163 | t.Fatalf("el hijo %d no llegó a estar vivo", hijo) |
| 164 | } |
| 165 | cl.conn.Close() |
| 166 | if !esperaMuerto(t, hijo) { |
| 167 | _ = syscall.Kill(hijo, syscall.SIGKILL) |
| 168 | t.Fatalf("cerrar el socket dejó vivo el hijo %d", hijo) |
| 169 | } |
| 170 | } |