summaryrefslogtreecommitdiff
path: root/src/mongo/db/repl/noop_writer.cpp
blob: b3adb9da2cfb5afdccc2dfc49a30c8ff5bf360a5 (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
/**
 *    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::kReplication

#include "mongo/platform/basic.h"

#include <functional>

#include "mongo/db/commands.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/curop.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/repl/noop_writer.h"
#include "mongo/db/repl/oplog.h"
#include "mongo/db/repl/repl_server_parameters_gen.h"
#include "mongo/logv2/log.h"
#include "mongo/util/concurrency/idle_thread_block.h"
#include "mongo/util/testing_proctor.h"

namespace mongo {
namespace repl {

namespace {

const auto kMsgObj = BSON("msg"
                          << "periodic noop");

}  // namespace


/**
 *  Runs the noopWrite argument with waitTime period until its destroyed.
 */
class NoopWriter::PeriodicNoopRunner {
    PeriodicNoopRunner(const PeriodicNoopRunner&) = delete;
    PeriodicNoopRunner& operator=(const PeriodicNoopRunner&) = delete;

    using NoopWriteFn = std::function<void(OperationContext*)>;

public:
    PeriodicNoopRunner(Seconds waitTime, NoopWriteFn noopWrite)
        : _thread([this, noopWrite, waitTime] { run(waitTime, std::move(noopWrite)); }) {}

    ~PeriodicNoopRunner() {
        stdx::unique_lock<Latch> lk(_mutex);
        _inShutdown = true;
        _cv.notify_all();
        lk.unlock();
        _thread.join();
    }

private:
    void run(Seconds waitTime, NoopWriteFn noopWrite) {
        Client::initThread("NoopWriter");
        while (true) {
            const ServiceContext::UniqueOperationContext opCtxPtr = cc().makeOperationContext();
            OperationContext& opCtx = *opCtxPtr;
            {
                stdx::unique_lock<Latch> lk(_mutex);
                MONGO_IDLE_THREAD_BLOCK;
                _cv.wait_for(lk, waitTime.toSystemDuration(), [&] { return _inShutdown; });

                if (_inShutdown)
                    return;
            }
            noopWrite(&opCtx);
        }
    }

    /**
     *  Indicator that thread is shutting down.
     */
    bool _inShutdown{false};

    /**
     *  Mutex for the CV
     */
    Mutex _mutex = MONGO_MAKE_LATCH("PeriodicNoopRunner::_mutex");

    /**
     * CV to wait for.
     */
    stdx::condition_variable _cv;

    /**
     * Thread that runs the tasks. Must be last so all other members are initialized before
     * starting.
     */
    stdx::thread _thread;
};

NoopWriter::NoopWriter(Seconds writeInterval) : _writeInterval(writeInterval) {
    uassert(ErrorCodes::BadValue, "write interval must be positive", writeInterval > Seconds(0));
}

NoopWriter::~NoopWriter() {
    stopWritingPeriodicNoops();
}

Status NoopWriter::startWritingPeriodicNoops(OpTime lastKnownOpTime) {
    stdx::lock_guard<Latch> lk(_mutex);
    _lastKnownOpTime = lastKnownOpTime;

    invariant(!_noopRunner);
    _noopRunner =
        std::make_unique<PeriodicNoopRunner>(_writeInterval, [this](OperationContext* opCtx) {
            opCtx->setShouldParticipateInFlowControl(false);
            _writeNoop(opCtx);
        });
    return Status::OK();
}

void NoopWriter::stopWritingPeriodicNoops() {
    stdx::lock_guard<Latch> lk(_mutex);
    _noopRunner.reset();
}

void NoopWriter::_writeNoop(OperationContext* opCtx) {
    // Use GlobalLock instead of DBLock to allow return when the lock is not available. It may
    // happen when the primary steps down and a shared global lock is acquired.
    Lock::GlobalLock lock(
        opCtx, MODE_IX, Date_t::now() + Milliseconds(1), Lock::InterruptBehavior::kLeaveUnlocked);
    if (!lock.isLocked()) {
        LOGV2_DEBUG(21219, 1, "Global lock is not available, skipping the noop write");
        return;
    }

    auto replCoord = ReplicationCoordinator::get(opCtx);
    // Its a proxy for being a primary
    if (!replCoord->canAcceptWritesForDatabase(opCtx, "admin")) {
        LOGV2_DEBUG(21220, 1, "Not a primary, skipping the noop write");
        return;
    }

    auto lastAppliedOpTime = replCoord->getMyLastAppliedOpTime();

    // _lastKnownOpTime is not protected by lock as its used only by one thread.
    if (lastAppliedOpTime != _lastKnownOpTime) {
        LOGV2_DEBUG(21221,
                    1,
                    "Not scheduling a noop write. Last known OpTime: {lastKnownOpTime} != last "
                    "primary OpTime: {lastAppliedOpTime}",
                    "Not scheduling a noop write. Last known OpTime != last primary OpTime",
                    "lastKnownOpTime"_attr = _lastKnownOpTime,
                    "lastAppliedOpTime"_attr = lastAppliedOpTime);
    } else {
        if (writePeriodicNoops.load()) {
            const auto logLevel = TestingProctor::instance().isEnabled() ? 0 : 1;
            LOGV2_DEBUG(21222,
                        logLevel,
                        "Writing noop to oplog as there has been no writes to this replica set in "
                        "over {writeInterval}",
                        "Writing noop to oplog as there has been no writes to this replica set "
                        "within write interval",
                        "writeInterval"_attr = _writeInterval);
            writeConflictRetry(
                opCtx, "writeNoop", NamespaceString::kRsOplogNamespace.ns(), [&opCtx] {
                    WriteUnitOfWork uow(opCtx);
                    opCtx->getClient()->getServiceContext()->getOpObserver()->onOpMessage(opCtx,
                                                                                          kMsgObj);
                    uow.commit();
                });
        }
    }

    _lastKnownOpTime = replCoord->getMyLastAppliedOpTime();
    LOGV2_DEBUG(21223,
                1,
                "Set last known op time to {lastKnownOpTime}",
                "Set last known op time",
                "lastKnownOpTime"_attr = _lastKnownOpTime);
}

}  // namespace repl
}  // namespace mongo