logs_test.go 5.6 KB

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