exec.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. "github.com/docker/cli/cli/streams"
  19. moby "github.com/docker/docker/api/types"
  20. "github.com/docker/docker/api/types/filters"
  21. "github.com/docker/docker/pkg/stdcopy"
  22. "github.com/moby/term"
  23. "github.com/docker/compose/v2/pkg/api"
  24. )
  25. func (s *composeService) Exec(ctx context.Context, project string, opts api.RunOptions) (int, error) {
  26. container, err := s.getExecTarget(ctx, project, opts)
  27. if err != nil {
  28. return 0, err
  29. }
  30. exec, err := s.apiClient.ContainerExecCreate(ctx, container.ID, moby.ExecConfig{
  31. Cmd: opts.Command,
  32. Env: opts.Environment,
  33. User: opts.User,
  34. Privileged: opts.Privileged,
  35. Tty: opts.Tty,
  36. Detach: opts.Detach,
  37. WorkingDir: opts.WorkingDir,
  38. AttachStdin: true,
  39. AttachStdout: true,
  40. AttachStderr: true,
  41. })
  42. if err != nil {
  43. return 0, err
  44. }
  45. if opts.Detach {
  46. return 0, s.apiClient.ContainerExecStart(ctx, exec.ID, moby.ExecStartCheck{
  47. Detach: true,
  48. Tty: opts.Tty,
  49. })
  50. }
  51. resp, err := s.apiClient.ContainerExecAttach(ctx, exec.ID, moby.ExecStartCheck{
  52. Tty: opts.Tty,
  53. })
  54. if err != nil {
  55. return 0, err
  56. }
  57. defer resp.Close() //nolint:errcheck
  58. if opts.Tty {
  59. s.monitorTTySize(ctx, exec.ID, s.apiClient.ContainerExecResize)
  60. if err != nil {
  61. return 0, err
  62. }
  63. }
  64. err = s.interactiveExec(ctx, opts, resp)
  65. if err != nil {
  66. return 0, err
  67. }
  68. return s.getExecExitStatus(ctx, exec.ID)
  69. }
  70. // inspired by https://github.com/docker/cli/blob/master/cli/command/container/exec.go#L116
  71. func (s *composeService) interactiveExec(ctx context.Context, opts api.RunOptions, resp moby.HijackedResponse) error {
  72. outputDone := make(chan error)
  73. inputDone := make(chan error)
  74. stdout := ContainerStdout{HijackedResponse: resp}
  75. stdin := ContainerStdin{HijackedResponse: resp}
  76. r, err := s.getEscapeKeyProxy(opts.Stdin, opts.Tty)
  77. if err != nil {
  78. return err
  79. }
  80. in := streams.NewIn(opts.Stdin)
  81. if in.IsTerminal() {
  82. state, err := term.SetRawTerminal(in.FD())
  83. if err != nil {
  84. return err
  85. }
  86. defer term.RestoreTerminal(in.FD(), state) //nolint:errcheck
  87. }
  88. go func() {
  89. if opts.Tty {
  90. _, err := io.Copy(opts.Stdout, stdout)
  91. outputDone <- err
  92. } else {
  93. _, err := stdcopy.StdCopy(opts.Stdout, opts.Stderr, stdout)
  94. outputDone <- err
  95. }
  96. stdout.Close() //nolint:errcheck
  97. }()
  98. go func() {
  99. _, err := io.Copy(stdin, r)
  100. inputDone <- err
  101. stdin.Close() //nolint:errcheck
  102. }()
  103. for {
  104. select {
  105. case err := <-outputDone:
  106. return err
  107. case err := <-inputDone:
  108. if _, ok := err.(term.EscapeError); ok {
  109. return nil
  110. }
  111. if err != nil {
  112. return err
  113. }
  114. // Wait for output to complete streaming
  115. case <-ctx.Done():
  116. return ctx.Err()
  117. }
  118. }
  119. }
  120. func (s *composeService) getExecTarget(ctx context.Context, projectName string, opts api.RunOptions) (moby.Container, error) {
  121. containers, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  122. Filters: filters.NewArgs(
  123. projectFilter(projectName),
  124. serviceFilter(opts.Service),
  125. containerNumberFilter(opts.Index),
  126. ),
  127. })
  128. if err != nil {
  129. return moby.Container{}, err
  130. }
  131. if len(containers) < 1 {
  132. return moby.Container{}, fmt.Errorf("service %q is not running container #%d", opts.Service, opts.Index)
  133. }
  134. container := containers[0]
  135. return container, nil
  136. }
  137. func (s *composeService) getExecExitStatus(ctx context.Context, execID string) (int, error) {
  138. resp, err := s.apiClient.ContainerExecInspect(ctx, execID)
  139. if err != nil {
  140. return 0, err
  141. }
  142. return resp.ExitCode, nil
  143. }