summaryrefslogtreecommitdiff
path: root/src/mongo/db/repl/apply_ops.cpp
blob: 1fdf6450262ebacb7135c2e20039cbb25ea819f9 (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
/**
 *    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/repl/apply_ops.h"

#include "mongo/bson/util/bson_extract.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/catalog/document_validation.h"
#include "mongo/db/client.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/curop.h"
#include "mongo/db/database_name.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index_builds_coordinator.h"
#include "mongo/db/op_observer/op_observer.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/service_context.h"
#include "mongo/db/session/session_catalog_mongod.h"
#include "mongo/db/shard_role.h"
#include "mongo/db/transaction/transaction_participant.h"
#include "mongo/logv2/log.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/util/fail_point.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand

namespace mongo {
namespace repl {

constexpr StringData ApplyOps::kOplogApplicationModeFieldName;

namespace {

// If enabled, causes loop in _applyOps() to hang after applying current operation.
MONGO_FAIL_POINT_DEFINE(applyOpsPauseBetweenOperations);

Status _applyOps(OperationContext* opCtx,
                 const ApplyOpsCommandInfo& info,
                 const DatabaseName& dbName,
                 repl::OplogApplication::Mode oplogApplicationMode,
                 BSONObjBuilder* result,
                 int* numApplied,
                 BSONArrayBuilder* opsBuilder) {
    const auto& ops = info.getOperations();
    // apply
    *numApplied = 0;
    int errors = 0;

    BSONArrayBuilder ab;
    const auto& alwaysUpsert = info.getAlwaysUpsert();
    // Apply each op in the given 'applyOps' command object.
    for (const auto& opObj : ops) {
        // Ignore 'n' operations.
        const char* opType = opObj.getStringField("op").rawData();
        if (*opType == 'n')
            continue;

        const NamespaceString nss(
            NamespaceStringUtil::deserialize(dbName.tenantId(), opObj["ns"].String()));

        // Need to check this here, or OldClientContext may fail an invariant.
        if (*opType != 'c' && !nss.isValid())
            return {ErrorCodes::InvalidNamespace, "invalid ns: " + nss.toStringForErrorMsg()};

        Status status = Status::OK();

        try {
            status = writeConflictRetry(
                opCtx,
                "applyOps",
                nss,
                [opCtx, nss, opObj, opType, alwaysUpsert, oplogApplicationMode, &info, &dbName] {
                    BSONObjBuilder builder;
                    // Remove 'hash' field if it is set. A bit slow as it rebuilds the object.
                    // TODO(SERVER-69062): Remove this step.
                    auto opObjectWithoutHash = opObj;
                    if (opObj.hasField(OplogEntry::kHashFieldName)) {
                        opObjectWithoutHash = opObj.removeField(OplogEntry::kHashFieldName);
                    }

                    builder.appendElements(opObjectWithoutHash);
                    if (!builder.hasField(OplogEntry::kTimestampFieldName)) {
                        builder.append(OplogEntry::kTimestampFieldName, Timestamp());
                    }
                    if (!builder.hasField(OplogEntry::kWallClockTimeFieldName)) {
                        builder.append(OplogEntry::kWallClockTimeFieldName, Date_t());
                    }
                    auto entry = uassertStatusOK(OplogEntry::parse(builder.done()));

                    if (*opType == 'c') {
                        if (entry.getCommandType() == OplogEntry::CommandType::kDropDatabase) {
                            invariant(info.getOperations().size() == 1,
                                      "dropDatabase in applyOps must be the only entry");
                            // This method is explicitly called without locks in spite of the
                            // _inlock suffix. dropDatabase cannot hold any locks for execution
                            // of the operation due to potential replication waits.
                            uassertStatusOK(applyCommand_inlock(
                                opCtx, ApplierOperation{&entry}, oplogApplicationMode));
                            return Status::OK();
                        }
                        invariant(opCtx->lockState()->isW());
                        uassertStatusOK(applyCommand_inlock(
                            opCtx, ApplierOperation{&entry}, oplogApplicationMode));
                        return Status::OK();
                    }

                    // If the namespace and uuid passed into applyOps point to different
                    // namespaces, throw an error.
                    auto catalog = CollectionCatalog::get(opCtx);
                    if (opObjectWithoutHash.hasField("ui")) {
                        auto uuid = UUID::parse(opObjectWithoutHash["ui"]).getValue();
                        auto nssFromUuid = catalog->lookupNSSByUUID(opCtx, uuid);
                        if (nssFromUuid != nss) {
                            return Status{ErrorCodes::Error(3318200),
                                          str::stream()
                                              << "Namespace '" << nss.toStringForErrorMsg()
                                              << "' and UUID '" << uuid.toString()
                                              << "' point to different collections"};
                        }
                    }

                    auto collection = acquireCollection(
                        opCtx,
                        CollectionAcquisitionRequest(nss,
                                                     AcquisitionPrerequisites::kPretendUnsharded,
                                                     repl::ReadConcernArgs::get(opCtx),
                                                     AcquisitionPrerequisites::kWrite),
                        fixLockModeForSystemDotViewsChanges(nss, MODE_IX));
                    if (!collection.exists()) {
                        // For idempotency reasons, return success on delete operations.
                        if (*opType == 'd') {
                            return Status::OK();
                        }
                        uasserted(ErrorCodes::NamespaceNotFound,
                                  str::stream()
                                      << "cannot apply insert or update operation on a "
                                         "non-existent namespace "
                                      << nss.toStringForErrorMsg() << ": " << mongo::redact(opObj));
                    }

                    OldClientContext ctx(opCtx, nss);

                    // We return the status rather than merely aborting so failure of CRUD
                    // ops doesn't stop the applyOps from trying to process the rest of the
                    // ops.  This is to leave the door open to parallelizing CRUD op
                    // application in the future.
                    const bool isDataConsistent = true;
                    return repl::applyOperation_inlock(opCtx,
                                                       collection,
                                                       ApplierOperation{&entry},
                                                       alwaysUpsert,
                                                       oplogApplicationMode,
                                                       isDataConsistent);
                });
        } catch (const DBException& ex) {
            ab.append(false);
            result->append("applied", ++(*numApplied));
            result->append("code", ex.code());
            result->append("codeName", ErrorCodes::errorString(ex.code()));
            result->append("errmsg", ex.what());
            result->append("results", ab.arr());
            return ex.toStatus();
        }

        ab.append(status.isOK());
        if (!status.isOK()) {
            LOGV2(21064,
                  "applyOps error applying: {error}",
                  "applyOps error applying",
                  "error"_attr = status);
            errors++;
        }

        (*numApplied)++;

        if (MONGO_unlikely(applyOpsPauseBetweenOperations.shouldFail())) {
            applyOpsPauseBetweenOperations.pauseWhileSet();
        }
    }

    result->append("applied", *numApplied);
    result->append("results", ab.arr());

    if (errors != 0) {
        return Status(ErrorCodes::UnknownError, "applyOps had one or more errors applying ops");
    }

    return Status::OK();
}

}  // namespace

Status applyApplyOpsOplogEntry(OperationContext* opCtx,
                               const OplogEntry& entry,
                               repl::OplogApplication::Mode oplogApplicationMode) {
    invariant(!entry.shouldPrepare());
    BSONObjBuilder resultWeDontCareAbout;
    return applyOps(opCtx,
                    entry.getNss().dbName(),
                    entry.getObject(),
                    oplogApplicationMode,
                    &resultWeDontCareAbout);
}

Status applyOps(OperationContext* opCtx,
                const DatabaseName& dbName,
                const BSONObj& applyOpCmd,
                repl::OplogApplication::Mode oplogApplicationMode,
                BSONObjBuilder* result) {
    auto info = ApplyOpsCommandInfo::parse(applyOpCmd);

    int numApplied = 0;

    boost::optional<Lock::GlobalWrite> globalWriteLock;
    boost::optional<Lock::DBLock> dbWriteLock;

    uassert(
        ErrorCodes::BadValue, "applyOps command can't have 'prepare' field", !info.getPrepare());
    uassert(31056, "applyOps command can't have 'partialTxn' field.", !info.getPartialTxn());
    uassert(31240, "applyOps command can't have 'count' field.", !info.getCount());

    if (info.areOpsCrudOnly()) {
        dbWriteLock.emplace(opCtx, dbName, MODE_IX);
    } else {
        globalWriteLock.emplace(opCtx);
    }

    auto replCoord = repl::ReplicationCoordinator::get(opCtx);
    bool userInitiatedWritesAndNotPrimary =
        opCtx->writesAreReplicated() && !replCoord->canAcceptWritesForDatabase(opCtx, dbName);

    if (userInitiatedWritesAndNotPrimary)
        return Status(ErrorCodes::NotWritablePrimary,
                      str::stream() << "Not primary while applying ops to database "
                                    << dbName.toStringForErrorMsg());

    LOGV2_DEBUG(5854600,
                2,
                "applyOps command",
                "dbName"_attr = redact(toStringForLogging(dbName)),
                "cmd"_attr = redact(applyOpCmd));

    auto hasDropDatabase = std::any_of(
        info.getOperations().begin(), info.getOperations().end(), [](const BSONObj& op) {
            return op.getStringField("op") == "c" &&
                parseCommandType(op.getObjectField("o")) == OplogEntry::CommandType::kDropDatabase;
        });
    if (hasDropDatabase) {
        // Normally the contract for applyOps is to hold a global exclusive lock during
        // application of ops. However, dropDatabase must specially not hold locks because it
        // may need to await replication internally during application. Additionally, since
        // dropDatabase is abnormal in locking behavior, applyOps is only allowed to apply a
        // dropDatabase op singly, not in combination with additional ops.
        uassert(6275900,
                "dropDatabase in an applyOps must be the only entry",
                info.getOperations().size() == 1);
        globalWriteLock.reset();
    }
    return _applyOps(
        opCtx, info, dbName, oplogApplicationMode, result, &numApplied, nullptr /* opsBuilder */);
}

}  // namespace repl
}  // namespace mongo