JeetKunDoug commented on code in PR #74: URL: https://github.com/apache/cassandra-sidecar/pull/74#discussion_r1379275603
########## common/src/main/java/org/apache/cassandra/sidecar/common/SidecarLoadBalancingPolicy.java: ########## @@ -0,0 +1,204 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.apache.cassandra.sidecar.common; + +import java.net.InetSocketAddress; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.Set; + +import com.google.common.collect.Iterators; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.DriverExtensions; +import com.datastax.driver.core.Host; +import com.datastax.driver.core.HostDistance; +import com.datastax.driver.core.Statement; +import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; +import com.datastax.driver.core.policies.LoadBalancingPolicy; +import com.datastax.driver.core.policies.RoundRobinPolicy; + +/** + * The SidecarLoadBalancingPolicy is designed to ensure that the Cassandra Metadata objects associated with the + * CqlSessionProvider have enough non-local hosts in their allowed connections to be kept up-to-date + * even if the local Cassandra instances are down/have their native transport disabled. + * NOTE: This policy won't work with a child policy that is token-aware + */ +class SidecarLoadBalancingPolicy implements LoadBalancingPolicy +{ + public static final int MIN_ADDITIONAL_CONNECTIONS = 2; + private static final Logger logger = LoggerFactory.getLogger(SidecarLoadBalancingPolicy.class); + private final Set<Host> selectedHosts = new HashSet<>(); + private final Set<InetSocketAddress> localHostAddresses; + private final LoadBalancingPolicy childPolicy; + private final int totalRequestedConnections; + private final Random secureRandom = new SecureRandom(); + private final HashSet<Host> allHosts = new HashSet<>(); + private Cluster cluster; + + public SidecarLoadBalancingPolicy(List<InetSocketAddress> localHostAddresses, + String localDc, + int numAdditionalConnections) + { + this.childPolicy = getChildPolicy(localDc); + this.localHostAddresses = new HashSet<>(localHostAddresses); + if (numAdditionalConnections < MIN_ADDITIONAL_CONNECTIONS) + { + logger.warn("Additional instances requested was {}, which is less than the minimum of {}. Using {}.", + numAdditionalConnections, MIN_ADDITIONAL_CONNECTIONS, MIN_ADDITIONAL_CONNECTIONS); + numAdditionalConnections = MIN_ADDITIONAL_CONNECTIONS; + } + this.totalRequestedConnections = this.localHostAddresses.size() + numAdditionalConnections; + } + + private LoadBalancingPolicy getChildPolicy(String localDc) + { + if (localDc != null) + { + return DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).build(); + } + return new RoundRobinPolicy(); + } + + public void init(Cluster cluster, Collection<Host> hosts) + { + this.cluster = cluster; + this.allHosts.addAll(hosts); + recalculateSelectedHosts(); + childPolicy.init(cluster, hosts); + } + + public HostDistance distance(Host host) + { + if (!selectedHosts.contains(host)) + { + return HostDistance.IGNORED; + } + return childPolicy.distance(host); + } + + public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) + { + Iterator<Host> child = childPolicy.newQueryPlan(loggedKeyspace, statement); + // Filter the child policy to only selected hosts + return Iterators.filter(child, selectedHosts::contains); + } + + public synchronized void onAdd(Host host) + { + this.allHosts.add(host); + childPolicy.onAdd(host); + onUp(host); + } + + public synchronized void onUp(Host host) + { + if (selectedHosts.size() < totalRequestedConnections) + { + recalculateSelectedHosts(); + } + childPolicy.onUp(host); + } + + public synchronized void onDown(Host host) + { + // Don't remove local addresses from the selected host list + if (localHostAddresses.contains(host.getBroadcastRpcAddress())) + { + return; + } + + boolean wasSelected = selectedHosts.remove(host); + if (!wasSelected) + { + // Non-selected nodes have been marked with HostDistance.IGNORED + // even if they may otherwise be useful. This has a side effect + // of preventing the driver from trying to reconnect to them + // if we miss the `onUp` event, so we need to schedule reconnects + // for these hosts explicitly unless we have active connections. + DriverExtensions.startPeriodicReconnectionAttempt(cluster, host); + } + recalculateSelectedHosts(); + childPolicy.onDown(host); + } + + public synchronized void onRemove(Host host) + { + this.allHosts.remove(host); + onDown(host); + childPolicy.onRemove(host); + } + + public void close() + { + childPolicy.close(); + } + + /** + * Adds any local hosts to the selected host list + * + * @param hosts the list of hosts provided by the control connection + */ + private void addLocalHosts(List<Host> hosts) + { + Iterator<Host> hostIterator = hosts.iterator(); + while (hostIterator.hasNext()) + { + Host h = hostIterator.next(); + if (localHostAddresses.contains(h.getEndPoint().resolve())) + { + selectedHosts.add(h); + hostIterator.remove(); + } + } + } + + private synchronized void recalculateSelectedHosts() + { + // Copy the list to allow us to remove hosts as we build the list + List<Host> hosts = new ArrayList<>(this.allHosts); Review Comment: So I guess `addLocalHosts` is misnamed - we're not adding them to the `hosts` collection, we're adding them to `selectedHosts` and _removing_ them from the `hosts` list so we only consider non-local hosts when we do the rest of the selection. Let me see if I can rename some of these things to make sure that it's clearer. `addLocalHosts` -> `addLocalHostsToSelected` `hosts` -> `sourceHosts` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

