-
Notifications
You must be signed in to change notification settings - Fork 561
/
push.go
238 lines (216 loc) · 8.34 KB
/
push.go
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
/*
Copyright The containerd Authors.
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 image
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"github.com/containerd/containerd"
"github.com/containerd/containerd/content"
"github.com/containerd/containerd/images"
"github.com/containerd/containerd/images/converter"
"github.com/containerd/containerd/reference"
refdocker "github.com/containerd/containerd/reference/docker"
"github.com/containerd/containerd/remotes"
"github.com/containerd/containerd/remotes/docker"
dockerconfig "github.com/containerd/containerd/remotes/docker/config"
"github.com/containerd/log"
"github.com/containerd/nerdctl/v2/pkg/api/types"
"github.com/containerd/nerdctl/v2/pkg/errutil"
"github.com/containerd/nerdctl/v2/pkg/imgutil/dockerconfigresolver"
"github.com/containerd/nerdctl/v2/pkg/imgutil/push"
"github.com/containerd/nerdctl/v2/pkg/ipfs"
"github.com/containerd/nerdctl/v2/pkg/platformutil"
"github.com/containerd/nerdctl/v2/pkg/referenceutil"
"github.com/containerd/nerdctl/v2/pkg/signutil"
"github.com/containerd/nerdctl/v2/pkg/snapshotterutil"
"github.com/containerd/stargz-snapshotter/estargz"
"github.com/containerd/stargz-snapshotter/estargz/zstdchunked"
estargzconvert "github.com/containerd/stargz-snapshotter/nativeconverter/estargz"
"github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
// Push pushes an image specified by `rawRef`.
func Push(ctx context.Context, client *containerd.Client, rawRef string, options types.ImagePushOptions) error {
if scheme, ref, err := referenceutil.ParseIPFSRefWithScheme(rawRef); err == nil {
if scheme != "ipfs" {
return fmt.Errorf("ipfs scheme is only supported but got %q", scheme)
}
log.G(ctx).Infof("pushing image %q to IPFS", ref)
var ipfsPath string
if options.IpfsAddress != "" {
dir, err := os.MkdirTemp("", "apidirtmp")
if err != nil {
return err
}
defer os.RemoveAll(dir)
if err := os.WriteFile(filepath.Join(dir, "api"), []byte(options.IpfsAddress), 0600); err != nil {
return err
}
ipfsPath = dir
}
var layerConvert converter.ConvertFunc
if options.Estargz {
layerConvert = eStargzConvertFunc()
}
c, err := ipfs.Push(ctx, client, ref, layerConvert, options.AllPlatforms, options.Platforms, options.IpfsEnsureImage, ipfsPath)
if err != nil {
log.G(ctx).WithError(err).Warnf("ipfs push failed")
return err
}
fmt.Fprintln(options.Stdout, c)
return nil
}
named, err := refdocker.ParseDockerRef(rawRef)
if err != nil {
return err
}
ref := named.String()
refDomain := refdocker.Domain(named)
platMC, err := platformutil.NewMatchComparer(options.AllPlatforms, options.Platforms)
if err != nil {
return err
}
pushRef := ref
if !options.AllPlatforms {
pushRef = ref + "-tmp-reduced-platform"
// Push fails with "400 Bad Request" when the manifest is multi-platform but we do not locally have multi-platform blobs.
// So we create a tmp reduced-platform image to avoid the error.
platImg, err := converter.Convert(ctx, client, pushRef, ref, converter.WithPlatform(platMC))
if err != nil {
if len(options.Platforms) == 0 {
return fmt.Errorf("failed to create a tmp single-platform image %q: %w", pushRef, err)
}
return fmt.Errorf("failed to create a tmp reduced-platform image %q (platform=%v): %w", pushRef, options.Platforms, err)
}
defer client.ImageService().Delete(ctx, platImg.Name, images.SynchronousDelete())
log.G(ctx).Infof("pushing as a reduced-platform image (%s, %s)", platImg.Target.MediaType, platImg.Target.Digest)
}
if options.Estargz {
pushRef = ref + "-tmp-esgz"
esgzImg, err := converter.Convert(ctx, client, pushRef, ref, converter.WithPlatform(platMC), converter.WithLayerConvertFunc(eStargzConvertFunc()))
if err != nil {
return fmt.Errorf("failed to convert to eStargz: %v", err)
}
defer client.ImageService().Delete(ctx, esgzImg.Name, images.SynchronousDelete())
log.G(ctx).Infof("pushing as an eStargz image (%s, %s)", esgzImg.Target.MediaType, esgzImg.Target.Digest)
}
// In order to push images where most layers are the same but the
// repository name is different, it is necessary to refresh the
// PushTracker. Otherwise, the MANIFEST_BLOB_UNKNOWN error will occur due
// to the registry not creating the corresponding layer link file,
// resulting in the failure of the entire image push.
pushTracker := docker.NewInMemoryTracker()
pushFunc := func(r remotes.Resolver) error {
return push.Push(ctx, client, r, pushTracker, options.Stdout, pushRef, ref, platMC, options.AllowNondistributableArtifacts, options.Quiet)
}
var dOpts []dockerconfigresolver.Opt
if options.GOptions.InsecureRegistry {
log.G(ctx).Warnf("skipping verifying HTTPS certs for %q", refDomain)
dOpts = append(dOpts, dockerconfigresolver.WithSkipVerifyCerts(true))
}
dOpts = append(dOpts, dockerconfigresolver.WithHostsDirs(options.GOptions.HostsDir))
ho, err := dockerconfigresolver.NewHostOptions(ctx, refDomain, dOpts...)
if err != nil {
return err
}
resolverOpts := docker.ResolverOptions{
Tracker: pushTracker,
Hosts: dockerconfig.ConfigureHosts(ctx, *ho),
}
resolver := docker.NewResolver(resolverOpts)
if err = pushFunc(resolver); err != nil {
// In some circumstance (e.g. people just use 80 port to support pure http), the error will contain message like "dial tcp <port>: connection refused"
if !errutil.IsErrHTTPResponseToHTTPSClient(err) && !errutil.IsErrConnectionRefused(err) {
return err
}
if options.GOptions.InsecureRegistry {
log.G(ctx).WithError(err).Warnf("server %q does not seem to support HTTPS, falling back to plain HTTP", refDomain)
dOpts = append(dOpts, dockerconfigresolver.WithPlainHTTP(true))
resolver, err = dockerconfigresolver.New(ctx, refDomain, dOpts...)
if err != nil {
return err
}
return pushFunc(resolver)
}
log.G(ctx).WithError(err).Errorf("server %q does not seem to support HTTPS", refDomain)
log.G(ctx).Info("Hint: you may want to try --insecure-registry to allow plain HTTP (if you are in a trusted network)")
return err
}
img, err := client.ImageService().Get(ctx, pushRef)
if err != nil {
return err
}
refSpec, err := reference.Parse(pushRef)
if err != nil {
return err
}
signRef := fmt.Sprintf("%s@%s", refSpec.String(), img.Target.Digest.String())
if err = signutil.Sign(signRef,
options.GOptions.Experimental,
options.SignOptions); err != nil {
return err
}
if options.GOptions.Snapshotter == "soci" {
if err = snapshotterutil.CreateSoci(ref, options.GOptions, options.AllPlatforms, options.Platforms, options.SociOptions); err != nil {
return err
}
if err = snapshotterutil.PushSoci(ref, options.GOptions, options.AllPlatforms, options.Platforms); err != nil {
return err
}
}
if options.Quiet {
fmt.Fprintln(options.Stdout, ref)
}
return nil
}
func eStargzConvertFunc() converter.ConvertFunc {
convertToESGZ := estargzconvert.LayerConvertFunc()
return func(ctx context.Context, cs content.Store, desc ocispec.Descriptor) (*ocispec.Descriptor, error) {
if isReusableESGZ(ctx, cs, desc) {
log.L.Infof("reusing estargz %s without conversion", desc.Digest)
return nil, nil
}
newDesc, err := convertToESGZ(ctx, cs, desc)
if err != nil {
return nil, err
}
log.L.Infof("converted %q to %s", desc.MediaType, newDesc.Digest)
return newDesc, err
}
}
func isReusableESGZ(ctx context.Context, cs content.Store, desc ocispec.Descriptor) bool {
dgstStr, ok := desc.Annotations[estargz.TOCJSONDigestAnnotation]
if !ok {
return false
}
tocdgst, err := digest.Parse(dgstStr)
if err != nil {
return false
}
ra, err := cs.ReaderAt(ctx, desc)
if err != nil {
return false
}
defer ra.Close()
r, err := estargz.Open(io.NewSectionReader(ra, 0, desc.Size), estargz.WithDecompressors(new(zstdchunked.Decompressor)))
if err != nil {
return false
}
if _, err := r.VerifyTOC(tocdgst); err != nil {
return false
}
return true
}