attach.go 4.6 KB

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