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