summaryrefslogtreecommitdiff
path: root/src/mongo/db/storage/flow_control.cpp
blob: ab5669fa8b0ab26cbd3f374b73273d3fb9fd700b (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
/**
 *    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::kStorage
#define DEBUG_LOG_LEVEL 4

#include "mongo/platform/basic.h"

#include "mongo/db/storage/flow_control.h"

#include <algorithm>

#include "mongo/db/concurrency/flow_control_ticketholder.h"
#include "mongo/db/concurrency/lock_manager_defs.h"
#include "mongo/db/repl/member_data.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/server_options.h"
#include "mongo/db/storage/flow_control_parameters_gen.h"
#include "mongo/util/background.h"
#include "mongo/util/log.h"

namespace mongo {

namespace {
const auto getFlowControl = ServiceContext::declareDecoration<std::unique_ptr<FlowControl>>();
}  // namespace

FlowControl::FlowControl(ServiceContext* service, repl::ReplicationCoordinator* replCoord)
    : ServerStatusSection("flowControl"), _replCoord(replCoord) {
    _lastTargetTicketsPermitted.store(0);
    _lastLocksPerOp.store(0.0);
    _lastSustainerAppliedCount.store(0);

    FlowControlTicketholder::set(service, stdx::make_unique<FlowControlTicketholder>(1000));

    service->getPeriodicRunner()->scheduleJob(
        {"FlowControlRefresher",
         [this](Client* client) {
             FlowControlTicketholder::get(client->getServiceContext())->refreshTo(getNumTickets());
         },
         Seconds(1)});
}

FlowControl* FlowControl::get(ServiceContext* service) {
    return getFlowControl(service).get();
}

FlowControl* FlowControl::get(ServiceContext& service) {
    return getFlowControl(service).get();
}

FlowControl* FlowControl::get(OperationContext* ctx) {
    return get(ctx->getClient()->getServiceContext());
}

void FlowControl::set(ServiceContext* service, std::unique_ptr<FlowControl> flowControl) {
    auto& globalFlow = getFlowControl(service);
    globalFlow = std::move(flowControl);
}

double FlowControl::_getMyLocksPerOp() {
    // Primaries sample the number of operations it has applied alongside how many global lock
    // acquisitions (in MODE_IX) it took to process those operations. This method looks at the two
    // most recent samples and returns the ratio of global lock acquisitions to operations processed
    // for the current client workload.
    Sample backTwo;
    Sample backOne;
    std::size_t numSamples;
    {
        stdx::lock_guard<stdx::mutex> lk(_sampledOpsMutex);
        numSamples = _sampledOpsApplied.size();
        if (numSamples >= 2) {
            backTwo = _sampledOpsApplied[numSamples - 2];
            backOne = _sampledOpsApplied[numSamples - 1];
        }
    }

    return (double)(std::get<2>(backOne) - std::get<2>(backTwo)) /
        (double)(std::get<1>(backOne) - std::get<1>(backTwo));
}

BSONObj FlowControl::generateSection(OperationContext* opCtx,
                                     const BSONElement& configElement) const {
    const int lagSecs = _replCoord->getMyLastAppliedOpTime().getSecs() -
        _replCoord->getLastCommittedOpTime().getSecs();

    BSONObjBuilder bob;
    bob.append("targetRateLimit", _lastTargetTicketsPermitted.load());
    bob.append("timeAcquiringMicros", 0);
    bob.append("locksPerOp", _lastLocksPerOp.load());
    bob.append("sustainerRate", _lastSustainerAppliedCount.load());
    bob.append("isLagged", lagSecs >= gFlowControlTargetLagSeconds.load());

    return bob.obj();
}

int FlowControl::getNumTickets() {
    const int maxTickets = 1000 * 1000 * 1000;
    if (serverGlobalParams.enableMajorityReadConcern == false || gFlowControlEnabled == false) {
        return maxTickets;
    }

    const Timestamp myLastApplied = _replCoord->getMyLastAppliedOpTime().getTimestamp();
    const Timestamp lastCommitted = _replCoord->getLastCommittedOpTime().getTimestamp();
    const int lagSecs = myLastApplied.getSecs() - lastCommitted.getSecs();

    bool areWeLagged = lagSecs >= gFlowControlTargetLagSeconds.load();
    if (areWeLagged && _approximateOpsBetween(lastCommitted.asULL(), myLastApplied.asULL()) == -1) {
        // _approximateOpsBetween will return -1 if the input timestamps are in the same
        // "bucket". This is an indication that there are very few ops between the two timestamps.
        //
        // Don't let the no-op writer on idle systems fool the sophisticated "is the replica set
        // lagged" classifier.
        areWeLagged = false;
    }

    std::vector<repl::MemberData> currMemberData = _replCoord->getMemberData();
    // Sort MemberData with the 0th index being the node with the lowest applied optime.
    std::sort(currMemberData.begin(),
              currMemberData.end(),
              [](const repl::MemberData& left, const repl::MemberData& right) -> bool {
                  return left.getLastAppliedOpTime() < right.getLastAppliedOpTime();
              });

    int ret = 0;
    auto locksUsedLastPeriod = getLocksUsedLastPeriod();
    if (areWeLagged) {
        std::int64_t sustainerAppliedCount = -1;
        if (currMemberData.size() > 0 && currMemberData.size() == _prevMemberData.size()) {
            // The index into the array of sorted MemberData that represents the sustaining node.
            int sustainerIdx = currMemberData.size() / 2;

            auto currSustainerAppliedTs =
                currMemberData[sustainerIdx].getLastAppliedOpTime().getTimestamp();
            auto prevSustainerAppliedTs =
                _prevMemberData[sustainerIdx].getLastAppliedOpTime().getTimestamp();

            sustainerAppliedCount = _approximateOpsBetween(prevSustainerAppliedTs.asULL(),
                                                           currSustainerAppliedTs.asULL());
            LOG(DEBUG_LOG_LEVEL) << " PrevApplied: " << prevSustainerAppliedTs
                                 << " CurrApplied: " << currSustainerAppliedTs
                                 << " NumSustainerApplied: " << sustainerAppliedCount;
        } else {
            error() << "ERRORING FLOW CONTROL. Size diff.";
        }

        _lastSustainerAppliedCount.store(static_cast<int>(sustainerAppliedCount));
        if (sustainerAppliedCount > -1) {
            // We know how many ops the sustainer applied, use that for calculating the new number
            // of tickets.
            const double sustainerAppliedPenalty = (double)(sustainerAppliedCount) / 2.0;
            _lastTargetTicketsPermitted.store(static_cast<int>(sustainerAppliedPenalty));
            const auto locksPerOp = _getMyLocksPerOp();
            _lastLocksPerOp.store(locksPerOp);
            LOG(DEBUG_LOG_LEVEL) << "LocksPerOp: " << locksPerOp
                                 << " Sustainer: " << sustainerAppliedCount
                                 << " Target: " << sustainerAppliedPenalty;
            ret = static_cast<int>(locksPerOp * sustainerAppliedPenalty);
        } else {
            // We don't know how many ops the sustainer applied. Hand out less tickets than were
            // used in the last period.
            ret = static_cast<int>(locksUsedLastPeriod / 2.0);
            _lastTargetTicketsPermitted.store(-1);
        }

        // Always have at least 100 tickets.
        ret = std::max(ret, 100);
    } else {
        ret = static_cast<int>((_lastTargetTicketsPermitted.load() + 1000) * 1.1);
    }

    _prevMemberData = std::move(currMemberData);

    ret = std::min(ret, maxTickets);

    LOG(DEBUG_LOG_LEVEL) << "Are lagged? " << areWeLagged << " Prev lag: " << _prevLagSecs
                         << " Curr lag: " << lagSecs << " OpsLagged: "
                         << _approximateOpsBetween(lastCommitted.asULL(), myLastApplied.asULL())
                         << " Granting: " << ret
                         << " Last granted: " << _lastTargetTicketsPermitted.load()
                         << " Acquisitions since last check: " << locksUsedLastPeriod;

    _lastTargetTicketsPermitted.store(ret);
    _prevLagSecs = lagSecs;
    return ret;
}

std::int64_t FlowControl::_approximateOpsBetween(std::uint64_t prevTs, std::uint64_t currTs) {
    std::int64_t prevApplied = -1;
    std::int64_t currApplied = -1;

    stdx::lock_guard<stdx::mutex> lk(_sampledOpsMutex);
    for (auto&& sample : _sampledOpsApplied) {
        if (prevApplied == -1 && prevTs < std::get<0>(sample)) {
            prevApplied = std::get<1>(sample);
        }

        if (currApplied == -1 && currTs < std::get<0>(sample)) {
            currApplied = std::get<1>(sample);
            break;
        }
    }

    if (prevApplied != -1 && currApplied == -1) {
        currApplied = std::get<1>(_sampledOpsApplied[_sampledOpsApplied.size() - 1]);
    }

    if (prevApplied != -1 && currApplied != -1) {
        return currApplied - prevApplied;
    }

    return -1;
}

void FlowControl::sample(Timestamp timestamp, std::uint64_t opsApplied) {
    if (serverGlobalParams.enableMajorityReadConcern == false || gFlowControlEnabled == false) {
        // TODO SERVER-39616: Remove this feature flag such that flow control can be turned on/off
        // at runtime.
        return;
    }

    stdx::lock_guard<stdx::mutex> lk(_sampledOpsMutex);
    _numOpsSinceStartup += opsApplied;
    if (_numOpsSinceStartup - _lastSample < 1000) {
        // Naively sample once every 1000 or so operations.
        return;
    }

    SingleThreadedLockStats stats;
    reportGlobalLockingStats(&stats);

    _lastSample = _numOpsSinceStartup;

    const auto lockAcquisitions = stats.get(resourceIdGlobal, LockMode::MODE_IX).numAcquisitions;
    LOG(DEBUG_LOG_LEVEL) << "Sampling. Time: " << timestamp << " Applied: " << _numOpsSinceStartup
                         << " LockAcquisitions: " << lockAcquisitions;
    _sampledOpsApplied.emplace_back(
        static_cast<std::uint64_t>(timestamp.asULL()), _numOpsSinceStartup, lockAcquisitions);
}

int64_t FlowControl::getLocksUsedLastPeriod() {
    SingleThreadedLockStats stats;
    reportGlobalLockingStats(&stats);

    int64_t counter = stats.get(resourceIdGlobal, LockMode::MODE_IX).numAcquisitions;
    int64_t ret = counter - _lastPollLockAcquisitions;
    _lastPollLockAcquisitions = counter;

    _lastLocksPerOp.store(ret);

    return ret;
}

}  // namespace mongo