001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.replication.regionserver;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertTrue;
022
023import java.io.IOException;
024import java.util.ArrayList;
025import java.util.List;
026import java.util.Map;
027import java.util.concurrent.CompletableFuture;
028import java.util.concurrent.ExecutorService;
029import java.util.concurrent.atomic.AtomicBoolean;
030import java.util.concurrent.atomic.AtomicInteger;
031import org.apache.hadoop.conf.Configuration;
032import org.apache.hadoop.hbase.Cell;
033import org.apache.hadoop.hbase.CellBuilder;
034import org.apache.hadoop.hbase.CellBuilderFactory;
035import org.apache.hadoop.hbase.CellBuilderType;
036import org.apache.hadoop.hbase.CellScanner;
037import org.apache.hadoop.hbase.HBaseClassTestRule;
038import org.apache.hadoop.hbase.HBaseConfiguration;
039import org.apache.hadoop.hbase.HConstants;
040import org.apache.hadoop.hbase.ServerName;
041import org.apache.hadoop.hbase.Stoppable;
042import org.apache.hadoop.hbase.TableName;
043import org.apache.hadoop.hbase.client.AdvancedScanResultConsumer;
044import org.apache.hadoop.hbase.client.AsyncAdminBuilder;
045import org.apache.hadoop.hbase.client.AsyncBufferedMutatorBuilder;
046import org.apache.hadoop.hbase.client.AsyncConnection;
047import org.apache.hadoop.hbase.client.AsyncTable;
048import org.apache.hadoop.hbase.client.AsyncTableBuilder;
049import org.apache.hadoop.hbase.client.AsyncTableRegionLocator;
050import org.apache.hadoop.hbase.client.Connection;
051import org.apache.hadoop.hbase.client.ConnectionFactory;
052import org.apache.hadoop.hbase.client.ConnectionRegistry;
053import org.apache.hadoop.hbase.client.DoNothingConnectionRegistry;
054import org.apache.hadoop.hbase.client.DummyAsyncTable;
055import org.apache.hadoop.hbase.client.Hbck;
056import org.apache.hadoop.hbase.client.Row;
057import org.apache.hadoop.hbase.client.ScanResultConsumer;
058import org.apache.hadoop.hbase.security.User;
059import org.apache.hadoop.hbase.testclassification.ReplicationTests;
060import org.apache.hadoop.hbase.testclassification.SmallTests;
061import org.apache.hadoop.hbase.util.Bytes;
062import org.junit.ClassRule;
063import org.junit.Rule;
064import org.junit.Test;
065import org.junit.experimental.categories.Category;
066import org.junit.rules.TestName;
067import org.slf4j.Logger;
068import org.slf4j.LoggerFactory;
069
070import org.apache.hbase.thirdparty.com.google.protobuf.ByteString;
071
072import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos;
073
074/**
075 * Simple test of sink-side wal entry filter facility.
076 */
077@Category({ ReplicationTests.class, SmallTests.class })
078public class TestWALEntrySinkFilter {
079
080  @ClassRule
081  public static final HBaseClassTestRule CLASS_RULE =
082    HBaseClassTestRule.forClass(TestWALEntrySinkFilter.class);
083
084  private static final Logger LOG = LoggerFactory.getLogger(TestReplicationSink.class);
085  @Rule
086  public TestName name = new TestName();
087  static final int BOUNDARY = 5;
088  static final AtomicInteger UNFILTERED = new AtomicInteger();
089  static final AtomicInteger FILTERED = new AtomicInteger();
090
091  /**
092   * Implemetentation of Stoppable to pass into ReplicationSink.
093   */
094  private static Stoppable STOPPABLE = new Stoppable() {
095    private final AtomicBoolean stop = new AtomicBoolean(false);
096
097    @Override
098    public boolean isStopped() {
099      return this.stop.get();
100    }
101
102    @Override
103    public void stop(String why) {
104      LOG.info("STOPPING BECAUSE: " + why);
105      this.stop.set(true);
106    }
107  };
108
109  /**
110   * Test filter. Filter will filter out any write time that is <= 5 (BOUNDARY). We count how many
111   * items we filter out and we count how many cells make it through for distribution way down below
112   * in the Table#batch implementation. Puts in place a custom DevNullConnection so we can insert
113   * our counting Table.
114   */
115  @Test
116  public void testWALEntryFilter() throws IOException {
117    Configuration conf = HBaseConfiguration.create();
118    // Make it so our filter is instantiated on construction of ReplicationSink.
119    conf.setClass(HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY,
120      DevNullConnectionRegistry.class, ConnectionRegistry.class);
121    conf.setClass(WALEntrySinkFilter.WAL_ENTRY_FILTER_KEY,
122      IfTimeIsGreaterThanBOUNDARYWALEntrySinkFilterImpl.class, WALEntrySinkFilter.class);
123    conf.setClass(ConnectionFactory.HBASE_CLIENT_ASYNC_CONNECTION_IMPL,
124      DevNullAsyncConnection.class, AsyncConnection.class);
125    ReplicationSink sink = new ReplicationSink(conf, null);
126    // Create some dumb walentries.
127    List<org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.WALEntry> entries =
128      new ArrayList<>();
129    AdminProtos.WALEntry.Builder entryBuilder = AdminProtos.WALEntry.newBuilder();
130    // Need a tablename.
131    ByteString tableName =
132      ByteString.copyFromUtf8(TableName.valueOf(this.name.getMethodName()).toString());
133    // Add WALEdit Cells to Cells List. The way edits arrive at the sink is with protos
134    // describing the edit with all Cells from all edits aggregated in a single CellScanner.
135    final List<Cell> cells = new ArrayList<>();
136    int count = BOUNDARY * 2;
137    for (int i = 0; i < count; i++) {
138      byte[] bytes = Bytes.toBytes(i);
139      // Create a wal entry. Everything is set to the current index as bytes or int/long.
140      entryBuilder.clear();
141      entryBuilder.setKey(entryBuilder.getKeyBuilder().setLogSequenceNumber(i)
142        .setEncodedRegionName(ByteString.copyFrom(bytes)).setWriteTime(i).setTableName(tableName)
143        .build());
144      // Lets have one Cell associated with each WALEdit.
145      entryBuilder.setAssociatedCellCount(1);
146      entries.add(entryBuilder.build());
147      // We need to add a Cell per WALEdit to the cells array.
148      CellBuilder cellBuilder = CellBuilderFactory.create(CellBuilderType.DEEP_COPY);
149      // Make cells whose row, family, cell, value, and ts are == 'i'.
150      Cell cell = cellBuilder.setRow(bytes).setFamily(bytes).setQualifier(bytes)
151        .setType(Cell.Type.Put).setTimestamp(i).setValue(bytes).build();
152      cells.add(cell);
153    }
154    // Now wrap our cells array in a CellScanner that we can pass in to replicateEntries. It has
155    // all Cells from all the WALEntries made above.
156    CellScanner cellScanner = new CellScanner() {
157      // Set to -1 because advance gets called before current.
158      int index = -1;
159
160      @Override
161      public Cell current() {
162        return cells.get(index);
163      }
164
165      @Override
166      public boolean advance() throws IOException {
167        index++;
168        return index < cells.size();
169      }
170    };
171    // Call our sink.
172    sink.replicateEntries(entries, cellScanner, null, null, null);
173    // Check what made it through and what was filtered.
174    assertTrue(FILTERED.get() > 0);
175    assertTrue(UNFILTERED.get() > 0);
176    assertEquals(count, FILTERED.get() + UNFILTERED.get());
177  }
178
179  /**
180   * Simple filter that will filter out any entry wholse writeTime is <= 5.
181   */
182  public static class IfTimeIsGreaterThanBOUNDARYWALEntrySinkFilterImpl
183    implements WALEntrySinkFilter {
184    public IfTimeIsGreaterThanBOUNDARYWALEntrySinkFilterImpl() {
185    }
186
187    @Override
188    public void init(Connection connection) {
189      // Do nothing.
190    }
191
192    @Override
193    public boolean filter(TableName table, long writeTime) {
194      boolean b = writeTime <= BOUNDARY;
195      if (b) {
196        FILTERED.incrementAndGet();
197      }
198      return b;
199    }
200  }
201
202  public static class DevNullConnectionRegistry extends DoNothingConnectionRegistry {
203
204    public DevNullConnectionRegistry(Configuration conf, User user) {
205      super(conf, user);
206    }
207
208    @Override
209    public CompletableFuture<String> getClusterId() {
210      return CompletableFuture.completedFuture("test");
211    }
212  }
213
214  /**
215   * A DevNull AsyncConnection whose only purpose is checking what edits made it through. See down
216   * in {@link AsyncTable#batchAll}.
217   */
218  public static class DevNullAsyncConnection implements AsyncConnection {
219
220    private final Configuration conf;
221
222    public DevNullAsyncConnection(Configuration conf, ConnectionRegistry registry, String clusterId,
223      User user, Map<String, byte[]> connectionAttributes) {
224      this.conf = conf;
225    }
226
227    @Override
228    public AsyncTableRegionLocator getRegionLocator(TableName tableName) {
229      return null;
230    }
231
232    @Override
233    public void clearRegionLocationCache() {
234    }
235
236    @Override
237    public AsyncTableBuilder<AdvancedScanResultConsumer> getTableBuilder(TableName tableName) {
238      return null;
239    }
240
241    @Override
242    public AsyncTableBuilder<ScanResultConsumer> getTableBuilder(TableName tableName,
243      ExecutorService pool) {
244      return null;
245    }
246
247    @Override
248    public AsyncAdminBuilder getAdminBuilder() {
249      return null;
250    }
251
252    @Override
253    public AsyncAdminBuilder getAdminBuilder(ExecutorService pool) {
254      return null;
255    }
256
257    @Override
258    public AsyncBufferedMutatorBuilder getBufferedMutatorBuilder(TableName tableName) {
259      return null;
260    }
261
262    @Override
263    public AsyncBufferedMutatorBuilder getBufferedMutatorBuilder(TableName tableName,
264      ExecutorService pool) {
265      return null;
266    }
267
268    @Override
269    public CompletableFuture<Hbck> getHbck() {
270      return null;
271    }
272
273    @Override
274    public Hbck getHbck(ServerName masterServer) throws IOException {
275      return null;
276    }
277
278    @Override
279    public boolean isClosed() {
280      return false;
281    }
282
283    @Override
284    public void close() throws IOException {
285    }
286
287    @Override
288    public AsyncTable<AdvancedScanResultConsumer> getTable(TableName tableName) {
289      return new DummyAsyncTable<AdvancedScanResultConsumer>() {
290
291        @Override
292        public <T> CompletableFuture<List<T>> batchAll(List<? extends Row> actions) {
293          List<T> list = new ArrayList<>(actions.size());
294          for (Row action : actions) {
295            // Row is the index of the loop above where we make WALEntry and Cells.
296            int row = Bytes.toInt(action.getRow());
297            assertTrue("" + row, row > BOUNDARY);
298            UNFILTERED.incrementAndGet();
299            list.add(null);
300          }
301          return CompletableFuture.completedFuture(list);
302        }
303      };
304    }
305
306    @Override
307    public Configuration getConfiguration() {
308      return conf;
309    }
310  }
311}