attach.go 4.5 KB

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