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