environment.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package environment // import "github.com/docker/docker/testutil/environment"
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "testing"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/filters"
  11. "github.com/docker/docker/client"
  12. "github.com/docker/docker/testutil/fixtures/load"
  13. "github.com/pkg/errors"
  14. "gotest.tools/v3/assert"
  15. )
  16. // Execution contains information about the current test execution and daemon
  17. // under test
  18. type Execution struct {
  19. client client.APIClient
  20. DaemonInfo types.Info
  21. PlatformDefaults PlatformDefaults
  22. protectedElements protectedElements
  23. }
  24. // PlatformDefaults are defaults values for the platform of the daemon under test
  25. type PlatformDefaults struct {
  26. BaseImage string
  27. VolumesConfigPath string
  28. ContainerStoragePath string
  29. }
  30. // New creates a new Execution struct
  31. // This is configured using the env client (see client.FromEnv)
  32. func New() (*Execution, error) {
  33. c, err := client.NewClientWithOpts(client.FromEnv)
  34. if err != nil {
  35. return nil, errors.Wrapf(err, "failed to create client")
  36. }
  37. return FromClient(c)
  38. }
  39. // FromClient creates a new Execution environment from the passed in client
  40. func FromClient(c *client.Client) (*Execution, error) {
  41. info, err := c.Info(context.Background())
  42. if err != nil {
  43. return nil, errors.Wrapf(err, "failed to get info from daemon")
  44. }
  45. return &Execution{
  46. client: c,
  47. DaemonInfo: info,
  48. PlatformDefaults: getPlatformDefaults(info),
  49. protectedElements: newProtectedElements(),
  50. }, nil
  51. }
  52. func getPlatformDefaults(info types.Info) PlatformDefaults {
  53. volumesPath := filepath.Join(info.DockerRootDir, "volumes")
  54. containersPath := filepath.Join(info.DockerRootDir, "containers")
  55. switch info.OSType {
  56. case "linux":
  57. return PlatformDefaults{
  58. BaseImage: "scratch",
  59. VolumesConfigPath: toSlash(volumesPath),
  60. ContainerStoragePath: toSlash(containersPath),
  61. }
  62. case "windows":
  63. baseImage := "microsoft/windowsservercore"
  64. if overrideBaseImage := os.Getenv("WINDOWS_BASE_IMAGE"); overrideBaseImage != "" {
  65. baseImage = overrideBaseImage
  66. if overrideBaseImageTag := os.Getenv("WINDOWS_BASE_IMAGE_TAG"); overrideBaseImageTag != "" {
  67. baseImage = baseImage + ":" + overrideBaseImageTag
  68. }
  69. }
  70. fmt.Println("INFO: Windows Base image is ", baseImage)
  71. return PlatformDefaults{
  72. BaseImage: baseImage,
  73. VolumesConfigPath: filepath.FromSlash(volumesPath),
  74. ContainerStoragePath: filepath.FromSlash(containersPath),
  75. }
  76. default:
  77. panic(fmt.Sprintf("unknown OSType for daemon: %s", info.OSType))
  78. }
  79. }
  80. // Make sure in context of daemon, not the local platform. Note we can't
  81. // use filepath.ToSlash here as that is a no-op on Unix.
  82. func toSlash(path string) string {
  83. return strings.ReplaceAll(path, `\`, `/`)
  84. }
  85. // IsLocalDaemon is true if the daemon under test is on the same
  86. // host as the test process.
  87. //
  88. // Deterministically working out the environment in which CI is running
  89. // to evaluate whether the daemon is local or remote is not possible through
  90. // a build tag.
  91. //
  92. // For example Windows to Linux CI under Jenkins tests the 64-bit
  93. // Windows binary build with the daemon build tag, but calls a remote
  94. // Linux daemon.
  95. //
  96. // We can't just say if Windows then assume the daemon is local as at
  97. // some point, we will be testing the Windows CLI against a Windows daemon.
  98. //
  99. // Similarly, it will be perfectly valid to also run CLI tests from
  100. // a Linux CLI (built with the daemon tag) against a Windows daemon.
  101. func (e *Execution) IsLocalDaemon() bool {
  102. return os.Getenv("DOCKER_REMOTE_DAEMON") == ""
  103. }
  104. // IsRemoteDaemon is true if the daemon under test is on different host
  105. // as the test process.
  106. func (e *Execution) IsRemoteDaemon() bool {
  107. return !e.IsLocalDaemon()
  108. }
  109. // DaemonAPIVersion returns the negotiated daemon api version
  110. func (e *Execution) DaemonAPIVersion() string {
  111. version, err := e.APIClient().ServerVersion(context.TODO())
  112. if err != nil {
  113. return ""
  114. }
  115. return version.APIVersion
  116. }
  117. // Print the execution details to stdout
  118. // TODO: print everything
  119. func (e *Execution) Print() {
  120. if e.IsLocalDaemon() {
  121. fmt.Println("INFO: Testing against a local daemon")
  122. } else {
  123. fmt.Println("INFO: Testing against a remote daemon")
  124. }
  125. }
  126. // APIClient returns an APIClient connected to the daemon under test
  127. func (e *Execution) APIClient() client.APIClient {
  128. return e.client
  129. }
  130. // IsUserNamespace returns whether the user namespace remapping is enabled
  131. func (e *Execution) IsUserNamespace() bool {
  132. root := os.Getenv("DOCKER_REMAP_ROOT")
  133. return root != ""
  134. }
  135. // RuntimeIsWindowsContainerd returns whether containerd runtime is used on Windows
  136. func (e *Execution) RuntimeIsWindowsContainerd() bool {
  137. return os.Getenv("DOCKER_WINDOWS_CONTAINERD_RUNTIME") == "1"
  138. }
  139. // IsRootless returns whether the rootless mode is enabled
  140. func (e *Execution) IsRootless() bool {
  141. return os.Getenv("DOCKER_ROOTLESS") != ""
  142. }
  143. // IsUserNamespaceInKernel returns whether the kernel supports user namespaces
  144. func (e *Execution) IsUserNamespaceInKernel() bool {
  145. if _, err := os.Stat("/proc/self/uid_map"); os.IsNotExist(err) {
  146. /*
  147. * This kernel-provided file only exists if user namespaces are
  148. * supported
  149. */
  150. return false
  151. }
  152. // We need extra check on redhat based distributions
  153. if f, err := os.Open("/sys/module/user_namespace/parameters/enable"); err == nil {
  154. defer f.Close()
  155. b := make([]byte, 1)
  156. _, _ = f.Read(b)
  157. return string(b) != "N"
  158. }
  159. return true
  160. }
  161. // UsingSnapshotter returns whether containerd snapshotters are used for the
  162. // tests by checking if the "TEST_INTEGRATION_USE_SNAPSHOTTER" is set to a
  163. // non-empty value.
  164. func (e *Execution) UsingSnapshotter() bool {
  165. return os.Getenv("TEST_INTEGRATION_USE_SNAPSHOTTER") != ""
  166. }
  167. // HasExistingImage checks whether there is an image with the given reference.
  168. // Note that this is done by filtering and then checking whether there were any
  169. // results -- so ambiguous references might result in false-positives.
  170. func (e *Execution) HasExistingImage(t testing.TB, reference string) bool {
  171. imageList, err := e.APIClient().ImageList(context.Background(), types.ImageListOptions{
  172. All: true,
  173. Filters: filters.NewArgs(
  174. filters.Arg("dangling", "false"),
  175. filters.Arg("reference", reference),
  176. ),
  177. })
  178. assert.NilError(t, err, "failed to list images")
  179. return len(imageList) > 0
  180. }
  181. // EnsureFrozenImagesLinux loads frozen test images into the daemon
  182. // if they aren't already loaded
  183. func EnsureFrozenImagesLinux(testEnv *Execution) error {
  184. if testEnv.DaemonInfo.OSType == "linux" {
  185. err := load.FrozenImagesLinux(testEnv.APIClient(), frozenImages...)
  186. if err != nil {
  187. return errors.Wrap(err, "error loading frozen images")
  188. }
  189. }
  190. return nil
  191. }
  192. // GitHubActions is true if test is executed on a GitHub Runner.
  193. func (e *Execution) GitHubActions() bool {
  194. return os.Getenv("GITHUB_ACTIONS") != ""
  195. }