run.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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/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.dockerCli, containerID, sigc)
  37. defer signal.Stop(sigc)
  38. err = cmd.RunStart(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. if err := prepareVolumes(project); err != nil { // all dependencies already checked, but might miss service img
  51. return "", err
  52. }
  53. service, err := project.GetService(opts.Service)
  54. if err != nil {
  55. return "", err
  56. }
  57. applyRunOptions(project, &service, opts)
  58. if err := s.stdin().CheckTty(opts.Interactive, service.Tty); err != nil {
  59. return "", err
  60. }
  61. slug := stringid.GenerateRandomID()
  62. if service.ContainerName == "" {
  63. 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)
  64. }
  65. service.Scale = 1
  66. service.Restart = ""
  67. if service.Deploy != nil {
  68. service.Deploy.RestartPolicy = nil
  69. }
  70. service.CustomLabels = service.CustomLabels.
  71. Add(api.SlugLabel, slug).
  72. Add(api.OneoffLabel, "True")
  73. if err := s.ensureImagesExists(ctx, project, opts.QuietPull); err != nil { // all dependencies already checked, but might miss service img
  74. return "", err
  75. }
  76. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  77. if err != nil {
  78. return "", err
  79. }
  80. updateServices(&service, observedState)
  81. if !opts.NoDeps {
  82. if err := s.waitDependencies(ctx, project, service.DependsOn, observedState); err != nil {
  83. return "", err
  84. }
  85. }
  86. createOpts := createOptions{
  87. AutoRemove: opts.AutoRemove,
  88. AttachStdin: opts.Interactive,
  89. UseNetworkAliases: opts.UseNetworkAliases,
  90. Labels: mergeLabels(service.Labels, service.CustomLabels),
  91. }
  92. created, err := s.createContainer(ctx, project, service, service.ContainerName, 1, createOpts)
  93. if err != nil {
  94. return "", err
  95. }
  96. return created.ID, nil
  97. }
  98. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  99. service.Tty = opts.Tty
  100. service.StdinOpen = opts.Interactive
  101. service.ContainerName = opts.Name
  102. if len(opts.Command) > 0 {
  103. service.Command = opts.Command
  104. }
  105. if len(opts.User) > 0 {
  106. service.User = opts.User
  107. }
  108. if len(opts.CapAdd) > 0 {
  109. service.CapAdd = append(service.CapAdd, opts.CapAdd...)
  110. service.CapDrop = utils.Remove(service.CapDrop, opts.CapAdd...)
  111. }
  112. if len(opts.CapDrop) > 0 {
  113. service.CapDrop = append(service.CapDrop, opts.CapDrop...)
  114. service.CapAdd = utils.Remove(service.CapAdd, opts.CapDrop...)
  115. }
  116. if len(opts.WorkingDir) > 0 {
  117. service.WorkingDir = opts.WorkingDir
  118. }
  119. if opts.Entrypoint != nil {
  120. service.Entrypoint = opts.Entrypoint
  121. if len(opts.Command) == 0 {
  122. service.Command = []string{}
  123. }
  124. }
  125. if len(opts.Environment) > 0 {
  126. cmdEnv := types.NewMappingWithEquals(opts.Environment)
  127. serviceOverrideEnv := cmdEnv.Resolve(func(s string) (string, bool) {
  128. v, ok := envResolver(project.Environment)(s)
  129. return v, ok
  130. }).RemoveEmpty()
  131. service.Environment.OverrideBy(serviceOverrideEnv)
  132. }
  133. for k, v := range opts.Labels {
  134. service.Labels = service.Labels.Add(k, v)
  135. }
  136. }