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
|
/**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* 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 GNU Affero General 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::kReplication
#include "mongo/platform/basic.h"
#include "mongo/bson/json.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/operation_context_noop.h"
#include "mongo/db/repl/repl_set_config.h"
#include "mongo/db/repl/repl_set_heartbeat_args.h"
#include "mongo/db/repl/repl_set_heartbeat_args_v1.h"
#include "mongo/db/repl/replication_coordinator_external_state_mock.h"
#include "mongo/db/repl/replication_coordinator_impl.h"
#include "mongo/db/repl/replication_coordinator_test_fixture.h"
#include "mongo/db/repl/topology_coordinator_impl.h"
#include "mongo/executor/network_interface_mock.h"
#include "mongo/rpc/metadata/repl_set_metadata.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/log.h"
namespace mongo {
namespace repl {
namespace {
using executor::NetworkInterfaceMock;
using executor::RemoteCommandRequest;
using executor::RemoteCommandResponse;
class ReplCoordHBV1Test : public ReplCoordTest {
protected:
void assertMemberState(MemberState expected, std::string msg = "");
ReplSetHeartbeatResponse receiveHeartbeatFrom(const ReplSetConfig& rsConfig,
int sourceId,
const HostAndPort& source);
};
void ReplCoordHBV1Test::assertMemberState(const MemberState expected, std::string msg) {
const MemberState actual = getReplCoord()->getMemberState();
ASSERT(expected == actual) << "Expected coordinator to report state " << expected.toString()
<< " but found " << actual.toString() << " - " << msg;
}
ReplSetHeartbeatResponse ReplCoordHBV1Test::receiveHeartbeatFrom(const ReplSetConfig& rsConfig,
int sourceId,
const HostAndPort& source) {
ReplSetHeartbeatArgsV1 hbArgs;
hbArgs.setConfigVersion(rsConfig.getConfigVersion());
hbArgs.setSetName(rsConfig.getReplSetName());
hbArgs.setSenderHost(source);
hbArgs.setSenderId(sourceId);
hbArgs.setTerm(1);
ASSERT(hbArgs.isInitialized());
ReplSetHeartbeatResponse response;
ASSERT_OK(getReplCoord()->processHeartbeatV1(hbArgs, &response));
return response;
}
TEST_F(ReplCoordHBV1Test,
NodeJoinsExistingReplSetWhenReceivingAConfigContainingTheNodeViaHeartbeat) {
logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Debug(3));
ReplSetConfig rsConfig = assertMakeRSConfig(BSON("_id"
<< "mySet"
<< "version"
<< 3
<< "members"
<< BSON_ARRAY(BSON("_id" << 1 << "host"
<< "h1:1")
<< BSON("_id" << 2 << "host"
<< "h2:1")
<< BSON("_id" << 3 << "host"
<< "h3:1"))
<< "protocolVersion"
<< 1));
init("mySet");
addSelf(HostAndPort("h2", 1));
const Date_t startDate = getNet()->now();
start();
enterNetwork();
assertMemberState(MemberState::RS_STARTUP);
NetworkInterfaceMock* net = getNet();
ASSERT_FALSE(net->hasReadyRequests());
exitNetwork();
receiveHeartbeatFrom(rsConfig, 1, HostAndPort("h1", 1));
enterNetwork();
NetworkInterfaceMock::NetworkOperationIterator noi = net->getNextReadyRequest();
const RemoteCommandRequest& request = noi->getRequest();
ASSERT_EQUALS(HostAndPort("h1", 1), request.target);
ReplSetHeartbeatArgs hbArgs;
ASSERT_OK(hbArgs.initialize(request.cmdObj));
ASSERT_EQUALS("mySet", hbArgs.getSetName());
ASSERT_EQUALS(-2, hbArgs.getConfigVersion());
ReplSetHeartbeatResponse hbResp;
hbResp.setSetName("mySet");
hbResp.setState(MemberState::RS_PRIMARY);
hbResp.setConfigVersion(rsConfig.getConfigVersion());
hbResp.setConfig(rsConfig);
BSONObjBuilder responseBuilder;
responseBuilder << "ok" << 1;
hbResp.addToBSON(&responseBuilder, true);
net->scheduleResponse(
noi, startDate + Milliseconds(200), makeResponseStatus(responseBuilder.obj()));
assertRunUntil(startDate + Milliseconds(200));
// Because the new config is stored using an out-of-band thread, we need to perform some
// extra synchronization to let the executor finish the heartbeat reconfig. We know that
// after the out-of-band thread completes, it schedules new heartbeats. We assume that no
// other network operations get scheduled during or before the reconfig, though this may
// cease to be true in the future.
noi = net->getNextReadyRequest();
assertMemberState(MemberState::RS_STARTUP2);
OperationContextNoop opCtx;
ReplSetConfig storedConfig;
ASSERT_OK(storedConfig.initialize(
unittest::assertGet(getExternalState()->loadLocalConfigDocument(&opCtx))));
ASSERT_OK(storedConfig.validate());
ASSERT_EQUALS(3, storedConfig.getConfigVersion());
ASSERT_EQUALS(3, storedConfig.getNumMembers());
exitNetwork();
ASSERT_TRUE(getExternalState()->threadsStarted());
}
TEST_F(ReplCoordHBV1Test,
ArbiterJoinsExistingReplSetWhenReceivingAConfigContainingTheArbiterViaHeartbeat) {
logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Debug(3));
ReplSetConfig rsConfig = assertMakeRSConfig(BSON("_id"
<< "mySet"
<< "version"
<< 3
<< "members"
<< BSON_ARRAY(BSON("_id" << 1 << "host"
<< "h1:1")
<< BSON("_id" << 2 << "host"
<< "h2:1"
<< "arbiterOnly"
<< true)
<< BSON("_id" << 3 << "host"
<< "h3:1"))
<< "protocolVersion"
<< 1));
init("mySet");
addSelf(HostAndPort("h2", 1));
const Date_t startDate = getNet()->now();
start();
enterNetwork();
assertMemberState(MemberState::RS_STARTUP);
NetworkInterfaceMock* net = getNet();
ASSERT_FALSE(net->hasReadyRequests());
exitNetwork();
receiveHeartbeatFrom(rsConfig, 1, HostAndPort("h1", 1));
enterNetwork();
NetworkInterfaceMock::NetworkOperationIterator noi = net->getNextReadyRequest();
const RemoteCommandRequest& request = noi->getRequest();
ASSERT_EQUALS(HostAndPort("h1", 1), request.target);
ReplSetHeartbeatArgs hbArgs;
ASSERT_OK(hbArgs.initialize(request.cmdObj));
ASSERT_EQUALS("mySet", hbArgs.getSetName());
ASSERT_EQUALS(-2, hbArgs.getConfigVersion());
ReplSetHeartbeatResponse hbResp;
hbResp.setSetName("mySet");
hbResp.setState(MemberState::RS_PRIMARY);
hbResp.setConfigVersion(rsConfig.getConfigVersion());
hbResp.setConfig(rsConfig);
BSONObjBuilder responseBuilder;
responseBuilder << "ok" << 1;
hbResp.addToBSON(&responseBuilder, true);
net->scheduleResponse(
noi, startDate + Milliseconds(200), makeResponseStatus(responseBuilder.obj()));
assertRunUntil(startDate + Milliseconds(200));
// Because the new config is stored using an out-of-band thread, we need to perform some
// extra synchronization to let the executor finish the heartbeat reconfig. We know that
// after the out-of-band thread completes, it schedules new heartbeats. We assume that no
// other network operations get scheduled during or before the reconfig, though this may
// cease to be true in the future.
noi = net->getNextReadyRequest();
assertMemberState(MemberState::RS_ARBITER);
OperationContextNoop opCtx;
ReplSetConfig storedConfig;
ASSERT_OK(storedConfig.initialize(
unittest::assertGet(getExternalState()->loadLocalConfigDocument(&opCtx))));
ASSERT_OK(storedConfig.validate());
ASSERT_EQUALS(3, storedConfig.getConfigVersion());
ASSERT_EQUALS(3, storedConfig.getNumMembers());
exitNetwork();
ASSERT_FALSE(getExternalState()->threadsStarted());
}
TEST_F(ReplCoordHBV1Test,
NodeDoesNotJoinExistingReplSetWhenReceivingAConfigNotContainingTheNodeViaHeartbeat) {
// Tests that a node in RS_STARTUP will not transition to RS_REMOVED if it receives a
// configuration that does not contain it.
logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Debug(3));
ReplSetConfig rsConfig = assertMakeRSConfig(BSON("_id"
<< "mySet"
<< "version"
<< 3
<< "members"
<< BSON_ARRAY(BSON("_id" << 1 << "host"
<< "h1:1")
<< BSON("_id" << 2 << "host"
<< "h2:1")
<< BSON("_id" << 3 << "host"
<< "h3:1"))
<< "protocolVersion"
<< 1));
init("mySet");
addSelf(HostAndPort("h4", 1));
const Date_t startDate = getNet()->now();
start();
enterNetwork();
assertMemberState(MemberState::RS_STARTUP, "1");
NetworkInterfaceMock* net = getNet();
ASSERT_FALSE(net->hasReadyRequests());
exitNetwork();
receiveHeartbeatFrom(rsConfig, 1, HostAndPort("h1", 1));
enterNetwork();
NetworkInterfaceMock::NetworkOperationIterator noi = net->getNextReadyRequest();
const RemoteCommandRequest& request = noi->getRequest();
ASSERT_EQUALS(HostAndPort("h1", 1), request.target);
ReplSetHeartbeatArgs hbArgs;
ASSERT_OK(hbArgs.initialize(request.cmdObj));
ASSERT_EQUALS("mySet", hbArgs.getSetName());
ASSERT_EQUALS(-2, hbArgs.getConfigVersion());
ReplSetHeartbeatResponse hbResp;
hbResp.setSetName("mySet");
hbResp.setState(MemberState::RS_PRIMARY);
hbResp.setConfigVersion(rsConfig.getConfigVersion());
hbResp.setConfig(rsConfig);
BSONObjBuilder responseBuilder;
responseBuilder << "ok" << 1;
hbResp.addToBSON(&responseBuilder, true);
net->scheduleResponse(
noi, startDate + Milliseconds(200), makeResponseStatus(responseBuilder.obj()));
assertRunUntil(startDate + Milliseconds(2200));
// Because the new config is stored using an out-of-band thread, we need to perform some
// extra synchronization to let the executor finish the heartbeat reconfig. We know that
// after the out-of-band thread completes, it schedules new heartbeats. We assume that no
// other network operations get scheduled during or before the reconfig, though this may
// cease to be true in the future.
noi = net->getNextReadyRequest();
assertMemberState(MemberState::RS_STARTUP, "2");
OperationContextNoop opCtx;
StatusWith<BSONObj> loadedConfig(getExternalState()->loadLocalConfigDocument(&opCtx));
ASSERT_NOT_OK(loadedConfig.getStatus()) << loadedConfig.getValue();
exitNetwork();
}
TEST_F(ReplCoordHBV1Test,
NodeReturnsNotYetInitializedInResponseToAHeartbeatReceivedPriorToAConfig) {
// ensure that if we've yet to receive an initial config, we return NotYetInitialized
init("mySet");
ReplSetHeartbeatArgsV1 hbArgs;
hbArgs.setConfigVersion(3);
hbArgs.setSetName("mySet");
hbArgs.setSenderHost(HostAndPort("h1:1"));
hbArgs.setSenderId(1);
hbArgs.setTerm(1);
ASSERT(hbArgs.isInitialized());
ReplSetHeartbeatResponse response;
Status status = getReplCoord()->processHeartbeatV1(hbArgs, &response);
ASSERT_EQUALS(ErrorCodes::NotYetInitialized, status.code());
}
TEST_F(ReplCoordHBV1Test,
NodeChangesToRecoveringStateWhenAllNodesRespondToHeartbeatsWithUnauthorized) {
// Tests that a node that only has auth error heartbeats is recovering
logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Debug(3));
assertStartSuccess(BSON("_id"
<< "mySet"
<< "version"
<< 1
<< "members"
<< BSON_ARRAY(BSON("_id" << 1 << "host"
<< "node1:12345")
<< BSON("_id" << 2 << "host"
<< "node2:12345"))),
HostAndPort("node1", 12345));
ASSERT(getReplCoord()->setFollowerMode(MemberState::RS_SECONDARY));
// process heartbeat
enterNetwork();
const NetworkInterfaceMock::NetworkOperationIterator noi = getNet()->getNextReadyRequest();
const RemoteCommandRequest& request = noi->getRequest();
log() << request.target.toString() << " processing " << request.cmdObj;
getNet()->scheduleResponse(noi,
getNet()->now(),
makeResponseStatus(BSON("ok" << 0.0 << "errmsg"
<< "unauth'd"
<< "code"
<< ErrorCodes::Unauthorized)));
if (request.target != HostAndPort("node2", 12345) &&
request.cmdObj.firstElement().fieldNameStringData() != "replSetHeartbeat") {
error() << "Black holing unexpected request to " << request.target << ": "
<< request.cmdObj;
getNet()->blackHole(noi);
}
getNet()->runReadyNetworkOperations();
exitNetwork();
ASSERT_TRUE(getTopoCoord().getMemberState().recovering());
assertMemberState(MemberState::RS_RECOVERING, "0");
}
TEST_F(ReplCoordHBV1Test, IgnoreTheContentsOfMetadataWhenItsReplicaSetIdDoesNotMatchOurs) {
// Tests that a secondary node will not update its committed optime from the heartbeat metadata
// if the replica set ID is inconsistent with the existing configuration.
HostAndPort host2("node2:12345");
assertStartSuccess(BSON("_id"
<< "mySet"
<< "version"
<< 1
<< "members"
<< BSON_ARRAY(BSON("_id" << 1 << "host"
<< "node1:12345")
<< BSON("_id" << 2 << "host" << host2.toString()))
<< "settings"
<< BSON("replicaSetId" << OID::gen())
<< "protocolVersion"
<< 1),
HostAndPort("node1", 12345));
ASSERT(getReplCoord()->setFollowerMode(MemberState::RS_SECONDARY));
auto rsConfig = getReplCoord()->getConfig();
// Prepare heartbeat response.
OID unexpectedId = OID::gen();
OpTime opTime{Timestamp{10, 10}, 10};
RemoteCommandResponse heartbeatResponse(ErrorCodes::InternalError, "not initialized");
{
ReplSetHeartbeatResponse hbResp;
hbResp.setSetName(rsConfig.getReplSetName());
hbResp.setState(MemberState::RS_PRIMARY);
hbResp.setConfigVersion(rsConfig.getConfigVersion());
BSONObjBuilder responseBuilder;
responseBuilder << "ok" << 1;
hbResp.addToBSON(&responseBuilder, true);
rpc::ReplSetMetadata metadata(
opTime.getTerm(), opTime, opTime, rsConfig.getConfigVersion(), unexpectedId, 1, -1);
BSONObjBuilder metadataBuilder;
metadata.writeToMetadata(&metadataBuilder);
heartbeatResponse = makeResponseStatus(responseBuilder.obj(), metadataBuilder.obj());
}
// process heartbeat
enterNetwork();
auto net = getNet();
while (net->hasReadyRequests()) {
const NetworkInterfaceMock::NetworkOperationIterator noi = net->getNextReadyRequest();
const RemoteCommandRequest& request = noi->getRequest();
if (request.target == host2 &&
request.cmdObj.firstElement().fieldNameStringData() == "replSetHeartbeat") {
log() << request.target.toString() << " processing " << request.cmdObj;
net->scheduleResponse(noi, net->now(), heartbeatResponse);
} else {
log() << "blackholing request to " << request.target.toString() << ": "
<< request.cmdObj;
net->blackHole(noi);
}
net->runReadyNetworkOperations();
}
exitNetwork();
ASSERT_NOT_EQUALS(opTime, getReplCoord()->getLastCommittedOpTime());
ASSERT_NOT_EQUALS(opTime.getTerm(), getTopoCoord().getTerm());
BSONObjBuilder statusBuilder;
ASSERT_OK(getReplCoord()->processReplSetGetStatus(
&statusBuilder, ReplicationCoordinator::ReplSetGetStatusResponseStyle::kBasic));
auto statusObj = statusBuilder.obj();
unittest::log() << "replica set status = " << statusObj;
ASSERT_EQ(mongo::Array, statusObj["members"].type());
auto members = statusObj["members"].Array();
ASSERT_EQ(2U, members.size());
ASSERT_TRUE(members[1].isABSONObj());
auto member = members[1].Obj();
ASSERT_EQ(host2, HostAndPort(member["name"].String()));
ASSERT_EQ(MemberState(MemberState::RS_DOWN).toString(),
MemberState(member["state"].numberInt()).toString());
ASSERT_EQ(member["lastHeartbeatMessage"].String(),
std::string(str::stream() << "replica set IDs do not match, ours: "
<< rsConfig.getReplicaSetId()
<< "; remote node's: "
<< unexpectedId));
}
} // namespace
} // namespace repl
} // namespace mongo
|