1
0

attach.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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/docker/cli/cli/streams"
  22. containerType "github.com/docker/docker/api/types/container"
  23. "github.com/docker/docker/pkg/stdcopy"
  24. "github.com/moby/term"
  25. "github.com/sirupsen/logrus"
  26. "github.com/docker/compose/v5/pkg/api"
  27. "github.com/docker/compose/v5/pkg/utils"
  28. )
  29. func (s *composeService) attach(ctx context.Context, project *types.Project, listener api.ContainerEventListener, selectedServices []string) (Containers, error) {
  30. containers, err := s.getContainers(ctx, project.Name, oneOffExclude, true, selectedServices...)
  31. if err != nil {
  32. return nil, err
  33. }
  34. if len(containers) == 0 {
  35. return containers, nil
  36. }
  37. containers.sorted() // This enforces predictable colors assignment
  38. var names []string
  39. for _, c := range containers {
  40. names = append(names, getContainerNameWithoutProject(c))
  41. }
  42. _, err = fmt.Fprintf(s.stdout(), "Attaching to %s\n", strings.Join(names, ", "))
  43. if err != nil {
  44. logrus.Debugf("failed to write attach message: %v", err)
  45. }
  46. for _, ctr := range containers {
  47. err := s.attachContainer(ctx, ctr, listener)
  48. if err != nil {
  49. return nil, err
  50. }
  51. }
  52. return containers, nil
  53. }
  54. func (s *composeService) attachContainer(ctx context.Context, container containerType.Summary, listener api.ContainerEventListener) error {
  55. service := container.Labels[api.ServiceLabel]
  56. name := getContainerNameWithoutProject(container)
  57. return s.doAttachContainer(ctx, service, container.ID, name, listener)
  58. }
  59. func (s *composeService) doAttachContainer(ctx context.Context, service, id, name string, listener api.ContainerEventListener) error {
  60. inspect, err := s.apiClient().ContainerInspect(ctx, id)
  61. if err != nil {
  62. return err
  63. }
  64. wOut := utils.GetWriter(func(line string) {
  65. listener(api.ContainerEvent{
  66. Type: api.ContainerEventLog,
  67. Source: name,
  68. ID: id,
  69. Service: service,
  70. Line: line,
  71. })
  72. })
  73. wErr := utils.GetWriter(func(line string) {
  74. listener(api.ContainerEvent{
  75. Type: api.ContainerEventErr,
  76. Source: name,
  77. ID: id,
  78. Service: service,
  79. Line: line,
  80. })
  81. })
  82. restore, _, err := s.attachContainerStreams(ctx, id, inspect.Config.Tty, nil, wOut, wErr)
  83. if err != nil {
  84. return err
  85. }
  86. defer restore()
  87. return nil
  88. }
  89. //nolint:gocyclo
  90. func (s *composeService) attachContainerStreams(ctx context.Context, container string, tty bool, stdin io.ReadCloser, stdout, stderr io.WriteCloser) (func(), chan bool, error) {
  91. detached := make(chan bool)
  92. restore := func() { /* noop */ }
  93. if stdin != nil {
  94. in := streams.NewIn(stdin)
  95. if in.IsTerminal() {
  96. state, err := term.SetRawTerminal(in.FD())
  97. if err != nil {
  98. return restore, detached, err
  99. }
  100. restore = func() {
  101. err := term.RestoreTerminal(in.FD(), state)
  102. if err != nil {
  103. logrus.Warnf("failed to restore terminal: %v", err)
  104. }
  105. }
  106. }
  107. }
  108. streamIn, streamOut, err := s.getContainerStreams(ctx, container)
  109. if err != nil {
  110. return restore, detached, err
  111. }
  112. go func() {
  113. <-ctx.Done()
  114. if stdin != nil {
  115. err := stdin.Close()
  116. if err != nil {
  117. logrus.Debugf("failed to close stdin: %v", err)
  118. }
  119. }
  120. }()
  121. if streamIn != nil && stdin != nil {
  122. go func() {
  123. _, err := io.Copy(streamIn, stdin)
  124. var escapeErr term.EscapeError
  125. if errors.As(err, &escapeErr) {
  126. close(detached)
  127. } else if err != nil && !errors.Is(err, io.EOF) {
  128. logrus.Debugf("stdin copy error for container %s: %v", container, err)
  129. }
  130. }()
  131. }
  132. if stdout != nil {
  133. go func() {
  134. defer func() {
  135. if err := stdout.Close(); err != nil {
  136. logrus.Debugf("failed to close stdout: %v", err)
  137. }
  138. if err := stderr.Close(); err != nil {
  139. logrus.Debugf("failed to close stderr: %v", err)
  140. }
  141. if err := streamOut.Close(); err != nil {
  142. logrus.Debugf("failed to close stream output: %v", err)
  143. }
  144. }()
  145. var err error
  146. if tty {
  147. _, err = io.Copy(stdout, streamOut)
  148. } else {
  149. _, err = stdcopy.StdCopy(stdout, stderr, streamOut)
  150. }
  151. if err != nil && !errors.Is(err, io.EOF) {
  152. logrus.Debugf("stream copy error for container %s: %v", container, err)
  153. }
  154. }()
  155. }
  156. return restore, detached, nil
  157. }
  158. func (s *composeService) getContainerStreams(ctx context.Context, container string) (io.WriteCloser, io.ReadCloser, error) {
  159. cnx, err := s.apiClient().ContainerAttach(ctx, container, containerType.AttachOptions{
  160. Stream: true,
  161. Stdin: true,
  162. Stdout: true,
  163. Stderr: true,
  164. Logs: false,
  165. DetachKeys: s.configFile().DetachKeys,
  166. })
  167. if err == nil {
  168. stdout := ContainerStdout{HijackedResponse: cnx}
  169. stdin := ContainerStdin{HijackedResponse: cnx}
  170. return stdin, stdout, nil
  171. }
  172. // Fallback to logs API
  173. logs, err := s.apiClient().ContainerLogs(ctx, container, containerType.LogsOptions{
  174. ShowStdout: true,
  175. ShowStderr: true,
  176. Follow: true,
  177. })
  178. if err != nil {
  179. return nil, nil, err
  180. }
  181. return nil, logs, nil
  182. }