|
| 1 | +/* |
| 2 | + * Tencent is pleased to support the open source community by making polaris-java available. |
| 3 | + * |
| 4 | + * Copyright (C) 2021 Tencent. All rights reserved. |
| 5 | + * |
| 6 | + * Licensed under the BSD 3-Clause License (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * https://opensource.org/licenses/BSD-3-Clause |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software distributed |
| 13 | + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 14 | + * CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 15 | + * specific language governing permissions and limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package com.tencent.polaris.plugins.loadbalancer.leastconnection; |
| 19 | + |
| 20 | +import com.tencent.polaris.api.config.consumer.LoadBalanceConfig; |
| 21 | +import com.tencent.polaris.api.control.Destroyable; |
| 22 | +import com.tencent.polaris.api.exception.ErrorCode; |
| 23 | +import com.tencent.polaris.api.exception.PolarisException; |
| 24 | +import com.tencent.polaris.api.plugin.PluginType; |
| 25 | +import com.tencent.polaris.api.plugin.common.InitContext; |
| 26 | +import com.tencent.polaris.api.plugin.common.PluginTypes; |
| 27 | +import com.tencent.polaris.api.plugin.compose.Extensions; |
| 28 | +import com.tencent.polaris.api.plugin.loadbalance.LoadBalancer; |
| 29 | +import com.tencent.polaris.api.plugin.registry.LocalRegistry; |
| 30 | +import com.tencent.polaris.api.pojo.DefaultServiceEventKeysProvider; |
| 31 | +import com.tencent.polaris.api.pojo.Instance; |
| 32 | +import com.tencent.polaris.api.pojo.ServiceEventKey; |
| 33 | +import com.tencent.polaris.api.pojo.ServiceEventKey.EventType; |
| 34 | +import com.tencent.polaris.api.pojo.ServiceInstances; |
| 35 | +import com.tencent.polaris.api.pojo.ServiceKey; |
| 36 | +import com.tencent.polaris.api.rpc.Criteria; |
| 37 | +import com.tencent.polaris.api.utils.CollectionUtils; |
| 38 | +import com.tencent.polaris.client.flow.BaseFlow; |
| 39 | +import com.tencent.polaris.client.flow.DefaultFlowControlParam; |
| 40 | +import com.tencent.polaris.client.flow.ResourcesResponse; |
| 41 | +import com.tencent.polaris.client.pojo.InstanceByProto; |
| 42 | +import com.tencent.polaris.logging.LoggerFactory; |
| 43 | +import java.util.HashMap; |
| 44 | +import java.util.HashSet; |
| 45 | +import java.util.List; |
| 46 | +import java.util.Map; |
| 47 | +import java.util.Set; |
| 48 | +import java.util.stream.Collectors; |
| 49 | +import org.slf4j.Logger; |
| 50 | + |
| 51 | +/** |
| 52 | + * Least Connections Load Balancer |
| 53 | + * |
| 54 | + * @author Yuwei Fu |
| 55 | + */ |
| 56 | +public class LeastConnectionLoadBalance extends Destroyable implements LoadBalancer { |
| 57 | + |
| 58 | + private LocalRegistry localRegistry; |
| 59 | + |
| 60 | + private Extensions extensions; |
| 61 | + |
| 62 | + private static final Logger LOG = LoggerFactory.getLogger(LeastConnectionLoadBalance.class); |
| 63 | + |
| 64 | + @Override |
| 65 | + public Instance chooseInstance(Criteria criteria, ServiceInstances instances) throws PolarisException { |
| 66 | + if (instances == null || CollectionUtils.isEmpty(instances.getInstances())) { |
| 67 | + throw new PolarisException(ErrorCode.INSTANCE_NOT_FOUND, "request instances is empty"); |
| 68 | + } |
| 69 | + ServiceKey serviceKey = instances.getServiceKey(); |
| 70 | + List<Instance> requestInstanceList = instances.getInstances(); |
| 71 | + Map<String, Instance> requestInstanceMap = new HashMap<>(requestInstanceList.size()); |
| 72 | + for (Instance instance : requestInstanceList) { |
| 73 | + if (instance.getWeight() != 0) { |
| 74 | + requestInstanceMap.put(instance.getHost() + ":" + instance.getPort(), instance); |
| 75 | + } |
| 76 | + } |
| 77 | + ServiceEventKey serviceEventKey = new ServiceEventKey(serviceKey, EventType.INSTANCE); |
| 78 | + Set<ServiceEventKey> serviceEventKeySet = new HashSet<>(); |
| 79 | + serviceEventKeySet.add(serviceEventKey); |
| 80 | + DefaultServiceEventKeysProvider svcKeysProvider = new DefaultServiceEventKeysProvider(); |
| 81 | + svcKeysProvider.setSvcEventKeys(serviceEventKeySet); |
| 82 | + DefaultFlowControlParam engineFlowControlParam = new DefaultFlowControlParam(); |
| 83 | + ResourcesResponse resourcesResponse = BaseFlow.syncGetResources(extensions, false, svcKeysProvider, |
| 84 | + engineFlowControlParam); |
| 85 | + ServiceInstances serviceInstances = resourcesResponse.getServiceInstances(serviceEventKey); |
| 86 | + |
| 87 | + List<Instance> localInstanceList = serviceInstances.getInstances(); |
| 88 | + if (CollectionUtils.isEmpty(localInstanceList)) { |
| 89 | + throw new PolarisException(ErrorCode.INSTANCE_NOT_FOUND, "local instances is empty"); |
| 90 | + } |
| 91 | + // intersection lookup |
| 92 | + List<Instance> instanceList = localInstanceList.stream() |
| 93 | + .filter(instance -> requestInstanceMap.containsKey(instance.getHost() + ":" + instance.getPort())) |
| 94 | + .collect(Collectors.toList()); |
| 95 | + if (instanceList.isEmpty()) { |
| 96 | + throw new PolarisException(ErrorCode.INSTANCE_NOT_FOUND, |
| 97 | + "No instance found. serviceKey=" + serviceKey.toString()); |
| 98 | + } |
| 99 | + |
| 100 | + int[] candidateIndexes = new int[instanceList.size()]; |
| 101 | + int sameActiveCount = 0; |
| 102 | + long leastActive = Long.MAX_VALUE; |
| 103 | + long[] instanceActive = new long[instanceList.size()]; |
| 104 | + for (int i = 0; i < instanceList.size(); i++) { |
| 105 | + InstanceByProto instance = (InstanceByProto) instanceList.get(i); |
| 106 | + long curActive = instance.getInstanceLocalValue().getInstanceStatistic().getActive(); |
| 107 | + instanceActive[i] = curActive; |
| 108 | + if (curActive < leastActive) { |
| 109 | + leastActive = curActive; |
| 110 | + sameActiveCount = 0; |
| 111 | + candidateIndexes[sameActiveCount++] = i; |
| 112 | + } else if (curActive == leastActive) { |
| 113 | + candidateIndexes[sameActiveCount++] = i; |
| 114 | + } |
| 115 | + } |
| 116 | + // If there is only one instance with the same least active count, |
| 117 | + // return it directly and increase its active count. |
| 118 | + if (sameActiveCount == 1) { |
| 119 | + InstanceByProto targetInstance = (InstanceByProto) instanceList.get(candidateIndexes[0]); |
| 120 | + targetInstance.getInstanceLocalValue().getInstanceStatistic().incrementAndGetActive(); |
| 121 | + LOG.debug("[LeastConnectionLoadBalance] instances active count: {}, choose instance: {}:{}", instanceActive, |
| 122 | + targetInstance.getHost(), targetInstance.getPort()); |
| 123 | + return requestInstanceMap.get(targetInstance.getHost() + ":" + targetInstance.getPort()); |
| 124 | + } |
| 125 | + // If there are multiple instances with the same active connections, |
| 126 | + // randomly select one by weight and increase its active count. |
| 127 | + int[] candidatesWeights = new int[sameActiveCount]; |
| 128 | + int totalWeight = 0; |
| 129 | + for (int i = 0; i < sameActiveCount; i++) { |
| 130 | + candidatesWeights[i] = (instanceList.get(candidateIndexes[i])).getWeight(); |
| 131 | + totalWeight += candidatesWeights[i]; |
| 132 | + } |
| 133 | + int randomWeight = (int) (Math.random() * totalWeight); |
| 134 | + for (int i = 0; i < sameActiveCount; i++) { |
| 135 | + randomWeight -= candidatesWeights[i]; |
| 136 | + if (randomWeight < 0) { |
| 137 | + InstanceByProto targetInstance = (InstanceByProto) instanceList.get(candidateIndexes[i]); |
| 138 | + targetInstance.getInstanceLocalValue().getInstanceStatistic().incrementAndGetActive(); |
| 139 | + LOG.debug("[LeastConnectionLoadBalance] instances active count: {}, choose instance: {}:{}", |
| 140 | + instanceActive, targetInstance.getHost(), targetInstance.getPort()); |
| 141 | + return requestInstanceMap.get(targetInstance.getHost() + ":" + targetInstance.getPort()); |
| 142 | + } |
| 143 | + } |
| 144 | + throw new PolarisException(ErrorCode.INSTANCE_NOT_FOUND, |
| 145 | + "No instance selected. serviceKey=" + serviceKey.toString()); |
| 146 | + } |
| 147 | + |
| 148 | + |
| 149 | + @Override |
| 150 | + public String getName() { |
| 151 | + return LoadBalanceConfig.LOAD_BALANCE_LEAST_CONNECTION; |
| 152 | + } |
| 153 | + |
| 154 | + @Override |
| 155 | + public PluginType getType() { |
| 156 | + return PluginTypes.LOAD_BALANCER.getBaseType(); |
| 157 | + } |
| 158 | + |
| 159 | + @Override |
| 160 | + public void init(InitContext ctx) { |
| 161 | + } |
| 162 | + |
| 163 | + @Override |
| 164 | + public void postContextInit(Extensions extensions) throws PolarisException { |
| 165 | + this.extensions = extensions; |
| 166 | + localRegistry = extensions.getLocalRegistry(); |
| 167 | + } |
| 168 | + |
| 169 | +} |
0 commit comments