summaryrefslogtreecommitdiff
path: root/src/mongo/db/repl/oplog_applier.h
blob: ecc45bf76dfb01de19074e5a7826c5a45328ac01 (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

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


#pragma once

#include <boost/optional.hpp>
#include <vector>

#include "mongo/base/disallow_copying.h"
#include "mongo/base/status.h"
#include "mongo/base/status_with.h"
#include "mongo/db/repl/oplog_buffer.h"
#include "mongo/db/repl/oplog_entry.h"
#include "mongo/db/repl/storage_interface.h"
#include "mongo/executor/task_executor.h"
#include "mongo/util/concurrency/thread_pool.h"
#include "mongo/util/future.h"
#include "mongo/util/net/hostandport.h"

namespace mongo {
namespace repl {

/**
 * Applies oplog entries.
 * Reads from an OplogBuffer batches of operations that may be applied in parallel.
 */
class OplogApplier {
    MONGO_DISALLOW_COPYING(OplogApplier);

public:
    /**
     * Used to configure behavior of this OplogApplier.
     **/
    class Options {
    public:
        bool allowNamespaceNotFoundErrorsOnCrudOps = false;
        bool relaxUniqueIndexConstraints = false;
        bool skipWritesToOplog = false;

        // For initial sync only. If an update fails, the missing document is fetched from
        // this sync source to insert into the local collection.
        boost::optional<HostAndPort> missingDocumentSourceForInitialSync;

        // Used to determine which operations should be applied. Only initial sync will set this to
        // be something other than the null optime.
        OpTime beginApplyingOpTime = OpTime();
    };

    /**
     * Controls what can popped from the oplog buffer into a single batch of operations that can be
     * applied using multiApply().
     */
    class BatchLimits {
    public:
        size_t bytes = 0;
        size_t ops = 0;

        // If provided, the batch will not include any operations with timestamps after this point.
        // This is intended for implementing slaveDelay, so it should be some number of seconds
        // before now.
        boost::optional<Date_t> slaveDelayLatestTimestamp = {};
    };

    // Used to report oplog application progress.
    class Observer;

    using Operations = std::vector<OplogEntry>;

    /**
     * Lower bound of batch limit size (in bytes) returned by calculateBatchLimitBytes().
     */
    static const unsigned int replBatchLimitBytes = 100 * 1024 * 1024;

    /**
     * Creates thread pool for writer tasks.
     */
    static std::unique_ptr<ThreadPool> makeWriterPool();
    static std::unique_ptr<ThreadPool> makeWriterPool(int threadCount);

    /**
     * Returns maximum number of operations in each batch that can be applied using multiApply().
     */
    static std::size_t getBatchLimitOperations();

    /**
     * Calculates batch limit size (in bytes) using the maximum capped collection size of the oplog
     * size.
     * Batches are limited to 10% of the oplog.
     */
    static std::size_t calculateBatchLimitBytes(OperationContext* opCtx,
                                                StorageInterface* storageInterface);

    /**
     * Constructs this OplogApplier with specific options.
     * Obtains batches of operations from the OplogBuffer to apply.
     * Reports oplog application progress using the Observer.
     */
    OplogApplier(executor::TaskExecutor* executor, OplogBuffer* oplogBuffer, Observer* observer);

    virtual ~OplogApplier() = default;

    /**
     * Returns this applier's buffer.
     */
    OplogBuffer* getBuffer() const;

    /**
     * Starts this OplogApplier.
     * Use the Future object to be notified when this OplogApplier has finished shutting down.
     */
    Future<void> startup();

    /**
     * Starts the shutdown process for this OplogApplier.
     * It is safe to call shutdown() multiplie times.
     */
    void shutdown();

    /**
     * Pushes operations read into oplog buffer.
     * Accepts both Operations (OplogEntry) and OplogBuffer::Batch (BSONObj) iterators.
     * This supports current implementations of OplogFetcher and OplogBuffer which work in terms of
     * BSONObj.
     */
    void enqueue(OperationContext* opCtx,
                 Operations::const_iterator begin,
                 Operations::const_iterator end);
    void enqueue(OperationContext* opCtx,
                 OplogBuffer::Batch::const_iterator begin,
                 OplogBuffer::Batch::const_iterator end);

    /**
     * Returns a new batch of ops to apply.
     * A batch may consist of:
     *     at most "BatchLimits::ops" OplogEntries
     *     at most "BatchLimits::bytes" worth of OplogEntries
     *     only OplogEntries from before the "BatchLimits::slaveDelayLatestTimestamp" point
     *     a single command OplogEntry (excluding applyOps, which are grouped with CRUD ops)
     */
    StatusWith<Operations> getNextApplierBatch(OperationContext* opCtx,
                                               const BatchLimits& batchLimits);

    /**
     * Applies a batch of oplog entries by writing the oplog entries to the local oplog and then
     * using a set of threads to apply the operations.
     *
     * If the batch application is successful, returns the optime of the last op applied, which
     * should be the last op in the batch.
     * Returns ErrorCodes::CannotApplyOplogWhilePrimary if the node has become primary.
     *
     * To provide crash resilience, this function will advance the persistent value of 'minValid'
     * to at least the last optime of the batch. If 'minValid' is already greater than or equal
     * to the last optime of this batch, it will not be updated.
     *
     * TODO: remove when enqueue() is implemented.
     */
    StatusWith<OpTime> multiApply(OperationContext* opCtx, Operations ops);

private:
    /**
     * Called from startup() to run oplog application loop.
     * Currently applicable to steady state replication only.
     * Implemented in subclasses but not visible otherwise.
     */
    virtual void _run(OplogBuffer* oplogBuffer) = 0;

    /**
     * Called from shutdown to signals oplog application loop to stop running.
     * Currently applicable to steady state replication only.
     * Implemented in subclasses but not visible otherwise.
     */
    virtual void _shutdown() = 0;

    /**
     * Called from multiApply() to apply a batch of operations in parallel.
     * Implemented in subclasses but not visible otherwise.
     */
    virtual StatusWith<OpTime> _multiApply(OperationContext* opCtx, Operations ops) = 0;

    // Used to schedule task for oplog application loop.
    // Not owned by us.
    executor::TaskExecutor* const _executor;

    // Not owned by us.
    OplogBuffer* const _oplogBuffer;

    // Not owned by us.
    Observer* const _observer;
};

/**
 * The OplogApplier reports its progress using the Observer interface.
 */
class OplogApplier::Observer {
public:
    virtual ~Observer() = default;

    /**
     * Called when the OplogApplier is ready to start applying a batch of operations read from the
     * OplogBuffer.
     **/
    virtual void onBatchBegin(const OplogApplier::Operations& operations) = 0;

    /**
     * When the OplogApplier has completed applying a batch of operations, it will call this
     * function to report the last optime applied on success. Any errors during oplog application
     * will also be here.
     */
    virtual void onBatchEnd(const StatusWith<OpTime>& lastOpTimeApplied,
                            const OplogApplier::Operations& operations) = 0;

    /**
     * Called when documents are fetched and inserted into the collection in order to
     * apply an update operation.
     * Applies to initial sync only.
     *
     * TODO: Delegate fetching behavior to OplogApplier owner.
     */
    using FetchInfo = std::pair<OplogEntry, BSONObj>;
    virtual void onMissingDocumentsFetchedAndInserted(
        const std::vector<FetchInfo>& documentsFetchedAndInserted) = 0;
};

}  // namespace repl
}  // namespace mongo