docker_cli_ps_test.go 37 KB

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