attach.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. service := container.Labels[api.ServiceLabel]
  52. name := getContainerNameWithoutProject(container)
  53. return s.doAttachContainer(ctx, service, container.ID, name, listener)
  54. }
  55. func (s *composeService) doAttachContainer(ctx context.Context, service, id, name string, listener api.ContainerEventListener) error {
  56. inspect, err := s.apiClient().ContainerInspect(ctx, id)
  57. if err != nil {
  58. return err
  59. }
  60. wOut := utils.GetWriter(func(line string) {
  61. listener(api.ContainerEvent{
  62. Type: api.ContainerEventLog,
  63. Source: name,
  64. ID: id,
  65. Service: service,
  66. Line: line,
  67. })
  68. })
  69. wErr := utils.GetWriter(func(line string) {
  70. listener(api.ContainerEvent{
  71. Type: api.ContainerEventErr,
  72. Source: name,
  73. ID: id,
  74. Service: service,
  75. Line: line,
  76. })
  77. })
  78. _, _, err = s.attachContainerStreams(ctx, id, inspect.Config.Tty, nil, wOut, wErr)
  79. return err
  80. }
  81. func (s *composeService) attachContainerStreams(ctx context.Context, container string, tty bool, stdin io.ReadCloser, stdout, stderr io.WriteCloser) (func(), chan bool, error) {
  82. detached := make(chan bool)
  83. restore := func() { /* noop */ }
  84. if stdin != nil {
  85. in := streams.NewIn(stdin)
  86. if in.IsTerminal() {
  87. state, err := term.SetRawTerminal(in.FD())
  88. if err != nil {
  89. return restore, detached, err
  90. }
  91. restore = func() {
  92. term.RestoreTerminal(in.FD(), state) //nolint:errcheck
  93. }
  94. }
  95. }
  96. streamIn, streamOut, err := s.getContainerStreams(ctx, container)
  97. if err != nil {
  98. return restore, detached, err
  99. }
  100. go func() {
  101. <-ctx.Done()
  102. if stdin != nil {
  103. stdin.Close() //nolint:errcheck
  104. }
  105. }()
  106. if streamIn != nil && stdin != nil {
  107. go func() {
  108. _, err := io.Copy(streamIn, stdin)
  109. var escapeErr term.EscapeError
  110. if errors.As(err, &escapeErr) {
  111. close(detached)
  112. }
  113. }()
  114. }
  115. if stdout != nil {
  116. go func() {
  117. defer stdout.Close() //nolint:errcheck
  118. defer stderr.Close() //nolint:errcheck
  119. defer streamOut.Close() //nolint:errcheck
  120. if tty {
  121. io.Copy(stdout, streamOut) //nolint:errcheck
  122. } else {
  123. stdcopy.StdCopy(stdout, stderr, streamOut) //nolint:errcheck
  124. }
  125. }()
  126. }
  127. return restore, detached, nil
  128. }
  129. func (s *composeService) getContainerStreams(ctx context.Context, container string) (io.WriteCloser, io.ReadCloser, error) {
  130. var stdout io.ReadCloser
  131. var stdin io.WriteCloser
  132. cnx, err := s.apiClient().ContainerAttach(ctx, container, containerType.AttachOptions{
  133. Stream: true,
  134. Stdin: true,
  135. Stdout: true,
  136. Stderr: true,
  137. Logs: false,
  138. })
  139. if err == nil {
  140. stdout = ContainerStdout{HijackedResponse: cnx}
  141. stdin = ContainerStdin{HijackedResponse: cnx}
  142. return stdin, stdout, nil
  143. }
  144. // Fallback to logs API
  145. logs, err := s.apiClient().ContainerLogs(ctx, container, containerType.LogsOptions{
  146. ShowStdout: true,
  147. ShowStderr: true,
  148. Follow: true,
  149. })
  150. if err != nil {
  151. return nil, nil, err
  152. }
  153. return stdin, logs, nil
  154. }