github.com/adityamillind98/moby@v23.0.0-rc.4+incompatible/integration-cli/docker_cli_inspect_test.go (about)

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