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.coprocessor;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNull;
022
023import java.io.IOException;
024import java.util.Collections;
025import java.util.List;
026import java.util.Optional;
027import java.util.concurrent.CountDownLatch;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.fs.FileSystem;
030import org.apache.hadoop.fs.Path;
031import org.apache.hadoop.hbase.Cell;
032import org.apache.hadoop.hbase.Coprocessor;
033import org.apache.hadoop.hbase.HBaseClassTestRule;
034import org.apache.hadoop.hbase.HBaseTestingUtil;
035import org.apache.hadoop.hbase.HConstants;
036import org.apache.hadoop.hbase.TableName;
037import org.apache.hadoop.hbase.client.Admin;
038import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
039import org.apache.hadoop.hbase.client.CoprocessorDescriptorBuilder;
040import org.apache.hadoop.hbase.client.Get;
041import org.apache.hadoop.hbase.client.Put;
042import org.apache.hadoop.hbase.client.RegionInfo;
043import org.apache.hadoop.hbase.client.RegionInfoBuilder;
044import org.apache.hadoop.hbase.client.Result;
045import org.apache.hadoop.hbase.client.Scan;
046import org.apache.hadoop.hbase.client.Table;
047import org.apache.hadoop.hbase.client.TableDescriptor;
048import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
049import org.apache.hadoop.hbase.filter.FilterBase;
050import org.apache.hadoop.hbase.regionserver.ChunkCreator;
051import org.apache.hadoop.hbase.regionserver.FlushLifeCycleTracker;
052import org.apache.hadoop.hbase.regionserver.HRegion;
053import org.apache.hadoop.hbase.regionserver.HRegionServer;
054import org.apache.hadoop.hbase.regionserver.HStore;
055import org.apache.hadoop.hbase.regionserver.InternalScanner;
056import org.apache.hadoop.hbase.regionserver.MemStoreLAB;
057import org.apache.hadoop.hbase.regionserver.Region;
058import org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost;
059import org.apache.hadoop.hbase.regionserver.RegionServerServices;
060import org.apache.hadoop.hbase.regionserver.ScanType;
061import org.apache.hadoop.hbase.regionserver.ScannerContext;
062import org.apache.hadoop.hbase.regionserver.Store;
063import org.apache.hadoop.hbase.regionserver.StoreScanner;
064import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext;
065import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker;
066import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;
067import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController;
068import org.apache.hadoop.hbase.security.User;
069import org.apache.hadoop.hbase.testclassification.CoprocessorTests;
070import org.apache.hadoop.hbase.testclassification.MediumTests;
071import org.apache.hadoop.hbase.util.Bytes;
072import org.apache.hadoop.hbase.wal.WAL;
073import org.junit.ClassRule;
074import org.junit.Rule;
075import org.junit.Test;
076import org.junit.experimental.categories.Category;
077import org.junit.rules.TestName;
078
079@Category({CoprocessorTests.class, MediumTests.class})
080public class TestRegionObserverScannerOpenHook {
081
082  @ClassRule
083  public static final HBaseClassTestRule CLASS_RULE =
084      HBaseClassTestRule.forClass(TestRegionObserverScannerOpenHook.class);
085
086  private static HBaseTestingUtil UTIL = new HBaseTestingUtil();
087  static final Path DIR = UTIL.getDataTestDir();
088
089  @Rule
090  public TestName name = new TestName();
091
092  public static class NoDataFilter extends FilterBase {
093
094    @Override
095    public ReturnCode filterCell(final Cell ignored) {
096      return ReturnCode.SKIP;
097    }
098
099    @Override
100    public boolean filterAllRemaining() throws IOException {
101      return true;
102    }
103
104    @Override
105    public boolean filterRow() throws IOException {
106      return true;
107    }
108  }
109
110  /**
111   * Do the default logic in {@link RegionObserver} interface.
112   */
113  public static class EmptyRegionObsever implements RegionCoprocessor, RegionObserver {
114    @Override
115    public Optional<RegionObserver> getRegionObserver() {
116      return Optional.of(this);
117    }
118  }
119
120  /**
121   * Don't return any data from a scan by creating a custom {@link StoreScanner}.
122   */
123  public static class NoDataFromScan implements RegionCoprocessor, RegionObserver {
124    @Override
125    public Optional<RegionObserver> getRegionObserver() {
126      return Optional.of(this);
127    }
128
129    @Override
130    public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> c, Get get,
131        List<Cell> result) throws IOException {
132      c.bypass();
133    }
134
135    @Override
136    public void preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan)
137        throws IOException {
138      scan.setFilter(new NoDataFilter());
139    }
140  }
141
142  private static final InternalScanner NO_DATA = new InternalScanner() {
143
144    @Override
145    public boolean next(List<Cell> result, ScannerContext scannerContext) throws IOException {
146      return false;
147    }
148
149    @Override
150    public void close() throws IOException {}
151  };
152  /**
153   * Don't allow any data in a flush by creating a custom {@link StoreScanner}.
154   */
155  public static class NoDataFromFlush implements RegionCoprocessor, RegionObserver {
156    @Override
157    public Optional<RegionObserver> getRegionObserver() {
158      return Optional.of(this);
159    }
160
161    @Override
162    public InternalScanner preFlush(ObserverContext<RegionCoprocessorEnvironment> c, Store store,
163        InternalScanner scanner, FlushLifeCycleTracker tracker) throws IOException {
164      return NO_DATA;
165    }
166  }
167
168  /**
169   * Don't allow any data to be written out in the compaction by creating a custom
170   * {@link StoreScanner}.
171   */
172  public static class NoDataFromCompaction implements RegionCoprocessor, RegionObserver {
173    @Override
174    public Optional<RegionObserver> getRegionObserver() {
175      return Optional.of(this);
176    }
177
178    @Override
179    public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> c, Store store,
180        InternalScanner scanner, ScanType scanType, CompactionLifeCycleTracker tracker,
181        CompactionRequest request) throws IOException {
182      return NO_DATA;
183    }
184  }
185
186  HRegion initHRegion(byte[] tableName, String callingMethod, Configuration conf,
187      byte[]... families) throws IOException {
188    TableDescriptorBuilder builder =
189      TableDescriptorBuilder.newBuilder(TableName.valueOf(tableName));
190    for (byte[] family : families) {
191      builder.setColumnFamily(
192        ColumnFamilyDescriptorBuilder.of(family));
193    }
194    TableDescriptor tableDescriptor = builder.build();
195    ChunkCreator.initialize(MemStoreLAB.CHUNK_SIZE_DEFAULT, false, 0, 0,
196      0, null, MemStoreLAB.INDEX_CHUNK_SIZE_PERCENTAGE_DEFAULT);
197    RegionInfo info = RegionInfoBuilder.newBuilder(tableDescriptor.getTableName()).build();
198    Path path = new Path(DIR + callingMethod);
199    WAL wal = HBaseTestingUtil.createWal(conf, path, info);
200    HRegion r = HRegion.createHRegion(info, path, conf, tableDescriptor, wal);
201    // this following piece is a hack. currently a coprocessorHost
202    // is secretly loaded at OpenRegionHandler. we don't really
203    // start a region server here, so just manually create cphost
204    // and set it to region.
205    RegionCoprocessorHost host = new RegionCoprocessorHost(r, null, conf);
206    r.setCoprocessorHost(host);
207    return r;
208  }
209
210  @Test
211  public void testRegionObserverScanTimeStacking() throws Exception {
212    byte[] ROW = Bytes.toBytes("testRow");
213    byte[] TABLE = Bytes.toBytes(getClass().getName());
214    byte[] A = Bytes.toBytes("A");
215    byte[][] FAMILIES = new byte[][] { A };
216
217    // Use new HTU to not overlap with the DFS cluster started in #CompactionStacking
218    Configuration conf = new HBaseTestingUtil().getConfiguration();
219    HRegion region = initHRegion(TABLE, getClass().getName(), conf, FAMILIES);
220    RegionCoprocessorHost h = region.getCoprocessorHost();
221    h.load(NoDataFromScan.class, Coprocessor.PRIORITY_HIGHEST, conf);
222    h.load(EmptyRegionObsever.class, Coprocessor.PRIORITY_USER, conf);
223
224    Put put = new Put(ROW);
225    put.addColumn(A, A, A);
226    region.put(put);
227
228    Get get = new Get(ROW);
229    Result r = region.get(get);
230    assertNull(
231      "Got an unexpected number of rows - no data should be returned with the NoDataFromScan coprocessor. Found: "
232          + r, r.listCells());
233    HBaseTestingUtil.closeRegionAndWAL(region);
234  }
235
236  @Test
237  public void testRegionObserverFlushTimeStacking() throws Exception {
238    byte[] ROW = Bytes.toBytes("testRow");
239    byte[] TABLE = Bytes.toBytes(getClass().getName());
240    byte[] A = Bytes.toBytes("A");
241    byte[][] FAMILIES = new byte[][] { A };
242
243    // Use new HTU to not overlap with the DFS cluster started in #CompactionStacking
244    Configuration conf = new HBaseTestingUtil().getConfiguration();
245    HRegion region = initHRegion(TABLE, getClass().getName(), conf, FAMILIES);
246    RegionCoprocessorHost h = region.getCoprocessorHost();
247    h.load(NoDataFromFlush.class, Coprocessor.PRIORITY_HIGHEST, conf);
248    h.load(EmptyRegionObsever.class, Coprocessor.PRIORITY_USER, conf);
249
250    // put a row and flush it to disk
251    Put put = new Put(ROW);
252    put.addColumn(A, A, A);
253    region.put(put);
254    region.flush(true);
255    Get get = new Get(ROW);
256    Result r = region.get(get);
257    assertNull(
258      "Got an unexpected number of rows - no data should be returned with the NoDataFromScan coprocessor. Found: "
259          + r, r.listCells());
260    HBaseTestingUtil.closeRegionAndWAL(region);
261  }
262
263  /*
264   * Custom HRegion which uses CountDownLatch to signal the completion of compaction
265   */
266  public static class CompactionCompletionNotifyingRegion extends HRegion {
267    private static volatile CountDownLatch compactionStateChangeLatch = null;
268
269    @SuppressWarnings("deprecation")
270    public CompactionCompletionNotifyingRegion(Path tableDir, WAL log,
271        FileSystem fs, Configuration confParam, RegionInfo info,
272        TableDescriptor htd, RegionServerServices rsServices) {
273      super(tableDir, log, fs, confParam, info, htd, rsServices);
274    }
275
276    public CountDownLatch getCompactionStateChangeLatch() {
277      if (compactionStateChangeLatch == null) compactionStateChangeLatch = new CountDownLatch(1);
278      return compactionStateChangeLatch;
279    }
280
281    @Override
282    public boolean compact(CompactionContext compaction, HStore store,
283        ThroughputController throughputController) throws IOException {
284      boolean ret = super.compact(compaction, store, throughputController);
285      if (ret) compactionStateChangeLatch.countDown();
286      return ret;
287    }
288
289    @Override
290    public boolean compact(CompactionContext compaction, HStore store,
291        ThroughputController throughputController, User user) throws IOException {
292      boolean ret = super.compact(compaction, store, throughputController, user);
293      if (ret) compactionStateChangeLatch.countDown();
294      return ret;
295    }
296  }
297
298  /**
299   * Unfortunately, the easiest way to test this is to spin up a mini-cluster since we want to do
300   * the usual compaction mechanism on the region, rather than going through the backdoor to the
301   * region
302   */
303  @Test
304  public void testRegionObserverCompactionTimeStacking() throws Exception {
305    // setup a mini cluster so we can do a real compaction on a region
306    Configuration conf = UTIL.getConfiguration();
307    conf.setClass(HConstants.REGION_IMPL, CompactionCompletionNotifyingRegion.class, HRegion.class);
308    conf.setInt("hbase.hstore.compaction.min", 2);
309    UTIL.startMiniCluster();
310    byte[] ROW = Bytes.toBytes("testRow");
311    byte[] A = Bytes.toBytes("A");
312    TableDescriptor tableDescriptor =
313      TableDescriptorBuilder.newBuilder(TableName.valueOf(name.getMethodName()))
314        .setColumnFamily(ColumnFamilyDescriptorBuilder.of(A))
315        .setCoprocessor(CoprocessorDescriptorBuilder
316          .newBuilder(EmptyRegionObsever.class.getName()).setJarPath(null)
317          .setPriority(Coprocessor.PRIORITY_USER).setProperties(Collections.emptyMap()).build())
318        .setCoprocessor(CoprocessorDescriptorBuilder
319          .newBuilder(NoDataFromCompaction.class.getName()).setJarPath(null)
320          .setPriority(Coprocessor.PRIORITY_HIGHEST).setProperties(Collections.emptyMap()).build())
321        .build();
322
323    Admin admin = UTIL.getAdmin();
324    admin.createTable(tableDescriptor);
325
326    Table table = UTIL.getConnection().getTable(tableDescriptor.getTableName());
327
328    // put a row and flush it to disk
329    Put put = new Put(ROW);
330    put.addColumn(A, A, A);
331    table.put(put);
332
333    HRegionServer rs = UTIL.getRSForFirstRegionInTable(tableDescriptor.getTableName());
334    List<HRegion> regions = rs.getRegions(tableDescriptor.getTableName());
335    assertEquals("More than 1 region serving test table with 1 row", 1, regions.size());
336    Region region = regions.get(0);
337    admin.flushRegion(region.getRegionInfo().getRegionName());
338    CountDownLatch latch = ((CompactionCompletionNotifyingRegion)region)
339        .getCompactionStateChangeLatch();
340
341    // put another row and flush that too
342    put = new Put(Bytes.toBytes("anotherrow"));
343    put.addColumn(A, A, A);
344    table.put(put);
345    admin.flushRegion(region.getRegionInfo().getRegionName());
346
347    // run a compaction, which normally would should get rid of the data
348    // wait for the compaction checker to complete
349    latch.await();
350    // check both rows to ensure that they aren't there
351    Get get = new Get(ROW);
352    Result r = table.get(get);
353    assertNull(
354      "Got an unexpected number of rows - no data should be returned with the NoDataFromScan coprocessor. Found: "
355          + r, r.listCells());
356
357    get = new Get(Bytes.toBytes("anotherrow"));
358    r = table.get(get);
359    assertNull(
360      "Got an unexpected number of rows - no data should be returned with the NoDataFromScan coprocessor Found: "
361          + r, r.listCells());
362
363    table.close();
364    UTIL.shutdownMiniCluster();
365  }
366}