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;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertTrue;
022
023import java.io.IOException;
024import java.util.ArrayList;
025import java.util.List;
026import org.apache.hadoop.hbase.client.Put;
027import org.apache.hadoop.hbase.client.Result;
028import org.apache.hadoop.hbase.client.ResultScanner;
029import org.apache.hadoop.hbase.client.Scan;
030import org.apache.hadoop.hbase.client.Table;
031import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
032import org.apache.hadoop.hbase.client.metrics.ServerSideScanMetrics;
033import org.apache.hadoop.hbase.filter.BinaryComparator;
034import org.apache.hadoop.hbase.filter.ColumnPrefixFilter;
035import org.apache.hadoop.hbase.filter.Filter;
036import org.apache.hadoop.hbase.filter.FilterList;
037import org.apache.hadoop.hbase.filter.FilterList.Operator;
038import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
039import org.apache.hadoop.hbase.filter.RowFilter;
040import org.apache.hadoop.hbase.filter.SingleColumnValueExcludeFilter;
041import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
042import org.apache.hadoop.hbase.testclassification.MediumTests;
043import org.apache.hadoop.hbase.util.Bytes;
044import org.junit.AfterClass;
045import org.junit.BeforeClass;
046import org.junit.ClassRule;
047import org.junit.Test;
048import org.junit.experimental.categories.Category;
049
050@Category(MediumTests.class)
051public class TestServerSideScanMetricsFromClientSide {
052
053  @ClassRule
054  public static final HBaseClassTestRule CLASS_RULE =
055      HBaseClassTestRule.forClass(TestServerSideScanMetricsFromClientSide.class);
056
057  private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
058
059  private static Table TABLE = null;
060
061  /**
062   * Table configuration
063   */
064  private static TableName TABLE_NAME = TableName.valueOf("testTable");
065
066  private static int NUM_ROWS = 10;
067  private static byte[] ROW = Bytes.toBytes("testRow");
068  private static byte[][] ROWS = HTestConst.makeNAscii(ROW, NUM_ROWS);
069
070  // Should keep this value below 10 to keep generation of expected kv's simple. If above 10 then
071  // table/row/cf1/... will be followed by table/row/cf10/... instead of table/row/cf2/... which
072  // breaks the simple generation of expected kv's
073  private static int NUM_FAMILIES = 1;
074  private static byte[] FAMILY = Bytes.toBytes("testFamily");
075  private static byte[][] FAMILIES = HTestConst.makeNAscii(FAMILY, NUM_FAMILIES);
076
077  private static int NUM_QUALIFIERS = 1;
078  private static byte[] QUALIFIER = Bytes.toBytes("testQualifier");
079  private static byte[][] QUALIFIERS = HTestConst.makeNAscii(QUALIFIER, NUM_QUALIFIERS);
080
081  private static int VALUE_SIZE = 10;
082  private static byte[] VALUE = Bytes.createMaxByteArray(VALUE_SIZE);
083
084  private static int NUM_COLS = NUM_FAMILIES * NUM_QUALIFIERS;
085
086  // Approximation of how large the heap size of cells in our table. Should be accessed through
087  // getCellHeapSize().
088  private static long CELL_HEAP_SIZE = -1;
089
090  @BeforeClass
091  public static void setUpBeforeClass() throws Exception {
092    TEST_UTIL.startMiniCluster(3);
093    TABLE = createTestTable(TABLE_NAME, ROWS, FAMILIES, QUALIFIERS, VALUE);
094  }
095
096  static Table createTestTable(TableName name, byte[][] rows, byte[][] families,
097      byte[][] qualifiers, byte[] cellValue) throws IOException {
098    Table ht = TEST_UTIL.createTable(name, families);
099    List<Put> puts = createPuts(rows, families, qualifiers, cellValue);
100    ht.put(puts);
101
102    return ht;
103  }
104
105  @AfterClass
106  public static void tearDownAfterClass() throws Exception {
107    TEST_UTIL.shutdownMiniCluster();
108  }
109
110  /**
111   * Make puts to put the input value into each combination of row, family, and qualifier
112   * @param rows the rows to use
113   * @param families the column families to use
114   * @param qualifiers the column qualifiers to use
115   * @param value the value to put
116   * @return the putted input values added in puts
117   * @throws IOException If an IO problem is encountered
118   */
119  static ArrayList<Put> createPuts(byte[][] rows, byte[][] families, byte[][] qualifiers,
120      byte[] value) throws IOException {
121    Put put;
122    ArrayList<Put> puts = new ArrayList<>();
123
124    for (int row = 0; row < rows.length; row++) {
125      put = new Put(rows[row]);
126      for (int fam = 0; fam < families.length; fam++) {
127        for (int qual = 0; qual < qualifiers.length; qual++) {
128          KeyValue kv = new KeyValue(rows[row], families[fam], qualifiers[qual], qual, value);
129          put.add(kv);
130        }
131      }
132      puts.add(put);
133    }
134
135    return puts;
136  }
137
138  /**
139   * @return The approximate heap size of a cell in the test table. All cells should have
140   *         approximately the same heap size, so the value is cached to avoid repeating the
141   *         calculation
142   * @throws Exception on unexpected failure
143   */
144  private long getCellHeapSize() throws Exception {
145    if (CELL_HEAP_SIZE == -1) {
146      // Do a partial scan that will return a single result with a single cell
147      Scan scan = new Scan();
148      scan.setMaxResultSize(1);
149      scan.setAllowPartialResults(true);
150      ResultScanner scanner = TABLE.getScanner(scan);
151
152      Result result = scanner.next();
153
154      assertTrue(result != null);
155      assertTrue(result.rawCells() != null);
156      assertTrue(result.rawCells().length == 1);
157
158      CELL_HEAP_SIZE = result.rawCells()[0].heapSize();
159      scanner.close();
160    }
161
162    return CELL_HEAP_SIZE;
163  }
164
165  @Test
166  public void testRowsSeenMetricWithSync() throws Exception {
167    testRowsSeenMetric(false);
168  }
169
170  @Test
171  public void testRowsSeenMetricWithAsync() throws Exception {
172    testRowsSeenMetric(true);
173  }
174
175  private void testRowsSeenMetric(boolean async) throws Exception {
176    // Base scan configuration
177    Scan baseScan;
178    baseScan = new Scan();
179    baseScan.setScanMetricsEnabled(true);
180    baseScan.setAsyncPrefetch(async);
181    testRowsSeenMetric(baseScan);
182
183    // Test case that only a single result will be returned per RPC to the serer
184    baseScan.setCaching(1);
185    testRowsSeenMetric(baseScan);
186
187    // Test case that partial results are returned from the server. At most one cell will be
188    // contained in each response
189    baseScan.setMaxResultSize(1);
190    testRowsSeenMetric(baseScan);
191
192    // Test case that size limit is set such that a few cells are returned per partial result from
193    // the server
194    baseScan.setCaching(NUM_ROWS);
195    baseScan.setMaxResultSize(getCellHeapSize() * (NUM_COLS - 1));
196    testRowsSeenMetric(baseScan);
197  }
198
199  public void testRowsSeenMetric(Scan baseScan) throws Exception {
200    Scan scan;
201    scan = new Scan(baseScan);
202    testMetric(scan, ServerSideScanMetrics.COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME, NUM_ROWS);
203
204    for (int i = 0; i < ROWS.length - 1; i++) {
205      scan = new Scan(baseScan);
206      scan.withStartRow(ROWS[0]);
207      scan.withStopRow(ROWS[i + 1]);
208      testMetric(scan, ServerSideScanMetrics.COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME, i + 1);
209    }
210
211    for (int i = ROWS.length - 1; i > 0; i--) {
212      scan = new Scan(baseScan);
213      scan.withStartRow(ROWS[i - 1]);
214      scan.withStopRow(ROWS[ROWS.length - 1]);
215      testMetric(scan, ServerSideScanMetrics.COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME, ROWS.length - i);
216    }
217
218    // The filter should filter out all rows, but we still expect to see every row.
219    Filter filter =
220        new RowFilter(CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes("xyz")));
221    scan = new Scan(baseScan);
222    scan.setFilter(filter);
223    testMetric(scan, ServerSideScanMetrics.COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME, ROWS.length);
224
225    // Filter should pass on all rows
226    SingleColumnValueFilter singleColumnValueFilter =
227        new SingleColumnValueFilter(FAMILIES[0], QUALIFIERS[0], CompareOperator.EQUAL, VALUE);
228    scan = new Scan(baseScan);
229    scan.setFilter(singleColumnValueFilter);
230    testMetric(scan, ServerSideScanMetrics.COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME, ROWS.length);
231
232    // Filter should filter out all rows
233    singleColumnValueFilter =
234        new SingleColumnValueFilter(FAMILIES[0], QUALIFIERS[0], CompareOperator.NOT_EQUAL, VALUE);
235    scan = new Scan(baseScan);
236    scan.setFilter(singleColumnValueFilter);
237    testMetric(scan, ServerSideScanMetrics.COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME, ROWS.length);
238  }
239
240  @Test
241  public void testRowsFilteredMetric() throws Exception {
242    // Base scan configuration
243    Scan baseScan;
244    baseScan = new Scan();
245    baseScan.setScanMetricsEnabled(true);
246
247    // Test case where scan uses default values
248    testRowsFilteredMetric(baseScan);
249
250    // Test case where at most one Result is retrieved per RPC
251    baseScan.setCaching(1);
252    testRowsFilteredMetric(baseScan);
253
254    // Test case where size limit is very restrictive and partial results will be returned from
255    // server
256    baseScan.setMaxResultSize(1);
257    testRowsFilteredMetric(baseScan);
258
259    // Test a case where max result size limits response from server to only a few cells (not all
260    // cells from the row)
261    baseScan.setCaching(NUM_ROWS);
262    baseScan.setMaxResultSize(getCellHeapSize() * (NUM_COLS - 1));
263    testRowsSeenMetric(baseScan);
264  }
265
266  public void testRowsFilteredMetric(Scan baseScan) throws Exception {
267    testRowsFilteredMetric(baseScan, null, 0);
268
269    // Row filter doesn't match any row key. All rows should be filtered
270    Filter filter =
271        new RowFilter(CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes("xyz")));
272    testRowsFilteredMetric(baseScan, filter, ROWS.length);
273
274    // Filter will return results containing only the first key. Number of entire rows filtered
275    // should be 0.
276    filter = new FirstKeyOnlyFilter();
277    testRowsFilteredMetric(baseScan, filter, 0);
278
279    // Column prefix will find some matching qualifier on each row. Number of entire rows filtered
280    // should be 0
281    filter = new ColumnPrefixFilter(QUALIFIERS[0]);
282    testRowsFilteredMetric(baseScan, filter, 0);
283
284    // Column prefix will NOT find any matching qualifier on any row. All rows should be filtered
285    filter = new ColumnPrefixFilter(Bytes.toBytes("xyz"));
286    testRowsFilteredMetric(baseScan, filter, ROWS.length);
287
288    // Matching column value should exist in each row. No rows should be filtered.
289    filter = new SingleColumnValueFilter(FAMILIES[0], QUALIFIERS[0], CompareOperator.EQUAL, VALUE);
290    testRowsFilteredMetric(baseScan, filter, 0);
291
292    // No matching column value should exist in any row. Filter all rows
293    filter = new SingleColumnValueFilter(FAMILIES[0], QUALIFIERS[0],
294      CompareOperator.NOT_EQUAL, VALUE);
295    testRowsFilteredMetric(baseScan, filter, ROWS.length);
296
297    List<Filter> filters = new ArrayList<>();
298    filters.add(new RowFilter(CompareOperator.EQUAL, new BinaryComparator(ROWS[0])));
299    filters.add(new RowFilter(CompareOperator.EQUAL, new BinaryComparator(ROWS[3])));
300    int numberOfMatchingRowFilters = filters.size();
301    filter = new FilterList(Operator.MUST_PASS_ONE, filters);
302    testRowsFilteredMetric(baseScan, filter, ROWS.length - numberOfMatchingRowFilters);
303    filters.clear();
304
305    // Add a single column value exclude filter for each column... The net effect is that all
306    // columns will be excluded when scanning on the server side. This will result in an empty cell
307    // array in RegionScanner#nextInternal which should be interpreted as a row being filtered.
308    for (int family = 0; family < FAMILIES.length; family++) {
309      for (int qualifier = 0; qualifier < QUALIFIERS.length; qualifier++) {
310        filters.add(new SingleColumnValueExcludeFilter(FAMILIES[family], QUALIFIERS[qualifier],
311          CompareOperator.EQUAL, VALUE));
312      }
313    }
314    filter = new FilterList(Operator.MUST_PASS_ONE, filters);
315    testRowsFilteredMetric(baseScan, filter, ROWS.length);
316  }
317
318  public void testRowsFilteredMetric(Scan baseScan, Filter filter, int expectedNumFiltered)
319      throws Exception {
320    Scan scan = new Scan(baseScan);
321    if (filter != null) scan.setFilter(filter);
322    testMetric(scan, ServerSideScanMetrics.COUNT_OF_ROWS_FILTERED_KEY_METRIC_NAME, expectedNumFiltered);
323  }
324
325  /**
326   * Run the scan to completetion and check the metric against the specified value
327   * @param scan The scan instance to use to record metrics
328   * @param metricKey The metric key name
329   * @param expectedValue The expected value of metric
330   * @throws Exception on unexpected failure
331   */
332  public void testMetric(Scan scan, String metricKey, long expectedValue) throws Exception {
333    assertTrue("Scan should be configured to record metrics", scan.isScanMetricsEnabled());
334    ResultScanner scanner = TABLE.getScanner(scan);
335    // Iterate through all the results
336    while (scanner.next() != null) {
337
338    }
339    scanner.close();
340    ScanMetrics metrics = scanner.getScanMetrics();
341    assertTrue("Metrics are null", metrics != null);
342    assertTrue("Metric : " + metricKey + " does not exist", metrics.hasCounter(metricKey));
343    final long actualMetricValue = metrics.getCounter(metricKey).get();
344    assertEquals("Metric: " + metricKey + " Expected: " + expectedValue + " Actual: "
345        + actualMetricValue, expectedValue, actualMetricValue);
346
347  }
348}