e2e-aci_test.go 27 KB

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