opts.go 5.2 KB

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