summaryrefslogtreecommitdiff
path: root/src/mongo/s/mongos_topology_coordinator.cpp
blob: 9d762c8d0c1ad925bfaa46a0944dce89533272dd (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
/**
 *    Copyright (C) 2020-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::kCommand

#include "mongo/logv2/log.h"

#include "mongo/db/client.h"
#include "mongo/db/service_context.h"
#include "mongo/s/mongos_topology_coordinator.h"
#include "mongo/util/fail_point.h"

namespace mongo {

namespace {

const auto getMongosTopologyCoordinator =
    ServiceContext::declareDecoration<MongosTopologyCoordinator>();

/**
 * Generate an identifier unique to this instance.
 */
OID instanceId;

MONGO_INITIALIZER(GenerateMongosInstanceId)(InitializerContext*) {
    instanceId = OID::gen();
    return Status::OK();
}

// Signals that an isMaster request has started waiting.
MONGO_FAIL_POINT_DEFINE(waitForIsMasterResponse);
// Awaitable isMaster requests with the proper topologyVersions are expected to wait for
// maxAwaitTimeMS on mongos. When set, this failpoint will hang right before waiting on a
// topology change.
MONGO_FAIL_POINT_DEFINE(hangWhileWaitingForIsMasterResponse);
// Failpoint for hanging during quiesce mode on mongos.
MONGO_FAIL_POINT_DEFINE(hangDuringQuiesceMode);

template <typename T>
StatusOrStatusWith<T> futureGetNoThrowWithDeadline(OperationContext* opCtx,
                                                   SharedSemiFuture<T>& f,
                                                   Date_t deadline,
                                                   ErrorCodes::Error error) {
    try {
        return opCtx->runWithDeadline(deadline, error, [&] { return f.getNoThrow(opCtx); });
    } catch (const DBException& e) {
        return e.toStatus();
    }
}

/**
 * ShutdownInProgress error
 */

const Status kQuiesceModeShutdownStatus =
    Status(ErrorCodes::ShutdownInProgress, "Mongos is in quiesce mode and will shut down");

}  // namespace

// Make MongosTopologyCoordinator a decoration on the ServiceContext.
MongosTopologyCoordinator* MongosTopologyCoordinator::get(OperationContext* opCtx) {
    return &getMongosTopologyCoordinator(opCtx->getClient()->getServiceContext());
}

MongosTopologyCoordinator::MongosTopologyCoordinator()
    : _topologyVersion(instanceId, 0),
      _inQuiesceMode(false),
      _promise(std::make_shared<SharedPromise<std::shared_ptr<const MongosIsMasterResponse>>>()) {}

std::shared_ptr<MongosIsMasterResponse> MongosTopologyCoordinator::_makeIsMasterResponse(
    WithLock lock) const {
    // It's possible for us to transition to Quiesce Mode after an isMaster request timed out.
    // Check that we are not in Quiesce Mode before returning a response to avoid responding with
    // a higher topology version, but no indication that we are shutting down.
    uassert(
        kQuiesceModeShutdownStatus.code(), kQuiesceModeShutdownStatus.reason(), !_inQuiesceMode);

    auto response = std::make_shared<MongosIsMasterResponse>(_topologyVersion);
    return response;
}

std::shared_ptr<const MongosIsMasterResponse> MongosTopologyCoordinator::awaitIsMasterResponse(
    OperationContext* opCtx,
    boost::optional<TopologyVersion> clientTopologyVersion,
    boost::optional<Date_t> deadline) const {
    stdx::unique_lock lk(_mutex);

    // Fail all new isMaster requests with ShutdownInProgress if we've transitioned to Quiesce
    // Mode.
    uassert(
        kQuiesceModeShutdownStatus.code(), kQuiesceModeShutdownStatus.reason(), !_inQuiesceMode);

    // Respond immediately if:
    // (1) There is no clientTopologyVersion, which indicates that the client is not using
    //     awaitable ismaster.
    // (2) The process IDs are different.
    // (3) The clientTopologyVersion counter is less than mongos' counter.
    if (!clientTopologyVersion ||
        clientTopologyVersion->getProcessId() != _topologyVersion.getProcessId() ||
        clientTopologyVersion->getCounter() < _topologyVersion.getCounter()) {
        return _makeIsMasterResponse(lk);
    }
    uassert(51761,
            str::stream() << "Received a topology version with counter: "
                          << clientTopologyVersion->getCounter()
                          << " which is greater than the mongos topology version counter: "
                          << _topologyVersion.getCounter(),
            clientTopologyVersion->getCounter() == _topologyVersion.getCounter());

    auto future = _promise->getFuture();
    // At this point, we have verified that clientTopologyVersion is not none. It this is true,
    // deadline must also be not none.
    invariant(deadline);

    IsMasterMetrics::get(opCtx)->incrementNumAwaitingTopologyChanges();
    lk.unlock();

    if (MONGO_unlikely(waitForIsMasterResponse.shouldFail())) {
        // Used in tests that wait for this failpoint to be entered before shutting down mongos,
        // which is the only action that triggers a topology change.
        LOGV2(4695704, "waitForIsMasterResponse failpoint enabled");
    }

    if (MONGO_unlikely(hangWhileWaitingForIsMasterResponse.shouldFail())) {
        LOGV2(4695501, "hangWhileWaitingForIsMasterResponse failpoint enabled");
        hangWhileWaitingForIsMasterResponse.pauseWhileSet(opCtx);
    }

    // Wait for a mongos topology change with timeout set to deadline.
    LOGV2_DEBUG(4695502,
                1,
                "Waiting for an isMaster response from a topology change or until deadline",
                "deadline"_attr = deadline.get(),
                "currentMongosTopologyVersionCounter"_attr = _topologyVersion.getCounter());

    auto statusWithIsMaster =
        futureGetNoThrowWithDeadline(opCtx, future, deadline.get(), opCtx->getTimeoutError());
    auto status = statusWithIsMaster.getStatus();

    if (status == ErrorCodes::ExceededTimeLimit) {
        // Return a MongosIsMasterResponse with the current topology version on timeout when
        // waiting for a topology change.
        stdx::lock_guard lk(_mutex);
        IsMasterMetrics::get(opCtx)->decrementNumAwaitingTopologyChanges();
        return _makeIsMasterResponse(lk);
    }

    // A topology change has happened so we return an IsMasterResponse with the updated
    // topology version.
    uassertStatusOK(status);
    return statusWithIsMaster.getValue();
}

void MongosTopologyCoordinator::enterQuiesceModeAndWait(OperationContext* opCtx,
                                                        Milliseconds quiesceTime) {
    {
        stdx::lock_guard lk(_mutex);
        _inQuiesceMode = true;

        // Increment the topology version and respond to any waiting isMaster request with an error.
        auto counter = _topologyVersion.getCounter();
        _topologyVersion.setCounter(counter + 1);
        _promise->setError(
            {ErrorCodes::ShutdownInProgress, "Mongos is in quiesce mode and will shut down"});

        // Reset counter to 0 since we will respond to all waiting isMaster requests with an error.
        // All new isMaster requests will immediately fail with ShutdownInProgress.
        IsMasterMetrics::get(getGlobalServiceContext())->resetNumAwaitingTopologyChanges();
    }

    if (MONGO_unlikely(hangDuringQuiesceMode.shouldFail())) {
        LOGV2(4695700, "hangDuringQuiesceMode failpoint enabled");
        hangDuringQuiesceMode.pauseWhileSet(opCtx);
    }

    LOGV2(4695701, "Entering quiesce mode for mongos shutdown", "quiesceTime"_attr = quiesceTime);
    opCtx->sleepFor(quiesceTime);
    LOGV2(4695702, "Exiting quiesce mode for mongos shutdown");
}

}  // namespace mongo