exec.go 2.2 KB

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