-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
service_entry_point_common.cpp
2468 lines (2139 loc) · 108 KB
/
service_entry_point_common.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/service_entry_point_common.h"
#include <algorithm>
#include <boost/optional.hpp>
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <cstdint>
#include <fmt/format.h>
#include <mutex>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include <absl/container/node_hash_map.h>
#include <boost/cstdint.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/none.hpp>
#include <boost/optional/optional.hpp>
#include <boost/smart_ptr/intrusive_ptr.hpp>
#include "mongo/base/status.h"
#include "mongo/base/status_with.h"
#include "mongo/base/string_data.h"
#include "mongo/bson/bsonelement.h"
#include "mongo/bson/bsonmisc.h"
#include "mongo/bson/bsontypes.h"
#include "mongo/bson/mutable/document.h"
#include "mongo/client/read_preference.h"
#include "mongo/db/admission/ingress_admission_controller.h"
#include "mongo/db/api_parameters.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/auth/impersonation_session.h"
#include "mongo/db/auth/ldap_cumulative_operation_stats.h"
#include "mongo/db/auth/ldap_operation_stats.h"
#include "mongo/db/auth/resource_pattern.h"
#include "mongo/db/auth/security_token_authentication_guard.h"
#include "mongo/db/auth/user_acquisition_stats.h"
#include "mongo/db/auth/validated_tenancy_scope.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/client.h"
#include "mongo/db/cluster_role.h"
#include "mongo/db/command_can_run_here.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/server_status_metric.h"
#include "mongo/db/commands/txn_cmds_gen.h"
#include "mongo/db/common_request_args_gen.h"
#include "mongo/db/concurrency/lock_manager_defs.h"
#include "mongo/db/concurrency/replication_state_transition_lock_guard.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/error_labels.h"
#include "mongo/db/feature_flag.h"
#include "mongo/db/initialize_operation_session_info.h"
#include "mongo/db/introspect.h"
#include "mongo/db/logical_time.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/not_primary_error_tracker.h"
#include "mongo/db/op_observer/op_observer.h"
#include "mongo/db/query/max_time_ms_parser.h"
#include "mongo/db/query/query_request_helper.h"
#include "mongo/db/read_concern_support_result.h"
#include "mongo/db/read_write_concern_defaults.h"
#include "mongo/db/read_write_concern_defaults_gen.h"
#include "mongo/db/read_write_concern_provenance.h"
#include "mongo/db/repl/member_state.h"
#include "mongo/db/repl/optime.h"
#include "mongo/db/repl/read_concern_args.h"
#include "mongo/db/repl/read_concern_level.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl/storage_interface.h"
#include "mongo/db/repl/tenant_migration_access_blocker_util.h"
#include "mongo/db/request_execution_context.h"
#include "mongo/db/s/operation_sharding_state.h"
#include "mongo/db/s/sharding_cluster_parameters_gen.h"
#include "mongo/db/s/sharding_statistics.h"
#include "mongo/db/s/transaction_coordinator_factory.h"
#include "mongo/db/server_feature_flags_gen.h"
#include "mongo/db/server_options.h"
#include "mongo/db/server_parameter.h"
#include "mongo/db/server_parameter_with_storage.h"
#include "mongo/db/service_context.h"
#include "mongo/db/session/logical_session_id_gen.h"
#include "mongo/db/session/session_catalog.h"
#include "mongo/db/session/session_catalog_mongod.h"
#include "mongo/db/shard_id.h"
#include "mongo/db/stats/api_version_metrics.h"
#include "mongo/db/stats/counters.h"
#include "mongo/db/stats/read_preference_metrics.h"
#include "mongo/db/stats/resource_consumption_metrics.h"
#include "mongo/db/stats/server_read_concern_metrics.h"
#include "mongo/db/stats/top.h"
#include "mongo/db/tenant_id.h"
#include "mongo/db/transaction/transaction_participant.h"
#include "mongo/db/transaction_resources.h"
#include "mongo/db/transaction_validation.h"
#include "mongo/db/validate_api_parameters.h"
#include "mongo/db/vector_clock.h"
#include "mongo/db/write_concern.h"
#include "mongo/db/write_concern_options.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/mutex.h"
#include "mongo/rpc/check_allowed_op_query_cmd.h"
#include "mongo/rpc/factory.h"
#include "mongo/rpc/message.h"
#include "mongo/rpc/metadata.h"
#include "mongo/rpc/metadata/client_metadata.h"
#include "mongo/rpc/metadata/tracking_metadata.h"
#include "mongo/rpc/op_msg.h"
#include "mongo/rpc/protocol.h"
#include "mongo/rpc/reply_builder_interface.h"
#include "mongo/rpc/topology_version_gen.h"
#include "mongo/s/analyze_shard_key_role.h"
#include "mongo/s/chunk_version.h"
#include "mongo/s/database_version.h"
#include "mongo/s/query_analysis_sampler.h"
#include "mongo/s/shard_cannot_refresh_due_to_locks_held_exception.h"
#include "mongo/s/shard_version.h"
#include "mongo/s/sharding_feature_flags_gen.h"
#include "mongo/s/sharding_state.h"
#include "mongo/s/stale_exception.h"
#include "mongo/s/transaction_router.h"
#include "mongo/s/would_change_owning_shard_exception.h"
#include "mongo/transport/hello_metrics.h"
#include "mongo/transport/service_executor.h"
#include "mongo/transport/session.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/clock_source.h"
#include "mongo/util/concurrency/admission_context.h"
#include "mongo/util/concurrency/ticketholder.h"
#include "mongo/util/database_name_util.h"
#include "mongo/util/decorable.h"
#include "mongo/util/duration.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/future_impl.h"
#include "mongo/util/future_util.h"
#include "mongo/util/namespace_string_util.h"
#include "mongo/util/net/hostandport.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/str.h"
#include "mongo/util/string_map.h"
#include "mongo/util/time_support.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand
namespace mongo {
MONGO_FAIL_POINT_DEFINE(respondWithNotPrimaryInCommandDispatch);
MONGO_FAIL_POINT_DEFINE(skipCheckingForNotPrimaryInCommandDispatch);
MONGO_FAIL_POINT_DEFINE(waitAfterNewStatementBlocksBehindPrepare);
MONGO_FAIL_POINT_DEFINE(waitAfterNewStatementBlocksBehindOpenInternalTransactionForRetryableWrite);
MONGO_FAIL_POINT_DEFINE(waitAfterCommandFinishesExecution);
MONGO_FAIL_POINT_DEFINE(failWithErrorCodeInRunCommand);
MONGO_FAIL_POINT_DEFINE(hangBeforeSessionCheckOut);
MONGO_FAIL_POINT_DEFINE(hangAfterSessionCheckOut);
MONGO_FAIL_POINT_DEFINE(hangBeforeSettingTxnInterruptFlag);
MONGO_FAIL_POINT_DEFINE(hangAfterCheckingWritabilityForMultiDocumentTransactions);
MONGO_FAIL_POINT_DEFINE(enforceDirectShardOperationsCheck);
// Tracks the number of times a legacy unacknowledged write failed due to
// not primary error resulted in network disconnection.
auto& notPrimaryLegacyUnackWrites =
*MetricBuilder<Counter64>{"repl.network.notPrimaryLegacyUnacknowledgedWrites"};
// Tracks the number of times an unacknowledged write failed due to not primary error
// resulted in network disconnection.
auto& notPrimaryUnackWrites =
*MetricBuilder<Counter64>{"repl.network.notPrimaryUnacknowledgedWrites"};
namespace {
using namespace fmt::literals;
void runCommandInvocation(const RequestExecutionContext& rec, CommandInvocation* invocation) {
CommandHelpers::runCommandInvocation(
rec.getOpCtx(), rec.getRequest(), invocation, rec.getReplyBuilder());
}
/*
* Allows for the very complex handleRequest function to be decomposed into parts.
* It also provides the infrastructure to futurize the process of executing commands.
*/
struct HandleRequest {
// Maintains the context (e.g., opCtx and replyBuilder) required for command execution.
class ExecutionContext final : public RequestExecutionContext {
public:
ExecutionContext(OperationContext* opCtx,
Message msg,
const ServiceEntryPointCommon::Hooks& hooks)
: RequestExecutionContext(opCtx, std::move(msg)), behaviors(hooks) {}
~ExecutionContext() = default;
Client& client() const {
return *getOpCtx()->getClient();
}
auto session() const {
return client().session();
}
NetworkOp op() const {
return getMessage().operation();
}
CurOp& currentOp() {
return *CurOp::get(getOpCtx());
}
NamespaceString nsString() const {
auto& dbmsg = getDbMessage();
if (!dbmsg.messageShouldHaveNs())
return {};
return NamespaceStringUtil::deserialize(
boost::none, dbmsg.getns(), SerializationContext::stateDefault());
}
void assertValidNsString() {
if (!nsString().isValid()) {
uassert(
16257, fmt::format("Invalid ns [{}]", nsString().toStringForErrorMsg()), false);
}
}
/**
* Note that DBDirectClient is treated as an internal client in relation to letting
* internal errors escape.
*/
bool isInternalClient() const {
return client().isInDirectClient() ||
(client().session() && client().isInternalClient());
}
const ServiceEntryPointCommon::Hooks& behaviors;
boost::optional<long long> slowMsOverride;
bool forceLog = false;
};
HandleRequest(OperationContext* opCtx,
const Message& msg,
const ServiceEntryPointCommon::Hooks& behaviors)
: executionContext(ExecutionContext(opCtx, const_cast<Message&>(msg), behaviors)) {}
void startOperation();
DbResponse runOperation();
void completeOperation(DbResponse&);
ExecutionContext executionContext;
};
void registerError(OperationContext* opCtx, const Status& status) {
NotPrimaryErrorTracker::get(opCtx->getClient()).recordError(status.code());
CurOp::get(opCtx)->debug().errInfo = status;
}
void generateErrorResponse(OperationContext* opCtx,
rpc::ReplyBuilderInterface* replyBuilder,
const Status& status,
const BSONObj& replyMetadata,
BSONObj extraFields = {}) {
invariant(!status.isOK());
registerError(opCtx, status);
// We could have thrown an exception after setting fields in the builder,
// so we need to reset it to a clean state just to be sure.
replyBuilder->reset();
replyBuilder->setCommandReply(status, extraFields);
replyBuilder->getBodyBuilder().appendElements(replyMetadata);
}
/**
* For replica set members it returns the last known op time from opCtx. Otherwise will return
* uninitialized cluster time.
*/
LogicalTime getClientOperationTime(OperationContext* opCtx) {
auto const replCoord = repl::ReplicationCoordinator::get(opCtx);
const bool isReplSet = replCoord->getSettings().isReplSet();
if (!isReplSet) {
return LogicalTime();
}
return LogicalTime(
repl::ReplClientInfo::forClient(opCtx->getClient()).getMaxKnownOperationTime());
}
/**
* Returns the proper operationTime for a command. To construct the operationTime for replica set
* members, it uses the last optime in the oplog for writes, last committed optime for majority
* reads, and the last applied optime for every other read. An uninitialized cluster time is
* returned for non replica set members.
*
* The latest in-memory clusterTime is returned if the start operationTime is uninitialized.
*/
LogicalTime computeOperationTime(OperationContext* opCtx, LogicalTime startOperationTime) {
auto const replCoord = repl::ReplicationCoordinator::get(opCtx);
const bool isReplSet = replCoord->getSettings().isReplSet();
invariant(isReplSet);
auto operationTime = getClientOperationTime(opCtx);
invariant(operationTime >= startOperationTime);
// If the last operationTime has not changed, consider this command a read, and, for replica set
// members, construct the operationTime with the proper optime for its read concern level.
if (operationTime == startOperationTime) {
auto& readConcernArgs = repl::ReadConcernArgs::get(opCtx);
// Note: ReadConcernArgs::getLevel returns kLocal if none was set.
if (readConcernArgs.getLevel() == repl::ReadConcernLevel::kMajorityReadConcern) {
operationTime =
LogicalTime(replCoord->getCurrentCommittedSnapshotOpTime().getTimestamp());
} else {
operationTime = LogicalTime(replCoord->getMyLastAppliedOpTime().getTimestamp());
}
}
return operationTime;
}
/**
* Computes the proper $clusterTime and operationTime values to include in the command response and
* appends them to it. $clusterTime is added as metadata and operationTime as a command body field.
*
* The command body BSONObjBuilder is either the builder for the command body itself, or a builder
* for extra fields to be added to the reply when generating an error response.
*/
void appendClusterAndOperationTime(OperationContext* opCtx,
BSONObjBuilder* commandBodyFieldsBob,
BSONObjBuilder* metadataBob,
LogicalTime startTime) {
if (!repl::ReplicationCoordinator::get(opCtx)->getSettings().isReplSet() ||
!VectorClock::get(opCtx)->isEnabled()) {
return;
}
// The appended operationTime must always be <= the appended $clusterTime, so first compute the
// operationTime.
auto operationTime = computeOperationTime(opCtx, startTime);
bool clusterTimeWasOutput = VectorClock::get(opCtx)->gossipOut(opCtx, metadataBob);
// Ensure that either both operationTime and $clusterTime are output, or neither.
if (clusterTimeWasOutput) {
operationTime.appendAsOperationTime(metadataBob);
}
}
void appendErrorLabelsAndTopologyVersion(OperationContext* opCtx,
BSONObjBuilder* commandBodyFieldsBob,
const OperationSessionInfoFromClient& sessionOptions,
const std::string& commandName,
boost::optional<ErrorCodes::Error> code,
boost::optional<ErrorCodes::Error> wcCode,
bool isInternalClient,
const repl::OpTime& lastOpBeforeRun,
const repl::OpTime& lastOpAfterRun) {
if (!code && !wcCode) {
return;
}
auto errorLabels = getErrorLabels(opCtx,
sessionOptions,
commandName,
code,
wcCode,
isInternalClient,
false /* isMongos */,
lastOpBeforeRun,
lastOpAfterRun);
commandBodyFieldsBob->appendElements(errorLabels);
const auto isNotPrimaryError =
(code && ErrorCodes::isA<ErrorCategory::NotPrimaryError>(*code)) ||
(wcCode && ErrorCodes::isA<ErrorCategory::NotPrimaryError>(*wcCode));
const auto isShutdownError = (code && ErrorCodes::isA<ErrorCategory::ShutdownError>(*code)) ||
(wcCode && ErrorCodes::isA<ErrorCategory::ShutdownError>(*wcCode));
const auto replCoord = repl::ReplicationCoordinator::get(opCtx);
// NotPrimary errors always include a topologyVersion, since we increment topologyVersion on
// stepdown. ShutdownErrors only include a topologyVersion if the server is in quiesce mode,
// since we only increment the topologyVersion at shutdown and alert waiting isMaster/hello
// commands if the server enters quiesce mode.
const auto shouldAppendTopologyVersion =
(replCoord->getSettings().isReplSet() && isNotPrimaryError) ||
(isShutdownError && replCoord->inQuiesceMode());
if (!shouldAppendTopologyVersion) {
return;
}
const auto topologyVersion = replCoord->getTopologyVersion();
BSONObjBuilder topologyVersionBuilder(commandBodyFieldsBob->subobjStart("topologyVersion"));
topologyVersion.serialize(&topologyVersionBuilder);
}
// TODO SERVER-85353 Remove commandName and nss parameters, which are used only for the failpoint
// in TxnRouter::getAdditionalParticipantsForResponse
void appendAdditionalParticipants(OperationContext* opCtx,
BSONObjBuilder* commandBodyFieldsBob,
const std::string& commandName,
const NamespaceString& nss) {
auto txnRouter = TransactionRouter::get(opCtx);
if (!txnRouter)
return;
auto additionalParticipants =
txnRouter.getAdditionalParticipantsForResponse(opCtx, commandName, nss);
if (!additionalParticipants)
return;
std::vector<BSONObj> participantArray;
for (const auto& p : *additionalParticipants) {
auto shardId = ShardId(p.first);
// The "readOnly" value is set for participants upon a successful response. If an error
// occurred before getting a response from a participant, it will not have a readOnly value
// set.
auto readOnly = p.second;
if (readOnly) {
participantArray.emplace_back(BSON("shardId" << shardId << "readOnly" << *readOnly));
} else {
participantArray.emplace_back(BSON("shardId" << shardId));
}
}
commandBodyFieldsBob->appendElements(BSON("additionalParticipants" << participantArray));
}
class RunCommandOpTimes {
public:
RunCommandOpTimes(OperationContext* opCtx) : _lastOpBeforeRun(getLastOp(opCtx)) {}
void onCommandFinished(OperationContext* opCtx) {
if (!_lastOpAfterRun.isNull()) {
return;
}
_lastOpAfterRun = getLastOp(opCtx);
}
const repl::OpTime& getLastOpBeforeRun() const {
return _lastOpBeforeRun;
}
const repl::OpTime& getLastOpAfterRun() const {
return _lastOpAfterRun;
}
private:
repl::OpTime getLastOp(OperationContext* opCtx) {
return repl::ReplClientInfo::forClient(opCtx->getClient()).getLastOp();
}
repl::OpTime _lastOpBeforeRun;
repl::OpTime _lastOpAfterRun;
};
class ExecCommandDatabase {
public:
explicit ExecCommandDatabase(HandleRequest::ExecutionContext& execContext)
: _execContext(execContext) {
_parseCommand();
}
// Executes a command after stripping metadata, performing authorization checks, handling audit
// impersonation, and (potentially) setting maintenance mode. Also checks that the command is
// permissible to run on the node given its current replication state. All the logic here is
// independent of any particular command; any functionality relevant to a specific command
// should be confined to its run() method.
void run() {
auto status = [&] {
try {
_initiateCommand();
_commandExec();
} catch (const DBException& ex) {
return ex.toStatus();
}
return Status::OK();
}();
// Ensure the lifetime of `_scopedMetrics` ends here.
_scopedMetrics = boost::none;
// Release the ingress admission ticket
_admissionTicket = boost::none;
if (!_execContext.client().isInDirectClient()) {
auto authzSession = AuthorizationSession::get(_execContext.client());
authzSession->verifyContract(_execContext.getCommand()->getAuthorizationContract());
}
if (MONGO_unlikely(!status.isOK()))
_handleFailure(std::move(status));
}
const HandleRequest::ExecutionContext& getExecutionContext() {
return _execContext;
}
CommandInvocation* getInvocation() {
return _invocation.get();
}
const OperationSessionInfoFromClient& getSessionOptions() const {
return _sessionOptions;
}
BSONObjBuilder* getExtraFieldsBuilder() {
return &_extraFieldsBuilder;
}
const LogicalTime& getStartOperationTime() const {
return _startOperationTime;
}
void onCommandFinished() {
if (!_runCommandOpTimes) {
return;
}
_runCommandOpTimes->onCommandFinished(_execContext.getOpCtx());
}
const boost::optional<RunCommandOpTimes>& getRunCommandOpTimes() {
return _runCommandOpTimes;
}
repl::OpTime getLastOpBeforeRun() {
if (!_runCommandOpTimes) {
return repl::OpTime{};
}
return _runCommandOpTimes->getLastOpBeforeRun();
}
repl::OpTime getLastOpAfterRun() {
if (!_runCommandOpTimes) {
return repl::OpTime{};
}
return _runCommandOpTimes->getLastOpAfterRun();
}
bool isHello() const {
return _execContext.getCommand()->getName() == "hello"_sd ||
_execContext.getCommand()->getName() == "isMaster"_sd;
}
const CommonRequestArgs& getCommonRequestArgs() const {
return _requestArgs;
}
private:
void _parseCommand() {
auto opCtx = _execContext.getOpCtx();
auto command = _execContext.getCommand();
auto& request = _execContext.getRequest();
CommandHelpers::uassertShouldAttemptParse(opCtx, command, request);
_requestArgs = CommonRequestArgs::parse(IDLParserContext("request"), request.body);
validateAPIParameters(request.body, _requestArgs.getAPIParametersFromClient(), command);
Client* client = opCtx->getClient();
{
stdx::lock_guard<Client> lk(*client);
CurOp::get(opCtx)->setCommand_inlock(command);
APIParameters::get(opCtx) =
APIParameters::fromClient(_requestArgs.getAPIParametersFromClient());
}
_startOperationTime = getClientOperationTime(opCtx);
rpc::readRequestMetadata(opCtx, _requestArgs, request, command->requiresAuth());
_invocation = command->parse(opCtx, request);
CommandInvocation::set(opCtx, _invocation);
const auto session = _execContext.getOpCtx()->getClient()->session();
if (session) {
if (!opCtx->isExhaust() || !isHello()) {
InExhaustHello::get(session.get())->setInExhaust(false, request.getCommandName());
}
}
}
// Do any initialization of the lock state required for a transaction.
void _setLockStateForTransaction(OperationContext* opCtx) {
shard_role_details::getLocker(opCtx)->setSharedLocksShouldTwoPhaseLock(true);
}
// Clear any lock state which may have changed after the locker update.
void _resetLockerStateAfterShardingUpdate(OperationContext* opCtx) {
dassert(!opCtx->isContinuingMultiDocumentTransaction());
_execContext.behaviors.resetLockerState(opCtx);
if (opCtx->isStartingMultiDocumentTransaction())
_setLockStateForTransaction(opCtx);
}
// Any logic, such as authorization and auditing, that must precede execution of the command.
void _initiateCommand();
// Executes the parsed command against the database.
void _commandExec();
// Any error-handling logic that must be performed if the command initiation/execution fails.
void _handleFailure(Status status);
bool _isInternalClient() const {
return _execContext.isInternalClient();
}
StatusWith<repl::ReadConcernArgs> _extractReadConcern(OperationContext* opCtx,
bool startTransaction,
bool startOrContinueTransaction);
const HandleRequest::ExecutionContext& _execContext;
// The following allows `_initiateCommand`, `_commandExec`, and `_handleFailure` to share
// execution state without concerning the lifetime of these variables.
BSONObjBuilder _extraFieldsBuilder;
std::shared_ptr<CommandInvocation> _invocation;
LogicalTime _startOperationTime;
OperationSessionInfoFromClient _sessionOptions;
CommonRequestArgs _requestArgs;
boost::optional<RunCommandOpTimes> _runCommandOpTimes;
boost::optional<ResourceConsumption::ScopedMetricsCollector> _scopedMetrics;
boost::optional<ImpersonationSessionGuard> _impersonationSessionGuard;
boost::optional<auth::SecurityTokenAuthenticationGuard> _tokenAuthorizationSessionGuard;
std::unique_ptr<PolymorphicScoped> _scoped;
bool _refreshedDatabase = false;
bool _refreshedCollection = false;
bool _refreshedCatalogCache = false;
boost::optional<Ticket> _admissionTicket;
// Keep a static variable to track the last time a warning about direct shard connections was
// logged.
static Mutex _staticMutex;
static Date_t _lastDirectConnectionWarningTime;
};
class RunCommandImpl {
public:
explicit RunCommandImpl(ExecCommandDatabase* ecd) : _ecd(ecd) {}
virtual ~RunCommandImpl() = default;
void run() {
auto status = [&] {
try {
_prologue();
_runImpl();
_epilogue();
return Status::OK();
} catch (const DBException& ex) {
return ex.toStatus();
}
}();
// Failure to run a command is either indicated by throwing an exception or
// adding a non-okay field to the replyBuilder.
if (MONGO_unlikely(!status.isOK() || !_ok)) {
auto& execContext = _ecd->getExecutionContext();
if (status.code() == ErrorCodes::QueryRejectedBySettings) {
execContext.getCommand()->incrementCommandsRejected();
} else {
execContext.getCommand()->incrementCommandsFailed();
}
if (status.code() == ErrorCodes::Unauthorized) {
CommandHelpers::auditLogAuthEvent(execContext.getOpCtx(),
_ecd->getInvocation(),
execContext.getRequest(),
status.code());
}
iassert(status);
}
}
protected:
// Reference to attributes defined in `ExecCommandDatabase` (e.g., sessionOptions).
ExecCommandDatabase* const _ecd;
// Any code that must run before command execution (e.g., reserving bytes for reply builder).
void _prologue();
// Runs the command possibly waiting for write concern.
virtual void _runImpl();
// Runs the command without waiting for write concern.
void _runCommand();
// Any code that must run after command execution.
void _epilogue();
bool _isInternalClient() const {
return _ecd->getExecutionContext().isInternalClient();
}
// If the command resolved successfully.
bool _ok = false;
};
class RunCommandAndWaitForWriteConcern final : public RunCommandImpl {
public:
explicit RunCommandAndWaitForWriteConcern(ExecCommandDatabase* ecd)
: RunCommandImpl(ecd),
_execContext(_ecd->getExecutionContext()),
_oldWriteConcern(_execContext.getOpCtx()->getWriteConcern()) {}
~RunCommandAndWaitForWriteConcern() override {
_execContext.getOpCtx()->setWriteConcern(_oldWriteConcern);
}
void _runImpl() override;
private:
void _setup();
void _runCommandWithFailPoint();
void _waitForWriteConcern(BSONObjBuilder& bb);
void _handleError(Status status);
void _checkWriteConcern();
const HandleRequest::ExecutionContext& _execContext;
// Allows changing the write concern while running the command and resetting on destruction.
const WriteConcernOptions _oldWriteConcern;
boost::optional<WriteConcernOptions> _extractedWriteConcern;
};
// Simplifies the interface for invoking commands and allows asynchronous execution of command
// invocations.
class InvokeCommand {
public:
explicit InvokeCommand(ExecCommandDatabase* ecd) : _ecd(ecd) {}
void run();
private:
ExecCommandDatabase* const _ecd;
};
class CheckoutSessionAndInvokeCommand {
public:
CheckoutSessionAndInvokeCommand(ExecCommandDatabase* ecd) : _ecd{ecd} {}
~CheckoutSessionAndInvokeCommand() {
auto opCtx = _ecd->getExecutionContext().getOpCtx();
if (auto txnParticipant = TransactionParticipant::get(opCtx)) {
// Only cleanup if we didn't yield the session.
_cleanupTransaction(txnParticipant);
}
}
void run();
private:
void _stashTransaction(TransactionParticipant::Participant& txnParticipant);
void _cleanupTransaction(TransactionParticipant::Participant& txnParticipant);
void _checkOutSession();
void _tapError(Status);
void _commitInvocation();
ExecCommandDatabase* const _ecd;
std::unique_ptr<MongoDSessionCatalog::Session> _sessionTxnState;
bool _shouldCleanUp = false;
};
void InvokeCommand::run() try {
auto& execContext = _ecd->getExecutionContext();
const auto dbName = _ecd->getInvocation()->ns().dbName();
tenant_migration_access_blocker::checkIfCanRunCommandOrBlock(
execContext.getOpCtx(), dbName, execContext.getRequest())
.get(execContext.getOpCtx());
runCommandInvocation(_ecd->getExecutionContext(), _ecd->getInvocation());
} catch (const ExceptionForCat<ErrorCategory::TenantMigrationConflictError>& ex) {
uassertStatusOK(tenant_migration_access_blocker::handleTenantMigrationConflict(
_ecd->getExecutionContext().getOpCtx(), ex.toStatus()));
}
void CheckoutSessionAndInvokeCommand::run() {
auto status = [&] {
try {
_checkOutSession();
auto& execContext = _ecd->getExecutionContext();
const auto dbName = _ecd->getInvocation()->ns().dbName();
tenant_migration_access_blocker::checkIfCanRunCommandOrBlock(
execContext.getOpCtx(), dbName, execContext.getRequest())
.get(execContext.getOpCtx());
runCommandInvocation(_ecd->getExecutionContext(), _ecd->getInvocation());
return Status::OK();
} catch (const ExceptionForCat<ErrorCategory::TenantMigrationConflictError>& ex) {
auto opCtx = _ecd->getExecutionContext().getOpCtx();
if (auto txnParticipant = TransactionParticipant::get(opCtx)) {
// If the command didn't yield its session, abort transaction and clean up
// transaction resources before blocking the command to allow the stable timestamp
// on the node to advance.
_cleanupTransaction(txnParticipant);
}
uassertStatusOK(tenant_migration_access_blocker::handleTenantMigrationConflict(
opCtx, ex.toStatus()));
return Status::OK();
} catch (const ExceptionFor<ErrorCodes::WouldChangeOwningShard>& ex) {
auto opCtx = _ecd->getExecutionContext().getOpCtx();
auto txnParticipant = TransactionParticipant::get(opCtx);
if (!txnParticipant) {
// No code paths that can throw this error should yield their session but uassert
// instead of invariant in case that assumption is ever broken since this only needs
// to be operation fatal.
auto statusWithContext = ex.toStatus().withContext(
"Cannot handle WouldChangeOwningShard error because the operation yielded its "
"session");
uasserted(6609000, statusWithContext.reason());
}
auto wouldChangeOwningShardInfo = ex.toStatus().extraInfo<WouldChangeOwningShardInfo>();
invariant(wouldChangeOwningShardInfo);
txnParticipant.handleWouldChangeOwningShardError(opCtx, wouldChangeOwningShardInfo);
_stashTransaction(txnParticipant);
auto txnResponseMetadata = txnParticipant.getResponseMetadata();
(_ecd->getExtraFieldsBuilder())->appendElements(txnResponseMetadata);
return ex.toStatus();
} catch (const DBException& ex) {
return ex.toStatus();
}
}();
if (MONGO_unlikely(!status.isOK())) {
_tapError(status);
iasserted(status);
}
_commitInvocation();
}
void CheckoutSessionAndInvokeCommand::_stashTransaction(
TransactionParticipant::Participant& txnParticipant) {
invariant(txnParticipant);
if (!_shouldCleanUp) {
return;
}
_shouldCleanUp = false;
auto opCtx = _ecd->getExecutionContext().getOpCtx();
txnParticipant.stashTransactionResources(opCtx);
}
void CheckoutSessionAndInvokeCommand::_cleanupTransaction(
TransactionParticipant::Participant& txnParticipant) {
invariant(txnParticipant);
if (!_shouldCleanUp) {
return;
}
_shouldCleanUp = false;
auto opCtx = _ecd->getExecutionContext().getOpCtx();
const bool isPrepared = txnParticipant.transactionIsPrepared();
try {
if (isPrepared)
txnParticipant.stashTransactionResources(opCtx);
else if (txnParticipant.transactionIsOpen())
txnParticipant.abortTransaction(opCtx);
} catch (...) {
// It is illegal for this to throw so we catch and log this here for diagnosability.
LOGV2_FATAL(21974,
"Unable to stash/abort transaction",
"operation"_attr = (isPrepared ? "stash" : "abort"),
"txnNumber"_attr = opCtx->getTxnNumber(),
"logicalSessionId"_attr = opCtx->getLogicalSessionId()->toBSON(),
"error"_attr = exceptionToStatus());
}
}
void CheckoutSessionAndInvokeCommand::_checkOutSession() {
auto& execContext = _ecd->getExecutionContext();
auto opCtx = execContext.getOpCtx();
CommandInvocation* invocation = _ecd->getInvocation();
const OperationSessionInfoFromClient& sessionOptions = _ecd->getSessionOptions();
// This constructor will check out the session. It handles the appropriate state management
// for both multi-statement transactions and retryable writes. Currently, only requests with
// a transaction number will check out the session.
hangBeforeSessionCheckOut.pauseWhileSet();
auto mongoDSessionCatalog = MongoDSessionCatalog::get(opCtx);
_sessionTxnState = mongoDSessionCatalog->checkOutSession(opCtx);
auto txnParticipant = TransactionParticipant::get(opCtx);
hangAfterSessionCheckOut.pauseWhileSet();
// Used for waiting for an in-progress transaction to transition out of the conflicting state.
auto waitForInProgressTxn = [this](OperationContext* opCtx, auto& stateTransitionFuture) {
// Check the session back in and wait for the conflict to resolve.
_sessionTxnState->checkIn(opCtx, OperationContextSession::CheckInReason::kYield);
stateTransitionFuture.wait(opCtx);
// Wait for any commit or abort oplog entry to be visible in the oplog. This will prevent a
// new transaction from missing the transaction table update for the previous commit or
// abort due to an oplog hole.
auto storageInterface = repl::StorageInterface::get(opCtx);
storageInterface->waitForAllEarlierOplogWritesToBeVisible(opCtx);
// Check out the session again.
_sessionTxnState->checkOut(opCtx);
};
auto apiParamsFromClient = APIParameters::get(opCtx);
auto apiParamsFromTxn = txnParticipant.getAPIParameters(opCtx);
uassert(
ErrorCodes::APIMismatchError,
"API parameter mismatch: {} used params {}, the transaction's first command used {}"_format(
invocation->definition()->getName(),
apiParamsFromClient.toBSON().toString(),
apiParamsFromTxn.toBSON().toString()),
apiParamsFromTxn == apiParamsFromClient);
if (!opCtx->getClient()->isInDirectClient()) {
bool beganOrContinuedTxn{false};
// This loop allows new transactions on a session to block behind a previous prepared
// transaction on that session.
while (!beganOrContinuedTxn) {
try {
auto opObserver = opCtx->getServiceContext()->getOpObserver();
opObserver->onTransactionStart(opCtx);
auto transactionAction = TransactionParticipant::TransactionActions::kNone;
if (sessionOptions.getStartTransaction()) {
transactionAction = TransactionParticipant::TransactionActions::kStart;
} else if (sessionOptions.getStartOrContinueTransaction()) {
transactionAction =
TransactionParticipant::TransactionActions::kStartOrContinue;
} else if (sessionOptions.getAutocommit()) {
transactionAction = TransactionParticipant::TransactionActions::kContinue;
}
txnParticipant.beginOrContinue(
opCtx,
{*sessionOptions.getTxnNumber(), sessionOptions.getTxnRetryCounter()},
sessionOptions.getAutocommit(),
transactionAction);
beganOrContinuedTxn = true;
} catch (const ExceptionFor<ErrorCodes::PreparedTransactionInProgress>&) {
auto prevTxnExitedPrepare = txnParticipant.onExitPrepare();
CurOpFailpointHelpers::waitWhileFailPointEnabled(
&waitAfterNewStatementBlocksBehindPrepare,
opCtx,
"waitAfterNewStatementBlocksBehindPrepare");
waitForInProgressTxn(opCtx, prevTxnExitedPrepare);
} catch (const ExceptionFor<ErrorCodes::RetryableTransactionInProgress>&) {
auto conflictingTxnCommittedOrAborted =
txnParticipant.onConflictingInternalTransactionCompletion(opCtx);
waitAfterNewStatementBlocksBehindOpenInternalTransactionForRetryableWrite
.pauseWhileSet();
waitForInProgressTxn(opCtx, conflictingTxnCommittedOrAborted);
}
}
// Create coordinator if needed. If "startTransaction" is present, it must be true.
if (sessionOptions.getStartTransaction()) {
// If this shard has been selected as the coordinator, set up the coordinator state
// to be ready to receive votes.
if (sessionOptions.getCoordinator() == boost::optional<bool>(true)) {