run.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. // Only ensure image exists for the target service, dependencies were already handled by startDependencies
  84. var buildOpts *api.BuildOptions
  85. if opts.Build != nil {
  86. // Create a copy of build options and restrict to only the target service
  87. buildOptsCopy := *opts.Build
  88. buildOptsCopy.Services = []string{opts.Service}
  89. buildOpts = &buildOptsCopy
  90. }
  91. if err := s.ensureImagesExists(ctx, project, buildOpts, opts.QuietPull); err != nil { // all dependencies already checked, but might miss service img
  92. return "", err
  93. }
  94. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  95. if err != nil {
  96. return "", err
  97. }
  98. if !opts.NoDeps {
  99. if err := s.waitDependencies(ctx, project, service.Name, service.DependsOn, observedState, 0); err != nil {
  100. return "", err
  101. }
  102. }
  103. createOpts := createOptions{
  104. AutoRemove: opts.AutoRemove,
  105. AttachStdin: opts.Interactive,
  106. UseNetworkAliases: opts.UseNetworkAliases,
  107. Labels: mergeLabels(service.Labels, service.CustomLabels),
  108. }
  109. err = newConvergence(project.ServiceNames(), observedState, nil, nil, s).resolveServiceReferences(&service)
  110. if err != nil {
  111. return "", err
  112. }
  113. err = s.ensureModels(ctx, project, opts.QuietPull)
  114. if err != nil {
  115. return "", err
  116. }
  117. created, err := s.createContainer(ctx, project, service, service.ContainerName, -1, createOpts)
  118. if err != nil {
  119. return "", err
  120. }
  121. ctr, err := s.apiClient().ContainerInspect(ctx, created.ID)
  122. if err != nil {
  123. return "", err
  124. }
  125. err = s.injectSecrets(ctx, project, service, ctr.ID)
  126. if err != nil {
  127. return created.ID, err
  128. }
  129. err = s.injectConfigs(ctx, project, service, ctr.ID)
  130. return created.ID, err
  131. }
  132. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  133. service.Tty = opts.Tty
  134. service.StdinOpen = opts.Interactive
  135. service.ContainerName = opts.Name
  136. if len(opts.Command) > 0 {
  137. service.Command = opts.Command
  138. }
  139. if opts.User != "" {
  140. service.User = opts.User
  141. }
  142. if len(opts.CapAdd) > 0 {
  143. service.CapAdd = append(service.CapAdd, opts.CapAdd...)
  144. service.CapDrop = slices.DeleteFunc(service.CapDrop, func(e string) bool { return slices.Contains(opts.CapAdd, e) })
  145. }
  146. if len(opts.CapDrop) > 0 {
  147. service.CapDrop = append(service.CapDrop, opts.CapDrop...)
  148. service.CapAdd = slices.DeleteFunc(service.CapAdd, func(e string) bool { return slices.Contains(opts.CapDrop, e) })
  149. }
  150. if opts.WorkingDir != "" {
  151. service.WorkingDir = opts.WorkingDir
  152. }
  153. if opts.Entrypoint != nil {
  154. service.Entrypoint = opts.Entrypoint
  155. if len(opts.Command) == 0 {
  156. service.Command = []string{}
  157. }
  158. }
  159. if len(opts.Environment) > 0 {
  160. cmdEnv := types.NewMappingWithEquals(opts.Environment)
  161. serviceOverrideEnv := cmdEnv.Resolve(func(s string) (string, bool) {
  162. v, ok := envResolver(project.Environment)(s)
  163. return v, ok
  164. }).RemoveEmpty()
  165. if service.Environment == nil {
  166. service.Environment = types.MappingWithEquals{}
  167. }
  168. service.Environment.OverrideBy(serviceOverrideEnv)
  169. }
  170. for k, v := range opts.Labels {
  171. service.Labels = service.Labels.Add(k, v)
  172. }
  173. }
  174. func (s *composeService) startDependencies(ctx context.Context, project *types.Project, options api.RunOptions) error {
  175. project = project.WithServicesDisabled(options.Service)
  176. err := s.Create(ctx, project, api.CreateOptions{
  177. Build: options.Build,
  178. IgnoreOrphans: options.IgnoreOrphans,
  179. RemoveOrphans: options.RemoveOrphans,
  180. QuietPull: options.QuietPull,
  181. })
  182. if err != nil {
  183. return err
  184. }
  185. if len(project.Services) > 0 {
  186. return s.Start(ctx, project.Name, api.StartOptions{
  187. Project: project,
  188. })
  189. }
  190. return nil
  191. }