-
Notifications
You must be signed in to change notification settings - Fork 93
/
HostSelectionWithFallback.java
519 lines (434 loc) · 21.3 KB
/
HostSelectionWithFallback.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
/*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.dyno.connectionpool.impl.lb;
import com.netflix.dyno.connectionpool.BaseOperation;
import com.netflix.dyno.connectionpool.Connection;
import com.netflix.dyno.connectionpool.ConnectionPoolConfiguration;
import com.netflix.dyno.connectionpool.ConnectionPoolConfiguration.LoadBalancingStrategy;
import com.netflix.dyno.connectionpool.ConnectionPoolMonitor;
import com.netflix.dyno.connectionpool.HashPartitioner;
import com.netflix.dyno.connectionpool.Host;
import com.netflix.dyno.connectionpool.HostConnectionPool;
import com.netflix.dyno.connectionpool.RetryPolicy;
import com.netflix.dyno.connectionpool.TokenMapSupplier;
import com.netflix.dyno.connectionpool.TokenPoolTopology;
import com.netflix.dyno.connectionpool.TokenRackMapper;
import com.netflix.dyno.connectionpool.exception.DynoConnectException;
import com.netflix.dyno.connectionpool.exception.DynoException;
import com.netflix.dyno.connectionpool.exception.NoAvailableHostsException;
import com.netflix.dyno.connectionpool.exception.PoolExhaustedException;
import com.netflix.dyno.connectionpool.exception.PoolOfflineException;
import com.netflix.dyno.connectionpool.exception.PoolTimeoutException;
import com.netflix.dyno.connectionpool.impl.HostSelectionStrategy;
import com.netflix.dyno.connectionpool.impl.HostSelectionStrategy.HostSelectionStrategyFactory;
import com.netflix.dyno.connectionpool.impl.RunOnce;
import com.netflix.dyno.connectionpool.impl.utils.CollectionUtils;
import com.netflix.dyno.connectionpool.impl.utils.CollectionUtils.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
/**
* Acts as a coordinator over multiple HostSelectionStrategy implementations, where each maps to a particular rack.
* This class doesn't actually implement the logic (e.g Round Robin or Token Aware) to borrow the connections. It
* relies on a local HostSelectionStrategy implementation and a collection of remote HostSelectionStrategy(s).
* It gives preference to the "local" HostSelectionStrategy but if the local pool is offline or hosts are down etc, then
* it falls back to the remote HostSelectionStrategy. Also it uses pure round robin for distributing load on the fall
* back HostSelectionStrategy implementations for even distribution of load on the remote racks in the event of an
* outage in the local rack.
* <p>
* Note that this class does not prefer any one remote HostSelectionStrategy over another.
*
* @param <CL>
* @author poberai
* @author jcacciatore
*/
public class HostSelectionWithFallback<CL> {
private static final Logger logger = LoggerFactory.getLogger(HostSelectionWithFallback.class);
// Only used in calculating replication factor
private final String localDataCenter;
// tracks the local zone
private final String localRack;
// The selector for the local zone
private final HostSelectionStrategy<CL> localSelector;
// Track selectors for each remote zone
private final ConcurrentHashMap<String, HostSelectionStrategy<CL>> remoteRackSelectors = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Host, HostToken> hostTokens = new ConcurrentHashMap<>();
private final TokenMapSupplier tokenSupplier;
private final ConnectionPoolConfiguration cpConfig;
private final ConnectionPoolMonitor cpMonitor;
private final AtomicInteger replicationFactor = new AtomicInteger(-1);
// Represents the *initial* topology from the token supplier. This does not affect selection of a host connection
// pool for traffic. It only affects metrics such as failover/fallback
private final AtomicReference<TokenPoolTopology> topology = new AtomicReference<>(null);
// list of names of remote zones. Used for RoundRobin over remote zones when local zone host is down
private final CircularList<String> remoteRackNames = new CircularList<>(new ArrayList<>());
private final HostSelectionStrategyFactory<CL> selectorFactory;
public HostSelectionWithFallback(ConnectionPoolConfiguration config, ConnectionPoolMonitor monitor) {
cpMonitor = monitor;
cpConfig = config;
localRack = cpConfig.getLocalRack();
localDataCenter = cpConfig.getLocalDataCenter();
tokenSupplier = cpConfig.getTokenSupplier();
selectorFactory = new DefaultSelectionFactory(cpConfig);
localSelector = selectorFactory.vendPoolSelectionStrategy();
}
public Connection<CL> getConnection(BaseOperation<CL, ?> op, int duration, TimeUnit unit) throws NoAvailableHostsException, PoolExhaustedException {
return getConnection(op, null, duration, unit, cpConfig.getRetryPolicyFactory().getRetryPolicy());
}
public Connection<CL> getConnectionUsingRetryPolicy(BaseOperation<CL, ?> op, int duration, TimeUnit unit, RetryPolicy retry) throws NoAvailableHostsException, PoolExhaustedException {
return getConnection(op, null, duration, unit, retry);
}
private Connection<CL> getConnection(BaseOperation<CL, ?> op, Long token, int duration, TimeUnit unit, RetryPolicy retry)
throws NoAvailableHostsException, PoolExhaustedException, PoolTimeoutException, PoolOfflineException {
DynoConnectException lastEx = null;
HostConnectionPool<CL> hostPool = null;
if (retry.getAttemptCount() == 0 || (retry.getAttemptCount() > 0 && !retry.allowCrossZoneFallback())) {
// By default zone affinity is enabled; if the local rack is not known at startup it is disabled
if (cpConfig.localZoneAffinity()) {
hostPool = getHostPoolForOperationOrTokenInLocalZone(op, token);
} else {
hostPool = getFallbackHostPool(op, token);
}
}
if (hostPool != null) {
try {
// Note that if a PoolExhaustedException is thrown it is caught by the calling
// ConnectionPoolImpl#executeXXX() method
return hostPool.borrowConnection(duration, unit);
} catch (PoolTimeoutException pte) {
lastEx = pte;
cpMonitor.incOperationFailure(null, pte);
}
}
if (attemptFallback()) {
if (topology.get().getTokensForRack(localRack) != null) {
cpMonitor.incFailover(null, lastEx);
}
hostPool = getFallbackHostPool(op, token);
if (hostPool != null) {
return hostPool.borrowConnection(duration, unit);
}
}
if (lastEx == null) {
throw new PoolOfflineException(hostPool == null ? null : hostPool.getHost(), "host pool is offline and no Racks available for fallback");
} else {
throw lastEx;
}
}
// Should be called when a connection is required on that particular zone with no fall backs what so ever
private Connection<CL> getConnectionForTokenOnRackNoFallback(BaseOperation<CL, ?> op, Long token, String rack, int duration, TimeUnit unit, RetryPolicy retry)
throws NoAvailableHostsException, PoolExhaustedException, PoolTimeoutException, PoolOfflineException {
DynoConnectException lastEx = null;
// find the selector for that rack,
HostSelectionStrategy<CL> selector = findSelectorForRack(rack);
// get the host using that selector
HostConnectionPool<CL> hostPool = selector.getPoolForToken(token);
if (hostPool != null) {
try {
// Note that if a PoolExhaustedException is thrown it is caught by the calling
// ConnectionPoolImpl#executeXXX() method
return hostPool.borrowConnection(duration, unit);
} catch (PoolTimeoutException pte) {
lastEx = pte;
cpMonitor.incOperationFailure(null, pte);
}
}
if (lastEx == null) {
throw new PoolOfflineException(hostPool == null ? null : hostPool.getHost(), "host pool is offline and we are forcing no fallback");
} else {
throw lastEx;
}
}
private HostConnectionPool<CL> getHostPoolForOperationOrTokenInLocalZone(BaseOperation<CL, ?> op, Long token) {
HostConnectionPool<CL> hostPool;
try {
if (!localSelector.isEmpty()) {
hostPool = (op != null) ? localSelector.getPoolForOperation(op, cpConfig.getHashtag()) : localSelector.getPoolForToken(token);
if (isConnectionPoolActive(hostPool)) {
return hostPool;
}
}
} catch (NoAvailableHostsException e) {
cpMonitor.incOperationFailure(null, e);
}
return null;
}
private boolean attemptFallback() {
return cpConfig.getMaxFailoverCount() > 0 &&
(cpConfig.localZoneAffinity() && remoteRackNames.getEntireList().size() > 0) ||
(!cpConfig.localZoneAffinity() && !localSelector.isEmpty());
}
private HostConnectionPool<CL> getFallbackHostPool(BaseOperation<CL, ?> op, Long token) {
int numRemotes = remoteRackNames.getEntireList().size();
if (numRemotes == 0) {
throw new NoAvailableHostsException("Could not find any remote Racks for fallback");
}
int numTries = Math.min(numRemotes, cpConfig.getMaxFailoverCount());
DynoException lastEx = null;
while ((numTries > 0)) {
numTries--;
String remoteRack = remoteRackNames.getNextElement();
HostSelectionStrategy<CL> remoteRackSelector = remoteRackSelectors.get(remoteRack);
try {
HostConnectionPool<CL> fallbackHostPool =
(op != null) ? remoteRackSelector.getPoolForOperation(op, cpConfig.getHashtag()) : remoteRackSelector.getPoolForToken(token);
if (isConnectionPoolActive(fallbackHostPool)) {
return fallbackHostPool;
}
} catch (NoAvailableHostsException e) {
cpMonitor.incOperationFailure(null, e);
lastEx = e;
}
}
if (lastEx != null) {
throw lastEx;
} else {
throw new NoAvailableHostsException("Local rack host offline and could not find any remote hosts for fallback connection");
}
}
public Collection<Connection<CL>> getConnectionsToRing(TokenRackMapper tokenRackMapper, int duration, TimeUnit unit) throws NoAvailableHostsException, PoolExhaustedException {
String targetRack = localRack;
if (targetRack == null) {
// get tokens for random rack
targetRack = topology.get().getRandomRack();
}
final Set<Long> tokens = topology.get().getTokenHostsForRack(targetRack).keySet();
DynoConnectException lastEx = null;
final List<Connection<CL>> connections = new ArrayList<>();
for (Long token : tokens) {
try {
// Cursor has a map of token to rack which indicates an affinity to a zone for that token.
// This is valid in case of an iterator based query like scan.
// Try to use that same rack if it is specified.
String rack = null;
if (tokenRackMapper != null)
rack = tokenRackMapper.getRackForToken(token);
if (rack != null) {
connections.add(getConnectionForTokenOnRackNoFallback(null, token, rack, duration, unit, new RunOnce()));
} else {
Connection<CL> c = getConnection(null, token, duration, unit, new RunOnce());
if (tokenRackMapper != null) {
tokenRackMapper.setRackForToken(token, c.getHost().getRack());
}
connections.add(c);
}
} catch (DynoConnectException e) {
logger.warn("Failed to get connection when getting all connections from ring", e.getMessage());
lastEx = e;
break;
}
}
if (lastEx != null) {
// Return all previously borrowed connection to avoid any connection leaks
for (Connection<CL> connection : connections) {
try {
connection.getParentConnectionPool().returnConnection(connection);
} catch (DynoConnectException e) {
// do nothing
}
}
throw lastEx;
} else {
return connections;
}
}
private HostSelectionStrategy<CL> findSelectorForRack(String rack) {
if (localRack == null) {
return localSelector;
}
if (localRack.equals(rack)) {
return localSelector;
}
HostSelectionStrategy<CL> remoteSelector = remoteRackSelectors.get(rack);
return remoteSelector;
}
private boolean isConnectionPoolActive(HostConnectionPool<CL> hPool) {
if (hPool == null) {
return false;
}
Host host = hPool.getHost();
return host.isUp() && hPool.isActive();
}
private Map<HostToken, HostConnectionPool<CL>> getHostPoolsForRack(final Map<HostToken, HostConnectionPool<CL>> map, final String rack) {
Map<HostToken, HostConnectionPool<CL>> dcPools =
CollectionUtils.filterKeys(map, new Predicate<HostToken>() {
@Override
public boolean apply(HostToken x) {
if (localRack == null) {
return true;
}
return rack.equals(x.getHost().getRack());
}
});
return dcPools;
}
/**
* Initialize the topology with the host pools obtained from discovery.
* hPools comes from discovery.
*
* @param hPools
*/
public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) {
// Get the list of tokens for these hosts
//tokenSupplier.initWithHosts(hPools.keySet());
List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet());
Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, HostConnectionPool<CL>>();
// Update inner state with the host tokens.
for (HostToken hToken : allHostTokens) {
hostTokens.put(hToken.getHost(), hToken);
tokenPoolMap.put(hToken, hPools.get(hToken.getHost()));
}
// Initialize Local selector
Map<HostToken, HostConnectionPool<CL>> localPools = getHostPoolsForRack(tokenPoolMap, localRack);
localSelector.initWithHosts(localPools);
if (localSelector.isTokenAware()) {
replicationFactor.set(HostUtils.calculateReplicationFactorForDC(allHostTokens, cpConfig.getLocalDataCenter(), localRack));
}
// Initialize Remote selectors
Set<String> remoteRacks = hPools.keySet().stream().map(h -> h.getRack()).filter(rack -> rack != null && !rack.equals(localRack)).collect(Collectors.toSet());
for (String rack : remoteRacks) {
Map<HostToken, HostConnectionPool<CL>> dcPools = getHostPoolsForRack(tokenPoolMap, rack);
HostSelectionStrategy<CL> remoteSelector = selectorFactory.vendPoolSelectionStrategy();
remoteSelector.initWithHosts(dcPools);
remoteRackSelectors.put(rack, remoteSelector);
}
remoteRackNames.swapWithList(remoteRackSelectors.keySet());
topology.set(createTokenPoolTopology(allHostTokens));
}
/**
* Calculate replication factor from the given list of hosts
*
* @param allHostTokens
* @return replicationFactor
*/
int calculateReplicationFactor(List<HostToken> allHostTokens) {
return HostUtils.calculateReplicationFactorForDC(allHostTokens, null, localRack);
}
public void addHost(Host host, HostConnectionPool<CL> hostPool) {
HostToken hostToken = tokenSupplier.getTokenForHost(host, hostTokens.keySet());
if (hostToken == null) {
throw new DynoConnectException("Could not find host token for host: " + host);
}
hostTokens.put(hostToken.getHost(), hostToken);
HostSelectionStrategy<CL> selector = findSelectorForRack(host.getRack());
if (selector != null) {
selector.addHostPool(hostToken, hostPool);
}
topology.get().addHostToken(hostToken.getHost().getRack(), hostToken.getToken(), hostToken.getHost());
}
public void removeHost(Host host) {
HostToken hostToken = hostTokens.remove(host);
if (hostToken != null) {
HostSelectionStrategy<CL> selector = findSelectorForRack(host.getRack());
if (selector != null) {
selector.removeHostPool(hostToken);
}
topology.get().removeHost(hostToken.getHost().getRack(), hostToken.getToken(), hostToken.getHost());
}
}
private class DefaultSelectionFactory implements HostSelectionStrategyFactory<CL> {
private final LoadBalancingStrategy lbStrategy;
private final HashPartitioner hashPartitioner;
private DefaultSelectionFactory(ConnectionPoolConfiguration config) {
lbStrategy = config.getLoadBalancingStrategy();
hashPartitioner = config.getHashPartitioner();
}
@Override
public HostSelectionStrategy<CL> vendPoolSelectionStrategy() {
switch (lbStrategy) {
case RoundRobin:
return new RoundRobinSelection<CL>();
case TokenAware:
return hashPartitioner != null
? new TokenAwareSelection<CL>(hashPartitioner)
: new TokenAwareSelection<CL>();
default:
throw new RuntimeException("LoadBalancing strategy not supported! " + cpConfig.getLoadBalancingStrategy().name());
}
}
}
private void updateTokenPoolTopology(TokenPoolTopology topology) {
if (localRack != null) {
addTokens(topology, localRack, localSelector);
}
for (String remoteRack : remoteRackSelectors.keySet()) {
addTokens(topology, remoteRack, remoteRackSelectors.get(remoteRack));
}
}
/**
* Create token pool topology from the host tokens
*
* @param allHostTokens
* @return tokenPoolTopology with the host information
*/
public TokenPoolTopology createTokenPoolTopology(List<HostToken> allHostTokens) {
TokenPoolTopology topology = new TokenPoolTopology(replicationFactor.get());
for (HostToken hostToken : allHostTokens) {
String rack = hostToken.getHost().getRack();
topology.addHostToken(rack, hostToken.getToken(), hostToken.getHost());
}
updateTokenPoolTopology(topology);
return topology;
}
public TokenPoolTopology getTokenPoolTopology() {
TokenPoolTopology topology = new TokenPoolTopology(replicationFactor.get());
updateTokenPoolTopology(topology);
return topology;
}
private void addTokens(TokenPoolTopology topology, String rack, HostSelectionStrategy<CL> selectionStrategy) {
Collection<HostConnectionPool<CL>> pools = selectionStrategy.getOrderedHostPools();
for (HostConnectionPool<CL> pool : pools) {
if (pool == null) {
continue;
}
HostToken hToken = hostTokens.get(pool.getHost());
if (hToken == null) {
continue;
}
topology.addToken(rack, hToken.getToken(), pool);
}
}
public Long getTokenForKey(String key) {
return localSelector.getTokenForKey(key).getToken();
}
@Override
public String toString() {
return "HostSelectionWithFallback{" +
"localDataCenter='" + localDataCenter + '\'' +
", localRack='" + localRack + '\'' +
", localSelector=" + localSelector +
", remoteRackSelectors=" + remoteRackSelectors +
", hostTokens=" + hostTokens +
", tokenSupplier=" + tokenSupplier +
", cpConfig=" + cpConfig +
", cpMonitor=" + cpMonitor +
", replicationFactor=" + replicationFactor +
", topology=" + topology +
", remoteRackNames=" + remoteRackNames +
", selectorFactory=" + selectorFactory +
'}';
}
}