run.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. //addComposeCommonFlags(runCmd.Flags(), &opts.ComposeOpts)
  72. runCmd.Flags().SetInterspersed(false)
  73. return runCmd
  74. }
  75. func runRun(ctx context.Context, opts runOptions) error {
  76. // target service
  77. services := []string{opts.Name}
  78. projectOpts := composeOptions{}
  79. options, err := projectOpts.toProjectOptions()
  80. if err != nil {
  81. return err
  82. }
  83. project, err := cli.ProjectFromOptions(options)
  84. if err != nil {
  85. return err
  86. }
  87. err = filter(project, services)
  88. if err != nil {
  89. return err
  90. }
  91. c, err := client.NewWithDefaultLocalBackend(ctx)
  92. if err != nil {
  93. return err
  94. }
  95. containerID, err := progress.Run(ctx, func(ctx context.Context) (string, error) {
  96. return c.ComposeService().CreateOneOffContainer(ctx, project, compose.RunOptions{
  97. Name: opts.Name,
  98. Command: opts.Command,
  99. })
  100. })
  101. if err != nil {
  102. return err
  103. }
  104. // start container and attach to container streams
  105. err = c.ComposeService().Run(ctx, containerID, opts.Detach)
  106. if err != nil {
  107. return err
  108. }
  109. if opts.Detach {
  110. fmt.Printf("%s", containerID)
  111. return nil
  112. }
  113. if opts.Remove {
  114. return c.ContainerService().Delete(ctx, containerID, containers.DeleteRequest{
  115. Force: true,
  116. })
  117. }
  118. return nil
  119. }