summaryrefslogtreecommitdiff
path: root/src/mongo/db/s/config/configsvr_drop_collection_command.cpp
blob: 6743958f1f53d811c89af35396aeffb3233faf64 (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
/**
 *    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_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::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.h"
#include "mongo/util/scopeguard.h"

namespace mongo {
namespace {

MONGO_FAIL_POINT_DEFINE(setDropCollDistLockWait);

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

    /**
     * We accept any apiVersion, apiStrict, and/or apiDeprecationErrors, and forward it with the
     * "drop" command to shards.
     */
    bool acceptsAnyApiVersionParameters() const override {
        return true;
    }

    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);
        setDropCollDistLockWait.execute(
            [&](const BSONObj& data) { 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()->invalidateCollectionEntry_LINEARIZABLE(nss);
        });

        _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, and the primary shard for the database is
            // the config server, run the drop only against the config server unless the collection
            // is config.system.sessions, since no other collections whose primary shard is the
            // config server can have been sharded.
            const auto primaryShard = dbStatus.getValue().value.getPrimary();
            if (primaryShard == "config" && nss != NamespaceString::kLogicalSessionsNamespace) {
                auto cmdDropResult =
                    uassertStatusOK(Grid::get(opCtx)
                                        ->shardRegistry()
                                        ->getConfigShard()
                                        ->runCommandWithFixedRetryAttempts(
                                            opCtx,
                                            ReadPreferenceSetting{ReadPreference::PrimaryOnly},
                                            nss.db().toString(),
                                            BSON("drop" << nss.coll()),
                                            Shard::RetryPolicy::kIdempotent));

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

            ShardingCatalogManager::get(opCtx)->ensureDropCollectionCompleted(opCtx, nss);
        } else {
            uassertStatusOK(collStatus);
            ShardingCatalogManager::get(opCtx)->dropCollection(opCtx, nss);
        }
    }

} configsvrDropCollectionCmd;

}  // namespace
}  // namespace mongo