container.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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, containerID string) (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: containerID,
  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. },
  39. },
  40. },
  41. Volumes: projectVolumes,
  42. }
  43. return project, nil
  44. }
  45. func toComposeEnvs(opts []string) types.MappingWithEquals {
  46. result := map[string]*string{}
  47. for _, env := range opts {
  48. tokens := strings.Split(env, "=")
  49. if len(tokens) > 1 {
  50. result[tokens[0]] = &tokens[1]
  51. } else {
  52. result[env] = nil
  53. }
  54. }
  55. return result
  56. }