run.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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)
  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() {
  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.Labels = service.Labels.Add(api.SlugLabel, slug)
  135. service.Labels = service.Labels.Add(api.OneoffLabel, "True")
  136. if err := s.ensureImagesExists(ctx, project, false); 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); err != nil {
  141. return "", err
  142. }
  143. }
  144. created, err := s.createContainer(ctx, project, service, service.ContainerName, 1, opts.Detach && opts.AutoRemove, opts.UseNetworkAliases)
  145. if err != nil {
  146. return "", err
  147. }
  148. containerID := created.ID
  149. return containerID, nil
  150. }
  151. func (s *composeService) getEscapeKeyProxy(r io.ReadCloser) (io.ReadCloser, error) {
  152. var escapeKeys = []byte{16, 17}
  153. if s.configFile.DetachKeys != "" {
  154. customEscapeKeys, err := term.ToBytes(s.configFile.DetachKeys)
  155. if err != nil {
  156. return nil, err
  157. }
  158. escapeKeys = customEscapeKeys
  159. }
  160. return ioutils.NewReadCloserWrapper(term.NewEscapeProxy(r, escapeKeys), r.Close), nil
  161. }
  162. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  163. service.Tty = opts.Tty
  164. service.ContainerName = opts.Name
  165. if len(opts.Command) > 0 {
  166. service.Command = opts.Command
  167. }
  168. if len(opts.User) > 0 {
  169. service.User = opts.User
  170. }
  171. if len(opts.WorkingDir) > 0 {
  172. service.WorkingDir = opts.WorkingDir
  173. }
  174. if opts.Entrypoint != nil {
  175. service.Entrypoint = opts.Entrypoint
  176. }
  177. if len(opts.Environment) > 0 {
  178. env := types.NewMappingWithEquals(opts.Environment)
  179. projectEnv := env.Resolve(func(s string) (string, bool) {
  180. v, ok := project.Environment[s]
  181. return v, ok
  182. }).RemoveEmpty()
  183. service.Environment.OverrideBy(projectEnv)
  184. }
  185. for k, v := range opts.Labels {
  186. service.Labels.Add(k, v)
  187. }
  188. }