forked from nats-io/nats-streaming-server
/
filestore.go
1683 lines (1518 loc) · 43.8 KB
/
filestore.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 Apcera Inc. All rights reserved.
package stores
import (
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
"bufio"
"github.com/nats-io/go-nats-streaming/pb"
"github.com/nats-io/nats-streaming-server/spb"
"github.com/nats-io/nats-streaming-server/util"
)
const (
// Our file version.
fileVersion = 1
// Number of files for a MsgStore on a given channel.
numFiles = 5
// Name of the subscriptions file.
subsFileName = "subs.dat"
// Name of the clients file.
clientsFileName = "clients.dat"
// Name of the server file.
serverFileName = "server.dat"
// Number of bytes required to store a CRC-32 checksum
crcSize = crc32.Size
// Size of a record header.
// 4 bytes: For typed records: 1 byte for type, 3 bytes for buffer size
// For non typed rec: buffer size
// +4 bytes for CRC-32
recordHeaderSize = 4 + crcSize
// defaultBufSize is used for various buffered IO operations
defaultBufSize = 10 * 1024 * 1024
)
// FileStoreOption is a function on the options for a File Store
type FileStoreOption func(*FileStoreOptions) error
// FileStoreOptions can be used to customize a File Store
type FileStoreOptions struct {
// BufferSize is the size of the buffer used during store operations.
BufferSize int
// CompactEnabled allows to enable/disable files compaction.
CompactEnabled bool
// CompactInterval indicates the minimum interval (in seconds) between compactions.
CompactInterval int
// CompactFragmentation indicates the minimum ratio of fragmentation
// to trigger compaction. For instance, 50 means that compaction
// would not happen until fragmentation is more than 50%.
CompactFragmentation int
// CompactMinFileSize indicates the minimum file size before compaction
// can be performed, regardless of the current file fragmentation.
CompactMinFileSize int64
// DoCRC enables (or disables) CRC checksum verification on read operations.
DoCRC bool
// CRCPoly is a polynomial used to make the table used in CRC computation.
CRCPolynomial int64
// DoSync indicates if `File.Sync()`` is called during a flush.
DoSync bool
}
// DefaultFileStoreOptions defines the default options for a File Store.
var DefaultFileStoreOptions = FileStoreOptions{
BufferSize: 2 * 1024 * 1024, // 2MB
CompactEnabled: true,
CompactInterval: 5 * 60, // 5 minutes
CompactFragmentation: 50,
CompactMinFileSize: 1024 * 1024,
DoCRC: true,
CRCPolynomial: int64(crc32.IEEE),
DoSync: true,
}
// BufferSize is a FileStore option that sets the size of the buffer used
// during store writes. This can help improve write performance.
func BufferSize(size int) FileStoreOption {
return func(o *FileStoreOptions) error {
o.BufferSize = size
return nil
}
}
// CompactEnabled is a FileStore option that enables or disables file compaction.
// The value false will disable compaction.
func CompactEnabled(enabled bool) FileStoreOption {
return func(o *FileStoreOptions) error {
o.CompactEnabled = enabled
return nil
}
}
// CompactInterval is a FileStore option that defines the minimum compaction interval.
// Compaction is not timer based, but instead when things get "deleted". This value
// prevents compaction to happen too often.
func CompactInterval(seconds int) FileStoreOption {
return func(o *FileStoreOptions) error {
o.CompactInterval = seconds
return nil
}
}
// CompactFragmentation is a FileStore option that defines the fragmentation ratio
// below which compaction would not occur. For instance, specifying 50 means that
// if other variables would allow for compaction, the compaction would occur only
// after 50% of the file has data that is no longer valid.
func CompactFragmentation(fragmentation int) FileStoreOption {
return func(o *FileStoreOptions) error {
o.CompactFragmentation = fragmentation
return nil
}
}
// CompactMinFileSize is a FileStore option that defines the minimum file size below
// which compaction would not occur. Specify `-1` if you don't want any minimum.
func CompactMinFileSize(fileSize int64) FileStoreOption {
return func(o *FileStoreOptions) error {
o.CompactMinFileSize = fileSize
return nil
}
}
// DoCRC is a FileStore option that defines if a CRC checksum verification should
// be performed when records are read from disk.
func DoCRC(enableCRC bool) FileStoreOption {
return func(o *FileStoreOptions) error {
o.DoCRC = enableCRC
return nil
}
}
// CRCPolynomial is a FileStore option that defines the polynomial to use to create
// the table used for CRC-32 Checksum.
// See https://golang.org/pkg/hash/crc32/#MakeTable
func CRCPolynomial(polynomial int64) FileStoreOption {
return func(o *FileStoreOptions) error {
o.CRCPolynomial = polynomial
return nil
}
}
// DoSync is a FileStore option that defines if `File.Sync()` should be called
// during a `Flush()` call.
func DoSync(enableFileSync bool) FileStoreOption {
return func(o *FileStoreOptions) error {
o.DoSync = enableFileSync
return nil
}
}
// AllOptions is a convenient option to pass all options from a FileStoreOptions
// structure to the constructor.
func AllOptions(opts *FileStoreOptions) FileStoreOption {
return func(o *FileStoreOptions) error {
// Make a copy
*o = *opts
return nil
}
}
// Type for the records in the subscriptions file
type recordType byte
// Protobufs do not share a common interface, yet, when saving a
// record on disk, we have to get the size and marshal the record in
// a buffer. These methods are available in all the protobuf.
// So we create this interface with those two methods to be used by the
// writeRecord method.
type record interface {
Size() int
MarshalTo([]byte) (int, error)
}
// This is use for cases when the record is not typed
const recNoType = recordType(0)
// Record types for subscription file
const (
subRecNew = recordType(iota) + 1
subRecUpdate
subRecDel
subRecAck
subRecMsg
)
// Record types for client store
const (
addClient = recordType(iota) + 1
delClient
)
// FileStore is the storage interface for STAN servers, backed by files.
type FileStore struct {
genericStore
rootDir string
serverFile *os.File
clientsFile *os.File
opts FileStoreOptions
compactItvl time.Duration
addClientRec spb.ClientInfo
delClientRec spb.ClientDelete
cliFileSize int64
cliDeleteRecs int // Number of deleted client records
cliCompactTS time.Time
crcTable *crc32.Table
}
type subscription struct {
sub *spb.SubState
seqnos map[uint64]struct{}
}
// FileSubStore is a subscription store in files.
type FileSubStore struct {
genericSubStore
tmpSubBuf []byte
file *os.File
bw *bufio.Writer
delSub spb.SubStateDelete
updateSub spb.SubStateUpdate
subs map[uint64]*subscription
opts *FileStoreOptions // points to options from FileStore
compactItvl time.Duration
fileSize int64
numRecs int // Number of records (sub and msgs)
delRecs int // Number of delete (or ack) records
rootDir string
compactTS time.Time
crcTable *crc32.Table // reference to the one from FileStore
}
// fileSlice represents one of the message store file (there are a number
// of files for a MsgStore on a given channel).
type fileSlice struct {
fileName string
firstMsg *pb.MsgProto
lastMsg *pb.MsgProto
msgsCount int
msgsSize uint64
}
// FileMsgStore is a per channel message file store.
type FileMsgStore struct {
genericMsgStore
tmpMsgBuf []byte
file *os.File
bw *bufio.Writer
files [numFiles]*fileSlice
currSliceIdx int
opts *FileStoreOptions // points to FileStore options
crcTable *crc32.Table // reference to the one from FileStore
}
// openFile opens the file specified by `filename`.
// If the file exists, it checks that the version is supported.
// If no file mode is provided, the file is created if not present,
// opened in Read/Write and Append mode.
func openFile(fileName string, modes ...int) (*os.File, error) {
checkVersion := false
mode := os.O_RDWR | os.O_CREATE | os.O_APPEND
if len(modes) > 0 {
// Use the provided modes instead
mode = 0
for _, m := range modes {
mode |= m
}
}
// Check if file already exists
if s, err := os.Stat(fileName); s != nil && err == nil {
checkVersion = true
}
file, err := os.OpenFile(fileName, mode, 0666)
if err != nil {
return nil, err
}
if checkVersion {
err = checkFileVersion(file)
} else {
// This is a new file, write our file version
err = util.WriteInt(file, fileVersion)
}
if err != nil {
file.Close()
file = nil
}
return file, err
}
// check that the version of the file is understood by this interface
func checkFileVersion(r io.Reader) error {
fv, err := util.ReadInt(r)
if err != nil {
return fmt.Errorf("unable to verify file version: %v", err)
}
if fv == 0 || fv > fileVersion {
return fmt.Errorf("unsupported file version: %v (supports [1..%v])", fv, fileVersion)
}
return nil
}
// writeRecord writes a record to `w`.
// The record layout is as follows:
// 8 bytes: 4 bytes for type and/or size combined
// 4 bytes for CRC-32
// variable bytes: payload.
// If a buffer is provided, this function uses it and expands it if necessary.
// The function returns the buffer (possibly changed due to expansion) and the
// number of bytes written into that buffer.
func writeRecord(w io.Writer, buf []byte, recType recordType, rec record, crcTable *crc32.Table) ([]byte, int, error) {
// Size of record itself
recSize := rec.Size()
// This is the header + payload size
totalSize := recordHeaderSize + recSize
// Alloc or realloc as needed
buf = util.EnsureBufBigEnough(buf, totalSize)
// If there is a record type, encode it
headerFirstInt := 0
if recType != recNoType {
if recSize > 0xFFFFFF {
panic("record size too big")
}
// Encode the type in the high byte of the header
headerFirstInt = int(recType)<<24 | recSize
} else {
// The header is the size of the record
headerFirstInt = recSize
}
// Write the first part of the header at the beginning of the buffer
util.ByteOrder.PutUint32(buf[:4], uint32(headerFirstInt))
// Marshal the record into the given buffer, after the header offset
if _, err := rec.MarshalTo(buf[recordHeaderSize:totalSize]); err != nil {
// Return the buffer because the caller may have provided one
return buf, 0, err
}
// Compute CRC
crc := crc32.Checksum(buf[recordHeaderSize:totalSize], crcTable)
// Write it in the buffer
util.ByteOrder.PutUint32(buf[4:recordHeaderSize], crc)
// Write the content of our slice into the writer `w`
if _, err := w.Write(buf[:totalSize]); err != nil {
// Return the tmpBuf because the caller may have provided one
return buf, 0, err
}
return buf, totalSize, nil
}
// readRecord reads a record from `r`, possibly checking the CRC-32 checksum.
// When `buf`` is not nil, this function ensures the buffer is big enough to
// hold the payload (expanding if necessary). Therefore, this call always
// return `buf`, regardless if there is an error or not.
// The caller is indicating if the record is supposed to be typed or not.
func readRecord(r io.Reader, buf []byte, recTyped bool, crcTable *crc32.Table, checkCRC bool) ([]byte, int, recordType, error) {
_header := [recordHeaderSize]byte{}
header := _header[:]
if _, err := io.ReadFull(r, header); err != nil {
return buf, 0, recNoType, err
}
recType := recNoType
recSize := 0
firstInt := int(util.ByteOrder.Uint32(header[:4]))
if recTyped {
recType = recordType(firstInt >> 24 & 0xFF)
recSize = firstInt & 0xFFFFFF
} else {
recSize = firstInt
}
crc := util.ByteOrder.Uint32(header[4:recordHeaderSize])
// Now we are going to read the payload
buf = util.EnsureBufBigEnough(buf, recSize)
if _, err := io.ReadFull(r, buf[:recSize]); err != nil {
return buf, 0, recNoType, err
}
if checkCRC {
// check CRC against what was stored
if c := crc32.Checksum(buf[:recSize], crcTable); c != crc {
return buf, 0, recNoType, fmt.Errorf("corrupted data, expected crc to be 0x%08x, got 0x%08x", crc, c)
}
}
return buf, recSize, recType, nil
}
////////////////////////////////////////////////////////////////////////////
// FileStore methods
////////////////////////////////////////////////////////////////////////////
// NewFileStore returns a factory for stores backed by files, and recovers
// any state present.
// If not limits are provided, the store will be created with
// DefaultChannelLimits.
func NewFileStore(rootDir string, limits *ChannelLimits, options ...FileStoreOption) (*FileStore, *RecoveredState, error) {
fs := &FileStore{
rootDir: rootDir,
opts: DefaultFileStoreOptions,
}
fs.init(TypeFile, limits)
for _, opt := range options {
if err := opt(&fs.opts); err != nil {
return nil, nil, err
}
}
// Convert the compact interval in time.Duration
fs.compactItvl = time.Duration(fs.opts.CompactInterval) * time.Second
// Create the table using polynomial in options
if fs.opts.CRCPolynomial == int64(crc32.IEEE) {
fs.crcTable = crc32.IEEETable
} else {
fs.crcTable = crc32.MakeTable(uint32(fs.opts.CRCPolynomial))
}
if err := os.MkdirAll(rootDir, os.ModeDir+os.ModePerm); err != nil && !os.IsExist(err) {
return nil, nil, fmt.Errorf("unable to create the root directory [%s]: %v", rootDir, err)
}
var err error
var recoveredState *RecoveredState
var serverInfo *spb.ServerInfo
var recoveredClients []*Client
var recoveredSubs = make(RecoveredSubscriptions)
var channels []os.FileInfo
var msgStore *FileMsgStore
var subStore *FileSubStore
// Ensure store is closed in case of return with error
defer func() {
if err != nil {
fs.Close()
}
}()
// Open/Create the server file (note that this file must not be opened,
// in APPEND mode to allow truncate to work).
fileName := filepath.Join(fs.rootDir, serverFileName)
fs.serverFile, err = openFile(fileName, os.O_RDWR, os.O_CREATE)
if err != nil {
return nil, nil, err
}
// Open/Create the client file.
fileName = filepath.Join(fs.rootDir, clientsFileName)
fs.clientsFile, err = openFile(fileName)
if err != nil {
return nil, nil, err
}
// Recover the server file.
serverInfo, err = fs.recoverServerInfo()
if err != nil {
return nil, nil, err
}
// If the server file is empty, then we are done
if serverInfo == nil {
// We return the file store instance, but no recovered state.
return fs, nil, nil
}
// Recover the clients file
recoveredClients, err = fs.recoverClients()
if err != nil {
return nil, nil, err
}
// Get the channels (there are subdirectories of rootDir)
channels, err = ioutil.ReadDir(rootDir)
if err != nil {
return nil, nil, err
}
// Go through the list
for _, c := range channels {
// Channels are directories. Ignore simple files
if !c.IsDir() {
continue
}
channel := c.Name()
channelDirName := filepath.Join(rootDir, channel)
// Recover messages for this channel
msgStore, err = fs.newFileMsgStore(channelDirName, channel, true)
if err != nil {
break
}
subStore, err = fs.newFileSubStore(channelDirName, channel, true)
if err != nil {
msgStore.Close()
break
}
// For this channel, construct an array of RecoveredSubState
rssArray := make([]*RecoveredSubState, 0, len(subStore.subs))
// Fill that array with what we got from newFileSubStore.
for _, sub := range subStore.subs {
rss := &RecoveredSubState{
Sub: sub.sub,
Pending: make(PendingAcks),
}
// If we recovered any seqno...
if len(sub.seqnos) > 0 {
// Lookup messages, and if we find those, update the
// Pending map.
for seq := range sub.seqnos {
// Access directly 'msgs' here. If we have a
// different implementation where we don't
// keep messages around, we would still have
// a cache of messages per channel that will
// then be cleared after this loop when we
// are done restoring the subscriptions.
if m := msgStore.msgs[seq]; m != nil {
rss.Pending[seq] = m
}
}
}
// Add to the array of recovered subscriptions
rssArray = append(rssArray, rss)
}
// This is the recovered subscription state for this channel
recoveredSubs[channel] = rssArray
fs.channels[channel] = &ChannelStore{
Subs: subStore,
Msgs: msgStore,
}
}
if err != nil {
return nil, nil, err
}
// Create the recovered state to return
recoveredState = &RecoveredState{
Info: serverInfo,
Clients: recoveredClients,
Subs: recoveredSubs,
}
return fs, recoveredState, nil
}
// Init is used to persist server's information after the first start
func (fs *FileStore) Init(info *spb.ServerInfo) error {
fs.Lock()
defer fs.Unlock()
f := fs.serverFile
// Truncate the file (4 is the size of the fileVersion record)
if err := f.Truncate(4); err != nil {
return err
}
// Move offset to 4 (truncate does not do that)
if _, err := f.Seek(4, 0); err != nil {
return err
}
// ServerInfo record is not typed. We also don't pass a reusable buffer.
if _, _, err := writeRecord(f, nil, recNoType, info, fs.crcTable); err != nil {
return err
}
return nil
}
// recoverClients reads the client files and returns an array of RecoveredClient
func (fs *FileStore) recoverClients() ([]*Client, error) {
var err error
var recType recordType
var recSize int
_buf := [256]byte{}
buf := _buf[:]
// Create a buffered reader to speed-up recovery
br := bufio.NewReaderSize(fs.clientsFile, defaultBufSize)
for {
buf, recSize, recType, err = readRecord(br, buf, true, fs.crcTable, fs.opts.DoCRC)
if err != nil {
if err == io.EOF {
err = nil
break
}
return nil, err
}
fs.cliFileSize += int64(recSize + recordHeaderSize)
switch recType {
case addClient:
c := &Client{}
if err := c.ClientInfo.Unmarshal(buf[:recSize]); err != nil {
return nil, err
}
// Add to the map. Note that if one already exists, which should
// not, just replace with this most recent one.
fs.clients[c.ID] = c
case delClient:
c := spb.ClientDelete{}
if err := c.Unmarshal(buf[:recSize]); err != nil {
return nil, err
}
delete(fs.clients, c.ID)
fs.cliDeleteRecs++
default:
return nil, fmt.Errorf("invalid client record type: %v", recType)
}
}
clients := make([]*Client, len(fs.clients))
i := 0
// Convert the map into an array
for _, c := range fs.clients {
clients[i] = c
i++
}
return clients, nil
}
// recoverServerInfo reads the server file and returns a ServerInfo structure
func (fs *FileStore) recoverServerInfo() (*spb.ServerInfo, error) {
file := fs.serverFile
info := &spb.ServerInfo{}
buf, size, _, err := readRecord(file, nil, false, fs.crcTable, fs.opts.DoCRC)
if err != nil {
if err == io.EOF {
// We are done, no state recovered
return nil, nil
}
return nil, err
}
// Check that the size of the file is consistent with the size
// of the record we are supposed to recover. Account for the
// 12 bytes (4 + recordHeaderSize) corresponding to the fileVersion and
// record header.
fstat, err := file.Stat()
if err != nil {
return nil, err
}
expectedSize := int64(size + 4 + recordHeaderSize)
if fstat.Size() != expectedSize {
return nil, fmt.Errorf("incorrect file size, expected %v bytes, got %v bytes",
expectedSize, fstat.Size())
}
// Reconstruct now
if err := info.Unmarshal(buf[:size]); err != nil {
return nil, err
}
return info, nil
}
// CreateChannel creates a ChannelStore for the given channel, and returns
// `true` to indicate that the channel is new, false if it already exists.
func (fs *FileStore) CreateChannel(channel string, userData interface{}) (*ChannelStore, bool, error) {
fs.Lock()
defer fs.Unlock()
channelStore := fs.channels[channel]
if channelStore != nil {
return channelStore, false, nil
}
// Check for limits
if err := fs.canAddChannel(); err != nil {
return nil, false, err
}
// We create the channel here...
channelDirName := filepath.Join(fs.rootDir, channel)
if err := os.MkdirAll(channelDirName, os.ModeDir+os.ModePerm); err != nil {
return nil, false, err
}
var err error
var msgStore MsgStore
var subStore SubStore
msgStore, err = fs.newFileMsgStore(channelDirName, channel, false)
if err != nil {
return nil, false, err
}
subStore, err = fs.newFileSubStore(channelDirName, channel, false)
if err != nil {
msgStore.Close()
return nil, false, err
}
channelStore = &ChannelStore{
Subs: subStore,
Msgs: msgStore,
UserData: userData,
}
fs.channels[channel] = channelStore
return channelStore, true, nil
}
// AddClient stores information about the client identified by `clientID`.
func (fs *FileStore) AddClient(clientID, hbInbox string, userData interface{}) (*Client, bool, error) {
sc, isNew, err := fs.genericStore.AddClient(clientID, hbInbox, userData)
if err != nil {
return nil, false, err
}
if !isNew {
return sc, false, nil
}
fs.Lock()
fs.addClientRec = spb.ClientInfo{ID: clientID, HbInbox: hbInbox}
_, size, err := writeRecord(fs.clientsFile, nil, addClient, &fs.addClientRec, fs.crcTable)
if err != nil {
delete(fs.clients, clientID)
fs.Unlock()
return nil, false, err
}
fs.cliFileSize += int64(size)
fs.Unlock()
return sc, true, nil
}
// DeleteClient invalidates the client identified by `clientID`.
func (fs *FileStore) DeleteClient(clientID string) *Client {
sc := fs.genericStore.DeleteClient(clientID)
if sc != nil {
fs.Lock()
fs.delClientRec = spb.ClientDelete{ID: clientID}
_, size, _ := writeRecord(fs.clientsFile, nil, delClient, &fs.delClientRec, fs.crcTable)
fs.cliDeleteRecs++
fs.cliFileSize += int64(size)
// Check if this triggers a need for compaction
if fs.shouldCompactClientFile() {
fs.compactClientFile()
}
fs.Unlock()
}
return sc
}
// shouldCompactClientFile returns true if the client file should be compacted
// Lock is held by caller
func (fs *FileStore) shouldCompactClientFile() bool {
// Global switch
if !fs.opts.CompactEnabled {
return false
}
// Check that if minimum file size is set, the client file
// is at least at the minimum.
if fs.opts.CompactMinFileSize > 0 && fs.cliFileSize < fs.opts.CompactMinFileSize {
return false
}
// Check fragmentation
frag := fs.cliDeleteRecs * 100 / (fs.cliDeleteRecs + len(fs.clients))
if frag < fs.opts.CompactFragmentation {
return false
}
// Check that we don't do too often
if time.Now().Sub(fs.cliCompactTS) < fs.compactItvl {
return false
}
return true
}
// Rewrite the content of the clients map into a temporary file,
// then swap back to active file.
// Store lock held on entry
func (fs *FileStore) compactClientFile() error {
// Open a temporary file
tmpFile, err := getTempFile(fs.rootDir, clientsFileName)
if err != nil {
return err
}
defer func() {
if tmpFile != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
}
}()
bw := bufio.NewWriterSize(tmpFile, defaultBufSize)
fileSize := int64(0)
size := 0
_buf := [256]byte{}
buf := _buf[:]
// Dump the content of active clients into the temporary file.
for _, c := range fs.clients {
fs.addClientRec = spb.ClientInfo{ID: c.ID, HbInbox: c.HbInbox}
buf, size, err = writeRecord(bw, buf, addClient, &fs.addClientRec, fs.crcTable)
if err != nil {
return err
}
fileSize += int64(size)
}
// Flush the buffer on disk
if err := bw.Flush(); err != nil {
return err
}
// Switch the temporary file with the original one.
fs.clientsFile, err = swapFiles(tmpFile, fs.clientsFile)
if err != nil {
return err
}
// Avoid unnecesary attempt to cleanup
tmpFile = nil
fs.cliDeleteRecs = 0
fs.cliFileSize = fileSize
fs.cliCompactTS = time.Now()
return nil
}
// Return a temporary file (including file version)
func getTempFile(rootDir, prefix string) (*os.File, error) {
tmpFile, err := ioutil.TempFile(rootDir, prefix)
if err != nil {
return nil, err
}
if err := util.WriteInt(tmpFile, fileVersion); err != nil {
return nil, err
}
return tmpFile, nil
}
// When a store file is compacted, the content is rewritten into a
// temporary file. When this is done, the temporary file replaces
// the original file.
func swapFiles(tempFile *os.File, activeFile *os.File) (*os.File, error) {
activeFileName := activeFile.Name()
tempFileName := tempFile.Name()
// Lots of things we do here is because Windows would not accept working
// on files that are currently opened.
// On exit, ensure temporary file is removed.
defer func() {
os.Remove(tempFileName)
}()
// Start by closing the temporary file.
if err := tempFile.Close(); err != nil {
return activeFile, err
}
// Close original file before trying to rename it.
if err := activeFile.Close(); err != nil {
return activeFile, err
}
// Rename the tmp file to original file name
err := os.Rename(tempFileName, activeFileName)
// Need to re-open the active file anyway
file, lerr := openFile(activeFileName)
if lerr != nil && err == nil {
err = lerr
}
return file, err
}
// Close closes all stores.
func (fs *FileStore) Close() error {
fs.Lock()
defer fs.Unlock()
if fs.closed {
return nil
}
fs.closed = true
var err error
closeFile := func(f *os.File) {
if f == nil {
return
}
if lerr := f.Close(); lerr != nil && err == nil {
err = lerr
}
}
err = fs.genericStore.close()
closeFile(fs.serverFile)
closeFile(fs.clientsFile)
return err
}
////////////////////////////////////////////////////////////////////////////
// FileMsgStore methods
////////////////////////////////////////////////////////////////////////////
// newFileMsgStore returns a new instace of a file MsgStore.
func (fs *FileStore) newFileMsgStore(channelDirName, channel string, doRecover bool) (*FileMsgStore, error) {
var err error
var file *os.File
// Create an instance and initialize
ms := &FileMsgStore{
opts: &fs.opts,
crcTable: fs.crcTable,
}
ms.init(channel, fs.limits)
// Open/create all the files
for i := 0; i < numFiles; i++ {
// Fully qualified file name.
fileName := filepath.Join(channelDirName, fmt.Sprintf("msgs.%d.dat", (i+1)))
// Open the file.
file, err = openFile(fileName)
if err != nil {
break
}
// Save slice
ms.files[i] = &fileSlice{fileName: fileName}
// Should we try to recover (startup case)
if doRecover {
err = ms.recoverOneMsgFile(file, i)
} else if i == 0 {
// Otherwise, keep the first file opened...
ms.setFile(file)
} else {
// and close all others.
err = file.Close()
}
if err != nil {
break
}
}
// Cleanup on error
if err != nil {
ms.Close()
ms = nil
action := "create"
if doRecover {
action = "recover"
}
err = fmt.Errorf("unable to %s message store for [%s]: %v", action, channel, err)
return nil, err
}
return ms, nil
}
func (ms *FileMsgStore) setFile(f *os.File) {
ms.bw = nil
ms.file = f
if ms.file != nil {
ms.bw = bufio.NewWriterSize(ms.file, ms.opts.BufferSize)
}
}
// recovers one of the file
func (ms *FileMsgStore) recoverOneMsgFile(file *os.File, numFile int) error {
var err error
msgSize := 0
var msg *pb.MsgProto
fslice := ms.files[numFile]
// Create a buffered reader to speed-up recovery
br := bufio.NewReaderSize(file, defaultBufSize)
for {
ms.tmpMsgBuf, msgSize, _, err = readRecord(br, ms.tmpMsgBuf, false, ms.crcTable, ms.opts.DoCRC)
if err != nil {
if err == io.EOF {
// We are done, reset err
err = nil
}
break
}
// Recover this message
msg = &pb.MsgProto{}
err = msg.Unmarshal(ms.tmpMsgBuf[:msgSize])
if err != nil {
break
}
if fslice.firstMsg == nil {
fslice.firstMsg = msg
}
fslice.lastMsg = msg
fslice.msgsCount++
fslice.msgsSize += uint64(len(msg.Data))
if ms.first == 0 {
ms.first = msg.Sequence
}
ms.msgs[msg.Sequence] = msg
}
// Do more accounting and bump the current slice index if we recovered