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.coprocessor;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNotNull;
022
023import java.io.IOException;
024import java.util.Arrays;
025import java.util.List;
026import java.util.Optional;
027import org.apache.hadoop.conf.Configuration;
028import org.apache.hadoop.hbase.Cell;
029import org.apache.hadoop.hbase.HBaseClassTestRule;
030import org.apache.hadoop.hbase.HBaseConfiguration;
031import org.apache.hadoop.hbase.HBaseTestingUtil;
032import org.apache.hadoop.hbase.TableName;
033import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
034import org.apache.hadoop.hbase.client.Delete;
035import org.apache.hadoop.hbase.client.Mutation;
036import org.apache.hadoop.hbase.client.Put;
037import org.apache.hadoop.hbase.client.RegionInfo;
038import org.apache.hadoop.hbase.client.Result;
039import org.apache.hadoop.hbase.client.ResultScanner;
040import org.apache.hadoop.hbase.client.Scan;
041import org.apache.hadoop.hbase.client.Table;
042import org.apache.hadoop.hbase.client.TableDescriptor;
043import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
044import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress;
045import org.apache.hadoop.hbase.testclassification.MediumTests;
046import org.apache.hadoop.hbase.util.Bytes;
047import org.apache.hadoop.hbase.wal.WALEdit;
048import org.apache.hadoop.hbase.wal.WALKey;
049import org.junit.AfterClass;
050import org.junit.Before;
051import org.junit.BeforeClass;
052import org.junit.ClassRule;
053import org.junit.Rule;
054import org.junit.Test;
055import org.junit.experimental.categories.Category;
056import org.junit.rules.TestName;
057import org.slf4j.Logger;
058import org.slf4j.LoggerFactory;
059
060import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
061
062@Category(MediumTests.class)
063public class TestRegionObserverForAddingMutationsFromCoprocessors {
064
065  @ClassRule
066  public static final HBaseClassTestRule CLASS_RULE =
067      HBaseClassTestRule.forClass(TestRegionObserverForAddingMutationsFromCoprocessors.class);
068
069  private static final Logger LOG
070    = LoggerFactory.getLogger(TestRegionObserverForAddingMutationsFromCoprocessors.class);
071
072  private static HBaseTestingUtil util;
073  private static final byte[] dummy = Bytes.toBytes("dummy");
074  private static final byte[] row1 = Bytes.toBytes("r1");
075  private static final byte[] row2 = Bytes.toBytes("r2");
076  private static final byte[] row3 = Bytes.toBytes("r3");
077  private static final byte[] test = Bytes.toBytes("test");
078
079  @Rule
080  public TestName name = new TestName();
081  private TableName tableName;
082
083  @BeforeClass
084  public static void setUpBeforeClass() throws Exception {
085    Configuration conf = HBaseConfiguration.create();
086    conf.set(CoprocessorHost.WAL_COPROCESSOR_CONF_KEY, TestWALObserver.class.getName());
087    util = new HBaseTestingUtil(conf);
088    util.startMiniCluster();
089  }
090
091  @AfterClass
092  public static void tearDownAfterClass() throws Exception {
093    util.shutdownMiniCluster();
094  }
095
096  @Before
097  public void setUp() throws Exception {
098    tableName = TableName.valueOf(name.getMethodName());
099  }
100
101  private void createTable(String coprocessor) throws IOException {
102    TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName)
103      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(dummy))
104      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(test)).setCoprocessor(coprocessor).build();
105    util.getAdmin().createTable(tableDescriptor);
106  }
107
108  /**
109   * Test various multiput operations.
110   */
111  @Test
112  public void testMulti() throws Exception {
113    createTable(TestMultiMutationCoprocessor.class.getName());
114
115    try (Table t = util.getConnection().getTable(tableName)) {
116      t.put(new Put(row1).addColumn(test, dummy, dummy));
117      assertRowCount(t, 3);
118    }
119  }
120
121  /**
122   * Tests that added mutations from coprocessors end up in the WAL.
123   */
124  @Test
125  public void testCPMutationsAreWrittenToWALEdit() throws Exception {
126    createTable(TestMultiMutationCoprocessor.class.getName());
127
128    try (Table t = util.getConnection().getTable(tableName)) {
129      t.put(new Put(row1).addColumn(test, dummy, dummy));
130      assertRowCount(t, 3);
131    }
132
133    assertNotNull(TestWALObserver.savedEdit);
134    assertEquals(4, TestWALObserver.savedEdit.getCells().size());
135  }
136
137  private static void assertRowCount(Table t, int expected) throws IOException {
138    try (ResultScanner scanner = t.getScanner(new Scan())) {
139      int i = 0;
140      for (Result r: scanner) {
141        LOG.info(r.toString());
142        i++;
143      }
144      assertEquals(expected, i);
145    }
146  }
147
148  @Test
149  public void testDeleteCell() throws Exception {
150    createTable(TestDeleteCellCoprocessor.class.getName());
151
152    try (Table t = util.getConnection().getTable(tableName)) {
153      t.put(Lists.newArrayList(
154        new Put(row1).addColumn(test, dummy, dummy),
155        new Put(row2).addColumn(test, dummy, dummy),
156        new Put(row3).addColumn(test, dummy, dummy)
157          ));
158
159      assertRowCount(t, 3);
160
161      t.delete(new Delete(test).addColumn(test, dummy)); // delete non-existing row
162      assertRowCount(t, 1);
163    }
164  }
165
166  @Test
167  public void testDeleteFamily() throws Exception {
168    createTable(TestDeleteFamilyCoprocessor.class.getName());
169
170    try (Table t = util.getConnection().getTable(tableName)) {
171      t.put(Lists.newArrayList(
172        new Put(row1).addColumn(test, dummy, dummy),
173        new Put(row2).addColumn(test, dummy, dummy),
174        new Put(row3).addColumn(test, dummy, dummy)
175          ));
176
177      assertRowCount(t, 3);
178
179      t.delete(new Delete(test).addFamily(test)); // delete non-existing row
180      assertRowCount(t, 1);
181    }
182  }
183
184  @Test
185  public void testDeleteRow() throws Exception {
186    createTable(TestDeleteRowCoprocessor.class.getName());
187
188    try (Table t = util.getConnection().getTable(tableName)) {
189      t.put(Lists.newArrayList(
190        new Put(row1).addColumn(test, dummy, dummy),
191        new Put(row2).addColumn(test, dummy, dummy),
192        new Put(row3).addColumn(test, dummy, dummy)
193          ));
194
195      assertRowCount(t, 3);
196
197      t.delete(new Delete(test).addColumn(test, dummy)); // delete non-existing row
198      assertRowCount(t, 1);
199    }
200  }
201
202  @Test
203  public void testPutWithTTL() throws Exception {
204    createTable(TestPutWithTTLCoprocessor.class.getName());
205
206    try (Table t = util.getConnection().getTable(tableName)) {
207      t.put(new Put(row1).addColumn(test, dummy, dummy).setTTL(3000));
208      assertRowCount(t, 2);
209      // wait long enough for the TTL to expire
210      Thread.sleep(5000);
211      assertRowCount(t, 0);
212    }
213  }
214
215  public static class TestPutWithTTLCoprocessor implements RegionCoprocessor, RegionObserver {
216    @Override
217    public Optional<RegionObserver> getRegionObserver() {
218      return Optional.of(this);
219    }
220
221    @Override
222    public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
223        MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
224      Mutation mut = miniBatchOp.getOperation(0);
225      List<Cell> cells = mut.getFamilyCellMap().get(test);
226      Put[] puts = new Put[] {
227          new Put(Bytes.toBytes("cpPut")).addColumn(test, dummy, cells.get(0).getTimestamp(),
228            Bytes.toBytes("cpdummy")).setTTL(mut.getTTL())
229          };
230      LOG.info("Putting:" + Arrays.toString(puts));
231      miniBatchOp.addOperationsFromCP(0, puts);
232    }
233  }
234
235  public static class TestMultiMutationCoprocessor implements RegionCoprocessor, RegionObserver {
236    @Override
237    public Optional<RegionObserver> getRegionObserver() {
238      return Optional.of(this);
239    }
240
241    @Override
242    public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
243        MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
244      Mutation mut = miniBatchOp.getOperation(0);
245      List<Cell> cells = mut.getFamilyCellMap().get(test);
246      Put[] puts = new Put[] {
247          new Put(row1).addColumn(test, dummy, cells.get(0).getTimestamp(),
248            Bytes.toBytes("cpdummy")),
249          new Put(row2).addColumn(test, dummy, cells.get(0).getTimestamp(), dummy),
250          new Put(row3).addColumn(test, dummy, cells.get(0).getTimestamp(), dummy),
251      };
252      LOG.info("Putting:" + Arrays.toString(puts));
253      miniBatchOp.addOperationsFromCP(0, puts);
254    }
255  }
256
257  public static class TestDeleteCellCoprocessor implements RegionCoprocessor, RegionObserver {
258    @Override
259    public Optional<RegionObserver> getRegionObserver() {
260      return Optional.of(this);
261    }
262
263    @Override
264    public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
265        MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
266      Mutation mut = miniBatchOp.getOperation(0);
267
268      if (mut instanceof Delete) {
269        List<Cell> cells = mut.getFamilyCellMap().get(test);
270        Delete[] deletes = new Delete[] {
271            // delete only 2 rows
272            new Delete(row1).addColumns(test, dummy, cells.get(0).getTimestamp()),
273            new Delete(row2).addColumns(test, dummy, cells.get(0).getTimestamp()),
274        };
275        LOG.info("Deleting:" + Arrays.toString(deletes));
276        miniBatchOp.addOperationsFromCP(0, deletes);
277      }
278    }
279  }
280
281  public static class TestDeleteFamilyCoprocessor implements RegionCoprocessor, RegionObserver {
282    @Override
283    public Optional<RegionObserver> getRegionObserver() {
284      return Optional.of(this);
285    }
286
287    @Override
288    public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
289        MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
290      Mutation mut = miniBatchOp.getOperation(0);
291
292      if (mut instanceof Delete) {
293        List<Cell> cells = mut.getFamilyCellMap().get(test);
294        Delete[] deletes = new Delete[] {
295            // delete only 2 rows
296            new Delete(row1).addFamily(test, cells.get(0).getTimestamp()),
297            new Delete(row2).addFamily(test, cells.get(0).getTimestamp()),
298        };
299        LOG.info("Deleting:" + Arrays.toString(deletes));
300        miniBatchOp.addOperationsFromCP(0, deletes);
301      }
302    }
303  }
304
305  public static class TestDeleteRowCoprocessor implements RegionCoprocessor, RegionObserver {
306    @Override
307    public Optional<RegionObserver> getRegionObserver() {
308      return Optional.of(this);
309    }
310
311    @Override
312    public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
313        MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
314      Mutation mut = miniBatchOp.getOperation(0);
315
316      if (mut instanceof Delete) {
317        List<Cell> cells = mut.getFamilyCellMap().get(test);
318        Delete[] deletes = new Delete[] {
319            // delete only 2 rows
320            new Delete(row1, cells.get(0).getTimestamp()),
321            new Delete(row2, cells.get(0).getTimestamp()),
322        };
323        LOG.info("Deleting:" + Arrays.toString(deletes));
324        miniBatchOp.addOperationsFromCP(0, deletes);
325      }
326    }
327  }
328
329  public static class TestWALObserver implements WALCoprocessor, WALObserver {
330    static WALEdit savedEdit = null;
331
332    @Override
333    public Optional<WALObserver> getWALObserver() {
334      return Optional.of(this);
335    }
336
337    @Override
338    public void postWALWrite(ObserverContext<? extends WALCoprocessorEnvironment> ctx,
339                             RegionInfo info, WALKey logKey, WALEdit logEdit) throws IOException {
340      if (info.getTable().equals(TableName.valueOf("testCPMutationsAreWrittenToWALEdit"))) {
341        savedEdit = logEdit;
342      }
343    }
344  }
345}