run.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. "slices"
  21. "github.com/compose-spec/compose-go/v2/types"
  22. "github.com/docker/cli/cli"
  23. cmd "github.com/docker/cli/cli/command/container"
  24. "github.com/docker/compose/v2/pkg/api"
  25. "github.com/docker/compose/v2/pkg/progress"
  26. "github.com/docker/docker/pkg/stringid"
  27. )
  28. func (s *composeService) RunOneOffContainer(ctx context.Context, project *types.Project, opts api.RunOptions) (int, error) {
  29. containerID, err := s.prepareRun(ctx, project, opts)
  30. if err != nil {
  31. return 0, err
  32. }
  33. // remove cancellable context signal handler so we can forward signals to container without compose to exit
  34. signal.Reset()
  35. sigc := make(chan os.Signal, 128)
  36. signal.Notify(sigc)
  37. go cmd.ForwardAllSignals(ctx, s.apiClient(), containerID, sigc)
  38. defer signal.Stop(sigc)
  39. err = cmd.RunStart(ctx, s.dockerCli, &cmd.StartOptions{
  40. OpenStdin: !opts.Detach && opts.Interactive,
  41. Attach: !opts.Detach,
  42. Containers: []string{containerID},
  43. })
  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) prepareRun(ctx context.Context, project *types.Project, opts api.RunOptions) (string, error) {
  51. err = progress.Run(ctx, func(ctx context.Context) error {
  52. return s.startDependencies(ctx, project, opts)
  53. }, s.stdinfo())
  54. if err != nil {
  55. return "", err
  56. }
  57. service, err := project.GetService(opts.Service)
  58. if err != nil {
  59. return "", err
  60. }
  61. applyRunOptions(project, &service, opts)
  62. if err := s.stdin().CheckTty(opts.Interactive, service.Tty); err != nil {
  63. return "", err
  64. }
  65. slug := stringid.GenerateRandomID()
  66. if service.ContainerName == "" {
  67. 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)
  68. }
  69. one := 1
  70. service.Scale = &one
  71. service.Restart = ""
  72. if service.Deploy != nil {
  73. service.Deploy.RestartPolicy = nil
  74. }
  75. service.CustomLabels = service.CustomLabels.
  76. Add(api.SlugLabel, slug).
  77. Add(api.OneoffLabel, "True")
  78. if err := s.ensureImagesExists(ctx, project, opts.Build, opts.QuietPull); err != nil { // all dependencies already checked, but might miss service img
  79. return "", err
  80. }
  81. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  82. if err != nil {
  83. return "", err
  84. }
  85. if !opts.NoDeps {
  86. if err := s.waitDependencies(ctx, project, service.Name, service.DependsOn, observedState, 0); err != nil {
  87. return "", err
  88. }
  89. }
  90. createOpts := createOptions{
  91. AutoRemove: opts.AutoRemove,
  92. AttachStdin: opts.Interactive,
  93. UseNetworkAliases: opts.UseNetworkAliases,
  94. Labels: mergeLabels(service.Labels, service.CustomLabels),
  95. }
  96. err = newConvergence(project.ServiceNames(), observedState, nil, nil, s).resolveServiceReferences(&service)
  97. if err != nil {
  98. return "", err
  99. }
  100. created, err := s.createContainer(ctx, project, service, service.ContainerName, -1, createOpts)
  101. if err != nil {
  102. return "", err
  103. }
  104. return created.ID, nil
  105. }
  106. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  107. service.Tty = opts.Tty
  108. service.StdinOpen = opts.Interactive
  109. service.ContainerName = opts.Name
  110. if len(opts.Command) > 0 {
  111. service.Command = opts.Command
  112. }
  113. if opts.User != "" {
  114. service.User = opts.User
  115. }
  116. if len(opts.CapAdd) > 0 {
  117. service.CapAdd = append(service.CapAdd, opts.CapAdd...)
  118. service.CapDrop = slices.DeleteFunc(service.CapDrop, func(e string) bool { return slices.Contains(opts.CapAdd, e) })
  119. }
  120. if len(opts.CapDrop) > 0 {
  121. service.CapDrop = append(service.CapDrop, opts.CapDrop...)
  122. service.CapAdd = slices.DeleteFunc(service.CapAdd, func(e string) bool { return slices.Contains(opts.CapDrop, e) })
  123. }
  124. if opts.WorkingDir != "" {
  125. service.WorkingDir = opts.WorkingDir
  126. }
  127. if opts.Entrypoint != nil {
  128. service.Entrypoint = opts.Entrypoint
  129. if len(opts.Command) == 0 {
  130. service.Command = []string{}
  131. }
  132. }
  133. if len(opts.Environment) > 0 {
  134. cmdEnv := types.NewMappingWithEquals(opts.Environment)
  135. serviceOverrideEnv := cmdEnv.Resolve(func(s string) (string, bool) {
  136. v, ok := envResolver(project.Environment)(s)
  137. return v, ok
  138. }).RemoveEmpty()
  139. if service.Environment == nil {
  140. service.Environment = types.MappingWithEquals{}
  141. }
  142. service.Environment.OverrideBy(serviceOverrideEnv)
  143. }
  144. for k, v := range opts.Labels {
  145. service.Labels = service.Labels.Add(k, v)
  146. }
  147. }
  148. func (s *composeService) startDependencies(ctx context.Context, project *types.Project, options api.RunOptions) error {
  149. var dependencies []string
  150. for name, _ := range project.Services {
  151. if name != options.Service {
  152. dependencies = append(dependencies, name)
  153. }
  154. }
  155. project, err := project.WithSelectedServices(dependencies)
  156. if err != nil {
  157. return err
  158. }
  159. err = s.Create(ctx, project, api.CreateOptions{
  160. Build: options.Build,
  161. IgnoreOrphans: options.IgnoreOrphans,
  162. RemoveOrphans: options.RemoveOrphans,
  163. QuietPull: options.QuietPull,
  164. })
  165. if err != nil {
  166. return err
  167. }
  168. if len(dependencies) > 0 {
  169. return s.Start(ctx, project.Name, api.StartOptions{
  170. Project: project,
  171. })
  172. }
  173. return nil
  174. }