-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
CatchupPollingProcess.java
368 lines (331 loc) · 12.6 KB
/
CatchupPollingProcess.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
/*
* Copyright (c) 2002-2017 "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.causalclustering.catchup.tx;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.Supplier;
import org.neo4j.causalclustering.catchup.CatchUpClient;
import org.neo4j.causalclustering.catchup.CatchUpClientException;
import org.neo4j.causalclustering.catchup.CatchUpResponseAdaptor;
import org.neo4j.causalclustering.catchup.storecopy.LocalDatabase;
import org.neo4j.causalclustering.catchup.storecopy.StoreCopyFailedException;
import org.neo4j.causalclustering.catchup.storecopy.StoreCopyProcess;
import org.neo4j.causalclustering.catchup.storecopy.StreamingTransactionsFailedException;
import org.neo4j.causalclustering.core.consensus.schedule.RenewableTimeoutService;
import org.neo4j.causalclustering.core.consensus.schedule.RenewableTimeoutService.RenewableTimeout;
import org.neo4j.causalclustering.core.consensus.schedule.RenewableTimeoutService.TimeoutName;
import org.neo4j.causalclustering.core.state.snapshot.TopologyLookupException;
import org.neo4j.causalclustering.discovery.TopologyService;
import org.neo4j.causalclustering.identity.MemberId;
import org.neo4j.causalclustering.identity.StoreId;
import org.neo4j.causalclustering.readreplica.UpstreamDatabaseSelectionException;
import org.neo4j.causalclustering.readreplica.UpstreamDatabaseStrategySelector;
import org.neo4j.helpers.AdvertisedSocketAddress;
import org.neo4j.kernel.impl.transaction.CommittedTransactionRepresentation;
import org.neo4j.kernel.internal.DatabaseHealth;
import org.neo4j.kernel.lifecycle.Lifecycle;
import org.neo4j.kernel.lifecycle.LifecycleAdapter;
import org.neo4j.kernel.monitoring.Monitors;
import org.neo4j.logging.Log;
import org.neo4j.logging.LogProvider;
import static java.lang.String.format;
import static org.neo4j.causalclustering.catchup.tx.CatchupPollingProcess.State.CANCELLED;
import static org.neo4j.causalclustering.catchup.tx.CatchupPollingProcess.State.PANIC;
import static org.neo4j.causalclustering.catchup.tx.CatchupPollingProcess.State.STORE_COPYING;
import static org.neo4j.causalclustering.catchup.tx.CatchupPollingProcess.State.TX_PULLING;
import static org.neo4j.causalclustering.catchup.tx.CatchupPollingProcess.Timeouts.TX_PULLER_TIMEOUT;
/**
* This class is responsible for pulling transactions from a core server and queuing
* them to be applied with the {@link BatchingTxApplier}. Pull requests are issued on
* a fixed interval.
*
* If the necessary transactions are not remotely available then a fresh copy of the
* entire store will be pulled down.
*/
public class CatchupPollingProcess extends LifecycleAdapter
{
enum Timeouts implements TimeoutName
{
TX_PULLER_TIMEOUT
}
enum State
{
TX_PULLING,
STORE_COPYING,
PANIC,
CANCELLED
}
private final LocalDatabase localDatabase;
private final Log log;
private final Lifecycle startStopOnStoreCopy;
private final StoreCopyProcess storeCopyProcess;
private final Supplier<DatabaseHealth> databaseHealthSupplier;
private final CatchUpClient catchUpClient;
private final UpstreamDatabaseStrategySelector selectionStrategyPipeline;
private final RenewableTimeoutService timeoutService;
private final long txPullIntervalMillis;
private final BatchingTxApplier applier;
private final PullRequestMonitor pullRequestMonitor;
private final TopologyService topologyService;
private RenewableTimeout timeout;
private volatile State state = TX_PULLING;
private DatabaseHealth dbHealth;
private CompletableFuture<Boolean> upToDateFuture; // we are up-to-date when we are successfully pulling
private volatile long latestTxIdOfUpStream;
public CatchupPollingProcess( LogProvider logProvider, LocalDatabase localDatabase,
Lifecycle startStopOnStoreCopy, CatchUpClient catchUpClient,
UpstreamDatabaseStrategySelector selectionStrategy, RenewableTimeoutService timeoutService,
long txPullIntervalMillis, BatchingTxApplier applier, Monitors monitors,
StoreCopyProcess storeCopyProcess, Supplier<DatabaseHealth> databaseHealthSupplier, TopologyService topologyService )
{
this.localDatabase = localDatabase;
this.log = logProvider.getLog( getClass() );
this.startStopOnStoreCopy = startStopOnStoreCopy;
this.catchUpClient = catchUpClient;
this.selectionStrategyPipeline = selectionStrategy;
this.timeoutService = timeoutService;
this.txPullIntervalMillis = txPullIntervalMillis;
this.applier = applier;
this.pullRequestMonitor = monitors.newMonitor( PullRequestMonitor.class );
this.storeCopyProcess = storeCopyProcess;
this.databaseHealthSupplier = databaseHealthSupplier;
this.topologyService = topologyService;
}
@Override
public synchronized void start() throws Throwable
{
state = TX_PULLING;
timeout = timeoutService.create( TX_PULLER_TIMEOUT, txPullIntervalMillis, 0, timeout -> onTimeout() );
dbHealth = databaseHealthSupplier.get();
upToDateFuture = new CompletableFuture<>();
}
public Future<Boolean> upToDateFuture() throws InterruptedException
{
return upToDateFuture;
}
@Override
public void stop() throws Throwable
{
state = CANCELLED;
timeout.cancel();
}
public State state()
{
return state;
}
/**
* Time to catchup!
*/
private void onTimeout()
{
try
{
switch ( state )
{
case TX_PULLING:
pullTransactions();
break;
case STORE_COPYING:
copyStore();
break;
default:
throw new IllegalStateException( "Tried to execute catchup but was in state " + state );
}
}
catch ( Throwable e )
{
panic( e );
}
if ( state != PANIC && state != CANCELLED )
{
timeout.renew();
}
}
private synchronized void panic( Throwable e )
{
log.error( "Unexpected issue in catchup process. No more catchup requests will be scheduled.", e );
dbHealth.panic( e );
upToDateFuture.completeExceptionally( e );
state = PANIC;
}
private void pullTransactions()
{
MemberId upstream;
try
{
upstream = selectionStrategyPipeline.bestUpstreamDatabase();
}
catch ( UpstreamDatabaseSelectionException e )
{
log.warn( "Could not find upstream database from which to pull.", e );
return;
}
StoreId localStoreId = localDatabase.storeId();
boolean moreToPull = true;
int batchCount = 1;
while ( moreToPull )
{
moreToPull = pullAndApplyBatchOfTransactions( upstream, localStoreId, batchCount );
batchCount++;
}
}
private synchronized void handleTransaction( CommittedTransactionRepresentation tx )
{
if ( state == PANIC )
{
return;
}
try
{
applier.queue( tx );
}
catch ( Throwable e )
{
panic( e );
}
}
private synchronized void streamComplete()
{
if ( state == PANIC )
{
return;
}
try
{
applier.applyBatch();
}
catch ( Throwable e )
{
panic( e );
}
}
private boolean pullAndApplyBatchOfTransactions( MemberId upstream, StoreId localStoreId, int batchCount )
{
long lastQueuedTxId = applier.lastQueuedTxId();
pullRequestMonitor.txPullRequest( lastQueuedTxId );
TxPullRequest txPullRequest = new TxPullRequest( lastQueuedTxId, localStoreId );
log.debug( "Pull transactions from %s where tx id > %d [batch #%d]", upstream, lastQueuedTxId, batchCount );
AdvertisedSocketAddress fromAddress = topologyService.findCatchupAddress( upstream ).orElseThrow( () -> new TopologyLookupException( upstream ) );
TxStreamFinishedResponse response;
try
{
response = catchUpClient.makeBlockingRequest( fromAddress, txPullRequest, new CatchUpResponseAdaptor<TxStreamFinishedResponse>()
{
@Override
public void onTxPullResponse( CompletableFuture<TxStreamFinishedResponse> signal, TxPullResponse response )
{
handleTransaction( response.tx() );
}
@Override
public void onTxStreamFinishedResponse( CompletableFuture<TxStreamFinishedResponse> signal,
TxStreamFinishedResponse response )
{
streamComplete();
signal.complete( response );
}
} );
}
catch ( CatchUpClientException e )
{
log.warn( "Exception occurred while pulling transactions. Will retry shortly.", e );
streamComplete();
return false;
}
latestTxIdOfUpStream = response.latestTxId();
switch ( response.status() )
{
case SUCCESS_END_OF_BATCH:
return true;
case SUCCESS_END_OF_STREAM:
log.debug( "Successfully pulled transactions from tx id %d", lastQueuedTxId );
upToDateFuture.complete( true );
return false;
case E_TRANSACTION_PRUNED:
log.info( "Tx pull unable to get transactions starting from %d since transactions " +
"have been pruned. Attempting a store copy.", lastQueuedTxId ) ;
state = STORE_COPYING;
return false;
default:
log.info( "Tx pull request unable to get transactions > %d " + lastQueuedTxId );
return false;
}
}
private void copyStore()
{
MemberId upstream;
try
{
upstream = selectionStrategyPipeline.bestUpstreamDatabase();
}
catch ( UpstreamDatabaseSelectionException e )
{
log.warn( "Could not find upstream database from which to copy store", e );
return;
}
StoreId localStoreId = localDatabase.storeId();
downloadDatabase( upstream, localStoreId );
}
private void downloadDatabase( MemberId upstream, StoreId localStoreId )
{
try
{
localDatabase.stopForStoreCopy();
startStopOnStoreCopy.stop();
}
catch ( Throwable throwable )
{
throw new RuntimeException( throwable );
}
AdvertisedSocketAddress fromAddress = topologyService.findCatchupAddress( upstream ).orElseThrow( () -> new TopologyLookupException( upstream ) );
try
{
storeCopyProcess.replaceWithStoreFrom( fromAddress, localStoreId );
}
catch ( IOException | StoreCopyFailedException | StreamingTransactionsFailedException e )
{
log.warn( format( "Error copying store from: %s. Will retry shortly.", upstream ) );
return;
}
try
{
localDatabase.start();
startStopOnStoreCopy.start();
}
catch ( Throwable throwable )
{
throw new RuntimeException( throwable );
}
latestTxIdOfUpStream = 0; // we will find out on the next pull request response
state = TX_PULLING;
applier.refreshFromNewStore();
}
public String describeState()
{
if ( state == TX_PULLING && applier.lastQueuedTxId() > 0 && latestTxIdOfUpStream > 0 )
{
return format( "%s (%d of %d)", TX_PULLING.name(), applier.lastQueuedTxId(), latestTxIdOfUpStream );
}
else
{
return state.name();
}
}
}