attach.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. "errors"
  17. "fmt"
  18. "io"
  19. "strings"
  20. "github.com/compose-spec/compose-go/v2/types"
  21. "github.com/moby/moby/api/pkg/stdcopy"
  22. containerType "github.com/moby/moby/api/types/container"
  23. "github.com/moby/moby/client"
  24. "github.com/sirupsen/logrus"
  25. "github.com/docker/compose/v5/pkg/api"
  26. "github.com/docker/compose/v5/pkg/utils"
  27. )
  28. func (s *composeService) attach(ctx context.Context, project *types.Project, listener api.ContainerEventListener, selectedServices []string) (Containers, error) {
  29. containers, err := s.getContainers(ctx, project.Name, oneOffExclude, true, selectedServices...)
  30. if err != nil {
  31. return nil, err
  32. }
  33. if len(containers) == 0 {
  34. return containers, nil
  35. }
  36. containers.sorted() // This enforces predictable colors assignment
  37. var names []string
  38. for _, c := range containers {
  39. names = append(names, getContainerNameWithoutProject(c))
  40. }
  41. _, err = fmt.Fprintf(s.stdout(), "Attaching to %s\n", strings.Join(names, ", "))
  42. if err != nil {
  43. logrus.Debugf("failed to write attach message: %v", err)
  44. }
  45. for _, ctr := range containers {
  46. err := s.attachContainer(ctx, ctr, listener)
  47. if err != nil {
  48. return nil, err
  49. }
  50. }
  51. return containers, nil
  52. }
  53. func (s *composeService) attachContainer(ctx context.Context, container containerType.Summary, listener api.ContainerEventListener) error {
  54. service := container.Labels[api.ServiceLabel]
  55. name := getContainerNameWithoutProject(container)
  56. return s.doAttachContainer(ctx, service, container.ID, name, listener)
  57. }
  58. func (s *composeService) doAttachContainer(ctx context.Context, service, id, name string, listener api.ContainerEventListener) error {
  59. inspect, err := s.apiClient().ContainerInspect(ctx, id, client.ContainerInspectOptions{})
  60. if err != nil {
  61. return err
  62. }
  63. wOut := utils.GetWriter(func(line string) {
  64. listener(api.ContainerEvent{
  65. Type: api.ContainerEventLog,
  66. Source: name,
  67. ID: id,
  68. Service: service,
  69. Line: line,
  70. })
  71. })
  72. wErr := utils.GetWriter(func(line string) {
  73. listener(api.ContainerEvent{
  74. Type: api.ContainerEventErr,
  75. Source: name,
  76. ID: id,
  77. Service: service,
  78. Line: line,
  79. })
  80. })
  81. err = s.attachContainerStreams(ctx, id, inspect.Container.Config.Tty, wOut, wErr)
  82. if err != nil {
  83. return err
  84. }
  85. return nil
  86. }
  87. func (s *composeService) attachContainerStreams(ctx context.Context, container string, tty bool, stdout, stderr io.WriteCloser) error {
  88. streamOut, err := s.getContainerStreams(ctx, container)
  89. if err != nil {
  90. return err
  91. }
  92. if stdout != nil {
  93. go func() {
  94. defer func() {
  95. if err := stdout.Close(); err != nil {
  96. logrus.Debugf("failed to close stdout: %v", err)
  97. }
  98. if err := stderr.Close(); err != nil {
  99. logrus.Debugf("failed to close stderr: %v", err)
  100. }
  101. if err := streamOut.Close(); err != nil {
  102. logrus.Debugf("failed to close stream output: %v", err)
  103. }
  104. }()
  105. var err error
  106. if tty {
  107. _, err = io.Copy(stdout, streamOut)
  108. } else {
  109. _, err = stdcopy.StdCopy(stdout, stderr, streamOut)
  110. }
  111. if err != nil && !errors.Is(err, io.EOF) {
  112. logrus.Debugf("stream copy error for container %s: %v", container, err)
  113. }
  114. }()
  115. }
  116. return nil
  117. }
  118. func (s *composeService) getContainerStreams(ctx context.Context, container string) (io.ReadCloser, error) {
  119. cnx, err := s.apiClient().ContainerAttach(ctx, container, client.ContainerAttachOptions{
  120. Stream: true,
  121. Stdin: false,
  122. Stdout: true,
  123. Stderr: true,
  124. Logs: false,
  125. })
  126. if err == nil {
  127. stdout := ContainerStdout{HijackedResponse: cnx.HijackedResponse}
  128. return stdout, nil
  129. }
  130. // Fallback to logs API
  131. logs, err := s.apiClient().ContainerLogs(ctx, container, client.ContainerLogsOptions{
  132. ShowStdout: true,
  133. ShowStderr: true,
  134. Follow: true,
  135. })
  136. if err != nil {
  137. return nil, err
  138. }
  139. return logs, nil
  140. }