run.go 6.0 KB

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