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.regionserver;
019
020import static org.apache.hadoop.hbase.HBaseTestingUtility.COLUMNS;
021import static org.apache.hadoop.hbase.HBaseTestingUtility.fam1;
022import static org.apache.hadoop.hbase.HBaseTestingUtility.fam2;
023import static org.apache.hadoop.hbase.HBaseTestingUtility.fam3;
024import static org.junit.Assert.assertArrayEquals;
025import static org.junit.Assert.assertEquals;
026import static org.junit.Assert.assertFalse;
027import static org.junit.Assert.assertNotNull;
028import static org.junit.Assert.assertNull;
029import static org.junit.Assert.assertTrue;
030import static org.junit.Assert.fail;
031import static org.mockito.ArgumentMatchers.any;
032import static org.mockito.ArgumentMatchers.anyBoolean;
033import static org.mockito.ArgumentMatchers.anyLong;
034import static org.mockito.Mockito.doThrow;
035import static org.mockito.Mockito.mock;
036import static org.mockito.Mockito.never;
037import static org.mockito.Mockito.spy;
038import static org.mockito.Mockito.times;
039import static org.mockito.Mockito.verify;
040import static org.mockito.Mockito.when;
041
042import java.io.IOException;
043import java.io.InterruptedIOException;
044import java.math.BigDecimal;
045import java.nio.charset.StandardCharsets;
046import java.security.PrivilegedExceptionAction;
047import java.util.ArrayList;
048import java.util.Arrays;
049import java.util.Collection;
050import java.util.List;
051import java.util.Map;
052import java.util.NavigableMap;
053import java.util.Objects;
054import java.util.TreeMap;
055import java.util.UUID;
056import java.util.concurrent.Callable;
057import java.util.concurrent.CountDownLatch;
058import java.util.concurrent.ExecutorService;
059import java.util.concurrent.Executors;
060import java.util.concurrent.Future;
061import java.util.concurrent.TimeUnit;
062import java.util.concurrent.atomic.AtomicBoolean;
063import java.util.concurrent.atomic.AtomicInteger;
064import java.util.concurrent.atomic.AtomicReference;
065import org.apache.commons.lang3.RandomStringUtils;
066import org.apache.hadoop.conf.Configuration;
067import org.apache.hadoop.fs.FSDataOutputStream;
068import org.apache.hadoop.fs.FileStatus;
069import org.apache.hadoop.fs.FileSystem;
070import org.apache.hadoop.fs.Path;
071import org.apache.hadoop.hbase.ArrayBackedTag;
072import org.apache.hadoop.hbase.Cell;
073import org.apache.hadoop.hbase.Cell.Type;
074import org.apache.hadoop.hbase.CellBuilderFactory;
075import org.apache.hadoop.hbase.CellBuilderType;
076import org.apache.hadoop.hbase.CellUtil;
077import org.apache.hadoop.hbase.CompareOperator;
078import org.apache.hadoop.hbase.CompatibilitySingletonFactory;
079import org.apache.hadoop.hbase.DroppedSnapshotException;
080import org.apache.hadoop.hbase.HBaseClassTestRule;
081import org.apache.hadoop.hbase.HBaseConfiguration;
082import org.apache.hadoop.hbase.HBaseTestingUtility;
083import org.apache.hadoop.hbase.HColumnDescriptor;
084import org.apache.hadoop.hbase.HConstants;
085import org.apache.hadoop.hbase.HConstants.OperationStatusCode;
086import org.apache.hadoop.hbase.HDFSBlocksDistribution;
087import org.apache.hadoop.hbase.HRegionInfo;
088import org.apache.hadoop.hbase.HTableDescriptor;
089import org.apache.hadoop.hbase.KeyValue;
090import org.apache.hadoop.hbase.KeyValueUtil;
091import org.apache.hadoop.hbase.MiniHBaseCluster;
092import org.apache.hadoop.hbase.MultithreadedTestUtil;
093import org.apache.hadoop.hbase.MultithreadedTestUtil.RepeatingTestThread;
094import org.apache.hadoop.hbase.MultithreadedTestUtil.TestThread;
095import org.apache.hadoop.hbase.NotServingRegionException;
096import org.apache.hadoop.hbase.PrivateCellUtil;
097import org.apache.hadoop.hbase.RegionTooBusyException;
098import org.apache.hadoop.hbase.ServerName;
099import org.apache.hadoop.hbase.TableName;
100import org.apache.hadoop.hbase.TagType;
101import org.apache.hadoop.hbase.Waiter;
102import org.apache.hadoop.hbase.client.Append;
103import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
104import org.apache.hadoop.hbase.client.Delete;
105import org.apache.hadoop.hbase.client.Durability;
106import org.apache.hadoop.hbase.client.Get;
107import org.apache.hadoop.hbase.client.Increment;
108import org.apache.hadoop.hbase.client.Mutation;
109import org.apache.hadoop.hbase.client.Put;
110import org.apache.hadoop.hbase.client.RegionInfo;
111import org.apache.hadoop.hbase.client.RegionInfoBuilder;
112import org.apache.hadoop.hbase.client.Result;
113import org.apache.hadoop.hbase.client.RowMutations;
114import org.apache.hadoop.hbase.client.Scan;
115import org.apache.hadoop.hbase.client.Table;
116import org.apache.hadoop.hbase.client.TableDescriptor;
117import org.apache.hadoop.hbase.exceptions.FailedSanityCheckException;
118import org.apache.hadoop.hbase.filter.BigDecimalComparator;
119import org.apache.hadoop.hbase.filter.BinaryComparator;
120import org.apache.hadoop.hbase.filter.ColumnCountGetFilter;
121import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
122import org.apache.hadoop.hbase.filter.Filter;
123import org.apache.hadoop.hbase.filter.FilterBase;
124import org.apache.hadoop.hbase.filter.FilterList;
125import org.apache.hadoop.hbase.filter.NullComparator;
126import org.apache.hadoop.hbase.filter.PrefixFilter;
127import org.apache.hadoop.hbase.filter.SingleColumnValueExcludeFilter;
128import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
129import org.apache.hadoop.hbase.filter.SubstringComparator;
130import org.apache.hadoop.hbase.filter.ValueFilter;
131import org.apache.hadoop.hbase.io.hfile.HFile;
132import org.apache.hadoop.hbase.monitoring.MonitoredRPCHandler;
133import org.apache.hadoop.hbase.monitoring.MonitoredTask;
134import org.apache.hadoop.hbase.monitoring.TaskMonitor;
135import org.apache.hadoop.hbase.regionserver.HRegion.MutationBatchOperation;
136import org.apache.hadoop.hbase.regionserver.HRegion.RegionScannerImpl;
137import org.apache.hadoop.hbase.regionserver.Region.RowLock;
138import org.apache.hadoop.hbase.regionserver.TestHStore.FaultyFileSystem;
139import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequestImpl;
140import org.apache.hadoop.hbase.regionserver.wal.FSHLog;
141import org.apache.hadoop.hbase.regionserver.wal.MetricsWALSource;
142import org.apache.hadoop.hbase.regionserver.wal.WALUtil;
143import org.apache.hadoop.hbase.security.User;
144import org.apache.hadoop.hbase.test.MetricsAssertHelper;
145import org.apache.hadoop.hbase.testclassification.LargeTests;
146import org.apache.hadoop.hbase.testclassification.VerySlowRegionServerTests;
147import org.apache.hadoop.hbase.util.Bytes;
148import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
149import org.apache.hadoop.hbase.util.EnvironmentEdgeManagerTestHelper;
150import org.apache.hadoop.hbase.util.FSUtils;
151import org.apache.hadoop.hbase.util.IncrementingEnvironmentEdge;
152import org.apache.hadoop.hbase.util.ManualEnvironmentEdge;
153import org.apache.hadoop.hbase.util.Threads;
154import org.apache.hadoop.hbase.wal.AbstractFSWALProvider;
155import org.apache.hadoop.hbase.wal.FaultyFSLog;
156import org.apache.hadoop.hbase.wal.WAL;
157import org.apache.hadoop.hbase.wal.WALEdit;
158import org.apache.hadoop.hbase.wal.WALFactory;
159import org.apache.hadoop.hbase.wal.WALKeyImpl;
160import org.apache.hadoop.hbase.wal.WALProvider;
161import org.apache.hadoop.hbase.wal.WALProvider.Writer;
162import org.apache.hadoop.hbase.wal.WALSplitter;
163import org.junit.After;
164import org.junit.Assert;
165import org.junit.Before;
166import org.junit.ClassRule;
167import org.junit.Rule;
168import org.junit.Test;
169import org.junit.experimental.categories.Category;
170import org.junit.rules.ExpectedException;
171import org.junit.rules.TestName;
172import org.mockito.ArgumentCaptor;
173import org.mockito.ArgumentMatcher;
174import org.mockito.Mockito;
175import org.mockito.invocation.InvocationOnMock;
176import org.mockito.stubbing.Answer;
177import org.slf4j.Logger;
178import org.slf4j.LoggerFactory;
179
180import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
181import org.apache.hbase.thirdparty.com.google.protobuf.ByteString;
182
183import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
184import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.CompactionDescriptor;
185import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.FlushDescriptor;
186import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.FlushDescriptor.FlushAction;
187import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.FlushDescriptor.StoreFlushDescriptor;
188import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.RegionEventDescriptor;
189import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.StoreDescriptor;
190
191/**
192 * Basic stand-alone testing of HRegion.  No clusters!
193 *
194 * A lot of the meta information for an HRegion now lives inside other HRegions
195 * or in the HBaseMaster, so only basic testing is possible.
196 */
197@Category({VerySlowRegionServerTests.class, LargeTests.class})
198@SuppressWarnings("deprecation")
199public class TestHRegion {
200
201  @ClassRule
202  public static final HBaseClassTestRule CLASS_RULE =
203      HBaseClassTestRule.forClass(TestHRegion.class);
204
205  // Do not spin up clusters in here. If you need to spin up a cluster, do it
206  // over in TestHRegionOnCluster.
207  private static final Logger LOG = LoggerFactory.getLogger(TestHRegion.class);
208  @Rule
209  public TestName name = new TestName();
210  @Rule public final ExpectedException thrown = ExpectedException.none();
211
212  private static final String COLUMN_FAMILY = "MyCF";
213  private static final byte [] COLUMN_FAMILY_BYTES = Bytes.toBytes(COLUMN_FAMILY);
214
215  HRegion region = null;
216  // Do not run unit tests in parallel (? Why not?  It don't work?  Why not?  St.Ack)
217  protected static HBaseTestingUtility TEST_UTIL;
218  public static Configuration CONF ;
219  private String dir;
220  private static FileSystem FILESYSTEM;
221  private final int MAX_VERSIONS = 2;
222
223  // Test names
224  protected TableName tableName;
225  protected String method;
226  protected final byte[] qual = Bytes.toBytes("qual");
227  protected final byte[] qual1 = Bytes.toBytes("qual1");
228  protected final byte[] qual2 = Bytes.toBytes("qual2");
229  protected final byte[] qual3 = Bytes.toBytes("qual3");
230  protected final byte[] value = Bytes.toBytes("value");
231  protected final byte[] value1 = Bytes.toBytes("value1");
232  protected final byte[] value2 = Bytes.toBytes("value2");
233  protected final byte[] row = Bytes.toBytes("rowA");
234  protected final byte[] row2 = Bytes.toBytes("rowB");
235
236  protected final MetricsAssertHelper metricsAssertHelper = CompatibilitySingletonFactory
237      .getInstance(MetricsAssertHelper.class);
238
239  @Before
240  public void setup() throws IOException {
241    TEST_UTIL = HBaseTestingUtility.createLocalHTU();
242    FILESYSTEM = TEST_UTIL.getTestFileSystem();
243    CONF = TEST_UTIL.getConfiguration();
244    dir = TEST_UTIL.getDataTestDir("TestHRegion").toString();
245    method = name.getMethodName();
246    tableName = TableName.valueOf(method);
247    CONF.set(CompactingMemStore.IN_MEMORY_FLUSH_THRESHOLD_FACTOR_KEY, String.valueOf(0.09));
248  }
249
250  @After
251  public void tearDown() throws Exception {
252    EnvironmentEdgeManagerTestHelper.reset();
253    LOG.info("Cleaning test directory: " + TEST_UTIL.getDataTestDir());
254    TEST_UTIL.cleanupTestDir();
255  }
256
257  /**
258   * Test that I can use the max flushed sequence id after the close.
259   * @throws IOException
260   */
261  @Test
262  public void testSequenceId() throws IOException {
263    HRegion region = initHRegion(tableName, method, CONF, COLUMN_FAMILY_BYTES);
264    assertEquals(HConstants.NO_SEQNUM, region.getMaxFlushedSeqId());
265    // Weird. This returns 0 if no store files or no edits. Afraid to change it.
266    assertEquals(0, (long)region.getMaxStoreSeqId().get(COLUMN_FAMILY_BYTES));
267    region.close();
268    assertEquals(HConstants.NO_SEQNUM, region.getMaxFlushedSeqId());
269    assertEquals(0, (long)region.getMaxStoreSeqId().get(COLUMN_FAMILY_BYTES));
270    // Open region again.
271    region = initHRegion(tableName, method, CONF, COLUMN_FAMILY_BYTES);
272    byte [] value = Bytes.toBytes(method);
273    // Make a random put against our cf.
274    Put put = new Put(value);
275    put.addColumn(COLUMN_FAMILY_BYTES, null, value);
276    region.put(put);
277    // No flush yet so init numbers should still be in place.
278    assertEquals(HConstants.NO_SEQNUM, region.getMaxFlushedSeqId());
279    assertEquals(0, (long)region.getMaxStoreSeqId().get(COLUMN_FAMILY_BYTES));
280    region.flush(true);
281    long max = region.getMaxFlushedSeqId();
282    region.close();
283    assertEquals(max, region.getMaxFlushedSeqId());
284  }
285
286  /**
287   * Test for Bug 2 of HBASE-10466.
288   * "Bug 2: Conditions for the first flush of region close (so-called pre-flush) If memstoreSize
289   * is smaller than a certain value, or when region close starts a flush is ongoing, the first
290   * flush is skipped and only the second flush takes place. However, two flushes are required in
291   * case previous flush fails and leaves some data in snapshot. The bug could cause loss of data
292   * in current memstore. The fix is removing all conditions except abort check so we ensure 2
293   * flushes for region close."
294   * @throws IOException
295   */
296  @Test
297  public void testCloseCarryingSnapshot() throws IOException {
298    HRegion region = initHRegion(tableName, method, CONF, COLUMN_FAMILY_BYTES);
299    HStore store = region.getStore(COLUMN_FAMILY_BYTES);
300    // Get some random bytes.
301    byte [] value = Bytes.toBytes(method);
302    // Make a random put against our cf.
303    Put put = new Put(value);
304    put.addColumn(COLUMN_FAMILY_BYTES, null, value);
305    // First put something in current memstore, which will be in snapshot after flusher.prepare()
306    region.put(put);
307    StoreFlushContext storeFlushCtx = store.createFlushContext(12345, FlushLifeCycleTracker.DUMMY);
308    storeFlushCtx.prepare();
309    // Second put something in current memstore
310    put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("abc"), value);
311    region.put(put);
312    // Close with something in memstore and something in the snapshot.  Make sure all is cleared.
313    region.close();
314    assertEquals(0, region.getMemStoreDataSize());
315    HBaseTestingUtility.closeRegionAndWAL(region);
316  }
317
318  /*
319   * This test is for verifying memstore snapshot size is correctly updated in case of rollback
320   * See HBASE-10845
321   */
322  @Test
323  public void testMemstoreSnapshotSize() throws IOException {
324    class MyFaultyFSLog extends FaultyFSLog {
325      StoreFlushContext storeFlushCtx;
326      public MyFaultyFSLog(FileSystem fs, Path rootDir, String logName, Configuration conf)
327          throws IOException {
328        super(fs, rootDir, logName, conf);
329      }
330
331      void setStoreFlushCtx(StoreFlushContext storeFlushCtx) {
332        this.storeFlushCtx = storeFlushCtx;
333      }
334
335      @Override
336      public void sync(long txid) throws IOException {
337        storeFlushCtx.prepare();
338        super.sync(txid);
339      }
340    }
341
342    FileSystem fs = FileSystem.get(CONF);
343    Path rootDir = new Path(dir + "testMemstoreSnapshotSize");
344    MyFaultyFSLog faultyLog = new MyFaultyFSLog(fs, rootDir, "testMemstoreSnapshotSize", CONF);
345    HRegion region = initHRegion(tableName, null, null, false, Durability.SYNC_WAL, faultyLog,
346        COLUMN_FAMILY_BYTES);
347
348    HStore store = region.getStore(COLUMN_FAMILY_BYTES);
349    // Get some random bytes.
350    byte [] value = Bytes.toBytes(method);
351    faultyLog.setStoreFlushCtx(store.createFlushContext(12345, FlushLifeCycleTracker.DUMMY));
352
353    Put put = new Put(value);
354    put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("abc"), value);
355    faultyLog.setFailureType(FaultyFSLog.FailureType.SYNC);
356
357    boolean threwIOE = false;
358    try {
359      region.put(put);
360    } catch (IOException ioe) {
361      threwIOE = true;
362    } finally {
363      assertTrue("The regionserver should have thrown an exception", threwIOE);
364    }
365    MemStoreSize mss = store.getFlushableSize();
366    assertTrue("flushable size should be zero, but it is " + mss,
367        mss.getDataSize() == 0);
368    HBaseTestingUtility.closeRegionAndWAL(region);
369  }
370
371  /**
372   * Create a WAL outside of the usual helper in
373   * {@link HBaseTestingUtility#createWal(Configuration, Path, RegionInfo)} because that method
374   * doesn't play nicely with FaultyFileSystem. Call this method before overriding
375   * {@code fs.file.impl}.
376   * @param callingMethod a unique component for the path, probably the name of the test method.
377   */
378  private static WAL createWALCompatibleWithFaultyFileSystem(String callingMethod,
379      Configuration conf, TableName tableName) throws IOException {
380    final Path logDir = TEST_UTIL.getDataTestDirOnTestFS(callingMethod + ".log");
381    final Configuration walConf = new Configuration(conf);
382    FSUtils.setRootDir(walConf, logDir);
383    return new WALFactory(walConf, callingMethod)
384        .getWAL(RegionInfoBuilder.newBuilder(tableName).build());
385  }
386
387  @Test
388  public void testMemstoreSizeAccountingWithFailedPostBatchMutate() throws IOException {
389    String testName = "testMemstoreSizeAccountingWithFailedPostBatchMutate";
390    FileSystem fs = FileSystem.get(CONF);
391    Path rootDir = new Path(dir + testName);
392    FSHLog hLog = new FSHLog(fs, rootDir, testName, CONF);
393    HRegion region = initHRegion(tableName, null, null, false, Durability.SYNC_WAL, hLog,
394        COLUMN_FAMILY_BYTES);
395    HStore store = region.getStore(COLUMN_FAMILY_BYTES);
396    assertEquals(0, region.getMemStoreDataSize());
397
398    // Put one value
399    byte [] value = Bytes.toBytes(method);
400    Put put = new Put(value);
401    put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("abc"), value);
402    region.put(put);
403    long onePutSize = region.getMemStoreDataSize();
404    assertTrue(onePutSize > 0);
405
406    RegionCoprocessorHost mockedCPHost = Mockito.mock(RegionCoprocessorHost.class);
407    doThrow(new IOException())
408       .when(mockedCPHost).postBatchMutate(Mockito.<MiniBatchOperationInProgress<Mutation>>any());
409    region.setCoprocessorHost(mockedCPHost);
410
411    put = new Put(value);
412    put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("dfg"), value);
413    try {
414      region.put(put);
415      fail("Should have failed with IOException");
416    } catch (IOException expected) {
417    }
418    long expectedSize = onePutSize * 2;
419    assertEquals("memstoreSize should be incremented",
420        expectedSize, region.getMemStoreDataSize());
421    assertEquals("flushable size should be incremented",
422        expectedSize, store.getFlushableSize().getDataSize());
423
424    region.setCoprocessorHost(null);
425    HBaseTestingUtility.closeRegionAndWAL(region);
426  }
427
428  /**
429   * Test we do not lose data if we fail a flush and then close.
430   * Part of HBase-10466.  Tests the following from the issue description:
431   * "Bug 1: Wrong calculation of HRegion.memstoreSize: When a flush fails, data to be flushed is
432   * kept in each MemStore's snapshot and wait for next flush attempt to continue on it. But when
433   * the next flush succeeds, the counter of total memstore size in HRegion is always deduced by
434   * the sum of current memstore sizes instead of snapshots left from previous failed flush. This
435   * calculation is problematic that almost every time there is failed flush, HRegion.memstoreSize
436   * gets reduced by a wrong value. If region flush could not proceed for a couple cycles, the size
437   * in current memstore could be much larger than the snapshot. It's likely to drift memstoreSize
438   * much smaller than expected. In extreme case, if the error accumulates to even bigger than
439   * HRegion's memstore size limit, any further flush is skipped because flush does not do anything
440   * if memstoreSize is not larger than 0."
441   * @throws Exception
442   */
443  @Test
444  public void testFlushSizeAccounting() throws Exception {
445    final Configuration conf = HBaseConfiguration.create(CONF);
446    final WAL wal = createWALCompatibleWithFaultyFileSystem(method, conf, tableName);
447    // Only retry once.
448    conf.setInt("hbase.hstore.flush.retries.number", 1);
449    final User user =
450      User.createUserForTesting(conf, method, new String[]{"foo"});
451    // Inject our faulty LocalFileSystem
452    conf.setClass("fs.file.impl", FaultyFileSystem.class, FileSystem.class);
453    user.runAs(new PrivilegedExceptionAction<Object>() {
454      @Override
455      public Object run() throws Exception {
456        // Make sure it worked (above is sensitive to caching details in hadoop core)
457        FileSystem fs = FileSystem.get(conf);
458        Assert.assertEquals(FaultyFileSystem.class, fs.getClass());
459        FaultyFileSystem ffs = (FaultyFileSystem)fs;
460        HRegion region = null;
461        try {
462          // Initialize region
463          region = initHRegion(tableName, null, null, false, Durability.SYNC_WAL, wal,
464              COLUMN_FAMILY_BYTES);
465          long size = region.getMemStoreDataSize();
466          Assert.assertEquals(0, size);
467          // Put one item into memstore.  Measure the size of one item in memstore.
468          Put p1 = new Put(row);
469          p1.add(new KeyValue(row, COLUMN_FAMILY_BYTES, qual1, 1, (byte[]) null));
470          region.put(p1);
471          final long sizeOfOnePut = region.getMemStoreDataSize();
472          // Fail a flush which means the current memstore will hang out as memstore 'snapshot'.
473          try {
474            LOG.info("Flushing");
475            region.flush(true);
476            Assert.fail("Didn't bubble up IOE!");
477          } catch (DroppedSnapshotException dse) {
478            // What we are expecting
479            region.closing.set(false); // this is needed for the rest of the test to work
480          }
481          // Make it so all writes succeed from here on out
482          ffs.fault.set(false);
483          // Check sizes.  Should still be the one entry.
484          Assert.assertEquals(sizeOfOnePut, region.getMemStoreDataSize());
485          // Now add two entries so that on this next flush that fails, we can see if we
486          // subtract the right amount, the snapshot size only.
487          Put p2 = new Put(row);
488          p2.add(new KeyValue(row, COLUMN_FAMILY_BYTES, qual2, 2, (byte[])null));
489          p2.add(new KeyValue(row, COLUMN_FAMILY_BYTES, qual3, 3, (byte[])null));
490          region.put(p2);
491          long expectedSize = sizeOfOnePut * 3;
492          Assert.assertEquals(expectedSize, region.getMemStoreDataSize());
493          // Do a successful flush.  It will clear the snapshot only.  Thats how flushes work.
494          // If already a snapshot, we clear it else we move the memstore to be snapshot and flush
495          // it
496          region.flush(true);
497          // Make sure our memory accounting is right.
498          Assert.assertEquals(sizeOfOnePut * 2, region.getMemStoreDataSize());
499        } finally {
500          HBaseTestingUtility.closeRegionAndWAL(region);
501        }
502        return null;
503      }
504    });
505    FileSystem.closeAllForUGI(user.getUGI());
506  }
507
508  @Test
509  public void testCloseWithFailingFlush() throws Exception {
510    final Configuration conf = HBaseConfiguration.create(CONF);
511    final WAL wal = createWALCompatibleWithFaultyFileSystem(method, conf, tableName);
512    // Only retry once.
513    conf.setInt("hbase.hstore.flush.retries.number", 1);
514    final User user =
515      User.createUserForTesting(conf, this.method, new String[]{"foo"});
516    // Inject our faulty LocalFileSystem
517    conf.setClass("fs.file.impl", FaultyFileSystem.class, FileSystem.class);
518    user.runAs(new PrivilegedExceptionAction<Object>() {
519      @Override
520      public Object run() throws Exception {
521        // Make sure it worked (above is sensitive to caching details in hadoop core)
522        FileSystem fs = FileSystem.get(conf);
523        Assert.assertEquals(FaultyFileSystem.class, fs.getClass());
524        FaultyFileSystem ffs = (FaultyFileSystem)fs;
525        HRegion region = null;
526        try {
527          // Initialize region
528          region = initHRegion(tableName, null, null, false,
529              Durability.SYNC_WAL, wal, COLUMN_FAMILY_BYTES);
530          long size = region.getMemStoreDataSize();
531          Assert.assertEquals(0, size);
532          // Put one item into memstore.  Measure the size of one item in memstore.
533          Put p1 = new Put(row);
534          p1.add(new KeyValue(row, COLUMN_FAMILY_BYTES, qual1, 1, (byte[])null));
535          region.put(p1);
536          // Manufacture an outstanding snapshot -- fake a failed flush by doing prepare step only.
537          HStore store = region.getStore(COLUMN_FAMILY_BYTES);
538          StoreFlushContext storeFlushCtx =
539              store.createFlushContext(12345, FlushLifeCycleTracker.DUMMY);
540          storeFlushCtx.prepare();
541          // Now add two entries to the foreground memstore.
542          Put p2 = new Put(row);
543          p2.add(new KeyValue(row, COLUMN_FAMILY_BYTES, qual2, 2, (byte[])null));
544          p2.add(new KeyValue(row, COLUMN_FAMILY_BYTES, qual3, 3, (byte[])null));
545          region.put(p2);
546          // Now try close on top of a failing flush.
547          region.close();
548          fail();
549        } catch (DroppedSnapshotException dse) {
550          // Expected
551          LOG.info("Expected DroppedSnapshotException");
552        } finally {
553          // Make it so all writes succeed from here on out so can close clean
554          ffs.fault.set(false);
555          HBaseTestingUtility.closeRegionAndWAL(region);
556        }
557        return null;
558      }
559    });
560    FileSystem.closeAllForUGI(user.getUGI());
561  }
562
563  @Test
564  public void testCompactionAffectedByScanners() throws Exception {
565    byte[] family = Bytes.toBytes("family");
566    this.region = initHRegion(tableName, method, CONF, family);
567
568    Put put = new Put(Bytes.toBytes("r1"));
569    put.addColumn(family, Bytes.toBytes("q1"), Bytes.toBytes("v1"));
570    region.put(put);
571    region.flush(true);
572
573    Scan scan = new Scan();
574    scan.setMaxVersions(3);
575    // open the first scanner
576    RegionScanner scanner1 = region.getScanner(scan);
577
578    Delete delete = new Delete(Bytes.toBytes("r1"));
579    region.delete(delete);
580    region.flush(true);
581
582    // open the second scanner
583    RegionScanner scanner2 = region.getScanner(scan);
584
585    List<Cell> results = new ArrayList<>();
586
587    System.out.println("Smallest read point:" + region.getSmallestReadPoint());
588
589    // make a major compaction
590    region.compact(true);
591
592    // open the third scanner
593    RegionScanner scanner3 = region.getScanner(scan);
594
595    // get data from scanner 1, 2, 3 after major compaction
596    scanner1.next(results);
597    System.out.println(results);
598    assertEquals(1, results.size());
599
600    results.clear();
601    scanner2.next(results);
602    System.out.println(results);
603    assertEquals(0, results.size());
604
605    results.clear();
606    scanner3.next(results);
607    System.out.println(results);
608    assertEquals(0, results.size());
609  }
610
611  @Test
612  public void testToShowNPEOnRegionScannerReseek() throws Exception {
613    byte[] family = Bytes.toBytes("family");
614    this.region = initHRegion(tableName, method, CONF, family);
615
616    Put put = new Put(Bytes.toBytes("r1"));
617    put.addColumn(family, Bytes.toBytes("q1"), Bytes.toBytes("v1"));
618    region.put(put);
619    put = new Put(Bytes.toBytes("r2"));
620    put.addColumn(family, Bytes.toBytes("q1"), Bytes.toBytes("v1"));
621    region.put(put);
622    region.flush(true);
623
624    Scan scan = new Scan();
625    scan.setMaxVersions(3);
626    // open the first scanner
627    RegionScanner scanner1 = region.getScanner(scan);
628
629    System.out.println("Smallest read point:" + region.getSmallestReadPoint());
630
631    region.compact(true);
632
633    scanner1.reseek(Bytes.toBytes("r2"));
634    List<Cell> results = new ArrayList<>();
635    scanner1.next(results);
636    Cell keyValue = results.get(0);
637    Assert.assertTrue(Bytes.compareTo(CellUtil.cloneRow(keyValue), Bytes.toBytes("r2")) == 0);
638    scanner1.close();
639  }
640
641  @Test
642  public void testSkipRecoveredEditsReplay() throws Exception {
643    byte[] family = Bytes.toBytes("family");
644    this.region = initHRegion(tableName, method, CONF, family);
645    final WALFactory wals = new WALFactory(CONF, method);
646    try {
647      Path regiondir = region.getRegionFileSystem().getRegionDir();
648      FileSystem fs = region.getRegionFileSystem().getFileSystem();
649      byte[] regionName = region.getRegionInfo().getEncodedNameAsBytes();
650
651      Path recoveredEditsDir = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
652
653      long maxSeqId = 1050;
654      long minSeqId = 1000;
655
656      for (long i = minSeqId; i <= maxSeqId; i += 10) {
657        Path recoveredEdits = new Path(recoveredEditsDir, String.format("%019d", i));
658        fs.create(recoveredEdits);
659        WALProvider.Writer writer = wals.createRecoveredEditsWriter(fs, recoveredEdits);
660
661        long time = System.nanoTime();
662        WALEdit edit = new WALEdit();
663        edit.add(new KeyValue(row, family, Bytes.toBytes(i), time, KeyValue.Type.Put, Bytes
664            .toBytes(i)));
665        writer.append(new WAL.Entry(new WALKeyImpl(regionName, tableName, i, time,
666            HConstants.DEFAULT_CLUSTER_ID), edit));
667
668        writer.close();
669      }
670      MonitoredTask status = TaskMonitor.get().createStatus(method);
671      Map<byte[], Long> maxSeqIdInStores = new TreeMap<>(Bytes.BYTES_COMPARATOR);
672      for (HStore store : region.getStores()) {
673        maxSeqIdInStores.put(Bytes.toBytes(store.getColumnFamilyName()), minSeqId - 1);
674      }
675      long seqId = region.replayRecoveredEditsIfAny(regiondir, maxSeqIdInStores, null, status);
676      assertEquals(maxSeqId, seqId);
677      region.getMVCC().advanceTo(seqId);
678      Get get = new Get(row);
679      Result result = region.get(get);
680      for (long i = minSeqId; i <= maxSeqId; i += 10) {
681        List<Cell> kvs = result.getColumnCells(family, Bytes.toBytes(i));
682        assertEquals(1, kvs.size());
683        assertArrayEquals(Bytes.toBytes(i), CellUtil.cloneValue(kvs.get(0)));
684      }
685    } finally {
686      HBaseTestingUtility.closeRegionAndWAL(this.region);
687      this.region = null;
688      wals.close();
689    }
690  }
691
692  @Test
693  public void testSkipRecoveredEditsReplaySomeIgnored() throws Exception {
694    byte[] family = Bytes.toBytes("family");
695    this.region = initHRegion(tableName, method, CONF, family);
696    final WALFactory wals = new WALFactory(CONF, method);
697    try {
698      Path regiondir = region.getRegionFileSystem().getRegionDir();
699      FileSystem fs = region.getRegionFileSystem().getFileSystem();
700      byte[] regionName = region.getRegionInfo().getEncodedNameAsBytes();
701
702      Path recoveredEditsDir = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
703
704      long maxSeqId = 1050;
705      long minSeqId = 1000;
706
707      for (long i = minSeqId; i <= maxSeqId; i += 10) {
708        Path recoveredEdits = new Path(recoveredEditsDir, String.format("%019d", i));
709        fs.create(recoveredEdits);
710        WALProvider.Writer writer = wals.createRecoveredEditsWriter(fs, recoveredEdits);
711
712        long time = System.nanoTime();
713        WALEdit edit = new WALEdit();
714        edit.add(new KeyValue(row, family, Bytes.toBytes(i), time, KeyValue.Type.Put, Bytes
715            .toBytes(i)));
716        writer.append(new WAL.Entry(new WALKeyImpl(regionName, tableName, i, time,
717            HConstants.DEFAULT_CLUSTER_ID), edit));
718
719        writer.close();
720      }
721      long recoverSeqId = 1030;
722      MonitoredTask status = TaskMonitor.get().createStatus(method);
723      Map<byte[], Long> maxSeqIdInStores = new TreeMap<>(Bytes.BYTES_COMPARATOR);
724      for (HStore store : region.getStores()) {
725        maxSeqIdInStores.put(Bytes.toBytes(store.getColumnFamilyName()), recoverSeqId - 1);
726      }
727      long seqId = region.replayRecoveredEditsIfAny(regiondir, maxSeqIdInStores, null, status);
728      assertEquals(maxSeqId, seqId);
729      region.getMVCC().advanceTo(seqId);
730      Get get = new Get(row);
731      Result result = region.get(get);
732      for (long i = minSeqId; i <= maxSeqId; i += 10) {
733        List<Cell> kvs = result.getColumnCells(family, Bytes.toBytes(i));
734        if (i < recoverSeqId) {
735          assertEquals(0, kvs.size());
736        } else {
737          assertEquals(1, kvs.size());
738          assertArrayEquals(Bytes.toBytes(i), CellUtil.cloneValue(kvs.get(0)));
739        }
740      }
741    } finally {
742      HBaseTestingUtility.closeRegionAndWAL(this.region);
743      this.region = null;
744      wals.close();
745    }
746  }
747
748  @Test
749  public void testSkipRecoveredEditsReplayAllIgnored() throws Exception {
750    byte[] family = Bytes.toBytes("family");
751    this.region = initHRegion(tableName, method, CONF, family);
752    try {
753      Path regiondir = region.getRegionFileSystem().getRegionDir();
754      FileSystem fs = region.getRegionFileSystem().getFileSystem();
755
756      Path recoveredEditsDir = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
757      for (int i = 1000; i < 1050; i += 10) {
758        Path recoveredEdits = new Path(recoveredEditsDir, String.format("%019d", i));
759        FSDataOutputStream dos = fs.create(recoveredEdits);
760        dos.writeInt(i);
761        dos.close();
762      }
763      long minSeqId = 2000;
764      Path recoveredEdits = new Path(recoveredEditsDir, String.format("%019d", minSeqId - 1));
765      FSDataOutputStream dos = fs.create(recoveredEdits);
766      dos.close();
767
768      Map<byte[], Long> maxSeqIdInStores = new TreeMap<>(Bytes.BYTES_COMPARATOR);
769      for (HStore store : region.getStores()) {
770        maxSeqIdInStores.put(Bytes.toBytes(store.getColumnFamilyName()), minSeqId);
771      }
772      long seqId = region.replayRecoveredEditsIfAny(regiondir, maxSeqIdInStores, null, null);
773      assertEquals(minSeqId, seqId);
774    } finally {
775      HBaseTestingUtility.closeRegionAndWAL(this.region);
776      this.region = null;
777    }
778  }
779
780  @Test
781  public void testSkipRecoveredEditsReplayTheLastFileIgnored() throws Exception {
782    byte[] family = Bytes.toBytes("family");
783    this.region = initHRegion(tableName, method, CONF, family);
784    final WALFactory wals = new WALFactory(CONF, method);
785    try {
786      Path regiondir = region.getRegionFileSystem().getRegionDir();
787      FileSystem fs = region.getRegionFileSystem().getFileSystem();
788      byte[] regionName = region.getRegionInfo().getEncodedNameAsBytes();
789      byte[][] columns = region.getTableDescriptor().getColumnFamilyNames().toArray(new byte[0][]);
790
791      assertEquals(0, region.getStoreFileList(columns).size());
792
793      Path recoveredEditsDir = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
794
795      long maxSeqId = 1050;
796      long minSeqId = 1000;
797
798      for (long i = minSeqId; i <= maxSeqId; i += 10) {
799        Path recoveredEdits = new Path(recoveredEditsDir, String.format("%019d", i));
800        fs.create(recoveredEdits);
801        WALProvider.Writer writer = wals.createRecoveredEditsWriter(fs, recoveredEdits);
802
803        long time = System.nanoTime();
804        WALEdit edit = null;
805        if (i == maxSeqId) {
806          edit = WALEdit.createCompaction(region.getRegionInfo(),
807          CompactionDescriptor.newBuilder()
808          .setTableName(ByteString.copyFrom(tableName.getName()))
809          .setFamilyName(ByteString.copyFrom(regionName))
810          .setEncodedRegionName(ByteString.copyFrom(regionName))
811          .setStoreHomeDirBytes(ByteString.copyFrom(Bytes.toBytes(regiondir.toString())))
812          .setRegionName(ByteString.copyFrom(region.getRegionInfo().getRegionName()))
813          .build());
814        } else {
815          edit = new WALEdit();
816          edit.add(new KeyValue(row, family, Bytes.toBytes(i), time, KeyValue.Type.Put, Bytes
817            .toBytes(i)));
818        }
819        writer.append(new WAL.Entry(new WALKeyImpl(regionName, tableName, i, time,
820            HConstants.DEFAULT_CLUSTER_ID), edit));
821        writer.close();
822      }
823
824      long recoverSeqId = 1030;
825      Map<byte[], Long> maxSeqIdInStores = new TreeMap<>(Bytes.BYTES_COMPARATOR);
826      MonitoredTask status = TaskMonitor.get().createStatus(method);
827      for (HStore store : region.getStores()) {
828        maxSeqIdInStores.put(Bytes.toBytes(store.getColumnFamilyName()), recoverSeqId - 1);
829      }
830      long seqId = region.replayRecoveredEditsIfAny(regiondir, maxSeqIdInStores, null, status);
831      assertEquals(maxSeqId, seqId);
832
833      // assert that the files are flushed
834      assertEquals(1, region.getStoreFileList(columns).size());
835
836    } finally {
837      HBaseTestingUtility.closeRegionAndWAL(this.region);
838      this.region = null;
839      wals.close();
840    }
841  }
842
843  @Test
844  public void testRecoveredEditsReplayCompaction() throws Exception {
845    testRecoveredEditsReplayCompaction(false);
846    testRecoveredEditsReplayCompaction(true);
847  }
848
849  public void testRecoveredEditsReplayCompaction(boolean mismatchedRegionName) throws Exception {
850    CONF.setClass(HConstants.REGION_IMPL, HRegionForTesting.class, Region.class);
851    byte[] family = Bytes.toBytes("family");
852    this.region = initHRegion(tableName, method, CONF, family);
853    final WALFactory wals = new WALFactory(CONF, method);
854    try {
855      Path regiondir = region.getRegionFileSystem().getRegionDir();
856      FileSystem fs = region.getRegionFileSystem().getFileSystem();
857      byte[] regionName = region.getRegionInfo().getEncodedNameAsBytes();
858
859      long maxSeqId = 3;
860      long minSeqId = 0;
861
862      for (long i = minSeqId; i < maxSeqId; i++) {
863        Put put = new Put(Bytes.toBytes(i));
864        put.addColumn(family, Bytes.toBytes(i), Bytes.toBytes(i));
865        region.put(put);
866        region.flush(true);
867      }
868
869      // this will create a region with 3 files
870      assertEquals(3, region.getStore(family).getStorefilesCount());
871      List<Path> storeFiles = new ArrayList<>(3);
872      for (HStoreFile sf : region.getStore(family).getStorefiles()) {
873        storeFiles.add(sf.getPath());
874      }
875
876      // disable compaction completion
877      CONF.setBoolean("hbase.hstore.compaction.complete", false);
878      region.compactStores();
879
880      // ensure that nothing changed
881      assertEquals(3, region.getStore(family).getStorefilesCount());
882
883      // now find the compacted file, and manually add it to the recovered edits
884      Path tmpDir = new Path(region.getRegionFileSystem().getTempDir(), Bytes.toString(family));
885      FileStatus[] files = FSUtils.listStatus(fs, tmpDir);
886      String errorMsg = "Expected to find 1 file in the region temp directory "
887          + "from the compaction, could not find any";
888      assertNotNull(errorMsg, files);
889      assertEquals(errorMsg, 1, files.length);
890      // move the file inside region dir
891      Path newFile = region.getRegionFileSystem().commitStoreFile(Bytes.toString(family),
892          files[0].getPath());
893
894      byte[] encodedNameAsBytes = this.region.getRegionInfo().getEncodedNameAsBytes();
895      byte[] fakeEncodedNameAsBytes = new byte [encodedNameAsBytes.length];
896      for (int i=0; i < encodedNameAsBytes.length; i++) {
897        // Mix the byte array to have a new encodedName
898        fakeEncodedNameAsBytes[i] = (byte) (encodedNameAsBytes[i] + 1);
899      }
900
901      CompactionDescriptor compactionDescriptor = ProtobufUtil.toCompactionDescriptor(this.region
902        .getRegionInfo(), mismatchedRegionName ? fakeEncodedNameAsBytes : null, family,
903            storeFiles, Lists.newArrayList(newFile),
904            region.getRegionFileSystem().getStoreDir(Bytes.toString(family)));
905
906      WALUtil.writeCompactionMarker(region.getWAL(), this.region.getReplicationScope(),
907          this.region.getRegionInfo(), compactionDescriptor, region.getMVCC());
908
909      Path recoveredEditsDir = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
910
911      Path recoveredEdits = new Path(recoveredEditsDir, String.format("%019d", 1000));
912      fs.create(recoveredEdits);
913      WALProvider.Writer writer = wals.createRecoveredEditsWriter(fs, recoveredEdits);
914
915      long time = System.nanoTime();
916
917      writer.append(new WAL.Entry(new WALKeyImpl(regionName, tableName, 10, time,
918          HConstants.DEFAULT_CLUSTER_ID), WALEdit.createCompaction(region.getRegionInfo(),
919          compactionDescriptor)));
920      writer.close();
921
922      // close the region now, and reopen again
923      region.getTableDescriptor();
924      region.getRegionInfo();
925      region.close();
926      try {
927        region = HRegion.openHRegion(region, null);
928      } catch (WrongRegionException wre) {
929        fail("Matching encoded region name should not have produced WrongRegionException");
930      }
931
932      // now check whether we have only one store file, the compacted one
933      Collection<HStoreFile> sfs = region.getStore(family).getStorefiles();
934      for (HStoreFile sf : sfs) {
935        LOG.info(Objects.toString(sf.getPath()));
936      }
937      if (!mismatchedRegionName) {
938        assertEquals(1, region.getStore(family).getStorefilesCount());
939      }
940      files = FSUtils.listStatus(fs, tmpDir);
941      assertTrue("Expected to find 0 files inside " + tmpDir, files == null || files.length == 0);
942
943      for (long i = minSeqId; i < maxSeqId; i++) {
944        Get get = new Get(Bytes.toBytes(i));
945        Result result = region.get(get);
946        byte[] value = result.getValue(family, Bytes.toBytes(i));
947        assertArrayEquals(Bytes.toBytes(i), value);
948      }
949    } finally {
950      HBaseTestingUtility.closeRegionAndWAL(this.region);
951      this.region = null;
952      wals.close();
953      CONF.setClass(HConstants.REGION_IMPL, HRegion.class, Region.class);
954    }
955  }
956
957  @Test
958  public void testFlushMarkers() throws Exception {
959    // tests that flush markers are written to WAL and handled at recovered edits
960    byte[] family = Bytes.toBytes("family");
961    Path logDir = TEST_UTIL.getDataTestDirOnTestFS(method + ".log");
962    final Configuration walConf = new Configuration(TEST_UTIL.getConfiguration());
963    FSUtils.setRootDir(walConf, logDir);
964    final WALFactory wals = new WALFactory(walConf, method);
965    final WAL wal = wals.getWAL(RegionInfoBuilder.newBuilder(tableName).build());
966
967    this.region = initHRegion(tableName, HConstants.EMPTY_START_ROW,
968      HConstants.EMPTY_END_ROW, false, Durability.USE_DEFAULT, wal, family);
969    try {
970      Path regiondir = region.getRegionFileSystem().getRegionDir();
971      FileSystem fs = region.getRegionFileSystem().getFileSystem();
972      byte[] regionName = region.getRegionInfo().getEncodedNameAsBytes();
973
974      long maxSeqId = 3;
975      long minSeqId = 0;
976
977      for (long i = minSeqId; i < maxSeqId; i++) {
978        Put put = new Put(Bytes.toBytes(i));
979        put.addColumn(family, Bytes.toBytes(i), Bytes.toBytes(i));
980        region.put(put);
981        region.flush(true);
982      }
983
984      // this will create a region with 3 files from flush
985      assertEquals(3, region.getStore(family).getStorefilesCount());
986      List<String> storeFiles = new ArrayList<>(3);
987      for (HStoreFile sf : region.getStore(family).getStorefiles()) {
988        storeFiles.add(sf.getPath().getName());
989      }
990
991      // now verify that the flush markers are written
992      wal.shutdown();
993      WAL.Reader reader = WALFactory.createReader(fs, AbstractFSWALProvider.getCurrentFileName(wal),
994        TEST_UTIL.getConfiguration());
995      try {
996        List<WAL.Entry> flushDescriptors = new ArrayList<>();
997        long lastFlushSeqId = -1;
998        while (true) {
999          WAL.Entry entry = reader.next();
1000          if (entry == null) {
1001            break;
1002          }
1003          Cell cell = entry.getEdit().getCells().get(0);
1004          if (WALEdit.isMetaEditFamily(cell)) {
1005            FlushDescriptor flushDesc = WALEdit.getFlushDescriptor(cell);
1006            assertNotNull(flushDesc);
1007            assertArrayEquals(tableName.getName(), flushDesc.getTableName().toByteArray());
1008            if (flushDesc.getAction() == FlushAction.START_FLUSH) {
1009              assertTrue(flushDesc.getFlushSequenceNumber() > lastFlushSeqId);
1010            } else if (flushDesc.getAction() == FlushAction.COMMIT_FLUSH) {
1011              assertTrue(flushDesc.getFlushSequenceNumber() == lastFlushSeqId);
1012            }
1013            lastFlushSeqId = flushDesc.getFlushSequenceNumber();
1014            assertArrayEquals(regionName, flushDesc.getEncodedRegionName().toByteArray());
1015            assertEquals(1, flushDesc.getStoreFlushesCount()); //only one store
1016            StoreFlushDescriptor storeFlushDesc = flushDesc.getStoreFlushes(0);
1017            assertArrayEquals(family, storeFlushDesc.getFamilyName().toByteArray());
1018            assertEquals("family", storeFlushDesc.getStoreHomeDir());
1019            if (flushDesc.getAction() == FlushAction.START_FLUSH) {
1020              assertEquals(0, storeFlushDesc.getFlushOutputCount());
1021            } else {
1022              assertEquals(1, storeFlushDesc.getFlushOutputCount()); //only one file from flush
1023              assertTrue(storeFiles.contains(storeFlushDesc.getFlushOutput(0)));
1024            }
1025
1026            flushDescriptors.add(entry);
1027          }
1028        }
1029
1030        assertEquals(3 * 2, flushDescriptors.size()); // START_FLUSH and COMMIT_FLUSH per flush
1031
1032        // now write those markers to the recovered edits again.
1033
1034        Path recoveredEditsDir = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
1035
1036        Path recoveredEdits = new Path(recoveredEditsDir, String.format("%019d", 1000));
1037        fs.create(recoveredEdits);
1038        WALProvider.Writer writer = wals.createRecoveredEditsWriter(fs, recoveredEdits);
1039
1040        for (WAL.Entry entry : flushDescriptors) {
1041          writer.append(entry);
1042        }
1043        writer.close();
1044      } finally {
1045        if (null != reader) {
1046          try {
1047            reader.close();
1048          } catch (IOException exception) {
1049            LOG.warn("Problem closing wal: " + exception.getMessage());
1050            LOG.debug("exception details", exception);
1051          }
1052        }
1053      }
1054
1055
1056      // close the region now, and reopen again
1057      region.close();
1058      region = HRegion.openHRegion(region, null);
1059
1060      // now check whether we have can read back the data from region
1061      for (long i = minSeqId; i < maxSeqId; i++) {
1062        Get get = new Get(Bytes.toBytes(i));
1063        Result result = region.get(get);
1064        byte[] value = result.getValue(family, Bytes.toBytes(i));
1065        assertArrayEquals(Bytes.toBytes(i), value);
1066      }
1067    } finally {
1068      HBaseTestingUtility.closeRegionAndWAL(this.region);
1069      this.region = null;
1070      wals.close();
1071    }
1072  }
1073
1074  static class IsFlushWALMarker implements ArgumentMatcher<WALEdit> {
1075    volatile FlushAction[] actions;
1076    public IsFlushWALMarker(FlushAction... actions) {
1077      this.actions = actions;
1078    }
1079    @Override
1080    public boolean matches(WALEdit edit) {
1081      List<Cell> cells = edit.getCells();
1082      if (cells.isEmpty()) {
1083        return false;
1084      }
1085      if (WALEdit.isMetaEditFamily(cells.get(0))) {
1086        FlushDescriptor desc;
1087        try {
1088          desc = WALEdit.getFlushDescriptor(cells.get(0));
1089        } catch (IOException e) {
1090          LOG.warn(e.toString(), e);
1091          return false;
1092        }
1093        if (desc != null) {
1094          for (FlushAction action : actions) {
1095            if (desc.getAction() == action) {
1096              return true;
1097            }
1098          }
1099        }
1100      }
1101      return false;
1102    }
1103    public IsFlushWALMarker set(FlushAction... actions) {
1104      this.actions = actions;
1105      return this;
1106    }
1107  }
1108
1109  @Test
1110  public void testFlushMarkersWALFail() throws Exception {
1111    // test the cases where the WAL append for flush markers fail.
1112    byte[] family = Bytes.toBytes("family");
1113
1114    // spy an actual WAL implementation to throw exception (was not able to mock)
1115    Path logDir = TEST_UTIL.getDataTestDirOnTestFS(method + "log");
1116
1117    final Configuration walConf = new Configuration(TEST_UTIL.getConfiguration());
1118    FSUtils.setRootDir(walConf, logDir);
1119    // Make up a WAL that we can manipulate at append time.
1120    class FailAppendFlushMarkerWAL extends FSHLog {
1121      volatile FlushAction [] flushActions = null;
1122
1123      public FailAppendFlushMarkerWAL(FileSystem fs, Path root, String logDir, Configuration conf)
1124      throws IOException {
1125        super(fs, root, logDir, conf);
1126      }
1127
1128      @Override
1129      protected Writer createWriterInstance(Path path) throws IOException {
1130        final Writer w = super.createWriterInstance(path);
1131        return new Writer() {
1132          @Override
1133          public void close() throws IOException {
1134            w.close();
1135          }
1136
1137          @Override
1138          public void sync() throws IOException {
1139            w.sync();
1140          }
1141
1142          @Override
1143          public void append(Entry entry) throws IOException {
1144            List<Cell> cells = entry.getEdit().getCells();
1145            if (WALEdit.isMetaEditFamily(cells.get(0))) {
1146              FlushDescriptor desc = WALEdit.getFlushDescriptor(cells.get(0));
1147              if (desc != null) {
1148                for (FlushAction flushAction: flushActions) {
1149                  if (desc.getAction().equals(flushAction)) {
1150                    throw new IOException("Failed to append flush marker! " + flushAction);
1151                  }
1152                }
1153              }
1154            }
1155            w.append(entry);
1156          }
1157
1158          @Override
1159          public long getLength() {
1160            return w.getLength();
1161          }
1162        };
1163      }
1164    }
1165    FailAppendFlushMarkerWAL wal =
1166      new FailAppendFlushMarkerWAL(FileSystem.get(walConf), FSUtils.getRootDir(walConf),
1167        method, walConf);
1168    this.region = initHRegion(tableName, HConstants.EMPTY_START_ROW,
1169      HConstants.EMPTY_END_ROW, false, Durability.USE_DEFAULT, wal, family);
1170    try {
1171      int i = 0;
1172      Put put = new Put(Bytes.toBytes(i));
1173      put.setDurability(Durability.SKIP_WAL); // have to skip mocked wal
1174      put.addColumn(family, Bytes.toBytes(i), Bytes.toBytes(i));
1175      region.put(put);
1176
1177      // 1. Test case where START_FLUSH throws exception
1178      wal.flushActions = new FlushAction [] {FlushAction.START_FLUSH};
1179
1180      // start cache flush will throw exception
1181      try {
1182        region.flush(true);
1183        fail("This should have thrown exception");
1184      } catch (DroppedSnapshotException unexpected) {
1185        // this should not be a dropped snapshot exception. Meaning that RS will not abort
1186        throw unexpected;
1187      } catch (IOException expected) {
1188        // expected
1189      }
1190      // The WAL is hosed now. It has two edits appended. We cannot roll the log without it
1191      // throwing a DroppedSnapshotException to force an abort. Just clean up the mess.
1192      region.close(true);
1193      wal.close();
1194
1195      // 2. Test case where START_FLUSH succeeds but COMMIT_FLUSH will throw exception
1196      wal.flushActions = new FlushAction [] {FlushAction.COMMIT_FLUSH};
1197      wal = new FailAppendFlushMarkerWAL(FileSystem.get(walConf), FSUtils.getRootDir(walConf),
1198            method, walConf);
1199
1200      this.region = initHRegion(tableName, HConstants.EMPTY_START_ROW,
1201        HConstants.EMPTY_END_ROW, false, Durability.USE_DEFAULT, wal, family);
1202      region.put(put);
1203
1204      // 3. Test case where ABORT_FLUSH will throw exception.
1205      // Even if ABORT_FLUSH throws exception, we should not fail with IOE, but continue with
1206      // DroppedSnapshotException. Below COMMMIT_FLUSH will cause flush to abort
1207      wal.flushActions = new FlushAction [] {FlushAction.COMMIT_FLUSH, FlushAction.ABORT_FLUSH};
1208
1209      try {
1210        region.flush(true);
1211        fail("This should have thrown exception");
1212      } catch (DroppedSnapshotException expected) {
1213        // we expect this exception, since we were able to write the snapshot, but failed to
1214        // write the flush marker to WAL
1215      } catch (IOException unexpected) {
1216        throw unexpected;
1217      }
1218
1219    } finally {
1220      HBaseTestingUtility.closeRegionAndWAL(this.region);
1221      this.region = null;
1222    }
1223  }
1224
1225  @Test
1226  public void testGetWhileRegionClose() throws IOException {
1227    Configuration hc = initSplit();
1228    int numRows = 100;
1229    byte[][] families = { fam1, fam2, fam3 };
1230
1231    // Setting up region
1232    this.region = initHRegion(tableName, method, hc, families);
1233    try {
1234      // Put data in region
1235      final int startRow = 100;
1236      putData(startRow, numRows, qual1, families);
1237      putData(startRow, numRows, qual2, families);
1238      putData(startRow, numRows, qual3, families);
1239      final AtomicBoolean done = new AtomicBoolean(false);
1240      final AtomicInteger gets = new AtomicInteger(0);
1241      GetTillDoneOrException[] threads = new GetTillDoneOrException[10];
1242      try {
1243        // Set ten threads running concurrently getting from the region.
1244        for (int i = 0; i < threads.length / 2; i++) {
1245          threads[i] = new GetTillDoneOrException(i, Bytes.toBytes("" + startRow), done, gets);
1246          threads[i].setDaemon(true);
1247          threads[i].start();
1248        }
1249        // Artificially make the condition by setting closing flag explicitly.
1250        // I can't make the issue happen with a call to region.close().
1251        this.region.closing.set(true);
1252        for (int i = threads.length / 2; i < threads.length; i++) {
1253          threads[i] = new GetTillDoneOrException(i, Bytes.toBytes("" + startRow), done, gets);
1254          threads[i].setDaemon(true);
1255          threads[i].start();
1256        }
1257      } finally {
1258        if (this.region != null) {
1259          HBaseTestingUtility.closeRegionAndWAL(this.region);
1260        }
1261      }
1262      done.set(true);
1263      for (GetTillDoneOrException t : threads) {
1264        try {
1265          t.join();
1266        } catch (InterruptedException e) {
1267          e.printStackTrace();
1268        }
1269        if (t.e != null) {
1270          LOG.info("Exception=" + t.e);
1271          assertFalse("Found a NPE in " + t.getName(), t.e instanceof NullPointerException);
1272        }
1273      }
1274    } finally {
1275      HBaseTestingUtility.closeRegionAndWAL(this.region);
1276      this.region = null;
1277    }
1278  }
1279
1280  /*
1281   * Thread that does get on single row until 'done' flag is flipped. If an
1282   * exception causes us to fail, it records it.
1283   */
1284  class GetTillDoneOrException extends Thread {
1285    private final Get g;
1286    private final AtomicBoolean done;
1287    private final AtomicInteger count;
1288    private Exception e;
1289
1290    GetTillDoneOrException(final int i, final byte[] r, final AtomicBoolean d,
1291        final AtomicInteger c) {
1292      super("getter." + i);
1293      this.g = new Get(r);
1294      this.done = d;
1295      this.count = c;
1296    }
1297
1298    @Override
1299    public void run() {
1300      while (!this.done.get()) {
1301        try {
1302          assertTrue(region.get(g).size() > 0);
1303          this.count.incrementAndGet();
1304        } catch (Exception e) {
1305          this.e = e;
1306          break;
1307        }
1308      }
1309    }
1310  }
1311
1312  /*
1313   * An involved filter test. Has multiple column families and deletes in mix.
1314   */
1315  @Test
1316  public void testWeirdCacheBehaviour() throws Exception {
1317    final TableName tableName = TableName.valueOf(name.getMethodName());
1318    byte[][] FAMILIES = new byte[][] { Bytes.toBytes("trans-blob"), Bytes.toBytes("trans-type"),
1319        Bytes.toBytes("trans-date"), Bytes.toBytes("trans-tags"), Bytes.toBytes("trans-group") };
1320    this.region = initHRegion(tableName, method, CONF, FAMILIES);
1321    try {
1322      String value = "this is the value";
1323      String value2 = "this is some other value";
1324      String keyPrefix1 = "prefix1";
1325      String keyPrefix2 = "prefix2";
1326      String keyPrefix3 = "prefix3";
1327      putRows(this.region, 3, value, keyPrefix1);
1328      putRows(this.region, 3, value, keyPrefix2);
1329      putRows(this.region, 3, value, keyPrefix3);
1330      putRows(this.region, 3, value2, keyPrefix1);
1331      putRows(this.region, 3, value2, keyPrefix2);
1332      putRows(this.region, 3, value2, keyPrefix3);
1333      System.out.println("Checking values for key: " + keyPrefix1);
1334      assertEquals("Got back incorrect number of rows from scan", 3,
1335          getNumberOfRows(keyPrefix1, value2, this.region));
1336      System.out.println("Checking values for key: " + keyPrefix2);
1337      assertEquals("Got back incorrect number of rows from scan", 3,
1338          getNumberOfRows(keyPrefix2, value2, this.region));
1339      System.out.println("Checking values for key: " + keyPrefix3);
1340      assertEquals("Got back incorrect number of rows from scan", 3,
1341          getNumberOfRows(keyPrefix3, value2, this.region));
1342      deleteColumns(this.region, value2, keyPrefix1);
1343      deleteColumns(this.region, value2, keyPrefix2);
1344      deleteColumns(this.region, value2, keyPrefix3);
1345      System.out.println("Starting important checks.....");
1346      assertEquals("Got back incorrect number of rows from scan: " + keyPrefix1, 0,
1347          getNumberOfRows(keyPrefix1, value2, this.region));
1348      assertEquals("Got back incorrect number of rows from scan: " + keyPrefix2, 0,
1349          getNumberOfRows(keyPrefix2, value2, this.region));
1350      assertEquals("Got back incorrect number of rows from scan: " + keyPrefix3, 0,
1351          getNumberOfRows(keyPrefix3, value2, this.region));
1352    } finally {
1353      HBaseTestingUtility.closeRegionAndWAL(this.region);
1354      this.region = null;
1355    }
1356  }
1357
1358  @Test
1359  public void testAppendWithReadOnlyTable() throws Exception {
1360    final TableName tableName = TableName.valueOf(name.getMethodName());
1361    this.region = initHRegion(tableName, method, CONF, true, Bytes.toBytes("somefamily"));
1362    boolean exceptionCaught = false;
1363    Append append = new Append(Bytes.toBytes("somerow"));
1364    append.setDurability(Durability.SKIP_WAL);
1365    append.addColumn(Bytes.toBytes("somefamily"), Bytes.toBytes("somequalifier"),
1366        Bytes.toBytes("somevalue"));
1367    try {
1368      region.append(append);
1369    } catch (IOException e) {
1370      exceptionCaught = true;
1371    } finally {
1372      HBaseTestingUtility.closeRegionAndWAL(this.region);
1373      this.region = null;
1374    }
1375    assertTrue(exceptionCaught == true);
1376  }
1377
1378  @Test
1379  public void testIncrWithReadOnlyTable() throws Exception {
1380    final TableName tableName = TableName.valueOf(name.getMethodName());
1381    this.region = initHRegion(tableName, method, CONF, true, Bytes.toBytes("somefamily"));
1382    boolean exceptionCaught = false;
1383    Increment inc = new Increment(Bytes.toBytes("somerow"));
1384    inc.setDurability(Durability.SKIP_WAL);
1385    inc.addColumn(Bytes.toBytes("somefamily"), Bytes.toBytes("somequalifier"), 1L);
1386    try {
1387      region.increment(inc);
1388    } catch (IOException e) {
1389      exceptionCaught = true;
1390    } finally {
1391      HBaseTestingUtility.closeRegionAndWAL(this.region);
1392      this.region = null;
1393    }
1394    assertTrue(exceptionCaught == true);
1395  }
1396
1397  private void deleteColumns(HRegion r, String value, String keyPrefix) throws IOException {
1398    InternalScanner scanner = buildScanner(keyPrefix, value, r);
1399    int count = 0;
1400    boolean more = false;
1401    List<Cell> results = new ArrayList<>();
1402    do {
1403      more = scanner.next(results);
1404      if (results != null && !results.isEmpty())
1405        count++;
1406      else
1407        break;
1408      Delete delete = new Delete(CellUtil.cloneRow(results.get(0)));
1409      delete.addColumn(Bytes.toBytes("trans-tags"), Bytes.toBytes("qual2"));
1410      r.delete(delete);
1411      results.clear();
1412    } while (more);
1413    assertEquals("Did not perform correct number of deletes", 3, count);
1414  }
1415
1416  private int getNumberOfRows(String keyPrefix, String value, HRegion r) throws Exception {
1417    InternalScanner resultScanner = buildScanner(keyPrefix, value, r);
1418    int numberOfResults = 0;
1419    List<Cell> results = new ArrayList<>();
1420    boolean more = false;
1421    do {
1422      more = resultScanner.next(results);
1423      if (results != null && !results.isEmpty())
1424        numberOfResults++;
1425      else
1426        break;
1427      for (Cell kv : results) {
1428        System.out.println("kv=" + kv.toString() + ", " + Bytes.toString(CellUtil.cloneValue(kv)));
1429      }
1430      results.clear();
1431    } while (more);
1432    return numberOfResults;
1433  }
1434
1435  private InternalScanner buildScanner(String keyPrefix, String value, HRegion r)
1436      throws IOException {
1437    // Defaults FilterList.Operator.MUST_PASS_ALL.
1438    FilterList allFilters = new FilterList();
1439    allFilters.addFilter(new PrefixFilter(Bytes.toBytes(keyPrefix)));
1440    // Only return rows where this column value exists in the row.
1441    SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("trans-tags"),
1442        Bytes.toBytes("qual2"), CompareOp.EQUAL, Bytes.toBytes(value));
1443    filter.setFilterIfMissing(true);
1444    allFilters.addFilter(filter);
1445    Scan scan = new Scan();
1446    scan.addFamily(Bytes.toBytes("trans-blob"));
1447    scan.addFamily(Bytes.toBytes("trans-type"));
1448    scan.addFamily(Bytes.toBytes("trans-date"));
1449    scan.addFamily(Bytes.toBytes("trans-tags"));
1450    scan.addFamily(Bytes.toBytes("trans-group"));
1451    scan.setFilter(allFilters);
1452    return r.getScanner(scan);
1453  }
1454
1455  private void putRows(HRegion r, int numRows, String value, String key) throws IOException {
1456    for (int i = 0; i < numRows; i++) {
1457      String row = key + "_" + i/* UUID.randomUUID().toString() */;
1458      System.out.println(String.format("Saving row: %s, with value %s", row, value));
1459      Put put = new Put(Bytes.toBytes(row));
1460      put.setDurability(Durability.SKIP_WAL);
1461      put.addColumn(Bytes.toBytes("trans-blob"), null, Bytes.toBytes("value for blob"));
1462      put.addColumn(Bytes.toBytes("trans-type"), null, Bytes.toBytes("statement"));
1463      put.addColumn(Bytes.toBytes("trans-date"), null, Bytes.toBytes("20090921010101999"));
1464      put.addColumn(Bytes.toBytes("trans-tags"), Bytes.toBytes("qual2"), Bytes.toBytes(value));
1465      put.addColumn(Bytes.toBytes("trans-group"), null, Bytes.toBytes("adhocTransactionGroupId"));
1466      r.put(put);
1467    }
1468  }
1469
1470  @Test
1471  public void testFamilyWithAndWithoutColon() throws Exception {
1472    byte[] cf = Bytes.toBytes(COLUMN_FAMILY);
1473    this.region = initHRegion(tableName, method, CONF, cf);
1474    try {
1475      Put p = new Put(tableName.toBytes());
1476      byte[] cfwithcolon = Bytes.toBytes(COLUMN_FAMILY + ":");
1477      p.addColumn(cfwithcolon, cfwithcolon, cfwithcolon);
1478      boolean exception = false;
1479      try {
1480        this.region.put(p);
1481      } catch (NoSuchColumnFamilyException e) {
1482        exception = true;
1483      }
1484      assertTrue(exception);
1485    } finally {
1486      HBaseTestingUtility.closeRegionAndWAL(this.region);
1487      this.region = null;
1488    }
1489  }
1490
1491  @Test
1492  public void testBatchPut_whileNoRowLocksHeld() throws IOException {
1493    final Put[] puts = new Put[10];
1494    MetricsWALSource source = CompatibilitySingletonFactory.getInstance(MetricsWALSource.class);
1495    try {
1496      long syncs = prepareRegionForBachPut(puts, source, false);
1497
1498      OperationStatus[] codes = this.region.batchMutate(puts);
1499      assertEquals(10, codes.length);
1500      for (int i = 0; i < 10; i++) {
1501        assertEquals(OperationStatusCode.SUCCESS, codes[i].getOperationStatusCode());
1502      }
1503      metricsAssertHelper.assertCounter("syncTimeNumOps", syncs + 1, source);
1504
1505      LOG.info("Next a batch put with one invalid family");
1506      puts[5].addColumn(Bytes.toBytes("BAD_CF"), qual, value);
1507      codes = this.region.batchMutate(puts);
1508      assertEquals(10, codes.length);
1509      for (int i = 0; i < 10; i++) {
1510        assertEquals((i == 5) ? OperationStatusCode.BAD_FAMILY : OperationStatusCode.SUCCESS,
1511            codes[i].getOperationStatusCode());
1512      }
1513
1514      metricsAssertHelper.assertCounter("syncTimeNumOps", syncs + 2, source);
1515    } finally {
1516      HBaseTestingUtility.closeRegionAndWAL(this.region);
1517      this.region = null;
1518    }
1519  }
1520
1521  @Test
1522  public void testBatchPut_whileMultipleRowLocksHeld() throws Exception {
1523    final Put[] puts = new Put[10];
1524    MetricsWALSource source = CompatibilitySingletonFactory.getInstance(MetricsWALSource.class);
1525    try {
1526      long syncs = prepareRegionForBachPut(puts, source, false);
1527
1528      puts[5].addColumn(Bytes.toBytes("BAD_CF"), qual, value);
1529
1530      LOG.info("batchPut will have to break into four batches to avoid row locks");
1531      RowLock rowLock1 = region.getRowLock(Bytes.toBytes("row_2"));
1532      RowLock rowLock2 = region.getRowLock(Bytes.toBytes("row_1"));
1533      RowLock rowLock3 = region.getRowLock(Bytes.toBytes("row_3"));
1534      RowLock rowLock4 = region.getRowLock(Bytes.toBytes("row_3"), true);
1535
1536      MultithreadedTestUtil.TestContext ctx = new MultithreadedTestUtil.TestContext(CONF);
1537      final AtomicReference<OperationStatus[]> retFromThread = new AtomicReference<>();
1538      final CountDownLatch startingPuts = new CountDownLatch(1);
1539      final CountDownLatch startingClose = new CountDownLatch(1);
1540      TestThread putter = new TestThread(ctx) {
1541        @Override
1542        public void doWork() throws IOException {
1543          startingPuts.countDown();
1544          retFromThread.set(region.batchMutate(puts));
1545        }
1546      };
1547      LOG.info("...starting put thread while holding locks");
1548      ctx.addThread(putter);
1549      ctx.startThreads();
1550
1551      // Now attempt to close the region from another thread.  Prior to HBASE-12565
1552      // this would cause the in-progress batchMutate operation to to fail with
1553      // exception because it use to release and re-acquire the close-guard lock
1554      // between batches.  Caller then didn't get status indicating which writes succeeded.
1555      // We now expect this thread to block until the batchMutate call finishes.
1556      Thread regionCloseThread = new TestThread(ctx) {
1557        @Override
1558        public void doWork() {
1559          try {
1560            startingPuts.await();
1561            // Give some time for the batch mutate to get in.
1562            // We don't want to race with the mutate
1563            Thread.sleep(10);
1564            startingClose.countDown();
1565            HBaseTestingUtility.closeRegionAndWAL(region);
1566          } catch (IOException e) {
1567            throw new RuntimeException(e);
1568          } catch (InterruptedException e) {
1569            throw new RuntimeException(e);
1570          }
1571        }
1572      };
1573      regionCloseThread.start();
1574
1575      startingClose.await();
1576      startingPuts.await();
1577      Thread.sleep(100);
1578      LOG.info("...releasing row lock 1, which should let put thread continue");
1579      rowLock1.release();
1580      rowLock2.release();
1581      rowLock3.release();
1582      waitForCounter(source, "syncTimeNumOps", syncs + 1);
1583
1584      LOG.info("...joining on put thread");
1585      ctx.stop();
1586      regionCloseThread.join();
1587
1588      OperationStatus[] codes = retFromThread.get();
1589      for (int i = 0; i < codes.length; i++) {
1590        assertEquals((i == 5) ? OperationStatusCode.BAD_FAMILY : OperationStatusCode.SUCCESS,
1591            codes[i].getOperationStatusCode());
1592      }
1593      rowLock4.release();
1594    } finally {
1595      HBaseTestingUtility.closeRegionAndWAL(this.region);
1596      this.region = null;
1597    }
1598  }
1599
1600  private void waitForCounter(MetricsWALSource source, String metricName, long expectedCount)
1601      throws InterruptedException {
1602    long startWait = System.currentTimeMillis();
1603    long currentCount;
1604    while ((currentCount = metricsAssertHelper.getCounter(metricName, source)) < expectedCount) {
1605      Thread.sleep(100);
1606      if (System.currentTimeMillis() - startWait > 10000) {
1607        fail(String.format("Timed out waiting for '%s' >= '%s', currentCount=%s", metricName,
1608            expectedCount, currentCount));
1609      }
1610    }
1611  }
1612
1613  @Test
1614  public void testAtomicBatchPut() throws IOException {
1615    final Put[] puts = new Put[10];
1616    MetricsWALSource source = CompatibilitySingletonFactory.getInstance(MetricsWALSource.class);
1617    try {
1618      long syncs = prepareRegionForBachPut(puts, source, false);
1619
1620      // 1. Straight forward case, should succeed
1621      MutationBatchOperation batchOp = new MutationBatchOperation(region, puts, true,
1622          HConstants.NO_NONCE, HConstants.NO_NONCE);
1623      OperationStatus[] codes = this.region.batchMutate(batchOp);
1624      assertEquals(10, codes.length);
1625      for (int i = 0; i < 10; i++) {
1626        assertEquals(OperationStatusCode.SUCCESS, codes[i].getOperationStatusCode());
1627      }
1628      metricsAssertHelper.assertCounter("syncTimeNumOps", syncs + 1, source);
1629
1630      // 2. Failed to get lock
1631      RowLock lock = region.getRowLock(Bytes.toBytes("row_" + 3));
1632      // Method {@link HRegion#getRowLock(byte[])} is reentrant. As 'row_3' is locked in this
1633      // thread, need to run {@link HRegion#batchMutate(HRegion.BatchOperation)} in different thread
1634      MultithreadedTestUtil.TestContext ctx = new MultithreadedTestUtil.TestContext(CONF);
1635      final AtomicReference<IOException> retFromThread = new AtomicReference<>();
1636      final CountDownLatch finishedPuts = new CountDownLatch(1);
1637      final MutationBatchOperation finalBatchOp = new MutationBatchOperation(region, puts, true,
1638          HConstants
1639          .NO_NONCE,
1640          HConstants.NO_NONCE);
1641      TestThread putter = new TestThread(ctx) {
1642        @Override
1643        public void doWork() throws IOException {
1644          try {
1645            region.batchMutate(finalBatchOp);
1646          } catch (IOException ioe) {
1647            LOG.error("test failed!", ioe);
1648            retFromThread.set(ioe);
1649          }
1650          finishedPuts.countDown();
1651        }
1652      };
1653      LOG.info("...starting put thread while holding locks");
1654      ctx.addThread(putter);
1655      ctx.startThreads();
1656      LOG.info("...waiting for batch puts while holding locks");
1657      try {
1658        finishedPuts.await();
1659      } catch (InterruptedException e) {
1660        LOG.error("Interrupted!", e);
1661      } finally {
1662        if (lock != null) {
1663          lock.release();
1664        }
1665      }
1666      assertNotNull(retFromThread.get());
1667      metricsAssertHelper.assertCounter("syncTimeNumOps", syncs + 1, source);
1668
1669      // 3. Exception thrown in validation
1670      LOG.info("Next a batch put with one invalid family");
1671      puts[5].addColumn(Bytes.toBytes("BAD_CF"), qual, value);
1672      batchOp = new MutationBatchOperation(region, puts, true, HConstants.NO_NONCE,
1673          HConstants.NO_NONCE);
1674      thrown.expect(NoSuchColumnFamilyException.class);
1675      this.region.batchMutate(batchOp);
1676    } finally {
1677      HBaseTestingUtility.closeRegionAndWAL(this.region);
1678      this.region = null;
1679    }
1680  }
1681
1682  @Test
1683  public void testBatchPutWithTsSlop() throws Exception {
1684    // add data with a timestamp that is too recent for range. Ensure assert
1685    CONF.setInt("hbase.hregion.keyvalue.timestamp.slop.millisecs", 1000);
1686    final Put[] puts = new Put[10];
1687    MetricsWALSource source = CompatibilitySingletonFactory.getInstance(MetricsWALSource.class);
1688
1689    try {
1690      long syncs = prepareRegionForBachPut(puts, source, true);
1691
1692      OperationStatus[] codes = this.region.batchMutate(puts);
1693      assertEquals(10, codes.length);
1694      for (int i = 0; i < 10; i++) {
1695        assertEquals(OperationStatusCode.SANITY_CHECK_FAILURE, codes[i].getOperationStatusCode());
1696      }
1697      metricsAssertHelper.assertCounter("syncTimeNumOps", syncs, source);
1698    } finally {
1699      HBaseTestingUtility.closeRegionAndWAL(this.region);
1700      this.region = null;
1701    }
1702  }
1703
1704  /**
1705   * @return syncs initial syncTimeNumOps
1706   */
1707  private long prepareRegionForBachPut(final Put[] puts, final MetricsWALSource source,
1708      boolean slop) throws IOException {
1709    this.region = initHRegion(tableName, method, CONF, COLUMN_FAMILY_BYTES);
1710
1711    LOG.info("First a batch put with all valid puts");
1712    for (int i = 0; i < puts.length; i++) {
1713      puts[i] = slop ? new Put(Bytes.toBytes("row_" + i), Long.MAX_VALUE - 100) :
1714          new Put(Bytes.toBytes("row_" + i));
1715      puts[i].addColumn(COLUMN_FAMILY_BYTES, qual, value);
1716    }
1717
1718    long syncs = metricsAssertHelper.getCounter("syncTimeNumOps", source);
1719    metricsAssertHelper.assertCounter("syncTimeNumOps", syncs, source);
1720    return syncs;
1721  }
1722
1723  // ////////////////////////////////////////////////////////////////////////////
1724  // checkAndMutate tests
1725  // ////////////////////////////////////////////////////////////////////////////
1726  @Test
1727  public void testCheckAndMutate_WithEmptyRowValue() throws IOException {
1728    byte[] row1 = Bytes.toBytes("row1");
1729    byte[] fam1 = Bytes.toBytes("fam1");
1730    byte[] qf1 = Bytes.toBytes("qualifier");
1731    byte[] emptyVal = new byte[] {};
1732    byte[] val1 = Bytes.toBytes("value1");
1733    byte[] val2 = Bytes.toBytes("value2");
1734
1735    // Setting up region
1736    this.region = initHRegion(tableName, method, CONF, fam1);
1737    try {
1738      // Putting empty data in key
1739      Put put = new Put(row1);
1740      put.addColumn(fam1, qf1, emptyVal);
1741
1742      // checkAndPut with empty value
1743      boolean res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(
1744          emptyVal), put);
1745      assertTrue(res);
1746
1747      // Putting data in key
1748      put = new Put(row1);
1749      put.addColumn(fam1, qf1, val1);
1750
1751      // checkAndPut with correct value
1752      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(emptyVal),
1753          put);
1754      assertTrue(res);
1755
1756      // not empty anymore
1757      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(emptyVal),
1758          put);
1759      assertFalse(res);
1760
1761      Delete delete = new Delete(row1);
1762      delete.addColumn(fam1, qf1);
1763      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(emptyVal),
1764          delete);
1765      assertFalse(res);
1766
1767      put = new Put(row1);
1768      put.addColumn(fam1, qf1, val2);
1769      // checkAndPut with correct value
1770      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(val1),
1771          put);
1772      assertTrue(res);
1773
1774      // checkAndDelete with correct value
1775      delete = new Delete(row1);
1776      delete.addColumn(fam1, qf1);
1777      delete.addColumn(fam1, qf1);
1778      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(val2),
1779          delete);
1780      assertTrue(res);
1781
1782      delete = new Delete(row1);
1783      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(emptyVal),
1784          delete);
1785      assertTrue(res);
1786
1787      // checkAndPut looking for a null value
1788      put = new Put(row1);
1789      put.addColumn(fam1, qf1, val1);
1790
1791      res = region
1792          .checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new NullComparator(), put);
1793      assertTrue(res);
1794    } finally {
1795      HBaseTestingUtility.closeRegionAndWAL(this.region);
1796      this.region = null;
1797    }
1798  }
1799
1800  @Test
1801  public void testCheckAndMutate_WithWrongValue() throws IOException {
1802    byte[] row1 = Bytes.toBytes("row1");
1803    byte[] fam1 = Bytes.toBytes("fam1");
1804    byte[] qf1 = Bytes.toBytes("qualifier");
1805    byte[] val1 = Bytes.toBytes("value1");
1806    byte[] val2 = Bytes.toBytes("value2");
1807    BigDecimal bd1 = new BigDecimal(Double.MAX_VALUE);
1808    BigDecimal bd2 = new BigDecimal(Double.MIN_VALUE);
1809
1810    // Setting up region
1811    this.region = initHRegion(tableName, method, CONF, fam1);
1812    try {
1813      // Putting data in key
1814      Put put = new Put(row1);
1815      put.addColumn(fam1, qf1, val1);
1816      region.put(put);
1817
1818      // checkAndPut with wrong value
1819      boolean res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(
1820          val2), put);
1821      assertEquals(false, res);
1822
1823      // checkAndDelete with wrong value
1824      Delete delete = new Delete(row1);
1825      delete.addFamily(fam1);
1826      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(val2),
1827          put);
1828      assertEquals(false, res);
1829
1830      // Putting data in key
1831      put = new Put(row1);
1832      put.addColumn(fam1, qf1, Bytes.toBytes(bd1));
1833      region.put(put);
1834
1835      // checkAndPut with wrong value
1836      res =
1837          region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BigDecimalComparator(
1838              bd2), put);
1839      assertEquals(false, res);
1840
1841      // checkAndDelete with wrong value
1842      delete = new Delete(row1);
1843      delete.addFamily(fam1);
1844      res =
1845          region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BigDecimalComparator(
1846              bd2), put);
1847      assertEquals(false, res);
1848    } finally {
1849      HBaseTestingUtility.closeRegionAndWAL(this.region);
1850      this.region = null;
1851    }
1852  }
1853
1854  @Test
1855  public void testCheckAndMutate_WithCorrectValue() throws IOException {
1856    byte[] row1 = Bytes.toBytes("row1");
1857    byte[] fam1 = Bytes.toBytes("fam1");
1858    byte[] qf1 = Bytes.toBytes("qualifier");
1859    byte[] val1 = Bytes.toBytes("value1");
1860    BigDecimal bd1 = new BigDecimal(Double.MIN_VALUE);
1861
1862    // Setting up region
1863    this.region = initHRegion(tableName, method, CONF, fam1);
1864    try {
1865      // Putting data in key
1866      Put put = new Put(row1);
1867      put.addColumn(fam1, qf1, val1);
1868      region.put(put);
1869
1870      // checkAndPut with correct value
1871      boolean res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(
1872          val1), put);
1873      assertEquals(true, res);
1874
1875      // checkAndDelete with correct value
1876      Delete delete = new Delete(row1);
1877      delete.addColumn(fam1, qf1);
1878      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(val1),
1879          delete);
1880      assertEquals(true, res);
1881
1882      // Putting data in key
1883      put = new Put(row1);
1884      put.addColumn(fam1, qf1, Bytes.toBytes(bd1));
1885      region.put(put);
1886
1887      // checkAndPut with correct value
1888      res =
1889          region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BigDecimalComparator(
1890              bd1), put);
1891      assertEquals(true, res);
1892
1893      // checkAndDelete with correct value
1894      delete = new Delete(row1);
1895      delete.addColumn(fam1, qf1);
1896      res =
1897          region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BigDecimalComparator(
1898              bd1), delete);
1899      assertEquals(true, res);
1900    } finally {
1901      HBaseTestingUtility.closeRegionAndWAL(this.region);
1902      this.region = null;
1903    }
1904  }
1905
1906  @Test
1907  public void testCheckAndMutate_WithNonEqualCompareOp() throws IOException {
1908    byte[] row1 = Bytes.toBytes("row1");
1909    byte[] fam1 = Bytes.toBytes("fam1");
1910    byte[] qf1 = Bytes.toBytes("qualifier");
1911    byte[] val1 = Bytes.toBytes("value1");
1912    byte[] val2 = Bytes.toBytes("value2");
1913    byte[] val3 = Bytes.toBytes("value3");
1914    byte[] val4 = Bytes.toBytes("value4");
1915
1916    // Setting up region
1917    this.region = initHRegion(tableName, method, CONF, fam1);
1918    try {
1919      // Putting val3 in key
1920      Put put = new Put(row1);
1921      put.addColumn(fam1, qf1, val3);
1922      region.put(put);
1923
1924      // Test CompareOp.LESS: original = val3, compare with val3, fail
1925      boolean res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.LESS,
1926          new BinaryComparator(val3), put);
1927      assertEquals(false, res);
1928
1929      // Test CompareOp.LESS: original = val3, compare with val4, fail
1930      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.LESS,
1931          new BinaryComparator(val4), put);
1932      assertEquals(false, res);
1933
1934      // Test CompareOp.LESS: original = val3, compare with val2,
1935      // succeed (now value = val2)
1936      put = new Put(row1);
1937      put.addColumn(fam1, qf1, val2);
1938      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.LESS,
1939          new BinaryComparator(val2), put);
1940      assertEquals(true, res);
1941
1942      // Test CompareOp.LESS_OR_EQUAL: original = val2, compare with val3, fail
1943      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.LESS_OR_EQUAL,
1944          new BinaryComparator(val3), put);
1945      assertEquals(false, res);
1946
1947      // Test CompareOp.LESS_OR_EQUAL: original = val2, compare with val2,
1948      // succeed (value still = val2)
1949      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.LESS_OR_EQUAL,
1950          new BinaryComparator(val2), put);
1951      assertEquals(true, res);
1952
1953      // Test CompareOp.LESS_OR_EQUAL: original = val2, compare with val1,
1954      // succeed (now value = val3)
1955      put = new Put(row1);
1956      put.addColumn(fam1, qf1, val3);
1957      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.LESS_OR_EQUAL,
1958          new BinaryComparator(val1), put);
1959      assertEquals(true, res);
1960
1961      // Test CompareOp.GREATER: original = val3, compare with val3, fail
1962      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.GREATER,
1963          new BinaryComparator(val3), put);
1964      assertEquals(false, res);
1965
1966      // Test CompareOp.GREATER: original = val3, compare with val2, fail
1967      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.GREATER,
1968          new BinaryComparator(val2), put);
1969      assertEquals(false, res);
1970
1971      // Test CompareOp.GREATER: original = val3, compare with val4,
1972      // succeed (now value = val2)
1973      put = new Put(row1);
1974      put.addColumn(fam1, qf1, val2);
1975      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.GREATER,
1976          new BinaryComparator(val4), put);
1977      assertEquals(true, res);
1978
1979      // Test CompareOp.GREATER_OR_EQUAL: original = val2, compare with val1, fail
1980      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.GREATER_OR_EQUAL,
1981          new BinaryComparator(val1), put);
1982      assertEquals(false, res);
1983
1984      // Test CompareOp.GREATER_OR_EQUAL: original = val2, compare with val2,
1985      // succeed (value still = val2)
1986      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.GREATER_OR_EQUAL,
1987          new BinaryComparator(val2), put);
1988      assertEquals(true, res);
1989
1990      // Test CompareOp.GREATER_OR_EQUAL: original = val2, compare with val3, succeed
1991      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.GREATER_OR_EQUAL,
1992          new BinaryComparator(val3), put);
1993      assertEquals(true, res);
1994    } finally {
1995      HBaseTestingUtility.closeRegionAndWAL(this.region);
1996      this.region = null;
1997    }
1998  }
1999
2000  @Test
2001  public void testCheckAndPut_ThatPutWasWritten() throws IOException {
2002    byte[] row1 = Bytes.toBytes("row1");
2003    byte[] fam1 = Bytes.toBytes("fam1");
2004    byte[] fam2 = Bytes.toBytes("fam2");
2005    byte[] qf1 = Bytes.toBytes("qualifier");
2006    byte[] val1 = Bytes.toBytes("value1");
2007    byte[] val2 = Bytes.toBytes("value2");
2008
2009    byte[][] families = { fam1, fam2 };
2010
2011    // Setting up region
2012    this.region = initHRegion(tableName, method, CONF, families);
2013    try {
2014      // Putting data in the key to check
2015      Put put = new Put(row1);
2016      put.addColumn(fam1, qf1, val1);
2017      region.put(put);
2018
2019      // Creating put to add
2020      long ts = System.currentTimeMillis();
2021      KeyValue kv = new KeyValue(row1, fam2, qf1, ts, KeyValue.Type.Put, val2);
2022      put = new Put(row1);
2023      put.add(kv);
2024
2025      // checkAndPut with wrong value
2026      boolean res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(
2027          val1), put);
2028      assertEquals(true, res);
2029
2030      Get get = new Get(row1);
2031      get.addColumn(fam2, qf1);
2032      Cell[] actual = region.get(get).rawCells();
2033
2034      Cell[] expected = { kv };
2035
2036      assertEquals(expected.length, actual.length);
2037      for (int i = 0; i < actual.length; i++) {
2038        assertEquals(expected[i], actual[i]);
2039      }
2040    } finally {
2041      HBaseTestingUtility.closeRegionAndWAL(this.region);
2042      this.region = null;
2043    }
2044  }
2045
2046  @Test
2047  public void testCheckAndPut_wrongRowInPut() throws IOException {
2048    this.region = initHRegion(tableName, method, CONF, COLUMNS);
2049    try {
2050      Put put = new Put(row2);
2051      put.addColumn(fam1, qual1, value1);
2052      try {
2053        region.checkAndMutate(row, fam1, qual1, CompareOperator.EQUAL,
2054            new BinaryComparator(value2), put);
2055        fail();
2056      } catch (org.apache.hadoop.hbase.DoNotRetryIOException expected) {
2057        // expected exception.
2058      }
2059    } finally {
2060      HBaseTestingUtility.closeRegionAndWAL(this.region);
2061      this.region = null;
2062    }
2063  }
2064
2065  @Test
2066  public void testCheckAndDelete_ThatDeleteWasWritten() throws IOException {
2067    byte[] row1 = Bytes.toBytes("row1");
2068    byte[] fam1 = Bytes.toBytes("fam1");
2069    byte[] fam2 = Bytes.toBytes("fam2");
2070    byte[] qf1 = Bytes.toBytes("qualifier1");
2071    byte[] qf2 = Bytes.toBytes("qualifier2");
2072    byte[] qf3 = Bytes.toBytes("qualifier3");
2073    byte[] val1 = Bytes.toBytes("value1");
2074    byte[] val2 = Bytes.toBytes("value2");
2075    byte[] val3 = Bytes.toBytes("value3");
2076    byte[] emptyVal = new byte[] {};
2077
2078    byte[][] families = { fam1, fam2 };
2079
2080    // Setting up region
2081    this.region = initHRegion(tableName, method, CONF, families);
2082    try {
2083      // Put content
2084      Put put = new Put(row1);
2085      put.addColumn(fam1, qf1, val1);
2086      region.put(put);
2087      Threads.sleep(2);
2088
2089      put = new Put(row1);
2090      put.addColumn(fam1, qf1, val2);
2091      put.addColumn(fam2, qf1, val3);
2092      put.addColumn(fam2, qf2, val2);
2093      put.addColumn(fam2, qf3, val1);
2094      put.addColumn(fam1, qf3, val1);
2095      region.put(put);
2096
2097      // Multi-column delete
2098      Delete delete = new Delete(row1);
2099      delete.addColumn(fam1, qf1);
2100      delete.addColumn(fam2, qf1);
2101      delete.addColumn(fam1, qf3);
2102      boolean res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(
2103          val2), delete);
2104      assertEquals(true, res);
2105
2106      Get get = new Get(row1);
2107      get.addColumn(fam1, qf1);
2108      get.addColumn(fam1, qf3);
2109      get.addColumn(fam2, qf2);
2110      Result r = region.get(get);
2111      assertEquals(2, r.size());
2112      assertArrayEquals(val1, r.getValue(fam1, qf1));
2113      assertArrayEquals(val2, r.getValue(fam2, qf2));
2114
2115      // Family delete
2116      delete = new Delete(row1);
2117      delete.addFamily(fam2);
2118      res = region.checkAndMutate(row1, fam2, qf1, CompareOperator.EQUAL, new BinaryComparator(emptyVal),
2119          delete);
2120      assertEquals(true, res);
2121
2122      get = new Get(row1);
2123      r = region.get(get);
2124      assertEquals(1, r.size());
2125      assertArrayEquals(val1, r.getValue(fam1, qf1));
2126
2127      // Row delete
2128      delete = new Delete(row1);
2129      res = region.checkAndMutate(row1, fam1, qf1, CompareOperator.EQUAL, new BinaryComparator(val1),
2130          delete);
2131      assertEquals(true, res);
2132      get = new Get(row1);
2133      r = region.get(get);
2134      assertEquals(0, r.size());
2135    } finally {
2136      HBaseTestingUtility.closeRegionAndWAL(this.region);
2137      this.region = null;
2138    }
2139  }
2140
2141  // ////////////////////////////////////////////////////////////////////////////
2142  // Delete tests
2143  // ////////////////////////////////////////////////////////////////////////////
2144  @Test
2145  public void testDelete_multiDeleteColumn() throws IOException {
2146    byte[] row1 = Bytes.toBytes("row1");
2147    byte[] fam1 = Bytes.toBytes("fam1");
2148    byte[] qual = Bytes.toBytes("qualifier");
2149    byte[] value = Bytes.toBytes("value");
2150
2151    Put put = new Put(row1);
2152    put.addColumn(fam1, qual, 1, value);
2153    put.addColumn(fam1, qual, 2, value);
2154
2155    this.region = initHRegion(tableName, method, CONF, fam1);
2156    try {
2157      region.put(put);
2158
2159      // We do support deleting more than 1 'latest' version
2160      Delete delete = new Delete(row1);
2161      delete.addColumn(fam1, qual);
2162      delete.addColumn(fam1, qual);
2163      region.delete(delete);
2164
2165      Get get = new Get(row1);
2166      get.addFamily(fam1);
2167      Result r = region.get(get);
2168      assertEquals(0, r.size());
2169    } finally {
2170      HBaseTestingUtility.closeRegionAndWAL(this.region);
2171      this.region = null;
2172    }
2173  }
2174
2175  @Test
2176  public void testDelete_CheckFamily() throws IOException {
2177    byte[] row1 = Bytes.toBytes("row1");
2178    byte[] fam1 = Bytes.toBytes("fam1");
2179    byte[] fam2 = Bytes.toBytes("fam2");
2180    byte[] fam3 = Bytes.toBytes("fam3");
2181    byte[] fam4 = Bytes.toBytes("fam4");
2182
2183    // Setting up region
2184    this.region = initHRegion(tableName, method, CONF, fam1, fam2, fam3);
2185    try {
2186      List<Cell> kvs = new ArrayList<>();
2187      kvs.add(new KeyValue(row1, fam4, null, null));
2188
2189      // testing existing family
2190      byte[] family = fam2;
2191      try {
2192        NavigableMap<byte[], List<Cell>> deleteMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
2193        deleteMap.put(family, kvs);
2194        region.delete(deleteMap, Durability.SYNC_WAL);
2195      } catch (Exception e) {
2196        fail("Family " + new String(family, StandardCharsets.UTF_8) + " does not exist");
2197      }
2198
2199      // testing non existing family
2200      boolean ok = false;
2201      family = fam4;
2202      try {
2203        NavigableMap<byte[], List<Cell>> deleteMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
2204        deleteMap.put(family, kvs);
2205        region.delete(deleteMap, Durability.SYNC_WAL);
2206      } catch (Exception e) {
2207        ok = true;
2208      }
2209      assertTrue("Family " + new String(family, StandardCharsets.UTF_8) + " does exist", ok);
2210    } finally {
2211      HBaseTestingUtility.closeRegionAndWAL(this.region);
2212      this.region = null;
2213    }
2214  }
2215
2216  @Test
2217  public void testDelete_mixed() throws IOException, InterruptedException {
2218    byte[] fam = Bytes.toBytes("info");
2219    byte[][] families = { fam };
2220    this.region = initHRegion(tableName, method, CONF, families);
2221    try {
2222      EnvironmentEdgeManagerTestHelper.injectEdge(new IncrementingEnvironmentEdge());
2223
2224      byte[] row = Bytes.toBytes("table_name");
2225      // column names
2226      byte[] serverinfo = Bytes.toBytes("serverinfo");
2227      byte[] splitA = Bytes.toBytes("splitA");
2228      byte[] splitB = Bytes.toBytes("splitB");
2229
2230      // add some data:
2231      Put put = new Put(row);
2232      put.addColumn(fam, splitA, Bytes.toBytes("reference_A"));
2233      region.put(put);
2234
2235      put = new Put(row);
2236      put.addColumn(fam, splitB, Bytes.toBytes("reference_B"));
2237      region.put(put);
2238
2239      put = new Put(row);
2240      put.addColumn(fam, serverinfo, Bytes.toBytes("ip_address"));
2241      region.put(put);
2242
2243      // ok now delete a split:
2244      Delete delete = new Delete(row);
2245      delete.addColumns(fam, splitA);
2246      region.delete(delete);
2247
2248      // assert some things:
2249      Get get = new Get(row).addColumn(fam, serverinfo);
2250      Result result = region.get(get);
2251      assertEquals(1, result.size());
2252
2253      get = new Get(row).addColumn(fam, splitA);
2254      result = region.get(get);
2255      assertEquals(0, result.size());
2256
2257      get = new Get(row).addColumn(fam, splitB);
2258      result = region.get(get);
2259      assertEquals(1, result.size());
2260
2261      // Assert that after a delete, I can put.
2262      put = new Put(row);
2263      put.addColumn(fam, splitA, Bytes.toBytes("reference_A"));
2264      region.put(put);
2265      get = new Get(row);
2266      result = region.get(get);
2267      assertEquals(3, result.size());
2268
2269      // Now delete all... then test I can add stuff back
2270      delete = new Delete(row);
2271      region.delete(delete);
2272      assertEquals(0, region.get(get).size());
2273
2274      region.put(new Put(row).addColumn(fam, splitA, Bytes.toBytes("reference_A")));
2275      result = region.get(get);
2276      assertEquals(1, result.size());
2277    } finally {
2278      HBaseTestingUtility.closeRegionAndWAL(this.region);
2279      this.region = null;
2280    }
2281  }
2282
2283  @Test
2284  public void testDeleteRowWithFutureTs() throws IOException {
2285    byte[] fam = Bytes.toBytes("info");
2286    byte[][] families = { fam };
2287    this.region = initHRegion(tableName, method, CONF, families);
2288    try {
2289      byte[] row = Bytes.toBytes("table_name");
2290      // column names
2291      byte[] serverinfo = Bytes.toBytes("serverinfo");
2292
2293      // add data in the far future
2294      Put put = new Put(row);
2295      put.addColumn(fam, serverinfo, HConstants.LATEST_TIMESTAMP - 5, Bytes.toBytes("value"));
2296      region.put(put);
2297
2298      // now delete something in the present
2299      Delete delete = new Delete(row);
2300      region.delete(delete);
2301
2302      // make sure we still see our data
2303      Get get = new Get(row).addColumn(fam, serverinfo);
2304      Result result = region.get(get);
2305      assertEquals(1, result.size());
2306
2307      // delete the future row
2308      delete = new Delete(row, HConstants.LATEST_TIMESTAMP - 3);
2309      region.delete(delete);
2310
2311      // make sure it is gone
2312      get = new Get(row).addColumn(fam, serverinfo);
2313      result = region.get(get);
2314      assertEquals(0, result.size());
2315    } finally {
2316      HBaseTestingUtility.closeRegionAndWAL(this.region);
2317      this.region = null;
2318    }
2319  }
2320
2321  /**
2322   * Tests that the special LATEST_TIMESTAMP option for puts gets replaced by
2323   * the actual timestamp
2324   */
2325  @Test
2326  public void testPutWithLatestTS() throws IOException {
2327    byte[] fam = Bytes.toBytes("info");
2328    byte[][] families = { fam };
2329    this.region = initHRegion(tableName, method, CONF, families);
2330    try {
2331      byte[] row = Bytes.toBytes("row1");
2332      // column names
2333      byte[] qual = Bytes.toBytes("qual");
2334
2335      // add data with LATEST_TIMESTAMP, put without WAL
2336      Put put = new Put(row);
2337      put.addColumn(fam, qual, HConstants.LATEST_TIMESTAMP, Bytes.toBytes("value"));
2338      region.put(put);
2339
2340      // Make sure it shows up with an actual timestamp
2341      Get get = new Get(row).addColumn(fam, qual);
2342      Result result = region.get(get);
2343      assertEquals(1, result.size());
2344      Cell kv = result.rawCells()[0];
2345      LOG.info("Got: " + kv);
2346      assertTrue("LATEST_TIMESTAMP was not replaced with real timestamp",
2347          kv.getTimestamp() != HConstants.LATEST_TIMESTAMP);
2348
2349      // Check same with WAL enabled (historically these took different
2350      // code paths, so check both)
2351      row = Bytes.toBytes("row2");
2352      put = new Put(row);
2353      put.addColumn(fam, qual, HConstants.LATEST_TIMESTAMP, Bytes.toBytes("value"));
2354      region.put(put);
2355
2356      // Make sure it shows up with an actual timestamp
2357      get = new Get(row).addColumn(fam, qual);
2358      result = region.get(get);
2359      assertEquals(1, result.size());
2360      kv = result.rawCells()[0];
2361      LOG.info("Got: " + kv);
2362      assertTrue("LATEST_TIMESTAMP was not replaced with real timestamp",
2363          kv.getTimestamp() != HConstants.LATEST_TIMESTAMP);
2364    } finally {
2365      HBaseTestingUtility.closeRegionAndWAL(this.region);
2366      this.region = null;
2367    }
2368
2369  }
2370
2371  /**
2372   * Tests that there is server-side filtering for invalid timestamp upper
2373   * bound. Note that the timestamp lower bound is automatically handled for us
2374   * by the TTL field.
2375   */
2376  @Test
2377  public void testPutWithTsSlop() throws IOException {
2378    byte[] fam = Bytes.toBytes("info");
2379    byte[][] families = { fam };
2380
2381    // add data with a timestamp that is too recent for range. Ensure assert
2382    CONF.setInt("hbase.hregion.keyvalue.timestamp.slop.millisecs", 1000);
2383    this.region = initHRegion(tableName, method, CONF, families);
2384    boolean caughtExcep = false;
2385    try {
2386      try {
2387        // no TS specified == use latest. should not error
2388        region.put(new Put(row).addColumn(fam, Bytes.toBytes("qual"), Bytes.toBytes("value")));
2389        // TS out of range. should error
2390        region.put(new Put(row).addColumn(fam, Bytes.toBytes("qual"),
2391            System.currentTimeMillis() + 2000, Bytes.toBytes("value")));
2392        fail("Expected IOE for TS out of configured timerange");
2393      } catch (FailedSanityCheckException ioe) {
2394        LOG.debug("Received expected exception", ioe);
2395        caughtExcep = true;
2396      }
2397      assertTrue("Should catch FailedSanityCheckException", caughtExcep);
2398    } finally {
2399      HBaseTestingUtility.closeRegionAndWAL(this.region);
2400      this.region = null;
2401    }
2402  }
2403
2404  @Test
2405  public void testScanner_DeleteOneFamilyNotAnother() throws IOException {
2406    byte[] fam1 = Bytes.toBytes("columnA");
2407    byte[] fam2 = Bytes.toBytes("columnB");
2408    this.region = initHRegion(tableName, method, CONF, fam1, fam2);
2409    try {
2410      byte[] rowA = Bytes.toBytes("rowA");
2411      byte[] rowB = Bytes.toBytes("rowB");
2412
2413      byte[] value = Bytes.toBytes("value");
2414
2415      Delete delete = new Delete(rowA);
2416      delete.addFamily(fam1);
2417
2418      region.delete(delete);
2419
2420      // now create data.
2421      Put put = new Put(rowA);
2422      put.addColumn(fam2, null, value);
2423      region.put(put);
2424
2425      put = new Put(rowB);
2426      put.addColumn(fam1, null, value);
2427      put.addColumn(fam2, null, value);
2428      region.put(put);
2429
2430      Scan scan = new Scan();
2431      scan.addFamily(fam1).addFamily(fam2);
2432      InternalScanner s = region.getScanner(scan);
2433      List<Cell> results = new ArrayList<>();
2434      s.next(results);
2435      assertTrue(CellUtil.matchingRows(results.get(0), rowA));
2436
2437      results.clear();
2438      s.next(results);
2439      assertTrue(CellUtil.matchingRows(results.get(0), rowB));
2440    } finally {
2441      HBaseTestingUtility.closeRegionAndWAL(this.region);
2442      this.region = null;
2443    }
2444  }
2445
2446  @Test
2447  public void testDataInMemoryWithoutWAL() throws IOException {
2448    FileSystem fs = FileSystem.get(CONF);
2449    Path rootDir = new Path(dir + "testDataInMemoryWithoutWAL");
2450    FSHLog hLog = new FSHLog(fs, rootDir, "testDataInMemoryWithoutWAL", CONF);
2451    // This chunk creation is done throughout the code base. Do we want to move it into core?
2452    // It is missing from this test. W/o it we NPE.
2453    ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null);
2454    HRegion region = initHRegion(tableName, null, null, false, Durability.SYNC_WAL, hLog,
2455        COLUMN_FAMILY_BYTES);
2456
2457    Cell originalCell = CellUtil.createCell(row, COLUMN_FAMILY_BYTES, qual1,
2458      System.currentTimeMillis(), KeyValue.Type.Put.getCode(), value1);
2459    final long originalSize = KeyValueUtil.length(originalCell);
2460
2461    Cell addCell = CellUtil.createCell(row, COLUMN_FAMILY_BYTES, qual1,
2462      System.currentTimeMillis(), KeyValue.Type.Put.getCode(), Bytes.toBytes("xxxxxxxxxx"));
2463    final long addSize = KeyValueUtil.length(addCell);
2464
2465    LOG.info("originalSize:" + originalSize
2466      + ", addSize:" + addSize);
2467    // start test. We expect that the addPut's durability will be replaced
2468    // by originalPut's durability.
2469
2470    // case 1:
2471    testDataInMemoryWithoutWAL(region,
2472            new Put(row).add(originalCell).setDurability(Durability.SKIP_WAL),
2473            new Put(row).add(addCell).setDurability(Durability.SKIP_WAL),
2474            originalSize + addSize);
2475
2476    // case 2:
2477    testDataInMemoryWithoutWAL(region,
2478            new Put(row).add(originalCell).setDurability(Durability.SKIP_WAL),
2479            new Put(row).add(addCell).setDurability(Durability.SYNC_WAL),
2480            originalSize + addSize);
2481
2482    // case 3:
2483    testDataInMemoryWithoutWAL(region,
2484            new Put(row).add(originalCell).setDurability(Durability.SYNC_WAL),
2485            new Put(row).add(addCell).setDurability(Durability.SKIP_WAL),
2486            0);
2487
2488    // case 4:
2489    testDataInMemoryWithoutWAL(region,
2490            new Put(row).add(originalCell).setDurability(Durability.SYNC_WAL),
2491            new Put(row).add(addCell).setDurability(Durability.SYNC_WAL),
2492            0);
2493  }
2494
2495  private static void testDataInMemoryWithoutWAL(HRegion region, Put originalPut,
2496          final Put addPut, long delta) throws IOException {
2497    final long initSize = region.getDataInMemoryWithoutWAL();
2498    // save normalCPHost and replaced by mockedCPHost
2499    RegionCoprocessorHost normalCPHost = region.getCoprocessorHost();
2500    RegionCoprocessorHost mockedCPHost = Mockito.mock(RegionCoprocessorHost.class);
2501    // Because the preBatchMutate returns void, we can't do usual Mockito when...then form. Must
2502    // do below format (from Mockito doc).
2503    Mockito.doAnswer(new Answer() {
2504      @Override
2505      public Object answer(InvocationOnMock invocation) throws Throwable {
2506        MiniBatchOperationInProgress<Mutation> mb = invocation.getArgument(0);
2507        mb.addOperationsFromCP(0, new Mutation[]{addPut});
2508        return null;
2509      }
2510    }).when(mockedCPHost).preBatchMutate(Mockito.isA(MiniBatchOperationInProgress.class));
2511    region.setCoprocessorHost(mockedCPHost);
2512    region.put(originalPut);
2513    region.setCoprocessorHost(normalCPHost);
2514    final long finalSize = region.getDataInMemoryWithoutWAL();
2515    assertEquals("finalSize:" + finalSize + ", initSize:"
2516      + initSize + ", delta:" + delta,finalSize, initSize + delta);
2517  }
2518
2519  @Test
2520  public void testDeleteColumns_PostInsert() throws IOException, InterruptedException {
2521    Delete delete = new Delete(row);
2522    delete.addColumns(fam1, qual1);
2523    doTestDelete_AndPostInsert(delete);
2524  }
2525
2526  @Test
2527  public void testaddFamily_PostInsert() throws IOException, InterruptedException {
2528    Delete delete = new Delete(row);
2529    delete.addFamily(fam1);
2530    doTestDelete_AndPostInsert(delete);
2531  }
2532
2533  public void doTestDelete_AndPostInsert(Delete delete) throws IOException, InterruptedException {
2534    this.region = initHRegion(tableName, method, CONF, fam1);
2535    try {
2536      EnvironmentEdgeManagerTestHelper.injectEdge(new IncrementingEnvironmentEdge());
2537      Put put = new Put(row);
2538      put.addColumn(fam1, qual1, value1);
2539      region.put(put);
2540
2541      // now delete the value:
2542      region.delete(delete);
2543
2544      // ok put data:
2545      put = new Put(row);
2546      put.addColumn(fam1, qual1, value2);
2547      region.put(put);
2548
2549      // ok get:
2550      Get get = new Get(row);
2551      get.addColumn(fam1, qual1);
2552
2553      Result r = region.get(get);
2554      assertEquals(1, r.size());
2555      assertArrayEquals(value2, r.getValue(fam1, qual1));
2556
2557      // next:
2558      Scan scan = new Scan(row);
2559      scan.addColumn(fam1, qual1);
2560      InternalScanner s = region.getScanner(scan);
2561
2562      List<Cell> results = new ArrayList<>();
2563      assertEquals(false, s.next(results));
2564      assertEquals(1, results.size());
2565      Cell kv = results.get(0);
2566
2567      assertArrayEquals(value2, CellUtil.cloneValue(kv));
2568      assertArrayEquals(fam1, CellUtil.cloneFamily(kv));
2569      assertArrayEquals(qual1, CellUtil.cloneQualifier(kv));
2570      assertArrayEquals(row, CellUtil.cloneRow(kv));
2571    } finally {
2572      HBaseTestingUtility.closeRegionAndWAL(this.region);
2573      this.region = null;
2574    }
2575  }
2576
2577  @Test
2578  public void testDelete_CheckTimestampUpdated() throws IOException {
2579    byte[] row1 = Bytes.toBytes("row1");
2580    byte[] col1 = Bytes.toBytes("col1");
2581    byte[] col2 = Bytes.toBytes("col2");
2582    byte[] col3 = Bytes.toBytes("col3");
2583
2584    // Setting up region
2585    this.region = initHRegion(tableName, method, CONF, fam1);
2586    try {
2587      // Building checkerList
2588      List<Cell> kvs = new ArrayList<>();
2589      kvs.add(new KeyValue(row1, fam1, col1, null));
2590      kvs.add(new KeyValue(row1, fam1, col2, null));
2591      kvs.add(new KeyValue(row1, fam1, col3, null));
2592
2593      NavigableMap<byte[], List<Cell>> deleteMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
2594      deleteMap.put(fam1, kvs);
2595      region.delete(deleteMap, Durability.SYNC_WAL);
2596
2597      // extract the key values out the memstore:
2598      // This is kinda hacky, but better than nothing...
2599      long now = System.currentTimeMillis();
2600      AbstractMemStore memstore = (AbstractMemStore)region.getStore(fam1).memstore;
2601      Cell firstCell = memstore.getActive().first();
2602      assertTrue(firstCell.getTimestamp() <= now);
2603      now = firstCell.getTimestamp();
2604      for (Cell cell : memstore.getActive().getCellSet()) {
2605        assertTrue(cell.getTimestamp() <= now);
2606        now = cell.getTimestamp();
2607      }
2608    } finally {
2609      HBaseTestingUtility.closeRegionAndWAL(this.region);
2610      this.region = null;
2611    }
2612  }
2613
2614  // ////////////////////////////////////////////////////////////////////////////
2615  // Get tests
2616  // ////////////////////////////////////////////////////////////////////////////
2617  @Test
2618  public void testGet_FamilyChecker() throws IOException {
2619    byte[] row1 = Bytes.toBytes("row1");
2620    byte[] fam1 = Bytes.toBytes("fam1");
2621    byte[] fam2 = Bytes.toBytes("False");
2622    byte[] col1 = Bytes.toBytes("col1");
2623
2624    // Setting up region
2625    this.region = initHRegion(tableName, method, CONF, fam1);
2626    try {
2627      Get get = new Get(row1);
2628      get.addColumn(fam2, col1);
2629
2630      // Test
2631      try {
2632        region.get(get);
2633      } catch (org.apache.hadoop.hbase.DoNotRetryIOException e) {
2634        assertFalse(false);
2635        return;
2636      }
2637      assertFalse(true);
2638    } finally {
2639      HBaseTestingUtility.closeRegionAndWAL(this.region);
2640      this.region = null;
2641    }
2642  }
2643
2644  @Test
2645  public void testGet_Basic() throws IOException {
2646    byte[] row1 = Bytes.toBytes("row1");
2647    byte[] fam1 = Bytes.toBytes("fam1");
2648    byte[] col1 = Bytes.toBytes("col1");
2649    byte[] col2 = Bytes.toBytes("col2");
2650    byte[] col3 = Bytes.toBytes("col3");
2651    byte[] col4 = Bytes.toBytes("col4");
2652    byte[] col5 = Bytes.toBytes("col5");
2653
2654    // Setting up region
2655    this.region = initHRegion(tableName, method, CONF, fam1);
2656    try {
2657      // Add to memstore
2658      Put put = new Put(row1);
2659      put.addColumn(fam1, col1, null);
2660      put.addColumn(fam1, col2, null);
2661      put.addColumn(fam1, col3, null);
2662      put.addColumn(fam1, col4, null);
2663      put.addColumn(fam1, col5, null);
2664      region.put(put);
2665
2666      Get get = new Get(row1);
2667      get.addColumn(fam1, col2);
2668      get.addColumn(fam1, col4);
2669      // Expected result
2670      KeyValue kv1 = new KeyValue(row1, fam1, col2);
2671      KeyValue kv2 = new KeyValue(row1, fam1, col4);
2672      KeyValue[] expected = { kv1, kv2 };
2673
2674      // Test
2675      Result res = region.get(get);
2676      assertEquals(expected.length, res.size());
2677      for (int i = 0; i < res.size(); i++) {
2678        assertTrue(CellUtil.matchingRows(expected[i], res.rawCells()[i]));
2679        assertTrue(CellUtil.matchingFamily(expected[i], res.rawCells()[i]));
2680        assertTrue(CellUtil.matchingQualifier(expected[i], res.rawCells()[i]));
2681      }
2682
2683      // Test using a filter on a Get
2684      Get g = new Get(row1);
2685      final int count = 2;
2686      g.setFilter(new ColumnCountGetFilter(count));
2687      res = region.get(g);
2688      assertEquals(count, res.size());
2689    } finally {
2690      HBaseTestingUtility.closeRegionAndWAL(this.region);
2691      this.region = null;
2692    }
2693  }
2694
2695  @Test
2696  public void testGet_Empty() throws IOException {
2697    byte[] row = Bytes.toBytes("row");
2698    byte[] fam = Bytes.toBytes("fam");
2699
2700    this.region = initHRegion(tableName, method, CONF, fam);
2701    try {
2702      Get get = new Get(row);
2703      get.addFamily(fam);
2704      Result r = region.get(get);
2705
2706      assertTrue(r.isEmpty());
2707    } finally {
2708      HBaseTestingUtility.closeRegionAndWAL(this.region);
2709      this.region = null;
2710    }
2711  }
2712
2713  @Test
2714  public void testGetWithFilter() throws IOException, InterruptedException {
2715    byte[] row1 = Bytes.toBytes("row1");
2716    byte[] fam1 = Bytes.toBytes("fam1");
2717    byte[] col1 = Bytes.toBytes("col1");
2718    byte[] value1 = Bytes.toBytes("value1");
2719    byte[] value2 = Bytes.toBytes("value2");
2720
2721    final int maxVersions = 3;
2722    HColumnDescriptor hcd = new HColumnDescriptor(fam1);
2723    hcd.setMaxVersions(maxVersions);
2724    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("testFilterAndColumnTracker"));
2725    htd.addFamily(hcd);
2726    ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null);
2727    HRegionInfo info = new HRegionInfo(htd.getTableName(), null, null, false);
2728    Path logDir = TEST_UTIL.getDataTestDirOnTestFS(method + ".log");
2729    final WAL wal = HBaseTestingUtility.createWal(TEST_UTIL.getConfiguration(), logDir, info);
2730    this.region = TEST_UTIL.createLocalHRegion(info, htd, wal);
2731
2732    try {
2733      // Put 4 version to memstore
2734      long ts = 0;
2735      Put put = new Put(row1, ts);
2736      put.addColumn(fam1, col1, value1);
2737      region.put(put);
2738      put = new Put(row1, ts + 1);
2739      put.addColumn(fam1, col1, Bytes.toBytes("filter1"));
2740      region.put(put);
2741      put = new Put(row1, ts + 2);
2742      put.addColumn(fam1, col1, Bytes.toBytes("filter2"));
2743      region.put(put);
2744      put = new Put(row1, ts + 3);
2745      put.addColumn(fam1, col1, value2);
2746      region.put(put);
2747
2748      Get get = new Get(row1);
2749      get.setMaxVersions();
2750      Result res = region.get(get);
2751      // Get 3 versions, the oldest version has gone from user view
2752      assertEquals(maxVersions, res.size());
2753
2754      get.setFilter(new ValueFilter(CompareOp.EQUAL, new SubstringComparator("value")));
2755      res = region.get(get);
2756      // When use value filter, the oldest version should still gone from user view and it
2757      // should only return one key vaule
2758      assertEquals(1, res.size());
2759      assertTrue(CellUtil.matchingValue(new KeyValue(row1, fam1, col1, value2), res.rawCells()[0]));
2760      assertEquals(ts + 3, res.rawCells()[0].getTimestamp());
2761
2762      region.flush(true);
2763      region.compact(true);
2764      Thread.sleep(1000);
2765      res = region.get(get);
2766      // After flush and compact, the result should be consistent with previous result
2767      assertEquals(1, res.size());
2768      assertTrue(CellUtil.matchingValue(new KeyValue(row1, fam1, col1, value2), res.rawCells()[0]));
2769    } finally {
2770      HBaseTestingUtility.closeRegionAndWAL(this.region);
2771      this.region = null;
2772    }
2773  }
2774
2775  // ////////////////////////////////////////////////////////////////////////////
2776  // Scanner tests
2777  // ////////////////////////////////////////////////////////////////////////////
2778  @Test
2779  public void testGetScanner_WithOkFamilies() throws IOException {
2780    byte[] fam1 = Bytes.toBytes("fam1");
2781    byte[] fam2 = Bytes.toBytes("fam2");
2782
2783    byte[][] families = { fam1, fam2 };
2784
2785    // Setting up region
2786    this.region = initHRegion(tableName, method, CONF, families);
2787    try {
2788      Scan scan = new Scan();
2789      scan.addFamily(fam1);
2790      scan.addFamily(fam2);
2791      try {
2792        region.getScanner(scan);
2793      } catch (Exception e) {
2794        assertTrue("Families could not be found in Region", false);
2795      }
2796    } finally {
2797      HBaseTestingUtility.closeRegionAndWAL(this.region);
2798      this.region = null;
2799    }
2800  }
2801
2802  @Test
2803  public void testGetScanner_WithNotOkFamilies() throws IOException {
2804    byte[] fam1 = Bytes.toBytes("fam1");
2805    byte[] fam2 = Bytes.toBytes("fam2");
2806
2807    byte[][] families = { fam1 };
2808
2809    // Setting up region
2810    this.region = initHRegion(tableName, method, CONF, families);
2811    try {
2812      Scan scan = new Scan();
2813      scan.addFamily(fam2);
2814      boolean ok = false;
2815      try {
2816        region.getScanner(scan);
2817      } catch (Exception e) {
2818        ok = true;
2819      }
2820      assertTrue("Families could not be found in Region", ok);
2821    } finally {
2822      HBaseTestingUtility.closeRegionAndWAL(this.region);
2823      this.region = null;
2824    }
2825  }
2826
2827  @Test
2828  public void testGetScanner_WithNoFamilies() throws IOException {
2829    byte[] row1 = Bytes.toBytes("row1");
2830    byte[] fam1 = Bytes.toBytes("fam1");
2831    byte[] fam2 = Bytes.toBytes("fam2");
2832    byte[] fam3 = Bytes.toBytes("fam3");
2833    byte[] fam4 = Bytes.toBytes("fam4");
2834
2835    byte[][] families = { fam1, fam2, fam3, fam4 };
2836
2837    // Setting up region
2838    this.region = initHRegion(tableName, method, CONF, families);
2839    try {
2840
2841      // Putting data in Region
2842      Put put = new Put(row1);
2843      put.addColumn(fam1, null, null);
2844      put.addColumn(fam2, null, null);
2845      put.addColumn(fam3, null, null);
2846      put.addColumn(fam4, null, null);
2847      region.put(put);
2848
2849      Scan scan = null;
2850      HRegion.RegionScannerImpl is = null;
2851
2852      // Testing to see how many scanners that is produced by getScanner,
2853      // starting
2854      // with known number, 2 - current = 1
2855      scan = new Scan();
2856      scan.addFamily(fam2);
2857      scan.addFamily(fam4);
2858      is = region.getScanner(scan);
2859      assertEquals(1, is.storeHeap.getHeap().size());
2860
2861      scan = new Scan();
2862      is = region.getScanner(scan);
2863      assertEquals(families.length - 1, is.storeHeap.getHeap().size());
2864    } finally {
2865      HBaseTestingUtility.closeRegionAndWAL(this.region);
2866      this.region = null;
2867    }
2868  }
2869
2870  /**
2871   * This method tests https://issues.apache.org/jira/browse/HBASE-2516.
2872   *
2873   * @throws IOException
2874   */
2875  @Test
2876  public void testGetScanner_WithRegionClosed() throws IOException {
2877    byte[] fam1 = Bytes.toBytes("fam1");
2878    byte[] fam2 = Bytes.toBytes("fam2");
2879
2880    byte[][] families = { fam1, fam2 };
2881
2882    // Setting up region
2883    try {
2884      this.region = initHRegion(tableName, method, CONF, families);
2885    } catch (IOException e) {
2886      e.printStackTrace();
2887      fail("Got IOException during initHRegion, " + e.getMessage());
2888    }
2889    try {
2890      region.closed.set(true);
2891      try {
2892        region.getScanner(null);
2893        fail("Expected to get an exception during getScanner on a region that is closed");
2894      } catch (NotServingRegionException e) {
2895        // this is the correct exception that is expected
2896      } catch (IOException e) {
2897        fail("Got wrong type of exception - should be a NotServingRegionException, " +
2898            "but was an IOException: "
2899            + e.getMessage());
2900      }
2901    } finally {
2902      HBaseTestingUtility.closeRegionAndWAL(this.region);
2903      this.region = null;
2904    }
2905  }
2906
2907  @Test
2908  public void testRegionScanner_Next() throws IOException {
2909    byte[] row1 = Bytes.toBytes("row1");
2910    byte[] row2 = Bytes.toBytes("row2");
2911    byte[] fam1 = Bytes.toBytes("fam1");
2912    byte[] fam2 = Bytes.toBytes("fam2");
2913    byte[] fam3 = Bytes.toBytes("fam3");
2914    byte[] fam4 = Bytes.toBytes("fam4");
2915
2916    byte[][] families = { fam1, fam2, fam3, fam4 };
2917    long ts = System.currentTimeMillis();
2918
2919    // Setting up region
2920    this.region = initHRegion(tableName, method, CONF, families);
2921    try {
2922      // Putting data in Region
2923      Put put = null;
2924      put = new Put(row1);
2925      put.addColumn(fam1, (byte[]) null, ts, null);
2926      put.addColumn(fam2, (byte[]) null, ts, null);
2927      put.addColumn(fam3, (byte[]) null, ts, null);
2928      put.addColumn(fam4, (byte[]) null, ts, null);
2929      region.put(put);
2930
2931      put = new Put(row2);
2932      put.addColumn(fam1, (byte[]) null, ts, null);
2933      put.addColumn(fam2, (byte[]) null, ts, null);
2934      put.addColumn(fam3, (byte[]) null, ts, null);
2935      put.addColumn(fam4, (byte[]) null, ts, null);
2936      region.put(put);
2937
2938      Scan scan = new Scan();
2939      scan.addFamily(fam2);
2940      scan.addFamily(fam4);
2941      InternalScanner is = region.getScanner(scan);
2942
2943      List<Cell> res = null;
2944
2945      // Result 1
2946      List<Cell> expected1 = new ArrayList<>();
2947      expected1.add(new KeyValue(row1, fam2, null, ts, KeyValue.Type.Put, null));
2948      expected1.add(new KeyValue(row1, fam4, null, ts, KeyValue.Type.Put, null));
2949
2950      res = new ArrayList<>();
2951      is.next(res);
2952      for (int i = 0; i < res.size(); i++) {
2953        assertTrue(PrivateCellUtil.equalsIgnoreMvccVersion(expected1.get(i), res.get(i)));
2954      }
2955
2956      // Result 2
2957      List<Cell> expected2 = new ArrayList<>();
2958      expected2.add(new KeyValue(row2, fam2, null, ts, KeyValue.Type.Put, null));
2959      expected2.add(new KeyValue(row2, fam4, null, ts, KeyValue.Type.Put, null));
2960
2961      res = new ArrayList<>();
2962      is.next(res);
2963      for (int i = 0; i < res.size(); i++) {
2964        assertTrue(PrivateCellUtil.equalsIgnoreMvccVersion(expected2.get(i), res.get(i)));
2965      }
2966    } finally {
2967      HBaseTestingUtility.closeRegionAndWAL(this.region);
2968      this.region = null;
2969    }
2970  }
2971
2972  @Test
2973  public void testScanner_ExplicitColumns_FromMemStore_EnforceVersions() throws IOException {
2974    byte[] row1 = Bytes.toBytes("row1");
2975    byte[] qf1 = Bytes.toBytes("qualifier1");
2976    byte[] qf2 = Bytes.toBytes("qualifier2");
2977    byte[] fam1 = Bytes.toBytes("fam1");
2978    byte[][] families = { fam1 };
2979
2980    long ts1 = System.currentTimeMillis();
2981    long ts2 = ts1 + 1;
2982    long ts3 = ts1 + 2;
2983
2984    // Setting up region
2985    this.region = initHRegion(tableName, method, CONF, families);
2986    try {
2987      // Putting data in Region
2988      Put put = null;
2989      KeyValue kv13 = new KeyValue(row1, fam1, qf1, ts3, KeyValue.Type.Put, null);
2990      KeyValue kv12 = new KeyValue(row1, fam1, qf1, ts2, KeyValue.Type.Put, null);
2991      KeyValue kv11 = new KeyValue(row1, fam1, qf1, ts1, KeyValue.Type.Put, null);
2992
2993      KeyValue kv23 = new KeyValue(row1, fam1, qf2, ts3, KeyValue.Type.Put, null);
2994      KeyValue kv22 = new KeyValue(row1, fam1, qf2, ts2, KeyValue.Type.Put, null);
2995      KeyValue kv21 = new KeyValue(row1, fam1, qf2, ts1, KeyValue.Type.Put, null);
2996
2997      put = new Put(row1);
2998      put.add(kv13);
2999      put.add(kv12);
3000      put.add(kv11);
3001      put.add(kv23);
3002      put.add(kv22);
3003      put.add(kv21);
3004      region.put(put);
3005
3006      // Expected
3007      List<Cell> expected = new ArrayList<>();
3008      expected.add(kv13);
3009      expected.add(kv12);
3010
3011      Scan scan = new Scan(row1);
3012      scan.addColumn(fam1, qf1);
3013      scan.setMaxVersions(MAX_VERSIONS);
3014      List<Cell> actual = new ArrayList<>();
3015      InternalScanner scanner = region.getScanner(scan);
3016
3017      boolean hasNext = scanner.next(actual);
3018      assertEquals(false, hasNext);
3019
3020      // Verify result
3021      for (int i = 0; i < expected.size(); i++) {
3022        assertEquals(expected.get(i), actual.get(i));
3023      }
3024    } finally {
3025      HBaseTestingUtility.closeRegionAndWAL(this.region);
3026      this.region = null;
3027    }
3028  }
3029
3030  @Test
3031  public void testScanner_ExplicitColumns_FromFilesOnly_EnforceVersions() throws IOException {
3032    byte[] row1 = Bytes.toBytes("row1");
3033    byte[] qf1 = Bytes.toBytes("qualifier1");
3034    byte[] qf2 = Bytes.toBytes("qualifier2");
3035    byte[] fam1 = Bytes.toBytes("fam1");
3036    byte[][] families = { fam1 };
3037
3038    long ts1 = 1; // System.currentTimeMillis();
3039    long ts2 = ts1 + 1;
3040    long ts3 = ts1 + 2;
3041
3042    // Setting up region
3043    this.region = initHRegion(tableName, method, CONF, families);
3044    try {
3045      // Putting data in Region
3046      Put put = null;
3047      KeyValue kv13 = new KeyValue(row1, fam1, qf1, ts3, KeyValue.Type.Put, null);
3048      KeyValue kv12 = new KeyValue(row1, fam1, qf1, ts2, KeyValue.Type.Put, null);
3049      KeyValue kv11 = new KeyValue(row1, fam1, qf1, ts1, KeyValue.Type.Put, null);
3050
3051      KeyValue kv23 = new KeyValue(row1, fam1, qf2, ts3, KeyValue.Type.Put, null);
3052      KeyValue kv22 = new KeyValue(row1, fam1, qf2, ts2, KeyValue.Type.Put, null);
3053      KeyValue kv21 = new KeyValue(row1, fam1, qf2, ts1, KeyValue.Type.Put, null);
3054
3055      put = new Put(row1);
3056      put.add(kv13);
3057      put.add(kv12);
3058      put.add(kv11);
3059      put.add(kv23);
3060      put.add(kv22);
3061      put.add(kv21);
3062      region.put(put);
3063      region.flush(true);
3064
3065      // Expected
3066      List<Cell> expected = new ArrayList<>();
3067      expected.add(kv13);
3068      expected.add(kv12);
3069      expected.add(kv23);
3070      expected.add(kv22);
3071
3072      Scan scan = new Scan(row1);
3073      scan.addColumn(fam1, qf1);
3074      scan.addColumn(fam1, qf2);
3075      scan.setMaxVersions(MAX_VERSIONS);
3076      List<Cell> actual = new ArrayList<>();
3077      InternalScanner scanner = region.getScanner(scan);
3078
3079      boolean hasNext = scanner.next(actual);
3080      assertEquals(false, hasNext);
3081
3082      // Verify result
3083      for (int i = 0; i < expected.size(); i++) {
3084        assertTrue(PrivateCellUtil.equalsIgnoreMvccVersion(expected.get(i), actual.get(i)));
3085      }
3086    } finally {
3087      HBaseTestingUtility.closeRegionAndWAL(this.region);
3088      this.region = null;
3089    }
3090  }
3091
3092  @Test
3093  public void testScanner_ExplicitColumns_FromMemStoreAndFiles_EnforceVersions() throws
3094      IOException {
3095    byte[] row1 = Bytes.toBytes("row1");
3096    byte[] fam1 = Bytes.toBytes("fam1");
3097    byte[][] families = { fam1 };
3098    byte[] qf1 = Bytes.toBytes("qualifier1");
3099    byte[] qf2 = Bytes.toBytes("qualifier2");
3100
3101    long ts1 = 1;
3102    long ts2 = ts1 + 1;
3103    long ts3 = ts1 + 2;
3104    long ts4 = ts1 + 3;
3105
3106    // Setting up region
3107    this.region = initHRegion(tableName, method, CONF, families);
3108    try {
3109      // Putting data in Region
3110      KeyValue kv14 = new KeyValue(row1, fam1, qf1, ts4, KeyValue.Type.Put, null);
3111      KeyValue kv13 = new KeyValue(row1, fam1, qf1, ts3, KeyValue.Type.Put, null);
3112      KeyValue kv12 = new KeyValue(row1, fam1, qf1, ts2, KeyValue.Type.Put, null);
3113      KeyValue kv11 = new KeyValue(row1, fam1, qf1, ts1, KeyValue.Type.Put, null);
3114
3115      KeyValue kv24 = new KeyValue(row1, fam1, qf2, ts4, KeyValue.Type.Put, null);
3116      KeyValue kv23 = new KeyValue(row1, fam1, qf2, ts3, KeyValue.Type.Put, null);
3117      KeyValue kv22 = new KeyValue(row1, fam1, qf2, ts2, KeyValue.Type.Put, null);
3118      KeyValue kv21 = new KeyValue(row1, fam1, qf2, ts1, KeyValue.Type.Put, null);
3119
3120      Put put = null;
3121      put = new Put(row1);
3122      put.add(kv14);
3123      put.add(kv24);
3124      region.put(put);
3125      region.flush(true);
3126
3127      put = new Put(row1);
3128      put.add(kv23);
3129      put.add(kv13);
3130      region.put(put);
3131      region.flush(true);
3132
3133      put = new Put(row1);
3134      put.add(kv22);
3135      put.add(kv12);
3136      region.put(put);
3137      region.flush(true);
3138
3139      put = new Put(row1);
3140      put.add(kv21);
3141      put.add(kv11);
3142      region.put(put);
3143
3144      // Expected
3145      List<Cell> expected = new ArrayList<>();
3146      expected.add(kv14);
3147      expected.add(kv13);
3148      expected.add(kv12);
3149      expected.add(kv24);
3150      expected.add(kv23);
3151      expected.add(kv22);
3152
3153      Scan scan = new Scan(row1);
3154      scan.addColumn(fam1, qf1);
3155      scan.addColumn(fam1, qf2);
3156      int versions = 3;
3157      scan.setMaxVersions(versions);
3158      List<Cell> actual = new ArrayList<>();
3159      InternalScanner scanner = region.getScanner(scan);
3160
3161      boolean hasNext = scanner.next(actual);
3162      assertEquals(false, hasNext);
3163
3164      // Verify result
3165      for (int i = 0; i < expected.size(); i++) {
3166        assertTrue(PrivateCellUtil.equalsIgnoreMvccVersion(expected.get(i), actual.get(i)));
3167      }
3168    } finally {
3169      HBaseTestingUtility.closeRegionAndWAL(this.region);
3170      this.region = null;
3171    }
3172  }
3173
3174  @Test
3175  public void testScanner_Wildcard_FromMemStore_EnforceVersions() throws IOException {
3176    byte[] row1 = Bytes.toBytes("row1");
3177    byte[] qf1 = Bytes.toBytes("qualifier1");
3178    byte[] qf2 = Bytes.toBytes("qualifier2");
3179    byte[] fam1 = Bytes.toBytes("fam1");
3180    byte[][] families = { fam1 };
3181
3182    long ts1 = System.currentTimeMillis();
3183    long ts2 = ts1 + 1;
3184    long ts3 = ts1 + 2;
3185
3186    // Setting up region
3187    this.region = initHRegion(tableName, method, CONF, families);
3188    try {
3189      // Putting data in Region
3190      Put put = null;
3191      KeyValue kv13 = new KeyValue(row1, fam1, qf1, ts3, KeyValue.Type.Put, null);
3192      KeyValue kv12 = new KeyValue(row1, fam1, qf1, ts2, KeyValue.Type.Put, null);
3193      KeyValue kv11 = new KeyValue(row1, fam1, qf1, ts1, KeyValue.Type.Put, null);
3194
3195      KeyValue kv23 = new KeyValue(row1, fam1, qf2, ts3, KeyValue.Type.Put, null);
3196      KeyValue kv22 = new KeyValue(row1, fam1, qf2, ts2, KeyValue.Type.Put, null);
3197      KeyValue kv21 = new KeyValue(row1, fam1, qf2, ts1, KeyValue.Type.Put, null);
3198
3199      put = new Put(row1);
3200      put.add(kv13);
3201      put.add(kv12);
3202      put.add(kv11);
3203      put.add(kv23);
3204      put.add(kv22);
3205      put.add(kv21);
3206      region.put(put);
3207
3208      // Expected
3209      List<Cell> expected = new ArrayList<>();
3210      expected.add(kv13);
3211      expected.add(kv12);
3212      expected.add(kv23);
3213      expected.add(kv22);
3214
3215      Scan scan = new Scan(row1);
3216      scan.addFamily(fam1);
3217      scan.setMaxVersions(MAX_VERSIONS);
3218      List<Cell> actual = new ArrayList<>();
3219      InternalScanner scanner = region.getScanner(scan);
3220
3221      boolean hasNext = scanner.next(actual);
3222      assertEquals(false, hasNext);
3223
3224      // Verify result
3225      for (int i = 0; i < expected.size(); i++) {
3226        assertEquals(expected.get(i), actual.get(i));
3227      }
3228    } finally {
3229      HBaseTestingUtility.closeRegionAndWAL(this.region);
3230      this.region = null;
3231    }
3232  }
3233
3234  @Test
3235  public void testScanner_Wildcard_FromFilesOnly_EnforceVersions() throws IOException {
3236    byte[] row1 = Bytes.toBytes("row1");
3237    byte[] qf1 = Bytes.toBytes("qualifier1");
3238    byte[] qf2 = Bytes.toBytes("qualifier2");
3239    byte[] fam1 = Bytes.toBytes("fam1");
3240
3241    long ts1 = 1; // System.currentTimeMillis();
3242    long ts2 = ts1 + 1;
3243    long ts3 = ts1 + 2;
3244
3245    // Setting up region
3246    this.region = initHRegion(tableName, method, CONF, fam1);
3247    try {
3248      // Putting data in Region
3249      Put put = null;
3250      KeyValue kv13 = new KeyValue(row1, fam1, qf1, ts3, KeyValue.Type.Put, null);
3251      KeyValue kv12 = new KeyValue(row1, fam1, qf1, ts2, KeyValue.Type.Put, null);
3252      KeyValue kv11 = new KeyValue(row1, fam1, qf1, ts1, KeyValue.Type.Put, null);
3253
3254      KeyValue kv23 = new KeyValue(row1, fam1, qf2, ts3, KeyValue.Type.Put, null);
3255      KeyValue kv22 = new KeyValue(row1, fam1, qf2, ts2, KeyValue.Type.Put, null);
3256      KeyValue kv21 = new KeyValue(row1, fam1, qf2, ts1, KeyValue.Type.Put, null);
3257
3258      put = new Put(row1);
3259      put.add(kv13);
3260      put.add(kv12);
3261      put.add(kv11);
3262      put.add(kv23);
3263      put.add(kv22);
3264      put.add(kv21);
3265      region.put(put);
3266      region.flush(true);
3267
3268      // Expected
3269      List<Cell> expected = new ArrayList<>();
3270      expected.add(kv13);
3271      expected.add(kv12);
3272      expected.add(kv23);
3273      expected.add(kv22);
3274
3275      Scan scan = new Scan(row1);
3276      scan.addFamily(fam1);
3277      scan.setMaxVersions(MAX_VERSIONS);
3278      List<Cell> actual = new ArrayList<>();
3279      InternalScanner scanner = region.getScanner(scan);
3280
3281      boolean hasNext = scanner.next(actual);
3282      assertEquals(false, hasNext);
3283
3284      // Verify result
3285      for (int i = 0; i < expected.size(); i++) {
3286        assertTrue(PrivateCellUtil.equalsIgnoreMvccVersion(expected.get(i), actual.get(i)));
3287      }
3288    } finally {
3289      HBaseTestingUtility.closeRegionAndWAL(this.region);
3290      this.region = null;
3291    }
3292  }
3293
3294  @Test
3295  public void testScanner_StopRow1542() throws IOException {
3296    byte[] family = Bytes.toBytes("testFamily");
3297    this.region = initHRegion(tableName, method, CONF, family);
3298    try {
3299      byte[] row1 = Bytes.toBytes("row111");
3300      byte[] row2 = Bytes.toBytes("row222");
3301      byte[] row3 = Bytes.toBytes("row333");
3302      byte[] row4 = Bytes.toBytes("row444");
3303      byte[] row5 = Bytes.toBytes("row555");
3304
3305      byte[] col1 = Bytes.toBytes("Pub111");
3306      byte[] col2 = Bytes.toBytes("Pub222");
3307
3308      Put put = new Put(row1);
3309      put.addColumn(family, col1, Bytes.toBytes(10L));
3310      region.put(put);
3311
3312      put = new Put(row2);
3313      put.addColumn(family, col1, Bytes.toBytes(15L));
3314      region.put(put);
3315
3316      put = new Put(row3);
3317      put.addColumn(family, col2, Bytes.toBytes(20L));
3318      region.put(put);
3319
3320      put = new Put(row4);
3321      put.addColumn(family, col2, Bytes.toBytes(30L));
3322      region.put(put);
3323
3324      put = new Put(row5);
3325      put.addColumn(family, col1, Bytes.toBytes(40L));
3326      region.put(put);
3327
3328      Scan scan = new Scan(row3, row4);
3329      scan.setMaxVersions();
3330      scan.addColumn(family, col1);
3331      InternalScanner s = region.getScanner(scan);
3332
3333      List<Cell> results = new ArrayList<>();
3334      assertEquals(false, s.next(results));
3335      assertEquals(0, results.size());
3336    } finally {
3337      HBaseTestingUtility.closeRegionAndWAL(this.region);
3338      this.region = null;
3339    }
3340  }
3341
3342  @Test
3343  public void testScanner_Wildcard_FromMemStoreAndFiles_EnforceVersions() throws IOException {
3344    byte[] row1 = Bytes.toBytes("row1");
3345    byte[] fam1 = Bytes.toBytes("fam1");
3346    byte[] qf1 = Bytes.toBytes("qualifier1");
3347    byte[] qf2 = Bytes.toBytes("quateslifier2");
3348
3349    long ts1 = 1;
3350    long ts2 = ts1 + 1;
3351    long ts3 = ts1 + 2;
3352    long ts4 = ts1 + 3;
3353
3354    // Setting up region
3355    this.region = initHRegion(tableName, method, CONF, fam1);
3356    try {
3357      // Putting data in Region
3358      KeyValue kv14 = new KeyValue(row1, fam1, qf1, ts4, KeyValue.Type.Put, null);
3359      KeyValue kv13 = new KeyValue(row1, fam1, qf1, ts3, KeyValue.Type.Put, null);
3360      KeyValue kv12 = new KeyValue(row1, fam1, qf1, ts2, KeyValue.Type.Put, null);
3361      KeyValue kv11 = new KeyValue(row1, fam1, qf1, ts1, KeyValue.Type.Put, null);
3362
3363      KeyValue kv24 = new KeyValue(row1, fam1, qf2, ts4, KeyValue.Type.Put, null);
3364      KeyValue kv23 = new KeyValue(row1, fam1, qf2, ts3, KeyValue.Type.Put, null);
3365      KeyValue kv22 = new KeyValue(row1, fam1, qf2, ts2, KeyValue.Type.Put, null);
3366      KeyValue kv21 = new KeyValue(row1, fam1, qf2, ts1, KeyValue.Type.Put, null);
3367
3368      Put put = null;
3369      put = new Put(row1);
3370      put.add(kv14);
3371      put.add(kv24);
3372      region.put(put);
3373      region.flush(true);
3374
3375      put = new Put(row1);
3376      put.add(kv23);
3377      put.add(kv13);
3378      region.put(put);
3379      region.flush(true);
3380
3381      put = new Put(row1);
3382      put.add(kv22);
3383      put.add(kv12);
3384      region.put(put);
3385      region.flush(true);
3386
3387      put = new Put(row1);
3388      put.add(kv21);
3389      put.add(kv11);
3390      region.put(put);
3391
3392      // Expected
3393      List<KeyValue> expected = new ArrayList<>();
3394      expected.add(kv14);
3395      expected.add(kv13);
3396      expected.add(kv12);
3397      expected.add(kv24);
3398      expected.add(kv23);
3399      expected.add(kv22);
3400
3401      Scan scan = new Scan(row1);
3402      int versions = 3;
3403      scan.setMaxVersions(versions);
3404      List<Cell> actual = new ArrayList<>();
3405      InternalScanner scanner = region.getScanner(scan);
3406
3407      boolean hasNext = scanner.next(actual);
3408      assertEquals(false, hasNext);
3409
3410      // Verify result
3411      for (int i = 0; i < expected.size(); i++) {
3412        assertTrue(PrivateCellUtil.equalsIgnoreMvccVersion(expected.get(i), actual.get(i)));
3413      }
3414    } finally {
3415      HBaseTestingUtility.closeRegionAndWAL(this.region);
3416      this.region = null;
3417    }
3418  }
3419
3420  /**
3421   * Added for HBASE-5416
3422   *
3423   * Here we test scan optimization when only subset of CFs are used in filter
3424   * conditions.
3425   */
3426  @Test
3427  public void testScanner_JoinedScanners() throws IOException {
3428    byte[] cf_essential = Bytes.toBytes("essential");
3429    byte[] cf_joined = Bytes.toBytes("joined");
3430    byte[] cf_alpha = Bytes.toBytes("alpha");
3431    this.region = initHRegion(tableName, method, CONF, cf_essential, cf_joined, cf_alpha);
3432    try {
3433      byte[] row1 = Bytes.toBytes("row1");
3434      byte[] row2 = Bytes.toBytes("row2");
3435      byte[] row3 = Bytes.toBytes("row3");
3436
3437      byte[] col_normal = Bytes.toBytes("d");
3438      byte[] col_alpha = Bytes.toBytes("a");
3439
3440      byte[] filtered_val = Bytes.toBytes(3);
3441
3442      Put put = new Put(row1);
3443      put.addColumn(cf_essential, col_normal, Bytes.toBytes(1));
3444      put.addColumn(cf_joined, col_alpha, Bytes.toBytes(1));
3445      region.put(put);
3446
3447      put = new Put(row2);
3448      put.addColumn(cf_essential, col_alpha, Bytes.toBytes(2));
3449      put.addColumn(cf_joined, col_normal, Bytes.toBytes(2));
3450      put.addColumn(cf_alpha, col_alpha, Bytes.toBytes(2));
3451      region.put(put);
3452
3453      put = new Put(row3);
3454      put.addColumn(cf_essential, col_normal, filtered_val);
3455      put.addColumn(cf_joined, col_normal, filtered_val);
3456      region.put(put);
3457
3458      // Check two things:
3459      // 1. result list contains expected values
3460      // 2. result list is sorted properly
3461
3462      Scan scan = new Scan();
3463      Filter filter = new SingleColumnValueExcludeFilter(cf_essential, col_normal,
3464          CompareOp.NOT_EQUAL, filtered_val);
3465      scan.setFilter(filter);
3466      scan.setLoadColumnFamiliesOnDemand(true);
3467      InternalScanner s = region.getScanner(scan);
3468
3469      List<Cell> results = new ArrayList<>();
3470      assertTrue(s.next(results));
3471      assertEquals(1, results.size());
3472      results.clear();
3473
3474      assertTrue(s.next(results));
3475      assertEquals(3, results.size());
3476      assertTrue("orderCheck", CellUtil.matchingFamily(results.get(0), cf_alpha));
3477      assertTrue("orderCheck", CellUtil.matchingFamily(results.get(1), cf_essential));
3478      assertTrue("orderCheck", CellUtil.matchingFamily(results.get(2), cf_joined));
3479      results.clear();
3480
3481      assertFalse(s.next(results));
3482      assertEquals(0, results.size());
3483    } finally {
3484      HBaseTestingUtility.closeRegionAndWAL(this.region);
3485      this.region = null;
3486    }
3487  }
3488
3489  /**
3490   * HBASE-5416
3491   *
3492   * Test case when scan limits amount of KVs returned on each next() call.
3493   */
3494  @Test
3495  public void testScanner_JoinedScannersWithLimits() throws IOException {
3496    final byte[] cf_first = Bytes.toBytes("first");
3497    final byte[] cf_second = Bytes.toBytes("second");
3498
3499    this.region = initHRegion(tableName, method, CONF, cf_first, cf_second);
3500    try {
3501      final byte[] col_a = Bytes.toBytes("a");
3502      final byte[] col_b = Bytes.toBytes("b");
3503
3504      Put put;
3505
3506      for (int i = 0; i < 10; i++) {
3507        put = new Put(Bytes.toBytes("r" + Integer.toString(i)));
3508        put.addColumn(cf_first, col_a, Bytes.toBytes(i));
3509        if (i < 5) {
3510          put.addColumn(cf_first, col_b, Bytes.toBytes(i));
3511          put.addColumn(cf_second, col_a, Bytes.toBytes(i));
3512          put.addColumn(cf_second, col_b, Bytes.toBytes(i));
3513        }
3514        region.put(put);
3515      }
3516
3517      Scan scan = new Scan();
3518      scan.setLoadColumnFamiliesOnDemand(true);
3519      Filter bogusFilter = new FilterBase() {
3520        @Override
3521        public ReturnCode filterCell(final Cell ignored) throws IOException {
3522          return ReturnCode.INCLUDE;
3523        }
3524        @Override
3525        public boolean isFamilyEssential(byte[] name) {
3526          return Bytes.equals(name, cf_first);
3527        }
3528      };
3529
3530      scan.setFilter(bogusFilter);
3531      InternalScanner s = region.getScanner(scan);
3532
3533      // Our data looks like this:
3534      // r0: first:a, first:b, second:a, second:b
3535      // r1: first:a, first:b, second:a, second:b
3536      // r2: first:a, first:b, second:a, second:b
3537      // r3: first:a, first:b, second:a, second:b
3538      // r4: first:a, first:b, second:a, second:b
3539      // r5: first:a
3540      // r6: first:a
3541      // r7: first:a
3542      // r8: first:a
3543      // r9: first:a
3544
3545      // But due to next's limit set to 3, we should get this:
3546      // r0: first:a, first:b, second:a
3547      // r0: second:b
3548      // r1: first:a, first:b, second:a
3549      // r1: second:b
3550      // r2: first:a, first:b, second:a
3551      // r2: second:b
3552      // r3: first:a, first:b, second:a
3553      // r3: second:b
3554      // r4: first:a, first:b, second:a
3555      // r4: second:b
3556      // r5: first:a
3557      // r6: first:a
3558      // r7: first:a
3559      // r8: first:a
3560      // r9: first:a
3561
3562      List<Cell> results = new ArrayList<>();
3563      int index = 0;
3564      ScannerContext scannerContext = ScannerContext.newBuilder().setBatchLimit(3).build();
3565      while (true) {
3566        boolean more = s.next(results, scannerContext);
3567        if ((index >> 1) < 5) {
3568          if (index % 2 == 0) {
3569            assertEquals(3, results.size());
3570          } else {
3571            assertEquals(1, results.size());
3572          }
3573        } else {
3574          assertEquals(1, results.size());
3575        }
3576        results.clear();
3577        index++;
3578        if (!more) {
3579          break;
3580        }
3581      }
3582    } finally {
3583      HBaseTestingUtility.closeRegionAndWAL(this.region);
3584      this.region = null;
3585    }
3586  }
3587
3588  /**
3589   * Write an HFile block full with Cells whose qualifier that are identical between
3590   * 0 and Short.MAX_VALUE. See HBASE-13329.
3591   * @throws Exception
3592   */
3593  @Test
3594  public void testLongQualifier() throws Exception {
3595    byte[] family = Bytes.toBytes("family");
3596    this.region = initHRegion(tableName, method, CONF, family);
3597    byte[] q = new byte[Short.MAX_VALUE+2];
3598    Arrays.fill(q, 0, q.length-1, (byte)42);
3599    for (byte i=0; i<10; i++) {
3600      Put p = new Put(Bytes.toBytes("row"));
3601      // qualifiers that differ past Short.MAX_VALUE
3602      q[q.length-1]=i;
3603      p.addColumn(family, q, q);
3604      region.put(p);
3605    }
3606    region.flush(false);
3607    HBaseTestingUtility.closeRegionAndWAL(this.region);
3608    this.region = null;
3609  }
3610
3611  /**
3612   * Flushes the cache in a thread while scanning. The tests verify that the
3613   * scan is coherent - e.g. the returned results are always of the same or
3614   * later update as the previous results.
3615   *
3616   * @throws IOException
3617   *           scan / compact
3618   * @throws InterruptedException
3619   *           thread join
3620   */
3621  @Test
3622  public void testFlushCacheWhileScanning() throws IOException, InterruptedException {
3623    byte[] family = Bytes.toBytes("family");
3624    int numRows = 1000;
3625    int flushAndScanInterval = 10;
3626    int compactInterval = 10 * flushAndScanInterval;
3627
3628    this.region = initHRegion(tableName, method, CONF, family);
3629    FlushThread flushThread = new FlushThread();
3630    try {
3631      flushThread.start();
3632
3633      Scan scan = new Scan();
3634      scan.addFamily(family);
3635      scan.setFilter(new SingleColumnValueFilter(family, qual1, CompareOp.EQUAL,
3636          new BinaryComparator(Bytes.toBytes(5L))));
3637
3638      int expectedCount = 0;
3639      List<Cell> res = new ArrayList<>();
3640
3641      boolean toggle = true;
3642      for (long i = 0; i < numRows; i++) {
3643        Put put = new Put(Bytes.toBytes(i));
3644        put.setDurability(Durability.SKIP_WAL);
3645        put.addColumn(family, qual1, Bytes.toBytes(i % 10));
3646        region.put(put);
3647
3648        if (i != 0 && i % compactInterval == 0) {
3649          LOG.debug("iteration = " + i+ " ts="+System.currentTimeMillis());
3650          region.compact(true);
3651        }
3652
3653        if (i % 10 == 5L) {
3654          expectedCount++;
3655        }
3656
3657        if (i != 0 && i % flushAndScanInterval == 0) {
3658          res.clear();
3659          InternalScanner scanner = region.getScanner(scan);
3660          if (toggle) {
3661            flushThread.flush();
3662          }
3663          while (scanner.next(res))
3664            ;
3665          if (!toggle) {
3666            flushThread.flush();
3667          }
3668          assertEquals("toggle="+toggle+"i=" + i + " ts="+System.currentTimeMillis(),
3669              expectedCount, res.size());
3670          toggle = !toggle;
3671        }
3672      }
3673
3674    } finally {
3675      try {
3676        flushThread.done();
3677        flushThread.join();
3678        flushThread.checkNoError();
3679      } catch (InterruptedException ie) {
3680        LOG.warn("Caught exception when joining with flushThread", ie);
3681      }
3682      HBaseTestingUtility.closeRegionAndWAL(this.region);
3683      this.region = null;
3684    }
3685  }
3686
3687  protected class FlushThread extends Thread {
3688    private volatile boolean done;
3689    private Throwable error = null;
3690
3691    FlushThread() {
3692      super("FlushThread");
3693    }
3694
3695    public void done() {
3696      done = true;
3697      synchronized (this) {
3698        interrupt();
3699      }
3700    }
3701
3702    public void checkNoError() {
3703      if (error != null) {
3704        assertNull(error);
3705      }
3706    }
3707
3708    @Override
3709    public void run() {
3710      done = false;
3711      while (!done) {
3712        synchronized (this) {
3713          try {
3714            wait();
3715          } catch (InterruptedException ignored) {
3716            if (done) {
3717              break;
3718            }
3719          }
3720        }
3721        try {
3722          region.flush(true);
3723        } catch (IOException e) {
3724          if (!done) {
3725            LOG.error("Error while flushing cache", e);
3726            error = e;
3727          }
3728          break;
3729        } catch (Throwable t) {
3730          LOG.error("Uncaught exception", t);
3731          throw t;
3732        }
3733      }
3734    }
3735
3736    public void flush() {
3737      synchronized (this) {
3738        notify();
3739      }
3740    }
3741  }
3742
3743  /**
3744   * Writes very wide records and scans for the latest every time.. Flushes and
3745   * compacts the region every now and then to keep things realistic.
3746   *
3747   * @throws IOException
3748   *           by flush / scan / compaction
3749   * @throws InterruptedException
3750   *           when joining threads
3751   */
3752  @Test
3753  public void testWritesWhileScanning() throws IOException, InterruptedException {
3754    int testCount = 100;
3755    int numRows = 1;
3756    int numFamilies = 10;
3757    int numQualifiers = 100;
3758    int flushInterval = 7;
3759    int compactInterval = 5 * flushInterval;
3760    byte[][] families = new byte[numFamilies][];
3761    for (int i = 0; i < numFamilies; i++) {
3762      families[i] = Bytes.toBytes("family" + i);
3763    }
3764    byte[][] qualifiers = new byte[numQualifiers][];
3765    for (int i = 0; i < numQualifiers; i++) {
3766      qualifiers[i] = Bytes.toBytes("qual" + i);
3767    }
3768
3769    this.region = initHRegion(tableName, method, CONF, families);
3770    FlushThread flushThread = new FlushThread();
3771    PutThread putThread = new PutThread(numRows, families, qualifiers);
3772    try {
3773      putThread.start();
3774      putThread.waitForFirstPut();
3775
3776      flushThread.start();
3777
3778      Scan scan = new Scan(Bytes.toBytes("row0"), Bytes.toBytes("row1"));
3779
3780      int expectedCount = numFamilies * numQualifiers;
3781      List<Cell> res = new ArrayList<>();
3782
3783      long prevTimestamp = 0L;
3784      for (int i = 0; i < testCount; i++) {
3785
3786        if (i != 0 && i % compactInterval == 0) {
3787          region.compact(true);
3788          for (HStore store : region.getStores()) {
3789            store.closeAndArchiveCompactedFiles();
3790          }
3791        }
3792
3793        if (i != 0 && i % flushInterval == 0) {
3794          flushThread.flush();
3795        }
3796
3797        boolean previousEmpty = res.isEmpty();
3798        res.clear();
3799        InternalScanner scanner = region.getScanner(scan);
3800        while (scanner.next(res))
3801          ;
3802        if (!res.isEmpty() || !previousEmpty || i > compactInterval) {
3803          assertEquals("i=" + i, expectedCount, res.size());
3804          long timestamp = res.get(0).getTimestamp();
3805          assertTrue("Timestamps were broke: " + timestamp + " prev: " + prevTimestamp,
3806              timestamp >= prevTimestamp);
3807          prevTimestamp = timestamp;
3808        }
3809      }
3810
3811      putThread.done();
3812
3813      region.flush(true);
3814
3815    } finally {
3816      try {
3817        flushThread.done();
3818        flushThread.join();
3819        flushThread.checkNoError();
3820
3821        putThread.join();
3822        putThread.checkNoError();
3823      } catch (InterruptedException ie) {
3824        LOG.warn("Caught exception when joining with flushThread", ie);
3825      }
3826
3827      try {
3828          HBaseTestingUtility.closeRegionAndWAL(this.region);
3829      } catch (DroppedSnapshotException dse) {
3830        // We could get this on way out because we interrupt the background flusher and it could
3831        // fail anywhere causing a DSE over in the background flusher... only it is not properly
3832        // dealt with so could still be memory hanging out when we get to here -- memory we can't
3833        // flush because the accounting is 'off' since original DSE.
3834      }
3835      this.region = null;
3836    }
3837  }
3838
3839  protected class PutThread extends Thread {
3840    private volatile boolean done;
3841    private volatile int numPutsFinished = 0;
3842
3843    private Throwable error = null;
3844    private int numRows;
3845    private byte[][] families;
3846    private byte[][] qualifiers;
3847
3848    private PutThread(int numRows, byte[][] families, byte[][] qualifiers) {
3849      super("PutThread");
3850      this.numRows = numRows;
3851      this.families = families;
3852      this.qualifiers = qualifiers;
3853    }
3854
3855    /**
3856     * Block calling thread until this instance of PutThread has put at least one row.
3857     */
3858    public void waitForFirstPut() throws InterruptedException {
3859      // wait until put thread actually puts some data
3860      while (isAlive() && numPutsFinished == 0) {
3861        checkNoError();
3862        Thread.sleep(50);
3863      }
3864    }
3865
3866    public void done() {
3867      done = true;
3868      synchronized (this) {
3869        interrupt();
3870      }
3871    }
3872
3873    public void checkNoError() {
3874      if (error != null) {
3875        assertNull(error);
3876      }
3877    }
3878
3879    @Override
3880    public void run() {
3881      done = false;
3882      while (!done) {
3883        try {
3884          for (int r = 0; r < numRows; r++) {
3885            byte[] row = Bytes.toBytes("row" + r);
3886            Put put = new Put(row);
3887            put.setDurability(Durability.SKIP_WAL);
3888            byte[] value = Bytes.toBytes(String.valueOf(numPutsFinished));
3889            for (byte[] family : families) {
3890              for (byte[] qualifier : qualifiers) {
3891                put.addColumn(family, qualifier, numPutsFinished, value);
3892              }
3893            }
3894            region.put(put);
3895            numPutsFinished++;
3896            if (numPutsFinished > 0 && numPutsFinished % 47 == 0) {
3897              System.out.println("put iteration = " + numPutsFinished);
3898              Delete delete = new Delete(row, (long) numPutsFinished - 30);
3899              region.delete(delete);
3900            }
3901            numPutsFinished++;
3902          }
3903        } catch (InterruptedIOException e) {
3904          // This is fine. It means we are done, or didn't get the lock on time
3905          LOG.info("Interrupted", e);
3906        } catch (IOException e) {
3907          LOG.error("Error while putting records", e);
3908          error = e;
3909          break;
3910        }
3911      }
3912
3913    }
3914
3915  }
3916
3917  /**
3918   * Writes very wide records and gets the latest row every time.. Flushes and
3919   * compacts the region aggressivly to catch issues.
3920   *
3921   * @throws IOException
3922   *           by flush / scan / compaction
3923   * @throws InterruptedException
3924   *           when joining threads
3925   */
3926  @Test
3927  public void testWritesWhileGetting() throws Exception {
3928    int testCount = 50;
3929    int numRows = 1;
3930    int numFamilies = 10;
3931    int numQualifiers = 100;
3932    int compactInterval = 100;
3933    byte[][] families = new byte[numFamilies][];
3934    for (int i = 0; i < numFamilies; i++) {
3935      families[i] = Bytes.toBytes("family" + i);
3936    }
3937    byte[][] qualifiers = new byte[numQualifiers][];
3938    for (int i = 0; i < numQualifiers; i++) {
3939      qualifiers[i] = Bytes.toBytes("qual" + i);
3940    }
3941
3942
3943    // This test flushes constantly and can cause many files to be created,
3944    // possibly
3945    // extending over the ulimit. Make sure compactions are aggressive in
3946    // reducing
3947    // the number of HFiles created.
3948    Configuration conf = HBaseConfiguration.create(CONF);
3949    conf.setInt("hbase.hstore.compaction.min", 1);
3950    conf.setInt("hbase.hstore.compaction.max", 1000);
3951    this.region = initHRegion(tableName, method, conf, families);
3952    PutThread putThread = null;
3953    MultithreadedTestUtil.TestContext ctx = new MultithreadedTestUtil.TestContext(conf);
3954    try {
3955      putThread = new PutThread(numRows, families, qualifiers);
3956      putThread.start();
3957      putThread.waitForFirstPut();
3958
3959      // Add a thread that flushes as fast as possible
3960      ctx.addThread(new RepeatingTestThread(ctx) {
3961
3962        @Override
3963        public void doAnAction() throws Exception {
3964          region.flush(true);
3965          // Compact regularly to avoid creating too many files and exceeding
3966          // the ulimit.
3967          region.compact(false);
3968          for (HStore store : region.getStores()) {
3969            store.closeAndArchiveCompactedFiles();
3970          }
3971        }
3972      });
3973      ctx.startThreads();
3974
3975      Get get = new Get(Bytes.toBytes("row0"));
3976      Result result = null;
3977
3978      int expectedCount = numFamilies * numQualifiers;
3979
3980      long prevTimestamp = 0L;
3981      for (int i = 0; i < testCount; i++) {
3982        LOG.info("testWritesWhileGetting verify turn " + i);
3983        boolean previousEmpty = result == null || result.isEmpty();
3984        result = region.get(get);
3985        if (!result.isEmpty() || !previousEmpty || i > compactInterval) {
3986          assertEquals("i=" + i, expectedCount, result.size());
3987          // TODO this was removed, now what dangit?!
3988          // search looking for the qualifier in question?
3989          long timestamp = 0;
3990          for (Cell kv : result.rawCells()) {
3991            if (CellUtil.matchingFamily(kv, families[0])
3992                && CellUtil.matchingQualifier(kv, qualifiers[0])) {
3993              timestamp = kv.getTimestamp();
3994            }
3995          }
3996          assertTrue(timestamp >= prevTimestamp);
3997          prevTimestamp = timestamp;
3998          Cell previousKV = null;
3999
4000          for (Cell kv : result.rawCells()) {
4001            byte[] thisValue = CellUtil.cloneValue(kv);
4002            if (previousKV != null) {
4003              if (Bytes.compareTo(CellUtil.cloneValue(previousKV), thisValue) != 0) {
4004                LOG.warn("These two KV should have the same value." + " Previous KV:" + previousKV
4005                    + "(memStoreTS:" + previousKV.getSequenceId() + ")" + ", New KV: " + kv
4006                    + "(memStoreTS:" + kv.getSequenceId() + ")");
4007                assertEquals(0, Bytes.compareTo(CellUtil.cloneValue(previousKV), thisValue));
4008              }
4009            }
4010            previousKV = kv;
4011          }
4012        }
4013      }
4014    } finally {
4015      if (putThread != null)
4016        putThread.done();
4017
4018      region.flush(true);
4019
4020      if (putThread != null) {
4021        putThread.join();
4022        putThread.checkNoError();
4023      }
4024
4025      ctx.stop();
4026      HBaseTestingUtility.closeRegionAndWAL(this.region);
4027      this.region = null;
4028    }
4029  }
4030
4031  @Test
4032  public void testHolesInMeta() throws Exception {
4033    byte[] family = Bytes.toBytes("family");
4034    this.region = initHRegion(tableName, Bytes.toBytes("x"), Bytes.toBytes("z"), method, CONF,
4035        false, family);
4036    try {
4037      byte[] rowNotServed = Bytes.toBytes("a");
4038      Get g = new Get(rowNotServed);
4039      try {
4040        region.get(g);
4041        fail();
4042      } catch (WrongRegionException x) {
4043        // OK
4044      }
4045      byte[] row = Bytes.toBytes("y");
4046      g = new Get(row);
4047      region.get(g);
4048    } finally {
4049      HBaseTestingUtility.closeRegionAndWAL(this.region);
4050      this.region = null;
4051    }
4052  }
4053
4054  @Test
4055  public void testIndexesScanWithOneDeletedRow() throws IOException {
4056    byte[] family = Bytes.toBytes("family");
4057
4058    // Setting up region
4059    this.region = initHRegion(tableName, method, CONF, family);
4060    try {
4061      Put put = new Put(Bytes.toBytes(1L));
4062      put.addColumn(family, qual1, 1L, Bytes.toBytes(1L));
4063      region.put(put);
4064
4065      region.flush(true);
4066
4067      Delete delete = new Delete(Bytes.toBytes(1L), 1L);
4068      region.delete(delete);
4069
4070      put = new Put(Bytes.toBytes(2L));
4071      put.addColumn(family, qual1, 2L, Bytes.toBytes(2L));
4072      region.put(put);
4073
4074      Scan idxScan = new Scan();
4075      idxScan.addFamily(family);
4076      idxScan.setFilter(new FilterList(FilterList.Operator.MUST_PASS_ALL, Arrays.<Filter> asList(
4077          new SingleColumnValueFilter(family, qual1, CompareOp.GREATER_OR_EQUAL,
4078              new BinaryComparator(Bytes.toBytes(0L))), new SingleColumnValueFilter(family, qual1,
4079              CompareOp.LESS_OR_EQUAL, new BinaryComparator(Bytes.toBytes(3L))))));
4080      InternalScanner scanner = region.getScanner(idxScan);
4081      List<Cell> res = new ArrayList<>();
4082
4083      while (scanner.next(res))
4084        ;
4085      assertEquals(1L, res.size());
4086    } finally {
4087      HBaseTestingUtility.closeRegionAndWAL(this.region);
4088      this.region = null;
4089    }
4090  }
4091
4092  // ////////////////////////////////////////////////////////////////////////////
4093  // Bloom filter test
4094  // ////////////////////////////////////////////////////////////////////////////
4095  @Test
4096  public void testBloomFilterSize() throws IOException {
4097    byte[] fam1 = Bytes.toBytes("fam1");
4098    byte[] qf1 = Bytes.toBytes("col");
4099    byte[] val1 = Bytes.toBytes("value1");
4100    // Create Table
4101    HColumnDescriptor hcd = new HColumnDescriptor(fam1).setMaxVersions(Integer.MAX_VALUE)
4102        .setBloomFilterType(BloomType.ROWCOL);
4103
4104    HTableDescriptor htd = new HTableDescriptor(tableName);
4105    htd.addFamily(hcd);
4106    HRegionInfo info = new HRegionInfo(htd.getTableName(), null, null, false);
4107    this.region = TEST_UTIL.createLocalHRegion(info, htd);
4108    try {
4109      int num_unique_rows = 10;
4110      int duplicate_multiplier = 2;
4111      int num_storefiles = 4;
4112
4113      int version = 0;
4114      for (int f = 0; f < num_storefiles; f++) {
4115        for (int i = 0; i < duplicate_multiplier; i++) {
4116          for (int j = 0; j < num_unique_rows; j++) {
4117            Put put = new Put(Bytes.toBytes("row" + j));
4118            put.setDurability(Durability.SKIP_WAL);
4119            long ts = version++;
4120            put.addColumn(fam1, qf1, ts, val1);
4121            region.put(put);
4122          }
4123        }
4124        region.flush(true);
4125      }
4126      // before compaction
4127      HStore store = region.getStore(fam1);
4128      Collection<HStoreFile> storeFiles = store.getStorefiles();
4129      for (HStoreFile storefile : storeFiles) {
4130        StoreFileReader reader = storefile.getReader();
4131        reader.loadFileInfo();
4132        reader.loadBloomfilter();
4133        assertEquals(num_unique_rows * duplicate_multiplier, reader.getEntries());
4134        assertEquals(num_unique_rows, reader.getFilterEntries());
4135      }
4136
4137      region.compact(true);
4138
4139      // after compaction
4140      storeFiles = store.getStorefiles();
4141      for (HStoreFile storefile : storeFiles) {
4142        StoreFileReader reader = storefile.getReader();
4143        reader.loadFileInfo();
4144        reader.loadBloomfilter();
4145        assertEquals(num_unique_rows * duplicate_multiplier * num_storefiles, reader.getEntries());
4146        assertEquals(num_unique_rows, reader.getFilterEntries());
4147      }
4148    } finally {
4149      HBaseTestingUtility.closeRegionAndWAL(this.region);
4150      this.region = null;
4151    }
4152  }
4153
4154  @Test
4155  public void testAllColumnsWithBloomFilter() throws IOException {
4156    byte[] TABLE = Bytes.toBytes(name.getMethodName());
4157    byte[] FAMILY = Bytes.toBytes("family");
4158
4159    // Create table
4160    HColumnDescriptor hcd = new HColumnDescriptor(FAMILY).setMaxVersions(Integer.MAX_VALUE)
4161        .setBloomFilterType(BloomType.ROWCOL);
4162    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(TABLE));
4163    htd.addFamily(hcd);
4164    HRegionInfo info = new HRegionInfo(htd.getTableName(), null, null, false);
4165    this.region = TEST_UTIL.createLocalHRegion(info, htd);
4166    try {
4167      // For row:0, col:0: insert versions 1 through 5.
4168      byte row[] = Bytes.toBytes("row:" + 0);
4169      byte column[] = Bytes.toBytes("column:" + 0);
4170      Put put = new Put(row);
4171      put.setDurability(Durability.SKIP_WAL);
4172      for (long idx = 1; idx <= 4; idx++) {
4173        put.addColumn(FAMILY, column, idx, Bytes.toBytes("value-version-" + idx));
4174      }
4175      region.put(put);
4176
4177      // Flush
4178      region.flush(true);
4179
4180      // Get rows
4181      Get get = new Get(row);
4182      get.setMaxVersions();
4183      Cell[] kvs = region.get(get).rawCells();
4184
4185      // Check if rows are correct
4186      assertEquals(4, kvs.length);
4187      checkOneCell(kvs[0], FAMILY, 0, 0, 4);
4188      checkOneCell(kvs[1], FAMILY, 0, 0, 3);
4189      checkOneCell(kvs[2], FAMILY, 0, 0, 2);
4190      checkOneCell(kvs[3], FAMILY, 0, 0, 1);
4191    } finally {
4192      HBaseTestingUtility.closeRegionAndWAL(this.region);
4193      this.region = null;
4194    }
4195  }
4196
4197  /**
4198   * Testcase to cover bug-fix for HBASE-2823 Ensures correct delete when
4199   * issuing delete row on columns with bloom filter set to row+col
4200   * (BloomType.ROWCOL)
4201   */
4202  @Test
4203  public void testDeleteRowWithBloomFilter() throws IOException {
4204    byte[] familyName = Bytes.toBytes("familyName");
4205
4206    // Create Table
4207    HColumnDescriptor hcd = new HColumnDescriptor(familyName).setMaxVersions(Integer.MAX_VALUE)
4208        .setBloomFilterType(BloomType.ROWCOL);
4209
4210    HTableDescriptor htd = new HTableDescriptor(tableName);
4211    htd.addFamily(hcd);
4212    HRegionInfo info = new HRegionInfo(htd.getTableName(), null, null, false);
4213    this.region = TEST_UTIL.createLocalHRegion(info, htd);
4214    try {
4215      // Insert some data
4216      byte row[] = Bytes.toBytes("row1");
4217      byte col[] = Bytes.toBytes("col1");
4218
4219      Put put = new Put(row);
4220      put.addColumn(familyName, col, 1, Bytes.toBytes("SomeRandomValue"));
4221      region.put(put);
4222      region.flush(true);
4223
4224      Delete del = new Delete(row);
4225      region.delete(del);
4226      region.flush(true);
4227
4228      // Get remaining rows (should have none)
4229      Get get = new Get(row);
4230      get.addColumn(familyName, col);
4231
4232      Cell[] keyValues = region.get(get).rawCells();
4233      assertTrue(keyValues.length == 0);
4234    } finally {
4235      HBaseTestingUtility.closeRegionAndWAL(this.region);
4236      this.region = null;
4237    }
4238  }
4239
4240  @Test
4241  public void testgetHDFSBlocksDistribution() throws Exception {
4242    HBaseTestingUtility htu = new HBaseTestingUtility();
4243    // Why do we set the block size in this test?  If we set it smaller than the kvs, then we'll
4244    // break up the file in to more pieces that can be distributed across the three nodes and we
4245    // won't be able to have the condition this test asserts; that at least one node has
4246    // a copy of all replicas -- if small block size, then blocks are spread evenly across the
4247    // the three nodes.  hfilev3 with tags seems to put us over the block size.  St.Ack.
4248    // final int DEFAULT_BLOCK_SIZE = 1024;
4249    // htu.getConfiguration().setLong("dfs.blocksize", DEFAULT_BLOCK_SIZE);
4250    htu.getConfiguration().setInt("dfs.replication", 2);
4251
4252    // set up a cluster with 3 nodes
4253    MiniHBaseCluster cluster = null;
4254    String dataNodeHosts[] = new String[] { "host1", "host2", "host3" };
4255    int regionServersCount = 3;
4256
4257    try {
4258      cluster = htu.startMiniCluster(1, regionServersCount, dataNodeHosts);
4259      byte[][] families = { fam1, fam2 };
4260      Table ht = htu.createTable(tableName, families);
4261
4262      // Setting up region
4263      byte row[] = Bytes.toBytes("row1");
4264      byte col[] = Bytes.toBytes("col1");
4265
4266      Put put = new Put(row);
4267      put.addColumn(fam1, col, 1, Bytes.toBytes("test1"));
4268      put.addColumn(fam2, col, 1, Bytes.toBytes("test2"));
4269      ht.put(put);
4270
4271      HRegion firstRegion = htu.getHBaseCluster().getRegions(tableName).get(0);
4272      firstRegion.flush(true);
4273      HDFSBlocksDistribution blocksDistribution1 = firstRegion.getHDFSBlocksDistribution();
4274
4275      // Given the default replication factor is 2 and we have 2 HFiles,
4276      // we will have total of 4 replica of blocks on 3 datanodes; thus there
4277      // must be at least one host that have replica for 2 HFiles. That host's
4278      // weight will be equal to the unique block weight.
4279      long uniqueBlocksWeight1 = blocksDistribution1.getUniqueBlocksTotalWeight();
4280      StringBuilder sb = new StringBuilder();
4281      for (String host: blocksDistribution1.getTopHosts()) {
4282        if (sb.length() > 0) sb.append(", ");
4283        sb.append(host);
4284        sb.append("=");
4285        sb.append(blocksDistribution1.getWeight(host));
4286      }
4287
4288      String topHost = blocksDistribution1.getTopHosts().get(0);
4289      long topHostWeight = blocksDistribution1.getWeight(topHost);
4290      String msg = "uniqueBlocksWeight=" + uniqueBlocksWeight1 + ", topHostWeight=" +
4291        topHostWeight + ", topHost=" + topHost + "; " + sb.toString();
4292      LOG.info(msg);
4293      assertTrue(msg, uniqueBlocksWeight1 == topHostWeight);
4294
4295      // use the static method to compute the value, it should be the same.
4296      // static method is used by load balancer or other components
4297      HDFSBlocksDistribution blocksDistribution2 = HRegion.computeHDFSBlocksDistribution(
4298          htu.getConfiguration(), firstRegion.getTableDescriptor(), firstRegion.getRegionInfo());
4299      long uniqueBlocksWeight2 = blocksDistribution2.getUniqueBlocksTotalWeight();
4300
4301      assertTrue(uniqueBlocksWeight1 == uniqueBlocksWeight2);
4302
4303      ht.close();
4304    } finally {
4305      if (cluster != null) {
4306        htu.shutdownMiniCluster();
4307      }
4308    }
4309  }
4310
4311  /**
4312   * Testcase to check state of region initialization task set to ABORTED or not
4313   * if any exceptions during initialization
4314   *
4315   * @throws Exception
4316   */
4317  @Test
4318  public void testStatusSettingToAbortIfAnyExceptionDuringRegionInitilization() throws Exception {
4319    HRegionInfo info;
4320    try {
4321      FileSystem fs = Mockito.mock(FileSystem.class);
4322      Mockito.when(fs.exists((Path) Mockito.anyObject())).thenThrow(new IOException());
4323      HTableDescriptor htd = new HTableDescriptor(tableName);
4324      htd.addFamily(new HColumnDescriptor("cf"));
4325      info = new HRegionInfo(htd.getTableName(), HConstants.EMPTY_BYTE_ARRAY,
4326          HConstants.EMPTY_BYTE_ARRAY, false);
4327      Path path = new Path(dir + "testStatusSettingToAbortIfAnyExceptionDuringRegionInitilization");
4328      region = HRegion.newHRegion(path, null, fs, CONF, info, htd, null);
4329      // region initialization throws IOException and set task state to ABORTED.
4330      region.initialize();
4331      fail("Region initialization should fail due to IOException");
4332    } catch (IOException io) {
4333      List<MonitoredTask> tasks = TaskMonitor.get().getTasks();
4334      for (MonitoredTask monitoredTask : tasks) {
4335        if (!(monitoredTask instanceof MonitoredRPCHandler)
4336            && monitoredTask.getDescription().contains(region.toString())) {
4337          assertTrue("Region state should be ABORTED.",
4338              monitoredTask.getState().equals(MonitoredTask.State.ABORTED));
4339          break;
4340        }
4341      }
4342    } finally {
4343      HBaseTestingUtility.closeRegionAndWAL(region);
4344    }
4345  }
4346
4347  /**
4348   * Verifies that the .regioninfo file is written on region creation and that
4349   * is recreated if missing during region opening.
4350   */
4351  @Test
4352  public void testRegionInfoFileCreation() throws IOException {
4353    Path rootDir = new Path(dir + "testRegionInfoFileCreation");
4354
4355    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName()));
4356    htd.addFamily(new HColumnDescriptor("cf"));
4357
4358    HRegionInfo hri = new HRegionInfo(htd.getTableName());
4359
4360    // Create a region and skip the initialization (like CreateTableHandler)
4361    HRegion region = HBaseTestingUtility.createRegionAndWAL(hri, rootDir, CONF, htd, false);
4362    Path regionDir = region.getRegionFileSystem().getRegionDir();
4363    FileSystem fs = region.getRegionFileSystem().getFileSystem();
4364    HBaseTestingUtility.closeRegionAndWAL(region);
4365
4366    Path regionInfoFile = new Path(regionDir, HRegionFileSystem.REGION_INFO_FILE);
4367
4368    // Verify that the .regioninfo file is present
4369    assertTrue(HRegionFileSystem.REGION_INFO_FILE + " should be present in the region dir",
4370        fs.exists(regionInfoFile));
4371
4372    // Try to open the region
4373    region = HRegion.openHRegion(rootDir, hri, htd, null, CONF);
4374    assertEquals(regionDir, region.getRegionFileSystem().getRegionDir());
4375    HBaseTestingUtility.closeRegionAndWAL(region);
4376
4377    // Verify that the .regioninfo file is still there
4378    assertTrue(HRegionFileSystem.REGION_INFO_FILE + " should be present in the region dir",
4379        fs.exists(regionInfoFile));
4380
4381    // Remove the .regioninfo file and verify is recreated on region open
4382    fs.delete(regionInfoFile, true);
4383    assertFalse(HRegionFileSystem.REGION_INFO_FILE + " should be removed from the region dir",
4384        fs.exists(regionInfoFile));
4385
4386    region = HRegion.openHRegion(rootDir, hri, htd, null, CONF);
4387//    region = TEST_UTIL.openHRegion(hri, htd);
4388    assertEquals(regionDir, region.getRegionFileSystem().getRegionDir());
4389    HBaseTestingUtility.closeRegionAndWAL(region);
4390
4391    // Verify that the .regioninfo file is still there
4392    assertTrue(HRegionFileSystem.REGION_INFO_FILE + " should be present in the region dir",
4393        fs.exists(new Path(regionDir, HRegionFileSystem.REGION_INFO_FILE)));
4394  }
4395
4396  /**
4397   * TestCase for increment
4398   */
4399  private static class Incrementer implements Runnable {
4400    private HRegion region;
4401    private final static byte[] incRow = Bytes.toBytes("incRow");
4402    private final static byte[] family = Bytes.toBytes("family");
4403    private final static byte[] qualifier = Bytes.toBytes("qualifier");
4404    private final static long ONE = 1L;
4405    private int incCounter;
4406
4407    public Incrementer(HRegion region, int incCounter) {
4408      this.region = region;
4409      this.incCounter = incCounter;
4410    }
4411
4412    @Override
4413    public void run() {
4414      int count = 0;
4415      while (count < incCounter) {
4416        Increment inc = new Increment(incRow);
4417        inc.addColumn(family, qualifier, ONE);
4418        count++;
4419        try {
4420          region.increment(inc);
4421        } catch (IOException e) {
4422          LOG.info("Count=" + count + ", " + e);
4423          break;
4424        }
4425      }
4426    }
4427  }
4428
4429  /**
4430   * Test case to check increment function with memstore flushing
4431   * @throws Exception
4432   */
4433  @Test
4434  public void testParallelIncrementWithMemStoreFlush() throws Exception {
4435    byte[] family = Incrementer.family;
4436    this.region = initHRegion(tableName, method, CONF, family);
4437    final HRegion region = this.region;
4438    final AtomicBoolean incrementDone = new AtomicBoolean(false);
4439    Runnable flusher = new Runnable() {
4440      @Override
4441      public void run() {
4442        while (!incrementDone.get()) {
4443          try {
4444            region.flush(true);
4445          } catch (Exception e) {
4446            e.printStackTrace();
4447          }
4448        }
4449      }
4450    };
4451
4452    // after all increment finished, the row will increment to 20*100 = 2000
4453    int threadNum = 20;
4454    int incCounter = 100;
4455    long expected = (long) threadNum * incCounter;
4456    Thread[] incrementers = new Thread[threadNum];
4457    Thread flushThread = new Thread(flusher);
4458    for (int i = 0; i < threadNum; i++) {
4459      incrementers[i] = new Thread(new Incrementer(this.region, incCounter));
4460      incrementers[i].start();
4461    }
4462    flushThread.start();
4463    for (int i = 0; i < threadNum; i++) {
4464      incrementers[i].join();
4465    }
4466
4467    incrementDone.set(true);
4468    flushThread.join();
4469
4470    Get get = new Get(Incrementer.incRow);
4471    get.addColumn(Incrementer.family, Incrementer.qualifier);
4472    get.setMaxVersions(1);
4473    Result res = this.region.get(get);
4474    List<Cell> kvs = res.getColumnCells(Incrementer.family, Incrementer.qualifier);
4475
4476    // we just got the latest version
4477    assertEquals(1, kvs.size());
4478    Cell kv = kvs.get(0);
4479    assertEquals(expected, Bytes.toLong(kv.getValueArray(), kv.getValueOffset()));
4480    this.region = null;
4481  }
4482
4483  /**
4484   * TestCase for append
4485   */
4486  private static class Appender implements Runnable {
4487    private HRegion region;
4488    private final static byte[] appendRow = Bytes.toBytes("appendRow");
4489    private final static byte[] family = Bytes.toBytes("family");
4490    private final static byte[] qualifier = Bytes.toBytes("qualifier");
4491    private final static byte[] CHAR = Bytes.toBytes("a");
4492    private int appendCounter;
4493
4494    public Appender(HRegion region, int appendCounter) {
4495      this.region = region;
4496      this.appendCounter = appendCounter;
4497    }
4498
4499    @Override
4500    public void run() {
4501      int count = 0;
4502      while (count < appendCounter) {
4503        Append app = new Append(appendRow);
4504        app.addColumn(family, qualifier, CHAR);
4505        count++;
4506        try {
4507          region.append(app);
4508        } catch (IOException e) {
4509          LOG.info("Count=" + count + ", max=" + appendCounter + ", " + e);
4510          break;
4511        }
4512      }
4513    }
4514  }
4515
4516  /**
4517   * Test case to check append function with memstore flushing
4518   * @throws Exception
4519   */
4520  @Test
4521  public void testParallelAppendWithMemStoreFlush() throws Exception {
4522    byte[] family = Appender.family;
4523    this.region = initHRegion(tableName, method, CONF, family);
4524    final HRegion region = this.region;
4525    final AtomicBoolean appendDone = new AtomicBoolean(false);
4526    Runnable flusher = new Runnable() {
4527      @Override
4528      public void run() {
4529        while (!appendDone.get()) {
4530          try {
4531            region.flush(true);
4532          } catch (Exception e) {
4533            e.printStackTrace();
4534          }
4535        }
4536      }
4537    };
4538
4539    // After all append finished, the value will append to threadNum *
4540    // appendCounter Appender.CHAR
4541    int threadNum = 20;
4542    int appendCounter = 100;
4543    byte[] expected = new byte[threadNum * appendCounter];
4544    for (int i = 0; i < threadNum * appendCounter; i++) {
4545      System.arraycopy(Appender.CHAR, 0, expected, i, 1);
4546    }
4547    Thread[] appenders = new Thread[threadNum];
4548    Thread flushThread = new Thread(flusher);
4549    for (int i = 0; i < threadNum; i++) {
4550      appenders[i] = new Thread(new Appender(this.region, appendCounter));
4551      appenders[i].start();
4552    }
4553    flushThread.start();
4554    for (int i = 0; i < threadNum; i++) {
4555      appenders[i].join();
4556    }
4557
4558    appendDone.set(true);
4559    flushThread.join();
4560
4561    Get get = new Get(Appender.appendRow);
4562    get.addColumn(Appender.family, Appender.qualifier);
4563    get.setMaxVersions(1);
4564    Result res = this.region.get(get);
4565    List<Cell> kvs = res.getColumnCells(Appender.family, Appender.qualifier);
4566
4567    // we just got the latest version
4568    assertEquals(1, kvs.size());
4569    Cell kv = kvs.get(0);
4570    byte[] appendResult = new byte[kv.getValueLength()];
4571    System.arraycopy(kv.getValueArray(), kv.getValueOffset(), appendResult, 0, kv.getValueLength());
4572    assertArrayEquals(expected, appendResult);
4573    this.region = null;
4574  }
4575
4576  /**
4577   * Test case to check put function with memstore flushing for same row, same ts
4578   * @throws Exception
4579   */
4580  @Test
4581  public void testPutWithMemStoreFlush() throws Exception {
4582    byte[] family = Bytes.toBytes("family");
4583    byte[] qualifier = Bytes.toBytes("qualifier");
4584    byte[] row = Bytes.toBytes("putRow");
4585    byte[] value = null;
4586    this.region = initHRegion(tableName, method, CONF, family);
4587    Put put = null;
4588    Get get = null;
4589    List<Cell> kvs = null;
4590    Result res = null;
4591
4592    put = new Put(row);
4593    value = Bytes.toBytes("value0");
4594    put.addColumn(family, qualifier, 1234567L, value);
4595    region.put(put);
4596    get = new Get(row);
4597    get.addColumn(family, qualifier);
4598    get.setMaxVersions();
4599    res = this.region.get(get);
4600    kvs = res.getColumnCells(family, qualifier);
4601    assertEquals(1, kvs.size());
4602    assertArrayEquals(Bytes.toBytes("value0"), CellUtil.cloneValue(kvs.get(0)));
4603
4604    region.flush(true);
4605    get = new Get(row);
4606    get.addColumn(family, qualifier);
4607    get.setMaxVersions();
4608    res = this.region.get(get);
4609    kvs = res.getColumnCells(family, qualifier);
4610    assertEquals(1, kvs.size());
4611    assertArrayEquals(Bytes.toBytes("value0"), CellUtil.cloneValue(kvs.get(0)));
4612
4613    put = new Put(row);
4614    value = Bytes.toBytes("value1");
4615    put.addColumn(family, qualifier, 1234567L, value);
4616    region.put(put);
4617    get = new Get(row);
4618    get.addColumn(family, qualifier);
4619    get.setMaxVersions();
4620    res = this.region.get(get);
4621    kvs = res.getColumnCells(family, qualifier);
4622    assertEquals(1, kvs.size());
4623    assertArrayEquals(Bytes.toBytes("value1"), CellUtil.cloneValue(kvs.get(0)));
4624
4625    region.flush(true);
4626    get = new Get(row);
4627    get.addColumn(family, qualifier);
4628    get.setMaxVersions();
4629    res = this.region.get(get);
4630    kvs = res.getColumnCells(family, qualifier);
4631    assertEquals(1, kvs.size());
4632    assertArrayEquals(Bytes.toBytes("value1"), CellUtil.cloneValue(kvs.get(0)));
4633  }
4634
4635  @Test
4636  public void testDurability() throws Exception {
4637    // there are 5 x 5 cases:
4638    // table durability(SYNC,FSYNC,ASYC,SKIP,USE_DEFAULT) x mutation
4639    // durability(SYNC,FSYNC,ASYC,SKIP,USE_DEFAULT)
4640
4641    // expected cases for append and sync wal
4642    durabilityTest(method, Durability.SYNC_WAL, Durability.SYNC_WAL, 0, true, true, false);
4643    durabilityTest(method, Durability.SYNC_WAL, Durability.FSYNC_WAL, 0, true, true, false);
4644    durabilityTest(method, Durability.SYNC_WAL, Durability.USE_DEFAULT, 0, true, true, false);
4645
4646    durabilityTest(method, Durability.FSYNC_WAL, Durability.SYNC_WAL, 0, true, true, false);
4647    durabilityTest(method, Durability.FSYNC_WAL, Durability.FSYNC_WAL, 0, true, true, false);
4648    durabilityTest(method, Durability.FSYNC_WAL, Durability.USE_DEFAULT, 0, true, true, false);
4649
4650    durabilityTest(method, Durability.ASYNC_WAL, Durability.SYNC_WAL, 0, true, true, false);
4651    durabilityTest(method, Durability.ASYNC_WAL, Durability.FSYNC_WAL, 0, true, true, false);
4652
4653    durabilityTest(method, Durability.SKIP_WAL, Durability.SYNC_WAL, 0, true, true, false);
4654    durabilityTest(method, Durability.SKIP_WAL, Durability.FSYNC_WAL, 0, true, true, false);
4655
4656    durabilityTest(method, Durability.USE_DEFAULT, Durability.SYNC_WAL, 0, true, true, false);
4657    durabilityTest(method, Durability.USE_DEFAULT, Durability.FSYNC_WAL, 0, true, true, false);
4658    durabilityTest(method, Durability.USE_DEFAULT, Durability.USE_DEFAULT, 0, true, true, false);
4659
4660    // expected cases for async wal
4661    durabilityTest(method, Durability.SYNC_WAL, Durability.ASYNC_WAL, 0, true, false, false);
4662    durabilityTest(method, Durability.FSYNC_WAL, Durability.ASYNC_WAL, 0, true, false, false);
4663    durabilityTest(method, Durability.ASYNC_WAL, Durability.ASYNC_WAL, 0, true, false, false);
4664    durabilityTest(method, Durability.SKIP_WAL, Durability.ASYNC_WAL, 0, true, false, false);
4665    durabilityTest(method, Durability.USE_DEFAULT, Durability.ASYNC_WAL, 0, true, false, false);
4666    durabilityTest(method, Durability.ASYNC_WAL, Durability.USE_DEFAULT, 0, true, false, false);
4667
4668    durabilityTest(method, Durability.SYNC_WAL, Durability.ASYNC_WAL, 5000, true, false, true);
4669    durabilityTest(method, Durability.FSYNC_WAL, Durability.ASYNC_WAL, 5000, true, false, true);
4670    durabilityTest(method, Durability.ASYNC_WAL, Durability.ASYNC_WAL, 5000, true, false, true);
4671    durabilityTest(method, Durability.SKIP_WAL, Durability.ASYNC_WAL, 5000, true, false, true);
4672    durabilityTest(method, Durability.USE_DEFAULT, Durability.ASYNC_WAL, 5000, true, false, true);
4673    durabilityTest(method, Durability.ASYNC_WAL, Durability.USE_DEFAULT, 5000, true, false, true);
4674
4675    // expect skip wal cases
4676    durabilityTest(method, Durability.SYNC_WAL, Durability.SKIP_WAL, 0, false, false, false);
4677    durabilityTest(method, Durability.FSYNC_WAL, Durability.SKIP_WAL, 0, false, false, false);
4678    durabilityTest(method, Durability.ASYNC_WAL, Durability.SKIP_WAL, 0, false, false, false);
4679    durabilityTest(method, Durability.SKIP_WAL, Durability.SKIP_WAL, 0, false, false, false);
4680    durabilityTest(method, Durability.USE_DEFAULT, Durability.SKIP_WAL, 0, false, false, false);
4681    durabilityTest(method, Durability.SKIP_WAL, Durability.USE_DEFAULT, 0, false, false, false);
4682
4683  }
4684
4685  private void durabilityTest(String method, Durability tableDurability,
4686      Durability mutationDurability, long timeout, boolean expectAppend, final boolean expectSync,
4687      final boolean expectSyncFromLogSyncer) throws Exception {
4688    Configuration conf = HBaseConfiguration.create(CONF);
4689    method = method + "_" + tableDurability.name() + "_" + mutationDurability.name();
4690    byte[] family = Bytes.toBytes("family");
4691    Path logDir = new Path(new Path(dir + method), "log");
4692    final Configuration walConf = new Configuration(conf);
4693    FSUtils.setRootDir(walConf, logDir);
4694    // XXX: The spied AsyncFSWAL can not work properly because of a Mockito defect that can not
4695    // deal with classes which have a field of an inner class. See discussions in HBASE-15536.
4696    walConf.set(WALFactory.WAL_PROVIDER, "filesystem");
4697    final WALFactory wals = new WALFactory(walConf, UUID.randomUUID().toString());
4698    final WAL wal = spy(wals.getWAL(RegionInfoBuilder.newBuilder(tableName).build()));
4699    this.region = initHRegion(tableName, HConstants.EMPTY_START_ROW,
4700        HConstants.EMPTY_END_ROW, false, tableDurability, wal,
4701        new byte[][] { family });
4702
4703    Put put = new Put(Bytes.toBytes("r1"));
4704    put.addColumn(family, Bytes.toBytes("q1"), Bytes.toBytes("v1"));
4705    put.setDurability(mutationDurability);
4706    region.put(put);
4707
4708    //verify append called or not
4709    verify(wal, expectAppend ? times(1) : never())
4710      .append((HRegionInfo)any(), (WALKeyImpl)any(),
4711          (WALEdit)any(), Mockito.anyBoolean());
4712
4713    // verify sync called or not
4714    if (expectSync || expectSyncFromLogSyncer) {
4715      TEST_UTIL.waitFor(timeout, new Waiter.Predicate<Exception>() {
4716        @Override
4717        public boolean evaluate() throws Exception {
4718          try {
4719            if (expectSync) {
4720              verify(wal, times(1)).sync(anyLong()); // Hregion calls this one
4721            } else if (expectSyncFromLogSyncer) {
4722              verify(wal, times(1)).sync(); // wal syncer calls this one
4723            }
4724          } catch (Throwable ignore) {
4725          }
4726          return true;
4727        }
4728      });
4729    } else {
4730      //verify(wal, never()).sync(anyLong());
4731      verify(wal, never()).sync();
4732    }
4733
4734    HBaseTestingUtility.closeRegionAndWAL(this.region);
4735    wals.close();
4736    this.region = null;
4737  }
4738
4739  @Test
4740  public void testRegionReplicaSecondary() throws IOException {
4741    // create a primary region, load some data and flush
4742    // create a secondary region, and do a get against that
4743    Path rootDir = new Path(dir + name.getMethodName());
4744    FSUtils.setRootDir(TEST_UTIL.getConfiguration(), rootDir);
4745
4746    byte[][] families = new byte[][] {
4747        Bytes.toBytes("cf1"), Bytes.toBytes("cf2"), Bytes.toBytes("cf3")
4748    };
4749    byte[] cq = Bytes.toBytes("cq");
4750    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName()));
4751    for (byte[] family : families) {
4752      htd.addFamily(new HColumnDescriptor(family));
4753    }
4754
4755    long time = System.currentTimeMillis();
4756    HRegionInfo primaryHri = new HRegionInfo(htd.getTableName(),
4757      HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW,
4758      false, time, 0);
4759    HRegionInfo secondaryHri = new HRegionInfo(htd.getTableName(),
4760      HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW,
4761      false, time, 1);
4762
4763    HRegion primaryRegion = null, secondaryRegion = null;
4764
4765    try {
4766      primaryRegion = HBaseTestingUtility.createRegionAndWAL(primaryHri,
4767          rootDir, TEST_UTIL.getConfiguration(), htd);
4768
4769      // load some data
4770      putData(primaryRegion, 0, 1000, cq, families);
4771
4772      // flush region
4773      primaryRegion.flush(true);
4774
4775      // open secondary region
4776      secondaryRegion = HRegion.openHRegion(rootDir, secondaryHri, htd, null, CONF);
4777
4778      verifyData(secondaryRegion, 0, 1000, cq, families);
4779    } finally {
4780      if (primaryRegion != null) {
4781        HBaseTestingUtility.closeRegionAndWAL(primaryRegion);
4782      }
4783      if (secondaryRegion != null) {
4784        HBaseTestingUtility.closeRegionAndWAL(secondaryRegion);
4785      }
4786    }
4787  }
4788
4789  @Test
4790  public void testRegionReplicaSecondaryIsReadOnly() throws IOException {
4791    // create a primary region, load some data and flush
4792    // create a secondary region, and do a put against that
4793    Path rootDir = new Path(dir + name.getMethodName());
4794    FSUtils.setRootDir(TEST_UTIL.getConfiguration(), rootDir);
4795
4796    byte[][] families = new byte[][] {
4797        Bytes.toBytes("cf1"), Bytes.toBytes("cf2"), Bytes.toBytes("cf3")
4798    };
4799    byte[] cq = Bytes.toBytes("cq");
4800    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName()));
4801    for (byte[] family : families) {
4802      htd.addFamily(new HColumnDescriptor(family));
4803    }
4804
4805    long time = System.currentTimeMillis();
4806    HRegionInfo primaryHri = new HRegionInfo(htd.getTableName(),
4807      HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW,
4808      false, time, 0);
4809    HRegionInfo secondaryHri = new HRegionInfo(htd.getTableName(),
4810      HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW,
4811      false, time, 1);
4812
4813    HRegion primaryRegion = null, secondaryRegion = null;
4814
4815    try {
4816      primaryRegion = HBaseTestingUtility.createRegionAndWAL(primaryHri,
4817          rootDir, TEST_UTIL.getConfiguration(), htd);
4818
4819      // load some data
4820      putData(primaryRegion, 0, 1000, cq, families);
4821
4822      // flush region
4823      primaryRegion.flush(true);
4824
4825      // open secondary region
4826      secondaryRegion = HRegion.openHRegion(rootDir, secondaryHri, htd, null, CONF);
4827
4828      try {
4829        putData(secondaryRegion, 0, 1000, cq, families);
4830        fail("Should have thrown exception");
4831      } catch (IOException ex) {
4832        // expected
4833      }
4834    } finally {
4835      if (primaryRegion != null) {
4836        HBaseTestingUtility.closeRegionAndWAL(primaryRegion);
4837      }
4838      if (secondaryRegion != null) {
4839        HBaseTestingUtility.closeRegionAndWAL(secondaryRegion);
4840      }
4841    }
4842  }
4843
4844  static WALFactory createWALFactory(Configuration conf, Path rootDir) throws IOException {
4845    Configuration confForWAL = new Configuration(conf);
4846    confForWAL.set(HConstants.HBASE_DIR, rootDir.toString());
4847    return new WALFactory(confForWAL, "hregion-" + RandomStringUtils.randomNumeric(8));
4848  }
4849
4850  @Test
4851  public void testCompactionFromPrimary() throws IOException {
4852    Path rootDir = new Path(dir + name.getMethodName());
4853    FSUtils.setRootDir(TEST_UTIL.getConfiguration(), rootDir);
4854
4855    byte[][] families = new byte[][] {
4856        Bytes.toBytes("cf1"), Bytes.toBytes("cf2"), Bytes.toBytes("cf3")
4857    };
4858    byte[] cq = Bytes.toBytes("cq");
4859    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName()));
4860    for (byte[] family : families) {
4861      htd.addFamily(new HColumnDescriptor(family));
4862    }
4863
4864    long time = System.currentTimeMillis();
4865    HRegionInfo primaryHri = new HRegionInfo(htd.getTableName(),
4866      HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW,
4867      false, time, 0);
4868    HRegionInfo secondaryHri = new HRegionInfo(htd.getTableName(),
4869      HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW,
4870      false, time, 1);
4871
4872    HRegion primaryRegion = null, secondaryRegion = null;
4873
4874    try {
4875      primaryRegion = HBaseTestingUtility.createRegionAndWAL(primaryHri,
4876          rootDir, TEST_UTIL.getConfiguration(), htd);
4877
4878      // load some data
4879      putData(primaryRegion, 0, 1000, cq, families);
4880
4881      // flush region
4882      primaryRegion.flush(true);
4883
4884      // open secondary region
4885      secondaryRegion = HRegion.openHRegion(rootDir, secondaryHri, htd, null, CONF);
4886
4887      // move the file of the primary region to the archive, simulating a compaction
4888      Collection<HStoreFile> storeFiles = primaryRegion.getStore(families[0]).getStorefiles();
4889      primaryRegion.getRegionFileSystem().removeStoreFiles(Bytes.toString(families[0]), storeFiles);
4890      Collection<StoreFileInfo> storeFileInfos = primaryRegion.getRegionFileSystem()
4891          .getStoreFiles(families[0]);
4892      Assert.assertTrue(storeFileInfos == null || storeFileInfos.isEmpty());
4893
4894      verifyData(secondaryRegion, 0, 1000, cq, families);
4895    } finally {
4896      if (primaryRegion != null) {
4897        HBaseTestingUtility.closeRegionAndWAL(primaryRegion);
4898      }
4899      if (secondaryRegion != null) {
4900        HBaseTestingUtility.closeRegionAndWAL(secondaryRegion);
4901      }
4902    }
4903  }
4904
4905  private void putData(int startRow, int numRows, byte[] qf, byte[]... families) throws
4906      IOException {
4907    putData(this.region, startRow, numRows, qf, families);
4908  }
4909
4910  private void putData(HRegion region,
4911      int startRow, int numRows, byte[] qf, byte[]... families) throws IOException {
4912    putData(region, Durability.SKIP_WAL, startRow, numRows, qf, families);
4913  }
4914
4915  static void putData(HRegion region, Durability durability,
4916      int startRow, int numRows, byte[] qf, byte[]... families) throws IOException {
4917    for (int i = startRow; i < startRow + numRows; i++) {
4918      Put put = new Put(Bytes.toBytes("" + i));
4919      put.setDurability(durability);
4920      for (byte[] family : families) {
4921        put.addColumn(family, qf, null);
4922      }
4923      region.put(put);
4924      LOG.info(put.toString());
4925    }
4926  }
4927
4928  static void verifyData(HRegion newReg, int startRow, int numRows, byte[] qf, byte[]... families)
4929      throws IOException {
4930    for (int i = startRow; i < startRow + numRows; i++) {
4931      byte[] row = Bytes.toBytes("" + i);
4932      Get get = new Get(row);
4933      for (byte[] family : families) {
4934        get.addColumn(family, qf);
4935      }
4936      Result result = newReg.get(get);
4937      Cell[] raw = result.rawCells();
4938      assertEquals(families.length, result.size());
4939      for (int j = 0; j < families.length; j++) {
4940        assertTrue(CellUtil.matchingRows(raw[j], row));
4941        assertTrue(CellUtil.matchingFamily(raw[j], families[j]));
4942        assertTrue(CellUtil.matchingQualifier(raw[j], qf));
4943      }
4944    }
4945  }
4946
4947  static void assertGet(final HRegion r, final byte[] family, final byte[] k) throws IOException {
4948    // Now I have k, get values out and assert they are as expected.
4949    Get get = new Get(k).addFamily(family).setMaxVersions();
4950    Cell[] results = r.get(get).rawCells();
4951    for (int j = 0; j < results.length; j++) {
4952      byte[] tmp = CellUtil.cloneValue(results[j]);
4953      // Row should be equal to value every time.
4954      assertTrue(Bytes.equals(k, tmp));
4955    }
4956  }
4957
4958  /*
4959   * Assert first value in the passed region is <code>firstValue</code>.
4960   *
4961   * @param r
4962   *
4963   * @param fs
4964   *
4965   * @param firstValue
4966   *
4967   * @throws IOException
4968   */
4969  protected void assertScan(final HRegion r, final byte[] fs, final byte[] firstValue)
4970      throws IOException {
4971    byte[][] families = { fs };
4972    Scan scan = new Scan();
4973    for (int i = 0; i < families.length; i++)
4974      scan.addFamily(families[i]);
4975    InternalScanner s = r.getScanner(scan);
4976    try {
4977      List<Cell> curVals = new ArrayList<>();
4978      boolean first = true;
4979      OUTER_LOOP: while (s.next(curVals)) {
4980        for (Cell kv : curVals) {
4981          byte[] val = CellUtil.cloneValue(kv);
4982          byte[] curval = val;
4983          if (first) {
4984            first = false;
4985            assertTrue(Bytes.compareTo(curval, firstValue) == 0);
4986          } else {
4987            // Not asserting anything. Might as well break.
4988            break OUTER_LOOP;
4989          }
4990        }
4991      }
4992    } finally {
4993      s.close();
4994    }
4995  }
4996
4997  /**
4998   * Test that we get the expected flush results back
4999   */
5000  @Test
5001  public void testFlushResult() throws IOException {
5002    byte[] family = Bytes.toBytes("family");
5003
5004    this.region = initHRegion(tableName, method, family);
5005
5006    // empty memstore, flush doesn't run
5007    HRegion.FlushResult fr = region.flush(true);
5008    assertFalse(fr.isFlushSucceeded());
5009    assertFalse(fr.isCompactionNeeded());
5010
5011    // Flush enough files to get up to the threshold, doesn't need compactions
5012    for (int i = 0; i < 2; i++) {
5013      Put put = new Put(tableName.toBytes()).addColumn(family, family, tableName.toBytes());
5014      region.put(put);
5015      fr = region.flush(true);
5016      assertTrue(fr.isFlushSucceeded());
5017      assertFalse(fr.isCompactionNeeded());
5018    }
5019
5020    // Two flushes after the threshold, compactions are needed
5021    for (int i = 0; i < 2; i++) {
5022      Put put = new Put(tableName.toBytes()).addColumn(family, family, tableName.toBytes());
5023      region.put(put);
5024      fr = region.flush(true);
5025      assertTrue(fr.isFlushSucceeded());
5026      assertTrue(fr.isCompactionNeeded());
5027    }
5028  }
5029
5030  protected Configuration initSplit() {
5031    // Always compact if there is more than one store file.
5032    CONF.setInt("hbase.hstore.compactionThreshold", 2);
5033
5034    CONF.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, 10 * 1000);
5035
5036    // Increase the amount of time between client retries
5037    CONF.setLong("hbase.client.pause", 15 * 1000);
5038
5039    // This size should make it so we always split using the addContent
5040    // below. After adding all data, the first region is 1.3M
5041    CONF.setLong(HConstants.HREGION_MAX_FILESIZE, 1024 * 128);
5042    return CONF;
5043  }
5044
5045  /**
5046   * @return A region on which you must call
5047   *         {@link HBaseTestingUtility#closeRegionAndWAL(HRegion)} when done.
5048   */
5049  protected HRegion initHRegion(TableName tableName, String callingMethod, Configuration conf,
5050      byte[]... families) throws IOException {
5051    return initHRegion(tableName, callingMethod, conf, false, families);
5052  }
5053
5054  /**
5055   * @return A region on which you must call
5056   *         {@link HBaseTestingUtility#closeRegionAndWAL(HRegion)} when done.
5057   */
5058  protected HRegion initHRegion(TableName tableName, String callingMethod, Configuration conf,
5059      boolean isReadOnly, byte[]... families) throws IOException {
5060    return initHRegion(tableName, null, null, callingMethod, conf, isReadOnly, families);
5061  }
5062
5063  protected HRegion initHRegion(TableName tableName, byte[] startKey, byte[] stopKey,
5064      String callingMethod, Configuration conf, boolean isReadOnly, byte[]... families)
5065      throws IOException {
5066    Path logDir = TEST_UTIL.getDataTestDirOnTestFS(callingMethod + ".log");
5067    ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null);
5068    HRegionInfo hri = new HRegionInfo(tableName, startKey, stopKey);
5069    final WAL wal = HBaseTestingUtility.createWal(conf, logDir, hri);
5070    return initHRegion(tableName, startKey, stopKey, isReadOnly,
5071        Durability.SYNC_WAL, wal, families);
5072  }
5073
5074  /**
5075   * @return A region on which you must call
5076   *         {@link HBaseTestingUtility#closeRegionAndWAL(HRegion)} when done.
5077   */
5078  public HRegion initHRegion(TableName tableName, byte[] startKey, byte[] stopKey,
5079      boolean isReadOnly, Durability durability, WAL wal, byte[]... families) throws IOException {
5080    return TEST_UTIL.createLocalHRegion(tableName, startKey, stopKey,
5081        isReadOnly, durability, wal, families);
5082  }
5083
5084  /**
5085   * Assert that the passed in Cell has expected contents for the specified row,
5086   * column & timestamp.
5087   */
5088  private void checkOneCell(Cell kv, byte[] cf, int rowIdx, int colIdx, long ts) {
5089    String ctx = "rowIdx=" + rowIdx + "; colIdx=" + colIdx + "; ts=" + ts;
5090    assertEquals("Row mismatch which checking: " + ctx, "row:" + rowIdx,
5091        Bytes.toString(CellUtil.cloneRow(kv)));
5092    assertEquals("ColumnFamily mismatch while checking: " + ctx, Bytes.toString(cf),
5093        Bytes.toString(CellUtil.cloneFamily(kv)));
5094    assertEquals("Column qualifier mismatch while checking: " + ctx, "column:" + colIdx,
5095        Bytes.toString(CellUtil.cloneQualifier(kv)));
5096    assertEquals("Timestamp mismatch while checking: " + ctx, ts, kv.getTimestamp());
5097    assertEquals("Value mismatch while checking: " + ctx, "value-version-" + ts,
5098        Bytes.toString(CellUtil.cloneValue(kv)));
5099  }
5100
5101  @Test
5102  public void testReverseScanner_FromMemStore_SingleCF_Normal()
5103      throws IOException {
5104    byte[] rowC = Bytes.toBytes("rowC");
5105    byte[] rowA = Bytes.toBytes("rowA");
5106    byte[] rowB = Bytes.toBytes("rowB");
5107    byte[] cf = Bytes.toBytes("CF");
5108    byte[][] families = { cf };
5109    byte[] col = Bytes.toBytes("C");
5110    long ts = 1;
5111    this.region = initHRegion(tableName, method, families);
5112    try {
5113      KeyValue kv1 = new KeyValue(rowC, cf, col, ts, KeyValue.Type.Put, null);
5114      KeyValue kv11 = new KeyValue(rowC, cf, col, ts + 1, KeyValue.Type.Put,
5115          null);
5116      KeyValue kv2 = new KeyValue(rowA, cf, col, ts, KeyValue.Type.Put, null);
5117      KeyValue kv3 = new KeyValue(rowB, cf, col, ts, KeyValue.Type.Put, null);
5118      Put put = null;
5119      put = new Put(rowC);
5120      put.add(kv1);
5121      put.add(kv11);
5122      region.put(put);
5123      put = new Put(rowA);
5124      put.add(kv2);
5125      region.put(put);
5126      put = new Put(rowB);
5127      put.add(kv3);
5128      region.put(put);
5129
5130      Scan scan = new Scan(rowC);
5131      scan.setMaxVersions(5);
5132      scan.setReversed(true);
5133      InternalScanner scanner = region.getScanner(scan);
5134      List<Cell> currRow = new ArrayList<>();
5135      boolean hasNext = scanner.next(currRow);
5136      assertEquals(2, currRow.size());
5137      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5138          .get(0).getRowLength(), rowC, 0, rowC.length));
5139      assertTrue(hasNext);
5140      currRow.clear();
5141      hasNext = scanner.next(currRow);
5142      assertEquals(1, currRow.size());
5143      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5144          .get(0).getRowLength(), rowB, 0, rowB.length));
5145      assertTrue(hasNext);
5146      currRow.clear();
5147      hasNext = scanner.next(currRow);
5148      assertEquals(1, currRow.size());
5149      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5150          .get(0).getRowLength(), rowA, 0, rowA.length));
5151      assertFalse(hasNext);
5152      scanner.close();
5153    } finally {
5154      HBaseTestingUtility.closeRegionAndWAL(this.region);
5155      this.region = null;
5156    }
5157  }
5158
5159  @Test
5160  public void testReverseScanner_FromMemStore_SingleCF_LargerKey()
5161      throws IOException {
5162    byte[] rowC = Bytes.toBytes("rowC");
5163    byte[] rowA = Bytes.toBytes("rowA");
5164    byte[] rowB = Bytes.toBytes("rowB");
5165    byte[] rowD = Bytes.toBytes("rowD");
5166    byte[] cf = Bytes.toBytes("CF");
5167    byte[][] families = { cf };
5168    byte[] col = Bytes.toBytes("C");
5169    long ts = 1;
5170    this.region = initHRegion(tableName, method, families);
5171    try {
5172      KeyValue kv1 = new KeyValue(rowC, cf, col, ts, KeyValue.Type.Put, null);
5173      KeyValue kv11 = new KeyValue(rowC, cf, col, ts + 1, KeyValue.Type.Put,
5174          null);
5175      KeyValue kv2 = new KeyValue(rowA, cf, col, ts, KeyValue.Type.Put, null);
5176      KeyValue kv3 = new KeyValue(rowB, cf, col, ts, KeyValue.Type.Put, null);
5177      Put put = null;
5178      put = new Put(rowC);
5179      put.add(kv1);
5180      put.add(kv11);
5181      region.put(put);
5182      put = new Put(rowA);
5183      put.add(kv2);
5184      region.put(put);
5185      put = new Put(rowB);
5186      put.add(kv3);
5187      region.put(put);
5188
5189      Scan scan = new Scan(rowD);
5190      List<Cell> currRow = new ArrayList<>();
5191      scan.setReversed(true);
5192      scan.setMaxVersions(5);
5193      InternalScanner scanner = region.getScanner(scan);
5194      boolean hasNext = scanner.next(currRow);
5195      assertEquals(2, currRow.size());
5196      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5197          .get(0).getRowLength(), rowC, 0, rowC.length));
5198      assertTrue(hasNext);
5199      currRow.clear();
5200      hasNext = scanner.next(currRow);
5201      assertEquals(1, currRow.size());
5202      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5203          .get(0).getRowLength(), rowB, 0, rowB.length));
5204      assertTrue(hasNext);
5205      currRow.clear();
5206      hasNext = scanner.next(currRow);
5207      assertEquals(1, currRow.size());
5208      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5209          .get(0).getRowLength(), rowA, 0, rowA.length));
5210      assertFalse(hasNext);
5211      scanner.close();
5212    } finally {
5213      HBaseTestingUtility.closeRegionAndWAL(this.region);
5214      this.region = null;
5215    }
5216  }
5217
5218  @Test
5219  public void testReverseScanner_FromMemStore_SingleCF_FullScan()
5220      throws IOException {
5221    byte[] rowC = Bytes.toBytes("rowC");
5222    byte[] rowA = Bytes.toBytes("rowA");
5223    byte[] rowB = Bytes.toBytes("rowB");
5224    byte[] cf = Bytes.toBytes("CF");
5225    byte[][] families = { cf };
5226    byte[] col = Bytes.toBytes("C");
5227    long ts = 1;
5228    this.region = initHRegion(tableName, method, families);
5229    try {
5230      KeyValue kv1 = new KeyValue(rowC, cf, col, ts, KeyValue.Type.Put, null);
5231      KeyValue kv11 = new KeyValue(rowC, cf, col, ts + 1, KeyValue.Type.Put,
5232          null);
5233      KeyValue kv2 = new KeyValue(rowA, cf, col, ts, KeyValue.Type.Put, null);
5234      KeyValue kv3 = new KeyValue(rowB, cf, col, ts, KeyValue.Type.Put, null);
5235      Put put = null;
5236      put = new Put(rowC);
5237      put.add(kv1);
5238      put.add(kv11);
5239      region.put(put);
5240      put = new Put(rowA);
5241      put.add(kv2);
5242      region.put(put);
5243      put = new Put(rowB);
5244      put.add(kv3);
5245      region.put(put);
5246      Scan scan = new Scan();
5247      List<Cell> currRow = new ArrayList<>();
5248      scan.setReversed(true);
5249      InternalScanner scanner = region.getScanner(scan);
5250      boolean hasNext = scanner.next(currRow);
5251      assertEquals(1, currRow.size());
5252      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5253          .get(0).getRowLength(), rowC, 0, rowC.length));
5254      assertTrue(hasNext);
5255      currRow.clear();
5256      hasNext = scanner.next(currRow);
5257      assertEquals(1, currRow.size());
5258      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5259          .get(0).getRowLength(), rowB, 0, rowB.length));
5260      assertTrue(hasNext);
5261      currRow.clear();
5262      hasNext = scanner.next(currRow);
5263      assertEquals(1, currRow.size());
5264      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5265          .get(0).getRowLength(), rowA, 0, rowA.length));
5266      assertFalse(hasNext);
5267      scanner.close();
5268    } finally {
5269      HBaseTestingUtility.closeRegionAndWAL(this.region);
5270      this.region = null;
5271    }
5272  }
5273
5274  @Test
5275  public void testReverseScanner_moreRowsMayExistAfter() throws IOException {
5276    // case for "INCLUDE_AND_SEEK_NEXT_ROW & SEEK_NEXT_ROW" endless loop
5277    byte[] rowA = Bytes.toBytes("rowA");
5278    byte[] rowB = Bytes.toBytes("rowB");
5279    byte[] rowC = Bytes.toBytes("rowC");
5280    byte[] rowD = Bytes.toBytes("rowD");
5281    byte[] rowE = Bytes.toBytes("rowE");
5282    byte[] cf = Bytes.toBytes("CF");
5283    byte[][] families = { cf };
5284    byte[] col1 = Bytes.toBytes("col1");
5285    byte[] col2 = Bytes.toBytes("col2");
5286    long ts = 1;
5287    this.region = initHRegion(tableName, method, families);
5288    try {
5289      KeyValue kv1 = new KeyValue(rowA, cf, col1, ts, KeyValue.Type.Put, null);
5290      KeyValue kv2 = new KeyValue(rowB, cf, col1, ts, KeyValue.Type.Put, null);
5291      KeyValue kv3 = new KeyValue(rowC, cf, col1, ts, KeyValue.Type.Put, null);
5292      KeyValue kv4_1 = new KeyValue(rowD, cf, col1, ts, KeyValue.Type.Put, null);
5293      KeyValue kv4_2 = new KeyValue(rowD, cf, col2, ts, KeyValue.Type.Put, null);
5294      KeyValue kv5 = new KeyValue(rowE, cf, col1, ts, KeyValue.Type.Put, null);
5295      Put put = null;
5296      put = new Put(rowA);
5297      put.add(kv1);
5298      region.put(put);
5299      put = new Put(rowB);
5300      put.add(kv2);
5301      region.put(put);
5302      put = new Put(rowC);
5303      put.add(kv3);
5304      region.put(put);
5305      put = new Put(rowD);
5306      put.add(kv4_1);
5307      region.put(put);
5308      put = new Put(rowD);
5309      put.add(kv4_2);
5310      region.put(put);
5311      put = new Put(rowE);
5312      put.add(kv5);
5313      region.put(put);
5314      region.flush(true);
5315      Scan scan = new Scan(rowD, rowA);
5316      scan.addColumn(families[0], col1);
5317      scan.setReversed(true);
5318      List<Cell> currRow = new ArrayList<>();
5319      InternalScanner scanner = region.getScanner(scan);
5320      boolean hasNext = scanner.next(currRow);
5321      assertEquals(1, currRow.size());
5322      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5323          .get(0).getRowLength(), rowD, 0, rowD.length));
5324      assertTrue(hasNext);
5325      currRow.clear();
5326      hasNext = scanner.next(currRow);
5327      assertEquals(1, currRow.size());
5328      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5329          .get(0).getRowLength(), rowC, 0, rowC.length));
5330      assertTrue(hasNext);
5331      currRow.clear();
5332      hasNext = scanner.next(currRow);
5333      assertEquals(1, currRow.size());
5334      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5335          .get(0).getRowLength(), rowB, 0, rowB.length));
5336      assertFalse(hasNext);
5337      scanner.close();
5338
5339      scan = new Scan(rowD, rowA);
5340      scan.addColumn(families[0], col2);
5341      scan.setReversed(true);
5342      currRow.clear();
5343      scanner = region.getScanner(scan);
5344      hasNext = scanner.next(currRow);
5345      assertEquals(1, currRow.size());
5346      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5347          .get(0).getRowLength(), rowD, 0, rowD.length));
5348      scanner.close();
5349    } finally {
5350      HBaseTestingUtility.closeRegionAndWAL(this.region);
5351      this.region = null;
5352    }
5353  }
5354
5355  @Test
5356  public void testReverseScanner_smaller_blocksize() throws IOException {
5357    // case to ensure no conflict with HFile index optimization
5358    byte[] rowA = Bytes.toBytes("rowA");
5359    byte[] rowB = Bytes.toBytes("rowB");
5360    byte[] rowC = Bytes.toBytes("rowC");
5361    byte[] rowD = Bytes.toBytes("rowD");
5362    byte[] rowE = Bytes.toBytes("rowE");
5363    byte[] cf = Bytes.toBytes("CF");
5364    byte[][] families = { cf };
5365    byte[] col1 = Bytes.toBytes("col1");
5366    byte[] col2 = Bytes.toBytes("col2");
5367    long ts = 1;
5368    HBaseConfiguration config = new HBaseConfiguration();
5369    config.setInt("test.block.size", 1);
5370    this.region = initHRegion(tableName, method, config, families);
5371    try {
5372      KeyValue kv1 = new KeyValue(rowA, cf, col1, ts, KeyValue.Type.Put, null);
5373      KeyValue kv2 = new KeyValue(rowB, cf, col1, ts, KeyValue.Type.Put, null);
5374      KeyValue kv3 = new KeyValue(rowC, cf, col1, ts, KeyValue.Type.Put, null);
5375      KeyValue kv4_1 = new KeyValue(rowD, cf, col1, ts, KeyValue.Type.Put, null);
5376      KeyValue kv4_2 = new KeyValue(rowD, cf, col2, ts, KeyValue.Type.Put, null);
5377      KeyValue kv5 = new KeyValue(rowE, cf, col1, ts, KeyValue.Type.Put, null);
5378      Put put = null;
5379      put = new Put(rowA);
5380      put.add(kv1);
5381      region.put(put);
5382      put = new Put(rowB);
5383      put.add(kv2);
5384      region.put(put);
5385      put = new Put(rowC);
5386      put.add(kv3);
5387      region.put(put);
5388      put = new Put(rowD);
5389      put.add(kv4_1);
5390      region.put(put);
5391      put = new Put(rowD);
5392      put.add(kv4_2);
5393      region.put(put);
5394      put = new Put(rowE);
5395      put.add(kv5);
5396      region.put(put);
5397      region.flush(true);
5398      Scan scan = new Scan(rowD, rowA);
5399      scan.addColumn(families[0], col1);
5400      scan.setReversed(true);
5401      List<Cell> currRow = new ArrayList<>();
5402      InternalScanner scanner = region.getScanner(scan);
5403      boolean hasNext = scanner.next(currRow);
5404      assertEquals(1, currRow.size());
5405      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5406          .get(0).getRowLength(), rowD, 0, rowD.length));
5407      assertTrue(hasNext);
5408      currRow.clear();
5409      hasNext = scanner.next(currRow);
5410      assertEquals(1, currRow.size());
5411      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5412          .get(0).getRowLength(), rowC, 0, rowC.length));
5413      assertTrue(hasNext);
5414      currRow.clear();
5415      hasNext = scanner.next(currRow);
5416      assertEquals(1, currRow.size());
5417      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5418          .get(0).getRowLength(), rowB, 0, rowB.length));
5419      assertFalse(hasNext);
5420      scanner.close();
5421
5422      scan = new Scan(rowD, rowA);
5423      scan.addColumn(families[0], col2);
5424      scan.setReversed(true);
5425      currRow.clear();
5426      scanner = region.getScanner(scan);
5427      hasNext = scanner.next(currRow);
5428      assertEquals(1, currRow.size());
5429      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5430          .get(0).getRowLength(), rowD, 0, rowD.length));
5431      scanner.close();
5432    } finally {
5433      HBaseTestingUtility.closeRegionAndWAL(this.region);
5434      this.region = null;
5435    }
5436  }
5437
5438  @Test
5439  public void testReverseScanner_FromMemStoreAndHFiles_MultiCFs1()
5440      throws IOException {
5441    byte[] row0 = Bytes.toBytes("row0"); // 1 kv
5442    byte[] row1 = Bytes.toBytes("row1"); // 2 kv
5443    byte[] row2 = Bytes.toBytes("row2"); // 4 kv
5444    byte[] row3 = Bytes.toBytes("row3"); // 2 kv
5445    byte[] row4 = Bytes.toBytes("row4"); // 5 kv
5446    byte[] row5 = Bytes.toBytes("row5"); // 2 kv
5447    byte[] cf1 = Bytes.toBytes("CF1");
5448    byte[] cf2 = Bytes.toBytes("CF2");
5449    byte[] cf3 = Bytes.toBytes("CF3");
5450    byte[][] families = { cf1, cf2, cf3 };
5451    byte[] col = Bytes.toBytes("C");
5452    long ts = 1;
5453    HBaseConfiguration conf = new HBaseConfiguration();
5454    // disable compactions in this test.
5455    conf.setInt("hbase.hstore.compactionThreshold", 10000);
5456    this.region = initHRegion(tableName, method, conf, families);
5457    try {
5458      // kv naming style: kv(row number) totalKvCountInThisRow seq no
5459      KeyValue kv0_1_1 = new KeyValue(row0, cf1, col, ts, KeyValue.Type.Put,
5460          null);
5461      KeyValue kv1_2_1 = new KeyValue(row1, cf2, col, ts, KeyValue.Type.Put,
5462          null);
5463      KeyValue kv1_2_2 = new KeyValue(row1, cf1, col, ts + 1,
5464          KeyValue.Type.Put, null);
5465      KeyValue kv2_4_1 = new KeyValue(row2, cf2, col, ts, KeyValue.Type.Put,
5466          null);
5467      KeyValue kv2_4_2 = new KeyValue(row2, cf1, col, ts, KeyValue.Type.Put,
5468          null);
5469      KeyValue kv2_4_3 = new KeyValue(row2, cf3, col, ts, KeyValue.Type.Put,
5470          null);
5471      KeyValue kv2_4_4 = new KeyValue(row2, cf1, col, ts + 4,
5472          KeyValue.Type.Put, null);
5473      KeyValue kv3_2_1 = new KeyValue(row3, cf2, col, ts, KeyValue.Type.Put,
5474          null);
5475      KeyValue kv3_2_2 = new KeyValue(row3, cf1, col, ts + 4,
5476          KeyValue.Type.Put, null);
5477      KeyValue kv4_5_1 = new KeyValue(row4, cf1, col, ts, KeyValue.Type.Put,
5478          null);
5479      KeyValue kv4_5_2 = new KeyValue(row4, cf3, col, ts, KeyValue.Type.Put,
5480          null);
5481      KeyValue kv4_5_3 = new KeyValue(row4, cf3, col, ts + 5,
5482          KeyValue.Type.Put, null);
5483      KeyValue kv4_5_4 = new KeyValue(row4, cf2, col, ts, KeyValue.Type.Put,
5484          null);
5485      KeyValue kv4_5_5 = new KeyValue(row4, cf1, col, ts + 3,
5486          KeyValue.Type.Put, null);
5487      KeyValue kv5_2_1 = new KeyValue(row5, cf2, col, ts, KeyValue.Type.Put,
5488          null);
5489      KeyValue kv5_2_2 = new KeyValue(row5, cf3, col, ts, KeyValue.Type.Put,
5490          null);
5491      // hfiles(cf1/cf2) :"row1"(1 kv) / "row2"(1 kv) / "row4"(2 kv)
5492      Put put = null;
5493      put = new Put(row1);
5494      put.add(kv1_2_1);
5495      region.put(put);
5496      put = new Put(row2);
5497      put.add(kv2_4_1);
5498      region.put(put);
5499      put = new Put(row4);
5500      put.add(kv4_5_4);
5501      put.add(kv4_5_5);
5502      region.put(put);
5503      region.flush(true);
5504      // hfiles(cf1/cf3) : "row1" (1 kvs) / "row2" (1 kv) / "row4" (2 kv)
5505      put = new Put(row4);
5506      put.add(kv4_5_1);
5507      put.add(kv4_5_3);
5508      region.put(put);
5509      put = new Put(row1);
5510      put.add(kv1_2_2);
5511      region.put(put);
5512      put = new Put(row2);
5513      put.add(kv2_4_4);
5514      region.put(put);
5515      region.flush(true);
5516      // hfiles(cf1/cf3) : "row2"(2 kv) / "row3"(1 kvs) / "row4" (1 kv)
5517      put = new Put(row4);
5518      put.add(kv4_5_2);
5519      region.put(put);
5520      put = new Put(row2);
5521      put.add(kv2_4_2);
5522      put.add(kv2_4_3);
5523      region.put(put);
5524      put = new Put(row3);
5525      put.add(kv3_2_2);
5526      region.put(put);
5527      region.flush(true);
5528      // memstore(cf1/cf2/cf3) : "row0" (1 kvs) / "row3" ( 1 kv) / "row5" (max)
5529      // ( 2 kv)
5530      put = new Put(row0);
5531      put.add(kv0_1_1);
5532      region.put(put);
5533      put = new Put(row3);
5534      put.add(kv3_2_1);
5535      region.put(put);
5536      put = new Put(row5);
5537      put.add(kv5_2_1);
5538      put.add(kv5_2_2);
5539      region.put(put);
5540      // scan range = ["row4", min), skip the max "row5"
5541      Scan scan = new Scan(row4);
5542      scan.setMaxVersions(5);
5543      scan.setBatch(3);
5544      scan.setReversed(true);
5545      InternalScanner scanner = region.getScanner(scan);
5546      List<Cell> currRow = new ArrayList<>();
5547      boolean hasNext = false;
5548      // 1. scan out "row4" (5 kvs), "row5" can't be scanned out since not
5549      // included in scan range
5550      // "row4" takes 2 next() calls since batch=3
5551      hasNext = scanner.next(currRow);
5552      assertEquals(3, currRow.size());
5553      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5554          .get(0).getRowLength(), row4, 0, row4.length));
5555      assertTrue(hasNext);
5556      currRow.clear();
5557      hasNext = scanner.next(currRow);
5558      assertEquals(2, currRow.size());
5559      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(),
5560          currRow.get(0).getRowLength(), row4, 0,
5561        row4.length));
5562      assertTrue(hasNext);
5563      // 2. scan out "row3" (2 kv)
5564      currRow.clear();
5565      hasNext = scanner.next(currRow);
5566      assertEquals(2, currRow.size());
5567      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5568          .get(0).getRowLength(), row3, 0, row3.length));
5569      assertTrue(hasNext);
5570      // 3. scan out "row2" (4 kvs)
5571      // "row2" takes 2 next() calls since batch=3
5572      currRow.clear();
5573      hasNext = scanner.next(currRow);
5574      assertEquals(3, currRow.size());
5575      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5576          .get(0).getRowLength(), row2, 0, row2.length));
5577      assertTrue(hasNext);
5578      currRow.clear();
5579      hasNext = scanner.next(currRow);
5580      assertEquals(1, currRow.size());
5581      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5582          .get(0).getRowLength(), row2, 0, row2.length));
5583      assertTrue(hasNext);
5584      // 4. scan out "row1" (2 kv)
5585      currRow.clear();
5586      hasNext = scanner.next(currRow);
5587      assertEquals(2, currRow.size());
5588      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5589          .get(0).getRowLength(), row1, 0, row1.length));
5590      assertTrue(hasNext);
5591      // 5. scan out "row0" (1 kv)
5592      currRow.clear();
5593      hasNext = scanner.next(currRow);
5594      assertEquals(1, currRow.size());
5595      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5596          .get(0).getRowLength(), row0, 0, row0.length));
5597      assertFalse(hasNext);
5598
5599      scanner.close();
5600    } finally {
5601      HBaseTestingUtility.closeRegionAndWAL(this.region);
5602      this.region = null;
5603    }
5604  }
5605
5606  @Test
5607  public void testReverseScanner_FromMemStoreAndHFiles_MultiCFs2()
5608      throws IOException {
5609    byte[] row1 = Bytes.toBytes("row1");
5610    byte[] row2 = Bytes.toBytes("row2");
5611    byte[] row3 = Bytes.toBytes("row3");
5612    byte[] row4 = Bytes.toBytes("row4");
5613    byte[] cf1 = Bytes.toBytes("CF1");
5614    byte[] cf2 = Bytes.toBytes("CF2");
5615    byte[] cf3 = Bytes.toBytes("CF3");
5616    byte[] cf4 = Bytes.toBytes("CF4");
5617    byte[][] families = { cf1, cf2, cf3, cf4 };
5618    byte[] col = Bytes.toBytes("C");
5619    long ts = 1;
5620    HBaseConfiguration conf = new HBaseConfiguration();
5621    // disable compactions in this test.
5622    conf.setInt("hbase.hstore.compactionThreshold", 10000);
5623    this.region = initHRegion(tableName, method, conf, families);
5624    try {
5625      KeyValue kv1 = new KeyValue(row1, cf1, col, ts, KeyValue.Type.Put, null);
5626      KeyValue kv2 = new KeyValue(row2, cf2, col, ts, KeyValue.Type.Put, null);
5627      KeyValue kv3 = new KeyValue(row3, cf3, col, ts, KeyValue.Type.Put, null);
5628      KeyValue kv4 = new KeyValue(row4, cf4, col, ts, KeyValue.Type.Put, null);
5629      // storefile1
5630      Put put = new Put(row1);
5631      put.add(kv1);
5632      region.put(put);
5633      region.flush(true);
5634      // storefile2
5635      put = new Put(row2);
5636      put.add(kv2);
5637      region.put(put);
5638      region.flush(true);
5639      // storefile3
5640      put = new Put(row3);
5641      put.add(kv3);
5642      region.put(put);
5643      region.flush(true);
5644      // memstore
5645      put = new Put(row4);
5646      put.add(kv4);
5647      region.put(put);
5648      // scan range = ["row4", min)
5649      Scan scan = new Scan(row4);
5650      scan.setReversed(true);
5651      scan.setBatch(10);
5652      InternalScanner scanner = region.getScanner(scan);
5653      List<Cell> currRow = new ArrayList<>();
5654      boolean hasNext = scanner.next(currRow);
5655      assertEquals(1, currRow.size());
5656      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5657          .get(0).getRowLength(), row4, 0, row4.length));
5658      assertTrue(hasNext);
5659      currRow.clear();
5660      hasNext = scanner.next(currRow);
5661      assertEquals(1, currRow.size());
5662      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5663          .get(0).getRowLength(), row3, 0, row3.length));
5664      assertTrue(hasNext);
5665      currRow.clear();
5666      hasNext = scanner.next(currRow);
5667      assertEquals(1, currRow.size());
5668      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5669          .get(0).getRowLength(), row2, 0, row2.length));
5670      assertTrue(hasNext);
5671      currRow.clear();
5672      hasNext = scanner.next(currRow);
5673      assertEquals(1, currRow.size());
5674      assertTrue(Bytes.equals(currRow.get(0).getRowArray(), currRow.get(0).getRowOffset(), currRow
5675          .get(0).getRowLength(), row1, 0, row1.length));
5676      assertFalse(hasNext);
5677    } finally {
5678      HBaseTestingUtility.closeRegionAndWAL(this.region);
5679      this.region = null;
5680    }
5681  }
5682
5683  /**
5684   * Test for HBASE-14497: Reverse Scan threw StackOverflow caused by readPt checking
5685   */
5686  @Test
5687  public void testReverseScanner_StackOverflow() throws IOException {
5688    byte[] cf1 = Bytes.toBytes("CF1");
5689    byte[][] families = {cf1};
5690    byte[] col = Bytes.toBytes("C");
5691    HBaseConfiguration conf = new HBaseConfiguration();
5692    this.region = initHRegion(tableName, method, conf, families);
5693    try {
5694      // setup with one storefile and one memstore, to create scanner and get an earlier readPt
5695      Put put = new Put(Bytes.toBytes("19998"));
5696      put.addColumn(cf1, col, Bytes.toBytes("val"));
5697      region.put(put);
5698      region.flushcache(true, true, FlushLifeCycleTracker.DUMMY);
5699      Put put2 = new Put(Bytes.toBytes("19997"));
5700      put2.addColumn(cf1, col, Bytes.toBytes("val"));
5701      region.put(put2);
5702
5703      Scan scan = new Scan(Bytes.toBytes("19998"));
5704      scan.setReversed(true);
5705      InternalScanner scanner = region.getScanner(scan);
5706
5707      // create one storefile contains many rows will be skipped
5708      // to check StoreFileScanner.seekToPreviousRow
5709      for (int i = 10000; i < 20000; i++) {
5710        Put p = new Put(Bytes.toBytes(""+i));
5711        p.addColumn(cf1, col, Bytes.toBytes("" + i));
5712        region.put(p);
5713      }
5714      region.flushcache(true, true, FlushLifeCycleTracker.DUMMY);
5715
5716      // create one memstore contains many rows will be skipped
5717      // to check MemStoreScanner.seekToPreviousRow
5718      for (int i = 10000; i < 20000; i++) {
5719        Put p = new Put(Bytes.toBytes(""+i));
5720        p.addColumn(cf1, col, Bytes.toBytes("" + i));
5721        region.put(p);
5722      }
5723
5724      List<Cell> currRow = new ArrayList<>();
5725      boolean hasNext;
5726      do {
5727        hasNext = scanner.next(currRow);
5728      } while (hasNext);
5729      assertEquals(2, currRow.size());
5730      assertEquals("19998", Bytes.toString(currRow.get(0).getRowArray(),
5731        currRow.get(0).getRowOffset(), currRow.get(0).getRowLength()));
5732      assertEquals("19997", Bytes.toString(currRow.get(1).getRowArray(),
5733        currRow.get(1).getRowOffset(), currRow.get(1).getRowLength()));
5734    } finally {
5735      HBaseTestingUtility.closeRegionAndWAL(this.region);
5736      this.region = null;
5737    }
5738  }
5739
5740  @Test
5741  public void testReverseScanShouldNotScanMemstoreIfReadPtLesser() throws Exception {
5742    byte[] cf1 = Bytes.toBytes("CF1");
5743    byte[][] families = { cf1 };
5744    byte[] col = Bytes.toBytes("C");
5745    HBaseConfiguration conf = new HBaseConfiguration();
5746    this.region = initHRegion(tableName, method, conf, families);
5747    try {
5748      // setup with one storefile and one memstore, to create scanner and get an earlier readPt
5749      Put put = new Put(Bytes.toBytes("19996"));
5750      put.addColumn(cf1, col, Bytes.toBytes("val"));
5751      region.put(put);
5752      Put put2 = new Put(Bytes.toBytes("19995"));
5753      put2.addColumn(cf1, col, Bytes.toBytes("val"));
5754      region.put(put2);
5755      // create a reverse scan
5756      Scan scan = new Scan(Bytes.toBytes("19996"));
5757      scan.setReversed(true);
5758      RegionScannerImpl scanner = region.getScanner(scan);
5759
5760      // flush the cache. This will reset the store scanner
5761      region.flushcache(true, true, FlushLifeCycleTracker.DUMMY);
5762
5763      // create one memstore contains many rows will be skipped
5764      // to check MemStoreScanner.seekToPreviousRow
5765      for (int i = 10000; i < 20000; i++) {
5766        Put p = new Put(Bytes.toBytes("" + i));
5767        p.addColumn(cf1, col, Bytes.toBytes("" + i));
5768        region.put(p);
5769      }
5770      List<Cell> currRow = new ArrayList<>();
5771      boolean hasNext;
5772      boolean assertDone = false;
5773      do {
5774        hasNext = scanner.next(currRow);
5775        // With HBASE-15871, after the scanner is reset the memstore scanner should not be
5776        // added here
5777        if (!assertDone) {
5778          StoreScanner current =
5779              (StoreScanner) (scanner.storeHeap).getCurrentForTesting();
5780          List<KeyValueScanner> scanners = current.getAllScannersForTesting();
5781          assertEquals("There should be only one scanner the store file scanner", 1,
5782            scanners.size());
5783          assertDone = true;
5784        }
5785      } while (hasNext);
5786      assertEquals(2, currRow.size());
5787      assertEquals("19996", Bytes.toString(currRow.get(0).getRowArray(),
5788        currRow.get(0).getRowOffset(), currRow.get(0).getRowLength()));
5789      assertEquals("19995", Bytes.toString(currRow.get(1).getRowArray(),
5790        currRow.get(1).getRowOffset(), currRow.get(1).getRowLength()));
5791    } finally {
5792      HBaseTestingUtility.closeRegionAndWAL(this.region);
5793      this.region = null;
5794    }
5795  }
5796
5797  @Test
5798  public void testWriteRequestsCounter() throws IOException {
5799    byte[] fam = Bytes.toBytes("info");
5800    byte[][] families = { fam };
5801    this.region = initHRegion(tableName, method, CONF, families);
5802
5803    Assert.assertEquals(0L, region.getWriteRequestsCount());
5804
5805    Put put = new Put(row);
5806    put.addColumn(fam, fam, fam);
5807
5808    Assert.assertEquals(0L, region.getWriteRequestsCount());
5809    region.put(put);
5810    Assert.assertEquals(1L, region.getWriteRequestsCount());
5811    region.put(put);
5812    Assert.assertEquals(2L, region.getWriteRequestsCount());
5813    region.put(put);
5814    Assert.assertEquals(3L, region.getWriteRequestsCount());
5815
5816    region.delete(new Delete(row));
5817    Assert.assertEquals(4L, region.getWriteRequestsCount());
5818
5819    HBaseTestingUtility.closeRegionAndWAL(this.region);
5820    this.region = null;
5821  }
5822
5823  @Test
5824  public void testOpenRegionWrittenToWAL() throws Exception {
5825    final ServerName serverName = ServerName.valueOf(name.getMethodName(), 100, 42);
5826    final RegionServerServices rss = spy(TEST_UTIL.createMockRegionServerService(serverName));
5827
5828    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName()));
5829    htd.addFamily(new HColumnDescriptor(fam1));
5830    htd.addFamily(new HColumnDescriptor(fam2));
5831
5832    HRegionInfo hri = new HRegionInfo(htd.getTableName(),
5833      HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY);
5834
5835    // open the region w/o rss and wal and flush some files
5836    HRegion region =
5837         HBaseTestingUtility.createRegionAndWAL(hri, TEST_UTIL.getDataTestDir(), TEST_UTIL
5838             .getConfiguration(), htd);
5839    assertNotNull(region);
5840
5841    // create a file in fam1 for the region before opening in OpenRegionHandler
5842    region.put(new Put(Bytes.toBytes("a")).addColumn(fam1, fam1, fam1));
5843    region.flush(true);
5844    HBaseTestingUtility.closeRegionAndWAL(region);
5845
5846    ArgumentCaptor<WALEdit> editCaptor = ArgumentCaptor.forClass(WALEdit.class);
5847
5848    // capture append() calls
5849    WAL wal = mockWAL();
5850    when(rss.getWAL((HRegionInfo) any())).thenReturn(wal);
5851
5852    try {
5853      region = HRegion.openHRegion(hri, htd, rss.getWAL(hri),
5854        TEST_UTIL.getConfiguration(), rss, null);
5855
5856      verify(wal, times(1)).append((HRegionInfo)any(), (WALKeyImpl)any()
5857        , editCaptor.capture(), anyBoolean());
5858
5859      WALEdit edit = editCaptor.getValue();
5860      assertNotNull(edit);
5861      assertNotNull(edit.getCells());
5862      assertEquals(1, edit.getCells().size());
5863      RegionEventDescriptor desc = WALEdit.getRegionEventDescriptor(edit.getCells().get(0));
5864      assertNotNull(desc);
5865
5866      LOG.info("RegionEventDescriptor from WAL: " + desc);
5867
5868      assertEquals(RegionEventDescriptor.EventType.REGION_OPEN, desc.getEventType());
5869      assertTrue(Bytes.equals(desc.getTableName().toByteArray(), htd.getTableName().toBytes()));
5870      assertTrue(Bytes.equals(desc.getEncodedRegionName().toByteArray(),
5871        hri.getEncodedNameAsBytes()));
5872      assertTrue(desc.getLogSequenceNumber() > 0);
5873      assertEquals(serverName, ProtobufUtil.toServerName(desc.getServer()));
5874      assertEquals(2, desc.getStoresCount());
5875
5876      StoreDescriptor store = desc.getStores(0);
5877      assertTrue(Bytes.equals(store.getFamilyName().toByteArray(), fam1));
5878      assertEquals(store.getStoreHomeDir(), Bytes.toString(fam1));
5879      assertEquals(1, store.getStoreFileCount()); // 1store file
5880      assertFalse(store.getStoreFile(0).contains("/")); // ensure path is relative
5881
5882      store = desc.getStores(1);
5883      assertTrue(Bytes.equals(store.getFamilyName().toByteArray(), fam2));
5884      assertEquals(store.getStoreHomeDir(), Bytes.toString(fam2));
5885      assertEquals(0, store.getStoreFileCount()); // no store files
5886
5887    } finally {
5888      HBaseTestingUtility.closeRegionAndWAL(region);
5889    }
5890  }
5891
5892  // Helper for test testOpenRegionWrittenToWALForLogReplay
5893  static class HRegionWithSeqId extends HRegion {
5894    public HRegionWithSeqId(final Path tableDir, final WAL wal, final FileSystem fs,
5895        final Configuration confParam, final RegionInfo regionInfo,
5896        final TableDescriptor htd, final RegionServerServices rsServices) {
5897      super(tableDir, wal, fs, confParam, regionInfo, htd, rsServices);
5898    }
5899    @Override
5900    protected long getNextSequenceId(WAL wal) throws IOException {
5901      return 42;
5902    }
5903  }
5904
5905  @Test
5906  public void testFlushedFileWithNoTags() throws Exception {
5907    final TableName tableName = TableName.valueOf(name.getMethodName());
5908    HTableDescriptor htd = new HTableDescriptor(tableName);
5909    htd.addFamily(new HColumnDescriptor(fam1));
5910    HRegionInfo info = new HRegionInfo(tableName, null, null, false);
5911    Path path = TEST_UTIL.getDataTestDir(getClass().getSimpleName());
5912    region = HBaseTestingUtility.createRegionAndWAL(info, path, TEST_UTIL.getConfiguration(), htd);
5913    Put put = new Put(Bytes.toBytes("a-b-0-0"));
5914    put.addColumn(fam1, qual1, Bytes.toBytes("c1-value"));
5915    region.put(put);
5916    region.flush(true);
5917    HStore store = region.getStore(fam1);
5918    Collection<HStoreFile> storefiles = store.getStorefiles();
5919    for (HStoreFile sf : storefiles) {
5920      assertFalse("Tags should not be present "
5921          ,sf.getReader().getHFileReader().getFileContext().isIncludesTags());
5922    }
5923  }
5924
5925  /**
5926   * Utility method to setup a WAL mock.
5927   * Needs to do the bit where we close latch on the WALKeyImpl on append else test hangs.
5928   * @return
5929   * @throws IOException
5930   */
5931  private WAL mockWAL() throws IOException {
5932    WAL wal = mock(WAL.class);
5933    Mockito.when(wal.append((HRegionInfo)Mockito.any(),
5934        (WALKeyImpl)Mockito.any(), (WALEdit)Mockito.any(), Mockito.anyBoolean())).
5935      thenAnswer(new Answer<Long>() {
5936        @Override
5937        public Long answer(InvocationOnMock invocation) throws Throwable {
5938          WALKeyImpl key = invocation.getArgument(1);
5939          MultiVersionConcurrencyControl.WriteEntry we = key.getMvcc().begin();
5940          key.setWriteEntry(we);
5941          return 1L;
5942        }
5943
5944    });
5945    return wal;
5946  }
5947
5948  @Test
5949  public void testCloseRegionWrittenToWAL() throws Exception {
5950
5951    Path rootDir = new Path(dir + name.getMethodName());
5952    FSUtils.setRootDir(TEST_UTIL.getConfiguration(), rootDir);
5953
5954    final ServerName serverName = ServerName.valueOf("testCloseRegionWrittenToWAL", 100, 42);
5955    final RegionServerServices rss = spy(TEST_UTIL.createMockRegionServerService(serverName));
5956
5957    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName()));
5958    htd.addFamily(new HColumnDescriptor(fam1));
5959    htd.addFamily(new HColumnDescriptor(fam2));
5960
5961    final HRegionInfo hri = new HRegionInfo(htd.getTableName(),
5962      HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY);
5963
5964    ArgumentCaptor<WALEdit> editCaptor = ArgumentCaptor.forClass(WALEdit.class);
5965
5966    // capture append() calls
5967    WAL wal = mockWAL();
5968    when(rss.getWAL((HRegionInfo) any())).thenReturn(wal);
5969
5970
5971    // create and then open a region first so that it can be closed later
5972    region = HRegion.createHRegion(hri, rootDir, TEST_UTIL.getConfiguration(), htd, rss.getWAL(hri));
5973    region = HRegion.openHRegion(hri, htd, rss.getWAL(hri),
5974      TEST_UTIL.getConfiguration(), rss, null);
5975
5976    // close the region
5977    region.close(false);
5978
5979    // 2 times, one for region open, the other close region
5980    verify(wal, times(2)).append((HRegionInfo)any(), (WALKeyImpl)any(),
5981      editCaptor.capture(), anyBoolean());
5982
5983    WALEdit edit = editCaptor.getAllValues().get(1);
5984    assertNotNull(edit);
5985    assertNotNull(edit.getCells());
5986    assertEquals(1, edit.getCells().size());
5987    RegionEventDescriptor desc = WALEdit.getRegionEventDescriptor(edit.getCells().get(0));
5988    assertNotNull(desc);
5989
5990    LOG.info("RegionEventDescriptor from WAL: " + desc);
5991
5992    assertEquals(RegionEventDescriptor.EventType.REGION_CLOSE, desc.getEventType());
5993    assertTrue(Bytes.equals(desc.getTableName().toByteArray(), htd.getTableName().toBytes()));
5994    assertTrue(Bytes.equals(desc.getEncodedRegionName().toByteArray(),
5995      hri.getEncodedNameAsBytes()));
5996    assertTrue(desc.getLogSequenceNumber() > 0);
5997    assertEquals(serverName, ProtobufUtil.toServerName(desc.getServer()));
5998    assertEquals(2, desc.getStoresCount());
5999
6000    StoreDescriptor store = desc.getStores(0);
6001    assertTrue(Bytes.equals(store.getFamilyName().toByteArray(), fam1));
6002    assertEquals(store.getStoreHomeDir(), Bytes.toString(fam1));
6003    assertEquals(0, store.getStoreFileCount()); // no store files
6004
6005    store = desc.getStores(1);
6006    assertTrue(Bytes.equals(store.getFamilyName().toByteArray(), fam2));
6007    assertEquals(store.getStoreHomeDir(), Bytes.toString(fam2));
6008    assertEquals(0, store.getStoreFileCount()); // no store files
6009  }
6010
6011  /**
6012   * Test RegionTooBusyException thrown when region is busy
6013   */
6014  @Test
6015  public void testRegionTooBusy() throws IOException {
6016    byte[] family = Bytes.toBytes("family");
6017    long defaultBusyWaitDuration = CONF.getLong("hbase.busy.wait.duration",
6018      HRegion.DEFAULT_BUSY_WAIT_DURATION);
6019    CONF.setLong("hbase.busy.wait.duration", 1000);
6020    region = initHRegion(tableName, method, CONF, family);
6021    final AtomicBoolean stopped = new AtomicBoolean(true);
6022    Thread t = new Thread(new Runnable() {
6023      @Override
6024      public void run() {
6025        try {
6026          region.lock.writeLock().lock();
6027          stopped.set(false);
6028          while (!stopped.get()) {
6029            Thread.sleep(100);
6030          }
6031        } catch (InterruptedException ie) {
6032        } finally {
6033          region.lock.writeLock().unlock();
6034        }
6035      }
6036    });
6037    t.start();
6038    Get get = new Get(row);
6039    try {
6040      while (stopped.get()) {
6041        Thread.sleep(100);
6042      }
6043      region.get(get);
6044      fail("Should throw RegionTooBusyException");
6045    } catch (InterruptedException ie) {
6046      fail("test interrupted");
6047    } catch (RegionTooBusyException e) {
6048      // Good, expected
6049    } finally {
6050      stopped.set(true);
6051      try {
6052        t.join();
6053      } catch (Throwable e) {
6054      }
6055
6056      HBaseTestingUtility.closeRegionAndWAL(region);
6057      region = null;
6058      CONF.setLong("hbase.busy.wait.duration", defaultBusyWaitDuration);
6059    }
6060  }
6061
6062  @Test
6063  public void testCellTTLs() throws IOException {
6064    IncrementingEnvironmentEdge edge = new IncrementingEnvironmentEdge();
6065    EnvironmentEdgeManager.injectEdge(edge);
6066
6067    final byte[] row = Bytes.toBytes("testRow");
6068    final byte[] q1 = Bytes.toBytes("q1");
6069    final byte[] q2 = Bytes.toBytes("q2");
6070    final byte[] q3 = Bytes.toBytes("q3");
6071    final byte[] q4 = Bytes.toBytes("q4");
6072
6073    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName()));
6074    HColumnDescriptor hcd = new HColumnDescriptor(fam1);
6075    hcd.setTimeToLive(10); // 10 seconds
6076    htd.addFamily(hcd);
6077
6078    Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
6079    conf.setInt(HFile.FORMAT_VERSION_KEY, HFile.MIN_FORMAT_VERSION_WITH_TAGS);
6080
6081    HRegion region = HBaseTestingUtility.createRegionAndWAL(new HRegionInfo(htd.getTableName(),
6082            HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY),
6083        TEST_UTIL.getDataTestDir(), conf, htd);
6084    assertNotNull(region);
6085    try {
6086      long now = EnvironmentEdgeManager.currentTime();
6087      // Add a cell that will expire in 5 seconds via cell TTL
6088      region.put(new Put(row).add(new KeyValue(row, fam1, q1, now,
6089        HConstants.EMPTY_BYTE_ARRAY, new ArrayBackedTag[] {
6090          // TTL tags specify ts in milliseconds
6091          new ArrayBackedTag(TagType.TTL_TAG_TYPE, Bytes.toBytes(5000L)) } )));
6092      // Add a cell that will expire after 10 seconds via family setting
6093      region.put(new Put(row).addColumn(fam1, q2, now, HConstants.EMPTY_BYTE_ARRAY));
6094      // Add a cell that will expire in 15 seconds via cell TTL
6095      region.put(new Put(row).add(new KeyValue(row, fam1, q3, now + 10000 - 1,
6096        HConstants.EMPTY_BYTE_ARRAY, new ArrayBackedTag[] {
6097          // TTL tags specify ts in milliseconds
6098          new ArrayBackedTag(TagType.TTL_TAG_TYPE, Bytes.toBytes(5000L)) } )));
6099      // Add a cell that will expire in 20 seconds via family setting
6100      region.put(new Put(row).addColumn(fam1, q4, now + 10000 - 1, HConstants.EMPTY_BYTE_ARRAY));
6101
6102      // Flush so we are sure store scanning gets this right
6103      region.flush(true);
6104
6105      // A query at time T+0 should return all cells
6106      Result r = region.get(new Get(row));
6107      assertNotNull(r.getValue(fam1, q1));
6108      assertNotNull(r.getValue(fam1, q2));
6109      assertNotNull(r.getValue(fam1, q3));
6110      assertNotNull(r.getValue(fam1, q4));
6111
6112      // Increment time to T+5 seconds
6113      edge.incrementTime(5000);
6114
6115      r = region.get(new Get(row));
6116      assertNull(r.getValue(fam1, q1));
6117      assertNotNull(r.getValue(fam1, q2));
6118      assertNotNull(r.getValue(fam1, q3));
6119      assertNotNull(r.getValue(fam1, q4));
6120
6121      // Increment time to T+10 seconds
6122      edge.incrementTime(5000);
6123
6124      r = region.get(new Get(row));
6125      assertNull(r.getValue(fam1, q1));
6126      assertNull(r.getValue(fam1, q2));
6127      assertNotNull(r.getValue(fam1, q3));
6128      assertNotNull(r.getValue(fam1, q4));
6129
6130      // Increment time to T+15 seconds
6131      edge.incrementTime(5000);
6132
6133      r = region.get(new Get(row));
6134      assertNull(r.getValue(fam1, q1));
6135      assertNull(r.getValue(fam1, q2));
6136      assertNull(r.getValue(fam1, q3));
6137      assertNotNull(r.getValue(fam1, q4));
6138
6139      // Increment time to T+20 seconds
6140      edge.incrementTime(10000);
6141
6142      r = region.get(new Get(row));
6143      assertNull(r.getValue(fam1, q1));
6144      assertNull(r.getValue(fam1, q2));
6145      assertNull(r.getValue(fam1, q3));
6146      assertNull(r.getValue(fam1, q4));
6147
6148      // Fun with disappearing increments
6149
6150      // Start at 1
6151      region.put(new Put(row).addColumn(fam1, q1, Bytes.toBytes(1L)));
6152      r = region.get(new Get(row));
6153      byte[] val = r.getValue(fam1, q1);
6154      assertNotNull(val);
6155      assertEquals(1L, Bytes.toLong(val));
6156
6157      // Increment with a TTL of 5 seconds
6158      Increment incr = new Increment(row).addColumn(fam1, q1, 1L);
6159      incr.setTTL(5000);
6160      region.increment(incr); // 2
6161
6162      // New value should be 2
6163      r = region.get(new Get(row));
6164      val = r.getValue(fam1, q1);
6165      assertNotNull(val);
6166      assertEquals(2L, Bytes.toLong(val));
6167
6168      // Increment time to T+25 seconds
6169      edge.incrementTime(5000);
6170
6171      // Value should be back to 1
6172      r = region.get(new Get(row));
6173      val = r.getValue(fam1, q1);
6174      assertNotNull(val);
6175      assertEquals(1L, Bytes.toLong(val));
6176
6177      // Increment time to T+30 seconds
6178      edge.incrementTime(5000);
6179
6180      // Original value written at T+20 should be gone now via family TTL
6181      r = region.get(new Get(row));
6182      assertNull(r.getValue(fam1, q1));
6183
6184    } finally {
6185      HBaseTestingUtility.closeRegionAndWAL(region);
6186    }
6187  }
6188
6189  @Test
6190  public void testIncrementTimestampsAreMonotonic() throws IOException {
6191    HRegion region = initHRegion(tableName, method, CONF, fam1);
6192    ManualEnvironmentEdge edge = new ManualEnvironmentEdge();
6193    EnvironmentEdgeManager.injectEdge(edge);
6194
6195    edge.setValue(10);
6196    Increment inc = new Increment(row);
6197    inc.setDurability(Durability.SKIP_WAL);
6198    inc.addColumn(fam1, qual1, 1L);
6199    region.increment(inc);
6200
6201    Result result = region.get(new Get(row));
6202    Cell c = result.getColumnLatestCell(fam1, qual1);
6203    assertNotNull(c);
6204    assertEquals(10L, c.getTimestamp());
6205
6206    edge.setValue(1); // clock goes back
6207    region.increment(inc);
6208    result = region.get(new Get(row));
6209    c = result.getColumnLatestCell(fam1, qual1);
6210    assertEquals(11L, c.getTimestamp());
6211    assertEquals(2L, Bytes.toLong(c.getValueArray(), c.getValueOffset(), c.getValueLength()));
6212  }
6213
6214  @Test
6215  public void testAppendTimestampsAreMonotonic() throws IOException {
6216    HRegion region = initHRegion(tableName, method, CONF, fam1);
6217    ManualEnvironmentEdge edge = new ManualEnvironmentEdge();
6218    EnvironmentEdgeManager.injectEdge(edge);
6219
6220    edge.setValue(10);
6221    Append a = new Append(row);
6222    a.setDurability(Durability.SKIP_WAL);
6223    a.addColumn(fam1, qual1, qual1);
6224    region.append(a);
6225
6226    Result result = region.get(new Get(row));
6227    Cell c = result.getColumnLatestCell(fam1, qual1);
6228    assertNotNull(c);
6229    assertEquals(10L, c.getTimestamp());
6230
6231    edge.setValue(1); // clock goes back
6232    region.append(a);
6233    result = region.get(new Get(row));
6234    c = result.getColumnLatestCell(fam1, qual1);
6235    assertEquals(11L, c.getTimestamp());
6236
6237    byte[] expected = new byte[qual1.length*2];
6238    System.arraycopy(qual1, 0, expected, 0, qual1.length);
6239    System.arraycopy(qual1, 0, expected, qual1.length, qual1.length);
6240
6241    assertTrue(Bytes.equals(c.getValueArray(), c.getValueOffset(), c.getValueLength(),
6242      expected, 0, expected.length));
6243  }
6244
6245  @Test
6246  public void testCheckAndMutateTimestampsAreMonotonic() throws IOException {
6247    HRegion region = initHRegion(tableName, method, CONF, fam1);
6248    ManualEnvironmentEdge edge = new ManualEnvironmentEdge();
6249    EnvironmentEdgeManager.injectEdge(edge);
6250
6251    edge.setValue(10);
6252    Put p = new Put(row);
6253    p.setDurability(Durability.SKIP_WAL);
6254    p.addColumn(fam1, qual1, qual1);
6255    region.put(p);
6256
6257    Result result = region.get(new Get(row));
6258    Cell c = result.getColumnLatestCell(fam1, qual1);
6259    assertNotNull(c);
6260    assertEquals(10L, c.getTimestamp());
6261
6262    edge.setValue(1); // clock goes back
6263    p = new Put(row);
6264    p.setDurability(Durability.SKIP_WAL);
6265    p.addColumn(fam1, qual1, qual2);
6266    region.checkAndMutate(row, fam1, qual1, CompareOperator.EQUAL, new BinaryComparator(qual1), p);
6267    result = region.get(new Get(row));
6268    c = result.getColumnLatestCell(fam1, qual1);
6269    assertEquals(10L, c.getTimestamp());
6270
6271    assertTrue(Bytes.equals(c.getValueArray(), c.getValueOffset(), c.getValueLength(),
6272      qual2, 0, qual2.length));
6273  }
6274
6275  @Test
6276  public void testBatchMutateWithWrongRegionException() throws Exception {
6277    final byte[] a = Bytes.toBytes("a");
6278    final byte[] b = Bytes.toBytes("b");
6279    final byte[] c = Bytes.toBytes("c"); // exclusive
6280
6281    int prevLockTimeout = CONF.getInt("hbase.rowlock.wait.duration", 30000);
6282    CONF.setInt("hbase.rowlock.wait.duration", 1000);
6283    final HRegion region = initHRegion(tableName, a, c, method, CONF, false, fam1);
6284
6285    Mutation[] mutations = new Mutation[] {
6286        new Put(a)
6287            .add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY)
6288              .setRow(a)
6289              .setFamily(fam1)
6290              .setTimestamp(HConstants.LATEST_TIMESTAMP)
6291              .setType(Cell.Type.Put)
6292              .build()),
6293        // this is outside the region boundary
6294        new Put(c).add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY)
6295              .setRow(c)
6296              .setFamily(fam1)
6297              .setTimestamp(HConstants.LATEST_TIMESTAMP)
6298              .setType(Type.Put)
6299              .build()),
6300        new Put(b).add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY)
6301              .setRow(b)
6302              .setFamily(fam1)
6303              .setTimestamp(HConstants.LATEST_TIMESTAMP)
6304              .setType(Cell.Type.Put)
6305              .build())
6306    };
6307
6308    OperationStatus[] status = region.batchMutate(mutations);
6309    assertEquals(OperationStatusCode.SUCCESS, status[0].getOperationStatusCode());
6310    assertEquals(OperationStatusCode.SANITY_CHECK_FAILURE, status[1].getOperationStatusCode());
6311    assertEquals(OperationStatusCode.SUCCESS, status[2].getOperationStatusCode());
6312
6313
6314    // test with a row lock held for a long time
6315    final CountDownLatch obtainedRowLock = new CountDownLatch(1);
6316    ExecutorService exec = Executors.newFixedThreadPool(2);
6317    Future<Void> f1 = exec.submit(new Callable<Void>() {
6318      @Override
6319      public Void call() throws Exception {
6320        LOG.info("Acquiring row lock");
6321        RowLock rl = region.getRowLock(b);
6322        obtainedRowLock.countDown();
6323        LOG.info("Waiting for 5 seconds before releasing lock");
6324        Threads.sleep(5000);
6325        LOG.info("Releasing row lock");
6326        rl.release();
6327        return null;
6328      }
6329    });
6330    obtainedRowLock.await(30, TimeUnit.SECONDS);
6331
6332    Future<Void> f2 = exec.submit(new Callable<Void>() {
6333      @Override
6334      public Void call() throws Exception {
6335        Mutation[] mutations = new Mutation[] {
6336            new Put(a).add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY)
6337                .setRow(a)
6338                .setFamily(fam1)
6339                .setTimestamp(HConstants.LATEST_TIMESTAMP)
6340                .setType(Cell.Type.Put)
6341                .build()),
6342            new Put(b).add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY)
6343                .setRow(b)
6344                .setFamily(fam1)
6345                .setTimestamp(HConstants.LATEST_TIMESTAMP)
6346                .setType(Cell.Type.Put)
6347                .build()),
6348        };
6349
6350        // this will wait for the row lock, and it will eventually succeed
6351        OperationStatus[] status = region.batchMutate(mutations);
6352        assertEquals(OperationStatusCode.SUCCESS, status[0].getOperationStatusCode());
6353        assertEquals(OperationStatusCode.SUCCESS, status[1].getOperationStatusCode());
6354        return null;
6355      }
6356    });
6357
6358    f1.get();
6359    f2.get();
6360
6361    CONF.setInt("hbase.rowlock.wait.duration", prevLockTimeout);
6362  }
6363
6364  @Test
6365  public void testCheckAndRowMutateTimestampsAreMonotonic() throws IOException {
6366    HRegion region = initHRegion(tableName, method, CONF, fam1);
6367    ManualEnvironmentEdge edge = new ManualEnvironmentEdge();
6368    EnvironmentEdgeManager.injectEdge(edge);
6369
6370    edge.setValue(10);
6371    Put p = new Put(row);
6372    p.setDurability(Durability.SKIP_WAL);
6373    p.addColumn(fam1, qual1, qual1);
6374    region.put(p);
6375
6376    Result result = region.get(new Get(row));
6377    Cell c = result.getColumnLatestCell(fam1, qual1);
6378    assertNotNull(c);
6379    assertEquals(10L, c.getTimestamp());
6380
6381    edge.setValue(1); // clock goes back
6382    p = new Put(row);
6383    p.setDurability(Durability.SKIP_WAL);
6384    p.addColumn(fam1, qual1, qual2);
6385    RowMutations rm = new RowMutations(row);
6386    rm.add(p);
6387    assertTrue(region.checkAndRowMutate(row, fam1, qual1, CompareOperator.EQUAL,
6388        new BinaryComparator(qual1), rm));
6389    result = region.get(new Get(row));
6390    c = result.getColumnLatestCell(fam1, qual1);
6391    assertEquals(10L, c.getTimestamp());
6392    LOG.info("c value " +
6393      Bytes.toStringBinary(c.getValueArray(), c.getValueOffset(), c.getValueLength()));
6394
6395    assertTrue(Bytes.equals(c.getValueArray(), c.getValueOffset(), c.getValueLength(),
6396      qual2, 0, qual2.length));
6397  }
6398
6399  HRegion initHRegion(TableName tableName, String callingMethod,
6400      byte[]... families) throws IOException {
6401    return initHRegion(tableName, callingMethod, HBaseConfiguration.create(),
6402        families);
6403  }
6404
6405  /**
6406   * HBASE-16429 Make sure no stuck if roll writer when ring buffer is filled with appends
6407   * @throws IOException if IO error occurred during test
6408   */
6409  @Test
6410  public void testWritesWhileRollWriter() throws IOException {
6411    int testCount = 10;
6412    int numRows = 1024;
6413    int numFamilies = 2;
6414    int numQualifiers = 2;
6415    final byte[][] families = new byte[numFamilies][];
6416    for (int i = 0; i < numFamilies; i++) {
6417      families[i] = Bytes.toBytes("family" + i);
6418    }
6419    final byte[][] qualifiers = new byte[numQualifiers][];
6420    for (int i = 0; i < numQualifiers; i++) {
6421      qualifiers[i] = Bytes.toBytes("qual" + i);
6422    }
6423
6424    CONF.setInt("hbase.regionserver.wal.disruptor.event.count", 2);
6425    this.region = initHRegion(tableName, method, CONF, families);
6426    try {
6427      List<Thread> threads = new ArrayList<>();
6428      for (int i = 0; i < numRows; i++) {
6429        final int count = i;
6430        Thread t = new Thread(new Runnable() {
6431
6432          @Override
6433          public void run() {
6434            byte[] row = Bytes.toBytes("row" + count);
6435            Put put = new Put(row);
6436            put.setDurability(Durability.SYNC_WAL);
6437            byte[] value = Bytes.toBytes(String.valueOf(count));
6438            for (byte[] family : families) {
6439              for (byte[] qualifier : qualifiers) {
6440                put.addColumn(family, qualifier, count, value);
6441              }
6442            }
6443            try {
6444              region.put(put);
6445            } catch (IOException e) {
6446              throw new RuntimeException(e);
6447            }
6448          }
6449        });
6450        threads.add(t);
6451      }
6452      for (Thread t : threads) {
6453        t.start();
6454      }
6455
6456      for (int i = 0; i < testCount; i++) {
6457        region.getWAL().rollWriter();
6458        Thread.yield();
6459      }
6460    } finally {
6461      try {
6462        HBaseTestingUtility.closeRegionAndWAL(this.region);
6463        CONF.setInt("hbase.regionserver.wal.disruptor.event.count", 16 * 1024);
6464      } catch (DroppedSnapshotException dse) {
6465        // We could get this on way out because we interrupt the background flusher and it could
6466        // fail anywhere causing a DSE over in the background flusher... only it is not properly
6467        // dealt with so could still be memory hanging out when we get to here -- memory we can't
6468        // flush because the accounting is 'off' since original DSE.
6469      }
6470      this.region = null;
6471    }
6472  }
6473
6474  @Test
6475  public void testMutateRow_WriteRequestCount() throws Exception {
6476    byte[] row1 = Bytes.toBytes("row1");
6477    byte[] fam1 = Bytes.toBytes("fam1");
6478    byte[] qf1 = Bytes.toBytes("qualifier");
6479    byte[] val1 = Bytes.toBytes("value1");
6480
6481    RowMutations rm = new RowMutations(row1);
6482    Put put = new Put(row1);
6483    put.addColumn(fam1, qf1, val1);
6484    rm.add(put);
6485
6486    this.region = initHRegion(tableName, method, CONF, fam1);
6487    try {
6488      long wrcBeforeMutate = this.region.writeRequestsCount.longValue();
6489      this.region.mutateRow(rm);
6490      long wrcAfterMutate = this.region.writeRequestsCount.longValue();
6491      Assert.assertEquals(wrcBeforeMutate + rm.getMutations().size(), wrcAfterMutate);
6492    } finally {
6493      HBaseTestingUtility.closeRegionAndWAL(this.region);
6494      this.region = null;
6495    }
6496  }
6497
6498  /**
6499   * The same as HRegion class, the only difference is that instantiateHStore will
6500   * create a different HStore - HStoreForTesting. [HBASE-8518]
6501   */
6502  public static class HRegionForTesting extends HRegion {
6503
6504    public HRegionForTesting(final Path tableDir, final WAL wal, final FileSystem fs,
6505                             final Configuration confParam, final RegionInfo regionInfo,
6506                             final TableDescriptor htd, final RegionServerServices rsServices) {
6507      this(new HRegionFileSystem(confParam, fs, tableDir, regionInfo),
6508          wal, confParam, htd, rsServices);
6509    }
6510
6511    public HRegionForTesting(HRegionFileSystem fs, WAL wal,
6512                             Configuration confParam, TableDescriptor htd,
6513                             RegionServerServices rsServices) {
6514      super(fs, wal, confParam, htd, rsServices);
6515    }
6516
6517    /**
6518     * Create HStore instance.
6519     * @return If Mob is enabled, return HMobStore, otherwise return HStoreForTesting.
6520     */
6521    @Override
6522    protected HStore instantiateHStore(final ColumnFamilyDescriptor family) throws IOException {
6523      if (family.isMobEnabled()) {
6524        if (HFile.getFormatVersion(this.conf) < HFile.MIN_FORMAT_VERSION_WITH_TAGS) {
6525          throw new IOException("A minimum HFile version of "
6526              + HFile.MIN_FORMAT_VERSION_WITH_TAGS
6527              + " is required for MOB feature. Consider setting " + HFile.FORMAT_VERSION_KEY
6528              + " accordingly.");
6529        }
6530        return new HMobStore(this, family, this.conf);
6531      }
6532      return new HStoreForTesting(this, family, this.conf);
6533    }
6534  }
6535
6536  /**
6537   * HStoreForTesting is merely the same as HStore, the difference is in the doCompaction method
6538   * of HStoreForTesting there is a checkpoint "hbase.hstore.compaction.complete" which
6539   * doesn't let hstore compaction complete. In the former edition, this config is set in
6540   * HStore class inside compact method, though this is just for testing, otherwise it
6541   * doesn't do any help. In HBASE-8518, we try to get rid of all "hbase.hstore.compaction.complete"
6542   * config (except for testing code).
6543   */
6544  public static class HStoreForTesting extends HStore {
6545
6546    protected HStoreForTesting(final HRegion region,
6547        final ColumnFamilyDescriptor family,
6548        final Configuration confParam) throws IOException {
6549      super(region, family, confParam);
6550    }
6551
6552    @Override
6553    protected List<HStoreFile> doCompaction(CompactionRequestImpl cr,
6554        Collection<HStoreFile> filesToCompact, User user, long compactionStartTime,
6555        List<Path> newFiles) throws IOException {
6556      // let compaction incomplete.
6557      if (!this.conf.getBoolean("hbase.hstore.compaction.complete", true)) {
6558        LOG.warn("hbase.hstore.compaction.complete is set to false");
6559        List<HStoreFile> sfs = new ArrayList<>(newFiles.size());
6560        final boolean evictOnClose =
6561            cacheConf != null? cacheConf.shouldEvictOnClose(): true;
6562        for (Path newFile : newFiles) {
6563          // Create storefile around what we wrote with a reader on it.
6564          HStoreFile sf = createStoreFileAndReader(newFile);
6565          sf.closeStoreFile(evictOnClose);
6566          sfs.add(sf);
6567        }
6568        return sfs;
6569      }
6570      return super.doCompaction(cr, filesToCompact, user, compactionStartTime, newFiles);
6571    }
6572  }
6573}