/
catalog_manager_replica_set.cpp
1447 lines (1203 loc) · 57.3 KB
/
catalog_manager_replica_set.cpp
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 (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* 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 GNU Affero General 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/s/catalog/replset/catalog_manager_replica_set.h"
#include <pcrecpp.h>
#include "mongo/base/status.h"
#include "mongo/base/status_with.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/bson/util/bson_extract.h"
#include "mongo/client/read_preference.h"
#include "mongo/client/remote_command_targeter.h"
#include "mongo/db/audit.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/optime.h"
#include "mongo/db/repl/read_concern_args.h"
#include "mongo/executor/network_interface.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/rpc/metadata/repl_set_metadata.h"
#include "mongo/s/catalog/config_server_version.h"
#include "mongo/s/catalog/dist_lock_manager.h"
#include "mongo/s/catalog/type_collection.h"
#include "mongo/s/catalog/type_config_version.h"
#include "mongo/s/catalog/type_chunk.h"
#include "mongo/s/catalog/type_database.h"
#include "mongo/s/catalog/type_settings.h"
#include "mongo/s/catalog/type_shard.h"
#include "mongo/s/catalog/type_tags.h"
#include "mongo/s/client/shard.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/chunk_manager.h"
#include "mongo/s/config.h"
#include "mongo/s/grid.h"
#include "mongo/s/set_shard_version_request.h"
#include "mongo/s/shard_key_pattern.h"
#include "mongo/s/write_ops/batched_command_request.h"
#include "mongo/s/write_ops/batched_command_response.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/net/hostandport.h"
#include "mongo/util/time_support.h"
namespace mongo {
MONGO_FP_DECLARE(setDropCollDistLockWait);
using repl::OpTime;
using std::set;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::vector;
using str::stream;
namespace {
const char kWriteConcernField[] = "writeConcern";
const ReadPreferenceSetting kConfigReadSelector(ReadPreference::Nearest, TagSet{});
const ReadPreferenceSetting kConfigPrimaryPreferredSelector(ReadPreference::PrimaryPreferred,
TagSet{});
const WriteConcernOptions kMajorityWriteConcern(WriteConcernOptions::kMajority,
// Note: Even though we're setting UNSET here,
// kMajority implies JOURNAL if journaling is
// supported by mongod and
// writeConcernMajorityJournalDefault is set to true
// in the ReplicaSetConfig.
WriteConcernOptions::SyncMode::UNSET,
Seconds(15));
const int kMaxConfigVersionInitRetry = 3;
const int kMaxReadRetry = 3;
const int kMaxWriteRetry = 3;
void toBatchError(const Status& status, BatchedCommandResponse* response) {
response->clear();
response->setErrCode(status.code());
response->setErrMessage(status.reason());
response->setOk(false);
}
} // namespace
CatalogManagerReplicaSet::CatalogManagerReplicaSet(std::unique_ptr<DistLockManager> distLockManager)
: _distLockManager(std::move(distLockManager)) {}
CatalogManagerReplicaSet::~CatalogManagerReplicaSet() = default;
Status CatalogManagerReplicaSet::startup(OperationContext* txn, bool allowNetworking) {
_distLockManager->startUp();
return Status::OK();
}
void CatalogManagerReplicaSet::shutDown(OperationContext* txn, bool allowNetworking) {
invariant(allowNetworking);
LOG(1) << "CatalogManagerReplicaSet::shutDown() called.";
{
stdx::lock_guard<stdx::mutex> lk(_mutex);
_inShutdown = true;
}
invariant(_distLockManager);
_distLockManager->shutDown(txn, allowNetworking);
}
Status CatalogManagerReplicaSet::shardCollection(OperationContext* txn,
const string& ns,
const ShardKeyPattern& fieldsAndOrder,
bool unique,
const vector<BSONObj>& initPoints,
const set<ShardId>& initShardIds) {
// Lock the collection globally so that no other mongos can try to shard or drop the collection
// at the same time.
auto scopedDistLock = getDistLockManager()->lock(txn, ns, "shardCollection");
if (!scopedDistLock.isOK()) {
return scopedDistLock.getStatus();
}
auto status = getDatabase(txn, nsToDatabase(ns));
if (!status.isOK()) {
return status.getStatus();
}
ShardId dbPrimaryShardId = status.getValue().value.getPrimary();
const auto primaryShard = grid.shardRegistry()->getShard(txn, dbPrimaryShardId);
{
// In 3.0 and prior we include this extra safety check that the collection is not getting
// sharded concurrently by two different mongos instances. It is not 100%-proof, but it
// reduces the chance that two invocations of shard collection will step on each other's
// toes. Now we take the distributed lock so going forward this check won't be necessary
// but we leave it around for compatibility with other mongoses from 3.0.
// TODO(spencer): Remove this after 3.2 ships.
auto countStatus = _runCountCommandOnConfig(
txn, NamespaceString(ChunkType::ConfigNS), BSON(ChunkType::ns(ns)));
if (!countStatus.isOK()) {
return countStatus.getStatus();
}
if (countStatus.getValue() > 0) {
return Status(ErrorCodes::AlreadyInitialized,
str::stream() << "collection " << ns << " already sharded with "
<< countStatus.getValue() << " chunks.");
}
}
// Record start in changelog
{
BSONObjBuilder collectionDetail;
collectionDetail.append("shardKey", fieldsAndOrder.toBSON());
collectionDetail.append("collection", ns);
collectionDetail.append("primary", primaryShard->toString());
{
BSONArrayBuilder initialShards(collectionDetail.subarrayStart("initShards"));
for (const ShardId& shardId : initShardIds) {
initialShards.append(shardId);
}
}
collectionDetail.append("numChunks", static_cast<int>(initPoints.size() + 1));
logChange(txn, "shardCollection.start", ns, collectionDetail.obj());
}
shared_ptr<ChunkManager> manager(new ChunkManager(ns, fieldsAndOrder, unique));
Status createFirstChunksStatus =
manager->createFirstChunks(txn, dbPrimaryShardId, &initPoints, &initShardIds);
if (!createFirstChunksStatus.isOK()) {
return createFirstChunksStatus;
}
manager->loadExistingRanges(txn, nullptr);
CollectionInfo collInfo;
collInfo.useChunkManager(manager);
collInfo.save(txn, ns);
// Tell the primary mongod to refresh its data
// TODO: Think the real fix here is for mongos to just
// assume that all collections are sharded, when we get there
SetShardVersionRequest ssv = SetShardVersionRequest::makeForVersioningNoPersist(
grid.shardRegistry()->getConfigServerConnectionString(),
dbPrimaryShardId,
primaryShard->getConnString(),
NamespaceString(ns),
manager->getVersion(),
true);
auto ssvStatus = grid.shardRegistry()->runIdempotentCommandOnShard(
txn,
dbPrimaryShardId,
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
"admin",
ssv.toBSON());
if (!ssvStatus.isOK()) {
warning() << "could not update initial version of " << ns << " on shard primary "
<< dbPrimaryShardId << ssvStatus.getStatus();
}
logChange(txn, "shardCollection.end", ns, BSON("version" << manager->getVersion().toString()));
return Status::OK();
}
StatusWith<ShardDrainingStatus> CatalogManagerReplicaSet::removeShard(OperationContext* txn,
const std::string& name) {
// Check preconditions for removing the shard
auto countStatus = _runCountCommandOnConfig(
txn,
NamespaceString(ShardType::ConfigNS),
BSON(ShardType::name() << NE << name << ShardType::draining(true)));
if (!countStatus.isOK()) {
return countStatus.getStatus();
}
if (countStatus.getValue() > 0) {
return Status(ErrorCodes::ConflictingOperationInProgress,
"Can't have more than one draining shard at a time");
}
countStatus = _runCountCommandOnConfig(
txn, NamespaceString(ShardType::ConfigNS), BSON(ShardType::name() << NE << name));
if (!countStatus.isOK()) {
return countStatus.getStatus();
}
if (countStatus.getValue() == 0) {
return Status(ErrorCodes::IllegalOperation, "Can't remove last shard");
}
// Figure out if shard is already draining
countStatus =
_runCountCommandOnConfig(txn,
NamespaceString(ShardType::ConfigNS),
BSON(ShardType::name() << name << ShardType::draining(true)));
if (!countStatus.isOK()) {
return countStatus.getStatus();
}
if (countStatus.getValue() == 0) {
log() << "going to start draining shard: " << name;
auto updateStatus = updateConfigDocument(txn,
ShardType::ConfigNS,
BSON(ShardType::name() << name),
BSON("$set" << BSON(ShardType::draining(true))),
false);
if (!updateStatus.isOK()) {
log() << "error starting removeShard: " << name << causedBy(updateStatus.getStatus());
return updateStatus.getStatus();
}
grid.shardRegistry()->reload(txn);
// Record start in changelog
logChange(txn, "removeShard.start", "", BSON("shard" << name));
return ShardDrainingStatus::STARTED;
}
// Draining has already started, now figure out how many chunks and databases are still on the
// shard.
countStatus = _runCountCommandOnConfig(
txn, NamespaceString(ChunkType::ConfigNS), BSON(ChunkType::shard(name)));
if (!countStatus.isOK()) {
return countStatus.getStatus();
}
const long long chunkCount = countStatus.getValue();
countStatus = _runCountCommandOnConfig(
txn, NamespaceString(DatabaseType::ConfigNS), BSON(DatabaseType::primary(name)));
if (!countStatus.isOK()) {
return countStatus.getStatus();
}
const long long databaseCount = countStatus.getValue();
if (chunkCount > 0 || databaseCount > 0) {
// Still more draining to do
return ShardDrainingStatus::ONGOING;
}
// Draining is done, now finish removing the shard.
log() << "going to remove shard: " << name;
audit::logRemoveShard(txn->getClient(), name);
Status status =
removeConfigDocuments(txn, ShardType::ConfigNS, BSON(ShardType::name() << name));
if (!status.isOK()) {
log() << "Error concluding removeShard operation on: " << name
<< "; err: " << status.reason();
return status;
}
grid.shardRegistry()->remove(name);
grid.shardRegistry()->reload(txn);
// Record finish in changelog
logChange(txn, "removeShard", "", BSON("shard" << name));
return ShardDrainingStatus::COMPLETED;
}
StatusWith<OpTimePair<DatabaseType>> CatalogManagerReplicaSet::getDatabase(
OperationContext* txn, const std::string& dbName) {
if (!NamespaceString::validDBName(dbName)) {
return {ErrorCodes::InvalidNamespace, stream() << dbName << " is not a valid db name"};
}
// The two databases that are hosted on the config server are config and admin
if (dbName == "config" || dbName == "admin") {
DatabaseType dbt;
dbt.setName(dbName);
dbt.setSharded(false);
dbt.setPrimary("config");
return OpTimePair<DatabaseType>(dbt);
}
auto result = _fetchDatabaseMetadata(txn, dbName, kConfigReadSelector);
if (result == ErrorCodes::NamespaceNotFound) {
// If we failed to find the database metadata on the 'nearest' config server, try again
// against the primary, in case the database was recently created.
result =
_fetchDatabaseMetadata(txn, dbName, ReadPreferenceSetting{ReadPreference::PrimaryOnly});
if (!result.isOK() && (result != ErrorCodes::NamespaceNotFound)) {
return Status(result.getStatus().code(),
str::stream() << "Could not confirm non-existence of database \""
<< dbName
<< "\" due to inability to query the config server primary"
<< causedBy(result.getStatus()));
}
}
return result;
}
StatusWith<OpTimePair<DatabaseType>> CatalogManagerReplicaSet::_fetchDatabaseMetadata(
OperationContext* txn, const std::string& dbName, const ReadPreferenceSetting& readPref) {
dassert(dbName != "admin" && dbName != "config");
auto findStatus = _exhaustiveFindOnConfig(txn,
readPref,
NamespaceString(DatabaseType::ConfigNS),
BSON(DatabaseType::name(dbName)),
BSONObj(),
1);
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
const auto& docsWithOpTime = findStatus.getValue();
if (docsWithOpTime.value.empty()) {
return {ErrorCodes::NamespaceNotFound, stream() << "database " << dbName << " not found"};
}
invariant(docsWithOpTime.value.size() == 1);
auto parseStatus = DatabaseType::fromBSON(docsWithOpTime.value.front());
if (!parseStatus.isOK()) {
return parseStatus.getStatus();
}
return OpTimePair<DatabaseType>(parseStatus.getValue(), docsWithOpTime.opTime);
}
StatusWith<OpTimePair<CollectionType>> CatalogManagerReplicaSet::getCollection(
OperationContext* txn, const std::string& collNs) {
auto statusFind = _exhaustiveFindOnConfig(txn,
kConfigReadSelector,
NamespaceString(CollectionType::ConfigNS),
BSON(CollectionType::fullNs(collNs)),
BSONObj(),
1);
if (!statusFind.isOK()) {
return statusFind.getStatus();
}
const auto& retOpTimePair = statusFind.getValue();
const auto& retVal = retOpTimePair.value;
if (retVal.empty()) {
return Status(ErrorCodes::NamespaceNotFound,
stream() << "collection " << collNs << " not found");
}
invariant(retVal.size() == 1);
auto parseStatus = CollectionType::fromBSON(retVal.front());
if (!parseStatus.isOK()) {
return parseStatus.getStatus();
}
return OpTimePair<CollectionType>(parseStatus.getValue(), retOpTimePair.opTime);
}
Status CatalogManagerReplicaSet::getCollections(OperationContext* txn,
const std::string* dbName,
std::vector<CollectionType>* collections,
OpTime* opTime) {
BSONObjBuilder b;
if (dbName) {
invariant(!dbName->empty());
b.appendRegex(CollectionType::fullNs(),
string(str::stream() << "^" << pcrecpp::RE::QuoteMeta(*dbName) << "\\."));
}
auto findStatus = _exhaustiveFindOnConfig(txn,
kConfigReadSelector,
NamespaceString(CollectionType::ConfigNS),
b.obj(),
BSONObj(),
boost::none); // no limit
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
const auto& docsOpTimePair = findStatus.getValue();
for (const BSONObj& obj : docsOpTimePair.value) {
const auto collectionResult = CollectionType::fromBSON(obj);
if (!collectionResult.isOK()) {
collections->clear();
return {ErrorCodes::FailedToParse,
str::stream() << "error while parsing " << CollectionType::ConfigNS
<< " document: " << obj << " : "
<< collectionResult.getStatus().toString()};
}
collections->push_back(collectionResult.getValue());
}
if (opTime) {
*opTime = docsOpTimePair.opTime;
}
return Status::OK();
}
Status CatalogManagerReplicaSet::dropCollection(OperationContext* txn, const NamespaceString& ns) {
logChange(txn, "dropCollection.start", ns.ns(), BSONObj());
auto shardsStatus = getAllShards(txn);
if (!shardsStatus.isOK()) {
return shardsStatus.getStatus();
}
vector<ShardType> allShards = std::move(shardsStatus.getValue().value);
LOG(1) << "dropCollection " << ns << " started";
// Lock the collection globally so that split/migrate cannot run
stdx::chrono::seconds waitFor(DistLockManager::kDefaultLockTimeout);
MONGO_FAIL_POINT_BLOCK(setDropCollDistLockWait, customWait) {
const BSONObj& data = customWait.getData();
waitFor = stdx::chrono::seconds(data["waitForSecs"].numberInt());
}
auto scopedDistLock = getDistLockManager()->lock(txn, ns.ns(), "drop", waitFor);
if (!scopedDistLock.isOK()) {
return scopedDistLock.getStatus();
}
LOG(1) << "dropCollection " << ns << " locked";
std::map<string, BSONObj> errors;
auto* shardRegistry = grid.shardRegistry();
for (const auto& shardEntry : allShards) {
auto dropResult = shardRegistry->runIdempotentCommandOnShard(
txn,
shardEntry.getName(),
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
ns.db().toString(),
BSON("drop" << ns.coll()));
if (!dropResult.isOK()) {
return dropResult.getStatus();
}
auto dropStatus = getStatusFromCommandResult(dropResult.getValue());
if (!dropStatus.isOK()) {
if (dropStatus.code() == ErrorCodes::NamespaceNotFound) {
continue;
}
errors.emplace(shardEntry.getHost(), dropResult.getValue());
}
}
if (!errors.empty()) {
StringBuilder sb;
sb << "Dropping collection failed on the following hosts: ";
for (auto it = errors.cbegin(); it != errors.cend(); ++it) {
if (it != errors.cbegin()) {
sb << ", ";
}
sb << it->first << ": " << it->second;
}
return {ErrorCodes::OperationFailed, sb.str()};
}
LOG(1) << "dropCollection " << ns << " shard data deleted";
// Remove chunk data
Status result = removeConfigDocuments(txn, ChunkType::ConfigNS, BSON(ChunkType::ns(ns.ns())));
if (!result.isOK()) {
return result;
}
LOG(1) << "dropCollection " << ns << " chunk data deleted";
// Mark the collection as dropped
CollectionType coll;
coll.setNs(ns);
coll.setDropped(true);
coll.setEpoch(ChunkVersion::DROPPED().epoch());
coll.setUpdatedAt(grid.shardRegistry()->getNetwork()->now());
result = updateCollection(txn, ns.ns(), coll);
if (!result.isOK()) {
return result;
}
LOG(1) << "dropCollection " << ns << " collection marked as dropped";
for (const auto& shardEntry : allShards) {
SetShardVersionRequest ssv = SetShardVersionRequest::makeForVersioningNoPersist(
grid.shardRegistry()->getConfigServerConnectionString(),
shardEntry.getName(),
fassertStatusOK(28781, ConnectionString::parse(shardEntry.getHost())),
ns,
ChunkVersion::DROPPED(),
true);
auto ssvResult = shardRegistry->runIdempotentCommandOnShard(
txn,
shardEntry.getName(),
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
"admin",
ssv.toBSON());
if (!ssvResult.isOK()) {
return ssvResult.getStatus();
}
auto ssvStatus = getStatusFromCommandResult(ssvResult.getValue());
if (!ssvStatus.isOK()) {
return ssvStatus;
}
auto unsetShardingStatus = shardRegistry->runIdempotentCommandOnShard(
txn,
shardEntry.getName(),
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
"admin",
BSON("unsetSharding" << 1));
if (!unsetShardingStatus.isOK()) {
return unsetShardingStatus.getStatus();
}
auto unsetShardingResult = getStatusFromCommandResult(unsetShardingStatus.getValue());
if (!unsetShardingResult.isOK()) {
return unsetShardingResult;
}
}
LOG(1) << "dropCollection " << ns << " completed";
logChange(txn, "dropCollection", ns.ns(), BSONObj());
return Status::OK();
}
StatusWith<SettingsType> CatalogManagerReplicaSet::getGlobalSettings(OperationContext* txn,
const string& key) {
auto findStatus = _exhaustiveFindOnConfig(txn,
kConfigReadSelector,
NamespaceString(SettingsType::ConfigNS),
BSON(SettingsType::key(key)),
BSONObj(),
1);
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
const auto& docs = findStatus.getValue().value;
if (docs.empty()) {
return {ErrorCodes::NoMatchingDocument,
str::stream() << "can't find settings document with key: " << key};
}
BSONObj settingsDoc = docs.front();
StatusWith<SettingsType> settingsResult = SettingsType::fromBSON(settingsDoc);
if (!settingsResult.isOK()) {
return {ErrorCodes::FailedToParse,
str::stream() << "error while parsing settings document: " << settingsDoc << " : "
<< settingsResult.getStatus().toString()};
}
const SettingsType& settings = settingsResult.getValue();
Status validationStatus = settings.validate();
if (!validationStatus.isOK()) {
return validationStatus;
}
return settingsResult;
}
Status CatalogManagerReplicaSet::getDatabasesForShard(OperationContext* txn,
const string& shardName,
vector<string>* dbs) {
auto findStatus = _exhaustiveFindOnConfig(txn,
kConfigReadSelector,
NamespaceString(DatabaseType::ConfigNS),
BSON(DatabaseType::primary(shardName)),
BSONObj(),
boost::none); // no limit
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
for (const BSONObj& obj : findStatus.getValue().value) {
string dbName;
Status status = bsonExtractStringField(obj, DatabaseType::name(), &dbName);
if (!status.isOK()) {
dbs->clear();
return status;
}
dbs->push_back(dbName);
}
return Status::OK();
}
Status CatalogManagerReplicaSet::getChunks(OperationContext* txn,
const BSONObj& query,
const BSONObj& sort,
boost::optional<int> limit,
vector<ChunkType>* chunks,
OpTime* opTime) {
chunks->clear();
// Convert boost::optional<int> to boost::optional<long long>.
auto longLimit = limit ? boost::optional<long long>(*limit) : boost::none;
auto findStatus = _exhaustiveFindOnConfig(
txn, kConfigReadSelector, NamespaceString(ChunkType::ConfigNS), query, sort, longLimit);
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
const auto chunkDocsOpTimePair = findStatus.getValue();
for (const BSONObj& obj : chunkDocsOpTimePair.value) {
auto chunkRes = ChunkType::fromBSON(obj);
if (!chunkRes.isOK()) {
chunks->clear();
return {ErrorCodes::FailedToParse,
stream() << "Failed to parse chunk with id ("
<< obj[ChunkType::name()].toString()
<< "): " << chunkRes.getStatus().toString()};
}
chunks->push_back(chunkRes.getValue());
}
if (opTime) {
*opTime = chunkDocsOpTimePair.opTime;
}
return Status::OK();
}
Status CatalogManagerReplicaSet::getTagsForCollection(OperationContext* txn,
const std::string& collectionNs,
std::vector<TagsType>* tags) {
tags->clear();
auto findStatus = _exhaustiveFindOnConfig(txn,
kConfigReadSelector,
NamespaceString(TagsType::ConfigNS),
BSON(TagsType::ns(collectionNs)),
BSON(TagsType::min() << 1),
boost::none); // no limit
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
for (const BSONObj& obj : findStatus.getValue().value) {
auto tagRes = TagsType::fromBSON(obj);
if (!tagRes.isOK()) {
tags->clear();
return Status(ErrorCodes::FailedToParse,
str::stream()
<< "Failed to parse tag: " << tagRes.getStatus().toString());
}
tags->push_back(tagRes.getValue());
}
return Status::OK();
}
StatusWith<string> CatalogManagerReplicaSet::getTagForChunk(OperationContext* txn,
const std::string& collectionNs,
const ChunkType& chunk) {
BSONObj query =
BSON(TagsType::ns(collectionNs) << TagsType::min() << BSON("$lte" << chunk.getMin())
<< TagsType::max() << BSON("$gte" << chunk.getMax()));
auto findStatus = _exhaustiveFindOnConfig(
txn, kConfigReadSelector, NamespaceString(TagsType::ConfigNS), query, BSONObj(), 1);
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
const auto& docs = findStatus.getValue().value;
if (docs.empty()) {
return string{};
}
invariant(docs.size() == 1);
BSONObj tagsDoc = docs.front();
const auto tagsResult = TagsType::fromBSON(tagsDoc);
if (!tagsResult.isOK()) {
return {ErrorCodes::FailedToParse,
stream() << "error while parsing " << TagsType::ConfigNS << " document: " << tagsDoc
<< " : " << tagsResult.getStatus().toString()};
}
return tagsResult.getValue().getTag();
}
StatusWith<OpTimePair<std::vector<ShardType>>> CatalogManagerReplicaSet::getAllShards(
OperationContext* txn) {
std::vector<ShardType> shards;
auto findStatus = _exhaustiveFindOnConfig(txn,
kConfigReadSelector,
NamespaceString(ShardType::ConfigNS),
BSONObj(), // no query filter
BSONObj(), // no sort
boost::none); // no limit
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
for (const BSONObj& doc : findStatus.getValue().value) {
auto shardRes = ShardType::fromBSON(doc);
if (!shardRes.isOK()) {
shards.clear();
return {ErrorCodes::FailedToParse,
stream() << "Failed to parse shard with id ("
<< doc[ShardType::name()].toString() << ")"
<< causedBy(shardRes.getStatus())};
}
Status validateStatus = shardRes.getValue().validate();
if (!validateStatus.isOK()) {
return {validateStatus.code(),
stream() << "Failed to validate shard with id ("
<< doc[ShardType::name()].toString() << ")"
<< causedBy(validateStatus)};
}
shards.push_back(shardRes.getValue());
}
return OpTimePair<std::vector<ShardType>>{std::move(shards), findStatus.getValue().opTime};
}
bool CatalogManagerReplicaSet::runUserManagementWriteCommand(OperationContext* txn,
const std::string& commandName,
const std::string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder* result) {
BSONObj cmdToRun = cmdObj;
{
// Make sure that if the command has a write concern that it is w:1 or w:majority, and
// convert w:1 or no write concern to w:majority before sending.
WriteConcernOptions writeConcern;
writeConcern.reset();
const char* writeConcernFieldName = "writeConcern";
BSONElement writeConcernElement = cmdObj[writeConcernFieldName];
bool initialCmdHadWriteConcern = !writeConcernElement.eoo();
if (initialCmdHadWriteConcern) {
Status status = writeConcern.parse(writeConcernElement.Obj());
if (!status.isOK()) {
return Command::appendCommandStatus(*result, status);
}
if (!writeConcern.validForConfigServers()) {
return Command::appendCommandStatus(
*result,
Status(ErrorCodes::InvalidOptions,
str::stream()
<< "Invalid replication write concern. Writes to config server "
"replica sets must use w:'majority', got: "
<< writeConcern.toBSON()));
}
}
writeConcern.wMode = WriteConcernOptions::kMajority;
writeConcern.wNumNodes = 0;
BSONObjBuilder modifiedCmd;
if (!initialCmdHadWriteConcern) {
modifiedCmd.appendElements(cmdObj);
} else {
BSONObjIterator cmdObjIter(cmdObj);
while (cmdObjIter.more()) {
BSONElement e = cmdObjIter.next();
if (str::equals(e.fieldName(), writeConcernFieldName)) {
continue;
}
modifiedCmd.append(e);
}
}
modifiedCmd.append(writeConcernFieldName, writeConcern.toBSON());
cmdToRun = modifiedCmd.obj();
}
auto response = grid.shardRegistry()->runCommandOnConfigWithRetries(
txn, dbname, cmdToRun, ShardRegistry::kNotMasterErrors);
if (!response.isOK()) {
return Command::appendCommandStatus(*result, response.getStatus());
}
result->appendElements(response.getValue());
return Command::getStatusFromCommandResult(response.getValue()).isOK();
}
bool CatalogManagerReplicaSet::runReadCommandForTest(OperationContext* txn,
const std::string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder* result) {
BSONObjBuilder cmdBuilder;
cmdBuilder.appendElements(cmdObj);
_appendReadConcern(&cmdBuilder);
auto resultStatus = grid.shardRegistry()->runIdempotentCommandOnConfig(
txn, kConfigReadSelector, dbname, cmdBuilder.done());
if (resultStatus.isOK()) {
result->appendElements(resultStatus.getValue());
return Command::getStatusFromCommandResult(resultStatus.getValue()).isOK();
}
return Command::appendCommandStatus(*result, resultStatus.getStatus());
}
bool CatalogManagerReplicaSet::runUserManagementReadCommand(OperationContext* txn,
const std::string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder* result) {
auto resultStatus = grid.shardRegistry()->runIdempotentCommandOnConfig(
txn, kConfigPrimaryPreferredSelector, dbname, cmdObj);
if (resultStatus.isOK()) {
result->appendElements(resultStatus.getValue());
return Command::getStatusFromCommandResult(resultStatus.getValue()).isOK();
}
return Command::appendCommandStatus(*result, resultStatus.getStatus());
}
Status CatalogManagerReplicaSet::applyChunkOpsDeprecated(OperationContext* txn,
const BSONArray& updateOps,
const BSONArray& preCondition,
const std::string& nss,
const ChunkVersion& lastChunkVersion) {
BSONObj cmd = BSON("applyOps" << updateOps << "preCondition" << preCondition
<< kWriteConcernField << kMajorityWriteConcern.toBSON());
auto response = grid.shardRegistry()->runCommandOnConfigWithRetries(
txn, "config", cmd, ShardRegistry::kAllRetriableErrors);
if (!response.isOK()) {
return response.getStatus();
}
Status status = Command::getStatusFromCommandResult(response.getValue());
if (MONGO_FAIL_POINT(failApplyChunkOps)) {
status = Status(ErrorCodes::InternalError, "Failpoint 'failApplyChunkOps' generated error");
}
if (!status.isOK()) {
string errMsg;
// This could be a blip in the network connectivity. Check if the commit request made it.
//
// If all the updates were successfully written to the chunks collection, the last
// document in the list of updates should be returned from a query to the chunks
// collection. The last chunk can be identified by namespace and version number.
warning() << "chunk operation commit failed and metadata will be revalidated"
<< causedBy(status);
// Look for the chunk in this shard whose version got bumped. We assume that if that
// mod made it to the config server, then applyOps was successful.
std::vector<ChunkType> newestChunk;
BSONObjBuilder query;
lastChunkVersion.addToBSON(query, ChunkType::DEPRECATED_lastmod());
query.append(ChunkType::ns(), nss);
Status chunkStatus = getChunks(txn, query.obj(), BSONObj(), 1, &newestChunk, nullptr);
if (!chunkStatus.isOK()) {
warning() << "getChunks function failed, unable to validate chunk operation metadata"
<< causedBy(chunkStatus);
errMsg = str::stream() << "getChunks function failed, unable to validate chunk "
<< "operation metadata: " << causedBy(chunkStatus)
<< ". applyChunkOpsDeprecated failed to get confirmation "
<< "of commit. Unable to save chunk ops. Command: " << cmd
<< ". Result: " << response.getValue();
} else if (!newestChunk.empty()) {
invariant(newestChunk.size() == 1);
log() << "chunk operation commit confirmed";
return Status::OK();
} else {
errMsg = str::stream() << "chunk operation commit failed: version "
<< lastChunkVersion.toString() << " doesn't exist in namespace"
<< nss << ". Unable to save chunk ops. Command: " << cmd
<< ". Result: " << response.getValue();
}
return Status(status.code(), errMsg);
}
return Status::OK();
}
DistLockManager* CatalogManagerReplicaSet::getDistLockManager() {
invariant(_distLockManager);
return _distLockManager.get();
}
void CatalogManagerReplicaSet::writeConfigServerDirect(OperationContext* txn,
const BatchedCommandRequest& batchRequest,
BatchedCommandResponse* batchResponse) {
// We only support batch sizes of one for config writes
if (batchRequest.sizeWriteOps() != 1) {
toBatchError(Status(ErrorCodes::InvalidOptions,
str::stream() << "Writes to config servers must have batch size of 1, "
<< "found " << batchRequest.sizeWriteOps()),
batchResponse);
return;
}
_runBatchWriteCommand(txn, batchRequest, batchResponse, ShardRegistry::kNotMasterErrors);
}
void CatalogManagerReplicaSet::_runBatchWriteCommand(
OperationContext* txn,
const BatchedCommandRequest& batchRequest,
BatchedCommandResponse* batchResponse,
const ShardRegistry::ErrorCodesSet& errorsToCheck) {
const std::string dbname = batchRequest.getNS().db().toString();
invariant(dbname == "config" || dbname == "admin");
invariant(batchRequest.sizeWriteOps() == 1);
const BSONObj cmdObj = batchRequest.toBSON();
for (int retry = 1; retry <= kMaxWriteRetry; ++retry) {
// runCommandOnConfigWithRetries already does its own retries based on the generic command
// errors. If this fails, we know that it has done all the retries that it could do so there
// is no need to retry anymore.
auto response =
grid.shardRegistry()->runCommandOnConfigWithRetries(txn, dbname, cmdObj, errorsToCheck);
if (!response.isOK()) {
toBatchError(response.getStatus(), batchResponse);
return;
}