e2e-aci_test.go 35 KB

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