run.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. "fmt"
  18. "os"
  19. "os/signal"
  20. "github.com/compose-spec/compose-go/v2/types"
  21. "github.com/docker/cli/cli"
  22. cmd "github.com/docker/cli/cli/command/container"
  23. "github.com/docker/compose/v2/pkg/api"
  24. "github.com/docker/compose/v2/pkg/utils"
  25. "github.com/docker/docker/pkg/stringid"
  26. )
  27. func (s *composeService) RunOneOffContainer(ctx context.Context, project *types.Project, opts api.RunOptions) (int, error) {
  28. containerID, err := s.prepareRun(ctx, project, opts)
  29. if err != nil {
  30. return 0, err
  31. }
  32. // remove cancellable context signal handler so we can forward signals to container without compose to exit
  33. signal.Reset()
  34. sigc := make(chan os.Signal, 128)
  35. signal.Notify(sigc)
  36. go cmd.ForwardAllSignals(ctx, s.apiClient(), containerID, sigc)
  37. defer signal.Stop(sigc)
  38. err = cmd.RunStart(ctx, s.dockerCli, &cmd.StartOptions{
  39. OpenStdin: !opts.Detach && opts.Interactive,
  40. Attach: !opts.Detach,
  41. Containers: []string{containerID},
  42. })
  43. var stErr cli.StatusError
  44. if errors.As(err, &stErr) {
  45. return stErr.StatusCode, nil
  46. }
  47. return 0, err
  48. }
  49. func (s *composeService) prepareRun(ctx context.Context, project *types.Project, opts api.RunOptions) (string, error) {
  50. service, err := project.GetService(opts.Service)
  51. if err != nil {
  52. return "", err
  53. }
  54. applyRunOptions(project, &service, opts)
  55. if err := s.stdin().CheckTty(opts.Interactive, service.Tty); err != nil {
  56. return "", err
  57. }
  58. slug := stringid.GenerateRandomID()
  59. if service.ContainerName == "" {
  60. service.ContainerName = fmt.Sprintf("%[1]s%[4]s%[2]s%[4]srun%[4]s%[3]s", project.Name, service.Name, stringid.TruncateID(slug), api.Separator)
  61. }
  62. one := 1
  63. service.Scale = &one
  64. service.Restart = ""
  65. if service.Deploy != nil {
  66. service.Deploy.RestartPolicy = nil
  67. }
  68. service.CustomLabels = service.CustomLabels.
  69. Add(api.SlugLabel, slug).
  70. Add(api.OneoffLabel, "True")
  71. if err := s.ensureImagesExists(ctx, project, opts.Build, opts.QuietPull); err != nil { // all dependencies already checked, but might miss service img
  72. return "", err
  73. }
  74. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  75. if err != nil {
  76. return "", err
  77. }
  78. if !opts.NoDeps {
  79. if err := s.waitDependencies(ctx, project, service.Name, service.DependsOn, observedState); err != nil {
  80. return "", err
  81. }
  82. }
  83. createOpts := createOptions{
  84. AutoRemove: opts.AutoRemove,
  85. AttachStdin: opts.Interactive,
  86. UseNetworkAliases: opts.UseNetworkAliases,
  87. Labels: mergeLabels(service.Labels, service.CustomLabels),
  88. }
  89. err = newConvergence(project.ServiceNames(), observedState, s).resolveServiceReferences(&service)
  90. if err != nil {
  91. return "", err
  92. }
  93. created, err := s.createContainer(ctx, project, service, service.ContainerName, 1, createOpts)
  94. if err != nil {
  95. return "", err
  96. }
  97. return created.ID, nil
  98. }
  99. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  100. service.Tty = opts.Tty
  101. service.StdinOpen = opts.Interactive
  102. service.ContainerName = opts.Name
  103. if len(opts.Command) > 0 {
  104. service.Command = opts.Command
  105. }
  106. if len(opts.User) > 0 {
  107. service.User = opts.User
  108. }
  109. if len(opts.CapAdd) > 0 {
  110. service.CapAdd = append(service.CapAdd, opts.CapAdd...)
  111. service.CapDrop = utils.Remove(service.CapDrop, opts.CapAdd...)
  112. }
  113. if len(opts.CapDrop) > 0 {
  114. service.CapDrop = append(service.CapDrop, opts.CapDrop...)
  115. service.CapAdd = utils.Remove(service.CapAdd, opts.CapDrop...)
  116. }
  117. if len(opts.WorkingDir) > 0 {
  118. service.WorkingDir = opts.WorkingDir
  119. }
  120. if opts.Entrypoint != nil {
  121. service.Entrypoint = opts.Entrypoint
  122. if len(opts.Command) == 0 {
  123. service.Command = []string{}
  124. }
  125. }
  126. if len(opts.Environment) > 0 {
  127. cmdEnv := types.NewMappingWithEquals(opts.Environment)
  128. serviceOverrideEnv := cmdEnv.Resolve(func(s string) (string, bool) {
  129. v, ok := envResolver(project.Environment)(s)
  130. return v, ok
  131. }).RemoveEmpty()
  132. service.Environment.OverrideBy(serviceOverrideEnv)
  133. }
  134. for k, v := range opts.Labels {
  135. service.Labels = service.Labels.Add(k, v)
  136. }
  137. }