View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.regionserver;
19  
20  import static org.apache.hadoop.hbase.HConstants.REPLICATION_CLUSTER_ID;
21  import static org.apache.hadoop.hbase.HConstants.REPLICATION_CONF_DIR;
22  import static org.junit.Assert.assertEquals;
23  import static org.junit.Assert.assertTrue;
24  import java.io.File;
25  import java.io.FileOutputStream;
26  import java.io.IOException;
27  import java.util.List;
28  import java.util.concurrent.CountDownLatch;
29  import java.util.concurrent.TimeUnit;
30  import java.util.concurrent.atomic.AtomicInteger;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.fs.FSDataOutputStream;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.hbase.HBaseConfiguration;
35  import org.apache.hadoop.hbase.HBaseTestingUtility;
36  import org.apache.hadoop.hbase.HColumnDescriptor;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.HTableDescriptor;
39  import org.apache.hadoop.hbase.KeyValue;
40  import org.apache.hadoop.hbase.client.Admin;
41  import org.apache.hadoop.hbase.client.Connection;
42  import org.apache.hadoop.hbase.client.ConnectionFactory;
43  import org.apache.hadoop.hbase.client.Get;
44  import org.apache.hadoop.hbase.client.Result;
45  import org.apache.hadoop.hbase.client.Table;
46  import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
47  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
48  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
49  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
50  import org.apache.hadoop.hbase.io.hfile.HFile;
51  import org.apache.hadoop.hbase.io.hfile.HFileContext;
52  import org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles;
53  import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
54  import org.apache.hadoop.hbase.replication.TestReplicationBase;
55  import org.apache.hadoop.hbase.testclassification.MediumTests;
56  import org.apache.hadoop.hbase.testclassification.ReplicationTests;
57  import org.apache.hadoop.hbase.util.Bytes;
58  import org.apache.hadoop.hbase.util.Pair;
59  import org.apache.hadoop.hdfs.MiniDFSCluster;
60  import org.junit.After;
61  import org.junit.Before;
62  import org.junit.BeforeClass;
63  import org.junit.ClassRule;
64  import org.junit.Rule;
65  import org.junit.Test;
66  import org.junit.experimental.categories.Category;
67  import org.junit.rules.TemporaryFolder;
68  import org.junit.rules.TestName;
69  import org.slf4j.Logger;
70  import org.slf4j.LoggerFactory;
71  
72  /**
73   * Integration test for bulk load replication. Defines three clusters, with the following
74   * replication topology: "1 <-> 2 <-> 3" (active-active between 1 and 2, and active-active between
75   * 2 and 3).
76   *
77   * For each of defined test clusters, it performs a bulk load, asserting values on bulk loaded file
78   * gets replicated to other two peers. Since we are doing 3 bulk loads, with the given replication
79   * topology all these bulk loads should get replicated only once on each peer. To assert this,
80   * this test defines a preBulkLoad coprocessor and adds it to all test table regions, on each of the
81   * clusters. This CP counts the amount of times bulk load actually gets invoked, certifying
82   * we are not entering the infinite loop condition addressed by HBASE-22380.
83   */
84  @Category({ ReplicationTests.class, MediumTests.class})
85  public class TestBulkLoadReplication extends TestReplicationBase {
86  
87    protected static final Logger LOG =
88      LoggerFactory.getLogger(TestBulkLoadReplication.class);
89  
90    private static final String PEER1_CLUSTER_ID = "peer1";
91    private static final String PEER4_CLUSTER_ID = "peer4";
92    private static final String PEER3_CLUSTER_ID = "peer3";
93  
94    private static final String PEER_ID1 = "1";
95    private static final String PEER_ID3 = "3";
96    private static final String PEER_ID4 = "4";
97  
98    private static final AtomicInteger BULK_LOADS_COUNT = new AtomicInteger(0);
99    private static CountDownLatch BULK_LOAD_LATCH;
100 
101   private static HBaseTestingUtility utility3;
102   private static HBaseTestingUtility utility4;
103   private static Configuration conf3;
104   private static Configuration conf4;
105 //  private static Table htable3;
106 //  private static Table htable4;
107 
108   @Rule
109   public TestName name = new TestName();
110 
111   @ClassRule
112   public static TemporaryFolder testFolder = new TemporaryFolder();
113 
114   @BeforeClass
115   public static void setUpBeforeClass() throws Exception {
116     setupBulkLoadConfigsForCluster(conf1, PEER1_CLUSTER_ID);
117     conf3 = HBaseConfiguration.create(conf1);
118     setupBulkLoadConfigsForCluster(conf3, PEER3_CLUSTER_ID);
119     conf3.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/3");
120     utility3 = new HBaseTestingUtility(conf3);
121     conf4 = HBaseConfiguration.create(conf1);
122     setupBulkLoadConfigsForCluster(conf4, PEER4_CLUSTER_ID);
123     conf4.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/4");
124     utility4 = new HBaseTestingUtility(conf4);
125     TestReplicationBase.setUpBeforeClass();
126     startCluster(utility3, conf3);
127     startCluster(utility4, conf4);
128   }
129 
130   private static void startCluster(HBaseTestingUtility util, Configuration configuration)
131       throws Exception {
132     LOG.info("Setup Zk to same one from utility1 and utility4");
133     util.setZkCluster(utility1.getZkCluster());
134     util.startMiniCluster(2);
135 
136     HTableDescriptor tableDesc = new HTableDescriptor(tableName);
137     HColumnDescriptor columnDesc = new HColumnDescriptor(famName);
138     columnDesc.setScope(1);
139     tableDesc.addFamily(columnDesc);
140 
141     Connection connection = ConnectionFactory.createConnection(configuration);
142     try (Admin admin = connection.getAdmin()) {
143       admin.createTable(tableDesc, HBaseTestingUtility.KEYS_FOR_HBA_CREATE_TABLE);
144     }
145     util.waitUntilAllRegionsAssigned(tableName);
146   }
147 
148   @Before
149   public void setUpBase() throws Exception {
150     ReplicationPeerConfig peer1Config = getPeerConfigForCluster(utility1);
151     ReplicationPeerConfig peer4Config = getPeerConfigForCluster(utility4);
152     ReplicationPeerConfig peer3Config = getPeerConfigForCluster(utility3);
153     //adds cluster4 as a remote peer on cluster1
154     getReplicationAdmin(utility1.getConfiguration()).addPeer(PEER_ID4, peer4Config, null);
155     //adds cluster1 as a remote peer on cluster4
156     ReplicationAdmin admin4 = getReplicationAdmin(utility4.getConfiguration());
157     admin4.addPeer(PEER_ID1, peer1Config, null);
158     //adds cluster3 as a remote peer on cluster4
159     admin4.addPeer(PEER_ID3, peer3Config, null);
160     //adds cluster4 as a remote peer on cluster3
161     getReplicationAdmin(utility3.getConfiguration()).addPeer(PEER_ID4, peer4Config, null);
162     setupCoprocessor(utility1);
163     setupCoprocessor(utility4);
164     setupCoprocessor(utility3);
165   }
166 
167   private ReplicationAdmin getReplicationAdmin(Configuration configuration) throws IOException {
168     return new ReplicationAdmin(configuration);
169   }
170 
171   private ReplicationPeerConfig getPeerConfigForCluster(HBaseTestingUtility util) {
172     ReplicationPeerConfig config =  new ReplicationPeerConfig();
173     config.setClusterKey(util.getClusterKey());
174     return config;
175   }
176 
177   private void setupCoprocessor(HBaseTestingUtility cluster) throws IOException {
178     for(HRegion region : cluster.getHBaseCluster().getRegions(tableName)){
179       region.getCoprocessorHost().load(TestBulkLoadReplication.BulkReplicationTestObserver.class,
180         0, cluster.getConfiguration());
181     }
182   }
183 
184   @After
185   public void tearDownBase() throws Exception {
186     getReplicationAdmin(utility4.getConfiguration()).removePeer(PEER_ID1);
187     getReplicationAdmin(utility4.getConfiguration()).removePeer(PEER_ID3);
188     getReplicationAdmin(utility3.getConfiguration()).removePeer(PEER_ID4);
189   }
190 
191   private static void setupBulkLoadConfigsForCluster(Configuration config,
192     String clusterReplicationId) throws Exception {
193     config.setBoolean(HConstants.REPLICATION_BULKLOAD_ENABLE_KEY, true);
194     config.set(REPLICATION_CLUSTER_ID, clusterReplicationId);
195     File sourceConfigFolder = testFolder.newFolder(clusterReplicationId);
196     File sourceConfigFile = new File(sourceConfigFolder.getAbsolutePath()
197       + "/hbase-site.xml");
198     config.writeXml(new FileOutputStream(sourceConfigFile));
199     config.set(REPLICATION_CONF_DIR, testFolder.getRoot().getAbsolutePath());
200   }
201 
202   @Test
203   public void testBulkLoadReplicationActiveActive() throws Exception {
204     Table peer1TestTable = utility1.getConnection().getTable(TestReplicationBase.tableName);
205     Table peer4TestTable = utility4.getConnection().getTable(TestReplicationBase.tableName);
206     Table peer3TestTable = utility3.getConnection().getTable(TestReplicationBase.tableName);
207     byte[] row = Bytes.toBytes("001");
208     byte[] value = Bytes.toBytes("v1");
209     assertBulkLoadConditions(row, value, utility1, peer1TestTable, peer4TestTable, peer3TestTable);
210     row = Bytes.toBytes("002");
211     value = Bytes.toBytes("v2");
212     assertBulkLoadConditions(row, value, utility4, peer4TestTable, peer1TestTable, peer3TestTable);
213     row = Bytes.toBytes("003");
214     value = Bytes.toBytes("v3");
215     assertBulkLoadConditions(row, value, utility3, peer3TestTable, peer4TestTable, peer1TestTable);
216     //Additional wait to make sure no extra bulk load happens
217     Thread.sleep(400);
218     //We have 3 bulk load events (1 initiated on each cluster).
219     //Each event gets 3 counts (the originator cluster, plus the two peers),
220     //so BULK_LOADS_COUNT expected value is 3 * 3 = 9.
221     assertEquals(9, BULK_LOADS_COUNT.get());
222   }
223 
224   private void assertBulkLoadConditions(byte[] row, byte[] value,
225       HBaseTestingUtility utility, Table...tables) throws Exception {
226     BULK_LOAD_LATCH = new CountDownLatch(3);
227     bulkLoadOnCluster(row, value, utility);
228     assertTrue(BULK_LOAD_LATCH.await(1, TimeUnit.MINUTES));
229     assertTableHasValue(tables[0], row, value);
230     assertTableHasValue(tables[1], row, value);
231     assertTableHasValue(tables[2], row, value);
232   }
233 
234   private void bulkLoadOnCluster(byte[] row, byte[] value,
235       HBaseTestingUtility cluster) throws Exception {
236     String bulkLoadFile = createHFileForFamilies(row, value, cluster.getConfiguration());
237     copyToHdfs(bulkLoadFile, cluster.getDFSCluster());
238     LoadIncrementalHFiles bulkLoadHFilesTool =
239       new LoadIncrementalHFiles(cluster.getConfiguration());
240     bulkLoadHFilesTool.run(new String[]{"/bulk_dir/region1/", tableName.getNameAsString()});
241   }
242 
243   private void copyToHdfs(String bulkLoadFilePath, MiniDFSCluster cluster) throws Exception {
244     Path bulkLoadDir = new Path("/bulk_dir/region1/f");
245     cluster.getFileSystem().mkdirs(bulkLoadDir);
246     cluster.getFileSystem().copyFromLocalFile(new Path(bulkLoadFilePath), bulkLoadDir);
247   }
248 
249   private void assertTableHasValue(Table table, byte[] row, byte[] value) throws Exception {
250     Get get = new Get(row);
251     Result result = table.get(get);
252     assertTrue(result.advance());
253     assertEquals(Bytes.toString(value), Bytes.toString(result.value()));
254   }
255 
256   private String createHFileForFamilies(byte[] row, byte[] value,
257       Configuration clusterConfig) throws IOException {
258     final KeyValue kv = new KeyValue(row, famName, Bytes.toBytes("1"), System.currentTimeMillis(),
259       KeyValue.Type.Put, value);
260     final HFile.WriterFactory hFileFactory = HFile.getWriterFactoryNoCache(clusterConfig);
261     // TODO We need a way to do this without creating files
262     final File hFileLocation = testFolder.newFile();
263     final FSDataOutputStream out =
264       new FSDataOutputStream(new FileOutputStream(hFileLocation), null);
265     try {
266       hFileFactory.withOutputStream(out);
267       hFileFactory.withFileContext(new HFileContext());
268       HFile.Writer writer = hFileFactory.create();
269       try {
270         writer.append(kv);
271       } finally {
272         writer.close();
273       }
274     } finally {
275       out.close();
276     }
277     return hFileLocation.getAbsoluteFile().getAbsolutePath();
278   }
279 
280   public static class BulkReplicationTestObserver extends BaseRegionObserver {
281 
282     @Override
283     public void preBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx,
284       List<Pair<byte[], String>> familyPaths) throws IOException {
285         BULK_LOADS_COUNT.incrementAndGet();
286     }
287 
288     @Override
289     public boolean postBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx,
290         List<Pair<byte[], String>> familyPaths, boolean hasLoaded) throws IOException {
291       if(hasLoaded) {
292         BULK_LOAD_LATCH.countDown();
293       }
294       return true;
295     }
296 
297   }
298 }