exec.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "github.com/docker/cli/cli"
  18. "github.com/docker/cli/cli/command/container"
  19. "github.com/docker/compose/v2/pkg/api"
  20. moby "github.com/docker/docker/api/types"
  21. "github.com/docker/docker/api/types/filters"
  22. )
  23. func (s *composeService) Exec(ctx context.Context, project string, opts api.RunOptions) (int, error) {
  24. target, err := s.getExecTarget(ctx, project, opts)
  25. if err != nil {
  26. return 0, err
  27. }
  28. exec := container.NewExecOptions()
  29. exec.Interactive = opts.Interactive
  30. exec.TTY = opts.Tty
  31. exec.Detach = opts.Detach
  32. exec.User = opts.User
  33. exec.Privileged = opts.Privileged
  34. exec.Workdir = opts.WorkingDir
  35. exec.Container = target.ID
  36. exec.Command = opts.Command
  37. for _, v := range opts.Environment {
  38. err := exec.Env.Set(v)
  39. if err != nil {
  40. return 0, err
  41. }
  42. }
  43. err = container.RunExec(s.dockerCli, exec)
  44. if sterr, ok := err.(cli.StatusError); ok {
  45. return sterr.StatusCode, nil
  46. }
  47. return 0, err
  48. }
  49. func (s *composeService) getExecTarget(ctx context.Context, projectName string, opts api.RunOptions) (moby.Container, error) {
  50. containers, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{
  51. Filters: filters.NewArgs(
  52. projectFilter(projectName),
  53. serviceFilter(opts.Service),
  54. containerNumberFilter(opts.Index),
  55. ),
  56. })
  57. if err != nil {
  58. return moby.Container{}, err
  59. }
  60. if len(containers) < 1 {
  61. return moby.Container{}, fmt.Errorf("service %q is not running container #%d", opts.Service, opts.Index)
  62. }
  63. container := containers[0]
  64. return container, nil
  65. }