framework.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package e2e
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "io/fs"
  20. "net/http"
  21. "os"
  22. "path/filepath"
  23. "runtime"
  24. "strings"
  25. "testing"
  26. "time"
  27. cp "github.com/otiai10/copy"
  28. "github.com/stretchr/testify/require"
  29. "gotest.tools/v3/assert"
  30. "gotest.tools/v3/icmd"
  31. "gotest.tools/v3/poll"
  32. "github.com/docker/compose/v2/cmd/compose"
  33. )
  34. var (
  35. // DockerExecutableName is the OS dependent Docker CLI binary name
  36. DockerExecutableName = "docker"
  37. // DockerComposeExecutableName is the OS dependent Docker CLI binary name
  38. DockerComposeExecutableName = "docker-" + compose.PluginName
  39. // DockerScanExecutableName is the OS dependent Docker Scan plugin binary name
  40. DockerScanExecutableName = "docker-scan"
  41. // DockerBuildxExecutableName is the Os dependent Buildx plugin binary name
  42. DockerBuildxExecutableName = "docker-buildx"
  43. // DockerModelExecutableName is the Os dependent Docker-Model plugin binary name
  44. DockerModelExecutableName = "docker-model"
  45. // WindowsExecutableSuffix is the Windows executable suffix
  46. WindowsExecutableSuffix = ".exe"
  47. )
  48. func init() {
  49. if runtime.GOOS == "windows" {
  50. DockerExecutableName += WindowsExecutableSuffix
  51. DockerComposeExecutableName += WindowsExecutableSuffix
  52. DockerScanExecutableName += WindowsExecutableSuffix
  53. DockerBuildxExecutableName += WindowsExecutableSuffix
  54. }
  55. }
  56. // CLI is used to wrap the CLI for end to end testing
  57. type CLI struct {
  58. // ConfigDir for Docker configuration (set as DOCKER_CONFIG)
  59. ConfigDir string
  60. // HomeDir for tools that look for user files (set as HOME)
  61. HomeDir string
  62. // env overrides to apply to every invoked command
  63. //
  64. // To populate, use WithEnv when creating a CLI instance.
  65. env []string
  66. }
  67. // CLIOption to customize behavior for all commands for a CLI instance.
  68. type CLIOption func(c *CLI)
  69. // NewParallelCLI marks the parent test as parallel and returns a CLI instance
  70. // suitable for usage across child tests.
  71. func NewParallelCLI(t *testing.T, opts ...CLIOption) *CLI {
  72. t.Helper()
  73. t.Parallel()
  74. return NewCLI(t, opts...)
  75. }
  76. // NewCLI creates a CLI instance for running E2E tests.
  77. func NewCLI(t testing.TB, opts ...CLIOption) *CLI {
  78. t.Helper()
  79. configDir := t.TempDir()
  80. copyLocalConfig(t, configDir)
  81. initializePlugins(t, configDir)
  82. initializeContextDir(t, configDir)
  83. c := &CLI{
  84. ConfigDir: configDir,
  85. HomeDir: t.TempDir(),
  86. }
  87. for _, opt := range opts {
  88. opt(c)
  89. }
  90. c.RunDockerComposeCmdNoCheck(t, "version")
  91. return c
  92. }
  93. // WithEnv sets environment variables that will be passed to commands.
  94. func WithEnv(env ...string) CLIOption {
  95. return func(c *CLI) {
  96. c.env = append(c.env, env...)
  97. }
  98. }
  99. func copyLocalConfig(t testing.TB, configDir string) {
  100. t.Helper()
  101. // copy local config.json if exists
  102. localConfig := filepath.Join(os.Getenv("HOME"), ".docker", "config.json")
  103. // if no config present just continue
  104. if _, err := os.Stat(localConfig); err != nil {
  105. // copy the local config.json to the test config dir
  106. CopyFile(t, localConfig, filepath.Join(configDir, "config.json"))
  107. }
  108. }
  109. // initializePlugins copies the necessary plugin files to the temporary config
  110. // directory for the test.
  111. func initializePlugins(t testing.TB, configDir string) {
  112. t.Cleanup(func() {
  113. if t.Failed() {
  114. if conf, err := os.ReadFile(filepath.Join(configDir, "config.json")); err == nil {
  115. t.Logf("Config: %s\n", string(conf))
  116. }
  117. t.Log("Contents of config dir:")
  118. for _, p := range dirContents(configDir) {
  119. t.Logf(" - %s", p)
  120. }
  121. }
  122. })
  123. require.NoError(t, os.MkdirAll(filepath.Join(configDir, "cli-plugins"), 0o755),
  124. "Failed to create cli-plugins directory")
  125. composePlugin, err := findExecutable(DockerComposeExecutableName)
  126. if errors.Is(err, fs.ErrNotExist) {
  127. t.Logf("WARNING: docker-compose cli-plugin not found")
  128. }
  129. if err == nil {
  130. CopyFile(t, composePlugin, filepath.Join(configDir, "cli-plugins", DockerComposeExecutableName))
  131. buildxPlugin, err := findPluginExecutable(DockerBuildxExecutableName)
  132. if err != nil {
  133. t.Logf("WARNING: docker-buildx cli-plugin not found, using default buildx installation.")
  134. } else {
  135. CopyFile(t, buildxPlugin, filepath.Join(configDir, "cli-plugins", DockerBuildxExecutableName))
  136. }
  137. // We don't need a functional scan plugin, but a valid plugin binary
  138. CopyFile(t, composePlugin, filepath.Join(configDir, "cli-plugins", DockerScanExecutableName))
  139. modelPlugin, err := findPluginExecutable(DockerModelExecutableName)
  140. if err != nil {
  141. t.Logf("WARNING: docker-model cli-plugin not found")
  142. } else {
  143. CopyFile(t, modelPlugin, filepath.Join(configDir, "cli-plugins", DockerModelExecutableName))
  144. }
  145. }
  146. }
  147. func initializeContextDir(t testing.TB, configDir string) {
  148. dockerUserDir := ".docker/contexts"
  149. userDir, err := os.UserHomeDir()
  150. require.NoError(t, err, "Failed to get user home directory")
  151. userContextsDir := filepath.Join(userDir, dockerUserDir)
  152. if checkExists(userContextsDir) {
  153. dstContexts := filepath.Join(configDir, "contexts")
  154. require.NoError(t, cp.Copy(userContextsDir, dstContexts), "Failed to copy contexts directory")
  155. }
  156. }
  157. func checkExists(path string) bool {
  158. _, err := os.Stat(path)
  159. return err == nil
  160. }
  161. func dirContents(dir string) []string {
  162. var res []string
  163. _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  164. res = append(res, path)
  165. return nil
  166. })
  167. return res
  168. }
  169. func findExecutable(executableName string) (string, error) {
  170. bin := os.Getenv("COMPOSE_E2E_BIN_PATH")
  171. if bin == "" {
  172. _, filename, _, _ := runtime.Caller(0)
  173. buildPath := filepath.Join(filepath.Dir(filename), "..", "..", "bin", "build")
  174. var err error
  175. bin, err = filepath.Abs(filepath.Join(buildPath, executableName))
  176. if err != nil {
  177. return "", err
  178. }
  179. }
  180. if _, err := os.Stat(bin); err == nil {
  181. return bin, nil
  182. }
  183. return "", fmt.Errorf("looking for %q: %w", bin, fs.ErrNotExist)
  184. }
  185. func findPluginExecutable(pluginExecutableName string) (string, error) {
  186. dockerUserDir := ".docker/cli-plugins"
  187. userDir, err := os.UserHomeDir()
  188. if err != nil {
  189. return "", err
  190. }
  191. candidates := []string{
  192. filepath.Join(userDir, dockerUserDir),
  193. "/usr/local/lib/docker/cli-plugins",
  194. "/usr/local/libexec/docker/cli-plugins",
  195. "/usr/lib/docker/cli-plugins",
  196. "/usr/libexec/docker/cli-plugins",
  197. }
  198. for _, path := range candidates {
  199. bin, err := filepath.Abs(filepath.Join(path, pluginExecutableName))
  200. if err != nil {
  201. return "", err
  202. }
  203. if _, err := os.Stat(bin); err == nil {
  204. return bin, nil
  205. }
  206. }
  207. return "", fmt.Errorf("plugin not found %s: %w", pluginExecutableName, os.ErrNotExist)
  208. }
  209. // CopyFile copies a file from a sourceFile to a destinationFile setting permissions to 0755
  210. func CopyFile(t testing.TB, sourceFile string, destinationFile string) {
  211. t.Helper()
  212. src, err := os.Open(sourceFile)
  213. require.NoError(t, err, "Failed to open source file: %s")
  214. //nolint:errcheck
  215. defer src.Close()
  216. dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)
  217. require.NoError(t, err, "Failed to open destination file: %s", destinationFile)
  218. //nolint:errcheck
  219. defer dst.Close()
  220. _, err = io.Copy(dst, src)
  221. require.NoError(t, err, "Failed to copy file: %s", sourceFile)
  222. }
  223. // BaseEnvironment provides the minimal environment variables used across all
  224. // Docker / Compose commands.
  225. func (c *CLI) BaseEnvironment() []string {
  226. env := []string{
  227. "HOME=" + c.HomeDir,
  228. "USER=" + os.Getenv("USER"),
  229. "DOCKER_CONFIG=" + c.ConfigDir,
  230. "KUBECONFIG=invalid",
  231. "PATH=" + os.Getenv("PATH"),
  232. }
  233. dockerContextEnv, ok := os.LookupEnv("DOCKER_CONTEXT")
  234. if ok {
  235. env = append(env, "DOCKER_CONTEXT="+dockerContextEnv)
  236. }
  237. if coverdir, ok := os.LookupEnv("GOCOVERDIR"); ok {
  238. _, filename, _, _ := runtime.Caller(0)
  239. root := filepath.Join(filepath.Dir(filename), "..", "..")
  240. coverdir = filepath.Join(root, coverdir)
  241. env = append(env, fmt.Sprintf("GOCOVERDIR=%s", coverdir))
  242. }
  243. return env
  244. }
  245. // NewCmd creates a cmd object configured with the test environment set
  246. func (c *CLI) NewCmd(command string, args ...string) icmd.Cmd {
  247. return icmd.Cmd{
  248. Command: append([]string{command}, args...),
  249. Env: append(c.BaseEnvironment(), c.env...),
  250. }
  251. }
  252. // NewCmdWithEnv creates a cmd object configured with the test environment set with additional env vars
  253. func (c *CLI) NewCmdWithEnv(envvars []string, command string, args ...string) icmd.Cmd {
  254. // base env -> CLI overrides -> cmd overrides
  255. cmdEnv := append(c.BaseEnvironment(), c.env...)
  256. cmdEnv = append(cmdEnv, envvars...)
  257. return icmd.Cmd{
  258. Command: append([]string{command}, args...),
  259. Env: cmdEnv,
  260. }
  261. }
  262. // MetricsSocket get the path where test metrics will be sent
  263. func (c *CLI) MetricsSocket() string {
  264. return filepath.Join(c.ConfigDir, "docker-cli.sock")
  265. }
  266. // NewDockerCmd creates a docker cmd without running it
  267. func (c *CLI) NewDockerCmd(t testing.TB, args ...string) icmd.Cmd {
  268. t.Helper()
  269. for _, arg := range args {
  270. if arg == compose.PluginName {
  271. t.Fatal("This test called 'RunDockerCmd' for 'compose'. Please prefer 'RunDockerComposeCmd' to be able to test as a plugin and standalone")
  272. }
  273. }
  274. return c.NewCmd(DockerExecutableName, args...)
  275. }
  276. // RunDockerOrExitError runs a docker command and returns a result
  277. func (c *CLI) RunDockerOrExitError(t testing.TB, args ...string) *icmd.Result {
  278. t.Helper()
  279. t.Logf("\t[%s] docker %s\n", t.Name(), strings.Join(args, " "))
  280. return icmd.RunCmd(c.NewDockerCmd(t, args...))
  281. }
  282. // RunCmd runs a command, expects no error and returns a result
  283. func (c *CLI) RunCmd(t testing.TB, args ...string) *icmd.Result {
  284. t.Helper()
  285. t.Logf("\t[%s] %s\n", t.Name(), strings.Join(args, " "))
  286. assert.Assert(t, len(args) >= 1, "require at least one command in parameters")
  287. res := icmd.RunCmd(c.NewCmd(args[0], args[1:]...))
  288. res.Assert(t, icmd.Success)
  289. return res
  290. }
  291. // RunCmdInDir runs a command in a given dir, expects no error and returns a result
  292. func (c *CLI) RunCmdInDir(t testing.TB, dir string, args ...string) *icmd.Result {
  293. t.Helper()
  294. t.Logf("\t[%s] %s\n", t.Name(), strings.Join(args, " "))
  295. assert.Assert(t, len(args) >= 1, "require at least one command in parameters")
  296. cmd := c.NewCmd(args[0], args[1:]...)
  297. cmd.Dir = dir
  298. res := icmd.RunCmd(cmd)
  299. res.Assert(t, icmd.Success)
  300. return res
  301. }
  302. // RunDockerCmd runs a docker command, expects no error and returns a result
  303. func (c *CLI) RunDockerCmd(t testing.TB, args ...string) *icmd.Result {
  304. t.Helper()
  305. res := c.RunDockerOrExitError(t, args...)
  306. res.Assert(t, icmd.Success)
  307. return res
  308. }
  309. // RunDockerComposeCmd runs a docker compose command, expects no error and returns a result
  310. func (c *CLI) RunDockerComposeCmd(t testing.TB, args ...string) *icmd.Result {
  311. t.Helper()
  312. res := c.RunDockerComposeCmdNoCheck(t, args...)
  313. res.Assert(t, icmd.Success)
  314. return res
  315. }
  316. // RunDockerComposeCmdNoCheck runs a docker compose command, don't presume of any expectation and returns a result
  317. func (c *CLI) RunDockerComposeCmdNoCheck(t testing.TB, args ...string) *icmd.Result {
  318. t.Helper()
  319. cmd := c.NewDockerComposeCmd(t, args...)
  320. cmd.Stdout = os.Stdout
  321. t.Logf("Running command: %s", strings.Join(cmd.Command, " "))
  322. return icmd.RunCmd(cmd)
  323. }
  324. // NewDockerComposeCmd creates a command object for Compose, either in plugin
  325. // or standalone mode (based on build tags).
  326. func (c *CLI) NewDockerComposeCmd(t testing.TB, args ...string) icmd.Cmd {
  327. t.Helper()
  328. if composeStandaloneMode {
  329. return c.NewCmd(ComposeStandalonePath(t), args...)
  330. }
  331. args = append([]string{"compose"}, args...)
  332. return c.NewCmd(DockerExecutableName, args...)
  333. }
  334. // ComposeStandalonePath returns the path to the locally-built Compose
  335. // standalone binary from the repo.
  336. //
  337. // This function will fail the test immediately if invoked when not running
  338. // in standalone test mode.
  339. func ComposeStandalonePath(t testing.TB) string {
  340. t.Helper()
  341. if !composeStandaloneMode {
  342. require.Fail(t, "Not running in standalone mode")
  343. }
  344. composeBinary, err := findExecutable(DockerComposeExecutableName)
  345. require.NoError(t, err, "Could not find standalone Compose binary (%q)",
  346. DockerComposeExecutableName)
  347. return composeBinary
  348. }
  349. // StdoutContains returns a predicate on command result expecting a string in stdout
  350. func StdoutContains(expected string) func(*icmd.Result) bool {
  351. return func(res *icmd.Result) bool {
  352. return strings.Contains(res.Stdout(), expected)
  353. }
  354. }
  355. func IsHealthy(service string) func(res *icmd.Result) bool {
  356. return func(res *icmd.Result) bool {
  357. type state struct {
  358. Name string `json:"name"`
  359. Health string `json:"health"`
  360. }
  361. decoder := json.NewDecoder(strings.NewReader(res.Stdout()))
  362. for decoder.More() {
  363. ps := state{}
  364. err := decoder.Decode(&ps)
  365. if err != nil {
  366. return false
  367. }
  368. if ps.Name == service && ps.Health == "healthy" {
  369. return true
  370. }
  371. }
  372. return false
  373. }
  374. }
  375. // WaitForCmdResult try to execute a cmd until resulting output matches given predicate
  376. func (c *CLI) WaitForCmdResult(
  377. t testing.TB,
  378. command icmd.Cmd,
  379. predicate func(*icmd.Result) bool,
  380. timeout time.Duration,
  381. delay time.Duration,
  382. ) {
  383. t.Helper()
  384. assert.Assert(t, timeout.Nanoseconds() > delay.Nanoseconds(), "timeout must be greater than delay")
  385. var res *icmd.Result
  386. checkStopped := func(logt poll.LogT) poll.Result {
  387. fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(command.Command, " "))
  388. res = icmd.RunCmd(command)
  389. if !predicate(res) {
  390. return poll.Continue("Cmd output did not match requirement: %q", res.Combined())
  391. }
  392. return poll.Success()
  393. }
  394. poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  395. }
  396. // WaitForCondition wait for predicate to execute to true
  397. func (c *CLI) WaitForCondition(
  398. t testing.TB,
  399. predicate func() (bool, string),
  400. timeout time.Duration,
  401. delay time.Duration,
  402. ) {
  403. t.Helper()
  404. checkStopped := func(logt poll.LogT) poll.Result {
  405. pass, description := predicate()
  406. if !pass {
  407. return poll.Continue("Condition not met: %q", description)
  408. }
  409. return poll.Success()
  410. }
  411. poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  412. }
  413. // Lines split output into lines
  414. func Lines(output string) []string {
  415. return strings.Split(strings.TrimSpace(output), "\n")
  416. }
  417. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  418. // In the case of an error or the response status is not the expected one, it retries the same request,
  419. // returning the response body as a string (empty if we could not reach it)
  420. func HTTPGetWithRetry(
  421. t testing.TB,
  422. endpoint string,
  423. expectedStatus int,
  424. retryDelay time.Duration,
  425. timeout time.Duration,
  426. ) string {
  427. t.Helper()
  428. var (
  429. r *http.Response
  430. err error
  431. )
  432. client := &http.Client{
  433. Timeout: retryDelay,
  434. }
  435. fmt.Printf("\t[%s] GET %s\n", t.Name(), endpoint)
  436. checkUp := func(t poll.LogT) poll.Result {
  437. r, err = client.Get(endpoint)
  438. if err != nil {
  439. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  440. }
  441. if r.StatusCode == expectedStatus {
  442. return poll.Success()
  443. }
  444. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  445. }
  446. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  447. if r != nil {
  448. b, err := io.ReadAll(r.Body)
  449. assert.NilError(t, err)
  450. return string(b)
  451. }
  452. return ""
  453. }
  454. func (c *CLI) cleanupWithDown(t testing.TB, project string, args ...string) {
  455. t.Helper()
  456. c.RunDockerComposeCmd(t, append([]string{"-p", project, "down", "-v", "--remove-orphans"}, args...)...)
  457. }