run.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. // Temporary implementation of use_api_socket until we get actual support inside docker engine
  52. project, err := s.useAPISocket(project)
  53. if err != nil {
  54. return "", err
  55. }
  56. err = progress.Run(ctx, func(ctx context.Context) error {
  57. return s.startDependencies(ctx, project, opts)
  58. }, s.stdinfo())
  59. if err != nil {
  60. return "", err
  61. }
  62. service, err := project.GetService(opts.Service)
  63. if err != nil {
  64. return "", err
  65. }
  66. applyRunOptions(project, &service, opts)
  67. if err := s.stdin().CheckTty(opts.Interactive, service.Tty); err != nil {
  68. return "", err
  69. }
  70. slug := stringid.GenerateRandomID()
  71. if service.ContainerName == "" {
  72. 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)
  73. }
  74. one := 1
  75. service.Scale = &one
  76. service.Restart = ""
  77. if service.Deploy != nil {
  78. service.Deploy.RestartPolicy = nil
  79. }
  80. service.CustomLabels = service.CustomLabels.
  81. Add(api.SlugLabel, slug).
  82. Add(api.OneoffLabel, "True")
  83. if err := s.ensureImagesExists(ctx, project, opts.Build, opts.QuietPull); err != nil { // all dependencies already checked, but might miss service img
  84. return "", err
  85. }
  86. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  87. if err != nil {
  88. return "", err
  89. }
  90. if !opts.NoDeps {
  91. if err := s.waitDependencies(ctx, project, service.Name, service.DependsOn, observedState, 0); err != nil {
  92. return "", err
  93. }
  94. }
  95. createOpts := createOptions{
  96. AutoRemove: opts.AutoRemove,
  97. AttachStdin: opts.Interactive,
  98. UseNetworkAliases: opts.UseNetworkAliases,
  99. Labels: mergeLabels(service.Labels, service.CustomLabels),
  100. }
  101. err = newConvergence(project.ServiceNames(), observedState, nil, nil, s).resolveServiceReferences(&service)
  102. if err != nil {
  103. return "", err
  104. }
  105. err = s.ensureModels(ctx, project, opts.QuietPull)
  106. if err != nil {
  107. return "", err
  108. }
  109. created, err := s.createContainer(ctx, project, service, service.ContainerName, -1, createOpts)
  110. if err != nil {
  111. return "", err
  112. }
  113. err = s.injectSecrets(ctx, project, service, created.ID)
  114. if err != nil {
  115. return created.ID, err
  116. }
  117. err = s.injectConfigs(ctx, project, service, created.ID)
  118. return created.ID, err
  119. }
  120. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  121. service.Tty = opts.Tty
  122. service.StdinOpen = opts.Interactive
  123. service.ContainerName = opts.Name
  124. if len(opts.Command) > 0 {
  125. service.Command = opts.Command
  126. }
  127. if opts.User != "" {
  128. service.User = opts.User
  129. }
  130. if len(opts.CapAdd) > 0 {
  131. service.CapAdd = append(service.CapAdd, opts.CapAdd...)
  132. service.CapDrop = slices.DeleteFunc(service.CapDrop, func(e string) bool { return slices.Contains(opts.CapAdd, e) })
  133. }
  134. if len(opts.CapDrop) > 0 {
  135. service.CapDrop = append(service.CapDrop, opts.CapDrop...)
  136. service.CapAdd = slices.DeleteFunc(service.CapAdd, func(e string) bool { return slices.Contains(opts.CapDrop, e) })
  137. }
  138. if opts.WorkingDir != "" {
  139. service.WorkingDir = opts.WorkingDir
  140. }
  141. if opts.Entrypoint != nil {
  142. service.Entrypoint = opts.Entrypoint
  143. if len(opts.Command) == 0 {
  144. service.Command = []string{}
  145. }
  146. }
  147. if len(opts.Environment) > 0 {
  148. cmdEnv := types.NewMappingWithEquals(opts.Environment)
  149. serviceOverrideEnv := cmdEnv.Resolve(func(s string) (string, bool) {
  150. v, ok := envResolver(project.Environment)(s)
  151. return v, ok
  152. }).RemoveEmpty()
  153. if service.Environment == nil {
  154. service.Environment = types.MappingWithEquals{}
  155. }
  156. service.Environment.OverrideBy(serviceOverrideEnv)
  157. }
  158. for k, v := range opts.Labels {
  159. service.Labels = service.Labels.Add(k, v)
  160. }
  161. }
  162. func (s *composeService) startDependencies(ctx context.Context, project *types.Project, options api.RunOptions) error {
  163. project = project.WithServicesDisabled(options.Service)
  164. err := s.Create(ctx, project, api.CreateOptions{
  165. Build: options.Build,
  166. IgnoreOrphans: options.IgnoreOrphans,
  167. RemoveOrphans: options.RemoveOrphans,
  168. QuietPull: options.QuietPull,
  169. })
  170. if err != nil {
  171. return err
  172. }
  173. if len(project.Services) > 0 {
  174. return s.Start(ctx, project.Name, api.StartOptions{
  175. Project: project,
  176. })
  177. }
  178. return nil
  179. }