001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.master.balancer; 019 020import java.util.Collection; 021import org.apache.yetus.audience.InterfaceAudience; 022 023/** 024 * Base class the allows writing costs functions from rolling average of some number from 025 * RegionLoad. 026 */ 027@InterfaceAudience.Private 028abstract class CostFromRegionLoadFunction extends CostFunction { 029 030 private final DoubleArrayCost cost = new DoubleArrayCost(); 031 032 private double computeCostForRegionServer(int regionServerIndex) { 033 // Cost this server has from RegionLoad 034 double cost = 0; 035 036 // for every region on this server get the rl 037 for (int regionIndex : cluster.regionsPerServer[regionServerIndex]) { 038 Collection<BalancerRegionLoad> regionLoadList = cluster.regionLoads[regionIndex]; 039 040 // Now if we found a region load get the type of cost that was requested. 041 if (regionLoadList != null) { 042 cost += getRegionLoadCost(regionLoadList); 043 } 044 } 045 return cost; 046 } 047 048 @Override 049 void prepare(BalancerClusterState cluster) { 050 super.prepare(cluster); 051 cost.prepare(cluster.numServers); 052 cost.applyCostsChange(costs -> { 053 for (int i = 0; i < costs.length; i++) { 054 costs[i] = computeCostForRegionServer(i); 055 } 056 }); 057 } 058 059 @Override 060 protected void regionMoved(int region, int oldServer, int newServer) { 061 // recompute the stat for the given two region servers 062 cost.applyCostsChange(costs -> { 063 costs[oldServer] = computeCostForRegionServer(oldServer); 064 costs[newServer] = computeCostForRegionServer(newServer); 065 }); 066 } 067 068 @Override 069 protected final double cost() { 070 return cost.cost(); 071 } 072 073 protected double getRegionLoadCost(Collection<BalancerRegionLoad> regionLoadList) { 074 double cost = 0; 075 for (BalancerRegionLoad rl : regionLoadList) { 076 cost += getCostFromRl(rl); 077 } 078 return cost / regionLoadList.size(); 079 } 080 081 protected abstract double getCostFromRl(BalancerRegionLoad rl); 082}