protect.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package environment
  2. import (
  3. "context"
  4. "github.com/docker/docker/api/types"
  5. "github.com/docker/docker/api/types/filters"
  6. "github.com/docker/docker/integration-cli/fixtures/load"
  7. "github.com/stretchr/testify/require"
  8. )
  9. type protectedElements struct {
  10. images map[string]struct{}
  11. }
  12. // ProtectImage adds the specified image(s) to be protected in case of clean
  13. func (e *Execution) ProtectImage(t testingT, images ...string) {
  14. for _, image := range images {
  15. e.protectedElements.images[image] = struct{}{}
  16. }
  17. }
  18. func newProtectedElements() protectedElements {
  19. return protectedElements{
  20. images: map[string]struct{}{},
  21. }
  22. }
  23. // ProtectImages protects existing images and on linux frozen images from being
  24. // cleaned up at the end of test runs
  25. func ProtectImages(t testingT, testEnv *Execution) {
  26. images := getExistingImages(t, testEnv)
  27. if testEnv.DaemonInfo.OSType == "linux" {
  28. images = append(images, ensureFrozenImagesLinux(t, testEnv)...)
  29. }
  30. testEnv.ProtectImage(t, images...)
  31. }
  32. func getExistingImages(t require.TestingT, testEnv *Execution) []string {
  33. client := testEnv.APIClient()
  34. filter := filters.NewArgs()
  35. filter.Add("dangling", "false")
  36. imageList, err := client.ImageList(context.Background(), types.ImageListOptions{
  37. Filters: filter,
  38. })
  39. require.NoError(t, err, "failed to list images")
  40. images := []string{}
  41. for _, image := range imageList {
  42. images = append(images, tagsFromImageSummary(image)...)
  43. }
  44. return images
  45. }
  46. func tagsFromImageSummary(image types.ImageSummary) []string {
  47. result := []string{}
  48. for _, tag := range image.RepoTags {
  49. if tag != "<none>:<none>" {
  50. result = append(result, tag)
  51. }
  52. }
  53. for _, digest := range image.RepoDigests {
  54. if digest != "<none>@<none>" {
  55. result = append(result, digest)
  56. }
  57. }
  58. return result
  59. }
  60. func ensureFrozenImagesLinux(t testingT, testEnv *Execution) []string {
  61. images := []string{"busybox:latest", "hello-world:frozen", "debian:jessie"}
  62. err := load.FrozenImagesLinux(testEnv.APIClient(), images...)
  63. if err != nil {
  64. t.Fatalf("Failed to load frozen images: %s", err)
  65. }
  66. return images
  67. }