-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathfs.go
1134 lines (998 loc) · 31 KB
/
fs.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
/*
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.
*/
/*
Copyright 2019 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the NOTICE.md file.
*/
//
// Example implementation of FileSystem.
//
// This implementation uses stargz by CRFS(https://github.com/google/crfs) as
// image format, which has following feature:
// - We can use docker registry as a backend store (means w/o additional layer
// stores).
// - The stargz-formatted image is still docker-compatible (means normal
// runtimes can still use the formatted image).
//
// Currently, we reimplemented CRFS-like filesystem for ease of integration.
// But in the near future, we intend to integrate it with CRFS.
//
package stargz
import (
"archive/tar"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"github.com/containerd/containerd/log"
"github.com/containerd/stargz-snapshotter/cache"
snbase "github.com/containerd/stargz-snapshotter/snapshot"
"github.com/containerd/stargz-snapshotter/stargz/handler"
"github.com/containerd/stargz-snapshotter/stargz/keychain"
"github.com/containerd/stargz-snapshotter/stargz/reader"
"github.com/containerd/stargz-snapshotter/stargz/remote"
"github.com/containerd/stargz-snapshotter/task"
"github.com/golang/groupcache/lru"
"github.com/google/crfs/stargz"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/hanwen/go-fuse/fuse"
"github.com/hanwen/go-fuse/fuse/nodefs"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
)
const (
blockSize = 512
memoryCacheType = "memory"
whiteoutPrefix = ".wh."
whiteoutOpaqueDir = whiteoutPrefix + whiteoutPrefix + ".opq"
opaqueXattr = "trusted.overlay.opaque"
opaqueXattrValue = "y"
stateDirName = ".stargz-snapshotter"
defaultLRUCacheEntry = 100
defaultResolveResultEntry = 100
// targetRefLabelCRI is a label which contains image reference passed from CRI plugin
targetRefLabelCRI = "containerd.io/snapshot/cri.image-ref"
// targetDigestLabelCRI is a label which contains layer digest passed from CRI plugin
targetDigestLabelCRI = "containerd.io/snapshot/cri.layer-digest"
// targetImageLayersLabel is a label which contains layer digests contained in
// the target image and is passed from CRI plugin.
targetImageLayersLabel = "containerd.io/snapshot/cri.image-layers"
// PrefetchLandmark is a file entry which indicates the end position of
// prefetch in the stargz file.
PrefetchLandmark = ".prefetch.landmark"
// NoPrefetchLandmark is a file entry which indicates that no prefetch should
// occur in the stargz file.
NoPrefetchLandmark = ".no.prefetch.landmark"
)
type Config struct {
remote.ResolverConfig `toml:"resolver"`
remote.BlobConfig `toml:"blob"`
keychain.KubeconfigKeychainConfig `toml:"kubeconfig_keychain"`
HTTPCacheType string `toml:"http_cache_type"`
FSCacheType string `toml:"filesystem_cache_type"`
LRUCacheEntry int `toml:"lru_max_entry"`
ResolveResultEntry int `toml:"resolve_result_entry"`
PrefetchSize int64 `toml:"prefetch_size"`
NoPrefetch bool `toml:"noprefetch"`
Debug bool `toml:"debug"`
}
func NewFilesystem(ctx context.Context, root string, config *Config) (snbase.FileSystem, error) {
maxEntry := config.LRUCacheEntry
if maxEntry == 0 {
maxEntry = defaultLRUCacheEntry
}
httpCache, err := getCache(config.HTTPCacheType, filepath.Join(root, "httpcache"), maxEntry)
if err != nil {
return nil, err
}
fsCache, err := getCache(config.FSCacheType, filepath.Join(root, "fscache"), maxEntry)
if err != nil {
return nil, err
}
keychain := authn.NewMultiKeychain(
authn.DefaultKeychain,
keychain.NewKubeconfigKeychain(ctx, config.KubeconfigKeychainConfig),
)
resolveResultEntry := config.ResolveResultEntry
if resolveResultEntry == 0 {
resolveResultEntry = defaultResolveResultEntry
}
return &filesystem{
resolver: remote.NewResolver(keychain, config.ResolverConfig),
blobConfig: config.BlobConfig,
httpCache: httpCache,
fsCache: fsCache,
prefetchSize: config.PrefetchSize,
noprefetch: config.NoPrefetch,
debug: config.Debug,
layer: make(map[string]*layer),
resolveResult: lru.New(resolveResultEntry),
backgroundTaskManager: task.NewBackgroundTaskManager(2, 5*time.Second),
}, nil
}
// getCache gets a cache corresponding to specified type.
func getCache(ctype, dir string, maxEntry int) (cache.BlobCache, error) {
if ctype == memoryCacheType {
return cache.NewMemoryCache(), nil
}
return cache.NewDirectoryCache(dir, maxEntry)
}
type filesystem struct {
resolver *remote.Resolver
blobConfig remote.BlobConfig
httpCache cache.BlobCache
fsCache cache.BlobCache
prefetchSize int64
noprefetch bool
debug bool
layer map[string]*layer
layerMu sync.Mutex
resolveResult *lru.Cache
resolveResultMu sync.Mutex
backgroundTaskManager *task.BackgroundTaskManager
}
func (fs *filesystem) Mount(ctx context.Context, mountpoint string, labels map[string]string) error {
// This is a prioritized task and all background tasks will be stopped
// execution so this can avoid being disturbed for NW traffic by background
// tasks.
fs.backgroundTaskManager.DoPrioritizedTask()
defer fs.backgroundTaskManager.DonePrioritizedTask()
logCtx := log.G(ctx).WithField("mountpoint", mountpoint)
// Get basic information of this layer.
ref, digest, layers, prefetchSize, err := fs.parseLabels(labels)
if err != nil {
logCtx.WithError(err).Debug("failed to get necessary information from labels")
return err
}
logCtx = logCtx.WithField("ref", ref).WithField("digest", digest)
// Resolve the target layer and the all chained layers
var (
resolved *resolveResult
target = append([]string{digest}, layers...)
)
for _, dgst := range target {
var (
rr *resolveResult
key = fmt.Sprintf("%s/%s", ref, dgst)
)
fs.resolveResultMu.Lock()
if cached, ok := fs.resolveResult.Get(key); ok && cached.(*resolveResult).err == nil {
rr = cached.(*resolveResult) // hit cache
} else {
rr = fs.resolve(ctx, ref, dgst) // missed cache
fs.resolveResult.Add(key, rr)
}
if dgst == digest {
resolved = rr
}
fs.resolveResultMu.Unlock()
}
// Get the resolved layer
if resolved == nil {
logCtx.Debug("resolve result isn't registered")
return fmt.Errorf("resolve result(%q,%q) isn't registered", ref, digest)
}
l, err := resolved.get(30 * time.Second) // get layer with timeout
if err != nil {
logCtx.WithError(err).Debug("failed to resolve layer")
return errors.Wrapf(err, "failed to resolve layer(%q,%q)", ref, digest)
}
if err := fs.check(ctx, l); err != nil { // check the connectivity
return err
}
// Register the mountpoint layer
fs.layerMu.Lock()
fs.layer[mountpoint] = l
fs.layerMu.Unlock()
// RoundTripper only used for pre-/background-fetch.
// We use a separated transport because we don't want these fetching
// functionalities to disturb other HTTP-related operations
fetchTr := lazyTransport(func() (http.RoundTripper, error) {
return l.blob.Authn(http.DefaultTransport.(*http.Transport).Clone())
})
// Prefetch this layer. We prefetch several layers in parallel. The first
// Check() for this layer waits for the prefetch completion. We recreate
// RoundTripper to avoid disturbing other NW-related operations.
if !fs.noprefetch {
go func() {
fs.backgroundTaskManager.DoPrioritizedTask()
defer fs.backgroundTaskManager.DonePrioritizedTask()
tr, err := fetchTr()
if err != nil {
logCtx.WithError(err).Debug("failed to prepare transport for prefetch")
return
}
if err := l.prefetch(prefetchSize, remote.WithRoundTripper(tr)); err != nil {
logCtx.WithError(err).Debug("failed to prefetched layer")
return
}
logCtx.Debug("completed to prefetch")
}()
}
// Fetch whole layer aggressively in background. We use background
// reader for this so prioritized tasks(Mount, Check, etc...) can
// interrupt the reading. This can avoid disturbing prioritized tasks
// about NW traffic. We read layer with a buffer to reduce num of
// requests to the registry.
go func() {
br := io.NewSectionReader(readerAtFunc(func(p []byte, offset int64) (retN int, retErr error) {
fs.backgroundTaskManager.InvokeBackgroundTask(func(ctx context.Context) {
tr, err := fetchTr()
if err != nil {
logCtx.WithError(err).Debug("failed to prepare transport for background fetch")
retN, retErr = 0, err
return
}
retN, retErr = l.blob.ReadAt(p, offset, remote.WithContext(ctx), remote.WithRoundTripper(tr))
}, 120*time.Second)
return
}), 0, l.blob.Size())
if err := l.reader.CacheTarGzWithReader(br); err != nil {
logCtx.WithError(err).Debug("failed to fetch whole layer")
return
}
logCtx.Debug("completed to fetch all layer data in background")
}()
// Mounting stargz
// TODO: bind mount the state directory as a read-only fs on snapshotter's side
conn := nodefs.NewFileSystemConnector(&node{
Node: nodefs.NewDefaultNode(),
fs: fs,
layer: l.reader,
e: l.root,
s: newState(digest, l.blob),
root: mountpoint,
}, &nodefs.Options{
NegativeTimeout: 0,
AttrTimeout: time.Second,
EntryTimeout: time.Second,
Owner: nil, // preserve owners.
})
server, err := fuse.NewServer(conn.RawFS(), mountpoint, &fuse.MountOptions{
AllowOther: true, // allow users other than root&mounter to access fs
Options: []string{"suid"}, // allow setuid inside container
})
if err != nil {
logCtx.WithError(err).Debug("failed to make filesstem server")
return err
}
server.SetDebug(fs.debug)
go server.Serve()
return server.WaitMount()
}
func (fs *filesystem) resolve(ctx context.Context, ref, digest string) *resolveResult {
return newResolveResult(func() (*layer, error) {
log.G(ctx).Debugf("resolving (%q, %q)", ref, digest)
defer log.G(ctx).Debugf("resolved (%q, %q)", ref, digest)
// Resolve the reference and digest
blob, err := fs.resolver.Resolve(ref, digest, fs.httpCache, fs.blobConfig)
if err != nil {
return nil, errors.Wrap(err, "failed to resolve the reference")
}
// Get a reader for stargz archive.
// Each file's read operation is a prioritized task and all background tasks
// will be stopped during the execution so this can avoid being disturbed for
// NW traffic by background tasks.
sr := io.NewSectionReader(readerAtFunc(func(p []byte, offset int64) (n int, err error) {
fs.backgroundTaskManager.DoPrioritizedTask()
defer fs.backgroundTaskManager.DonePrioritizedTask()
return blob.ReadAt(p, offset)
}), 0, blob.Size())
gr, root, err := reader.NewReader(sr, fs.fsCache)
if err != nil {
return nil, errors.Wrap(err, "failed to read layer")
}
return newLayer(blob, gr, root), nil
})
}
func (fs *filesystem) Check(ctx context.Context, mountpoint string) error {
// This is a prioritized task and all background tasks will be stopped
// execution so this can avoid being disturbed for NW traffic by background
// tasks.
fs.backgroundTaskManager.DoPrioritizedTask()
defer fs.backgroundTaskManager.DonePrioritizedTask()
logCtx := log.G(ctx).WithField("mountpoint", mountpoint)
fs.layerMu.Lock()
l := fs.layer[mountpoint]
fs.layerMu.Unlock()
if l == nil {
logCtx.Debug("layer not registered")
return fmt.Errorf("layer not registered")
}
// Wait for prefetch compeletion
if err := l.waitForPrefetchCompletion(10 * time.Second); err != nil {
logCtx.WithError(err).Warn("failed to sync with prefetch completion")
}
// Check the blob connectivity and refresh the connection if possible
if err := fs.check(ctx, l); err != nil {
logCtx.WithError(err).Warn("check failed")
return err
}
return nil
}
func (fs *filesystem) check(ctx context.Context, l *layer) error {
logCtx := log.G(ctx)
if err := l.blob.Check(); err != nil {
// Check failed. Try to refresh the connection
logCtx.WithError(err).Warn("failed to connect to blob; refreshing...")
for retry := 0; retry < 3; retry++ {
if iErr := fs.resolver.Refresh(l.blob); iErr != nil {
logCtx.WithError(iErr).Warnf("failed to refresh connection(%d)", retry)
err = errors.Wrapf(err, "error(%d): %v", retry, iErr)
continue // retry
}
logCtx.Debug("Successfully refreshed connection")
err = nil
break
}
if err != nil {
return err
}
}
return nil
}
func (fs *filesystem) unregister(mountpoint string) {
fs.layerMu.Lock()
delete(fs.layer, mountpoint)
fs.layerMu.Unlock()
}
func (fs *filesystem) parseLabels(labels map[string]string) (rRef, rDigest string, rLayers []string, rPrefetchSize int64, _ error) {
// mandatory labels
if ref, ok := labels[targetRefLabelCRI]; ok {
rRef = ref
} else if ref, ok := labels[handler.TargetRefLabel]; ok {
rRef = ref
} else {
return "", "", nil, 0, fmt.Errorf("reference hasn't been passed")
}
if digest, ok := labels[targetDigestLabelCRI]; ok {
rDigest = digest
} else if digest, ok := labels[handler.TargetDigestLabel]; ok {
rDigest = digest
} else {
return "", "", nil, 0, fmt.Errorf("digest hasn't been passed")
}
if l, ok := labels[targetImageLayersLabel]; ok {
rLayers = strings.Split(l, ",")
} else if l, ok := labels[handler.TargetImageLayersLabel]; ok {
rLayers = strings.Split(l, ",")
} else {
return "", "", nil, 0, fmt.Errorf("image layers hasn't been passed")
}
// optional label
rPrefetchSize = fs.prefetchSize
if psStr, ok := labels[handler.TargetPrefetchSizeLabel]; ok {
if ps, err := strconv.ParseInt(psStr, 10, 64); err == nil {
rPrefetchSize = ps
}
}
return
}
func lazyTransport(trFunc func() (http.RoundTripper, error)) func() (http.RoundTripper, error) {
var (
tr http.RoundTripper
trMu sync.Mutex
)
return func() (http.RoundTripper, error) {
trMu.Lock()
defer trMu.Unlock()
if tr != nil {
return tr, nil
}
gotTr, err := trFunc()
if err != nil {
return nil, err
}
tr = gotTr
return tr, nil
}
}
func newResolveResult(init func() (*layer, error)) *resolveResult {
rr := &resolveResult{
progress: newWaiter(),
}
rr.progress.start()
go func() {
rr.layer, rr.err = init()
rr.progress.done()
}()
return rr
}
type resolveResult struct {
layer *layer
err error
progress *waiter
}
func (rr *resolveResult) get(timeout time.Duration) (*layer, error) {
if err := rr.progress.wait(timeout); err != nil {
return nil, err
} else if rr.layer == nil && rr.err == nil {
return nil, fmt.Errorf("failed to get result")
}
return rr.layer, rr.err
}
func newLayer(blob remote.Blob, r reader.Reader, root *stargz.TOCEntry) *layer {
return &layer{
blob: blob,
reader: r,
root: root,
prefetchWaiter: newWaiter(),
}
}
type layer struct {
blob remote.Blob
reader reader.Reader
root *stargz.TOCEntry
prefetchWaiter *waiter
}
func (l *layer) prefetch(prefetchSize int64, opts ...remote.Option) error {
l.prefetchWaiter.start()
defer l.prefetchWaiter.done()
if _, ok := l.reader.Lookup(NoPrefetchLandmark); ok {
// do not prefetch this layer
return nil
} else if e, ok := l.reader.Lookup(PrefetchLandmark); ok {
// override the prefetch size with optimized value
prefetchSize = e.Offset
} else if prefetchSize > l.blob.Size() {
// adjust prefetch size not to exceed the whole layer size
prefetchSize = l.blob.Size()
}
if err := l.blob.Cache(0, prefetchSize, opts...); err != nil {
return errors.Wrap(err, "failed to prefetch layer")
}
pr := io.NewSectionReader(readerAtFunc(func(p []byte, off int64) (int, error) {
return l.blob.ReadAt(p, off, opts...)
}), 0, prefetchSize)
err := l.reader.CacheTarGzWithReader(pr)
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return errors.Wrap(err, "failed to cache prefetched layer")
}
return nil
}
func (l *layer) waitForPrefetchCompletion(timeout time.Duration) error {
return l.prefetchWaiter.wait(timeout)
}
func newWaiter() *waiter {
return &waiter{
completionCond: sync.NewCond(&sync.Mutex{}),
}
}
type waiter struct {
inProgress bool
completionCond *sync.Cond
}
func (w *waiter) start() {
w.inProgress = true
}
func (w *waiter) done() {
w.inProgress = false
w.completionCond.Broadcast()
}
func (w *waiter) wait(timeout time.Duration) error {
wait := func() <-chan struct{} {
ch := make(chan struct{})
go func() {
w.completionCond.L.Lock()
if w.inProgress {
w.completionCond.Wait()
}
w.completionCond.L.Unlock()
ch <- struct{}{}
}()
return ch
}
select {
case <-time.After(timeout):
w.inProgress = false
w.completionCond.Broadcast()
return fmt.Errorf("timeout(%v)", timeout)
case <-wait():
return nil
}
}
type readerAtFunc func([]byte, int64) (int, error)
func (f readerAtFunc) ReadAt(p []byte, offset int64) (int, error) { return f(p, offset) }
type fileReader interface {
OpenFile(name string) (io.ReaderAt, error)
}
// node is a filesystem inode abstraction which implements node in go-fuse.
type node struct {
nodefs.Node
fs *filesystem
layer fileReader
e *stargz.TOCEntry
s *state
root string
opaque bool // true if this node is an overlayfs opaque directory
}
func (n *node) OnUnmount() {
n.fs.unregister(n.root)
}
func (n *node) OpenDir(context *fuse.Context) ([]fuse.DirEntry, fuse.Status) {
var ents []fuse.DirEntry
whiteouts := map[string]*stargz.TOCEntry{}
normalEnts := map[string]bool{}
n.e.ForeachChild(func(baseName string, ent *stargz.TOCEntry) bool {
// We don't want to show prefetch landmarks in "/".
if n.e.Name == "" && (baseName == PrefetchLandmark || baseName == NoPrefetchLandmark) {
return true
}
// We don't want to show whiteouts.
if strings.HasPrefix(baseName, whiteoutPrefix) {
if baseName == whiteoutOpaqueDir {
return true
}
// Add the overlayfs-compiant whiteout later.
whiteouts[baseName] = ent
return true
}
// This is a normal entry.
normalEnts[baseName] = true
ents = append(ents, fuse.DirEntry{
Mode: modeOfEntry(ent),
Name: baseName,
Ino: inodeOfEnt(ent),
})
return true
})
// Append whiteouts if no entry replaces the target entry in the lower layer.
for w, ent := range whiteouts {
if !normalEnts[w[len(whiteoutPrefix):]] {
ents = append(ents, fuse.DirEntry{
Mode: syscall.S_IFCHR,
Name: w[len(whiteoutPrefix):],
Ino: inodeOfEnt(ent),
})
}
}
sort.Slice(ents, func(i, j int) bool { return ents[i].Name < ents[j].Name })
return ents, fuse.OK
}
func (n *node) Lookup(out *fuse.Attr, name string, context *fuse.Context) (*nodefs.Inode, fuse.Status) {
c := n.Inode().GetChild(name)
if c != nil {
s := c.Node().GetAttr(out, nil, context)
if s != fuse.OK {
return nil, s
}
return c, fuse.OK
}
// We don't want to show prefetch landmarks in "/".
if n.e.Name == "" && (name == PrefetchLandmark || name == NoPrefetchLandmark) {
return nil, fuse.ENOENT
}
// We don't want to show whiteouts.
if strings.HasPrefix(name, whiteoutPrefix) {
return nil, fuse.ENOENT
}
// state directory
if n.e.Name == "" && name == stateDirName {
return n.Inode().NewChild(name, true, n.s), n.s.attr(out)
}
ce, ok := n.e.LookupChild(name)
if !ok {
// If the entry exists as a whiteout, show an overlayfs-styled whiteout node.
if wh, ok := n.e.LookupChild(fmt.Sprintf("%s%s", whiteoutPrefix, name)); ok {
return n.Inode().NewChild(name, false, &whiteout{
Node: nodefs.NewDefaultNode(),
oe: wh,
}), entryToWhAttr(wh, out)
}
return nil, fuse.ENOENT
}
var opaque bool
if _, ok := ce.LookupChild(whiteoutOpaqueDir); ok {
// This entry is an opaque directory so make it recognizable for overlayfs.
opaque = true
}
return n.Inode().NewChild(name, ce.Stat().IsDir(), &node{
Node: nodefs.NewDefaultNode(),
fs: n.fs,
layer: n.layer,
e: ce,
s: n.s,
root: n.root,
opaque: opaque,
}), entryToAttr(ce, out)
}
func (n *node) Access(mode uint32, context *fuse.Context) fuse.Status {
if context.Owner.Uid == 0 {
// root can do anything.
return fuse.OK
}
if mode == 0 {
// Requires nothing.
return fuse.OK
}
var shift uint32
if uint32(n.e.Uid) == context.Owner.Uid {
shift = 6
} else if uint32(n.e.Gid) == context.Owner.Gid {
shift = 3
} else {
shift = 0
}
if mode<<shift&modeOfEntry(n.e) != 0 {
return fuse.OK
}
return fuse.EPERM
}
func (n *node) Open(flags uint32, context *fuse.Context) (nodefs.File, fuse.Status) {
ra, err := n.layer.OpenFile(n.e.Name)
if err != nil {
n.s.report(fmt.Errorf("failed to open node: %v", err))
return nil, fuse.EIO
}
return &file{
File: nodefs.NewDefaultFile(),
n: n,
e: n.e,
ra: ra,
}, fuse.OK
}
func (n *node) GetAttr(out *fuse.Attr, file nodefs.File, context *fuse.Context) fuse.Status {
return entryToAttr(n.e, out)
}
func (n *node) GetXAttr(attribute string, context *fuse.Context) ([]byte, fuse.Status) {
if attribute == opaqueXattr && n.opaque {
// This node is an opaque directory so give overlayfs-compliant indicator.
return []byte(opaqueXattrValue), fuse.OK
}
if v, ok := n.e.Xattrs[attribute]; ok {
return v, fuse.OK
}
return nil, fuse.ENOATTR
}
func (n *node) ListXAttr(ctx *fuse.Context) (attrs []string, code fuse.Status) {
if n.opaque {
// This node is an opaque directory so add overlayfs-compliant indicator.
attrs = append(attrs, opaqueXattr)
}
for k := range n.e.Xattrs {
attrs = append(attrs, k)
}
return attrs, fuse.OK
}
func (n *node) Readlink(c *fuse.Context) ([]byte, fuse.Status) {
return []byte(n.e.LinkName), fuse.OK
}
func (n *node) Deletable() bool {
// read-only filesystem
return false
}
func (n *node) StatFs() *fuse.StatfsOut {
return defaultStatfs()
}
// file is a file abstraction which implements file in go-fuse.
type file struct {
nodefs.File
n *node
e *stargz.TOCEntry
ra io.ReaderAt
}
func (f *file) String() string {
return "stargzFile"
}
func (f *file) Read(buf []byte, off int64) (fuse.ReadResult, fuse.Status) {
n, err := f.ra.ReadAt(buf, off)
if err != nil && err != io.EOF {
f.n.s.report(fmt.Errorf("failed to read node: %v", err))
return nil, fuse.EIO
}
return fuse.ReadResultData(buf[:n]), fuse.OK
}
func (f *file) GetAttr(out *fuse.Attr) fuse.Status {
return entryToAttr(f.e, out)
}
// whiteout is a whiteout abstraction compliant to overlayfs. This implements
// node in go-fuse.
type whiteout struct {
nodefs.Node
oe *stargz.TOCEntry
}
func (w *whiteout) GetAttr(out *fuse.Attr, file nodefs.File, context *fuse.Context) fuse.Status {
return entryToWhAttr(w.oe, out)
}
// newState provides new state directory node.
// It creates statFile at the same time to give it stable inode number.
func newState(digest string, blob remote.Blob) *state {
return &state{
Node: nodefs.NewDefaultNode(),
statFile: &statFile{
Node: nodefs.NewDefaultNode(),
name: digest + ".json",
statJSON: statJSON{
Digest: digest,
Size: blob.Size(),
},
blob: blob,
},
}
}
// state is a directory which contain a "state file" of this layer aming to
// observability. This filesystem uses it to report something(e.g. error) to
// the clients(e.g. Kubernetes's livenessProbe).
// This directory has mode "dr-x------ root root".
type state struct {
nodefs.Node
statFile *statFile
}
func (s *state) report(err error) {
s.statFile.report(err)
}
func (s *state) OpenDir(context *fuse.Context) ([]fuse.DirEntry, fuse.Status) {
return []fuse.DirEntry{
{
Mode: syscall.S_IFREG | s.statFile.mode(),
Name: s.statFile.name,
Ino: s.statFile.ino(),
},
}, fuse.OK
}
func (s *state) Lookup(out *fuse.Attr, name string, context *fuse.Context) (*nodefs.Inode, fuse.Status) {
if c := s.Inode().GetChild(name); c != nil {
if status := c.Node().GetAttr(out, nil, context); status != fuse.OK {
return nil, status
}
return c, fuse.OK
}
if name != s.statFile.name {
return nil, fuse.ENOENT
}
return s.Inode().NewChild(name, false, s.statFile), s.statFile.attr(out)
}
func (s *state) Access(mode uint32, context *fuse.Context) fuse.Status {
if mode == 0 {
// Requires nothing.
return fuse.OK
}
if context.Owner.Uid == 0 && mode&s.mode()>>6 != 0 {
// root can read and open it (dr-x------ root root).
return fuse.OK
}
return fuse.EPERM
}
func (s *state) GetAttr(out *fuse.Attr, file nodefs.File, context *fuse.Context) fuse.Status {
return s.attr(out)
}
func (s *state) StatFs() *fuse.StatfsOut {
return defaultStatfs()
}
func (s *state) ino() uint64 {
// calculates the inode number which is one-to-one conresspondence
// with this state directory node inscance.
return uint64(uintptr(unsafe.Pointer(s)))
}
func (s *state) mode() uint32 {
return 0500
}
func (s *state) attr(out *fuse.Attr) fuse.Status {
out.Ino = s.ino()
out.Size = 0
out.Blksize = blockSize
out.Blocks = 0
out.Mode = syscall.S_IFDIR | s.mode()
out.Owner = fuse.Owner{Uid: 0, Gid: 0}
out.Nlink = 1
// dummy
out.Mtime = 0
out.Mtimensec = 0
out.Rdev = 0
out.Padding = 0
return fuse.OK
}
type statJSON struct {
Error string `json:"error,omitempty"`
Digest string `json:"digest"`
// URL is excluded for potential security reason
Size int64 `json:"size"`
FetchedSize int64 `json:"fetchedSize"`
FetchedPercent float64 `json:"fetchedPercent"` // Fetched / Size * 100.0
}
// statFile is a file which contain something to be reported from this layer.
// This filesystem uses statFile.report() to report something(e.g. error) to
// the clients(e.g. Kubernetes's livenessProbe).
// This directory has mode "-r-------- root root".
type statFile struct {
nodefs.Node
name string
blob remote.Blob
statJSON statJSON
mu sync.Mutex
}
func (e *statFile) report(err error) {
e.mu.Lock()
defer e.mu.Unlock()
e.statJSON.Error = err.Error()
}
func (e *statFile) updateStatUnlocked() ([]byte, error) {
e.statJSON.FetchedSize = e.blob.FetchedSize()
e.statJSON.FetchedPercent = float64(e.statJSON.FetchedSize) / float64(e.statJSON.Size) * 100.0
j, err := json.Marshal(&e.statJSON)
if err != nil {
return nil, err
}
j = append(j, []byte("\n")...)
return j, nil
}
func (e *statFile) Access(mode uint32, context *fuse.Context) fuse.Status {
if mode == 0 {
// Requires nothing.
return fuse.OK
}
if context.Owner.Uid == 0 && mode&e.mode()>>6 != 0 {
// root can operate it.
return fuse.OK
}
return fuse.EPERM
}
func (e *statFile) Open(flags uint32, context *fuse.Context) (nodefs.File, fuse.Status) {
return nil, fuse.OK
}
func (e *statFile) Read(file nodefs.File, dest []byte, off int64, context *fuse.Context) (fuse.ReadResult, fuse.Status) {
e.mu.Lock()
defer e.mu.Unlock()
st, err := e.updateStatUnlocked()
if err != nil {
return nil, fuse.EIO
}
n, err := bytes.NewReader(st).ReadAt(dest, off)
if err != nil && err != io.EOF {
return nil, fuse.EIO
}
return fuse.ReadResultData(dest[:n]), fuse.OK
}
func (e *statFile) GetAttr(out *fuse.Attr, file nodefs.File, context *fuse.Context) fuse.Status {
return e.attr(out)
}
func (e *statFile) StatFs() *fuse.StatfsOut {
return defaultStatfs()
}
func (e *statFile) ino() uint64 {
// calculates the inode number which is one-to-one conresspondence
// with this state file node inscance.
return uint64(uintptr(unsafe.Pointer(e)))
}
func (e *statFile) mode() uint32 {