container.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 convert
  14. import (
  15. "fmt"
  16. "strings"
  17. "github.com/compose-spec/compose-go/types"
  18. "github.com/docker/compose-cli/api/containers"
  19. )
  20. // ContainerToComposeProject convert container config to compose project
  21. func ContainerToComposeProject(r containers.ContainerConfig) (types.Project, error) {
  22. var ports []types.ServicePortConfig
  23. for _, p := range r.Ports {
  24. ports = append(ports, types.ServicePortConfig{
  25. Target: p.ContainerPort,
  26. Published: p.HostPort,
  27. Protocol: p.Protocol,
  28. })
  29. }
  30. projectVolumes, serviceConfigVolumes, err := GetRunVolumes(r.Volumes)
  31. if err != nil {
  32. return types.Project{}, err
  33. }
  34. retries := uint64(r.Healthcheck.Retries)
  35. project := types.Project{
  36. Name: r.ID,
  37. Services: []types.ServiceConfig{
  38. {
  39. Name: r.ID,
  40. Image: r.Image,
  41. Command: r.Command,
  42. Ports: ports,
  43. Labels: r.Labels,
  44. Volumes: serviceConfigVolumes,
  45. DomainName: r.DomainName,
  46. Environment: toComposeEnvs(r.Environment),
  47. HealthCheck: &types.HealthCheckConfig{
  48. Test: r.Healthcheck.Test,
  49. Timeout: &r.Healthcheck.Timeout,
  50. Interval: &r.Healthcheck.Interval,
  51. Retries: &retries,
  52. StartPeriod: &r.Healthcheck.StartPeriod,
  53. Disable: r.Healthcheck.Disable,
  54. },
  55. Deploy: &types.DeployConfig{
  56. Resources: types.Resources{
  57. Reservations: &types.Resource{
  58. NanoCPUs: fmt.Sprintf("%f", r.CPULimit),
  59. MemoryBytes: types.UnitBytes(r.MemLimit.Value()),
  60. },
  61. },
  62. RestartPolicy: &types.RestartPolicy{
  63. Condition: r.RestartPolicyCondition,
  64. },
  65. },
  66. },
  67. },
  68. Volumes: projectVolumes,
  69. }
  70. return project, nil
  71. }
  72. func toComposeEnvs(opts []string) types.MappingWithEquals {
  73. result := types.MappingWithEquals{}
  74. for _, env := range opts {
  75. tokens := strings.SplitN(env, "=", 2)
  76. if len(tokens) > 1 {
  77. result[tokens[0]] = &tokens[1]
  78. } else {
  79. result[env] = nil
  80. }
  81. }
  82. return result
  83. }