github.com/rish1988/moby@v25.0.2+incompatible/integration-cli/docker_cli_inspect_test.go (about)

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