exec.go 4.1 KB

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