-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
ElectionContextImpl.java
411 lines (356 loc) · 13.4 KB
/
ElectionContextImpl.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
/*
* Copyright (c) 2002-2018 "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.cluster.protocol.atomicbroadcast.multipaxos.context;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.DefaultWinnerStrategy;
import org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.Vote;
import org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.WinnerStrategy;
import org.neo4j.cluster.protocol.cluster.ClusterContext;
import org.neo4j.cluster.protocol.cluster.ClusterMessage;
import org.neo4j.cluster.protocol.election.ElectionContext;
import org.neo4j.cluster.protocol.election.ElectionCredentials;
import org.neo4j.cluster.protocol.election.ElectionCredentialsProvider;
import org.neo4j.cluster.protocol.election.ElectionRole;
import org.neo4j.cluster.protocol.election.NotElectableElectionCredentials;
import org.neo4j.cluster.protocol.heartbeat.HeartbeatContext;
import org.neo4j.cluster.protocol.heartbeat.HeartbeatListener;
import org.neo4j.cluster.timeout.Timeouts;
import org.neo4j.logging.LogProvider;
import static org.neo4j.cluster.util.Quorums.isQuorum;
import static org.neo4j.helpers.collection.Iterables.asList;
import static org.neo4j.helpers.collection.Iterables.filter;
import static org.neo4j.helpers.collection.Iterables.map;
public class ElectionContextImpl
extends AbstractContextImpl
implements ElectionContext, HeartbeatListener
{
private final ClusterContext clusterContext;
private final HeartbeatContext heartbeatContext;
private final List<ElectionRole> roles;
private final Map<String, Election> elections;
private final ElectionCredentialsProvider electionCredentialsProvider;
ElectionContextImpl( org.neo4j.cluster.InstanceId me, CommonContextState commonState,
LogProvider logging,
Timeouts timeouts, Iterable<ElectionRole> roles, ClusterContext clusterContext,
HeartbeatContext heartbeatContext, ElectionCredentialsProvider electionCredentialsProvider )
{
super( me, commonState, logging, timeouts );
this.electionCredentialsProvider = electionCredentialsProvider;
this.roles = new ArrayList<>( asList(roles));
this.elections = new HashMap<>();
this.clusterContext = clusterContext;
this.heartbeatContext = heartbeatContext;
heartbeatContext.addHeartbeatListener( this );
}
ElectionContextImpl( InstanceId me, CommonContextState commonState, LogProvider logging, Timeouts timeouts,
ClusterContext clusterContext, HeartbeatContext heartbeatContext, List<ElectionRole> roles,
Map<String, Election> elections, ElectionCredentialsProvider electionCredentialsProvider )
{
super( me, commonState, logging, timeouts );
this.clusterContext = clusterContext;
this.heartbeatContext = heartbeatContext;
this.roles = roles;
this.elections = elections;
this.electionCredentialsProvider = electionCredentialsProvider;
heartbeatContext.addHeartbeatListener( this );
}
@Override
public void created()
{
for ( ElectionRole role : roles )
{
// Elect myself for all roles
clusterContext.elected( role.getName(), clusterContext.getMyId(), clusterContext.getMyId(), 1 );
}
}
@Override
public List<ElectionRole> getPossibleRoles()
{
return roles;
}
/*
* Removes all roles from the provided node. This is expected to be the first call when receiving a demote
* message for a node, since it is the way to ensure that election will happen for each role that node had
*/
@Override
public void nodeFailed( org.neo4j.cluster.InstanceId node )
{
Iterable<String> rolesToDemote = getRoles( node );
for ( String role : rolesToDemote )
{
clusterContext.getConfiguration().removeElected( role );
}
}
@Override
public Iterable<String> getRoles( org.neo4j.cluster.InstanceId server )
{
return clusterContext.getConfiguration().getRolesOf( server );
}
public ClusterContext getClusterContext()
{
return clusterContext;
}
public HeartbeatContext getHeartbeatContext()
{
return heartbeatContext;
}
@Override
public boolean isElectionProcessInProgress( String role )
{
return elections.containsKey( role );
}
@Override
public void startElectionProcess( String role )
{
clusterContext.getLog( getClass() ).info( "Doing elections for role " + role );
if ( !clusterContext.getMyId().equals( clusterContext.getLastElector() ) )
{
clusterContext.setLastElector( clusterContext.getMyId() );
}
elections.put( role, new Election( new DefaultWinnerStrategy( clusterContext ) ) );
}
@Override
public boolean voted( String role, org.neo4j.cluster.InstanceId suggestedNode,
ElectionCredentials suggestionCredentials, long electionVersion )
{
if ( !isElectionProcessInProgress( role ) ||
(electionVersion != -1 && electionVersion < clusterContext.getLastElectorVersion() ) )
{
return false;
}
Map<org.neo4j.cluster.InstanceId, Vote> votes = elections.get( role ).getVotes();
votes.put( suggestedNode, new Vote( suggestedNode, suggestionCredentials ) );
return true;
}
@Override
public org.neo4j.cluster.InstanceId getElectionWinner( String role )
{
Election election = elections.get( role );
if ( election == null || election.getVotes().size() != getNeededVoteCount() )
{
return null;
}
elections.remove( role );
return election.pickWinner();
}
@Override
public ElectionCredentials getCredentialsForRole( String role )
{
return electionCredentialsProvider.getCredentials( role );
}
@Override
public int getVoteCount( String role )
{
Election election = elections.get( role );
if ( election != null )
{
Map<org.neo4j.cluster.InstanceId, Vote> voteList = election.getVotes();
if ( voteList == null )
{
return 0;
}
return voteList.size();
}
else
{
return 0;
}
}
@Override
public int getNeededVoteCount()
{
return clusterContext.getConfiguration().getMembers().size() - heartbeatContext.getFailed().size();
// TODO increment election epoch
}
@Override
public void forgetElection( String role )
{
elections.remove( role );
clusterContext.setLastElectorVersion( clusterContext.getLastElectorVersion() + 1 );
}
@Override
public Iterable<String> getRolesRequiringElection()
{
return filter( role -> clusterContext.getConfiguration().getElected( role ) == null,
map( ElectionRole::getName, roles ) );
}
@Override
public boolean electionOk()
{
int total = clusterContext.getConfiguration().getMembers().size();
int available = total - heartbeatContext.getFailed().size();
return isQuorum( available, total );
}
@Override
public boolean isInCluster()
{
return clusterContext.isInCluster();
}
@Override
public Iterable<org.neo4j.cluster.InstanceId> getAlive()
{
return heartbeatContext.getAlive();
}
@Override
public org.neo4j.cluster.InstanceId getMyId()
{
return clusterContext.getMyId();
}
@Override
public boolean isElector()
{
// Only the first *alive* server should try elections. Everyone else waits
// This also takes into account the instances reported by the cluster join response as failed, to
// cover for the case where we just joined and our suspicions are not reliable yet.
List<org.neo4j.cluster.InstanceId> aliveInstances = asList( getAlive() );
aliveInstances.removeAll( getFailed() );
Collections.sort( aliveInstances );
// Either we are the first one or the only one
return aliveInstances.indexOf( getMyId() ) == 0 || aliveInstances.isEmpty();
}
@Override
public boolean isFailed( org.neo4j.cluster.InstanceId key )
{
return heartbeatContext.getFailed().contains( key );
}
@Override
public org.neo4j.cluster.InstanceId getElected( String roleName )
{
return clusterContext.getConfiguration().getElected( roleName );
}
@Override
public boolean hasCurrentlyElectedVoted( String role, org.neo4j.cluster.InstanceId currentElected )
{
return elections.containsKey( role ) && elections.get(role).getVotes().containsKey( currentElected );
}
@Override
public Set<InstanceId> getFailed()
{
return heartbeatContext.getFailed();
}
public ElectionContextImpl snapshot( CommonContextState commonStateSnapshot, LogProvider logging, Timeouts timeouts,
ClusterContextImpl snapshotClusterContext,
HeartbeatContextImpl snapshotHeartbeatContext,
ElectionCredentialsProvider credentialsProvider )
{
Map<String, Election> electionsSnapshot = new HashMap<>();
for ( Map.Entry<String, Election> election : elections.entrySet() )
{
electionsSnapshot.put( election.getKey(), election.getValue().snapshot() );
}
return new ElectionContextImpl( me, commonStateSnapshot, logging, timeouts, snapshotClusterContext,
snapshotHeartbeatContext, new ArrayList<>(roles), electionsSnapshot, credentialsProvider );
}
private static class Election
{
private final WinnerStrategy winnerStrategy;
private final Map<org.neo4j.cluster.InstanceId, Vote> votes;
private Election( WinnerStrategy winnerStrategy )
{
this.winnerStrategy = winnerStrategy;
this.votes = new HashMap<>();
}
private Election( WinnerStrategy winnerStrategy, HashMap<InstanceId, Vote> votes )
{
this.votes = votes;
this.winnerStrategy = winnerStrategy;
}
public Map<InstanceId, Vote> getVotes()
{
return votes;
}
public InstanceId pickWinner()
{
return winnerStrategy.pickWinner( votes.values() );
}
public Election snapshot()
{
return new Election( winnerStrategy, new HashMap<>(votes));
}
}
@Override
public ClusterMessage.VersionedConfigurationStateChange newConfigurationStateChange()
{
ClusterMessage.VersionedConfigurationStateChange result = new ClusterMessage
.VersionedConfigurationStateChange();
result.setElector( clusterContext.getMyId() );
result.setVersion( clusterContext.getLastElectorVersion() );
return result;
}
@Override
public VoteRequest voteRequestForRole( ElectionRole role )
{
return new VoteRequest( role.getName(), clusterContext.getLastElectorVersion() );
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
ElectionContextImpl that = (ElectionContextImpl) o;
if ( elections != null ? !elections.equals( that.elections ) : that.elections != null )
{
return false;
}
if ( roles != null ? !roles.equals( that.roles ) : that.roles != null )
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = roles != null ? roles.hashCode() : 0;
result = 31 * result + (elections != null ? elections.hashCode() : 0);
return result;
}
@Override
public void failed( org.neo4j.cluster.InstanceId server )
{
for ( Map.Entry<String, Election> ongoingElection : elections.entrySet() )
{
ongoingElection.getValue().getVotes().remove( server );
}
}
@Override
public void alive( org.neo4j.cluster.InstanceId server )
{
// Not needed
}
public static List<Vote> removeBlankVotes( Collection<Vote> voteList )
{
return asList( filter( item ->
!(item.getCredentials() instanceof NotElectableElectionCredentials), voteList ) );
}
}