e2e-aci_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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.CPUReservation, 1.0)
  216. assert.Equal(t, containerInspect.HostConfig.RestartPolicy, containers.RestartPolicyNone)
  217. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  218. hostIP = containerInspect.Ports[0].HostIP
  219. endpoint = fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  220. })
  221. t.Run("ps", func(t *testing.T) {
  222. res := c.RunDockerCmd("ps")
  223. out := lines(res.Stdout())
  224. l := out[len(out)-1]
  225. assert.Assert(t, strings.Contains(l, container), "Looking for %q in line: %s", container, l)
  226. assert.Assert(t, strings.Contains(l, "nginx"))
  227. assert.Assert(t, strings.Contains(l, "Running"))
  228. assert.Assert(t, strings.Contains(l, hostIP+":80->80/tcp"))
  229. })
  230. t.Run("http get", func(t *testing.T) {
  231. output := HTTPGetWithRetry(t, endpoint, http.StatusOK, 2*time.Second, 20*time.Second)
  232. assert.Assert(t, strings.Contains(output, testFileContent), "Actual content: "+output)
  233. })
  234. t.Run("logs", func(t *testing.T) {
  235. res := c.RunDockerCmd("logs", container)
  236. res.Assert(t, icmd.Expected{Out: "GET"})
  237. })
  238. t.Run("exec", func(t *testing.T) {
  239. res := c.RunDockerOrExitError("exec", container, "pwd")
  240. assert.Assert(t, strings.Contains(res.Stdout(), "/"))
  241. res = c.RunDockerOrExitError("exec", container, "echo", "fail_with_argument")
  242. res.Assert(t, icmd.Expected{
  243. ExitCode: 1,
  244. Err: "ACI exec command does not accept arguments to the command. Only the binary should be specified",
  245. })
  246. })
  247. t.Run("logs follow", func(t *testing.T) {
  248. cmd := c.NewDockerCmd("logs", "--follow", container)
  249. res := icmd.StartCmd(cmd)
  250. checkUp := func(t poll.LogT) poll.Result {
  251. r, _ := http.Get(endpoint + "/is_up")
  252. if r != nil && r.StatusCode == http.StatusNotFound {
  253. return poll.Success()
  254. }
  255. return poll.Continue("waiting for container to serve request")
  256. }
  257. poll.WaitOn(t, checkUp, poll.WithDelay(1*time.Second), poll.WithTimeout(60*time.Second))
  258. assert.Assert(t, !strings.Contains(res.Stdout(), "/test"))
  259. checkLogs := func(t poll.LogT) poll.Result {
  260. if strings.Contains(res.Stdout(), "/test") {
  261. return poll.Success()
  262. }
  263. return poll.Continue("waiting for logs to contain /test")
  264. }
  265. // Do request on /test
  266. go func() {
  267. time.Sleep(3 * time.Second)
  268. _, _ = http.Get(endpoint + "/test")
  269. }()
  270. poll.WaitOn(t, checkLogs, poll.WithDelay(3*time.Second), poll.WithTimeout(20*time.Second))
  271. if runtime.GOOS == "windows" {
  272. err := res.Cmd.Process.Kill()
  273. assert.NilError(t, err)
  274. } else {
  275. err := res.Cmd.Process.Signal(syscall.SIGTERM)
  276. assert.NilError(t, err)
  277. }
  278. })
  279. t.Run("rm a running container", func(t *testing.T) {
  280. res := c.RunDockerOrExitError("rm", container)
  281. res.Assert(t, icmd.Expected{
  282. Err: fmt.Sprintf("Error: you cannot remove a running container %s. Stop the container before attempting removal or force remove", container),
  283. ExitCode: 1,
  284. })
  285. })
  286. t.Run("force rm", func(t *testing.T) {
  287. res := c.RunDockerCmd("rm", "-f", container)
  288. res.Assert(t, icmd.Expected{Out: container})
  289. checkStopped := func(t poll.LogT) poll.Result {
  290. res := c.RunDockerOrExitError("inspect", container)
  291. if res.ExitCode == 1 {
  292. return poll.Success()
  293. }
  294. return poll.Continue("waiting for container to stop")
  295. }
  296. poll.WaitOn(t, checkStopped, poll.WithDelay(5*time.Second), poll.WithTimeout(60*time.Second))
  297. })
  298. }
  299. func lines(output string) []string {
  300. return strings.Split(strings.TrimSpace(output), "\n")
  301. }
  302. func TestContainerRunAttached(t *testing.T) {
  303. c := NewParallelE2eCLI(t, binDir)
  304. _, groupID, location := setupTestResourceGroup(t, c)
  305. // Used in subtests
  306. var (
  307. container string = "test-container"
  308. endpoint string
  309. followLogsProcess *icmd.Result
  310. )
  311. t.Run("run attached limits", func(t *testing.T) {
  312. dnsLabelName := "nginx-" + groupID
  313. fqdn := dnsLabelName + "." + location + ".azurecontainer.io"
  314. cmd := c.NewDockerCmd(
  315. "run",
  316. "--name", container,
  317. "--restart", "on-failure",
  318. "--memory", "0.1G", "--cpus", "0.1",
  319. "-p", "80:80",
  320. "--domainname",
  321. dnsLabelName,
  322. "nginx",
  323. )
  324. followLogsProcess = icmd.StartCmd(cmd)
  325. checkRunning := func(t poll.LogT) poll.Result {
  326. res := c.RunDockerOrExitError("inspect", container)
  327. if res.ExitCode == 0 && strings.Contains(res.Stdout(), `"Status": "Running"`) && !strings.Contains(res.Stdout(), `"HostIP": ""`) {
  328. return poll.Success()
  329. }
  330. return poll.Continue("waiting for container to be running, current inspect result: \n%s", res.Combined())
  331. }
  332. poll.WaitOn(t, checkRunning, poll.WithDelay(5*time.Second), poll.WithTimeout(90*time.Second))
  333. inspectRes := c.RunDockerCmd("inspect", container)
  334. containerInspect, err := ParseContainerInspect(inspectRes.Stdout())
  335. assert.NilError(t, err)
  336. assert.Equal(t, containerInspect.Platform, "Linux")
  337. assert.Equal(t, containerInspect.HostConfig.CPULimit, 0.1)
  338. assert.Equal(t, containerInspect.HostConfig.MemoryLimit, uint64(107374182))
  339. assert.Equal(t, containerInspect.HostConfig.CPUReservation, 0.1)
  340. assert.Equal(t, containerInspect.HostConfig.MemoryReservation, uint64(107374182))
  341. assert.Equal(t, containerInspect.HostConfig.RestartPolicy, containers.RestartPolicyOnFailure)
  342. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  343. port := containerInspect.Ports[0]
  344. assert.Assert(t, port.HostIP != "", "empty hostIP, inspect: \n"+inspectRes.Stdout())
  345. assert.Equal(t, port.ContainerPort, uint32(80))
  346. assert.Equal(t, port.HostPort, uint32(80))
  347. assert.Equal(t, containerInspect.Config.FQDN, fqdn)
  348. endpoint = fmt.Sprintf("http://%s:%d", fqdn, port.HostPort)
  349. assert.Assert(t, !strings.Contains(followLogsProcess.Stdout(), "/test"))
  350. checkRequest := func(t poll.LogT) poll.Result {
  351. r, _ := http.Get(endpoint + "/test")
  352. if r != nil && r.StatusCode == http.StatusNotFound {
  353. return poll.Success()
  354. }
  355. return poll.Continue("waiting for container to serve request")
  356. }
  357. poll.WaitOn(t, checkRequest, poll.WithDelay(1*time.Second), poll.WithTimeout(60*time.Second))
  358. checkLog := func(t poll.LogT) poll.Result {
  359. if strings.Contains(followLogsProcess.Stdout(), "/test") {
  360. return poll.Success()
  361. }
  362. return poll.Continue("waiting for logs to contain /test")
  363. }
  364. poll.WaitOn(t, checkLog, poll.WithDelay(1*time.Second), poll.WithTimeout(20*time.Second))
  365. })
  366. t.Run("stop wrong container", func(t *testing.T) {
  367. res := c.RunDockerOrExitError("stop", "unknown-container")
  368. res.Assert(t, icmd.Expected{
  369. Err: "Error: container unknown-container not found",
  370. ExitCode: 1,
  371. })
  372. })
  373. t.Run("stop container", func(t *testing.T) {
  374. res := c.RunDockerCmd("stop", container)
  375. res.Assert(t, icmd.Expected{Out: container})
  376. waitForStatus(t, c, container, "Terminated", "Node Stopped")
  377. })
  378. t.Run("check we stoppped following logs", func(t *testing.T) {
  379. // nolint errcheck
  380. followLogsStopped := waitWithTimeout(func() { followLogsProcess.Cmd.Process.Wait() }, 10*time.Second)
  381. assert.NilError(t, followLogsStopped, "Follow logs process did not stop after container is stopped")
  382. })
  383. t.Run("ps stopped container with --all", func(t *testing.T) {
  384. res := c.RunDockerCmd("ps", container)
  385. out := lines(res.Stdout())
  386. assert.Assert(t, is.Len(out, 1))
  387. res = c.RunDockerCmd("ps", "--all", container)
  388. out = lines(res.Stdout())
  389. assert.Assert(t, is.Len(out, 2))
  390. })
  391. t.Run("restart container", func(t *testing.T) {
  392. res := c.RunDockerCmd("start", container)
  393. res.Assert(t, icmd.Expected{Out: container})
  394. waitForStatus(t, c, container, convert.StatusRunning)
  395. })
  396. t.Run("kill & rm stopped container", func(t *testing.T) {
  397. res := c.RunDockerCmd("kill", container)
  398. res.Assert(t, icmd.Expected{Out: container})
  399. waitForStatus(t, c, container, "Terminated", "Node Stopped")
  400. res = c.RunDockerCmd("rm", container)
  401. res.Assert(t, icmd.Expected{Out: container})
  402. })
  403. }
  404. func overwriteFileStorageAccount(t *testing.T, absComposefileName string, storageAccount string) {
  405. data, err := ioutil.ReadFile(absComposefileName)
  406. assert.NilError(t, err)
  407. override := strings.Replace(string(data), "dockertestvolumeaccount", storageAccount, 1)
  408. err = ioutil.WriteFile(absComposefileName, []byte(override), 0644)
  409. assert.NilError(t, err)
  410. }
  411. func TestUpResources(t *testing.T) {
  412. const (
  413. composeProjectName = "testresources"
  414. serverContainer = composeProjectName + "_web"
  415. wordsContainer = composeProjectName + "_words"
  416. )
  417. c := NewParallelE2eCLI(t, binDir)
  418. setupTestResourceGroup(t, c)
  419. t.Run("compose up", func(t *testing.T) {
  420. c.RunDockerCmd("compose", "up", "-f", "../composefiles/aci-demo/aci_demo_port_resources.yaml", "--project-name", composeProjectName)
  421. res := c.RunDockerCmd("inspect", serverContainer)
  422. webInspect, err := ParseContainerInspect(res.Stdout())
  423. assert.NilError(t, err)
  424. assert.Equal(t, webInspect.HostConfig.CPULimit, 0.7)
  425. assert.Equal(t, webInspect.HostConfig.MemoryLimit, uint64(1073741824))
  426. assert.Equal(t, webInspect.HostConfig.CPUReservation, 0.5)
  427. assert.Equal(t, webInspect.HostConfig.MemoryReservation, uint64(536870912))
  428. res = c.RunDockerCmd("inspect", wordsContainer)
  429. wordsInspect, err := ParseContainerInspect(res.Stdout())
  430. assert.NilError(t, err)
  431. assert.Equal(t, wordsInspect.HostConfig.CPULimit, 0.5)
  432. assert.Equal(t, wordsInspect.HostConfig.MemoryLimit, uint64(751619276))
  433. assert.Equal(t, wordsInspect.HostConfig.CPUReservation, 0.5)
  434. assert.Equal(t, wordsInspect.HostConfig.MemoryReservation, uint64(751619276))
  435. })
  436. }
  437. func TestUpUpdate(t *testing.T) {
  438. const (
  439. composeProjectName = "acidemo"
  440. serverContainer = composeProjectName + "_web"
  441. wordsContainer = composeProjectName + "_words"
  442. dbContainer = composeProjectName + "_db"
  443. )
  444. var (
  445. singlePortVolumesComposefile = "aci_demo_port_volumes.yaml"
  446. multiPortComposefile = "aci_demo_multi_port.yaml"
  447. )
  448. c := NewParallelE2eCLI(t, binDir)
  449. sID, groupID, location := setupTestResourceGroup(t, c)
  450. composeAccountName := groupID + "-sa"
  451. composeAccountName = strings.ReplaceAll(composeAccountName, "-", "")
  452. composeAccountName = strings.ToLower(composeAccountName)
  453. dstDir := filepath.Join(os.TempDir(), "e2e-aci-volume-"+composeAccountName)
  454. srcDir := filepath.Join("..", "composefiles", "aci-demo")
  455. err := fileutil.CopyDirs(srcDir, dstDir)
  456. assert.NilError(t, err)
  457. t.Cleanup(func() {
  458. assert.NilError(t, os.RemoveAll(dstDir))
  459. })
  460. singlePortVolumesComposefile = filepath.Join(dstDir, singlePortVolumesComposefile)
  461. overwriteFileStorageAccount(t, singlePortVolumesComposefile, composeAccountName)
  462. multiPortComposefile = filepath.Join(dstDir, multiPortComposefile)
  463. volumeID := composeAccountName + "/" + fileshareName
  464. t.Run("compose up", func(t *testing.T) {
  465. const (
  466. testFileName = "msg.txt"
  467. testFileContent = "VOLUME_OK"
  468. projectName = "acidemo"
  469. )
  470. c.RunDockerCmd("volume", "create", "--storage-account", composeAccountName, fileshareName)
  471. // Bootstrap volume
  472. aciContext := store.AciContext{
  473. SubscriptionID: sID,
  474. Location: location,
  475. ResourceGroup: groupID,
  476. }
  477. uploadTestFile(t, aciContext, composeAccountName, fileshareName, testFileName, testFileContent)
  478. dnsLabelName := "nginx-" + groupID
  479. fqdn := dnsLabelName + "." + location + ".azurecontainer.io"
  480. // Name of Compose project is taken from current folder "acie2e"
  481. c.RunDockerCmd("compose", "up", "-f", singlePortVolumesComposefile, "--domainname", dnsLabelName, "--project-name", projectName)
  482. res := c.RunDockerCmd("ps")
  483. out := lines(res.Stdout())
  484. // Check three containers are running
  485. assert.Assert(t, is.Len(out, 4))
  486. webRunning := false
  487. for _, l := range out {
  488. if strings.Contains(l, serverContainer) {
  489. webRunning = true
  490. strings.Contains(l, ":80->80/tcp")
  491. }
  492. }
  493. assert.Assert(t, webRunning, "web container not running ; ps:\n"+res.Stdout())
  494. res = c.RunDockerCmd("inspect", serverContainer)
  495. containerInspect, err := ParseContainerInspect(res.Stdout())
  496. assert.NilError(t, err)
  497. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  498. endpoint := fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  499. output := HTTPGetWithRetry(t, endpoint+"/words/noun", http.StatusOK, 2*time.Second, 20*time.Second)
  500. assert.Assert(t, strings.Contains(output, `"word":`))
  501. endpoint = fmt.Sprintf("http://%s:%d", fqdn, containerInspect.Ports[0].HostPort)
  502. HTTPGetWithRetry(t, endpoint+"/words/noun", http.StatusOK, 2*time.Second, 20*time.Second)
  503. body := HTTPGetWithRetry(t, endpoint+"/volume_test/"+testFileName, http.StatusOK, 2*time.Second, 20*time.Second)
  504. assert.Assert(t, strings.Contains(body, testFileContent))
  505. // Try to remove the volume while it's still in use
  506. res = c.RunDockerOrExitError("volume", "rm", volumeID)
  507. res.Assert(t, icmd.Expected{
  508. ExitCode: 1,
  509. Err: fmt.Sprintf(`Error: volume "%s/%s" is used in container group %q`,
  510. composeAccountName, fileshareName, projectName),
  511. })
  512. })
  513. t.Cleanup(func() {
  514. c.RunDockerCmd("volume", "rm", volumeID)
  515. })
  516. t.Run("compose ps", func(t *testing.T) {
  517. res := c.RunDockerCmd("compose", "ps", "--project-name", composeProjectName)
  518. lines := lines(res.Stdout())
  519. assert.Assert(t, is.Len(lines, 4))
  520. var wordsDisplayed, webDisplayed, dbDisplayed bool
  521. for _, line := range lines {
  522. fields := strings.Fields(line)
  523. containerID := fields[0]
  524. switch containerID {
  525. case wordsContainer:
  526. wordsDisplayed = true
  527. assert.DeepEqual(t, fields, []string{containerID, "words", "1/1"})
  528. case dbContainer:
  529. dbDisplayed = true
  530. assert.DeepEqual(t, fields, []string{containerID, "db", "1/1"})
  531. case serverContainer:
  532. webDisplayed = true
  533. assert.Equal(t, fields[1], "web")
  534. assert.Check(t, strings.Contains(fields[3], ":80->80/tcp"))
  535. }
  536. }
  537. assert.Check(t, webDisplayed && wordsDisplayed && dbDisplayed, "\n%s\n", res.Stdout())
  538. })
  539. t.Run("compose ls", func(t *testing.T) {
  540. res := c.RunDockerCmd("compose", "ls")
  541. lines := lines(res.Stdout())
  542. assert.Equal(t, 2, len(lines))
  543. fields := strings.Fields(lines[1])
  544. assert.Equal(t, 2, len(fields))
  545. assert.Equal(t, fields[0], composeProjectName)
  546. assert.Equal(t, "Running", fields[1])
  547. })
  548. t.Run("logs web", func(t *testing.T) {
  549. res := c.RunDockerCmd("logs", serverContainer)
  550. res.Assert(t, icmd.Expected{Out: "Listening on port 80"})
  551. })
  552. t.Run("update", func(t *testing.T) {
  553. c.RunDockerCmd("compose", "up", "-f", multiPortComposefile, "--project-name", composeProjectName)
  554. res := c.RunDockerCmd("ps")
  555. out := lines(res.Stdout())
  556. // Check three containers are running
  557. assert.Assert(t, is.Len(out, 4))
  558. for _, cName := range []string{serverContainer, wordsContainer} {
  559. res = c.RunDockerCmd("inspect", cName)
  560. containerInspect, err := ParseContainerInspect(res.Stdout())
  561. assert.NilError(t, err)
  562. assert.Assert(t, is.Len(containerInspect.Ports, 1))
  563. endpoint := fmt.Sprintf("http://%s:%d", containerInspect.Ports[0].HostIP, containerInspect.Ports[0].HostPort)
  564. var route string
  565. switch cName {
  566. case serverContainer:
  567. route = "/words/noun"
  568. assert.Equal(t, containerInspect.Ports[0].HostPort, uint32(80))
  569. assert.Equal(t, containerInspect.Ports[0].ContainerPort, uint32(80))
  570. case wordsContainer:
  571. route = "/noun"
  572. assert.Equal(t, containerInspect.Ports[0].HostPort, uint32(8080))
  573. assert.Equal(t, containerInspect.Ports[0].ContainerPort, uint32(8080))
  574. }
  575. HTTPGetWithRetry(t, endpoint+route, http.StatusOK, 1*time.Second, 60*time.Second)
  576. res = c.RunDockerCmd("ps")
  577. p := containerInspect.Ports[0]
  578. res.Assert(t, icmd.Expected{
  579. Out: fmt.Sprintf("%s:%d->%d/tcp", p.HostIP, p.HostPort, p.ContainerPort),
  580. })
  581. }
  582. })
  583. t.Run("down", func(t *testing.T) {
  584. c.RunDockerCmd("compose", "down", "--project-name", composeProjectName)
  585. res := c.RunDockerCmd("ps")
  586. out := lines(res.Stdout())
  587. assert.Equal(t, len(out), 1)
  588. })
  589. }
  590. /*
  591. func TestRunEnvVars(t *testing.T) {
  592. c := NewParallelE2eCLI(t, binDir)
  593. _, _, _ = setupTestResourceGroup(t, c)
  594. t.Run("run", func(t *testing.T) {
  595. cmd := c.NewDockerCmd(
  596. "run", "-d",
  597. "-e", "MYSQL_ROOT_PASSWORD=rootpwd",
  598. "-e", "MYSQL_DATABASE=mytestdb",
  599. "-e", "MYSQL_USER",
  600. "-e", "MYSQL_PASSWORD=userpwd",
  601. "-e", "DATASOURCE_URL=jdbc:mysql://mydb.mysql.database.azure.com/db1?useSSL=true&requireSSL=false&serverTimezone=America/Recife",
  602. "mysql:5.7",
  603. )
  604. cmd.Env = append(cmd.Env, "MYSQL_USER=user1")
  605. res := icmd.RunCmd(cmd)
  606. res.Assert(t, icmd.Success)
  607. out := lines(res.Stdout())
  608. container := strings.TrimSpace(out[len(out)-1])
  609. res = c.RunDockerCmd("inspect", container)
  610. containerInspect, err := ParseContainerInspect(res.Stdout())
  611. assert.NilError(t, err)
  612. assert.Assert(t, containerInspect.Config != nil, "nil container config")
  613. assert.Assert(t, containerInspect.Config.Env != nil, "nil container env variables")
  614. assert.Equal(t, containerInspect.Image, "mysql:5.7")
  615. envVars := containerInspect.Config.Env
  616. assert.Equal(t, len(envVars), 5)
  617. assert.Equal(t, envVars["MYSQL_ROOT_PASSWORD"], "rootpwd")
  618. assert.Equal(t, envVars["MYSQL_DATABASE"], "mytestdb")
  619. assert.Equal(t, envVars["MYSQL_USER"], "user1")
  620. assert.Equal(t, envVars["MYSQL_PASSWORD"], "userpwd")
  621. assert.Equal(t, envVars["DATASOURCE_URL"], "jdbc:mysql://mydb.mysql.database.azure.com/db1?useSSL=true&requireSSL=false&serverTimezone=America/Recife")
  622. check := func(t poll.LogT) poll.Result {
  623. res := c.RunDockerOrExitError("logs", container)
  624. if strings.Contains(res.Stdout(), "Giving user user1 access to schema mytestdb") {
  625. return poll.Success()
  626. }
  627. return poll.Continue("waiting for DB container to be up\n" + res.Stdout())
  628. }
  629. poll.WaitOn(t, check, poll.WithDelay(5*time.Second), poll.WithTimeout(60*time.Second))
  630. })
  631. }
  632. */
  633. func setupTestResourceGroup(t *testing.T, c *E2eCLI) (string, string, string) {
  634. startTime := strconv.Itoa(int(time.Now().Unix()))
  635. rg := "E2E-" + t.Name() + "-" + startTime[5:]
  636. azureLogin(t, c)
  637. sID := getSubscriptionID(t)
  638. location := getTestLocation()
  639. err := createResourceGroup(t, sID, rg, location)
  640. assert.Check(t, is.Nil(err))
  641. t.Cleanup(func() {
  642. if err := deleteResourceGroup(t, rg); err != nil {
  643. t.Error(err)
  644. }
  645. })
  646. createAciContextAndUseIt(t, c, sID, rg, location)
  647. // Check nothing is running
  648. res := c.RunDockerCmd("ps")
  649. assert.Assert(t, is.Len(lines(res.Stdout()), 1))
  650. return sID, rg, location
  651. }
  652. func deleteResourceGroup(t *testing.T, rgName string) error {
  653. fmt.Printf(" [%s] deleting resource group %s\n", t.Name(), rgName)
  654. ctx := context.TODO()
  655. helper := aci.NewACIResourceGroupHelper()
  656. models, err := helper.GetSubscriptionIDs(ctx)
  657. if err != nil {
  658. return err
  659. }
  660. if len(models) == 0 {
  661. return errors.New("unable to delete resource group: no models")
  662. }
  663. return helper.DeleteAsync(ctx, *models[0].SubscriptionID, rgName)
  664. }
  665. func azureLogin(t *testing.T, c *E2eCLI) {
  666. // in order to create new service principal and get these 3 values : `az ad sp create-for-rbac --name 'TestServicePrincipal' --sdk-auth`
  667. clientID := os.Getenv("AZURE_CLIENT_ID")
  668. clientSecret := os.Getenv("AZURE_CLIENT_SECRET")
  669. tenantID := os.Getenv("AZURE_TENANT_ID")
  670. assert.Check(t, clientID != "", "AZURE_CLIENT_ID must not be empty")
  671. assert.Check(t, clientSecret != "", "AZURE_CLIENT_SECRET must not be empty")
  672. assert.Check(t, tenantID != "", "AZURE_TENANT_ID must not be empty")
  673. c.RunDockerCmd("login", "azure", "--client-id", clientID, "--client-secret", clientSecret, "--tenant-id", tenantID)
  674. }
  675. func getSubscriptionID(t *testing.T) string {
  676. ctx := context.TODO()
  677. helper := aci.NewACIResourceGroupHelper()
  678. models, err := helper.GetSubscriptionIDs(ctx)
  679. assert.Check(t, is.Nil(err))
  680. assert.Check(t, len(models) == 1)
  681. return *models[0].SubscriptionID
  682. }
  683. func createResourceGroup(t *testing.T, sID, rgName string, location string) error {
  684. fmt.Printf(" [%s] creating resource group %s\n", t.Name(), rgName)
  685. helper := aci.NewACIResourceGroupHelper()
  686. _, err := helper.CreateOrUpdate(context.TODO(), sID, rgName, resources.Group{Location: to.StringPtr(location)})
  687. return err
  688. }
  689. func createAciContextAndUseIt(t *testing.T, c *E2eCLI, sID, rgName string, location string) {
  690. res := c.RunDockerCmd("context", "create", "aci", contextName, "--subscription-id", sID, "--resource-group", rgName, "--location", location)
  691. res.Assert(t, icmd.Expected{Out: "Successfully created aci context \"" + contextName + "\""})
  692. res = c.RunDockerCmd("context", "use", contextName)
  693. res.Assert(t, icmd.Expected{Out: contextName})
  694. res = c.RunDockerCmd("context", "ls")
  695. res.Assert(t, icmd.Expected{Out: contextName + " *"})
  696. }
  697. func uploadFile(t *testing.T, cred azfile.SharedKeyCredential, baseURL, fileName, content string) {
  698. fURL, err := url.Parse(baseURL + "/" + fileName)
  699. assert.NilError(t, err)
  700. fileURL := azfile.NewFileURL(*fURL, azfile.NewPipeline(&cred, azfile.PipelineOptions{}))
  701. err = azfile.UploadBufferToAzureFile(context.TODO(), []byte(content), fileURL, azfile.UploadToAzureFileOptions{})
  702. assert.NilError(t, err)
  703. }
  704. func getContainerName(stdout string) string {
  705. out := lines(stdout)
  706. return strings.TrimSpace(out[len(out)-1])
  707. }
  708. func waitForStatus(t *testing.T, c *E2eCLI, containerID string, statuses ...string) {
  709. checkStopped := func(logt poll.LogT) poll.Result {
  710. res := c.RunDockerCmd("inspect", containerID)
  711. containerInspect, err := ParseContainerInspect(res.Stdout())
  712. assert.NilError(t, err)
  713. for _, status := range statuses {
  714. if containerInspect.Status == status {
  715. return poll.Success()
  716. }
  717. }
  718. return poll.Continue("Status %s != %s (expected) for container %s", containerInspect.Status, statuses, containerID)
  719. }
  720. poll.WaitOn(t, checkStopped, poll.WithDelay(5*time.Second), poll.WithTimeout(90*time.Second))
  721. }
  722. func waitWithTimeout(blockingCall func(), timeout time.Duration) error {
  723. c := make(chan struct{})
  724. go func() {
  725. defer close(c)
  726. blockingCall()
  727. }()
  728. select {
  729. case <-c:
  730. return nil
  731. case <-time.After(timeout):
  732. return fmt.Errorf("Timed out after %s", timeout)
  733. }
  734. }