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

Enable embedding of ko publish #348

Merged
merged 1 commit into from
May 25, 2021
Merged
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
46 changes: 31 additions & 15 deletions pkg/commands/config.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
// Copyright 2018 Google LLC All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
Copyright 2018 Google LLC All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package commands

Expand All @@ -31,6 +33,7 @@ import (
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/types"
"github.com/google/ko/pkg/build"
"github.com/google/ko/pkg/commands/options"
"github.com/spf13/viper"
)

Expand All @@ -39,7 +42,9 @@ var (
baseImageOverrides map[string]name.Reference
)

func getBaseImage(platform string) build.GetBase {
// getBaseImage returns a function that determines the base image for a given import path.
// If the `bo.BaseImage` parameter is non-empty, it overrides base image configuration from `.ko.yaml`.
func getBaseImage(platform string, bo *options.BuildOptions) build.GetBase {
return func(ctx context.Context, s string) (build.Result, error) {
s = strings.TrimPrefix(s, build.StrictScheme)
// Viper configuration file keys are case insensitive, and are
Expand All @@ -52,9 +57,20 @@ func getBaseImage(platform string) build.GetBase {
if !ok {
ref = defaultBaseImage
}
if bo.BaseImage != "" {
var err error
ref, err = name.ParseReference(bo.BaseImage)
if err != nil {
return nil, fmt.Errorf("parsing bo.BaseImage (%q): %v", bo.BaseImage, err)
}
}
userAgent := ua()
if bo.UserAgent != "" {
userAgent = bo.UserAgent
}
ropt := []remote.Option{
remote.WithAuthFromKeychain(authn.DefaultKeychain),
remote.WithUserAgent(ua()),
remote.WithUserAgent(userAgent),
remote.WithContext(ctx),
}

Expand Down
47 changes: 47 additions & 0 deletions pkg/commands/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
Copyright 2021 Google LLC All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package commands

import (
"context"
"testing"

"github.com/google/ko/pkg/commands/options"
)

func TestOverrideDefaultBaseImageUsingBuildOption(t *testing.T) {
wantDigest := "sha256:76c39a6f76890f8f8b026f89e081084bc8c64167d74e6c93da7a053cb4ccb5dd"
wantImage := "gcr.io/distroless/static-debian9@" + wantDigest
bo := &options.BuildOptions{
BaseImage: wantImage,
}

baseFn := getBaseImage("all", bo)
res, err := baseFn(context.Background(), "ko://example.com/helloworld")
if err != nil {
t.Fatalf("getBaseImage(): %v", err)
}

digest, err := res.Digest()
if err != nil {
t.Fatalf("res.Digest(): %v", err)
}
gotDigest := digest.String()
if gotDigest != wantDigest {
t.Errorf("got digest %s, wanted %s", gotDigest, wantDigest)
}
}
6 changes: 6 additions & 0 deletions pkg/commands/options/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,16 @@ import (

// BuildOptions represents options for the ko builder.
type BuildOptions struct {
// BaseImage enables setting the default base image programmatically.
// If non-empty, this takes precedence over the value in `.ko.yaml`.
BaseImage string
ConcurrentBuilds int
DisableOptimizations bool
Platform string
Labels []string
// UserAgent enables overriding the default value of the `User-Agent` HTTP
// request header used when retrieving the base image.
UserAgent string
}

func AddBuildOptions(cmd *cobra.Command, bo *BuildOptions) {
Expand Down
6 changes: 5 additions & 1 deletion pkg/commands/options/publish.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2021 Google LLC All Rights Reserved.
Copyright 2018 Google LLC All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -35,6 +35,10 @@ type PublishOptions struct {
// LocalDomain overrides the default domain for images loaded into the local Docker daemon. Use with Local=true.
LocalDomain string

// UserAgent enables overriding the default value of the `User-Agent` HTTP
// request header used when pushing the built image to an image registry.
UserAgent string

Tags []string
// TagOnly resolves images into tag-only references.
TagOnly bool
Expand Down
33 changes: 20 additions & 13 deletions pkg/commands/publisher.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
// Copyright 2018 Google LLC All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
Copyright 2018 Google LLC All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package commands

Expand Down Expand Up @@ -41,6 +43,11 @@ func qualifyLocalImport(importpath string) (string, error) {
return pkgs[0].PkgPath, nil
}

// PublishImages publishes images
func PublishImages(ctx context.Context, importpaths []string, pub publish.Interface, b build.Interface) (map[string]name.Reference, error) {
Copy link
Member

Choose a reason for hiding this comment

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

Is there a reason to prefer exporting this new wrapper method, versus exporting publishImages directly?

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think it makes the diff smaller, which is nice. I kind of like it :P

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 be okay with it as a specific diff-shrinking measure that we intend to clean up with a followup PR.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, it was just to keep the diff small.

return publishImages(ctx, importpaths, pub, b)
}

func publishImages(ctx context.Context, importpaths []string, pub publish.Interface, b build.Interface) (map[string]name.Reference, error) {
imgs := make(map[string]name.Reference)
for _, importpath := range importpaths {
Expand Down
100 changes: 100 additions & 0 deletions pkg/commands/publisher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
Copyright 2021 Google LLC All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package commands

import (
"context"
"fmt"
"path/filepath"
"runtime"
"strings"
"testing"

"github.com/google/ko/pkg/build"
"github.com/google/ko/pkg/commands/options"
)

func TestPublishImages(t *testing.T) {
repo := "registry.example.com/repository"
sampleAppDir, err := sampleAppRelDir()
if err != nil {
t.Fatalf("sampleAppRelDir(): %v", err)
}
tests := []struct {
description string
publishArg string
importpath string
}{
{
description: "import path with ko scheme",
publishArg: "ko://github.com/google/ko/test",
importpath: "github.com/google/ko/test",
},
{
description: "import path without ko scheme",
publishArg: "github.com/google/ko/test",
importpath: "github.com/google/ko/test",
},
{
description: "file path",
publishArg: sampleAppDir,
importpath: "github.com/google/ko/test",
},
}
for _, test := range tests {
ctx := context.Background()
bo := &options.BuildOptions{
ConcurrentBuilds: 1,
}
builder, err := NewBuilder(ctx, bo)
if err != nil {
t.Fatalf("%s: MakeBuilder(): %v", test.description, err)
}
po := &options.PublishOptions{
DockerRepo: repo,
PreserveImportPaths: true,
}
publisher, err := NewPublisher(po)
if err != nil {
t.Fatalf("%s: MakePublisher(): %v", test.description, err)
}
importpathWithScheme := build.StrictScheme + test.importpath
refs, err := PublishImages(ctx, []string{test.publishArg}, publisher, builder)
if err != nil {
t.Fatalf("%s: PublishImages(): %v", test.description, err)
}
ref, exists := refs[importpathWithScheme]
if !exists {
t.Errorf("%s: could not find image for importpath %s", test.description, importpathWithScheme)
}
gotImageName := ref.Context().Name()
wantImageName := strings.ToLower(fmt.Sprintf("%s/%s", repo, test.importpath))
if gotImageName != wantImageName {
t.Errorf("%s: got %s, wanted %s", test.description, gotImageName, wantImageName)
}
}
}

func sampleAppRelDir() (string, error) {
_, filename, _, ok := runtime.Caller(0)
if !ok {
return "", fmt.Errorf("could not get current filename")
}
basepath := filepath.Dir(filename)
testAppDir := filepath.Join(basepath, "..", "..", "test")
return filepath.Rel(basepath, testAppDir)
}
24 changes: 20 additions & 4 deletions pkg/commands/resolver.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2021 Google LLC All Rights Reserved.
Copyright 2018 Google LLC All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -41,6 +41,7 @@ import (
"k8s.io/apimachinery/pkg/labels"
)

// ua returns the ko user agent.
func ua() string {
if v := version(); v != "" {
return "ko/" + v
Expand Down Expand Up @@ -79,7 +80,7 @@ func gobuildOptions(bo *options.BuildOptions) ([]build.Option, error) {
}

opts := []build.Option{
build.WithBaseImages(getBaseImage(platform)),
build.WithBaseImages(getBaseImage(platform, bo)),
build.WithPlatforms(platform),
}
if creationTime != nil {
Expand All @@ -98,6 +99,11 @@ func gobuildOptions(bo *options.BuildOptions) ([]build.Option, error) {
return opts, nil
}

// NewBuilder creates a ko builder
func NewBuilder(ctx context.Context, bo *options.BuildOptions) (build.Interface, error) {
return makeBuilder(ctx, bo)
}

func makeBuilder(ctx context.Context, bo *options.BuildOptions) (*build.Caching, error) {
opt, err := gobuildOptions(bo)
if err != nil {
Expand Down Expand Up @@ -129,6 +135,11 @@ func makeBuilder(ctx context.Context, bo *options.BuildOptions) (*build.Caching,
return build.NewCaching(innerBuilder)
}

// NewPublisher creates a ko publisher
func NewPublisher(po *options.PublishOptions) (publish.Interface, error) {
return makePublisher(po)
Copy link
Member

Choose a reason for hiding this comment

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

Same comment about makePublisher vs MakePublisher, makeBuilder, etc. -- if we're going to export them, I'd prefer to just export them.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

As above. I was thinking of an expand-and-contract style of approach (https://www.martinfowler.com/bliki/ParallelChange.html).

}

func makePublisher(po *options.PublishOptions) (publish.Interface, error) {
// Create the publish.Interface that we will use to publish image references
// to either a docker daemon or a container image registry.
Expand All @@ -151,7 +162,7 @@ func makePublisher(po *options.PublishOptions) (publish.Interface, error) {
}
if _, err := name.NewRegistry(repoName); err != nil {
if _, err := name.NewRepository(repoName); err != nil {
return nil, fmt.Errorf("failed to parse environment variable KO_DOCKER_REPO=%q as repository: %v", repoName, err)
return nil, fmt.Errorf("failed to parse %q as repository: %v", repoName, err)
}
}

Expand All @@ -167,9 +178,13 @@ func makePublisher(po *options.PublishOptions) (publish.Interface, error) {
tp := publish.NewTarball(po.TarballFile, repoName, namer, po.Tags)
publishers = append(publishers, tp)
}
userAgent := ua()
if po.UserAgent != "" {
userAgent = po.UserAgent
}
if po.Push {
dp, err := publish.NewDefault(repoName,
publish.WithUserAgent(ua()),
publish.WithUserAgent(userAgent),
publish.WithAuthFromKeychain(authn.DefaultKeychain),
publish.WithNamer(namer),
publish.WithTags(po.Tags),
Expand Down Expand Up @@ -208,6 +223,7 @@ type nopPublisher struct {
}

func (n nopPublisher) Publish(_ context.Context, br build.Result, s string) (name.Reference, error) {
s = strings.TrimPrefix(s, build.StrictScheme)
Copy link
Member

Choose a reason for hiding this comment

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

Why is this change necessary?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Ah, that was unrelated - the nopPublisher failed in a unit test because the scheme prefix wasn't trimmed.

h, err := br.Digest()
if err != nil {
return nil, err
Expand Down
Loading