attach.go 5.0 KB

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