attach.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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/docker/compose-cli/api/compose"
  20. convert "github.com/docker/compose-cli/local/moby"
  21. "github.com/docker/compose-cli/utils"
  22. "github.com/compose-spec/compose-go/types"
  23. "github.com/docker/cli/cli/streams"
  24. moby "github.com/docker/docker/api/types"
  25. "github.com/docker/docker/pkg/stdcopy"
  26. )
  27. func (s *composeService) attach(ctx context.Context, project *types.Project, listener compose.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. // Watch events to capture container restart and re-attach
  45. go func() {
  46. crashed := map[string]struct{}{}
  47. s.Events(ctx, project.Name, compose.EventsOptions{ // nolint: errcheck
  48. Services: selectedServices,
  49. Consumer: func(event compose.Event) error {
  50. if event.Status == "die" {
  51. crashed[event.Container] = struct{}{}
  52. return nil
  53. }
  54. if _, ok := crashed[event.Container]; ok {
  55. inspect, err := s.apiClient.ContainerInspect(ctx, event.Container)
  56. if err != nil {
  57. return err
  58. }
  59. container := moby.Container{
  60. ID: event.Container,
  61. Names: []string{inspect.Name},
  62. State: convert.ContainerRunning,
  63. Labels: map[string]string{
  64. projectLabel: project.Name,
  65. serviceLabel: event.Service,
  66. },
  67. }
  68. // Just ignore errors when reattaching to already crashed containers
  69. s.attachContainer(ctx, container, listener, project) // nolint: errcheck
  70. delete(crashed, event.Container)
  71. s.waitContainer(container, listener)
  72. }
  73. return nil
  74. },
  75. })
  76. }()
  77. return containers, err
  78. }
  79. func (s *composeService) attachContainer(ctx context.Context, container moby.Container, listener compose.ContainerEventListener, project *types.Project) error {
  80. serviceName := container.Labels[serviceLabel]
  81. w := utils.GetWriter(getContainerNameWithoutProject(container), serviceName, listener)
  82. service, err := project.GetService(serviceName)
  83. if err != nil {
  84. return err
  85. }
  86. listener(compose.ContainerEvent{
  87. Type: compose.ContainerEventAttach,
  88. Container: getContainerNameWithoutProject(container),
  89. Service: container.Labels[serviceLabel],
  90. })
  91. _, err = s.attachContainerStreams(ctx, container.ID, service.Tty, nil, w)
  92. return err
  93. }
  94. func (s *composeService) attachContainerStreams(ctx context.Context, container string, tty bool, r io.ReadCloser, w io.Writer) (func(), error) {
  95. var (
  96. in *streams.In
  97. restore = func() { /* noop */ }
  98. )
  99. if r != nil {
  100. in = streams.NewIn(r)
  101. restore = in.RestoreTerminal
  102. }
  103. stdin, stdout, err := s.getContainerStreams(ctx, container)
  104. if err != nil {
  105. return restore, err
  106. }
  107. go func() {
  108. <-ctx.Done()
  109. if in != nil {
  110. in.Close() //nolint:errcheck
  111. }
  112. stdout.Close() //nolint:errcheck
  113. }()
  114. if in != nil && stdin != nil {
  115. err := in.SetRawTerminal()
  116. if err != nil {
  117. return restore, err
  118. }
  119. go func() {
  120. io.Copy(stdin, in) //nolint:errcheck
  121. }()
  122. }
  123. if w != nil {
  124. go func() {
  125. if tty {
  126. io.Copy(w, stdout) // nolint:errcheck
  127. } else {
  128. stdcopy.StdCopy(w, w, stdout) // nolint:errcheck
  129. }
  130. }()
  131. }
  132. return restore, nil
  133. }
  134. func (s *composeService) getContainerStreams(ctx context.Context, container string) (io.WriteCloser, io.ReadCloser, error) {
  135. var stdout io.ReadCloser
  136. var stdin io.WriteCloser
  137. cnx, err := s.apiClient.ContainerAttach(ctx, container, moby.ContainerAttachOptions{
  138. Stream: true,
  139. Stdin: true,
  140. Stdout: true,
  141. Stderr: true,
  142. Logs: false,
  143. })
  144. if err == nil {
  145. stdout = convert.ContainerStdout{HijackedResponse: cnx}
  146. stdin = convert.ContainerStdin{HijackedResponse: cnx}
  147. return stdin, stdout, nil
  148. }
  149. // Fallback to logs API
  150. logs, err := s.apiClient.ContainerLogs(ctx, container, moby.ContainerLogsOptions{
  151. ShowStdout: true,
  152. ShowStderr: true,
  153. Follow: true,
  154. })
  155. if err != nil {
  156. return nil, nil, err
  157. }
  158. return stdin, logs, nil
  159. }