View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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   * <p>
65   * This class is responsible for replicating the edits coming
66   * from another cluster.
67   * </p><p>
68   * This replication process is currently waiting for the edits to be applied
69   * before the method can return. This means that the replication of edits
70   * is synchronized (after reading from WALs in ReplicationSource) and that a
71   * single region server cannot receive edits from two sources at the same time
72   * </p><p>
73   * This class uses the native HBase client in order to replicate entries.
74   * </p>
75   *
76   * TODO make this class more like ReplicationSource wrt log handling
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    // Volatile because of note in here -- look for double-checked locking:
84    // http://www.oracle.com/technetwork/articles/javase/bloch-effective-08-qa-140880.html
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    // Number of hfiles that we successfully replicated
90    private long hfilesReplicated = 0;
91    private SourceFSConfigurationProvider provider;
92  
93    /**
94     * Create a sink for replication
95     *
96     * @param conf                conf object
97     * @param stopper             boolean to tell this thread to stop
98     * @throws IOException thrown when HDFS goes bad or bad file name
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    * decorate the Configuration object to make replication more receptive to delays:
121    * lessen the timeout and numTries.
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    * Replicate this array of entries directly into the local cluster using the native client. Only
136    * operates against raw protobuf type saving on a conversion from pb to pojo.
137    * @param entries
138    * @param cells
139    * @param replicationClusterId Id which will uniquely identify source cluster FS client
140    *          configurations in the replication configuration directory
141    * @param sourceBaseNamespaceDirPath Path that point to the source cluster base namespace
142    *          directory
143    * @param sourceHFileArchiveDirPath Path that point to the source cluster hfile archive directory
144    * @throws IOException If failed to replicate the data
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     // Very simple optimization where we batch sequences of rows going
152     // to the same table.
153     try {
154       long totalReplicated = 0;
155       // Map of table => list of Rows, grouped by cluster id, we only want to flushCommits once per
156       // invocation of this method per table and cluster id.
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           // Throw index out of bounds if our cell count is off
169           if (!cells.advance()) {
170             throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
171           }
172           Cell cell = cells.current();
173           // Handle bulk load hfiles replication
174           if (CellUtil.matchingQualifier(cell, WALEdit.BULK_LOAD)) {
175             BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cell);
176             if(bulkLoadsPerClusters == null) {
177               bulkLoadsPerClusters = new HashMap<>();
178             }
179             // Map of table name Vs list of pair of family and list of
180             // hfile paths from its namespace
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             // Handle wal replication
190             if (isNewRowOrType(previousCell, cell)) {
191               // Create new mutation
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       // TODO Replicating mutations and bulk loaded data can be made parallel
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         // Build hfile relative path from its namespace
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               // Found family already present, just add the path to the existing list
279               familyHFilePathsPair.getSecond().add(pathToHfileFromNS);
280               foundFamily = true;
281               break;
282             }
283           }
284           if (!foundFamily) {
285             // Family not found, add this family and its hfile paths pair to the list
286             addFamilyAndItsHFilePathToTableInMap(family, pathToHfileFromNS, familyHFilePathsList);
287           }
288         } else {
289           // Add this table entry into the map
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    * @param previousCell
326    * @param cell
327    * @return True if we have crossed over onto a new row or type
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    * Simple helper to a map from key to (a list of) values
340    * TODO: Make a general utility method
341    * @param map
342    * @param key1
343    * @param key2
344    * @param value
345    * @return the list of values corresponding to key1 and key2
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    * stop the thread pool executor. It is called when the regionserver is stopped.
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); // ignoring as we are closing.
377     }
378   }
379 
380 
381   /**
382    * Do the changes and handle the pool
383    * @param tableName table to insert into
384    * @param allRows list of actions
385    * @throws IOException
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     // See https://en.wikipedia.org/wiki/Double-checked_locking
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    * Get a string representation of this sink's metrics
430    * @return string with the total replicated edits count and the date
431    * of the last edit that was applied
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    * Get replication Sink Metrics
441    * @return MetricsSink
442    */
443   public MetricsSink getSinkMetrics() {
444     return this.metrics;
445   }
446 }