forked from GoogleContainerTools/kaniko
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpush.go
More file actions
305 lines (273 loc) · 9.31 KB
/
push.go
File metadata and controls
305 lines (273 loc) · 9.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
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 executor
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/GoogleContainerTools/kaniko/pkg/cache"
"github.com/GoogleContainerTools/kaniko/pkg/config"
"github.com/GoogleContainerTools/kaniko/pkg/constants"
"github.com/GoogleContainerTools/kaniko/pkg/creds"
"github.com/GoogleContainerTools/kaniko/pkg/timing"
"github.com/GoogleContainerTools/kaniko/pkg/util"
"github.com/GoogleContainerTools/kaniko/pkg/version"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/empty"
"github.com/google/go-containerregistry/pkg/v1/layout"
"github.com/google/go-containerregistry/pkg/v1/mutate"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
"github.com/google/go-containerregistry/pkg/v1/tarball"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/afero"
)
type withUserAgent struct {
t http.RoundTripper
}
// for testing
var (
newRetry = transport.NewRetry
)
const (
UpstreamClientUaKey = "UPSTREAM_CLIENT_TYPE"
)
// DockerConfLocation returns the file system location of the Docker
// configuration file under the directory set in the DOCKER_CONFIG environment
// variable. If that variable is not set, it returns the OS-equivalent of
// "/kaniko/.docker/config.json".
func DockerConfLocation() string {
configFile := "config.json"
if dockerConfDir := os.Getenv("DOCKER_CONFIG"); dockerConfDir != "" {
return filepath.Join(dockerConfDir, configFile)
}
return string(os.PathSeparator) + filepath.Join("kaniko", ".docker", configFile)
}
func (w *withUserAgent) RoundTrip(r *http.Request) (*http.Response, error) {
ua := []string{fmt.Sprintf("kaniko/%s", version.Version())}
if upstream := os.Getenv(UpstreamClientUaKey); upstream != "" {
ua = append(ua, upstream)
}
r.Header.Set("User-Agent", strings.Join(ua, ","))
return w.t.RoundTrip(r)
}
// for testing
var (
fs = afero.NewOsFs()
execCommand = exec.Command
checkRemotePushPermission = remote.CheckPushPermission
)
// CheckPushPermissions checks that the configured credentials can be used to
// push to every specified destination.
func CheckPushPermissions(opts *config.KanikoOptions) error {
if opts.NoPush {
return nil
}
checked := map[string]bool{}
for _, destination := range opts.Destinations {
destRef, err := name.NewTag(destination, name.WeakValidation)
if err != nil {
return errors.Wrap(err, "getting tag for destination")
}
if checked[destRef.Context().RepositoryStr()] {
continue
}
registryName := destRef.Repository.Registry.Name()
// Historically kaniko was pre-configured by default with gcr credential helper,
// in here we keep the backwards compatibility by enabling the GCR helper only
// when gcr.io (or pkg.dev) is in one of the destinations.
if registryName == "gcr.io" || strings.HasSuffix(registryName, ".gcr.io") || strings.HasSuffix(registryName, ".pkg.dev") {
// Checking for existence of docker.config as it's normally required for
// authenticated registries and prevent overwriting user provided docker conf
if _, err := fs.Stat(DockerConfLocation()); os.IsNotExist(err) {
flags := fmt.Sprintf("--registries=%s", registryName)
if err := execCommand("docker-credential-gcr", "configure-docker", flags).Run(); err != nil {
return errors.Wrap(err, "error while configuring docker-credential-gcr helper")
}
}
}
if opts.Insecure || opts.InsecureRegistries.Contains(registryName) {
newReg, err := name.NewRegistry(registryName, name.WeakValidation, name.Insecure)
if err != nil {
return errors.Wrap(err, "getting new insecure registry")
}
destRef.Repository.Registry = newReg
}
tr := newRetry(util.MakeTransport(opts, registryName))
if err := checkRemotePushPermission(destRef, creds.GetKeychain(), tr); err != nil {
return errors.Wrapf(err, "checking push permission for %q", destRef)
}
checked[destRef.Context().RepositoryStr()] = true
}
return nil
}
func getDigest(image v1.Image) ([]byte, error) {
digest, err := image.Digest()
if err != nil {
return nil, err
}
return []byte(digest.String()), nil
}
// DoPush is responsible for pushing image to the destinations specified in opts
func DoPush(image v1.Image, opts *config.KanikoOptions) error {
t := timing.Start("Total Push Time")
var digestByteArray []byte
var builder strings.Builder
if opts.DigestFile != "" || opts.ImageNameDigestFile != "" {
var err error
digestByteArray, err = getDigest(image)
if err != nil {
return errors.Wrap(err, "error fetching digest")
}
}
if opts.DigestFile != "" {
err := ioutil.WriteFile(opts.DigestFile, digestByteArray, 0644)
if err != nil {
return errors.Wrap(err, "writing digest to file failed")
}
}
if opts.OCILayoutPath != "" {
path, err := layout.Write(opts.OCILayoutPath, empty.Index)
if err != nil {
return errors.Wrap(err, "writing empty layout")
}
if err := path.AppendImage(image); err != nil {
return errors.Wrap(err, "appending image")
}
}
destRefs := []name.Tag{}
for _, destination := range opts.Destinations {
destRef, err := name.NewTag(destination, name.WeakValidation)
if err != nil {
return errors.Wrap(err, "getting tag for destination")
}
if opts.ImageNameDigestFile != "" {
imageName := []byte(destRef.Repository.Name() + "@")
builder.Write(append(imageName, digestByteArray...))
builder.WriteString("\n")
}
destRefs = append(destRefs, destRef)
}
if opts.ImageNameDigestFile != "" {
err := ioutil.WriteFile(opts.ImageNameDigestFile, []byte(builder.String()), 0644)
if err != nil {
return errors.Wrap(err, "writing image name with digest to file failed")
}
}
if opts.TarPath != "" {
tagToImage := map[name.Tag]v1.Image{}
for _, destRef := range destRefs {
tagToImage[destRef] = image
}
return tarball.MultiWriteToFile(opts.TarPath, tagToImage)
}
if opts.NoPush {
logrus.Info("Skipping push to container registry due to --no-push flag")
return nil
}
// continue pushing unless an error occurs
for _, destRef := range destRefs {
registryName := destRef.Repository.Registry.Name()
if opts.Insecure || opts.InsecureRegistries.Contains(registryName) {
newReg, err := name.NewRegistry(registryName, name.WeakValidation, name.Insecure)
if err != nil {
return errors.Wrap(err, "getting new insecure registry")
}
destRef.Repository.Registry = newReg
}
pushAuth, err := creds.GetKeychain().Resolve(destRef.Context().Registry)
if err != nil {
return errors.Wrap(err, "resolving pushAuth")
}
tr := newRetry(util.MakeTransport(opts, registryName))
rt := &withUserAgent{t: tr}
if err := remote.Write(destRef, image, remote.WithAuth(pushAuth), remote.WithTransport(rt)); err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to push to destination %s", destRef))
}
}
timing.DefaultRun.Stop(t)
return writeImageOutputs(image, destRefs)
}
func writeImageOutputs(image v1.Image, destRefs []name.Tag) error {
dir := os.Getenv("BUILDER_OUTPUT")
if dir == "" {
return nil
}
f, err := fs.Create(filepath.Join(dir, "images"))
if err != nil {
return err
}
defer f.Close()
d, err := image.Digest()
if err != nil {
return err
}
type imageOutput struct {
Name string `json:"name"`
Digest string `json:"digest"`
}
for _, r := range destRefs {
if err := json.NewEncoder(f).Encode(imageOutput{
Name: r.String(),
Digest: d.String(),
}); err != nil {
return err
}
}
return nil
}
// pushLayerToCache pushes layer (tagged with cacheKey) to opts.Cache
// if opts.Cache doesn't exist, infer the cache from the given destination
func pushLayerToCache(opts *config.KanikoOptions, cacheKey string, tarPath string, createdBy string) error {
layer, err := tarball.LayerFromFile(tarPath)
if err != nil {
return err
}
cache, err := cache.Destination(opts, cacheKey)
if err != nil {
return errors.Wrap(err, "getting cache destination")
}
logrus.Infof("Pushing layer %s to cache now", cache)
empty := empty.Image
empty, err = mutate.CreatedAt(empty, v1.Time{Time: time.Now()})
if err != nil {
return errors.Wrap(err, "setting empty image created time")
}
empty, err = mutate.Append(empty,
mutate.Addendum{
Layer: layer,
History: v1.History{
Author: constants.Author,
CreatedBy: createdBy,
},
},
)
if err != nil {
return errors.Wrap(err, "appending layer onto empty image")
}
cacheOpts := *opts
cacheOpts.TarPath = "" // tarPath doesn't make sense for Docker layers
cacheOpts.NoPush = false // we want to push cached layers
cacheOpts.Destinations = []string{cache}
cacheOpts.InsecureRegistries = opts.InsecureRegistries
cacheOpts.SkipTLSVerifyRegistries = opts.SkipTLSVerifyRegistries
return DoPush(empty, &cacheOpts)
}