e2e-aci_test.go 32 KB

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