e2e-aci_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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 main
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "runtime"
  22. "strconv"
  23. "strings"
  24. "syscall"
  25. "testing"
  26. "time"
  27. "gotest.tools/v3/assert"
  28. is "gotest.tools/v3/assert/cmp"
  29. "gotest.tools/v3/icmd"
  30. "gotest.tools/v3/poll"
  31. "github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/resources/mgmt/resources"
  32. "github.com/Azure/azure-storage-file-go/azfile"
  33. "github.com/Azure/go-autorest/autorest/to"
  34. "github.com/docker/compose-cli/aci"
  35. "github.com/docker/compose-cli/aci/convert"
  36. "github.com/docker/compose-cli/aci/login"
  37. "github.com/docker/compose-cli/api/containers"
  38. "github.com/docker/compose-cli/context/store"
  39. "github.com/docker/compose-cli/errdefs"
  40. . "github.com/docker/compose-cli/tests/framework"
  41. )
  42. const (
  43. contextName = "aci-test"
  44. location = "eastus2"
  45. )
  46. var binDir string
  47. func TestMain(m *testing.M) {
  48. p, cleanup, err := SetupExistingCLI()
  49. if err != nil {
  50. fmt.Println(err)
  51. os.Exit(1)
  52. }
  53. binDir = p
  54. exitCode := m.Run()
  55. cleanup()
  56. os.Exit(exitCode)
  57. }
  58. // Cannot be parallelized as login/logout is global.
  59. func TestLoginLogout(t *testing.T) {
  60. startTime := strconv.Itoa(int(time.Now().UnixNano()))
  61. c := NewE2eCLI(t, binDir)
  62. rg := "E2E-" + startTime
  63. t.Run("login", func(t *testing.T) {
  64. azureLogin(t, c)
  65. })
  66. t.Run("create context", func(t *testing.T) {
  67. sID := getSubscriptionID(t)
  68. err := createResourceGroup(t, sID, rg)
  69. assert.Check(t, is.Nil(err))
  70. t.Cleanup(func() {
  71. _ = deleteResourceGroup(t, rg)
  72. })
  73. c.RunDockerCmd("context", "create", "aci", contextName, "--subscription-id", sID, "--resource-group", rg, "--location", location)
  74. res := c.RunDockerCmd("context", "use", contextName)
  75. res.Assert(t, icmd.Expected{Out: contextName})
  76. res = c.RunDockerCmd("context", "ls")
  77. res.Assert(t, icmd.Expected{Out: contextName + " *"})
  78. })
  79. t.Run("delete context", func(t *testing.T) {
  80. res := c.RunDockerCmd("context", "use", "default")
  81. res.Assert(t, icmd.Expected{Out: "default"})
  82. res = c.RunDockerCmd("context", "rm", contextName)
  83. res.Assert(t, icmd.Expected{Out: contextName})
  84. })
  85. t.Run("logout", func(t *testing.T) {
  86. _, err := os.Stat(login.GetTokenStorePath())
  87. assert.NilError(t, err)
  88. res := c.RunDockerCmd("logout", "azure")
  89. res.Assert(t, icmd.Expected{Out: "Removing login credentials for Azure"})
  90. _, err = os.Stat(login.GetTokenStorePath())
  91. errMsg := "no such file or directory"
  92. if runtime.GOOS == "windows" {
  93. errMsg = "The system cannot find the file specified"
  94. }
  95. assert.ErrorContains(t, err, errMsg)
  96. })
  97. t.Run("create context fail", func(t *testing.T) {
  98. res := c.RunDockerOrExitError("context", "create", "aci", "fail-context")
  99. res.Assert(t, icmd.Expected{
  100. ExitCode: errdefs.ExitCodeLoginRequired,
  101. Err: `not logged in to azure, you need to run "docker login azure" first`,
  102. })
  103. })
  104. }
  105. func TestContainerRunVolume(t *testing.T) {
  106. c := NewParallelE2eCLI(t, binDir)
  107. sID, rg := setupTestResourceGroup(t, c)
  108. const (
  109. fileshareName = "dockertestshare"
  110. testFileContent = "Volume mounted successfully!"
  111. testFileName = "index.html"
  112. )
  113. // Bootstrap volume
  114. aciContext := store.AciContext{
  115. SubscriptionID: sID,
  116. Location: location,
  117. ResourceGroup: rg,
  118. }
  119. // Used in subtests
  120. var (
  121. container string
  122. hostIP string
  123. endpoint string
  124. volumeID string
  125. accountName = "e2e" + strconv.Itoa(int(time.Now().UnixNano()))
  126. )
  127. t.Run("check empty volume name validity", func(t *testing.T) {
  128. invalidName := ""
  129. res := c.RunDockerOrExitError("volume", "create", "--storage-account", invalidName, fileshareName)
  130. res.Assert(t, icmd.Expected{
  131. ExitCode: 1,
  132. Err: `parameter=accountName constraint=MinLength value="" details: value length must be greater than or equal to 3`,
  133. })
  134. })
  135. t.Run("check volume name validity", func(t *testing.T) {
  136. invalidName := "some-storage-123"
  137. res := c.RunDockerOrExitError("volume", "create", "--storage-account", invalidName, fileshareName)
  138. res.Assert(t, icmd.Expected{
  139. ExitCode: 1,
  140. 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.",
  141. })
  142. })
  143. t.Run("create volumes", func(t *testing.T) {
  144. c.RunDockerCmd("volume", "create", "--storage-account", accountName, fileshareName)
  145. })
  146. volumeID = accountName + "/" + fileshareName
  147. t.Cleanup(func() {
  148. c.RunDockerCmd("volume", "rm", volumeID)
  149. res := c.RunDockerCmd("volume", "ls")
  150. lines := lines(res.Stdout())
  151. assert.Equal(t, len(lines), 1)
  152. })
  153. t.Run("create second fileshare", func(t *testing.T) {
  154. c.RunDockerCmd("volume", "create", "--storage-account", accountName, "dockertestshare2")
  155. })
  156. volumeID2 := accountName + "/dockertestshare2"
  157. t.Run("list volumes", func(t *testing.T) {
  158. res := c.RunDockerCmd("volume", "ls")
  159. lines := lines(res.Stdout())
  160. assert.Equal(t, len(lines), 3)
  161. firstAccount := lines[1]
  162. fields := strings.Fields(firstAccount)
  163. assert.Equal(t, fields[0], volumeID)
  164. secondAccount := lines[2]
  165. fields = strings.Fields(secondAccount)
  166. assert.Equal(t, fields[0], volumeID2)
  167. })
  168. t.Run("delete only fileshare", func(t *testing.T) {
  169. c.RunDockerCmd("volume", "rm", volumeID2)
  170. res := c.RunDockerCmd("volume", "ls")
  171. lines := lines(res.Stdout())
  172. assert.Equal(t, len(lines), 2)
  173. assert.Assert(t, !strings.Contains(res.Stdout(), "dockertestshare2"), "second fileshare still visible after rm")
  174. })
  175. t.Run("upload file", func(t *testing.T) {
  176. storageLogin := login.StorageLoginImpl{AciContext: aciContext}
  177. key, err := storageLogin.GetAzureStorageAccountKey(context.TODO(), accountName)
  178. assert.NilError(t, err)
  179. cred, err := azfile.NewSharedKeyCredential(accountName, key)
  180. assert.NilError(t, err)
  181. u, _ := url.Parse(fmt.Sprintf("https://%s.file.core.windows.net/%s", accountName, fileshareName))
  182. uploadFile(t, *cred, u.String(), testFileName, testFileContent)
  183. })
  184. t.Run("run", func(t *testing.T) {
  185. mountTarget := "/usr/share/nginx/html"
  186. res := c.RunDockerCmd(
  187. "run", "-d",
  188. "-v", fmt.Sprintf("%s:%s", volumeID, mountTarget),
  189. "-p", "80:80",
  190. "nginx",
  191. )
  192. container = getContainerName(res.Stdout())
  193. })
  194. t.Run("inspect", func(t *testing.T) {
  195. res := c.RunDockerCmd("inspect", container)
  196. containerInspect, err := ParseContainerInspect(res.Stdout())
  197. assert.NilError(t, err)
  198. assert.Equal(t, containerInspect.Platform, "Linux")
  199. assert.Equal(t, containerInspect.CPULimit, 1.0)
  200. assert.Equal(t, containerInspect.RestartPolicyCondition, containers.RestartPolicyNone)
  201. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  202. hostIP = containerInspect.Ports[0].HostIP
  203. endpoint = fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  204. })
  205. t.Run("ps", func(t *testing.T) {
  206. res := c.RunDockerCmd("ps")
  207. out := lines(res.Stdout())
  208. l := out[len(out)-1]
  209. assert.Assert(t, strings.Contains(l, container), "Looking for %q in line: %s", container, l)
  210. assert.Assert(t, strings.Contains(l, "nginx"))
  211. assert.Assert(t, strings.Contains(l, "Running"))
  212. assert.Assert(t, strings.Contains(l, hostIP+":80->80/tcp"))
  213. })
  214. t.Run("http get", func(t *testing.T) {
  215. output := HTTPGetWithRetry(t, endpoint, http.StatusOK, 2*time.Second, 20*time.Second)
  216. assert.Assert(t, strings.Contains(output, testFileContent), "Actual content: "+output)
  217. })
  218. t.Run("logs", func(t *testing.T) {
  219. res := c.RunDockerCmd("logs", container)
  220. res.Assert(t, icmd.Expected{Out: "GET"})
  221. })
  222. t.Run("exec", func(t *testing.T) {
  223. res := c.RunDockerCmd("exec", container, "pwd")
  224. res.Assert(t, icmd.Expected{Out: "/"})
  225. res = c.RunDockerOrExitError("exec", container, "echo", "fail_with_argument")
  226. res.Assert(t, icmd.Expected{
  227. ExitCode: 1,
  228. Err: "ACI exec command does not accept arguments to the command. Only the binary should be specified",
  229. })
  230. })
  231. t.Run("logs follow", func(t *testing.T) {
  232. cmd := c.NewDockerCmd("logs", "--follow", container)
  233. res := icmd.StartCmd(cmd)
  234. checkUp := func(t poll.LogT) poll.Result {
  235. r, _ := http.Get(endpoint + "/is_up")
  236. if r != nil && r.StatusCode == http.StatusNotFound {
  237. return poll.Success()
  238. }
  239. return poll.Continue("waiting for container to serve request")
  240. }
  241. poll.WaitOn(t, checkUp, poll.WithDelay(1*time.Second), poll.WithTimeout(60*time.Second))
  242. assert.Assert(t, !strings.Contains(res.Stdout(), "/test"))
  243. checkLogs := func(t poll.LogT) poll.Result {
  244. if strings.Contains(res.Stdout(), "/test") {
  245. return poll.Success()
  246. }
  247. return poll.Continue("waiting for logs to contain /test")
  248. }
  249. // Do request on /test
  250. go func() {
  251. time.Sleep(3 * time.Second)
  252. _, _ = http.Get(endpoint + "/test")
  253. }()
  254. poll.WaitOn(t, checkLogs, poll.WithDelay(3*time.Second), poll.WithTimeout(20*time.Second))
  255. if runtime.GOOS == "windows" {
  256. err := res.Cmd.Process.Kill()
  257. assert.NilError(t, err)
  258. } else {
  259. err := res.Cmd.Process.Signal(syscall.SIGTERM)
  260. assert.NilError(t, err)
  261. }
  262. })
  263. t.Run("rm a running container", func(t *testing.T) {
  264. res := c.RunDockerOrExitError("rm", container)
  265. res.Assert(t, icmd.Expected{
  266. Err: fmt.Sprintf("Error: you cannot remove a running container %s. Stop the container before attempting removal or force remove", container),
  267. ExitCode: 1,
  268. })
  269. })
  270. t.Run("force rm", func(t *testing.T) {
  271. res := c.RunDockerCmd("rm", "-f", container)
  272. res.Assert(t, icmd.Expected{Out: container})
  273. checkStopped := func(t poll.LogT) poll.Result {
  274. res := c.RunDockerOrExitError("inspect", container)
  275. if res.ExitCode == 1 {
  276. return poll.Success()
  277. }
  278. return poll.Continue("waiting for container to stop")
  279. }
  280. poll.WaitOn(t, checkStopped, poll.WithDelay(5*time.Second), poll.WithTimeout(60*time.Second))
  281. })
  282. }
  283. func lines(output string) []string {
  284. return strings.Split(strings.TrimSpace(output), "\n")
  285. }
  286. func TestContainerRunAttached(t *testing.T) {
  287. c := NewParallelE2eCLI(t, binDir)
  288. _, groupID := setupTestResourceGroup(t, c)
  289. // Used in subtests
  290. var (
  291. container string = "test-container"
  292. endpoint string
  293. followLogsProcess *icmd.Result
  294. )
  295. t.Run("run attached limits", func(t *testing.T) {
  296. dnsLabelName := "nginx-" + groupID
  297. fqdn := dnsLabelName + "." + location + ".azurecontainer.io"
  298. cmd := c.NewDockerCmd(
  299. "run",
  300. "--name", container,
  301. "--restart", "on-failure",
  302. "--memory", "0.1G", "--cpus", "0.1",
  303. "-p", "80:80",
  304. "nginx",
  305. "--domainname",
  306. dnsLabelName,
  307. )
  308. followLogsProcess = icmd.StartCmd(cmd)
  309. checkRunning := func(t poll.LogT) poll.Result {
  310. res := c.RunDockerOrExitError("inspect", container)
  311. if res.ExitCode == 0 && strings.Contains(res.Stdout(), `"Status": "Running"`) {
  312. return poll.Success()
  313. }
  314. return poll.Continue("waiting for container to be running, current inspect result: \n%s", res.Combined())
  315. }
  316. poll.WaitOn(t, checkRunning, poll.WithDelay(5*time.Second), poll.WithTimeout(60*time.Second))
  317. inspectRes := c.RunDockerCmd("inspect", container)
  318. containerInspect, err := ParseContainerInspect(inspectRes.Stdout())
  319. assert.NilError(t, err)
  320. assert.Equal(t, containerInspect.Platform, "Linux")
  321. assert.Equal(t, containerInspect.CPULimit, 0.1)
  322. assert.Equal(t, containerInspect.MemoryLimit, uint64(107374182))
  323. assert.Equal(t, containerInspect.RestartPolicyCondition, containers.RestartPolicyOnFailure)
  324. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  325. port := containerInspect.Ports[0]
  326. assert.Assert(t, len(port.HostIP) > 0)
  327. assert.Equal(t, port.ContainerPort, uint32(80))
  328. assert.Equal(t, port.HostPort, uint32(80))
  329. assert.Equal(t, containerInspect.Config.FQDN, fqdn)
  330. endpoint = fmt.Sprintf("http://%s:%d", fqdn, port.HostPort)
  331. assert.Assert(t, !strings.Contains(followLogsProcess.Stdout(), "/test"))
  332. checkRequest := func(t poll.LogT) poll.Result {
  333. r, _ := http.Get(endpoint + "/test")
  334. if r != nil && r.StatusCode == http.StatusNotFound {
  335. return poll.Success()
  336. }
  337. return poll.Continue("waiting for container to serve request")
  338. }
  339. poll.WaitOn(t, checkRequest, poll.WithDelay(1*time.Second), poll.WithTimeout(60*time.Second))
  340. checkLog := func(t poll.LogT) poll.Result {
  341. if strings.Contains(followLogsProcess.Stdout(), "/test") {
  342. return poll.Success()
  343. }
  344. return poll.Continue("waiting for logs to contain /test")
  345. }
  346. poll.WaitOn(t, checkLog, poll.WithDelay(1*time.Second), poll.WithTimeout(20*time.Second))
  347. })
  348. t.Run("stop wrong container", func(t *testing.T) {
  349. res := c.RunDockerOrExitError("stop", "unknown-container")
  350. res.Assert(t, icmd.Expected{
  351. Err: "Error: container unknown-container not found",
  352. ExitCode: 1,
  353. })
  354. })
  355. t.Run("stop container", func(t *testing.T) {
  356. res := c.RunDockerCmd("stop", container)
  357. res.Assert(t, icmd.Expected{Out: container})
  358. waitForStatus(t, c, container, "Terminated", "Node Stopped")
  359. })
  360. t.Run("check we stoppped following logs", func(t *testing.T) {
  361. // nolint errcheck
  362. followLogsStopped := waitWithTimeout(func() { followLogsProcess.Cmd.Process.Wait() }, 10*time.Second)
  363. assert.NilError(t, followLogsStopped, "Follow logs process did not stop after container is stopped")
  364. })
  365. t.Run("ps stopped container with --all", func(t *testing.T) {
  366. res := c.RunDockerCmd("ps", container)
  367. out := lines(res.Stdout())
  368. assert.Assert(t, is.Len(out, 1))
  369. res = c.RunDockerCmd("ps", "--all", container)
  370. out = lines(res.Stdout())
  371. assert.Assert(t, is.Len(out, 2))
  372. })
  373. t.Run("restart container", func(t *testing.T) {
  374. res := c.RunDockerCmd("start", container)
  375. res.Assert(t, icmd.Expected{Out: container})
  376. waitForStatus(t, c, container, convert.StatusRunning)
  377. })
  378. t.Run("kill & rm stopped container", func(t *testing.T) {
  379. res := c.RunDockerCmd("kill", container)
  380. res.Assert(t, icmd.Expected{Out: container})
  381. waitForStatus(t, c, container, "Terminated", "Node Stopped")
  382. res = c.RunDockerCmd("rm", container)
  383. res.Assert(t, icmd.Expected{Out: container})
  384. })
  385. }
  386. func TestComposeUpUpdate(t *testing.T) {
  387. c := NewParallelE2eCLI(t, binDir)
  388. _, groupID := setupTestResourceGroup(t, c)
  389. const (
  390. composeFile = "../composefiles/aci-demo/aci_demo_port.yaml"
  391. composeFileMultiplePorts = "../composefiles/aci-demo/aci_demo_multi_port.yaml"
  392. composeProjectName = "acidemo"
  393. serverContainer = composeProjectName + "_web"
  394. wordsContainer = composeProjectName + "_words"
  395. dbContainer = composeProjectName + "_db"
  396. )
  397. t.Run("compose up", func(t *testing.T) {
  398. dnsLabelName := "nginx-" + groupID
  399. fqdn := dnsLabelName + "." + location + ".azurecontainer.io"
  400. // Name of Compose project is taken from current folder "acie2e"
  401. c.RunDockerCmd("compose", "up", "-f", composeFile, "--domainname", dnsLabelName)
  402. res := c.RunDockerCmd("ps")
  403. out := lines(res.Stdout())
  404. // Check three containers are running
  405. assert.Assert(t, is.Len(out, 4))
  406. webRunning := false
  407. for _, l := range out {
  408. if strings.Contains(l, serverContainer) {
  409. webRunning = true
  410. strings.Contains(l, ":80->80/tcp")
  411. }
  412. }
  413. assert.Assert(t, webRunning, "web container not running")
  414. res = c.RunDockerCmd("inspect", serverContainer)
  415. containerInspect, err := ParseContainerInspect(res.Stdout())
  416. assert.NilError(t, err)
  417. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  418. endpoint := fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  419. output := HTTPGetWithRetry(t, endpoint+"/words/noun", http.StatusOK, 2*time.Second, 20*time.Second)
  420. assert.Assert(t, strings.Contains(output, `"word":`))
  421. endpoint = fmt.Sprintf("http://%s:%d", fqdn, containerInspect.Ports[0].HostPort)
  422. HTTPGetWithRetry(t, endpoint+"/words/noun", http.StatusOK, 2*time.Second, 20*time.Second)
  423. })
  424. t.Run("compose ps", func(t *testing.T) {
  425. res := c.RunDockerCmd("compose", "ps", "--project-name", composeProjectName)
  426. lines := lines(res.Stdout())
  427. assert.Assert(t, is.Len(lines, 4))
  428. var wordsDisplayed, webDisplayed, dbDisplayed bool
  429. for _, line := range lines {
  430. fields := strings.Fields(line)
  431. containerID := fields[0]
  432. switch containerID {
  433. case wordsContainer:
  434. wordsDisplayed = true
  435. assert.DeepEqual(t, fields, []string{containerID, "words", "1/1"})
  436. case dbContainer:
  437. dbDisplayed = true
  438. assert.DeepEqual(t, fields, []string{containerID, "db", "1/1"})
  439. case serverContainer:
  440. webDisplayed = true
  441. assert.Equal(t, fields[1], "web")
  442. assert.Check(t, strings.Contains(fields[3], ":80->80/tcp"))
  443. }
  444. }
  445. assert.Check(t, webDisplayed && wordsDisplayed && dbDisplayed, "\n%s\n", res.Stdout())
  446. })
  447. t.Run("compose ls", func(t *testing.T) {
  448. res := c.RunDockerCmd("compose", "ls")
  449. lines := lines(res.Stdout())
  450. assert.Equal(t, 2, len(lines))
  451. fields := strings.Fields(lines[1])
  452. assert.Equal(t, 2, len(fields))
  453. assert.Equal(t, fields[0], composeProjectName)
  454. assert.Equal(t, "Running", fields[1])
  455. })
  456. t.Run("logs web", func(t *testing.T) {
  457. res := c.RunDockerCmd("logs", serverContainer)
  458. res.Assert(t, icmd.Expected{Out: "Listening on port 80"})
  459. })
  460. t.Run("update", func(t *testing.T) {
  461. c.RunDockerCmd("compose", "up", "-f", composeFileMultiplePorts, "--project-name", composeProjectName)
  462. res := c.RunDockerCmd("ps")
  463. out := lines(res.Stdout())
  464. // Check three containers are running
  465. assert.Assert(t, is.Len(out, 4))
  466. for _, cName := range []string{serverContainer, wordsContainer} {
  467. res = c.RunDockerCmd("inspect", cName)
  468. containerInspect, err := ParseContainerInspect(res.Stdout())
  469. assert.NilError(t, err)
  470. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  471. endpoint := fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  472. var route string
  473. switch cName {
  474. case serverContainer:
  475. route = "/words/noun"
  476. assert.Equal(t, containerInspect.Ports[0].HostPort, uint32(80))
  477. assert.Equal(t, containerInspect.Ports[0].ContainerPort, uint32(80))
  478. case wordsContainer:
  479. route = "/noun"
  480. assert.Equal(t, containerInspect.Ports[0].HostPort, uint32(8080))
  481. assert.Equal(t, containerInspect.Ports[0].ContainerPort, uint32(8080))
  482. }
  483. HTTPGetWithRetry(t, endpoint+route, http.StatusOK, 1*time.Second, 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. }