opts.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. "fmt"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/docker/compose-cli/utils"
  20. "github.com/compose-spec/compose-go/types"
  21. "github.com/containerd/containerd/platforms"
  22. "github.com/docker/cli/opts"
  23. "github.com/docker/docker/pkg/namesgenerator"
  24. "github.com/docker/go-connections/nat"
  25. specs "github.com/opencontainers/image-spec/specs-go/v1"
  26. "github.com/docker/compose-cli/api/containers"
  27. )
  28. // Opts contain run command options
  29. type Opts struct {
  30. Name string
  31. Command []string
  32. Publish []string
  33. Labels []string
  34. Volumes []string
  35. Cpus float64
  36. Memory utils.MemBytes
  37. Detach bool
  38. Environment []string
  39. EnvironmentFiles []string
  40. RestartPolicyCondition string
  41. DomainName string
  42. Rm bool
  43. HealthCmd string
  44. HealthInterval time.Duration
  45. HealthRetries int
  46. HealthStartPeriod time.Duration
  47. HealthTimeout time.Duration
  48. Platform string
  49. }
  50. // RestartPolicyList all available restart policy values
  51. var RestartPolicyList = []string{containers.RestartPolicyRunNo, containers.RestartPolicyRunAlways, containers.RestartPolicyOnFailure}
  52. // ToContainerConfig convert run options to a container configuration
  53. func (r *Opts) ToContainerConfig(image string) (containers.ContainerConfig, error) {
  54. if r.Name == "" {
  55. r.Name = getRandomName()
  56. }
  57. publish, err := r.toPorts()
  58. if err != nil {
  59. return containers.ContainerConfig{}, err
  60. }
  61. labels, err := toLabels(r.Labels)
  62. if err != nil {
  63. return containers.ContainerConfig{}, err
  64. }
  65. restartPolicy, err := toRestartPolicy(r.RestartPolicyCondition)
  66. if err != nil {
  67. return containers.ContainerConfig{}, err
  68. }
  69. envVars := r.Environment
  70. for _, f := range r.EnvironmentFiles {
  71. vars, err := opts.ParseEnvFile(f)
  72. if err != nil {
  73. return containers.ContainerConfig{}, err
  74. }
  75. envVars = append(envVars, vars...)
  76. }
  77. var platform *specs.Platform
  78. if r.Platform != "" {
  79. p, err := platforms.Parse(r.Platform)
  80. if err != nil {
  81. return containers.ContainerConfig{}, err
  82. }
  83. platform = &p
  84. }
  85. return containers.ContainerConfig{
  86. ID: r.Name,
  87. Image: image,
  88. Command: r.Command,
  89. Ports: publish,
  90. Labels: labels,
  91. Volumes: r.Volumes,
  92. MemLimit: r.Memory,
  93. CPULimit: r.Cpus,
  94. Environment: envVars,
  95. RestartPolicyCondition: restartPolicy,
  96. DomainName: r.DomainName,
  97. AutoRemove: r.Rm,
  98. Healthcheck: r.toHealthcheck(),
  99. Platform: platform,
  100. }, nil
  101. }
  102. func (r *Opts) toHealthcheck() containers.Healthcheck {
  103. var healthCmd []string
  104. if len(r.HealthCmd) > 0 {
  105. healthCmd = strings.Split(r.HealthCmd, " ")
  106. }
  107. return containers.Healthcheck{
  108. Disable: len(healthCmd) == 0,
  109. Test: healthCmd,
  110. Interval: types.Duration(r.HealthInterval),
  111. StartPeriod: types.Duration(r.HealthStartPeriod),
  112. Timeout: types.Duration(r.HealthTimeout),
  113. Retries: r.HealthRetries,
  114. }
  115. }
  116. var restartPolicyMap = map[string]string{
  117. "": containers.RestartPolicyNone,
  118. containers.RestartPolicyNone: containers.RestartPolicyNone,
  119. containers.RestartPolicyAny: containers.RestartPolicyAny,
  120. containers.RestartPolicyOnFailure: containers.RestartPolicyOnFailure,
  121. containers.RestartPolicyRunNo: containers.RestartPolicyNone,
  122. containers.RestartPolicyRunAlways: containers.RestartPolicyAny,
  123. }
  124. func toRestartPolicy(value string) (string, error) {
  125. value, ok := restartPolicyMap[value]
  126. if !ok {
  127. return "", fmt.Errorf("invalid restart value, must be one of %s", strings.Join(RestartPolicyList, ", "))
  128. }
  129. return value, nil
  130. }
  131. func (r *Opts) toPorts() ([]containers.Port, error) {
  132. _, bindings, err := nat.ParsePortSpecs(r.Publish)
  133. if err != nil {
  134. return nil, err
  135. }
  136. var result []containers.Port
  137. for port, bind := range bindings {
  138. for _, portbind := range bind {
  139. var hostPort uint32
  140. if portbind.HostPort != "" {
  141. hp, err := strconv.Atoi(portbind.HostPort)
  142. if err != nil {
  143. return nil, err
  144. }
  145. hostPort = uint32(hp)
  146. } else {
  147. hostPort = uint32(port.Int())
  148. }
  149. result = append(result, containers.Port{
  150. HostPort: hostPort,
  151. ContainerPort: uint32(port.Int()),
  152. Protocol: port.Proto(),
  153. HostIP: portbind.HostIP,
  154. })
  155. }
  156. }
  157. return result, nil
  158. }
  159. func toLabels(labels []string) (map[string]string, error) {
  160. result := map[string]string{}
  161. for _, label := range labels {
  162. parts := strings.Split(label, "=")
  163. if len(parts) != 2 {
  164. return nil, fmt.Errorf("wrong label format %q", label)
  165. }
  166. result[parts[0]] = parts[1]
  167. }
  168. return result, nil
  169. }
  170. func getRandomName() string {
  171. // Azure supports hyphen but not underscore in names
  172. return strings.Replace(namesgenerator.GetRandomName(0), "_", "-", -1)
  173. }