001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.replication.regionserver;
019
020import java.io.IOException;
021import java.util.ArrayList;
022import java.util.Collection;
023import java.util.Collections;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027import java.util.Map.Entry;
028import java.util.TreeMap;
029import java.util.UUID;
030import java.util.concurrent.Future;
031import java.util.concurrent.atomic.AtomicLong;
032import java.util.stream.Collectors;
033import org.apache.commons.lang3.StringUtils;
034import org.apache.hadoop.conf.Configuration;
035import org.apache.hadoop.fs.Path;
036import org.apache.hadoop.hbase.Cell;
037import org.apache.hadoop.hbase.CellScanner;
038import org.apache.hadoop.hbase.CellUtil;
039import org.apache.hadoop.hbase.HBaseConfiguration;
040import org.apache.hadoop.hbase.HConstants;
041import org.apache.hadoop.hbase.TableName;
042import org.apache.hadoop.hbase.TableNotFoundException;
043import org.apache.hadoop.hbase.client.AsyncClusterConnection;
044import org.apache.hadoop.hbase.client.AsyncTable;
045import org.apache.hadoop.hbase.client.ClusterConnectionFactory;
046import org.apache.hadoop.hbase.client.Delete;
047import org.apache.hadoop.hbase.client.Mutation;
048import org.apache.hadoop.hbase.client.Put;
049import org.apache.hadoop.hbase.client.RetriesExhaustedException;
050import org.apache.hadoop.hbase.client.Row;
051import org.apache.hadoop.hbase.replication.ReplicationUtils;
052import org.apache.hadoop.hbase.security.UserProvider;
053import org.apache.hadoop.hbase.util.Bytes;
054import org.apache.hadoop.hbase.util.FutureUtils;
055import org.apache.hadoop.hbase.util.Pair;
056import org.apache.hadoop.hbase.wal.WALEdit;
057import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
058import org.apache.yetus.audience.InterfaceAudience;
059import org.slf4j.Logger;
060import org.slf4j.LoggerFactory;
061import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.WALEntry;
062import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;
063import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.BulkLoadDescriptor;
064import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.StoreDescriptor;
065
066/**
067 * <p>
068 * This class is responsible for replicating the edits coming
069 * from another cluster.
070 * </p><p>
071 * This replication process is currently waiting for the edits to be applied
072 * before the method can return. This means that the replication of edits
073 * is synchronized (after reading from WALs in ReplicationSource) and that a
074 * single region server cannot receive edits from two sources at the same time
075 * </p><p>
076 * This class uses the native HBase client in order to replicate entries.
077 * </p>
078 *
079 * TODO make this class more like ReplicationSource wrt log handling
080 */
081@InterfaceAudience.Private
082public class ReplicationSink {
083
084  private static final Logger LOG = LoggerFactory.getLogger(ReplicationSink.class);
085  private final Configuration conf;
086  // Volatile because of note in here -- look for double-checked locking:
087  // http://www.oracle.com/technetwork/articles/javase/bloch-effective-08-qa-140880.html
088  private volatile AsyncClusterConnection sharedConn;
089  private final MetricsSink metrics;
090  private final AtomicLong totalReplicatedEdits = new AtomicLong();
091  private final Object sharedConnLock = new Object();
092  // Number of hfiles that we successfully replicated
093  private long hfilesReplicated = 0;
094  private SourceFSConfigurationProvider provider;
095  private WALEntrySinkFilter walEntrySinkFilter;
096
097  /**
098   * Row size threshold for multi requests above which a warning is logged
099   */
100  private final int rowSizeWarnThreshold;
101
102  /**
103   * Create a sink for replication
104   * @param conf conf object
105   * @throws IOException thrown when HDFS goes bad or bad file name
106   */
107  public ReplicationSink(Configuration conf)
108      throws IOException {
109    this.conf = HBaseConfiguration.create(conf);
110    rowSizeWarnThreshold = conf.getInt(
111      HConstants.BATCH_ROWS_THRESHOLD_NAME, HConstants.BATCH_ROWS_THRESHOLD_DEFAULT);
112    decorateConf();
113    this.metrics = new MetricsSink();
114    this.walEntrySinkFilter = setupWALEntrySinkFilter();
115    String className = conf.get("hbase.replication.source.fs.conf.provider",
116      DefaultSourceFSConfigurationProvider.class.getCanonicalName());
117    try {
118      Class<? extends SourceFSConfigurationProvider> c =
119          Class.forName(className).asSubclass(SourceFSConfigurationProvider.class);
120      this.provider = c.getDeclaredConstructor().newInstance();
121    } catch (Exception e) {
122      throw new IllegalArgumentException(
123          "Configured source fs configuration provider class " + className + " throws error.", e);
124    }
125  }
126
127  private WALEntrySinkFilter setupWALEntrySinkFilter() throws IOException {
128    Class<?> walEntryFilterClass =
129        this.conf.getClass(WALEntrySinkFilter.WAL_ENTRY_FILTER_KEY, null);
130    WALEntrySinkFilter filter = null;
131    try {
132      filter = walEntryFilterClass == null? null:
133          (WALEntrySinkFilter)walEntryFilterClass.getDeclaredConstructor().newInstance();
134    } catch (Exception e) {
135      LOG.warn("Failed to instantiate " + walEntryFilterClass);
136    }
137    if (filter != null) {
138      filter.init(getConnection());
139    }
140    return filter;
141  }
142
143  /**
144   * decorate the Configuration object to make replication more receptive to delays:
145   * lessen the timeout and numTries.
146   */
147  private void decorateConf() {
148    this.conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
149        this.conf.getInt("replication.sink.client.retries.number", 4));
150    this.conf.setInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
151        this.conf.getInt("replication.sink.client.ops.timeout", 10000));
152    String replicationCodec = this.conf.get(HConstants.REPLICATION_CODEC_CONF_KEY);
153    if (StringUtils.isNotEmpty(replicationCodec)) {
154      this.conf.set(HConstants.RPC_CODEC_CONF_KEY, replicationCodec);
155    }
156    // use server ZK cluster for replication, so we unset the client ZK related properties if any
157    if (this.conf.get(HConstants.CLIENT_ZOOKEEPER_QUORUM) != null) {
158      this.conf.unset(HConstants.CLIENT_ZOOKEEPER_QUORUM);
159    }
160  }
161
162  /**
163   * Replicate this array of entries directly into the local cluster using the native client. Only
164   * operates against raw protobuf type saving on a conversion from pb to pojo.
165   * @param replicationClusterId Id which will uniquely identify source cluster FS client
166   *          configurations in the replication configuration directory
167   * @param sourceBaseNamespaceDirPath Path that point to the source cluster base namespace
168   *          directory
169   * @param sourceHFileArchiveDirPath Path that point to the source cluster hfile archive directory
170   * @throws IOException If failed to replicate the data
171   */
172  public void replicateEntries(List<WALEntry> entries, final CellScanner cells,
173      String replicationClusterId, String sourceBaseNamespaceDirPath,
174      String sourceHFileArchiveDirPath) throws IOException {
175    if (entries.isEmpty()) {
176      return;
177    }
178    // Very simple optimization where we batch sequences of rows going
179    // to the same table.
180    try {
181      long totalReplicated = 0;
182      // Map of table => list of Rows, grouped by cluster id, we only want to flushCommits once per
183      // invocation of this method per table and cluster id.
184      Map<TableName, Map<List<UUID>, List<Row>>> rowMap = new TreeMap<>();
185
186      Map<List<String>, Map<String, List<Pair<byte[], List<String>>>>> bulkLoadsPerClusters = null;
187      for (WALEntry entry : entries) {
188        TableName table = TableName.valueOf(entry.getKey().getTableName().toByteArray());
189        if (this.walEntrySinkFilter != null) {
190          if (this.walEntrySinkFilter.filter(table, entry.getKey().getWriteTime())) {
191            // Skip Cells in CellScanner associated with this entry.
192            int count = entry.getAssociatedCellCount();
193            for (int i = 0; i < count; i++) {
194              // Throw index out of bounds if our cell count is off
195              if (!cells.advance()) {
196                throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
197              }
198            }
199            continue;
200          }
201        }
202        Cell previousCell = null;
203        Mutation mutation = null;
204        int count = entry.getAssociatedCellCount();
205        for (int i = 0; i < count; i++) {
206          // Throw index out of bounds if our cell count is off
207          if (!cells.advance()) {
208            throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
209          }
210          Cell cell = cells.current();
211          // Handle bulk load hfiles replication
212          if (CellUtil.matchingQualifier(cell, WALEdit.BULK_LOAD)) {
213            BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cell);
214            if(bld.getReplicate()) {
215              if (bulkLoadsPerClusters == null) {
216                bulkLoadsPerClusters = new HashMap<>();
217              }
218              // Map of table name Vs list of pair of family and list of
219              // hfile paths from its namespace
220              Map<String, List<Pair<byte[], List<String>>>> bulkLoadHFileMap =
221                bulkLoadsPerClusters.computeIfAbsent(bld.getClusterIdsList(), k -> new HashMap<>());
222              buildBulkLoadHFileMap(bulkLoadHFileMap, table, bld);
223            }
224          } else {
225            // Handle wal replication
226            if (isNewRowOrType(previousCell, cell)) {
227              // Create new mutation
228              mutation =
229                  CellUtil.isDelete(cell) ? new Delete(cell.getRowArray(), cell.getRowOffset(),
230                      cell.getRowLength()) : new Put(cell.getRowArray(), cell.getRowOffset(),
231                      cell.getRowLength());
232              List<UUID> clusterIds = new ArrayList<>(entry.getKey().getClusterIdsList().size());
233              for (HBaseProtos.UUID clusterId : entry.getKey().getClusterIdsList()) {
234                clusterIds.add(toUUID(clusterId));
235              }
236              mutation.setClusterIds(clusterIds);
237              mutation.setAttribute(ReplicationUtils.REPLICATION_ATTR_NAME,
238                HConstants.EMPTY_BYTE_ARRAY);
239              addToHashMultiMap(rowMap, table, clusterIds, mutation);
240            }
241            if (CellUtil.isDelete(cell)) {
242              ((Delete) mutation).add(cell);
243            } else {
244              ((Put) mutation).add(cell);
245            }
246            previousCell = cell;
247          }
248        }
249        totalReplicated++;
250      }
251
252      // TODO Replicating mutations and bulk loaded data can be made parallel
253      if (!rowMap.isEmpty()) {
254        LOG.debug("Started replicating mutations.");
255        for (Entry<TableName, Map<List<UUID>, List<Row>>> entry : rowMap.entrySet()) {
256          batch(entry.getKey(), entry.getValue().values(), rowSizeWarnThreshold);
257        }
258        LOG.debug("Finished replicating mutations.");
259      }
260
261      if(bulkLoadsPerClusters != null) {
262        for (Entry<List<String>, Map<String, List<Pair<byte[], List<String>>>>> entry :
263            bulkLoadsPerClusters.entrySet()) {
264          Map<String, List<Pair<byte[], List<String>>>> bulkLoadHFileMap = entry.getValue();
265          if (bulkLoadHFileMap != null && !bulkLoadHFileMap.isEmpty()) {
266            LOG.debug("Replicating {} bulk loaded data", entry.getKey().toString());
267            Configuration providerConf = this.provider.getConf(this.conf, replicationClusterId);
268            try (HFileReplicator hFileReplicator = new HFileReplicator(providerConf,
269                sourceBaseNamespaceDirPath, sourceHFileArchiveDirPath, bulkLoadHFileMap, conf,
270                getConnection(), entry.getKey())) {
271              hFileReplicator.replicate();
272              LOG.debug("Finished replicating {} bulk loaded data", entry.getKey().toString());
273            }
274          }
275        }
276      }
277
278      int size = entries.size();
279      this.metrics.setAgeOfLastAppliedOp(entries.get(size - 1).getKey().getWriteTime());
280      this.metrics.applyBatch(size + hfilesReplicated, hfilesReplicated);
281      this.totalReplicatedEdits.addAndGet(totalReplicated);
282    } catch (IOException ex) {
283      LOG.error("Unable to accept edit because:", ex);
284      throw ex;
285    }
286  }
287
288  private void buildBulkLoadHFileMap(
289      final Map<String, List<Pair<byte[], List<String>>>> bulkLoadHFileMap, TableName table,
290      BulkLoadDescriptor bld) throws IOException {
291    List<StoreDescriptor> storesList = bld.getStoresList();
292    int storesSize = storesList.size();
293    for (int j = 0; j < storesSize; j++) {
294      StoreDescriptor storeDescriptor = storesList.get(j);
295      List<String> storeFileList = storeDescriptor.getStoreFileList();
296      int storeFilesSize = storeFileList.size();
297      hfilesReplicated += storeFilesSize;
298      for (int k = 0; k < storeFilesSize; k++) {
299        byte[] family = storeDescriptor.getFamilyName().toByteArray();
300
301        // Build hfile relative path from its namespace
302        String pathToHfileFromNS = getHFilePath(table, bld, storeFileList.get(k), family);
303        String tableName = table.getNameWithNamespaceInclAsString();
304        List<Pair<byte[], List<String>>> familyHFilePathsList = bulkLoadHFileMap.get(tableName);
305        if (familyHFilePathsList != null) {
306          boolean foundFamily = false;
307          for (Pair<byte[], List<String>> familyHFilePathsPair :  familyHFilePathsList) {
308            if (Bytes.equals(familyHFilePathsPair.getFirst(), family)) {
309              // Found family already present, just add the path to the existing list
310              familyHFilePathsPair.getSecond().add(pathToHfileFromNS);
311              foundFamily = true;
312              break;
313            }
314          }
315          if (!foundFamily) {
316            // Family not found, add this family and its hfile paths pair to the list
317            addFamilyAndItsHFilePathToTableInMap(family, pathToHfileFromNS, familyHFilePathsList);
318          }
319        } else {
320          // Add this table entry into the map
321          addNewTableEntryInMap(bulkLoadHFileMap, family, pathToHfileFromNS, tableName);
322        }
323      }
324    }
325  }
326
327  private void addFamilyAndItsHFilePathToTableInMap(byte[] family, String pathToHfileFromNS,
328      List<Pair<byte[], List<String>>> familyHFilePathsList) {
329    List<String> hfilePaths = new ArrayList<>(1);
330    hfilePaths.add(pathToHfileFromNS);
331    familyHFilePathsList.add(new Pair<>(family, hfilePaths));
332  }
333
334  private void addNewTableEntryInMap(
335      final Map<String, List<Pair<byte[], List<String>>>> bulkLoadHFileMap, byte[] family,
336      String pathToHfileFromNS, String tableName) {
337    List<String> hfilePaths = new ArrayList<>(1);
338    hfilePaths.add(pathToHfileFromNS);
339    Pair<byte[], List<String>> newFamilyHFilePathsPair = new Pair<>(family, hfilePaths);
340    List<Pair<byte[], List<String>>> newFamilyHFilePathsList = new ArrayList<>();
341    newFamilyHFilePathsList.add(newFamilyHFilePathsPair);
342    bulkLoadHFileMap.put(tableName, newFamilyHFilePathsList);
343  }
344
345  private String getHFilePath(TableName table, BulkLoadDescriptor bld, String storeFile,
346      byte[] family) {
347    return new StringBuilder(100).append(table.getNamespaceAsString()).append(Path.SEPARATOR)
348        .append(table.getQualifierAsString()).append(Path.SEPARATOR)
349        .append(Bytes.toString(bld.getEncodedRegionName().toByteArray())).append(Path.SEPARATOR)
350        .append(Bytes.toString(family)).append(Path.SEPARATOR).append(storeFile).toString();
351  }
352
353  /**
354   * @return True if we have crossed over onto a new row or type
355   */
356  private boolean isNewRowOrType(final Cell previousCell, final Cell cell) {
357    return previousCell == null || previousCell.getTypeByte() != cell.getTypeByte() ||
358        !CellUtil.matchingRows(previousCell, cell);
359  }
360
361  private java.util.UUID toUUID(final HBaseProtos.UUID uuid) {
362    return new java.util.UUID(uuid.getMostSigBits(), uuid.getLeastSigBits());
363  }
364
365  /**
366   * Simple helper to a map from key to (a list of) values
367   * TODO: Make a general utility method
368   * @return the list of values corresponding to key1 and key2
369   */
370  private <K1, K2, V> List<V> addToHashMultiMap(Map<K1, Map<K2,List<V>>> map, K1 key1,
371      K2 key2, V value) {
372    Map<K2, List<V>> innerMap = map.computeIfAbsent(key1, k -> new HashMap<>());
373    List<V> values = innerMap.computeIfAbsent(key2, k -> new ArrayList<>());
374    values.add(value);
375    return values;
376  }
377
378  /**
379   * stop the thread pool executor. It is called when the regionserver is stopped.
380   */
381  public void stopReplicationSinkServices() {
382    try {
383      if (this.sharedConn != null) {
384        synchronized (sharedConnLock) {
385          if (this.sharedConn != null) {
386            this.sharedConn.close();
387            this.sharedConn = null;
388          }
389        }
390      }
391    } catch (IOException e) {
392      LOG.warn("IOException while closing the connection", e); // ignoring as we are closing.
393    }
394  }
395
396
397  /**
398   * Do the changes and handle the pool
399   * @param tableName table to insert into
400   * @param allRows list of actions
401   * @param batchRowSizeThreshold rowSize threshold for batch mutation
402   */
403  private void batch(TableName tableName, Collection<List<Row>> allRows, int batchRowSizeThreshold)
404      throws IOException {
405    if (allRows.isEmpty()) {
406      return;
407    }
408    AsyncTable<?> table = getConnection().getTable(tableName);
409    List<Future<?>> futures = new ArrayList<>();
410    for (List<Row> rows : allRows) {
411      List<List<Row>> batchRows;
412      if (rows.size() > batchRowSizeThreshold) {
413        batchRows = Lists.partition(rows, batchRowSizeThreshold);
414      } else {
415        batchRows = Collections.singletonList(rows);
416      }
417      futures.addAll(batchRows.stream().map(table::batchAll).collect(Collectors.toList()));
418    }
419    for (Future<?> future : futures) {
420      try {
421        FutureUtils.get(future);
422      } catch (RetriesExhaustedException e) {
423        if (e.getCause() instanceof TableNotFoundException) {
424          throw new TableNotFoundException("'" + tableName + "'");
425        }
426        throw e;
427      }
428    }
429  }
430
431  private AsyncClusterConnection getConnection() throws IOException {
432    // See https://en.wikipedia.org/wiki/Double-checked_locking
433    AsyncClusterConnection connection = sharedConn;
434    if (connection == null) {
435      synchronized (sharedConnLock) {
436        connection = sharedConn;
437        if (connection == null) {
438          connection = ClusterConnectionFactory.createAsyncClusterConnection(conf, null,
439            UserProvider.instantiate(conf).getCurrent());
440          sharedConn = connection;
441        }
442      }
443    }
444    return connection;
445  }
446
447  /**
448   * Get a string representation of this sink's metrics
449   * @return string with the total replicated edits count and the date
450   *   of the last edit that was applied
451   */
452  public String getStats() {
453    long total = this.totalReplicatedEdits.get();
454    return total == 0 ? ""
455        : "Sink: " + "age in ms of last applied edit: " + this.metrics.refreshAgeOfLastAppliedOp() +
456          ", total replicated edits: " + total;
457  }
458
459  /**
460   * Get replication Sink Metrics
461   * @return MetricsSink
462   */
463  public MetricsSink getSinkMetrics() {
464    return this.metrics;
465  }
466}