/
log.go
1271 lines (1136 loc) · 33.2 KB
/
log.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 The Upspin Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package serverlog
import (
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"upspin.io/cloud/storage"
"upspin.io/errors"
"upspin.io/log"
"upspin.io/upspin"
"upspin.io/valid"
)
// User holds the log state for a single user.
type User struct {
name upspin.UserName
directory string
// mu locks all writes to the writer, root, and checkpoint, and the
// offSeqs structure. Readers have their own lock. A pointer so its
// clones share the lock (see ReadOnlyClone).
mu *sync.Mutex
writer *writer
root *root
checkpoint *checkpoint
// files are sorted in increasing offset order.
files []*logFile
// Kept in increasing sequence order.
// TODO: Make this a sparse slice and do small linear scans.
offSeqs []offSeq
// v1transition records the time that the logs switched
// from version 0 to version 1. If there are no version 0
// logs, it will be zero.
v1Transition upspin.Time
}
// Operation is the kind of operation performed on the DirEntry.
type Operation int
// Operations on dir entries that are logged.
const (
Put Operation = iota
Delete
)
// MaxLogSize is the maximum size of a single log file.
// It can be modified, such as for testing.
var MaxLogSize int64 = 100 * 1024 * 1024 // 100 MB
// Entry is the unit of logging.
type Entry struct {
Op Operation
Entry upspin.DirEntry
}
// writer is an append-only log of Entry.
type writer struct {
user *User // owner of this writer.
fd *os.File // file descriptor for the log.
file *logFile // log this writer is writing to.
}
// Write implements io.Writer for the our User type.
// It is the method clients use to append data to the set of log files.
// TODO: Used only in a test of corrupted data in ../tree - could be deleted.
func (u *User) Write(b []byte) (int, error) {
return u.writer.fd.Write(b)
}
// Reader reads LogEntries from the log.
type Reader struct {
// user owns the log.
user *User
// mu protects the fields below. If user.mu must be held, it must be
// held after mu.
mu sync.Mutex
fd *os.File // file descriptor for the log.
file *logFile // log this writer is writing to.
// A common buffer to avoid allocation. Too big and it
// wastes time doing I/O, too small and it misses too
// many opportunities. 4K seems good - DirEntries
// can be fairly large.
// TODO: Do some empirical measurements to help
// pick the right size.
data [4096]byte
}
// checkpoint reads and writes from/to stable storage the log state information
// and the user's root entry. It is used by Tree to track its progress
// processing the log and storing the root.
type checkpoint struct {
user *User // owner of this checkpoint.
checkpointFile *os.File // file descriptor for the checkpoint.
}
func newCheckpoint(u *User) (*checkpoint, error) {
f, err := os.OpenFile(u.checkpointFile(), os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return nil, errors.E(errors.IO, err)
}
return &checkpoint{
user: u,
checkpointFile: f,
}, nil
}
// root reads and writes the tree root from/to stable storage. Optionally, it
// lazily saves the root to a storage backend for safe keeping.
type root struct {
readOnly bool // if true, writes to this root will fail.
file *os.File // local file containing the user's root.
// savedSeq remembers the sequence number of the
// last root saved to the root file.
savedSeq int64
// TODO: Consider whether the reference should be encrypted.
ref string // storage ref for the user's root.
saveRoot chan bool // signal that the root should be saved.
saveDone chan bool // closed when saveLoop exits.
mu sync.Mutex
root []byte // contents of the root file.
}
// newRoot creates or opens the given rootFile and manages I/O to that file.
// If a storage.Storage implementation is provided, root lazily stores the
// contents of rootFile to a reference in that storage backend whenever
// rootFile is updated. The given config is used to generate a secret reference
// name for the backup.
func newRoot(rootFile string, fac upspin.Factotum, s storage.Storage) (*root, error) {
var rootRef string
var err error
if s != nil {
// Use the provided factotum to generate the secret reference.
if fac == nil {
return nil, errors.Str("cannot backup root: config has no factotum")
}
base := filepath.Base(rootFile)
rootRef, err = hashRoot(base, fac)
if err != nil {
return nil, err
}
// Try to access the storage backend now
// so a misconfiguration is caught at startup.
_, err = s.Download(rootRef)
if err != nil && !errors.Is(errors.NotExist, err) {
return nil, err
}
}
f, err := os.OpenFile(rootFile, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return nil, errors.E(errors.IO, err)
}
r := &root{file: f}
if s != nil {
r.ref = rootRef
r.saveRoot = make(chan bool, 1)
r.saveDone = make(chan bool)
go r.saveLoop(s)
}
return r, nil
}
func hashRoot(base string, fac upspin.Factotum) (string, error) {
salt := []byte("@@hashRoot!!")
suffix := make([]byte, 8)
err := fac.HKDF(salt, []byte(base), suffix)
if err != nil {
return "", err
}
return fmt.Sprintf("%s.%x", base, suffix), nil
}
func (r *root) saveLoop(s storage.Storage) {
defer close(r.saveDone)
for _ = range r.saveRoot {
r.mu.Lock()
buf := r.root
r.mu.Unlock()
err := s.Put(r.ref, buf)
if err != nil {
log.Error.Printf("dir/server: could not save root to storage backend: %v", err)
// TODO(adg): do we want to retry on failure?
// If so, what kinds of failures?
}
}
}
func (r *root) close() error {
if r.saveRoot != nil {
close(r.saveRoot)
<-r.saveDone
}
return nil
}
func (r *root) readOnlyClone() (*root, error) {
f, err := os.Open(r.file.Name())
if err != nil {
return nil, err
}
return &root{
readOnly: true,
file: f,
}, nil
}
// offSeq remembers the correspondence between a global offset
// for a user and the sequence number of the change at that offset.
type offSeq struct {
offset int64
sequence int64
}
// logFile gathers the information about a log file on disk.
type logFile struct {
name string // Full path name.
index int // Position in User.files.
version int // Version number of the format used.
offset int64 // Offset at start of file.
}
const (
// Version 0 refers to the old logs that did not have a version number
// in their name.
version = 1
oldStyleLogFilePrefix = "tree.log."
// Version 0 logs had 23 low bits of actual sequence; the upper
// bits were random. When we read version 0 logs, we clear
// the random bits.
version0SeqMask = 1<<23 - 1
)
// Open returns a User structure holding the open logs for the user in the
// named local file system's directory. If the user does not already have logs
// in this directory, Open will create them.
//
// If a store is provided then the root will be backed up to that storage
// backend whenever it changes, so that the tree may be recovered in the event
// that the log directory is lost or corrupted. If store is non-nil then the
// provided factotum must also be non-nil, as it is used to geneate the secret
// reference under which the root is backed up.
//
// Only one User can be opened for a given user in a given directory
// or logs could be corrupted. It is the caller's responsibility to
// provide this guarantee.
func Open(userName upspin.UserName, directory string, fac upspin.Factotum, store storage.Storage) (*User, error) {
if err := valid.UserName(userName); err != nil {
return nil, err
}
u := &User{
name: userName,
directory: directory,
mu: new(sync.Mutex),
}
subdir := u.logSubDir()
// Make the log directory if it doesn't exist.
// (MkdirAll returns a nil error if the directory exists.)
if err := os.MkdirAll(subdir, 0700); err != nil {
return nil, errors.E(errors.IO, err)
}
// If there's an old log, move it.
// TODO: Remove this code once all users are updated, or by June 2018.
oldLogName := filepath.Join(directory, oldStyleLogFilePrefix+string(userName))
if _, err := os.Stat(oldLogName); err == nil {
err := moveIfNotExist(oldLogName, u.logFileName(0, 0))
if err != nil {
return nil, errors.E(errors.IO, err)
}
// If we've reached this point then we've either moved the old log file
// to its new location, or it was previously hard-linked as log entry
// zero. In either case, just blindly try to delete the old log file.
// We don't need it anymore.
os.Remove(oldLogName)
}
u.findLogFiles(subdir)
u.populateOffSeqs()
u.setV1Transition()
// Create user's first log if none exists.
var (
fd *os.File
err error
)
last := len(u.files) - 1
switch {
case len(u.files) == 0:
// No files for this user yet.
_, fd, err = u.createLogFile(0)
case u.files[last].version != version:
// Must create new file with current version.
// We can only write to files with the latest version.
file := u.files[last]
size, err := sizeOfFile(file.name)
if err != nil {
break
}
_, fd, err = u.createLogFile(file.offset + size)
fd, err = os.OpenFile(u.files[len(u.files)-1].name, os.O_APPEND|os.O_WRONLY, 0600)
case u.files[last].version > version:
// Cannot happen!
return nil, errors.E(errors.Internal, errors.Errorf("bad version number for log file %q", u.files[last].name))
default:
// Things are normal.
fd, err = os.OpenFile(u.files[len(u.files)-1].name, os.O_APPEND|os.O_WRONLY, 0600)
}
if err != nil {
return nil, errors.E(errors.IO, err)
}
u.root, err = newRoot(u.rootFile(), fac, store)
if err != nil {
return nil, err
}
u.checkpoint, err = newCheckpoint(u)
if err != nil {
return nil, err
}
w := &writer{
user: u,
fd: fd,
file: u.files[len(u.files)-1],
}
u.writer = w
return u, nil
}
// ReadOnlyClone returns a copy of the user structure with no writer,
// creating a read-only accessor for the logs.
func (u *User) ReadOnlyClone() (*User, error) {
clone := *u
clone.writer = nil
var err error
clone.root, err = u.root.readOnlyClone()
if err != nil {
return nil, err
}
clone.checkpoint, err = u.checkpoint.readOnlyClone()
if err != nil {
return nil, err
}
return &clone, nil
}
// moveIfNotExist moves src to dst if dst does not yet exist.
// Otherwise it does nothing. If src does not exist, it does nothing.
func moveIfNotExist(src, dst string) error {
_, err := os.Stat(dst)
if err == nil {
// Target already exists, nothing to do.
return nil
}
if err != nil && !os.IsNotExist(err) {
return err
}
_, err = os.Stat(src)
if os.IsNotExist(err) {
// Source does not exist, nothing to do.
return nil
}
if err != nil {
return err
}
return os.Rename(src, dst)
}
// HasLog reports whether user has logs in its directory.
func HasLog(user upspin.UserName, directory string) (bool, error) {
var firstErr error
u := &User{
name: user,
directory: directory,
}
for _, name := range []string{
filepath.Join(directory, oldStyleLogFilePrefix+string(user)),
u.logSubDir(),
} {
_, err := os.Stat(name)
if err != nil {
if !os.IsNotExist(err) && firstErr != nil {
firstErr = errors.E(errors.IO, err)
}
continue
}
return true, nil
}
return false, firstErr
}
// DeleteLogs deletes all data for a user in its directory. Any existing logs
// associated with user must not be used subsequently.
func (u *User) DeleteLogs() error {
for _, fn := range []string{
filepath.Join(u.directory, oldStyleLogFilePrefix+string(u.name)),
u.checkpointFile(),
} {
err := os.Remove(fn)
if err != nil && !os.IsNotExist(err) {
return errors.E(errors.IO, err)
}
}
// Remove the user's log directory, if any, with all its contents.
// Note: RemoveAll returns nil if the subdir does not exist.
err := os.RemoveAll(u.logSubDir())
if err != nil && !os.IsNotExist(err) {
return errors.E(errors.IO, err)
}
return u.DeleteRoot()
}
// userGlob returns the set of users in the directory that match the pattern.
// The pattern is as per filePath.Glob, applied to the directory.
func userGlob(pattern string, directory string) ([]upspin.UserName, error) {
prefix := filepath.Join(directory, checkpointFilePrefix)
matches, err := filepath.Glob(prefix + pattern)
if err != nil {
return nil, errors.E(errors.IO, err)
}
users := make([]upspin.UserName, len(matches))
for i, m := range matches {
users[i] = upspin.UserName(strings.TrimPrefix(m, prefix))
}
return users, nil
}
// ListUsers returns all user names found in the given log directory.
func ListUsers(directory string) ([]upspin.UserName, error) {
return userGlob("*@*", directory)
}
// ListUsersWithSuffix returns a list is user names found in the given log
// directory that contain the required suffix, without the leading "+".
// The special suffix "*" matches all users with a non-empty suffix.
func ListUsersWithSuffix(suffix, directory string) ([]upspin.UserName, error) {
return userGlob("*+"+suffix+"@*", directory)
}
func (u *User) Close() error {
u.mu.Lock()
defer u.mu.Unlock()
err1 := u.writer.close()
err2 := u.checkpoint.close()
err3 := u.root.close()
if err1 != nil {
return err1
}
if err2 != nil {
return err2
}
return err3
}
func (u *User) Name() upspin.UserName {
return u.name
}
func (u *User) logFileName(offset int64, version int) string {
// Version 0 logs don't have a .0 at the end.
if version == 0 {
return filepath.Join(u.logSubDir(), fmt.Sprintf("%d", offset))
}
return filepath.Join(u.logSubDir(), fmt.Sprintf("%d.%d", offset, version))
}
func (u *User) logSubDir() string {
return filepath.Join(u.directory, "d.tree.log."+string(u.name))
}
const (
rootFilePrefix = "tree.root."
// For historical reasons, the checkpoint file name is "index".
checkpointFilePrefix = "tree.index."
)
func (u *User) checkpointFile() string {
return filepath.Join(u.directory, checkpointFilePrefix+string(u.name))
}
func (u *User) rootFile() string {
return filepath.Join(u.directory, rootFilePrefix+string(u.name))
}
// findLogFiles populates u.files with the log files available for this user.
// They are stored in increasing offset order.
func (u *User) findLogFiles(dir string) {
u.files = nil // Safety; shouldn't be necessary.
files, err := filepath.Glob(filepath.Join(dir, "*"))
if err != nil || len(files) == 0 {
return
}
for _, file := range files {
// Format of name is ..../*tree.log.ann@example.com/oooo.vvvv where o=offset, v=version.
// For old files, .vvvv will be missing, and version is 0.
elems := strings.Split(filepath.Base(file), ".")
var ints []int64
for _, elem := range elems {
x, err := strconv.ParseInt(elem, 10, 64)
if err != nil {
log.Error.Printf("serverlog.findLogFiles: can't parse %q", file)
continue
}
ints = append(ints, x)
}
lf := &logFile{
name: file,
index: len(u.files),
}
switch len(ints) {
case 2:
lf.version = int(ints[1])
fallthrough
case 1:
lf.offset = ints[0]
default:
log.Error.Printf("serverlog.findLogFiles: can't parse %q", file)
continue
}
u.files = append(u.files, lf)
}
sort.Slice(u.files, func(i, j int) bool { return u.files[i].offset < u.files[j].offset })
}
// populateOffSeqs reads the entries in the logs and builds User.offSeqs.
func (u *User) populateOffSeqs() {
data := make([]byte, 4096)
for _, file := range u.files {
fd, err := os.Open(file.name)
if err != nil {
log.Error.Printf("dir/server/serverlog.populateOffSeqs: user %s: %v", u.name, err)
return
}
defer fd.Close()
offset := int64(0)
for {
var le Entry
count, err := le.unmarshal(fd, data, offset)
if err != nil {
break
}
seq := le.Entry.Sequence
if file.version == 0 {
seq &= version0SeqMask
}
u.addOffSeq(file.offset+offset, seq)
offset += int64(count)
}
}
}
func (u *User) setV1Transition() {
if len(u.files) == 0 || u.files[0].version > 0 {
return // No old logs.
}
// Read the first entry past the transition, looking for the first non-zero time.
// It may take several files to get there.
data := make([]byte, 4096)
for _, file := range u.files {
if file.version == 0 {
continue
}
fd, err := os.Open(file.name)
if err != nil {
log.Error.Printf("dir/server/serverlog.setV1Transition: user %s: %v", u.name, err)
return
}
defer fd.Close()
offset := int64(0)
for {
var le Entry
count, err := le.unmarshal(fd, data, offset)
if err != nil {
// EOF or otherwise, go to next file.
break
}
offset += int64(count)
if le.Entry.Time != 0 {
u.v1Transition = le.Entry.Time
return
}
}
}
// If there were any files but we got here
// then the transition happens now.
if len(u.files) > 0 {
u.v1Transition = upspin.Now()
return
}
// No luck. Zero it is. TODO: Should we fail?
}
// V1Transition returns a time that marks the transition from old (version 0)
// logs to version 1. DirEntries created before this time use the old Sequence
// number scheme, in which the upper 23 bits are noise. These should be
// cleared before reporting the sequence number to the client.
func (u *User) V1Transition() upspin.Time {
return u.v1Transition
}
// createLogFile creates a file for the offset and returns the logFile and open fd.
func (u *User) createLogFile(offset int64) (*logFile, *os.File, error) {
name := u.logFileName(offset, version)
fd, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return nil, nil, err
}
lf := &logFile{
name: name,
index: len(u.files),
version: version,
offset: offset,
}
u.files = append(u.files, lf)
return lf, fd, err
}
// isWriter reports whether the index is that of the most recent log file.
// It's used to permit Reader to check whether it will interfere with writer.
func (u *User) isWriter(file *logFile) bool {
u.mu.Lock()
defer u.mu.Unlock()
return file == u.writer.file
}
// whichLogFile returns the log file to use to read this offset.
// u.mu must be held.
func (u *User) whichLogFile(offset int64) *logFile {
for i := 1; i < len(u.files); i++ {
if u.files[i].offset > offset {
return u.files[i-1]
}
}
return u.files[len(u.files)-1]
}
// OffsetOf returns the global offset in the user's logs for this sequence number.
// It returns -1 if the sequence number does not appear in the logs.
// ReadAt will return an error if asked to read at a negative offset.
func (u *User) OffsetOf(seq int64) int64 {
if seq == 0 {
// Start of file. There may be no data yet.
// TODO: How does this arise? (It does, but it shouldn't.)
return 0
}
u.mu.Lock()
defer u.mu.Unlock()
i := sort.Search(len(u.offSeqs), func(i int) bool { return u.offSeqs[i].sequence >= seq })
if i < len(u.offSeqs) && u.offSeqs[i].sequence == seq {
return u.offSeqs[i].offset
}
return -1
}
// Append appends a Entry to the end of the writer log.
func (u *User) Append(e *Entry) error {
buf, err := e.marshal()
if err != nil {
return err
}
u.mu.Lock()
defer u.mu.Unlock()
w := u.writer
prevSize := size(w.fd)
offset := w.file.offset + prevSize
// Is it time to move to a new log file?
if prevSize >= MaxLogSize {
// Close the current underlying log file.
err = w.close()
if err != nil {
return errors.E(errors.IO, err)
}
// Create a new log file where the previous one left off.
file, fd, err := u.createLogFile(w.file.offset + prevSize)
if err != nil {
return errors.E(errors.IO, err)
}
w.file = file
w.fd = fd
prevSize = 0
}
// File is append-only, so this is guaranteed to write to the tail.
n, err := w.fd.Write(buf)
if err != nil {
return errors.E(errors.IO, err)
}
err = w.fd.Sync()
if err != nil {
return errors.E(errors.IO, err)
}
// Sanity check: flush worked and the new offset relative to the
// beginning of this file is the expected one.
newOffs := prevSize + int64(n)
if newOffs != size(w.fd) {
// This might indicate a race somewhere, despite the locks.
return errors.E(errors.IO, errors.Errorf("file.Sync did not update offset: expected %d, got %d", newOffs, size(w.fd)))
}
u.addOffSeq(offset, e.Entry.Sequence)
return nil
}
// addOffSeq remembers an offset/sequence pair.
func (u *User) addOffSeq(offset, sequence int64) {
// The offSeqs slice must be kept in Sequence order, which might not be
// in offset order if there is concurrent access. We could sort the list but
// the invariant is that it's sorted when we get here, so all we need to do
// is insert the new record in the right place. Moreover, it will be near
// the end so it's fastest just to scan backwards.
var i int
for i = len(u.offSeqs); i > 0; i-- {
if u.offSeqs[i-1].sequence <= sequence {
break
}
}
u.offSeqs = append(u.offSeqs, offSeq{})
copy(u.offSeqs[i+1:], u.offSeqs[i:])
u.offSeqs[i] = offSeq{
offset: offset,
sequence: sequence,
}
}
// ReadAt reads an entry from the log at offset. It returns the log entry and
// the next offset. If offset is negative, which may correspond to an invalid
// sequence number processed by OffsetOf, it returns an error.
func (r *Reader) ReadAt(offset int64) (le Entry, next int64, err error) {
r.mu.Lock()
defer r.mu.Unlock()
// The maximum offset we can satisfy with the current log file.
maxOff := r.file.offset + size(r.fd)
// Is the requested offset outside the bounds of the current log file?
before := offset < r.file.offset
after := offset >= maxOff
if before || after {
// Locate the file and open it.
r.user.mu.Lock()
err := r.openLogForOffset(offset)
r.user.mu.Unlock()
if err != nil {
return le, 0, errors.E(errors.IO, err)
}
// Recompute maxOff for the new file.
maxOff = r.file.offset + size(r.fd)
}
// If we're reading from the log file being written, then we
// must lock r.user.mu to avoid reading partially-written data.
if r.user.isWriter(r.file) {
r.user.mu.Lock()
defer r.user.mu.Unlock()
}
// Are we past the end of the current file?
if offset >= maxOff {
return le, maxOff, nil
}
next = offset
count, err := le.unmarshal(r.fd, r.data[:], offset-r.file.offset)
if err != nil {
return le, next, err
}
next += int64(count)
if r.file.version == 0 {
le.Entry.Sequence &= version0SeqMask
}
return
}
// AppendOffset returns the offset of the end of the written log file or -1 on error.
func (u *User) AppendOffset() int64 {
u.mu.Lock()
defer u.mu.Unlock()
w := u.writer
return w.file.offset + size(w.fd)
}
// EndOffset returns the offset of the end of the current file or -1 on error.
// TODO: Used only in a test in ../tree. Could be deleted.
func (r *Reader) EndOffset() int64 {
r.mu.Lock()
defer r.mu.Unlock()
// If we're reading from the same file as the current writer, lock it.
// Order is important.
if r.file.offset == r.user.files[len(r.user.files)-1].offset {
r.user.mu.Lock()
defer r.user.mu.Unlock()
}
return r.file.offset + size(r.fd)
}
// size returns the offset at the end of the file or -1 on error.
// The file must be changed simultaneously with this call.
func size(f *os.File) int64 {
fi, err := f.Stat()
if err != nil {
return -1
}
return fi.Size()
}
// sizeOfFile returns the offset at the end of the named file.
func sizeOfFile(name string) (int64, error) {
fi, err := os.Stat(name)
return fi.Size(), err
}
// Truncate truncates the write log at offset.
func (u *User) Truncate(offset int64) error {
u.mu.Lock()
defer u.mu.Unlock()
// Delete any files after the one holding offset.
file := u.whichLogFile(offset)
for i := file.index + 1; i < len(u.files); i++ {
err := os.Remove(u.files[i].name)
if err != nil {
return errors.E(errors.IO, err)
}
}
u.files = u.files[:file.index+1]
// Move the writer to that file, if not already there.
w := u.writer
if w.file != file {
if err := w.close(); err != nil {
return errors.E(errors.IO, err)
}
fd, err := os.OpenFile(file.name, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return errors.E(errors.IO, err)
}
w.file = file
w.fd = fd
}
// Truncate the active file.
pos := offset - w.file.offset
if pos < size(w.fd) {
err := w.fd.Truncate(pos)
if err != nil {
return errors.E(errors.IO, err)
}
w.fd.Seek(pos, io.SeekStart)
}
u.truncateOffSeqs(offset)
return nil
}
// truncateOffSeqs truncates the offSeqs list at the specified offset. u.mu must be locked.
func (u *User) truncateOffSeqs(offset int64) {
i := sort.Search(len(u.offSeqs), func(i int) bool { return u.offSeqs[i].offset >= offset })
if i >= len(u.offSeqs) {
/* Nothing to do */
return
}
// Make a copy to save what might be a lot of memory. Append will add some headroom.
u.offSeqs = append([]offSeq{}, u.offSeqs[:i]...)
}
// NewReader makes a reader of the user's log.
func (u *User) NewReader() (*Reader, error) {
r := &Reader{}
// Order is important.
r.mu.Lock()
defer r.mu.Unlock()
u.mu.Lock()
defer u.mu.Unlock()
w := u.writer
r.user = u
if w.fd == nil {
panic("nil writer")
}
err := r.openLogForOffset(w.file.offset)
if err != nil {
return nil, errors.E(errors.IO, err)
}
return r, nil
}
// openLogForOffset opens the log file that holds the offset.
// r.mu must be held.
func (r *Reader) openLogForOffset(offset int64) error {
logFile := r.user.whichLogFile(offset)
// Re-opening the same offset?
if r.fd != nil && r.fd.Name() == logFile.name {
return nil
}
f, err := os.Open(logFile.name)
if err != nil {
return err
}
if r.fd != nil {
r.fd.Close()
}
r.fd = f
r.file = logFile
return nil
}
// close closes the writer. user.mu must be held.
func (w *writer) close() error {
if w == nil || w.fd == nil {
return nil
}
err := w.fd.Close()
w.fd = nil
return err
}
// Close closes the reader.
func (r *Reader) Close() error {
r.mu.Lock()
defer r.mu.Unlock()
if r.fd != nil {
err := r.fd.Close()
r.fd = nil
return err
}
return nil
}
// Root returns the user's root by retrieving it from local stable storage.
func (u *User) Root() (*upspin.DirEntry, error) {
u.mu.Lock()
defer u.mu.Unlock()
de, err := u.root.get()
if err != nil {
return nil, errors.E(u.Name(), err)
}
return de, nil
}
func (r *root) get() (*upspin.DirEntry, error) {
buf, err := readAllFromTop(r.file)
if err != nil {
return nil, errors.E(errors.IO, err)
}
if len(buf) == 0 {
return nil, errors.E(errors.NotExist, "no root for user")
}
var root upspin.DirEntry
more, err := root.Unmarshal(buf)
if err != nil {
return nil, err
}
if len(more) != 0 {
return nil, errors.E(errors.IO, errors.Errorf("root has %d left over bytes", len(more)))
}
r.savedSeq = root.Sequence
return &root, nil
}
// SaveRoot saves the user's root entry to stable storage.