run.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. created, err := s.createContainer(ctx, project, service, service.ContainerName, -1, createOpts)
  106. if err != nil {
  107. return "", err
  108. }
  109. err = s.injectSecrets(ctx, project, service, created.ID)
  110. if err != nil {
  111. return created.ID, err
  112. }
  113. err = s.injectConfigs(ctx, project, service, created.ID)
  114. return created.ID, err
  115. }
  116. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  117. service.Tty = opts.Tty
  118. service.StdinOpen = opts.Interactive
  119. service.ContainerName = opts.Name
  120. if len(opts.Command) > 0 {
  121. service.Command = opts.Command
  122. }
  123. if opts.User != "" {
  124. service.User = opts.User
  125. }
  126. if len(opts.CapAdd) > 0 {
  127. service.CapAdd = append(service.CapAdd, opts.CapAdd...)
  128. service.CapDrop = slices.DeleteFunc(service.CapDrop, func(e string) bool { return slices.Contains(opts.CapAdd, e) })
  129. }
  130. if len(opts.CapDrop) > 0 {
  131. service.CapDrop = append(service.CapDrop, opts.CapDrop...)
  132. service.CapAdd = slices.DeleteFunc(service.CapAdd, func(e string) bool { return slices.Contains(opts.CapDrop, e) })
  133. }
  134. if opts.WorkingDir != "" {
  135. service.WorkingDir = opts.WorkingDir
  136. }
  137. if opts.Entrypoint != nil {
  138. service.Entrypoint = opts.Entrypoint
  139. if len(opts.Command) == 0 {
  140. service.Command = []string{}
  141. }
  142. }
  143. if len(opts.Environment) > 0 {
  144. cmdEnv := types.NewMappingWithEquals(opts.Environment)
  145. serviceOverrideEnv := cmdEnv.Resolve(func(s string) (string, bool) {
  146. v, ok := envResolver(project.Environment)(s)
  147. return v, ok
  148. }).RemoveEmpty()
  149. if service.Environment == nil {
  150. service.Environment = types.MappingWithEquals{}
  151. }
  152. service.Environment.OverrideBy(serviceOverrideEnv)
  153. }
  154. for k, v := range opts.Labels {
  155. service.Labels = service.Labels.Add(k, v)
  156. }
  157. }
  158. func (s *composeService) startDependencies(ctx context.Context, project *types.Project, options api.RunOptions) error {
  159. project = project.WithServicesDisabled(options.Service)
  160. err := s.Create(ctx, project, api.CreateOptions{
  161. Build: options.Build,
  162. IgnoreOrphans: options.IgnoreOrphans,
  163. RemoveOrphans: options.RemoveOrphans,
  164. QuietPull: options.QuietPull,
  165. })
  166. if err != nil {
  167. return err
  168. }
  169. if len(project.Services) > 0 {
  170. return s.Start(ctx, project.Name, api.StartOptions{
  171. Project: project,
  172. })
  173. }
  174. return nil
  175. }