1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.replication.regionserver;
20
21 import java.io.IOException;
22 import java.io.InterruptedIOException;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.TreeMap;
30 import java.util.UUID;
31 import java.util.concurrent.atomic.AtomicLong;
32
33 import org.apache.commons.lang.StringUtils;
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.apache.hadoop.conf.Configuration;
37 import org.apache.hadoop.fs.Path;
38 import org.apache.hadoop.hbase.Cell;
39 import org.apache.hadoop.hbase.CellScanner;
40 import org.apache.hadoop.hbase.CellUtil;
41 import org.apache.hadoop.hbase.HBaseConfiguration;
42 import org.apache.hadoop.hbase.HConstants;
43 import org.apache.hadoop.hbase.Stoppable;
44 import org.apache.hadoop.hbase.TableName;
45 import org.apache.hadoop.hbase.classification.InterfaceAudience;
46 import org.apache.hadoop.hbase.client.Connection;
47 import org.apache.hadoop.hbase.client.ConnectionFactory;
48 import org.apache.hadoop.hbase.client.Delete;
49 import org.apache.hadoop.hbase.client.Mutation;
50 import org.apache.hadoop.hbase.client.Put;
51 import org.apache.hadoop.hbase.client.Row;
52 import org.apache.hadoop.hbase.client.Table;
53 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.WALEntry;
54 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
55 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.BulkLoadDescriptor;
56 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.StoreDescriptor;
57 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
58 import org.apache.hadoop.hbase.util.Bytes;
59 import org.apache.hadoop.hbase.util.Pair;
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76 @InterfaceAudience.Private
77 public class ReplicationSink {
78
79 private static final Log LOG = LogFactory.getLog(ReplicationSink.class);
80 private final Configuration conf;
81
82
83 private volatile Connection sharedHtableCon;
84 private final MetricsSink metrics;
85 private final AtomicLong totalReplicatedEdits = new AtomicLong();
86 private final Object sharedHtableConLock = new Object();
87
88 private long hfilesReplicated = 0;
89 private SourceFSConfigurationProvider provider;
90
91
92
93
94
95
96
97
98 public ReplicationSink(Configuration conf, Stoppable stopper)
99 throws IOException {
100 this.conf = HBaseConfiguration.create(conf);
101 decorateConf();
102 this.metrics = new MetricsSink();
103
104 String className =
105 conf.get("hbase.replication.source.fs.conf.provider",
106 DefaultSourceFSConfigurationProvider.class.getCanonicalName());
107 try {
108 @SuppressWarnings("rawtypes")
109 Class c = Class.forName(className);
110 this.provider = (SourceFSConfigurationProvider) c.newInstance();
111 } catch (Exception e) {
112 throw new IllegalArgumentException("Configured source fs configuration provider class "
113 + className + " throws error.", e);
114 }
115 }
116
117
118
119
120
121 private void decorateConf() {
122 this.conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
123 this.conf.getInt("replication.sink.client.retries.number", 4));
124 this.conf.setInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
125 this.conf.getInt("replication.sink.client.ops.timeout", 10000));
126 String replicationCodec = this.conf.get(HConstants.REPLICATION_CODEC_CONF_KEY);
127 if (StringUtils.isNotEmpty(replicationCodec)) {
128 this.conf.set(HConstants.RPC_CODEC_CONF_KEY, replicationCodec);
129 }
130 }
131
132
133
134
135
136
137
138
139
140
141
142
143
144 public void replicateEntries(List<WALEntry> entries, final CellScanner cells,
145 String replicationClusterId, String sourceBaseNamespaceDirPath,
146 String sourceHFileArchiveDirPath) throws IOException {
147 if (entries.isEmpty()) return;
148 if (cells == null) throw new NullPointerException("TODO: Add handling of null CellScanner");
149
150
151 try {
152 long totalReplicated = 0;
153
154
155 Map<TableName, Map<List<UUID>, List<Row>>> rowMap =
156 new TreeMap<TableName, Map<List<UUID>, List<Row>>>();
157
158 Map<List<String>, Map<String, List<Pair<byte[], List<String>>>>> bulkLoadsPerClusters = null;
159 for (WALEntry entry : entries) {
160 TableName table =
161 TableName.valueOf(entry.getKey().getTableName().toByteArray());
162 Cell previousCell = null;
163 Mutation m = null;
164 int count = entry.getAssociatedCellCount();
165 for (int i = 0; i < count; i++) {
166
167 if (!cells.advance()) {
168 throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
169 }
170 Cell cell = cells.current();
171
172 if (CellUtil.matchingQualifier(cell, WALEdit.BULK_LOAD)) {
173 BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cell);
174 if(bulkLoadsPerClusters == null) {
175 bulkLoadsPerClusters = new HashMap<>();
176 }
177
178
179 Map<String, List<Pair<byte[], List<String>>>> bulkLoadHFileMap =
180 bulkLoadsPerClusters.get(bld.getClusterIdsList());
181 if (bulkLoadHFileMap == null) {
182 bulkLoadHFileMap = new HashMap<>();
183 bulkLoadsPerClusters.put(bld.getClusterIdsList(), bulkLoadHFileMap);
184 }
185 buildBulkLoadHFileMap(bulkLoadHFileMap, table, bld);
186 } else {
187
188 if (isNewRowOrType(previousCell, cell)) {
189
190 m =
191 CellUtil.isDelete(cell) ? new Delete(cell.getRowArray(), cell.getRowOffset(),
192 cell.getRowLength()) : new Put(cell.getRowArray(), cell.getRowOffset(),
193 cell.getRowLength());
194 List<UUID> clusterIds = new ArrayList<UUID>();
195 for (HBaseProtos.UUID clusterId : entry.getKey().getClusterIdsList()) {
196 clusterIds.add(toUUID(clusterId));
197 }
198 m.setClusterIds(clusterIds);
199 addToHashMultiMap(rowMap, table, clusterIds, m);
200 }
201 if (CellUtil.isDelete(cell)) {
202 ((Delete) m).addDeleteMarker(cell);
203 } else {
204 ((Put) m).add(cell);
205 }
206 previousCell = cell;
207 }
208 }
209 totalReplicated++;
210 }
211
212
213 if (!rowMap.isEmpty()) {
214 LOG.debug("Started replicating mutations.");
215 for (Entry<TableName, Map<List<UUID>, List<Row>>> entry : rowMap.entrySet()) {
216 batch(entry.getKey(), entry.getValue().values());
217 }
218 LOG.debug("Finished replicating mutations.");
219 }
220
221 if(bulkLoadsPerClusters != null) {
222 for (Entry<List<String>, Map<String, List<Pair<byte[],
223 List<String>>>>> entry : bulkLoadsPerClusters.entrySet()) {
224 Map<String, List<Pair<byte[], List<String>>>> bulkLoadHFileMap = entry.getValue();
225 if (bulkLoadHFileMap != null && !bulkLoadHFileMap.isEmpty()) {
226 if(LOG.isDebugEnabled()) {
227 LOG.debug("Started replicating bulk loaded data from cluster ids: " +
228 entry.getKey().toString());
229 }
230 HFileReplicator hFileReplicator =
231 new HFileReplicator(this.provider.getConf(this.conf, replicationClusterId),
232 sourceBaseNamespaceDirPath, sourceHFileArchiveDirPath, bulkLoadHFileMap, conf,
233 getConnection(), entry.getKey());
234 hFileReplicator.replicate();
235 if(LOG.isDebugEnabled()) {
236 LOG.debug("Finished replicating bulk loaded data from cluster id: " +
237 entry.getKey().toString());
238 }
239 }
240 }
241 }
242
243 int size = entries.size();
244 this.metrics.setAgeOfLastAppliedOp(entries.get(size - 1).getKey().getWriteTime());
245 this.metrics.applyBatch(size + hfilesReplicated, hfilesReplicated);
246 this.totalReplicatedEdits.addAndGet(totalReplicated);
247 } catch (IOException ex) {
248 LOG.error("Unable to accept edit because:", ex);
249 throw ex;
250 }
251 }
252
253 private void buildBulkLoadHFileMap(
254 final Map<String, List<Pair<byte[], List<String>>>> bulkLoadHFileMap, TableName table,
255 BulkLoadDescriptor bld) throws IOException {
256 List<StoreDescriptor> storesList = bld.getStoresList();
257 int storesSize = storesList.size();
258 for (int j = 0; j < storesSize; j++) {
259 StoreDescriptor storeDescriptor = storesList.get(j);
260 List<String> storeFileList = storeDescriptor.getStoreFileList();
261 int storeFilesSize = storeFileList.size();
262 hfilesReplicated += storeFilesSize;
263 for (int k = 0; k < storeFilesSize; k++) {
264 byte[] family = storeDescriptor.getFamilyName().toByteArray();
265
266
267 String pathToHfileFromNS = getHFilePath(table, bld, storeFileList.get(k), family);
268
269 String tableName = table.getNameWithNamespaceInclAsString();
270 if (bulkLoadHFileMap.containsKey(tableName)) {
271 List<Pair<byte[], List<String>>> familyHFilePathsList = bulkLoadHFileMap.get(tableName);
272 boolean foundFamily = false;
273 for (int i = 0; i < familyHFilePathsList.size(); i++) {
274 Pair<byte[], List<String>> familyHFilePathsPair = familyHFilePathsList.get(i);
275 if (Bytes.equals(familyHFilePathsPair.getFirst(), family)) {
276
277 familyHFilePathsPair.getSecond().add(pathToHfileFromNS);
278 foundFamily = true;
279 break;
280 }
281 }
282 if (!foundFamily) {
283
284 addFamilyAndItsHFilePathToTableInMap(family, pathToHfileFromNS, familyHFilePathsList);
285 }
286 } else {
287
288 addNewTableEntryInMap(bulkLoadHFileMap, family, pathToHfileFromNS, tableName);
289 }
290 }
291 }
292 }
293
294 private void addFamilyAndItsHFilePathToTableInMap(byte[] family, String pathToHfileFromNS,
295 List<Pair<byte[], List<String>>> familyHFilePathsList) {
296 List<String> hfilePaths = new ArrayList<String>();
297 hfilePaths.add(pathToHfileFromNS);
298 familyHFilePathsList.add(new Pair<byte[], List<String>>(family, hfilePaths));
299 }
300
301 private void addNewTableEntryInMap(
302 final Map<String, List<Pair<byte[], List<String>>>> bulkLoadHFileMap, byte[] family,
303 String pathToHfileFromNS, String tableName) {
304 List<String> hfilePaths = new ArrayList<String>();
305 hfilePaths.add(pathToHfileFromNS);
306 Pair<byte[], List<String>> newFamilyHFilePathsPair =
307 new Pair<byte[], List<String>>(family, hfilePaths);
308 List<Pair<byte[], List<String>>> newFamilyHFilePathsList =
309 new ArrayList<Pair<byte[], List<String>>>();
310 newFamilyHFilePathsList.add(newFamilyHFilePathsPair);
311 bulkLoadHFileMap.put(tableName, newFamilyHFilePathsList);
312 }
313
314 private String getHFilePath(TableName table, BulkLoadDescriptor bld, String storeFile,
315 byte[] family) {
316 return new StringBuilder(100).append(table.getNamespaceAsString()).append(Path.SEPARATOR)
317 .append(table.getQualifierAsString()).append(Path.SEPARATOR)
318 .append(Bytes.toString(bld.getEncodedRegionName().toByteArray())).append(Path.SEPARATOR)
319 .append(Bytes.toString(family)).append(Path.SEPARATOR).append(storeFile).toString();
320 }
321
322
323
324
325
326
327 private boolean isNewRowOrType(final Cell previousCell, final Cell cell) {
328 return previousCell == null || previousCell.getTypeByte() != cell.getTypeByte() ||
329 !CellUtil.matchingRow(previousCell, cell);
330 }
331
332 private java.util.UUID toUUID(final HBaseProtos.UUID uuid) {
333 return new java.util.UUID(uuid.getMostSigBits(), uuid.getLeastSigBits());
334 }
335
336
337
338
339
340
341
342
343
344
345 private <K1, K2, V> List<V> addToHashMultiMap(Map<K1, Map<K2,List<V>>> map, K1 key1, K2 key2, V value) {
346 Map<K2,List<V>> innerMap = map.get(key1);
347 if (innerMap == null) {
348 innerMap = new HashMap<K2, List<V>>();
349 map.put(key1, innerMap);
350 }
351 List<V> values = innerMap.get(key2);
352 if (values == null) {
353 values = new ArrayList<V>();
354 innerMap.put(key2, values);
355 }
356 values.add(value);
357 return values;
358 }
359
360
361
362
363 public void stopReplicationSinkServices() {
364 try {
365 if (this.sharedHtableCon != null) {
366 synchronized (sharedHtableConLock) {
367 if (this.sharedHtableCon != null) {
368 this.sharedHtableCon.close();
369 this.sharedHtableCon = null;
370 }
371 }
372 }
373 } catch (IOException e) {
374 LOG.warn("IOException while closing the connection", e);
375 }
376 }
377
378
379
380
381
382
383
384
385 protected void batch(TableName tableName, Collection<List<Row>> allRows) throws IOException {
386 if (allRows.isEmpty()) {
387 return;
388 }
389 Table table = null;
390 try {
391 Connection connection = getConnection();
392 table = connection.getTable(tableName);
393 for (List<Row> rows : allRows) {
394 table.batch(rows);
395 }
396 } catch (InterruptedException ix) {
397 throw (InterruptedIOException) new InterruptedIOException().initCause(ix);
398 } finally {
399 if (table != null) {
400 table.close();
401 }
402 }
403 }
404
405 private Connection getConnection() throws IOException {
406
407 Connection connection = sharedHtableCon;
408 if (connection == null) {
409 synchronized (sharedHtableConLock) {
410 connection = sharedHtableCon;
411 if (connection == null) {
412 connection = sharedHtableCon = ConnectionFactory.createConnection(conf);
413 }
414 }
415 }
416 return connection;
417 }
418
419
420
421
422
423
424 public String getStats() {
425 return this.totalReplicatedEdits.get() == 0 ? "" : "Sink: " +
426 "age in ms of last applied edit: " + this.metrics.refreshAgeOfLastAppliedOp() +
427 ", total replicated edits: " + this.totalReplicatedEdits;
428 }
429
430
431
432
433
434 public MetricsSink getSinkMetrics() {
435 return this.metrics;
436 }
437 }