summaryrefslogtreecommitdiff
path: root/src/mongo/db/repl/repl_set_config.h
blob: 36fdb2d0e8e95b631c674edb9f24585bca14f1be (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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/**
 *    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 <string>
#include <vector>

#include "mongo/base/status.h"
#include "mongo/base/status_with.h"
#include "mongo/client/connection_string.h"
#include "mongo/db/repl/member_config.h"
#include "mongo/db/repl/repl_set_tag.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/util/string_map.h"
#include "mongo/util/time_support.h"

namespace mongo {

class BSONObj;

namespace repl {

/**
 * A structure that stores a ReplSetConfig (version, term) pair.
 *
 * This can be used to compare two ReplSetConfig objects to determine which is logically newer.
 */
class ConfigVersionAndTerm {
public:
    ConfigVersionAndTerm() : _version(0), _term(OpTime::kUninitializedTerm) {}
    ConfigVersionAndTerm(int version, long long term) : _version(version), _term(term) {}

    inline bool operator==(const ConfigVersionAndTerm& rhs) const {
        // If term of either item is uninitialized (-1), then we ignore terms entirely and only
        // compare versions.
        if (_term == OpTime::kUninitializedTerm || rhs._term == OpTime::kUninitializedTerm) {
            return _version == rhs._version;
        }
        // Compare term first, then the versions.
        return std::tie(_term, _version) == std::tie(rhs._term, rhs._version);
    }

    inline bool operator<(const ConfigVersionAndTerm& rhs) const {
        // If term of either item is uninitialized (-1), then we ignore terms entirely and only
        // compare versions. This allows force reconfigs, which set the config term to -1, to
        // override other configs by using a high config version.
        if (_term == OpTime::kUninitializedTerm || rhs._term == OpTime::kUninitializedTerm) {
            return _version < rhs._version;
        }
        // Compare term first, then the versions.
        return std::tie(_term, _version) < std::tie(rhs._term, rhs._version);
    }

    inline bool operator!=(const ConfigVersionAndTerm& rhs) const {
        return !(*this == rhs);
    }

    inline bool operator<=(const ConfigVersionAndTerm& rhs) const {
        return *this < rhs || *this == rhs;
    }

    inline bool operator>(const ConfigVersionAndTerm& rhs) const {
        return !(*this <= rhs);
    }

    inline bool operator>=(const ConfigVersionAndTerm& rhs) const {
        return !(*this < rhs);
    }

    std::string toString() const {
        return str::stream() << "{version: " << _version << ", term: " << _term << "}";
    };

    friend std::ostream& operator<<(std::ostream& out, const ConfigVersionAndTerm& cvt) {
        return out << cvt.toString();
    }

private:
    long long _version;
    long long _term;
};

/**
 * Representation of the configuration information about a particular replica set.
 */
class ReplSetConfig {
public:
    typedef std::vector<MemberConfig>::const_iterator MemberIterator;

    static const std::string kConfigServerFieldName;
    static const std::string kVersionFieldName;
    static const std::string kTermFieldName;
    static const std::string kMajorityWriteConcernModeName;

    // If this field is present, a repair operation potentially modified replicated data. This
    // should never be included in a valid configuration document.
    static const std::string kRepairedFieldName;

    /**
     * Inline `kMaxMembers` to allow others (e.g, `WriteConcernOptions`) use
     * the constant without linking to `repl_set_config.cpp`.
     */
    inline static const size_t kMaxMembers = 50;
    static const size_t kMaxVotingMembers = 7;
    static const Milliseconds kInfiniteCatchUpTimeout;
    static const Milliseconds kCatchUpDisabled;
    static const Milliseconds kCatchUpTakeoverDisabled;

    static const Milliseconds kDefaultElectionTimeoutPeriod;
    static const Milliseconds kDefaultHeartbeatInterval;
    static const Seconds kDefaultHeartbeatTimeoutPeriod;
    static const Milliseconds kDefaultCatchUpTimeoutPeriod;
    static const bool kDefaultChainingAllowed;
    static const Milliseconds kDefaultCatchUpTakeoverDelay;

    /**
     * Initializes this ReplSetConfig from the contents of "cfg".
     * Sets _replicaSetId to "defaultReplicaSetId" if a replica set ID is not specified in "cfg".
     * If forceTerm is not boost::none, sets _term to the given term. Otherwise, parses term from
     * config BSON.
     */
    Status initialize(const BSONObj& cfg,
                      boost::optional<long long> forceTerm = boost::none,
                      OID defaultReplicaSetId = OID());

    /**
     * Same as the generic initialize() above except will default "configsvr" setting to the value
     * of serverGlobalParams.configsvr.
     * Sets _term to kInitialTerm.
     */
    Status initializeForInitiate(const BSONObj& cfg);

    /**
     * Returns true if this object has been successfully initialized or copied from
     * an initialized object.
     */
    bool isInitialized() const {
        return _isInitialized;
    }

    /**
     * Performs basic consistency checks on the replica set configuration.
     */
    Status validate() const;

    /**
     * Checks if this configuration can satisfy the given write concern.
     *
     * Things that are taken into consideration include:
     * 1. If the set has enough data-bearing members.
     * 2. If the write concern mode exists.
     * 3. If there are enough members for the write concern mode specified.
     */
    Status checkIfWriteConcernCanBeSatisfied(const WriteConcernOptions& writeConcern) const;

    /**
     * Gets the version of this configuration.
     *
     * The version number sequences configurations of the replica set, so that
     * nodes may distinguish between "older" and "newer" configurations.
     */
    long long getConfigVersion() const {
        return _version;
    }

    /**
     * Gets the term of this configuration.
     *
     * The configuration term is the term of the primary that originally created this configuration.
     * Configurations in a replica set are totally ordered by their term and configuration version.
     */
    long long getConfigTerm() const {
        return _term;
    }

    /**
     * Gets the (version, term) pair of this configuration.
     */
    ConfigVersionAndTerm getConfigVersionAndTerm() const {
        return ConfigVersionAndTerm(_version, _term);
    }

    /**
     * Gets the name (_id field value) of the replica set described by this configuration.
     */
    const std::string& getReplSetName() const {
        return _replSetName;
    }

    /**
     * Gets the connection string that can be used to talk to this replica set.
     */
    ConnectionString getConnectionString() const {
        return _connectionString;
    }

    /**
     * Gets the number of members in this configuration.
     */
    int getNumMembers() const {
        return _members.size();
    }

    /**
     * Gets the number of data-bearing members in this configuration.
     */
    int getNumDataBearingMembers() const;

    /**
     * Gets a begin iterator over the MemberConfigs stored in this ReplSetConfig.
     */
    MemberIterator membersBegin() const {
        return _members.begin();
    }

    /**
     * Gets an end iterator over the MemberConfigs stored in this ReplSetConfig.
     */
    MemberIterator membersEnd() const {
        return _members.end();
    }

    const std::vector<MemberConfig>& members() const {
        return _members;
    }

    /**
     * Returns all voting members in this ReplSetConfig.
     */
    std::vector<MemberConfig> votingMembers() const {
        std::vector<MemberConfig> votingMembers;
        for (const MemberConfig& m : _members) {
            if (m.getNumVotes() > 0) {
                votingMembers.push_back(m);
            }
        }
        return votingMembers;
    };

    /**
     * Access a MemberConfig element by index.
     */
    const MemberConfig& getMemberAt(size_t i) const;

    /**
     * Returns a pointer to the MemberConfig corresponding to the member with the given _id in
     * the config, or NULL if there is no member with that ID.
     */
    const MemberConfig* findMemberByID(int id) const;

    /**
     * Returns a pointer to the MemberConfig corresponding to the member with the given
     * HostAndPort in the config, or NULL if there is no member with that address.
     */
    const MemberConfig* findMemberByHostAndPort(const HostAndPort& hap) const;

    /**
     * Returns a MemberConfig index position corresponding to the member with the given
     * HostAndPort in the config, or -1 if there is no member with that address.
     */
    int findMemberIndexByHostAndPort(const HostAndPort& hap) const;

    /**
     * Returns a MemberConfig index position corresponding to the member with the given
     * _id in the config, or -1 if there is no member with that address.
     */
    int findMemberIndexByConfigId(long long configId) const;

    /**
     * Gets the default write concern for the replica set described by this configuration.
     */
    const WriteConcernOptions& getDefaultWriteConcern() const {
        return _defaultWriteConcern;
    }

    /**
     * Interval between the time the last heartbeat from a node was received successfully, or
     * the time when we gave up retrying, and when the next heartbeat should be sent to a target.
     * Returns default heartbeat interval if this configuration is not initialized.
     */
    Milliseconds getHeartbeatInterval() const;

    /**
     * Gets the timeout for determining when the current PRIMARY is dead, which triggers a node to
     * run for election.
     */
    Milliseconds getElectionTimeoutPeriod() const {
        return _electionTimeoutPeriod;
    }

    /**
     * Gets the amount of time to wait for a response to hearbeats sent to other
     * nodes in the replica set.
     */
    Seconds getHeartbeatTimeoutPeriod() const {
        return _heartbeatTimeoutPeriod;
    }

    /**
     * Gets the amount of time to wait for a response to hearbeats sent to other
     * nodes in the replica set, as above, but returns a Milliseconds instead of
     * Seconds object.
     */
    Milliseconds getHeartbeatTimeoutPeriodMillis() const {
        return _heartbeatTimeoutPeriod;
    }

    /**
     * Gets the timeout to wait for a primary to catch up its oplog.
     */
    Milliseconds getCatchUpTimeoutPeriod() const {
        return _catchUpTimeoutPeriod;
    }

    /**
     * Gets the number of votes required to win an election.
     */
    int getMajorityVoteCount() const {
        return _majorityVoteCount;
    }

    /**
     * Gets the number of voters.
     */
    int getTotalVotingMembers() const {
        return _totalVotingMembers;
    }

    /**
     * Returns true if automatic (not explicitly set) chaining is allowed.
     */
    bool isChainingAllowed() const {
        return _chainingAllowed;
    }

    /**
     * Returns whether all members of this replica set have hostname localhost.
     */
    bool isLocalHostAllowed() const;

    /**
     * Returns whether or not majority write concerns should implicitly journal, if j has not been
     * explicitly set.
     */
    bool getWriteConcernMajorityShouldJournal() const {
        return _writeConcernMajorityJournalDefault;
    }

    /**
     * Returns true if this replica set is for use as a config server replica set.
     */
    bool isConfigServer() const {
        return _configServer;
    }

    /**
     * Returns a ReplSetTag with the given "key" and "value", or an invalid
     * tag if the configuration describes no such tag.
     */
    ReplSetTag findTag(StringData key, StringData value) const;

    /**
     * Returns the pattern corresponding to "patternName" in this configuration.
     * If "patternName" is not a valid pattern in this configuration, returns
     * ErrorCodes::NoSuchKey.
     */
    StatusWith<ReplSetTagPattern> findCustomWriteMode(StringData patternName) const;

    /**
     * Returns the "tags configuration" for this replicaset.
     *
     * NOTE(schwerin): Not clear if this should be used other than for reporting/debugging.
     */
    const ReplSetTagConfig& getTagConfig() const {
        return _tagConfig;
    }

    /**
     * Returns the config as a BSONObj.
     */
    BSONObj toBSON() const;

    /**
     * Returns a vector of strings which are the names of the WriteConcernModes.
     * Currently used in unit tests to compare two configs.
     */
    std::vector<std::string> getWriteConcernNames() const;

    /**
     * Returns the number of voting data-bearing members that must acknowledge a write
     * in order to satisfy a write concern of {w: "majority"}.
     */
    int getWriteMajority() const {
        return _writeMajority;
    }

    /**
     * Gets the protocol version for this configuration.
     *
     * The protocol version number currently determines what election protocol is used by the
     * cluster; 1 is the default.
     */
    long long getProtocolVersion() const {
        return _protocolVersion;
    }

    /**
     * Returns true if this configuration contains a valid replica set ID.
     * This ID is set at creation and is used to disambiguate replica set configurations that may
     * have the same replica set name (_id field) but meant for different replica set instances.
     */
    bool hasReplicaSetId() const {
        return _replicaSetId.isSet();
    }

    /**
     * Returns replica set ID.
     */
    OID getReplicaSetId() const {
        return _replicaSetId;
    }

    /**
     * Returns the duration to wait before running for election when this node (indicated by
     * "memberIdx") sees that it has higher priority than the current primary.
     */
    Milliseconds getPriorityTakeoverDelay(int memberIdx) const;

    /**
     * Returns the duration to wait before running for election when this node
     * sees that it is more caught up than the current primary.
     */
    Milliseconds getCatchUpTakeoverDelay() const {
        return _catchUpTakeoverDelay;
    }

    /**
     * Return the number of members with a priority greater than "priority".
     */
    int calculatePriorityRank(double priority) const;

    /**
     * Returns true if this replica set has at least one arbiter.
     */
    bool containsArbiter() const;

private:
    /**
     * Parses the "settings" subdocument of a replica set configuration.
     */
    Status _parseSettingsSubdocument(const BSONObj& settings);

    /**
     * Calculates and stores the majority for electing a primary (_majorityVoteCount).
     */
    void _calculateMajorities();

    /**
     * Adds internal write concern modes to the getLastErrorModes list.
     */
    void _addInternalWriteConcernModes();

    /**
     * Populate _connectionString based on the contents of _members and _replSetName.
     */
    void _initializeConnectionString();

    /**
     * Sets replica set ID to 'defaultReplicaSetId' if forInitiate is false and 'cfg' does not
     * contain an ID.
     * Sets _term to kInitialTerm for initiate.
     * Sets _term to forceTerm if it is not boost::none. Otherwise, parses term from 'cfg'.
     */
    Status _initialize(const BSONObj& cfg,
                       bool forInitiate,
                       boost::optional<long long> forceTerm,
                       OID defaultReplicaSetId);

    bool _isInitialized = false;
    long long _version = 1;
    long long _term = OpTime::kUninitializedTerm;
    std::string _replSetName;
    std::vector<MemberConfig> _members;
    WriteConcernOptions _defaultWriteConcern;
    Milliseconds _electionTimeoutPeriod = kDefaultElectionTimeoutPeriod;
    Milliseconds _heartbeatInterval = kDefaultHeartbeatInterval;
    Seconds _heartbeatTimeoutPeriod = kDefaultHeartbeatTimeoutPeriod;
    Milliseconds _catchUpTimeoutPeriod = kDefaultCatchUpTimeoutPeriod;
    Milliseconds _catchUpTakeoverDelay = kDefaultCatchUpTakeoverDelay;
    bool _chainingAllowed = kDefaultChainingAllowed;
    bool _writeConcernMajorityJournalDefault = false;
    int _majorityVoteCount = 0;
    int _writeMajority = 0;
    int _totalVotingMembers = 0;
    ReplSetTagConfig _tagConfig;
    StringMap<ReplSetTagPattern> _customWriteConcernModes;
    long long _protocolVersion = 1;
    bool _configServer = false;
    OID _replicaSetId;
    ConnectionString _connectionString;
};


}  // namespace repl
}  // namespace mongo