attach.go 4.6 KB

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