exec.go 4.7 KB

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