-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathpersistent_config_test.go
1507 lines (1256 loc) · 60.7 KB
/
persistent_config_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 2022-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package rest
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/couchbase/sync_gateway/base"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAutomaticConfigUpgrade(t *testing.T) {
if base.UnitTestUrlIsWalrus() {
t.Skip("CBS required")
}
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
config := fmt.Sprintf(`{
"server_tls_skip_verify": %t,
"interface": ":4444",
"adminInterface": ":4445",
"databases": {
"db": {
"server": "%s",
"username": "%s",
"password": "%s",
"bucket": "%s"
}
}
}`,
base.TestTLSSkipVerify(),
base.UnitTestUrl(),
base.TestClusterUsername(),
base.TestClusterPassword(),
tb.GetName(),
)
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, "config.json")
err := os.WriteFile(configPath, []byte(config), os.FileMode(0644))
require.NoError(t, err)
startupConfig, _, _, _, err := automaticConfigUpgrade(ctx, configPath)
require.NoError(t, err)
assert.Equal(t, "", startupConfig.Bootstrap.ConfigGroupID)
assert.Equal(t, base.UnitTestUrl(), startupConfig.Bootstrap.Server)
assert.Equal(t, base.TestClusterUsername(), startupConfig.Bootstrap.Username)
assert.Equal(t, base.TestClusterPassword(), startupConfig.Bootstrap.Password)
assert.Equal(t, ":4444", startupConfig.API.PublicInterface)
assert.Equal(t, ":4445", startupConfig.API.AdminInterface)
writtenNewFile, err := os.ReadFile(configPath)
require.NoError(t, err)
var writtenFileStartupConfig StartupConfig
err = json.Unmarshal(writtenNewFile, &writtenFileStartupConfig)
require.NoError(t, err)
assert.Equal(t, "", startupConfig.Bootstrap.ConfigGroupID)
assert.Equal(t, base.UnitTestUrl(), writtenFileStartupConfig.Bootstrap.Server)
assert.Equal(t, base.TestClusterUsername(), writtenFileStartupConfig.Bootstrap.Username)
assert.Equal(t, base.TestClusterPassword(), writtenFileStartupConfig.Bootstrap.Password)
assert.Equal(t, ":4444", writtenFileStartupConfig.API.PublicInterface)
assert.Equal(t, ":4445", writtenFileStartupConfig.API.AdminInterface)
backupFileName := ""
err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error {
if strings.Contains(filepath.Base(path), "backup") {
backupFileName = path
}
return nil
})
require.NoError(t, err)
writtenBackupFile, err := os.ReadFile(backupFileName)
require.NoError(t, err)
assert.Equal(t, config, string(writtenBackupFile))
cbs, err := CreateBootstrapConnectionFromStartupConfig(ctx, startupConfig, base.PerUseClusterConnections)
require.NoError(t, err)
bootstrapContext := &bootstrapContext{
Connection: cbs,
}
var dbConfig DatabaseConfig
_, err = bootstrapContext.GetConfig(ctx, tb.GetName(), PersistentConfigDefaultGroupID, "db", &dbConfig)
require.NoError(t, err)
assert.Equal(t, "db", dbConfig.Name)
assert.Equal(t, tb.GetName(), *dbConfig.Bucket)
assert.Nil(t, dbConfig.Server)
assert.Equal(t, "", dbConfig.Username)
assert.Equal(t, "", dbConfig.Password)
}
func TestAutomaticConfigUpgradeError(t *testing.T) {
if base.UnitTestUrlIsWalrus() {
t.Skip("CBS required")
}
testCases := []struct {
Name string
Config string
}{
{
"Multiple DBs different servers",
`
{
"server_tls_skip_verify": %t,
"databases": {
"db": {
"server": "%s",
"username": "%s",
"password": "%s",
"bucket": "%s"
},
"db2": {
"server": "rand",
"username": "",
"password": "",
"bucket": ""
}
}
}`,
},
}
for _, testCase := range testCases {
// Create tempdir here to avoid slash operator in t.Name()
tmpDir := t.TempDir()
t.Run(testCase.Name, func(t *testing.T) {
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
config := fmt.Sprintf(testCase.Config, base.TestTLSSkipVerify(), base.UnitTestUrl(), base.TestClusterUsername(), base.TestClusterPassword(), tb.GetName())
configPath := filepath.Join(tmpDir, "config.json")
err := os.WriteFile(configPath, []byte(config), os.FileMode(0644))
require.NoError(t, err)
_, _, _, _, err = automaticConfigUpgrade(base.TestCtx(t), configPath)
assert.Error(t, err)
})
}
}
func TestUnmarshalBrokenConfig(t *testing.T) {
t.Skip("Disabled, CBG-2420")
if base.UnitTestUrlIsWalrus() {
t.Skip("CBS required")
}
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
rt := NewRestTester(t, &RestTesterConfig{PersistentConfig: true})
defer rt.Close()
resp := rt.SendAdminRequest(http.MethodPut, "/newdb/",
fmt.Sprintf(
`{"bucket": "%s", "num_index_replicas": 0, "enable_shared_bucket_access": %t, "use_views": %t}`,
tb.GetName(), base.TestUseXattrs(), base.TestsDisableGSI(),
),
)
RequireStatus(t, resp, http.StatusCreated)
// Use underlying connection to unmarshal to untyped config
cnf := make(map[string]interface{}, 1)
key := PersistentConfigKey(ctx, rt.ServerContext().Config.Bootstrap.ConfigGroupID, "newdb")
cas, err := rt.ServerContext().BootstrapContext.Connection.GetMetadataDocument(ctx, tb.GetName(), key, &cnf)
require.NoError(t, err)
// Add invalid json fields to the config
cnf["num_index_replicas"] = "0"
// Both calls to UpdateMetadataDocument and fetchAndLoadConfigs needed to enter the broken state
_, err = rt.ServerContext().BootstrapContext.Connection.WriteMetadataDocument(ctx, tb.GetName(), key, cas, &cnf)
require.NoError(t, err)
_, err = rt.ServerContext().fetchAndLoadConfigs(rt.Context(), false)
assert.NoError(t, err)
resp = rt.SendAdminRequest(http.MethodGet, "/newdb/", "")
RequireStatus(t, resp, http.StatusNotFound)
resp = rt.SendAdminRequest(http.MethodDelete, "/newdb/", "")
RequireStatus(t, resp, http.StatusOK)
}
func TestAutomaticConfigUpgradeExistingConfigAndNewGroup(t *testing.T) {
if base.UnitTestUrlIsWalrus() {
t.Skip("CBS required")
}
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
tmpDir := t.TempDir()
config := fmt.Sprintf(`{
"server_tls_skip_verify": %t,
"databases": {
"db": {
"server": "%s",
"username": "%s",
"password": "%s",
"bucket": "%s"
}
}
}`,
base.TestTLSSkipVerify(),
base.UnitTestUrl(),
base.TestClusterUsername(),
base.TestClusterPassword(),
tb.GetName(),
)
configPath := filepath.Join(tmpDir, "config.json")
err := os.WriteFile(configPath, []byte(config), os.FileMode(0644))
require.NoError(t, err)
// Run migration once
_, _, _, _, err = automaticConfigUpgrade(ctx, configPath)
require.NoError(t, err)
updatedConfig := fmt.Sprintf(`{
"server_tls_skip_verify": %t,
"databases": {
"db": {
"revs_limit": 20000,
"server": "%s",
"username": "%s",
"password": "%s",
"bucket": "%s"
}
}
}`,
base.TestTLSSkipVerify(),
base.UnitTestUrl(),
base.TestClusterUsername(),
base.TestClusterPassword(),
tb.GetName(),
)
updatedConfigPath := filepath.Join(tmpDir, "config-updated.json")
err = os.WriteFile(updatedConfigPath, []byte(updatedConfig), os.FileMode(0644))
require.NoError(t, err)
// Run migration again to ensure no error and validate it doesn't actually update db
startupConfig, _, _, _, err := automaticConfigUpgrade(ctx, updatedConfigPath)
require.NoError(t, err)
cbs, err := CreateBootstrapConnectionFromStartupConfig(ctx, startupConfig, base.PerUseClusterConnections)
require.NoError(t, err)
bootstrapContext := &bootstrapContext{
Connection: cbs,
}
var dbConfig DatabaseConfig
originalDefaultDbConfigCAS, err := bootstrapContext.GetConfig(ctx, tb.GetName(), PersistentConfigDefaultGroupID, "db", &dbConfig)
assert.NoError(t, err)
// Ensure that revs limit hasn't actually been set
assert.Nil(t, dbConfig.RevsLimit)
// Now attempt an upgrade for a non-default group ID, and ensure it's written correctly, and separately from the default group.
const configUpgradeGroupID = "import"
importConfig := fmt.Sprintf(`{
"server_tls_skip_verify": %t,
"config_upgrade_group_id": "%s",
"databases": {
"db": {
"enable_shared_bucket_access": true,
"import_docs": true,
"server": "%s",
"username": "%s",
"password": "%s",
"bucket": "%s"
}
}
}`,
base.TestTLSSkipVerify(),
configUpgradeGroupID,
base.UnitTestUrl(),
base.TestClusterUsername(),
base.TestClusterPassword(),
tb.GetName(),
)
importConfigPath := filepath.Join(tmpDir, "config-import.json")
err = os.WriteFile(importConfigPath, []byte(importConfig), os.FileMode(0644))
require.NoError(t, err)
startupConfig, _, _, _, err = automaticConfigUpgrade(ctx, importConfigPath)
// only supported in EE
if base.IsEnterpriseEdition() {
require.NoError(t, err)
// Ensure that startupConfig group ID has been set
assert.Equal(t, configUpgradeGroupID, startupConfig.Bootstrap.ConfigGroupID)
// Ensure dbConfig is saved as the specified config group ID
var dbConfig DatabaseConfig
_, err = bootstrapContext.GetConfig(ctx, tb.GetName(), configUpgradeGroupID, "db", &dbConfig)
assert.NoError(t, err)
// Ensure default has not changed
dbConfig = DatabaseConfig{}
defaultDbConfigCAS, err := bootstrapContext.GetConfig(ctx, tb.GetName(), PersistentConfigDefaultGroupID, "db", &dbConfig)
assert.NoError(t, err)
assert.Equal(t, originalDefaultDbConfigCAS, defaultDbConfigCAS)
} else {
assert.Error(t, err)
assert.Contains(t, err.Error(), "only supported in enterprise edition")
assert.Nil(t, startupConfig)
}
}
func TestImportFilterEndpoint(t *testing.T) {
base.SkipImportTestsIfNotEnabled(t) // import tests don't work without xattrs
rt := NewRestTesterPersistentConfig(t)
defer rt.Close()
rt.CreateDatabase("db1", rt.NewDbConfig())
// Ensure we won't fail with an empty import filter
resp := rt.SendAdminRequest(http.MethodPut, "/{{.keyspace}}/_config/import_filter", "")
RequireStatus(t, resp, http.StatusOK)
// Add a document
require.NoError(t, rt.GetSingleDataStore().Set("importDoc1", 0, nil, []byte("{}")))
// Ensure document is imported based on default import filter
resp = rt.SendAdminRequest(http.MethodGet, "/{{.keyspace}}/importDoc1", "")
RequireStatus(t, resp, http.StatusOK)
// Modify the import filter to always reject import
resp = rt.SendAdminRequest(http.MethodPut, "/{{.keyspace}}/_config/import_filter", `function(){return false}`)
RequireStatus(t, resp, http.StatusOK)
// Add a document
require.NoError(t, rt.GetSingleDataStore().Set("importDoc2", 0, nil, []byte("{}")))
// Ensure document is not imported and is rejected based on updated filter
resp = rt.SendAdminRequest(http.MethodGet, "/{{.keyspace}}/importDoc2", "")
RequireStatus(t, resp, http.StatusNotFound)
assert.Contains(t, resp.Body.String(), "Not imported")
resp = rt.SendAdminRequest(http.MethodDelete, "/{{.keyspace}}/_config/import_filter", "")
RequireStatus(t, resp, http.StatusOK)
// Add a document
require.NoError(t, rt.GetSingleDataStore().Set("importDoc3", 0, nil, []byte("{}")))
// Ensure document is imported based on default import filter
resp = rt.SendAdminRequest(http.MethodGet, "/{{.keyspace}}/importDoc3", "")
RequireStatus(t, resp, http.StatusOK)
}
func TestPersistentConfigWithCollectionConflicts(t *testing.T) {
base.TestRequiresCollections(t)
rt := NewRestTester(t, &RestTesterConfig{PersistentConfig: true})
defer rt.Close()
_ = rt.Bucket()
threeCollectionScopesConfig := GetCollectionsConfig(t, rt.TestBucket, 3)
dataStoreNames := GetDataStoreNamesFromScopesConfig(threeCollectionScopesConfig)
scopeName := dataStoreNames[0].ScopeName()
collection1Name := dataStoreNames[0].CollectionName()
collection2Name := dataStoreNames[1].CollectionName()
collection3Name := dataStoreNames[2].CollectionName()
collection1ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}}}}
collection2ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection2Name: {}}}}
collection3ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection3Name: {}}}}
collection1and2ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}, collection2Name: {}}}}
collection2and3ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection2Name: {}, collection3Name: {}}}}
// 1. Test collection registry with db create and delete
// Create db1, with collection1
collection1DBConfig := rt.NewDbConfig()
collection1DBConfig.Scopes = collection1ScopesConfig
RequireStatus(t, rt.CreateDatabase("db1", collection1DBConfig), http.StatusCreated)
// Verify fetch config
RequireStatus(t, rt.SendAdminRequest(http.MethodGet, "/db1/_config", ""), http.StatusOK)
// Create db2, with collection 2
collection2DBConfig := rt.NewDbConfig()
collection2DBConfig.Scopes = collection2ScopesConfig
rt.CreateDatabase("db2", collection2DBConfig)
// Create db1a with collection 1, expect conflict with db1
RequireStatus(t, rt.CreateDatabase("db1a", collection1DBConfig), http.StatusConflict)
// Delete db1
RequireStatus(t, rt.SendAdminRequest(http.MethodDelete, "/db1/", ""), http.StatusOK)
// Create db1a with collection 1, should now succeed
RequireStatus(t, rt.CreateDatabase("db1a", collection1DBConfig), http.StatusCreated)
// Attempt to recreate db1, expect conflict with db1a
RequireStatus(t, rt.CreateDatabase("db1", collection1DBConfig), http.StatusConflict)
// 2. Test collection registry during existing db update
// Add a new (unused) collection3 to existing database db2, should succeed
collection2And3DbConfig := rt.NewDbConfig()
collection2And3DbConfig.Scopes = collection2and3ScopesConfig
RequireStatus(t, rt.UpsertDbConfig("db2", collection2And3DbConfig), http.StatusCreated)
// Attempt to add already in use collection (collection2) to existing database db1a, should be rejected as conflict
collection1And2DbConfig := rt.NewDbConfig()
collection1And2DbConfig.Scopes = collection1and2ScopesConfig
RequireStatus(t, rt.UpsertDbConfig("db1a", collection1And2DbConfig), http.StatusConflict)
// Remove collection 2 from db2 (leaving collection 3 only)
collection3DbConfig := rt.NewDbConfig()
collection3DbConfig.Scopes = collection3ScopesConfig
RequireStatus(t, rt.UpsertDbConfig("db2", collection3DbConfig), http.StatusCreated)
// Attempt to add collection2 to existing database db1a again, should now succeed
RequireStatus(t, rt.UpsertDbConfig("db1a", collection1And2DbConfig), http.StatusCreated)
// 3. default collection tests
// Add a new db targeting default scope and collection
defaultCollectionDbConfig := rt.NewDbConfig()
defaultCollectionDbConfig.Scopes = nil
RequireStatus(t, rt.CreateDatabase("default1", defaultCollectionDbConfig), http.StatusCreated)
// Add a second db targeting default scope and collection, expect conflict
RequireStatus(t, rt.CreateDatabase("default2", defaultCollectionDbConfig), http.StatusConflict)
// Delete default1
RequireStatus(t, rt.SendAdminRequest(http.MethodDelete, "/default1/", ""), http.StatusOK)
// Create default2 targeting default scope and collection, should now succeed
RequireStatus(t, rt.CreateDatabase("default2", defaultCollectionDbConfig), http.StatusCreated)
}
// TestPersistentConfigRegistryRollbackAfterDbConfigRollback simulates a vbucket rollback for the dbconfig,
// leaving the registry version ahead of the config.
func TestPersistentConfigRegistryRollbackAfterDbConfigRollback(t *testing.T) {
base.TestRequiresCollections(t)
base.SetUpTestLogging(t, base.LevelDebug, base.KeyHTTP, base.KeyConfig)
for _, test := range persistentConfigTestCases() {
t.Run(test.name, func(t *testing.T) {
sc, closeFn := startBootstrapServerWithoutConfigPolling(t, test.xattrConfig)
defer closeFn()
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
oneCollectionScopesConfig := GetCollectionsConfig(t, tb, 1)
dataStoreNames := GetDataStoreNamesFromScopesConfig(oneCollectionScopesConfig)
bucketName := tb.GetName()
scopeName := dataStoreNames[0].ScopeName()
groupID := sc.Config.Bootstrap.ConfigGroupID
bc := sc.BootstrapContext
// reduce retry timeout for testing
bc.configRetryTimeout = 1 * time.Millisecond
// set up ScopesConfigs used by tests
collection1Name := dataStoreNames[0].CollectionName()
collection1ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}}}}
const dbName = "c1_db1"
collection1db1Config := getTestDatabaseConfig(bucketName, dbName, collection1ScopesConfig, "2-a")
collection1db1Config.RevsLimit = base.Ptr(uint32(1000))
cas, err := bc.InsertConfig(ctx, bucketName, groupID, collection1db1Config)
require.NoError(t, err)
configs, err := bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 1)
db, err := sc.GetDatabase(ctx, dbName)
require.NoError(t, err)
assert.Equal(t, int64(1000), int64(db.RevsLimit))
// simulate a rollback (not exactly - CAS increments, but lowering the config version is enough)
docID := PersistentConfigKey(ctx, groupID, dbName)
updatedConfig := *collection1db1Config
updatedConfig.Version = "1-a"
updatedConfig.RevsLimit = base.Ptr(uint32(500))
_, err = bc.Connection.WriteMetadataDocument(ctx, bucketName, docID, cas, &updatedConfig)
require.NoError(t, err)
// we've not polled for config updates yet
db, err = sc.GetDatabase(ctx, dbName)
require.NoError(t, err)
assert.Equal(t, int64(1000), int64(db.RevsLimit))
_, err = sc.fetchAndLoadConfigs(ctx, false)
require.NoError(t, err)
db, err = sc.GetDatabase(ctx, dbName)
require.NoError(t, err)
assert.Equal(t, int64(500), int64(db.RevsLimit))
// at this point the config and registry are re-aligned, but let's just write another config update to make sure it's in an updatable state
_, err = bc.UpdateConfig(ctx, bucketName, groupID, dbName, func(bucketDbConfig *DatabaseConfig) (updatedConfig *DatabaseConfig, err error) {
bucketDbConfig.Version = "3-c"
bucketDbConfig.RevsLimit = base.Ptr(uint32(1234))
return bucketDbConfig, nil
})
require.NoError(t, err)
_, err = sc.fetchAndLoadConfigs(ctx, false)
require.NoError(t, err)
db, err = sc.GetDatabase(ctx, dbName)
require.NoError(t, err)
assert.Equal(t, int64(1234), int64(db.RevsLimit))
})
}
}
// TestPersistentConfigRegistryRollbackCollectionConflictAfterDbConfigRollback simulates a vbucket rollback for the dbconfig,
// leaving the registry version ahead of the config - but also with a collection conflict occurring in the subsequent rollback.
func TestPersistentConfigRegistryRollbackCollectionConflictAfterDbConfigRollback(t *testing.T) {
base.TestRequiresCollections(t)
base.RequireNumTestDataStores(t, 3)
base.SetUpTestLogging(t, base.LevelDebug, base.KeyHTTP, base.KeyConfig)
tests := []struct {
name string
multiDatabaseRollback bool
useXattrConfig bool
}{
{"single database rollback - document persistence",
false,
false,
},
{"single database rollback - xattr persistence",
false,
true,
},
{"multi database rollback - document persistence",
true,
false,
},
{"multi database rollback - xattr persistence",
true,
true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
sc, closeFn := startBootstrapServerWithoutConfigPolling(t, test.useXattrConfig)
defer closeFn()
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
threeCollectionScopesConfig := GetCollectionsConfig(t, tb, 3)
dataStoreNames := GetDataStoreNamesFromScopesConfig(threeCollectionScopesConfig)
bucketName := tb.GetName()
scopeName := dataStoreNames[0].ScopeName()
groupID := sc.Config.Bootstrap.ConfigGroupID
bc := sc.BootstrapContext
// reduce retry timeout for testing
bc.configRetryTimeout = 1 * time.Millisecond
// set up ScopesConfigs used by tests
collection1Name := dataStoreNames[0].CollectionName()
collection1ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}}}}
collection2Name := dataStoreNames[1].CollectionName()
collection2ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection2Name: {}}}}
collection3Name := dataStoreNames[2].CollectionName()
collection3ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection3Name: {}}}}
const dbName1 = "c1_db1"
collection1db1Config := getTestDatabaseConfig(bucketName, dbName1, collection1ScopesConfig, "2-a")
_, err := bc.InsertConfig(ctx, bucketName, groupID, collection1db1Config)
require.NoError(t, err)
const dbName2 = "c1_db2"
collection1db2Config := getTestDatabaseConfig(bucketName, dbName2, collection2ScopesConfig, "2-a")
db2CAS, err := bc.InsertConfig(ctx, bucketName, groupID, collection1db2Config)
require.NoError(t, err)
const dbName3 = "c1_db3"
collection1db3Config := getTestDatabaseConfig(bucketName, dbName3, collection3ScopesConfig, "2-a")
db3CAS, err := bc.InsertConfig(ctx, bucketName, groupID, collection1db3Config)
require.NoError(t, err)
configs, err := bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 3)
// simulate a rollback (not exactly - CAS increments, but lowering the config version is enough)
// this time we'll "roll back" to a version of dbconfig that contains a collection now in use by db1
docID := PersistentConfigKey(ctx, groupID, dbName2)
updatedDb2Config := *collection1db2Config
updatedDb2Config.Version = "1-a"
updatedDb2Config.Scopes = ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}, collection2Name: {}}}}
_, err = bc.Connection.WriteMetadataDocument(ctx, bucketName, docID, db2CAS, &updatedDb2Config)
require.NoError(t, err)
// also roll back db3 to the same collection as db1 if multiDatabaseRollback
if test.multiDatabaseRollback {
docID = PersistentConfigKey(ctx, groupID, dbName3)
updatedDb3Config := *collection1db3Config
updatedDb3Config.Version = "1-a"
updatedDb3Config.Scopes = ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}, collection3Name: {}}}}
_, err = bc.Connection.WriteMetadataDocument(ctx, bucketName, docID, db3CAS, &updatedDb3Config)
require.NoError(t, err)
}
// should expect db2 (and db3) to fail because collection2 is shared by two databases during rollback handling, db1 should (re)load
count, err := sc.fetchAndLoadConfigs(ctx, false)
assert.NoError(t, err)
_, err = sc.GetActiveDatabase(dbName1)
require.NoError(t, err)
_, err = sc.GetActiveDatabase(dbName2)
require.Error(t, err)
if test.multiDatabaseRollback {
assert.Equal(t, 1, count) // db1 is still valid
_, err = sc.GetActiveDatabase(dbName3)
require.Error(t, err)
sc.RequireInvalidDatabaseConfigNames(t, []string{dbName2, dbName3})
} else {
assert.Equal(t, 2, count) // db1 and db3 still valid
_, err = sc.GetActiveDatabase(dbName3)
require.NoError(t, err)
sc.RequireInvalidDatabaseConfigNames(t, []string{dbName2})
}
// invalid databases not accessible, but also don't expect this to do anything like an on-demand load
resp := BootstrapAdminRequest(t, sc, http.MethodGet, fmt.Sprintf("/%s/_config", dbName2), "")
resp.RequireStatus(http.StatusNotFound)
// should be able to put as a new database with a repaired config
updatedDb2Config.Scopes = ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection2Name: {}}}}
db2Config := base.MustJSONMarshal(t, updatedDb2Config.DbConfig)
resp = BootstrapAdminRequest(t, sc, http.MethodPut, fmt.Sprintf("/%s/", dbName2), string(db2Config))
resp.RequireStatus(http.StatusCreated)
// database config and registry should now be aligned
count, err = sc.fetchAndLoadConfigs(ctx, false)
assert.NoError(t, err)
assert.Equal(t, 0, count) // both databases valid but already loaded
_, err = sc.GetActiveDatabase(dbName1)
require.NoError(t, err)
_, err = sc.GetActiveDatabase(dbName2)
require.NoError(t, err)
if test.multiDatabaseRollback {
// db3 still invalid
sc.RequireInvalidDatabaseConfigNames(t, []string{dbName3})
} else {
// and no remaining invalid databases
sc.RequireInvalidDatabaseConfigNames(t, []string{})
}
})
}
}
// TestPersistentConfigRegistryRollbackAfterCreateFailure simulates node failure during an insertConfig operation, leaving
// the registry updated but not the config file. Verifies rollback and registry cleanup in the following cases:
// 1. GetDatabaseConfigs (triggers rollback)
// 2. InsertConfig for the same db name (triggers rollback, then insert succeeds)
// 3. UpdateConfig for the same db name (triggers rollback, then returns ErrNotFound for the update operation)
// 4. InsertConfig for a different db, with collection conflict with the failed create (should fail with conflict, but succeed after GetDatabaseConfigs runs)
// 5. UpdateConfig to a different db, with collection conflict with the failed create (should fail with conflict, but succeed after GetDatabaseConfigs runs)
// 6. DeleteConfig for the same db name (triggers rollback, then returns ErrNotFound for the delete operation)
func TestPersistentConfigRegistryRollbackAfterCreateFailure(t *testing.T) {
base.TestRequiresCollections(t)
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeyConfig)
for _, test := range persistentConfigTestCases() {
t.Run(test.name, func(t *testing.T) {
sc, closeFn := startBootstrapServerWithoutConfigPolling(t, test.xattrConfig)
defer closeFn()
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
threeCollectionScopesConfig := GetCollectionsConfig(t, tb, 3)
dataStoreNames := GetDataStoreNamesFromScopesConfig(threeCollectionScopesConfig)
bucketName := tb.GetName()
scopeName := dataStoreNames[0].ScopeName()
groupID := sc.Config.Bootstrap.ConfigGroupID
bc := sc.BootstrapContext
// reduce retry timeout for testing
bc.configRetryTimeout = 1 * time.Millisecond
// SimulateCreateFailure updates the registry with a new config, but doesn't create the associated config file
simulateCreateFailure := func(t *testing.T, config *DatabaseConfig) {
registry, err := bc.getGatewayRegistry(ctx, bucketName)
require.NoError(t, err)
_, err = registry.upsertDatabaseConfig(ctx, groupID, config)
require.NoError(t, err)
require.NoError(t, bc.setGatewayRegistry(ctx, bucketName, registry))
}
// set up ScopesConfigs used by tests
collection1Name := dataStoreNames[0].CollectionName()
collection2Name := dataStoreNames[1].CollectionName()
collection3Name := dataStoreNames[2].CollectionName()
collection1ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}}}}
collection2ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection2Name: {}}}}
collection3ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection3Name: {}}}}
collection1and2ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}, collection2Name: {}}}}
// Case 1. GetDatabaseConfigs should roll back registry after create failure
collection1db1Config := getTestDatabaseConfig(bucketName, "c1_db1", collection1ScopesConfig, "1-a")
simulateCreateFailure(t, collection1db1Config)
configs, err := bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 0)
// Case 2. InsertConfig with conflicting name should trigger registry rollback and then successful creation
simulateCreateFailure(t, collection1db1Config)
_, err = bc.InsertConfig(ctx, bucketName, groupID, collection1db1Config)
require.NoError(t, err)
// Case 3. UpdateConfig on the database after create failure should return not found
collection2db1Config := getTestDatabaseConfig(bucketName, "c2_db1", collection2ScopesConfig, "2-a")
simulateCreateFailure(t, collection2db1Config)
_, err = bc.UpdateConfig(ctx, bucketName, groupID, "c2_db1", func(bucketDbConfig *DatabaseConfig) (updatedConfig *DatabaseConfig, err error) {
bucketDbConfig.Version = "2-abc"
return bucketDbConfig, nil
})
require.Error(t, err)
require.True(t, err == base.ErrNotFound)
// Case 4. InsertConfig with a conflicting collection should return error, but should succeed after next GetDatabaseConfigs
collection3db1Config := getTestDatabaseConfig(bucketName, "c3_db1", collection3ScopesConfig, "1-a")
simulateCreateFailure(t, collection3db1Config)
collection3db2Config := getTestDatabaseConfig(bucketName, "c3_db2", collection3ScopesConfig, "1-b")
_, err = bc.InsertConfig(ctx, bucketName, groupID, collection3db2Config)
require.Error(t, err) // collection conflict
configs, err = bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 1)
// Reattempt insert, should now succeed
_, err = bc.InsertConfig(ctx, bucketName, groupID, collection3db2Config)
require.NoError(t, err)
// Case 5. Update different db with conflicting collection after create failure
// - create failure adding new db 'c2_db2' that has collection 2
// - attempt to update existing database c1db1 to add collection 2
collection2db2Config := getTestDatabaseConfig(bucketName, "c2_db2", collection2ScopesConfig, "1-a")
simulateCreateFailure(t, collection2db2Config)
_, err = bc.UpdateConfig(ctx, bucketName, groupID, "c1_db1", func(bucketDbConfig *DatabaseConfig) (updatedConfig *DatabaseConfig, err error) {
bucketDbConfig.Scopes = collection1and2ScopesConfig
bucketDbConfig.Version = "2-a"
return bucketDbConfig, nil
})
require.Error(t, err) // collection conflict
// GetDatabaseConfigs should rollback and remove the failed c2_db2
configs, err = bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 2)
// Update should now succeed
_, err = bc.UpdateConfig(ctx, bucketName, groupID, "c1_db1", func(bucketDbConfig *DatabaseConfig) (updatedConfig *DatabaseConfig, err error) {
bucketDbConfig.Scopes = collection1and2ScopesConfig
bucketDbConfig.Version = "2-a"
return bucketDbConfig, nil
})
require.NoError(t, err) // collection conflict
// Remove c3 (clean up for next case)
deleteErr := bc.DeleteConfig(ctx, bucketName, groupID, "c3_db2")
require.NoError(t, deleteErr)
// Case 6. Attempt to delete db after create failure for that db
// - create failure for c3_db1 with collection 3
// - attempt to delete c3_db1, rollback will remove from registry, then return 'not found' for the attempted delete
simulateCreateFailure(t, collection3db1Config)
deleteErr = bc.DeleteConfig(ctx, bucketName, groupID, "c3_db1")
require.Equal(t, base.ErrNotFound, deleteErr)
})
}
}
// TestPersistentConfigRegistryRollbackAfterUpdateFailure simulates node failure during an updateConfig operation, leaving
// the registry updated but not the config file. Database has collection 1, failed update switches to collection 2.
// Verifies rollback and registry cleanup in the following cases:
// 1. GetDatabaseConfigs (triggers rollback)
// 2. UpdateConfig for the same db name (triggers rollback, then update succeeds)
// 3. InsertConfig for a different db, with collection conflict with the new, failed update (should fail with conflict, but succeed after GetDatabaseConfigs runs)
// 4. InsertConfig for a different db, with collection conflict with the previous version (should fail with conflict, and continue to fail after GetDatabaseConfigs runs)
// 5. DeleteConfig for the same db name (triggers rollback, then successfully deletes)
func TestPersistentConfigRegistryRollbackAfterUpdateFailure(t *testing.T) {
base.TestRequiresCollections(t)
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeyConfig)
for _, test := range persistentConfigTestCases() {
t.Run(test.name, func(t *testing.T) {
sc, closeFn := startBootstrapServerWithoutConfigPolling(t, test.xattrConfig)
defer closeFn()
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
threeCollectionScopesConfig := GetCollectionsConfig(t, tb, 3)
dataStoreNames := GetDataStoreNamesFromScopesConfig(threeCollectionScopesConfig)
bucketName := tb.GetName()
scopeName := dataStoreNames[0].ScopeName()
groupID := sc.Config.Bootstrap.ConfigGroupID
collection1Name := dataStoreNames[0].CollectionName()
collection2Name := dataStoreNames[1].CollectionName()
collection3Name := dataStoreNames[2].CollectionName()
collection1ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}}}}
collection2ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection2Name: {}}}}
collection3ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection3Name: {}}}}
bc := sc.BootstrapContext
// reduce retry timeout for testing
bc.configRetryTimeout = 1 * time.Millisecond
// Create database with collection 1
collection1db1Config := getTestDatabaseConfig(bucketName, "db1", collection1ScopesConfig, "1-a")
_, err := bc.InsertConfig(ctx, bucketName, groupID, collection1db1Config)
require.NoError(t, err)
// simulateUpdateFailure updates the database registry but doesn't persist the updated config. Simulates
// node failure between registry update and config update.
simulateUpdateFailure := func(t *testing.T, config *DatabaseConfig) {
registry, err := bc.getGatewayRegistry(ctx, bucketName)
require.NoError(t, err)
_, err = registry.upsertDatabaseConfig(ctx, groupID, config)
require.NoError(t, err)
require.NoError(t, bc.setGatewayRegistry(ctx, bucketName, registry))
}
// Case 1. GetDatabaseConfigs should roll back registry after update failure
collection2db1Config := getTestDatabaseConfig(bucketName, "db1", collection2ScopesConfig, "2-a")
simulateUpdateFailure(t, collection2db1Config)
configs, err := bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 1)
require.Equal(t, "1-a", configs[0].Version)
// Retrieve registry to ensure the previous version has been removed
registry, err := bc.getGatewayRegistry(ctx, bucketName)
require.NoError(t, err)
registryDb, ok := registry.getRegistryDatabase(groupID, "db1")
require.True(t, ok)
require.Equal(t, "1-a", registryDb.Version)
require.Nil(t, registryDb.PreviousVersion)
// Case 2. UpdateConfig with a version that conflicts with the failed update. Should trigger registry rollback and then successful update
simulateUpdateFailure(t, collection1db1Config)
_, err = bc.UpdateConfig(ctx, bucketName, groupID, "db1", func(bucketDbConfig *DatabaseConfig) (updatedConfig *DatabaseConfig, err error) {
bucketDbConfig.Scopes = collection2ScopesConfig
bucketDbConfig.Version = "2-b"
return bucketDbConfig, nil
})
require.NoError(t, err)
// Retrieve registry to ensure the previous version has been removed and version updated to the new version
registry, err = bc.getGatewayRegistry(ctx, bucketName)
require.NoError(t, err)
registryDb, ok = registry.getRegistryDatabase(groupID, "db1")
require.True(t, ok)
require.Equal(t, "2-b", registryDb.Version)
require.Nil(t, registryDb.PreviousVersion)
// Case 3. InsertConfig for a different db with collection conflict with the failed update (should fail with conflict, but succeed after GetDatabaseConfigs runs)
collection1db1Config_v3 := getTestDatabaseConfig(bucketName, "db1", collection1ScopesConfig, "3-a")
simulateUpdateFailure(t, collection1db1Config_v3)
collection1db2Config := getTestDatabaseConfig(bucketName, "db2", collection1ScopesConfig, "1-a")
_, err = bc.InsertConfig(ctx, bucketName, groupID, collection1db2Config)
require.Error(t, err) // collection conflict
configs, err = bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 1)
// Reattempt insert, should now succeed
_, err = bc.InsertConfig(ctx, bucketName, groupID, collection1db2Config)
require.NoError(t, err)
// Case 4. InsertConfig for a different db with collection conflict with the version prior to the failed update
collection3db1Config := getTestDatabaseConfig(bucketName, "db1", collection3ScopesConfig, "3-a")
simulateUpdateFailure(t, collection3db1Config)
collection2db3Config := getTestDatabaseConfig(bucketName, "db3", collection1ScopesConfig, "1-a")
_, err = bc.InsertConfig(ctx, bucketName, groupID, collection2db3Config)
require.Error(t, err) // collection conflict
configs, err = bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 2)
// Reattempt insert, should still be in conflict post-rollback
_, err = bc.InsertConfig(ctx, bucketName, groupID, collection2db3Config)
require.Error(t, err) // collection conflict
configs, err = bc.GetDatabaseConfigs(ctx, bucketName, groupID)
require.NoError(t, err)
require.Len(t, configs, 2)
// Case 5. Attempt to delete db after update failure for that db
simulateUpdateFailure(t, collection3db1Config)
deleteErr := bc.DeleteConfig(ctx, bucketName, groupID, "db1")
require.NoError(t, deleteErr)
// Retrieve registry to ensure the delete was successful
registry, err = bc.getGatewayRegistry(ctx, bucketName)
require.NoError(t, err)
_, ok = registry.getRegistryDatabase(groupID, "db1")
require.False(t, ok)
})
}
}
// TestPersistentConfigRegistryRollbackAfterDeleteFailure simulates node failure during an deleteConfig operation, leaving
// the registry updated but not the config file.
// 1. Attempt retrieval of database after delete fails, should fail with not found.
// 2. Attempt recreation of database with matching version, after delete fails. Should resolve delete and succeed
// 3. Attempt recreation of database with matching generation only, after delete fails. Should resolve delete and succeed
// 4. Attempt recreation of database with earlier version generation, after delete fails. Should resolve delete and succeed
// 5. Attempt update of database after delete fails. Should return "database does not exist" error
func TestPersistentConfigRegistryRollbackAfterDeleteFailure(t *testing.T) {
base.TestRequiresCollections(t)
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeyConfig)
for _, test := range persistentConfigTestCases() {
t.Run(test.name, func(t *testing.T) {
sc, closeFn := startBootstrapServerWithoutConfigPolling(t, test.xattrConfig)
defer closeFn()
ctx := base.TestCtx(t)
tb := base.GetTestBucket(t)
defer tb.Close(ctx)
threeCollectionScopesConfig := GetCollectionsConfig(t, tb, 3)
dataStoreNames := GetDataStoreNamesFromScopesConfig(threeCollectionScopesConfig)
bucketName := tb.GetName()
scopeName := dataStoreNames[0].ScopeName()
groupID := sc.Config.Bootstrap.ConfigGroupID
collection1Name := dataStoreNames[0].CollectionName()
collection2Name := dataStoreNames[1].CollectionName()
collection1ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection1Name: {}}}}
collection2ScopesConfig := ScopesConfig{scopeName: ScopeConfig{map[string]*CollectionConfig{collection2Name: {}}}}
// SimulateDeleteFailure updates the registry with a new config, but doesn't create the associated config file
bc := sc.BootstrapContext
// reduce retry timeout for testing
bc.configRetryTimeout = 1 * time.Millisecond
// Create database with collection 1
collection1db1Config := getTestDatabaseConfig(bucketName, "db1", collection1ScopesConfig, "1-a")
_, err := bc.InsertConfig(ctx, bucketName, groupID, collection1db1Config)
require.NoError(t, err)
// simulateDeleteFailure removes the database from the database registry but doesn't remove the associated config file.
// Simulates node failure between registry update and config removal.
simulateDeleteFailure := func(t *testing.T, config *DatabaseConfig) {
registry, err := bc.getGatewayRegistry(ctx, bucketName)