-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
create_collection_coordinator.cpp
1770 lines (1538 loc) · 81.3 KB
/
create_collection_coordinator.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) 2020-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.
*/
#include <algorithm>
#include <boost/cstdint.hpp>
#include <boost/none.hpp>
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <list>
#include <mutex>
#include <set>
#include <tuple>
#include <utility>
#include <vector>
#include <boost/move/utility_core.hpp>
#include <boost/optional/optional.hpp>
#include "mongo/base/error_codes.h"
#include "mongo/base/status_with.h"
#include "mongo/bson/bsonelement.h"
#include "mongo/bson/bsontypes.h"
#include "mongo/bson/simple_bsonobj_comparator.h"
#include "mongo/client/read_preference.h"
#include "mongo/db/audit.h"
#include "mongo/db/basic_types.h"
#include "mongo/db/basic_types_gen.h"
#include "mongo/db/cancelable_operation_context.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/collection_uuid_mismatch.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/create_gen.h"
#include "mongo/db/concurrency/lock_manager_defs.h"
#include "mongo/db/database_name.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/keypattern.h"
#include "mongo/db/locker_api.h"
#include "mongo/db/ops/write_ops_gen.h"
#include "mongo/db/query/collation/collator_factory_interface.h"
#include "mongo/db/query/collation/collator_interface.h"
#include "mongo/db/repl/change_stream_oplog_notification.h"
#include "mongo/db/repl/read_concern_level.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/s/collection_sharding_runtime.h"
#include "mongo/db/s/create_collection_coordinator.h"
#include "mongo/db/s/create_collection_coordinator_document_gen.h"
#include "mongo/db/s/forwardable_operation_metadata.h"
#include "mongo/db/s/participant_block_gen.h"
#include "mongo/db/s/remove_chunks_gen.h"
#include "mongo/db/s/shard_filtering_metadata_refresh.h"
#include "mongo/db/s/shard_key_util.h"
#include "mongo/db/s/sharding_ddl_coordinator.h"
#include "mongo/db/s/sharding_ddl_coordinator_gen.h"
#include "mongo/db/s/sharding_ddl_util.h"
#include "mongo/db/s/sharding_logging.h"
#include "mongo/db/s/sharding_recovery_service.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/db/service_context.h"
#include "mongo/db/session/logical_session_id.h"
#include "mongo/db/shard_id.h"
#include "mongo/db/timeseries/timeseries_constants.h"
#include "mongo/db/timeseries/timeseries_gen.h"
#include "mongo/db/timeseries/timeseries_index_schema_conversion_functions.h"
#include "mongo/db/timeseries/timeseries_options.h"
#include "mongo/db/transaction/transaction_api.h"
#include "mongo/db/write_concern.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/executor/remote_command_response.h"
#include "mongo/executor/task_executor_pool.h"
#include "mongo/idl/idl_parser.h"
#include "mongo/logv2/log.h"
#include "mongo/logv2/log_attr.h"
#include "mongo/logv2/log_component.h"
#include "mongo/logv2/redaction.h"
#include "mongo/platform/compiler.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/s/async_requests_sender.h"
#include "mongo/s/catalog/sharding_catalog_client.h"
#include "mongo/s/catalog/type_chunk.h"
#include "mongo/s/catalog/type_collection.h"
#include "mongo/s/catalog/type_namespace_placement_gen.h"
#include "mongo/s/catalog/type_tags.h"
#include "mongo/s/catalog_cache.h"
#include "mongo/s/chunk_manager.h"
#include "mongo/s/chunk_version.h"
#include "mongo/s/client/shard.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/cluster_commands_helpers.h"
#include "mongo/s/cluster_write.h"
#include "mongo/s/grid.h"
#include "mongo/s/index_version.h"
#include "mongo/s/shard_util.h"
#include "mongo/s/shard_version.h"
#include "mongo/s/shard_version_factory.h"
#include "mongo/s/sharding_feature_flags_gen.h"
#include "mongo/s/type_collection_common_types_gen.h"
#include "mongo/s/write_ops/batch_write_exec.h"
#include "mongo/s/write_ops/batched_command_request.h"
#include "mongo/s/write_ops/batched_command_response.h"
#include "mongo/util/decorable.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/future_impl.h"
#include "mongo/util/out_of_line_executor.h"
#include "mongo/util/str.h"
#include "mongo/util/time_support.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kSharding
MONGO_FAIL_POINT_DEFINE(failAtCommitCreateCollectionCoordinator);
namespace mongo {
namespace create_collection_util {
std::unique_ptr<InitialSplitPolicy> createPolicy(
OperationContext* opCtx,
const ShardKeyPattern& shardKeyPattern,
const bool presplitHashedZones,
std::vector<TagsType> tags,
size_t numShards,
bool collectionIsEmpty,
bool isUnsplittable,
boost::optional<ShardId> dataShard,
boost::optional<std::vector<ShardId>> availableShardIds) {
uassert(ErrorCodes::InvalidOptions,
str::stream() << "dataShard can only be specified in unsplittable collections",
!dataShard || (dataShard && isUnsplittable));
uassert(ErrorCodes::InvalidOptions,
str::stream() << "When dataShard or unsplittable is specified, the collection must be "
"empty and no other option must be specified",
!isUnsplittable ||
(collectionIsEmpty && !presplitHashedZones && tags.empty() &&
shardKeyPattern.getKeyPattern().toBSON().woCompare((BSON("_id" << 1))) == 0));
// if unsplittable, the collection is always equivalent to a single chunk collection
if (isUnsplittable) {
if (dataShard) {
return std::make_unique<SingleChunkOnShardSplitPolicy>(opCtx, *dataShard);
} else {
return std::make_unique<SingleChunkOnPrimarySplitPolicy>();
}
}
// If 'presplitHashedZones' flag is set, we always use 'PresplitHashedZonesSplitPolicy', to make
// sure we throw the correct assertion if further validation fails.
if (presplitHashedZones) {
return std::make_unique<PresplitHashedZonesSplitPolicy>(opCtx,
shardKeyPattern,
std::move(tags),
collectionIsEmpty,
std::move(availableShardIds));
}
// If the collection is empty, some optimizations for the chunk distribution may be available.
if (collectionIsEmpty) {
if (tags.empty() && shardKeyPattern.hasHashedPrefix()) {
// Evenly distribute chunks across shards (in combination with hashed shard keys, this
// should increase the probability of establishing an already balanced collection).
return std::make_unique<SplitPointsBasedSplitPolicy>(
shardKeyPattern, numShards, std::move(availableShardIds));
}
if (!tags.empty()) {
// Enforce zone constraints.
return std::make_unique<SingleChunkPerTagSplitPolicy>(
opCtx, std::move(tags), std::move(availableShardIds));
}
}
// Generic case.
return std::make_unique<SingleChunkOnPrimarySplitPolicy>();
}
} // namespace create_collection_util
namespace {
struct OptionsAndIndexes {
BSONObj options;
std::vector<BSONObj> indexSpecs;
BSONObj idIndexSpec;
};
OptionsAndIndexes getCollectionOptionsAndIndexes(OperationContext* opCtx,
const NamespaceStringOrUUID& nssOrUUID) {
DBDirectClient localClient(opCtx);
BSONObj idIndex;
BSONObjBuilder optionsBob;
auto all =
localClient.getCollectionInfos(nssOrUUID.dbName(), BSON("info.uuid" << nssOrUUID.uuid()));
// There must be a collection at this time.
invariant(!all.empty());
auto& entry = all.front();
if (entry["options"].isABSONObj()) {
optionsBob.appendElements(entry["options"].Obj());
}
optionsBob.append(entry["info"]["uuid"]);
if (entry["idIndex"]) {
idIndex = entry["idIndex"].Obj().getOwned();
}
auto indexSpecsList = localClient.getIndexSpecs(nssOrUUID, false, 0);
return {optionsBob.obj(),
std::vector<BSONObj>(std::begin(indexSpecsList), std::end(indexSpecsList)),
idIndex};
}
// NOTES on the 'collation' optional parameter contained by the shardCollection() request:
// 1. It specifies the ordering criteria that will be applied when comparing chunk boundaries
// during sharding operations (such as move/mergeChunks).
// 2. As per today, the only supported value (and the one applied by default) is 'simple'
// collation.
// 3. If the collection being sharded does not exist yet, it will also be used as the ordering
// criteria to serve user queries over the shard index fields.
// 4. If an existing unsharded collection is being targeted, the original 'collation' will still
// be used to serve user queries, but the shardCollection is required to explicitly include the
// 'collation' parameter to succeed (as an acknowledge of what specified in points 1. and 2.)
BSONObj resolveCollationForUserQueries(OperationContext* opCtx,
const NamespaceString& nss,
const boost::optional<BSONObj>& collationInRequest) {
// Ensure the collation is valid. Currently we only allow the simple collation.
std::unique_ptr<CollatorInterface> requestedCollator = nullptr;
if (collationInRequest) {
const auto& collationBson = collationInRequest.value();
requestedCollator = uassertStatusOK(
CollatorFactoryInterface::get(opCtx->getServiceContext())->makeFromBSON(collationBson));
uassert(ErrorCodes::BadValue,
str::stream() << "The collation for shardCollection must be {locale: 'simple'}, "
<< "but found: " << collationBson,
!requestedCollator);
}
AutoGetCollection autoColl(opCtx, nss, MODE_IS);
const auto actualCollator = [&]() -> const CollatorInterface* {
const auto& coll = autoColl.getCollection();
if (coll) {
uassert(
ErrorCodes::InvalidOptions, "can't shard a capped collection", !coll->isCapped());
return coll->getDefaultCollator();
}
return nullptr;
}();
if (!requestedCollator && !actualCollator)
return BSONObj();
auto actualCollation = actualCollator->getSpec();
auto actualCollatorBSON = actualCollation.toBSON();
if (!collationInRequest) {
auto actualCollatorFilter =
uassertStatusOK(CollatorFactoryInterface::get(opCtx->getServiceContext())
->makeFromBSON(actualCollatorBSON));
uassert(ErrorCodes::BadValue,
str::stream() << "If no collation was specified, the collection collation must be "
"{locale: 'simple'}, "
<< "but found: " << actualCollatorBSON,
!actualCollatorFilter);
}
return actualCollatorBSON;
}
/**
* Constructs the BSON specification document for the create collections command using the given
* namespace, collation, and timeseries options.
*/
BSONObj makeCreateCommand(const NamespaceString& nss,
const boost::optional<Collation>& collation,
const TimeseriesOptions& tsOpts) {
CreateCommand create(nss);
CreateCollectionRequest baseRequest;
baseRequest.setTimeseries(tsOpts);
if (collation) {
baseRequest.setCollation(*collation);
}
BSONObj commandPassthroughFields;
create.setCreateCollectionRequest(baseRequest);
return create.toBSON(commandPassthroughFields);
}
/**
* Compares the proposed shard key with the shard key of the collection's existing zones
* to ensure they are a legal combination.
*/
void validateShardKeyAgainstExistingZones(OperationContext* opCtx,
const NamespaceString& nss,
const BSONObj& proposedKey,
const std::vector<TagsType>& tags) {
const AutoGetCollection coll(opCtx, nss, MODE_IS);
for (const auto& tag : tags) {
BSONObjIterator tagMinFields(tag.getMinKey());
BSONObjIterator tagMaxFields(tag.getMaxKey());
BSONObjIterator proposedFields(proposedKey);
while (tagMinFields.more() && proposedFields.more()) {
BSONElement tagMinKeyElement = tagMinFields.next();
BSONElement tagMaxKeyElement = tagMaxFields.next();
uassert(ErrorCodes::InvalidOptions,
str::stream() << "the min and max of the existing zone " << tag.getMinKey()
<< " -->> " << tag.getMaxKey() << " have non-matching keys",
tagMinKeyElement.fieldNameStringData() ==
tagMaxKeyElement.fieldNameStringData());
BSONElement proposedKeyElement = proposedFields.next();
bool match = ((tagMinKeyElement.fieldNameStringData() ==
proposedKeyElement.fieldNameStringData()) &&
((tagMinFields.more() && proposedFields.more()) ||
(!tagMinFields.more() && !proposedFields.more())));
uassert(ErrorCodes::InvalidOptions,
str::stream() << "the proposed shard key " << proposedKey.toString()
<< " does not match with the shard key of the existing zone "
<< tag.getMinKey() << " -->> " << tag.getMaxKey(),
match);
// If the field is hashed, make sure that the min and max values are of supported type.
uassert(
ErrorCodes::InvalidOptions,
str::stream() << "cannot do hash sharding with the proposed key "
<< proposedKey.toString() << " because there exists a zone "
<< tag.getMinKey() << " -->> " << tag.getMaxKey()
<< " whose boundaries are not of type NumberLong, MinKey or MaxKey",
!ShardKeyPattern::isHashedPatternEl(proposedKeyElement) ||
(ShardKeyPattern::isValidHashedValue(tagMinKeyElement) &&
ShardKeyPattern::isValidHashedValue(tagMaxKeyElement)));
if (coll && coll->getTimeseriesOptions()) {
const std::string controlTimeField =
timeseries::kControlMinFieldNamePrefix.toString() +
coll->getTimeseriesOptions()->getTimeField();
if (tagMinKeyElement.fieldNameStringData() == controlTimeField) {
uassert(ErrorCodes::InvalidOptions,
str::stream() << "time field cannot be specified in the zone range for "
"time-series collections",
tagMinKeyElement.type() == MinKey);
}
if (tagMaxKeyElement.fieldNameStringData() == controlTimeField) {
uassert(ErrorCodes::InvalidOptions,
str::stream() << "time field cannot be specified in the zone range for "
"time-series collections",
tagMaxKeyElement.type() == MinKey);
}
}
}
}
}
std::vector<TagsType> getTagsAndValidate(OperationContext* opCtx,
const NamespaceString& nss,
const BSONObj& proposedKey) {
// Read zone info
const auto catalogClient = Grid::get(opCtx)->catalogClient();
auto tags = uassertStatusOK(catalogClient->getTagsForCollection(opCtx, nss));
if (!tags.empty()) {
validateShardKeyAgainstExistingZones(opCtx, nss, proposedKey, tags);
}
return tags;
}
bool checkIfCollectionIsEmpty(OperationContext* opCtx, const NamespaceString& nss) {
// Use find with predicate instead of count in order to ensure that the count
// command doesn't just consult the cached metadata, which may not always be
// correct
DBDirectClient localClient(opCtx);
return localClient.findOne(nss, BSONObj{}).isEmpty();
}
int getNumShards(OperationContext* opCtx) {
const auto shardRegistry = Grid::get(opCtx)->shardRegistry();
shardRegistry->reload(opCtx);
return shardRegistry->getNumShards(opCtx);
}
void cleanupPartialChunksFromPreviousAttempt(OperationContext* opCtx,
const UUID& uuid,
const OperationSessionInfo& osi) {
auto configShard = Grid::get(opCtx)->shardRegistry()->getConfigShard();
// Remove the chunks matching uuid
ConfigsvrRemoveChunks configsvrRemoveChunksCmd(uuid);
configsvrRemoveChunksCmd.setDbName(DatabaseName::kAdmin);
const auto swRemoveChunksResult = configShard->runCommandWithFixedRetryAttempts(
opCtx,
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
DatabaseName::kAdmin,
CommandHelpers::appendMajorityWriteConcern(configsvrRemoveChunksCmd.toBSON(osi.toBSON())),
Shard::RetryPolicy::kIdempotent);
uassertStatusOKWithContext(Shard::CommandResponse::getEffectiveStatus(swRemoveChunksResult),
str::stream() << "Error removing chunks matching uuid " << uuid);
}
void updateCollectionMetadataInTransaction(OperationContext* opCtx,
const std::shared_ptr<executor::TaskExecutor>& executor,
const std::vector<ChunkType>& chunks,
const CollectionType& coll,
const ChunkVersion& placementVersion,
const std::set<ShardId>& shardIds,
const OperationSessionInfo& osi) {
/*
* As part of this chain, we will do the following operations:
* 1. Delete any existing chunk entries (there can be 1 or 0 depending on whether we are
* creating a collection or converting from unsplittable to splittable).
* 2. Insert new chunk entries - there can be a maximum of (2 * number of shards) or (number of
* zones) new chunks.
* 3. Replace the old collection entry with the new one (change the version and the shard key).
* 4. Update the placement information.
*/
const auto transactionChain = [&](const txn_api::TransactionClient& txnClient,
ExecutorPtr txnExec) {
write_ops::DeleteCommandRequest deleteOp(ChunkType::ConfigNS);
deleteOp.setDeletes({[&] {
write_ops::DeleteOpEntry entry;
entry.setQ(BSON(ChunkType::collectionUUID.name() << coll.getUuid()));
entry.setMulti(false);
return entry;
}()});
return txnClient.runCRUDOp({deleteOp}, {0})
.thenRunOn(txnExec)
.then([&](const BatchedCommandResponse& deleteChunkEntryResponse) {
uassertStatusOK(deleteChunkEntryResponse.toStatus());
std::vector<StmtId> chunkStmts;
BatchedCommandRequest insertChunkEntries([&]() {
write_ops::InsertCommandRequest insertOp(ChunkType::ConfigNS);
std::vector<BSONObj> entries;
entries.reserve(chunks.size());
chunkStmts.reserve(chunks.size());
int counter = 1;
for (const auto& chunk : chunks) {
entries.push_back(chunk.toConfigBSON());
chunkStmts.push_back({counter++});
}
insertOp.setDocuments(std::move(entries));
insertOp.setWriteCommandRequestBase([] {
write_ops::WriteCommandRequestBase wcb;
wcb.setOrdered(false);
return wcb;
}());
return insertOp;
}());
return txnClient.runCRUDOp(insertChunkEntries, chunkStmts);
})
.thenRunOn(txnExec)
.then([&](const BatchedCommandResponse& insertChunkEntriesResponse) {
uassertStatusOK(insertChunkEntriesResponse.toStatus());
write_ops::UpdateCommandRequest updateCollectionEntry(CollectionType::ConfigNS);
updateCollectionEntry.setUpdates({[&] {
write_ops::UpdateOpEntry updateEntry;
updateEntry.setMulti(false);
updateEntry.setUpsert(true);
updateEntry.setQ(
BSON(CollectionType::kNssFieldName
<< NamespaceStringUtil::serialize(coll.getNss(),
SerializationContext::stateDefault())
<< CollectionType::kUuidFieldName << coll.getUuid()));
updateEntry.setU(mongo::write_ops::UpdateModification(
coll.toBSON(), write_ops::UpdateModification::ReplacementTag{}));
return updateEntry;
}()});
int collUpdateId = 1 + chunks.size() + 1;
return txnClient.runCRUDOp(updateCollectionEntry, {collUpdateId});
})
.thenRunOn(txnExec)
.then([&](const BatchedCommandResponse& updateCollectionEntryResponse) {
uassertStatusOK(updateCollectionEntryResponse.toStatus());
NamespacePlacementType placementInfo(
NamespaceString(coll.getNss()),
placementVersion.getTimestamp(),
std::vector<mongo::ShardId>(shardIds.cbegin(), shardIds.cend()));
placementInfo.setUuid(coll.getUuid());
write_ops::InsertCommandRequest insertPlacementEntry(
NamespaceString::kConfigsvrPlacementHistoryNamespace, {placementInfo.toBSON()});
int historyUpdateId = 1 + chunks.size() + 2;
return txnClient.runCRUDOp(insertPlacementEntry, {historyUpdateId});
})
.thenRunOn(txnExec)
.then([](const BatchedCommandResponse& insertPlacementEntryResponse) {
uassertStatusOK(insertPlacementEntryResponse.toStatus());
})
.semi();
};
// Ensure that this function will only return once the transaction gets majority committed
auto wc = WriteConcernOptions{WriteConcernOptions::kMajority,
WriteConcernOptions::SyncMode::UNSET,
WriteConcernOptions::kNoTimeout};
// This always runs in the shard role so should use a cluster transaction to guarantee targeting
// the config server.
bool useClusterTransaction = true;
sharding_ddl_util::runTransactionOnShardingCatalog(
opCtx, std::move(transactionChain), wc, osi, useClusterTransaction, executor);
}
void broadcastDropCollection(OperationContext* opCtx,
const NamespaceString& nss,
const std::shared_ptr<executor::TaskExecutor>& executor,
const OperationSessionInfo& osi) {
const auto primaryShardId = ShardingState::get(opCtx)->shardId();
auto participants = Grid::get(opCtx)->shardRegistry()->getAllShardIds(opCtx);
// Remove primary shard from participants
participants.erase(std::remove(participants.begin(), participants.end(), primaryShardId),
participants.end());
sharding_ddl_util::sendDropCollectionParticipantCommandToShards(
opCtx,
nss,
participants,
executor,
osi,
true /* fromMigrate */,
false /* dropSystemCollections */);
}
boost::optional<CreateCollectionResponse> checkIfCollectionAlreadyTrackedWithSameOptions(
OperationContext* opCtx,
const ShardsvrCreateCollectionRequest& request,
const NamespaceString& originalNss) {
// If the request is part of a C2C synchronisation, the check on the received UUID must be
// performed first to honor the contract with mongosync (see SERVER-67885 for details).
if (request.getCollectionUUID()) {
if (AutoGetCollection stdColl{opCtx, originalNss, MODE_IS}; stdColl) {
checkCollectionUUIDMismatch(opCtx, originalNss, *stdColl, request.getCollectionUUID());
} else {
// No standard collection is present on the local catalog, but the request is not yet
// translated; a timeseries version of the requested namespace may still match the
// requested UUID.
auto bucketsNamespace = originalNss.makeTimeseriesBucketsNamespace();
AutoGetCollection timeseriesColl{opCtx, bucketsNamespace, MODE_IS};
checkCollectionUUIDMismatch(
opCtx, originalNss, *timeseriesColl, request.getCollectionUUID());
}
}
// Check if there is a standard collection that matches the original request parameters
auto cri = uassertStatusOK(
Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfoWithRefresh(opCtx, originalNss));
auto& cm = cri.cm;
auto& sii = cri.sii;
if (cm.hasRoutingTable()) {
auto requestToShardAnUnsplittableCollection =
!request.getUnsplittable().value_or(false) && cm.isUnsplittable();
if (requestToShardAnUnsplittableCollection) {
return boost::none;
}
auto requestMatchesExistingCollection = [&] {
// No timeseries fields in request
if (request.getTimeseries()) {
return false;
}
if (request.getUnique().value_or(false) != cm.isUnique()) {
return false;
}
if (request.getUnsplittable().value_or(false) != cm.isUnsplittable()) {
return false;
}
if (SimpleBSONObjComparator::kInstance.evaluate(*request.getShardKey() !=
cm.getShardKeyPattern().toBSON())) {
return false;
}
auto defaultCollator =
cm.getDefaultCollator() ? cm.getDefaultCollator()->getSpec().toBSON() : BSONObj();
if (SimpleBSONObjComparator::kInstance.evaluate(
defaultCollator !=
resolveCollationForUserQueries(opCtx, originalNss, request.getCollation()))) {
return false;
}
return true;
}();
uassert(ErrorCodes::AlreadyInitialized,
str::stream() << "collection already tracked with different options for collection "
<< originalNss.toStringForErrorMsg(),
requestMatchesExistingCollection);
CreateCollectionResponse response(cri.getCollectionVersion());
response.setCollectionUUID(cm.getUUID());
return response;
}
// If the request is still unresolved, check if there is an existing TS buckets namespace that
// may be matched by the request.
auto bucketsNss = originalNss.makeTimeseriesBucketsNamespace();
cri = uassertStatusOK(
Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfoWithRefresh(opCtx, bucketsNss));
cm = cri.cm;
sii = cri.sii;
if (!cm.hasRoutingTable()) {
return boost::none;
}
auto requestToShardAnUnsplittableCollection =
!request.getUnsplittable().value_or(false) && cm.isUnsplittable();
if (requestToShardAnUnsplittableCollection) {
return boost::none;
}
auto requestMatchesExistingCollection = [&] {
if (cm.isUnique() != request.getUnique().value_or(false)) {
return false;
}
if (cm.isUnsplittable() != request.getUnsplittable().value_or(false)) {
return false;
}
// Timeseries options match
const auto& timeseriesOptionsOnDisk = (*cm.getTimeseriesFields()).getTimeseriesOptions();
if (request.getTimeseries() &&
!timeseries::optionsAreEqual(*request.getTimeseries(), timeseriesOptionsOnDisk)) {
return false;
}
auto defaultCollator =
cm.getDefaultCollator() ? cm.getDefaultCollator()->getSpec().toBSON() : BSONObj();
if (SimpleBSONObjComparator::kInstance.evaluate(
defaultCollator !=
resolveCollationForUserQueries(opCtx, bucketsNss, request.getCollation()))) {
return false;
}
// Same Key Pattern
const auto& timeseriesOptions =
request.getTimeseries() ? *request.getTimeseries() : timeseriesOptionsOnDisk;
auto requestKeyPattern =
uassertStatusOK(timeseries::createBucketsShardKeySpecFromTimeseriesShardKeySpec(
timeseriesOptions, *request.getShardKey()));
if (SimpleBSONObjComparator::kInstance.evaluate(cm.getShardKeyPattern().toBSON() !=
requestKeyPattern)) {
return false;
}
return true;
}();
uassert(ErrorCodes::AlreadyInitialized,
str::stream() << "collection already tracked with different options for collection "
<< bucketsNss.toStringForErrorMsg(),
requestMatchesExistingCollection);
CreateCollectionResponse response(cri.getCollectionVersion());
response.setCollectionUUID(cm.getUUID());
return response;
}
void checkCommandArguments(OperationContext* opCtx,
const ShardsvrCreateCollectionRequest& request,
const NamespaceString& originalNss) {
LOGV2_DEBUG(5277902, 2, "Create collection checkCommandArguments", logAttrs(originalNss));
uassert(ErrorCodes::IllegalOperation,
"Special collection '" + originalNss.toStringForErrorMsg() + "' cannot be sharded",
!originalNss.isNamespaceAlwaysUntracked());
// Ensure that hashed and unique are not both set.
uassert(ErrorCodes::InvalidOptions,
"Hashed shard keys cannot be declared unique. It's possible to ensure uniqueness on "
"the hashed field by declaring an additional (non-hashed) unique index on the field.",
!ShardKeyPattern(*request.getShardKey()).isHashedPattern() ||
!request.getUnique().value_or(false));
if (originalNss.dbName() == DatabaseName::kConfig) {
auto configShard = Grid::get(opCtx)->shardRegistry()->getConfigShard();
auto findReponse = uassertStatusOK(
configShard->exhaustiveFindOnConfig(opCtx,
ReadPreferenceSetting{ReadPreference::PrimaryOnly},
repl::ReadConcernLevel::kMajorityReadConcern,
originalNss,
BSONObj(),
BSONObj(),
1));
auto numDocs = findReponse.docs.size();
// If this is a collection on the config db, it must be empty to be sharded.
uassert(ErrorCodes::IllegalOperation,
"collections in the config db must be empty to be sharded",
numDocs == 0);
}
}
/**
* Helper function to audit and log the shard collection event.
*/
void logStartCreateCollection(OperationContext* opCtx,
const ShardsvrCreateCollectionRequest& request,
const NamespaceString& originalNss) {
BSONObjBuilder collectionDetail;
collectionDetail.append("shardKey", *request.getShardKey());
collectionDetail.append(
"collection",
NamespaceStringUtil::serialize(originalNss, SerializationContext::stateDefault()));
collectionDetail.append("primary", ShardingState::get(opCtx)->shardId().toString());
ShardingLogging::get(opCtx)->logChange(
opCtx, "shardCollection.start", originalNss, collectionDetail.obj());
}
void acquireCriticalSectionsOnCoordinator(OperationContext* opCtx,
const BSONObj& critSecReason,
const NamespaceString& originalNss) {
ShardingRecoveryService::get(opCtx)->acquireRecoverableCriticalSectionBlockWrites(
opCtx, originalNss, critSecReason, ShardingCatalogClient::kMajorityWriteConcern);
// Preventively acquire the critical section protecting the buckets namespace that the
// creation of a timeseries collection would require.
ShardingRecoveryService::get(opCtx)->acquireRecoverableCriticalSectionBlockWrites(
opCtx,
originalNss.makeTimeseriesBucketsNamespace(),
critSecReason,
ShardingCatalogClient::kMajorityWriteConcern);
}
void releaseCriticalSectionsOnCoordinator(OperationContext* opCtx,
bool throwIfReasonDiffers,
const BSONObj& critSecReason,
const NamespaceString& originalNss) {
ShardingRecoveryService::get(opCtx)->releaseRecoverableCriticalSection(
opCtx,
originalNss,
critSecReason,
ShardingCatalogClient::kMajorityWriteConcern,
throwIfReasonDiffers);
ShardingRecoveryService::get(opCtx)->releaseRecoverableCriticalSection(
opCtx,
originalNss.makeTimeseriesBucketsNamespace(),
critSecReason,
ShardingCatalogClient::kMajorityWriteConcern,
throwIfReasonDiffers);
}
/**
* Updates the parameters contained in request based on the content of the local catalog and returns
* an equivalent descriptor that may be persisted with the recovery document.
*/
TranslatedRequestParams translateRequestParameters(OperationContext* opCtx,
ShardsvrCreateCollectionRequest& request,
const NamespaceString& originalNss) {
auto performCheckOnCollectionUUID = [opCtx, request](const NamespaceString& resolvedNss) {
AutoGetCollection coll{
opCtx,
resolvedNss,
MODE_IS,
AutoGetCollection::Options{}.expectedUUID(request.getCollectionUUID())};
};
auto bucketsNs = originalNss.makeTimeseriesBucketsNamespace();
// Hold reference to the catalog for collection lookup without locks to be safe.
auto catalog = CollectionCatalog::get(opCtx);
auto existingBucketsColl = catalog->lookupCollectionByNamespace(opCtx, bucketsNs);
auto targetingStandardCollection = !request.getTimeseries() && !existingBucketsColl;
if (targetingStandardCollection) {
const auto& resolvedNamespace = originalNss;
performCheckOnCollectionUUID(resolvedNamespace);
uassert(ErrorCodes::InvalidNamespace,
str::stream() << "Namespace too long. Namespace: "
<< resolvedNamespace.toStringForErrorMsg()
<< " Max: " << NamespaceString::MaxNsShardedCollectionLen,
resolvedNamespace.size() <= NamespaceString::MaxNsShardedCollectionLen);
return TranslatedRequestParams(
resolvedNamespace,
*request.getShardKey(),
resolveCollationForUserQueries(opCtx, resolvedNamespace, request.getCollation()));
}
// The request is targeting a new or existing Timeseries collection and the request has not been
// patched yet.
const auto& resolvedNamespace = bucketsNs;
performCheckOnCollectionUUID(resolvedNamespace);
uassert(ErrorCodes::InvalidNamespace,
str::stream() << "Namespace too long. Namespace: "
<< resolvedNamespace.toStringForErrorMsg()
<< " Max: " << NamespaceString::MaxNsShardedCollectionLen,
resolvedNamespace.size() <= NamespaceString::MaxNsShardedCollectionLen);
// Consolidate the related request parameters...
auto existingTimeseriesOptions = [&bucketsNs, &existingBucketsColl] {
if (!existingBucketsColl) {
return boost::optional<TimeseriesOptions>();
}
uassert(6159000,
str::stream() << "the collection '" << bucketsNs.toStringForErrorMsg()
<< "' does not have 'timeseries' options",
existingBucketsColl->getTimeseriesOptions());
return existingBucketsColl->getTimeseriesOptions();
}();
if (request.getTimeseries() && existingTimeseriesOptions) {
uassert(5731500,
str::stream() << "the 'timeseries' spec provided must match that of exists '"
<< originalNss.toStringForErrorMsg() << "' collection",
timeseries::optionsAreEqual(*request.getTimeseries(), *existingTimeseriesOptions));
} else if (!request.getTimeseries()) {
request.setTimeseries(existingTimeseriesOptions);
}
if (request.getUnsplittable()) {
return TranslatedRequestParams(
resolvedNamespace,
request.getShardKey().value(),
resolveCollationForUserQueries(opCtx, resolvedNamespace, request.getCollation()));
}
// check that they are consistent with the requested shard key before creating the key pattern
// object.
auto timeFieldName = request.getTimeseries()->getTimeField();
auto metaFieldName = request.getTimeseries()->getMetaField();
BSONObjIterator shardKeyElems{*request.getShardKey()};
while (auto elem = shardKeyElems.next()) {
if (elem.fieldNameStringData() == timeFieldName) {
uassert(5914000,
str::stream() << "the time field '" << timeFieldName
<< "' can be only at the end of the shard key pattern",
!shardKeyElems.more());
} else {
uassert(5914001,
str::stream() << "only the time field or meta field can be "
"part of shard key pattern",
metaFieldName &&
(elem.fieldNameStringData() == *metaFieldName ||
elem.fieldNameStringData().startsWith(*metaFieldName + ".")));
}
}
KeyPattern keyPattern(
uassertStatusOK(timeseries::createBucketsShardKeySpecFromTimeseriesShardKeySpec(
*request.getTimeseries(), *request.getShardKey())));
return TranslatedRequestParams(
resolvedNamespace,
keyPattern,
resolveCollationForUserQueries(opCtx, resolvedNamespace, request.getCollation()));
}
/**
* Helper function to log the end of the shard collection event.
*/
void logEndCreateCollection(
OperationContext* opCtx,
const NamespaceString& originalNss,
const boost::optional<CreateCollectionResponse>& result,
const boost::optional<bool>& collectionEmpty,
const boost::optional<InitialSplitPolicy::ShardCollectionConfig>& initialChunks) {
BSONObjBuilder collectionDetail;
result->getCollectionUUID()->appendToBuilder(&collectionDetail, "uuid");
collectionDetail.append("placementVersion", result->getCollectionVersion().toString());
if (collectionEmpty)
collectionDetail.append("empty", *collectionEmpty);
if (initialChunks)
collectionDetail.appendNumber("numChunks",
static_cast<long long>(initialChunks->chunks.size()));
ShardingLogging::get(opCtx)->logChange(
opCtx, "shardCollection.end", originalNss, collectionDetail.obj());
}
/**
* If the optimized path can be taken, ensure the collection is already created in all the
* participant shards.
*/
void createCollectionOnNonPrimaryShards(
OperationContext* opCtx,
const OperationSessionInfo& osi,
const boost::optional<UUID>& collectionUUID,
const boost::optional<InitialSplitPolicy::ShardCollectionConfig>& initialChunks,
const NamespaceString& nss) {
LOGV2_DEBUG(5277905, 2, "Create collection createCollectionOnNonPrimaryShards", logAttrs(nss));
std::vector<AsyncRequestsSender::Request> requests;
std::set<ShardId> initializedShards;
auto dbPrimaryShardId = ShardingState::get(opCtx)->shardId();
NamespaceStringOrUUID nssOrUUID{nss.dbName(), *collectionUUID};
auto [collOptions, indexes, idIndex] = getCollectionOptionsAndIndexes(opCtx, nssOrUUID);
for (const auto& chunk : initialChunks->chunks) {
const auto& chunkShardId = chunk.getShard();
if (chunkShardId == dbPrimaryShardId ||
initializedShards.find(chunkShardId) != initializedShards.end()) {
continue;
}
ShardsvrCreateCollectionParticipant createCollectionParticipantRequest(nss);
createCollectionParticipantRequest.setCollectionUUID(*collectionUUID);
createCollectionParticipantRequest.setOptions(collOptions);
createCollectionParticipantRequest.setIdIndex(idIndex);
createCollectionParticipantRequest.setIndexes(indexes);
requests.emplace_back(chunkShardId,
CommandHelpers::appendMajorityWriteConcern(
createCollectionParticipantRequest.toBSON(osi.toBSON())));
initializedShards.emplace(chunkShardId);
}
if (!requests.empty()) {
auto responses = gatherResponses(opCtx,
nss.dbName(),
ReadPreferenceSetting(ReadPreference::PrimaryOnly),
Shard::RetryPolicy::kIdempotent,
requests);
// If any shards fail to create the collection, fail the entire shardCollection command
// (potentially leaving incomplely created sharded collection)
for (auto&& response : responses) {
auto shardResponse = uassertStatusOKWithContext(
std::move(response.swResponse),
str::stream() << "Unable to create collection " << nss.toStringForErrorMsg()
<< " on " << response.shardId);
auto status = getStatusFromCommandResult(shardResponse.data);
uassertStatusOK(status.withContext(str::stream() << "Unable to create collection "
<< nss.toStringForErrorMsg() << " on "
<< response.shardId));
auto wcStatus = getWriteConcernStatusFromCommandResult(shardResponse.data);
uassertStatusOK(wcStatus.withContext(str::stream() << "Unable to create collection "
<< nss.toStringForErrorMsg()
<< " on " << response.shardId));
}
}
}
/**
* Given the appropiate split policy, create the initial chunks.
*/
boost::optional<InitialSplitPolicy::ShardCollectionConfig> createChunks(
OperationContext* opCtx,
const ShardKeyPattern& shardKeyPattern,
const boost::optional<UUID>& collectionUUID,
const std::unique_ptr<InitialSplitPolicy>& splitPolicy,
const NamespaceString& nss) {
LOGV2_DEBUG(5277904, 2, "Create collection createChunks", logAttrs(nss));
boost::optional<InitialSplitPolicy::ShardCollectionConfig> initialChunks =
splitPolicy->createFirstChunks(
opCtx, shardKeyPattern, {*collectionUUID, ShardingState::get(opCtx)->shardId()});
// There must be at least one chunk.
invariant(initialChunks);
invariant(!initialChunks->chunks.empty());
return initialChunks;
}
void promoteCriticalSectionsOnCoordinatorToBlockReads(OperationContext* opCtx,