attach.go 4.2 KB

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