watch_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /*
  2. Copyright 2020 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 compose
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "testing"
  19. "time"
  20. "github.com/compose-spec/compose-go/v2/types"
  21. "github.com/docker/cli/cli/streams"
  22. "github.com/docker/compose/v2/internal/sync"
  23. "github.com/docker/compose/v2/pkg/api"
  24. "github.com/docker/compose/v2/pkg/mocks"
  25. "github.com/docker/compose/v2/pkg/watch"
  26. moby "github.com/docker/docker/api/types"
  27. "github.com/docker/docker/api/types/filters"
  28. "github.com/docker/docker/api/types/image"
  29. "github.com/jonboulle/clockwork"
  30. "github.com/stretchr/testify/require"
  31. "go.uber.org/mock/gomock"
  32. "gotest.tools/v3/assert"
  33. )
  34. func TestDebounceBatching(t *testing.T) {
  35. ch := make(chan fileEvent)
  36. clock := clockwork.NewFakeClock()
  37. ctx, stop := context.WithCancel(context.Background())
  38. t.Cleanup(stop)
  39. eventBatchCh := batchDebounceEvents(ctx, clock, quietPeriod, ch)
  40. for i := 0; i < 100; i++ {
  41. var action types.WatchAction = "a"
  42. if i%2 == 0 {
  43. action = "b"
  44. }
  45. ch <- fileEvent{Action: action}
  46. }
  47. // we sent 100 events + the debouncer
  48. clock.BlockUntil(101)
  49. clock.Advance(quietPeriod)
  50. select {
  51. case batch := <-eventBatchCh:
  52. require.ElementsMatch(t, batch, []fileEvent{
  53. {Action: "a"},
  54. {Action: "b"},
  55. })
  56. case <-time.After(50 * time.Millisecond):
  57. t.Fatal("timed out waiting for events")
  58. }
  59. clock.BlockUntil(1)
  60. clock.Advance(quietPeriod)
  61. // there should only be a single batch
  62. select {
  63. case batch := <-eventBatchCh:
  64. t.Fatalf("unexpected events: %v", batch)
  65. case <-time.After(50 * time.Millisecond):
  66. // channel is empty
  67. }
  68. }
  69. type testWatcher struct {
  70. events chan watch.FileEvent
  71. errors chan error
  72. }
  73. func (t testWatcher) Start() error {
  74. return nil
  75. }
  76. func (t testWatcher) Close() error {
  77. return nil
  78. }
  79. func (t testWatcher) Events() chan watch.FileEvent {
  80. return t.events
  81. }
  82. func (t testWatcher) Errors() chan error {
  83. return t.errors
  84. }
  85. type stdLogger struct{}
  86. func (s stdLogger) Log(containerName, message string) {
  87. fmt.Printf("%s: %s\n", containerName, message)
  88. }
  89. func (s stdLogger) Err(containerName, message string) {
  90. fmt.Fprintf(os.Stderr, "%s: %s\n", containerName, message)
  91. }
  92. func (s stdLogger) Status(container, msg string) {
  93. fmt.Printf("%s: %s\n", container, msg)
  94. }
  95. func (s stdLogger) Register(container string) {
  96. }
  97. func TestWatch_Sync(t *testing.T) {
  98. mockCtrl := gomock.NewController(t)
  99. cli := mocks.NewMockCli(mockCtrl)
  100. cli.EXPECT().Err().Return(streams.NewOut(os.Stderr)).AnyTimes()
  101. cli.EXPECT().BuildKitEnabled().Return(true, nil)
  102. apiClient := mocks.NewMockAPIClient(mockCtrl)
  103. apiClient.EXPECT().ContainerList(gomock.Any(), gomock.Any()).Return([]moby.Container{
  104. testContainer("test", "123", false),
  105. }, nil).AnyTimes()
  106. // we expect the image to be pruned
  107. apiClient.EXPECT().ImageList(gomock.Any(), image.ListOptions{
  108. Filters: filters.NewArgs(
  109. filters.Arg("dangling", "true"),
  110. filters.Arg("label", api.ProjectLabel+"=myProjectName"),
  111. ),
  112. }).Return([]image.Summary{
  113. {ID: "123"},
  114. {ID: "456"},
  115. }, nil).Times(1)
  116. apiClient.EXPECT().ImageRemove(gomock.Any(), "123", image.RemoveOptions{}).Times(1)
  117. apiClient.EXPECT().ImageRemove(gomock.Any(), "456", image.RemoveOptions{}).Times(1)
  118. //
  119. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  120. ctx, cancelFunc := context.WithCancel(context.Background())
  121. t.Cleanup(cancelFunc)
  122. proj := types.Project{
  123. Name: "myProjectName",
  124. Services: types.Services{
  125. "test": {
  126. Name: "test",
  127. },
  128. },
  129. }
  130. watcher := testWatcher{
  131. events: make(chan watch.FileEvent),
  132. errors: make(chan error),
  133. }
  134. syncer := newFakeSyncer()
  135. clock := clockwork.NewFakeClock()
  136. go func() {
  137. service := composeService{
  138. dockerCli: cli,
  139. clock: clock,
  140. }
  141. err := service.watchEvents(ctx, &proj, "test", api.WatchOptions{
  142. Build: &api.BuildOptions{},
  143. LogTo: stdLogger{},
  144. Prune: true,
  145. }, watcher, syncer, []types.Trigger{
  146. {
  147. Path: "/sync",
  148. Action: "sync",
  149. Target: "/work",
  150. Ignore: []string{"ignore"},
  151. },
  152. {
  153. Path: "/rebuild",
  154. Action: "rebuild",
  155. },
  156. })
  157. assert.NilError(t, err)
  158. }()
  159. watcher.Events() <- watch.NewFileEvent("/sync/changed")
  160. watcher.Events() <- watch.NewFileEvent("/sync/changed/sub")
  161. clock.BlockUntil(3)
  162. clock.Advance(quietPeriod)
  163. select {
  164. case actual := <-syncer.synced:
  165. require.ElementsMatch(t, []sync.PathMapping{
  166. {HostPath: "/sync/changed", ContainerPath: "/work/changed"},
  167. {HostPath: "/sync/changed/sub", ContainerPath: "/work/changed/sub"},
  168. }, actual)
  169. case <-time.After(100 * time.Millisecond):
  170. t.Error("timeout")
  171. }
  172. watcher.Events() <- watch.NewFileEvent("/sync/ignore")
  173. watcher.Events() <- watch.NewFileEvent("/sync/ignore/sub")
  174. watcher.Events() <- watch.NewFileEvent("/sync/changed")
  175. clock.BlockUntil(4)
  176. clock.Advance(quietPeriod)
  177. select {
  178. case actual := <-syncer.synced:
  179. require.ElementsMatch(t, []sync.PathMapping{
  180. {HostPath: "/sync/changed", ContainerPath: "/work/changed"},
  181. }, actual)
  182. case <-time.After(100 * time.Millisecond):
  183. t.Error("timed out waiting for events")
  184. }
  185. watcher.Events() <- watch.NewFileEvent("/rebuild")
  186. watcher.Events() <- watch.NewFileEvent("/sync/changed")
  187. clock.BlockUntil(4)
  188. clock.Advance(quietPeriod)
  189. select {
  190. case batch := <-syncer.synced:
  191. t.Fatalf("received unexpected events: %v", batch)
  192. case <-time.After(100 * time.Millisecond):
  193. // expected
  194. }
  195. // TODO: there's not a great way to assert that the rebuild attempt happened
  196. }
  197. type fakeSyncer struct {
  198. synced chan []sync.PathMapping
  199. }
  200. func newFakeSyncer() *fakeSyncer {
  201. return &fakeSyncer{
  202. synced: make(chan []sync.PathMapping),
  203. }
  204. }
  205. func (f *fakeSyncer) Sync(_ context.Context, _ types.ServiceConfig, paths []sync.PathMapping) error {
  206. f.synced <- paths
  207. return nil
  208. }