run.go 4.6 KB

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