logs.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. "io"
  17. "github.com/docker/compose/v2/pkg/api"
  18. "github.com/docker/compose/v2/pkg/utils"
  19. "github.com/docker/docker/api/types"
  20. "github.com/docker/docker/pkg/stdcopy"
  21. "golang.org/x/sync/errgroup"
  22. )
  23. func (s *composeService) Logs(ctx context.Context, projectName string, consumer api.LogConsumer, options api.LogOptions) error {
  24. containers, err := s.getContainers(ctx, projectName, oneOffExclude, true, options.Services...)
  25. if err != nil {
  26. return err
  27. }
  28. eg, ctx := errgroup.WithContext(ctx)
  29. if options.Follow {
  30. printer := newLogPrinter(consumer)
  31. eg.Go(func() error {
  32. return s.watchContainers(ctx, projectName, options.Services, printer.HandleEvent, containers, func(c types.Container) error {
  33. return s.logContainers(ctx, consumer, c, options)
  34. })
  35. })
  36. eg.Go(func() error {
  37. _, err := printer.Run(ctx, false, "", nil)
  38. return err
  39. })
  40. }
  41. for _, c := range containers {
  42. c := c
  43. eg.Go(func() error {
  44. return s.logContainers(ctx, consumer, c, options)
  45. })
  46. }
  47. return eg.Wait()
  48. }
  49. func (s *composeService) logContainers(ctx context.Context, consumer api.LogConsumer, c types.Container, options api.LogOptions) error {
  50. cnt, err := s.apiClient.ContainerInspect(ctx, c.ID)
  51. if err != nil {
  52. return err
  53. }
  54. service := c.Labels[api.ServiceLabel]
  55. r, err := s.apiClient.ContainerLogs(ctx, cnt.ID, types.ContainerLogsOptions{
  56. ShowStdout: true,
  57. ShowStderr: true,
  58. Follow: options.Follow,
  59. Since: options.Since,
  60. Until: options.Until,
  61. Tail: options.Tail,
  62. Timestamps: options.Timestamps,
  63. })
  64. if err != nil {
  65. return err
  66. }
  67. defer r.Close() // nolint errcheck
  68. name := getContainerNameWithoutProject(c)
  69. w := utils.GetWriter(func(line string) {
  70. consumer.Log(name, service, line)
  71. })
  72. if cnt.Config.Tty {
  73. _, err = io.Copy(w, r)
  74. } else {
  75. _, err = stdcopy.StdCopy(w, w, r)
  76. }
  77. return err
  78. }