docker_cli_inspect_test.go 17 KB

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