run.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. "github.com/compose-spec/compose-go/cli"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose-cli/api/client"
  20. "github.com/docker/compose-cli/api/compose"
  21. "github.com/docker/compose-cli/api/containers"
  22. apicontext "github.com/docker/compose-cli/context"
  23. "github.com/docker/compose-cli/context/store"
  24. "github.com/docker/compose-cli/progress"
  25. )
  26. type runOptions struct {
  27. Name string
  28. Command []string
  29. WorkingDir string
  30. Environment []string
  31. Detach bool
  32. Publish []string
  33. Labels []string
  34. Volumes []string
  35. NoDeps bool
  36. Remove bool
  37. }
  38. func runCommand() *cobra.Command {
  39. opts := runOptions{}
  40. runCmd := &cobra.Command{
  41. Use: "run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] SERVICE [COMMAND] [ARGS...]",
  42. Short: "Run a one-off command on a service.",
  43. Args: cobra.MinimumNArgs(1),
  44. RunE: func(cmd *cobra.Command, args []string) error {
  45. s := store.ContextStore(cmd.Context())
  46. currentCtx, err := s.Get(apicontext.CurrentContext(cmd.Context()))
  47. if err != nil {
  48. return err
  49. }
  50. switch currentCtx.Type() {
  51. case store.DefaultContextType:
  52. default:
  53. return fmt.Errorf(`Command "run" is not yet implemented for %q context type`, currentCtx.Type())
  54. }
  55. if len(args) > 1 {
  56. opts.Command = args[1:]
  57. }
  58. opts.Name = args[0]
  59. return runRun(cmd.Context(), opts)
  60. },
  61. }
  62. runCmd.Flags().StringVar(&opts.WorkingDir, "workdir", "", "Work dir")
  63. runCmd.Flags().StringArrayVarP(&opts.Publish, "publish", "p", []string{}, "Publish a container's port(s). [HOST_PORT:]CONTAINER_PORT")
  64. runCmd.Flags().StringVar(&opts.Name, "name", "", "Assign a name to the container")
  65. runCmd.Flags().BoolVar(&opts.NoDeps, "no-deps", false, "Don't start linked services.")
  66. runCmd.Flags().StringArrayVarP(&opts.Labels, "label", "l", []string{}, "Set meta data on a container")
  67. runCmd.Flags().StringArrayVarP(&opts.Volumes, "volume", "v", []string{}, "Volume. Ex: storageaccount/my_share[:/absolute/path/to/target][:ro]")
  68. runCmd.Flags().BoolVarP(&opts.Detach, "detach", "d", false, "Run container in background and print container ID")
  69. runCmd.Flags().StringArrayVarP(&opts.Environment, "env", "e", []string{}, "Set environment variables")
  70. runCmd.Flags().BoolVar(&opts.Remove, "rm", false, "Automatically remove the container when it exits")
  71. runCmd.Flags().SetInterspersed(false)
  72. return runCmd
  73. }
  74. func runRun(ctx context.Context, opts runOptions) error {
  75. // target service
  76. services := []string{opts.Name}
  77. projectOpts := composeOptions{}
  78. options, err := projectOpts.toProjectOptions()
  79. if err != nil {
  80. return err
  81. }
  82. project, err := cli.ProjectFromOptions(options)
  83. if err != nil {
  84. return err
  85. }
  86. err = filter(project, services)
  87. if err != nil {
  88. return err
  89. }
  90. c, err := client.NewWithDefaultLocalBackend(ctx)
  91. if err != nil {
  92. return err
  93. }
  94. containerID, err := progress.Run(ctx, func(ctx context.Context) (string, error) {
  95. return c.ComposeService().CreateOneOffContainer(ctx, project, compose.RunOptions{
  96. Name: opts.Name,
  97. Command: opts.Command,
  98. })
  99. })
  100. if err != nil {
  101. return err
  102. }
  103. // start container and attach to container streams
  104. err = c.ComposeService().Run(ctx, containerID, opts.Detach)
  105. if err != nil {
  106. return err
  107. }
  108. if opts.Detach {
  109. fmt.Printf("%s", containerID)
  110. return nil
  111. }
  112. if opts.Remove {
  113. return c.ContainerService().Delete(ctx, containerID, containers.DeleteRequest{
  114. Force: true,
  115. })
  116. }
  117. return nil
  118. }