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