From 66cf6e3a7a3c6e661bcdf78aec0a1347fca80b5e Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 19 Jan 2024 12:31:25 +0100 Subject: [PATCH 1/4] rename "image" vars to prevent conflicts with imports We have many "image" packages, so these vars easily conflict/shadow imports. Let's rename them (and in some cases use a const) to prevent that. Signed-off-by: Sebastiaan van Stijn --- .../distribution/distribution_routes.go | 6 ++--- api/server/router/image/image_routes.go | 4 ++-- client/distribution_inspect.go | 8 +++---- daemon/cluster/convert/service_test.go | 8 +++---- integration-cli/docker_api_images_test.go | 8 +++---- integration-cli/docker_cli_build_test.go | 12 +++++----- integration-cli/docker_cli_create_test.go | 6 ++--- integration-cli/docker_cli_events_test.go | 12 +++++----- integration-cli/docker_cli_images_test.go | 4 ++-- integration-cli/docker_cli_import_test.go | 22 ++++++++--------- integration-cli/docker_cli_rmi_test.go | 16 ++++++------- integration-cli/docker_cli_run_test.go | 24 +++++++++---------- integration-cli/docker_cli_swarm_unix_test.go | 12 +++++----- integration-cli/docker_cli_volume_test.go | 24 +++++++++---------- integration/build/build_test.go | 18 +++++++------- integration/image/remove_unix_test.go | 8 +++---- runconfig/config_test.go | 10 ++++---- testutil/environment/clean.go | 8 +++---- testutil/environment/protect.go | 4 ++-- 19 files changed, 107 insertions(+), 107 deletions(-) diff --git a/api/server/router/distribution/distribution_routes.go b/api/server/router/distribution/distribution_routes.go index 9fb0f47a92ec8..7b9d1284365ba 100644 --- a/api/server/router/distribution/distribution_routes.go +++ b/api/server/router/distribution/distribution_routes.go @@ -24,10 +24,10 @@ func (s *distributionRouter) getDistributionInfo(ctx context.Context, w http.Res w.Header().Set("Content-Type", "application/json") - image := vars["name"] + imgName := vars["name"] // TODO why is reference.ParseAnyReference() / reference.ParseNormalizedNamed() not using the reference.ErrTagInvalidFormat (and so on) errors? - ref, err := reference.ParseAnyReference(image) + ref, err := reference.ParseAnyReference(imgName) if err != nil { return errdefs.InvalidParameter(err) } @@ -37,7 +37,7 @@ func (s *distributionRouter) getDistributionInfo(ctx context.Context, w http.Res // full image ID return errors.Errorf("no manifest found for full image ID") } - return errdefs.InvalidParameter(errors.Errorf("unknown image reference format: %s", image)) + return errdefs.InvalidParameter(errors.Errorf("unknown image reference format: %s", imgName)) } // For a search it is not an error if no auth was given. Ignore invalid diff --git a/api/server/router/image/image_routes.go b/api/server/router/image/image_routes.go index 7921d49575de4..7a8159a9ad6d0 100644 --- a/api/server/router/image/image_routes.go +++ b/api/server/router/image/image_routes.go @@ -72,9 +72,9 @@ func (ir *imageRouter) postImagesCreate(ctx context.Context, w http.ResponseWrit // Special case: "pull -a" may send an image name with a // trailing :. This is ugly, but let's not break API // compatibility. - image := strings.TrimSuffix(img, ":") + imgName := strings.TrimSuffix(img, ":") - ref, err := reference.ParseNormalizedNamed(image) + ref, err := reference.ParseNormalizedNamed(imgName) if err != nil { return errdefs.InvalidParameter(err) } diff --git a/client/distribution_inspect.go b/client/distribution_inspect.go index 68ef31b78b07a..68e6ec5ed6bff 100644 --- a/client/distribution_inspect.go +++ b/client/distribution_inspect.go @@ -10,11 +10,11 @@ import ( ) // DistributionInspect returns the image digest with the full manifest. -func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registry.DistributionInspect, error) { +func (cli *Client) DistributionInspect(ctx context.Context, imageRef, encodedRegistryAuth string) (registry.DistributionInspect, error) { // Contact the registry to retrieve digest and platform information var distributionInspect registry.DistributionInspect - if image == "" { - return distributionInspect, objectNotFoundError{object: "distribution", id: image} + if imageRef == "" { + return distributionInspect, objectNotFoundError{object: "distribution", id: imageRef} } if err := cli.NewVersionError(ctx, "1.30", "distribution inspect"); err != nil { @@ -28,7 +28,7 @@ func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegist } } - resp, err := cli.get(ctx, "/distribution/"+image+"/json", url.Values{}, headers) + resp, err := cli.get(ctx, "/distribution/"+imageRef+"/json", url.Values{}, headers) defer ensureReaderClosed(resp) if err != nil { return distributionInspect, err diff --git a/daemon/cluster/convert/service_test.go b/daemon/cluster/convert/service_test.go index dd0520e4c49db..12907f3115d42 100644 --- a/daemon/cluster/convert/service_test.go +++ b/daemon/cluster/convert/service_test.go @@ -109,11 +109,11 @@ func TestServiceConvertToGRPCGenericRuntimePlugin(t *testing.T) { } func TestServiceConvertToGRPCContainerRuntime(t *testing.T) { - image := "alpine:latest" + const imgName = "alpine:latest" s := swarmtypes.ServiceSpec{ TaskTemplate: swarmtypes.TaskSpec{ ContainerSpec: &swarmtypes.ContainerSpec{ - Image: image, + Image: imgName, }, }, Mode: swarmtypes.ServiceMode{ @@ -131,8 +131,8 @@ func TestServiceConvertToGRPCContainerRuntime(t *testing.T) { t.Fatal("expected type swarmapi.TaskSpec_Container") } - if v.Container.Image != image { - t.Fatalf("expected image %s; received %s", image, v.Container.Image) + if v.Container.Image != imgName { + t.Fatalf("expected image %s; received %s", imgName, v.Container.Image) } } diff --git a/integration-cli/docker_api_images_test.go b/integration-cli/docker_api_images_test.go index b75cb79b26a59..f7ac5558553ab 100644 --- a/integration-cli/docker_api_images_test.go +++ b/integration-cli/docker_api_images_test.go @@ -132,8 +132,8 @@ func (s *DockerAPISuite) TestAPIImagesSizeCompatibility(c *testing.T) { images, err := apiclient.ImageList(testutil.GetContext(c), types.ImageListOptions{}) assert.NilError(c, err) assert.Assert(c, len(images) != 0) - for _, image := range images { - assert.Assert(c, image.Size != int64(-1)) + for _, img := range images { + assert.Assert(c, img.Size != int64(-1)) } apiclient, err = client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.24")) @@ -143,7 +143,7 @@ func (s *DockerAPISuite) TestAPIImagesSizeCompatibility(c *testing.T) { v124Images, err := apiclient.ImageList(testutil.GetContext(c), types.ImageListOptions{}) assert.NilError(c, err) assert.Assert(c, len(v124Images) != 0) - for _, image := range v124Images { - assert.Assert(c, image.Size != int64(-1)) + for _, img := range v124Images { + assert.Assert(c, img.Size != int64(-1)) } } diff --git a/integration-cli/docker_cli_build_test.go b/integration-cli/docker_cli_build_test.go index e6f9ff536fdb1..15f1c6b714b01 100644 --- a/integration-cli/docker_cli_build_test.go +++ b/integration-cli/docker_cli_build_test.go @@ -6044,22 +6044,22 @@ func (s *DockerCLIBuildSuite) TestBuildWindowsEnvCaseInsensitive(c *testing.T) { // Test case for 29667 func (s *DockerCLIBuildSuite) TestBuildWorkdirImageCmd(c *testing.T) { - image := "testworkdirimagecmd" - buildImageSuccessfully(c, image, build.WithDockerfile(` + imgName := "testworkdirimagecmd" + buildImageSuccessfully(c, imgName, build.WithDockerfile(` FROM busybox WORKDIR /foo/bar `)) - out := cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image).Stdout() + out := cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", imgName).Stdout() assert.Equal(c, strings.TrimSpace(out), `["sh"]`) - image = "testworkdirlabelimagecmd" - buildImageSuccessfully(c, image, build.WithDockerfile(` + imgName = "testworkdirlabelimagecmd" + buildImageSuccessfully(c, imgName, build.WithDockerfile(` FROM busybox WORKDIR /foo/bar LABEL a=b `)) - out = cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image).Stdout() + out = cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", imgName).Stdout() assert.Equal(c, strings.TrimSpace(out), `["sh"]`) } diff --git a/integration-cli/docker_cli_create_test.go b/integration-cli/docker_cli_create_test.go index f3912d805d669..38e0a31c62310 100644 --- a/integration-cli/docker_cli_create_test.go +++ b/integration-cli/docker_cli_create_test.go @@ -195,12 +195,12 @@ func (s *DockerCLICreateSuite) TestCreateLabelFromImage(c *testing.T) { } func (s *DockerCLICreateSuite) TestCreateHostnameWithNumber(c *testing.T) { - image := "busybox" + imgName := "busybox" // Busybox on Windows does not implement hostname command if testEnv.DaemonInfo.OSType == "windows" { - image = testEnv.PlatformDefaults.BaseImage + imgName = testEnv.PlatformDefaults.BaseImage } - out := cli.DockerCmd(c, "run", "-h", "web.0", image, "hostname").Combined() + out := cli.DockerCmd(c, "run", "-h", "web.0", imgName, "hostname").Combined() assert.Equal(c, strings.TrimSpace(out), "web.0", "hostname not set, expected `web.0`, got: %s", out) } diff --git a/integration-cli/docker_cli_events_test.go b/integration-cli/docker_cli_events_test.go index 1e655e666ac06..e0304af750afd 100644 --- a/integration-cli/docker_cli_events_test.go +++ b/integration-cli/docker_cli_events_test.go @@ -67,9 +67,9 @@ func (s *DockerCLIEventSuite) TestEventsTimestampFormats(c *testing.T) { } func (s *DockerCLIEventSuite) TestEventsUntag(c *testing.T) { - image := "busybox" - cli.DockerCmd(c, "tag", image, "utest:tag1") - cli.DockerCmd(c, "tag", image, "utest:tag2") + const imgName = "busybox" + cli.DockerCmd(c, "tag", imgName, "utest:tag1") + cli.DockerCmd(c, "tag", imgName, "utest:tag2") cli.DockerCmd(c, "rmi", "utest:tag1") cli.DockerCmd(c, "rmi", "utest:tag2") @@ -143,8 +143,8 @@ func (s *DockerCLIEventSuite) TestEventsContainerEventsSinceUnixEpoch(c *testing func (s *DockerCLIEventSuite) TestEventsImageTag(c *testing.T) { time.Sleep(1 * time.Second) // because API has seconds granularity since := daemonUnixTime(c) - image := "testimageevents:tag" - cli.DockerCmd(c, "tag", "busybox", image) + const imgName = "testimageevents:tag" + cli.DockerCmd(c, "tag", "busybox", imgName) out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c)).Stdout() @@ -153,7 +153,7 @@ func (s *DockerCLIEventSuite) TestEventsImageTag(c *testing.T) { event := strings.TrimSpace(events[0]) matches := eventstestutils.ScanMap(event) - assert.Assert(c, matchEventID(matches, image), "matches: %v\nout:\n%s", matches, out) + assert.Assert(c, matchEventID(matches, imgName), "matches: %v\nout:\n%s", matches, out) assert.Equal(c, matches["action"], "tag") } diff --git a/integration-cli/docker_cli_images_test.go b/integration-cli/docker_cli_images_test.go index 737b58e3e70b3..86e662e3b25df 100644 --- a/integration-cli/docker_cli_images_test.go +++ b/integration-cli/docker_cli_images_test.go @@ -227,8 +227,8 @@ func (s *DockerCLIImagesSuite) TestImagesFilterSpaceTrimCase(c *testing.T) { if idx < 4 && !reflect.DeepEqual(listing, imageListings[idx+1]) { for idx, errListing := range imageListings { fmt.Printf("out %d\n", idx) - for _, image := range errListing { - fmt.Print(image) + for _, img := range errListing { + fmt.Print(img) } fmt.Print("") } diff --git a/integration-cli/docker_cli_import_test.go b/integration-cli/docker_cli_import_test.go index 050dff7095bfe..70f6f05ccae28 100644 --- a/integration-cli/docker_cli_import_test.go +++ b/integration-cli/docker_cli_import_test.go @@ -40,8 +40,8 @@ func (s *DockerCLIImportSuite) TestImportDisplay(c *testing.T) { assert.Assert(c, strings.Count(out, "\n") == 1, "display is expected 1 '\\n' but didn't") - image := strings.TrimSpace(out) - out = cli.DockerCmd(c, "run", "--rm", image, "true").Combined() + imgRef := strings.TrimSpace(out) + out = cli.DockerCmd(c, "run", "--rm", imgRef, "true").Combined() assert.Equal(c, out, "", "command output should've been nothing.") } @@ -71,9 +71,9 @@ func (s *DockerCLIImportSuite) TestImportFile(c *testing.T) { out := cli.DockerCmd(c, "import", temporaryFile.Name()).Combined() assert.Assert(c, strings.Count(out, "\n") == 1, "display is expected 1 '\\n' but didn't") - image := strings.TrimSpace(out) + imgRef := strings.TrimSpace(out) - out = cli.DockerCmd(c, "run", "--rm", image, "true").Combined() + out = cli.DockerCmd(c, "run", "--rm", imgRef, "true").Combined() assert.Equal(c, out, "", "command output should've been nothing.") } @@ -94,9 +94,9 @@ func (s *DockerCLIImportSuite) TestImportGzipped(c *testing.T) { temporaryFile.Close() out := cli.DockerCmd(c, "import", temporaryFile.Name()).Combined() assert.Assert(c, strings.Count(out, "\n") == 1, "display is expected 1 '\\n' but didn't") - image := strings.TrimSpace(out) + imgRef := strings.TrimSpace(out) - out = cli.DockerCmd(c, "run", "--rm", image, "true").Combined() + out = cli.DockerCmd(c, "run", "--rm", imgRef, "true").Combined() assert.Equal(c, out, "", "command output should've been nothing.") } @@ -116,9 +116,9 @@ func (s *DockerCLIImportSuite) TestImportFileWithMessage(c *testing.T) { message := "Testing commit message" out := cli.DockerCmd(c, "import", "-m", message, temporaryFile.Name()).Combined() assert.Assert(c, strings.Count(out, "\n") == 1, "display is expected 1 '\\n' but didn't") - image := strings.TrimSpace(out) + imgRef := strings.TrimSpace(out) - out = cli.DockerCmd(c, "history", image).Combined() + out = cli.DockerCmd(c, "history", imgRef).Combined() split := strings.Split(out, "\n") assert.Equal(c, len(split), 3, "expected 3 lines from image history") @@ -127,7 +127,7 @@ func (s *DockerCLIImportSuite) TestImportFileWithMessage(c *testing.T) { assert.Equal(c, message, split[3], "didn't get expected value in commit message") - out = cli.DockerCmd(c, "run", "--rm", image, "true").Combined() + out = cli.DockerCmd(c, "run", "--rm", imgRef, "true").Combined() assert.Equal(c, out, "", "command output should've been nothing") } @@ -147,8 +147,8 @@ func (s *DockerCLIImportSuite) TestImportWithQuotedChanges(c *testing.T) { cli.Docker(cli.Args("export", "test-import"), cli.WithStdout(bufio.NewWriter(temporaryFile))).Assert(c, icmd.Success) result := cli.DockerCmd(c, "import", "-c", `ENTRYPOINT ["/bin/sh", "-c"]`, temporaryFile.Name()) - image := strings.TrimSpace(result.Stdout()) + imgRef := strings.TrimSpace(result.Stdout()) - result = cli.DockerCmd(c, "run", "--rm", image, "true") + result = cli.DockerCmd(c, "run", "--rm", imgRef, "true") result.Assert(c, icmd.Expected{Out: icmd.None}) } diff --git a/integration-cli/docker_cli_rmi_test.go b/integration-cli/docker_cli_rmi_test.go index 584ba29fbdc29..189ff284ce88e 100644 --- a/integration-cli/docker_cli_rmi_test.go +++ b/integration-cli/docker_cli_rmi_test.go @@ -179,17 +179,17 @@ func (s *DockerCLIRmiSuite) TestRmiTagWithExistingContainers(c *testing.T) { } func (s *DockerCLIRmiSuite) TestRmiForceWithExistingContainers(c *testing.T) { - image := "busybox-clone" + const imgName = "busybox-clone" icmd.RunCmd(icmd.Cmd{ - Command: []string{dockerBinary, "build", "--no-cache", "-t", image, "-"}, + Command: []string{dockerBinary, "build", "--no-cache", "-t", imgName, "-"}, Stdin: strings.NewReader(`FROM busybox MAINTAINER foo`), }).Assert(c, icmd.Success) - cli.DockerCmd(c, "run", "--name", "test-force-rmi", image, "/bin/true") + cli.DockerCmd(c, "run", "--name", "test-force-rmi", imgName, "/bin/true") - cli.DockerCmd(c, "rmi", "-f", image) + cli.DockerCmd(c, "rmi", "-f", imgName) } func (s *DockerCLIRmiSuite) TestRmiWithMultipleRepositories(c *testing.T) { @@ -260,7 +260,7 @@ func (s *DockerCLIRmiSuite) TestRmiContainerImageNotFound(c *testing.T) { // #13422 func (s *DockerCLIRmiSuite) TestRmiUntagHistoryLayer(c *testing.T) { - image := "tmp1" + const imgName = "tmp1" // Build an image for testing. dockerfile := `FROM busybox MAINTAINER foo @@ -268,8 +268,8 @@ RUN echo 0 #layer0 RUN echo 1 #layer1 RUN echo 2 #layer2 ` - buildImageSuccessfully(c, image, build.WithoutCache, build.WithDockerfile(dockerfile)) - out := cli.DockerCmd(c, "history", "-q", image).Stdout() + buildImageSuccessfully(c, imgName, build.WithoutCache, build.WithDockerfile(dockerfile)) + out := cli.DockerCmd(c, "history", "-q", imgName).Stdout() ids := strings.Split(out, "\n") idToTag := ids[2] @@ -277,7 +277,7 @@ RUN echo 2 #layer2 newTag := "tmp2" cli.DockerCmd(c, "tag", idToTag, newTag) // Create a container based on "tmp1". - cli.DockerCmd(c, "run", "-d", image, "true") + cli.DockerCmd(c, "run", "-d", imgName, "true") // See if the "tmp2" can be untagged. out = cli.DockerCmd(c, "rmi", newTag).Combined() diff --git a/integration-cli/docker_cli_run_test.go b/integration-cli/docker_cli_run_test.go index d9fcd3a1c7db1..166d2d4ed78eb 100644 --- a/integration-cli/docker_cli_run_test.go +++ b/integration-cli/docker_cli_run_test.go @@ -145,19 +145,19 @@ func (s *DockerCLIRunSuite) TestRunDetachedContainerIDPrinting(c *testing.T) { // the working directory should be set correctly func (s *DockerCLIRunSuite) TestRunWorkingDirectory(c *testing.T) { dir := "/root" - image := "busybox" + const imgName = "busybox" if testEnv.DaemonInfo.OSType == "windows" { dir = `C:/Windows` } // First with -w - out := cli.DockerCmd(c, "run", "-w", dir, image, "pwd").Stdout() + out := cli.DockerCmd(c, "run", "-w", dir, imgName, "pwd").Stdout() if strings.TrimSpace(out) != dir { c.Errorf("-w failed to set working directory") } // Then with --workdir - out = cli.DockerCmd(c, "run", "--workdir", dir, image, "pwd").Stdout() + out = cli.DockerCmd(c, "run", "--workdir", dir, imgName, "pwd").Stdout() if strings.TrimSpace(out) != dir { c.Errorf("--workdir failed to set working directory") } @@ -166,14 +166,14 @@ func (s *DockerCLIRunSuite) TestRunWorkingDirectory(c *testing.T) { // pinging Google's DNS resolver should fail when we disable the networking func (s *DockerCLIRunSuite) TestRunWithoutNetworking(c *testing.T) { count := "-c" - image := "busybox" + imgName := "busybox" if testEnv.DaemonInfo.OSType == "windows" { count = "-n" - image = testEnv.PlatformDefaults.BaseImage + imgName = testEnv.PlatformDefaults.BaseImage } // First using the long form --net - out, exitCode, err := dockerCmdWithError("run", "--net=none", image, "ping", count, "1", "8.8.8.8") + out, exitCode, err := dockerCmdWithError("run", "--net=none", imgName, "ping", count, "1", "8.8.8.8") if err != nil && exitCode != 1 { c.Fatal(out, err) } @@ -623,18 +623,18 @@ func (s *DockerCLIRunSuite) TestRunCreateVolumeWithSymlink(c *testing.T) { testRequires(c, DaemonIsLinux) workingDirectory, err := os.MkdirTemp("", "TestRunCreateVolumeWithSymlink") assert.NilError(c, err) - image := "docker-test-createvolumewithsymlink" + const imgName = "docker-test-createvolumewithsymlink" - buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-") + buildCmd := exec.Command(dockerBinary, "build", "-t", imgName, "-") buildCmd.Stdin = strings.NewReader(`FROM busybox RUN ln -s home /bar`) buildCmd.Dir = workingDirectory err = buildCmd.Run() if err != nil { - c.Fatalf("could not build '%s': %v", image, err) + c.Fatalf("could not build '%s': %v", imgName, err) } - _, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo") + _, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", imgName, "sh", "-c", "mount | grep -q /home/foo") if err != nil || exitCode != 0 { c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) } @@ -1934,9 +1934,9 @@ func (s *DockerCLIRunSuite) TestRunCidFileCleanupIfEmpty(c *testing.T) { tmpCidFile := path.Join(tmpDir, "cid") // This must be an image that has no CMD or ENTRYPOINT set - image := loadSpecialImage(c, specialimage.EmptyFS) + imgRef := loadSpecialImage(c, specialimage.EmptyFS) - out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, image) + out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, imgRef) if err == nil { c.Fatalf("Run without command must fail. out=%s", out) } else if !strings.Contains(out, "no command specified") { diff --git a/integration-cli/docker_cli_swarm_unix_test.go b/integration-cli/docker_cli_swarm_unix_test.go index c971be1470c9e..2e8f2aad294a8 100644 --- a/integration-cli/docker_cli_swarm_unix_test.go +++ b/integration-cli/docker_cli_swarm_unix_test.go @@ -65,7 +65,7 @@ func (s *DockerSwarmSuite) TestSwarmNetworkPluginV2(c *testing.T) { d2 := s.AddDaemon(ctx, c, true, false) // install plugin on d1 and d2 - pluginName := "aragunathan/global-net-plugin:latest" + const pluginName = "aragunathan/global-net-plugin:latest" _, err := d1.Cmd("plugin", "install", pluginName, "--grant-all-permissions") assert.NilError(c, err) @@ -74,12 +74,12 @@ func (s *DockerSwarmSuite) TestSwarmNetworkPluginV2(c *testing.T) { assert.NilError(c, err) // create network - networkName := "globalnet" + const networkName = "globalnet" _, err = d1.Cmd("network", "create", "--driver", pluginName, networkName) assert.NilError(c, err) // create a global service to ensure that both nodes will have an instance - serviceName := "my-service" + const serviceName = "my-service" _, err = d1.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--mode=global", "--network", networkName, "busybox", "top") assert.NilError(c, err) @@ -100,10 +100,10 @@ func (s *DockerSwarmSuite) TestSwarmNetworkPluginV2(c *testing.T) { time.Sleep(20 * time.Second) - image := "busybox:latest" + const imgName = "busybox:latest" // create a new global service again. - _, err = d1.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--mode=global", "--network", networkName, image, "top") + _, err = d1.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--mode=global", "--network", networkName, imgName, "top") assert.NilError(c, err) - poll.WaitOn(c, pollCheck(c, d1.CheckRunningTaskImages(ctx), checker.DeepEquals(map[string]int{image: 1})), poll.WithTimeout(defaultReconciliationTimeout)) + poll.WaitOn(c, pollCheck(c, d1.CheckRunningTaskImages(ctx), checker.DeepEquals(map[string]int{imgName: 1})), poll.WithTimeout(defaultReconciliationTimeout)) } diff --git a/integration-cli/docker_cli_volume_test.go b/integration-cli/docker_cli_volume_test.go index 7fc4d20b393a6..746d8e3c2fa97 100644 --- a/integration-cli/docker_cli_volume_test.go +++ b/integration-cli/docker_cli_volume_test.go @@ -469,13 +469,13 @@ func (s *DockerCLIVolumeSuite) TestVolumeCliInspectWithVolumeOpts(c *testing.T) func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFrom(c *testing.T) { testRequires(c, DaemonIsLinux) - const image = "vimage" - buildImageSuccessfully(c, image, build.WithDockerfile(` + const imgName = "vimage" + buildImageSuccessfully(c, imgName, build.WithDockerfile(` FROM busybox VOLUME ["/tmp/data"]`)) - cli.DockerCmd(c, "run", "--name=data1", image, "true") - cli.DockerCmd(c, "run", "--name=data2", image, "true") + cli.DockerCmd(c, "run", "--name=data1", imgName, "true") + cli.DockerCmd(c, "run", "--name=data2", imgName, "true") data1 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1").Stdout() data1 = strings.TrimSpace(data1) @@ -510,13 +510,13 @@ func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFrom(c *testing func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFromAndBind(c *testing.T) { testRequires(c, DaemonIsLinux) - const image = "vimage" - buildImageSuccessfully(c, image, build.WithDockerfile(` + const imgName = "vimage" + buildImageSuccessfully(c, imgName, build.WithDockerfile(` FROM busybox VOLUME ["/tmp/data"]`)) - cli.DockerCmd(c, "run", "--name=data1", image, "true") - cli.DockerCmd(c, "run", "--name=data2", image, "true") + cli.DockerCmd(c, "run", "--name=data1", imgName, "true") + cli.DockerCmd(c, "run", "--name=data2", imgName, "true") data1 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1").Stdout() data1 = strings.TrimSpace(data1) @@ -552,13 +552,13 @@ func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFromAndBind(c * func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - const image = "vimage" - buildImageSuccessfully(c, image, build.WithDockerfile(` + const imgName = "vimage" + buildImageSuccessfully(c, imgName, build.WithDockerfile(` FROM busybox VOLUME ["/tmp/data"]`)) - cli.DockerCmd(c, "run", "--name=data1", image, "true") - cli.DockerCmd(c, "run", "--name=data2", image, "true") + cli.DockerCmd(c, "run", "--name=data1", imgName, "true") + cli.DockerCmd(c, "run", "--name=data2", imgName, "true") data1 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1").Stdout() data1 = strings.TrimSpace(data1) diff --git a/integration/build/build_test.go b/integration/build/build_test.go index 033790c7ad2c0..e4e30658c8323 100644 --- a/integration/build/build_test.go +++ b/integration/build/build_test.go @@ -219,15 +219,15 @@ func TestBuildMultiStageParentConfig(t *testing.T) { resp.Body.Close() assert.NilError(t, err) - image, _, err := apiclient.ImageInspectWithRaw(ctx, imgName) + img, _, err := apiclient.ImageInspectWithRaw(ctx, imgName) assert.NilError(t, err) expected := "/foo/sub2" if testEnv.DaemonInfo.OSType == "windows" { expected = `C:\foo\sub2` } - assert.Check(t, is.Equal(expected, image.Config.WorkingDir)) - assert.Check(t, is.Contains(image.Config.Env, "WHO=parent")) + assert.Check(t, is.Equal(expected, img.Config.WorkingDir)) + assert.Check(t, is.Contains(img.Config.Env, "WHO=parent")) } // Test cases in #36996 @@ -268,12 +268,12 @@ func TestBuildLabelWithTargets(t *testing.T) { resp.Body.Close() assert.NilError(t, err) - image, _, err := apiclient.ImageInspectWithRaw(ctx, imgName) + img, _, err := apiclient.ImageInspectWithRaw(ctx, imgName) assert.NilError(t, err) testLabels["label-a"] = "inline-a" for k, v := range testLabels { - x, ok := image.Config.Labels[k] + x, ok := img.Config.Labels[k] assert.Assert(t, ok) assert.Assert(t, x == v) } @@ -295,12 +295,12 @@ func TestBuildLabelWithTargets(t *testing.T) { resp.Body.Close() assert.NilError(t, err) - image, _, err = apiclient.ImageInspectWithRaw(ctx, imgName) + img, _, err = apiclient.ImageInspectWithRaw(ctx, imgName) assert.NilError(t, err) testLabels["label-b"] = "inline-b" for k, v := range testLabels { - x, ok := image.Config.Labels[k] + x, ok := img.Config.Labels[k] assert.Assert(t, ok) assert.Assert(t, x == v) } @@ -376,9 +376,9 @@ RUN cat somefile` assert.NilError(t, err) assert.Assert(t, is.Equal(3, len(imageIDs))) - image, _, err := apiclient.ImageInspectWithRaw(ctx, imageIDs[2]) + img, _, err := apiclient.ImageInspectWithRaw(ctx, imageIDs[2]) assert.NilError(t, err) - assert.Check(t, is.Contains(image.Config.Env, "bar=baz")) + assert.Check(t, is.Contains(img.Config.Env, "bar=baz")) } // #35403 #36122 diff --git a/integration/image/remove_unix_test.go b/integration/image/remove_unix_test.go index a7ffafa61408e..d84bfcf0398df 100644 --- a/integration/image/remove_unix_test.go +++ b/integration/image/remove_unix_test.go @@ -58,7 +58,7 @@ func TestRemoveImageGarbageCollector(t *testing.T) { LayerStore: layerStore, }) - img := "test-garbage-collector" + const imgName = "test-garbage-collector" // Build a image with multiple layers dockerfile := `FROM busybox @@ -70,13 +70,13 @@ func TestRemoveImageGarbageCollector(t *testing.T) { types.ImageBuildOptions{ Remove: true, ForceRemove: true, - Tags: []string{img}, + Tags: []string{imgName}, }) assert.NilError(t, err) _, err = io.Copy(io.Discard, resp.Body) resp.Body.Close() assert.NilError(t, err) - image, _, err := client.ImageInspectWithRaw(ctx, img) + image, _, err := client.ImageInspectWithRaw(ctx, imgName) assert.NilError(t, err) // Mark latest image layer to immutable @@ -90,7 +90,7 @@ func TestRemoveImageGarbageCollector(t *testing.T) { // Try to remove the image, it should generate error // but marking layer back to mutable before checking errors (so we don't break CI server) - _, err = client.ImageRemove(ctx, img, types.ImageRemoveOptions{}) + _, err = client.ImageRemove(ctx, imgName, types.ImageRemoveOptions{}) attr = 0x00000000 argp = uintptr(unsafe.Pointer(&attr)) _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, file.Fd(), fsflags, argp) diff --git a/runconfig/config_test.go b/runconfig/config_test.go index 64647493495c1..c001fe932ec45 100644 --- a/runconfig/config_test.go +++ b/runconfig/config_test.go @@ -23,18 +23,18 @@ type f struct { func TestDecodeContainerConfig(t *testing.T) { var ( fixtures []f - image string + imgName string ) if runtime.GOOS != "windows" { - image = "ubuntu" + imgName = "ubuntu" fixtures = []f{ {"fixtures/unix/container_config_1_14.json", strslice.StrSlice{}}, {"fixtures/unix/container_config_1_17.json", strslice.StrSlice{"bash"}}, {"fixtures/unix/container_config_1_19.json", strslice.StrSlice{"bash"}}, } } else { - image = "windows" + imgName = "windows" fixtures = []f{ {"fixtures/windows/container_config_1_19.json", strslice.StrSlice{"cmd"}}, } @@ -53,8 +53,8 @@ func TestDecodeContainerConfig(t *testing.T) { t.Fatal(err) } - if c.Image != image { - t.Fatalf("Expected %s image, found %s", image, c.Image) + if c.Image != imgName { + t.Fatalf("Expected %s image, found %s", imgName, c.Image) } if len(c.Entrypoint) != len(f.entrypoint) { diff --git a/testutil/environment/clean.go b/testutil/environment/clean.go index e03cef90d6a33..40642143fb644 100644 --- a/testutil/environment/clean.go +++ b/testutil/environment/clean.go @@ -100,13 +100,13 @@ func deleteAllImages(ctx context.Context, t testing.TB, apiclient client.ImageAP images, err := apiclient.ImageList(ctx, types.ImageListOptions{}) assert.Check(t, err, "failed to list images") - for _, image := range images { - tags := tagsFromImageSummary(image) - if _, ok := protectedImages[image.ID]; ok { + for _, img := range images { + tags := tagsFromImageSummary(img) + if _, ok := protectedImages[img.ID]; ok { continue } if len(tags) == 0 { - removeImage(ctx, t, apiclient, image.ID) + removeImage(ctx, t, apiclient, img.ID) continue } for _, tag := range tags { diff --git a/testutil/environment/protect.go b/testutil/environment/protect.go index 14bb56992854c..55f95b158f147 100644 --- a/testutil/environment/protect.go +++ b/testutil/environment/protect.go @@ -89,8 +89,8 @@ func getExistingContainers(ctx context.Context, t testing.TB, testEnv *Execution // ProtectImage adds the specified image(s) to be protected in case of clean func (e *Execution) ProtectImage(t testing.TB, images ...string) { t.Helper() - for _, image := range images { - e.protectedElements.images[image] = struct{}{} + for _, img := range images { + e.protectedElements.images[img] = struct{}{} } } From 5581efe7cd846a8eaaa7f59495466b4516f4cd19 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 19 Jan 2024 12:50:13 +0100 Subject: [PATCH 2/4] rename "ociimage" var to be proper camelCase Signed-off-by: Sebastiaan van Stijn --- daemon/containerd/image.go | 4 ++-- daemon/containerd/image_history.go | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/daemon/containerd/image.go b/daemon/containerd/image.go index ff7d8609fdb4c..db68bfb0d156e 100644 --- a/daemon/containerd/image.go +++ b/daemon/containerd/image.go @@ -81,9 +81,9 @@ func (i *ImageService) GetImage(ctx context.Context, refOrID string, options ima sort.SliceStable(presentImages, func(i, j int) bool { return platform.Less(presentImages[i].Platform, presentImages[j].Platform) }) - ociimage := presentImages[0] + ociImage := presentImages[0] - img := dockerOciImageToDockerImagePartial(image.ID(desc.Target.Digest), ociimage) + img := dockerOciImageToDockerImagePartial(image.ID(desc.Target.Digest), ociImage) parent, err := i.getImageLabelByDigest(ctx, desc.Target.Digest, imageLabelClassicBuilderParent) if err != nil { diff --git a/daemon/containerd/image_history.go b/daemon/containerd/image_history.go index b6fdfe053ac1c..2fd01169d4234 100644 --- a/daemon/containerd/image_history.go +++ b/daemon/containerd/image_history.go @@ -36,11 +36,11 @@ func (i *ImageService) ImageHistory(ctx context.Context, name string) ([]*imaget if err != nil { return err } - var ociimage ocispec.Image - if err := readConfig(ctx, cs, conf, &ociimage); err != nil { + var ociImage ocispec.Image + if err := readConfig(ctx, cs, conf, &ociImage); err != nil { return err } - presentImages = append(presentImages, ociimage) + presentImages = append(presentImages, ociImage) return nil }) if err != nil { @@ -53,7 +53,7 @@ func (i *ImageService) ImageHistory(ctx context.Context, name string) ([]*imaget sort.SliceStable(presentImages, func(i, j int) bool { return platform.Less(presentImages[i].Platform, presentImages[j].Platform) }) - ociimage := presentImages[0] + ociImage := presentImages[0] var ( history []*imagetype.HistoryResponseItem @@ -61,7 +61,7 @@ func (i *ImageService) ImageHistory(ctx context.Context, name string) ([]*imaget ) s := i.client.SnapshotService(i.snapshotter) - diffIDs := ociimage.RootFS.DiffIDs + diffIDs := ociImage.RootFS.DiffIDs for i := range diffIDs { chainID := identity.ChainID(diffIDs[0 : i+1]).String() @@ -73,7 +73,7 @@ func (i *ImageService) ImageHistory(ctx context.Context, name string) ([]*imaget sizes = append(sizes, use.Size) } - for _, h := range ociimage.History { + for _, h := range ociImage.History { size := int64(0) if !h.EmptyLayer { if len(sizes) == 0 { From 7c1914411f780d5e7d1663afc90fae718fafd478 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 19 Jan 2024 13:08:30 +0100 Subject: [PATCH 3/4] daemon/images: ImageService.manifestMatchesPlatform: optimize logger We constructed a "function level" logger, which was used once "as-is", but also added additional Fields in a loop (for each resource), effectively overwriting the previous one for each iteration. Adding additional fields can result in some overhead, so let's construct a "logger" only for inside the loop. Signed-off-by: Sebastiaan van Stijn --- daemon/images/image.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/daemon/images/image.go b/daemon/images/image.go index 0510deb5fe1fb..9298ff0798f11 100644 --- a/daemon/images/image.go +++ b/daemon/images/image.go @@ -52,14 +52,16 @@ func (i *ImageService) PrepareSnapshot(ctx context.Context, id string, parentIma } func (i *ImageService) manifestMatchesPlatform(ctx context.Context, img *image.Image, platform ocispec.Platform) (bool, error) { - logger := log.G(ctx).WithField("image", img.ID).WithField("desiredPlatform", platforms.Format(platform)) - ls, err := i.leases.ListResources(ctx, leases.Lease{ID: imageKey(img.ID().String())}) if err != nil { if cerrdefs.IsNotFound(err) { return false, nil } - logger.WithError(err).Error("Error looking up image leases") + log.G(ctx).WithFields(log.Fields{ + "error": err, + "image": img.ID, + "desiredPlatform": platforms.Format(platform), + }).Error("Error looking up image leases") return false, err } @@ -77,7 +79,12 @@ func (i *ImageService) manifestMatchesPlatform(ctx context.Context, img *image.I } for _, r := range ls { - logger := logger.WithField("resourceID", r.ID).WithField("resourceType", r.Type) + logger := log.G(ctx).WithFields(log.Fields{ + "image": img.ID, + "desiredPlatform": platforms.Format(platform), + "resourceID": r.ID, + "resourceType": r.Type, + }) logger.Debug("Checking lease resource for platform match") if r.Type != "content" { continue From 35789fce996fcf5975f1332f93375bd4b987da97 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 19 Jan 2024 13:11:40 +0100 Subject: [PATCH 4/4] daemon.images: ImageService.getImage: use named fields in struct literals Prevent things from breaking if additional fields are added to this struct. Signed-off-by: Sebastiaan van Stijn --- daemon/images/image.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/daemon/images/image.go b/daemon/images/image.go index 9298ff0798f11..febf9d1206275 100644 --- a/daemon/images/image.go +++ b/daemon/images/image.go @@ -248,12 +248,12 @@ func (i *ImageService) getImage(ctx context.Context, refOrID string, options ima if !ok { digested, ok := ref.(reference.Digested) if !ok { - return nil, ErrImageDoesNotExist{ref} + return nil, ErrImageDoesNotExist{Ref: ref} } if img, err := i.imageStore.Get(image.ID(digested.Digest())); err == nil { return img, nil } - return nil, ErrImageDoesNotExist{ref} + return nil, ErrImageDoesNotExist{Ref: ref} } if dgst, err := i.referenceStore.Get(namedRef); err == nil { @@ -267,12 +267,12 @@ func (i *ImageService) getImage(ctx context.Context, refOrID string, options ima if id, err := i.imageStore.Search(refOrID); err == nil { img, err := i.imageStore.Get(id) if err != nil { - return nil, ErrImageDoesNotExist{ref} + return nil, ErrImageDoesNotExist{Ref: ref} } return img, nil } - return nil, ErrImageDoesNotExist{ref} + return nil, ErrImageDoesNotExist{Ref: ref} } // OnlyPlatformWithFallback uses `platforms.Only` with a fallback to handle the case where the platform