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.mapreduce;
019
020import static org.apache.hadoop.hbase.regionserver.HStoreFile.BULKLOAD_TASK_KEY;
021import static org.apache.hadoop.hbase.regionserver.HStoreFile.BULKLOAD_TIME_KEY;
022import static org.apache.hadoop.hbase.regionserver.HStoreFile.EXCLUDE_FROM_MINOR_COMPACTION_KEY;
023import static org.apache.hadoop.hbase.regionserver.HStoreFile.MAJOR_COMPACTION_KEY;
024
025import java.io.IOException;
026import java.io.UnsupportedEncodingException;
027import java.net.InetSocketAddress;
028import java.net.URLDecoder;
029import java.net.URLEncoder;
030import java.nio.charset.Charset;
031import java.util.ArrayList;
032import java.util.Arrays;
033import java.util.Collections;
034import java.util.List;
035import java.util.Map;
036import java.util.Map.Entry;
037import java.util.Set;
038import java.util.TreeMap;
039import java.util.TreeSet;
040import java.util.UUID;
041import java.util.function.Function;
042import java.util.stream.Collectors;
043import org.apache.commons.lang3.StringUtils;
044import org.apache.hadoop.conf.Configuration;
045import org.apache.hadoop.fs.FileSystem;
046import org.apache.hadoop.fs.Path;
047import org.apache.hadoop.hbase.Cell;
048import org.apache.hadoop.hbase.CellUtil;
049import org.apache.hadoop.hbase.HConstants;
050import org.apache.hadoop.hbase.HRegionLocation;
051import org.apache.hadoop.hbase.HTableDescriptor;
052import org.apache.hadoop.hbase.KeyValue;
053import org.apache.hadoop.hbase.PrivateCellUtil;
054import org.apache.hadoop.hbase.TableName;
055import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
056import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
057import org.apache.hadoop.hbase.client.Connection;
058import org.apache.hadoop.hbase.client.ConnectionFactory;
059import org.apache.hadoop.hbase.client.Put;
060import org.apache.hadoop.hbase.client.RegionLocator;
061import org.apache.hadoop.hbase.client.Table;
062import org.apache.hadoop.hbase.client.TableDescriptor;
063import org.apache.hadoop.hbase.fs.HFileSystem;
064import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
065import org.apache.hadoop.hbase.io.compress.Compression;
066import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
067import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
068import org.apache.hadoop.hbase.io.hfile.CacheConfig;
069import org.apache.hadoop.hbase.io.hfile.HFile;
070import org.apache.hadoop.hbase.io.hfile.HFileContext;
071import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
072import org.apache.hadoop.hbase.io.hfile.HFileWriterImpl;
073import org.apache.hadoop.hbase.regionserver.BloomType;
074import org.apache.hadoop.hbase.regionserver.HStore;
075import org.apache.hadoop.hbase.regionserver.StoreFileWriter;
076import org.apache.hadoop.hbase.regionserver.StoreUtils;
077import org.apache.hadoop.hbase.util.BloomFilterUtil;
078import org.apache.hadoop.hbase.util.Bytes;
079import org.apache.hadoop.hbase.util.CommonFSUtils;
080import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
081import org.apache.hadoop.hbase.util.MapReduceExtendedCell;
082import org.apache.hadoop.hbase.util.ReflectionUtils;
083import org.apache.hadoop.io.NullWritable;
084import org.apache.hadoop.io.SequenceFile;
085import org.apache.hadoop.io.Text;
086import org.apache.hadoop.mapreduce.Job;
087import org.apache.hadoop.mapreduce.OutputCommitter;
088import org.apache.hadoop.mapreduce.OutputFormat;
089import org.apache.hadoop.mapreduce.RecordWriter;
090import org.apache.hadoop.mapreduce.TaskAttemptContext;
091import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
092import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
093import org.apache.yetus.audience.InterfaceAudience;
094import org.slf4j.Logger;
095import org.slf4j.LoggerFactory;
096
097/**
098 * Writes HFiles. Passed Cells must arrive in order. Writes current time as the sequence id for the
099 * file. Sets the major compacted attribute on created {@link HFile}s. Calling write(null,null) will
100 * forcibly roll all HFiles being written.
101 * <p>
102 * Using this class as part of a MapReduce job is best done using
103 * {@link #configureIncrementalLoad(Job, TableDescriptor, RegionLocator)}.
104 */
105@InterfaceAudience.Public
106public class HFileOutputFormat2 extends FileOutputFormat<ImmutableBytesWritable, Cell> {
107  private static final Logger LOG = LoggerFactory.getLogger(HFileOutputFormat2.class);
108
109  static class TableInfo {
110    private TableDescriptor tableDesctiptor;
111    private RegionLocator regionLocator;
112
113    public TableInfo(TableDescriptor tableDesctiptor, RegionLocator regionLocator) {
114      this.tableDesctiptor = tableDesctiptor;
115      this.regionLocator = regionLocator;
116    }
117
118    /**
119     * The modification for the returned HTD doesn't affect the inner TD.
120     * @return A clone of inner table descriptor
121     * @deprecated since 2.0.0 and will be removed in 3.0.0. Use {@link #getTableDescriptor()}
122     *             instead.
123     * @see #getTableDescriptor()
124     * @see <a href="https://issues.apache.org/jira/browse/HBASE-18241">HBASE-18241</a>
125     */
126    @Deprecated
127    public HTableDescriptor getHTableDescriptor() {
128      return new HTableDescriptor(tableDesctiptor);
129    }
130
131    public TableDescriptor getTableDescriptor() {
132      return tableDesctiptor;
133    }
134
135    public RegionLocator getRegionLocator() {
136      return regionLocator;
137    }
138  }
139
140  protected static final byte[] tableSeparator = Bytes.toBytes(";");
141
142  protected static byte[] combineTableNameSuffix(byte[] tableName, byte[] suffix) {
143    return Bytes.add(tableName, tableSeparator, suffix);
144  }
145
146  // The following constants are private since these are used by
147  // HFileOutputFormat2 to internally transfer data between job setup and
148  // reducer run using conf.
149  // These should not be changed by the client.
150  static final String COMPRESSION_FAMILIES_CONF_KEY =
151    "hbase.hfileoutputformat.families.compression";
152  static final String BLOOM_TYPE_FAMILIES_CONF_KEY = "hbase.hfileoutputformat.families.bloomtype";
153  static final String BLOOM_PARAM_FAMILIES_CONF_KEY = "hbase.hfileoutputformat.families.bloomparam";
154  static final String BLOCK_SIZE_FAMILIES_CONF_KEY = "hbase.mapreduce.hfileoutputformat.blocksize";
155  static final String DATABLOCK_ENCODING_FAMILIES_CONF_KEY =
156    "hbase.mapreduce.hfileoutputformat.families.datablock.encoding";
157
158  // When MULTI_TABLE_HFILEOUTPUTFORMAT_CONF_KEY is enabled, should table names be written
159  // with namespace included. Enabling this means downstream jobs which use this output will
160  // need to account for namespace when finding the directory of the job output.
161  // For example: a table named my-table in namespace default would be in `/output/default/my-table`
162  // instead of current `/output/my-table`
163  // This will be the behavior when upgrading to hbase 3.0.
164  public static final String TABLE_NAME_WITH_NAMESPACE_INCLUSIVE_KEY =
165    "hbase.hfileoutputformat.tablename.namespace.inclusive";
166
167  private static final boolean TABLE_NAME_WITH_NAMESPACE_INCLUSIVE_DEFAULT_VALUE = false;
168
169  // This constant is public since the client can modify this when setting
170  // up their conf object and thus refer to this symbol.
171  // It is present for backwards compatibility reasons. Use it only to
172  // override the auto-detection of datablock encoding and compression.
173  public static final String DATABLOCK_ENCODING_OVERRIDE_CONF_KEY =
174    "hbase.mapreduce.hfileoutputformat.datablock.encoding";
175  public static final String COMPRESSION_OVERRIDE_CONF_KEY =
176    "hbase.mapreduce.hfileoutputformat.compression";
177
178  /**
179   * Keep locality while generating HFiles for bulkload. See HBASE-12596
180   */
181  public static final String LOCALITY_SENSITIVE_CONF_KEY =
182    "hbase.bulkload.locality.sensitive.enabled";
183  private static final boolean DEFAULT_LOCALITY_SENSITIVE = true;
184  static final String OUTPUT_TABLE_NAME_CONF_KEY = "hbase.mapreduce.hfileoutputformat.table.name";
185  static final String MULTI_TABLE_HFILEOUTPUTFORMAT_CONF_KEY =
186    "hbase.mapreduce.use.multi.table.hfileoutputformat";
187
188  /**
189   * ExtendedCell and ExtendedCellSerialization are InterfaceAudience.Private. We expose this config
190   * for internal usage in jobs like WALPlayer which need to use features of ExtendedCell.
191   */
192  @InterfaceAudience.Private
193  public static final String EXTENDED_CELL_SERIALIZATION_ENABLED_KEY =
194    "hbase.mapreduce.hfileoutputformat.extendedcell.enabled";
195  static final boolean EXTENDED_CELL_SERIALIZATION_ENABLED_DEFULT = false;
196
197  public static final String REMOTE_CLUSTER_CONF_PREFIX = "hbase.hfileoutputformat.remote.cluster.";
198  public static final String REMOTE_CLUSTER_ZOOKEEPER_QUORUM_CONF_KEY =
199    REMOTE_CLUSTER_CONF_PREFIX + "zookeeper.quorum";
200  public static final String REMOTE_CLUSTER_ZOOKEEPER_CLIENT_PORT_CONF_KEY =
201    REMOTE_CLUSTER_CONF_PREFIX + "zookeeper." + HConstants.CLIENT_PORT_STR;
202  public static final String REMOTE_CLUSTER_ZOOKEEPER_ZNODE_PARENT_CONF_KEY =
203    REMOTE_CLUSTER_CONF_PREFIX + HConstants.ZOOKEEPER_ZNODE_PARENT;
204
205  public static final String STORAGE_POLICY_PROPERTY = HStore.BLOCK_STORAGE_POLICY_KEY;
206  public static final String STORAGE_POLICY_PROPERTY_CF_PREFIX = STORAGE_POLICY_PROPERTY + ".";
207
208  @Override
209  public RecordWriter<ImmutableBytesWritable, Cell>
210    getRecordWriter(final TaskAttemptContext context) throws IOException, InterruptedException {
211    return createRecordWriter(context, this.getOutputCommitter(context));
212  }
213
214  protected static byte[] getTableNameSuffixedWithFamily(byte[] tableName, byte[] family) {
215    return combineTableNameSuffix(tableName, family);
216  }
217
218  protected static Path getWorkPath(final OutputCommitter committer) {
219    return (Path) ReflectionUtils.invokeMethod(committer, "getWorkPath");
220  }
221
222  static <V extends Cell> RecordWriter<ImmutableBytesWritable, V> createRecordWriter(
223    final TaskAttemptContext context, final OutputCommitter committer) throws IOException {
224
225    // Get the path of the temporary output file
226    final Path outputDir = getWorkPath(committer);
227    final Configuration conf = context.getConfiguration();
228    final boolean writeMultipleTables =
229      conf.getBoolean(MULTI_TABLE_HFILEOUTPUTFORMAT_CONF_KEY, false);
230    final boolean writeToTableWithNamespace = conf.getBoolean(
231      TABLE_NAME_WITH_NAMESPACE_INCLUSIVE_KEY, TABLE_NAME_WITH_NAMESPACE_INCLUSIVE_DEFAULT_VALUE);
232    final String writeTableNames = conf.get(OUTPUT_TABLE_NAME_CONF_KEY);
233    if (writeTableNames == null || writeTableNames.isEmpty()) {
234      throw new IllegalArgumentException("" + OUTPUT_TABLE_NAME_CONF_KEY + " cannot be empty");
235    }
236    final FileSystem fs = outputDir.getFileSystem(conf);
237    // These configs. are from hbase-*.xml
238    final long maxsize =
239      conf.getLong(HConstants.HREGION_MAX_FILESIZE, HConstants.DEFAULT_MAX_FILE_SIZE);
240    // Invented config. Add to hbase-*.xml if other than default compression.
241    final String defaultCompressionStr =
242      conf.get("hfile.compression", Compression.Algorithm.NONE.getName());
243    final Algorithm defaultCompression = HFileWriterImpl.compressionByName(defaultCompressionStr);
244    String compressionStr = conf.get(COMPRESSION_OVERRIDE_CONF_KEY);
245    final Algorithm overriddenCompression =
246      compressionStr != null ? Compression.getCompressionAlgorithmByName(compressionStr) : null;
247    final boolean compactionExclude =
248      conf.getBoolean("hbase.mapreduce.hfileoutputformat.compaction.exclude", false);
249    final Set<String> allTableNames = Arrays
250      .stream(writeTableNames.split(Bytes.toString(tableSeparator))).collect(Collectors.toSet());
251
252    // create a map from column family to the compression algorithm
253    final Map<byte[], Algorithm> compressionMap = createFamilyCompressionMap(conf);
254    final Map<byte[], BloomType> bloomTypeMap = createFamilyBloomTypeMap(conf);
255    final Map<byte[], String> bloomParamMap = createFamilyBloomParamMap(conf);
256    final Map<byte[], Integer> blockSizeMap = createFamilyBlockSizeMap(conf);
257
258    String dataBlockEncodingStr = conf.get(DATABLOCK_ENCODING_OVERRIDE_CONF_KEY);
259    final Map<byte[], DataBlockEncoding> datablockEncodingMap =
260      createFamilyDataBlockEncodingMap(conf);
261    final DataBlockEncoding overriddenEncoding =
262      dataBlockEncodingStr != null ? DataBlockEncoding.valueOf(dataBlockEncodingStr) : null;
263
264    return new RecordWriter<ImmutableBytesWritable, V>() {
265      // Map of families to writers and how much has been output on the writer.
266      private final Map<byte[], WriterLength> writers = new TreeMap<>(Bytes.BYTES_COMPARATOR);
267      private final Map<byte[], byte[]> previousRows = new TreeMap<>(Bytes.BYTES_COMPARATOR);
268      private final long now = EnvironmentEdgeManager.currentTime();
269      private byte[] tableNameBytes = writeMultipleTables ? null : Bytes.toBytes(writeTableNames);
270
271      @Override
272      public void write(ImmutableBytesWritable row, V cell) throws IOException {
273        Cell kv = cell;
274        // null input == user explicitly wants to flush
275        if (row == null && kv == null) {
276          rollWriters(null);
277          return;
278        }
279
280        byte[] rowKey = CellUtil.cloneRow(kv);
281        int length = (PrivateCellUtil.estimatedSerializedSizeOf(kv)) - Bytes.SIZEOF_INT;
282        byte[] family = CellUtil.cloneFamily(kv);
283        if (writeMultipleTables) {
284          tableNameBytes = MultiTableHFileOutputFormat.getTableName(row.get());
285          tableNameBytes = writeToTableWithNamespace
286            ? TableName.valueOf(tableNameBytes).getNameWithNamespaceInclAsString()
287              .getBytes(Charset.defaultCharset())
288            : TableName.valueOf(tableNameBytes).toBytes();
289          if (!allTableNames.contains(Bytes.toString(tableNameBytes))) {
290            throw new IllegalArgumentException(
291              "TableName " + Bytes.toString(tableNameBytes) + " not expected");
292          }
293        }
294        byte[] tableAndFamily = getTableNameSuffixedWithFamily(tableNameBytes, family);
295
296        WriterLength wl = this.writers.get(tableAndFamily);
297
298        // If this is a new column family, verify that the directory exists
299        if (wl == null) {
300          Path writerPath = null;
301          if (writeMultipleTables) {
302            Path tableRelPath = getTableRelativePath(tableNameBytes);
303            writerPath = new Path(outputDir, new Path(tableRelPath, Bytes.toString(family)));
304          } else {
305            writerPath = new Path(outputDir, Bytes.toString(family));
306          }
307          fs.mkdirs(writerPath);
308          configureStoragePolicy(conf, fs, tableAndFamily, writerPath);
309        }
310
311        // This can only happen once a row is finished though
312        if (
313          wl != null && wl.written + length >= maxsize
314            && Bytes.compareTo(this.previousRows.get(family), rowKey) != 0
315        ) {
316          rollWriters(wl);
317        }
318
319        // create a new WAL writer, if necessary
320        if (wl == null || wl.writer == null) {
321          InetSocketAddress[] favoredNodes = null;
322          if (conf.getBoolean(LOCALITY_SENSITIVE_CONF_KEY, DEFAULT_LOCALITY_SENSITIVE)) {
323            HRegionLocation loc = null;
324            String tableName = Bytes.toString(tableNameBytes);
325            if (tableName != null) {
326              try (
327                Connection connection =
328                  ConnectionFactory.createConnection(createRemoteClusterConf(conf));
329                RegionLocator locator = connection.getRegionLocator(TableName.valueOf(tableName))) {
330                loc = locator.getRegionLocation(rowKey);
331              } catch (Throwable e) {
332                LOG.warn("Something wrong locating rowkey {} in {}", Bytes.toString(rowKey),
333                  tableName, e);
334                loc = null;
335              }
336            }
337            if (null == loc) {
338              LOG.trace("Failed get of location, use default writer {}", Bytes.toString(rowKey));
339            } else {
340              LOG.debug("First rowkey: [{}]", Bytes.toString(rowKey));
341              InetSocketAddress initialIsa =
342                new InetSocketAddress(loc.getHostname(), loc.getPort());
343              if (initialIsa.isUnresolved()) {
344                LOG.trace("Failed resolve address {}, use default writer", loc.getHostnamePort());
345              } else {
346                LOG.debug("Use favored nodes writer: {}", initialIsa.getHostString());
347                favoredNodes = new InetSocketAddress[] { initialIsa };
348              }
349            }
350          }
351          wl = getNewWriter(tableNameBytes, family, conf, favoredNodes);
352
353        }
354
355        // we now have the proper WAL writer. full steam ahead
356        PrivateCellUtil.updateLatestStamp(cell, this.now);
357        wl.writer.append(kv);
358        wl.written += length;
359
360        // Copy the row so we know when a row transition.
361        this.previousRows.put(family, rowKey);
362      }
363
364      private Path getTableRelativePath(byte[] tableNameBytes) {
365        String tableName = Bytes.toString(tableNameBytes);
366        String[] tableNameParts = tableName.split(":");
367        Path tableRelPath = new Path(tableNameParts[0]);
368        if (tableNameParts.length > 1) {
369          tableRelPath = new Path(tableRelPath, tableNameParts[1]);
370        }
371        return tableRelPath;
372      }
373
374      private void rollWriters(WriterLength writerLength) throws IOException {
375        if (writerLength != null) {
376          closeWriter(writerLength);
377        } else {
378          for (WriterLength wl : this.writers.values()) {
379            closeWriter(wl);
380          }
381        }
382      }
383
384      private void closeWriter(WriterLength wl) throws IOException {
385        if (wl.writer != null) {
386          LOG.info(
387            "Writer=" + wl.writer.getPath() + ((wl.written == 0) ? "" : ", wrote=" + wl.written));
388          close(wl.writer);
389          wl.writer = null;
390        }
391        wl.written = 0;
392      }
393
394      private Configuration createRemoteClusterConf(Configuration conf) {
395        final Configuration newConf = new Configuration(conf);
396
397        final String quorum = conf.get(REMOTE_CLUSTER_ZOOKEEPER_QUORUM_CONF_KEY);
398        final String clientPort = conf.get(REMOTE_CLUSTER_ZOOKEEPER_CLIENT_PORT_CONF_KEY);
399        final String parent = conf.get(REMOTE_CLUSTER_ZOOKEEPER_ZNODE_PARENT_CONF_KEY);
400
401        if (quorum != null && clientPort != null && parent != null) {
402          newConf.set(HConstants.ZOOKEEPER_QUORUM, quorum);
403          newConf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, Integer.parseInt(clientPort));
404          newConf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, parent);
405        }
406
407        for (Entry<String, String> entry : conf) {
408          String key = entry.getKey();
409          if (
410            REMOTE_CLUSTER_ZOOKEEPER_QUORUM_CONF_KEY.equals(key)
411              || REMOTE_CLUSTER_ZOOKEEPER_CLIENT_PORT_CONF_KEY.equals(key)
412              || REMOTE_CLUSTER_ZOOKEEPER_ZNODE_PARENT_CONF_KEY.equals(key)
413          ) {
414            // Handled them above
415            continue;
416          }
417
418          if (entry.getKey().startsWith(REMOTE_CLUSTER_CONF_PREFIX)) {
419            String originalKey = entry.getKey().substring(REMOTE_CLUSTER_CONF_PREFIX.length());
420            if (!originalKey.isEmpty()) {
421              newConf.set(originalKey, entry.getValue());
422            }
423          }
424        }
425
426        return newConf;
427      }
428
429      /*
430       * Create a new StoreFile.Writer.
431       * @return A WriterLength, containing a new StoreFile.Writer.
432       */
433      @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "BX_UNBOXING_IMMEDIATELY_REBOXED",
434          justification = "Not important")
435      private WriterLength getNewWriter(byte[] tableName, byte[] family, Configuration conf,
436        InetSocketAddress[] favoredNodes) throws IOException {
437        byte[] tableAndFamily = getTableNameSuffixedWithFamily(tableName, family);
438        Path familydir = new Path(outputDir, Bytes.toString(family));
439        if (writeMultipleTables) {
440          familydir =
441            new Path(outputDir, new Path(getTableRelativePath(tableName), Bytes.toString(family)));
442        }
443        WriterLength wl = new WriterLength();
444        Algorithm compression = overriddenCompression;
445        compression = compression == null ? compressionMap.get(tableAndFamily) : compression;
446        compression = compression == null ? defaultCompression : compression;
447        BloomType bloomType = bloomTypeMap.get(tableAndFamily);
448        bloomType = bloomType == null ? BloomType.NONE : bloomType;
449        String bloomParam = bloomParamMap.get(tableAndFamily);
450        if (bloomType == BloomType.ROWPREFIX_FIXED_LENGTH) {
451          conf.set(BloomFilterUtil.PREFIX_LENGTH_KEY, bloomParam);
452        }
453        Integer blockSize = blockSizeMap.get(tableAndFamily);
454        blockSize = blockSize == null ? HConstants.DEFAULT_BLOCKSIZE : blockSize;
455        DataBlockEncoding encoding = overriddenEncoding;
456        encoding = encoding == null ? datablockEncodingMap.get(tableAndFamily) : encoding;
457        encoding = encoding == null ? DataBlockEncoding.NONE : encoding;
458        HFileContextBuilder contextBuilder = new HFileContextBuilder().withCompression(compression)
459          .withDataBlockEncoding(encoding).withChecksumType(StoreUtils.getChecksumType(conf))
460          .withBytesPerCheckSum(StoreUtils.getBytesPerChecksum(conf)).withBlockSize(blockSize)
461          .withColumnFamily(family).withTableName(tableName)
462          .withCreateTime(EnvironmentEdgeManager.currentTime());
463
464        if (HFile.getFormatVersion(conf) >= HFile.MIN_FORMAT_VERSION_WITH_TAGS) {
465          contextBuilder.withIncludesTags(true);
466        }
467
468        HFileContext hFileContext = contextBuilder.build();
469        if (null == favoredNodes) {
470          wl.writer =
471            new StoreFileWriter.Builder(conf, CacheConfig.DISABLED, fs).withOutputDir(familydir)
472              .withBloomType(bloomType).withFileContext(hFileContext).build();
473        } else {
474          wl.writer = new StoreFileWriter.Builder(conf, CacheConfig.DISABLED, new HFileSystem(fs))
475            .withOutputDir(familydir).withBloomType(bloomType).withFileContext(hFileContext)
476            .withFavoredNodes(favoredNodes).build();
477        }
478
479        this.writers.put(tableAndFamily, wl);
480        return wl;
481      }
482
483      private void close(final StoreFileWriter w) throws IOException {
484        if (w != null) {
485          w.appendFileInfo(BULKLOAD_TIME_KEY, Bytes.toBytes(EnvironmentEdgeManager.currentTime()));
486          w.appendFileInfo(BULKLOAD_TASK_KEY, Bytes.toBytes(context.getTaskAttemptID().toString()));
487          w.appendFileInfo(MAJOR_COMPACTION_KEY, Bytes.toBytes(true));
488          w.appendFileInfo(EXCLUDE_FROM_MINOR_COMPACTION_KEY, Bytes.toBytes(compactionExclude));
489          w.appendTrackedTimestampsToMetadata();
490          w.close();
491        }
492      }
493
494      @Override
495      public void close(TaskAttemptContext c) throws IOException, InterruptedException {
496        for (WriterLength wl : this.writers.values()) {
497          close(wl.writer);
498        }
499      }
500    };
501  }
502
503  /**
504   * Configure block storage policy for CF after the directory is created.
505   */
506  static void configureStoragePolicy(final Configuration conf, final FileSystem fs,
507    byte[] tableAndFamily, Path cfPath) {
508    if (null == conf || null == fs || null == tableAndFamily || null == cfPath) {
509      return;
510    }
511
512    String policy = conf.get(STORAGE_POLICY_PROPERTY_CF_PREFIX + Bytes.toString(tableAndFamily),
513      conf.get(STORAGE_POLICY_PROPERTY));
514    CommonFSUtils.setStoragePolicy(fs, cfPath, policy);
515  }
516
517  /*
518   * Data structure to hold a Writer and amount of data written on it.
519   */
520  static class WriterLength {
521    long written = 0;
522    StoreFileWriter writer = null;
523  }
524
525  /**
526   * Return the start keys of all of the regions in this table, as a list of ImmutableBytesWritable.
527   */
528  private static List<ImmutableBytesWritable> getRegionStartKeys(List<RegionLocator> regionLocators,
529    boolean writeMultipleTables) throws IOException {
530
531    ArrayList<ImmutableBytesWritable> ret = new ArrayList<>();
532    for (RegionLocator regionLocator : regionLocators) {
533      TableName tableName = regionLocator.getName();
534      LOG.info("Looking up current regions for table " + tableName);
535      byte[][] byteKeys = regionLocator.getStartKeys();
536      for (byte[] byteKey : byteKeys) {
537        byte[] fullKey = byteKey; // HFileOutputFormat2 use case
538        if (writeMultipleTables) {
539          // MultiTableHFileOutputFormat use case
540          fullKey = combineTableNameSuffix(tableName.getName(), byteKey);
541        }
542        if (LOG.isDebugEnabled()) {
543          LOG.debug("SplitPoint startkey for " + tableName + ": " + Bytes.toStringBinary(fullKey));
544        }
545        ret.add(new ImmutableBytesWritable(fullKey));
546      }
547    }
548    return ret;
549  }
550
551  /**
552   * Write out a {@link SequenceFile} that can be read by {@link TotalOrderPartitioner} that
553   * contains the split points in startKeys.
554   */
555  @SuppressWarnings("deprecation")
556  private static void writePartitions(Configuration conf, Path partitionsPath,
557    List<ImmutableBytesWritable> startKeys, boolean writeMultipleTables) throws IOException {
558    LOG.info("Writing partition information to " + partitionsPath);
559    if (startKeys.isEmpty()) {
560      throw new IllegalArgumentException("No regions passed");
561    }
562
563    // We're generating a list of split points, and we don't ever
564    // have keys < the first region (which has an empty start key)
565    // so we need to remove it. Otherwise we would end up with an
566    // empty reducer with index 0
567    TreeSet<ImmutableBytesWritable> sorted = new TreeSet<>(startKeys);
568    ImmutableBytesWritable first = sorted.first();
569    if (writeMultipleTables) {
570      first =
571        new ImmutableBytesWritable(MultiTableHFileOutputFormat.getSuffix(sorted.first().get()));
572    }
573    if (!first.equals(HConstants.EMPTY_BYTE_ARRAY)) {
574      throw new IllegalArgumentException(
575        "First region of table should have empty start key. Instead has: "
576          + Bytes.toStringBinary(first.get()));
577    }
578    sorted.remove(sorted.first());
579
580    // Write the actual file
581    FileSystem fs = partitionsPath.getFileSystem(conf);
582    SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, partitionsPath,
583      ImmutableBytesWritable.class, NullWritable.class);
584
585    try {
586      for (ImmutableBytesWritable startKey : sorted) {
587        writer.append(startKey, NullWritable.get());
588      }
589    } finally {
590      writer.close();
591    }
592  }
593
594  /**
595   * Configure a MapReduce Job to perform an incremental load into the given table. This
596   * <ul>
597   * <li>Inspects the table to configure a total order partitioner</li>
598   * <li>Uploads the partitions file to the cluster and adds it to the DistributedCache</li>
599   * <li>Sets the number of reduce tasks to match the current number of regions</li>
600   * <li>Sets the output key/value class to match HFileOutputFormat2's requirements</li>
601   * <li>Sets the reducer up to perform the appropriate sorting (either KeyValueSortReducer or
602   * PutSortReducer)</li>
603   * <li>Sets the HBase cluster key to load region locations for locality-sensitive</li>
604   * </ul>
605   * The user should be sure to set the map output value class to either KeyValue or Put before
606   * running this function.
607   */
608  public static void configureIncrementalLoad(Job job, Table table, RegionLocator regionLocator)
609    throws IOException {
610    configureIncrementalLoad(job, table.getDescriptor(), regionLocator);
611    configureRemoteCluster(job, table.getConfiguration());
612  }
613
614  /**
615   * Configure a MapReduce Job to perform an incremental load into the given table. This
616   * <ul>
617   * <li>Inspects the table to configure a total order partitioner</li>
618   * <li>Uploads the partitions file to the cluster and adds it to the DistributedCache</li>
619   * <li>Sets the number of reduce tasks to match the current number of regions</li>
620   * <li>Sets the output key/value class to match HFileOutputFormat2's requirements</li>
621   * <li>Sets the reducer up to perform the appropriate sorting (either KeyValueSortReducer or
622   * PutSortReducer)</li>
623   * </ul>
624   * The user should be sure to set the map output value class to either KeyValue or Put before
625   * running this function.
626   */
627  public static void configureIncrementalLoad(Job job, TableDescriptor tableDescriptor,
628    RegionLocator regionLocator) throws IOException {
629    ArrayList<TableInfo> singleTableInfo = new ArrayList<>();
630    singleTableInfo.add(new TableInfo(tableDescriptor, regionLocator));
631    configureIncrementalLoad(job, singleTableInfo, HFileOutputFormat2.class);
632  }
633
634  static void configureIncrementalLoad(Job job, List<TableInfo> multiTableInfo,
635    Class<? extends OutputFormat<?, ?>> cls) throws IOException {
636    Configuration conf = job.getConfiguration();
637    job.setOutputKeyClass(ImmutableBytesWritable.class);
638    job.setOutputValueClass(MapReduceExtendedCell.class);
639    job.setOutputFormatClass(cls);
640
641    final boolean writeToTableWithNamespace = conf.getBoolean(
642      TABLE_NAME_WITH_NAMESPACE_INCLUSIVE_KEY, TABLE_NAME_WITH_NAMESPACE_INCLUSIVE_DEFAULT_VALUE);
643
644    if (multiTableInfo.stream().distinct().count() != multiTableInfo.size()) {
645      throw new IllegalArgumentException("Duplicate entries found in TableInfo argument");
646    }
647    boolean writeMultipleTables = false;
648    if (MultiTableHFileOutputFormat.class.equals(cls)) {
649      writeMultipleTables = true;
650      conf.setBoolean(MULTI_TABLE_HFILEOUTPUTFORMAT_CONF_KEY, true);
651    }
652    // Based on the configured map output class, set the correct reducer to properly
653    // sort the incoming values.
654    // TODO it would be nice to pick one or the other of these formats.
655    if (
656      KeyValue.class.equals(job.getMapOutputValueClass())
657        || MapReduceExtendedCell.class.equals(job.getMapOutputValueClass())
658    ) {
659      job.setReducerClass(CellSortReducer.class);
660    } else if (Put.class.equals(job.getMapOutputValueClass())) {
661      job.setReducerClass(PutSortReducer.class);
662    } else if (Text.class.equals(job.getMapOutputValueClass())) {
663      job.setReducerClass(TextSortReducer.class);
664    } else {
665      LOG.warn("Unknown map output value type:" + job.getMapOutputValueClass());
666    }
667
668    mergeSerializations(conf);
669
670    if (conf.getBoolean(LOCALITY_SENSITIVE_CONF_KEY, DEFAULT_LOCALITY_SENSITIVE)) {
671      LOG.info("bulkload locality sensitive enabled");
672    }
673
674    /* Now get the region start keys for every table required */
675    List<String> allTableNames = new ArrayList<>(multiTableInfo.size());
676    List<RegionLocator> regionLocators = new ArrayList<>(multiTableInfo.size());
677    List<TableDescriptor> tableDescriptors = new ArrayList<>(multiTableInfo.size());
678
679    for (TableInfo tableInfo : multiTableInfo) {
680      regionLocators.add(tableInfo.getRegionLocator());
681      allTableNames.add(writeMultipleTables && writeToTableWithNamespace
682        ? tableInfo.getRegionLocator().getName().getNameWithNamespaceInclAsString()
683        : tableInfo.getRegionLocator().getName().getNameAsString());
684      tableDescriptors.add(tableInfo.getTableDescriptor());
685    }
686    // Record tablenames for creating writer by favored nodes, and decoding compression,
687    // block size and other attributes of columnfamily per table
688    conf.set(OUTPUT_TABLE_NAME_CONF_KEY,
689      StringUtils.join(allTableNames, Bytes.toString(tableSeparator)));
690    List<ImmutableBytesWritable> startKeys =
691      getRegionStartKeys(regionLocators, writeMultipleTables);
692    // Use table's region boundaries for TOP split points.
693    LOG.info("Configuring " + startKeys.size() + " reduce partitions "
694      + "to match current region count for all tables");
695    job.setNumReduceTasks(startKeys.size());
696
697    configurePartitioner(job, startKeys, writeMultipleTables);
698    // Set compression algorithms based on column families
699
700    conf.set(COMPRESSION_FAMILIES_CONF_KEY,
701      serializeColumnFamilyAttribute(compressionDetails, tableDescriptors));
702    conf.set(BLOCK_SIZE_FAMILIES_CONF_KEY,
703      serializeColumnFamilyAttribute(blockSizeDetails, tableDescriptors));
704    conf.set(BLOOM_TYPE_FAMILIES_CONF_KEY,
705      serializeColumnFamilyAttribute(bloomTypeDetails, tableDescriptors));
706    conf.set(BLOOM_PARAM_FAMILIES_CONF_KEY,
707      serializeColumnFamilyAttribute(bloomParamDetails, tableDescriptors));
708    conf.set(DATABLOCK_ENCODING_FAMILIES_CONF_KEY,
709      serializeColumnFamilyAttribute(dataBlockEncodingDetails, tableDescriptors));
710
711    TableMapReduceUtil.addDependencyJars(job);
712    TableMapReduceUtil.initCredentials(job);
713    LOG.info("Incremental output configured for tables: " + StringUtils.join(allTableNames, ","));
714  }
715
716  private static void mergeSerializations(Configuration conf) {
717    List<String> serializations = new ArrayList<>();
718
719    // add any existing values that have been set
720    String[] existing = conf.getStrings("io.serializations");
721    if (existing != null) {
722      Collections.addAll(serializations, existing);
723    }
724
725    serializations.add(MutationSerialization.class.getName());
726    serializations.add(ResultSerialization.class.getName());
727
728    // Add ExtendedCellSerialization, if configured. Order matters here. Hadoop's
729    // SerializationFactory runs through serializations in the order they are registered.
730    // We want to register ExtendedCellSerialization before CellSerialization because both
731    // work for ExtendedCells but only ExtendedCellSerialization handles them properly.
732    if (
733      conf.getBoolean(EXTENDED_CELL_SERIALIZATION_ENABLED_KEY,
734        EXTENDED_CELL_SERIALIZATION_ENABLED_DEFULT)
735    ) {
736      serializations.add(ExtendedCellSerialization.class.getName());
737    }
738    serializations.add(CellSerialization.class.getName());
739
740    conf.setStrings("io.serializations", serializations.toArray(new String[0]));
741  }
742
743  public static void configureIncrementalLoadMap(Job job, TableDescriptor tableDescriptor)
744    throws IOException {
745    Configuration conf = job.getConfiguration();
746
747    job.setOutputKeyClass(ImmutableBytesWritable.class);
748    job.setOutputValueClass(MapReduceExtendedCell.class);
749    job.setOutputFormatClass(HFileOutputFormat2.class);
750
751    ArrayList<TableDescriptor> singleTableDescriptor = new ArrayList<>(1);
752    singleTableDescriptor.add(tableDescriptor);
753
754    conf.set(OUTPUT_TABLE_NAME_CONF_KEY, tableDescriptor.getTableName().getNameAsString());
755    // Set compression algorithms based on column families
756    conf.set(COMPRESSION_FAMILIES_CONF_KEY,
757      serializeColumnFamilyAttribute(compressionDetails, singleTableDescriptor));
758    conf.set(BLOCK_SIZE_FAMILIES_CONF_KEY,
759      serializeColumnFamilyAttribute(blockSizeDetails, singleTableDescriptor));
760    conf.set(BLOOM_TYPE_FAMILIES_CONF_KEY,
761      serializeColumnFamilyAttribute(bloomTypeDetails, singleTableDescriptor));
762    conf.set(BLOOM_PARAM_FAMILIES_CONF_KEY,
763      serializeColumnFamilyAttribute(bloomParamDetails, singleTableDescriptor));
764    conf.set(DATABLOCK_ENCODING_FAMILIES_CONF_KEY,
765      serializeColumnFamilyAttribute(dataBlockEncodingDetails, singleTableDescriptor));
766
767    TableMapReduceUtil.addDependencyJars(job);
768    TableMapReduceUtil.initCredentials(job);
769    LOG.info("Incremental table " + tableDescriptor.getTableName() + " output configured.");
770  }
771
772  /**
773   * Configure HBase cluster key for remote cluster to load region location for locality-sensitive
774   * if it's enabled. It's not necessary to call this method explicitly when the cluster key for
775   * HBase cluster to be used to load region location is configured in the job configuration. Call
776   * this method when another HBase cluster key is configured in the job configuration. For example,
777   * you should call when you load data from HBase cluster A using {@link TableInputFormat} and
778   * generate hfiles for HBase cluster B. Otherwise, HFileOutputFormat2 fetch location from cluster
779   * A and locality-sensitive won't working correctly.
780   * {@link #configureIncrementalLoad(Job, Table, RegionLocator)} calls this method using
781   * {@link Table#getConfiguration} as clusterConf. See HBASE-25608.
782   * @param job         which has configuration to be updated
783   * @param clusterConf which contains cluster key of the HBase cluster to be locality-sensitive
784   * @see #configureIncrementalLoad(Job, Table, RegionLocator)
785   * @see #LOCALITY_SENSITIVE_CONF_KEY
786   * @see #REMOTE_CLUSTER_ZOOKEEPER_QUORUM_CONF_KEY
787   * @see #REMOTE_CLUSTER_ZOOKEEPER_CLIENT_PORT_CONF_KEY
788   * @see #REMOTE_CLUSTER_ZOOKEEPER_ZNODE_PARENT_CONF_KEY
789   */
790  public static void configureRemoteCluster(Job job, Configuration clusterConf) {
791    Configuration conf = job.getConfiguration();
792
793    if (!conf.getBoolean(LOCALITY_SENSITIVE_CONF_KEY, DEFAULT_LOCALITY_SENSITIVE)) {
794      return;
795    }
796
797    final String quorum = clusterConf.get(HConstants.ZOOKEEPER_QUORUM);
798    final int clientPort = clusterConf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT,
799      HConstants.DEFAULT_ZOOKEEPER_CLIENT_PORT);
800    final String parent =
801      clusterConf.get(HConstants.ZOOKEEPER_ZNODE_PARENT, HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
802
803    conf.set(REMOTE_CLUSTER_ZOOKEEPER_QUORUM_CONF_KEY, quorum);
804    conf.setInt(REMOTE_CLUSTER_ZOOKEEPER_CLIENT_PORT_CONF_KEY, clientPort);
805    conf.set(REMOTE_CLUSTER_ZOOKEEPER_ZNODE_PARENT_CONF_KEY, parent);
806
807    LOG.info("ZK configs for remote cluster of bulkload is configured: " + quorum + ":" + clientPort
808      + "/" + parent);
809  }
810
811  /**
812   * Runs inside the task to deserialize column family to compression algorithm map from the
813   * configuration.
814   * @param conf to read the serialized values from
815   * @return a map from column family to the configured compression algorithm
816   */
817  @InterfaceAudience.Private
818  static Map<byte[], Algorithm> createFamilyCompressionMap(Configuration conf) {
819    Map<byte[], String> stringMap = createFamilyConfValueMap(conf, COMPRESSION_FAMILIES_CONF_KEY);
820    Map<byte[], Algorithm> compressionMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
821    for (Map.Entry<byte[], String> e : stringMap.entrySet()) {
822      Algorithm algorithm = HFileWriterImpl.compressionByName(e.getValue());
823      compressionMap.put(e.getKey(), algorithm);
824    }
825    return compressionMap;
826  }
827
828  /**
829   * Runs inside the task to deserialize column family to bloom filter type map from the
830   * configuration.
831   * @param conf to read the serialized values from
832   * @return a map from column family to the the configured bloom filter type
833   */
834  @InterfaceAudience.Private
835  static Map<byte[], BloomType> createFamilyBloomTypeMap(Configuration conf) {
836    Map<byte[], String> stringMap = createFamilyConfValueMap(conf, BLOOM_TYPE_FAMILIES_CONF_KEY);
837    Map<byte[], BloomType> bloomTypeMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
838    for (Map.Entry<byte[], String> e : stringMap.entrySet()) {
839      BloomType bloomType = BloomType.valueOf(e.getValue());
840      bloomTypeMap.put(e.getKey(), bloomType);
841    }
842    return bloomTypeMap;
843  }
844
845  /**
846   * Runs inside the task to deserialize column family to bloom filter param map from the
847   * configuration.
848   * @param conf to read the serialized values from
849   * @return a map from column family to the the configured bloom filter param
850   */
851  @InterfaceAudience.Private
852  static Map<byte[], String> createFamilyBloomParamMap(Configuration conf) {
853    return createFamilyConfValueMap(conf, BLOOM_PARAM_FAMILIES_CONF_KEY);
854  }
855
856  /**
857   * Runs inside the task to deserialize column family to block size map from the configuration.
858   * @param conf to read the serialized values from
859   * @return a map from column family to the configured block size
860   */
861  @InterfaceAudience.Private
862  static Map<byte[], Integer> createFamilyBlockSizeMap(Configuration conf) {
863    Map<byte[], String> stringMap = createFamilyConfValueMap(conf, BLOCK_SIZE_FAMILIES_CONF_KEY);
864    Map<byte[], Integer> blockSizeMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
865    for (Map.Entry<byte[], String> e : stringMap.entrySet()) {
866      Integer blockSize = Integer.parseInt(e.getValue());
867      blockSizeMap.put(e.getKey(), blockSize);
868    }
869    return blockSizeMap;
870  }
871
872  /**
873   * Runs inside the task to deserialize column family to data block encoding type map from the
874   * configuration.
875   * @param conf to read the serialized values from
876   * @return a map from column family to HFileDataBlockEncoder for the configured data block type
877   *         for the family
878   */
879  @InterfaceAudience.Private
880  static Map<byte[], DataBlockEncoding> createFamilyDataBlockEncodingMap(Configuration conf) {
881    Map<byte[], String> stringMap =
882      createFamilyConfValueMap(conf, DATABLOCK_ENCODING_FAMILIES_CONF_KEY);
883    Map<byte[], DataBlockEncoding> encoderMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
884    for (Map.Entry<byte[], String> e : stringMap.entrySet()) {
885      encoderMap.put(e.getKey(), DataBlockEncoding.valueOf((e.getValue())));
886    }
887    return encoderMap;
888  }
889
890  /**
891   * Run inside the task to deserialize column family to given conf value map.
892   * @param conf     to read the serialized values from
893   * @param confName conf key to read from the configuration
894   * @return a map of column family to the given configuration value
895   */
896  private static Map<byte[], String> createFamilyConfValueMap(Configuration conf, String confName) {
897    Map<byte[], String> confValMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
898    String confVal = conf.get(confName, "");
899    for (String familyConf : confVal.split("&")) {
900      String[] familySplit = familyConf.split("=");
901      if (familySplit.length != 2) {
902        continue;
903      }
904      try {
905        confValMap.put(Bytes.toBytes(URLDecoder.decode(familySplit[0], "UTF-8")),
906          URLDecoder.decode(familySplit[1], "UTF-8"));
907      } catch (UnsupportedEncodingException e) {
908        // will not happen with UTF-8 encoding
909        throw new AssertionError(e);
910      }
911    }
912    return confValMap;
913  }
914
915  /**
916   * Configure <code>job</code> with a TotalOrderPartitioner, partitioning against
917   * <code>splitPoints</code>. Cleans up the partitions file after job exists.
918   */
919  static void configurePartitioner(Job job, List<ImmutableBytesWritable> splitPoints,
920    boolean writeMultipleTables) throws IOException {
921    Configuration conf = job.getConfiguration();
922    // create the partitions file
923    FileSystem fs = FileSystem.get(conf);
924    String hbaseTmpFsDir =
925      conf.get(HConstants.TEMPORARY_FS_DIRECTORY_KEY, HConstants.DEFAULT_TEMPORARY_HDFS_DIRECTORY);
926    Path partitionsPath = new Path(hbaseTmpFsDir, "partitions_" + UUID.randomUUID());
927    fs.makeQualified(partitionsPath);
928    writePartitions(conf, partitionsPath, splitPoints, writeMultipleTables);
929    fs.deleteOnExit(partitionsPath);
930
931    // configure job to use it
932    job.setPartitionerClass(TotalOrderPartitioner.class);
933    TotalOrderPartitioner.setPartitionFile(conf, partitionsPath);
934  }
935
936  @edu.umd.cs.findbugs.annotations.SuppressWarnings(
937      value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
938  @InterfaceAudience.Private
939  static String serializeColumnFamilyAttribute(Function<ColumnFamilyDescriptor, String> fn,
940    List<TableDescriptor> allTables) throws UnsupportedEncodingException {
941    StringBuilder attributeValue = new StringBuilder();
942    int i = 0;
943    for (TableDescriptor tableDescriptor : allTables) {
944      if (tableDescriptor == null) {
945        // could happen with mock table instance
946        // CODEREVIEW: Can I set an empty string in conf if mock table instance?
947        return "";
948      }
949      for (ColumnFamilyDescriptor familyDescriptor : tableDescriptor.getColumnFamilies()) {
950        if (i++ > 0) {
951          attributeValue.append('&');
952        }
953        attributeValue.append(URLEncoder
954          .encode(Bytes.toString(combineTableNameSuffix(tableDescriptor.getTableName().getName(),
955            familyDescriptor.getName())), "UTF-8"));
956        attributeValue.append('=');
957        attributeValue.append(URLEncoder.encode(fn.apply(familyDescriptor), "UTF-8"));
958      }
959    }
960    // Get rid of the last ampersand
961    return attributeValue.toString();
962  }
963
964  /**
965   * Serialize column family to compression algorithm map to configuration. Invoked while
966   * configuring the MR job for incremental load.
967   */
968  @InterfaceAudience.Private
969  static Function<ColumnFamilyDescriptor, String> compressionDetails =
970    familyDescriptor -> familyDescriptor.getCompressionType().getName();
971
972  /**
973   * Serialize column family to block size map to configuration. Invoked while configuring the MR
974   * job for incremental load.
975   */
976  @InterfaceAudience.Private
977  static Function<ColumnFamilyDescriptor, String> blockSizeDetails =
978    familyDescriptor -> String.valueOf(familyDescriptor.getBlocksize());
979
980  /**
981   * Serialize column family to bloom type map to configuration. Invoked while configuring the MR
982   * job for incremental load.
983   */
984  @InterfaceAudience.Private
985  static Function<ColumnFamilyDescriptor, String> bloomTypeDetails = familyDescriptor -> {
986    String bloomType = familyDescriptor.getBloomFilterType().toString();
987    if (bloomType == null) {
988      bloomType = ColumnFamilyDescriptorBuilder.DEFAULT_BLOOMFILTER.name();
989    }
990    return bloomType;
991  };
992
993  /**
994   * Serialize column family to bloom param map to configuration. Invoked while configuring the MR
995   * job for incremental load.
996   */
997  @InterfaceAudience.Private
998  static Function<ColumnFamilyDescriptor, String> bloomParamDetails = familyDescriptor -> {
999    BloomType bloomType = familyDescriptor.getBloomFilterType();
1000    String bloomParam = "";
1001    if (bloomType == BloomType.ROWPREFIX_FIXED_LENGTH) {
1002      bloomParam = familyDescriptor.getConfigurationValue(BloomFilterUtil.PREFIX_LENGTH_KEY);
1003    }
1004    return bloomParam;
1005  };
1006
1007  /**
1008   * Serialize column family to data block encoding map to configuration. Invoked while configuring
1009   * the MR job for incremental load.
1010   */
1011  @InterfaceAudience.Private
1012  static Function<ColumnFamilyDescriptor, String> dataBlockEncodingDetails = familyDescriptor -> {
1013    DataBlockEncoding encoding = familyDescriptor.getDataBlockEncoding();
1014    if (encoding == null) {
1015      encoding = DataBlockEncoding.NONE;
1016    }
1017    return encoding.toString();
1018  };
1019
1020}