run.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. if err != nil {
  85. return 0, err
  86. }
  87. inspect, err := s.apiClient.ContainerInspect(ctx, containerID)
  88. if err != nil {
  89. return 0, err
  90. }
  91. exitCode := 0
  92. if inspect.State != nil {
  93. exitCode = inspect.State.ExitCode
  94. }
  95. return exitCode, nil
  96. case err := <-inputDone:
  97. if _, ok := err.(term.EscapeError); ok {
  98. return 0, nil
  99. }
  100. if err != nil {
  101. return 0, err
  102. }
  103. // Wait for output to complete streaming
  104. case <-ctx.Done():
  105. return 0, ctx.Err()
  106. }
  107. }
  108. }
  109. func (s *composeService) prepareRun(ctx context.Context, project *types.Project, opts api.RunOptions) (string, error) {
  110. if err := prepareVolumes(project); err != nil { // all dependencies already checked, but might miss service img
  111. return "", err
  112. }
  113. service, err := project.GetService(opts.Service)
  114. if err != nil {
  115. return "", err
  116. }
  117. applyRunOptions(project, &service, opts)
  118. slug := stringid.GenerateRandomID()
  119. if service.ContainerName == "" {
  120. service.ContainerName = fmt.Sprintf("%s_%s_run_%s", project.Name, service.Name, stringid.TruncateID(slug))
  121. }
  122. service.Scale = 1
  123. service.StdinOpen = true
  124. service.Restart = ""
  125. if service.Deploy != nil {
  126. service.Deploy.RestartPolicy = nil
  127. }
  128. service.Labels = service.Labels.Add(api.SlugLabel, slug)
  129. service.Labels = service.Labels.Add(api.OneoffLabel, "True")
  130. if err := s.ensureImagesExists(ctx, project, false); err != nil { // all dependencies already checked, but might miss service img
  131. return "", err
  132. }
  133. if err := s.waitDependencies(ctx, project, service); err != nil {
  134. return "", err
  135. }
  136. created, err := s.createContainer(ctx, project, service, service.ContainerName, 1, opts.AutoRemove, opts.UseNetworkAliases)
  137. if err != nil {
  138. return "", err
  139. }
  140. containerID := created.ID
  141. return containerID, nil
  142. }
  143. func (s *composeService) getEscapeKeyProxy(r io.ReadCloser) (io.ReadCloser, error) {
  144. var escapeKeys = []byte{16, 17}
  145. if s.configFile.DetachKeys != "" {
  146. customEscapeKeys, err := term.ToBytes(s.configFile.DetachKeys)
  147. if err != nil {
  148. return nil, err
  149. }
  150. escapeKeys = customEscapeKeys
  151. }
  152. return ioutils.NewReadCloserWrapper(term.NewEscapeProxy(r, escapeKeys), r.Close), nil
  153. }
  154. func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) {
  155. service.Tty = opts.Tty
  156. service.ContainerName = opts.Name
  157. if len(opts.Command) > 0 {
  158. service.Command = opts.Command
  159. }
  160. if len(opts.User) > 0 {
  161. service.User = opts.User
  162. }
  163. if len(opts.WorkingDir) > 0 {
  164. service.WorkingDir = opts.WorkingDir
  165. }
  166. if len(opts.Entrypoint) > 0 {
  167. service.Entrypoint = opts.Entrypoint
  168. }
  169. if len(opts.Environment) > 0 {
  170. env := types.NewMappingWithEquals(opts.Environment)
  171. projectEnv := env.Resolve(func(s string) (string, bool) {
  172. v, ok := project.Environment[s]
  173. return v, ok
  174. }).RemoveEmpty()
  175. service.Environment.OverrideBy(projectEnv)
  176. }
  177. for k, v := range opts.Labels {
  178. service.Labels.Add(k, v)
  179. }
  180. }