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