clean.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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/client"
  10. "gotest.tools/v3/assert"
  11. )
  12. // Clean the environment, preserving protected objects (images, containers, ...)
  13. // and removing everything else. It's meant to run after any tests so that they don't
  14. // depend on each others.
  15. func (e *Execution) Clean(t testing.TB) {
  16. t.Helper()
  17. client := e.APIClient()
  18. platform := e.OSType
  19. if (platform != "windows") || (platform == "windows" && e.DaemonInfo.Isolation == "hyperv") {
  20. unpauseAllContainers(t, client)
  21. }
  22. deleteAllContainers(t, client, e.protectedElements.containers)
  23. deleteAllImages(t, client, e.protectedElements.images)
  24. deleteAllVolumes(t, client, e.protectedElements.volumes)
  25. deleteAllNetworks(t, client, platform, e.protectedElements.networks)
  26. if platform == "linux" {
  27. deleteAllPlugins(t, client, e.protectedElements.plugins)
  28. }
  29. }
  30. func unpauseAllContainers(t testing.TB, client client.ContainerAPIClient) {
  31. t.Helper()
  32. ctx := context.Background()
  33. containers := getPausedContainers(ctx, t, client)
  34. if len(containers) > 0 {
  35. for _, container := range containers {
  36. err := client.ContainerUnpause(ctx, container.ID)
  37. assert.Check(t, err, "failed to unpause container %s", container.ID)
  38. }
  39. }
  40. }
  41. func getPausedContainers(ctx context.Context, t testing.TB, client client.ContainerAPIClient) []types.Container {
  42. t.Helper()
  43. filter := filters.NewArgs()
  44. filter.Add("status", "paused")
  45. containers, err := client.ContainerList(ctx, types.ContainerListOptions{
  46. Filters: filter,
  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 || client.IsErrNotFound(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 len(tags) == 0 {
  90. removeImage(ctx, t, apiclient, image.ID)
  91. continue
  92. }
  93. for _, tag := range tags {
  94. if _, ok := protectedImages[tag]; !ok {
  95. removeImage(ctx, t, apiclient, tag)
  96. }
  97. }
  98. }
  99. }
  100. func removeImage(ctx context.Context, t testing.TB, apiclient client.ImageAPIClient, ref string) {
  101. t.Helper()
  102. _, err := apiclient.ImageRemove(ctx, ref, types.ImageRemoveOptions{
  103. Force: true,
  104. })
  105. if client.IsErrNotFound(err) {
  106. return
  107. }
  108. assert.Check(t, err, "failed to remove image %s", ref)
  109. }
  110. func deleteAllVolumes(t testing.TB, c client.VolumeAPIClient, protectedVolumes map[string]struct{}) {
  111. t.Helper()
  112. volumes, err := c.VolumeList(context.Background(), filters.Args{})
  113. assert.Check(t, err, "failed to list volumes")
  114. for _, v := range volumes.Volumes {
  115. if _, ok := protectedVolumes[v.Name]; ok {
  116. continue
  117. }
  118. err := c.VolumeRemove(context.Background(), v.Name, true)
  119. // Docker EE may list volumes that no longer exist.
  120. if isErrNotFoundSwarmClassic(err) {
  121. continue
  122. }
  123. assert.Check(t, err, "failed to remove volume %s", v.Name)
  124. }
  125. }
  126. func deleteAllNetworks(t testing.TB, c client.NetworkAPIClient, daemonPlatform string, protectedNetworks map[string]struct{}) {
  127. t.Helper()
  128. networks, err := c.NetworkList(context.Background(), types.NetworkListOptions{})
  129. assert.Check(t, err, "failed to list networks")
  130. for _, n := range networks {
  131. if n.Name == "bridge" || n.Name == "none" || n.Name == "host" {
  132. continue
  133. }
  134. if _, ok := protectedNetworks[n.ID]; ok {
  135. continue
  136. }
  137. if daemonPlatform == "windows" && strings.ToLower(n.Name) == "nat" {
  138. // nat is a pre-defined network on Windows and cannot be removed
  139. continue
  140. }
  141. err := c.NetworkRemove(context.Background(), n.ID)
  142. assert.Check(t, err, "failed to remove network %s", n.ID)
  143. }
  144. }
  145. func deleteAllPlugins(t testing.TB, c client.PluginAPIClient, protectedPlugins map[string]struct{}) {
  146. t.Helper()
  147. plugins, err := c.PluginList(context.Background(), filters.Args{})
  148. // Docker EE does not allow cluster-wide plugin management.
  149. if client.IsErrNotImplemented(err) {
  150. return
  151. }
  152. assert.Check(t, err, "failed to list plugins")
  153. for _, p := range plugins {
  154. if _, ok := protectedPlugins[p.Name]; ok {
  155. continue
  156. }
  157. err := c.PluginRemove(context.Background(), p.Name, types.PluginRemoveOptions{Force: true})
  158. assert.Check(t, err, "failed to remove plugin %s", p.ID)
  159. }
  160. }
  161. // Swarm classic aggregates node errors and returns a 500 so we need to check
  162. // the error string instead of just IsErrNotFound().
  163. func isErrNotFoundSwarmClassic(err error) bool {
  164. return err != nil && strings.Contains(strings.ToLower(err.Error()), "no such")
  165. }