attach.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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/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 enforces 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 _, ctr := range containers {
  43. err := s.attachContainer(ctx, ctr, 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 containerType.Summary, 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. restore := func() { /* noop */ }
  87. if stdin != nil {
  88. in := streams.NewIn(stdin)
  89. if in.IsTerminal() {
  90. state, err := term.SetRawTerminal(in.FD())
  91. if err != nil {
  92. return restore, detached, err
  93. }
  94. restore = func() {
  95. term.RestoreTerminal(in.FD(), state) //nolint:errcheck
  96. }
  97. }
  98. }
  99. streamIn, streamOut, err := s.getContainerStreams(ctx, container)
  100. if err != nil {
  101. return restore, detached, err
  102. }
  103. go func() {
  104. <-ctx.Done()
  105. if stdin != nil {
  106. stdin.Close() //nolint:errcheck
  107. }
  108. }()
  109. if streamIn != nil && stdin != nil {
  110. go func() {
  111. _, err := io.Copy(streamIn, stdin)
  112. var escapeErr term.EscapeError
  113. if errors.As(err, &escapeErr) {
  114. close(detached)
  115. }
  116. }()
  117. }
  118. if stdout != nil {
  119. go func() {
  120. defer stdout.Close() //nolint:errcheck
  121. defer stderr.Close() //nolint:errcheck
  122. defer streamOut.Close() //nolint:errcheck
  123. if tty {
  124. io.Copy(stdout, streamOut) //nolint:errcheck
  125. } else {
  126. stdcopy.StdCopy(stdout, stderr, streamOut) //nolint:errcheck
  127. }
  128. }()
  129. }
  130. return restore, detached, nil
  131. }
  132. func (s *composeService) getContainerStreams(ctx context.Context, container string) (io.WriteCloser, io.ReadCloser, error) {
  133. var stdout io.ReadCloser
  134. var stdin io.WriteCloser
  135. cnx, err := s.apiClient().ContainerAttach(ctx, container, containerType.AttachOptions{
  136. Stream: true,
  137. Stdin: true,
  138. Stdout: true,
  139. Stderr: true,
  140. Logs: false,
  141. })
  142. if err == nil {
  143. stdout = ContainerStdout{HijackedResponse: cnx}
  144. stdin = ContainerStdin{HijackedResponse: cnx}
  145. return stdin, stdout, nil
  146. }
  147. // Fallback to logs API
  148. logs, err := s.apiClient().ContainerLogs(ctx, container, containerType.LogsOptions{
  149. ShowStdout: true,
  150. ShowStderr: true,
  151. Follow: true,
  152. })
  153. if err != nil {
  154. return nil, nil, err
  155. }
  156. return stdin, logs, nil
  157. }