run.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. "fmt"
  17. "io"
  18. "github.com/compose-spec/compose-go/types"
  19. "github.com/docker/cli/cli/streams"
  20. "github.com/docker/compose/v2/pkg/api"
  21. moby "github.com/docker/docker/api/types"
  22. "github.com/docker/docker/api/types/container"
  23. "github.com/docker/docker/pkg/ioutils"
  24. "github.com/docker/docker/pkg/stdcopy"
  25. "github.com/docker/docker/pkg/stringid"
  26. "github.com/moby/term"
  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. if opts.Detach {
  34. err := s.apiClient.ContainerStart(ctx, containerID, moby.ContainerStartOptions{})
  35. if err != nil {
  36. return 0, err
  37. }
  38. fmt.Fprintln(opts.Stdout, containerID)
  39. return 0, nil
  40. }
  41. return s.runInteractive(ctx, containerID, opts)
  42. }
  43. func (s *composeService) runInteractive(ctx context.Context, containerID string, opts api.RunOptions) (int, error) {
  44. r, err := s.getEscapeKeyProxy(opts.Stdin, opts.Tty)
  45. if err != nil {
  46. return 0, err
  47. }
  48. stdin, stdout, err := s.getContainerStreams(ctx, containerID)
  49. if err != nil {
  50. return 0, err
  51. }
  52. in := streams.NewIn(opts.Stdin)
  53. if in.IsTerminal() && opts.Tty {
  54. state, err := term.SetRawTerminal(in.FD())
  55. if err != nil {
  56. return 0, err
  57. }
  58. defer term.RestoreTerminal(in.FD(), state) //nolint:errcheck
  59. }
  60. outputDone := make(chan error)
  61. inputDone := make(chan error)
  62. go func() {
  63. if opts.Tty {
  64. _, err := io.Copy(opts.Stdout, stdout) //nolint:errcheck
  65. outputDone <- err
  66. } else {
  67. _, err := stdcopy.StdCopy(opts.Stdout, opts.Stderr, stdout) //nolint:errcheck
  68. outputDone <- err
  69. }
  70. stdout.Close() //nolint:errcheck
  71. }()
  72. go func() {
  73. _, err := io.Copy(stdin, r)
  74. inputDone <- err
  75. stdin.Close() //nolint:errcheck
  76. }()
  77. err = s.apiClient.ContainerStart(ctx, containerID, moby.ContainerStartOptions{})
  78. if err != nil {
  79. return 0, err
  80. }
  81. s.monitorTTySize(ctx, containerID, s.apiClient.ContainerResize)
  82. for {
  83. select {
  84. case err := <-outputDone:
  85. if err != nil {
  86. return 0, err
  87. }
  88. return s.terminateRun(ctx, containerID, opts)
  89. case err := <-inputDone:
  90. if _, ok := err.(term.EscapeError); ok {
  91. return 0, nil
  92. }
  93. if err != nil {
  94. return 0, err
  95. }
  96. // Wait for output to complete streaming
  97. case <-ctx.Done():
  98. return 0, ctx.Err()
  99. }
  100. }
  101. }
  102. func (s *composeService) terminateRun(ctx context.Context, containerID string, opts api.RunOptions) (exitCode int, err error) {
  103. exitCh, errCh := s.apiClient.ContainerWait(ctx, containerID, container.WaitConditionNotRunning)
  104. select {
  105. case exit := <-exitCh:
  106. exitCode = int(exit.StatusCode)
  107. case err = <-errCh:
  108. return
  109. }
  110. if opts.AutoRemove {
  111. err = s.apiClient.ContainerRemove(ctx, containerID, moby.ContainerRemoveOptions{})
  112. }
  113. return
  114. }
  115. func (s *composeService) prepareRun(ctx context.Context, project *types.Project, opts api.RunOptions) (string, error) {
  116. if err := prepareVolumes(project); err != nil { // all dependencies already checked, but might miss service img
  117. return "", err
  118. }
  119. service, err := project.GetService(opts.Service)
  120. if err != nil {
  121. return "", err
  122. }
  123. applyRunOptions(project, &service, opts)
  124. slug := stringid.GenerateRandomID()
  125. if service.ContainerName == "" {
  126. service.ContainerName = fmt.Sprintf("%s_%s_run_%s", project.Name, service.Name, stringid.TruncateID(slug))
  127. }
  128. service.Scale = 1
  129. service.StdinOpen = true
  130. service.Restart = ""
  131. if service.Deploy != nil {
  132. service.Deploy.RestartPolicy = nil
  133. }
  134. service.CustomLabels = service.CustomLabels.
  135. Add(api.SlugLabel, slug).
  136. Add(api.OneoffLabel, "True")
  137. if err := s.ensureImagesExists(ctx, project, opts.QuietPull); err != nil { // all dependencies already checked, but might miss service img
  138. return "", err
  139. }
  140. if !opts.NoDeps {
  141. if err := s.waitDependencies(ctx, project, service.DependsOn); err != nil {
  142. return "", err
  143. }
  144. }
  145. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  146. if err != nil {
  147. return "", err
  148. }
  149. updateServices(&service, observedState)
  150. created, err := s.createContainer(ctx, project, service, service.ContainerName, 1, opts.Detach && opts.AutoRemove, opts.UseNetworkAliases, true)
  151. if err != nil {
  152. return "", err
  153. }
  154. containerID := created.ID
  155. return containerID, nil
  156. }
  157. func (s *composeService) getEscapeKeyProxy(r io.ReadCloser, isTty bool) (io.ReadCloser, error) {
  158. if !isTty {
  159. return r, nil
  160. }
  161. var escapeKeys = []byte{16, 17}
  162. if s.configFile.DetachKeys != "" {
  163. customEscapeKeys, err := term.ToBytes(s.configFile.DetachKeys)
  164. if err != nil {
  165. return nil, err
  166. }
  167. escapeKeys = customEscapeKeys
  168. }
  169. return ioutils.NewReadCloserWrapper(term.NewEscapeProxy(r, escapeKeys), r.Close), nil
  170. }
  171. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  172. service.Tty = opts.Tty
  173. service.StdinOpen = true
  174. service.ContainerName = opts.Name
  175. if len(opts.Command) > 0 {
  176. service.Command = opts.Command
  177. }
  178. if len(opts.User) > 0 {
  179. service.User = opts.User
  180. }
  181. if len(opts.WorkingDir) > 0 {
  182. service.WorkingDir = opts.WorkingDir
  183. }
  184. if opts.Entrypoint != nil {
  185. service.Entrypoint = opts.Entrypoint
  186. }
  187. if len(opts.Environment) > 0 {
  188. env := types.NewMappingWithEquals(opts.Environment)
  189. projectEnv := env.Resolve(func(s string) (string, bool) {
  190. v, ok := project.Environment[s]
  191. return v, ok
  192. }).RemoveEmpty()
  193. service.Environment.OverrideBy(projectEnv)
  194. }
  195. for k, v := range opts.Labels {
  196. service.Labels = service.Labels.Add(k, v)
  197. }
  198. }