attach.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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/types"
  21. "github.com/docker/cli/cli/streams"
  22. moby "github.com/docker/docker/api/types"
  23. "github.com/docker/docker/pkg/stdcopy"
  24. "github.com/moby/term"
  25. "github.com/docker/compose/v2/pkg/api"
  26. "github.com/docker/compose/v2/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 enforce predictable colors assignment
  37. var names []string
  38. for _, c := range containers {
  39. names = append(names, getContainerNameWithoutProject(c))
  40. }
  41. fmt.Fprintf(s.stdout(), "Attaching to %s\n", strings.Join(names, ", "))
  42. for _, container := range containers {
  43. err := s.attachContainer(ctx, container, listener)
  44. if err != nil {
  45. return nil, err
  46. }
  47. }
  48. return containers, err
  49. }
  50. func (s *composeService) attachContainer(ctx context.Context, container moby.Container, listener api.ContainerEventListener) error {
  51. serviceName := container.Labels[api.ServiceLabel]
  52. containerName := getContainerNameWithoutProject(container)
  53. listener(api.ContainerEvent{
  54. Type: api.ContainerEventAttach,
  55. Container: containerName,
  56. ID: container.ID,
  57. Service: serviceName,
  58. })
  59. wOut := utils.GetWriter(func(line string) {
  60. listener(api.ContainerEvent{
  61. Type: api.ContainerEventLog,
  62. Container: containerName,
  63. ID: container.ID,
  64. Service: serviceName,
  65. Line: line,
  66. })
  67. })
  68. wErr := utils.GetWriter(func(line string) {
  69. listener(api.ContainerEvent{
  70. Type: api.ContainerEventErr,
  71. Container: containerName,
  72. ID: container.ID,
  73. Service: serviceName,
  74. Line: line,
  75. })
  76. })
  77. inspect, err := s.apiClient().ContainerInspect(ctx, container.ID)
  78. if err != nil {
  79. return err
  80. }
  81. _, _, err = s.attachContainerStreams(ctx, container.ID, inspect.Config.Tty, nil, wOut, wErr)
  82. return err
  83. }
  84. func (s *composeService) attachContainerStreams(ctx context.Context, container string, tty bool, stdin io.ReadCloser, stdout, stderr io.WriteCloser) (func(), chan bool, error) {
  85. detached := make(chan bool)
  86. var (
  87. restore = func() { /* noop */ }
  88. )
  89. if stdin != nil {
  90. in := streams.NewIn(stdin)
  91. if in.IsTerminal() {
  92. state, err := term.SetRawTerminal(in.FD())
  93. if err != nil {
  94. return restore, detached, err
  95. }
  96. restore = func() {
  97. term.RestoreTerminal(in.FD(), state) //nolint:errcheck
  98. }
  99. }
  100. }
  101. streamIn, streamOut, err := s.getContainerStreams(ctx, container)
  102. if err != nil {
  103. return restore, detached, err
  104. }
  105. go func() {
  106. <-ctx.Done()
  107. if stdin != nil {
  108. stdin.Close() //nolint:errcheck
  109. }
  110. streamOut.Close() //nolint:errcheck
  111. }()
  112. if streamIn != nil && stdin != nil {
  113. go func() {
  114. _, err := io.Copy(streamIn, stdin)
  115. var escapeErr term.EscapeError
  116. if errors.As(err, &escapeErr) {
  117. close(detached)
  118. }
  119. }()
  120. }
  121. if stdout != nil {
  122. go func() {
  123. defer stdout.Close() //nolint:errcheck
  124. defer stderr.Close() //nolint:errcheck
  125. if tty {
  126. io.Copy(stdout, streamOut) //nolint:errcheck
  127. } else {
  128. stdcopy.StdCopy(stdout, stderr, streamOut) //nolint:errcheck
  129. }
  130. }()
  131. }
  132. return restore, detached, nil
  133. }
  134. func (s *composeService) getContainerStreams(ctx context.Context, container string) (io.WriteCloser, io.ReadCloser, error) {
  135. var stdout io.ReadCloser
  136. var stdin io.WriteCloser
  137. cnx, err := s.apiClient().ContainerAttach(ctx, container, moby.ContainerAttachOptions{
  138. Stream: true,
  139. Stdin: true,
  140. Stdout: true,
  141. Stderr: true,
  142. Logs: false,
  143. })
  144. if err == nil {
  145. stdout = ContainerStdout{HijackedResponse: cnx}
  146. stdin = ContainerStdin{HijackedResponse: cnx}
  147. return stdin, stdout, nil
  148. }
  149. // Fallback to logs API
  150. logs, err := s.apiClient().ContainerLogs(ctx, container, moby.ContainerLogsOptions{
  151. ShowStdout: true,
  152. ShowStderr: true,
  153. Follow: true,
  154. })
  155. if err != nil {
  156. return nil, nil, err
  157. }
  158. return stdin, logs, nil
  159. }