forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
journal_manager.go
1458 lines (1280 loc) · 41.9 KB
/
journal_manager.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 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/keybase/client/go/kbfs/data"
"github.com/keybase/client/go/kbfs/ioutil"
"github.com/keybase/client/go/kbfs/kbfsblock"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/kbfs/kbfsmd"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/kbfs/tlfhandle"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/pkg/errors"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
const (
tlfJournalBrokenFmt = "%s-%d.broken"
)
var tlfJournalBrokenRegexp = regexp.MustCompile(
`[/\\]([[:alnum:]]+)-([[:digit:]]+)\.broken$`)
type journalManagerConfig struct {
// EnableAuto, if true, means the user has explicitly set its
// value. If false, then either the user turned it on and then
// off, or the user hasn't turned it on at all.
EnableAuto bool
// EnableAutoSetByUser means the user has explicitly set the
// value of EnableAuto (after this field was added).
EnableAutoSetByUser bool
}
func (jsc journalManagerConfig) getEnableAuto(currentUID keybase1.UID) (
enableAuto, enableAutoSetByUser bool) {
// If EnableAuto is true, the user has explicitly set its value.
if jsc.EnableAuto {
return true, true
}
// Otherwise, if EnableAutoSetByUser is true, it means the
// user has explicitly set the value of EnableAuto (after that
// field was added).
if jsc.EnableAutoSetByUser {
return false, true
}
// Otherwise, if the user hasn't explicitly turned off journaling,
// it's enabled by default.
return true, false
}
// ConflictJournalRecord contains info for TLF journals that are
// currently in conflict on the local device.
type ConflictJournalRecord struct {
Name tlf.CanonicalName
Type tlf.Type
Path string
ID tlf.ID
ServerViewPath keybase1.Path // for cleared conflicts only
LocalViewPath keybase1.Path // for cleared conflicts only
}
// JournalManagerStatus represents the overall status of the
// JournalManager for display in diagnostics. It is suitable for
// encoding directly as JSON.
type JournalManagerStatus struct {
RootDir string
Version int
CurrentUID keybase1.UID
CurrentVerifyingKey kbfscrypto.VerifyingKey
EnableAuto bool
EnableAutoSetByUser bool
JournalCount int
// The byte counters below are signed because
// os.FileInfo.Size() is signed. The file counter is signed
// for consistency.
StoredBytes int64
StoredFiles int64
UnflushedBytes int64
UnflushedPaths []string
EndEstimate *time.Time
DiskLimiterStatus interface{}
Conflicts []ConflictJournalRecord `json:",omitempty"`
ClearedConflicts []ConflictJournalRecord `json:",omitempty"`
}
// branchChangeListener describes a caller that will get updates via
// the onTLFBranchChange method call when the journal branch changes
// for the given TlfID. If a new branch has been created, the given
// kbfsmd.BranchID will be something other than kbfsmd.NullBranchID. If the current
// branch was pruned, it will be kbfsmd.NullBranchID. If the implementer
// will be accessing the journal, it must do so from another goroutine
// to avoid deadlocks.
type branchChangeListener interface {
onTLFBranchChange(tlf.ID, kbfsmd.BranchID)
}
// mdFlushListener describes a caller that will ge updates via the
// onMDFlush metod when an MD is flushed. If the implementer will be
// accessing the journal, it must do so from another goroutine to
// avoid deadlocks.
type mdFlushListener interface {
onMDFlush(tlf.ID, kbfsmd.BranchID, kbfsmd.Revision)
}
type clearedConflictKey struct {
tlfID tlf.ID
date time.Time // the conflict time truncated to be just the date
num uint16
}
type clearedConflictVal struct {
fakeTlfID tlf.ID
t time.Time
}
// JournalManager is the server that handles write journals. It
// interposes itself in front of BlockServer and MDOps. It uses MDOps
// instead of MDServer because it has to potentially modify the
// RootMetadata passed in, and by the time it hits MDServer it's
// already too late. However, this assumes that all MD ops go through
// MDOps.
//
// The maximum number of characters added to the root dir by a journal
// server journal is 108: 51 for the TLF journal, and 57 for
// everything else.
//
// /v1/de...-...(53 characters total)...ff(/tlf journal)
type JournalManager struct {
config Config
defaultBWS TLFJournalBackgroundWorkStatus
log traceLogger
deferLog traceLogger
dir string
delegateBlockCache data.BlockCache
delegateDirtyBlockCache data.DirtyBlockCache
delegateBlockServer BlockServer
delegateMDOps MDOps
onBranchChange branchChangeListener
onMDFlush mdFlushListener
// Just protects lastQuotaError.
lastQuotaErrorLock sync.Mutex
lastQuotaError time.Time
// Just protects lastDiskLimitError.
lastDiskLimitErrorLock sync.Mutex
lastDiskLimitError time.Time
// Protects all fields below.
lock sync.RWMutex
currentUID keybase1.UID
currentVerifyingKey kbfscrypto.VerifyingKey
tlfJournals map[tlf.ID]*tlfJournal
dirtyOps map[tlf.ID]uint
dirtyOpsDone *sync.Cond
serverConfig journalManagerConfig
// Real TLF ID -> time that conflict was cleared -> fake TLF ID
clearedConflictTlfs map[clearedConflictKey]clearedConflictVal
delegateMaker func(tlf.ID) tlfJournalBWDelegate
}
func makeJournalManager(
config Config, log logger.Logger, dir string,
bcache data.BlockCache, dirtyBcache data.DirtyBlockCache,
bserver BlockServer, mdOps MDOps, onBranchChange branchChangeListener,
onMDFlush mdFlushListener,
bws TLFJournalBackgroundWorkStatus) *JournalManager {
if len(dir) == 0 {
panic("journal root path string unexpectedly empty")
}
jManager := JournalManager{
config: config,
defaultBWS: bws,
log: traceLogger{log},
deferLog: traceLogger{log.CloneWithAddedDepth(1)},
dir: dir,
delegateBlockCache: bcache,
delegateDirtyBlockCache: dirtyBcache,
delegateBlockServer: bserver,
delegateMDOps: mdOps,
onBranchChange: onBranchChange,
onMDFlush: onMDFlush,
tlfJournals: make(map[tlf.ID]*tlfJournal),
dirtyOps: make(map[tlf.ID]uint),
clearedConflictTlfs: make(map[clearedConflictKey]clearedConflictVal),
}
jManager.dirtyOpsDone = sync.NewCond(&jManager.lock)
return &jManager
}
func (j *JournalManager) rootPath() string {
return filepath.Join(j.dir, "v1")
}
func (j *JournalManager) configPath() string {
return filepath.Join(j.rootPath(), "config.json")
}
func (j *JournalManager) readConfig() error {
return ioutil.DeserializeFromJSONFile(j.configPath(), &j.serverConfig)
}
func (j *JournalManager) writeConfig() error {
return ioutil.SerializeToJSONFile(j.serverConfig, j.configPath())
}
func (j *JournalManager) tlfJournalPathLocked(tlfID tlf.ID) string {
if j.currentVerifyingKey == (kbfscrypto.VerifyingKey{}) {
panic("currentVerifyingKey is zero")
}
// We need to generate a unique path for each (UID, device,
// TLF) tuple. Verifying keys (which are unique to a device)
// are globally unique, so no need to have the uid in the
// path. Furthermore, everything after the first two bytes
// (four characters) is randomly generated, so taking the
// first 36 characters of the verifying key gives us 16 random
// bytes (since the first two bytes encode version/type) or
// 128 random bits, which means that the expected number of
// devices generated before getting a collision in the first
// part of the path is 2^64 (see
// https://en.wikipedia.org/wiki/Birthday_problem#Cast_as_a_collision_problem
// ).
//
// By similar reasoning, for a single device, taking the first
// 16 characters of the TLF ID gives us 64 random bits, which
// means that the expected number of TLFs associated to that
// device before getting a collision in the second part of the
// path is 2^32.
shortDeviceIDStr := j.currentVerifyingKey.String()[:36]
shortTlfIDStr := tlfID.String()[:16]
dir := fmt.Sprintf("%s-%s", shortDeviceIDStr, shortTlfIDStr)
return filepath.Join(j.rootPath(), dir)
}
func (j *JournalManager) getEnableAutoLocked() (
enableAuto, enableAutoSetByUser bool) {
return j.serverConfig.getEnableAuto(j.currentUID)
}
func (j *JournalManager) getConflictIDForHandle(
tlfID tlf.ID, h *tlfhandle.Handle) (tlf.ID, bool) {
j.lock.RLock()
defer j.lock.RUnlock()
// If the handle represents a local conflict, change the
// handle's TLF ID to reflect that.
ci := h.ConflictInfo()
if ci == nil {
return tlf.NullID, false
}
if ci.Type != tlf.HandleExtensionLocalConflict {
return tlf.NullID, false
}
key := clearedConflictKey{
tlfID: tlfID,
date: time.Unix(ci.Date, 0).UTC().Round(0),
num: ci.Number,
}
val, ok := j.clearedConflictTlfs[key]
if !ok || val.fakeTlfID == tlf.NullID {
return tlf.NullID, false
}
return val.fakeTlfID, true
}
func (j *JournalManager) getTLFJournal(
tlfID tlf.ID, h *tlfhandle.Handle) (*tlfJournal, bool) {
getJournalFn := func() (*tlfJournal, bool, bool, bool) {
j.lock.RLock()
defer j.lock.RUnlock()
// Don't create any journals when logged out.
if j.currentUID.IsNil() {
return nil, false, false, false
}
tlfJournal, ok := j.tlfJournals[tlfID]
enableAuto, enableAutoSetByUser := j.getEnableAutoLocked()
return tlfJournal, enableAuto, enableAutoSetByUser, ok
}
tlfJournal, enableAuto, enableAutoSetByUser, ok := getJournalFn()
if !ok && enableAuto {
ctx := context.TODO() // plumb through from callers
if h == nil {
// h must always be passed in for MD write operations, so
// we are always safe in refusing new TLF journals in this
// case.
return nil, false
}
// Because of the above handle check, which will happen on
// every put of a TLF, we will be able to create a journal on
// the first write that happens after the user becomes a
// writer for the TLF.
isWriter, err := IsWriterFromHandle(
ctx, h, j.config.KBPKI(), j.config, j.currentUID,
j.currentVerifyingKey)
if err != nil {
j.log.CWarningf(ctx, "Couldn't find writership for %s: %+v",
tlfID, err)
return nil, false
}
if !isWriter {
return nil, false
}
j.log.CDebugf(ctx, "Enabling a new journal for %s (enableAuto=%t, set by user=%t)",
tlfID, enableAuto, enableAutoSetByUser)
err = j.Enable(ctx, tlfID, h, j.defaultBWS)
if err != nil {
j.log.CWarningf(ctx, "Couldn't enable journal for %s: %+v", tlfID, err)
return nil, false
}
tlfJournal, _, _, ok = getJournalFn()
}
return tlfJournal, ok
}
func (j *JournalManager) hasTLFJournal(tlfID tlf.ID) bool {
j.lock.RLock()
defer j.lock.RUnlock()
_, ok := j.tlfJournals[tlfID]
return ok
}
func (j *JournalManager) getHandleForJournal(
ctx context.Context, tj *tlfJournal, tlfID tlf.ID) (
*tlfhandle.Handle, error) {
bid, err := tj.getBranchID()
if err != nil {
return nil, err
}
head, err := tj.getMDHead(ctx, bid)
if err != nil {
return nil, err
}
if head == (ImmutableBareRootMetadata{}) {
return nil, nil
}
headBareHandle, err := head.MakeBareTlfHandleWithExtra()
if err != nil {
return nil, err
}
return tlfhandle.MakeHandleWithTlfID(
ctx, headBareHandle, tlfID.Type(), j.config.KBPKI(),
j.config.KBPKI(), tlfID, j.config.OfflineAvailabilityForID(tlfID))
}
func (j *JournalManager) makeFBOForJournal(
ctx context.Context, tj *tlfJournal, tlfID tlf.ID) error {
handle, err := j.getHandleForJournal(ctx, tj, tlfID)
if err != nil {
return err
}
if handle == nil {
return nil
}
_, _, err = j.config.KBFSOps().GetRootNode(ctx, handle, data.MasterBranch)
return err
}
// MakeFBOsForExistingJournals creates folderBranchOps objects for all
// existing, non-empty journals. This is useful to initialize the
// unflushed edit history, for example. It returns a wait group that
// the caller can use to determine when all the FBOs have been
// initialized. If the caller is not going to wait on the group, it
// should provoide a context that won't be canceled before the wait
// group is finished.
func (j *JournalManager) MakeFBOsForExistingJournals(
ctx context.Context) *sync.WaitGroup {
var wg sync.WaitGroup
j.lock.Lock()
defer j.lock.Unlock()
for tlfID, tj := range j.tlfJournals {
wg.Add(1)
tlfID := tlfID
tj := tj
go func() {
ctx := CtxWithRandomIDReplayable(
context.Background(), CtxFBOIDKey, CtxFBOOpID, j.log)
// Turn off tracker popups.
ctx, err := tlfhandle.MakeExtendedIdentify(
ctx, keybase1.TLFIdentifyBehavior_KBFS_INIT)
if err != nil {
j.log.CWarningf(ctx, "Error making extended identify: %+v", err)
}
defer wg.Done()
j.log.CDebugf(ctx,
"Initializing FBO for non-empty journal: %s", tlfID)
err = j.makeFBOForJournal(ctx, tj, tlfID)
if err != nil {
j.log.CWarningf(ctx,
"Error when making FBO for existing journal for %s: "+
"%+v", tlfID, err)
}
// The popups and errors were suppressed, but any errors would
// have been logged. So just close out the extended identify. If
// the user accesses the TLF directly, another proper identify
// should happen that shows errors.
_ = tlfhandle.GetExtendedIdentify(ctx).GetTlfBreakAndClose()
}()
}
return &wg
}
func (j *JournalManager) makeJournalForConflictTlfLocked(
ctx context.Context, dir string, tlfID tlf.ID,
chargedTo keybase1.UserOrTeamID) (*tlfJournal, tlf.ID, time.Time, error) {
// If this is a bak directory representing a
// moved-away conflicts branch, we should assign it a
// fake TLF ID.
matches := tlfJournalBakRegexp.FindStringSubmatch(dir)
if len(matches) == 0 {
return nil, tlf.ID{}, time.Time{},
errors.Errorf("%s is not a backup conflict dir", dir)
}
unixNano, err := strconv.ParseInt(matches[2], 10, 64)
if err != nil {
return nil, tlf.ID{}, time.Time{}, err
}
fakeTlfID, err := tlf.MakeRandomID(tlfID.Type())
if err != nil {
return nil, tlf.ID{}, time.Time{}, err
}
var delegate tlfJournalBWDelegate
if j.delegateMaker != nil {
delegate = j.delegateMaker(fakeTlfID)
}
tj, err := makeTLFJournal(
ctx, j.currentUID, j.currentVerifyingKey, dir,
tlfID, chargedTo, tlfJournalConfigAdapter{j.config},
j.delegateBlockServer, TLFJournalBackgroundWorkPaused, delegate,
j.onBranchChange, j.onMDFlush, j.config.DiskLimiter(), fakeTlfID)
if err != nil {
return nil, tlf.ID{}, time.Time{}, err
}
return tj, fakeTlfID, time.Unix(0, unixNano), nil
}
func (j *JournalManager) insertConflictJournalLocked(
ctx context.Context, tj *tlfJournal, fakeTlfID tlf.ID, t time.Time) {
const dateFormat = "2006-01-02"
dateStr := t.UTC().Format(dateFormat)
date, err := time.Parse(dateFormat, dateStr)
if err != nil {
panic(err.Error())
}
date = date.UTC().Round(0)
key := clearedConflictKey{
tlfID: tj.tlfID,
date: date,
}
val := clearedConflictVal{
fakeTlfID: fakeTlfID,
t: t,
}
// Figure out what number conflict this should be.
num := uint16(1)
toDel := make([]clearedConflictKey, 0)
toAdd := make(map[clearedConflictKey]clearedConflictVal)
for otherKey, otherVal := range j.clearedConflictTlfs {
if otherKey.tlfID != tj.tlfID || !otherKey.date.Equal(date) {
continue
}
// Increase the number for each conflict that happened before
// this one; increase any existing numbers that happened after
// it.
if otherVal.t.Before(t) {
num++
} else {
toDel = append(toDel, otherKey)
otherKey.num++
toAdd[otherKey] = otherVal
}
}
key.num = num
for _, k := range toDel {
delete(j.clearedConflictTlfs, k)
}
for k, v := range toAdd {
j.clearedConflictTlfs[k] = v
}
j.clearedConflictTlfs[key] = val
j.tlfJournals[fakeTlfID] = tj
j.log.CDebugf(ctx, "Made conflict journal for %s, real "+
"TLF ID = %s, fake TLF ID = %s, date = %s, num = %d",
tj.dir, tj.tlfID, fakeTlfID, date, num)
}
// EnableExistingJournals turns on the write journal for all TLFs for
// the given (UID, device) tuple (with the device identified by its
// verifying key) with an existing journal. Any returned error means
// that the JournalManager remains in the same state as it was before.
//
// Once this is called, this must not be called again until
// shutdownExistingJournals is called.
func (j *JournalManager) EnableExistingJournals(
ctx context.Context, currentUID keybase1.UID,
currentVerifyingKey kbfscrypto.VerifyingKey,
bws TLFJournalBackgroundWorkStatus) (err error) {
j.log.CDebugf(ctx, "Enabling existing journals (%s)", bws)
defer func() {
if err != nil {
j.deferLog.CDebugf(ctx,
"Error when enabling existing journals: %+v",
err)
}
}()
if currentUID == keybase1.UID("") {
return errors.New("Current UID is empty")
}
if currentVerifyingKey == (kbfscrypto.VerifyingKey{}) {
return errors.New("Current verifying key is empty")
}
// TODO: We should also look up journals from other
// users/devices so that we can take into account their
// journal usage.
j.lock.Lock()
defer j.lock.Unlock()
if j.currentUID == currentUID {
// The user is not changing, so nothing needs to be done.
return nil
} else if j.currentUID != keybase1.UID("") {
return errors.Errorf("Trying to set current UID from %s to %s",
j.currentUID, currentUID)
}
if j.currentVerifyingKey != (kbfscrypto.VerifyingKey{}) {
return errors.Errorf(
"Trying to set current verifying key from %s to %s",
j.currentVerifyingKey, currentVerifyingKey)
}
err = j.readConfig()
switch {
case ioutil.IsNotExist(err):
// Config file doesn't exist, so write out a default one.
err := j.writeConfig()
if err != nil {
return err
}
case err != nil:
return err
}
// Need to set it here since tlfJournalPathLocked and
// enableLocked depend on it.
j.currentUID = currentUID
j.currentVerifyingKey = currentVerifyingKey
enableSucceeded := false
defer func() {
// Revert to a clean state if the enable doesn't
// succeed, either due to a panic or error.
if !enableSucceeded {
j.shutdownExistingJournalsLocked(ctx)
}
}()
fileInfos, err := ioutil.ReadDir(j.rootPath())
if ioutil.IsNotExist(err) {
enableSucceeded = true
return nil
} else if err != nil {
return err
}
eg, groupCtx := errgroup.WithContext(ctx)
fileCh := make(chan os.FileInfo, len(fileInfos))
type journalRet struct {
id tlf.ID
journal *tlfJournal
}
journalCh := make(chan journalRet, len(fileInfos))
var conflictLock sync.Mutex
worker := func() error {
for fi := range fileCh {
name := fi.Name()
if !fi.IsDir() {
j.log.CDebugf(groupCtx, "Skipping file %q", name)
continue
}
dir := filepath.Join(j.rootPath(), name)
// Skip directories that have already been marked as broken.
matches := tlfJournalBrokenRegexp.FindStringSubmatch(dir)
if len(matches) > 0 {
j.log.CDebugf(groupCtx, "Skipping broken dir %q", name)
continue
}
// Skip directories that don't have an info file at all.
_, err := os.Lstat(getTLFJournalInfoFilePath(dir))
switch {
case err == nil:
case os.IsNotExist(err):
j.log.CDebugf(
groupCtx, "Skipping non-TLF dir %q", name)
continue
default:
j.log.CDebugf(
groupCtx, "Error stat'ing info file in dir %q: %+v",
name, err)
continue
}
uid, key, tlfID, chargedTo, err := readTLFJournalInfoFile(dir)
if err != nil {
idParts := strings.Split(name, "-")
newDirName := fmt.Sprintf(
tlfJournalBrokenFmt, idParts[len(idParts)-1],
j.config.Clock().Now().UnixNano())
fullDirName := filepath.Join(j.rootPath(), newDirName)
j.log.CDebugf(
groupCtx, "Renaming broken dir %q to %q due to error: %+v",
name, newDirName, err)
err := os.Rename(dir, fullDirName)
if err != nil {
j.log.CDebugf(
groupCtx, "Error renaming broken dir %q: %+v",
name, err)
}
continue
}
if uid != currentUID {
j.log.CDebugf(
groupCtx, "Skipping dir %q due to mismatched UID %s",
name, uid)
continue
}
if key != currentVerifyingKey {
j.log.CDebugf(
groupCtx, "Skipping dir %q due to mismatched key %s",
name, uid)
continue
}
expectedDir := j.tlfJournalPathLocked(tlfID)
if dir != expectedDir {
tj, fakeTlfID, t, err := j.makeJournalForConflictTlfLocked(
groupCtx, dir, tlfID, chargedTo)
if err != nil {
j.log.CDebugf(
groupCtx, "Skipping misnamed dir %s: %+v", dir, err)
continue
}
// Take a lock while inserting the conflict journal
// (even though we already have `journalLock`), since
// multiple workers could be running at once and we
// need to protect the cleared conflct TLF map from
// concurrent access.
conflictLock.Lock()
j.insertConflictJournalLocked(groupCtx, tj, fakeTlfID, t)
conflictLock.Unlock()
continue
}
// Allow enable even if dirty, since any dirty writes
// in flight are most likely for another user.
tj, err := j.enableLocked(groupCtx, tlfID, chargedTo, bws, true)
if err != nil {
// Don't treat per-TLF errors as fatal.
j.log.CWarningf(
groupCtx,
"Error when enabling existing journal for %s: %+v",
tlfID, err)
continue
}
// Delete any empty journals so they don't clutter up the
// directory, until the TLF is accessed again.
blockEntryCount, mdEntryCount, err := tj.getJournalEntryCounts()
if err != nil {
tj.shutdown(groupCtx)
// Don't treat per-TLF errors as fatal.
j.log.CWarningf(
groupCtx,
"Error when getting status of existing journal for %s: %+v",
tlfID, err)
continue
}
if blockEntryCount == 0 && mdEntryCount == 0 {
j.log.CDebugf(groupCtx, "Nuking empty journal for %s", tlfID)
tj.shutdown(groupCtx)
os.RemoveAll(dir)
continue
}
journalCh <- journalRet{tlfID, tj}
}
return nil
}
// Initialize many TLF journals at once to overlap disk latency as
// much as possible.
numWorkers := 100
if numWorkers > len(fileInfos) {
numWorkers = len(fileInfos)
}
for i := 0; i < numWorkers; i++ {
eg.Go(worker)
}
for _, fi := range fileInfos {
fileCh <- fi
}
close(fileCh)
err = eg.Wait()
if err != nil {
// None of the workers return an error so this should never
// happen...
return err
}
close(journalCh)
for r := range journalCh {
j.tlfJournals[r.id] = r.journal
}
j.log.CDebugf(ctx, "Done enabling journals")
enableSucceeded = true
return nil
}
// enabledLocked returns an enabled journal; it is the caller's
// responsibility to add it to `j.tlfJournals`. This allows this
// method to be called in parallel during initialization, if desired.
func (j *JournalManager) enableLocked(
ctx context.Context, tlfID tlf.ID, chargedTo keybase1.UserOrTeamID,
bws TLFJournalBackgroundWorkStatus, allowEnableIfDirty bool) (
tj *tlfJournal, err error) {
j.log.CDebugf(ctx, "Enabling journal for %s (%s)", tlfID, bws)
defer func() {
if err != nil {
j.deferLog.CDebugf(ctx,
"Error when enabling journal for %s: %+v",
tlfID, err)
}
}()
if j.currentUID == keybase1.UID("") {
return nil, errors.New("Current UID is empty")
}
if j.currentVerifyingKey == (kbfscrypto.VerifyingKey{}) {
return nil, errors.New("Current verifying key is empty")
}
if tj, ok := j.tlfJournals[tlfID]; ok {
err = tj.enable()
if err != nil {
return nil, err
}
return tj, nil
}
err = func() error {
if j.dirtyOps[tlfID] > 0 {
return errors.Errorf("Can't enable journal for %s while there "+
"are outstanding dirty ops", tlfID)
}
if j.delegateDirtyBlockCache.IsAnyDirty(tlfID) {
return errors.Errorf("Can't enable journal for %s while there "+
"are any dirty blocks outstanding", tlfID)
}
return nil
}()
if err != nil {
if !allowEnableIfDirty {
return nil, err
}
j.log.CWarningf(ctx,
"Got ignorable error on journal enable, and proceeding anyway: %+v",
err)
}
var delegate tlfJournalBWDelegate
if j.delegateMaker != nil {
delegate = j.delegateMaker(tlfID)
}
tlfDir := j.tlfJournalPathLocked(tlfID)
tj, err = makeTLFJournal(
ctx, j.currentUID, j.currentVerifyingKey, tlfDir,
tlfID, chargedTo, tlfJournalConfigAdapter{j.config},
j.delegateBlockServer, bws, delegate, j.onBranchChange, j.onMDFlush,
j.config.DiskLimiter(),
tlf.NullID)
if err != nil {
return nil, err
}
return tj, nil
}
// Enable turns on the write journal for the given TLF. If h is nil,
// it will be attempted to be fetched from the remote MD server.
func (j *JournalManager) Enable(ctx context.Context, tlfID tlf.ID,
h *tlfhandle.Handle, bws TLFJournalBackgroundWorkStatus) (err error) {
j.lock.Lock()
defer j.lock.Unlock()
chargedTo := j.currentUID.AsUserOrTeam()
if tlfID.Type() == tlf.SingleTeam {
if h == nil {
// Any path that creates a single-team TLF journal should
// also provide a handle. If not, we'd have to fetch it
// from the server, which isn't a trusted path.
return errors.Errorf(
"No handle provided for single-team TLF %s", tlfID)
}
chargedTo = h.FirstResolvedWriter()
if tid := chargedTo.AsTeamOrBust(); tid.IsSubTeam() {
// We can't charge to subteams; find the root team.
rootID, err := j.config.KBPKI().GetTeamRootID(
ctx, tid, j.config.OfflineAvailabilityForID(tlfID))
if err != nil {
return err
}
chargedTo = rootID.AsUserOrTeam()
}
}
tj, err := j.enableLocked(ctx, tlfID, chargedTo, bws, false)
if err != nil {
return err
}
j.tlfJournals[tlfID] = tj
return nil
}
// EnableAuto turns on the write journal for all TLFs, even new ones,
// persistently.
func (j *JournalManager) EnableAuto(ctx context.Context) error {
j.lock.Lock()
defer j.lock.Unlock()
if j.serverConfig.EnableAuto {
// Nothing to do.
return nil
}
j.log.CDebugf(ctx, "Enabling auto-journaling")
j.serverConfig.EnableAuto = true
j.serverConfig.EnableAutoSetByUser = true
return j.writeConfig()
}
// DisableAuto turns off automatic write journal for any
// newly-accessed TLFs. Existing journaled TLFs need to be disabled
// manually.
func (j *JournalManager) DisableAuto(ctx context.Context) error {
j.lock.Lock()
defer j.lock.Unlock()
if enabled, _ := j.getEnableAutoLocked(); !enabled {
// Nothing to do.
return nil
}
j.log.CDebugf(ctx, "Disabling auto-journaling")
j.serverConfig.EnableAuto = false
j.serverConfig.EnableAutoSetByUser = true
return j.writeConfig()
}
func (j *JournalManager) dirtyOpStart(tlfID tlf.ID) {
j.lock.Lock()
defer j.lock.Unlock()
j.dirtyOps[tlfID]++
}
func (j *JournalManager) dirtyOpEnd(tlfID tlf.ID) {
j.lock.Lock()
defer j.lock.Unlock()
if j.dirtyOps[tlfID] == 0 {
panic("Trying to end a dirty op when count is 0")
}
j.dirtyOps[tlfID]--
if j.dirtyOps[tlfID] == 0 {
delete(j.dirtyOps, tlfID)
}
if len(j.dirtyOps) == 0 {
j.dirtyOpsDone.Broadcast()
}
}
// PauseBackgroundWork pauses the background work goroutine, if it's
// not already paused.
func (j *JournalManager) PauseBackgroundWork(ctx context.Context, tlfID tlf.ID) {
j.log.CDebugf(ctx, "Signaling pause for %s", tlfID)
if tlfJournal, ok := j.getTLFJournal(tlfID, nil); ok {
tlfJournal.pauseBackgroundWork()
return
}
j.log.CDebugf(ctx,
"Could not find journal for %s; dropping pause signal",
tlfID)
}
// ResumeBackgroundWork resumes the background work goroutine, if it's
// not already resumed.
func (j *JournalManager) ResumeBackgroundWork(ctx context.Context, tlfID tlf.ID) {
j.log.CDebugf(ctx, "Signaling resume for %s", tlfID)
if tlfJournal, ok := j.getTLFJournal(tlfID, nil); ok {
tlfJournal.resumeBackgroundWork()
return
}
j.log.CDebugf(ctx,
"Could not find journal for %s; dropping resume signal",
tlfID)
}
// Flush flushes the write journal for the given TLF.
func (j *JournalManager) Flush(ctx context.Context, tlfID tlf.ID) (err error) {
j.log.CDebugf(ctx, "Flushing journal for %s", tlfID)
if tlfJournal, ok := j.getTLFJournal(tlfID, nil); ok {
// TODO: do we want to plumb lc through here as well?
return tlfJournal.flush(ctx)
}
j.log.CDebugf(ctx, "Journal not enabled for %s", tlfID)
return nil
}
// Wait blocks until the write journal has finished flushing
// everything. It is essentially the same as Flush() when the journal
// is enabled and unpaused, except that it is safe to cancel the
// context without leaving the journal in a partially-flushed state.
// It does not wait for any conflicts or squashes resulting from
// flushing the data currently in the journal.
func (j *JournalManager) Wait(ctx context.Context, tlfID tlf.ID) (err error) {
j.log.CDebugf(ctx, "Waiting on journal for %s", tlfID)
if tlfJournal, ok := j.getTLFJournal(tlfID, nil); ok {
return tlfJournal.wait(ctx)
}
j.log.CDebugf(ctx, "Journal not enabled for %s", tlfID)
return nil
}
// WaitForCompleteFlush blocks until the write journal has finished
// flushing everything. Unlike `Wait()`, it also waits for any
// conflicts or squashes detected during each flush attempt.
func (j *JournalManager) WaitForCompleteFlush(