docker_cli_inspect_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "strconv"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/integration-cli/cli"
  14. "github.com/docker/docker/internal/testutils/specialimage"
  15. "gotest.tools/v3/assert"
  16. "gotest.tools/v3/icmd"
  17. )
  18. type DockerCLIInspectSuite struct {
  19. ds *DockerSuite
  20. }
  21. func (s *DockerCLIInspectSuite) TearDownTest(ctx context.Context, c *testing.T) {
  22. s.ds.TearDownTest(ctx, c)
  23. }
  24. func (s *DockerCLIInspectSuite) OnTimeout(c *testing.T) {
  25. s.ds.OnTimeout(c)
  26. }
  27. func (s *DockerCLIInspectSuite) TestInspectImage(c *testing.T) {
  28. testRequires(c, DaemonIsLinux)
  29. imageTest := loadSpecialImage(c, specialimage.EmptyFS)
  30. // It is important that this ID remain stable. If a code change causes
  31. // it to be different, this is equivalent to a cache bust when pulling
  32. // a legacy-format manifest. If the check at the end of this function
  33. // fails, fix the difference in the image serialization instead of
  34. // updating this hash.
  35. imageTestID := "sha256:11f64303f0f7ffdc71f001788132bca5346831939a956e3e975c93267d89a16d"
  36. if containerdSnapshotterEnabled() {
  37. // Under containerd ID of the image is the digest of the manifest list.
  38. imageTestID = "sha256:e43ca824363c5c56016f6ede3a9035afe0e9bd43333215e0b0bde6193969725d"
  39. }
  40. id := inspectField(c, imageTest, "Id")
  41. assert.Equal(c, id, imageTestID)
  42. }
  43. func (s *DockerCLIInspectSuite) TestInspectInt64(c *testing.T) {
  44. cli.DockerCmd(c, "run", "-d", "-m=300M", "--name", "inspectTest", "busybox", "true")
  45. inspectOut := inspectField(c, "inspectTest", "HostConfig.Memory")
  46. assert.Equal(c, inspectOut, "314572800")
  47. }
  48. func (s *DockerCLIInspectSuite) TestInspectDefault(c *testing.T) {
  49. // Both the container and image are named busybox. docker inspect will fetch the container JSON.
  50. // If the container JSON is not available, it will go for the image JSON.
  51. out := cli.DockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true").Stdout()
  52. containerID := strings.TrimSpace(out)
  53. inspectOut := inspectField(c, "busybox", "Id")
  54. assert.Equal(c, strings.TrimSpace(inspectOut), containerID)
  55. }
  56. func (s *DockerCLIInspectSuite) TestInspectStatus(c *testing.T) {
  57. id := runSleepingContainer(c, "-d")
  58. inspectOut := inspectField(c, id, "State.Status")
  59. assert.Equal(c, inspectOut, "running")
  60. // Windows does not support pause/unpause on Windows Server Containers.
  61. // (RS1 does for Hyper-V Containers, but production CI is not setup for that)
  62. if testEnv.DaemonInfo.OSType != "windows" {
  63. cli.DockerCmd(c, "pause", id)
  64. inspectOut = inspectField(c, id, "State.Status")
  65. assert.Equal(c, inspectOut, "paused")
  66. cli.DockerCmd(c, "unpause", id)
  67. inspectOut = inspectField(c, id, "State.Status")
  68. assert.Equal(c, inspectOut, "running")
  69. }
  70. cli.DockerCmd(c, "stop", id)
  71. inspectOut = inspectField(c, id, "State.Status")
  72. assert.Equal(c, inspectOut, "exited")
  73. }
  74. func (s *DockerCLIInspectSuite) TestInspectTypeFlagContainer(c *testing.T) {
  75. // Both the container and image are named busybox. docker inspect will fetch container
  76. // JSON State.Running field. If the field is true, it's a container.
  77. runSleepingContainer(c, "--name=busybox", "-d")
  78. formatStr := "--format={{.State.Running}}"
  79. out := cli.DockerCmd(c, "inspect", "--type=container", formatStr, "busybox").Stdout()
  80. assert.Equal(c, out, "true\n") // not a container JSON
  81. }
  82. func (s *DockerCLIInspectSuite) TestInspectTypeFlagWithNoContainer(c *testing.T) {
  83. // Run this test on an image named busybox. docker inspect will try to fetch container
  84. // JSON. Since there is no container named busybox and --type=container, docker inspect will
  85. // not try to get the image JSON. It will throw an error.
  86. cli.DockerCmd(c, "run", "-d", "busybox", "true")
  87. _, _, err := dockerCmdWithError("inspect", "--type=container", "busybox")
  88. // docker inspect should fail, as there is no container named busybox
  89. assert.ErrorContains(c, err, "")
  90. }
  91. func (s *DockerCLIInspectSuite) TestInspectTypeFlagWithImage(c *testing.T) {
  92. // Both the container and image are named busybox. docker inspect will fetch image
  93. // JSON as --type=image. if there is no image with name busybox, docker inspect
  94. // will throw an error.
  95. cli.DockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true")
  96. out := cli.DockerCmd(c, "inspect", "--type=image", "busybox").Stdout()
  97. // not an image JSON
  98. assert.Assert(c, !strings.Contains(out, "State"))
  99. }
  100. func (s *DockerCLIInspectSuite) TestInspectTypeFlagWithInvalidValue(c *testing.T) {
  101. // Both the container and image are named busybox. docker inspect will fail
  102. // as --type=foobar is not a valid value for the flag.
  103. cli.DockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true")
  104. out, exitCode, err := dockerCmdWithError("inspect", "--type=foobar", "busybox")
  105. assert.Assert(c, err != nil, "%d", exitCode)
  106. assert.Equal(c, exitCode, 1, err)
  107. assert.Assert(c, strings.Contains(out, "not a valid value for --type"))
  108. }
  109. func (s *DockerCLIInspectSuite) TestInspectImageFilterInt(c *testing.T) {
  110. testRequires(c, DaemonIsLinux)
  111. imageTest := loadSpecialImage(c, specialimage.EmptyFS)
  112. out := inspectField(c, imageTest, "Size")
  113. size, err := strconv.Atoi(out)
  114. assert.Assert(c, err == nil, "failed to inspect size of the image: %s, %v", out, err)
  115. // now see if the size turns out to be the same
  116. formatStr := fmt.Sprintf("--format={{eq .Size %d}}", size)
  117. out = cli.DockerCmd(c, "inspect", formatStr, imageTest).Stdout()
  118. result, err := strconv.ParseBool(strings.TrimSuffix(out, "\n"))
  119. assert.NilError(c, err)
  120. assert.Equal(c, result, true)
  121. }
  122. func (s *DockerCLIInspectSuite) TestInspectContainerFilterInt(c *testing.T) {
  123. result := icmd.RunCmd(icmd.Cmd{
  124. Command: []string{dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat"},
  125. Stdin: strings.NewReader("blahblah"),
  126. })
  127. result.Assert(c, icmd.Success)
  128. out := result.Stdout()
  129. id := strings.TrimSpace(out)
  130. out = inspectField(c, id, "State.ExitCode")
  131. exitCode, err := strconv.Atoi(out)
  132. assert.Assert(c, err == nil, "failed to inspect exitcode of the container: %s, %v", out, err)
  133. // now get the exit code to verify
  134. formatStr := fmt.Sprintf("--format={{eq .State.ExitCode %d}}", exitCode)
  135. out = cli.DockerCmd(c, "inspect", formatStr, id).Stdout()
  136. inspectResult, err := strconv.ParseBool(strings.TrimSuffix(out, "\n"))
  137. assert.NilError(c, err)
  138. assert.Equal(c, inspectResult, true)
  139. }
  140. func (s *DockerCLIInspectSuite) TestInspectBindMountPoint(c *testing.T) {
  141. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  142. mopt := prefix + slash + "data:" + prefix + slash + "data"
  143. mode := ""
  144. if testEnv.DaemonInfo.OSType == "windows" {
  145. // Linux creates the host directory if it doesn't exist. Windows does not.
  146. os.Mkdir(`c:\data`, os.ModeDir)
  147. } else {
  148. mode = "z" // Relabel
  149. }
  150. if mode != "" {
  151. mopt += ":" + mode
  152. }
  153. cli.DockerCmd(c, "run", "-d", "--name", "test", "-v", mopt, "busybox", "cat")
  154. vol := inspectFieldJSON(c, "test", "Mounts")
  155. var mp []types.MountPoint
  156. err := json.Unmarshal([]byte(vol), &mp)
  157. assert.NilError(c, err)
  158. // check that there is only one mountpoint
  159. assert.Equal(c, len(mp), 1)
  160. m := mp[0]
  161. assert.Equal(c, m.Name, "")
  162. assert.Equal(c, m.Driver, "")
  163. assert.Equal(c, m.Source, prefix+slash+"data")
  164. assert.Equal(c, m.Destination, prefix+slash+"data")
  165. assert.Equal(c, m.Mode, mode)
  166. assert.Equal(c, m.RW, true)
  167. }
  168. func (s *DockerCLIInspectSuite) TestInspectNamedMountPoint(c *testing.T) {
  169. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  170. cli.DockerCmd(c, "run", "-d", "--name", "test", "-v", "data:"+prefix+slash+"data", "busybox", "cat")
  171. vol := inspectFieldJSON(c, "test", "Mounts")
  172. var mp []types.MountPoint
  173. err := json.Unmarshal([]byte(vol), &mp)
  174. assert.NilError(c, err)
  175. // check that there is only one mountpoint
  176. assert.Equal(c, len(mp), 1)
  177. m := mp[0]
  178. assert.Equal(c, m.Name, "data")
  179. assert.Equal(c, m.Driver, "local")
  180. assert.Assert(c, m.Source != "")
  181. assert.Equal(c, m.Destination, prefix+slash+"data")
  182. assert.Equal(c, m.RW, true)
  183. }
  184. // #14947
  185. func (s *DockerCLIInspectSuite) TestInspectTimesAsRFC3339Nano(c *testing.T) {
  186. out := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout()
  187. id := strings.TrimSpace(out)
  188. startedAt := inspectField(c, id, "State.StartedAt")
  189. finishedAt := inspectField(c, id, "State.FinishedAt")
  190. created := inspectField(c, id, "Created")
  191. _, err := time.Parse(time.RFC3339Nano, startedAt)
  192. assert.NilError(c, err)
  193. _, err = time.Parse(time.RFC3339Nano, finishedAt)
  194. assert.NilError(c, err)
  195. _, err = time.Parse(time.RFC3339Nano, created)
  196. assert.NilError(c, err)
  197. created = inspectField(c, "busybox", "Created")
  198. _, err = time.Parse(time.RFC3339Nano, created)
  199. assert.NilError(c, err)
  200. }
  201. // #15633
  202. func (s *DockerCLIInspectSuite) TestInspectLogConfigNoType(c *testing.T) {
  203. cli.DockerCmd(c, "create", "--name=test", "--log-opt", "max-file=42", "busybox")
  204. var logConfig container.LogConfig
  205. out := inspectFieldJSON(c, "test", "HostConfig.LogConfig")
  206. err := json.NewDecoder(strings.NewReader(out)).Decode(&logConfig)
  207. assert.Assert(c, err == nil, "%v", out)
  208. assert.Equal(c, logConfig.Type, "json-file")
  209. assert.Equal(c, logConfig.Config["max-file"], "42", fmt.Sprintf("%v", logConfig))
  210. }
  211. func (s *DockerCLIInspectSuite) TestInspectNoSizeFlagContainer(c *testing.T) {
  212. // Both the container and image are named busybox. docker inspect will fetch container
  213. // JSON SizeRw and SizeRootFs field. If there is no flag --size/-s, there are no size fields.
  214. runSleepingContainer(c, "--name=busybox", "-d")
  215. formatStr := "--format={{.SizeRw}},{{.SizeRootFs}}"
  216. out := cli.DockerCmd(c, "inspect", "--type=container", formatStr, "busybox").Stdout()
  217. assert.Equal(c, strings.TrimSpace(out), "<nil>,<nil>", fmt.Sprintf("Expected not to display size info: %s", out))
  218. }
  219. func (s *DockerCLIInspectSuite) TestInspectSizeFlagContainer(c *testing.T) {
  220. runSleepingContainer(c, "--name=busybox", "-d")
  221. formatStr := "--format='{{.SizeRw}},{{.SizeRootFs}}'"
  222. out := cli.DockerCmd(c, "inspect", "-s", "--type=container", formatStr, "busybox").Stdout()
  223. sz := strings.Split(out, ",")
  224. assert.Assert(c, strings.TrimSpace(sz[0]) != "<nil>")
  225. assert.Assert(c, strings.TrimSpace(sz[1]) != "<nil>")
  226. }
  227. func (s *DockerCLIInspectSuite) TestInspectTemplateError(c *testing.T) {
  228. // Template parsing error for both the container and image.
  229. runSleepingContainer(c, "--name=container1", "-d")
  230. out, _, err := dockerCmdWithError("inspect", "--type=container", "--format='Format container: {{.ThisDoesNotExist}}'", "container1")
  231. assert.Assert(c, err != nil)
  232. assert.Assert(c, strings.Contains(out, "Template parsing error"))
  233. out, _, err = dockerCmdWithError("inspect", "--type=image", "--format='Format container: {{.ThisDoesNotExist}}'", "busybox")
  234. assert.Assert(c, err != nil)
  235. assert.Assert(c, strings.Contains(out, "Template parsing error"))
  236. }
  237. func (s *DockerCLIInspectSuite) TestInspectJSONFields(c *testing.T) {
  238. runSleepingContainer(c, "--name=busybox", "-d")
  239. out, _, err := dockerCmdWithError("inspect", "--type=container", "--format={{.HostConfig.Dns}}", "busybox")
  240. assert.NilError(c, err)
  241. assert.Equal(c, out, "[]\n")
  242. }
  243. func (s *DockerCLIInspectSuite) TestInspectByPrefix(c *testing.T) {
  244. id := inspectField(c, "busybox", "Id")
  245. assert.Assert(c, strings.HasPrefix(id, "sha256:"))
  246. id2 := inspectField(c, id[:12], "Id")
  247. assert.Equal(c, id, id2)
  248. id3 := inspectField(c, strings.TrimPrefix(id, "sha256:")[:12], "Id")
  249. assert.Equal(c, id, id3)
  250. }
  251. func (s *DockerCLIInspectSuite) TestInspectStopWhenNotFound(c *testing.T) {
  252. runSleepingContainer(c, "--name=busybox1", "-d")
  253. runSleepingContainer(c, "--name=busybox2", "-d")
  254. result := dockerCmdWithResult("inspect", "--type=container", "--format='{{.Name}}'", "busybox1", "busybox2", "missing")
  255. assert.Assert(c, result.Error != nil)
  256. assert.Assert(c, strings.Contains(result.Stdout(), "busybox1"))
  257. assert.Assert(c, strings.Contains(result.Stdout(), "busybox2"))
  258. assert.Assert(c, strings.Contains(result.Stderr(), "Error: No such container: missing"))
  259. // test inspect would not fast fail
  260. result = dockerCmdWithResult("inspect", "--type=container", "--format='{{.Name}}'", "missing", "busybox1", "busybox2")
  261. assert.Assert(c, result.Error != nil)
  262. assert.Assert(c, strings.Contains(result.Stdout(), "busybox1"))
  263. assert.Assert(c, strings.Contains(result.Stdout(), "busybox2"))
  264. assert.Assert(c, strings.Contains(result.Stderr(), "Error: No such container: missing"))
  265. }
  266. func (s *DockerCLIInspectSuite) TestInspectHistory(c *testing.T) {
  267. cli.DockerCmd(c, "run", "--name=testcont", "busybox", "echo", "hello")
  268. cli.DockerCmd(c, "commit", "-m", "test comment", "testcont", "testimg")
  269. out, _, err := dockerCmdWithError("inspect", "--format='{{.Comment}}'", "testimg")
  270. assert.NilError(c, err)
  271. assert.Assert(c, strings.Contains(out, "test comment"))
  272. }
  273. func (s *DockerCLIInspectSuite) TestInspectContainerNetworkDefault(c *testing.T) {
  274. testRequires(c, DaemonIsLinux)
  275. contName := "test1"
  276. cli.DockerCmd(c, "run", "--name", contName, "-d", "busybox", "top")
  277. netOut := cli.DockerCmd(c, "network", "inspect", "--format={{.ID}}", "bridge").Stdout()
  278. out := inspectField(c, contName, "NetworkSettings.Networks")
  279. assert.Assert(c, strings.Contains(out, "bridge"))
  280. out = inspectField(c, contName, "NetworkSettings.Networks.bridge.NetworkID")
  281. assert.Equal(c, strings.TrimSpace(out), strings.TrimSpace(netOut))
  282. }
  283. func (s *DockerCLIInspectSuite) TestInspectContainerNetworkCustom(c *testing.T) {
  284. testRequires(c, DaemonIsLinux)
  285. netOut := cli.DockerCmd(c, "network", "create", "net1").Stdout()
  286. cli.DockerCmd(c, "run", "--name=container1", "--net=net1", "-d", "busybox", "top")
  287. out := inspectField(c, "container1", "NetworkSettings.Networks")
  288. assert.Assert(c, strings.Contains(out, "net1"))
  289. out = inspectField(c, "container1", "NetworkSettings.Networks.net1.NetworkID")
  290. assert.Equal(c, strings.TrimSpace(out), strings.TrimSpace(netOut))
  291. }
  292. func (s *DockerCLIInspectSuite) TestInspectRootFS(c *testing.T) {
  293. out, _, err := dockerCmdWithError("inspect", "busybox")
  294. assert.NilError(c, err)
  295. var imageJSON []types.ImageInspect
  296. err = json.Unmarshal([]byte(out), &imageJSON)
  297. assert.NilError(c, err)
  298. assert.Assert(c, len(imageJSON[0].RootFS.Layers) >= 1)
  299. }
  300. func (s *DockerCLIInspectSuite) TestInspectAmpersand(c *testing.T) {
  301. testRequires(c, DaemonIsLinux)
  302. name := "test"
  303. out := cli.DockerCmd(c, "run", "--name", name, "--env", `TEST_ENV="soanni&rtr"`, "busybox", "env").Stdout()
  304. assert.Assert(c, strings.Contains(out, `soanni&rtr`))
  305. out = cli.DockerCmd(c, "inspect", name).Stdout()
  306. assert.Assert(c, strings.Contains(out, `soanni&rtr`))
  307. }
  308. func (s *DockerCLIInspectSuite) TestInspectPlugin(c *testing.T) {
  309. testRequires(c, DaemonIsLinux, IsAmd64, Network)
  310. _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag)
  311. assert.NilError(c, err)
  312. out, _, err := dockerCmdWithError("inspect", "--type", "plugin", "--format", "{{.Name}}", pNameWithTag)
  313. assert.NilError(c, err)
  314. assert.Equal(c, strings.TrimSpace(out), pNameWithTag)
  315. out, _, err = dockerCmdWithError("inspect", "--format", "{{.Name}}", pNameWithTag)
  316. assert.NilError(c, err)
  317. assert.Equal(c, strings.TrimSpace(out), pNameWithTag)
  318. // Even without tag the inspect still work
  319. out, _, err = dockerCmdWithError("inspect", "--type", "plugin", "--format", "{{.Name}}", pNameWithTag)
  320. assert.NilError(c, err)
  321. assert.Equal(c, strings.TrimSpace(out), pNameWithTag)
  322. out, _, err = dockerCmdWithError("inspect", "--format", "{{.Name}}", pNameWithTag)
  323. assert.NilError(c, err)
  324. assert.Equal(c, strings.TrimSpace(out), pNameWithTag)
  325. _, _, err = dockerCmdWithError("plugin", "disable", pNameWithTag)
  326. assert.NilError(c, err)
  327. out, _, err = dockerCmdWithError("plugin", "remove", pNameWithTag)
  328. assert.NilError(c, err)
  329. assert.Assert(c, strings.Contains(out, pNameWithTag))
  330. }
  331. // Test case for 29185
  332. func (s *DockerCLIInspectSuite) TestInspectUnknownObject(c *testing.T) {
  333. // This test should work on both Windows and Linux
  334. out, _, err := dockerCmdWithError("inspect", "foobar")
  335. assert.ErrorContains(c, err, "")
  336. assert.Assert(c, strings.Contains(out, "Error: No such object: foobar"))
  337. assert.ErrorContains(c, err, "Error: No such object: foobar")
  338. }