attach.go 4.7 KB

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