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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
|
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding
#include "mongo/platform/basic.h"
#include "mongo/db/s/shard_server_catalog_cache_loader.h"
#include <memory>
#include "mongo/db/client.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/operation_context_group.h"
#include "mongo/db/read_concern.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/s/shard_metadata_util.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/s/catalog/type_shard_collection.h"
#include "mongo/s/catalog/type_shard_database.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/grid.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/log.h"
namespace mongo {
using namespace shardmetadatautil;
using CollectionAndChangedChunks = CatalogCacheLoader::CollectionAndChangedChunks;
namespace {
MONGO_FAIL_POINT_DEFINE(hangPersistCollectionAndChangedChunksAfterDropChunks);
AtomicWord<unsigned long long> taskIdGenerator{0};
/**
* Constructs the options for the loader thread pool.
*/
ThreadPool::Options makeDefaultThreadPoolOptions() {
ThreadPool::Options options;
options.poolName = "ShardServerCatalogCacheLoader";
options.minThreads = 0;
options.maxThreads = 6;
// Ensure all threads have a client.
options.onCreateThread = [](const std::string& threadName) {
Client::initThread(threadName.c_str());
};
return options;
}
void dropChunksIfEpochChanged(OperationContext* opCtx,
const NamespaceString& nss,
const CollectionAndChangedChunks& collAndChunks,
const ChunkVersion& maxLoaderVersion) {
if (collAndChunks.epoch != maxLoaderVersion.epoch() &&
maxLoaderVersion != ChunkVersion::UNSHARDED()) {
// If the collection has a new epoch, delete all existing chunks in the persisted routing
// table cache.
dropChunks(opCtx, nss);
if (MONGO_unlikely(hangPersistCollectionAndChangedChunksAfterDropChunks.shouldFail())) {
log() << "Hit hangPersistCollectionAndChangedChunksAfterDropChunks failpoint";
hangPersistCollectionAndChangedChunksAfterDropChunks.pauseWhileSet(opCtx);
}
}
}
/**
* Takes a CollectionAndChangedChunks object and persists the changes to the shard's metadata
* collections.
*
* Returns ConflictingOperationInProgress if a chunk is found with a new epoch.
*/
Status persistCollectionAndChangedChunks(OperationContext* opCtx,
const NamespaceString& nss,
const CollectionAndChangedChunks& collAndChunks,
const ChunkVersion& maxLoaderVersion) {
// Update the collections collection entry for 'nss' in case there are any new updates.
ShardCollectionType update = ShardCollectionType(
nss, collAndChunks.epoch, collAndChunks.shardKeyPattern, collAndChunks.shardKeyIsUnique);
update.setUuid(collAndChunks.uuid);
if (!collAndChunks.defaultCollation.isEmpty()) {
update.setDefaultCollation(collAndChunks.defaultCollation.getOwned());
}
// Mark the chunk metadata as refreshing, so that secondaries are aware of refresh.
update.setRefreshing(true);
Status status =
updateShardCollectionsEntry(opCtx,
BSON(ShardCollectionType::kNssFieldName << nss.ns()),
update.toBSON(),
BSONObj(),
true /*upsert*/);
if (!status.isOK()) {
return status;
}
// Update the chunks.
try {
dropChunksIfEpochChanged(opCtx, nss, collAndChunks, maxLoaderVersion);
} catch (const DBException& ex) {
return ex.toStatus();
}
status = updateShardChunks(opCtx, nss, collAndChunks.changedChunks, collAndChunks.epoch);
if (!status.isOK()) {
return status;
}
// Mark the chunk metadata as done refreshing.
status =
unsetPersistedRefreshFlags(opCtx, nss, collAndChunks.changedChunks.back().getVersion());
if (!status.isOK()) {
return status;
}
return Status::OK();
}
/**
* Takes a DatabaseType object and persists the changes to the shard's metadata
* collections.
*/
Status persistDbVersion(OperationContext* opCtx, const DatabaseType& dbt) {
// Update the databases collection entry for 'dbName' in case there are any new updates.
Status status = updateShardDatabasesEntry(opCtx,
BSON(ShardDatabaseType::name() << dbt.getName()),
dbt.toBSON(),
BSONObj(),
true /*upsert*/);
if (!status.isOK()) {
return status;
}
return Status::OK();
}
/**
* This function will throw on error!
*
* Retrieves the persisted max chunk version for 'nss', if there are any persisted chunks. If there
* are none -- meaning there's no persisted metadata for 'nss' --, returns a
* ChunkVersion::UNSHARDED() version.
*
* It is unsafe to call this when a task for 'nss' is running concurrently because the collection
* could be dropped and recreated between reading the collection epoch and retrieving the chunk,
* which would make the returned ChunkVersion corrupt.
*/
ChunkVersion getPersistedMaxChunkVersion(OperationContext* opCtx, const NamespaceString& nss) {
// Must read the collections entry to get the epoch to pass into ChunkType for shard's chunk
// collection.
auto statusWithCollection = readShardCollectionsEntry(opCtx, nss);
if (statusWithCollection == ErrorCodes::NamespaceNotFound) {
// There is no persisted metadata.
return ChunkVersion::UNSHARDED();
}
uassert(ErrorCodes::OperationFailed,
str::stream() << "Failed to read persisted collections entry for collection '"
<< nss.ns() << "' due to '" << statusWithCollection.getStatus().toString()
<< "'.",
statusWithCollection.isOK());
auto statusWithChunk =
shardmetadatautil::readShardChunks(opCtx,
nss,
BSONObj(),
BSON(ChunkType::lastmod() << -1),
1LL,
statusWithCollection.getValue().getEpoch());
uassert(ErrorCodes::OperationFailed,
str::stream() << "Failed to read highest version persisted chunk for collection '"
<< nss.ns() << "' due to '" << statusWithChunk.getStatus().toString()
<< "'.",
statusWithChunk.isOK());
return statusWithChunk.getValue().empty() ? ChunkVersion::UNSHARDED()
: statusWithChunk.getValue().front().getVersion();
}
/**
* This function will throw on error!
*
* Tries to find persisted chunk metadata with chunk versions GTE to 'version'.
*
* If 'version's epoch matches persisted metadata, returns persisted metadata GTE 'version'.
* If 'version's epoch doesn't match persisted metadata, returns all persisted metadata.
* If collections entry does not exist, throws NamespaceNotFound error. Can return an empty
* chunks vector in CollectionAndChangedChunks without erroring, if collections entry IS found.
*/
CollectionAndChangedChunks getPersistedMetadataSinceVersion(OperationContext* opCtx,
const NamespaceString& nss,
ChunkVersion version) {
ShardCollectionType shardCollectionEntry =
uassertStatusOK(readShardCollectionsEntry(opCtx, nss));
// If the persisted epoch doesn't match what the CatalogCache requested, read everything.
ChunkVersion startingVersion = (shardCollectionEntry.getEpoch() == version.epoch())
? version
: ChunkVersion(0, 0, shardCollectionEntry.getEpoch());
QueryAndSort diff = createShardChunkDiffQuery(startingVersion);
auto changedChunks = uassertStatusOK(
readShardChunks(opCtx, nss, diff.query, diff.sort, boost::none, startingVersion.epoch()));
return CollectionAndChangedChunks{shardCollectionEntry.getUuid(),
shardCollectionEntry.getEpoch(),
shardCollectionEntry.getKeyPattern().toBSON(),
shardCollectionEntry.getDefaultCollation(),
shardCollectionEntry.getUnique(),
std::move(changedChunks)};
}
DatabaseType getPersistedDbMetadata(OperationContext* opCtx, StringData dbName) {
ShardDatabaseType shardDatabaseEntry = uassertStatusOK(readShardDatabasesEntry(opCtx, dbName));
DatabaseType dbt(shardDatabaseEntry.getDbName(),
shardDatabaseEntry.getPrimary(),
shardDatabaseEntry.getPartitioned(),
shardDatabaseEntry.getDbVersion());
return dbt;
}
/**
* Attempts to read the collection and chunk metadata. May not read a complete diff if the metadata
* for the collection is being updated concurrently. This is safe if those updates are appended.
*
* If the epoch changes while reading the chunks, returns an empty object.
*/
StatusWith<CollectionAndChangedChunks> getIncompletePersistedMetadataSinceVersion(
OperationContext* opCtx, const NamespaceString& nss, ChunkVersion version) {
try {
CollectionAndChangedChunks collAndChunks =
getPersistedMetadataSinceVersion(opCtx, nss, version);
if (collAndChunks.changedChunks.empty()) {
// Found a collections entry, but the chunks are being updated.
return CollectionAndChangedChunks();
}
// Make sure the collections entry epoch has not changed since we began reading chunks --
// an epoch change between reading the collections entry and reading the chunk metadata
// would invalidate the chunks.
auto afterShardCollectionsEntry = uassertStatusOK(readShardCollectionsEntry(opCtx, nss));
if (collAndChunks.epoch != afterShardCollectionsEntry.getEpoch()) {
// The collection was dropped and recreated since we began. Return empty results.
return CollectionAndChangedChunks();
}
return collAndChunks;
} catch (const DBException& ex) {
Status status = ex.toStatus();
if (status == ErrorCodes::NamespaceNotFound) {
return CollectionAndChangedChunks();
}
return Status(ErrorCodes::OperationFailed,
str::stream()
<< "Failed to load local metadata due to '" << status.toString() << "'.");
}
}
/**
* Sends _flushRoutingTableCacheUpdates to the primary to force it to refresh its routing table for
* collection 'nss' and then waits for the refresh to replicate to this node.
*/
void forcePrimaryCollectionRefreshAndWaitForReplication(OperationContext* opCtx,
const NamespaceString& nss) {
auto const shardingState = ShardingState::get(opCtx);
invariant(shardingState->enabled());
auto selfShard = uassertStatusOK(
Grid::get(opCtx)->shardRegistry()->getShard(opCtx, shardingState->shardId()));
auto cmdResponse = uassertStatusOK(selfShard->runCommandWithFixedRetryAttempts(
opCtx,
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
"admin",
BSON("_flushRoutingTableCacheUpdates" << nss.ns()),
Seconds{30},
Shard::RetryPolicy::kIdempotent));
uassertStatusOK(cmdResponse.commandStatus);
uassertStatusOK(repl::ReplicationCoordinator::get(opCtx)->waitUntilOpTimeForRead(
opCtx, {LogicalTime::fromOperationTime(cmdResponse.response), boost::none}));
}
/**
* Sends _flushDatabaseCacheUpdates to the primary to force it to refresh its routing table for
* database 'dbName' and then waits for the refresh to replicate to this node.
*/
void forcePrimaryDatabaseRefreshAndWaitForReplication(OperationContext* opCtx, StringData dbName) {
auto const shardingState = ShardingState::get(opCtx);
invariant(shardingState->enabled());
auto selfShard = uassertStatusOK(
Grid::get(opCtx)->shardRegistry()->getShard(opCtx, shardingState->shardId()));
auto cmdResponse = uassertStatusOK(selfShard->runCommandWithFixedRetryAttempts(
opCtx,
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
"admin",
BSON("_flushDatabaseCacheUpdates" << dbName.toString()),
Seconds{30},
Shard::RetryPolicy::kIdempotent));
uassertStatusOK(cmdResponse.commandStatus);
uassertStatusOK(repl::ReplicationCoordinator::get(opCtx)->waitUntilOpTimeForRead(
opCtx, {LogicalTime::fromOperationTime(cmdResponse.response), boost::none}));
}
/**
* Reads the local chunk metadata to obtain the current ChunkVersion. If there is no local
* metadata for the namespace, returns ChunkVersion::UNSHARDED(), since only metadata for sharded
* collections is persisted.
*/
ChunkVersion getLocalVersion(OperationContext* opCtx, const NamespaceString& nss) {
auto swRefreshState = getPersistedRefreshFlags(opCtx, nss);
if (swRefreshState == ErrorCodes::NamespaceNotFound)
return ChunkVersion::UNSHARDED();
return uassertStatusOK(std::move(swRefreshState)).lastRefreshedCollectionVersion;
}
} // namespace
ShardServerCatalogCacheLoader::ShardServerCatalogCacheLoader(
std::unique_ptr<CatalogCacheLoader> configServerLoader)
: _configServerLoader(std::move(configServerLoader)),
_threadPool(makeDefaultThreadPoolOptions()) {
_threadPool.startup();
}
ShardServerCatalogCacheLoader::~ShardServerCatalogCacheLoader() {
shutDown();
}
void ShardServerCatalogCacheLoader::notifyOfCollectionVersionUpdate(const NamespaceString& nss) {
_namespaceNotifications.notifyChange(nss);
}
void ShardServerCatalogCacheLoader::initializeReplicaSetRole(bool isPrimary) {
stdx::lock_guard<Latch> lg(_mutex);
invariant(_role == ReplicaSetRole::None);
if (isPrimary) {
_role = ReplicaSetRole::Primary;
} else {
_role = ReplicaSetRole::Secondary;
}
}
void ShardServerCatalogCacheLoader::onStepDown() {
stdx::lock_guard<Latch> lg(_mutex);
invariant(_role != ReplicaSetRole::None);
_contexts.interrupt(ErrorCodes::PrimarySteppedDown);
++_term;
_role = ReplicaSetRole::Secondary;
}
void ShardServerCatalogCacheLoader::onStepUp() {
stdx::lock_guard<Latch> lg(_mutex);
invariant(_role != ReplicaSetRole::None);
++_term;
_role = ReplicaSetRole::Primary;
}
void ShardServerCatalogCacheLoader::shutDown() {
{
stdx::lock_guard<Latch> lg(_mutex);
if (_inShutdown) {
return;
}
_inShutdown = true;
}
// Prevent further scheduling, then interrupt ongoing tasks.
_threadPool.shutdown();
{
stdx::lock_guard<Latch> lock(_mutex);
_contexts.interrupt(ErrorCodes::InterruptedAtShutdown);
++_term;
}
_threadPool.join();
invariant(_contexts.isEmpty());
_configServerLoader->shutDown();
}
std::shared_ptr<Notification<void>> ShardServerCatalogCacheLoader::getChunksSince(
const NamespaceString& nss, ChunkVersion version, GetChunksSinceCallbackFn callbackFn) {
auto notify = std::make_shared<Notification<void>>();
bool isPrimary;
long long term;
std::tie(isPrimary, term) = [&] {
stdx::lock_guard<Latch> lock(_mutex);
return std::make_tuple(_role == ReplicaSetRole::Primary, _term);
}();
_threadPool.schedule(
[ this, nss, version, callbackFn, notify, isPrimary, term ](auto status) noexcept {
invariant(status);
auto context = _contexts.makeOperationContext(*Client::getCurrent());
auto const opCtx = context.opCtx();
try {
{
// We may have missed an OperationContextGroup interrupt since this operation
// began but before the OperationContext was added to the group. So we'll check
// that we're still in the same _term.
stdx::lock_guard<Latch> lock(_mutex);
uassert(ErrorCodes::InterruptedDueToReplStateChange,
"Unable to refresh routing table because replica set state changed or "
"the node is shutting down.",
_term == term);
}
if (isPrimary) {
_schedulePrimaryGetChunksSince(opCtx, nss, version, term, callbackFn, notify);
} else {
_runSecondaryGetChunksSince(opCtx, nss, version, callbackFn, notify);
}
} catch (const DBException& ex) {
callbackFn(opCtx, ex.toStatus());
notify->set();
}
});
return notify;
}
void ShardServerCatalogCacheLoader::getDatabase(
StringData dbName,
std::function<void(OperationContext*, StatusWith<DatabaseType>)> callbackFn) {
bool isPrimary;
long long term;
std::tie(isPrimary, term) = [&] {
stdx::lock_guard<Latch> lock(_mutex);
return std::make_tuple(_role == ReplicaSetRole::Primary, _term);
}();
_threadPool.schedule([ this, name = dbName.toString(), callbackFn, isPrimary,
term ](auto status) noexcept {
invariant(status);
auto context = _contexts.makeOperationContext(*Client::getCurrent());
auto const opCtx = context.opCtx();
try {
{
// We may have missed an OperationContextGroup interrupt since this operation began
// but before the OperationContext was added to the group. So we'll check that we're
// still in the same _term.
stdx::lock_guard<Latch> lock(_mutex);
uassert(ErrorCodes::InterruptedDueToReplStateChange,
"Unable to refresh database because replica set state changed or the node "
"is shutting down.",
_term == term);
}
if (isPrimary) {
_schedulePrimaryGetDatabase(opCtx, name, term, callbackFn);
} else {
_runSecondaryGetDatabase(opCtx, name, callbackFn);
}
} catch (const DBException& ex) {
callbackFn(context.opCtx(), ex.toStatus());
}
});
}
void ShardServerCatalogCacheLoader::waitForCollectionFlush(OperationContext* opCtx,
const NamespaceString& nss) {
stdx::unique_lock<Latch> lg(_mutex);
const auto initialTerm = _term;
boost::optional<uint64_t> taskNumToWait;
while (true) {
uassert(ErrorCodes::NotMaster,
str::stream() << "Unable to wait for collection metadata flush for " << nss.ns()
<< " because the node's replication role changed.",
_role == ReplicaSetRole::Primary && _term == initialTerm);
auto it = _collAndChunkTaskLists.find(nss);
// If there are no tasks for the specified namespace, everything must have been completed
if (it == _collAndChunkTaskLists.end())
return;
auto& taskList = it->second;
if (!taskNumToWait) {
const auto& lastTask = taskList.back();
taskNumToWait = lastTask.taskNum;
} else {
const auto& activeTask = taskList.front();
if (activeTask.taskNum > *taskNumToWait) {
auto secondTaskIt = std::next(taskList.begin());
// Because of an optimization where a namespace drop clears all tasks except the
// active it is possible that the task number we are waiting on will never actually
// be written. Because of this we move the task number to the drop which can only be
// in the active task or in the one after the active.
if (activeTask.dropped) {
taskNumToWait = activeTask.taskNum;
} else if (secondTaskIt != taskList.end() && secondTaskIt->dropped) {
taskNumToWait = secondTaskIt->taskNum;
} else {
return;
}
}
}
// It is not safe to use taskList after this call, because it will unlock and lock the tasks
// mutex, so we just loop around.
taskList.waitForActiveTaskCompletion(lg);
}
}
void ShardServerCatalogCacheLoader::waitForDatabaseFlush(OperationContext* opCtx,
StringData dbName) {
stdx::unique_lock<Latch> lg(_mutex);
const auto initialTerm = _term;
boost::optional<uint64_t> taskNumToWait;
while (true) {
uassert(ErrorCodes::NotMaster,
str::stream() << "Unable to wait for database metadata flush for "
<< dbName.toString()
<< " because the node's replication role changed.",
_role == ReplicaSetRole::Primary && _term == initialTerm);
auto it = _dbTaskLists.find(dbName.toString());
// If there are no tasks for the specified namespace, everything must have been completed
if (it == _dbTaskLists.end())
return;
auto& taskList = it->second;
if (!taskNumToWait) {
const auto& lastTask = taskList.back();
taskNumToWait = lastTask.taskNum;
} else {
const auto& activeTask = taskList.front();
if (activeTask.taskNum > *taskNumToWait) {
auto secondTaskIt = std::next(taskList.begin());
// Because of an optimization where a namespace drop clears all tasks except the
// active it is possible that the task number we are waiting on will never actually
// be written. Because of this we move the task number to the drop which can only be
// in the active task or in the one after the active.
if (!activeTask.dbType) {
// The task is for a drop.
taskNumToWait = activeTask.taskNum;
} else if (secondTaskIt != taskList.end() && !secondTaskIt->dbType) {
taskNumToWait = secondTaskIt->taskNum;
} else {
return;
}
}
}
// It is not safe to use taskList after this call, because it will unlock and lock the tasks
// mutex, so we just loop around.
taskList.waitForActiveTaskCompletion(lg);
}
}
void ShardServerCatalogCacheLoader::_runSecondaryGetChunksSince(
OperationContext* opCtx,
const NamespaceString& nss,
const ChunkVersion& catalogCacheSinceVersion,
std::function<void(OperationContext*, StatusWith<CollectionAndChangedChunks>)> callbackFn,
std::shared_ptr<Notification<void>> notify) {
forcePrimaryCollectionRefreshAndWaitForReplication(opCtx, nss);
// Read the local metadata.
// Disallow reading on an older snapshot because this relies on being able to read the
// side effects of writes during secondary replication after being signalled from the
// CollectionVersionLogOpHandler.
BlockSecondaryReadsDuringBatchApplication_DONT_USE secondaryReadsBlockBehindReplication(opCtx);
auto swCollAndChunks =
_getCompletePersistedMetadataForSecondarySinceVersion(opCtx, nss, catalogCacheSinceVersion);
callbackFn(opCtx, std::move(swCollAndChunks));
notify->set();
}
void ShardServerCatalogCacheLoader::_schedulePrimaryGetChunksSince(
OperationContext* opCtx,
const NamespaceString& nss,
const ChunkVersion& catalogCacheSinceVersion,
long long termScheduled,
std::function<void(OperationContext*, StatusWith<CollectionAndChangedChunks>)> callbackFn,
std::shared_ptr<Notification<void>> notify) {
// Get the max version the loader has.
const ChunkVersion maxLoaderVersion = [&] {
{
stdx::lock_guard<Latch> lock(_mutex);
auto taskListIt = _collAndChunkTaskLists.find(nss);
if (taskListIt != _collAndChunkTaskLists.end() &&
taskListIt->second.hasTasksFromThisTerm(termScheduled)) {
// Enqueued tasks have the latest metadata
return taskListIt->second.getHighestVersionEnqueued();
}
}
// If there are no enqueued tasks, get the max persisted
return getPersistedMaxChunkVersion(opCtx, nss);
}();
auto remoteRefreshFn = [this, nss, catalogCacheSinceVersion, maxLoaderVersion, termScheduled](
OperationContext* opCtx,
StatusWith<CollectionAndChangedChunks> swCollectionAndChangedChunks)
-> StatusWith<CollectionAndChangedChunks> {
if (swCollectionAndChangedChunks == ErrorCodes::NamespaceNotFound) {
_ensureMajorityPrimaryAndScheduleCollAndChunksTask(
opCtx,
nss,
collAndChunkTask{swCollectionAndChangedChunks, maxLoaderVersion, termScheduled});
LOG_CATALOG_REFRESH(1)
<< "Cache loader remotely refreshed for collection " << nss << " from version "
<< maxLoaderVersion << " and no metadata was found.";
return swCollectionAndChangedChunks;
}
if (!swCollectionAndChangedChunks.isOK()) {
return swCollectionAndChangedChunks;
}
auto& collAndChunks = swCollectionAndChangedChunks.getValue();
if (collAndChunks.changedChunks.back().getVersion().epoch() != collAndChunks.epoch) {
return Status{ErrorCodes::ConflictingOperationInProgress,
str::stream()
<< "Invalid chunks found when reloading '" << nss.toString()
<< "' Previous collection epoch was '"
<< collAndChunks.epoch.toString() << "', but found a new epoch '"
<< collAndChunks.changedChunks.back().getVersion().epoch().toString()
<< "'. Collection was dropped and recreated."};
}
if ((collAndChunks.epoch != maxLoaderVersion.epoch()) ||
(collAndChunks.changedChunks.back().getVersion() > maxLoaderVersion)) {
_ensureMajorityPrimaryAndScheduleCollAndChunksTask(
opCtx,
nss,
collAndChunkTask{swCollectionAndChangedChunks, maxLoaderVersion, termScheduled});
}
LOG_CATALOG_REFRESH(1) << "Cache loader remotely refreshed for collection " << nss
<< " from collection version " << maxLoaderVersion
<< " and found collection version "
<< collAndChunks.changedChunks.back().getVersion();
// Metadata was found remotely
// -- otherwise we would have received NamespaceNotFound rather than Status::OK().
// Return metadata for CatalogCache that's GTE catalogCacheSinceVersion,
// from the loader's persisted and enqueued metadata.
swCollectionAndChangedChunks =
_getLoaderMetadata(opCtx, nss, catalogCacheSinceVersion, termScheduled);
if (!swCollectionAndChangedChunks.isOK()) {
return swCollectionAndChangedChunks;
}
const auto termAfterRefresh = [&] {
stdx::lock_guard<Latch> lock(_mutex);
return _term;
}();
if (termAfterRefresh != termScheduled) {
// Raising a ConflictingOperationInProgress error here will cause the CatalogCache to
// attempt the refresh as secondary instead of failing the operation
return Status(ErrorCodes::ConflictingOperationInProgress,
str::stream() << "Replication stepdown occurred during refresh for '"
<< nss.toString());
}
// After finding metadata remotely, we must have found metadata locally.
invariant(!collAndChunks.changedChunks.empty());
return swCollectionAndChangedChunks;
};
// Refresh the loader's metadata from the config server. The caller's request will
// then be serviced from the loader's up-to-date metadata.
_configServerLoader->getChunksSince(
nss,
maxLoaderVersion,
[this, remoteRefreshFn, callbackFn, notify](auto opCtx, auto swCollectionAndChangedChunks) {
// Complete the callbackFn work.
callbackFn(opCtx, remoteRefreshFn(opCtx, std::move(swCollectionAndChangedChunks)));
notify->set();
});
}
void ShardServerCatalogCacheLoader::_runSecondaryGetDatabase(
OperationContext* opCtx,
StringData dbName,
std::function<void(OperationContext*, StatusWith<DatabaseType>)> callbackFn) {
forcePrimaryDatabaseRefreshAndWaitForReplication(opCtx, dbName);
// Read the local metadata.
auto swDatabaseType = getPersistedDbMetadata(opCtx, dbName);
callbackFn(opCtx, std::move(swDatabaseType));
}
void ShardServerCatalogCacheLoader::_schedulePrimaryGetDatabase(
OperationContext* opCtx,
StringData dbName,
long long termScheduled,
std::function<void(OperationContext*, StatusWith<DatabaseType>)> callbackFn) {
auto remoteRefreshFn = [this, name = dbName.toString(), termScheduled](
OperationContext* opCtx, StatusWith<DatabaseType> swDatabaseType) {
if (swDatabaseType == ErrorCodes::NamespaceNotFound) {
_ensureMajorityPrimaryAndScheduleDbTask(
opCtx, name, DBTask{swDatabaseType, termScheduled});
LOG_CATALOG_REFRESH(1) << "Cache loader remotely refreshed for database " << name
<< " and found the database has been dropped.";
return swDatabaseType;
}
if (!swDatabaseType.isOK()) {
return swDatabaseType;
}
_ensureMajorityPrimaryAndScheduleDbTask(opCtx, name, DBTask{swDatabaseType, termScheduled});
LOG_CATALOG_REFRESH(1) << "Cache loader remotely refreshed for database " << name
<< " and found " << swDatabaseType.getValue().toBSON();
return swDatabaseType;
};
_configServerLoader->getDatabase(
dbName, [this, remoteRefreshFn, callbackFn](auto opCtx, auto swDatabaseType) {
callbackFn(opCtx, remoteRefreshFn(opCtx, std::move(swDatabaseType)));
});
}
StatusWith<CollectionAndChangedChunks> ShardServerCatalogCacheLoader::_getLoaderMetadata(
OperationContext* opCtx,
const NamespaceString& nss,
const ChunkVersion& catalogCacheSinceVersion,
long long expectedTerm) {
// Get the enqueued metadata first. Otherwise we could miss data between reading persisted and
// enqueued, if an enqueued task finished after the persisted read but before the enqueued read.
auto enqueuedRes = _getEnqueuedMetadata(nss, catalogCacheSinceVersion, expectedTerm);
bool tasksAreEnqueued = std::move(enqueuedRes.first);
CollectionAndChangedChunks enqueued = std::move(enqueuedRes.second);
auto swPersisted =
getIncompletePersistedMetadataSinceVersion(opCtx, nss, catalogCacheSinceVersion);
CollectionAndChangedChunks persisted;
if (swPersisted == ErrorCodes::NamespaceNotFound) {
// No persisted metadata found, create an empty object.
persisted = CollectionAndChangedChunks();
} else if (!swPersisted.isOK()) {
return swPersisted;
} else {
persisted = std::move(swPersisted.getValue());
}
LOG_CATALOG_REFRESH(1)
<< "Cache loader found "
<< (enqueued.changedChunks.empty()
? (tasksAreEnqueued ? "a drop enqueued" : "no enqueued metadata")
: ("enqueued metadata from " +
enqueued.changedChunks.front().getVersion().toString() + " to " +
enqueued.changedChunks.back().getVersion().toString()))
<< " and "
<< (persisted.changedChunks.empty()
? "no persisted metadata"
: ("persisted metadata from " +
persisted.changedChunks.front().getVersion().toString() + " to " +
persisted.changedChunks.back().getVersion().toString()))
<< ", GTE cache version " << catalogCacheSinceVersion;
if (!tasksAreEnqueued) {
// There are no tasks in the queue. Return the persisted metadata.
return persisted;
} else if (persisted.changedChunks.empty() || enqueued.changedChunks.empty() ||
enqueued.epoch != persisted.epoch) {
// There is a task queue and:
// - nothing is persisted.
// - nothing was returned from enqueued, which means the last task enqueued is a drop task.
// - the epoch changed in the enqueued metadata, which means there's a drop operation
// enqueued somewhere.
// Whichever the cause, the persisted metadata is out-dated/non-existent. Return enqueued
// results.
return enqueued;
} else {
// There can be overlap between persisted and enqueued metadata because enqueued work can
// be applied while persisted was read. We must remove this overlap.
const ChunkVersion minEnqueuedVersion = enqueued.changedChunks.front().getVersion();
// Remove chunks from 'persisted' that are GTE the minimum in 'enqueued' -- this is
// the overlap.
auto persistedChangedChunksIt = persisted.changedChunks.begin();
while (persistedChangedChunksIt != persisted.changedChunks.end() &&
persistedChangedChunksIt->getVersion() < minEnqueuedVersion) {
++persistedChangedChunksIt;
}
persisted.changedChunks.erase(persistedChangedChunksIt, persisted.changedChunks.end());
// Append 'enqueued's chunks to 'persisted', which no longer overlaps.
persisted.changedChunks.insert(persisted.changedChunks.end(),
enqueued.changedChunks.begin(),
enqueued.changedChunks.end());
return persisted;
}
}
std::pair<bool, CollectionAndChangedChunks> ShardServerCatalogCacheLoader::_getEnqueuedMetadata(
const NamespaceString& nss,
const ChunkVersion& catalogCacheSinceVersion,
const long long term) {
stdx::unique_lock<Latch> lock(_mutex);
auto taskListIt = _collAndChunkTaskLists.find(nss);
if (taskListIt == _collAndChunkTaskLists.end()) {
return std::make_pair(false, CollectionAndChangedChunks());
} else if (!taskListIt->second.hasTasksFromThisTerm(term)) {
// If task list does not have a term that matches, there's no valid task data to collect.
return std::make_pair(false, CollectionAndChangedChunks());
}
// Only return task data of tasks scheduled in the same term as the given 'term': older term
// task data is no longer valid.
CollectionAndChangedChunks collAndChunks = taskListIt->second.getEnqueuedMetadataForTerm(term);
// Return all the results if 'catalogCacheSinceVersion's epoch does not match. Otherwise, trim
// the results to be GTE to 'catalogCacheSinceVersion'.
if (collAndChunks.epoch != catalogCacheSinceVersion.epoch()) {
return std::make_pair(true, collAndChunks);
}
auto changedChunksIt = collAndChunks.changedChunks.begin();
while (changedChunksIt != collAndChunks.changedChunks.end() &&
changedChunksIt->getVersion() < catalogCacheSinceVersion) {
++changedChunksIt;
}
collAndChunks.changedChunks.erase(collAndChunks.changedChunks.begin(), changedChunksIt);
return std::make_pair(true, collAndChunks);
}
void ShardServerCatalogCacheLoader::_ensureMajorityPrimaryAndScheduleCollAndChunksTask(
OperationContext* opCtx, const NamespaceString& nss, collAndChunkTask task) {
{
stdx::lock_guard<Latch> lock(_mutex);
auto& list = _collAndChunkTaskLists[nss];
auto wasEmpty = list.empty();
list.addTask(std::move(task));
if (!wasEmpty)
return;
}
_threadPool.schedule([this, nss](auto status) {
invariant(status);
_runCollAndChunksTasks(nss);
});
}
void ShardServerCatalogCacheLoader::_ensureMajorityPrimaryAndScheduleDbTask(OperationContext* opCtx,
StringData dbName,
DBTask task) {
{
stdx::lock_guard<Latch> lock(_mutex);
auto& list = _dbTaskLists[dbName.toString()];
auto wasEmpty = list.empty();
list.addTask(std::move(task));
if (!wasEmpty)
return;
}
_threadPool.schedule([this, name = dbName.toString()](auto status) {
invariant(status);
_runDbTasks(name);
});
}
void ShardServerCatalogCacheLoader::_runCollAndChunksTasks(const NamespaceString& nss) {
auto context = _contexts.makeOperationContext(*Client::getCurrent());
bool taskFinished = false;
bool inShutdown = false;
try {
_updatePersistedCollAndChunksMetadata(context.opCtx(), nss);
taskFinished = true;
} catch (const ExceptionForCat<ErrorCategory::ShutdownError>&) {
LOG(0) << "Failed to persist chunk metadata update for collection '" << nss
<< "' due to shutdown.";
inShutdown = true;
} catch (const DBException& ex) {
LOG(0) << "Failed to persist chunk metadata update for collection '" << nss
<< causedBy(redact(ex));
}
{
stdx::lock_guard<Latch> lock(_mutex);
// If task completed successfully, remove it from work queue.
if (taskFinished) {
_collAndChunkTaskLists[nss].pop_front();
}
// Return if have no more work
if (_collAndChunkTaskLists[nss].empty()) {
_collAndChunkTaskLists.erase(nss);
return;
}
// If shutting down need to remove tasks to end waiting on its completion.
if (inShutdown) {
while (!_collAndChunkTaskLists[nss].empty()) {
_collAndChunkTaskLists[nss].pop_front();
}
_collAndChunkTaskLists.erase(nss);
return;
}
}
_threadPool.schedule([this, nss](auto status) {
if (ErrorCodes::isCancelationError(status.code())) {
LOG(0) << "Cache loader failed to schedule a persisted metadata update"
<< " task for namespace '" << nss << "' due to '" << redact(status)
<< "'. Clearing task list so that scheduling will be attempted by the next"
<< " caller to refresh this namespace.";
{
stdx::lock_guard<Latch> lock(_mutex);
_collAndChunkTaskLists.erase(nss);
}
return;
}
invariant(status);
_runCollAndChunksTasks(nss);
});
}
void ShardServerCatalogCacheLoader::_runDbTasks(StringData dbName) {
auto context = _contexts.makeOperationContext(*Client::getCurrent());
bool taskFinished = false;
bool inShutdown = false;
try {
_updatePersistedDbMetadata(context.opCtx(), dbName);
taskFinished = true;
} catch (const ExceptionForCat<ErrorCategory::ShutdownError>&) {
LOG(0) << "Failed to persist metadata update for db '" << dbName << "' due to shutdown.";
inShutdown = true;
} catch (const DBException& ex) {
LOG(0) << "Failed to persist chunk metadata update for database " << dbName
<< causedBy(redact(ex));
}
{
stdx::lock_guard<Latch> lock(_mutex);
// If task completed successfully, remove it from work queue.
if (taskFinished) {
_dbTaskLists[dbName.toString()].pop_front();
}
// Return if have no more work
if (_dbTaskLists[dbName.toString()].empty()) {
_dbTaskLists.erase(dbName.toString());
return;
}
// If shutting down need to remove tasks to end waiting on its completion.
if (inShutdown) {
while (!_dbTaskLists[dbName.toString()].empty()) {
_dbTaskLists[dbName.toString()].pop_front();
}
_dbTaskLists.erase(dbName.toString());
return;
}
}
_threadPool.schedule([this, name = dbName.toString()](auto status) {
if (ErrorCodes::isCancelationError(status.code())) {
LOG(0) << "Cache loader failed to schedule a persisted metadata update"
<< " task for namespace '" << name << "' due to '" << redact(status)
<< "'. Clearing task list so that scheduling will be attempted by the next"
<< " caller to refresh this namespace.";
{
stdx::lock_guard<Latch> lock(_mutex);
_dbTaskLists.erase(name);
}
return;
}
invariant(status);
_runDbTasks(name);
});
}
void ShardServerCatalogCacheLoader::_updatePersistedCollAndChunksMetadata(
OperationContext* opCtx, const NamespaceString& nss) {
stdx::unique_lock<Latch> lock(_mutex);
const collAndChunkTask& task = _collAndChunkTaskLists[nss].front();
invariant(task.dropped || !task.collectionAndChangedChunks->changedChunks.empty());
// If this task is from an old term and no longer valid, do not execute and return true so that
// the task gets removed from the task list
if (task.termCreated != _term) {
return;
}
lock.unlock();
// Check if this is a drop task
if (task.dropped) {
// The namespace was dropped. The persisted metadata for the collection must be cleared.
uassertStatusOKWithContext(
dropChunksAndDeleteCollectionsEntry(opCtx, nss),
str::stream() << "Failed to clear persisted chunk metadata for collection '" << nss.ns()
<< "'. Will be retried.");
return;
}
uassertStatusOKWithContext(
persistCollectionAndChangedChunks(
opCtx, nss, *task.collectionAndChangedChunks, task.minQueryVersion),
str::stream() << "Failed to update the persisted chunk metadata for collection '"
<< nss.ns() << "' from '" << task.minQueryVersion.toString() << "' to '"
<< task.maxQueryVersion.toString() << "'. Will be retried.");
LOG_CATALOG_REFRESH(1) << "Successfully updated persisted chunk metadata for collection '"
<< nss << "' from '" << task.minQueryVersion
<< "' to collection version '" << task.maxQueryVersion << "'.";
}
void ShardServerCatalogCacheLoader::_updatePersistedDbMetadata(OperationContext* opCtx,
StringData dbName) {
stdx::unique_lock<Latch> lock(_mutex);
const DBTask& task = _dbTaskLists[dbName.toString()].front();
// If this task is from an old term and no longer valid, do not execute and return true so that
// the task gets removed from the task list
if (task.termCreated != _term) {
return;
}
lock.unlock();
// Check if this is a drop task
if (!task.dbType) {
// The database was dropped. The persisted metadata for the collection must be cleared.
uassertStatusOKWithContext(deleteDatabasesEntry(opCtx, dbName),
str::stream() << "Failed to clear persisted metadata for db '"
<< dbName.toString() << "'. Will be retried.");
return;
}
uassertStatusOKWithContext(persistDbVersion(opCtx, *task.dbType),
str::stream() << "Failed to update the persisted metadata for db '"
<< dbName.toString() << "'. Will be retried.");
LOG_CATALOG_REFRESH(1) << "Successfully updated persisted metadata for db "
<< dbName.toString();
}
CollectionAndChangedChunks
ShardServerCatalogCacheLoader::_getCompletePersistedMetadataForSecondarySinceVersion(
OperationContext* opCtx, const NamespaceString& nss, const ChunkVersion& version) {
// Keep trying to load the metadata until we get a complete view without updates being
// concurrently applied.
while (true) {
const auto beginRefreshState = [&]() {
while (true) {
auto notif = _namespaceNotifications.createNotification(nss);
auto refreshState = uassertStatusOK(getPersistedRefreshFlags(opCtx, nss));
if (!refreshState.refreshing) {
return refreshState;
}
notif.get(opCtx);
}
}();
// Load the metadata.
CollectionAndChangedChunks collAndChangedChunks =
getPersistedMetadataSinceVersion(opCtx, nss, version);
// Check that no updates were concurrently applied while we were loading the metadata: this
// could cause the loaded metadata to provide an incomplete view of the chunk ranges.
const auto endRefreshState = uassertStatusOK(getPersistedRefreshFlags(opCtx, nss));
if (beginRefreshState == endRefreshState) {
return collAndChangedChunks;
}
LOG_CATALOG_REFRESH(1)
<< "Cache loader read meatadata while updates were being applied: this metadata may"
<< " be incomplete. Retrying. Refresh state before read: " << beginRefreshState
<< ". Current refresh state: '" << endRefreshState << "'.";
}
}
ShardServerCatalogCacheLoader::collAndChunkTask::collAndChunkTask(
StatusWith<CollectionAndChangedChunks> statusWithCollectionAndChangedChunks,
ChunkVersion minimumQueryVersion,
long long currentTerm)
: taskNum(taskIdGenerator.fetchAndAdd(1)),
minQueryVersion(minimumQueryVersion),
termCreated(currentTerm) {
if (statusWithCollectionAndChangedChunks.isOK()) {
collectionAndChangedChunks = statusWithCollectionAndChangedChunks.getValue();
invariant(!collectionAndChangedChunks->changedChunks.empty());
maxQueryVersion = collectionAndChangedChunks->changedChunks.back().getVersion();
} else {
invariant(statusWithCollectionAndChangedChunks == ErrorCodes::NamespaceNotFound);
dropped = true;
maxQueryVersion = ChunkVersion::UNSHARDED();
}
}
ShardServerCatalogCacheLoader::DBTask::DBTask(StatusWith<DatabaseType> swDatabaseType,
long long currentTerm)
: taskNum(taskIdGenerator.fetchAndAdd(1)), termCreated(currentTerm) {
if (swDatabaseType.isOK()) {
dbType = std::move(swDatabaseType.getValue());
} else {
invariant(swDatabaseType == ErrorCodes::NamespaceNotFound);
}
}
ShardServerCatalogCacheLoader::CollAndChunkTaskList::CollAndChunkTaskList()
: _activeTaskCompletedCondVar(std::make_shared<stdx::condition_variable>()) {}
ShardServerCatalogCacheLoader::DbTaskList::DbTaskList()
: _activeTaskCompletedCondVar(std::make_shared<stdx::condition_variable>()) {}
void ShardServerCatalogCacheLoader::CollAndChunkTaskList::addTask(collAndChunkTask task) {
if (_tasks.empty()) {
_tasks.emplace_back(std::move(task));
return;
}
if (task.dropped) {
invariant(_tasks.back().maxQueryVersion == task.minQueryVersion);
// As an optimization, on collection drop, clear any pending tasks in order to prevent any
// throw-away work from executing. Because we have no way to differentiate whether the
// active tasks is currently being operated on by a thread or not, we must leave the front
// intact.
_tasks.erase(std::next(_tasks.begin()), _tasks.end());
// No need to schedule a drop if one is already currently active.
if (!_tasks.front().dropped) {
_tasks.emplace_back(std::move(task));
}
} else {
// Tasks must have contiguous versions, unless a complete reload occurs.
invariant(_tasks.back().maxQueryVersion == task.minQueryVersion ||
!task.minQueryVersion.isSet());
_tasks.emplace_back(std::move(task));
}
}
void ShardServerCatalogCacheLoader::DbTaskList::addTask(DBTask task) {
if (_tasks.empty()) {
_tasks.emplace_back(std::move(task));
return;
}
if (!task.dbType) {
// As an optimization, on database drop, clear any pending tasks in order to prevent any
// throw-away work from executing. Because we have no way to differentiate whether the
// active tasks is currently being operated on by a thread or not, we must leave the front
// intact.
_tasks.erase(std::next(_tasks.begin()), _tasks.end());
// No need to schedule a drop if one is already currently active.
if (_tasks.front().dbType) {
_tasks.emplace_back(std::move(task));
}
} else {
_tasks.emplace_back(std::move(task));
}
}
void ShardServerCatalogCacheLoader::CollAndChunkTaskList::pop_front() {
invariant(!_tasks.empty());
_tasks.pop_front();
_activeTaskCompletedCondVar->notify_all();
}
void ShardServerCatalogCacheLoader::DbTaskList::pop_front() {
invariant(!_tasks.empty());
_tasks.pop_front();
_activeTaskCompletedCondVar->notify_all();
}
void ShardServerCatalogCacheLoader::CollAndChunkTaskList::waitForActiveTaskCompletion(
stdx::unique_lock<Latch>& lg) {
// Increase the use_count of the condition variable shared pointer, because the entire task list
// might get deleted during the unlocked interval
auto condVar = _activeTaskCompletedCondVar;
condVar->wait(lg);
}
void ShardServerCatalogCacheLoader::DbTaskList::waitForActiveTaskCompletion(
stdx::unique_lock<Latch>& lg) {
// Increase the use_count of the condition variable shared pointer, because the entire task list
// might get deleted during the unlocked interval
auto condVar = _activeTaskCompletedCondVar;
condVar->wait(lg);
}
bool ShardServerCatalogCacheLoader::CollAndChunkTaskList::hasTasksFromThisTerm(
long long term) const {
invariant(!_tasks.empty());
return _tasks.back().termCreated == term;
}
bool ShardServerCatalogCacheLoader::DbTaskList::hasTasksFromThisTerm(long long term) const {
invariant(!_tasks.empty());
return _tasks.back().termCreated == term;
}
ChunkVersion ShardServerCatalogCacheLoader::CollAndChunkTaskList::getHighestVersionEnqueued()
const {
invariant(!_tasks.empty());
return _tasks.back().maxQueryVersion;
}
CollectionAndChangedChunks
ShardServerCatalogCacheLoader::CollAndChunkTaskList::getEnqueuedMetadataForTerm(
const long long term) const {
CollectionAndChangedChunks collAndChunks;
for (const auto& task : _tasks) {
if (task.termCreated != term) {
// Task data is no longer valid. Go on to the next task in the list.
continue;
}
if (task.dropped) {
// A drop task should reset the metadata.
collAndChunks = CollectionAndChangedChunks();
} else {
if (task.collectionAndChangedChunks->epoch != collAndChunks.epoch) {
// An epoch change should reset the metadata and start from the new.
collAndChunks = *task.collectionAndChangedChunks;
} else {
// Epochs match, so the new results should be appended.
// Make sure we do not append a duplicate chunk. The diff query is GTE, so there can
// be duplicates of the same exact versioned chunk across tasks. This is no problem
// for our diff application algorithms, but it can return unpredictable numbers of
// chunks for testing purposes. Eliminate unpredicatable duplicates for testing
// stability.
auto taskCollectionAndChangedChunksIt =
task.collectionAndChangedChunks->changedChunks.begin();
if (collAndChunks.changedChunks.back().getVersion() ==
task.collectionAndChangedChunks->changedChunks.front().getVersion()) {
++taskCollectionAndChangedChunksIt;
}
collAndChunks.changedChunks.insert(
collAndChunks.changedChunks.end(),
taskCollectionAndChangedChunksIt,
task.collectionAndChangedChunks->changedChunks.end());
}
}
}
return collAndChunks;
}
} // namespace mongo
|