-
Notifications
You must be signed in to change notification settings - Fork 82
/
tag.go
358 lines (334 loc) · 9.55 KB
/
tag.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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package reg
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
// crypto libraries included for go-digest
_ "crypto/sha256"
_ "crypto/sha512"
"github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
"github.com/regclient/regclient/internal/httplink"
"github.com/regclient/regclient/internal/reghttp"
"github.com/regclient/regclient/scheme"
"github.com/regclient/regclient/types/descriptor"
"github.com/regclient/regclient/types/docker/schema2"
"github.com/regclient/regclient/types/errs"
"github.com/regclient/regclient/types/manifest"
"github.com/regclient/regclient/types/mediatype"
v1 "github.com/regclient/regclient/types/oci/v1"
"github.com/regclient/regclient/types/platform"
"github.com/regclient/regclient/types/ref"
"github.com/regclient/regclient/types/tag"
)
// TagDelete removes a tag from a repository.
// It first attempts the newer OCI API to delete by tag name (not widely supported).
// If the OCI API fails, it falls back to pushing a unique empty manifest and deleting that.
func (reg *Reg) TagDelete(ctx context.Context, r ref.Ref) error {
var tempManifest manifest.Manifest
if r.Tag == "" {
return errs.ErrMissingTag
}
// attempt to delete the tag directly, available in OCI distribution-spec, and Hub API
req := ®http.Req{
Host: r.Registry,
NoMirrors: true,
APIs: map[string]reghttp.ReqAPI{
"": {
Method: "DELETE",
Repository: r.Repository,
Path: "manifests/" + r.Tag,
IgnoreErr: true, // do not trigger backoffs if this fails
},
"hub": {
Method: "DELETE",
Path: "repositories/" + r.Repository + "/tags/" + r.Tag + "/",
},
},
}
resp, err := reg.reghttp.Do(ctx, req)
if resp != nil {
defer resp.Close()
}
// TODO: Hub may return a different status
if err == nil && resp != nil && resp.HTTPResponse().StatusCode == 202 {
return nil
}
// ignore errors, fallback to creating a temporary manifest to replace the tag and deleting that manifest
// lookup the current manifest media type
curManifest, err := reg.ManifestHead(ctx, r)
if err != nil && errors.Is(err, errs.ErrUnsupportedAPI) {
curManifest, err = reg.ManifestGet(ctx, r)
}
if err != nil {
return err
}
// create empty image config with single label
// Note, this should be MediaType specific, but it appears that docker uses OCI for the config
now := time.Now()
conf := v1.Image{
Created: &now,
Config: v1.ImageConfig{
Labels: map[string]string{
"delete-tag": r.Tag,
"delete-date": now.String(),
},
},
Platform: platform.Platform{
OS: "linux",
Architecture: "amd64",
},
History: []v1.History{
{
Created: &now,
CreatedBy: "# regclient",
Comment: "empty JSON blob",
},
},
RootFS: v1.RootFS{
Type: "layers",
DiffIDs: []digest.Digest{
descriptor.EmptyDigest,
},
},
}
confB, err := json.Marshal(conf)
if err != nil {
return err
}
digester := digest.Canonical.Digester()
confBuf := bytes.NewBuffer(confB)
_, err = confBuf.WriteTo(digester.Hash())
if err != nil {
return err
}
confDigest := digester.Digest()
// create manifest with config, matching the original tag manifest type
switch manifest.GetMediaType(curManifest) {
case mediatype.OCI1Manifest, mediatype.OCI1ManifestList:
tempManifest, err = manifest.New(manifest.WithOrig(v1.Manifest{
Versioned: v1.ManifestSchemaVersion,
MediaType: mediatype.OCI1Manifest,
Config: descriptor.Descriptor{
MediaType: mediatype.OCI1ImageConfig,
Digest: confDigest,
Size: int64(len(confB)),
},
Layers: []descriptor.Descriptor{
{
MediaType: mediatype.OCI1Layer,
Size: int64(len(descriptor.EmptyData)),
Digest: descriptor.EmptyDigest,
},
},
}))
if err != nil {
return err
}
default: // default to the docker v2 schema
tempManifest, err = manifest.New(manifest.WithOrig(schema2.Manifest{
Versioned: schema2.ManifestSchemaVersion,
Config: descriptor.Descriptor{
MediaType: mediatype.Docker2ImageConfig,
Digest: confDigest,
Size: int64(len(confB)),
},
Layers: []descriptor.Descriptor{
{
MediaType: mediatype.Docker2LayerGzip,
Size: int64(len(descriptor.EmptyData)),
Digest: descriptor.EmptyDigest,
},
},
}))
if err != nil {
return err
}
}
reg.log.WithFields(logrus.Fields{
"ref": r.Reference,
}).Debug("Sending dummy manifest to replace tag")
// push empty layer
_, err = reg.BlobPut(ctx, r, descriptor.Descriptor{Digest: descriptor.EmptyDigest, Size: int64(len(descriptor.EmptyData))}, bytes.NewReader(descriptor.EmptyData))
if err != nil {
return err
}
// push config
_, err = reg.BlobPut(ctx, r, descriptor.Descriptor{Digest: confDigest, Size: int64(len(confB))}, bytes.NewReader(confB))
if err != nil {
return fmt.Errorf("failed sending dummy config to delete %s: %w", r.CommonName(), err)
}
// push manifest to tag
err = reg.ManifestPut(ctx, r, tempManifest)
if err != nil {
return fmt.Errorf("failed sending dummy manifest to delete %s: %w", r.CommonName(), err)
}
r.Digest = tempManifest.GetDescriptor().Digest.String()
// delete manifest by digest
reg.log.WithFields(logrus.Fields{
"ref": r.Reference,
"digest": r.Digest,
}).Debug("Deleting dummy manifest")
err = reg.ManifestDelete(ctx, r)
if err != nil {
return fmt.Errorf("failed deleting dummy manifest for %s: %w", r.CommonName(), err)
}
return nil
}
// TagList returns a listing to tags from the repository
func (reg *Reg) TagList(ctx context.Context, r ref.Ref, opts ...scheme.TagOpts) (*tag.List, error) {
var config scheme.TagConfig
for _, opt := range opts {
opt(&config)
}
tl, err := reg.tagListOCI(ctx, r, config)
if err != nil {
return tl, err
}
for {
// if limit reached, stop searching
if config.Limit > 0 && len(tl.Tags) >= config.Limit {
break
}
tlHead, err := tl.RawHeaders()
if err != nil {
return tl, err
}
links, err := httplink.Parse(tlHead.Values("Link"))
if err != nil {
return tl, err
}
next, err := links.Get("rel", "next")
// if Link header with rel="next" is defined
if err == nil {
link := tl.GetURL()
if link == nil {
return tl, fmt.Errorf("tag list, failed to get URL of previous request")
}
link, err = link.Parse(next.URI)
if err != nil {
return tl, fmt.Errorf("tag list failed to parse Link: %w", err)
}
tlAdd, err := reg.tagListLink(ctx, r, config, link)
if err != nil {
return tl, fmt.Errorf("tag list failed to get Link: %w", err)
}
err = tl.Append(tlAdd)
if err != nil {
return tl, fmt.Errorf("tag list failed to append entries: %w", err)
}
} else {
// do not automatically expand tags with OCI methods,
// OCI registries should send all possible entries up to the specified limit
break
}
}
return tl, nil
}
func (reg *Reg) tagListOCI(ctx context.Context, r ref.Ref, config scheme.TagConfig) (*tag.List, error) {
query := url.Values{}
if config.Last != "" {
query.Set("last", config.Last)
}
if config.Limit > 0 {
query.Set("n", strconv.Itoa(config.Limit))
}
headers := http.Header{
"Accept": []string{"application/json"},
}
req := ®http.Req{
Host: r.Registry,
APIs: map[string]reghttp.ReqAPI{
"": {
Method: "GET",
Repository: r.Repository,
Path: "tags/list",
Query: query,
Headers: headers,
},
},
}
resp, err := reg.reghttp.Do(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to list tags for %s: %w", r.CommonName(), err)
}
defer resp.Close()
if resp.HTTPResponse().StatusCode != 200 {
return nil, fmt.Errorf("failed to list tags for %s: %w", r.CommonName(), reghttp.HTTPError(resp.HTTPResponse().StatusCode))
}
respBody, err := io.ReadAll(resp)
if err != nil {
reg.log.WithFields(logrus.Fields{
"err": err,
"ref": r.CommonName(),
}).Warn("Failed to read tag list")
return nil, fmt.Errorf("failed to read tags for %s: %w", r.CommonName(), err)
}
tl, err := tag.New(
tag.WithRef(r),
tag.WithRaw(respBody),
tag.WithResp(resp.HTTPResponse()),
)
if err != nil {
reg.log.WithFields(logrus.Fields{
"err": err,
"body": respBody,
"ref": r.CommonName(),
}).Warn("Failed to unmarshal tag list")
return tl, fmt.Errorf("failed to unmarshal tag list for %s: %w", r.CommonName(), err)
}
return tl, nil
}
func (reg *Reg) tagListLink(ctx context.Context, r ref.Ref, _ scheme.TagConfig, link *url.URL) (*tag.List, error) {
headers := http.Header{
"Accept": []string{"application/json"},
}
req := ®http.Req{
Host: r.Registry,
APIs: map[string]reghttp.ReqAPI{
"": {
Method: "GET",
DirectURL: link,
Repository: r.Repository,
Headers: headers,
},
},
}
resp, err := reg.reghttp.Do(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to list tags for %s: %w", r.CommonName(), err)
}
defer resp.Close()
if resp.HTTPResponse().StatusCode != 200 {
return nil, fmt.Errorf("failed to list tags for %s: %w", r.CommonName(), reghttp.HTTPError(resp.HTTPResponse().StatusCode))
}
respBody, err := io.ReadAll(resp)
if err != nil {
reg.log.WithFields(logrus.Fields{
"err": err,
"ref": r.CommonName(),
}).Warn("Failed to read tag list")
return nil, fmt.Errorf("failed to read tags for %s: %w", r.CommonName(), err)
}
tl, err := tag.New(
tag.WithRef(r),
tag.WithRaw(respBody),
tag.WithResp(resp.HTTPResponse()),
)
if err != nil {
reg.log.WithFields(logrus.Fields{
"err": err,
"body": respBody,
"ref": r.CommonName(),
}).Warn("Failed to unmarshal tag list")
return tl, fmt.Errorf("failed to unmarshal tag list for %s: %w", r.CommonName(), err)
}
return tl, nil
}