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