e2e-aci_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. /*
  2. Copyright 2020 Docker, Inc.
  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 main
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "runtime"
  23. "strconv"
  24. "strings"
  25. "syscall"
  26. "testing"
  27. "time"
  28. "github.com/docker/compose-cli/aci/convert"
  29. "gotest.tools/v3/assert"
  30. is "gotest.tools/v3/assert/cmp"
  31. "gotest.tools/v3/icmd"
  32. "gotest.tools/v3/poll"
  33. "github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/resources/mgmt/resources"
  34. "github.com/Azure/azure-storage-file-go/azfile"
  35. "github.com/Azure/go-autorest/autorest/to"
  36. "github.com/docker/compose-cli/aci"
  37. "github.com/docker/compose-cli/aci/login"
  38. "github.com/docker/compose-cli/api/containers"
  39. "github.com/docker/compose-cli/context/store"
  40. "github.com/docker/compose-cli/errdefs"
  41. . "github.com/docker/compose-cli/tests/framework"
  42. )
  43. const (
  44. contextName = "aci-test"
  45. location = "eastus2"
  46. )
  47. var binDir string
  48. func TestMain(m *testing.M) {
  49. p, cleanup, err := SetupExistingCLI()
  50. if err != nil {
  51. fmt.Println(err)
  52. os.Exit(1)
  53. }
  54. binDir = p
  55. exitCode := m.Run()
  56. cleanup()
  57. os.Exit(exitCode)
  58. }
  59. // Cannot be parallelized as login/logout is global.
  60. func TestLoginLogout(t *testing.T) {
  61. startTime := strconv.Itoa(int(time.Now().UnixNano()))
  62. c := NewE2eCLI(t, binDir)
  63. rg := "E2E-" + startTime
  64. t.Run("login", func(t *testing.T) {
  65. azureLogin(t, c)
  66. })
  67. t.Run("create context", func(t *testing.T) {
  68. sID := getSubscriptionID(t)
  69. err := createResourceGroup(t, sID, rg)
  70. assert.Check(t, is.Nil(err))
  71. t.Cleanup(func() {
  72. _ = deleteResourceGroup(t, rg)
  73. })
  74. c.RunDockerCmd("context", "create", "aci", contextName, "--subscription-id", sID, "--resource-group", rg, "--location", location)
  75. res := c.RunDockerCmd("context", "use", contextName)
  76. res.Assert(t, icmd.Expected{Out: contextName})
  77. res = c.RunDockerCmd("context", "ls")
  78. res.Assert(t, icmd.Expected{Out: contextName + " *"})
  79. })
  80. t.Run("delete context", func(t *testing.T) {
  81. res := c.RunDockerCmd("context", "use", "default")
  82. res.Assert(t, icmd.Expected{Out: "default"})
  83. res = c.RunDockerCmd("context", "rm", contextName)
  84. res.Assert(t, icmd.Expected{Out: contextName})
  85. })
  86. t.Run("logout", func(t *testing.T) {
  87. _, err := os.Stat(login.GetTokenStorePath())
  88. assert.NilError(t, err)
  89. res := c.RunDockerCmd("logout", "azure")
  90. res.Assert(t, icmd.Expected{Out: "Removing login credentials for Azure"})
  91. _, err = os.Stat(login.GetTokenStorePath())
  92. errMsg := "no such file or directory"
  93. if runtime.GOOS == "windows" {
  94. errMsg = "The system cannot find the file specified"
  95. }
  96. assert.ErrorContains(t, err, errMsg)
  97. })
  98. t.Run("create context fail", func(t *testing.T) {
  99. res := c.RunDockerOrExitError("context", "create", "aci", "fail-context")
  100. res.Assert(t, icmd.Expected{
  101. ExitCode: errdefs.ExitCodeLoginRequired,
  102. Err: `not logged in to azure, you need to run "docker login azure" first`,
  103. })
  104. })
  105. }
  106. func TestContainerRunVolume(t *testing.T) {
  107. c := NewParallelE2eCLI(t, binDir)
  108. sID, rg := setupTestResourceGroup(t, c)
  109. const (
  110. fileshareName = "dockertestshare"
  111. testFileContent = "Volume mounted successfully!"
  112. testFileName = "index.html"
  113. )
  114. // Bootstrap volume
  115. aciContext := store.AciContext{
  116. SubscriptionID: sID,
  117. Location: location,
  118. ResourceGroup: rg,
  119. }
  120. // Used in subtests
  121. var (
  122. container string
  123. hostIP string
  124. endpoint string
  125. volumeID string
  126. accountName = "e2e" + strconv.Itoa(int(time.Now().UnixNano()))
  127. )
  128. t.Run("check volume name validity", func(t *testing.T) {
  129. invalidName := "some-storage-123"
  130. res := c.RunDockerOrExitError("volume", "create", "--storage-account", invalidName, "--fileshare", fileshareName)
  131. res.Assert(t, icmd.Expected{
  132. ExitCode: 1,
  133. Err: "some-storage-123 is not a valid storage account name. Storage account name must be between 3 and 24 characters in length and use numbers and lower-case letters only.",
  134. })
  135. })
  136. t.Run("create volumes", func(t *testing.T) {
  137. c.RunDockerCmd("volume", "create", "--storage-account", accountName, "--fileshare", fileshareName)
  138. })
  139. volumeID = accountName + "/" + fileshareName
  140. t.Cleanup(func() {
  141. c.RunDockerCmd("volume", "rm", volumeID)
  142. res := c.RunDockerCmd("volume", "ls")
  143. lines := lines(res.Stdout())
  144. assert.Equal(t, len(lines), 1)
  145. })
  146. t.Run("create second fileshare", func(t *testing.T) {
  147. c.RunDockerCmd("volume", "create", "--storage-account", accountName, "--fileshare", "dockertestshare2")
  148. })
  149. volumeID2 := accountName + "/dockertestshare2"
  150. t.Run("list volumes", func(t *testing.T) {
  151. res := c.RunDockerCmd("volume", "ls")
  152. lines := lines(res.Stdout())
  153. assert.Equal(t, len(lines), 3)
  154. firstAccount := lines[1]
  155. fields := strings.Fields(firstAccount)
  156. assert.Equal(t, fields[0], volumeID)
  157. secondAccount := lines[2]
  158. fields = strings.Fields(secondAccount)
  159. assert.Equal(t, fields[0], volumeID2)
  160. })
  161. t.Run("delete only fileshare", func(t *testing.T) {
  162. c.RunDockerCmd("volume", "rm", volumeID2)
  163. res := c.RunDockerCmd("volume", "ls")
  164. lines := lines(res.Stdout())
  165. assert.Equal(t, len(lines), 2)
  166. assert.Assert(t, !strings.Contains(res.Stdout(), "dockertestshare2"), "second fileshare still visible after rm")
  167. })
  168. t.Run("upload file", func(t *testing.T) {
  169. storageLogin := login.StorageLogin{AciContext: aciContext}
  170. key, err := storageLogin.GetAzureStorageAccountKey(context.TODO(), accountName)
  171. assert.NilError(t, err)
  172. cred, err := azfile.NewSharedKeyCredential(accountName, key)
  173. assert.NilError(t, err)
  174. u, _ := url.Parse(fmt.Sprintf("https://%s.file.core.windows.net/%s", accountName, fileshareName))
  175. uploadFile(t, *cred, u.String(), testFileName, testFileContent)
  176. })
  177. t.Run("run", func(t *testing.T) {
  178. mountTarget := "/usr/share/nginx/html"
  179. res := c.RunDockerCmd(
  180. "run", "-d",
  181. "-v", fmt.Sprintf("%s:%s", volumeID, mountTarget),
  182. "-p", "80:80",
  183. "nginx",
  184. )
  185. container = getContainerName(res.Stdout())
  186. })
  187. t.Run("inspect", func(t *testing.T) {
  188. res := c.RunDockerCmd("inspect", container)
  189. containerInspect, err := ParseContainerInspect(res.Stdout())
  190. assert.NilError(t, err)
  191. assert.Equal(t, containerInspect.Platform, "Linux")
  192. assert.Equal(t, containerInspect.CPULimit, 1.0)
  193. assert.Equal(t, containerInspect.RestartPolicyCondition, containers.RestartPolicyNone)
  194. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  195. hostIP = containerInspect.Ports[0].HostIP
  196. endpoint = fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  197. })
  198. t.Run("ps", func(t *testing.T) {
  199. res := c.RunDockerCmd("ps")
  200. out := lines(res.Stdout())
  201. l := out[len(out)-1]
  202. assert.Assert(t, strings.Contains(l, container), "Looking for %q in line: %s", container, l)
  203. assert.Assert(t, strings.Contains(l, "nginx"))
  204. assert.Assert(t, strings.Contains(l, "Running"))
  205. assert.Assert(t, strings.Contains(l, hostIP+":80->80/tcp"))
  206. })
  207. t.Run("http get", func(t *testing.T) {
  208. r, err := HTTPGetWithRetry(endpoint, 3)
  209. assert.NilError(t, err)
  210. assert.Equal(t, r.StatusCode, http.StatusOK)
  211. b, err := ioutil.ReadAll(r.Body)
  212. assert.NilError(t, err)
  213. assert.Assert(t, strings.Contains(string(b), testFileContent), "Actual content: "+string(b))
  214. })
  215. t.Run("logs", func(t *testing.T) {
  216. res := c.RunDockerCmd("logs", container)
  217. res.Assert(t, icmd.Expected{Out: "GET"})
  218. })
  219. t.Run("exec", func(t *testing.T) {
  220. res := c.RunDockerCmd("exec", container, "pwd")
  221. res.Assert(t, icmd.Expected{Out: "/"})
  222. res = c.RunDockerOrExitError("exec", container, "echo", "fail_with_argument")
  223. res.Assert(t, icmd.Expected{
  224. ExitCode: 1,
  225. Err: "ACI exec command does not accept arguments to the command. Only the binary should be specified",
  226. })
  227. })
  228. t.Run("logs follow", func(t *testing.T) {
  229. cmd := c.NewDockerCmd("logs", "--follow", container)
  230. res := icmd.StartCmd(cmd)
  231. checkUp := func(t poll.LogT) poll.Result {
  232. r, _ := http.Get(endpoint + "/is_up")
  233. if r != nil && r.StatusCode == http.StatusNotFound {
  234. return poll.Success()
  235. }
  236. return poll.Continue("waiting for container to serve request")
  237. }
  238. poll.WaitOn(t, checkUp, poll.WithDelay(1*time.Second), poll.WithTimeout(60*time.Second))
  239. assert.Assert(t, !strings.Contains(res.Stdout(), "/test"))
  240. checkLogs := func(t poll.LogT) poll.Result {
  241. if strings.Contains(res.Stdout(), "/test") {
  242. return poll.Success()
  243. }
  244. return poll.Continue("waiting for logs to contain /test")
  245. }
  246. // Do request on /test
  247. go func() {
  248. time.Sleep(3 * time.Second)
  249. _, _ = http.Get(endpoint + "/test")
  250. }()
  251. poll.WaitOn(t, checkLogs, poll.WithDelay(3*time.Second), poll.WithTimeout(20*time.Second))
  252. if runtime.GOOS == "windows" {
  253. err := res.Cmd.Process.Kill()
  254. assert.NilError(t, err)
  255. } else {
  256. err := res.Cmd.Process.Signal(syscall.SIGTERM)
  257. assert.NilError(t, err)
  258. }
  259. })
  260. t.Run("rm a running container", func(t *testing.T) {
  261. res := c.RunDockerOrExitError("rm", container)
  262. res.Assert(t, icmd.Expected{
  263. Err: fmt.Sprintf("Error: you cannot remove a running container %s. Stop the container before attempting removal or force remove", container),
  264. ExitCode: 1,
  265. })
  266. })
  267. t.Run("force rm", func(t *testing.T) {
  268. res := c.RunDockerCmd("rm", "-f", container)
  269. res.Assert(t, icmd.Expected{Out: container})
  270. checkStopped := func(t poll.LogT) poll.Result {
  271. res := c.RunDockerOrExitError("inspect", container)
  272. if res.ExitCode == 1 {
  273. return poll.Success()
  274. }
  275. return poll.Continue("waiting for container to stop")
  276. }
  277. poll.WaitOn(t, checkStopped, poll.WithDelay(5*time.Second), poll.WithTimeout(60*time.Second))
  278. })
  279. }
  280. func lines(output string) []string {
  281. return strings.Split(strings.TrimSpace(output), "\n")
  282. }
  283. func TestContainerRunAttached(t *testing.T) {
  284. c := NewParallelE2eCLI(t, binDir)
  285. _, _ = setupTestResourceGroup(t, c)
  286. // Used in subtests
  287. var (
  288. container string
  289. endpoint string
  290. )
  291. container = "test-container"
  292. var followLogsProcess *icmd.Result
  293. t.Run("run attached limits", func(t *testing.T) {
  294. cmd := c.NewDockerCmd(
  295. "run",
  296. "--name", container,
  297. "--restart", "on-failure",
  298. "--memory", "0.1G", "--cpus", "0.1",
  299. "-p", "80:80",
  300. "nginx",
  301. )
  302. followLogsProcess = icmd.StartCmd(cmd)
  303. checkRunning := func(t poll.LogT) poll.Result {
  304. res := c.RunDockerOrExitError("inspect", container)
  305. if res.ExitCode == 0 {
  306. return poll.Success()
  307. }
  308. return poll.Continue("waiting for container to be running")
  309. }
  310. poll.WaitOn(t, checkRunning, poll.WithDelay(5*time.Second), poll.WithTimeout(60*time.Second))
  311. inspectRes := c.RunDockerCmd("inspect", container)
  312. containerInspect, err := ParseContainerInspect(inspectRes.Stdout())
  313. assert.NilError(t, err)
  314. assert.Equal(t, containerInspect.Platform, "Linux")
  315. assert.Equal(t, containerInspect.CPULimit, 0.1)
  316. assert.Equal(t, containerInspect.MemoryLimit, uint64(107374182))
  317. assert.Equal(t, containerInspect.RestartPolicyCondition, containers.RestartPolicyOnFailure)
  318. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  319. port := containerInspect.Ports[0]
  320. assert.Assert(t, len(port.HostIP) > 0)
  321. assert.Equal(t, port.ContainerPort, uint32(80))
  322. assert.Equal(t, port.HostPort, uint32(80))
  323. endpoint = fmt.Sprintf("http://%s:%d", port.HostIP, port.HostPort)
  324. assert.Assert(t, !strings.Contains(followLogsProcess.Stdout(), "/test"))
  325. checkRequest := func(t poll.LogT) poll.Result {
  326. r, _ := http.Get(endpoint + "/test")
  327. if r != nil && r.StatusCode == http.StatusNotFound {
  328. return poll.Success()
  329. }
  330. return poll.Continue("waiting for container to serve request")
  331. }
  332. poll.WaitOn(t, checkRequest, poll.WithDelay(1*time.Second), poll.WithTimeout(60*time.Second))
  333. checkLog := func(t poll.LogT) poll.Result {
  334. if strings.Contains(followLogsProcess.Stdout(), "/test") {
  335. return poll.Success()
  336. }
  337. return poll.Continue("waiting for logs to contain /test")
  338. }
  339. poll.WaitOn(t, checkLog, poll.WithDelay(1*time.Second), poll.WithTimeout(20*time.Second))
  340. })
  341. t.Run("stop wrong container", func(t *testing.T) {
  342. res := c.RunDockerOrExitError("stop", "unknown-container")
  343. res.Assert(t, icmd.Expected{
  344. Err: "Error: container unknown-container not found",
  345. ExitCode: 1,
  346. })
  347. })
  348. t.Run("stop container", func(t *testing.T) {
  349. res := c.RunDockerCmd("stop", container)
  350. res.Assert(t, icmd.Expected{Out: container})
  351. waitForStatus(t, c, container, "Terminated", "Node Stopped")
  352. })
  353. t.Run("check we stoppped following logs", func(t *testing.T) {
  354. // nolint errcheck
  355. followLogsStopped := waitWithTimeout(func() { followLogsProcess.Cmd.Process.Wait() }, 10*time.Second)
  356. assert.NilError(t, followLogsStopped, "Follow logs process did not stop after container is stopped")
  357. })
  358. t.Run("ps stopped container with --all", func(t *testing.T) {
  359. res := c.RunDockerCmd("ps", container)
  360. out := lines(res.Stdout())
  361. assert.Assert(t, is.Len(out, 1))
  362. res = c.RunDockerCmd("ps", "--all", container)
  363. out = lines(res.Stdout())
  364. assert.Assert(t, is.Len(out, 2))
  365. })
  366. t.Run("restart container", func(t *testing.T) {
  367. res := c.RunDockerCmd("start", container)
  368. res.Assert(t, icmd.Expected{Out: container})
  369. waitForStatus(t, c, container, convert.StatusRunning)
  370. })
  371. t.Run("kill & rm stopped container", func(t *testing.T) {
  372. res := c.RunDockerCmd("kill", container)
  373. res.Assert(t, icmd.Expected{Out: container})
  374. waitForStatus(t, c, container, "Terminated", "Node Stopped")
  375. res = c.RunDockerCmd("rm", container)
  376. res.Assert(t, icmd.Expected{Out: container})
  377. })
  378. }
  379. func TestComposeUpUpdate(t *testing.T) {
  380. c := NewParallelE2eCLI(t, binDir)
  381. _, _ = setupTestResourceGroup(t, c)
  382. const (
  383. composeFile = "../composefiles/aci-demo/aci_demo_port.yaml"
  384. composeFileMultiplePorts = "../composefiles/aci-demo/aci_demo_multi_port.yaml"
  385. composeProjectName = "acidemo"
  386. serverContainer = composeProjectName + "_web"
  387. wordsContainer = composeProjectName + "_words"
  388. dbContainer = composeProjectName + "_db"
  389. )
  390. t.Run("compose up", func(t *testing.T) {
  391. // Name of Compose project is taken from current folder "acie2e"
  392. c.RunDockerCmd("compose", "up", "-f", composeFile)
  393. res := c.RunDockerCmd("ps")
  394. out := lines(res.Stdout())
  395. // Check three containers are running
  396. assert.Assert(t, is.Len(out, 4))
  397. webRunning := false
  398. for _, l := range out {
  399. if strings.Contains(l, serverContainer) {
  400. webRunning = true
  401. strings.Contains(l, ":80->80/tcp")
  402. }
  403. }
  404. assert.Assert(t, webRunning, "web container not running")
  405. res = c.RunDockerCmd("inspect", serverContainer)
  406. containerInspect, err := ParseContainerInspect(res.Stdout())
  407. assert.NilError(t, err)
  408. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  409. endpoint := fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  410. r, err := HTTPGetWithRetry(endpoint+"/words/noun", 3)
  411. assert.NilError(t, err)
  412. assert.Equal(t, r.StatusCode, http.StatusOK)
  413. b, err := ioutil.ReadAll(r.Body)
  414. assert.NilError(t, err)
  415. assert.Assert(t, strings.Contains(string(b), `"word":`))
  416. })
  417. t.Run("compose ps", func(t *testing.T) {
  418. res := c.RunDockerCmd("compose", "ps", "--project-name", composeProjectName)
  419. lines := lines(res.Stdout())
  420. assert.Assert(t, is.Len(lines, 4))
  421. var wordsDisplayed, webDisplayed, dbDisplayed bool
  422. for _, line := range lines {
  423. fields := strings.Fields(line)
  424. containerID := fields[0]
  425. switch containerID {
  426. case wordsContainer:
  427. wordsDisplayed = true
  428. assert.DeepEqual(t, fields, []string{containerID, "words", "1/1"})
  429. case dbContainer:
  430. dbDisplayed = true
  431. assert.DeepEqual(t, fields, []string{containerID, "db", "1/1"})
  432. case serverContainer:
  433. webDisplayed = true
  434. assert.Equal(t, fields[1], "web")
  435. assert.Check(t, strings.Contains(fields[3], ":80->80/tcp"))
  436. }
  437. }
  438. assert.Check(t, webDisplayed && wordsDisplayed && dbDisplayed, "\n%s\n", res.Stdout())
  439. })
  440. t.Run("compose ls", func(t *testing.T) {
  441. res := c.RunDockerCmd("compose", "ls")
  442. lines := lines(res.Stdout())
  443. assert.Equal(t, 2, len(lines))
  444. fields := strings.Fields(lines[1])
  445. assert.Equal(t, 2, len(fields))
  446. assert.Equal(t, fields[0], composeProjectName)
  447. assert.Equal(t, "Running", fields[1])
  448. })
  449. t.Run("logs web", func(t *testing.T) {
  450. res := c.RunDockerCmd("logs", serverContainer)
  451. res.Assert(t, icmd.Expected{Out: "Listening on port 80"})
  452. })
  453. t.Run("update", func(t *testing.T) {
  454. c.RunDockerCmd("compose", "up", "-f", composeFileMultiplePorts, "--project-name", composeProjectName)
  455. res := c.RunDockerCmd("ps")
  456. out := lines(res.Stdout())
  457. // Check three containers are running
  458. assert.Assert(t, is.Len(out, 4))
  459. for _, cName := range []string{serverContainer, wordsContainer} {
  460. res = c.RunDockerCmd("inspect", cName)
  461. containerInspect, err := ParseContainerInspect(res.Stdout())
  462. assert.NilError(t, err)
  463. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  464. endpoint := fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  465. var route string
  466. switch cName {
  467. case serverContainer:
  468. route = "/words/noun"
  469. assert.Equal(t, containerInspect.Ports[0].HostPort, uint32(80))
  470. assert.Equal(t, containerInspect.Ports[0].ContainerPort, uint32(80))
  471. case wordsContainer:
  472. route = "/noun"
  473. assert.Equal(t, containerInspect.Ports[0].HostPort, uint32(8080))
  474. assert.Equal(t, containerInspect.Ports[0].ContainerPort, uint32(8080))
  475. }
  476. checkUp := func(t poll.LogT) poll.Result {
  477. r, _ := http.Get(endpoint + route)
  478. if r != nil && r.StatusCode == http.StatusOK {
  479. return poll.Success()
  480. }
  481. return poll.Continue("Waiting for container to serve request")
  482. }
  483. poll.WaitOn(t, checkUp, poll.WithDelay(1*time.Second), poll.WithTimeout(60*time.Second))
  484. res = c.RunDockerCmd("ps")
  485. p := containerInspect.Ports[0]
  486. res.Assert(t, icmd.Expected{
  487. Out: fmt.Sprintf("%s:%d->%d/tcp", p.HostIP, p.HostPort, p.ContainerPort),
  488. })
  489. }
  490. })
  491. t.Run("down", func(t *testing.T) {
  492. c.RunDockerCmd("compose", "down", "--project-name", composeProjectName)
  493. res := c.RunDockerCmd("ps")
  494. out := lines(res.Stdout())
  495. assert.Equal(t, len(out), 1)
  496. })
  497. }
  498. func TestRunEnvVars(t *testing.T) {
  499. c := NewParallelE2eCLI(t, binDir)
  500. _, _ = setupTestResourceGroup(t, c)
  501. t.Run("run", func(t *testing.T) {
  502. cmd := c.NewDockerCmd(
  503. "run", "-d",
  504. "-e", "MYSQL_ROOT_PASSWORD=rootpwd",
  505. "-e", "MYSQL_DATABASE=mytestdb",
  506. "-e", "MYSQL_USER",
  507. "-e", "MYSQL_PASSWORD=userpwd",
  508. "-e", "DATASOURCE_URL=jdbc:mysql://mydb.mysql.database.azure.com/db1?useSSL=true&requireSSL=false&serverTimezone=America/Recife",
  509. "mysql:5.7",
  510. )
  511. cmd.Env = append(cmd.Env, "MYSQL_USER=user1")
  512. res := icmd.RunCmd(cmd)
  513. res.Assert(t, icmd.Success)
  514. out := lines(res.Stdout())
  515. container := strings.TrimSpace(out[len(out)-1])
  516. res = c.RunDockerCmd("inspect", container)
  517. containerInspect, err := ParseContainerInspect(res.Stdout())
  518. assert.NilError(t, err)
  519. assert.Assert(t, containerInspect.Config != nil, "nil container config")
  520. assert.Assert(t, containerInspect.Config.Env != nil, "nil container env variables")
  521. assert.Equal(t, containerInspect.Image, "mysql:5.7")
  522. envVars := containerInspect.Config.Env
  523. assert.Equal(t, len(envVars), 5)
  524. assert.Equal(t, envVars["MYSQL_ROOT_PASSWORD"], "rootpwd")
  525. assert.Equal(t, envVars["MYSQL_DATABASE"], "mytestdb")
  526. assert.Equal(t, envVars["MYSQL_USER"], "user1")
  527. assert.Equal(t, envVars["MYSQL_PASSWORD"], "userpwd")
  528. assert.Equal(t, envVars["DATASOURCE_URL"], "jdbc:mysql://mydb.mysql.database.azure.com/db1?useSSL=true&requireSSL=false&serverTimezone=America/Recife")
  529. check := func(t poll.LogT) poll.Result {
  530. res := c.RunDockerOrExitError("logs", container)
  531. if strings.Contains(res.Stdout(), "Giving user user1 access to schema mytestdb") {
  532. return poll.Success()
  533. }
  534. return poll.Continue("waiting for DB container to be up")
  535. }
  536. poll.WaitOn(t, check, poll.WithDelay(5*time.Second), poll.WithTimeout(60*time.Second))
  537. })
  538. }
  539. func setupTestResourceGroup(t *testing.T, c *E2eCLI) (string, string) {
  540. startTime := strconv.Itoa(int(time.Now().Unix()))
  541. rg := "E2E-" + t.Name() + "-" + startTime
  542. azureLogin(t, c)
  543. sID := getSubscriptionID(t)
  544. err := createResourceGroup(t, sID, rg)
  545. assert.Check(t, is.Nil(err))
  546. t.Cleanup(func() {
  547. if err := deleteResourceGroup(t, rg); err != nil {
  548. t.Error(err)
  549. }
  550. })
  551. createAciContextAndUseIt(t, c, sID, rg)
  552. // Check nothing is running
  553. res := c.RunDockerCmd("ps")
  554. assert.Assert(t, is.Len(lines(res.Stdout()), 1))
  555. return sID, rg
  556. }
  557. func deleteResourceGroup(t *testing.T, rgName string) error {
  558. fmt.Printf(" [%s] deleting resource group %s\n", t.Name(), rgName)
  559. ctx := context.TODO()
  560. helper := aci.NewACIResourceGroupHelper()
  561. models, err := helper.GetSubscriptionIDs(ctx)
  562. if err != nil {
  563. return err
  564. }
  565. if len(models) == 0 {
  566. return errors.New("unable to delete resource group: no models")
  567. }
  568. return helper.DeleteAsync(ctx, *models[0].SubscriptionID, rgName)
  569. }
  570. func azureLogin(t *testing.T, c *E2eCLI) {
  571. // in order to create new service principal and get these 3 values : `az ad sp create-for-rbac --name 'TestServicePrincipal' --sdk-auth`
  572. clientID := os.Getenv("AZURE_CLIENT_ID")
  573. clientSecret := os.Getenv("AZURE_CLIENT_SECRET")
  574. tenantID := os.Getenv("AZURE_TENANT_ID")
  575. assert.Check(t, clientID != "", "AZURE_CLIENT_ID must not be empty")
  576. assert.Check(t, clientSecret != "", "AZURE_CLIENT_SECRET must not be empty")
  577. assert.Check(t, tenantID != "", "AZURE_TENANT_ID must not be empty")
  578. c.RunDockerCmd("login", "azure", "--client-id", clientID, "--client-secret", clientSecret, "--tenant-id", tenantID)
  579. }
  580. func getSubscriptionID(t *testing.T) string {
  581. ctx := context.TODO()
  582. helper := aci.NewACIResourceGroupHelper()
  583. models, err := helper.GetSubscriptionIDs(ctx)
  584. assert.Check(t, is.Nil(err))
  585. assert.Check(t, len(models) == 1)
  586. return *models[0].SubscriptionID
  587. }
  588. func createResourceGroup(t *testing.T, sID, rgName string) error {
  589. fmt.Printf(" [%s] creating resource group %s\n", t.Name(), rgName)
  590. helper := aci.NewACIResourceGroupHelper()
  591. _, err := helper.CreateOrUpdate(context.TODO(), sID, rgName, resources.Group{Location: to.StringPtr(location)})
  592. return err
  593. }
  594. func createAciContextAndUseIt(t *testing.T, c *E2eCLI, sID, rgName string) {
  595. res := c.RunDockerCmd("context", "create", "aci", contextName, "--subscription-id", sID, "--resource-group", rgName, "--location", location)
  596. res.Assert(t, icmd.Expected{Out: "Successfully created aci context \"" + contextName + "\""})
  597. res = c.RunDockerCmd("context", "use", contextName)
  598. res.Assert(t, icmd.Expected{Out: contextName})
  599. res = c.RunDockerCmd("context", "ls")
  600. res.Assert(t, icmd.Expected{Out: contextName + " *"})
  601. }
  602. func uploadFile(t *testing.T, cred azfile.SharedKeyCredential, baseURL, fileName, content string) {
  603. fURL, err := url.Parse(baseURL + "/" + fileName)
  604. assert.NilError(t, err)
  605. fileURL := azfile.NewFileURL(*fURL, azfile.NewPipeline(&cred, azfile.PipelineOptions{}))
  606. err = azfile.UploadBufferToAzureFile(context.TODO(), []byte(content), fileURL, azfile.UploadToAzureFileOptions{})
  607. assert.NilError(t, err)
  608. }
  609. func getContainerName(stdout string) string {
  610. out := lines(stdout)
  611. return strings.TrimSpace(out[len(out)-1])
  612. }
  613. func waitForStatus(t *testing.T, c *E2eCLI, containerID string, statuses ...string) {
  614. checkStopped := func(logt poll.LogT) poll.Result {
  615. res := c.RunDockerCmd("inspect", containerID)
  616. containerInspect, err := ParseContainerInspect(res.Stdout())
  617. assert.NilError(t, err)
  618. for _, status := range statuses {
  619. if containerInspect.Status == status {
  620. return poll.Success()
  621. }
  622. }
  623. return poll.Continue("Status %s != %s (expected) for container %s", containerInspect.Status, statuses, containerID)
  624. }
  625. poll.WaitOn(t, checkStopped, poll.WithDelay(5*time.Second), poll.WithTimeout(90*time.Second))
  626. }
  627. func waitWithTimeout(blockingCall func(), timeout time.Duration) error {
  628. c := make(chan struct{})
  629. go func() {
  630. defer close(c)
  631. blockingCall()
  632. }()
  633. select {
  634. case <-c:
  635. return nil
  636. case <-time.After(timeout):
  637. return fmt.Errorf("Timed out after %s", timeout)
  638. }
  639. }