container.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package convert
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/compose-spec/compose-go/types"
  6. "github.com/docker/api/containers"
  7. )
  8. // ContainerToComposeProject convert container config to compose project
  9. func ContainerToComposeProject(r containers.ContainerConfig) (types.Project, error) {
  10. var ports []types.ServicePortConfig
  11. for _, p := range r.Ports {
  12. ports = append(ports, types.ServicePortConfig{
  13. Target: p.ContainerPort,
  14. Published: p.HostPort,
  15. })
  16. }
  17. projectVolumes, serviceConfigVolumes, err := GetRunVolumes(r.Volumes)
  18. if err != nil {
  19. return types.Project{}, err
  20. }
  21. project := types.Project{
  22. Name: r.ID,
  23. Services: []types.ServiceConfig{
  24. {
  25. Name: r.ID,
  26. Image: r.Image,
  27. Ports: ports,
  28. Labels: r.Labels,
  29. Volumes: serviceConfigVolumes,
  30. Environment: toComposeEnvs(r.Environment),
  31. Deploy: &types.DeployConfig{
  32. Resources: types.Resources{
  33. Limits: &types.Resource{
  34. NanoCPUs: fmt.Sprintf("%f", r.CPULimit),
  35. MemoryBytes: types.UnitBytes(r.MemLimit.Value()),
  36. },
  37. },
  38. RestartPolicy: &types.RestartPolicy{
  39. Condition: r.RestartPolicyCondition,
  40. },
  41. },
  42. },
  43. },
  44. Volumes: projectVolumes,
  45. }
  46. return project, nil
  47. }
  48. func toComposeEnvs(opts []string) types.MappingWithEquals {
  49. result := map[string]*string{}
  50. for _, env := range opts {
  51. tokens := strings.Split(env, "=")
  52. if len(tokens) > 1 {
  53. result[tokens[0]] = &tokens[1]
  54. } else {
  55. result[env] = nil
  56. }
  57. }
  58. return result
  59. }