logs_test.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /*
  2. Copyright 2022 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. "io"
  17. "strings"
  18. "sync"
  19. "testing"
  20. "github.com/compose-spec/compose-go/types"
  21. moby "github.com/docker/docker/api/types"
  22. "github.com/docker/docker/api/types/container"
  23. "github.com/docker/docker/api/types/filters"
  24. "github.com/docker/docker/pkg/stdcopy"
  25. "github.com/golang/mock/gomock"
  26. "github.com/stretchr/testify/assert"
  27. "github.com/stretchr/testify/require"
  28. compose "github.com/docker/compose/v2/pkg/api"
  29. "github.com/docker/compose/v2/pkg/mocks"
  30. )
  31. func TestComposeService_Logs_Demux(t *testing.T) {
  32. mockCtrl := gomock.NewController(t)
  33. defer mockCtrl.Finish()
  34. api := mocks.NewMockAPIClient(mockCtrl)
  35. cli := mocks.NewMockCli(mockCtrl)
  36. tested := composeService{
  37. dockerCli: cli,
  38. }
  39. cli.EXPECT().Client().Return(api).AnyTimes()
  40. name := strings.ToLower(testProject)
  41. ctx := context.Background()
  42. api.EXPECT().ContainerList(ctx, moby.ContainerListOptions{
  43. All: true,
  44. Filters: filters.NewArgs(oneOffFilter(false), projectFilter(name)),
  45. }).Return(
  46. []moby.Container{
  47. testContainer("service", "c", false),
  48. },
  49. nil,
  50. )
  51. api.EXPECT().
  52. ContainerInspect(anyCancellableContext(), "c").
  53. Return(moby.ContainerJSON{
  54. ContainerJSONBase: &moby.ContainerJSONBase{ID: "c"},
  55. Config: &container.Config{Tty: false},
  56. }, nil)
  57. c1Reader, c1Writer := io.Pipe()
  58. t.Cleanup(func() {
  59. _ = c1Reader.Close()
  60. _ = c1Writer.Close()
  61. })
  62. c1Stdout := stdcopy.NewStdWriter(c1Writer, stdcopy.Stdout)
  63. c1Stderr := stdcopy.NewStdWriter(c1Writer, stdcopy.Stderr)
  64. go func() {
  65. _, err := c1Stdout.Write([]byte("hello stdout\n"))
  66. assert.NoError(t, err, "Writing to fake stdout")
  67. _, err = c1Stderr.Write([]byte("hello stderr\n"))
  68. assert.NoError(t, err, "Writing to fake stderr")
  69. _ = c1Writer.Close()
  70. }()
  71. api.EXPECT().ContainerLogs(anyCancellableContext(), "c", gomock.Any()).
  72. Return(c1Reader, nil)
  73. opts := compose.LogOptions{
  74. Project: &types.Project{
  75. Services: types.Services{
  76. {Name: "service"},
  77. },
  78. },
  79. }
  80. consumer := &testLogConsumer{}
  81. err := tested.Logs(ctx, name, consumer, opts)
  82. require.NoError(t, err)
  83. require.Equal(
  84. t,
  85. []string{"hello stdout", "hello stderr"},
  86. consumer.LogsForContainer("service", "c"),
  87. )
  88. }
  89. // TestComposeService_Logs_ServiceFiltering ensures that we do not include
  90. // logs from out-of-scope services based on the Compose file vs actual state.
  91. //
  92. // NOTE(milas): This test exists because each method is currently duplicating
  93. // a lot of the project/service filtering logic. We should consider moving it
  94. // to an earlier point in the loading process, at which point this test could
  95. // safely be removed.
  96. func TestComposeService_Logs_ServiceFiltering(t *testing.T) {
  97. mockCtrl := gomock.NewController(t)
  98. defer mockCtrl.Finish()
  99. api := mocks.NewMockAPIClient(mockCtrl)
  100. cli := mocks.NewMockCli(mockCtrl)
  101. tested := composeService{
  102. dockerCli: cli,
  103. }
  104. cli.EXPECT().Client().Return(api).AnyTimes()
  105. name := strings.ToLower(testProject)
  106. ctx := context.Background()
  107. api.EXPECT().ContainerList(ctx, moby.ContainerListOptions{
  108. All: true,
  109. Filters: filters.NewArgs(oneOffFilter(false), projectFilter(name)),
  110. }).Return(
  111. []moby.Container{
  112. testContainer("serviceA", "c1", false),
  113. testContainer("serviceA", "c2", false),
  114. // serviceB will be filtered out by the project definition to
  115. // ensure we ignore "orphan" containers
  116. testContainer("serviceB", "c3", false),
  117. testContainer("serviceC", "c4", false),
  118. },
  119. nil,
  120. )
  121. for _, id := range []string{"c1", "c2", "c4"} {
  122. id := id
  123. api.EXPECT().
  124. ContainerInspect(anyCancellableContext(), id).
  125. Return(
  126. moby.ContainerJSON{
  127. ContainerJSONBase: &moby.ContainerJSONBase{ID: id},
  128. Config: &container.Config{Tty: true},
  129. },
  130. nil,
  131. )
  132. api.EXPECT().ContainerLogs(anyCancellableContext(), id, gomock.Any()).
  133. Return(io.NopCloser(strings.NewReader("hello "+id+"\n")), nil).
  134. Times(1)
  135. }
  136. // this simulates passing `--filename` with a Compose file that does NOT
  137. // reference `serviceB` even though it has running services for this proj
  138. proj := &types.Project{
  139. Services: types.Services{
  140. {Name: "serviceA"},
  141. {Name: "serviceC"},
  142. },
  143. }
  144. consumer := &testLogConsumer{}
  145. opts := compose.LogOptions{
  146. Project: proj,
  147. }
  148. err := tested.Logs(ctx, name, consumer, opts)
  149. require.NoError(t, err)
  150. require.Equal(t, []string{"hello c1"}, consumer.LogsForContainer("serviceA", "c1"))
  151. require.Equal(t, []string{"hello c2"}, consumer.LogsForContainer("serviceA", "c2"))
  152. require.Empty(t, consumer.LogsForContainer("serviceB", "c3"))
  153. require.Equal(t, []string{"hello c4"}, consumer.LogsForContainer("serviceC", "c4"))
  154. }
  155. type testLogConsumer struct {
  156. mu sync.Mutex
  157. // logs is keyed by service, then container; values are log lines
  158. logs map[string]map[string][]string
  159. }
  160. func (l *testLogConsumer) Log(containerName, service, message string) {
  161. l.mu.Lock()
  162. defer l.mu.Unlock()
  163. if l.logs == nil {
  164. l.logs = make(map[string]map[string][]string)
  165. }
  166. if l.logs[service] == nil {
  167. l.logs[service] = make(map[string][]string)
  168. }
  169. l.logs[service][containerName] = append(l.logs[service][containerName], message)
  170. }
  171. func (l *testLogConsumer) Status(containerName, msg string) {}
  172. func (l *testLogConsumer) Register(containerName string) {}
  173. func (l *testLogConsumer) LogsForContainer(svc string, containerName string) []string {
  174. l.mu.Lock()
  175. defer l.mu.Unlock()
  176. return l.logs[svc][containerName]
  177. }