summaryrefslogtreecommitdiff
path: root/src/mongo/db/ops/write_ops.cpp
blob: 54cef4d3d2a734c8295e1a101eb021dcab21fef0 (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
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
/**
 *    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.h"

#include "mongo/db/dbmessage.h"
#include "mongo/db/ops/new_write_error_exception_format_feature_flag_gen.h"
#include "mongo/db/pipeline/aggregation_request_helper.h"
#include "mongo/db/update/update_oplog_entry_serialization.h"
#include "mongo/db/update/update_oplog_entry_version.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/str.h"
#include "mongo/util/visit_helper.h"

namespace mongo {

using write_ops::DeleteCommandReply;
using write_ops::DeleteCommandRequest;
using write_ops::DeleteOpEntry;
using write_ops::FindAndModifyCommandReply;
using write_ops::InsertCommandReply;
using write_ops::InsertCommandRequest;
using write_ops::UpdateCommandReply;
using write_ops::UpdateCommandRequest;
using write_ops::UpdateOpEntry;
using write_ops::WriteCommandRequestBase;

namespace {

template <class T>
void checkOpCountForCommand(const T& op, size_t numOps) {
    uassert(ErrorCodes::InvalidLength,
            str::stream() << "Write batch sizes must be between 1 and "
                          << write_ops::kMaxWriteBatchSize << ". Got " << numOps << " operations.",
            numOps != 0 && numOps <= write_ops::kMaxWriteBatchSize);

    if (const auto& stmtIds = op.getWriteCommandRequestBase().getStmtIds()) {
        uassert(
            ErrorCodes::InvalidLength,
            str::stream() << "Number of statement ids must match the number of batch entries. Got "
                          << stmtIds->size() << " statement ids but " << numOps
                          << " operations. Statement ids: " << BSON("stmtIds" << *stmtIds)
                          << ". Write command: " << op.toBSON({}),
            stmtIds->size() == numOps);
        uassert(ErrorCodes::InvalidOptions,
                str::stream() << "May not specify both stmtId and stmtIds in write command. Got "
                              << BSON("stmtId" << *op.getWriteCommandRequestBase().getStmtId()
                                               << "stmtIds" << *stmtIds)
                              << ". Write command: " << op.toBSON({}),
                !op.getWriteCommandRequestBase().getStmtId());
    }
}

}  // namespace

namespace write_ops {

/**
 * IMPORTANT: The method should not be modified, as API version input/output guarantees could
 * break because of it.
 */
bool readMultiDeleteProperty(const BSONElement& limitElement) {
    // Using a double to avoid throwing away illegal fractional portion. Don't want to accept 0.5
    // here
    const double limit = limitElement.numberDouble();
    uassert(ErrorCodes::FailedToParse,
            str::stream() << "The limit field in delete objects must be 0 or 1. Got " << limit,
            limit == 0 || limit == 1);

    return limit == 0;
}

/**
 * IMPORTANT: The method should not be modified, as API version input/output guarantees could
 * break because of it.
 */
void writeMultiDeleteProperty(bool isMulti, StringData fieldName, BSONObjBuilder* builder) {
    builder->append(fieldName, isMulti ? 0 : 1);
}

void opTimeSerializerWithTermCheck(repl::OpTime opTime, StringData fieldName, BSONObjBuilder* bob) {
    if (opTime.getTerm() == repl::OpTime::kUninitializedTerm) {
        bob->append(fieldName, opTime.getTimestamp());
    } else {
        opTime.append(bob, fieldName.toString());
    }
}

repl::OpTime opTimeParser(BSONElement elem) {
    if (elem.type() == BSONType::Object) {
        return repl::OpTime::parse(elem.Obj());
    } else if (elem.type() == BSONType::bsonTimestamp) {
        return repl::OpTime(elem.timestamp(), repl::OpTime::kUninitializedTerm);
    }

    uasserted(ErrorCodes::TypeMismatch,
              str::stream() << "Expected BSON type " << BSONType::Object << " or "
                            << BSONType::bsonTimestamp << ", but found " << elem.type());
}

int32_t getStmtIdForWriteAt(const WriteCommandRequestBase& writeCommandBase, size_t writePos) {
    const auto& stmtIds = writeCommandBase.getStmtIds();

    if (stmtIds) {
        return stmtIds->at(writePos);
    }

    const auto& stmtId = writeCommandBase.getStmtId();
    const int32_t kFirstStmtId = stmtId ? *stmtId : 0;
    return kFirstStmtId + writePos;
}

bool isClassicalUpdateReplacement(const BSONObj& update) {
    // An empty update object will be treated as replacement as firstElementFieldName() returns "".
    return update.firstElementFieldName()[0] != '$';
}

void checkWriteErrors(const WriteCommandReplyBase& reply) {
    if (!reply.getWriteErrors())
        return;

    const auto& writeErrors = *reply.getWriteErrors();
    uassert(633310, "Write errors must not be empty", !writeErrors.empty());

    const auto& firstError = writeErrors.front();
    uassertStatusOK(firstError.getStatus());
}

UpdateModification UpdateModification::parseFromOplogEntry(const BSONObj& oField,
                                                           const DiffOptions& options) {
    BSONElement vField = oField[kUpdateOplogEntryVersionFieldName];
    BSONElement idField = oField["_id"];

    // If _id field is present, we're getting a replacement style update in which $v can be a user
    // field. Otherwise, $v field has to be either missing or be one of the version flag $v:1 /
    // $v:2.
    uassert(4772600,
            str::stream() << "Expected _id field or $v field missing or $v:1/$v:2, but got: "
                          << vField,
            idField.ok() || !vField.ok() ||
                vField.numberInt() == static_cast<int>(UpdateOplogEntryVersion::kUpdateNodeV1) ||
                vField.numberInt() == static_cast<int>(UpdateOplogEntryVersion::kDeltaV2));

    if (!idField.ok() && vField.ok() &&
        vField.numberInt() == static_cast<int>(UpdateOplogEntryVersion::kDeltaV2)) {
        // Make sure there's a diff field.
        BSONElement diff = oField[update_oplog_entry::kDiffObjectFieldName];
        uassert(4772601,
                str::stream() << "Expected 'diff' field to be an object, instead got type: "
                              << diff.type(),
                diff.type() == BSONType::Object);

        return UpdateModification(doc_diff::Diff{diff.embeddedObject()}, options);
    } else {
        // Treat it as a "classic" update which can either be a full replacement or a
        // modifier-style update. Use "_id" field to determine whether which style it is.
        return UpdateModification(oField, ClassicTag{}, idField.ok());
    }
}

UpdateModification::UpdateModification(doc_diff::Diff diff, DiffOptions options)
    : _update(DeltaUpdate{std::move(diff), options}) {}

UpdateModification::UpdateModification(TransformFunc transform)
    : _update(TransformUpdate{std::move(transform)}) {}

UpdateModification::UpdateModification(BSONElement update) {
    const auto type = update.type();
    if (type == BSONType::Object) {
        _update = UpdateModification(update.Obj(), ClassicTag{})._update;
        return;
    }

    uassert(ErrorCodes::FailedToParse,
            "Update argument must be either an object or an array",
            type == BSONType::Array);

    _update = PipelineUpdate{parsePipelineFromBSON(update)};
}

// If we know whether the update is a replacement, use that value. For example, when we're parsing
// the oplog entry, we know if the update is a replacement by checking whether there's an _id field.
UpdateModification::UpdateModification(const BSONObj& update, ClassicTag, bool isReplacement) {
    if (isReplacement) {
        _update = ReplacementUpdate{update};
    } else {
        _update = ModifierUpdate{update};
    }
}

// If we don't know whether the update is a replacement, for example while we are parsing a user
// request, we infer this by checking whether the first element is a $-field to distinguish modifier
// style updates.
UpdateModification::UpdateModification(const BSONObj& update, ClassicTag)
    : UpdateModification(update, ClassicTag{}, isClassicalUpdateReplacement(update)) {}

UpdateModification::UpdateModification(std::vector<BSONObj> pipeline)
    : _update{PipelineUpdate{std::move(pipeline)}} {}

/**
 * IMPORTANT: The method should not be modified, as API version input/output guarantees could
 * break because of it.
 */
UpdateModification UpdateModification::parseFromBSON(BSONElement elem) {
    return UpdateModification(elem);
}

int UpdateModification::objsize() const {
    return stdx::visit(
        visit_helper::Overloaded{
            [](const ReplacementUpdate& replacement) -> int { return replacement.bson.objsize(); },
            [](const ModifierUpdate& modifier) -> int { return modifier.bson.objsize(); },
            [](const PipelineUpdate& pipeline) -> int {
                int size = 0;
                std::for_each(pipeline.begin(), pipeline.end(), [&size](const BSONObj& obj) {
                    size += obj.objsize() + kWriteCommandBSONArrayPerElementOverheadBytes;
                });

                return size + kWriteCommandBSONArrayPerElementOverheadBytes;
            },
            [](const DeltaUpdate& delta) -> int { return delta.diff.objsize(); },
            [](const TransformUpdate& transform) -> int { return 0; }},
        _update);
}

UpdateModification::Type UpdateModification::type() const {
    return stdx::visit(
        visit_helper::Overloaded{
            [](const ReplacementUpdate& replacement) { return Type::kReplacement; },
            [](const ModifierUpdate& modifier) { return Type::kModifier; },
            [](const PipelineUpdate& pipelineUpdate) { return Type::kPipeline; },
            [](const DeltaUpdate& delta) { return Type::kDelta; },
            [](const TransformUpdate& transform) { return Type::kTransform; }},
        _update);
}

/**
 * IMPORTANT: The method should not be modified, as API version input/output guarantees could
 * break because of it.
 */
void UpdateModification::serializeToBSON(StringData fieldName, BSONObjBuilder* bob) const {

    stdx::visit(
        visit_helper::Overloaded{
            [fieldName, bob](const ReplacementUpdate& replacement) {
                *bob << fieldName << replacement.bson;
            },
            [fieldName, bob](const ModifierUpdate& modifier) {
                *bob << fieldName << modifier.bson;
            },
            [fieldName, bob](const PipelineUpdate& pipeline) {
                BSONArrayBuilder arrayBuilder(bob->subarrayStart(fieldName));
                for (auto&& stage : pipeline) {
                    arrayBuilder << stage;
                }
                arrayBuilder.doneFast();
            },
            [fieldName, bob](const DeltaUpdate& delta) { *bob << fieldName << delta.diff; },
            [](const TransformUpdate& transform) {}},
        _update);
}

WriteError::WriteError(int32_t index, Status status) : _index(index), _status(std::move(status)) {}

WriteError WriteError::parse(const BSONObj& obj) {
    auto index = int32_t(obj[WriteError::kIndexFieldName].Int());
    auto status = [&] {
        auto code = ErrorCodes::Error(obj[WriteError::kCodeFieldName].Int());
        auto errmsg = obj[WriteError::kErrmsgFieldName].valueStringDataSafe();

        // At least up to FCV 5.x, the write commands operation used to convert StaleConfig errors
        // into StaleShardVersion and store the extra info of StaleConfig in a sub-field called
        // "errInfo".
        //
        // TODO (SERVER-64449): This special parsing should be removed in the stable version
        // following the resolution of this ticket.
        if (code == ErrorCodes::OBSOLETE_StaleShardVersion) {
            return Status(ErrorCodes::StaleConfig,
                          std::move(errmsg),
                          obj[WriteError::kErrInfoFieldName].Obj());
        }

        // All remaining errors have the error stored at the same level as the code and errmsg (in
        // the same way that Status is serialised as part of regular command response)
        return Status(code, std::move(errmsg), obj);
    }();

    return WriteError(index, std::move(status));
}

BSONObj WriteError::serialize() const {
    BSONObjBuilder errBuilder;
    errBuilder.append(WriteError::kIndexFieldName, _index);

    // At least up to FCV 5.x, the write commands operation used to convert StaleConfig errors into
    // StaleShardVersion and store the extra info of StaleConfig in a sub-field called "errInfo".
    // This logic preserves this for backwards compatibility.
    //
    // TODO (SERVER-64449): This special serialisation should be removed in the stable version
    // following the resolution of this ticket.
    if (_status == ErrorCodes::StaleConfig &&
        !feature_flags::gFeatureFlagNewWriteErrorExceptionFormat.isEnabled(
            serverGlobalParams.featureCompatibility)) {
        errBuilder.append(WriteError::kCodeFieldName,
                          int32_t(ErrorCodes::OBSOLETE_StaleShardVersion));
        errBuilder.append(WriteError::kErrmsgFieldName, _status.reason());
        auto extraInfo = _status.extraInfo();
        invariant(extraInfo);
        BSONObjBuilder extraInfoBuilder(errBuilder.subobjStart(WriteError::kErrInfoFieldName));
        extraInfo->serialize(&extraInfoBuilder);
    } else {
        errBuilder.append(WriteError::kCodeFieldName, int32_t(_status.code()));
        errBuilder.append(WriteError::kErrmsgFieldName, _status.reason());
        if (auto extraInfo = _status.extraInfo()) {
            extraInfo->serialize(&errBuilder);
        }
    }

    return errBuilder.obj();
}

}  // namespace write_ops

InsertCommandRequest InsertOp::parse(const OpMsgRequest& request) {
    auto insertOp = InsertCommandRequest::parse(IDLParserErrorContext("insert"), request);

    validate(insertOp);
    return insertOp;
}

InsertCommandRequest InsertOp::parseLegacy(const Message& msgRaw) {
    DbMessage msg(msgRaw);

    InsertCommandRequest op(NamespaceString(msg.getns()));

    {
        WriteCommandRequestBase writeCommandBase;
        writeCommandBase.setBypassDocumentValidation(false);
        writeCommandBase.setOrdered(!(msg.reservedField() & InsertOption_ContinueOnError));
        op.setWriteCommandRequestBase(std::move(writeCommandBase));
    }

    uassert(ErrorCodes::InvalidLength, "Need at least one object to insert", msg.moreJSObjs());

    op.setDocuments([&] {
        std::vector<BSONObj> documents;
        while (msg.moreJSObjs()) {
            documents.push_back(msg.nextJsObj());
        }

        return documents;
    }());

    validate(op);
    return op;
}

InsertCommandReply InsertOp::parseResponse(const BSONObj& obj) {
    uassertStatusOK(getStatusFromCommandResult(obj));
    return InsertCommandReply::parse(IDLParserErrorContext("insertReply"), obj);
}

void InsertOp::validate(const InsertCommandRequest& insertOp) {
    const auto& docs = insertOp.getDocuments();
    checkOpCountForCommand(insertOp, docs.size());
}

UpdateCommandRequest UpdateOp::parse(const OpMsgRequest& request) {
    auto updateOp = UpdateCommandRequest::parse(IDLParserErrorContext("update"), request);

    checkOpCountForCommand(updateOp, updateOp.getUpdates().size());
    return updateOp;
}

UpdateCommandReply UpdateOp::parseResponse(const BSONObj& obj) {
    uassertStatusOK(getStatusFromCommandResult(obj));

    return UpdateCommandReply::parse(IDLParserErrorContext("updateReply"), obj);
}

void UpdateOp::validate(const UpdateCommandRequest& updateOp) {
    checkOpCountForCommand(updateOp, updateOp.getUpdates().size());
}

FindAndModifyCommandReply FindAndModifyOp::parseResponse(const BSONObj& obj) {
    uassertStatusOK(getStatusFromCommandResult(obj));

    return FindAndModifyCommandReply::parse(IDLParserErrorContext("findAndModifyReply"), obj);
}

DeleteCommandRequest DeleteOp::parse(const OpMsgRequest& request) {
    auto deleteOp = DeleteCommandRequest::parse(IDLParserErrorContext("delete"), request);

    checkOpCountForCommand(deleteOp, deleteOp.getDeletes().size());
    return deleteOp;
}

DeleteCommandReply DeleteOp::parseResponse(const BSONObj& obj) {
    uassertStatusOK(getStatusFromCommandResult(obj));
    return DeleteCommandReply::parse(IDLParserErrorContext("deleteReply"), obj);
}

void DeleteOp::validate(const DeleteCommandRequest& deleteOp) {
    checkOpCountForCommand(deleteOp, deleteOp.getDeletes().size());
}

}  // namespace mongo