summaryrefslogtreecommitdiff
path: root/src/mongo/db/s/config/configsvr_drop_collection_command.cpp
blob: 44f0aa0aabc049d4905d7c3d070997bac7bf3ab2 (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

/**
 *    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.
 */

#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding

#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/read_concern_args.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/s/config/sharding_catalog_manager.h"
#include "mongo/db/s/operation_sharding_state.h"
#include "mongo/s/catalog/dist_lock_manager.h"
#include "mongo/s/catalog/type_database.h"
#include "mongo/s/catalog_cache.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/cluster_commands_helpers.h"
#include "mongo/s/grid.h"
#include "mongo/s/stale_exception.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/log.h"
#include "mongo/util/scopeguard.h"

namespace mongo {
namespace {

MONGO_FAIL_POINT_DEFINE(setDropCollDistLockWait);

template <typename F>
auto staleExceptionRetry(OperationContext* opCtx, StringData opStr, F&& f) {
    uassert(ErrorCodes::IllegalOperation,
            str::stream() << "Command " << opStr << " does not support database versioning",
            !OperationShardingState::get(opCtx).hasDbVersion());
    uassert(ErrorCodes::IllegalOperation,
            str::stream() << "Command " << opStr << " does not support collection versioning",
            !OperationShardingState::get(opCtx).hasShardVersion());

    for (int tries = 0;; ++tries) {
        // Try kMaxStaleExceptionTries times and on the last try, rethrow the exception
        const bool canRetry = tries < kMaxNumStaleVersionRetries - 1;
        try {
            return f();
        } catch (const ExceptionForCat<ErrorCategory::StaleShardVersionError>& ex) {
            log() << "Attempt " << tries << " of " << opStr << " received StaleShardVersion error"
                  << causedBy(ex);

            if (canRetry) {
                continue;
            }
            throw;
        }
        MONGO_UNREACHABLE;
    }
}

/**
 * Internal sharding command run on config servers to drop a collection from a database.
 */
class ConfigSvrDropCollectionCommand : public BasicCommand {
public:
    ConfigSvrDropCollectionCommand() : BasicCommand("_configsvrDropCollection") {}

    AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
        return AllowedOnSecondary::kNever;
    }

    bool adminOnly() const override {
        return true;
    }

    bool supportsWriteConcern(const BSONObj& cmd) const override {
        return true;
    }

    std::string help() const override {
        return "Internal command, which is exported by the sharding config server. Do not call "
               "directly. Drops a collection from a database.";
    }

    Status checkAuthForCommand(Client* client,
                               const std::string& dbname,
                               const BSONObj& cmdObj) const override {
        if (!AuthorizationSession::get(client)->isAuthorizedForActionsOnResource(
                ResourcePattern::forClusterResource(), ActionType::internal)) {
            return Status(ErrorCodes::Unauthorized, "Unauthorized");
        }
        return Status::OK();
    }

    std::string parseNs(const std::string& dbname, const BSONObj& cmdObj) const override {
        return CommandHelpers::parseNsFullyQualified(cmdObj);
    }

    bool run(OperationContext* opCtx,
             const std::string& dbname,
             const BSONObj& cmdObj,
             BSONObjBuilder& result) override {
        uassert(ErrorCodes::IllegalOperation,
                "_configsvrDropCollection can only be run on config servers",
                serverGlobalParams.clusterRole == ClusterRole::ConfigServer);

        // Set the operation context read concern level to local for reads into the config database.
        repl::ReadConcernArgs::get(opCtx) =
            repl::ReadConcernArgs(repl::ReadConcernLevel::kLocalReadConcern);

        const NamespaceString nss(parseNs(dbname, cmdObj));

        uassert(ErrorCodes::InvalidOptions,
                str::stream() << "dropCollection must be called with majority writeConcern, got "
                              << cmdObj,
                opCtx->getWriteConcern().wMode == WriteConcernOptions::kMajority);

        Seconds waitFor(DistLockManager::kDefaultLockTimeout);
        MONGO_FAIL_POINT_BLOCK(setDropCollDistLockWait, customWait) {
            const BSONObj& data = customWait.getData();
            waitFor = Seconds(data["waitForSecs"].numberInt());
        }

        auto const catalogClient = Grid::get(opCtx)->catalogClient();

        auto scopedDbLock =
            ShardingCatalogManager::get(opCtx)->serializeCreateOrDropDatabase(opCtx, nss.db());
        auto scopedCollLock =
            ShardingCatalogManager::get(opCtx)->serializeCreateOrDropCollection(opCtx, nss);

        auto dbDistLock = uassertStatusOK(
            catalogClient->getDistLockManager()->lock(opCtx, nss.db(), "dropCollection", waitFor));
        auto collDistLock = uassertStatusOK(
            catalogClient->getDistLockManager()->lock(opCtx, nss.ns(), "dropCollection", waitFor));

        ON_BLOCK_EXIT(
            [opCtx, nss] { Grid::get(opCtx)->catalogCache()->invalidateShardedCollection(nss); });

        staleExceptionRetry(
            opCtx, "_configsvrDropCollection", [&] { _dropCollection(opCtx, nss); });

        return true;
    }

private:
    static void _dropCollection(OperationContext* opCtx, const NamespaceString& nss) {
        auto const catalogClient = Grid::get(opCtx)->catalogClient();

        auto collStatus =
            catalogClient->getCollection(opCtx, nss, repl::ReadConcernArgs::get(opCtx).getLevel());
        if (collStatus == ErrorCodes::NamespaceNotFound) {
            // We checked the sharding catalog and found that this collection doesn't exist. This
            // may be because it never existed, or because a drop command was sent previously. This
            // data might not be majority committed though, so we will set the client's last optime
            // to the system's last optime to ensure the client waits for the writeConcern to be
            // satisfied.
            repl::ReplClientInfo::forClient(opCtx->getClient()).setLastOpToSystemLastOpTime(opCtx);

            // If the DB isn't in the sharding catalog either, consider the drop a success.
            auto dbStatus = catalogClient->getDatabase(
                opCtx, nss.db().toString(), repl::ReadConcernArgs::get(opCtx).getLevel());
            if (dbStatus == ErrorCodes::NamespaceNotFound) {
                return;
            }
            uassertStatusOK(dbStatus);

            // If we found the DB but not the collection, the collection might exist and not be
            // sharded, so send the command to the primary shard.
            _dropUnshardedCollectionFromShard(opCtx, dbStatus.getValue().value.getPrimary(), nss);
        } else {
            uassertStatusOK(collStatus);
            uassertStatusOK(ShardingCatalogManager::get(opCtx)->dropCollection(opCtx, nss));
        }
    }

    static void _dropUnshardedCollectionFromShard(OperationContext* opCtx,
                                                  const ShardId& shardId,
                                                  const NamespaceString& nss) {

        const auto shardRegistry = Grid::get(opCtx)->shardRegistry();

        const auto dropCommandBSON = [shardRegistry, opCtx, &shardId, &nss] {
            BSONObjBuilder builder;
            builder.append("drop", nss.coll());

            // Append the chunk version for the specified namespace indicating that we believe it is
            // not sharded. Collections residing on the config server are never sharded so do not
            // send the shard version.
            if (shardId != shardRegistry->getConfigShard()->getId()) {
                ChunkVersion::UNSHARDED().appendToCommand(&builder);
            }

            if (!opCtx->getWriteConcern().usedDefault) {
                builder.append(WriteConcernOptions::kWriteConcernField,
                               opCtx->getWriteConcern().toBSON());
            }

            return builder.obj();
        }();

        const auto shard = uassertStatusOK(shardRegistry->getShard(opCtx, shardId));

        auto cmdDropResult = uassertStatusOK(shard->runCommandWithFixedRetryAttempts(
            opCtx,
            ReadPreferenceSetting{ReadPreference::PrimaryOnly},
            nss.db().toString(),
            dropCommandBSON,
            Shard::RetryPolicy::kIdempotent));

        // If the collection doesn't exist, consider the drop a success.
        if (cmdDropResult.commandStatus == ErrorCodes::NamespaceNotFound) {
            return;
        }

        uassertStatusOK(cmdDropResult.commandStatus);
        uassertStatusOK(cmdDropResult.writeConcernStatus);
    };

} configsvrDropCollectionCmd;

}  // namespace
}  // namespace mongo