summaryrefslogtreecommitdiff
path: root/src/mongo/db/pipeline/document_source_change_stream_handle_topology_change.cpp
blob: 28b695c89be06176b40f31777d771ac6bfd507ca (plain)
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
/**
 *    Copyright (C) 2021-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/pipeline/document_source_change_stream_handle_topology_change.h"

#include <algorithm>

#include "mongo/db/pipeline/change_stream_topology_change_info.h"
#include "mongo/db/pipeline/document_source_change_stream.h"
#include "mongo/db/pipeline/sharded_agg_helpers.h"
#include "mongo/db/query/query_feature_flags_gen.h"
#include "mongo/s/catalog/type_shard.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/grid.h"
#include "mongo/s/query/establish_cursors.h"
#include "mongo/util/fail_point.h"

namespace mongo {
namespace {

// Failpoint to throw an exception when the 'kNewShardDetected' event is observed.
MONGO_FAIL_POINT_DEFINE(throwChangeStreamTopologyChangeExceptionToClient);

// Returns true if the change stream document is an event in 'config.shards'.
bool isShardConfigEvent(const Document& eventDoc) {
    // TODO SERVER-44039: we continue to generate 'kNewShardDetected' events for compatibility
    // with 4.2, even though we no longer rely on them to detect new shards. We swallow the event
    // here. We may wish to remove this mechanism entirely in 4.7+, or retain it for future cases
    // where a change stream is targeted to a subset of shards. See SERVER-44039 for details.

    auto opType = eventDoc[DocumentSourceChangeStream::kOperationTypeField];

    // If opType isn't a string, then this document has been manipulated. This means it cannot have
    // been produced by the internal shard-monitoring cursor that we opened on the config servers,
    // or by the kNewShardDetectedOpType mechanism, which bypasses filtering and projection stages.
    if (opType.getType() != BSONType::String) {
        return false;
    }

    if (opType.getStringData() == DocumentSourceChangeStream::kNewShardDetectedOpType) {
        // If the failpoint is enabled, throw the 'ChangeStreamToplogyChange' exception to the
        // client. This is used in testing to confirm that the swallowed 'kNewShardDetected' event
        // has reached the mongoS.
        // TODO SERVER-30784: remove this failpoint when the 'kNewShardDetected' event is the only
        // way we detect a new shard.
        if (MONGO_unlikely(throwChangeStreamTopologyChangeExceptionToClient.shouldFail())) {
            uasserted(ChangeStreamTopologyChangeInfo(eventDoc.toBsonWithMetaData()),
                      "Collection migrated to new shard");
        }

        return true;
    }

    // Check whether this event occurred on the config.shards collection.
    auto nsObj = eventDoc[DocumentSourceChangeStream::kNamespaceField];
    const bool isConfigDotShardsEvent = nsObj["db"_sd].getType() == BSONType::String &&
        nsObj["db"_sd].getStringData() == NamespaceString::kConfigsvrShardsNamespace.db() &&
        nsObj["coll"_sd].getType() == BSONType::String &&
        nsObj["coll"_sd].getStringData() == NamespaceString::kConfigsvrShardsNamespace.coll();

    // If it isn't from config.shards, treat it as a normal user event.
    if (!isConfigDotShardsEvent) {
        return false;
    }

    // We need to validate that this event hasn't been faked by a user projection in a way that
    // would cause us to tassert. Check the clusterTime field, which is needed to determine the
    // point from which the new shard should start reporting change events.
    if (eventDoc["clusterTime"].getType() != BSONType::bsonTimestamp) {
        return false;
    }
    // Check the fullDocument field, which should contain details of the new shard's name and hosts.
    auto fullDocument = eventDoc[DocumentSourceChangeStream::kFullDocumentField];
    if (opType.getStringData() == "insert"_sd && fullDocument.getType() != BSONType::Object) {
        return false;
    }

    // The event is on config.shards and is well-formed. It is still possible that it is a forgery,
    // but all the user can do is cause their own stream to uassert.
    return true;
}
}  // namespace

boost::intrusive_ptr<DocumentSourceChangeStreamHandleTopologyChange>
DocumentSourceChangeStreamHandleTopologyChange::create(
    const boost::intrusive_ptr<ExpressionContext>& expCtx) {
    return new DocumentSourceChangeStreamHandleTopologyChange(expCtx);
}

DocumentSourceChangeStreamHandleTopologyChange::DocumentSourceChangeStreamHandleTopologyChange(
    const boost::intrusive_ptr<ExpressionContext>& expCtx)
    : DocumentSource(kStageName, expCtx) {}

StageConstraints DocumentSourceChangeStreamHandleTopologyChange::constraints(
    Pipeline::SplitState) const {
    StageConstraints constraints{StreamType::kStreaming,
                                 PositionRequirement::kNone,
                                 HostTypeRequirement::kMongoS,
                                 DiskUseRequirement::kNoDiskUse,
                                 FacetRequirement::kNotAllowed,
                                 TransactionRequirement::kNotAllowed,
                                 LookupRequirement::kNotAllowed,
                                 UnionRequirement::kNotAllowed,
                                 ChangeStreamRequirement::kChangeStreamStage};

    // Can be swapped with the '$match' and 'DocumentSourceSingleDocumentTransformation' stages and
    // ensures that they get pushed down to the shards, as this stage bisects the change streams
    // pipeline.
    constraints.canSwapWithMatch = true;
    constraints.canSwapWithSingleDocTransform = true;

    return constraints;
}

DocumentSource::GetNextResult DocumentSourceChangeStreamHandleTopologyChange::doGetNext() {
    // For the first call to the 'doGetNext', the '_mergeCursors' will be null and must be
    // populated. We also resolve the original aggregation command from the expression context.
    if (!_mergeCursors) {
        _mergeCursors = dynamic_cast<DocumentSourceMergeCursors*>(pSource);
        _originalAggregateCommand = pExpCtx->originalAggregateCommand.getOwned();

        tassert(5549100, "Missing $mergeCursors stage", _mergeCursors);
        tassert(
            5549101, "Empty $changeStream command object", !_originalAggregateCommand.isEmpty());
    }

    auto childResult = pSource->getNext();

    // If this is an insertion into the 'config.shards' collection, open a cursor on the new shard.
    while (childResult.isAdvanced() && isShardConfigEvent(childResult.getDocument())) {
        auto opType = childResult.getDocument()[DocumentSourceChangeStream::kOperationTypeField];
        if (opType.getStringData() == DocumentSourceChangeStream::kInsertOpType) {
            addNewShardCursors(childResult.getDocument());
        }
        // For shard removal or update, we do nothing. We also swallow kNewShardDetectedOpType.
        childResult = pSource->getNext();
    }
    return childResult;
}

void DocumentSourceChangeStreamHandleTopologyChange::addNewShardCursors(
    const Document& newShardDetectedObj) {
    _mergeCursors->addNewShardCursors(establishShardCursorsOnNewShards(newShardDetectedObj));
}

std::vector<RemoteCursor>
DocumentSourceChangeStreamHandleTopologyChange::establishShardCursorsOnNewShards(
    const Document& newShardDetectedObj) {
    // Reload the shard registry to see the new shard.
    auto* opCtx = pExpCtx->opCtx;
    Grid::get(opCtx)->shardRegistry()->reload(opCtx);

    // Parse the new shard's information from the document inserted into 'config.shards'.
    auto newShardSpec = newShardDetectedObj[DocumentSourceChangeStream::kFullDocumentField];
    auto newShard = uassertStatusOK(ShardType::fromBSON(newShardSpec.getDocument().toBson()));

    // Make sure we are not attempting to open a cursor on a shard that already has one.
    if (_mergeCursors->getShardIds().count(newShard.getName()) != 0) {
        return {};
    }

    auto cmdObj = createUpdatedCommandForNewShard(
        newShardDetectedObj[DocumentSourceChangeStream::kClusterTimeField].getTimestamp());

    const bool allowPartialResults = false;  // partial results are not allowed
    return establishCursors(opCtx,
                            pExpCtx->mongoProcessInterface->taskExecutor,
                            pExpCtx->ns,
                            ReadPreferenceSetting::get(opCtx),
                            {{newShard.getName(), cmdObj}},
                            allowPartialResults);
}

BSONObj DocumentSourceChangeStreamHandleTopologyChange::createUpdatedCommandForNewShard(
    Timestamp shardAddedTime) {
    // We must start the new cursor from the moment at which the shard became visible.
    const auto newShardAddedTime = LogicalTime{shardAddedTime};
    auto resumeTokenForNewShard = ResumeToken::makeHighWaterMarkToken(
        newShardAddedTime.addTicks(1).asTimestamp(), pExpCtx->changeStreamTokenVersion);

    // Create a new shard command object containing the new resume token.
    auto shardCommand = replaceResumeTokenInCommand(resumeTokenForNewShard.toDocument());

    auto* opCtx = pExpCtx->opCtx;
    bool apiStrict = APIParameters::get(opCtx).getAPIStrict().value_or(false);

    // Create the 'AggregateCommandRequest' object which will help in creating the parsed pipeline.
    auto aggCmdRequest = aggregation_request_helper::parseFromBSON(
        opCtx, pExpCtx->ns, shardCommand, boost::none, apiStrict);

    // Parse and optimize the pipeline.
    auto pipeline = Pipeline::parse(aggCmdRequest.getPipeline(), pExpCtx);
    pipeline->optimizePipeline();

    // Split the full pipeline to get the shard pipeline.
    auto splitPipelines = sharded_agg_helpers::splitPipeline(std::move(pipeline));

    // Create the new command that will run on the shard.
    return sharded_agg_helpers::createCommandForTargetedShards(pExpCtx,
                                                               Document{shardCommand},
                                                               splitPipelines,
                                                               boost::none, /* exhangeSpec */
                                                               true /* needsMerge */,
                                                               boost::none /* explain */);
}

BSONObj DocumentSourceChangeStreamHandleTopologyChange::replaceResumeTokenInCommand(
    Document resumeToken) {
    Document originalCmd(_originalAggregateCommand);
    auto pipeline = originalCmd[AggregateCommandRequest::kPipelineFieldName].getArray();

    // A $changeStream must be the first element of the pipeline in order to be able
    // to replace (or add) a resume token.
    tassert(5549102,
            "Invalid $changeStream command object",
            !pipeline[0][DocumentSourceChangeStream::kStageName].missing());

    MutableDocument changeStreamStage(
        pipeline[0][DocumentSourceChangeStream::kStageName].getDocument());
    changeStreamStage[DocumentSourceChangeStreamSpec::kResumeAfterFieldName] = Value(resumeToken);

    // If the command was initially specified with a startAtOperationTime, we need to remove it to
    // use the new resume token.
    changeStreamStage[DocumentSourceChangeStreamSpec::kStartAtOperationTimeFieldName] = Value();
    pipeline[0] =
        Value(Document{{DocumentSourceChangeStream::kStageName, changeStreamStage.freeze()}});
    MutableDocument newCmd(std::move(originalCmd));
    newCmd[AggregateCommandRequest::kPipelineFieldName] = Value(pipeline);
    return newCmd.freeze().toBson();
}

Value DocumentSourceChangeStreamHandleTopologyChange::serialize(SerializationOptions opts) const {
    if (opts.verbosity) {
        return Value(DOC(DocumentSourceChangeStream::kStageName
                         << DOC("stage"
                                << "internalHandleTopologyChange"_sd)));
    }

    return Value(Document{{kStageName, Document()}});
}

}  // namespace mongo