logs_test.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. "bytes"
  16. "encoding/binary"
  17. "errors"
  18. "io"
  19. "strings"
  20. "sync"
  21. "testing"
  22. "github.com/compose-spec/compose-go/v2/types"
  23. "github.com/moby/moby/api/pkg/stdcopy"
  24. containerType "github.com/moby/moby/api/types/container"
  25. "github.com/moby/moby/client"
  26. "go.uber.org/mock/gomock"
  27. "gotest.tools/v3/assert"
  28. is "gotest.tools/v3/assert/cmp"
  29. compose "github.com/docker/compose/v5/pkg/api"
  30. )
  31. // newStdWriter is copied from github.com/moby/moby/daemon/internal/stdcopymux
  32. // because NewStdWriter was moved to a daemon-internal package in moby v2 and
  33. // is no longer publicly importable. We need it in tests to produce multiplexed
  34. // streams that stdcopy.StdCopy can demultiplex.
  35. const (
  36. stdWriterPrefixLen = 8
  37. stdWriterFdIndex = 0
  38. stdWriterSizeIndex = 4
  39. )
  40. var bufPool = &sync.Pool{New: func() any { return bytes.NewBuffer(nil) }}
  41. type stdWriter struct {
  42. io.Writer
  43. prefix byte
  44. }
  45. func (w *stdWriter) Write(p []byte) (int, error) {
  46. if w == nil || w.Writer == nil {
  47. return 0, errors.New("writer not instantiated")
  48. }
  49. if p == nil {
  50. return 0, nil
  51. }
  52. header := [stdWriterPrefixLen]byte{stdWriterFdIndex: w.prefix}
  53. binary.BigEndian.PutUint32(header[stdWriterSizeIndex:], uint32(len(p)))
  54. buf := bufPool.Get().(*bytes.Buffer)
  55. buf.Write(header[:])
  56. buf.Write(p)
  57. n, err := w.Writer.Write(buf.Bytes())
  58. n -= stdWriterPrefixLen
  59. if n < 0 {
  60. n = 0
  61. }
  62. buf.Reset()
  63. bufPool.Put(buf)
  64. return n, err
  65. }
  66. func newStdWriter(w io.Writer, streamType stdcopy.StdType) io.Writer {
  67. return &stdWriter{
  68. Writer: w,
  69. prefix: byte(streamType),
  70. }
  71. }
  72. func TestComposeService_Logs_Demux(t *testing.T) {
  73. mockCtrl := gomock.NewController(t)
  74. defer mockCtrl.Finish()
  75. api, cli := prepareMocks(mockCtrl)
  76. tested, err := NewComposeService(cli)
  77. assert.NilError(t, err)
  78. name := strings.ToLower(testProject)
  79. api.EXPECT().ContainerList(t.Context(), client.ContainerListOptions{
  80. All: true,
  81. Filters: projectFilter(name).Add("label", oneOffFilter(false), hasConfigHashLabel()),
  82. }).Return(
  83. client.ContainerListResult{
  84. Items: []containerType.Summary{
  85. testContainer("service", "c", false),
  86. },
  87. },
  88. nil,
  89. )
  90. api.EXPECT().
  91. ContainerInspect(anyCancellableContext(), "c", gomock.Any()).
  92. Return(client.ContainerInspectResult{
  93. Container: containerType.InspectResponse{
  94. ID: "c",
  95. Config: &containerType.Config{Tty: false},
  96. },
  97. }, nil)
  98. c1Reader, c1Writer := io.Pipe()
  99. t.Cleanup(func() {
  100. _ = c1Reader.Close()
  101. _ = c1Writer.Close()
  102. })
  103. c1Stdout := newStdWriter(c1Writer, stdcopy.Stdout)
  104. c1Stderr := newStdWriter(c1Writer, stdcopy.Stderr)
  105. go func() {
  106. _, err := c1Stdout.Write([]byte("hello stdout\n"))
  107. assert.NilError(t, err, "Writing to fake stdout")
  108. _, err = c1Stderr.Write([]byte("hello stderr\n"))
  109. assert.NilError(t, err, "Writing to fake stderr")
  110. _ = c1Writer.Close()
  111. }()
  112. api.EXPECT().ContainerLogs(anyCancellableContext(), "c", gomock.Any()).
  113. Return(c1Reader, nil)
  114. opts := compose.LogOptions{
  115. Project: &types.Project{
  116. Services: types.Services{
  117. "service": {Name: "service"},
  118. },
  119. },
  120. }
  121. consumer := &testLogConsumer{}
  122. err = tested.Logs(t.Context(), name, consumer, opts)
  123. assert.NilError(t, err)
  124. assert.DeepEqual(t, []string{"hello stdout", "hello stderr"}, consumer.LogsForContainer("c"))
  125. }
  126. // TestComposeService_Logs_ServiceFiltering ensures that we do not include
  127. // logs from out-of-scope services based on the Compose file vs actual state.
  128. //
  129. // NOTE(milas): This test exists because each method is currently duplicating
  130. // a lot of the project/service filtering logic. We should consider moving it
  131. // to an earlier point in the loading process, at which point this test could
  132. // safely be removed.
  133. func TestComposeService_Logs_ServiceFiltering(t *testing.T) {
  134. mockCtrl := gomock.NewController(t)
  135. defer mockCtrl.Finish()
  136. api, cli := prepareMocks(mockCtrl)
  137. tested, err := NewComposeService(cli)
  138. assert.NilError(t, err)
  139. name := strings.ToLower(testProject)
  140. api.EXPECT().ContainerList(t.Context(), client.ContainerListOptions{
  141. All: true,
  142. Filters: projectFilter(name).Add("label", oneOffFilter(false), hasConfigHashLabel()),
  143. }).Return(
  144. client.ContainerListResult{
  145. Items: []containerType.Summary{
  146. testContainer("serviceA", "c1", false),
  147. testContainer("serviceA", "c2", false),
  148. // serviceB will be filtered out by the project definition to
  149. // ensure we ignore "orphan" containers
  150. testContainer("serviceB", "c3", false),
  151. testContainer("serviceC", "c4", false),
  152. },
  153. },
  154. nil,
  155. )
  156. for _, id := range []string{"c1", "c2", "c4"} {
  157. api.EXPECT().
  158. ContainerInspect(anyCancellableContext(), id, gomock.Any()).
  159. Return(
  160. client.ContainerInspectResult{
  161. Container: containerType.InspectResponse{
  162. ID: id,
  163. Config: &containerType.Config{Tty: true},
  164. },
  165. },
  166. nil,
  167. )
  168. api.EXPECT().ContainerLogs(anyCancellableContext(), id, gomock.Any()).
  169. Return(io.NopCloser(strings.NewReader("hello "+id+"\n")), nil).
  170. Times(1)
  171. }
  172. // this simulates passing `--filename` with a Compose file that does NOT
  173. // reference `serviceB` even though it has running services for this proj
  174. proj := &types.Project{
  175. Services: types.Services{
  176. "serviceA": {Name: "serviceA"},
  177. "serviceC": {Name: "serviceC"},
  178. },
  179. }
  180. consumer := &testLogConsumer{}
  181. opts := compose.LogOptions{
  182. Project: proj,
  183. }
  184. err = tested.Logs(t.Context(), name, consumer, opts)
  185. assert.NilError(t, err)
  186. assert.Assert(t, is.DeepEqual([]string{"hello c1"}, consumer.LogsForContainer("c1")))
  187. assert.Assert(t, is.DeepEqual([]string{"hello c2"}, consumer.LogsForContainer("c2")))
  188. assert.Assert(t, is.Len(consumer.LogsForContainer("c3"), 0))
  189. assert.Assert(t, is.DeepEqual([]string{"hello c4"}, consumer.LogsForContainer("c4")))
  190. }
  191. type testLogConsumer struct {
  192. mu sync.Mutex
  193. // logs is keyed by container ID; values are log lines
  194. logs map[string][]string
  195. }
  196. func (l *testLogConsumer) Log(containerName, message string) {
  197. l.mu.Lock()
  198. defer l.mu.Unlock()
  199. if l.logs == nil {
  200. l.logs = make(map[string][]string)
  201. }
  202. l.logs[containerName] = append(l.logs[containerName], message)
  203. }
  204. func (l *testLogConsumer) Err(containerName, message string) {
  205. l.Log(containerName, message)
  206. }
  207. func (l *testLogConsumer) Status(containerName, msg string) {}
  208. func (l *testLogConsumer) LogsForContainer(containerName string) []string {
  209. l.mu.Lock()
  210. defer l.mu.Unlock()
  211. return l.logs[containerName]
  212. }