clean.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package environment // import "github.com/docker/docker/testutil/environment"
  2. import (
  3. "context"
  4. "regexp"
  5. "strings"
  6. "testing"
  7. "github.com/docker/docker/api/types"
  8. "github.com/docker/docker/api/types/filters"
  9. "github.com/docker/docker/api/types/volume"
  10. "github.com/docker/docker/client"
  11. "github.com/docker/docker/errdefs"
  12. "gotest.tools/v3/assert"
  13. )
  14. // Clean the environment, preserving protected objects (images, containers, ...)
  15. // and removing everything else. It's meant to run after any tests so that they don't
  16. // depend on each others.
  17. func (e *Execution) Clean(t testing.TB) {
  18. t.Helper()
  19. apiClient := e.APIClient()
  20. platform := e.DaemonInfo.OSType
  21. if (platform != "windows") || (platform == "windows" && e.DaemonInfo.Isolation == "hyperv") {
  22. unpauseAllContainers(t, apiClient)
  23. }
  24. deleteAllContainers(t, apiClient, e.protectedElements.containers)
  25. deleteAllImages(t, apiClient, e.protectedElements.images)
  26. deleteAllVolumes(t, apiClient, e.protectedElements.volumes)
  27. deleteAllNetworks(t, apiClient, platform, e.protectedElements.networks)
  28. if platform == "linux" {
  29. deleteAllPlugins(t, apiClient, e.protectedElements.plugins)
  30. }
  31. }
  32. func unpauseAllContainers(t testing.TB, client client.ContainerAPIClient) {
  33. t.Helper()
  34. ctx := context.Background()
  35. containers := getPausedContainers(ctx, t, client)
  36. if len(containers) > 0 {
  37. for _, container := range containers {
  38. err := client.ContainerUnpause(ctx, container.ID)
  39. assert.Check(t, err, "failed to unpause container %s", container.ID)
  40. }
  41. }
  42. }
  43. func getPausedContainers(ctx context.Context, t testing.TB, client client.ContainerAPIClient) []types.Container {
  44. t.Helper()
  45. containers, err := client.ContainerList(ctx, types.ContainerListOptions{
  46. Filters: filters.NewArgs(filters.Arg("status", "paused")),
  47. All: true,
  48. })
  49. assert.Check(t, err, "failed to list containers")
  50. return containers
  51. }
  52. var alreadyExists = regexp.MustCompile(`Error response from daemon: removal of container (\w+) is already in progress`)
  53. func deleteAllContainers(t testing.TB, apiclient client.ContainerAPIClient, protectedContainers map[string]struct{}) {
  54. t.Helper()
  55. ctx := context.Background()
  56. containers := getAllContainers(ctx, t, apiclient)
  57. if len(containers) == 0 {
  58. return
  59. }
  60. for _, container := range containers {
  61. if _, ok := protectedContainers[container.ID]; ok {
  62. continue
  63. }
  64. err := apiclient.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{
  65. Force: true,
  66. RemoveVolumes: true,
  67. })
  68. if err == nil || errdefs.IsNotFound(err) || alreadyExists.MatchString(err.Error()) || isErrNotFoundSwarmClassic(err) {
  69. continue
  70. }
  71. assert.Check(t, err, "failed to remove %s", container.ID)
  72. }
  73. }
  74. func getAllContainers(ctx context.Context, t testing.TB, client client.ContainerAPIClient) []types.Container {
  75. t.Helper()
  76. containers, err := client.ContainerList(ctx, types.ContainerListOptions{
  77. All: true,
  78. })
  79. assert.Check(t, err, "failed to list containers")
  80. return containers
  81. }
  82. func deleteAllImages(t testing.TB, apiclient client.ImageAPIClient, protectedImages map[string]struct{}) {
  83. t.Helper()
  84. images, err := apiclient.ImageList(context.Background(), types.ImageListOptions{})
  85. assert.Check(t, err, "failed to list images")
  86. ctx := context.Background()
  87. for _, image := range images {
  88. tags := tagsFromImageSummary(image)
  89. if _, ok := protectedImages[image.ID]; ok {
  90. continue
  91. }
  92. if len(tags) == 0 {
  93. removeImage(ctx, t, apiclient, image.ID)
  94. continue
  95. }
  96. for _, tag := range tags {
  97. if _, ok := protectedImages[tag]; !ok {
  98. removeImage(ctx, t, apiclient, tag)
  99. }
  100. }
  101. }
  102. }
  103. func removeImage(ctx context.Context, t testing.TB, apiclient client.ImageAPIClient, ref string) {
  104. t.Helper()
  105. _, err := apiclient.ImageRemove(ctx, ref, types.ImageRemoveOptions{
  106. Force: true,
  107. })
  108. if errdefs.IsNotFound(err) {
  109. return
  110. }
  111. assert.Check(t, err, "failed to remove image %s", ref)
  112. }
  113. func deleteAllVolumes(t testing.TB, c client.VolumeAPIClient, protectedVolumes map[string]struct{}) {
  114. t.Helper()
  115. volumes, err := c.VolumeList(context.Background(), volume.ListOptions{})
  116. assert.Check(t, err, "failed to list volumes")
  117. for _, v := range volumes.Volumes {
  118. if _, ok := protectedVolumes[v.Name]; ok {
  119. continue
  120. }
  121. err := c.VolumeRemove(context.Background(), v.Name, true)
  122. // Docker EE may list volumes that no longer exist.
  123. if isErrNotFoundSwarmClassic(err) {
  124. continue
  125. }
  126. assert.Check(t, err, "failed to remove volume %s", v.Name)
  127. }
  128. }
  129. func deleteAllNetworks(t testing.TB, c client.NetworkAPIClient, daemonPlatform string, protectedNetworks map[string]struct{}) {
  130. t.Helper()
  131. networks, err := c.NetworkList(context.Background(), types.NetworkListOptions{})
  132. assert.Check(t, err, "failed to list networks")
  133. for _, n := range networks {
  134. if n.Name == "bridge" || n.Name == "none" || n.Name == "host" {
  135. continue
  136. }
  137. if _, ok := protectedNetworks[n.ID]; ok {
  138. continue
  139. }
  140. if daemonPlatform == "windows" && strings.ToLower(n.Name) == "nat" {
  141. // nat is a pre-defined network on Windows and cannot be removed
  142. continue
  143. }
  144. err := c.NetworkRemove(context.Background(), n.ID)
  145. assert.Check(t, err, "failed to remove network %s", n.ID)
  146. }
  147. }
  148. func deleteAllPlugins(t testing.TB, c client.PluginAPIClient, protectedPlugins map[string]struct{}) {
  149. t.Helper()
  150. plugins, err := c.PluginList(context.Background(), filters.Args{})
  151. // Docker EE does not allow cluster-wide plugin management.
  152. if errdefs.IsNotImplemented(err) {
  153. return
  154. }
  155. assert.Check(t, err, "failed to list plugins")
  156. for _, p := range plugins {
  157. if _, ok := protectedPlugins[p.Name]; ok {
  158. continue
  159. }
  160. err := c.PluginRemove(context.Background(), p.Name, types.PluginRemoveOptions{Force: true})
  161. assert.Check(t, err, "failed to remove plugin %s", p.ID)
  162. }
  163. }
  164. // Swarm classic aggregates node errors and returns a 500 so we need to check
  165. // the error string instead of just IsErrNotFound().
  166. func isErrNotFoundSwarmClassic(err error) bool {
  167. return err != nil && strings.Contains(strings.ToLower(err.Error()), "no such")
  168. }