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

Persistent volume caching for base images #383

Merged
merged 21 commits into from
Oct 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
fcfc2f4
comments
sharifelgamal Aug 31, 2018
4db3991
Merge branch 'master' of github.com:GoogleCloudPlatform/kaniko into c…
sharifelgamal Sep 10, 2018
f12eadc
Merge branch 'master' of github.com:GoogleCloudPlatform/kaniko into c…
sharifelgamal Sep 12, 2018
e915460
Merge branch 'master' of github.com:GoogleCloudPlatform/kaniko into c…
sharifelgamal Sep 27, 2018
8dd6d47
initial commit for persisent volume caching
sharifelgamal Oct 2, 2018
fc1d3e1
Merge branch 'master' of github.com:GoogleCloudPlatform/kaniko into c…
sharifelgamal Oct 2, 2018
979092e
cache warmer works
sharifelgamal Oct 3, 2018
1667b39
Merge branch 'master' of github.com:GoogleCloudPlatform/kaniko into c…
sharifelgamal Oct 3, 2018
ad4f604
general cleanup
sharifelgamal Oct 3, 2018
69a760e
adding some debugging
sharifelgamal Oct 8, 2018
c44bd34
adding missing files
sharifelgamal Oct 8, 2018
123d5f3
Fixing up cache retrieval and cleanup
sharifelgamal Oct 9, 2018
88c6945
Merge branch 'master' of github.com:GoogleCloudPlatform/kaniko into c…
sharifelgamal Oct 9, 2018
72e71ce
fix tests
sharifelgamal Oct 9, 2018
78c2111
removing auth since we only cache public images
sharifelgamal Oct 9, 2018
b8ac1be
simplifying the caching logic
sharifelgamal Oct 10, 2018
27888f3
fixing logic
sharifelgamal Oct 10, 2018
d158f70
adding volume cache to integration tests. remove auth from cache warm…
sharifelgamal Oct 11, 2018
0a550f0
add building warmer to integration-test
sharifelgamal Oct 11, 2018
47c8ff4
move sample yaml files to examples dir
sharifelgamal Oct 11, 2018
78d4898
small test fix
sharifelgamal Oct 11, 2018
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
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,15 @@ GO_LDFLAGS += -w -s # Drop debugging symbols.
GO_LDFLAGS += '

EXECUTOR_PACKAGE = $(REPOPATH)/cmd/executor
WARMER_PACKAGE = $(REPOPATH)/cmd/warmer
KANIKO_PROJECT = $(REPOPATH)/kaniko

out/executor: $(GO_FILES)
GOARCH=$(GOARCH) GOOS=linux CGO_ENABLED=0 go build -ldflags $(GO_LDFLAGS) -o $@ $(EXECUTOR_PACKAGE)

out/warmer: $(GO_FILES)
GOARCH=$(GOARCH) GOOS=linux CGO_ENABLED=0 go build -ldflags $(GO_LDFLAGS) -o $@ $(WARMER_PACKAGE)

.PHONY: test
test: out/executor
@ ./test.sh
Expand All @@ -52,3 +56,4 @@ integration-test:
images:
docker build -t $(REGISTRY)/executor:latest -f deploy/Dockerfile .
docker build -t $(REGISTRY)/executor:debug -f deploy/Dockerfile_debug .
docker build -t $(REGISTRY)/warmer:latest -f deploy/Dockerfile_warmer .
1 change: 1 addition & 0 deletions cmd/executor/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ func addKanikoOptionsFlags(cmd *cobra.Command) {
RootCmd.PersistentFlags().StringVarP(&opts.Target, "target", "", "", "Set the target build stage to build")
RootCmd.PersistentFlags().BoolVarP(&opts.NoPush, "no-push", "", false, "Do not push the image to the registry")
RootCmd.PersistentFlags().StringVarP(&opts.CacheRepo, "cache-repo", "", "", "Specify a repository to use as a cache, otherwise one will be inferred from the destination provided")
RootCmd.PersistentFlags().StringVarP(&opts.CacheDir, "cache-dir", "", "/cache", "Specify a local directory to use as a cache.")
RootCmd.PersistentFlags().BoolVarP(&opts.Cache, "cache", "", false, "Use cache when building image")
RootCmd.PersistentFlags().BoolVarP(&opts.Cleanup, "cleanup", "", false, "Clean the filesystem at the end")
}
Expand Down
74 changes: 74 additions & 0 deletions cmd/warmer/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
Copyright 2018 Google LLC

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 cmd

import (
"fmt"
"os"

"github.com/GoogleContainerTools/kaniko/pkg/cache"
"github.com/GoogleContainerTools/kaniko/pkg/config"
"github.com/GoogleContainerTools/kaniko/pkg/constants"
"github.com/GoogleContainerTools/kaniko/pkg/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)

var (
opts = &config.WarmerOptions{}
logLevel string
)

func init() {
RootCmd.PersistentFlags().StringVarP(&logLevel, "verbosity", "v", constants.DefaultLogLevel, "Log level (debug, info, warn, error, fatal, panic")
addKanikoOptionsFlags(RootCmd)
addHiddenFlags(RootCmd)
}

var RootCmd = &cobra.Command{
Use: "cache warmer",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := util.ConfigureLogging(logLevel); err != nil {
return err
}
if len(opts.Images) == 0 {
return errors.New("You must select at least one image to cache")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
if err := cache.WarmCache(opts); err != nil {
exit(errors.Wrap(err, "Failed warming cache"))
}
},
}

// addKanikoOptionsFlags configures opts
func addKanikoOptionsFlags(cmd *cobra.Command) {
RootCmd.PersistentFlags().VarP(&opts.Images, "image", "i", "Image to cache. Set it repeatedly for multiple images.")
RootCmd.PersistentFlags().StringVarP(&opts.CacheDir, "cache-dir", "c", "/cache", "Directory of the cache.")
}

// addHiddenFlags marks certain flags as hidden from the executor help text
func addHiddenFlags(cmd *cobra.Command) {
RootCmd.PersistentFlags().MarkHidden("azure-container-registry-config")
}

func exit(err error) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: we shouldn't need this if we return an error

fmt.Println(err)
os.Exit(1)
}
29 changes: 29 additions & 0 deletions cmd/warmer/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Copyright 2018 Google LLC

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 main

import (
"os"

"github.com/GoogleContainerTools/kaniko/cmd/warmer/cmd"
)

func main() {
if err := cmd.RootCmd.Execute(); err != nil {
os.Exit(1)
}
}
32 changes: 32 additions & 0 deletions deploy/Dockerfile_warmer
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright 2018 Google, Inc. 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.

# Builds the static Go image to execute in a Kubernetes job

FROM golang:1.10
WORKDIR /go/src/github.com/GoogleContainerTools/kaniko
COPY . .
RUN make

FROM scratch
COPY --from=0 /go/src/github.com/GoogleContainerTools/kaniko/out/warmer /kaniko/warmer
COPY files/ca-certificates.crt /kaniko/ssl/certs/
COPY files/config.json /kaniko/.docker/
ENV HOME /root
ENV USER /root
ENV PATH /usr/local/bin:/kaniko
ENV SSL_CERT_DIR=/kaniko/ssl/certs
ENV DOCKER_CONFIG /kaniko/.docker/
WORKDIR /workspace
ENTRYPOINT ["/kaniko/warmer"]
11 changes: 11 additions & 0 deletions examples/kaniko-cache-claim.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: kaniko-cache-claim
spec:
storageClassName: manual
accessModes:
- ReadOnlyMany
resources:
requests:
storage: 8Gi
14 changes: 14 additions & 0 deletions examples/kaniko-cache-volume.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
kind: PersistentVolume
apiVersion: v1
metadata:
name: kaniko-cache-volume
labels:
type: local
spec:
storageClassName: manual
capacity:
storage: 10Gi
accessModes:
- ReadOnlyMany
hostPath:
path: "/tmp/kaniko-cache"
30 changes: 30 additions & 0 deletions examples/kaniko-test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
apiVersion: v1
kind: Pod
metadata:
name: kaniko
spec:
containers:
- name: kaniko
image: gcr.io/kaniko-project/executor:latest
args: ["--dockerfile=<dockerfile>",
"--context=<context>",
"--destination=<destination>",
"--cache",
"--cache-dir=/cache"]
volumeMounts:
- name: kaniko-secret
mountPath: /secret
- name: kaniko-cache
mountPath: /cache
env:
- name: GOOGLE_APPLICATION_CREDENTIALS
value: /secret/kaniko-secret.json
restartPolicy: Never
volumes:
- name: kaniko-secret
secret:
secretName: kaniko-secret
- name: kaniko-cache
persistentVolumeClaim:
claimName: kaniko-cache-claim

27 changes: 27 additions & 0 deletions examples/kaniko-warmer.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
apiVersion: v1
kind: Pod
metadata:
name: kaniko-warmer
spec:
containers:
- name: kaniko-warmer
image: gcr.io/kaniko-project/warmer:latest
args: ["--cache-dir=/cache",
"--image=gcr.io/google-appengine/debian9"]
volumeMounts:
- name: kaniko-secret
mountPath: /secret
- name: kaniko-cache
mountPath: /cache
env:
- name: GOOGLE_APPLICATION_CREDENTIALS
value: /secret/kaniko-secret.json
restartPolicy: Never
volumes:
- name: kaniko-secret
secret:
secretName: kaniko-secret
- name: kaniko-cache
persistentVolumeClaim:
claimName: kaniko-cache-claim

1 change: 1 addition & 0 deletions integration-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,6 @@ fi

echo "Running integration tests..."
make out/executor
make out/warmer
pushd integration
go test -v --bucket "${GCS_BUCKET}" --repo "${IMAGE_REPO}" --timeout 30m
26 changes: 25 additions & 1 deletion integration/images.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@ import (
const (
// ExecutorImage is the name of the kaniko executor image
ExecutorImage = "executor-image"
WarmerImage = "warmer-image"

dockerPrefix = "docker-"
kanikoPrefix = "kaniko-"
buildContextPath = "/workspace"
cacheDir = "/workspace/cache"
baseImageToCache = "gcr.io/google-appengine/debian9@sha256:1d6a9a6d106bd795098f60f4abb7083626354fa6735e81743c7f8cfca11259f0"
)

// Arguments to build Dockerfiles with, used for both docker and kaniko builds
Expand Down Expand Up @@ -201,6 +204,26 @@ func (d *DockerFileBuilder) BuildImage(imageRepo, gcsBucket, dockerfilesPath, do
return nil
}

func populateVolumeCache() error {
_, ex, _, _ := runtime.Caller(0)
cwd := filepath.Dir(ex)
warmerCmd := exec.Command("docker",
append([]string{"run",
"-v", os.Getenv("HOME") + "/.config/gcloud:/root/.config/gcloud",
"-v", cwd + ":/workspace",
WarmerImage,
"-c", cacheDir,
"-i", baseImageToCache},
)...,
)

if _, err := RunCommandWithoutTest(warmerCmd); err != nil {
return fmt.Errorf("Failed to warm kaniko cache: %s", err)
}

return nil
}

// buildCachedImages builds the images for testing caching via kaniko where version is the nth time this image has been built
func (d *DockerFileBuilder) buildCachedImages(imageRepo, cacheRepo, dockerfilesPath string, version int) error {
_, ex, _, _ := runtime.Caller(0)
Expand All @@ -219,7 +242,8 @@ func (d *DockerFileBuilder) buildCachedImages(imageRepo, cacheRepo, dockerfilesP
"-d", kanikoImage,
"-c", buildContextPath,
cacheFlag,
"--cache-repo", cacheRepo})...,
"--cache-repo", cacheRepo,
"--cache-dir", cacheDir})...,
)

if _, err := RunCommandWithoutTest(kanikoCmd); err != nil {
Expand Down
8 changes: 8 additions & 0 deletions integration/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,13 @@ func TestMain(m *testing.M) {
os.Exit(1)
}

fmt.Println("Building cache warmer image")
cmd = exec.Command("docker", "build", "-t", WarmerImage, "-f", "../deploy/Dockerfile_warmer", "..")
if _, err = RunCommandWithoutTest(cmd); err != nil {
fmt.Printf("Building kaniko's cache warmer failed: %s", err)
os.Exit(1)
}

fmt.Println("Building onbuild base image")
buildOnbuildBase := exec.Command("docker", "build", "-t", config.onbuildBaseImage, "-f", "dockerfiles/Dockerfile_onbuild_base", ".")
if err := buildOnbuildBase.Run(); err != nil {
Expand Down Expand Up @@ -238,6 +245,7 @@ func TestLayers(t *testing.T) {

// Build each image with kaniko twice, and then make sure they're exactly the same
func TestCache(t *testing.T) {
populateVolumeCache()
for dockerfile := range imageBuilder.TestCacheDockerfiles {
t.Run("test_cache_"+dockerfile, func(t *testing.T) {
cache := filepath.Join(config.imageRepo, "cache", fmt.Sprintf("%v", time.Now().UnixNano()))
Expand Down
19 changes: 19 additions & 0 deletions pkg/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ package cache

import (
"fmt"
"path"

"github.com/GoogleContainerTools/kaniko/pkg/config"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/authn/k8schain"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/tarball"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
Expand Down Expand Up @@ -68,3 +70,20 @@ func Destination(opts *config.KanikoOptions, cacheKey string) (string, error) {
}
return fmt.Sprintf("%s:%s", cache, cacheKey), nil
}

func LocalSource(opts *config.KanikoOptions, cacheKey string) (v1.Image, error) {
cache := opts.CacheDir
if cache == "" {
return nil, nil
}

path := path.Join(cache, cacheKey)

imgTar, err := tarball.ImageFromPath(path, nil)
if err != nil {
return nil, errors.Wrap(err, "getting image from path")
}

logrus.Infof("Found %s in local cache", cacheKey)
return imgTar, nil
}
Loading