-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
RaftLogShipper.java
475 lines (410 loc) · 16.3 KB
/
RaftLogShipper.java
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
/*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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/>.
*/
package org.neo4j.coreedge.raft.replication.shipping;
import java.io.IOException;
import java.time.Clock;
import org.neo4j.coreedge.catchup.storecopy.LocalDatabase;
import org.neo4j.coreedge.network.Message;
import org.neo4j.coreedge.raft.DelayedRenewableTimeoutService;
import org.neo4j.coreedge.raft.LeaderContext;
import org.neo4j.coreedge.raft.RaftMessages;
import org.neo4j.coreedge.raft.RenewableTimeoutService;
import org.neo4j.coreedge.raft.log.RaftLogEntry;
import org.neo4j.coreedge.raft.log.ReadableRaftLog;
import org.neo4j.coreedge.raft.log.segmented.InFlightMap;
import org.neo4j.coreedge.raft.net.Outbound;
import org.neo4j.coreedge.raft.state.InFlightLogEntrySupplier;
import org.neo4j.logging.Log;
import org.neo4j.logging.LogProvider;
import static java.lang.Long.max;
import static java.lang.Long.min;
import static java.lang.String.format;
import static org.neo4j.coreedge.raft.RenewableTimeoutService.RenewableTimeout;
import static org.neo4j.coreedge.raft.replication.shipping.RaftLogShipper.Mode.PIPELINE;
import static org.neo4j.coreedge.raft.replication.shipping.RaftLogShipper.Timeouts.RESEND;
/// Optimizations
// TODO: Have several outstanding batches in catchup mode, to bridge the latency gap.
// TODO: Bisect search for mismatch.
// TODO: Maximum bound on size of batch in bytes, not just entry count.
// Production ready
// TODO: Replace sender service with something more appropriate. No need for queue and multiplex capability, in fact
// is it bad to have?
// TODO Should we drop messages to unconnected channels instead? Use UDP? Because we are not allowed to go below a
// certain cluster size (safety)
// TODO then leader will keep trying to replicate to gone members, thus queuing things up is hurtful.
// TODO: Replace the timeout service with something better. More efficient for the constantly rescheduling use case
// and also useful for deterministic unit tests.
// Core functionality
// TODO: Consider making even CommitUpdate a raft-message of its own.
/**
* This class handles the shipping of raft logs from this node when it is the leader to the followers.
* Each instance handles a single follower and acts on events and associated state updates originating
* within the main raft state machine.
* <p>
* It is crucial that all actions happen within the context of the leaders state at some point in time.
*
* @param <MEMBER> The member type.
*/
public class RaftLogShipper<MEMBER>
{
enum Mode
{
/**
* In the mismatch mode we are unsure about the follower state, thus
* we tread with caution, going backwards trying to find the point where
* our logs match.
*/
MISMATCH,
/**
* In the catchup mode we are trying to catch up the follower as quickly
* as possible. The follower receives batches of entries in series until
* it is fully caught up.
*/
CATCHUP,
/**
* In the pipeline mode the follower is treated as caught up and we
* optimistically ship any latest entries without waiting for responses,
* expecting successful responses.
*/
PIPELINE
}
private final Outbound<MEMBER, RaftMessages.RaftMessage<MEMBER>> outbound;
private final LogProvider logProvider;
private final Log log;
private final ReadableRaftLog raftLog;
private final Clock clock;
private final MEMBER follower;
private final MEMBER leader;
private DelayedRenewableTimeoutService timeoutService;
public enum Timeouts implements RenewableTimeoutService.TimeoutName
{
RESEND
}
private final long retryTimeMillis;
private final int catchupBatchSize;
private final int maxAllowedShippingLag;
private RenewableTimeout timeout;
private long timeoutAbsoluteMillis;
private long lastSentIndex;
private long matchIndex = -1;
InFlightMap<Long, RaftLogEntry> inFlightMap;
private LeaderContext lastLeaderContext;
private Mode mode = Mode.MISMATCH;
RaftLogShipper( Outbound<MEMBER, RaftMessages.RaftMessage<MEMBER>> outbound, LogProvider logProvider,
ReadableRaftLog raftLog, Clock clock,
MEMBER leader, MEMBER follower, long leaderTerm, long leaderCommit, long retryTimeMillis,
int catchupBatchSize, int maxAllowedShippingLag, InFlightMap<Long, RaftLogEntry> inFlightMap )
{
this.outbound = outbound;
this.catchupBatchSize = catchupBatchSize;
this.maxAllowedShippingLag = maxAllowedShippingLag;
this.logProvider = logProvider;
this.log = logProvider.getLog( getClass() );
this.raftLog = raftLog;
this.clock = clock;
this.follower = follower;
this.leader = leader;
this.retryTimeMillis = retryTimeMillis;
this.lastLeaderContext = new LeaderContext( leaderTerm, leaderCommit );
this.inFlightMap = inFlightMap;
}
public Object identity()
{
return follower;
}
public synchronized void start()
{
log.info( "Starting log shipper: %s", statusAsString() );
timeoutService = new DelayedRenewableTimeoutService( clock, logProvider );
timeoutService.init();
timeoutService.start();
sendSingle( raftLog.appendIndex(), lastLeaderContext );
}
public synchronized void stop()
{
log.info( "Stopping log shipper %s", statusAsString() );
try
{
timeoutService.stop();
timeoutService.shutdown();
}
catch ( Throwable e )
{
log.error( "Failed to start log shipper " + statusAsString(), e );
}
abortTimeout();
}
public synchronized void onMismatch( long lastRemoteAppendIndex, LeaderContext leaderContext )
{
switch ( mode )
{
case MISMATCH:
long logIndex = max( min( lastSentIndex - 1, lastRemoteAppendIndex ), 0 );
sendSingle( logIndex, leaderContext );
break;
case PIPELINE:
case CATCHUP:
log.info( "%s: mismatch in mode %s from follower %s, moving to MISMATCH mode",
statusAsString(), mode, follower );
mode = Mode.MISMATCH;
sendSingle( lastSentIndex, leaderContext );
break;
}
lastLeaderContext = leaderContext;
}
public synchronized void onMatch( long newMatchIndex, LeaderContext leaderContext )
{
boolean progress = newMatchIndex > matchIndex;
matchIndex = max( newMatchIndex, matchIndex );
switch ( mode )
{
case MISMATCH:
if ( sendNextBatchAfterMatch( leaderContext ) )
{
log.info( "%s: caught up after mismatch, moving to PIPELINE mode", statusAsString() );
mode = PIPELINE;
}
else
{
log.info( "%s: starting catch up after mismatch, moving to CATCHUP mode", statusAsString() );
mode = Mode.CATCHUP;
}
break;
case CATCHUP:
if ( matchIndex >= lastSentIndex )
{
if ( sendNextBatchAfterMatch( leaderContext ) )
{
log.info( "%s: caught up, moving to PIPELINE mode", statusAsString() );
mode = PIPELINE;
}
}
break;
case PIPELINE:
if ( matchIndex == lastSentIndex )
{
abortTimeout();
}
else if ( progress )
{
scheduleTimeout( retryTimeMillis );
}
break;
}
lastLeaderContext = leaderContext;
}
public synchronized void onNewEntries( long prevLogIndex, long prevLogTerm, RaftLogEntry[] newLogEntries,
LeaderContext leaderContext )
{
switch ( mode )
{
case PIPELINE:
while ( lastSentIndex <= prevLogIndex )
{
if ( prevLogIndex - matchIndex <= maxAllowedShippingLag )
{
sendNewEntries( prevLogIndex, prevLogTerm, newLogEntries, leaderContext ); // all sending
// functions update lastSentIndex
}
else
{
/* The timer is still set at this point. Either we will send the next batch
* as soon as the follower has caught up with the last pipelined entry,
* or when we timeout and resend. */
log.info( "%s: follower has fallen behind (target prevLogIndex was %d, maxAllowedShippingLag " +
"is %d), moving to CATCHUP mode", statusAsString(), prevLogIndex,
maxAllowedShippingLag );
mode = Mode.CATCHUP;
break;
}
}
break;
}
lastLeaderContext = leaderContext;
}
public synchronized void onCommitUpdate( LeaderContext leaderContext )
{
switch ( mode )
{
case PIPELINE:
sendCommitUpdate( leaderContext );
break;
}
lastLeaderContext = leaderContext;
}
private synchronized void onScheduledTimeoutExpiry()
{
if ( timedOut() )
{
onTimeout();
return;
}
if ( timeoutAbsoluteMillis <= 0 )
{
return;
}
long timeLeft = timeoutAbsoluteMillis - clock.millis();
if ( timeLeft > 0 )
{
scheduleTimeout( timeLeft );
}
else
{
onTimeout();
}
}
private void onTimeout()
{
if ( mode == PIPELINE )
{
/* The follower seems unresponsive and we do not want to spam it with new entries */
log.info( "%s: timed out, moving to CATCHUP mode", statusAsString() );
mode = Mode.CATCHUP;
}
if ( lastLeaderContext != null )
{
sendSingle( lastSentIndex, lastLeaderContext );
}
}
private boolean timedOut()
{
return timeoutAbsoluteMillis != 0 && (clock.millis() - timeoutAbsoluteMillis) >= 0;
}
private void scheduleTimeout( long deltaMillis )
{
// TODO: This cancel/create dance is a bit inefficient... consider something better.
timeoutAbsoluteMillis = clock.millis() + deltaMillis;
if ( timeout != null )
{
timeout.cancel();
}
timeout = timeoutService.create( RESEND, deltaMillis, 0, timeout -> onScheduledTimeoutExpiry() );
}
private void abortTimeout()
{
if ( timeout != null )
{
timeout.cancel();
}
timeoutAbsoluteMillis = 0;
}
/**
* Returns true if this sent the last batch.
*/
private boolean sendNextBatchAfterMatch( LeaderContext leaderContext )
{
long lastIndex = raftLog.appendIndex();
if ( lastIndex > matchIndex )
{
long endIndex = min( lastIndex, matchIndex + catchupBatchSize );
scheduleTimeout( retryTimeMillis );
sendRange( matchIndex + 1, endIndex, leaderContext );
return endIndex == lastIndex;
}
else
{
return true;
}
}
private void sendCommitUpdate( LeaderContext leaderContext )
{
/*
* This is a commit update. That means that we just received enough success responses to an append
* request to allow us to send a commit. By Raft invariants, this means that the term for the committed
* entry is the current term.
*/
RaftMessages.Heartbeat<MEMBER> appendRequest =
new RaftMessages.Heartbeat<>( leader, leaderContext.term, leaderContext.commitIndex,
leaderContext.term );
outbound.send( follower, appendRequest );
}
private void sendSingle( long logIndex, LeaderContext leaderContext )
{
logIndex = max( raftLog.prevIndex() + 1, logIndex );
scheduleTimeout( retryTimeMillis );
sendRange( logIndex, logIndex, leaderContext );
}
private void sendNewEntries( long prevLogIndex, long prevLogTerm, RaftLogEntry[] newEntries,
LeaderContext leaderContext )
{
scheduleTimeout( retryTimeMillis );
lastSentIndex = prevLogIndex + 1;
RaftMessages.AppendEntries.Request<MEMBER> appendRequest = new RaftMessages.AppendEntries.Request<>(
leader, leaderContext.term, prevLogIndex, prevLogTerm, newEntries, leaderContext.commitIndex
);
outbound.send( follower, appendRequest );
}
private void sendRange( long startIndex, long endIndex, LeaderContext leaderContext )
{
if ( startIndex > endIndex )
{
return;
}
lastSentIndex = endIndex;
try
{
int batchSize = (int) (endIndex - startIndex + 1);
RaftLogEntry[] entries = new RaftLogEntry[batchSize];
long prevLogIndex = startIndex - 1;
long prevLogTerm = raftLog.readEntryTerm( prevLogIndex );
if ( prevLogTerm > leaderContext.term )
{
log.warn( "%s aborting send. Not leader anymore? %s, prevLogTerm=%d",
statusAsString(), leaderContext, prevLogTerm );
return;
}
if ( (prevLogIndex == -1 && prevLogTerm != -1) || (prevLogTerm == -1 && prevLogIndex != -1) )
{
log.warn( "%s aborting append entry request since someone has pruned away the entries we needed." +
"Sending a LogCompactionInfo instead. Leader context=%s, prevLogTerm=%d",
statusAsString(), leaderContext, prevLogTerm );
outbound.send( follower, new RaftMessages.LogCompactionInfo<>( leader, leaderContext.term,
prevLogIndex ) );
return;
}
RaftMessages.AppendEntries.Request<MEMBER> appendRequest =
new RaftMessages.AppendEntries.Request<>( leader, leaderContext.term, prevLogIndex, prevLogTerm,
entries, leaderContext.commitIndex );
try ( InFlightLogEntrySupplier logEntrySupplier = new InFlightLogEntrySupplier( raftLog, inFlightMap ) )
{
for ( int offset = 0; offset < batchSize; offset++ )
{
entries[offset] = logEntrySupplier.get( startIndex + offset );
if ( entries[offset].term() > leaderContext.term )
{
log.warn( "%s aborting send. Not leader anymore? %s, entryTerm=%d",
statusAsString(), leaderContext, entries[offset].term() );
return;
}
}
}
outbound.send( follower, appendRequest );
}
catch ( IOException e )
{
log.warn( statusAsString() + " exception during batch send", e );
}
}
private String statusAsString()
{
return format( "%s[matchIndex: %d, lastSentIndex: %d, localAppendIndex: %d, mode: %s]", follower, matchIndex,
lastSentIndex, raftLog.appendIndex(), mode );
}
}