/
filestore_test.go
2090 lines (1899 loc) · 59.5 KB
/
filestore_test.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-2019 The NATS Authors
// 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 stores
import (
"bufio"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"math/rand"
"os"
"path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/nats-streaming-server/spb"
"github.com/nats-io/nats-streaming-server/util"
"github.com/nats-io/stan.go/pb"
)
var (
testFSDefaultDatastore string
testFSDisableBufferWriters bool
testFSSetFDsLimit bool
testFSDisableReadBuffer bool
)
var testFDsLimit = int64(5)
func init() {
tmpDir, err := ioutil.TempDir(".", "data_stores_")
if err != nil {
panic("Could not create tmp dir")
}
if err := os.Remove(tmpDir); err != nil {
panic(fmt.Errorf("Error removing temp directory: %v", err))
}
testFSDefaultDatastore = tmpDir
FileStoreTestSetBackgroundTaskInterval(testFSDefaultBackgroundTaskInterval)
}
func cleanupFSDatastore(t tLogger) {
if err := os.RemoveAll(testFSDefaultDatastore); err != nil {
stackFatalf(t, "Error cleaning up datastore: %v", err)
}
}
func newFileStore(t tLogger, dataStore string, limits *StoreLimits, options ...FileStoreOption) (*FileStore, *RecoveredState) {
opts := DefaultFileStoreOptions
// Set those options based on command line parameters.
// Each test may override those.
if testFSDisableBufferWriters {
opts.BufferSize = 0
}
if testFSDisableReadBuffer {
opts.ReadBufferSize = 0
}
if testFSSetFDsLimit {
opts.FileDescriptorsLimit = testFDsLimit
}
// Apply the provided options
for _, opt := range options {
if err := opt(&opts); err != nil {
stackFatalf(t, "Error creating file store: %v", err)
}
}
fs, err := NewFileStore(testLogger, dataStore, limits, AllOptions(&opts))
if err != nil {
stackFatalf(t, "Error creating file store: %v", err)
}
state, err := fs.Recover()
if err != nil {
fs.Close()
stackFatalf(t, "Error recovering file store: %v", err)
}
return fs, state
}
func createDefaultFileStore(t tLogger, options ...FileStoreOption) *FileStore {
limits := testDefaultStoreLimits
fs, state := newFileStore(t, testFSDefaultDatastore, &limits, options...)
if state == nil {
info := testDefaultServerInfo
if err := fs.Init(&info); err != nil {
stackFatalf(t, "Unexpected error durint Init: %v", err)
}
}
return fs
}
func openDefaultFileStore(t *testing.T, options ...FileStoreOption) (*FileStore, *RecoveredState) {
return openDefaultFileStoreWithLimits(t, nil, options...)
}
func openDefaultFileStoreWithLimits(t tLogger, limits *StoreLimits, options ...FileStoreOption) (*FileStore, *RecoveredState) {
if limits == nil {
l := testDefaultStoreLimits
limits = &l
}
return newFileStore(t, testFSDefaultDatastore, limits, options...)
}
func expectedErrorOpeningDefaultFileStore(t *testing.T) error {
limits := testDefaultStoreLimits
fs, err := NewFileStore(testLogger, testFSDefaultDatastore, &limits)
if err == nil {
_, err = fs.Recover()
fs.Close()
}
if err == nil {
stackFatalf(t, "Expected an error opening the FileStore, got none")
}
return err
}
func TestFSFilesManager(t *testing.T) {
cleanupFSDatastore(t)
defer cleanupFSDatastore(t)
if err := os.MkdirAll(testFSDefaultDatastore, os.ModeDir+os.ModePerm); err != nil && !os.IsExist(err) {
t.Fatalf("Unable to create the root directory [%s]: %v", testFSDefaultDatastore, err)
}
fm := createFilesManager(testFSDefaultDatastore, 4)
defer fm.close()
// This should fail since file does not exist
failedFile, err := fm.createFile("foo", os.O_RDONLY, nil)
if err == nil {
t.Fatal("Creating file should have failed")
}
if failedFile != nil {
t.Fatalf("On error, file should be nil, got %#v", failedFile)
}
// Ensure not in fm's map
fm.Lock()
lenMap := len(fm.files)
fm.Unlock()
if lenMap > 0 {
t.Fatalf("Map should be empty, got %v", lenMap)
}
closeCbCalled := 0
bccb := func() error {
closeCbCalled++
return nil
}
firstFile, err := fm.createFile("foo", defaultFileFlags, bccb)
if err != nil {
t.Fatalf("Unexpected error on create: %v", err)
}
if firstFile.id == invalidFileID {
t.Fatal("Got invalid file ID on success")
}
if firstFile == nil {
t.Fatal("Got nil file on success")
}
// Check content
// The callback cannot be checked, we set it to nil for the DeepEqual call.
firstFile.beforeClose = nil
expectedFile := file{
id: fileID(1),
handle: firstFile.handle, // we cannot know what to expect here, so use value returned
name: filepath.Join(testFSDefaultDatastore, "foo"),
flags: defaultFileFlags,
state: fileInUse,
}
fobj := *firstFile
if !reflect.DeepEqual(expectedFile, fobj) {
t.Fatalf("Expected file to be %#v, got %#v", expectedFile, fobj)
}
firstFile.beforeClose = bccb
// unlock the file
fm.unlockFile(firstFile)
// Create more files
moreFiles := make([]*file, 10)
for i := 0; i < len(moreFiles); i++ {
fname := fmt.Sprintf("foo.%d", (i + 1))
f, err := fm.createFile(fname, defaultFileFlags, nil)
if err != nil {
t.Fatalf("Error on file create: %q - %v", fname, err)
}
moreFiles[i] = f
fm.unlockFile(f)
}
// Check the number of opened files.
fm.Lock()
opened := fm.openedFDs
fm.Unlock()
if opened > fm.limit {
t.Fatalf("Expected up to %v opened files, got %v", fm.limit, opened)
}
// Verify that number is accurate
actualOpened := int64(0)
fm.Lock()
for _, file := range fm.files {
if file.state == fileOpened && file.handle != nil {
actualOpened++
}
}
fm.Unlock()
if actualOpened != opened {
t.Fatalf("FM's opened is %v, but actual number of files opened is %v", opened, actualOpened)
}
// Lock all files, which should cause the opened count to go over limit
for _, file := range moreFiles {
fm.lockFile(file)
}
fm.Lock()
opened = fm.openedFDs
fm.Unlock()
if opened != int64(len(moreFiles)) {
t.Fatalf("Expected opened to be %v, got %v", len(moreFiles), opened)
}
// Unlock the files now
for _, file := range moreFiles {
fm.unlockFile(file)
}
// We should be able to lock them back and they should still be opened
for _, file := range moreFiles {
if !fm.lockFileIfOpened(file) {
t.Fatalf("LockIfOpened for file %q should not have failed", file.name)
}
// This would panic if the file is not locked
if err := fm.closeLockedFile(file); err != nil {
t.Fatalf("Unexpected error on close: %v", err)
}
// This should do nothing and not return an error
if err := fm.closeFileIfOpened(file); err != nil {
t.Fatalf("Unexpected error on closeIfOpened: %v", err)
}
}
// Open them all again and closed if opened
for _, file := range moreFiles {
if _, err := fm.lockFile(file); err != nil {
t.Fatalf("Unexpected error opening file %q: %v", file.name, err)
}
fm.unlockFile(file)
if err := fm.closeFileIfOpened(file); err != nil {
t.Fatalf("Unexpected error closing file %q that was opened: %v", file.name, err)
}
}
// Remove all the files in moreFiles
for _, file := range moreFiles {
if !fm.remove(file) {
t.Fatalf("Should have been able to remove file %q", file.name)
}
}
// Try to remove a file already removed
if fm.remove(moreFiles[0]) {
t.Fatalf("Should have failed to remove file %q", moreFiles[0].name)
}
// At this point, there should be no file opened
fm.Lock()
opened = fm.openedFDs
fm.Unlock()
if opened != 0 {
t.Fatalf("There should be no file opened, got %v", opened)
}
// Open our first file
fm.lockFile(firstFile)
// Unlock now, it should stay opened
fm.unlockFile(firstFile)
// Create a file that will be left locked when calling close
lockedFile, err := fm.createFile("bar", defaultFileFlags, nil)
if err != nil {
t.Fatalf("Unexpected error on file create: %v", err)
}
// Close the manager, which should close this file
if err := fm.close(); err == nil || !strings.Contains(err.Error(), "still probably locked") {
t.Fatalf("Unexpected error on FM close: %v", err)
}
if closeCbCalled != 2 {
t.Fatal("Expected closeCbCalled to not be 0")
}
// Ensure that closing a second time is fine
if err := fm.close(); err != nil {
t.Fatalf("Unexpected error on double close: %v", err)
}
// Check file `f` is closed
if firstFile.handle != nil || firstFile.state != fileClosed {
t.Fatalf("File %q should be closed: handle=%v state=%v", firstFile.name, firstFile.handle, firstFile.state)
}
// Close the lockedFile
if err := fm.closeLockedFile(lockedFile); err != nil {
t.Fatalf("Error closing locked file: %v", err)
}
// Verify that we can no longer create or open files
if fmClosedFile, err := fm.createFile("baz", defaultFileFlags, nil); err == nil || !strings.Contains(err.Error(), "is being closed") {
fm.closeLockedFile(fmClosedFile)
t.Fatalf("Creating file should have failed after FM was closed, got %v", err)
}
if _, err := fm.lockFile(lockedFile); err == nil || !strings.Contains(err.Error(), "is being closed") {
fm.closeLockedFile(lockedFile)
t.Fatalf("Should not be able to lock a file after FM was closed, got %v", err)
}
// Recreate a file manager
fm = createFilesManager(testFSDefaultDatastore, 0)
defer fm.close()
closeCbCalled = 0
testcb, err := fm.createFile("testcb", defaultFileFlags, bccb)
if err != nil {
t.Fatalf("Failed to create file: %v", err)
}
if err := fm.closeLockedFile(testcb); err != nil {
t.Fatalf("Failed to close file: %v", err)
}
if closeCbCalled != 1 {
t.Fatalf("Expected callback to be invoked once, got %v", closeCbCalled)
}
fm.setBeforeCloseCb(testcb, nil)
if _, err := fm.lockFile(testcb); err != nil {
t.Fatalf("Failed to open file: %v", err)
}
if err := fm.closeLockedFile(testcb); err != nil {
t.Fatalf("Failed to close file: %v", err)
}
if closeCbCalled != 1 {
t.Fatalf("Expected callback to be invoked once, got %v", closeCbCalled)
}
if !fm.remove(testcb) {
t.Fatal("Should have been able to remove file")
}
testcloseOrOpenedFile, err := fm.createFile("testcloselockedoropened", defaultFileFlags, nil)
if err != nil {
t.Fatalf("Failed to create file: %v", err)
}
if err := fm.closeLockedOrOpenedFile(testcloseOrOpenedFile); err != nil {
t.Fatalf("Error closing file: %v", err)
}
if _, err := fm.lockFile(testcloseOrOpenedFile); err != nil {
t.Fatalf("Error opening file: %v", err)
}
// simply unlock (which will leave it opened)
fm.unlockFile(testcloseOrOpenedFile)
if err := fm.closeLockedOrOpenedFile(testcloseOrOpenedFile); err != nil {
t.Fatalf("Error closing file: %v", err)
}
if !fm.remove(testcloseOrOpenedFile) {
t.Fatal("Should have been able to remove file")
}
// Trying to open a removed file should fail.
if err := fm.openFile(testcloseOrOpenedFile); err == nil {
t.Fatal("Should have been unable to open a removed file")
}
// Try to do concurrent lock/unlock while file is being removed
for i := 0; i < 20; i++ {
fileToRemove, err := fm.createFile("concurrentremove", defaultFileFlags, nil)
if err != nil {
t.Fatalf("Error creating file: %v", err)
}
fm.unlockFile(fileToRemove)
wg := sync.WaitGroup{}
wg.Add(1)
ch := make(chan bool)
go func() {
defer wg.Done()
for {
select {
case <-ch:
return
default:
if _, err := fm.lockFile(fileToRemove); err == nil {
fm.unlockFile(fileToRemove)
}
}
}
}()
time.Sleep(time.Duration(rand.Intn(45)+5) * time.Millisecond)
removed := fm.remove(fileToRemove)
ch <- true
wg.Wait()
if !removed {
fm.remove(fileToRemove)
}
fileToRemove.handle.Close()
os.Remove(fileToRemove.name)
}
// Following tests are supposed to produce panic
file, err := fm.createFile("failure", defaultFileFlags, nil)
if err != nil {
t.Fatalf("Failed to create file: %v", err)
}
lockLockedFile := func() {
defer func() {
if r := recover(); r == nil {
t.Fatal("Locking a locked file should panic")
}
}()
fm.lockFile(file)
}
lockLockedFile()
if err := fm.closeLockedFile(file); err != nil {
t.Fatalf("Error closing locked file: %v", err)
}
fm.lockFile(file)
fm.unlockFile(file)
closeLockedFile := func() {
defer func() {
if r := recover(); r == nil {
t.Fatal("closeLockedFile should panic if file is not locked")
}
}()
fm.closeLockedFile(file)
}
closeLockedFile()
unlockUnlockedFile := func() {
defer func() {
if r := recover(); r == nil {
t.Fatal("Unlocking an unlocked file should panic")
}
}()
fm.unlockFile(file)
}
unlockUnlockedFile()
if !fm.remove(file) {
t.Fatal("File should have been removed")
}
fm.close()
fm.Lock()
lenMap = len(fm.files)
fm.Unlock()
if lenMap != 0 {
t.Fatalf("Map should be empty, got %v", lenMap)
}
// Close file to avoid issue when cleaning up datastore on Windows.
file.handle.Close()
}
func TestFSNoDirectoryError(t *testing.T) {
cleanupFSDatastore(t)
defer cleanupFSDatastore(t)
fs, err := NewFileStore(nil, "", nil)
if err == nil || !strings.Contains(err.Error(), "specified") {
if fs != nil {
fs.Close()
}
t.Fatalf("Expected error about missing root directory, got: %v", err)
}
}
func TestFSUseDefaultLimits(t *testing.T) {
cleanupFSDatastore(t)
defer cleanupFSDatastore(t)
fs, _ := newFileStore(t, testFSDefaultDatastore, nil)
defer fs.Close()
if !reflect.DeepEqual(*fs.limits, DefaultStoreLimits) {
t.Fatalf("Default limits are not used: %v\n", *fs.limits)
}
}
func TestFSUnsupportedFileVersion(t *testing.T) {
cleanupFSDatastore(t)
defer cleanupFSDatastore(t)
fs := createDefaultFileStore(t)
defer fs.Close()
cs := storeCreateChannel(t, fs, "foo")
storeMsg(t, cs, "foo", 1, []byte("test"))
storeSub(t, cs, "foo")
// Close store
fs.Close()
// Overwrite the file version of a message store to an unsupported version
writeVersion(t, filepath.Join(testFSDefaultDatastore, "foo", msgFilesPrefix+"1"+datSuffix), fileVersion+1)
// Recover store (should fail)
err := expectedErrorOpeningDefaultFileStore(t)
fileVerStr := fmt.Sprintf("%d", (fileVersion + 1))
if !strings.Contains(err.Error(), fileVerStr) {
t.Fatalf("Expected error to report unsupported file version %q, got %v", fileVerStr, err)
}
// Restore the correct version.
writeVersion(t, filepath.Join(testFSDefaultDatastore, "foo", msgFilesPrefix+"1"+datSuffix), fileVersion)
// Overwrite the file version of the subscriptions store to an unsupported version
writeVersion(t, filepath.Join(testFSDefaultDatastore, "foo", subsFileName), fileVersion+1)
// Recover store (should fail)
err = expectedErrorOpeningDefaultFileStore(t)
if !strings.Contains(err.Error(), fileVerStr) {
t.Fatalf("Expected error to report unsupported file version %q, got %v", fileVerStr, err)
}
}
func writeVersion(t *testing.T, fileName string, version int) {
file, err := os.OpenFile(fileName, os.O_RDWR, 0666)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if err := util.WriteInt(file, version); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if err := file.Close(); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
}
func TestFSOptions(t *testing.T) {
cleanupFSDatastore(t)
defer cleanupFSDatastore(t)
fs := createDefaultFileStore(t)
defer fs.Close()
// Check that default options are used
fs.RLock()
opts := fs.opts
fs.RUnlock()
checkOpts := func(expected, actual FileStoreOptions) {
if !reflect.DeepEqual(actual, expected) {
stackFatalf(t, "Expected options to be %v, got %v", expected, actual)
}
}
expected := DefaultFileStoreOptions
if testFSDisableBufferWriters {
expected.BufferSize = 0
}
if testFSSetFDsLimit {
expected.FileDescriptorsLimit = testFDsLimit
}
checkOpts(expected, opts)
cs := storeCreateChannel(t, fs, "foo")
ss := cs.Subs.(*FileSubStore)
ss.RLock()
opts = *ss.opts
ss.RUnlock()
checkOpts(expected, opts)
// Now try to set the options in the constructor
fs.Close()
cleanupFSDatastore(t)
// Prepare the golden options with custom values
expected = FileStoreOptions{
BufferSize: 1025 * 1024,
CompactEnabled: false,
CompactFragmentation: 60,
CompactInterval: 60,
CompactMinFileSize: 1024 * 1024,
DoCRC: false,
CRCPolynomial: int64(crc32.Castagnoli),
DoSync: false,
SliceMaxMsgs: 100,
SliceMaxBytes: 1024 * 1024,
SliceMaxAge: time.Second,
SliceArchiveScript: "myscript.sh",
FileDescriptorsLimit: 20,
ParallelRecovery: 5,
ReadBufferSize: 5 * 1024,
AutoSync: 2 * time.Minute,
}
// Create the file with custom options
fs, err := NewFileStore(testLogger, testFSDefaultDatastore, &testDefaultStoreLimits,
BufferSize(expected.BufferSize),
CompactEnabled(expected.CompactEnabled),
CompactFragmentation(expected.CompactFragmentation),
CompactInterval(expected.CompactInterval),
CompactMinFileSize(expected.CompactMinFileSize),
DoCRC(expected.DoCRC),
CRCPolynomial(expected.CRCPolynomial),
DoSync(expected.DoSync),
SliceConfig(100, 1024*1024, time.Second, "myscript.sh"),
FileDescriptorsLimit(20),
ParallelRecovery(5),
ReadBufferSize(5*1024),
AutoSync(2*time.Minute))
if err != nil {
t.Fatalf("Unexpected error on file store create: %v", err)
}
defer fs.Close()
fs.RLock()
opts = fs.opts
fs.RUnlock()
checkOpts(expected, opts)
fs.Close()
fs, err = NewFileStore(testLogger, testFSDefaultDatastore, &testDefaultStoreLimits,
AllOptions(&expected))
if err != nil {
t.Fatalf("Unexpected error on file store create: %v", err)
}
defer fs.Close()
fs.RLock()
opts = fs.opts
fs.RUnlock()
checkOpts(expected, opts)
cs = storeCreateChannel(t, fs, "foo")
ss = cs.Subs.(*FileSubStore)
ss.RLock()
opts = *ss.opts
ss.RUnlock()
checkOpts(expected, opts)
fs.Close()
cleanupFSDatastore(t)
// Create the file with custom options, pass all of them at once
fs, err = NewFileStore(testLogger, testFSDefaultDatastore, &testDefaultStoreLimits, AllOptions(&expected))
if err != nil {
t.Fatalf("Unexpected error on file store create: %v", err)
}
defer fs.Close()
if _, err := fs.Recover(); err != nil {
t.Fatalf("Error recovering state: %v", err)
}
fs.RLock()
opts = fs.opts
fs.RUnlock()
checkOpts(expected, opts)
cs = storeCreateChannel(t, fs, "foo")
ss = cs.Subs.(*FileSubStore)
ss.RLock()
opts = *ss.opts
ss.RUnlock()
checkOpts(expected, opts)
fs.Close()
expectError := func(opts *FileStoreOptions, errTxt string) {
f, err := NewFileStore(testLogger, testFSDefaultDatastore, &testDefaultStoreLimits, AllOptions(opts))
if f != nil {
f.Close()
}
if err == nil || !strings.Contains(err.Error(), errTxt) {
stackFatalf(t, "Expected error to contain %q, got %v", errTxt, err)
}
}
badOpts := DefaultFileStoreOptions
badOpts.BufferSize = -1
expectError(&badOpts, "buffer size")
badOpts = DefaultFileStoreOptions
badOpts.CompactFragmentation = -1
expectError(&badOpts, "compact fragmentation")
badOpts.CompactFragmentation = 0
expectError(&badOpts, "compact fragmentation")
badOpts = DefaultFileStoreOptions
badOpts.CompactInterval = -1
expectError(&badOpts, "compact interval")
badOpts.CompactInterval = 0
expectError(&badOpts, "compact interval")
badOpts = DefaultFileStoreOptions
badOpts.CompactMinFileSize = -1
expectError(&badOpts, "compact minimum file size")
badOpts = DefaultFileStoreOptions
badOpts.CRCPolynomial = 0
expectError(&badOpts, "crc polynomial")
badOpts.CRCPolynomial = 0xFFFFFFFF + 10
expectError(&badOpts, "crc polynomial")
badOpts = DefaultFileStoreOptions
badOpts.FileDescriptorsLimit = -1
expectError(&badOpts, "file descriptor")
badOpts = DefaultFileStoreOptions
badOpts.ParallelRecovery = -1
expectError(&badOpts, "parallel recovery")
badOpts.ParallelRecovery = 0
expectError(&badOpts, "parallel recovery")
badOpts = DefaultFileStoreOptions
badOpts.SliceMaxMsgs = -1
expectError(&badOpts, "slice max values")
badOpts = DefaultFileStoreOptions
badOpts.SliceMaxBytes = -1
expectError(&badOpts, "slice max values")
badOpts = DefaultFileStoreOptions
badOpts.SliceMaxAge = -1
expectError(&badOpts, "slice max values")
badOpts = DefaultFileStoreOptions
badOpts.ReadBufferSize = -1
expectError(&badOpts, "read buffer size")
}
func TestFSLimitsOnRecovery(t *testing.T) {
cleanupFSDatastore(t)
defer cleanupFSDatastore(t)
fs := createDefaultFileStore(t)
defer fs.Close()
// Store some messages in various channels
chanCount := 5
msgCount := 50
subsCount := 3
payload := []byte("hello")
expectedMsgBytes := uint64(0)
maxMsgsAfterRecovery := 4
expectedMsgBytesAfterRecovery := uint64(0)
for c := 0; c < chanCount; c++ {
channelName := fmt.Sprintf("channel.%d", (c + 1))
cs := storeCreateChannel(t, fs, channelName)
seq := uint64(1)
// Create several subscriptions per channel.
for s := 0; s < subsCount; s++ {
storeSub(t, cs, channelName)
}
for m := 0; m < msgCount; m++ {
msg := storeMsg(t, cs, channelName, seq, payload)
seq++
expectedMsgBytes += uint64(msg.Size())
if c == 0 {
if m < maxMsgsAfterRecovery {
expectedMsgBytesAfterRecovery += uint64(msg.Size() + msgRecordOverhead)
}
}
}
}
// Close the store
fs.Close()
// Now re-open with limits below all the above counts
limit := testDefaultStoreLimits
limit.MaxChannels = 1
limit.MaxMsgs = maxMsgsAfterRecovery
limit.MaxSubscriptions = 1
fs, state := newFileStore(t, testFSDefaultDatastore, &limit, SliceConfig(1, int64(maxMsgsAfterRecovery), 0, ""))
defer fs.Close()
if state == nil {
t.Fatal("Expected state to be recovered")
}
rcs := state.Channels
// Make sure that all our channels are recovered.
if len(rcs) != chanCount {
t.Fatalf("Unexpected count of recovered channels. Expected %v, got %v", chanCount, len(rcs))
}
var (
recMsg int
recBytes uint64
)
// Make sure that all our subscriptions are recovered.
for _, rc := range rcs {
if len(rc.Subscriptions) != subsCount {
t.Fatalf("Unexpected count of recovered subs. Expected %v, got %v", subsCount, len(rc.Subscriptions))
}
m, b := msgStoreState(t, rc.Channel.Msgs)
recMsg += m
recBytes += b
}
// Messages limits, however, are enforced on restart.
if recMsg != chanCount*maxMsgsAfterRecovery {
t.Fatalf("Unexpected count of recovered msgs. Expected %v, got %v", chanCount*maxMsgsAfterRecovery, recMsg)
}
if recBytes != uint64(chanCount)*expectedMsgBytesAfterRecovery {
t.Fatalf("Unexpected count of recovered bytes: Expected %v, got %v", uint64(chanCount)*expectedMsgBytesAfterRecovery, recBytes)
}
// Now check that any new addition would be rejected
if _, err := fs.CreateChannel("new.channel"); err == nil {
t.Fatal("Expected trying to create a new channel to fail")
}
rc := rcs["channel.1"]
if rc == nil {
t.Fatal("Expected channel.1 to exist")
}
channelOne := rc.Channel
sub := &spb.SubState{
ClientID: "me",
Inbox: "inbox",
AckInbox: "ackinbox",
AckWaitInSecs: 10,
}
if err := channelOne.Subs.CreateSub(sub); err == nil {
t.Fatal("Expected trying to create a new subscription to fail")
}
// Store one message
lastMsg := storeMsg(t, channelOne, "channel.1", uint64(msgCount+1), payload)
// Check limits (should be 4 msgs)
recMsg, recBytes = msgStoreState(t, channelOne.Msgs)
if recMsg != limit.MaxMsgs {
t.Fatalf("Unexpected count of recovered msgs. Expected %v, got %v", limit.MaxMsgs, recMsg)
}
if recBytes != expectedMsgBytesAfterRecovery {
t.Fatalf("Unexpected count of recovered bytes: Expected %v, got %v", expectedMsgBytes, recBytes)
}
cs := fs.channels["channel.1"]
msgStore := cs.Msgs.(*FileMsgStore)
// Check first avail message sequence
expectedNewFirstSeq := uint64((msgCount + 1 - limit.MaxMsgs) + 1)
if msgStore.first != expectedNewFirstSeq {
t.Fatalf("Expected first sequence to be %v, got %v", expectedNewFirstSeq, msgStore.first)
}
// We should have moved to the second slice
if msgStore.lastFSlSeq != 2 {
t.Fatalf("Expected file slice to be the second one, got %v", msgStore.lastFSlSeq)
}
// Check second slice content
secondSlice := msgStore.files[2]
if secondSlice.msgsCount != 1 {
t.Fatalf("Expected second slice to have 1 message, got %v", secondSlice.msgsCount)
}
if secondSlice.firstSeq != lastMsg.Sequence {
t.Fatalf("Expected last message seq to be %v, got %v", lastMsg.Sequence, secondSlice.firstSeq)
}
// The first slice should have the new limit msgs count - 1.
firstSlice := msgStore.files[1]
left := firstSlice.msgsCount - firstSlice.rmCount
if left != limit.MaxMsgs-1 {
t.Fatalf("Expected first slice to have %v msgs, got %v", limit.MaxMsgs-1, left)
}
// Close the store
fs.Close()
// We are going to add an age limit (of 1ms for test purposes) and since
// messages were stored before, if we wait say 5ms, no message should be
// recovered.
time.Sleep(5 * time.Millisecond)
// Now re-open with limits below all the above counts
limit = testDefaultStoreLimits
limit.MaxMsgs = maxMsgsAfterRecovery
limit.MaxAge = time.Millisecond
fs, state = newFileStore(t, testFSDefaultDatastore, &limit)
defer fs.Close()
for _, rc := range state.Channels {
recMsg, recBytes = msgStoreState(t, rc.Channel.Msgs)
if recMsg != 0 || recBytes != 0 {
t.Fatalf("There should be no message recovered, got %v, %v bytes", recMsg, recBytes)
}
}
}
func TestFSBadClientFile(t *testing.T) {
cleanupFSDatastore(t)
defer cleanupFSDatastore(t)
// Create a valid store file first
fs := createDefaultFileStore(t)
// Close it
fs.Close()
// Delete the client's file
fileName := filepath.Join(testFSDefaultDatastore, clientsFileName)
if err := os.Remove(fileName); err != nil {
t.Fatalf("Unable to delete the client's file %q: %v", fileName, err)
}
// This will create the file without the file version
if file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err != nil {
t.Fatalf("Error creating client file: %v", err)
} else {
file.Close()
}
// So we should fail to create the filestore
expectedErrorOpeningDefaultFileStore(t)
resetToValidFile := func() *os.File {
// First remove the file
if err := os.Remove(fileName); err != nil {
t.Fatalf("Unexpected error removing file: %v", err)
}
// Create the file with proper file version
file, err := openFile(fileName)
if err != nil {
t.Fatalf("Error creating client file: %v", err)
}
return file
}
clientID := "this-is-a-valid-client-id"
cli := spb.ClientInfo{ID: clientID, HbInbox: "hbInbox"}
b, _ := cli.Marshal()
//
// WRONG CRC
//
file := resetToValidFile()
// Write the header
if err := util.WriteInt(file, int(addClient)<<24|len(b)); err != nil {
t.Fatalf("Error writing header: %v", err)
}
// Write WRONG crc
if err := util.WriteInt(file, int(crc32.ChecksumIEEE(b))+3); err != nil {
t.Fatalf("Error writing crc: %v", err)
}
// Write content
if _, err := file.Write(b); err != nil {
t.Fatalf("Error writing info: %v", err)
}
// Close the file
if err := file.Close(); err != nil {
t.Fatalf("Unexpected error closing file: %v", err)
}
expectedErrorOpeningDefaultFileStore(t)
//
// UNMARSHAL addClient ERROR
//
file = resetToValidFile()
copy(b, []byte("hello"))
// Write the header
if err := util.WriteInt(file, int(addClient)<<24|len(b)); err != nil {
t.Fatalf("Error writing header: %v", err)
}
// Write crc
if err := util.WriteInt(file, int(crc32.ChecksumIEEE(b))); err != nil {
t.Fatalf("Error writing crc: %v", err)
}
// Write content
if _, err := file.Write(b); err != nil {
t.Fatalf("Error writing info: %v", err)
}
// Close the file
if err := file.Close(); err != nil {
t.Fatalf("Unexpected error closing file: %v", err)
}
expectedErrorOpeningDefaultFileStore(t)
//
// UNMARSHAL delClient ERROR
//
file = resetToValidFile()
// First write a valid addClient
writeRecord(file, nil, addClient, &cli, cli.Size(), crc32.IEEETable)
// Then write an invalid delClient
delCli := spb.ClientDelete{ID: clientID}
b, _ = delCli.Marshal()
copy(b, []byte("hello"))
// Write the header
if err := util.WriteInt(file, int(delClient)<<24|len(b)); err != nil {
t.Fatalf("Error writing header: %v", err)
}
// Write crc
if err := util.WriteInt(file, int(crc32.ChecksumIEEE(b))); err != nil {
t.Fatalf("Error writing crc: %v", err)
}
// Write content
if _, err := file.Write(b); err != nil {
t.Fatalf("Error writing info: %v", err)
}
// Close the file
if err := file.Close(); err != nil {
t.Fatalf("Unexpected error closing file: %v", err)
}
expectedErrorOpeningDefaultFileStore(t)
//
// INVALID TYPE
//
file = resetToValidFile()
b, _ = cli.Marshal()
// Write the header
if err := util.WriteInt(file, 99<<24|len(b)); err != nil {
t.Fatalf("Error writing header: %v", err)
}
// Write crc
if err := util.WriteInt(file, int(crc32.ChecksumIEEE(b))); err != nil {
t.Fatalf("Error writing crc: %v", err)
}
// Write content
if _, err := file.Write(b); err != nil {
t.Fatalf("Error writing info: %v", err)
}
// Close the file
if err := file.Close(); err != nil {
t.Fatalf("Unexpected error closing file: %v", err)
}
expectedErrorOpeningDefaultFileStore(t)
}
func TestFSBadServerFile(t *testing.T) {
cleanupFSDatastore(t)
defer cleanupFSDatastore(t)