/
write_ops_exec.cpp
3180 lines (2775 loc) · 139 KB
/
write_ops_exec.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) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/db/ops/write_ops_exec.h"
#include "mongo/base/error_codes.h"
#include <absl/container/flat_hash_map.h>
#include <absl/hash/hash.h>
#include <algorithm>
#include <boost/cstdint.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/none.hpp>
#include <boost/optional/optional.hpp>
#include <boost/smart_ptr.hpp>
#include <cstdint>
#include <fmt/format.h>
#include <functional>
#include <iterator>
#include <memory>
#include <mutex>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include "mongo/base/counter.h"
#include "mongo/base/string_data.h"
#include "mongo/bson/bsonelement.h"
#include "mongo/bson/bsonelement_comparator.h"
#include "mongo/bson/bsontypes.h"
#include "mongo/bson/oid.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/auth/resource_pattern.h"
#include "mongo/db/catalog/clustered_collection_options_gen.h"
#include "mongo/db/catalog/clustered_collection_util.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/collection_options.h"
#include "mongo/db/catalog/collection_uuid_mismatch.h"
#include "mongo/db/catalog/collection_write_path.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/document_validation.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/feature_compatibility_version.h"
#include "mongo/db/commands/server_status_metric.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/concurrency/lock_manager_defs.h"
#include "mongo/db/curop.h"
#include "mongo/db/curop_failpoint_helpers.h"
#include "mongo/db/curop_metrics.h"
#include "mongo/db/database_name.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/error_labels.h"
#include "mongo/db/feature_flag.h"
#include "mongo/db/introspect.h"
#include "mongo/db/matcher/expression.h"
#include "mongo/db/matcher/expression_leaf.h"
#include "mongo/db/not_primary_error_tracker.h"
#include "mongo/db/ops/delete_request_gen.h"
#include "mongo/db/ops/insert.h"
#include "mongo/db/ops/parsed_delete.h"
#include "mongo/db/ops/parsed_update.h"
#include "mongo/db/ops/parsed_writes_common.h"
#include "mongo/db/ops/update_request.h"
#include "mongo/db/ops/write_ops.h"
#include "mongo/db/ops/write_ops_gen.h"
#include "mongo/db/ops/write_ops_retryability.h"
#include "mongo/db/pipeline/legacy_runtime_constants_gen.h"
#include "mongo/db/pipeline/variables.h"
#include "mongo/db/query/canonical_query.h"
#include "mongo/db/query/collection_query_info.h"
#include "mongo/db/query/explain_options.h"
#include "mongo/db/query/get_executor.h"
#include "mongo/db/query/plan_executor.h"
#include "mongo/db/query/plan_explainer.h"
#include "mongo/db/query/plan_summary_stats.h"
#include "mongo/db/query/plan_yield_policy.h"
#include "mongo/db/query/query_knobs_gen.h"
#include "mongo/db/record_id_helpers.h"
#include "mongo/db/repl/optime.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl/tenant_migration_access_blocker_util.h"
#include "mongo/db/repl/tenant_migration_conflict_info.h"
#include "mongo/db/repl/tenant_migration_decoration.h"
#include "mongo/db/resource_yielder.h"
#include "mongo/db/s/collection_sharding_state.h"
#include "mongo/db/s/operation_sharding_state.h"
#include "mongo/db/s/query_analysis_writer.h"
#include "mongo/db/s/scoped_collection_metadata.h"
#include "mongo/db/server_options.h"
#include "mongo/db/shard_role.h"
#include "mongo/db/stats/counters.h"
#include "mongo/db/stats/resource_consumption_metrics.h"
#include "mongo/db/stats/server_write_concern_metrics.h"
#include "mongo/db/stats/top.h"
#include "mongo/db/storage/duplicate_key_error_info.h"
#include "mongo/db/storage/recovery_unit.h"
#include "mongo/db/storage/snapshot.h"
#include "mongo/db/storage/storage_parameters_gen.h"
#include "mongo/db/storage/write_unit_of_work.h"
#include "mongo/db/timeseries/bucket_catalog/bucket_catalog.h"
#include "mongo/db/timeseries/bucket_catalog/bucket_catalog_internal.h"
#include "mongo/db/timeseries/bucket_catalog/bucket_identifiers.h"
#include "mongo/db/timeseries/bucket_catalog/closed_bucket.h"
#include "mongo/db/timeseries/bucket_catalog/write_batch.h"
#include "mongo/db/timeseries/bucket_compression.h"
#include "mongo/db/timeseries/bucket_compression_failure.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/timeseries/timeseries_update_delete_util.h"
#include "mongo/db/timeseries/timeseries_write_util.h"
#include "mongo/db/transaction/retryable_writes_stats.h"
#include "mongo/db/transaction/transaction_api.h"
#include "mongo/db/transaction/transaction_participant.h"
#include "mongo/db/transaction/transaction_participant_resource_yielder.h"
#include "mongo/db/transaction_resources.h"
#include "mongo/db/update/document_diff_applier.h"
#include "mongo/db/update/path_support.h"
#include "mongo/db/update/update_oplog_entry_serialization.h"
#include "mongo/executor/inline_executor.h"
#include "mongo/logv2/log.h"
#include "mongo/logv2/log_attr.h"
#include "mongo/logv2/log_component.h"
#include "mongo/logv2/log_severity.h"
#include "mongo/logv2/redaction.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/platform/compiler.h"
#include "mongo/rpc/message.h"
#include "mongo/s/analyze_shard_key_common_gen.h"
#include "mongo/s/analyze_shard_key_role.h"
#include "mongo/s/query_analysis_sampler_util.h"
#include "mongo/s/sharding_feature_flags_gen.h"
#include "mongo/s/type_collection_common_types_gen.h"
#include "mongo/s/would_change_owning_shard_exception.h"
#include "mongo/s/write_ops/batched_command_response.h"
#include "mongo/s/write_ops/batched_upsert_detail.h"
#include "mongo/stdx/unordered_map.h"
#include "mongo/util/decorable.h"
#include "mongo/util/duration.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/future.h"
#include "mongo/util/log_and_backoff.h"
#include "mongo/util/namespace_string_util.h"
#include "mongo/util/out_of_line_executor.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/str.h"
#include "mongo/util/timer.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kWrite
namespace mongo::write_ops_exec {
// Convention in this file: generic helpers go in the anonymous namespace. Helpers that are for a
// single type of operation are static functions defined above their caller.
namespace {
MONGO_FAIL_POINT_DEFINE(failAllInserts);
MONGO_FAIL_POINT_DEFINE(failAllUpdates);
MONGO_FAIL_POINT_DEFINE(failAllRemoves);
MONGO_FAIL_POINT_DEFINE(hangBeforeChildRemoveOpFinishes);
MONGO_FAIL_POINT_DEFINE(hangBeforeChildRemoveOpIsPopped);
MONGO_FAIL_POINT_DEFINE(hangAfterAllChildRemoveOpsArePopped);
MONGO_FAIL_POINT_DEFINE(hangWriteBeforeWaitingForMigrationDecision);
MONGO_FAIL_POINT_DEFINE(hangDuringBatchInsert);
MONGO_FAIL_POINT_DEFINE(hangDuringBatchUpdate);
MONGO_FAIL_POINT_DEFINE(hangAfterBatchUpdate);
MONGO_FAIL_POINT_DEFINE(hangDuringBatchRemove);
MONGO_FAIL_POINT_DEFINE(hangAndFailAfterDocumentInsertsReserveOpTimes);
// The withLock fail points are for testing interruptability of these operations, so they will not
// themselves check for interrupt.
MONGO_FAIL_POINT_DEFINE(hangWithLockDuringBatchInsert);
MONGO_FAIL_POINT_DEFINE(hangWithLockDuringBatchUpdate);
MONGO_FAIL_POINT_DEFINE(hangWithLockDuringBatchRemove);
MONGO_FAIL_POINT_DEFINE(failAtomicTimeseriesWrites);
MONGO_FAIL_POINT_DEFINE(hangTimeseriesInsertBeforeCommit);
MONGO_FAIL_POINT_DEFINE(hangTimeseriesInsertBeforeWrite);
MONGO_FAIL_POINT_DEFINE(failUnorderedTimeseriesInsert);
/**
* Metrics group for the `updateMany` and `deleteMany` operations. For each
* operation, the `duration` and `numDocs` will contribute to aggregated total
* and max metrics.
*/
class MultiUpdateDeleteMetrics {
public:
void operator()(Microseconds duration, size_t numDocs) {
_durationTotalMicroseconds.increment(durationCount<Microseconds>(duration));
_durationTotalMs.set(
durationCount<Milliseconds>(Microseconds{_durationTotalMicroseconds.get()}));
_durationMaxMs.setToMax(durationCount<Milliseconds>(duration));
_numDocsTotal.increment(numDocs);
_numDocsMax.setToMax(numDocs);
}
private:
/**
* To avoid rapid accumulation of roundoff error in the duration total, it
* is maintained precisely, and we arrange for the corresponding
* Millisecond metric to hold an exported low-res image of it.
*/
Counter64 _durationTotalMicroseconds;
Atomic64Metric& _durationTotalMs =
*MetricBuilder<Atomic64Metric>("query.updateDeleteManyDurationTotalMs");
Atomic64Metric& _durationMaxMs =
*MetricBuilder<Atomic64Metric>("query.updateDeleteManyDurationMaxMs");
Counter64& _numDocsTotal =
*MetricBuilder<Counter64>{"query.updateDeleteManyDocumentsTotalCount"};
Atomic64Metric& _numDocsMax =
*MetricBuilder<Atomic64Metric>("query.updateDeleteManyDocumentsMaxCount");
};
MultiUpdateDeleteMetrics collectMultiUpdateDeleteMetrics;
void finishCurOp(OperationContext* opCtx, CurOp* curOp) {
try {
curOp->done();
auto executionTimeMicros = duration_cast<Microseconds>(curOp->elapsedTimeExcludingPauses());
curOp->debug().additiveMetrics.executionTime = executionTimeMicros;
recordCurOpMetrics(opCtx);
Top::get(opCtx->getServiceContext())
.record(opCtx,
curOp->getNSS(),
curOp->getLogicalOp(),
Top::LockType::WriteLocked,
durationCount<Microseconds>(curOp->elapsedTimeExcludingPauses()),
curOp->isCommand(),
curOp->getReadWriteType());
if (!curOp->debug().errInfo.isOK()) {
LOGV2_DEBUG(20886,
3,
"Caught Assertion in finishCurOp",
"operation"_attr = redact(logicalOpToString(curOp->getLogicalOp())),
"error"_attr = curOp->debug().errInfo.toString());
}
// Mark the op as complete, log it and profile if the op should be sampled for profiling.
logOperationAndProfileIfNeeded(opCtx, curOp);
} catch (const DBException& ex) {
// We need to ignore all errors here. We don't want a successful op to fail because of a
// failure to record stats. We also don't want to replace the error reported for an op that
// is failing.
LOGV2(20887, "Ignoring error from finishCurOp", "error"_attr = redact(ex));
}
}
void makeCollection(OperationContext* opCtx, const NamespaceString& ns) {
writeConflictRetry(opCtx, "implicit collection creation", ns, [&opCtx, &ns] {
AutoGetDb autoDb(opCtx, ns.dbName(), MODE_IX);
Lock::CollectionLock collLock(opCtx, ns, MODE_IX);
assertCanWrite_inlock(opCtx, ns);
if (!CollectionCatalog::get(opCtx)->lookupCollectionByNamespace(
opCtx, ns)) { // someone else may have beat us to it.
uassertStatusOK(userAllowedCreateNS(opCtx, ns));
// TODO (SERVER-77915): Remove once 8.0 becomes last LTS.
// TODO (SERVER-82066): Update handling for direct connections.
// TODO (SERVER-81937): Update handling for transactions.
// TODO (SERVER-85366): Update handling for retryable writes.
boost::optional<OperationShardingState::ScopedAllowImplicitCollectionCreate_UNSAFE>
allowCollectionCreation;
const auto fcvSnapshot = serverGlobalParams.featureCompatibility.acquireFCVSnapshot();
if (!fcvSnapshot.isVersionInitialized() ||
!feature_flags::gTrackUnshardedCollectionsOnShardingCatalog.isEnabled(
fcvSnapshot) ||
!OperationShardingState::get(opCtx).isComingFromRouter(opCtx) ||
(opCtx->inMultiDocumentTransaction() || opCtx->isRetryableWrite())) {
allowCollectionCreation.emplace(opCtx);
}
WriteUnitOfWork wuow(opCtx);
CollectionOptions defaultCollectionOptions;
if (auto fp = globalFailPointRegistry().find("clusterAllCollectionsByDefault");
fp && fp->shouldFail() && !clustered_util::requiresLegacyFormat(ns)) {
defaultCollectionOptions.clusteredIndex =
clustered_util::makeDefaultClusteredIdIndex();
}
auto db = autoDb.ensureDbExists(opCtx);
uassertStatusOK(db->userCreateNS(opCtx, ns, defaultCollectionOptions));
wuow.commit();
}
});
}
void insertDocumentsAtomically(OperationContext* opCtx,
const CollectionAcquisition& collection,
std::vector<InsertStatement>::iterator begin,
std::vector<InsertStatement>::iterator end,
bool fromMigrate) {
// Intentionally not using writeConflictRetry. That is handled by the caller so it can react to
// oversized batches.
WriteUnitOfWork wuow(opCtx);
// Acquire optimes and fill them in for each item in the batch.
// This must only be done for doc-locking storage engines, which are allowed to insert oplog
// documents out-of-timestamp-order. For other storage engines, the oplog entries must be
// physically written in timestamp order, so we defer optime assignment until the oplog is about
// to be written. Multidocument transactions should not generate opTimes because they are
// generated at the time of commit.
auto batchSize = std::distance(begin, end);
auto replCoord = repl::ReplicationCoordinator::get(opCtx);
auto inTransaction = opCtx->inMultiDocumentTransaction();
if (!inTransaction && !replCoord->isOplogDisabledFor(opCtx, collection.nss())) {
// Populate 'slots' with new optimes for each insert.
// This also notifies the storage engine of each new timestamp.
auto oplogSlots = repl::getNextOpTimes(opCtx, batchSize);
auto slot = oplogSlots.begin();
for (auto it = begin; it != end; it++) {
it->oplogSlot = *slot++;
}
}
hangAndFailAfterDocumentInsertsReserveOpTimes.executeIf(
[&](const BSONObj& data) {
hangAndFailAfterDocumentInsertsReserveOpTimes.pauseWhileSet(opCtx);
const auto skipFail = data["skipFail"];
if (!skipFail || !skipFail.boolean()) {
uasserted(51269,
"hangAndFailAfterDocumentInsertsReserveOpTimes fail point enabled");
}
},
[&](const BSONObj& data) {
// Check if the failpoint specifies no collection or matches the existing one.
const auto fpNss = NamespaceStringUtil::parseFailPointData(data, "collectionNS");
return fpNss.isEmpty() || collection.nss() == fpNss;
});
uassertStatusOK(collection_internal::insertDocuments(opCtx,
collection.getCollectionPtr(),
begin,
end,
&CurOp::get(opCtx)->debug(),
fromMigrate));
wuow.commit();
}
/**
* Returns a OperationNotSupportedInTransaction error Status if we are in a transaction and
* operating on a capped collection.
*
* The behavior of an operation against a capped collection may differ across replica set members,
* where it can succeed on one member and fail on another, crashing the failing member. Prepared
* transactions are not allowed to fail, so capped collections will not be allowed on shards.
* Even in the unsharded case, capped collections are still problematic with transactions because
* they only allow one operation at a time because they enforce insertion order with a MODE_X
* collection lock, which we cannot hold in transactions.
*/
Status checkIfTransactionOnCappedColl(OperationContext* opCtx, const CollectionPtr& collection) {
if (opCtx->inMultiDocumentTransaction() && collection->isCapped()) {
return {ErrorCodes::OperationNotSupportedInTransaction,
str::stream() << "Collection '" << collection->ns().toStringForErrorMsg()
<< "' is a capped collection. Writes in transactions are not allowed "
"on capped collections."};
}
return Status::OK();
}
void assertTimeseriesBucketsCollectionNotFound(const NamespaceString& ns) {
uasserted(ErrorCodes::NamespaceNotFound,
str::stream() << "Buckets collection not found for time-series collection "
<< ns.getTimeseriesViewNamespace().toStringForErrorMsg());
}
template <typename T>
StmtId getStmtIdForWriteOp(OperationContext* opCtx, const T& wholeOp, size_t opIndex) {
return opCtx->isRetryableWrite() ? write_ops::getStmtIdForWriteAt(wholeOp, opIndex)
: kUninitializedStmtId;
}
SingleWriteResult makeWriteResultForInsertOrDeleteRetry() {
SingleWriteResult res;
res.setN(1);
res.setNModified(0);
return res;
}
// Returns the flags that determine the type of document validation we want to
// perform. First item in the tuple determines whether to bypass document validation altogether,
// second item determines if _safeContent_ array can be modified in an encrypted collection.
std::tuple<bool, bool> getDocumentValidationFlags(OperationContext* opCtx,
const write_ops::WriteCommandRequestBase& req,
const boost::optional<TenantId>& tenantId) {
auto& encryptionInfo = req.getEncryptionInformation();
const bool fleCrudProcessed = getFleCrudProcessed(opCtx, encryptionInfo, tenantId);
return std::make_tuple(req.getBypassDocumentValidation(), fleCrudProcessed);
}
} // namespace
bool handleError(OperationContext* opCtx,
const DBException& ex,
const NamespaceString& nss,
const bool ordered,
bool isMultiUpdate,
const boost::optional<UUID> sampleId,
WriteResult* out) {
NotPrimaryErrorTracker::get(opCtx->getClient()).recordError(ex.code());
auto& curOp = *CurOp::get(opCtx);
curOp.debug().errInfo = ex.toStatus();
if (ErrorCodes::isInterruption(ex.code())) {
throw; // These have always failed the whole batch.
}
if (ErrorCodes::WouldChangeOwningShard == ex.code()) {
if (analyze_shard_key::supportsPersistingSampledQueries(opCtx) && sampleId) {
// Sample the diff before rethrowing the error since mongos will handle this update by
// by performing a delete on the shard owning the pre-image doc and an insert on the
// shard owning the post-image doc. As a result, this update will not show up in the
// OpObserver as an update.
auto wouldChangeOwningShardInfo = ex.extraInfo<WouldChangeOwningShardInfo>();
invariant(wouldChangeOwningShardInfo);
analyze_shard_key::QueryAnalysisWriter::get(opCtx)
->addDiff(*sampleId,
nss,
*wouldChangeOwningShardInfo->getUuid(),
wouldChangeOwningShardInfo->getPreImage(),
wouldChangeOwningShardInfo->getPostImage())
.getAsync([](auto) {});
}
throw; // Fail this write so mongos can retry
}
auto txnParticipant = TransactionParticipant::get(opCtx);
if (txnParticipant && opCtx->inMultiDocumentTransaction()) {
if (isTransientTransactionError(
ex.code(), false /* hasWriteConcernError */, false /* isCommitOrAbort */)) {
// Tell the client to try the whole txn again, by returning ok: 0 with errorLabels.
throw;
}
// If we are in a transaction, we must fail the whole batch.
out->results.emplace_back(ex.toStatus());
txnParticipant.abortTransaction(opCtx);
return false;
}
if (ex.code() == ErrorCodes::StaleDbVersion || ErrorCodes::isStaleShardVersionError(ex) ||
ex.code() == ErrorCodes::ShardCannotRefreshDueToLocksHeld ||
ex.code() == ErrorCodes::CannotImplicitlyCreateCollection) {
if (!opCtx->getClient()->isInDirectClient() &&
ex.code() != ErrorCodes::CannotImplicitlyCreateCollection) {
auto& oss = OperationShardingState::get(opCtx);
oss.setShardingOperationFailedStatus(ex.toStatus());
}
// For routing errors, it is guaranteed that all subsequent operations will fail
// with the same cause, so don't try doing any more operations. The command reply serializer
// will handle repeating this error for unordered writes.
// (On the other hand, ShardCannotRefreshDueToLocksHeld is caused by a temporary inability
// to access a stable version of the cache during the execution of the batch; the error is
// returned back to the router to leverage its capability of selectively retrying
// operations).
out->results.emplace_back(ex.toStatus());
return false;
}
if (ErrorCodes::isTenantMigrationError(ex)) {
// Multiple not-idempotent updates are not safe to retry at the cloud level. We treat these
// the same as an interruption due to a repl state change and fail the whole batch.
if (isMultiUpdate) {
if (ex.code() != ErrorCodes::TenantMigrationConflict) {
uassertStatusOK(kNonRetryableTenantMigrationStatus);
}
// If the migration is active, we throw a different code that will be caught higher up
// and replaced with a non-retryable code after the migration finishes to avoid wasted
// retries.
auto migrationConflictInfo = ex.toStatus().extraInfo<TenantMigrationConflictInfo>();
uassertStatusOK(
Status(NonRetryableTenantMigrationConflictInfo(
migrationConflictInfo->getMigrationId(),
migrationConflictInfo->getTenantMigrationAccessBlocker()),
"Multi update must block until this tenant migration commits or aborts"));
}
// If an op fails due to a TenantMigrationError then subsequent ops will also fail due to a
// migration blocking, committing, or aborting.
out->results.emplace_back(ex.toStatus());
return false;
}
out->results.emplace_back(ex.toStatus());
return !ordered;
}
bool getFleCrudProcessed(OperationContext* opCtx,
const boost::optional<EncryptionInformation>& encryptionInfo,
const boost::optional<TenantId>& tenantId) {
if (encryptionInfo && encryptionInfo->getCrudProcessed().value_or(false)) {
uassert(6666201,
"External users cannot have crudProcessed enabled",
AuthorizationSession::get(opCtx->getClient())
->isAuthorizedForActionsOnResource(
ResourcePattern::forClusterResource(tenantId), ActionType::internal));
return true;
}
return false;
}
/**
* Returns true if caller should try to insert more documents. Does nothing else if batch is empty.
*/
bool insertBatchAndHandleErrors(OperationContext* opCtx,
const NamespaceString& nss,
const boost::optional<mongo::UUID>& collectionUUID,
bool ordered,
std::vector<InsertStatement>& batch,
LastOpFixer* lastOpFixer,
WriteResult* out,
OperationSource source) {
if (batch.empty())
return true;
auto& curOp = *CurOp::get(opCtx);
CurOpFailpointHelpers::waitWhileFailPointEnabled(
&hangDuringBatchInsert,
opCtx,
"hangDuringBatchInsert",
[&nss]() {
LOGV2(20889,
"Batch insert - hangDuringBatchInsert fail point enabled for a namespace. "
"Blocking until fail point is disabled",
logAttrs(nss));
},
nss);
if (MONGO_unlikely(failAllInserts.shouldFail())) {
uasserted(ErrorCodes::InternalError, "failAllInserts failpoint active!");
}
boost::optional<CollectionAcquisition> collection;
auto acquireCollection = [&] {
while (true) {
collection.emplace(mongo::acquireCollection(
opCtx,
CollectionAcquisitionRequest::fromOpCtx(
opCtx, nss, AcquisitionPrerequisites::kWrite, collectionUUID),
fixLockModeForSystemDotViewsChanges(nss, MODE_IX)));
if (collection->exists()) {
break;
}
if (source == OperationSource::kTimeseriesInsert) {
assertTimeseriesBucketsCollectionNotFound(nss);
}
collection.reset(); // unlock.
makeCollection(opCtx, nss);
}
curOp.raiseDbProfileLevel(
CollectionCatalog::get(opCtx)->getDatabaseProfileLevel(nss.dbName()));
assertCanWrite_inlock(opCtx, nss);
CurOpFailpointHelpers::waitWhileFailPointEnabled(
&hangWithLockDuringBatchInsert, opCtx, "hangWithLockDuringBatchInsert");
};
auto txnParticipant = TransactionParticipant::get(opCtx);
auto inTxn = txnParticipant && opCtx->inMultiDocumentTransaction();
bool shouldProceedWithBatchInsert = true;
try {
acquireCollection();
} catch (const DBException& ex) {
collection.reset();
if (inTxn) {
// It is not safe to ignore errors from collection creation while inside a
// multi-document transaction.
auto canContinue = handleError(
opCtx, ex, nss, ordered, false /* multiUpdate */, boost::none /* sampleId */, out);
invariant(!canContinue);
return false;
}
// Otherwise, proceed as though the batch insert block failed, since the batch insert block
// assumes `acquireCollection` is successful.
shouldProceedWithBatchInsert = false;
}
if (shouldProceedWithBatchInsert) {
try {
if (!collection->getCollectionPtr()->isCapped() && !inTxn && batch.size() > 1) {
// First try doing it all together. If all goes well, this is all we need to do.
// See Collection::_insertDocuments for why we do all capped inserts one-at-a-time.
lastOpFixer->startingOp(nss);
insertDocumentsAtomically(opCtx,
*collection,
batch.begin(),
batch.end(),
source == OperationSource::kFromMigrate);
lastOpFixer->finishedOpSuccessfully();
globalOpCounters.gotInserts(batch.size());
SingleWriteResult result;
result.setN(1);
std::fill_n(std::back_inserter(out->results), batch.size(), std::move(result));
if (source != OperationSource::kTimeseriesInsert) {
ServerWriteConcernMetrics::get(opCtx)->recordWriteConcernForInserts(
opCtx->getWriteConcern(), batch.size());
curOp.debug().additiveMetrics.incrementNinserted(batch.size());
}
return true;
}
} catch (const DBException&) {
// Ignore this failure and behave as if we never tried to do the combined batch
// insert. The loop below will handle reporting any non-transient errors.
collection.reset();
}
}
// Try to insert the batch one-at-a-time. This path is executed for singular batches,
// multi-statement transactions, capped collections, and if we failed all-at-once inserting.
for (auto it = batch.begin(); it != batch.end(); ++it) {
globalOpCounters.gotInsert();
if (source != OperationSource::kTimeseriesInsert) {
ServerWriteConcernMetrics::get(opCtx)->recordWriteConcernForInsert(
opCtx->getWriteConcern());
}
try {
writeConflictRetry(opCtx, "insert", nss, [&] {
try {
if (!collection)
acquireCollection();
// Transactions are not allowed to operate on capped collections.
uassertStatusOK(
checkIfTransactionOnCappedColl(opCtx, collection->getCollectionPtr()));
lastOpFixer->startingOp(nss);
insertDocumentsAtomically(
opCtx, *collection, it, it + 1, source == OperationSource::kFromMigrate);
lastOpFixer->finishedOpSuccessfully();
SingleWriteResult result;
result.setN(1);
out->results.emplace_back(std::move(result));
if (source != OperationSource::kTimeseriesInsert) {
curOp.debug().additiveMetrics.incrementNinserted(1);
}
} catch (...) {
// Release the lock following any error if we are not in multi-statement
// transaction. Among other things, this ensures that we don't sleep in the WCE
// retry loop with the lock held.
// If we are in multi-statement transaction and under a WUOW, we will
// not actually release the lock.
collection.reset();
throw;
}
});
} catch (const DBException& ex) {
bool canContinue = handleError(
opCtx, ex, nss, ordered, false /* multiUpdate */, boost::none /* sampleId */, out);
if (!canContinue) {
// Failed in ordered batch, or in a transaction, or from some unrecoverable error.
return false;
}
}
}
return true;
}
boost::optional<BSONObj> advanceExecutor(OperationContext* opCtx,
PlanExecutor* exec,
bool isRemove,
StringData operationName) {
BSONObj value;
PlanExecutor::ExecState state;
try {
state = exec->getNext(&value, nullptr);
} catch (const StorageUnavailableException&) {
throw;
} catch (DBException& exception) {
auto&& explainer = exec->getPlanExplainer();
auto&& [stats, _] = explainer.getWinningPlanStats(ExplainOptions::Verbosity::kExecStats);
LOGV2_WARNING(7267501,
"Plan executor error",
"operation"_attr = operationName,
"error"_attr = exception.toStatus(),
"stats"_attr = redact(stats));
exception.addContext("Plan executor error during " + operationName);
throw;
}
if (PlanExecutor::ADVANCED == state) {
return {std::move(value)};
}
invariant(state == PlanExecutor::IS_EOF);
return boost::none;
}
UpdateResult performUpdate(OperationContext* opCtx,
const NamespaceString& nss,
CurOp* curOp,
bool inTransaction,
bool remove,
bool upsert,
const boost::optional<mongo::UUID>& collectionUUID,
boost::optional<BSONObj>& docFound,
UpdateRequest* updateRequest) {
auto [isTimeseriesViewUpdate, nsString] =
timeseries::isTimeseriesViewRequest(opCtx, *updateRequest);
if (isTimeseriesViewUpdate) {
checkCollectionUUIDMismatch(
opCtx, nsString.getTimeseriesViewNamespace(), nullptr, collectionUUID);
}
// TODO SERVER-76583: Remove this check.
uassert(7314600,
"Retryable findAndModify on a timeseries is not supported",
!isTimeseriesViewUpdate || !updateRequest->shouldReturnAnyDocs() ||
!opCtx->isRetryableWrite());
CurOpFailpointHelpers::waitWhileFailPointEnabled(
&hangDuringBatchUpdate,
opCtx,
"hangDuringBatchUpdate",
[&nss]() {
LOGV2(7280400,
"Batch update - hangDuringBatchUpdate fail point enabled for a namespace. "
"Blocking until fail point is disabled",
logAttrs(nss));
},
nss);
if (MONGO_unlikely(failAllUpdates.shouldFail())) {
uasserted(ErrorCodes::InternalError, "failAllUpdates failpoint active!");
}
auto collection =
acquireCollection(opCtx,
CollectionAcquisitionRequest::fromOpCtx(
opCtx, nsString, AcquisitionPrerequisites::kWrite, collectionUUID),
MODE_IX);
auto dbName = nsString.dbName();
Database* db = [&]() {
AutoGetDb autoDb(opCtx, dbName, MODE_IX);
return autoDb.ensureDbExists(opCtx);
}();
invariant(DatabaseHolder::get(opCtx)->getDb(opCtx, dbName));
curOp->raiseDbProfileLevel(CollectionCatalog::get(opCtx)->getDatabaseProfileLevel(dbName));
assertCanWrite_inlock(opCtx, nsString);
// TODO SERVER-50983: Create abstraction for creating collection when using
// AutoGetCollection Create the collection if it does not exist when performing an upsert
// because the update stage does not create its own collection
if (!collection.exists() && upsert) {
CollectionWriter collectionWriter(opCtx, &collection);
uassertStatusOK(userAllowedCreateNS(opCtx, nsString));
// TODO (SERVER-77915): Remove once 8.0 becomes last LTS.
// TODO (SERVER-82066): Update handling for direct connections.
// TODO (SERVER-81937): Update handling for transactions.
// TODO (SERVER-85366): Update handling for retryable writes.
boost::optional<OperationShardingState::ScopedAllowImplicitCollectionCreate_UNSAFE>
allowCollectionCreation;
const auto fcvSnapshot = serverGlobalParams.featureCompatibility.acquireFCVSnapshot();
if (!fcvSnapshot.isVersionInitialized() ||
!feature_flags::gTrackUnshardedCollectionsOnShardingCatalog.isEnabled(fcvSnapshot) ||
!OperationShardingState::get(opCtx).isComingFromRouter(opCtx) ||
(opCtx->inMultiDocumentTransaction() || opCtx->isRetryableWrite())) {
allowCollectionCreation.emplace(opCtx);
}
WriteUnitOfWork wuow(opCtx);
ScopedLocalCatalogWriteFence scopedLocalCatalogWriteFence(opCtx, &collection);
CollectionOptions defaultCollectionOptions;
uassertStatusOK(db->userCreateNS(opCtx, nsString, defaultCollectionOptions));
wuow.commit();
}
if (collection.exists() && collection.getCollectionPtr()->isCapped()) {
uassert(
ErrorCodes::OperationNotSupportedInTransaction,
str::stream() << "Collection '" << collection.nss().toStringForErrorMsg()
<< "' is a capped collection. Writes in transactions are not allowed on "
"capped collections.",
!inTransaction);
}
if (isTimeseriesViewUpdate) {
timeseries::timeseriesRequestChecks<UpdateRequest>(
collection.getCollectionPtr(), updateRequest, timeseries::updateRequestCheckFunction);
timeseries::timeseriesHintTranslation<UpdateRequest>(collection.getCollectionPtr(),
updateRequest);
}
ParsedUpdate parsedUpdate(opCtx,
updateRequest,
collection.getCollectionPtr(),
false /*forgoOpCounterIncrements*/,
isTimeseriesViewUpdate);
uassertStatusOK(parsedUpdate.parseRequest());
const auto exec = uassertStatusOK(
getExecutorUpdate(&curOp->debug(), collection, &parsedUpdate, boost::none /* verbosity
*/));
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
CurOp::get(opCtx)->setPlanSummary_inlock(exec->getPlanExplainer().getPlanSummary());
}
docFound = advanceExecutor(opCtx,
exec.get(),
remove,
updateRequest->shouldReturnAnyDocs() ? "findAndModify" : "update");
// Nothing after advancing the plan executor should throw a WriteConflictException,
// so the following bookkeeping with execution stats won't end up being done
// multiple times.
PlanSummaryStats summaryStats;
auto&& explainer = exec->getPlanExplainer();
explainer.getSummaryStats(&summaryStats);
if (collection.exists()) {
CollectionQueryInfo::get(collection.getCollectionPtr())
.notifyOfQuery(opCtx, collection.getCollectionPtr(), summaryStats);
}
auto updateResult = exec->getUpdateResult();
write_ops_exec::recordUpdateResultInOpDebug(updateResult, &curOp->debug());
curOp->debug().setPlanSummaryMetrics(summaryStats);
if (updateResult.containsDotsAndDollarsField) {
// If it's an upsert, increment 'inserts' metric, otherwise increment 'updates'.
dotsAndDollarsFieldsCounters.incrementForUpsert(!updateResult.upsertedId.isEmpty());
}
if (curOp->shouldDBProfile()) {
auto&& [stats, _] = explainer.getWinningPlanStats(ExplainOptions::Verbosity::kExecStats);
curOp->debug().execStats = std::move(stats);
}
if (docFound) {
ResourceConsumption::DocumentUnitCounter docUnitsReturned;
docUnitsReturned.observeOne(docFound->objsize());
auto& metricsCollector = ResourceConsumption::MetricsCollector::get(opCtx);
metricsCollector.incrementDocUnitsReturned(curOp->getNS(), docUnitsReturned);
}
CurOpFailpointHelpers::waitWhileFailPointEnabled(
&hangAfterBatchUpdate, opCtx, "hangAfterBatchUpdate");
return updateResult;
}
long long performDelete(OperationContext* opCtx,
const NamespaceString& nss,
DeleteRequest* deleteRequest,
CurOp* curOp,
bool inTransaction,
const boost::optional<mongo::UUID>& collectionUUID,
boost::optional<BSONObj>& docFound) {
auto [isTimeseriesViewDelete, nsString] =
timeseries::isTimeseriesViewRequest(opCtx, *deleteRequest);
if (isTimeseriesViewDelete) {
checkCollectionUUIDMismatch(
opCtx, nsString.getTimeseriesViewNamespace(), nullptr, collectionUUID);
}
// TODO SERVER-76583: Remove this check.
uassert(7308305,
"Retryable findAndModify on a timeseries is not supported",
!isTimeseriesViewDelete || !deleteRequest->getReturnDeleted() ||
!opCtx->isRetryableWrite());
CurOpFailpointHelpers::waitWhileFailPointEnabled(
&hangDuringBatchRemove, opCtx, "hangDuringBatchRemove", []() {
LOGV2(7280401,
"Batch remove - hangDuringBatchRemove fail point enabled. Blocking until fail "
"point is disabled");
});
if (MONGO_unlikely(failAllRemoves.shouldFail())) {
uasserted(ErrorCodes::InternalError, "failAllRemoves failpoint active!");
}
const auto collection =
acquireCollection(opCtx,
CollectionAcquisitionRequest::fromOpCtx(
opCtx, nsString, AcquisitionPrerequisites::kWrite, collectionUUID),
MODE_IX);
const auto& collectionPtr = collection.getCollectionPtr();
if (const auto& coll = collection.getCollectionPtr()) {
// Transactions are not allowed to operate on capped collections.
uassertStatusOK(checkIfTransactionOnCappedColl(opCtx, coll));
}
if (isTimeseriesViewDelete) {
timeseries::timeseriesRequestChecks<DeleteRequest>(
collection.getCollectionPtr(), deleteRequest, timeseries::deleteRequestCheckFunction);
timeseries::timeseriesHintTranslation<DeleteRequest>(collection.getCollectionPtr(),
deleteRequest);
}
ParsedDelete parsedDelete(opCtx, deleteRequest, collectionPtr, isTimeseriesViewDelete);
uassertStatusOK(parsedDelete.parseRequest());
auto dbName = nsString.dbName();
if (DatabaseHolder::get(opCtx)->getDb(opCtx, dbName)) {
curOp->raiseDbProfileLevel(CollectionCatalog::get(opCtx)->getDatabaseProfileLevel(dbName));
}
assertCanWrite_inlock(opCtx, nsString);
const auto exec = uassertStatusOK(
getExecutorDelete(&curOp->debug(), collection, &parsedDelete, boost::none /* verbosity
*/));
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
CurOp::get(opCtx)->setPlanSummary_inlock(exec->getPlanExplainer().getPlanSummary());
}
docFound = advanceExecutor(
opCtx, exec.get(), true, deleteRequest->getReturnDeleted() ? "findAndModify" : "delete");
// Nothing after advancing the plan executor should throw a WriteConflictException,
// so the following bookkeeping with execution stats won't end up being done
// multiple times.
PlanSummaryStats summaryStats;
exec->getPlanExplainer().getSummaryStats(&summaryStats);
if (const auto& coll = collectionPtr) {
CollectionQueryInfo::get(coll).notifyOfQuery(opCtx, coll, summaryStats);
}
curOp->debug().setPlanSummaryMetrics(summaryStats);
// Fill out OpDebug with the number of deleted docs.
auto nDeleted = exec->getDeleteResult();
curOp->debug().additiveMetrics.ndeleted = nDeleted;
if (curOp->shouldDBProfile()) {
auto&& explainer = exec->getPlanExplainer();
auto&& [stats, _] = explainer.getWinningPlanStats(ExplainOptions::Verbosity::kExecStats);
curOp->debug().execStats = std::move(stats);
}
if (docFound) {
ResourceConsumption::DocumentUnitCounter docUnitsReturned;
docUnitsReturned.observeOne(docFound->objsize());
auto& metricsCollector = ResourceConsumption::MetricsCollector::get(opCtx);
metricsCollector.incrementDocUnitsReturned(curOp->getNS(), docUnitsReturned);
}
return nDeleted;
}
boost::optional<write_ops::WriteError> generateError(OperationContext* opCtx,
const Status& status,
int index,
size_t numErrors) {
if (status.isOK()) {
return boost::none;
}
if (status == ErrorCodes::TenantMigrationConflict) {