001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.master.normalizer;
020
021import java.util.ArrayList;
022import java.util.Collections;
023import java.util.Comparator;
024import java.util.List;
025import org.apache.hadoop.hbase.HBaseConfiguration;
026import org.apache.hadoop.hbase.HBaseIOException;
027import org.apache.hadoop.hbase.RegionMetrics;
028import org.apache.hadoop.hbase.ServerName;
029import org.apache.hadoop.hbase.Size;
030import org.apache.hadoop.hbase.TableName;
031import org.apache.hadoop.hbase.client.MasterSwitchType;
032import org.apache.hadoop.hbase.client.RegionInfo;
033import org.apache.hadoop.hbase.master.MasterRpcServices;
034import org.apache.hadoop.hbase.master.MasterServices;
035import org.apache.hadoop.hbase.master.normalizer.NormalizationPlan.PlanType;
036import org.apache.yetus.audience.InterfaceAudience;
037import org.slf4j.Logger;
038import org.slf4j.LoggerFactory;
039
040import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
041
042/**
043 * Simple implementation of region normalizer.
044 *
045 * Logic in use:
046 *
047 *  <ol>
048 *  <li> Get all regions of a given table
049 *  <li> Get avg size S of each region (by total size of store files reported in RegionMetrics)
050 *  <li> Seek every single region one by one. If a region R0 is bigger than S * 2, it is
051 *  kindly requested to split. Thereon evaluate the next region R1
052 *  <li> Otherwise, if R0 + R1 is smaller than S, R0 and R1 are kindly requested to merge.
053 *  Thereon evaluate the next region R2
054 *  <li> Otherwise, R1 is evaluated
055 * </ol>
056 * <p>
057 * Region sizes are coarse and approximate on the order of megabytes. Additionally,
058 * "empty" regions (less than 1MB, with the previous note) are not merged away. This
059 * is by design to prevent normalization from undoing the pre-splitting of a table.
060 */
061@InterfaceAudience.Private
062public class SimpleRegionNormalizer implements RegionNormalizer {
063
064  private static final Logger LOG = LoggerFactory.getLogger(SimpleRegionNormalizer.class);
065  private int minRegionCount;
066  private MasterServices masterServices;
067  private MasterRpcServices masterRpcServices;
068  private static long[] skippedCount = new long[NormalizationPlan.PlanType.values().length];
069
070  public SimpleRegionNormalizer() {
071    minRegionCount = HBaseConfiguration.create().getInt("hbase.normalizer.min.region.count", 3);
072  }
073  /**
074   * Set the master service.
075   * @param masterServices inject instance of MasterServices
076   */
077  @Override
078  public void setMasterServices(MasterServices masterServices) {
079    this.masterServices = masterServices;
080  }
081
082  @Override
083  public void setMasterRpcServices(MasterRpcServices masterRpcServices) {
084    this.masterRpcServices = masterRpcServices;
085  }
086
087  @Override
088  public void planSkipped(RegionInfo hri, PlanType type) {
089    skippedCount[type.ordinal()]++;
090  }
091
092  @Override
093  public long getSkippedCount(NormalizationPlan.PlanType type) {
094    return skippedCount[type.ordinal()];
095  }
096
097  /**
098   * Comparator class that gives higher priority to region Split plan.
099   */
100  static class PlanComparator implements Comparator<NormalizationPlan> {
101    @Override
102    public int compare(NormalizationPlan plan1, NormalizationPlan plan2) {
103      boolean plan1IsSplit = plan1 instanceof SplitNormalizationPlan;
104      boolean plan2IsSplit = plan2 instanceof SplitNormalizationPlan;
105      if (plan1IsSplit && plan2IsSplit) {
106        return 0;
107      } else if (plan1IsSplit) {
108        return -1;
109      } else if (plan2IsSplit) {
110        return 1;
111      } else {
112        return 0;
113      }
114    }
115  }
116
117  private Comparator<NormalizationPlan> planComparator = new PlanComparator();
118
119  /**
120   * Computes next most "urgent" normalization action on the table.
121   * Action may be either a split, or a merge, or no action.
122   *
123   * @param table table to normalize
124   * @return normalization plan to execute
125   */
126  @Override
127  public List<NormalizationPlan> computePlanForTable(TableName table) throws HBaseIOException {
128    if (table == null || table.isSystemTable()) {
129      LOG.debug("Normalization of system table " + table + " isn't allowed");
130      return null;
131    }
132
133    List<NormalizationPlan> plans = new ArrayList<>();
134    List<RegionInfo> tableRegions = masterServices.getAssignmentManager().getRegionStates().
135      getRegionsOfTable(table);
136
137    //TODO: should we make min number of regions a config param?
138    if (tableRegions == null || tableRegions.size() < minRegionCount) {
139      int nrRegions = tableRegions == null ? 0 : tableRegions.size();
140      LOG.debug("Table " + table + " has " + nrRegions + " regions, required min number"
141        + " of regions for normalizer to run is " + minRegionCount + ", not running normalizer");
142      return null;
143    }
144
145    LOG.debug("Computing normalization plan for table: " + table +
146      ", number of regions: " + tableRegions.size());
147
148    long totalSizeMb = 0;
149    int acutalRegionCnt = 0;
150
151    for (int i = 0; i < tableRegions.size(); i++) {
152      RegionInfo hri = tableRegions.get(i);
153      long regionSize = getRegionSize(hri);
154      if (regionSize > 0) {
155        acutalRegionCnt++;
156        totalSizeMb += regionSize;
157      }
158    }
159
160    double avgRegionSize = acutalRegionCnt == 0 ? 0 : totalSizeMb / (double) acutalRegionCnt;
161
162    LOG.debug("Table " + table + ", total aggregated regions size: " + totalSizeMb);
163    LOG.debug("Table " + table + ", average region size: " + avgRegionSize);
164
165    int candidateIdx = 0;
166    boolean splitEnabled = true, mergeEnabled = true;
167    try {
168      splitEnabled = masterRpcServices.isSplitOrMergeEnabled(null,
169        RequestConverter.buildIsSplitOrMergeEnabledRequest(MasterSwitchType.SPLIT)).getEnabled();
170    } catch (org.apache.hbase.thirdparty.com.google.protobuf.ServiceException e) {
171      LOG.debug("Unable to determine whether split is enabled", e);
172    }
173    try {
174      mergeEnabled = masterRpcServices.isSplitOrMergeEnabled(null,
175        RequestConverter.buildIsSplitOrMergeEnabledRequest(MasterSwitchType.MERGE)).getEnabled();
176    } catch (org.apache.hbase.thirdparty.com.google.protobuf.ServiceException e) {
177      LOG.debug("Unable to determine whether split is enabled", e);
178    }
179    while (candidateIdx < tableRegions.size()) {
180      RegionInfo hri = tableRegions.get(candidateIdx);
181      long regionSize = getRegionSize(hri);
182      // if the region is > 2 times larger than average, we split it, split
183      // is more high priority normalization action than merge.
184      if (regionSize > 2 * avgRegionSize) {
185        if (splitEnabled) {
186          LOG.info("Table " + table + ", large region " + hri.getRegionNameAsString() + " has size "
187              + regionSize + ", more than twice avg size, splitting");
188          plans.add(new SplitNormalizationPlan(hri, null));
189        }
190      } else {
191        if (candidateIdx == tableRegions.size()-1) {
192          break;
193        }
194        if (mergeEnabled) {
195          RegionInfo hri2 = tableRegions.get(candidateIdx+1);
196          long regionSize2 = getRegionSize(hri2);
197          if (regionSize >= 0 && regionSize2 >= 0 && regionSize + regionSize2 < avgRegionSize) {
198            LOG.info("Table " + table + ", small region size: " + regionSize
199              + " plus its neighbor size: " + regionSize2
200              + ", less than the avg size " + avgRegionSize + ", merging them");
201            plans.add(new MergeNormalizationPlan(hri, hri2));
202            candidateIdx++;
203          }
204        }
205      }
206      candidateIdx++;
207    }
208    if (plans.isEmpty()) {
209      LOG.debug("No normalization needed, regions look good for table: " + table);
210      return null;
211    }
212    Collections.sort(plans, planComparator);
213    return plans;
214  }
215
216  private long getRegionSize(RegionInfo hri) {
217    ServerName sn = masterServices.getAssignmentManager().getRegionStates().
218      getRegionServerOfRegion(hri);
219    RegionMetrics regionLoad = masterServices.getServerManager().getLoad(sn).
220      getRegionMetrics().get(hri.getRegionName());
221    if (regionLoad == null) {
222      LOG.debug(hri.getRegionNameAsString() + " was not found in RegionsLoad");
223      return -1;
224    }
225    return (long) regionLoad.getStoreFileSize().get(Size.Unit.MEGABYTE);
226  }
227}