-
Notifications
You must be signed in to change notification settings - Fork 64
/
directory.go
1263 lines (1037 loc) · 32.7 KB
/
directory.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2022, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package handler
import (
"archive/tar"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"golang.org/x/sync/errgroup"
"kraftkit.sh/config"
"kraftkit.sh/internal/lockedfile"
"kraftkit.sh/internal/set"
"kraftkit.sh/internal/version"
"kraftkit.sh/log"
"kraftkit.sh/oci/cache"
"kraftkit.sh/oci/simpleauth"
ociutils "kraftkit.sh/oci/utils"
"github.com/containerd/containerd/content"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/types"
"github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
const (
DirectoryHandlerDigestsDir = "digests"
DirectoryHandlerIndexesDir = "indexes"
)
type DirectoryHandler struct {
path string
auths map[string]config.AuthConfig
}
func NewDirectoryHandler(path string, auths map[string]config.AuthConfig) (*DirectoryHandler, error) {
if err := os.MkdirAll(path, 0o775); err != nil {
return nil, fmt.Errorf("could not create local oci cache directory: %w", err)
}
return &DirectoryHandler{
path: path,
auths: auths,
}, nil
}
// DigestInfo implements DigestResolver.
func (handle *DirectoryHandler) DigestInfo(ctx context.Context, needle digest.Digest) (*content.Info, error) {
manifestsDir := filepath.Join(handle.path, DirectoryHandlerDigestsDir)
// If the digest directory does not exist and return nil, since there's
// nothing to return.
if _, err := os.Stat(manifestsDir); err != nil {
return nil, err
}
digestPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
needle.Algorithm().String(),
needle.Encoded(),
)
st, err := os.Stat(digestPath)
if err != nil {
return nil, err
}
return &content.Info{
Digest: needle,
Size: st.Size(),
CreatedAt: time.Time{}, // TODO(nderjung): General-purpose stat not avail.
UpdatedAt: st.ModTime(),
}, nil
}
// PullDigest implements DigestPuller.
func (handle *DirectoryHandler) PullDigest(ctx context.Context, mediaType, fullref string, dgst digest.Digest, plat *ocispec.Platform, onProgress func(float64)) error {
ref, err := name.ParseReference(fullref)
if err != nil {
return err
}
authConfig := &authn.AuthConfig{}
ropts := []remote.Option{
remote.WithContext(ctx),
remote.WithUserAgent(version.UserAgent()),
remote.WithPlatform(v1.Platform{
Architecture: plat.Architecture,
OS: plat.OS,
OSFeatures: plat.OSFeatures,
}),
}
// Annoyingly convert between regtypes and authn.
if auth, ok := handle.auths[ref.Context().RegistryStr()]; ok {
authConfig.Username = auth.User
authConfig.Password = auth.Token
ropts = append(ropts,
remote.WithAuth(&simpleauth.SimpleAuthenticator{
Auth: authConfig,
}),
)
if !auth.VerifySSL {
transport := remote.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
ropts = append(ropts, remote.WithTransport(transport))
}
}
switch mediaType {
case ocispec.MediaTypeImageIndex:
indexV1, err := cache.RemoteIndex(ref, ropts...)
if err != nil {
return fmt.Errorf("could not retrieve remote index: %w", err)
}
indexDgst, err := indexV1.Digest()
if err != nil {
return fmt.Errorf("could not get index digest: %w", err)
}
localManifests := []ocispec.Descriptor{}
var indexTagPath string
if !strings.ContainsRune(fullref, '@') && len(strings.SplitN(fullref, ":", 2)) == 2 {
indexTagPath = filepath.Join(
handle.path,
DirectoryHandlerIndexesDir,
strings.ReplaceAll(fullref, ":", string(filepath.Separator)),
)
if indexFi, err := os.Stat(indexTagPath); err == nil {
if indexFi.Mode()&fs.ModeSymlink == 0 {
oldIndexDigestPath, err := filepath.EvalSymlinks(indexTagPath)
if err != nil {
return err
}
if err := os.RemoveAll(indexTagPath); err != nil {
return fmt.Errorf("could not remove index symbolic link: %w", err)
}
// Check if a local index already exists, if it does we will append the
// requested manifest to it.
if _, err := os.Stat(oldIndexDigestPath); err == nil {
localIndexRaw, err := lockedfile.Read(oldIndexDigestPath)
if err != nil {
return fmt.Errorf("could not read existing index: %w", err)
}
localIndex := ocispec.Index{}
if err = json.Unmarshal(localIndexRaw, &localIndex); err != nil {
return fmt.Errorf("could not unmarshal raw index: %w", err)
}
// Save the existing local manifests
localManifests = localIndex.Manifests
if err := os.RemoveAll(oldIndexDigestPath); err != nil {
return fmt.Errorf("could not remove existing index: %w", err)
}
}
}
}
}
log.G(ctx).
WithField("digest", indexDgst.String()).
Debugf("pulling index")
var indexRaw []byte
index := ocispec.Index{}
indexRaw, err = indexV1.RawManifest()
if err != nil {
return fmt.Errorf("could not get raw index: %w", err)
}
if err = json.Unmarshal(indexRaw, &index); err != nil {
return fmt.Errorf("could not unmarshal raw index: %w", err)
}
newManifestPlatChecksums := map[string]bool{}
newManifests := []ocispec.Descriptor{}
// Remove manifests that do not match the platform selector.
manifestsToPull := []ocispec.Descriptor{}
checkManifest:
for _, manifest := range index.Manifests {
if plat.OS != "" && plat.OS != manifest.Platform.OS {
continue
}
if plat.Architecture != "" && plat.Architecture != manifest.Platform.Architecture {
continue
}
if len(plat.OSFeatures) > 0 {
available := set.NewStringSet(manifest.Platform.OSFeatures...)
// Iterate through the platform selector's requested set of features and
// skip only if the descriptor does not contain the requested feature.
for _, a := range plat.OSFeatures {
if !available.Contains(a) {
continue checkManifest
}
}
}
manifestsToPull = append(manifestsToPull, manifest)
}
eg, egCtx := errgroup.WithContext(ctx)
var mu sync.RWMutex
for i := range manifestsToPull {
eg.Go(func(i int) func() error {
return func() error {
if err := handle.PullDigest(egCtx,
ocispec.MediaTypeImageManifest,
fullref,
manifestsToPull[i].Digest,
plat,
onProgress,
); err != nil {
return fmt.Errorf("could not pull manifest: %w", err)
}
checksum, err := ociutils.PlatformChecksum(fullref, manifestsToPull[i].Platform)
if err != nil {
return fmt.Errorf("could not calculate platform checksum for '%s': %w", manifestsToPull[i].Digest.String(), err)
}
mu.Lock()
newManifestPlatChecksums[checksum] = true
newManifestPlatChecksums[manifestsToPull[i].Digest.String()] = true
newManifests = append(newManifests, manifestsToPull[i])
mu.Unlock()
return nil
}
}(i))
}
if err := eg.Wait(); err != nil {
return err
}
// Compare the local digests with the new digest and remove local digests
// which have the same platform checksum and zero layers.
for _, localManifest := range localManifests {
// Bypass the checksum check if the manifest digest is the same as the
// requested manifest, this can be safely stored in the index. Use the
// same `newManifestPlatChecksums` map to keep track of whether we have
// performed this .
if _, ok := newManifestPlatChecksums[localManifest.Digest.String()]; ok {
continue
}
if localManifest.Digest.String() == dgst.String() {
newManifests = append(newManifests, localManifest)
newManifestPlatChecksums[dgst.String()] = true
continue
}
checksum, err := ociutils.PlatformChecksum(fullref, localManifest.Platform)
if err != nil {
return fmt.Errorf("could not calculate platform checksum for '%s': %w", localManifest.Digest.String(), err)
}
// If this checksum does not exist in the existing list, we can safely add
// it to the new index.
if _, ok := newManifestPlatChecksums[checksum]; ok {
oldManifestPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
localManifest.Digest.Algorithm().String(),
localManifest.Digest.Encoded(),
)
if err := os.Remove(oldManifestPath); err != nil {
return fmt.Errorf("could not remove old manifest '%s': %w", oldManifestPath, err)
}
continue
}
newManifests = append(newManifests, localManifest)
}
index.Manifests = newManifests
indexRaw, err = json.Marshal(&index)
if err != nil {
return fmt.Errorf("could not marshal raw index: %w", err)
}
newIndexDigest := digest.FromBytes(indexRaw)
newIndexDigestPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
newIndexDigest.Algorithm().String(),
newIndexDigest.Encoded(),
)
if err = os.MkdirAll(filepath.Dir(newIndexDigestPath), 0o775); err != nil {
return fmt.Errorf("could not make manifest parent directories: %w", err)
}
indexWriter, err := lockedfile.Edit(newIndexDigestPath)
if err != nil {
return fmt.Errorf("could not get manifest file descriptor: %w", err)
}
defer indexWriter.Close()
if _, err = indexWriter.Write(indexRaw); err != nil {
return fmt.Errorf("could not write manifest: %w", err)
}
if len(indexTagPath) > 0 {
// Create the parent directory if it does not exist
if err := os.MkdirAll(filepath.Dir(indexTagPath), 0o774); err != nil {
return fmt.Errorf("could not make parent directory: %w", err)
}
if err := os.Symlink(newIndexDigestPath, indexTagPath); err != nil {
return err
}
}
case ocispec.MediaTypeImageManifest:
v1Index, err := cache.RemoteIndex(ref, ropts...)
if err != nil {
return fmt.Errorf("could not retrieve remote manifest: %w", err)
}
// Only pull the manifest if does not exist locally.
manifest, err := handle.ResolveManifest(ctx, fullref, dgst)
if err != nil {
manifestPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
dgst.Algorithm().String(),
dgst.Encoded(),
)
hash, err := v1.NewHash(dgst.String())
if err != nil {
return fmt.Errorf("could not calculate image digest: %w", err)
}
image, err := v1Index.Image(hash)
if err != nil {
return fmt.Errorf("could not retrieve image: %w", err)
}
log.G(ctx).
WithField("digest", dgst.String()).
Debugf("pulling manifest")
manifestRaw, err := image.RawManifest()
if err != nil {
return fmt.Errorf("could not get raw manifest: %w", err)
}
if err = json.Unmarshal(manifestRaw, &manifest); err != nil {
return fmt.Errorf("could not unmarshal raw manifest: %w", err)
}
if err = os.MkdirAll(filepath.Dir(manifestPath), 0o775); err != nil {
return fmt.Errorf("could not make manifest parent directories: %w", err)
}
manifestWriter, err := os.Create(manifestPath)
if err != nil {
return fmt.Errorf("could not get manifest file descriptor: %w", err)
}
defer manifestWriter.Close()
if _, err = manifestWriter.Write(manifestRaw); err != nil {
return fmt.Errorf("could not write manifest: %w", err)
}
}
configPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
manifest.Config.Digest.Algorithm().String(),
manifest.Config.Digest.Hex(),
)
// Only pull the config if does not exist locally.
if _, err := os.Stat(configPath); err != nil {
// NOTE(nderjung): Unfortunately, the `remote` package does not support
// simply `Get`ting the config, so we must traverse backwards to the image
// (and therefore make a remote request to an image manifest, even if we
// may have a copy of it locally, adding 1 additional external request to
// the registry).
log.G(ctx).
WithField("digest", manifest.Config.Digest.String()).
Debugf("pulling config")
image, err := remote.Image(ref, ropts...)
if err != nil {
return fmt.Errorf("could not retrieve remote manifest: %w", err)
}
configRaw, err := image.RawConfigFile()
if err != nil {
return fmt.Errorf("could not get raw config: %w", err)
}
config := ocispec.Image{}
if err = json.Unmarshal(configRaw, &config); err != nil {
return fmt.Errorf("could not unmarshal raw config: %w", err)
}
if err = os.MkdirAll(filepath.Dir(configPath), 0o775); err != nil {
return fmt.Errorf("could not create config parent directories: %w", err)
}
configWriter, err := os.Create(configPath)
if err != nil {
return fmt.Errorf("could not get config file descriptor: %w", err)
}
defer configWriter.Close()
if _, err = configWriter.Write(configRaw); err != nil {
return fmt.Errorf("could not write raw config: %w", err)
}
}
// First calculate the total size of all layers. This is done so that the
// onProgress callback correctly reports
var totalSize int64
for _, layer := range manifest.Layers {
totalSize += layer.Size
}
for _, layer := range manifest.Layers {
if err := handle.PullDigest(ctx,
ocispec.MediaTypeImageLayer,
fullref,
layer.Digest,
plat,
func(size float64) {
onProgress(size / float64(totalSize))
},
); err != nil {
return fmt.Errorf("could not pull layer from digest: %w", err)
}
}
case ocispec.MediaTypeImageLayer, ocispec.MediaTypeImageLayerGzip:
log.G(ctx).
WithField("digest", dgst.String()).
Debugf("pulling layer")
fullref = fmt.Sprintf("%s/%s@%s",
ref.Context().RegistryStr(),
ref.Context().RepositoryStr(),
dgst.String(),
)
layerV1Dgst, err := name.NewDigest(fullref)
if err != nil {
return fmt.Errorf("could not generate full digest: %w", err)
}
layer, err := remote.Layer(layerV1Dgst, ropts...)
if err != nil {
return fmt.Errorf("could not get remote layer: %w", err)
}
mediaType, err := layer.MediaType()
if err != nil {
return fmt.Errorf("could not get media type of layer: %w", err)
}
var reader io.ReadCloser
switch mediaType {
case ocispec.MediaTypeImageLayer, types.DockerUncompressedLayer:
reader, err = layer.Uncompressed()
case ocispec.MediaTypeImageLayerGzip, types.DockerLayer:
reader, err = layer.Compressed()
default:
return fmt.Errorf("unsupported layer mediatype '%s'", mediaType)
}
if err != nil {
return fmt.Errorf("could not open layer reader: %w", err)
}
var progresReader io.Reader
if onProgress != nil {
progresReader = &progressWriter{
Reader: reader,
onProgress: onProgress,
}
} else {
progresReader = reader
}
layerPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
dgst.Algorithm().String(),
dgst.Encoded(),
)
if err = os.MkdirAll(filepath.Dir((layerPath)), 0o775); err != nil {
return fmt.Errorf("could not make directory: %w", err)
}
blob, err := os.OpenFile(layerPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o664)
if err != nil {
return fmt.Errorf("could not create layer: %w", err)
}
if _, err := io.Copy(blob, progresReader); err != nil {
return fmt.Errorf("could not write layer: %w", err)
}
default:
return fmt.Errorf("cannot push descriptor: unsupported mediatype: %s", mediaType)
}
return nil
}
// SaveDescriptor implements DescriptorSaver.
func (handle *DirectoryHandler) SaveDescriptor(ctx context.Context, ref string, desc ocispec.Descriptor, reader io.Reader, onProgress func(float64)) error {
blobPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
desc.Digest.Algorithm().String(),
desc.Digest.Encoded(),
)
// Create the parent directory if it does not exist
if err := os.MkdirAll(filepath.Dir(blobPath), 0o774); err != nil {
return fmt.Errorf("could not make parent directory: %w", err)
}
blob, err := os.OpenFile(blobPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o664)
if err != nil {
return fmt.Errorf("could not create blob: %w", err)
}
var progresReader io.Reader
if onProgress != nil {
progresReader = &progressWriter{
Reader: reader,
onProgress: onProgress,
}
} else {
progresReader = reader
}
log.G(ctx).
WithField("ref", ref).
WithField("mediaType", desc.MediaType).
WithField("digest", desc.Digest.String()).
Trace("saving")
if _, err := io.Copy(blob, progresReader); err != nil {
return err
}
// Create a symbolic representing the tag if this is an index.
switch desc.MediaType {
case ocispec.MediaTypeImageIndex:
if !strings.ContainsRune(ref, '@') && len(strings.SplitN(ref, ":", 2)) == 2 {
indexTagPath := filepath.Join(
handle.path,
DirectoryHandlerIndexesDir,
strings.ReplaceAll(ref, ":", string(filepath.Separator)),
)
if _, err := os.Stat(indexTagPath); err == nil {
if err := os.RemoveAll(indexTagPath); err != nil {
return fmt.Errorf("could not create symbolic link to new index: %w", err)
}
}
// Create the parent directory if it does not exist
if err := os.MkdirAll(filepath.Dir(indexTagPath), 0o774); err != nil {
return fmt.Errorf("could not make parent directory: %w", err)
}
if err := os.Symlink(blobPath, indexTagPath); err != nil {
return fmt.Errorf("creating symbolic link to new index: %w", err)
}
}
}
return nil
}
// PushDescriptor implements DescriptorPusher.
func (handle *DirectoryHandler) PushDescriptor(ctx context.Context, fullref string, desc *ocispec.Descriptor) error {
ref, err := name.ParseReference(fullref)
if err != nil {
return err
}
ropts := []remote.Option{
remote.WithContext(ctx),
remote.WithUserAgent(version.UserAgent()),
}
authConfig := &authn.AuthConfig{}
// Annoyingly convert between regtypes and authn.
if auth, ok := handle.auths[ref.Context().RegistryStr()]; ok {
authConfig.Username = auth.User
authConfig.Password = auth.Token
ropts = append(ropts,
remote.WithAuth(&simpleauth.SimpleAuthenticator{
Auth: authConfig,
}),
)
if !auth.VerifySSL {
transport := remote.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
ropts = append(ropts, remote.WithTransport(transport))
}
}
log.G(ctx).
WithField("ref", ref.Name()).
WithField("mediaType", desc.MediaType).
WithField("digest", desc.Digest.String()).
Debugf("pushing")
switch desc.MediaType {
case ocispec.MediaTypeImageIndex:
return remote.WriteIndex(ref,
&DirectoryIndex{
ctx: ctx,
desc: desc,
handle: handle,
fullref: fullref,
},
ropts...,
)
case ocispec.MediaTypeImageManifest:
image, err := handle.resolveImage(ctx, fullref, desc.Digest)
if err != nil {
return err
}
return remote.Write(ref,
DirectoryManifest{
image: image,
desc: desc,
handle: handle,
},
append(ropts, remote.WithPlatform(v1.Platform{
Architecture: image.Architecture,
OS: image.OS,
OSVersion: image.OSVersion,
OSFeatures: image.OSFeatures,
Variant: image.Variant,
}))...,
)
// NOTE(nderjung): The manifest writer is able to handle pushing layers.
// Currently within KraftKit, pushing a layer directly is not used and
// therefore this code is not implemented.
// case ocispec.MediaTypeImageLayer:
// log.G(ctx).Debugf("pushing layer-%s", desc.Digest.String())
default:
return fmt.Errorf("cannot push descriptor: unsupported mediatype: %s", desc.MediaType)
}
}
// ResolveManifest implements ManifestResolver.
func (handle *DirectoryHandler) ResolveManifest(ctx context.Context, fullref string, dgst digest.Digest) (*ocispec.Manifest, error) {
manifestPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
dgst.Algorithm().String(),
dgst.Encoded(),
)
// Check whether the manifest exists
if _, err := os.Stat(manifestPath); err != nil {
return nil, fmt.Errorf("manifest for '%s' does not exist: %s", dgst.String(), manifestPath)
}
// Read the manifest
reader, err := os.Open(manifestPath)
if err != nil {
return nil, err
}
defer reader.Close()
manifestRaw, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
// Unmarshal the manifest
manifest := ocispec.Manifest{}
if err = json.Unmarshal(manifestRaw, &manifest); err != nil {
return nil, err
}
return &manifest, nil
}
// ListManifests implements DigestResolver.
func (handle *DirectoryHandler) ListManifests(ctx context.Context) (map[string]*ocispec.Manifest, error) {
manifestsDir := filepath.Join(handle.path, DirectoryHandlerDigestsDir)
manifests := map[string]*ocispec.Manifest{}
// Create the manifest directory if it does not exist and return nil, since
// there's nothing to return.
if _, err := os.Stat(manifestsDir); err != nil && os.IsNotExist(err) {
if err := os.MkdirAll(manifestsDir, 0o775); err != nil {
return nil, fmt.Errorf("could not create local oci cache directory: %w", err)
}
return nil, nil
}
// Since the directory structure is nested, recursively walk the manifest
// directory to find all manifest entries.
if err := filepath.WalkDir(manifestsDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// Skip directories
if d.IsDir() {
return nil
}
// Read the manifest
rawManifest, err := os.ReadFile(path)
if err != nil {
return nil
}
manifest := ocispec.Manifest{}
if err = json.Unmarshal(rawManifest, &manifest); err != nil {
return nil
}
// Append the manifest to the list
manifests[digest.FromBytes(rawManifest).String()] = &manifest
return nil
}); err != nil {
return nil, fmt.Errorf("could not walk manifests directory: %w", err)
}
return manifests, nil
}
func (handle *DirectoryHandler) DeleteManifest(ctx context.Context, fullref string, dgst digest.Digest) error {
manifestPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
dgst.Algorithm().String(),
dgst.Hex(),
)
// TODO(nderjung): Remove empty parent directories up until
// DirectoryHandlerManifestsDir.
defer func() {
log.G(ctx).
WithField("digest", dgst.String()).
Trace("deleting manifest")
if err := os.RemoveAll(manifestPath); err != nil {
log.G(ctx).
WithField("digest", dgst.String()).
Debug("could not delete manifest: %w", err)
}
}()
manifestReader, err := os.Open(manifestPath)
if err != nil {
return err
}
defer manifestReader.Close()
manifestRaw, err := io.ReadAll(manifestReader)
if err != nil {
return err
}
manifest := ocispec.Manifest{}
if err = json.Unmarshal(manifestRaw, &manifest); err != nil {
return err
}
for _, layer := range manifest.Layers {
layerPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
layer.Digest.Algorithm().String(),
layer.Digest.Hex(),
)
log.G(ctx).
WithField("digest", layer.Digest.String()).
Trace("deleting layer")
if err := os.RemoveAll(layerPath); err != nil {
return fmt.Errorf("could not delete layer digest from manifest '%s': %w", dgst.String(), err)
}
}
configPath := filepath.Join(
handle.path,
DirectoryHandlerDigestsDir,
manifest.Config.Digest.Algorithm().String(),
manifest.Config.Digest.Hex(),
)
log.G(ctx).
WithField("digest", manifest.Config.Digest.String()).
Trace("deleting config")
if err := os.RemoveAll(configPath); err != nil {
return fmt.Errorf("could not delete config digest from manifest '%s': %w", dgst.String(), err)
}
// Update the index manifest such that the specific manifests do not exit. If
// there are no more manifests in the index, also remove the index.
index, err := handle.ResolveIndex(ctx, fullref)
if err != nil {
return fmt.Errorf("could not resolve index from manifest: %w", err)
}
var manifests []ocispec.Descriptor
for _, m := range index.Manifests {
if m.Digest.String() == dgst.String() {
continue
}
manifests = append(manifests, m)
}
indexPath := filepath.Join(
handle.path,
DirectoryHandlerIndexesDir,
strings.ReplaceAll(fullref, ":", string(filepath.Separator)),
)
if len(manifests) == 0 {
indexFi, err := os.Stat(indexPath)
if err != nil {
return fmt.Errorf("could not stat index: %w", err)
}
if indexFi.Mode()&fs.ModeSymlink == 0 {
indexDigest, err := filepath.EvalSymlinks(indexPath)
if err != nil {
return err
}
if err := os.RemoveAll(indexDigest); err != nil {
return err
}
}
// TODO(nderjung): Remove empty parent directories up until
// DirectoryHandlerIndexesDir.
if err := os.RemoveAll(indexPath); err != nil {
return fmt.Errorf("could not delete index '%s': %w", fullref, err)
}
} else {
index.Manifests = manifests
indexJson, err := json.Marshal(index)
if err != nil {
return fmt.Errorf("could not marshal new index: %w", err)
}
indexFile, err := os.OpenFile(indexPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o664)
if err != nil {
return fmt.Errorf("could not open index file: %w", err)
}
defer indexFile.Close()
if _, err := indexFile.Write(indexJson); err != nil {
return fmt.Errorf("could not write index file: %w", err)
}
}
return nil
}
// ResolveIndex implements IndexResolver.
func (handle *DirectoryHandler) ResolveIndex(ctx context.Context, fullref string) (*ocispec.Index, error) {
// Find the index of this image
ref, err := name.ParseReference(fullref,
name.WithDefaultRegistry(""),
name.WithDefaultTag("latest"),
)
if err != nil {
return nil, err
}
var indexPath string
if strings.Contains(fullref, "@") {
indexPath = filepath.Join(
handle.path,
DirectoryHandlerIndexesDir,
// TODO: Do not hardcode
strings.ReplaceAll(ref.Name(), "@"+digest.SHA256.String()+":", string(filepath.Separator)),
)
} else {
indexPath = filepath.Join(
handle.path,
DirectoryHandlerIndexesDir,
strings.ReplaceAll(ref.Name(), ":", string(filepath.Separator)),
)
}
// Check whether the index exists
if _, err := os.Stat(indexPath); err != nil {
return nil, fmt.Errorf("index '%s' not found", ref.Name())
}
// Read the index
reader, err := os.Open(indexPath)
if err != nil {
return nil, err
}
defer reader.Close()
indexRaw, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
// Unmarshal the index
index := ocispec.Index{}
if err = json.Unmarshal(indexRaw, &index); err != nil {
return nil, err
}
return &index, nil
}
// ListIndexes implements IndexLister.
func (handle *DirectoryHandler) ListIndexes(ctx context.Context) (map[string]*ocispec.Index, error) {
indexesDir := filepath.Join(handle.path, DirectoryHandlerIndexesDir)
indexes := map[string]*ocispec.Index{}
// Create the manifest directory if it does not exist and return nil, since
// there's nothing to return.
if _, err := os.Stat(indexesDir); err != nil && os.IsNotExist(err) {
if err := os.MkdirAll(indexesDir, 0o775); err != nil {
return nil, fmt.Errorf("could not create local oci cache directory: %w", err)
}