docker.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package feed
  2. import (
  3. "context"
  4. "github.com/docker/docker/api/types/container"
  5. "github.com/docker/docker/client"
  6. "strings"
  7. )
  8. const (
  9. dockerAPIVersion = "1.24"
  10. dockerGlanceEnable = "glance.enable"
  11. dockerGlanceTitle = "glance.title"
  12. dockerGlanceUrl = "glance.url"
  13. dockerGlanceIconUrl = "glance.iconUrl"
  14. )
  15. type DockerContainer struct {
  16. Id string
  17. Image string
  18. Title string
  19. URL string
  20. IconURL string
  21. Status string
  22. State string
  23. }
  24. func FetchDockerContainers(ctx context.Context) ([]DockerContainer, error) {
  25. apiClient, err := client.NewClientWithOpts(client.WithVersion(dockerAPIVersion), client.FromEnv)
  26. if err != nil {
  27. return nil, err
  28. }
  29. defer apiClient.Close()
  30. containers, err := apiClient.ContainerList(ctx, container.ListOptions{})
  31. if err != nil {
  32. return nil, err
  33. }
  34. var results []DockerContainer
  35. for _, c := range containers {
  36. isGlanceEnabled := getLabelValue(c.Labels, dockerGlanceEnable, "true")
  37. if isGlanceEnabled != "true" {
  38. continue
  39. }
  40. results = append(results, DockerContainer{
  41. Id: c.ID,
  42. Image: c.Image,
  43. Title: getLabelValue(c.Labels, dockerGlanceTitle, strings.Join(c.Names, "")),
  44. URL: getLabelValue(c.Labels, dockerGlanceUrl, ""),
  45. IconURL: getLabelValue(c.Labels, dockerGlanceIconUrl, "si:docker"),
  46. Status: c.Status,
  47. State: c.State,
  48. })
  49. }
  50. return results, nil
  51. }
  52. // getLabelValue get string value associated to a label.
  53. func getLabelValue(labels map[string]string, labelName, defaultValue string) string {
  54. if value, ok := labels[labelName]; ok && len(value) > 0 {
  55. return value
  56. }
  57. return defaultValue
  58. }