docker_cli_inspect_test.go 17 KB

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