/
sharding_catalog_manager_impl.cpp
1981 lines (1682 loc) · 82 KB
/
sharding_catalog_manager_impl.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/sharding_catalog_manager_impl.h"
#include <iomanip>
#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/connection_string.h"
#include "mongo/client/read_preference.h"
#include "mongo/client/remote_command_targeter.h"
#include "mongo/client/replica_set_monitor.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/feature_compatibility_version.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/db/s/type_shard_identity.h"
#include "mongo/db/wire_version.h"
#include "mongo/executor/network_interface.h"
#include "mongo/executor/task_executor.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/s/balancer/balancer_policy.h"
#include "mongo/s/balancer/type_migration.h"
#include "mongo/s/catalog/config_server_version.h"
#include "mongo/s/catalog/sharding_catalog_client.h"
#include "mongo/s/catalog/type_collection.h"
#include "mongo/s/catalog/type_config_version.h"
#include "mongo/s/catalog/type_database.h"
#include "mongo/s/catalog/type_lockpings.h"
#include "mongo/s/catalog/type_locks.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/cluster_identity_loader.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/stdx/memory.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/scopeguard.h"
namespace mongo {
MONGO_FP_DECLARE(dontUpsertShardIdentityOnNewShards);
using std::string;
using std::vector;
using str::stream;
namespace {
using CallbackHandle = executor::TaskExecutor::CallbackHandle;
using CallbackArgs = executor::TaskExecutor::CallbackArgs;
using RemoteCommandCallbackArgs = executor::TaskExecutor::RemoteCommandCallbackArgs;
using RemoteCommandCallbackFn = executor::TaskExecutor::RemoteCommandCallbackFn;
const Seconds kDefaultFindHostMaxWaitTime(20);
const ReadPreferenceSetting kConfigReadSelector(ReadPreference::Nearest, TagSet{});
const ReadPreferenceSetting kConfigPrimarySelector(ReadPreference::PrimaryOnly);
const WriteConcernOptions kNoWaitWriteConcern(1, WriteConcernOptions::SyncMode::UNSET, Seconds(0));
/**
* Append min, max and version information from chunk to the buffer for logChange purposes.
*/
void _appendShortVersion(BufBuilder* b, const ChunkType& chunk) {
BSONObjBuilder bb(*b);
bb.append(ChunkType::min(), chunk.getMin());
bb.append(ChunkType::max(), chunk.getMax());
if (chunk.isVersionSet())
chunk.getVersion().addToBSON(bb, ChunkType::DEPRECATED_lastmod());
bb.done();
}
/**
* Checks if the given key range for the given namespace conflicts with an existing key range.
* Note: range should have the full shard key.
* Returns ErrorCodes::RangeOverlapConflict is an overlap is detected.
*/
Status checkForOveralappedZonedKeyRange(OperationContext* txn,
Shard* configServer,
const NamespaceString& ns,
const ChunkRange& range,
const string& zoneName,
const KeyPattern& shardKeyPattern) {
DistributionStatus chunkDist(ns, ShardToChunksMap{});
auto tagStatus = configServer->exhaustiveFindOnConfig(txn,
kConfigPrimarySelector,
repl::ReadConcernLevel::kLocalReadConcern,
NamespaceString(TagsType::ConfigNS),
BSON(TagsType::ns(ns.ns())),
BSONObj(),
0);
if (!tagStatus.isOK()) {
return tagStatus.getStatus();
}
const auto& tagDocList = tagStatus.getValue().docs;
for (const auto& tagDoc : tagDocList) {
auto tagParseStatus = TagsType::fromBSON(tagDoc);
if (!tagParseStatus.isOK()) {
return tagParseStatus.getStatus();
}
// Always extend ranges to full shard key to be compatible with tags created before
// the zone commands were implemented.
const auto& parsedTagDoc = tagParseStatus.getValue();
auto overlapStatus = chunkDist.addRangeToZone(
ZoneRange(shardKeyPattern.extendRangeBound(parsedTagDoc.getMinKey(), false),
shardKeyPattern.extendRangeBound(parsedTagDoc.getMaxKey(), false),
parsedTagDoc.getTag()));
if (!overlapStatus.isOK()) {
return overlapStatus;
}
}
auto overlapStatus =
chunkDist.addRangeToZone(ZoneRange(range.getMin(), range.getMax(), zoneName));
if (!overlapStatus.isOK()) {
return overlapStatus;
}
return Status::OK();
}
/**
* Returns a new range based on the given range with the full shard key.
* Returns:
* - ErrorCodes::NamespaceNotSharded if ns is not sharded.
* - ErrorCodes::ShardKeyNotFound if range is not compatible (for example, not a prefix of shard
* key) with the shard key of ns.
*/
StatusWith<ChunkRange> includeFullShardKey(OperationContext* txn,
Shard* configServer,
const NamespaceString& ns,
const ChunkRange& range,
KeyPattern* shardKeyPatternOut) {
auto findCollStatus =
configServer->exhaustiveFindOnConfig(txn,
kConfigPrimarySelector,
repl::ReadConcernLevel::kLocalReadConcern,
NamespaceString(CollectionType::ConfigNS),
BSON(CollectionType::fullNs(ns.ns())),
BSONObj(),
1);
if (!findCollStatus.isOK()) {
return findCollStatus.getStatus();
}
const auto& findCollResult = findCollStatus.getValue().docs;
if (findCollResult.size() < 1) {
return {ErrorCodes::NamespaceNotSharded, str::stream() << ns.ns() << " is not sharded"};
}
auto parseStatus = CollectionType::fromBSON(findCollResult.front());
if (!parseStatus.isOK()) {
return parseStatus.getStatus();
}
auto collDoc = parseStatus.getValue();
if (collDoc.getDropped()) {
return {ErrorCodes::NamespaceNotSharded, str::stream() << ns.ns() << " is not sharded"};
}
const auto& shardKeyPattern = collDoc.getKeyPattern();
const auto& shardKeyBSON = shardKeyPattern.toBSON();
*shardKeyPatternOut = shardKeyPattern;
if (!range.getMin().isFieldNamePrefixOf(shardKeyBSON)) {
return {ErrorCodes::ShardKeyNotFound,
str::stream() << "min: " << range.getMin() << " is not a prefix of the shard key "
<< shardKeyBSON
<< " of ns: "
<< ns.ns()};
}
if (!range.getMax().isFieldNamePrefixOf(shardKeyBSON)) {
return {ErrorCodes::ShardKeyNotFound,
str::stream() << "max: " << range.getMax() << " is not a prefix of the shard key "
<< shardKeyBSON
<< " of ns: "
<< ns.ns()};
}
return ChunkRange(shardKeyPattern.extendRangeBound(range.getMin(), false),
shardKeyPattern.extendRangeBound(range.getMax(), false));
}
BSONArray _buildMergeChunksApplyOpsUpdates(const std::vector<ChunkType>& chunksToMerge,
const ChunkVersion& mergeVersion) {
BSONArrayBuilder updates;
// Build an update operation to expand the first chunk into the newly merged chunk
{
BSONObjBuilder op;
op.append("op", "u");
op.appendBool("b", false); // no upsert
op.append("ns", ChunkType::ConfigNS);
// expand first chunk into newly merged chunk
ChunkType mergedChunk(chunksToMerge.front());
mergedChunk.setMax(chunksToMerge.back().getMax());
// fill in additional details for sending through applyOps
mergedChunk.setVersion(mergeVersion);
// add the new chunk information as the update object
op.append("o", mergedChunk.toBSON());
// query object
op.append("o2", BSON(ChunkType::name(mergedChunk.getName())));
updates.append(op.obj());
}
// Build update operations to delete the rest of the chunks to be merged. Remember not
// to delete the first chunk we're expanding
for (size_t i = 1; i < chunksToMerge.size(); ++i) {
BSONObjBuilder op;
op.append("op", "d");
op.append("ns", ChunkType::ConfigNS);
op.append("o", BSON(ChunkType::name(chunksToMerge[i].getName())));
updates.append(op.obj());
}
return updates.arr();
}
BSONArray _buildMergeChunksApplyOpsPrecond(const std::vector<ChunkType>& chunksToMerge,
const ChunkVersion& collVersion) {
BSONArrayBuilder preCond;
for (auto chunk : chunksToMerge) {
BSONObjBuilder b;
b.append("ns", ChunkType::ConfigNS);
b.append(
"q",
BSON("query" << BSON(ChunkType::ns(chunk.getNS()) << ChunkType::min(chunk.getMin())
<< ChunkType::max(chunk.getMax()))
<< "orderby"
<< BSON(ChunkType::DEPRECATED_lastmod() << -1)));
b.append("res",
BSON(ChunkType::DEPRECATED_epoch(collVersion.epoch())
<< ChunkType::shard(chunk.getShard().toString())));
preCond.append(b.obj());
}
return preCond.arr();
}
} // namespace
ShardingCatalogManagerImpl::ShardingCatalogManagerImpl(
ShardingCatalogClient* catalogClient, std::unique_ptr<executor::TaskExecutor> addShardExecutor)
: _catalogClient(catalogClient), _executorForAddShard(std::move(addShardExecutor)) {}
ShardingCatalogManagerImpl::~ShardingCatalogManagerImpl() = default;
Status ShardingCatalogManagerImpl::startup() {
stdx::lock_guard<stdx::mutex> lk(_mutex);
if (_started) {
return Status::OK();
}
_started = true;
_executorForAddShard->startup();
return Status::OK();
}
void ShardingCatalogManagerImpl::shutDown(OperationContext* txn) {
LOG(1) << "ShardingCatalogManagerImpl::shutDown() called.";
{
stdx::lock_guard<stdx::mutex> lk(_mutex);
_inShutdown = true;
}
_executorForAddShard->shutdown();
_executorForAddShard->join();
}
StatusWith<Shard::CommandResponse> ShardingCatalogManagerImpl::_runCommandForAddShard(
OperationContext* txn,
RemoteCommandTargeter* targeter,
const std::string& dbName,
const BSONObj& cmdObj) {
auto host = targeter->findHost(txn, ReadPreferenceSetting{ReadPreference::PrimaryOnly});
if (!host.isOK()) {
return host.getStatus();
}
executor::RemoteCommandRequest request(
host.getValue(), dbName, cmdObj, rpc::makeEmptyMetadata(), nullptr, Seconds(30));
executor::RemoteCommandResponse swResponse =
Status(ErrorCodes::InternalError, "Internal error running command");
auto callStatus = _executorForAddShard->scheduleRemoteCommand(
request, [&swResponse](const executor::TaskExecutor::RemoteCommandCallbackArgs& args) {
swResponse = args.response;
});
if (!callStatus.isOK()) {
return callStatus.getStatus();
}
// Block until the command is carried out
_executorForAddShard->wait(callStatus.getValue());
if (!swResponse.isOK()) {
if (swResponse.status.compareCode(ErrorCodes::ExceededTimeLimit)) {
LOG(0) << "Operation for addShard timed out with status " << swResponse.status;
}
return swResponse.status;
}
BSONObj responseObj = swResponse.data.getOwned();
BSONObj responseMetadata = swResponse.metadata.getOwned();
Status commandStatus = getStatusFromCommandResult(responseObj);
Status writeConcernStatus = getWriteConcernStatusFromCommandResult(responseObj);
return Shard::CommandResponse(std::move(responseObj),
std::move(responseMetadata),
std::move(commandStatus),
std::move(writeConcernStatus));
}
StatusWith<boost::optional<ShardType>> ShardingCatalogManagerImpl::_checkIfShardExists(
OperationContext* txn,
const ConnectionString& proposedShardConnectionString,
const std::string* proposedShardName,
long long proposedShardMaxSize) {
// Check whether any host in the connection is already part of the cluster.
const auto existingShards =
_catalogClient->getAllShards(txn, repl::ReadConcernLevel::kLocalReadConcern);
if (!existingShards.isOK()) {
return Status(existingShards.getStatus().code(),
str::stream() << "Failed to load existing shards during addShard"
<< causedBy(existingShards.getStatus().reason()));
}
// Now check if this shard already exists - if it already exists *with the same options* then
// the addShard request can return success early without doing anything more.
for (const auto& existingShard : existingShards.getValue().value) {
auto swExistingShardConnStr = ConnectionString::parse(existingShard.getHost());
if (!swExistingShardConnStr.isOK()) {
return swExistingShardConnStr.getStatus();
}
auto existingShardConnStr = std::move(swExistingShardConnStr.getValue());
// Function for determining if the options for the shard that is being added match the
// options of an existing shard that conflicts with it.
auto shardsAreEquivalent = [&]() {
if (proposedShardName && *proposedShardName != existingShard.getName()) {
return false;
}
if (proposedShardConnectionString.type() != existingShardConnStr.type()) {
return false;
}
if (proposedShardConnectionString.type() == ConnectionString::SET &&
proposedShardConnectionString.getSetName() != existingShardConnStr.getSetName()) {
return false;
}
if (proposedShardMaxSize != existingShard.getMaxSizeMB()) {
return false;
}
return true;
};
if (existingShardConnStr.type() == ConnectionString::SET &&
proposedShardConnectionString.type() == ConnectionString::SET &&
existingShardConnStr.getSetName() == proposedShardConnectionString.getSetName()) {
// An existing shard has the same replica set name as the shard being added.
// If the options aren't the same, then this is an error,
// but if the options match then the addShard operation should be immediately
// considered a success and terminated.
if (shardsAreEquivalent()) {
return {existingShard};
} else {
return {ErrorCodes::IllegalOperation,
str::stream() << "A shard already exists containing the replica set '"
<< existingShardConnStr.getSetName()
<< "'"};
}
}
for (const auto& existingHost : existingShardConnStr.getServers()) {
// Look if any of the hosts in the existing shard are present within the shard trying
// to be added.
for (const auto& addingHost : proposedShardConnectionString.getServers()) {
if (existingHost == addingHost) {
// At least one of the hosts in the shard being added already exists in an
// existing shard. If the options aren't the same, then this is an error,
// but if the options match then the addShard operation should be immediately
// considered a success and terminated.
if (shardsAreEquivalent()) {
return {existingShard};
} else {
return {ErrorCodes::IllegalOperation,
str::stream() << "'" << addingHost.toString() << "' "
<< "is already a member of the existing shard '"
<< existingShard.getHost()
<< "' ("
<< existingShard.getName()
<< ")."};
}
}
}
}
if (proposedShardName && *proposedShardName == existingShard.getName()) {
// If we get here then we're trying to add a shard with the same name as an existing
// shard, but there was no overlap in the hosts between the existing shard and the
// proposed connection string for the new shard.
return Status(ErrorCodes::IllegalOperation,
str::stream() << "A shard named " << *proposedShardName
<< " already exists");
}
}
return {boost::none};
}
StatusWith<ShardType> ShardingCatalogManagerImpl::_validateHostAsShard(
OperationContext* txn,
std::shared_ptr<RemoteCommandTargeter> targeter,
const std::string* shardProposedName,
const ConnectionString& connectionString) {
// Check if the node being added is a mongos or a version of mongod too old to speak the current
// communication protocol.
auto swCommandResponse =
_runCommandForAddShard(txn, targeter.get(), "admin", BSON("isMaster" << 1));
if (!swCommandResponse.isOK()) {
if (swCommandResponse.getStatus() == ErrorCodes::RPCProtocolNegotiationFailed) {
// Mongos to mongos commands are no longer supported in the wire protocol
// (because mongos does not support OP_COMMAND), similarly for a new mongos
// and an old mongod. So the call will fail in such cases.
// TODO: If/When mongos ever supports opCommands, this logic will break because
// cmdStatus will be OK.
return {ErrorCodes::RPCProtocolNegotiationFailed,
str::stream() << targeter->connectionString().toString()
<< " does not recognize the RPC protocol being used. This is"
<< " likely because it contains a node that is a mongos or an old"
<< " version of mongod."};
} else {
return swCommandResponse.getStatus();
}
}
// Check for a command response error
auto resIsMasterStatus = std::move(swCommandResponse.getValue().commandStatus);
if (!resIsMasterStatus.isOK()) {
return {resIsMasterStatus.code(),
str::stream() << "Error running isMaster against "
<< targeter->connectionString().toString()
<< ": "
<< causedBy(resIsMasterStatus)};
}
auto resIsMaster = std::move(swCommandResponse.getValue().response);
// Check that the node being added is a new enough version.
// If we're running this code, that means the mongos that the addShard request originated from
// must be at least version 3.4 (since 3.2 mongoses don't know about the _configsvrAddShard
// command). Since it is illegal to have v3.4 mongoses with v3.2 shards, we should reject
// adding any shards that are not v3.4. We can determine this by checking that the
// maxWireVersion reported in isMaster is at least COMMANDS_ACCEPT_WRITE_CONCERN.
// TODO(SERVER-25623): This approach won't work to prevent v3.6 mongoses from adding v3.4
// shards, so we'll have to rethink this during the 3.5 development cycle.
long long maxWireVersion;
Status status = bsonExtractIntegerField(resIsMaster, "maxWireVersion", &maxWireVersion);
if (!status.isOK()) {
return Status(status.code(),
str::stream() << "isMaster returned invalid 'maxWireVersion' "
<< "field when attempting to add "
<< connectionString.toString()
<< " as a shard: "
<< status.reason());
}
if (maxWireVersion < WireVersion::COMMANDS_ACCEPT_WRITE_CONCERN) {
return Status(ErrorCodes::IncompatibleServerVersion,
str::stream() << "Cannot add " << connectionString.toString()
<< " as a shard because we detected a mongod with server "
"version older than 3.4.0. It is invalid to add v3.2 and "
"older shards through a v3.4 mongos.");
}
// Check whether there is a master. If there isn't, the replica set may not have been
// initiated. If the connection is a standalone, it will return true for isMaster.
bool isMaster;
status = bsonExtractBooleanField(resIsMaster, "ismaster", &isMaster);
if (!status.isOK()) {
return Status(status.code(),
str::stream() << "isMaster returned invalid 'ismaster' "
<< "field when attempting to add "
<< connectionString.toString()
<< " as a shard: "
<< status.reason());
}
if (!isMaster) {
return {ErrorCodes::NotMaster,
str::stream()
<< connectionString.toString()
<< " does not have a master. If this is a replica set, ensure that it has a"
<< " healthy primary and that the set has been properly initiated."};
}
const string providedSetName = connectionString.getSetName();
const string foundSetName = resIsMaster["setName"].str();
// Make sure the specified replica set name (if any) matches the actual shard's replica set
if (providedSetName.empty() && !foundSetName.empty()) {
return {ErrorCodes::OperationFailed,
str::stream() << "host is part of set " << foundSetName << "; "
<< "use replica set url format "
<< "<setname>/<server1>,<server2>, ..."};
}
if (!providedSetName.empty() && foundSetName.empty()) {
return {ErrorCodes::OperationFailed,
str::stream() << "host did not return a set name; "
<< "is the replica set still initializing? "
<< resIsMaster};
}
// Make sure the set name specified in the connection string matches the one where its hosts
// belong into
if (!providedSetName.empty() && (providedSetName != foundSetName)) {
return {ErrorCodes::OperationFailed,
str::stream() << "the provided connection string (" << connectionString.toString()
<< ") does not match the actual set name "
<< foundSetName};
}
// Is it a config server?
if (resIsMaster.hasField("configsvr")) {
return {ErrorCodes::OperationFailed,
str::stream() << "Cannot add " << connectionString.toString()
<< " as a shard since it is a config server"};
}
// If the shard is part of a replica set, make sure all the hosts mentioned in the connection
// string are part of the set. It is fine if not all members of the set are mentioned in the
// connection string, though.
if (!providedSetName.empty()) {
std::set<string> hostSet;
BSONObjIterator iter(resIsMaster["hosts"].Obj());
while (iter.more()) {
hostSet.insert(iter.next().String()); // host:port
}
if (resIsMaster["passives"].isABSONObj()) {
BSONObjIterator piter(resIsMaster["passives"].Obj());
while (piter.more()) {
hostSet.insert(piter.next().String()); // host:port
}
}
if (resIsMaster["arbiters"].isABSONObj()) {
BSONObjIterator piter(resIsMaster["arbiters"].Obj());
while (piter.more()) {
hostSet.insert(piter.next().String()); // host:port
}
}
vector<HostAndPort> hosts = connectionString.getServers();
for (size_t i = 0; i < hosts.size(); i++) {
const string host = hosts[i].toString(); // host:port
if (hostSet.find(host) == hostSet.end()) {
return {ErrorCodes::OperationFailed,
str::stream() << "in seed list " << connectionString.toString() << ", host "
<< host
<< " does not belong to replica set "
<< foundSetName
<< "; found "
<< resIsMaster.toString()};
}
}
}
string actualShardName;
if (shardProposedName) {
actualShardName = *shardProposedName;
} else if (!foundSetName.empty()) {
// Default it to the name of the replica set
actualShardName = foundSetName;
}
// Disallow adding shard replica set with name 'config'
if (actualShardName == "config") {
return {ErrorCodes::BadValue, "use of shard replica set with name 'config' is not allowed"};
}
// Retrieve the most up to date connection string that we know from the replica set monitor (if
// this is a replica set shard, otherwise it will be the same value as connectionString).
ConnectionString actualShardConnStr = targeter->connectionString();
ShardType shard;
shard.setName(actualShardName);
shard.setHost(actualShardConnStr.toString());
shard.setState(ShardType::ShardState::kShardAware);
return shard;
}
StatusWith<std::vector<std::string>> ShardingCatalogManagerImpl::_getDBNamesListFromShard(
OperationContext* txn, std::shared_ptr<RemoteCommandTargeter> targeter) {
auto swCommandResponse =
_runCommandForAddShard(txn, targeter.get(), "admin", BSON("listDatabases" << 1));
if (!swCommandResponse.isOK()) {
return swCommandResponse.getStatus();
}
auto cmdStatus = std::move(swCommandResponse.getValue().commandStatus);
if (!cmdStatus.isOK()) {
return cmdStatus;
}
auto cmdResult = std::move(swCommandResponse.getValue().response);
vector<string> dbNames;
for (const auto& dbEntry : cmdResult["databases"].Obj()) {
const string& dbName = dbEntry["name"].String();
if (!(dbName == "local" || dbName == "admin")) {
dbNames.push_back(dbName);
}
}
return dbNames;
}
StatusWith<std::string> ShardingCatalogManagerImpl::_generateNewShardName(OperationContext* txn) {
BSONObjBuilder shardNameRegex;
shardNameRegex.appendRegex(ShardType::name(), "^shard");
auto findStatus = Grid::get(txn)->shardRegistry()->getConfigShard()->exhaustiveFindOnConfig(
txn,
kConfigReadSelector,
repl::ReadConcernLevel::kMajorityReadConcern,
NamespaceString(ShardType::ConfigNS),
shardNameRegex.obj(),
BSON(ShardType::name() << -1),
1);
if (!findStatus.isOK()) {
return findStatus.getStatus();
}
const auto& docs = findStatus.getValue().docs;
int count = 0;
if (!docs.empty()) {
const auto shardStatus = ShardType::fromBSON(docs.front());
if (!shardStatus.isOK()) {
return shardStatus.getStatus();
}
std::istringstream is(shardStatus.getValue().getName().substr(5));
is >> count;
count++;
}
// TODO fix so that we can have more than 10000 automatically generated shard names
if (count < 9999) {
std::stringstream ss;
ss << "shard" << std::setfill('0') << std::setw(4) << count;
return ss.str();
}
return Status(ErrorCodes::OperationFailed, "unable to generate new shard name");
}
StatusWith<string> ShardingCatalogManagerImpl::addShard(
OperationContext* txn,
const std::string* shardProposedName,
const ConnectionString& shardConnectionString,
const long long maxSize) {
if (shardConnectionString.type() == ConnectionString::INVALID) {
return {ErrorCodes::BadValue, "Invalid connection string"};
}
if (shardProposedName && shardProposedName->empty()) {
return {ErrorCodes::BadValue, "shard name cannot be empty"};
}
// Only one addShard operation can be in progress at a time.
Lock::ExclusiveLock lk(txn->lockState(), _kShardMembershipLock);
// TODO: Don't create a detached Shard object, create a detached RemoteCommandTargeter instead.
const std::shared_ptr<Shard> shard{
Grid::get(txn)->shardRegistry()->createConnection(shardConnectionString)};
invariant(shard);
auto targeter = shard->getTargeter();
auto stopMonitoringGuard = MakeGuard([&] {
if (shardConnectionString.type() == ConnectionString::SET) {
// This is a workaround for the case were we could have some bad shard being
// requested to be added and we put that bad connection string on the global replica set
// monitor registry. It needs to be cleaned up so that when a correct replica set is
// added, it will be recreated.
ReplicaSetMonitor::remove(shardConnectionString.getSetName());
}
});
// Validate the specified connection string may serve as shard at all
auto shardStatus =
_validateHostAsShard(txn, targeter, shardProposedName, shardConnectionString);
if (!shardStatus.isOK()) {
return shardStatus.getStatus();
}
ShardType& shardType = shardStatus.getValue();
// Check if this shard has already been added (can happen in the case of a retry after a network
// error, for example) and thus this addShard request should be considered a no-op.
auto existingShard =
_checkIfShardExists(txn, shardConnectionString, shardProposedName, maxSize);
if (!existingShard.isOK()) {
return existingShard.getStatus();
}
if (existingShard.getValue()) {
// These hosts already belong to an existing shard, so report success and terminate the
// addShard request. Make sure to set the last optime for the client to the system last
// optime so that we'll still wait for replication so that this state is visible in the
// committed snapshot.
repl::ReplClientInfo::forClient(txn->getClient()).setLastOpToSystemLastOpTime(txn);
return existingShard.getValue()->getName();
}
// Check that none of the existing shard candidate's dbs exist already
auto dbNamesStatus = _getDBNamesListFromShard(txn, targeter);
if (!dbNamesStatus.isOK()) {
return dbNamesStatus.getStatus();
}
for (const string& dbName : dbNamesStatus.getValue()) {
auto dbt = _catalogClient->getDatabase(txn, dbName);
if (dbt.isOK()) {
const auto& dbDoc = dbt.getValue().value;
return Status(ErrorCodes::OperationFailed,
str::stream() << "can't add shard "
<< "'"
<< shardConnectionString.toString()
<< "'"
<< " because a local database '"
<< dbName
<< "' exists in another "
<< dbDoc.getPrimary());
} else if (dbt != ErrorCodes::NamespaceNotFound) {
return dbt.getStatus();
}
}
// If a name for a shard wasn't provided, generate one
if (shardType.getName().empty()) {
StatusWith<string> result = _generateNewShardName(txn);
if (!result.isOK()) {
return result.getStatus();
}
shardType.setName(result.getValue());
}
if (maxSize > 0) {
shardType.setMaxSizeMB(maxSize);
}
// If the minimum allowed version for the cluster is 3.4, set the featureCompatibilityVersion to
// 3.4 on the shard.
if (serverGlobalParams.featureCompatibility.version.load() ==
ServerGlobalParams::FeatureCompatibility::Version::k34) {
auto versionResponse =
_runCommandForAddShard(txn,
targeter.get(),
"admin",
BSON(FeatureCompatibilityVersion::kCommandName
<< FeatureCompatibilityVersion::kVersion34));
if (!versionResponse.isOK()) {
return versionResponse.getStatus();
}
if (!versionResponse.getValue().commandStatus.isOK()) {
if (versionResponse.getStatus().code() == ErrorCodes::CommandNotFound) {
return Status(ErrorCodes::OperationFailed,
"featureCompatibilityVersion for cluster is 3.4, cannot add a shard "
"with version below 3.4. See "
"http://dochub.mongodb.org/core/3.4-feature-compatibility.");
}
return versionResponse.getValue().commandStatus;
}
}
if (!MONGO_FAIL_POINT(dontUpsertShardIdentityOnNewShards)) {
auto commandRequest = createShardIdentityUpsertForAddShard(txn, shardType.getName());
LOG(2) << "going to insert shardIdentity document into shard: " << shardType;
auto swCommandResponse =
_runCommandForAddShard(txn, targeter.get(), "admin", commandRequest);
if (!swCommandResponse.isOK()) {
return swCommandResponse.getStatus();
}
auto commandResponse = std::move(swCommandResponse.getValue());
BatchedCommandResponse batchResponse;
auto batchResponseStatus =
Shard::CommandResponse::processBatchWriteResponse(commandResponse, &batchResponse);
if (!batchResponseStatus.isOK()) {
return batchResponseStatus;
}
}
log() << "going to insert new entry for shard into config.shards: " << shardType.toString();
Status result = _catalogClient->insertConfigDocument(
txn, ShardType::ConfigNS, shardType.toBSON(), ShardingCatalogClient::kMajorityWriteConcern);
if (!result.isOK()) {
log() << "error adding shard: " << shardType.toBSON() << " err: " << result.reason();
return result;
}
// Add all databases which were discovered on the new shard
for (const string& dbName : dbNamesStatus.getValue()) {
DatabaseType dbt;
dbt.setName(dbName);
dbt.setPrimary(shardType.getName());
dbt.setSharded(false);
Status status = _catalogClient->updateDatabase(txn, dbName, dbt);
if (!status.isOK()) {
log() << "adding shard " << shardConnectionString.toString()
<< " even though could not add database " << dbName;
}
}
// Record in changelog
BSONObjBuilder shardDetails;
shardDetails.append("name", shardType.getName());
shardDetails.append("host", shardConnectionString.toString());
_catalogClient->logChange(
txn, "addShard", "", shardDetails.obj(), ShardingCatalogClient::kMajorityWriteConcern);
// Ensure the added shard is visible to this process.
auto shardRegistry = Grid::get(txn)->shardRegistry();
if (!shardRegistry->getShard(txn, shardType.getName()).isOK()) {
return {ErrorCodes::OperationFailed,
"Could not find shard metadata for shard after adding it. This most likely "
"indicates that the shard was removed immediately after it was added."};
}
stopMonitoringGuard.Dismiss();
return shardType.getName();
}
Status ShardingCatalogManagerImpl::addShardToZone(OperationContext* txn,
const std::string& shardName,
const std::string& zoneName) {
Lock::ExclusiveLock lk(txn->lockState(), _kZoneOpLock);
auto updateStatus = _catalogClient->updateConfigDocument(
txn,
ShardType::ConfigNS,
BSON(ShardType::name(shardName)),
BSON("$addToSet" << BSON(ShardType::tags() << zoneName)),
false,
kNoWaitWriteConcern);
if (!updateStatus.isOK()) {
return updateStatus.getStatus();
}
if (!updateStatus.getValue()) {
return {ErrorCodes::ShardNotFound,
str::stream() << "shard " << shardName << " does not exist"};
}
return Status::OK();
}
Status ShardingCatalogManagerImpl::removeShardFromZone(OperationContext* txn,
const std::string& shardName,
const std::string& zoneName) {
Lock::ExclusiveLock lk(txn->lockState(), _kZoneOpLock);
auto configShard = Grid::get(txn)->shardRegistry()->getConfigShard();
const NamespaceString shardNS(ShardType::ConfigNS);
//
// Check whether the shard even exist in the first place.
//
auto findShardExistsStatus =
configShard->exhaustiveFindOnConfig(txn,
kConfigPrimarySelector,
repl::ReadConcernLevel::kLocalReadConcern,
shardNS,
BSON(ShardType::name() << shardName),
BSONObj(),
1);
if (!findShardExistsStatus.isOK()) {
return findShardExistsStatus.getStatus();
}
if (findShardExistsStatus.getValue().docs.size() == 0) {
return {ErrorCodes::ShardNotFound,
str::stream() << "shard " << shardName << " does not exist"};
}
//
// Check how many shards belongs to this zone.
//
auto findShardStatus =
configShard->exhaustiveFindOnConfig(txn,
kConfigPrimarySelector,
repl::ReadConcernLevel::kLocalReadConcern,
shardNS,
BSON(ShardType::tags() << zoneName),
BSONObj(),
2);
if (!findShardStatus.isOK()) {
return findShardStatus.getStatus();
}
const auto shardDocs = findShardStatus.getValue().docs;
if (shardDocs.size() == 0) {
// The zone doesn't exists, this could be a retry.
return Status::OK();
}
if (shardDocs.size() == 1) {
auto shardDocStatus = ShardType::fromBSON(shardDocs.front());
if (!shardDocStatus.isOK()) {
return shardDocStatus.getStatus();
}
auto shardDoc = shardDocStatus.getValue();
if (shardDoc.getName() != shardName) {
// The last shard that belongs to this zone is a different shard.
// This could be a retry, so return OK.
return Status::OK();
}
auto findChunkRangeStatus =
configShard->exhaustiveFindOnConfig(txn,
kConfigPrimarySelector,
repl::ReadConcernLevel::kLocalReadConcern,
NamespaceString(TagsType::ConfigNS),