run.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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/docker/compose/v2/pkg/api"
  19. "github.com/compose-spec/compose-go/types"
  20. "github.com/docker/cli/cli/streams"
  21. moby "github.com/docker/docker/api/types"
  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(opts.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. r, err := s.getEscapeKeyProxy(opts.Stdin)
  44. if err != nil {
  45. return 0, err
  46. }
  47. stdin, stdout, err := s.getContainerStreams(ctx, containerID)
  48. if err != nil {
  49. return 0, err
  50. }
  51. in := streams.NewIn(opts.Stdin)
  52. if in.IsTerminal() {
  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(opts.Stdout, stdout) //nolint:errcheck
  64. outputDone <- err
  65. } else {
  66. _, err := stdcopy.StdCopy(opts.Stdout, opts.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. return s.terminateRun(ctx, containerID, opts, err)
  85. case err := <-inputDone:
  86. if _, ok := err.(term.EscapeError); ok {
  87. return 0, nil
  88. }
  89. if err != nil {
  90. return 0, err
  91. }
  92. // Wait for output to complete streaming
  93. case <-ctx.Done():
  94. return 0, ctx.Err()
  95. }
  96. }
  97. }
  98. func (s *composeService) terminateRun(ctx context.Context, containerID string, opts api.RunOptions, err error) (int, error) {
  99. if err != nil {
  100. return 0, err
  101. }
  102. inspect, err := s.apiClient.ContainerInspect(ctx, containerID)
  103. if err != nil {
  104. return 0, err
  105. }
  106. exitCode := 0
  107. if inspect.State != nil {
  108. exitCode = inspect.State.ExitCode
  109. }
  110. if opts.AutoRemove {
  111. err = s.apiClient.ContainerRemove(ctx, containerID, moby.ContainerRemoveOptions{})
  112. }
  113. return exitCode, err
  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 err := s.waitDependencies(ctx, project, service); err != nil {
  140. return "", err
  141. }
  142. created, err := s.createContainer(ctx, project, service, service.ContainerName, 1, opts.Detach && opts.AutoRemove, opts.UseNetworkAliases)
  143. if err != nil {
  144. return "", err
  145. }
  146. containerID := created.ID
  147. return containerID, nil
  148. }
  149. func (s *composeService) getEscapeKeyProxy(r io.ReadCloser) (io.ReadCloser, error) {
  150. var escapeKeys = []byte{16, 17}
  151. if s.configFile.DetachKeys != "" {
  152. customEscapeKeys, err := term.ToBytes(s.configFile.DetachKeys)
  153. if err != nil {
  154. return nil, err
  155. }
  156. escapeKeys = customEscapeKeys
  157. }
  158. return ioutils.NewReadCloserWrapper(term.NewEscapeProxy(r, escapeKeys), r.Close), nil
  159. }
  160. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  161. service.Tty = opts.Tty
  162. service.ContainerName = opts.Name
  163. if len(opts.Command) > 0 {
  164. service.Command = opts.Command
  165. }
  166. if len(opts.User) > 0 {
  167. service.User = opts.User
  168. }
  169. if len(opts.WorkingDir) > 0 {
  170. service.WorkingDir = opts.WorkingDir
  171. }
  172. if len(opts.Entrypoint) > 0 {
  173. service.Entrypoint = opts.Entrypoint
  174. }
  175. if len(opts.Environment) > 0 {
  176. env := types.NewMappingWithEquals(opts.Environment)
  177. projectEnv := env.Resolve(func(s string) (string, bool) {
  178. v, ok := project.Environment[s]
  179. return v, ok
  180. }).RemoveEmpty()
  181. service.Environment.OverrideBy(projectEnv)
  182. }
  183. for k, v := range opts.Labels {
  184. service.Labels.Add(k, v)
  185. }
  186. }