-
Notifications
You must be signed in to change notification settings - Fork 997
/
Copy pathredis.go
4381 lines (4165 loc) · 116 KB
/
redis.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
//go:build !noredis
// +build !noredis
/*
* 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 (
"bufio"
"context"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"hash/fnv"
"io"
"math/rand"
"net"
"net/url"
"os"
"runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/juicedata/juicefs/pkg/utils"
"github.com/redis/go-redis/v9"
)
/*
Node: i$inode -> Attribute{type,mode,uid,gid,atime,mtime,ctime,nlink,length,rdev}
Dir: d$inode -> {name -> {inode,type}}
Parent: p$inode -> {parent -> count} // for hard links
File: c$inode_$indx -> [Slice{pos,id,length,off,len}]
Symlink: s$inode -> target
Xattr: x$inode -> {name -> value}
Flock: lockf$inode -> { $sid_$owner -> ltype }
POSIX lock: lockp$inode -> { $sid_$owner -> Plock(pid,ltype,start,end) }
Sessions: sessions -> [ $sid -> heartbeat ]
sustained: session$sid -> [$inode]
locked: locked$sid -> { lockf$inode or lockp$inode }
Removed files: delfiles -> [$inode:$length -> seconds]
detached nodes: detachedNodes -> [$inode -> seconds]
Slices refs: k$sliceId_$size -> refcount
Dir data length: dirDataLength -> { $inode -> length }
Dir used space: dirUsedSpace -> { $inode -> usedSpace }
Dir used inodes: dirUsedInodes -> { $inode -> usedInodes }
Quota: dirQuota -> { $inode -> {maxSpace, maxInodes} }
Quota used space: dirQuotaUsedSpace -> { $inode -> usedSpace }
Quota used inodes: dirQuotaUsedInodes -> { $inode -> usedInodes }
Redis features:
Sorted Set: 1.2+
Hash Set: 4.0+
Transaction: 2.2+
Scripting: 2.6+
Scan: 2.8+
*/
type redisMeta struct {
*baseMeta
rdb redis.UniversalClient
prefix string
shaLookup string // The SHA returned by Redis for the loaded `scriptLookup`
shaResolve string // The SHA returned by Redis for the loaded `scriptResolve`
}
var _ Meta = &redisMeta{}
func init() {
Register("redis", newRedisMeta)
Register("rediss", newRedisMeta)
Register("unix", newRedisMeta)
}
// newRedisMeta return a meta store using Redis.
func newRedisMeta(driver, addr string, conf *Config) (Meta, error) {
uri := driver + "://" + addr
u, err := url.Parse(uri)
if err != nil {
return nil, fmt.Errorf("url parse %s: %s", uri, err)
}
values := u.Query()
query := queryMap{&values}
minRetryBackoff := query.duration("min-retry-backoff", "min_retry_backoff", time.Millisecond*20)
maxRetryBackoff := query.duration("max-retry-backoff", "max_retry_backoff", time.Second*10)
readTimeout := query.duration("read-timeout", "read_timeout", time.Second*30)
writeTimeout := query.duration("write-timeout", "write_timeout", time.Second*5)
routeRead := query.pop("route-read")
skipVerify := query.pop("insecure-skip-verify")
certFile := query.pop("tls-cert-file")
keyFile := query.pop("tls-key-file")
caCertFile := query.pop("tls-ca-cert-file")
u.RawQuery = values.Encode()
hosts := u.Host
opt, err := redis.ParseURL(u.String())
if err != nil {
return nil, fmt.Errorf("redis parse %s: %s", uri, err)
}
if opt.TLSConfig != nil {
opt.TLSConfig.ServerName = "" // use the host of each connection as ServerName
opt.TLSConfig.InsecureSkipVerify = skipVerify != ""
if certFile != "" {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("get certificate error certFile:%s keyFile:%s error:%s", certFile, keyFile, err)
}
opt.TLSConfig.Certificates = []tls.Certificate{cert}
}
if caCertFile != "" {
caCert, err := os.ReadFile(caCertFile)
if err != nil {
return nil, fmt.Errorf("read ca cert file error path:%s error:%s", caCertFile, err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
opt.TLSConfig.RootCAs = caCertPool
}
}
if opt.Password == "" {
opt.Password = os.Getenv("REDIS_PASSWORD")
}
if opt.Password == "" {
opt.Password = os.Getenv("META_PASSWORD")
}
opt.MaxRetries = conf.Retries
if opt.MaxRetries == 0 {
opt.MaxRetries = -1 // Redis use -1 to disable retries
}
opt.MinRetryBackoff = minRetryBackoff
opt.MaxRetryBackoff = maxRetryBackoff
opt.ReadTimeout = readTimeout
opt.WriteTimeout = writeTimeout
var rdb redis.UniversalClient
var prefix string
if strings.Contains(hosts, ",") && strings.Index(hosts, ",") < strings.Index(hosts, ":") {
var fopt redis.FailoverOptions
ps := strings.Split(hosts, ",")
fopt.MasterName = ps[0]
fopt.SentinelAddrs = ps[1:]
_, port, _ := net.SplitHostPort(fopt.SentinelAddrs[len(fopt.SentinelAddrs)-1])
if port == "" {
port = "26379"
}
for i, addr := range fopt.SentinelAddrs {
h, p, e := net.SplitHostPort(addr)
if e != nil {
fopt.SentinelAddrs[i] = net.JoinHostPort(addr, port)
} else if p == "" {
fopt.SentinelAddrs[i] = net.JoinHostPort(h, port)
}
}
fopt.SentinelPassword = os.Getenv("SENTINEL_PASSWORD")
fopt.DB = opt.DB
fopt.Username = opt.Username
fopt.Password = opt.Password
fopt.TLSConfig = opt.TLSConfig
fopt.MaxRetries = opt.MaxRetries
fopt.MinRetryBackoff = opt.MinRetryBackoff
fopt.MaxRetryBackoff = opt.MaxRetryBackoff
fopt.ReadTimeout = opt.ReadTimeout
fopt.WriteTimeout = opt.WriteTimeout
fopt.PoolSize = opt.PoolSize // default: GOMAXPROCS * 10
fopt.PoolTimeout = opt.PoolTimeout // default: ReadTimeout + 1 second.
fopt.MinIdleConns = opt.MinIdleConns // disable by default
fopt.MaxIdleConns = opt.MaxIdleConns // disable by default
fopt.ConnMaxIdleTime = opt.ConnMaxIdleTime // default: 30 minutes
fopt.ConnMaxLifetime = opt.ConnMaxLifetime // disable by default
if conf.ReadOnly {
// NOTE: RouteByLatency and RouteRandomly are not supported since they require cluster client
fopt.ReplicaOnly = routeRead == "replica"
}
rdb = redis.NewFailoverClient(&fopt)
} else {
if !strings.Contains(hosts, ",") {
c := redis.NewClient(opt)
info, err := c.ClusterInfo(Background).Result()
if err != nil && strings.Contains(err.Error(), "cluster mode") || err == nil && strings.Contains(info, "cluster_state:") {
logger.Infof("redis %s is in cluster mode", hosts)
} else {
rdb = c
}
}
if rdb == nil {
var copt redis.ClusterOptions
copt.Addrs = strings.Split(hosts, ",")
copt.MaxRedirects = 1
copt.Username = opt.Username
copt.Password = opt.Password
copt.TLSConfig = opt.TLSConfig
copt.MaxRetries = opt.MaxRetries
copt.MinRetryBackoff = opt.MinRetryBackoff
copt.MaxRetryBackoff = opt.MaxRetryBackoff
copt.ReadTimeout = opt.ReadTimeout
copt.WriteTimeout = opt.WriteTimeout
copt.PoolSize = opt.PoolSize // default: GOMAXPROCS * 10
copt.PoolTimeout = opt.PoolTimeout // default: ReadTimeout + 1 second.
copt.MinIdleConns = opt.MinIdleConns // disable by default
copt.MaxIdleConns = opt.MaxIdleConns // disable by default
copt.ConnMaxIdleTime = opt.ConnMaxIdleTime // default: 30 minutes
copt.ConnMaxLifetime = opt.ConnMaxLifetime // disable by default
if conf.ReadOnly {
switch routeRead {
case "random":
copt.RouteRandomly = true
case "latency":
copt.RouteByLatency = true
case "replica":
copt.ReadOnly = true
default:
// route to primary
}
}
rdb = redis.NewClusterClient(&copt)
prefix = fmt.Sprintf("{%d}", opt.DB)
}
}
m := &redisMeta{
baseMeta: newBaseMeta(addr, conf),
rdb: rdb,
prefix: prefix,
}
m.en = m
m.checkServerConfig()
return m, nil
}
func (m *redisMeta) Shutdown() error {
return m.rdb.Close()
}
func (m *redisMeta) doDeleteSlice(id uint64, size uint32) error {
return m.rdb.HDel(Background, m.sliceRefs(), m.sliceKey(id, size)).Err()
}
func (m *redisMeta) Name() string {
return "redis"
}
func (m *redisMeta) doInit(format *Format, force bool) error {
ctx := Background
body, err := m.rdb.Get(ctx, m.setting()).Bytes()
if err != nil && err != redis.Nil {
return err
}
if err == nil {
var old Format
err = json.Unmarshal(body, &old)
if err != nil {
return fmt.Errorf("existing format is broken: %s", err)
}
if !old.DirStats && format.DirStats {
// remove dir stats as they are outdated
err := m.rdb.Del(ctx, m.dirUsedInodesKey(), m.dirUsedSpaceKey()).Err()
if err != nil {
return errors.Wrap(err, "remove dir stats")
}
}
if err = format.update(&old, force); err != nil {
return errors.Wrap(err, "update format")
}
}
data, err := json.MarshalIndent(format, "", "")
if err != nil {
return fmt.Errorf("json: %s", err)
}
ts := time.Now().Unix()
attr := &Attr{
Typ: TypeDirectory,
Atime: ts,
Mtime: ts,
Ctime: ts,
Nlink: 2,
Length: 4 << 10,
Parent: 1,
}
if format.TrashDays > 0 {
attr.Mode = 0555
if err = m.rdb.SetNX(ctx, m.inodeKey(TrashInode), m.marshal(attr), 0).Err(); err != nil {
return err
}
}
if err = m.rdb.Set(ctx, m.setting(), data, 0).Err(); err != nil {
return err
}
m.fmt = format
if body != nil {
return nil
}
// root inode
attr.Mode = 0777
return m.rdb.Set(ctx, m.inodeKey(1), m.marshal(attr), 0).Err()
}
func (m *redisMeta) Reset() error {
if m.prefix != "" {
return m.scan(Background, "*", func(keys []string) error {
return m.rdb.Del(Background, keys...).Err()
})
}
return m.rdb.FlushDB(Background).Err()
}
func (m *redisMeta) doLoad() ([]byte, error) {
body, err := m.rdb.Get(Background, m.setting()).Bytes()
if err == redis.Nil {
return nil, nil
}
return body, err
}
func (m *redisMeta) doNewSession(sinfo []byte) error {
err := m.rdb.ZAdd(Background, m.allSessions(), redis.Z{
Score: float64(m.expireTime()),
Member: strconv.FormatUint(m.sid, 10)}).Err()
if err != nil {
return fmt.Errorf("set session ID %d: %s", m.sid, err)
}
if err = m.rdb.HSet(Background, m.sessionInfos(), m.sid, sinfo).Err(); err != nil {
return fmt.Errorf("set session info: %s", err)
}
if m.shaLookup, err = m.rdb.ScriptLoad(Background, scriptLookup).Result(); err != nil {
logger.Warnf("load scriptLookup: %v", err)
m.shaLookup = ""
}
if m.shaResolve, err = m.rdb.ScriptLoad(Background, scriptResolve).Result(); err != nil {
logger.Warnf("load scriptResolve: %v", err)
m.shaResolve = ""
}
if !m.conf.NoBGJob {
go m.cleanupLegacies()
}
return nil
}
func (m *redisMeta) getCounter(name string) (int64, error) {
v, err := m.rdb.Get(Background, m.prefix+name).Int64()
if err == redis.Nil {
err = nil
}
return v, err
}
func (m *redisMeta) incrCounter(name string, value int64) (int64, error) {
if m.conf.ReadOnly {
return 0, syscall.EROFS
}
if name == "nextInode" || name == "nextChunk" {
// for nextinode, nextchunk
// the current one is already used
v, err := m.rdb.IncrBy(Background, m.prefix+strings.ToLower(name), value).Result()
return v + 1, err
} else if name == "nextSession" {
name = "nextsession"
}
return m.rdb.IncrBy(Background, m.prefix+name, value).Result()
}
func (m *redisMeta) setIfSmall(name string, value, diff int64) (bool, error) {
var changed bool
name = m.prefix + name
err := m.txn(Background, func(tx *redis.Tx) error {
changed = false
old, err := tx.Get(Background, name).Int64()
if err != nil && err != redis.Nil {
return err
}
if old > value-diff {
return nil
} else {
changed = true
return tx.Set(Background, name, value, 0).Err()
}
}, name)
return changed, err
}
func (m *redisMeta) getSession(sid string, detail bool) (*Session, error) {
ctx := Background
info, err := m.rdb.HGet(ctx, m.sessionInfos(), sid).Bytes()
if err == redis.Nil { // legacy client has no info
info = []byte("{}")
} else if err != nil {
return nil, fmt.Errorf("HGet sessionInfos %s: %s", sid, err)
}
var s Session
if err := json.Unmarshal(info, &s); err != nil {
return nil, fmt.Errorf("corrupted session info; json error: %s", err)
}
s.Sid, _ = strconv.ParseUint(sid, 10, 64)
if detail {
inodes, err := m.rdb.SMembers(ctx, m.sustained(s.Sid)).Result()
if err != nil {
return nil, fmt.Errorf("SMembers %s: %s", sid, err)
}
s.Sustained = make([]Ino, 0, len(inodes))
for _, sinode := range inodes {
inode, _ := strconv.ParseUint(sinode, 10, 64)
s.Sustained = append(s.Sustained, Ino(inode))
}
locks, err := m.rdb.SMembers(ctx, m.lockedKey(s.Sid)).Result()
if err != nil {
return nil, fmt.Errorf("SMembers %s: %s", sid, err)
}
s.Flocks = make([]Flock, 0, len(locks)) // greedy
s.Plocks = make([]Plock, 0, len(locks))
for _, lock := range locks {
owners, err := m.rdb.HGetAll(ctx, lock).Result()
if err != nil {
return nil, fmt.Errorf("HGetAll %s: %s", lock, err)
}
isFlock := strings.HasPrefix(lock, m.prefix+"lockf")
inode, _ := strconv.ParseUint(lock[len(m.prefix)+5:], 10, 64)
for k, v := range owners {
parts := strings.Split(k, "_")
if parts[0] != sid {
continue
}
owner, _ := strconv.ParseUint(parts[1], 16, 64)
if isFlock {
s.Flocks = append(s.Flocks, Flock{Ino(inode), owner, v})
} else {
s.Plocks = append(s.Plocks, Plock{Ino(inode), owner, loadLocks([]byte(v))})
}
}
}
}
return &s, nil
}
func (m *redisMeta) GetSession(sid uint64, detail bool) (*Session, error) {
var legacy bool
key := strconv.FormatUint(sid, 10)
score, err := m.rdb.ZScore(Background, m.allSessions(), key).Result()
if err == redis.Nil {
legacy = true
score, err = m.rdb.ZScore(Background, legacySessions, key).Result()
}
if err == redis.Nil {
err = fmt.Errorf("session not found: %d", sid)
}
if err != nil {
return nil, err
}
s, err := m.getSession(key, detail)
if err != nil {
return nil, err
}
s.Expire = time.Unix(int64(score), 0)
if legacy {
s.Expire = s.Expire.Add(time.Minute * 5)
}
return s, nil
}
func (m *redisMeta) ListSessions() ([]*Session, error) {
keys, err := m.rdb.ZRangeWithScores(Background, m.allSessions(), 0, -1).Result()
if err != nil {
return nil, err
}
sessions := make([]*Session, 0, len(keys))
for _, k := range keys {
s, err := m.getSession(k.Member.(string), false)
if err != nil {
logger.Errorf("get session: %s", err)
continue
}
s.Expire = time.Unix(int64(k.Score), 0)
sessions = append(sessions, s)
}
// add clients with version before 1.0-beta3 as well
keys, err = m.rdb.ZRangeWithScores(Background, legacySessions, 0, -1).Result()
if err != nil {
logger.Errorf("Scan legacy sessions: %s", err)
return sessions, nil
}
for _, k := range keys {
s, err := m.getSession(k.Member.(string), false)
if err != nil {
logger.Errorf("Get legacy session: %s", err)
continue
}
s.Expire = time.Unix(int64(k.Score), 0).Add(time.Minute * 5)
sessions = append(sessions, s)
}
return sessions, nil
}
func (m *redisMeta) sustained(sid uint64) string {
return m.prefix + "session" + strconv.FormatUint(sid, 10)
}
func (m *redisMeta) lockedKey(sid uint64) string {
return m.prefix + "locked" + strconv.FormatUint(sid, 10)
}
func (m *redisMeta) symKey(inode Ino) string {
return m.prefix + "s" + inode.String()
}
func (m *redisMeta) inodeKey(inode Ino) string {
return m.prefix + "i" + inode.String()
}
func (m *redisMeta) entryKey(parent Ino) string {
return m.prefix + "d" + parent.String()
}
func (m *redisMeta) parentKey(inode Ino) string {
return m.prefix + "p" + inode.String()
}
func (m *redisMeta) chunkKey(inode Ino, indx uint32) string {
return m.prefix + "c" + inode.String() + "_" + strconv.FormatInt(int64(indx), 10)
}
func (m *redisMeta) sliceKey(id uint64, size uint32) string {
// inside hashset
return "k" + strconv.FormatUint(id, 10) + "_" + strconv.FormatUint(uint64(size), 10)
}
func (m *redisMeta) xattrKey(inode Ino) string {
return m.prefix + "x" + inode.String()
}
func (m *redisMeta) flockKey(inode Ino) string {
return m.prefix + "lockf" + inode.String()
}
func (m *redisMeta) ownerKey(owner uint64) string {
return fmt.Sprintf("%d_%016X", m.sid, owner)
}
func (m *redisMeta) plockKey(inode Ino) string {
return m.prefix + "lockp" + inode.String()
}
func (m *redisMeta) setting() string {
return m.prefix + "setting"
}
func (m *redisMeta) usedSpaceKey() string {
return m.prefix + usedSpace
}
func (m *redisMeta) dirDataLengthKey() string {
return m.prefix + "dirDataLength"
}
func (m *redisMeta) dirUsedSpaceKey() string {
return m.prefix + "dirUsedSpace"
}
func (m *redisMeta) dirUsedInodesKey() string {
return m.prefix + "dirUsedInodes"
}
func (m *redisMeta) dirQuotaUsedSpaceKey() string {
return m.prefix + "dirQuotaUsedSpace"
}
func (m *redisMeta) dirQuotaUsedInodesKey() string {
return m.prefix + "dirQuotaUsedInodes"
}
func (m *redisMeta) dirQuotaKey() string {
return m.prefix + "dirQuota"
}
func (m *redisMeta) totalInodesKey() string {
return m.prefix + totalInodes
}
func (m *redisMeta) delfiles() string {
return m.prefix + "delfiles"
}
func (m *redisMeta) detachedNodes() string {
return m.prefix + "detachedNodes"
}
func (r *redisMeta) delSlices() string {
return r.prefix + "delSlices"
}
func (r *redisMeta) allSessions() string {
return r.prefix + "allSessions"
}
func (m *redisMeta) sessionInfos() string {
return m.prefix + "sessionInfos"
}
func (m *redisMeta) sliceRefs() string {
return m.prefix + "sliceRef"
}
func (m *redisMeta) packQuota(space, inodes int64) []byte {
wb := utils.NewBuffer(16)
wb.Put64(uint64(space))
wb.Put64(uint64(inodes))
return wb.Bytes()
}
func (m *redisMeta) parseQuota(buf []byte) (space, inodes int64) {
if len(buf) == 0 {
return 0, 0
}
if len(buf) != 16 {
logger.Errorf("Invalid quota value: %v", buf)
return 0, 0
}
rb := utils.ReadBuffer(buf)
return int64(rb.Get64()), int64(rb.Get64())
}
func (m *redisMeta) packEntry(_type uint8, inode Ino) []byte {
wb := utils.NewBuffer(9)
wb.Put8(_type)
wb.Put64(uint64(inode))
return wb.Bytes()
}
func (m *redisMeta) parseEntry(buf []byte) (uint8, Ino) {
if len(buf) != 9 {
panic("invalid entry")
}
return buf[0], Ino(binary.BigEndian.Uint64(buf[1:]))
}
func (m *redisMeta) updateStats(space int64, inodes int64) {
atomic.AddInt64(&m.usedSpace, space)
atomic.AddInt64(&m.usedInodes, inodes)
}
// redisMeta updates the usage in each transaction
func (m *redisMeta) flushStats() {}
func (m *redisMeta) handleLuaResult(op string, res interface{}, err error, returnedIno *int64, returnedAttr *string) syscall.Errno {
if err != nil {
msg := err.Error()
if strings.Contains(msg, "NOSCRIPT") {
var err2 error
switch op {
case "lookup":
m.shaLookup, err2 = m.rdb.ScriptLoad(Background, scriptLookup).Result()
case "resolve":
m.shaResolve, err2 = m.rdb.ScriptLoad(Background, scriptResolve).Result()
default:
return syscall.ENOTSUP
}
if err2 == nil {
logger.Infof("loaded script succeed for %s", op)
return syscall.EAGAIN
} else {
logger.Warnf("load script %s: %s", op, err2)
return syscall.ENOTSUP
}
} else if strings.Contains(msg, "ENOENT") {
return syscall.ENOENT
} else if strings.Contains(msg, "EACCESS") {
return syscall.EACCES
} else if strings.Contains(msg, "ENOTDIR") {
return syscall.ENOTDIR
} else if strings.Contains(msg, "ENOTSUP") {
return syscall.ENOTSUP
} else {
logger.Warnf("unexpected error for %s: %s", op, msg)
switch op {
case "lookup":
m.shaLookup = ""
case "resolve":
m.shaResolve = ""
}
return syscall.ENOTSUP
}
}
vals, ok := res.([]interface{})
if !ok {
logger.Errorf("invalid script result: %v", res)
return syscall.ENOTSUP
}
*returnedIno, ok = vals[0].(int64)
if !ok {
logger.Errorf("invalid script result: %v", res)
return syscall.ENOTSUP
}
if vals[1] == nil {
return syscall.ENOTSUP
}
*returnedAttr, ok = vals[1].(string)
if !ok {
logger.Errorf("invalid script result: %v", res)
return syscall.ENOTSUP
}
return 0
}
func (m *redisMeta) doLookup(ctx Context, parent Ino, name string, inode *Ino, attr *Attr) syscall.Errno {
var foundIno Ino
var foundType uint8
var encodedAttr []byte
var err error
entryKey := m.entryKey(parent)
if len(m.shaLookup) > 0 && attr != nil && !m.conf.CaseInsensi && m.prefix == "" {
var res interface{}
var returnedIno int64
var returnedAttr string
res, err = m.rdb.EvalSha(ctx, m.shaLookup, []string{entryKey, name}).Result()
if st := m.handleLuaResult("lookup", res, err, &returnedIno, &returnedAttr); st == 0 {
foundIno = Ino(returnedIno)
encodedAttr = []byte(returnedAttr)
} else if st == syscall.EAGAIN {
return m.doLookup(ctx, parent, name, inode, attr)
} else if st != syscall.ENOTSUP {
return st
}
}
if foundIno == 0 || len(encodedAttr) == 0 {
var buf []byte
buf, err = m.rdb.HGet(ctx, entryKey, name).Bytes()
if err != nil {
return errno(err)
}
foundType, foundIno = m.parseEntry(buf)
encodedAttr, err = m.rdb.Get(ctx, m.inodeKey(foundIno)).Bytes()
}
if err == nil {
m.parseAttr(encodedAttr, attr)
} else if err == redis.Nil { // corrupt entry
logger.Warnf("no attribute for inode %d (%d, %s)", foundIno, parent, name)
*attr = Attr{Typ: foundType}
err = nil
}
*inode = foundIno
return errno(err)
}
func (m *redisMeta) Resolve(ctx Context, parent Ino, path string, inode *Ino, attr *Attr) syscall.Errno {
if len(m.shaResolve) == 0 || m.conf.CaseInsensi || m.prefix != "" {
return syscall.ENOTSUP
}
defer m.timeit("Resolve", time.Now())
parent = m.checkRoot(parent)
args := []string{parent.String(), path,
strconv.FormatUint(uint64(ctx.Uid()), 10),
strconv.FormatUint(uint64(ctx.Gid()), 10)}
res, err := m.rdb.EvalSha(ctx, m.shaResolve, args).Result()
var returnedIno int64
var returnedAttr string
st := m.handleLuaResult("resolve", res, err, &returnedIno, &returnedAttr)
if st == 0 {
if inode != nil {
*inode = Ino(returnedIno)
}
m.parseAttr([]byte(returnedAttr), attr)
} else if st == syscall.EAGAIN {
return m.Resolve(ctx, parent, path, inode, attr)
}
return st
}
func (m *redisMeta) doGetAttr(ctx Context, inode Ino, attr *Attr) syscall.Errno {
a, err := m.rdb.Get(ctx, m.inodeKey(inode)).Bytes()
if err == nil {
m.parseAttr(a, attr)
}
return errno(err)
}
type timeoutError interface {
Timeout() bool
}
func (m *redisMeta) shouldRetry(err error, retryOnFailure bool) bool {
switch err {
case redis.TxFailedErr:
return true
case io.EOF, io.ErrUnexpectedEOF:
return retryOnFailure
case nil, context.Canceled, context.DeadlineExceeded:
return false
}
if v, ok := err.(timeoutError); ok && v.Timeout() {
return retryOnFailure
}
s := err.Error()
if s == "ERR max number of clients reached" ||
strings.Contains(s, "Conn is in a bad state") ||
strings.Contains(s, "EXECABORT") {
return true
}
ps := strings.SplitN(s, " ", 3)
switch ps[0] {
case "LOADING":
case "READONLY":
case "CLUSTERDOWN":
case "TRYAGAIN":
case "MOVED":
case "ASK":
case "ERR":
if len(ps) > 1 {
switch ps[1] {
case "DISABLE":
fallthrough
case "NOWRITE":
fallthrough
case "NOREAD":
return true
}
}
return false
default:
return false
}
return true
}
// errNo is an alias to syscall.Errno to disable retry in Redis Cluster
type errNo uintptr
func (e errNo) Error() string {
return syscall.Errno(e).Error()
}
// replaceErrno replace returned syscall.Errno as errNo
func replaceErrno(txf func(tx *redis.Tx) error) func(tx *redis.Tx) error {
return func(tx *redis.Tx) error {
err := txf(tx)
if eno, ok := err.(syscall.Errno); ok {
err = errNo(eno)
}
return err
}
}
func (m *redisMeta) txn(ctx Context, txf func(tx *redis.Tx) error, keys ...string) error {
if m.conf.ReadOnly {
return syscall.EROFS
}
for _, k := range keys {
if !strings.HasPrefix(k, m.prefix) {
panic(fmt.Sprintf("Invalid key %s not starts with prefix %s", k, m.prefix))
}
}
var khash = fnv.New32()
_, _ = khash.Write([]byte(keys[0]))
h := uint(khash.Sum32())
start := time.Now()
defer func() { m.txDist.Observe(time.Since(start).Seconds()) }()
m.txLock(h)
defer m.txUnlock(h)
// TODO: enable retry for some of idempodent transactions
var retryOnFailture = false
var lastErr error
for i := 0; i < 50; i++ {
if ctx.Canceled() {
return syscall.EINTR
}
err := m.rdb.Watch(ctx, replaceErrno(txf), keys...)
if eno, ok := err.(errNo); ok {
if eno == 0 {
err = nil
} else {
err = syscall.Errno(eno)
}
}
if err != nil && m.shouldRetry(err, retryOnFailture) {
m.txRestart.Add(1)
logger.Debugf("Transaction failed, restart it (tried %d): %s", i+1, err)
lastErr = err
time.Sleep(time.Millisecond * time.Duration(rand.Int()%((i+1)*(i+1))))
continue
} else if err == nil && i > 1 {
logger.Warnf("Transaction succeeded after %d tries (%s), keys: %v, last error: %s", i+1, time.Since(start), keys, lastErr)
}
return err
}
logger.Warnf("Already tried 50 times, returning: %s", lastErr)
return lastErr
}
func (m *redisMeta) Truncate(ctx Context, inode Ino, flags uint8, length uint64, attr *Attr, skipPermCheck bool) syscall.Errno {
defer m.timeit("Truncate", time.Now())
f := m.of.find(inode)
if f != nil {
f.Lock()
defer f.Unlock()
}
defer func() { m.of.InvalidateChunk(inode, invalidateAllChunks) }()
var newLength, newSpace int64
if attr == nil {
attr = &Attr{}
}
err := m.txn(ctx, func(tx *redis.Tx) error {
newLength = 0
newSpace = 0
var t Attr
a, err := tx.Get(ctx, m.inodeKey(inode)).Bytes()
if err != nil {
return err
}
m.parseAttr(a, &t)
if t.Typ != TypeFile || t.Flags&(FlagImmutable|FlagAppend) != 0 || t.Parent > TrashInode {
return syscall.EPERM
}
if !skipPermCheck {
if st := m.Access(ctx, inode, MODE_MASK_W, &t); st != 0 {
return st
}
}
if length == t.Length {
if attr != nil {
*attr = t
}
return nil
}
newLength = int64(length) - int64(t.Length)
newSpace = align4K(length) - align4K(t.Length)
if err := m.checkQuota(ctx, newSpace, 0, m.getParents(ctx, tx, inode, t.Parent)...); err != 0 {
return err
}
var zeroChunks []uint32
var left, right = t.Length, length
if left > right {
right, left = left, right
}
if (right-left)/ChunkSize >= 100 {
// super large
var cursor uint64
var keys []string
for {
keys, cursor, err = tx.Scan(ctx, cursor, m.prefix+fmt.Sprintf("c%d_*", inode), 10000).Result()
if err != nil {
return err
}
for _, key := range keys {
indx, err := strconv.Atoi(strings.Split(key[len(m.prefix):], "_")[1])
if err != nil {
logger.Errorf("parse %s: %s", key, err)
continue
}
if uint64(indx) > left/ChunkSize && uint64(indx) < right/ChunkSize {
zeroChunks = append(zeroChunks, uint32(indx))
}
}
if cursor <= 0 {
break
}
}
} else {
for i := left/ChunkSize + 1; i < right/ChunkSize; i++ {
zeroChunks = append(zeroChunks, uint32(i))
}
}
t.Length = length
now := time.Now()
t.Mtime = now.Unix()
t.Mtimensec = uint32(now.Nanosecond())
t.Ctime = now.Unix()
t.Ctimensec = uint32(now.Nanosecond())