run.go 6.4 KB

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