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.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   * <p>
63   * This class is responsible for replicating the edits coming
64   * from another cluster.
65   * </p><p>
66   * This replication process is currently waiting for the edits to be applied
67   * before the method can return. This means that the replication of edits
68   * is synchronized (after reading from WALs in ReplicationSource) and that a
69   * single region server cannot receive edits from two sources at the same time
70   * </p><p>
71   * This class uses the native HBase client in order to replicate entries.
72   * </p>
73   *
74   * TODO make this class more like ReplicationSource wrt log handling
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    // Volatile because of note in here -- look for double-checked locking:
82    // http://www.oracle.com/technetwork/articles/javase/bloch-effective-08-qa-140880.html
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    // Number of hfiles that we successfully replicated
88    private long hfilesReplicated = 0;
89    private SourceFSConfigurationProvider provider;
90  
91    /**
92     * Create a sink for replication
93     *
94     * @param conf                conf object
95     * @param stopper             boolean to tell this thread to stop
96     * @throws IOException thrown when HDFS goes bad or bad file name
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    * decorate the Configuration object to make replication more receptive to delays:
119    * lessen the timeout and numTries.
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    * Replicate this array of entries directly into the local cluster using the native client. Only
134    * operates against raw protobuf type saving on a conversion from pb to pojo.
135    * @param entries
136    * @param cells
137    * @param replicationClusterId Id which will uniquely identify source cluster FS client
138    *          configurations in the replication configuration directory
139    * @param sourceBaseNamespaceDirPath Path that point to the source cluster base namespace
140    *          directory
141    * @param sourceHFileArchiveDirPath Path that point to the source cluster hfile archive directory
142    * @throws IOException If failed to replicate the data
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     // Very simple optimization where we batch sequences of rows going
150     // to the same table.
151     try {
152       long totalReplicated = 0;
153       // Map of table => list of Rows, grouped by cluster id, we only want to flushCommits once per
154       // invocation of this method per table and cluster id.
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           // Throw index out of bounds if our cell count is off
167           if (!cells.advance()) {
168             throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
169           }
170           Cell cell = cells.current();
171           // Handle bulk load hfiles replication
172           if (CellUtil.matchingQualifier(cell, WALEdit.BULK_LOAD)) {
173             BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cell);
174             if(bulkLoadsPerClusters == null) {
175               bulkLoadsPerClusters = new HashMap<>();
176             }
177             // Map of table name Vs list of pair of family and list of
178             // hfile paths from its namespace
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             // Handle wal replication
188             if (isNewRowOrType(previousCell, cell)) {
189               // Create new mutation
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       // TODO Replicating mutations and bulk loaded data can be made parallel
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         // Build hfile relative path from its namespace
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               // Found family already present, just add the path to the existing list
277               familyHFilePathsPair.getSecond().add(pathToHfileFromNS);
278               foundFamily = true;
279               break;
280             }
281           }
282           if (!foundFamily) {
283             // Family not found, add this family and its hfile paths pair to the list
284             addFamilyAndItsHFilePathToTableInMap(family, pathToHfileFromNS, familyHFilePathsList);
285           }
286         } else {
287           // Add this table entry into the map
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    * @param previousCell
324    * @param cell
325    * @return True if we have crossed over onto a new row or type
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    * Simple helper to a map from key to (a list of) values
338    * TODO: Make a general utility method
339    * @param map
340    * @param key1
341    * @param key2
342    * @param value
343    * @return the list of values corresponding to key1 and key2
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    * stop the thread pool executor. It is called when the regionserver is stopped.
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); // ignoring as we are closing.
375     }
376   }
377 
378 
379   /**
380    * Do the changes and handle the pool
381    * @param tableName table to insert into
382    * @param allRows list of actions
383    * @throws IOException
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     // See https://en.wikipedia.org/wiki/Double-checked_locking
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    * Get a string representation of this sink's metrics
421    * @return string with the total replicated edits count and the date
422    * of the last edit that was applied
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    * Get replication Sink Metrics
432    * @return MetricsSink
433    */
434   public MetricsSink getSinkMetrics() {
435     return this.metrics;
436   }
437 }