exec.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "errors"
  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. )
  23. func (s *composeService) Exec(ctx context.Context, projectName string, options api.RunOptions) (int, error) {
  24. projectName = strings.ToLower(projectName)
  25. target, err := s.getExecTarget(ctx, projectName, options)
  26. if err != nil {
  27. return 0, err
  28. }
  29. exec := container.NewExecOptions()
  30. exec.Interactive = options.Interactive
  31. exec.TTY = options.Tty
  32. exec.Detach = options.Detach
  33. exec.User = options.User
  34. exec.Privileged = options.Privileged
  35. exec.Workdir = options.WorkingDir
  36. exec.Command = options.Command
  37. for _, v := range options.Environment {
  38. err := exec.Env.Set(v)
  39. if err != nil {
  40. return 0, err
  41. }
  42. }
  43. err = container.RunExec(ctx, s.dockerCli, target.ID, exec)
  44. var sterr cli.StatusError
  45. if errors.As(err, &sterr) {
  46. return sterr.StatusCode, nil
  47. }
  48. return 0, err
  49. }
  50. func (s *composeService) getExecTarget(ctx context.Context, projectName string, opts api.RunOptions) (moby.Container, error) {
  51. return s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, opts.Service, opts.Index)
  52. }