run.go 4.6 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 run
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "os"
  19. "time"
  20. "github.com/containerd/console"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/compose-cli/api/client"
  23. "github.com/docker/compose-cli/api/containers"
  24. "github.com/docker/compose-cli/api/context/store"
  25. "github.com/docker/compose-cli/cli/options/run"
  26. "github.com/docker/compose-cli/pkg/progress"
  27. )
  28. // Command runs a container
  29. func Command(contextType string) *cobra.Command {
  30. var opts run.Opts
  31. cmd := &cobra.Command{
  32. Use: "run",
  33. Short: "Run a container",
  34. Args: cobra.MinimumNArgs(1),
  35. RunE: func(cmd *cobra.Command, args []string) error {
  36. if len(args) > 1 {
  37. opts.Command = args[1:]
  38. }
  39. return runRun(cmd.Context(), args[0], contextType, opts)
  40. },
  41. }
  42. cmd.Flags().SetInterspersed(false)
  43. cmd.Flags().StringArrayVarP(&opts.Publish, "publish", "p", []string{}, "Publish a container's port(s). [HOST_PORT:]CONTAINER_PORT")
  44. cmd.Flags().StringVar(&opts.Name, "name", "", "Assign a name to the container")
  45. cmd.Flags().StringArrayVarP(&opts.Labels, "label", "l", []string{}, "Set meta data on a container")
  46. cmd.Flags().StringArrayVarP(&opts.Volumes, "volume", "v", []string{}, "Volume. Ex: storageaccount/my_share[:/absolute/path/to/target][:ro]")
  47. cmd.Flags().BoolVarP(&opts.Detach, "detach", "d", false, "Run container in background and print container ID")
  48. cmd.Flags().Float64Var(&opts.Cpus, "cpus", 1., "Number of CPUs")
  49. cmd.Flags().VarP(&opts.Memory, "memory", "m", "Memory limit")
  50. cmd.Flags().StringArrayVarP(&opts.Environment, "env", "e", []string{}, "Set environment variables")
  51. cmd.Flags().StringArrayVar(&opts.EnvironmentFiles, "env-file", []string{}, "Path to environment files to be translated as environment variables")
  52. cmd.Flags().StringVarP(&opts.RestartPolicyCondition, "restart", "", containers.RestartPolicyRunNo, "Restart policy to apply when a container exits (no|always|on-failure)")
  53. cmd.Flags().BoolVar(&opts.Rm, "rm", false, "Automatically remove the container when it exits")
  54. cmd.Flags().StringVar(&opts.HealthCmd, "health-cmd", "", "Command to run to check health")
  55. cmd.Flags().DurationVar(&opts.HealthInterval, "health-interval", time.Duration(0), "Time between running the check (ms|s|m|h) (default 0s)")
  56. cmd.Flags().IntVar(&opts.HealthRetries, "health-retries", 0, "Consecutive failures needed to report unhealthy")
  57. cmd.Flags().DurationVar(&opts.HealthStartPeriod, "health-start-period", time.Duration(0), "Start period for the container to initialize before starting "+
  58. "health-retries countdown (ms|s|m|h) (default 0s)")
  59. cmd.Flags().DurationVar(&opts.HealthTimeout, "health-timeout", time.Duration(0), "Maximum time to allow one check to run (ms|s|m|h) (default 0s)")
  60. if contextType == store.LocalContextType {
  61. cmd.Flags().StringVar(&opts.Platform, "platform", os.Getenv("DOCKER_DEFAULT_PLATFORM"), "Set platform if server is multi-platform capable")
  62. }
  63. if contextType == store.AciContextType {
  64. cmd.Flags().StringVar(&opts.DomainName, "domainname", "", "Container NIS domain name")
  65. }
  66. switch contextType {
  67. case store.LocalContextType:
  68. default:
  69. _ = cmd.Flags().MarkHidden("rm")
  70. }
  71. return cmd
  72. }
  73. func runRun(ctx context.Context, image string, contextType string, opts run.Opts) error {
  74. switch contextType {
  75. case store.LocalContextType:
  76. default:
  77. if opts.Rm {
  78. return fmt.Errorf(`flag "--rm" is not yet implemented for %q context type`, contextType)
  79. }
  80. }
  81. c, err := client.New(ctx)
  82. if err != nil {
  83. return err
  84. }
  85. containerConfig, err := opts.ToContainerConfig(image)
  86. if err != nil {
  87. return err
  88. }
  89. result, err := progress.RunWithStatus(ctx, func(ctx context.Context) (string, error) {
  90. return containerConfig.ID, c.ContainerService().Run(ctx, containerConfig)
  91. })
  92. if err != nil {
  93. return err
  94. }
  95. if !opts.Detach {
  96. var con io.Writer = os.Stdout
  97. req := containers.LogsRequest{
  98. Follow: true,
  99. }
  100. if c, err := console.ConsoleFromFile(os.Stdout); err == nil {
  101. size, err := c.Size()
  102. if err != nil {
  103. return err
  104. }
  105. req.Width = int(size.Width)
  106. con = c
  107. }
  108. req.Writer = con
  109. return c.ContainerService().Logs(ctx, opts.Name, req)
  110. }
  111. fmt.Println(result)
  112. return nil
  113. }