-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
HighAvailabilityModeSwitcher.java
586 lines (513 loc) · 20.8 KB
/
HighAvailabilityModeSwitcher.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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
/*
* 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.kernel.ha.cluster;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.neo4j.cluster.BindingListener;
import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.client.ClusterClient;
import org.neo4j.cluster.member.ClusterMemberAvailability;
import org.neo4j.cluster.protocol.election.Election;
import org.neo4j.function.Supplier;
import org.neo4j.helpers.CancellationRequest;
import org.neo4j.helpers.Functions;
import org.neo4j.helpers.Listeners;
import org.neo4j.kernel.ha.store.HighAvailabilityStoreFailureException;
import org.neo4j.kernel.ha.store.UnableToCopyStoreFromOldMasterException;
import org.neo4j.kernel.impl.logging.LogService;
import org.neo4j.kernel.impl.store.MismatchingStoreIdException;
import org.neo4j.kernel.impl.store.StoreId;
import org.neo4j.kernel.impl.transaction.state.DataSourceManager;
import org.neo4j.kernel.lifecycle.LifeSupport;
import org.neo4j.kernel.lifecycle.Lifecycle;
import org.neo4j.logging.Log;
import static org.neo4j.cluster.ClusterSettings.INSTANCE_ID;
import static org.neo4j.helpers.Functions.withDefaults;
import static org.neo4j.helpers.NamedThreadFactory.named;
import static org.neo4j.helpers.Uris.parameter;
/**
* Performs the internal switches in various services from pending to slave/master, by listening for
* {@link HighAvailabilityMemberChangeEvent}s. When finished it will invoke
* {@link ClusterMemberAvailability#memberIsAvailable(String, URI, StoreId)} to announce it's new status to the
* cluster.
*/
public class HighAvailabilityModeSwitcher
implements HighAvailabilityMemberListener, ModeSwitcherNotifier, BindingListener, Lifecycle
{
public static final String MASTER = "master";
public static final String SLAVE = "slave";
public static final String UNKNOWN = "UNKNOWN";
public static final String INADDR_ANY = "0.0.0.0";
private Iterable<ModeSwitcher> modeSwitchListeners = Listeners.newListeners();
private volatile URI masterHaURI;
private volatile URI slaveHaURI;
private CancellationHandle cancellationHandle; // guarded by synchronized in startModeSwitching()
public static InstanceId getServerId( URI haUri )
{
// Get serverId parameter, default to -1 if it is missing, and parse to integer
return INSTANCE_ID.apply( withDefaults(
Functions.<URI, String>constant( "-1" ), parameter( "serverId" ) ).apply( haUri ) );
}
private URI availableMasterId;
private SwitchToSlave switchToSlave;
private SwitchToMaster switchToMaster;
private final Election election;
private final ClusterMemberAvailability clusterMemberAvailability;
private ClusterClient clusterClient;
private Supplier<StoreId> storeIdSupplier;
private final InstanceId instanceId;
private final Log msgLog;
private final Log userLog;
private LifeSupport haCommunicationLife;
private ScheduledExecutorService modeSwitcherExecutor;
private volatile URI me;
private volatile Future<?> modeSwitcherFuture;
private volatile HighAvailabilityMemberState currentTargetState;
private final AtomicBoolean canAskForElections = new AtomicBoolean( true );
private final DataSourceManager neoStoreDataSourceSupplier;
public HighAvailabilityModeSwitcher( SwitchToSlave switchToSlave,
SwitchToMaster switchToMaster,
Election election,
ClusterMemberAvailability clusterMemberAvailability,
ClusterClient clusterClient,
Supplier<StoreId> storeIdSupplier,
InstanceId instanceId, LogService logService,
DataSourceManager neoStoreDataSourceSupplier )
{
this.switchToSlave = switchToSlave;
this.switchToMaster = switchToMaster;
this.election = election;
this.clusterMemberAvailability = clusterMemberAvailability;
this.clusterClient = clusterClient;
this.storeIdSupplier = storeIdSupplier;
this.instanceId = instanceId;
this.msgLog = logService.getInternalLog( getClass() );
this.userLog = logService.getUserLog( getClass() );
this.neoStoreDataSourceSupplier = neoStoreDataSourceSupplier;
this.haCommunicationLife = new LifeSupport();
}
@Override
public void listeningAt( URI myUri )
{
me = myUri;
}
@Override
public synchronized void init() throws Throwable
{
modeSwitcherExecutor = createExecutor();
haCommunicationLife.init();
}
@Override
public synchronized void start() throws Throwable
{
haCommunicationLife.start();
}
@Override
public synchronized void stop() throws Throwable
{
haCommunicationLife.stop();
}
@Override
public synchronized void shutdown() throws Throwable
{
modeSwitcherExecutor.shutdown();
modeSwitcherExecutor.awaitTermination( 60, TimeUnit.SECONDS );
haCommunicationLife.shutdown();
switchToMaster.close();
switchToMaster = null;
switchToSlave = null;
}
@Override
public void masterIsElected( HighAvailabilityMemberChangeEvent event )
{
if ( event.getNewState() == event.getOldState() && event.getOldState() == HighAvailabilityMemberState.MASTER )
{
clusterMemberAvailability.memberIsAvailable( MASTER, masterHaURI, storeIdSupplier.get() );
}
else
{
stateChanged( event );
}
}
@Override
public void masterIsAvailable( HighAvailabilityMemberChangeEvent event )
{
if ( event.getNewState() == event.getOldState() && event.getOldState() == HighAvailabilityMemberState.SLAVE )
{
clusterMemberAvailability.memberIsAvailable( SLAVE, slaveHaURI, storeIdSupplier.get() );
}
else
{
stateChanged( event );
}
}
@Override
public void slaveIsAvailable( HighAvailabilityMemberChangeEvent event )
{
// ignored, we don't do any mode switching in slave available events
}
@Override
public void instanceStops( HighAvailabilityMemberChangeEvent event )
{
stateChanged( event );
}
@Override
public void instanceDetached( HighAvailabilityMemberChangeEvent event )
{
switchToDetached();
}
@Override
public void addModeSwitcher( ModeSwitcher modeSwitcher )
{
modeSwitchListeners = Listeners.addListener( modeSwitcher, modeSwitchListeners );
}
@Override
public void removeModeSwitcher( ModeSwitcher modeSwitcher )
{
modeSwitchListeners = Listeners.removeListener( modeSwitcher, modeSwitchListeners );
}
public void forceElections()
{
if ( canAskForElections.compareAndSet( true, false ) )
{
clusterMemberAvailability.memberIsUnavailable( HighAvailabilityModeSwitcher.SLAVE );
election.performRoleElections();
}
}
private void stateChanged( HighAvailabilityMemberChangeEvent event )
{
if ( event.getNewState() == event.getOldState() )
{
/*
* We get here if for example a new master becomes available while we are already switching. In that case
* we don't change state but we must update with the new availableMasterId, but only if it is not null.
*/
if ( event.getServerHaUri() != null )
{
availableMasterId = event.getServerHaUri();
}
return;
}
availableMasterId = event.getServerHaUri();
currentTargetState = event.getNewState();
switch ( event.getNewState() )
{
case TO_MASTER:
if ( event.getOldState().equals( HighAvailabilityMemberState.SLAVE ) )
{
clusterMemberAvailability.memberIsUnavailable( SLAVE );
}
switchToMaster();
break;
case TO_SLAVE:
switchToSlave();
break;
case PENDING:
switchToPending( event.getOldState() );
break;
default:
// do nothing
}
}
private void switchToMaster()
{
final CancellationHandle cancellationHandle = new CancellationHandle();
startModeSwitching( new Runnable()
{
@Override
public void run()
{
if ( currentTargetState != HighAvailabilityMemberState.TO_MASTER )
{
return;
}
// We just got scheduled. Maybe we are already obsolete - test
if ( cancellationHandle.cancellationRequested() )
{
msgLog.info( "Switch to master cancelled on start." );
return;
}
Listeners.notifyListeners( modeSwitchListeners, new Listeners.Notification<ModeSwitcher>()
{
@Override
public void notify( ModeSwitcher listener )
{
listener.switchToMaster();
}
} );
if ( cancellationHandle.cancellationRequested() )
{
msgLog.info( "Switch to master cancelled before ha communication started." );
return;
}
haCommunicationLife.shutdown();
haCommunicationLife = new LifeSupport();
try
{
masterHaURI = switchToMaster.switchToMaster( haCommunicationLife, me );
canAskForElections.set( true );
}
catch ( Throwable e )
{
msgLog.error( "Failed to switch to master", e );
// Since this master switch failed, elect someone else
election.demote( instanceId );
}
}
}, cancellationHandle );
}
private void switchToSlave()
{
// Do this with a scheduler, so that if it fails, it can retry later with an exponential backoff with max
// wait time.
/*
* This is purely defensive and should never trigger. There was a race where the switch to slave task would
* start after this instance was elected master and the task would constantly try to change as slave
* for itself, never cancelling. This now should not be possible, since we cancel the task and wait for it
* to complete, all in a single thread executor. However, this is a check worth doing because if this
* condition slips through via some other code path it can cause trouble.
*/
if ( getServerId( availableMasterId ).equals( instanceId ) )
{
msgLog.error( "I (" + me + ") tried to switch to slave for myself as master (" + availableMasterId + ")" );
return;
}
final AtomicLong wait = new AtomicLong();
final CancellationHandle cancellationHandle = new CancellationHandle();
startModeSwitching( new Runnable()
{
@Override
public void run()
{
if ( currentTargetState != HighAvailabilityMemberState.TO_SLAVE )
{
return; // Already switched - this can happen if a second master becomes available while waiting
}
if ( cancellationHandle.cancellationRequested() )
{
msgLog.info( "Switch to slave cancelled on start." );
return;
}
Listeners.notifyListeners( modeSwitchListeners, new Listeners.Notification<ModeSwitcher>()
{
@Override
public void notify( ModeSwitcher listener )
{
listener.switchToSlave();
}
} );
try
{
if ( cancellationHandle.cancellationRequested() )
{
msgLog.info( "Switch to slave cancelled before ha communication started." );
return;
}
haCommunicationLife.shutdown();
haCommunicationLife = new LifeSupport();
// it is important for availableMasterId to be re-read on every attempt so that
// slave switching would not result in an infinite loop with wrong/stale availableMasterId
URI resultingSlaveHaURI = switchToSlave.switchToSlave( haCommunicationLife, me, availableMasterId, cancellationHandle );
if ( resultingSlaveHaURI == null )
{
/*
* null slave uri means the task was cancelled. The task then must simply terminate and
* have no side effects.
*/
msgLog.info( "Switch to slave is effectively cancelled" );
}
else
{
slaveHaURI = resultingSlaveHaURI;
canAskForElections.set( true );
}
}
catch ( HighAvailabilityStoreFailureException e )
{
userLog.error( "UNABLE TO START UP AS SLAVE: %s", e.getMessage() );
msgLog.error( "Unable to start up as slave", e );
clusterMemberAvailability.memberIsUnavailable( SLAVE );
ClusterClient clusterClient = HighAvailabilityModeSwitcher.this.clusterClient;
try
{
// TODO I doubt this actually works
clusterClient.leave();
clusterClient.stop();
haCommunicationLife.shutdown();
}
catch ( Throwable t )
{
msgLog.error( "Unable to stop cluster client", t );
}
modeSwitcherExecutor.schedule( this, 5, TimeUnit.SECONDS );
}
catch ( MismatchingStoreIdException e )
{
// Try again immediately, the place that threw it have already treated the db
// as branched and so a new attempt will have this slave copy a new store from master.
run();
}
catch ( Throwable t )
{
msgLog.error( "Error while trying to switch to slave", t );
// Try again later
wait.set( (1 + wait.get() * 2) ); // Exponential backoff
wait.set( Math.min( wait.get(), 5 * 60 ) ); // Wait maximum 5 minutes
modeSwitcherFuture = modeSwitcherExecutor.schedule( this, wait.get(), TimeUnit.SECONDS );
msgLog.info( "Attempting to switch to slave in %ds", wait.get() );
}
}
}, cancellationHandle );
}
private void switchToPending( final HighAvailabilityMemberState oldState )
{
msgLog.info( "I am %s, moving to pending", instanceId );
startModeSwitching( new Runnable()
{
@Override
public void run()
{
if ( cancellationHandle.cancellationRequested() )
{
msgLog.info( "Switch to pending cancelled on start." );
return;
}
if ( oldState.equals( HighAvailabilityMemberState.SLAVE ) )
{
clusterMemberAvailability.memberIsUnavailable( SLAVE );
}
else if ( oldState.equals( HighAvailabilityMemberState.MASTER ) )
{
clusterMemberAvailability.memberIsUnavailable( MASTER );
}
Listeners.notifyListeners( modeSwitchListeners, new Listeners.Notification<ModeSwitcher>()
{
@Override
public void notify( ModeSwitcher listener )
{
listener.switchToPending();
}
} );
neoStoreDataSourceSupplier.getDataSource().beforeModeSwitch();
if ( cancellationHandle.cancellationRequested() )
{
msgLog.info( "Switch to pending cancelled before ha communication shutdown." );
return;
}
haCommunicationLife.shutdown();
haCommunicationLife = new LifeSupport();
}
}, new CancellationHandle() );
try
{
modeSwitcherFuture.get( 10, TimeUnit.SECONDS );
}
catch ( Exception e )
{
msgLog.warn( "Exception received while waiting for switching to pending", e );
}
}
private void switchToDetached()
{
msgLog.info( "I am %s, moving to detached", instanceId );
startModeSwitching( new Runnable()
{
@Override
public void run()
{
if ( cancellationHandle.cancellationRequested() )
{
msgLog.info( "Switch to pending cancelled on start." );
return;
}
Listeners.notifyListeners( modeSwitchListeners, new Listeners.Notification<ModeSwitcher>()
{
@Override
public void notify( ModeSwitcher listener )
{
listener.switchToSlave();
}
} );
neoStoreDataSourceSupplier.getDataSource().beforeModeSwitch();
if ( cancellationHandle.cancellationRequested() )
{
msgLog.info( "Switch to pending cancelled before ha communication shutdown." );
return;
}
haCommunicationLife.shutdown();
haCommunicationLife = new LifeSupport();
}
}, new CancellationHandle() );
try
{
modeSwitcherFuture.get( 10, TimeUnit.SECONDS );
}
catch ( Exception e )
{
msgLog.warn( "Exception received while waiting for switching to detached", e );
}
}
private synchronized void startModeSwitching( Runnable switcher, CancellationHandle cancellationHandle )
{
if ( modeSwitcherFuture != null )
{
// Cancel any delayed previous switching
this.cancellationHandle.cancel();
// Wait for it to actually stop what it was doing
try
{
modeSwitcherFuture.get();
}
catch ( UnableToCopyStoreFromOldMasterException e )
{
throw e;
}
catch ( Exception e )
{
msgLog.warn( "Got exception from cancelled task", e );
}
}
this.cancellationHandle = cancellationHandle;
modeSwitcherFuture = modeSwitcherExecutor.submit( switcher );
}
ScheduledExecutorService createExecutor()
{
return Executors.newSingleThreadScheduledExecutor( named( "HA Mode switcher" ) );
}
private static class CancellationHandle implements CancellationRequest
{
private volatile boolean cancelled = false;
@Override
public boolean cancellationRequested()
{
return cancelled;
}
public void cancel()
{
assert !cancelled : "Should not cancel on the same request twice";
cancelled = true;
}
}
}