watch_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. // NOTE: these tests all share a single Compose file but are safe to run concurrently
  50. func doTest(t *testing.T, svcName string, tarSync bool) {
  51. tmpdir := t.TempDir()
  52. dataDir := filepath.Join(tmpdir, "data")
  53. writeDataFile := func(name string, contents string) {
  54. t.Helper()
  55. dest := filepath.Join(dataDir, name)
  56. require.NoError(t, os.MkdirAll(filepath.Dir(dest), 0o700))
  57. t.Logf("writing %q to %q", contents, dest)
  58. require.NoError(t, os.WriteFile(dest, []byte(contents+"\n"), 0o600))
  59. }
  60. composeFilePath := filepath.Join(tmpdir, "compose.yaml")
  61. CopyFile(t, filepath.Join("fixtures", "watch", "compose.yaml"), composeFilePath)
  62. projName := "e2e-watch-" + svcName
  63. if tarSync {
  64. projName += "-tar"
  65. }
  66. env := []string{
  67. "COMPOSE_FILE=" + composeFilePath,
  68. "COMPOSE_PROJECT_NAME=" + projName,
  69. "COMPOSE_EXPERIMENTAL_WATCH_TAR=" + strconv.FormatBool(tarSync),
  70. }
  71. cli := NewCLI(t, WithEnv(env...))
  72. // important that --rmi is used to prune the images and ensure that watch builds on launch
  73. cleanup := func() {
  74. cli.RunDockerComposeCmd(t, "down", svcName, "--remove-orphans", "--volumes", "--rmi=local")
  75. }
  76. cleanup()
  77. t.Cleanup(cleanup)
  78. cmd := cli.NewDockerComposeCmd(t, "--verbose", "watch", svcName)
  79. // stream output since watch runs in the background
  80. cmd.Stdout = os.Stdout
  81. cmd.Stderr = os.Stderr
  82. r := icmd.StartCmd(cmd)
  83. require.NoError(t, r.Error)
  84. t.Cleanup(func() {
  85. // IMPORTANT: watch doesn't exit on its own, don't leak processes!
  86. if r.Cmd.Process != nil {
  87. t.Logf("Killing watch process: pid[%d]", r.Cmd.Process.Pid)
  88. _ = r.Cmd.Process.Kill()
  89. }
  90. })
  91. var testComplete atomic.Bool
  92. go func() {
  93. // if the process exits abnormally before the test is done, fail the test
  94. if err := r.Cmd.Wait(); err != nil && !t.Failed() && !testComplete.Load() {
  95. assert.Check(t, cmp.Nil(err))
  96. }
  97. }()
  98. require.NoError(t, os.Mkdir(dataDir, 0o700))
  99. checkFileContents := func(path string, contents string) poll.Check {
  100. return func(pollLog poll.LogT) poll.Result {
  101. if r.Cmd.ProcessState != nil {
  102. return poll.Error(fmt.Errorf("watch process exited early: %s", r.Cmd.ProcessState))
  103. }
  104. res := icmd.RunCmd(cli.NewDockerComposeCmd(t, "exec", svcName, "cat", path))
  105. if strings.Contains(res.Stdout(), contents) {
  106. return poll.Success()
  107. }
  108. return poll.Continue(res.Combined())
  109. }
  110. }
  111. waitForFlush := func() {
  112. b := make([]byte, 32)
  113. _, _ = rand.Read(b)
  114. sentinelVal := fmt.Sprintf("%x", b)
  115. writeDataFile("wait.txt", sentinelVal)
  116. poll.WaitOn(t, checkFileContents("/app/data/wait.txt", sentinelVal))
  117. }
  118. t.Logf("Writing to a file until Compose watch is up and running")
  119. poll.WaitOn(t, func(t poll.LogT) poll.Result {
  120. writeDataFile("hello.txt", "hello world")
  121. return checkFileContents("/app/data/hello.txt", "hello world")(t)
  122. }, poll.WithDelay(time.Second))
  123. t.Logf("Modifying file contents")
  124. writeDataFile("hello.txt", "hello watch")
  125. poll.WaitOn(t, checkFileContents("/app/data/hello.txt", "hello watch"))
  126. t.Logf("Deleting file")
  127. require.NoError(t, os.Remove(filepath.Join(dataDir, "hello.txt")))
  128. waitForFlush()
  129. cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/hello.txt").
  130. Assert(t, icmd.Expected{
  131. ExitCode: 1,
  132. Err: "No such file or directory",
  133. })
  134. t.Logf("Writing to ignored paths")
  135. writeDataFile("data.foo", "ignored")
  136. writeDataFile(filepath.Join("ignored", "hello.txt"), "ignored")
  137. waitForFlush()
  138. cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/data.foo").
  139. Assert(t, icmd.Expected{
  140. ExitCode: 1,
  141. Err: "No such file or directory",
  142. })
  143. cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/ignored").
  144. Assert(t, icmd.Expected{
  145. ExitCode: 1,
  146. Err: "No such file or directory",
  147. })
  148. t.Logf("Creating subdirectory")
  149. require.NoError(t, os.Mkdir(filepath.Join(dataDir, "subdir"), 0o700))
  150. waitForFlush()
  151. cli.RunDockerComposeCmd(t, "exec", svcName, "stat", "/app/data/subdir")
  152. t.Logf("Writing to file in subdirectory")
  153. writeDataFile(filepath.Join("subdir", "file.txt"), "a")
  154. poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "a"))
  155. t.Logf("Writing to file multiple times")
  156. writeDataFile(filepath.Join("subdir", "file.txt"), "x")
  157. writeDataFile(filepath.Join("subdir", "file.txt"), "y")
  158. writeDataFile(filepath.Join("subdir", "file.txt"), "z")
  159. poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "z"))
  160. writeDataFile(filepath.Join("subdir", "file.txt"), "z")
  161. writeDataFile(filepath.Join("subdir", "file.txt"), "y")
  162. writeDataFile(filepath.Join("subdir", "file.txt"), "x")
  163. poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "x"))
  164. t.Logf("Deleting directory")
  165. require.NoError(t, os.RemoveAll(filepath.Join(dataDir, "subdir")))
  166. waitForFlush()
  167. cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/subdir").
  168. Assert(t, icmd.Expected{
  169. ExitCode: 1,
  170. Err: "No such file or directory",
  171. })
  172. testComplete.Store(true)
  173. }