watch_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*
  2. Copyright 2023 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package e2e
  14. import (
  15. "crypto/rand"
  16. "fmt"
  17. "os"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "sync/atomic"
  22. "testing"
  23. "time"
  24. "github.com/stretchr/testify/require"
  25. "gotest.tools/v3/assert"
  26. "gotest.tools/v3/assert/cmp"
  27. "gotest.tools/v3/icmd"
  28. "gotest.tools/v3/poll"
  29. )
  30. func TestWatch(t *testing.T) {
  31. services := []string{"alpine", "busybox", "debian"}
  32. t.Run("docker cp", func(t *testing.T) {
  33. for _, svcName := range services {
  34. t.Run(svcName, func(t *testing.T) {
  35. t.Helper()
  36. doTest(t, svcName, false)
  37. })
  38. }
  39. })
  40. t.Run("tar", func(t *testing.T) {
  41. for _, svcName := range services {
  42. t.Run(svcName, func(t *testing.T) {
  43. t.Helper()
  44. doTest(t, svcName, true)
  45. })
  46. }
  47. })
  48. }
  49. func TestRebuildOnDotEnvWithExternalNetwork(t *testing.T) {
  50. const projectName = "test_rebuild_on_dotenv_with_external_network"
  51. const svcName = "ext-alpine"
  52. containerName := strings.Join([]string{projectName, svcName, "1"}, "-")
  53. const networkName = "e2e-watch-external_network_test"
  54. const dotEnvFilepath = "./fixtures/watch/.env"
  55. c := NewCLI(t, WithEnv(
  56. "COMPOSE_PROJECT_NAME="+projectName,
  57. "COMPOSE_FILE=./fixtures/watch/with-external-network.yaml",
  58. ))
  59. cleanup := func() {
  60. c.RunDockerComposeCmdNoCheck(t, "down", "--remove-orphans", "--volumes", "--rmi=local")
  61. c.RunDockerOrExitError(t, "network", "rm", networkName)
  62. os.Remove(dotEnvFilepath) //nolint:errcheck
  63. }
  64. cleanup()
  65. t.Log("create network that is referenced by the container we're testing")
  66. c.RunDockerCmd(t, "network", "create", networkName)
  67. res := c.RunDockerCmd(t, "network", "ls")
  68. assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined())
  69. t.Log("create a dotenv file that will be used to trigger the rebuild")
  70. err := os.WriteFile(dotEnvFilepath, []byte("HELLO=WORLD"), 0o666)
  71. assert.NilError(t, err)
  72. _, err = os.ReadFile(dotEnvFilepath)
  73. assert.NilError(t, err)
  74. // TODO: refactor this duplicated code into frameworks? Maybe?
  75. t.Log("starting docker compose watch")
  76. cmd := c.NewDockerComposeCmd(t, "--verbose", "watch", svcName)
  77. // stream output since watch runs in the background
  78. cmd.Stdout = os.Stdout
  79. cmd.Stderr = os.Stderr
  80. r := icmd.StartCmd(cmd)
  81. require.NoError(t, r.Error)
  82. var testComplete atomic.Bool
  83. go func() {
  84. // if the process exits abnormally before the test is done, fail the test
  85. if err := r.Cmd.Wait(); err != nil && !t.Failed() && !testComplete.Load() {
  86. assert.Check(t, cmp.Nil(err))
  87. }
  88. }()
  89. t.Log("wait for watch to start watching")
  90. c.WaitForCondition(t, func() (bool, string) {
  91. out := r.String()
  92. errors := r.String()
  93. return strings.Contains(out,
  94. "watching"), fmt.Sprintf("'watching' not found in : \n%s\nStderr: \n%s\n", out,
  95. errors)
  96. }, 30*time.Second, 1*time.Second)
  97. n := c.RunDockerCmd(t, "network", "inspect", networkName, "-f", "{{ .Id }}")
  98. pn := c.RunDockerCmd(t, "inspect", containerName, "-f", "{{ .HostConfig.NetworkMode }}")
  99. assert.Equal(t, pn.Stdout(), n.Stdout())
  100. t.Log("create a dotenv file that will be used to trigger the rebuild")
  101. err = os.WriteFile(dotEnvFilepath, []byte("HELLO=WORLD\nTEST=REBUILD"), 0o666)
  102. assert.NilError(t, err)
  103. _, err = os.ReadFile(dotEnvFilepath)
  104. assert.NilError(t, err)
  105. // NOTE: are there any other ways to check if the container has been rebuilt?
  106. t.Log("check if the container has been rebuild")
  107. c.WaitForCondition(t, func() (bool, string) {
  108. out := r.String()
  109. if strings.Count(out, "batch complete: service["+svcName+"]") != 1 {
  110. return false, fmt.Sprintf("container %s was not rebuilt", containerName)
  111. }
  112. return true, fmt.Sprintf("container %s was rebuilt", containerName)
  113. }, 30*time.Second, 1*time.Second)
  114. n2 := c.RunDockerCmd(t, "network", "inspect", networkName, "-f", "{{ .Id }}")
  115. pn2 := c.RunDockerCmd(t, "inspect", containerName, "-f", "{{ .HostConfig.NetworkMode }}")
  116. assert.Equal(t, pn2.Stdout(), n2.Stdout())
  117. assert.Check(t, !strings.Contains(r.Combined(), "Application failed to start after update"))
  118. t.Cleanup(cleanup)
  119. t.Cleanup(func() {
  120. // IMPORTANT: watch doesn't exit on its own, don't leak processes!
  121. if r.Cmd.Process != nil {
  122. t.Logf("Killing watch process: pid[%d]", r.Cmd.Process.Pid)
  123. _ = r.Cmd.Process.Kill()
  124. }
  125. })
  126. testComplete.Store(true)
  127. }
  128. // NOTE: these tests all share a single Compose file but are safe to run concurrently
  129. func doTest(t *testing.T, svcName string, tarSync bool) {
  130. tmpdir := t.TempDir()
  131. dataDir := filepath.Join(tmpdir, "data")
  132. configDir := filepath.Join(tmpdir, "config")
  133. writeTestFile := func(name, contents, sourceDir string) {
  134. t.Helper()
  135. dest := filepath.Join(sourceDir, name)
  136. require.NoError(t, os.MkdirAll(filepath.Dir(dest), 0o700))
  137. t.Logf("writing %q to %q", contents, dest)
  138. require.NoError(t, os.WriteFile(dest, []byte(contents+"\n"), 0o600))
  139. }
  140. writeDataFile := func(name, contents string) {
  141. writeTestFile(name, contents, dataDir)
  142. }
  143. composeFilePath := filepath.Join(tmpdir, "compose.yaml")
  144. CopyFile(t, filepath.Join("fixtures", "watch", "compose.yaml"), composeFilePath)
  145. projName := "e2e-watch-" + svcName
  146. if tarSync {
  147. projName += "-tar"
  148. }
  149. env := []string{
  150. "COMPOSE_FILE=" + composeFilePath,
  151. "COMPOSE_PROJECT_NAME=" + projName,
  152. "COMPOSE_EXPERIMENTAL_WATCH_TAR=" + strconv.FormatBool(tarSync),
  153. }
  154. cli := NewCLI(t, WithEnv(env...))
  155. // important that --rmi is used to prune the images and ensure that watch builds on launch
  156. cleanup := func() {
  157. cli.RunDockerComposeCmd(t, "down", svcName, "--remove-orphans", "--volumes", "--rmi=local")
  158. }
  159. cleanup()
  160. t.Cleanup(cleanup)
  161. cmd := cli.NewDockerComposeCmd(t, "--verbose", "watch", svcName)
  162. // stream output since watch runs in the background
  163. cmd.Stdout = os.Stdout
  164. cmd.Stderr = os.Stderr
  165. r := icmd.StartCmd(cmd)
  166. require.NoError(t, r.Error)
  167. t.Cleanup(func() {
  168. // IMPORTANT: watch doesn't exit on its own, don't leak processes!
  169. if r.Cmd.Process != nil {
  170. t.Logf("Killing watch process: pid[%d]", r.Cmd.Process.Pid)
  171. _ = r.Cmd.Process.Kill()
  172. }
  173. })
  174. var testComplete atomic.Bool
  175. go func() {
  176. // if the process exits abnormally before the test is done, fail the test
  177. if err := r.Cmd.Wait(); err != nil && !t.Failed() && !testComplete.Load() {
  178. assert.Check(t, cmp.Nil(err))
  179. }
  180. }()
  181. require.NoError(t, os.Mkdir(dataDir, 0o700))
  182. checkFileContents := func(path string, contents string) poll.Check {
  183. return func(pollLog poll.LogT) poll.Result {
  184. if r.Cmd.ProcessState != nil {
  185. return poll.Error(fmt.Errorf("watch process exited early: %s", r.Cmd.ProcessState))
  186. }
  187. res := icmd.RunCmd(cli.NewDockerComposeCmd(t, "exec", svcName, "cat", path))
  188. if strings.Contains(res.Stdout(), contents) {
  189. return poll.Success()
  190. }
  191. return poll.Continue(res.Combined())
  192. }
  193. }
  194. waitForFlush := func() {
  195. b := make([]byte, 32)
  196. _, _ = rand.Read(b)
  197. sentinelVal := fmt.Sprintf("%x", b)
  198. writeDataFile("wait.txt", sentinelVal)
  199. poll.WaitOn(t, checkFileContents("/app/data/wait.txt", sentinelVal))
  200. }
  201. t.Logf("Writing to a file until Compose watch is up and running")
  202. poll.WaitOn(t, func(t poll.LogT) poll.Result {
  203. writeDataFile("hello.txt", "hello world")
  204. return checkFileContents("/app/data/hello.txt", "hello world")(t)
  205. }, poll.WithDelay(time.Second))
  206. t.Logf("Modifying file contents")
  207. writeDataFile("hello.txt", "hello watch")
  208. poll.WaitOn(t, checkFileContents("/app/data/hello.txt", "hello watch"))
  209. t.Logf("Deleting file")
  210. require.NoError(t, os.Remove(filepath.Join(dataDir, "hello.txt")))
  211. waitForFlush()
  212. cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/hello.txt").
  213. Assert(t, icmd.Expected{
  214. ExitCode: 1,
  215. Err: "No such file or directory",
  216. })
  217. t.Logf("Writing to ignored paths")
  218. writeDataFile("data.foo", "ignored")
  219. writeDataFile(filepath.Join("ignored", "hello.txt"), "ignored")
  220. waitForFlush()
  221. cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/data.foo").
  222. Assert(t, icmd.Expected{
  223. ExitCode: 1,
  224. Err: "No such file or directory",
  225. })
  226. cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/ignored").
  227. Assert(t, icmd.Expected{
  228. ExitCode: 1,
  229. Err: "No such file or directory",
  230. })
  231. t.Logf("Creating subdirectory")
  232. require.NoError(t, os.Mkdir(filepath.Join(dataDir, "subdir"), 0o700))
  233. waitForFlush()
  234. cli.RunDockerComposeCmd(t, "exec", svcName, "stat", "/app/data/subdir")
  235. t.Logf("Writing to file in subdirectory")
  236. writeDataFile(filepath.Join("subdir", "file.txt"), "a")
  237. poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "a"))
  238. t.Logf("Writing to file multiple times")
  239. writeDataFile(filepath.Join("subdir", "file.txt"), "x")
  240. writeDataFile(filepath.Join("subdir", "file.txt"), "y")
  241. writeDataFile(filepath.Join("subdir", "file.txt"), "z")
  242. poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "z"))
  243. writeDataFile(filepath.Join("subdir", "file.txt"), "z")
  244. writeDataFile(filepath.Join("subdir", "file.txt"), "y")
  245. writeDataFile(filepath.Join("subdir", "file.txt"), "x")
  246. poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "x"))
  247. t.Logf("Deleting directory")
  248. require.NoError(t, os.RemoveAll(filepath.Join(dataDir, "subdir")))
  249. waitForFlush()
  250. cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/subdir").
  251. Assert(t, icmd.Expected{
  252. ExitCode: 1,
  253. Err: "No such file or directory",
  254. })
  255. t.Logf("Sync and restart use case")
  256. require.NoError(t, os.Mkdir(configDir, 0o700))
  257. writeTestFile("file.config", "This is an updated config file", configDir)
  258. checkRestart := func(state string) poll.Check {
  259. return func(pollLog poll.LogT) poll.Result {
  260. if strings.Contains(r.Combined(), state) {
  261. return poll.Success()
  262. }
  263. return poll.Continue(r.Combined())
  264. }
  265. }
  266. poll.WaitOn(t, checkRestart(fmt.Sprintf("%s-1 Restarting", svcName)))
  267. poll.WaitOn(t, checkRestart(fmt.Sprintf("%s-1 Started", svcName)))
  268. poll.WaitOn(t, checkFileContents("/app/config/file.config", "This is an updated config file"))
  269. testComplete.Store(true)
  270. }