Skip to content

Commit a4162d0

Browse files
committed
HBASE-22623 - Add RegionObserver coprocessor hook for preWALAppend
1 parent 5ce31dd commit a4162d0

File tree

8 files changed

+187
-1
lines changed

8 files changed

+187
-1
lines changed

hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/RegionObserver.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,4 +1104,15 @@ default DeleteTracker postInstantiateDeleteTracker(
11041104
throws IOException {
11051105
return delTracker;
11061106
}
1107+
1108+
/**
1109+
* Called just before the WAL Entry is appended to the WAL. Implementing this hook allows
1110+
* coprocessors to add extended attributes to the WALKey that then get persisted to the
1111+
* WAL, and are available to replication endpoints to use in processing WAL Entries.
1112+
* @param ctx the environment provided by the region server
1113+
* @param key the WALKey associated with a particular append to a WAL
1114+
*/
1115+
default void preWALAppend(ObserverContext<RegionCoprocessorEnvironment> ctx, WALKey key)
1116+
throws IOException {
1117+
}
11071118
}

hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7951,6 +7951,9 @@ private WriteEntry doWALAppend(WALEdit walEdit, Durability durability, List<UUID
79517951
if (walEdit.isReplay()) {
79527952
walKey.setOrigLogSeqNum(origLogSeqNum);
79537953
}
7954+
if (this.coprocessorHost != null) {
7955+
this.coprocessorHost.preWALAppend(walKey);
7956+
}
79547957
WriteEntry writeEntry = null;
79557958
try {
79567959
long txid = this.wal.append(this.getRegionInfo(), walKey, walEdit, true);

hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionCoprocessorHost.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1720,6 +1720,19 @@ public List<Pair<Cell, Cell>> call(RegionObserver observer) throws IOException {
17201720
});
17211721
}
17221722

1723+
public void preWALAppend(WALKey key) throws IOException {
1724+
if (this.coprocEnvironments.isEmpty()){
1725+
return;
1726+
}
1727+
execOperation(new RegionObserverOperationWithoutResult()
1728+
{
1729+
@Override
1730+
public void call(RegionObserver observer) throws IOException {
1731+
observer.preWALAppend(this, key);
1732+
}
1733+
});
1734+
}
1735+
17231736
public Message preEndpointInvocation(final Service service, final String methodName,
17241737
Message request) throws IOException {
17251738
if (coprocEnvironments.isEmpty()) {

hbase-server/src/main/java/org/apache/hadoop/hbase/wal/WALKey.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,13 @@ default long getNonce() {
8686
*/
8787
long getOrigLogSeqNum();
8888

89+
/**
90+
* Add a named String value to this WALKey to be persisted into the WAL
91+
* @param attributeKey Name of the attribute
92+
* @param attributeValue Value of the attribute
93+
*/
94+
void addExtendedAttribute(String attributeKey, byte[] attributeValue);
95+
8996
/**
9097
* Return a named String value injected into the WALKey during processing, such as by a
9198
* coprocessor

hbase-server/src/main/java/org/apache/hadoop/hbase/wal/WALKeyImpl.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,37 @@ public WALKeyImpl(final byte[] encodedRegionName,
195195
mvcc, null, null);
196196
}
197197

198+
/**
199+
* Copy constructor that takes in an existing WALKeyImpl plus some extended attributes.
200+
* Intended for coprocessors to add annotations to a system-generated WALKey
201+
* for persistence to the WAL.
202+
* @param key Key to be copied into this new key
203+
* @param extendedAttributes Extra attributes to copy into the new key
204+
*/
205+
public WALKeyImpl(WALKeyImpl key,
206+
Map<String, byte[]> extendedAttributes){
207+
init(key.getEncodedRegionName(), key.getTableName(), key.getSequenceId(),
208+
key.getWriteTime(), key.getClusterIds(), key.getNonceGroup(), key.getNonce(),
209+
key.getMvcc(), key.getReplicationScopes(), extendedAttributes);
210+
211+
}
212+
213+
/**
214+
* Copy constructor that takes in an existing WALKey, the extra WALKeyImpl fields that the
215+
* parent interface is missing, plus some extended attributes. Intended
216+
* for coprocessors to add annotations to a system-generated WALKey for
217+
* persistence to the WAL.
218+
*/
219+
public WALKeyImpl(WALKey key,
220+
List<UUID> clusterIds,
221+
MultiVersionConcurrencyControl mvcc,
222+
final NavigableMap<byte[], Integer> replicationScopes,
223+
Map<String, byte[]> extendedAttributes){
224+
init(key.getEncodedRegionName(), key.getTableName(), key.getSequenceId(),
225+
key.getWriteTime(), clusterIds, key.getNonceGroup(), key.getNonce(),
226+
mvcc, replicationScopes, extendedAttributes);
227+
228+
}
198229
/**
199230
* Create the log key for writing to somewhere.
200231
* We maintain the tablename mainly for debugging purposes.
@@ -464,6 +495,14 @@ public UUID getOriginatingClusterId(){
464495
return clusterIds.isEmpty()? HConstants.DEFAULT_CLUSTER_ID: clusterIds.get(0);
465496
}
466497

498+
@Override
499+
public void addExtendedAttribute(String attributeKey, byte[] attributeValue){
500+
if (extendedAttributes == null){
501+
extendedAttributes = new HashMap<String, byte[]>();
502+
}
503+
extendedAttributes.put(attributeKey, attributeValue);
504+
}
505+
467506
@Override
468507
public byte[] getExtendedAttribute(String attributeKey){
469508
return extendedAttributes != null ? extendedAttributes.get(attributeKey) : null;

hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/SimpleRegionObserver.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import static org.junit.Assert.assertTrue;
2626

2727
import java.io.IOException;
28+
import java.util.HashMap;
2829
import java.util.List;
2930
import java.util.Map;
3031
import java.util.Optional;
@@ -124,7 +125,11 @@ public class SimpleRegionObserver implements RegionCoprocessor, RegionObserver {
124125
final AtomicInteger ctPostStartRegionOperation = new AtomicInteger(0);
125126
final AtomicInteger ctPostCloseRegionOperation = new AtomicInteger(0);
126127
final AtomicBoolean throwOnPostFlush = new AtomicBoolean(false);
128+
final AtomicInteger ctPreWALAppend = new AtomicInteger(0);
129+
127130
static final String TABLE_SKIPPED = "SKIPPED_BY_PREWALRESTORE";
131+
Map<String, byte[]> extendedAttributes = new HashMap<String,byte[]>();
132+
static final byte[] WAL_EXTENDED_ATTRIBUTE_BYTES = Bytes.toBytes("foo");
128133

129134
public void setThrowOnPostFlush(Boolean val){
130135
throwOnPostFlush.set(val);
@@ -631,6 +636,15 @@ public StoreFileReader postStoreFileReaderOpen(ObserverContext<RegionCoprocessor
631636
return reader;
632637
}
633638

639+
@Override
640+
public void preWALAppend(ObserverContext<RegionCoprocessorEnvironment> ctx,
641+
WALKey key) throws IOException {
642+
ctPreWALAppend.incrementAndGet();
643+
644+
key.addExtendedAttribute(Integer.toString(ctPreWALAppend.get()),
645+
Bytes.toBytes("foo"));
646+
}
647+
634648
public boolean hadPreGet() {
635649
return ctPreGet.get() > 0;
636650
}
@@ -864,6 +878,10 @@ public int getCtPostWALRestore() {
864878
return ctPostWALRestore.get();
865879
}
866880

881+
public int getCtPreWALAppend() {
882+
return ctPreWALAppend.get();
883+
}
884+
867885
public boolean wasStoreFileReaderOpenCalled() {
868886
return ctPreStoreFileReaderOpen.get() > 0 && ctPostStoreFileReaderOpen.get() > 0;
869887
}

hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestRegionObserverInterface.java

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.io.IOException;
2626
import java.lang.reflect.Method;
2727
import java.util.ArrayList;
28+
import java.util.Arrays;
2829
import java.util.List;
2930
import java.util.Optional;
3031
import org.apache.hadoop.conf.Configuration;
@@ -70,20 +71,26 @@
7071
import org.apache.hadoop.hbase.regionserver.StoreFile;
7172
import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker;
7273
import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;
74+
import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
7375
import org.apache.hadoop.hbase.testclassification.CoprocessorTests;
7476
import org.apache.hadoop.hbase.testclassification.MediumTests;
7577
import org.apache.hadoop.hbase.tool.BulkLoadHFiles;
7678
import org.apache.hadoop.hbase.util.Bytes;
7779
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
7880
import org.apache.hadoop.hbase.util.JVMClusterUtil;
7981
import org.apache.hadoop.hbase.util.Threads;
82+
import org.apache.hadoop.hbase.wal.WALEdit;
83+
import org.apache.hadoop.hbase.wal.WALKey;
84+
import org.apache.hadoop.hbase.wal.WALKeyImpl;
8085
import org.junit.AfterClass;
86+
import org.junit.Assert;
8187
import org.junit.BeforeClass;
8288
import org.junit.ClassRule;
8389
import org.junit.Rule;
8490
import org.junit.Test;
8591
import org.junit.experimental.categories.Category;
8692
import org.junit.rules.TestName;
93+
import org.mockito.Mockito;
8794
import org.slf4j.Logger;
8895
import org.slf4j.LoggerFactory;
8996

@@ -663,6 +670,65 @@ public void testPreWALRestoreSkip() throws Exception {
663670
table.close();
664671
}
665672

673+
//called from testPreWALAppendIsWrittenToWAL
674+
private void testPreWALAppendHook(Table table, TableName tableName) throws IOException {
675+
int expectedCalls = 0;
676+
String [] methodArray = new String[1];
677+
methodArray[0] = "getCtPreWALAppend";
678+
Object[] resultArray = new Object[1];
679+
680+
Put p = new Put(ROW);
681+
p.addColumn(A, A, A);
682+
table.put(p);
683+
resultArray[0] = ++expectedCalls;
684+
verifyMethodResult(SimpleRegionObserver.class, methodArray, tableName, resultArray);
685+
686+
Append a = new Append(ROW);
687+
a.addColumn(B, B, B);
688+
table.append(a);
689+
resultArray[0] = ++expectedCalls;
690+
verifyMethodResult(SimpleRegionObserver.class, methodArray, tableName, resultArray);
691+
692+
Increment i = new Increment(ROW);
693+
i.addColumn(C, C, 1);
694+
table.increment(i);
695+
resultArray[0] = ++expectedCalls;
696+
verifyMethodResult(SimpleRegionObserver.class, methodArray, tableName, resultArray);
697+
698+
Delete d = new Delete(ROW);
699+
table.delete(d);
700+
resultArray[0] = ++expectedCalls;
701+
verifyMethodResult(SimpleRegionObserver.class, methodArray, tableName, resultArray);
702+
}
703+
704+
@Test
705+
public void testPreWALAppend() throws Exception {
706+
SimpleRegionObserver sro = new SimpleRegionObserver();
707+
ObserverContext ctx = Mockito.mock(ObserverContext.class);
708+
WALKey key = new WALKeyImpl(Bytes.toBytes("region"), TEST_TABLE,
709+
EnvironmentEdgeManager.currentTime());
710+
sro.preWALAppend(ctx, key);
711+
Assert.assertEquals(1, key.getExtendedAttributes().size());
712+
Assert.assertArrayEquals(SimpleRegionObserver.WAL_EXTENDED_ATTRIBUTE_BYTES,
713+
key.getExtendedAttribute(Integer.toString(sro.getCtPreWALAppend())));
714+
}
715+
716+
@Test
717+
public void testPreWALAppendIsWrittenToWAL() throws Exception {
718+
final TableName tableName = TableName.valueOf(TEST_TABLE.getNameAsString() +
719+
"." + name.getMethodName());
720+
Table table = util.createTable(tableName, new byte[][] { A, B, C });
721+
722+
PreWALAppendWALActionsListener listener = new PreWALAppendWALActionsListener();
723+
List<HRegion> regions = util.getHBaseCluster().getRegions(tableName);
724+
//should be only one region
725+
HRegion region = regions.get(0);
726+
region.getWAL().registerWALActionsListener(listener);
727+
testPreWALAppendHook(table, tableName);
728+
boolean[] expectedResults = {true, true, true, true};
729+
Assert.assertArrayEquals(expectedResults, listener.getWalKeysCorrectArray());
730+
731+
}
666732
// check each region whether the coprocessor upcalls are called or not.
667733
private void verifyMethodResult(Class<?> coprocessor, String methodName[], TableName tableName,
668734
Object value[]) throws IOException {
@@ -711,4 +777,23 @@ private static void createHFile(Configuration conf, FileSystem fs, Path path, by
711777
writer.close();
712778
}
713779
}
780+
781+
private static class PreWALAppendWALActionsListener implements WALActionsListener {
782+
boolean[] walKeysCorrect = {false, false, false, false};
783+
784+
@Override
785+
public void postAppend(long entryLen, long elapsedTimeMillis,
786+
WALKey logKey, WALEdit logEdit) throws IOException {
787+
for (int k = 0; k < 4; k++) {
788+
if (!walKeysCorrect[k]) {
789+
walKeysCorrect[k] = Arrays.equals(SimpleRegionObserver.WAL_EXTENDED_ATTRIBUTE_BYTES,
790+
logKey.getExtendedAttribute(Integer.toString(k + 1)));
791+
}
792+
}
793+
}
794+
795+
boolean[] getWalKeysCorrectArray() {
796+
return walKeysCorrect;
797+
}
798+
}
714799
}

hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@
104104
import org.apache.hadoop.hbase.Waiter;
105105
import org.apache.hadoop.hbase.client.Append;
106106
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
107+
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
107108
import org.apache.hadoop.hbase.client.Delete;
108109
import org.apache.hadoop.hbase.client.Durability;
109110
import org.apache.hadoop.hbase.client.Get;
@@ -165,7 +166,6 @@
165166
import org.apache.hadoop.hbase.wal.WALProvider;
166167
import org.apache.hadoop.hbase.wal.WALProvider.Writer;
167168
import org.apache.hadoop.hbase.wal.WALSplitUtil;
168-
import org.apache.hadoop.hbase.wal.WALSplitter;
169169
import org.apache.hadoop.metrics2.MetricsExecutor;
170170
import org.junit.After;
171171
import org.junit.Assert;
@@ -401,6 +401,7 @@ public void testMemstoreSizeAccountingWithFailedPostBatchMutate() throws IOExcep
401401
String testName = "testMemstoreSizeAccountingWithFailedPostBatchMutate";
402402
FileSystem fs = FileSystem.get(CONF);
403403
Path rootDir = new Path(dir + testName);
404+
ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null);
404405
FSHLog hLog = new FSHLog(fs, rootDir, testName, CONF);
405406
hLog.init();
406407
region = initHRegion(tableName, null, null, false, Durability.SYNC_WAL, hLog,
@@ -2427,7 +2428,16 @@ public Void answer(InvocationOnMock invocation) throws Throwable {
24272428
return null;
24282429
}
24292430
}).when(mockedCPHost).preBatchMutate(Mockito.isA(MiniBatchOperationInProgress.class));
2431+
ColumnFamilyDescriptorBuilder builder = ColumnFamilyDescriptorBuilder.
2432+
newBuilder(COLUMN_FAMILY_BYTES);
2433+
ScanInfo info = new ScanInfo(CONF, builder.build(), Long.MAX_VALUE,
2434+
Long.MAX_VALUE, region.getCellComparator());
2435+
Mockito.when(mockedCPHost.preFlushScannerOpen(Mockito.any(HStore.class),
2436+
Mockito.any())).thenReturn(info);
2437+
Mockito.when(mockedCPHost.preFlush(Mockito.any(), Mockito.any(StoreScanner.class),
2438+
Mockito.any())).thenAnswer(i -> i.getArgument(1));
24302439
region.setCoprocessorHost(mockedCPHost);
2440+
24312441
region.put(originalPut);
24322442
region.setCoprocessorHost(normalCPHost);
24332443
final long finalSize = region.getDataInMemoryWithoutWAL();

0 commit comments

Comments
 (0)