Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: push final image to cache repo #197

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions envbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -477,14 +477,19 @@ func Run(ctx context.Context, options Options) error {
if val, ok := os.LookupEnv("KANIKO_REGISTRY_MIRROR"); ok {
registryMirror = strings.Split(val, ";")
}
image, err := executor.DoBuild(&config.KanikoOptions{
var destinations []string
if options.CacheRepo != "" {
destinations = append(destinations, options.CacheRepo)
}
opts := &config.KanikoOptions{
// Boilerplate!
CustomPlatform: platforms.Format(platforms.Normalize(platforms.DefaultSpec())),
SnapshotMode: "redo",
RunV2: true,
RunStdout: stdoutWriter,
RunStderr: stderrWriter,
Destinations: []string{"local"},
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This causes problems when DoPush is called. I'm not sure what the original intent was.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you elaborate on what the problems are? Are you referring to #185 (comment)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty sure this was simply a bug that was present because DoPush wasn't being used previously. Kaniko expects you to either set it or use --no-push.

error: failed to push to destination local: HEAD https://index.docker.io/v2/library/local/manifests/latest: unexpected status code 401 Unauthorized (HEAD responses have no body, use GET for details)
error: running command "envbuilder": HEAD https://index.docker.io/v2/library/local/manifests/latest: unexpected status code 401 Unauthorized (HEAD responses have no body, use GET for details)
failed to push to destination local

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we make it optional too? If platform engineers are concerned about envbuilder speed, they can --enable-do-push

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It depends, do we want to expose multiple knobs, one for caching and one for pushing final image/build optimization, or do we want these to be behind one knob? I'm open to splitting it up but could use some thought. Just because it's two different moments in Kaniko, doesn't mean we have to follow that here.

Destinations: destinations,
NoPush: len(destinations) == 0,
CacheRunLayers: true,
CacheCopyLayers: true,
CompressedCaching: true,
Expand Down Expand Up @@ -515,11 +520,16 @@ func Run(ctx context.Context, options Options) error {
RegistryMirrors: registryMirror,
},
SrcContext: buildParams.BuildContext,
})
}
image, err := executor.DoBuild(opts)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to see more debugging/trace logging around this step and DoPush.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what the ask is here, I didn't change any of this code so seems out of scope?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Didn't you add image, err := executor.DoBuild(opts)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I just moved opts to a variable.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I missed L483. Anyway, I wanted to improve logging around this, but if you think this is useless here, I'm cool with leaving it as is.

if err != nil {
return nil, err
return nil, xerrors.Errorf("do build: %w", err)
}
if err := executor.DoPush(image, opts); err != nil {
return nil, xerrors.Errorf("do push: %w", err)
}
endStage("🏗️ Built image!")

return image, err
}

Expand Down
80 changes: 80 additions & 0 deletions integration/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import (
"github.com/go-git/go-billy/v5/memfs"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/registry"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -987,6 +989,84 @@ COPY %s .`, testImageAlpine, inclFile)
}
}

func TestPushImage(t *testing.T) {
t.Parallel()

t.Run("Push", func(t *testing.T) {
t.Parallel()

srv := createGitServer(t, gitServerOptions{
files: map[string]string{
".devcontainer/Dockerfile": fmt.Sprintf("FROM %s\nRUN date --utc > /root/date.txt", testImageAlpine),
".devcontainer/devcontainer.json": `{
"name": "Test",
"build": {
"dockerfile": "Dockerfile"
},
}`,
},
})

// Given: an empty registry
testReg := setupInMemoryRegistry(t)
testRepo := testReg + "/test"
ref, err := name.ParseReference(testRepo + ":latest")
require.NoError(t, err)
_, err = remote.Image(ref)
require.ErrorContains(t, err, "NAME_UNKNOWN", "expected image to not be present before build + push")

// When: we run envbuilder with PUSH_IMAGE set
_, err = runEnvbuilder(t, options{env: []string{
envbuilderEnv("GIT_URL", srv.URL),
envbuilderEnv("CACHE_REPO", testRepo),
}})
require.NoError(t, err)

// Then: the image should be pushed
_, err = remote.Image(ref)
require.NoError(t, err, "expected image to be present after build + push")
})

t.Run("PushErr", func(t *testing.T) {
t.Parallel()

srv := createGitServer(t, gitServerOptions{
files: map[string]string{
".devcontainer/Dockerfile": fmt.Sprintf("FROM %s\nRUN date --utc > /root/date.txt", testImageAlpine),
".devcontainer/devcontainer.json": `{
"name": "Test",
"build": {
"dockerfile": "Dockerfile"
},
}`,
},
})

// Given: registry is not set up (in this case, not a registry)
notRegSrv := httptest.NewServer(http.NotFoundHandler())
notRegURL := strings.TrimPrefix(notRegSrv.URL, "http://") + "/test"

// When: we run envbuilder with PUSH_IMAGE set
_, err := runEnvbuilder(t, options{env: []string{
envbuilderEnv("GIT_URL", srv.URL),
envbuilderEnv("CACHE_REPO", notRegURL),
}})
// Then: should fail with a descriptive error
require.ErrorContains(t, err, "unexpected status code 404 Not Found")
})
}

func setupInMemoryRegistry(t *testing.T) string {
t.Helper()
tempDir := t.TempDir()
testReg := registry.New(registry.WithBlobHandler(registry.NewDiskBlobHandler(tempDir)))
regSrv := httptest.NewServer(testReg)
t.Cleanup(func() { regSrv.Close() })
regSrvURL, err := url.Parse(regSrv.URL)
require.NoError(t, err)
return fmt.Sprintf("localhost:%s", regSrvURL.Port())
}

// TestMain runs before all tests to build the envbuilder image.
func TestMain(m *testing.M) {
checkTestRegistry()
Expand Down