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;
019
020import static org.junit.Assert.assertArrayEquals;
021import static org.junit.Assert.assertEquals;
022import static org.junit.Assert.fail;
023
024import java.io.IOException;
025import java.util.ArrayList;
026import java.util.List;
027import java.util.Optional;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.hbase.ArrayBackedTag;
030import org.apache.hadoop.hbase.Cell;
031import org.apache.hadoop.hbase.CellUtil;
032import org.apache.hadoop.hbase.HBaseClassTestRule;
033import org.apache.hadoop.hbase.HBaseConfiguration;
034import org.apache.hadoop.hbase.HBaseTestingUtility;
035import org.apache.hadoop.hbase.HColumnDescriptor;
036import org.apache.hadoop.hbase.HConstants;
037import org.apache.hadoop.hbase.HTableDescriptor;
038import org.apache.hadoop.hbase.KeyValue;
039import org.apache.hadoop.hbase.KeyValueUtil;
040import org.apache.hadoop.hbase.PrivateCellUtil;
041import org.apache.hadoop.hbase.TableName;
042import org.apache.hadoop.hbase.Tag;
043import org.apache.hadoop.hbase.client.Admin;
044import org.apache.hadoop.hbase.client.Connection;
045import org.apache.hadoop.hbase.client.ConnectionFactory;
046import org.apache.hadoop.hbase.client.Durability;
047import org.apache.hadoop.hbase.client.Get;
048import org.apache.hadoop.hbase.client.Put;
049import org.apache.hadoop.hbase.client.Result;
050import org.apache.hadoop.hbase.client.Table;
051import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
052import org.apache.hadoop.hbase.codec.KeyValueCodecWithTags;
053import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
054import org.apache.hadoop.hbase.coprocessor.ObserverContext;
055import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
056import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
057import org.apache.hadoop.hbase.coprocessor.RegionObserver;
058import org.apache.hadoop.hbase.testclassification.MediumTests;
059import org.apache.hadoop.hbase.testclassification.ReplicationTests;
060import org.apache.hadoop.hbase.util.Bytes;
061import org.apache.hadoop.hbase.wal.WALEdit;
062import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
063import org.junit.AfterClass;
064import org.junit.BeforeClass;
065import org.junit.ClassRule;
066import org.junit.Test;
067import org.junit.experimental.categories.Category;
068import org.slf4j.Logger;
069import org.slf4j.LoggerFactory;
070
071@Category({ ReplicationTests.class, MediumTests.class })
072public class TestReplicationWithTags {
073
074  @ClassRule
075  public static final HBaseClassTestRule CLASS_RULE =
076    HBaseClassTestRule.forClass(TestReplicationWithTags.class);
077
078  private static final Logger LOG = LoggerFactory.getLogger(TestReplicationWithTags.class);
079  private static final byte TAG_TYPE = 1;
080
081  private static Configuration conf1 = HBaseConfiguration.create();
082  private static Configuration conf2;
083
084  private static ReplicationAdmin replicationAdmin;
085
086  private static Connection connection1;
087  private static Connection connection2;
088
089  private static Table htable1;
090  private static Table htable2;
091
092  private static HBaseTestingUtility utility1;
093  private static HBaseTestingUtility utility2;
094  private static final long SLEEP_TIME = 500;
095  private static final int NB_RETRIES = 10;
096
097  private static final TableName TABLE_NAME = TableName.valueOf("TestReplicationWithTags");
098  private static final byte[] FAMILY = Bytes.toBytes("f");
099  private static final byte[] ROW = Bytes.toBytes("row");
100
101  @BeforeClass
102  public static void setUpBeforeClass() throws Exception {
103    conf1.setInt("hfile.format.version", 3);
104    conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1");
105    conf1.setInt("replication.source.size.capacity", 10240);
106    conf1.setLong("replication.source.sleepforretries", 100);
107    conf1.setInt("hbase.regionserver.maxlogs", 10);
108    conf1.setLong("hbase.master.logcleaner.ttl", 10);
109    conf1.setInt("zookeeper.recovery.retry", 1);
110    conf1.setInt("zookeeper.recovery.retry.intervalmill", 10);
111    conf1.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100);
112    conf1.setInt("replication.stats.thread.period.seconds", 5);
113    conf1.setBoolean("hbase.tests.use.shortcircuit.reads", false);
114    conf1.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName());
115    conf1.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
116      TestCoprocessorForTagsAtSource.class.getName());
117
118    utility1 = new HBaseTestingUtility(conf1);
119    utility1.startMiniZKCluster();
120    MiniZooKeeperCluster miniZK = utility1.getZkCluster();
121    // Have to reget conf1 in case zk cluster location different
122    // than default
123    conf1 = utility1.getConfiguration();
124    LOG.info("Setup first Zk");
125
126    // Base conf2 on conf1 so it gets the right zk cluster.
127    conf2 = HBaseConfiguration.create(conf1);
128    conf2.setInt("hfile.format.version", 3);
129    conf2.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/2");
130    conf2.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 6);
131    conf2.setBoolean("hbase.tests.use.shortcircuit.reads", false);
132    conf2.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName());
133    conf2.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
134      TestCoprocessorForTagsAtSink.class.getName());
135
136    utility2 = new HBaseTestingUtility(conf2);
137    utility2.setZkCluster(miniZK);
138
139    LOG.info("Setup second Zk");
140    utility1.startMiniCluster(2);
141    utility2.startMiniCluster(2);
142
143    replicationAdmin = new ReplicationAdmin(conf1);
144    ReplicationPeerConfig rpc = new ReplicationPeerConfig();
145    rpc.setClusterKey(utility2.getClusterKey());
146    replicationAdmin.addPeer("2", rpc, null);
147
148    HTableDescriptor table = new HTableDescriptor(TABLE_NAME);
149    HColumnDescriptor fam = new HColumnDescriptor(FAMILY);
150    fam.setMaxVersions(3);
151    fam.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
152    table.addFamily(fam);
153    try (Connection conn = ConnectionFactory.createConnection(conf1);
154      Admin admin = conn.getAdmin()) {
155      admin.createTable(table, HBaseTestingUtility.KEYS_FOR_HBA_CREATE_TABLE);
156    }
157    try (Connection conn = ConnectionFactory.createConnection(conf2);
158      Admin admin = conn.getAdmin()) {
159      admin.createTable(table, HBaseTestingUtility.KEYS_FOR_HBA_CREATE_TABLE);
160    }
161    htable1 = utility1.getConnection().getTable(TABLE_NAME);
162    htable2 = utility2.getConnection().getTable(TABLE_NAME);
163  }
164
165  @AfterClass
166  public static void tearDownAfterClass() throws Exception {
167    utility2.shutdownMiniCluster();
168    utility1.shutdownMiniCluster();
169  }
170
171  @Test
172  public void testReplicationWithCellTags() throws Exception {
173    LOG.info("testSimplePutDelete");
174    Put put = new Put(ROW);
175    put.setAttribute("visibility", Bytes.toBytes("myTag3"));
176    put.addColumn(FAMILY, ROW, ROW);
177
178    htable1 = utility1.getConnection().getTable(TABLE_NAME);
179    htable1.put(put);
180
181    Get get = new Get(ROW);
182    try {
183      for (int i = 0; i < NB_RETRIES; i++) {
184        if (i == NB_RETRIES - 1) {
185          fail("Waited too much time for put replication");
186        }
187        Result res = htable2.get(get);
188        if (res.isEmpty()) {
189          LOG.info("Row not available");
190          Thread.sleep(SLEEP_TIME);
191        } else {
192          assertArrayEquals(ROW, res.value());
193          assertEquals(1, TestCoprocessorForTagsAtSink.TAGS.size());
194          Tag tag = TestCoprocessorForTagsAtSink.TAGS.get(0);
195          assertEquals(TAG_TYPE, tag.getType());
196          break;
197        }
198      }
199    } finally {
200      TestCoprocessorForTagsAtSink.TAGS = null;
201    }
202  }
203
204  public static class TestCoprocessorForTagsAtSource implements RegionCoprocessor, RegionObserver {
205    @Override
206    public Optional<RegionObserver> getRegionObserver() {
207      return Optional.of(this);
208    }
209
210    @Override
211    public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e, final Put put,
212      final WALEdit edit, final Durability durability) throws IOException {
213      byte[] attribute = put.getAttribute("visibility");
214      byte[] cf = null;
215      List<Cell> updatedCells = new ArrayList<>();
216      if (attribute != null) {
217        for (List<? extends Cell> edits : put.getFamilyCellMap().values()) {
218          for (Cell cell : edits) {
219            KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
220            if (cf == null) {
221              cf = CellUtil.cloneFamily(kv);
222            }
223            Tag tag = new ArrayBackedTag(TAG_TYPE, attribute);
224            List<Tag> tagList = new ArrayList<>(1);
225            tagList.add(tag);
226
227            KeyValue newKV =
228              new KeyValue(CellUtil.cloneRow(kv), 0, kv.getRowLength(), CellUtil.cloneFamily(kv), 0,
229                kv.getFamilyLength(), CellUtil.cloneQualifier(kv), 0, kv.getQualifierLength(),
230                kv.getTimestamp(), KeyValue.Type.codeToType(kv.getTypeByte()),
231                CellUtil.cloneValue(kv), 0, kv.getValueLength(), tagList);
232            ((List<Cell>) updatedCells).add(newKV);
233          }
234        }
235        put.getFamilyCellMap().remove(cf);
236        // Update the family map
237        put.getFamilyCellMap().put(cf, updatedCells);
238      }
239    }
240  }
241
242  public static class TestCoprocessorForTagsAtSink implements RegionCoprocessor, RegionObserver {
243    private static List<Tag> TAGS = null;
244
245    @Override
246    public Optional<RegionObserver> getRegionObserver() {
247      return Optional.of(this);
248    }
249
250    @Override
251    public void postGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get,
252      List<Cell> results) throws IOException {
253      if (results.size() > 0) {
254        // Check tag presence in the 1st cell in 1st Result
255        if (!results.isEmpty()) {
256          Cell cell = results.get(0);
257          TAGS = PrivateCellUtil.getTags(cell);
258        }
259      }
260    }
261  }
262}