docker_cli_ps_test.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/docker/docker/api/types/versions"
  9. "github.com/docker/docker/integration-cli/checker"
  10. "github.com/docker/docker/integration-cli/cli"
  11. "github.com/docker/docker/integration-cli/cli/build"
  12. "github.com/docker/docker/pkg/stringid"
  13. "github.com/go-check/check"
  14. "gotest.tools/assert"
  15. is "gotest.tools/assert/cmp"
  16. "gotest.tools/icmd"
  17. )
  18. func (s *DockerSuite) TestPsListContainersBase(c *check.C) {
  19. existingContainers := ExistingContainerIDs(c)
  20. out := runSleepingContainer(c, "-d")
  21. firstID := strings.TrimSpace(out)
  22. out = runSleepingContainer(c, "-d")
  23. secondID := strings.TrimSpace(out)
  24. // not long running
  25. out, _ = dockerCmd(c, "run", "-d", "busybox", "true")
  26. thirdID := strings.TrimSpace(out)
  27. out = runSleepingContainer(c, "-d")
  28. fourthID := strings.TrimSpace(out)
  29. // make sure the second is running
  30. c.Assert(waitRun(secondID), checker.IsNil)
  31. // make sure third one is not running
  32. dockerCmd(c, "wait", thirdID)
  33. // make sure the forth is running
  34. c.Assert(waitRun(fourthID), checker.IsNil)
  35. // all
  36. out, _ = dockerCmd(c, "ps", "-a")
  37. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), []string{fourthID, thirdID, secondID, firstID}), checker.Equals, true, check.Commentf("ALL: Container list is not in the correct order: \n%s", out))
  38. // running
  39. out, _ = dockerCmd(c, "ps")
  40. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), []string{fourthID, secondID, firstID}), checker.Equals, true, check.Commentf("RUNNING: Container list is not in the correct order: \n%s", out))
  41. // limit
  42. out, _ = dockerCmd(c, "ps", "-n=2", "-a")
  43. expected := []string{fourthID, thirdID}
  44. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("LIMIT & ALL: Container list is not in the correct order: \n%s", out))
  45. out, _ = dockerCmd(c, "ps", "-n=2")
  46. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("LIMIT: Container list is not in the correct order: \n%s", out))
  47. // filter since
  48. out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-a")
  49. expected = []string{fourthID, thirdID, secondID}
  50. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter & ALL: Container list is not in the correct order: \n%s", out))
  51. out, _ = dockerCmd(c, "ps", "-f", "since="+firstID)
  52. expected = []string{fourthID, secondID}
  53. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter: Container list is not in the correct order: \n%s", out))
  54. out, _ = dockerCmd(c, "ps", "-f", "since="+thirdID)
  55. expected = []string{fourthID}
  56. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter: Container list is not in the correct order: \n%s", out))
  57. // filter before
  58. out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-a")
  59. expected = []string{thirdID, secondID, firstID}
  60. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("BEFORE filter & ALL: Container list is not in the correct order: \n%s", out))
  61. out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID)
  62. expected = []string{secondID, firstID}
  63. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("BEFORE filter: Container list is not in the correct order: \n%s", out))
  64. out, _ = dockerCmd(c, "ps", "-f", "before="+thirdID)
  65. expected = []string{secondID, firstID}
  66. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter: Container list is not in the correct order: \n%s", out))
  67. // filter since & before
  68. out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-a")
  69. expected = []string{thirdID, secondID}
  70. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter & ALL: Container list is not in the correct order: \n%s", out))
  71. out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID)
  72. expected = []string{secondID}
  73. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter: Container list is not in the correct order: \n%s", out))
  74. // filter since & limit
  75. out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2", "-a")
  76. expected = []string{fourthID, thirdID}
  77. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
  78. out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2")
  79. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter, LIMIT: Container list is not in the correct order: \n%s", out))
  80. // filter before & limit
  81. out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1", "-a")
  82. expected = []string{thirdID}
  83. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
  84. out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1")
  85. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out))
  86. // filter since & filter before & limit
  87. out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1", "-a")
  88. expected = []string{thirdID}
  89. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
  90. out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1")
  91. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out))
  92. }
  93. func assertContainerList(out string, expected []string) bool {
  94. lines := strings.Split(strings.Trim(out, "\n "), "\n")
  95. if len(lines)-1 != len(expected) {
  96. return false
  97. }
  98. containerIDIndex := strings.Index(lines[0], "CONTAINER ID")
  99. for i := 0; i < len(expected); i++ {
  100. foundID := lines[i+1][containerIDIndex : containerIDIndex+12]
  101. if foundID != expected[i][:12] {
  102. return false
  103. }
  104. }
  105. return true
  106. }
  107. func (s *DockerSuite) TestPsListContainersSize(c *check.C) {
  108. // Problematic on Windows as it doesn't report the size correctly @swernli
  109. testRequires(c, DaemonIsLinux)
  110. dockerCmd(c, "run", "-d", "busybox")
  111. baseOut, _ := dockerCmd(c, "ps", "-s", "-n=1")
  112. baseLines := strings.Split(strings.Trim(baseOut, "\n "), "\n")
  113. baseSizeIndex := strings.Index(baseLines[0], "SIZE")
  114. baseFoundsize := baseLines[1][baseSizeIndex:]
  115. baseBytes, err := strconv.Atoi(strings.Split(baseFoundsize, "B")[0])
  116. assert.NilError(c, err)
  117. name := "test_size"
  118. dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test")
  119. id := getIDByName(c, name)
  120. var result *icmd.Result
  121. wait := make(chan struct{})
  122. go func() {
  123. result = icmd.RunCommand(dockerBinary, "ps", "-s", "-n=1")
  124. close(wait)
  125. }()
  126. select {
  127. case <-wait:
  128. case <-time.After(3 * time.Second):
  129. c.Fatalf("Calling \"docker ps -s\" timed out!")
  130. }
  131. result.Assert(c, icmd.Success)
  132. lines := strings.Split(strings.Trim(result.Combined(), "\n "), "\n")
  133. assert.Equal(c, len(lines), 2, "Expected 2 lines for 'ps -s -n=1' output, got %d", len(lines))
  134. sizeIndex := strings.Index(lines[0], "SIZE")
  135. idIndex := strings.Index(lines[0], "CONTAINER ID")
  136. foundID := lines[1][idIndex : idIndex+12]
  137. c.Assert(foundID, checker.Equals, id[:12], check.Commentf("Expected id %s, got %s", id[:12], foundID))
  138. expectedSize := fmt.Sprintf("%dB", 2+baseBytes)
  139. foundSize := lines[1][sizeIndex:]
  140. c.Assert(foundSize, checker.Contains, expectedSize, check.Commentf("Expected size %q, got %q", expectedSize, foundSize))
  141. }
  142. func (s *DockerSuite) TestPsListContainersFilterStatus(c *check.C) {
  143. existingContainers := ExistingContainerIDs(c)
  144. // start exited container
  145. out := cli.DockerCmd(c, "run", "-d", "busybox").Combined()
  146. firstID := strings.TrimSpace(out)
  147. // make sure the exited container is not running
  148. cli.DockerCmd(c, "wait", firstID)
  149. // start running container
  150. out = cli.DockerCmd(c, "run", "-itd", "busybox").Combined()
  151. secondID := strings.TrimSpace(out)
  152. // filter containers by exited
  153. out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter=status=exited").Combined()
  154. containerOut := strings.TrimSpace(out)
  155. c.Assert(RemoveOutputForExistingElements(containerOut, existingContainers), checker.Equals, firstID)
  156. out = cli.DockerCmd(c, "ps", "-a", "--no-trunc", "-q", "--filter=status=running").Combined()
  157. containerOut = strings.TrimSpace(out)
  158. c.Assert(RemoveOutputForExistingElements(containerOut, existingContainers), checker.Equals, secondID)
  159. result := cli.Docker(cli.Args("ps", "-a", "-q", "--filter=status=rubbish"), cli.WithTimeout(time.Second*60))
  160. err := "Invalid filter 'status=rubbish'"
  161. if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
  162. err = "Unrecognised filter value for status: rubbish"
  163. }
  164. result.Assert(c, icmd.Expected{
  165. ExitCode: 1,
  166. Err: err,
  167. })
  168. // Windows doesn't support pausing of containers
  169. if testEnv.OSType != "windows" {
  170. // pause running container
  171. out = cli.DockerCmd(c, "run", "-itd", "busybox").Combined()
  172. pausedID := strings.TrimSpace(out)
  173. cli.DockerCmd(c, "pause", pausedID)
  174. // make sure the container is unpaused to let the daemon stop it properly
  175. defer func() { cli.DockerCmd(c, "unpause", pausedID) }()
  176. out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter=status=paused").Combined()
  177. containerOut = strings.TrimSpace(out)
  178. c.Assert(RemoveOutputForExistingElements(containerOut, existingContainers), checker.Equals, pausedID)
  179. }
  180. }
  181. func (s *DockerSuite) TestPsListContainersFilterHealth(c *check.C) {
  182. existingContainers := ExistingContainerIDs(c)
  183. // Test legacy no health check
  184. out := runSleepingContainer(c, "--name=none_legacy")
  185. containerID := strings.TrimSpace(out)
  186. cli.WaitRun(c, containerID)
  187. out = cli.DockerCmd(c, "ps", "-q", "-l", "--no-trunc", "--filter=health=none").Combined()
  188. containerOut := strings.TrimSpace(out)
  189. c.Assert(containerOut, checker.Equals, containerID, check.Commentf("Expected id %s, got %s for legacy none filter, output: %q", containerID, containerOut, out))
  190. // Test no health check specified explicitly
  191. out = runSleepingContainer(c, "--name=none", "--no-healthcheck")
  192. containerID = strings.TrimSpace(out)
  193. cli.WaitRun(c, containerID)
  194. out = cli.DockerCmd(c, "ps", "-q", "-l", "--no-trunc", "--filter=health=none").Combined()
  195. containerOut = strings.TrimSpace(out)
  196. c.Assert(containerOut, checker.Equals, containerID, check.Commentf("Expected id %s, got %s for none filter, output: %q", containerID, containerOut, out))
  197. // Test failing health check
  198. out = runSleepingContainer(c, "--name=failing_container", "--health-cmd=exit 1", "--health-interval=1s")
  199. containerID = strings.TrimSpace(out)
  200. waitForHealthStatus(c, "failing_container", "starting", "unhealthy")
  201. out = cli.DockerCmd(c, "ps", "-q", "--no-trunc", "--filter=health=unhealthy").Combined()
  202. containerOut = strings.TrimSpace(out)
  203. c.Assert(containerOut, checker.Equals, containerID, check.Commentf("Expected containerID %s, got %s for unhealthy filter, output: %q", containerID, containerOut, out))
  204. // Check passing healthcheck
  205. out = runSleepingContainer(c, "--name=passing_container", "--health-cmd=exit 0", "--health-interval=1s")
  206. containerID = strings.TrimSpace(out)
  207. waitForHealthStatus(c, "passing_container", "starting", "healthy")
  208. out = cli.DockerCmd(c, "ps", "-q", "--no-trunc", "--filter=health=healthy").Combined()
  209. containerOut = strings.TrimSpace(RemoveOutputForExistingElements(out, existingContainers))
  210. c.Assert(containerOut, checker.Equals, containerID, check.Commentf("Expected containerID %s, got %s for healthy filter, output: %q", containerID, containerOut, out))
  211. }
  212. func (s *DockerSuite) TestPsListContainersFilterID(c *check.C) {
  213. // start container
  214. out, _ := dockerCmd(c, "run", "-d", "busybox")
  215. firstID := strings.TrimSpace(out)
  216. // start another container
  217. runSleepingContainer(c)
  218. // filter containers by id
  219. out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=id="+firstID)
  220. containerOut := strings.TrimSpace(out)
  221. c.Assert(containerOut, checker.Equals, firstID[:12], check.Commentf("Expected id %s, got %s for exited filter, output: %q", firstID[:12], containerOut, out))
  222. }
  223. func (s *DockerSuite) TestPsListContainersFilterName(c *check.C) {
  224. // start container
  225. dockerCmd(c, "run", "--name=a_name_to_match", "busybox")
  226. id := getIDByName(c, "a_name_to_match")
  227. // start another container
  228. runSleepingContainer(c, "--name=b_name_to_match")
  229. // filter containers by name
  230. out, _ := dockerCmd(c, "ps", "-a", "-q", "--filter=name=a_name_to_match")
  231. containerOut := strings.TrimSpace(out)
  232. c.Assert(containerOut, checker.Equals, id[:12], check.Commentf("Expected id %s, got %s for exited filter, output: %q", id[:12], containerOut, out))
  233. }
  234. // Test for the ancestor filter for ps.
  235. // There is also the same test but with image:tag@digest in docker_cli_by_digest_test.go
  236. //
  237. // What the test setups :
  238. // - Create 2 image based on busybox using the same repository but different tags
  239. // - Create an image based on the previous image (images_ps_filter_test2)
  240. // - Run containers for each of those image (busybox, images_ps_filter_test1, images_ps_filter_test2)
  241. // - Filter them out :P
  242. func (s *DockerSuite) TestPsListContainersFilterAncestorImage(c *check.C) {
  243. existingContainers := ExistingContainerIDs(c)
  244. // Build images
  245. imageName1 := "images_ps_filter_test1"
  246. buildImageSuccessfully(c, imageName1, build.WithDockerfile(`FROM busybox
  247. LABEL match me 1`))
  248. imageID1 := getIDByName(c, imageName1)
  249. imageName1Tagged := "images_ps_filter_test1:tag"
  250. buildImageSuccessfully(c, imageName1Tagged, build.WithDockerfile(`FROM busybox
  251. LABEL match me 1 tagged`))
  252. imageID1Tagged := getIDByName(c, imageName1Tagged)
  253. imageName2 := "images_ps_filter_test2"
  254. buildImageSuccessfully(c, imageName2, build.WithDockerfile(fmt.Sprintf(`FROM %s
  255. LABEL match me 2`, imageName1)))
  256. imageID2 := getIDByName(c, imageName2)
  257. // start containers
  258. dockerCmd(c, "run", "--name=first", "busybox", "echo", "hello")
  259. firstID := getIDByName(c, "first")
  260. // start another container
  261. dockerCmd(c, "run", "--name=second", "busybox", "echo", "hello")
  262. secondID := getIDByName(c, "second")
  263. // start third container
  264. dockerCmd(c, "run", "--name=third", imageName1, "echo", "hello")
  265. thirdID := getIDByName(c, "third")
  266. // start fourth container
  267. dockerCmd(c, "run", "--name=fourth", imageName1Tagged, "echo", "hello")
  268. fourthID := getIDByName(c, "fourth")
  269. // start fifth container
  270. dockerCmd(c, "run", "--name=fifth", imageName2, "echo", "hello")
  271. fifthID := getIDByName(c, "fifth")
  272. var filterTestSuite = []struct {
  273. filterName string
  274. expectedIDs []string
  275. }{
  276. // non existent stuff
  277. {"nonexistent", []string{}},
  278. {"nonexistent:tag", []string{}},
  279. // image
  280. {"busybox", []string{firstID, secondID, thirdID, fourthID, fifthID}},
  281. {imageName1, []string{thirdID, fifthID}},
  282. {imageName2, []string{fifthID}},
  283. // image:tag
  284. {fmt.Sprintf("%s:latest", imageName1), []string{thirdID, fifthID}},
  285. {imageName1Tagged, []string{fourthID}},
  286. // short-id
  287. {stringid.TruncateID(imageID1), []string{thirdID, fifthID}},
  288. {stringid.TruncateID(imageID2), []string{fifthID}},
  289. // full-id
  290. {imageID1, []string{thirdID, fifthID}},
  291. {imageID1Tagged, []string{fourthID}},
  292. {imageID2, []string{fifthID}},
  293. }
  294. var out string
  295. for _, filter := range filterTestSuite {
  296. out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+filter.filterName)
  297. checkPsAncestorFilterOutput(c, RemoveOutputForExistingElements(out, existingContainers), filter.filterName, filter.expectedIDs)
  298. }
  299. // Multiple ancestor filter
  300. out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+imageName2, "--filter=ancestor="+imageName1Tagged)
  301. checkPsAncestorFilterOutput(c, RemoveOutputForExistingElements(out, existingContainers), imageName2+","+imageName1Tagged, []string{fourthID, fifthID})
  302. }
  303. func checkPsAncestorFilterOutput(c *check.C, out string, filterName string, expectedIDs []string) {
  304. var actualIDs []string
  305. if out != "" {
  306. actualIDs = strings.Split(out[:len(out)-1], "\n")
  307. }
  308. sort.Strings(actualIDs)
  309. sort.Strings(expectedIDs)
  310. c.Assert(actualIDs, checker.HasLen, len(expectedIDs), check.Commentf("Expected filtered container(s) for %s ancestor filter to be %v:%v, got %v:%v", filterName, len(expectedIDs), expectedIDs, len(actualIDs), actualIDs))
  311. if len(expectedIDs) > 0 {
  312. same := true
  313. for i := range expectedIDs {
  314. if actualIDs[i] != expectedIDs[i] {
  315. c.Logf("%s, %s", actualIDs[i], expectedIDs[i])
  316. same = false
  317. break
  318. }
  319. }
  320. c.Assert(same, checker.Equals, true, check.Commentf("Expected filtered container(s) for %s ancestor filter to be %v, got %v", filterName, expectedIDs, actualIDs))
  321. }
  322. }
  323. func (s *DockerSuite) TestPsListContainersFilterLabel(c *check.C) {
  324. // start container
  325. dockerCmd(c, "run", "--name=first", "-l", "match=me", "-l", "second=tag", "busybox")
  326. firstID := getIDByName(c, "first")
  327. // start another container
  328. dockerCmd(c, "run", "--name=second", "-l", "match=me too", "busybox")
  329. secondID := getIDByName(c, "second")
  330. // start third container
  331. dockerCmd(c, "run", "--name=third", "-l", "nomatch=me", "busybox")
  332. thirdID := getIDByName(c, "third")
  333. // filter containers by exact match
  334. out, _ := dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me")
  335. containerOut := strings.TrimSpace(out)
  336. c.Assert(containerOut, checker.Equals, firstID, check.Commentf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out))
  337. // filter containers by two labels
  338. out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag")
  339. containerOut = strings.TrimSpace(out)
  340. c.Assert(containerOut, checker.Equals, firstID, check.Commentf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out))
  341. // filter containers by two labels, but expect not found because of AND behavior
  342. out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag-no")
  343. containerOut = strings.TrimSpace(out)
  344. c.Assert(containerOut, checker.Equals, "", check.Commentf("Expected nothing, got %s for exited filter, output: %q", containerOut, out))
  345. // filter containers by exact key
  346. out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match")
  347. containerOut = strings.TrimSpace(out)
  348. c.Assert(containerOut, checker.Contains, firstID)
  349. c.Assert(containerOut, checker.Contains, secondID)
  350. c.Assert(containerOut, checker.Not(checker.Contains), thirdID)
  351. }
  352. func (s *DockerSuite) TestPsListContainersFilterExited(c *check.C) {
  353. runSleepingContainer(c, "--name=sleep")
  354. dockerCmd(c, "run", "--name", "zero1", "busybox", "true")
  355. firstZero := getIDByName(c, "zero1")
  356. dockerCmd(c, "run", "--name", "zero2", "busybox", "true")
  357. secondZero := getIDByName(c, "zero2")
  358. out, _, err := dockerCmdWithError("run", "--name", "nonzero1", "busybox", "false")
  359. c.Assert(err, checker.NotNil, check.Commentf("Should fail.", out, err))
  360. firstNonZero := getIDByName(c, "nonzero1")
  361. out, _, err = dockerCmdWithError("run", "--name", "nonzero2", "busybox", "false")
  362. c.Assert(err, checker.NotNil, check.Commentf("Should fail.", out, err))
  363. secondNonZero := getIDByName(c, "nonzero2")
  364. // filter containers by exited=0
  365. out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=0")
  366. ids := strings.Split(strings.TrimSpace(out), "\n")
  367. c.Assert(ids, checker.HasLen, 2, check.Commentf("Should be 2 zero exited containers got %d: %s", len(ids), out))
  368. c.Assert(ids[0], checker.Equals, secondZero, check.Commentf("First in list should be %q, got %q", secondZero, ids[0]))
  369. c.Assert(ids[1], checker.Equals, firstZero, check.Commentf("Second in list should be %q, got %q", firstZero, ids[1]))
  370. out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=1")
  371. ids = strings.Split(strings.TrimSpace(out), "\n")
  372. c.Assert(ids, checker.HasLen, 2, check.Commentf("Should be 2 zero exited containers got %d", len(ids)))
  373. c.Assert(ids[0], checker.Equals, secondNonZero, check.Commentf("First in list should be %q, got %q", secondNonZero, ids[0]))
  374. c.Assert(ids[1], checker.Equals, firstNonZero, check.Commentf("Second in list should be %q, got %q", firstNonZero, ids[1]))
  375. }
  376. func (s *DockerSuite) TestPsRightTagName(c *check.C) {
  377. // TODO Investigate further why this fails on Windows to Windows CI
  378. testRequires(c, DaemonIsLinux)
  379. existingContainers := ExistingContainerNames(c)
  380. tag := "asybox:shmatest"
  381. dockerCmd(c, "tag", "busybox", tag)
  382. var id1 string
  383. out := runSleepingContainer(c)
  384. id1 = strings.TrimSpace(string(out))
  385. var id2 string
  386. out = runSleepingContainerInImage(c, tag)
  387. id2 = strings.TrimSpace(string(out))
  388. var imageID string
  389. out = inspectField(c, "busybox", "Id")
  390. imageID = strings.TrimSpace(string(out))
  391. var id3 string
  392. out = runSleepingContainerInImage(c, imageID)
  393. id3 = strings.TrimSpace(string(out))
  394. out, _ = dockerCmd(c, "ps", "--no-trunc")
  395. lines := strings.Split(strings.TrimSpace(string(out)), "\n")
  396. lines = RemoveLinesForExistingElements(lines, existingContainers)
  397. // skip header
  398. lines = lines[1:]
  399. assert.Equal(c, len(lines), 3, "There should be 3 running container, got %d", len(lines))
  400. for _, line := range lines {
  401. f := strings.Fields(line)
  402. switch f[0] {
  403. case id1:
  404. c.Assert(f[1], checker.Equals, "busybox", check.Commentf("Expected %s tag for id %s, got %s", "busybox", id1, f[1]))
  405. case id2:
  406. c.Assert(f[1], checker.Equals, tag, check.Commentf("Expected %s tag for id %s, got %s", tag, id2, f[1]))
  407. case id3:
  408. c.Assert(f[1], checker.Equals, imageID, check.Commentf("Expected %s imageID for id %s, got %s", tag, id3, f[1]))
  409. default:
  410. c.Fatalf("Unexpected id %s, expected %s and %s and %s", f[0], id1, id2, id3)
  411. }
  412. }
  413. }
  414. func (s *DockerSuite) TestPsListContainersFilterCreated(c *check.C) {
  415. // create a container
  416. out, _ := dockerCmd(c, "create", "busybox")
  417. cID := strings.TrimSpace(out)
  418. shortCID := cID[:12]
  419. // Make sure it DOESN'T show up w/o a '-a' for normal 'ps'
  420. out, _ = dockerCmd(c, "ps", "-q")
  421. c.Assert(out, checker.Not(checker.Contains), shortCID, check.Commentf("Should have not seen '%s' in ps output:\n%s", shortCID, out))
  422. // Make sure it DOES show up as 'Created' for 'ps -a'
  423. out, _ = dockerCmd(c, "ps", "-a")
  424. hits := 0
  425. for _, line := range strings.Split(out, "\n") {
  426. if !strings.Contains(line, shortCID) {
  427. continue
  428. }
  429. hits++
  430. c.Assert(line, checker.Contains, "Created", check.Commentf("Missing 'Created' on '%s'", line))
  431. }
  432. c.Assert(hits, checker.Equals, 1, check.Commentf("Should have seen '%s' in ps -a output once:%d\n%s", shortCID, hits, out))
  433. // filter containers by 'create' - note, no -a needed
  434. out, _ = dockerCmd(c, "ps", "-q", "-f", "status=created")
  435. containerOut := strings.TrimSpace(out)
  436. assert.Assert(c, strings.HasPrefix(cID, containerOut))
  437. }
  438. // Test for GitHub issue #12595
  439. func (s *DockerSuite) TestPsImageIDAfterUpdate(c *check.C) {
  440. // TODO: Investigate why this fails on Windows to Windows CI further.
  441. testRequires(c, DaemonIsLinux)
  442. originalImageName := "busybox:TestPsImageIDAfterUpdate-original"
  443. updatedImageName := "busybox:TestPsImageIDAfterUpdate-updated"
  444. existingContainers := ExistingContainerIDs(c)
  445. icmd.RunCommand(dockerBinary, "tag", "busybox:latest", originalImageName).Assert(c, icmd.Success)
  446. originalImageID := getIDByName(c, originalImageName)
  447. result := icmd.RunCommand(dockerBinary, append([]string{"run", "-d", originalImageName}, sleepCommandForDaemonPlatform()...)...)
  448. result.Assert(c, icmd.Success)
  449. containerID := strings.TrimSpace(result.Combined())
  450. result = icmd.RunCommand(dockerBinary, "ps", "--no-trunc")
  451. result.Assert(c, icmd.Success)
  452. lines := strings.Split(strings.TrimSpace(string(result.Combined())), "\n")
  453. lines = RemoveLinesForExistingElements(lines, existingContainers)
  454. // skip header
  455. lines = lines[1:]
  456. c.Assert(len(lines), checker.Equals, 1)
  457. for _, line := range lines {
  458. f := strings.Fields(line)
  459. c.Assert(f[1], checker.Equals, originalImageName)
  460. }
  461. icmd.RunCommand(dockerBinary, "commit", containerID, updatedImageName).Assert(c, icmd.Success)
  462. icmd.RunCommand(dockerBinary, "tag", updatedImageName, originalImageName).Assert(c, icmd.Success)
  463. result = icmd.RunCommand(dockerBinary, "ps", "--no-trunc")
  464. result.Assert(c, icmd.Success)
  465. lines = strings.Split(strings.TrimSpace(string(result.Combined())), "\n")
  466. lines = RemoveLinesForExistingElements(lines, existingContainers)
  467. // skip header
  468. lines = lines[1:]
  469. c.Assert(len(lines), checker.Equals, 1)
  470. for _, line := range lines {
  471. f := strings.Fields(line)
  472. c.Assert(f[1], checker.Equals, originalImageID)
  473. }
  474. }
  475. func (s *DockerSuite) TestPsNotShowPortsOfStoppedContainer(c *check.C) {
  476. testRequires(c, DaemonIsLinux)
  477. dockerCmd(c, "run", "--name=foo", "-d", "-p", "5000:5000", "busybox", "top")
  478. c.Assert(waitRun("foo"), checker.IsNil)
  479. out, _ := dockerCmd(c, "ps")
  480. lines := strings.Split(strings.TrimSpace(string(out)), "\n")
  481. expected := "0.0.0.0:5000->5000/tcp"
  482. fields := strings.Fields(lines[1])
  483. c.Assert(fields[len(fields)-2], checker.Equals, expected, check.Commentf("Expected: %v, got: %v", expected, fields[len(fields)-2]))
  484. dockerCmd(c, "kill", "foo")
  485. dockerCmd(c, "wait", "foo")
  486. out, _ = dockerCmd(c, "ps", "-l")
  487. lines = strings.Split(strings.TrimSpace(string(out)), "\n")
  488. fields = strings.Fields(lines[1])
  489. c.Assert(fields[len(fields)-2], checker.Not(checker.Equals), expected, check.Commentf("Should not got %v", expected))
  490. }
  491. func (s *DockerSuite) TestPsShowMounts(c *check.C) {
  492. existingContainers := ExistingContainerNames(c)
  493. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  494. mp := prefix + slash + "test"
  495. dockerCmd(c, "volume", "create", "ps-volume-test")
  496. // volume mount containers
  497. runSleepingContainer(c, "--name=volume-test-1", "--volume", "ps-volume-test:"+mp)
  498. c.Assert(waitRun("volume-test-1"), checker.IsNil)
  499. runSleepingContainer(c, "--name=volume-test-2", "--volume", mp)
  500. c.Assert(waitRun("volume-test-2"), checker.IsNil)
  501. // bind mount container
  502. var bindMountSource string
  503. var bindMountDestination string
  504. if DaemonIsWindows() {
  505. bindMountSource = "c:\\"
  506. bindMountDestination = "c:\\t"
  507. } else {
  508. bindMountSource = "/tmp"
  509. bindMountDestination = "/t"
  510. }
  511. runSleepingContainer(c, "--name=bind-mount-test", "-v", bindMountSource+":"+bindMountDestination)
  512. c.Assert(waitRun("bind-mount-test"), checker.IsNil)
  513. out, _ := dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}")
  514. lines := strings.Split(strings.TrimSpace(string(out)), "\n")
  515. lines = RemoveLinesForExistingElements(lines, existingContainers)
  516. assert.Equal(c, len(lines), 3)
  517. fields := strings.Fields(lines[0])
  518. assert.Equal(c, len(fields), 2)
  519. c.Assert(fields[0], checker.Equals, "bind-mount-test")
  520. c.Assert(fields[1], checker.Equals, bindMountSource)
  521. fields = strings.Fields(lines[1])
  522. assert.Equal(c, len(fields), 2)
  523. anonymousVolumeID := fields[1]
  524. fields = strings.Fields(lines[2])
  525. c.Assert(fields[1], checker.Equals, "ps-volume-test")
  526. // filter by volume name
  527. out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=ps-volume-test")
  528. lines = strings.Split(strings.TrimSpace(string(out)), "\n")
  529. lines = RemoveLinesForExistingElements(lines, existingContainers)
  530. assert.Equal(c, len(lines), 1)
  531. fields = strings.Fields(lines[0])
  532. c.Assert(fields[1], checker.Equals, "ps-volume-test")
  533. // empty results filtering by unknown volume
  534. out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=this-volume-should-not-exist")
  535. c.Assert(strings.TrimSpace(string(out)), checker.HasLen, 0)
  536. // filter by mount destination
  537. out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+mp)
  538. lines = strings.Split(strings.TrimSpace(string(out)), "\n")
  539. lines = RemoveLinesForExistingElements(lines, existingContainers)
  540. assert.Equal(c, len(lines), 2)
  541. fields = strings.Fields(lines[0])
  542. c.Assert(fields[1], checker.Equals, anonymousVolumeID)
  543. fields = strings.Fields(lines[1])
  544. c.Assert(fields[1], checker.Equals, "ps-volume-test")
  545. // filter by bind mount source
  546. out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountSource)
  547. lines = strings.Split(strings.TrimSpace(string(out)), "\n")
  548. lines = RemoveLinesForExistingElements(lines, existingContainers)
  549. assert.Equal(c, len(lines), 1)
  550. fields = strings.Fields(lines[0])
  551. assert.Equal(c, len(fields), 2)
  552. c.Assert(fields[0], checker.Equals, "bind-mount-test")
  553. c.Assert(fields[1], checker.Equals, bindMountSource)
  554. // filter by bind mount destination
  555. out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountDestination)
  556. lines = strings.Split(strings.TrimSpace(string(out)), "\n")
  557. lines = RemoveLinesForExistingElements(lines, existingContainers)
  558. assert.Equal(c, len(lines), 1)
  559. fields = strings.Fields(lines[0])
  560. assert.Equal(c, len(fields), 2)
  561. c.Assert(fields[0], checker.Equals, "bind-mount-test")
  562. c.Assert(fields[1], checker.Equals, bindMountSource)
  563. // empty results filtering by unknown mount point
  564. out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+prefix+slash+"this-path-was-never-mounted")
  565. c.Assert(strings.TrimSpace(string(out)), checker.HasLen, 0)
  566. }
  567. func (s *DockerSuite) TestPsListContainersFilterNetwork(c *check.C) {
  568. existing := ExistingContainerIDs(c)
  569. // TODO default network on Windows is not called "bridge", and creating a
  570. // custom network fails on Windows fails with "Error response from daemon: plugin not found")
  571. testRequires(c, DaemonIsLinux)
  572. // create some containers
  573. runSleepingContainer(c, "--net=bridge", "--name=onbridgenetwork")
  574. runSleepingContainer(c, "--net=none", "--name=onnonenetwork")
  575. // Filter docker ps on non existing network
  576. out, _ := dockerCmd(c, "ps", "--filter", "network=doesnotexist")
  577. containerOut := strings.TrimSpace(string(out))
  578. lines := strings.Split(containerOut, "\n")
  579. // skip header
  580. lines = lines[1:]
  581. // ps output should have no containers
  582. assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 0)
  583. // Filter docker ps on network bridge
  584. out, _ = dockerCmd(c, "ps", "--filter", "network=bridge")
  585. containerOut = strings.TrimSpace(string(out))
  586. lines = strings.Split(containerOut, "\n")
  587. // skip header
  588. lines = lines[1:]
  589. // ps output should have only one container
  590. assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 1)
  591. // Making sure onbridgenetwork is on the output
  592. c.Assert(containerOut, checker.Contains, "onbridgenetwork", check.Commentf("Missing the container on network\n"))
  593. // Filter docker ps on networks bridge and none
  594. out, _ = dockerCmd(c, "ps", "--filter", "network=bridge", "--filter", "network=none")
  595. containerOut = strings.TrimSpace(string(out))
  596. lines = strings.Split(containerOut, "\n")
  597. // skip header
  598. lines = lines[1:]
  599. //ps output should have both the containers
  600. assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 2)
  601. // Making sure onbridgenetwork and onnonenetwork is on the output
  602. c.Assert(containerOut, checker.Contains, "onnonenetwork", check.Commentf("Missing the container on none network\n"))
  603. c.Assert(containerOut, checker.Contains, "onbridgenetwork", check.Commentf("Missing the container on bridge network\n"))
  604. nwID, _ := dockerCmd(c, "network", "inspect", "--format", "{{.ID}}", "bridge")
  605. // Filter by network ID
  606. out, _ = dockerCmd(c, "ps", "--filter", "network="+nwID)
  607. containerOut = strings.TrimSpace(string(out))
  608. assert.Assert(c, is.Contains(containerOut, "onbridgenetwork"))
  609. // Filter by partial network ID
  610. partialnwID := string(nwID[0:4])
  611. out, _ = dockerCmd(c, "ps", "--filter", "network="+partialnwID)
  612. containerOut = strings.TrimSpace(string(out))
  613. lines = strings.Split(containerOut, "\n")
  614. // skip header
  615. lines = lines[1:]
  616. // ps output should have only one container
  617. assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 1)
  618. // Making sure onbridgenetwork is on the output
  619. c.Assert(containerOut, checker.Contains, "onbridgenetwork", check.Commentf("Missing the container on network\n"))
  620. }
  621. func (s *DockerSuite) TestPsByOrder(c *check.C) {
  622. out := runSleepingContainer(c, "--name", "xyz-abc")
  623. container1 := strings.TrimSpace(out)
  624. out = runSleepingContainer(c, "--name", "xyz-123")
  625. container2 := strings.TrimSpace(out)
  626. runSleepingContainer(c, "--name", "789-abc")
  627. runSleepingContainer(c, "--name", "789-123")
  628. // Run multiple time should have the same result
  629. out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined()
  630. assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%s\n%s", container2, container1))
  631. // Run multiple time should have the same result
  632. out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined()
  633. assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%s\n%s", container2, container1))
  634. }
  635. func (s *DockerSuite) TestPsListContainersFilterPorts(c *check.C) {
  636. testRequires(c, DaemonIsLinux)
  637. existingContainers := ExistingContainerIDs(c)
  638. out, _ := dockerCmd(c, "run", "-d", "--publish=80", "busybox", "top")
  639. id1 := strings.TrimSpace(out)
  640. out, _ = dockerCmd(c, "run", "-d", "--expose=8080", "busybox", "top")
  641. id2 := strings.TrimSpace(out)
  642. out, _ = dockerCmd(c, "ps", "--no-trunc", "-q")
  643. c.Assert(strings.TrimSpace(out), checker.Contains, id1)
  644. c.Assert(strings.TrimSpace(out), checker.Contains, id2)
  645. out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-8080/udp")
  646. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id1)
  647. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id2)
  648. out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8081")
  649. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id1)
  650. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id2)
  651. out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-81")
  652. assert.Equal(c, strings.TrimSpace(out), id1)
  653. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id2)
  654. out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=80/tcp")
  655. assert.Equal(c, strings.TrimSpace(out), id1)
  656. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id2)
  657. out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8080/tcp")
  658. out = RemoveOutputForExistingElements(out, existingContainers)
  659. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id1)
  660. assert.Equal(c, strings.TrimSpace(out), id2)
  661. }
  662. func (s *DockerSuite) TestPsNotShowLinknamesOfDeletedContainer(c *check.C) {
  663. testRequires(c, DaemonIsLinux, MinimumAPIVersion("1.31"))
  664. existingContainers := ExistingContainerNames(c)
  665. dockerCmd(c, "create", "--name=aaa", "busybox", "top")
  666. dockerCmd(c, "create", "--name=bbb", "--link=aaa", "busybox", "top")
  667. out, _ := dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}")
  668. lines := strings.Split(strings.TrimSpace(string(out)), "\n")
  669. lines = RemoveLinesForExistingElements(lines, existingContainers)
  670. expected := []string{"bbb", "aaa,bbb/aaa"}
  671. var names []string
  672. names = append(names, lines...)
  673. assert.Assert(c, is.DeepEqual(names, expected), "Expected array with non-truncated names: %v, got: %v", expected, names)
  674. dockerCmd(c, "rm", "bbb")
  675. out, _ = dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}")
  676. out = RemoveOutputForExistingElements(out, existingContainers)
  677. assert.Equal(c, strings.TrimSpace(out), "aaa")
  678. }