/
base.go
2798 lines (2612 loc) · 71.5 KB
/
base.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
/*
* JuiceFS, Copyright 2020 Juicedata, Inc.
*
* 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 meta
import (
"encoding/binary"
"encoding/json"
"fmt"
"os"
"path"
"reflect"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
aclAPI "github.com/juicedata/juicefs/pkg/acl"
"github.com/juicedata/juicefs/pkg/utils"
"github.com/juicedata/juicefs/pkg/version"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sync/errgroup"
)
const (
inodeBatch = 1 << 10
sliceIdBatch = 4 << 10
nlocks = 1024
)
var maxCompactSlices = 1000
var maxSlices = 2500
type engine interface {
// Get the value of counter name.
getCounter(name string) (int64, error)
// Increase counter name by value. Do not use this if value is 0, use getCounter instead.
incrCounter(name string, value int64) (int64, error)
// Set counter name to value if old <= value - diff.
setIfSmall(name string, value, diff int64) (bool, error)
updateStats(space int64, inodes int64)
flushStats()
doLoad() ([]byte, error)
doNewSession(sinfo []byte, update bool) error
doRefreshSession() error
doFindStaleSessions(limit int) ([]uint64, error) // limit < 0 means all
doCleanStaleSession(sid uint64) error
doInit(format *Format, force bool) error
scanAllChunks(ctx Context, ch chan<- cchunk, bar *utils.Bar) error
doDeleteSustainedInode(sid uint64, inode Ino) error
doFindDeletedFiles(ts int64, limit int) (map[Ino]uint64, error) // limit < 0 means all
doDeleteFileData(inode Ino, length uint64)
doCleanupSlices()
doCleanupDelayedSlices(edge int64) (int, error)
doDeleteSlice(id uint64, size uint32) error
doCloneEntry(ctx Context, srcIno Ino, parent Ino, name string, ino Ino, attr *Attr, cmode uint8, cumask uint16, top bool) syscall.Errno
doAttachDirNode(ctx Context, parent Ino, dstIno Ino, name string) syscall.Errno
doFindDetachedNodes(t time.Time) []Ino
doCleanupDetachedNode(ctx Context, detachedNode Ino) syscall.Errno
doGetQuota(ctx Context, inode Ino) (*Quota, error)
// set quota, return true if there is no quota exists before
doSetQuota(ctx Context, inode Ino, quota *Quota) (created bool, err error)
doDelQuota(ctx Context, inode Ino) error
doLoadQuotas(ctx Context) (map[Ino]*Quota, error)
doFlushQuotas(ctx Context, quotas map[Ino]*Quota) error
doGetAttr(ctx Context, inode Ino, attr *Attr) syscall.Errno
doSetAttr(ctx Context, inode Ino, set uint16, sugidclearmode uint8, attr *Attr) syscall.Errno
doLookup(ctx Context, parent Ino, name string, inode *Ino, attr *Attr) syscall.Errno
doMknod(ctx Context, parent Ino, name string, _type uint8, mode, cumask uint16, path string, inode *Ino, attr *Attr) syscall.Errno
doLink(ctx Context, inode, parent Ino, name string, attr *Attr) syscall.Errno
doUnlink(ctx Context, parent Ino, name string, attr *Attr, skipCheckTrash ...bool) syscall.Errno
doRmdir(ctx Context, parent Ino, name string, inode *Ino, skipCheckTrash ...bool) syscall.Errno
doReadlink(ctx Context, inode Ino, noatime bool) (int64, []byte, error)
doReaddir(ctx Context, inode Ino, plus uint8, entries *[]*Entry, limit int) syscall.Errno
doRename(ctx Context, parentSrc Ino, nameSrc string, parentDst Ino, nameDst string, flags uint32, inode, tinode *Ino, attr, tattr *Attr) syscall.Errno
doSetXattr(ctx Context, inode Ino, name string, value []byte, flags uint32) syscall.Errno
doRemoveXattr(ctx Context, inode Ino, name string) syscall.Errno
doRepair(ctx Context, inode Ino, attr *Attr) syscall.Errno
doTouchAtime(ctx Context, inode Ino, attr *Attr, ts time.Time) (bool, error)
doRead(ctx Context, inode Ino, indx uint32) ([]*slice, syscall.Errno)
doWrite(ctx Context, inode Ino, indx uint32, off uint32, slice Slice, mtime time.Time, numSlices *int, delta *dirStat, attr *Attr) syscall.Errno
doTruncate(ctx Context, inode Ino, flags uint8, length uint64, delta *dirStat, attr *Attr, skipPermCheck bool) syscall.Errno
doFallocate(ctx Context, inode Ino, mode uint8, off uint64, size uint64, delta *dirStat, attr *Attr) syscall.Errno
doCompactChunk(inode Ino, indx uint32, origin []byte, ss []*slice, skipped int, pos uint32, id uint64, size uint32, delayed []byte) syscall.Errno
doGetParents(ctx Context, inode Ino) map[Ino]int
doUpdateDirStat(ctx Context, batch map[Ino]dirStat) error
// @trySync: try sync dir stat if broken or not existed
doGetDirStat(ctx Context, ino Ino, trySync bool) (*dirStat, syscall.Errno)
doSyncDirStat(ctx Context, ino Ino) (*dirStat, syscall.Errno)
scanTrashSlices(Context, trashSliceScan) error
scanPendingSlices(Context, pendingSliceScan) error
scanPendingFiles(Context, pendingFileScan) error
GetSession(sid uint64, detail bool) (*Session, error)
doSetFacl(ctx Context, ino Ino, aclType uint8, rule *aclAPI.Rule) syscall.Errno
doGetFacl(ctx Context, ino Ino, aclType uint8, aclId uint32, rule *aclAPI.Rule) syscall.Errno
cacheACLs(ctx Context) error
}
type trashSliceScan func(ss []Slice, ts int64) (clean bool, err error)
type pendingSliceScan func(id uint64, size uint32) (clean bool, err error)
type trashFileScan func(inode Ino, size uint64, ts time.Time) (clean bool, err error)
type pendingFileScan func(ino Ino, size uint64, ts int64) (clean bool, err error)
// fsStat aligned for atomic operations
// nolint:structcheck
type fsStat struct {
newSpace int64
newInodes int64
usedSpace int64
usedInodes int64
}
// chunk for compaction
type cchunk struct {
inode Ino
indx uint32
slices int
}
type baseMeta struct {
sync.Mutex
addr string
conf *Config
fmt *Format
root Ino
txlocks [nlocks]sync.Mutex // Pessimistic locks to reduce conflict
subTrash internalNode
sid uint64
of *openfiles
removedFiles map[Ino]bool
compacting map[uint64]bool
maxDeleting chan struct{}
dslices chan Slice // slices to delete
symlinks *sync.Map
msgCallbacks *msgCallbacks
reloadCb []func(*Format)
umounting bool
sesMu sync.Mutex
aclCache aclAPI.Cache
dirStatsLock sync.Mutex
dirStats map[Ino]dirStat
*fsStat
parentMu sync.Mutex // protect dirParents
quotaMu sync.RWMutex // protect dirQuotas
dirParents map[Ino]Ino // directory inode -> parent inode
dirQuotas map[Ino]*Quota // directory inode -> quota
freeMu sync.Mutex
freeInodes freeID
freeSlices freeID
usedSpaceG prometheus.Gauge
usedInodesG prometheus.Gauge
txDist prometheus.Histogram
txRestart prometheus.Counter
opDist prometheus.Histogram
opCount *prometheus.CounterVec
opDuration *prometheus.CounterVec
en engine
}
func newBaseMeta(addr string, conf *Config) *baseMeta {
return &baseMeta{
addr: utils.RemovePassword(addr),
conf: conf,
sid: conf.Sid,
root: RootInode,
of: newOpenFiles(conf.OpenCache, conf.OpenCacheLimit),
removedFiles: make(map[Ino]bool),
compacting: make(map[uint64]bool),
maxDeleting: make(chan struct{}, 100),
symlinks: &sync.Map{},
fsStat: new(fsStat),
dirStats: make(map[Ino]dirStat),
dirParents: make(map[Ino]Ino),
dirQuotas: make(map[Ino]*Quota),
msgCallbacks: &msgCallbacks{
callbacks: make(map[uint32]MsgCallback),
},
aclCache: aclAPI.NewCache(),
usedSpaceG: prometheus.NewGauge(prometheus.GaugeOpts{
Name: "used_space",
Help: "Total used space in bytes.",
}),
usedInodesG: prometheus.NewGauge(prometheus.GaugeOpts{
Name: "used_inodes",
Help: "Total number of inodes.",
}),
txDist: prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "transaction_durations_histogram_seconds",
Help: "Transactions latency distributions.",
Buckets: prometheus.ExponentialBuckets(0.0001, 1.5, 30),
}),
txRestart: prometheus.NewCounter(prometheus.CounterOpts{
Name: "transaction_restart",
Help: "The number of times a transaction is restarted.",
}),
opDist: prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "meta_ops_durations_histogram_seconds",
Help: "Operation latency distributions.",
Buckets: prometheus.ExponentialBuckets(0.0001, 1.5, 30),
}),
opCount: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "meta_ops_total",
Help: "Meta operation count",
}, []string{"method"}),
opDuration: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "meta_ops_duration_seconds",
Help: "Meta operation duration in seconds.",
}, []string{"method"}),
}
}
func (m *baseMeta) InitMetrics(reg prometheus.Registerer) {
if reg == nil {
return
}
reg.MustRegister(m.usedSpaceG)
reg.MustRegister(m.usedInodesG)
reg.MustRegister(m.txDist)
reg.MustRegister(m.txRestart)
reg.MustRegister(m.opDist)
reg.MustRegister(m.opCount)
reg.MustRegister(m.opDuration)
go func() {
for {
var totalSpace, availSpace, iused, iavail uint64
err := m.StatFS(Background, m.root, &totalSpace, &availSpace, &iused, &iavail)
if err == 0 {
m.usedSpaceG.Set(float64(totalSpace - availSpace))
m.usedInodesG.Set(float64(iused))
}
utils.SleepWithJitter(time.Second * 10)
}
}()
}
func (m *baseMeta) timeit(method string, start time.Time) {
used := time.Since(start).Seconds()
m.opDist.Observe(used)
m.opCount.WithLabelValues(method).Inc()
m.opDuration.WithLabelValues(method).Add(used)
}
func (m *baseMeta) getBase() *baseMeta {
return m
}
func (m *baseMeta) checkRoot(inode Ino) Ino {
switch inode {
case 0:
return RootInode // force using Root inode
case RootInode:
return m.root
default:
return inode
}
}
func (r *baseMeta) txLock(idx uint) {
r.txlocks[idx%nlocks].Lock()
}
func (r *baseMeta) txUnlock(idx uint) {
r.txlocks[idx%nlocks].Unlock()
}
func (r *baseMeta) OnMsg(mtype uint32, cb MsgCallback) {
r.msgCallbacks.Lock()
defer r.msgCallbacks.Unlock()
r.msgCallbacks.callbacks[mtype] = cb
}
func (r *baseMeta) newMsg(mid uint32, args ...interface{}) error {
r.msgCallbacks.Lock()
cb, ok := r.msgCallbacks.callbacks[mid]
r.msgCallbacks.Unlock()
if ok {
return cb(args...)
}
return fmt.Errorf("message %d is not supported", mid)
}
func (m *baseMeta) Load(checkVersion bool) (*Format, error) {
body, err := m.en.doLoad()
if err == nil && len(body) == 0 {
err = fmt.Errorf("database is not formatted, please run `juicefs format ...` first")
}
if err != nil {
return nil, err
}
var format = new(Format)
if err = json.Unmarshal(body, format); err != nil {
return nil, fmt.Errorf("json: %s", err)
}
if checkVersion {
if err = format.CheckVersion(); err != nil {
return nil, fmt.Errorf("check version: %s", err)
}
}
m.Lock()
m.fmt = format
m.Unlock()
return format, nil
}
func (m *baseMeta) newSessionInfo() []byte {
host, err := os.Hostname()
if err != nil {
logger.Warnf("Failed to get hostname: %s", err)
}
ips, err := utils.FindLocalIPs()
if err != nil {
logger.Warnf("Failed to get local IP: %s", err)
}
addrs := make([]string, 0, len(ips))
for _, i := range ips {
if ip := i.String(); ip[0] == '?' {
logger.Warnf("Invalid IP address: %s", ip)
} else {
addrs = append(addrs, ip)
}
}
buf, err := json.Marshal(&SessionInfo{
Version: version.Version(),
HostName: host,
IPAddrs: addrs,
MountPoint: m.conf.MountPoint,
MountTime: time.Now(),
ProcessID: os.Getpid(),
})
if err != nil {
panic(err) // marshal SessionInfo should never fail
}
return buf
}
func (m *baseMeta) NewSession(record bool) error {
go m.refresh()
if err := m.en.cacheACLs(Background); err != nil {
return err
}
if m.conf.ReadOnly {
logger.Infof("Create read-only session OK with version: %s", version.Version())
return nil
}
if record {
// use the original sid if it's not 0
action := "Update"
if m.sid == 0 {
v, err := m.en.incrCounter("nextSession", 1)
if err != nil {
return fmt.Errorf("get session ID: %s", err)
}
m.sid = uint64(v)
m.conf.Sid = m.sid
action = "Create"
}
if err := m.en.doNewSession(m.newSessionInfo(), action == "Update"); err != nil {
return fmt.Errorf("create session: %s", err)
}
logger.Infof("%s session %d OK with version: %s", action, m.sid, version.Version())
}
m.loadQuotas()
go m.en.flushStats()
go m.flushDirStat()
go m.flushQuotas()
if m.conf.MaxDeletes > 0 {
m.dslices = make(chan Slice, m.conf.MaxDeletes*10240)
for i := 0; i < m.conf.MaxDeletes; i++ {
go func() {
for s := range m.dslices {
m.deleteSlice_(s.Id, s.Size)
}
}()
}
}
if !m.conf.NoBGJob {
go m.cleanupDeletedFiles()
go m.cleanupSlices()
go m.cleanupTrash()
}
return nil
}
func (m *baseMeta) expireTime() int64 {
if m.conf.Heartbeat > 0 {
return time.Now().Add(m.conf.Heartbeat * 5).Unix()
} else {
return time.Now().Add(time.Hour * 24 * 365).Unix()
}
}
func (m *baseMeta) OnReload(fn func(f *Format)) {
m.msgCallbacks.Lock()
defer m.msgCallbacks.Unlock()
m.reloadCb = append(m.reloadCb, fn)
}
const UmountCode = 11
func (m *baseMeta) refresh() {
for {
if m.conf.Heartbeat > 0 {
utils.SleepWithJitter(m.conf.Heartbeat)
} else { // use default value
utils.SleepWithJitter(time.Second * 12)
}
m.sesMu.Lock()
if m.umounting {
m.sesMu.Unlock()
return
}
if !m.conf.ReadOnly && m.conf.Heartbeat > 0 && m.sid > 0 {
if err := m.en.doRefreshSession(); err != nil {
logger.Errorf("Refresh session %d: %s", m.sid, err)
}
}
m.sesMu.Unlock()
old := m.getFormat()
if format, err := m.Load(false); err != nil {
if strings.HasPrefix(err.Error(), "database is not formatted") {
logger.Errorf("reload setting: %s", err)
os.Exit(UmountCode)
}
logger.Warnf("reload setting: %s", err)
} else if format.MetaVersion > MaxVersion {
logger.Errorf("incompatible metadata version %d > max version %d", format.MetaVersion, MaxVersion)
os.Exit(UmountCode)
} else if format.UUID != old.UUID {
logger.Errorf("UUID changed from %s to %s", old.UUID, format.UUID)
os.Exit(UmountCode)
} else if !reflect.DeepEqual(format, old) {
m.msgCallbacks.Lock()
cbs := m.reloadCb
m.msgCallbacks.Unlock()
for _, cb := range cbs {
cb(format)
}
}
if v, err := m.en.getCounter(usedSpace); err == nil {
atomic.StoreInt64(&m.usedSpace, v)
} else {
logger.Warnf("Get counter %s: %s", usedSpace, err)
}
if v, err := m.en.getCounter(totalInodes); err == nil {
atomic.StoreInt64(&m.usedInodes, v)
} else {
logger.Warnf("Get counter %s: %s", totalInodes, err)
}
m.loadQuotas()
if m.conf.ReadOnly || m.conf.NoBGJob || m.conf.Heartbeat == 0 {
continue
}
if ok, err := m.en.setIfSmall("lastCleanupSessions", time.Now().Unix(), int64((m.conf.Heartbeat * 9 / 10).Seconds())); err != nil {
logger.Warnf("checking counter lastCleanupSessions: %s", err)
} else if ok {
go m.CleanStaleSessions()
}
}
}
func (m *baseMeta) CleanStaleSessions() {
sids, err := m.en.doFindStaleSessions(1000)
if err != nil {
logger.Warnf("scan stale sessions: %s", err)
return
}
for _, sid := range sids {
s, err := m.en.GetSession(sid, false)
if err != nil {
logger.Warnf("Get session info %d: %v", sid, err)
s = &Session{Sid: sid}
}
logger.Infof("clean up stale session %d %+v: %v", sid, s.SessionInfo, m.en.doCleanStaleSession(sid))
}
}
func (m *baseMeta) CloseSession() error {
if m.conf.ReadOnly {
return nil
}
m.doFlushDirStat()
m.doFlushQuotas()
m.sesMu.Lock()
m.umounting = true
m.sesMu.Unlock()
var err error
if m.sid > 0 {
err = m.en.doCleanStaleSession(m.sid)
}
logger.Infof("close session %d: %v", m.sid, err)
return err
}
func (m *baseMeta) Init(format *Format, force bool) error {
return m.en.doInit(format, force)
}
func (m *baseMeta) cleanupDeletedFiles() {
for {
utils.SleepWithJitter(time.Minute)
if ok, err := m.en.setIfSmall("lastCleanupFiles", time.Now().Unix(), int64(time.Minute.Seconds())*9/10); err != nil {
logger.Warnf("checking counter lastCleanupFiles: %s", err)
} else if ok {
files, err := m.en.doFindDeletedFiles(time.Now().Add(-time.Hour).Unix(), 10000)
if err != nil {
logger.Warnf("scan deleted files: %s", err)
continue
}
for inode, length := range files {
logger.Debugf("cleanup chunks of inode %d with %d bytes", inode, length)
m.en.doDeleteFileData(inode, length)
}
}
}
}
func (m *baseMeta) cleanupSlices() {
for {
utils.SleepWithJitter(time.Hour)
if ok, err := m.en.setIfSmall("nextCleanupSlices", time.Now().Unix(), int64(time.Hour.Seconds())*9/10); err != nil {
logger.Warnf("checking counter nextCleanupSlices: %s", err)
} else if ok {
m.en.doCleanupSlices()
}
}
}
func (m *baseMeta) StatFS(ctx Context, ino Ino, totalspace, availspace, iused, iavail *uint64) syscall.Errno {
defer m.timeit("StatFS", time.Now())
if st := m.statRootFs(ctx, totalspace, availspace, iused, iavail); st != 0 {
return st
}
ino = m.checkRoot(ino)
if ino == RootInode {
return 0
}
if st := m.Access(ctx, ino, MODE_MASK_R&MODE_MASK_X, nil); st != 0 {
return st
}
var usage *Quota
var attr Attr
for root := ino; root >= RootInode; root = attr.Parent {
if st := m.GetAttr(ctx, root, &attr); st != 0 {
return st
}
if root == RootInode {
attr.Parent = 0
}
q, err := m.en.doGetQuota(ctx, root)
if err != nil {
return errno(err)
}
if q == nil {
continue
}
q.sanitize()
if usage == nil {
usage = q
}
if q.MaxSpace > 0 {
ls := uint64(q.MaxSpace - q.UsedSpace)
if ls < *availspace {
*availspace = ls
}
}
if q.MaxInodes > 0 {
li := uint64(q.MaxInodes - q.UsedInodes)
if li < *iavail {
*iavail = li
}
}
}
if usage == nil {
return 0
}
*totalspace = uint64(usage.UsedSpace) + *availspace
*iused = uint64(usage.UsedInodes)
return 0
}
func (m *baseMeta) statRootFs(ctx Context, totalspace, availspace, iused, iavail *uint64) syscall.Errno {
var used, inodes int64
var err error
err = utils.WithTimeout(func() error {
used, err = m.en.getCounter(usedSpace)
return err
}, time.Millisecond*150)
if err != nil {
used = atomic.LoadInt64(&m.usedSpace)
}
err = utils.WithTimeout(func() error {
inodes, err = m.en.getCounter(totalInodes)
return err
}, time.Millisecond*150)
if err != nil {
inodes = atomic.LoadInt64(&m.usedInodes)
}
used += atomic.LoadInt64(&m.newSpace)
inodes += atomic.LoadInt64(&m.newInodes)
if used < 0 {
used = 0
}
format := m.getFormat()
if format.Capacity > 0 {
*totalspace = format.Capacity
if *totalspace < uint64(used) {
*totalspace = uint64(used)
}
} else {
*totalspace = 1 << 50
for *totalspace*8 < uint64(used)*10 {
*totalspace *= 2
}
}
*availspace = *totalspace - uint64(used)
if inodes < 0 {
inodes = 0
}
*iused = uint64(inodes)
if format.Inodes > 0 {
if *iused > format.Inodes {
*iavail = 0
} else {
*iavail = format.Inodes - *iused
}
} else {
*iavail = 10 << 20
for *iused*10 > (*iused+*iavail)*8 {
*iavail *= 2
}
}
return 0
}
func (m *baseMeta) resolveCase(ctx Context, parent Ino, name string) *Entry {
var entries []*Entry
_ = m.en.doReaddir(ctx, parent, 0, &entries, -1)
for _, e := range entries {
n := string(e.Name)
if strings.EqualFold(name, n) {
return e
}
}
return nil
}
func (m *baseMeta) Lookup(ctx Context, parent Ino, name string, inode *Ino, attr *Attr, checkPerm bool) syscall.Errno {
if inode == nil || attr == nil {
return syscall.EINVAL // bad request
}
defer m.timeit("Lookup", time.Now())
parent = m.checkRoot(parent)
if checkPerm {
if st := m.Access(ctx, parent, MODE_MASK_X, nil); st != 0 {
return st
}
}
if name == ".." {
if parent == m.root {
name = "."
} else {
if st := m.GetAttr(ctx, parent, attr); st != 0 {
return st
}
if attr.Typ != TypeDirectory {
return syscall.ENOTDIR
}
*inode = attr.Parent
return m.GetAttr(ctx, *inode, attr)
}
}
if name == "." {
if st := m.GetAttr(ctx, parent, attr); st != 0 {
return st
}
*inode = parent
return 0
}
if parent == RootInode && name == TrashName {
if st := m.GetAttr(ctx, TrashInode, attr); st != 0 {
return st
}
*inode = TrashInode
return 0
}
st := m.en.doLookup(ctx, parent, name, inode, attr)
if st == syscall.ENOENT && m.conf.CaseInsensi {
if e := m.resolveCase(ctx, parent, name); e != nil {
*inode = e.Inode
if st = m.GetAttr(ctx, *inode, attr); st == syscall.ENOENT {
logger.Warnf("no attribute for inode %d (%d, %s)", e.Inode, parent, e.Name)
*attr = *e.Attr
st = 0
}
}
}
if st == 0 && attr.Typ == TypeDirectory && !isTrash(parent) {
m.parentMu.Lock()
m.dirParents[*inode] = parent
m.parentMu.Unlock()
}
return st
}
func (m *baseMeta) parseAttr(buf []byte, attr *Attr) {
if attr == nil || len(buf) == 0 {
return
}
rb := utils.FromBuffer(buf)
attr.Flags = rb.Get8()
attr.Mode = rb.Get16()
attr.Typ = uint8(attr.Mode >> 12)
attr.Mode &= 0xfff
attr.Uid = rb.Get32()
attr.Gid = rb.Get32()
attr.Atime = int64(rb.Get64())
attr.Atimensec = rb.Get32()
attr.Mtime = int64(rb.Get64())
attr.Mtimensec = rb.Get32()
attr.Ctime = int64(rb.Get64())
attr.Ctimensec = rb.Get32()
attr.Nlink = rb.Get32()
attr.Length = rb.Get64()
attr.Rdev = rb.Get32()
if rb.Left() >= 8 {
attr.Parent = Ino(rb.Get64())
}
attr.Full = true
if rb.Left() >= 8 {
attr.AccessACL = rb.Get32()
attr.DefaultACL = rb.Get32()
}
logger.Tracef("attr: %+v -> %+v", buf, attr)
}
func (m *baseMeta) marshal(attr *Attr) []byte {
size := uint32(36 + 24 + 4 + 8)
if attr.AccessACL|attr.DefaultACL != aclAPI.None {
size += 8
}
w := utils.NewBuffer(size)
w.Put8(attr.Flags)
w.Put16((uint16(attr.Typ) << 12) | (attr.Mode & 0xfff))
w.Put32(attr.Uid)
w.Put32(attr.Gid)
w.Put64(uint64(attr.Atime))
w.Put32(attr.Atimensec)
w.Put64(uint64(attr.Mtime))
w.Put32(attr.Mtimensec)
w.Put64(uint64(attr.Ctime))
w.Put32(attr.Ctimensec)
w.Put32(attr.Nlink)
w.Put64(attr.Length)
w.Put32(attr.Rdev)
w.Put64(uint64(attr.Parent))
if attr.AccessACL+attr.DefaultACL > 0 {
w.Put32(attr.AccessACL)
w.Put32(attr.DefaultACL)
}
logger.Tracef("attr: %+v -> %+v", attr, w.Bytes())
return w.Bytes()
}
func (m *baseMeta) encodeDelayedSlice(id uint64, size uint32) []byte {
w := utils.NewBuffer(8 + 4)
w.Put64(id)
w.Put32(size)
return w.Bytes()
}
func (m *baseMeta) decodeDelayedSlices(buf []byte, ss *[]Slice) {
if len(buf) == 0 || len(buf)%12 != 0 {
return
}
for rb := utils.FromBuffer(buf); rb.HasMore(); {
*ss = append(*ss, Slice{Id: rb.Get64(), Size: rb.Get32()})
}
}
func clearSUGID(ctx Context, cur *Attr, set *Attr) {
switch runtime.GOOS {
case "darwin":
if ctx.Uid() != 0 {
// clear SUID and SGID
cur.Mode &= 01777
set.Mode &= 01777
}
case "linux":
// same as ext
if cur.Typ != TypeDirectory {
if ctx.Uid() != 0 || (cur.Mode>>3)&1 != 0 {
// clear SUID and SGID
cur.Mode &= 01777
set.Mode &= 01777
} else {
// keep SGID if the file is non-group-executable
cur.Mode &= 03777
set.Mode &= 03777
}
}
}
}
func (r *baseMeta) Resolve(ctx Context, parent Ino, path string, inode *Ino, attr *Attr) syscall.Errno {
return syscall.ENOTSUP
}
func (m *baseMeta) Access(ctx Context, inode Ino, mmask uint8, attr *Attr) syscall.Errno {
if ctx.Uid() == 0 {
return 0
}
if !ctx.CheckPermission() {
return 0
}
if attr == nil || !attr.Full {
if attr == nil {
attr = &Attr{}
}
err := m.GetAttr(ctx, inode, attr)
if err != 0 {
return err
}
}
// ref: https://github.com/torvalds/linux/blob/e5eb28f6d1afebed4bb7d740a797d0390bd3a357/fs/namei.c#L352-L357
// dont check acl if mask is 0
if attr.AccessACL != aclAPI.None && (attr.Mode&00070) != 0 {
rule := &aclAPI.Rule{}
if st := m.en.doGetFacl(ctx, inode, aclAPI.TypeAccess, attr.AccessACL, rule); st != 0 {
return st
}
if rule.CanAccess(ctx.Uid(), ctx.Gids(), attr.Uid, attr.Gid, mmask) {
return 0
}
return syscall.EACCES
}
mode := accessMode(attr, ctx.Uid(), ctx.Gids())
if mode&mmask != mmask {
logger.Debugf("Access inode %d %o, mode %o, request mode %o", inode, attr.Mode, mode, mmask)
return syscall.EACCES
}
return 0
}
func (m *baseMeta) GetAttr(ctx Context, inode Ino, attr *Attr) syscall.Errno {
inode = m.checkRoot(inode)
if m.conf.OpenCache > 0 && m.of.Check(inode, attr) {
return 0
}
defer m.timeit("GetAttr", time.Now())
var err syscall.Errno
if inode == RootInode || inode == TrashInode {
// doGetAttr could overwrite the `attr` after timeout
var a Attr
e := utils.WithTimeout(func() error {
err = m.en.doGetAttr(ctx, inode, &a)
return nil
}, time.Millisecond*300)
if e == nil && err == 0 {
*attr = a
} else {
err = 0
attr.Typ = TypeDirectory
attr.Mode = 0777
attr.Nlink = 2
attr.Length = 4 << 10
if inode == TrashInode {
attr.Mode = 0555
}
attr.Parent = RootInode
attr.Full = true
}
} else {
err = m.en.doGetAttr(ctx, inode, attr)
}
if err == 0 {
m.of.Update(inode, attr)
if attr.Typ == TypeDirectory && inode != RootInode && !isTrash(attr.Parent) {
m.parentMu.Lock()
m.dirParents[inode] = attr.Parent
m.parentMu.Unlock()
}
}
return err
}
func (m *baseMeta) SetAttr(ctx Context, inode Ino, set uint16, sugidclearmode uint8, attr *Attr) syscall.Errno {
defer m.timeit("SetAttr", time.Now())
inode = m.checkRoot(inode)
defer func() {
m.of.InvalidateChunk(inode, invalidateAttrOnly)
if set&(SetAttrAtime|SetAttrAtimeNow) != 0 {
if f := m.of.find(inode); f != nil {
f.attr.Full = false
}
}
}()
return m.en.doSetAttr(ctx, inode, set, sugidclearmode, attr)
}
func (m *baseMeta) nextInode() (Ino, error) {
m.freeMu.Lock()
defer m.freeMu.Unlock()
if m.freeInodes.next >= m.freeInodes.maxid {
v, err := m.en.incrCounter("nextInode", inodeBatch)
if err != nil {
return 0, err
}
m.freeInodes.next = uint64(v) - inodeBatch
m.freeInodes.maxid = uint64(v)
}
n := m.freeInodes.next
m.freeInodes.next++
for n <= 1 {
n = m.freeInodes.next
m.freeInodes.next++
}
return Ino(n), nil
}
func (m *baseMeta) Mknod(ctx Context, parent Ino, name string, _type uint8, mode, cumask uint16, rdev uint32, path string, inode *Ino, attr *Attr) syscall.Errno {
if _type < TypeFile || _type > TypeSocket {
return syscall.EINVAL
}
if isTrash(parent) {
return syscall.EPERM
}
if parent == RootInode && name == TrashName {
return syscall.EPERM
}
if m.conf.ReadOnly {
return syscall.EROFS
}
if name == "" {
return syscall.ENOENT
}
defer m.timeit("Mknod", time.Now())
parent = m.checkRoot(parent)
var space, inodes int64 = align4K(0), 1
if err := m.checkQuota(ctx, space, inodes, parent); err != 0 {
return err
}
ino, err := m.nextInode()
if err != nil {
return errno(err)
}
if inode == nil {
inode = &ino
}
*inode = ino
if attr == nil {
attr = &Attr{}
}