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.mapreduce;
20  
21  import java.io.IOException;
22  import java.io.UnsupportedEncodingException;
23  import java.net.URLDecoder;
24  import java.net.URLEncoder;
25  import java.util.ArrayList;
26  import java.util.Collection;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.TreeMap;
30  import java.util.TreeSet;
31  import java.util.UUID;
32  
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.apache.hadoop.classification.InterfaceAudience;
36  import org.apache.hadoop.classification.InterfaceStability;
37  import org.apache.hadoop.conf.Configuration;
38  import org.apache.hadoop.fs.FileSystem;
39  import org.apache.hadoop.fs.Path;
40  import org.apache.hadoop.hbase.HColumnDescriptor;
41  import org.apache.hadoop.hbase.HConstants;
42  import org.apache.hadoop.hbase.HTableDescriptor;
43  import org.apache.hadoop.hbase.KeyValue;
44  import org.apache.hadoop.hbase.client.HTable;
45  import org.apache.hadoop.hbase.client.Put;
46  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
47  import org.apache.hadoop.hbase.io.compress.Compression;
48  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
49  import org.apache.hadoop.hbase.io.hfile.AbstractHFileWriter;
50  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
51  import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder;
52  import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoderImpl;
53  import org.apache.hadoop.hbase.io.hfile.NoOpDataBlockEncoder;
54  import org.apache.hadoop.hbase.regionserver.BloomType;
55  import org.apache.hadoop.hbase.regionserver.HStore;
56  import org.apache.hadoop.hbase.regionserver.StoreFile;
57  import org.apache.hadoop.hbase.util.Bytes;
58  import org.apache.hadoop.io.NullWritable;
59  import org.apache.hadoop.io.SequenceFile;
60  import org.apache.hadoop.io.Text;
61  import org.apache.hadoop.mapreduce.Job;
62  import org.apache.hadoop.mapreduce.RecordWriter;
63  import org.apache.hadoop.mapreduce.TaskAttemptContext;
64  import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
65  import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
66  import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
67  
68  /**
69   * Writes HFiles. Passed KeyValues must arrive in order.
70   * Writes current time as the sequence id for the file. Sets the major compacted
71   * attribute on created hfiles. Calling write(null,null) will forceably roll
72   * all HFiles being written.
73   * <p>
74   * Using this class as part of a MapReduce job is best done
75   * using {@link #configureIncrementalLoad(Job, HTable)}.
76   * @see KeyValueSortReducer
77   */
78  @InterfaceAudience.Public
79  @InterfaceStability.Stable
80  public class HFileOutputFormat extends FileOutputFormat<ImmutableBytesWritable, KeyValue> {
81    static Log LOG = LogFactory.getLog(HFileOutputFormat.class);
82    static final String COMPRESSION_CONF_KEY = "hbase.hfileoutputformat.families.compression";
83    private static final String BLOOM_TYPE_CONF_KEY = "hbase.hfileoutputformat.families.bloomtype";
84    private static final String DATABLOCK_ENCODING_CONF_KEY =
85       "hbase.mapreduce.hfileoutputformat.datablock.encoding";
86    private static final String BLOCK_SIZE_CONF_KEY = "hbase.mapreduce.hfileoutputformat.blocksize";
87  
88    public RecordWriter<ImmutableBytesWritable, KeyValue> getRecordWriter(final TaskAttemptContext context)
89    throws IOException, InterruptedException {
90      // Get the path of the temporary output file
91      final Path outputPath = FileOutputFormat.getOutputPath(context);
92      final Path outputdir = new FileOutputCommitter(outputPath, context).getWorkPath();
93      final Configuration conf = context.getConfiguration();
94      final FileSystem fs = outputdir.getFileSystem(conf);
95      // These configs. are from hbase-*.xml
96      final long maxsize = conf.getLong(HConstants.HREGION_MAX_FILESIZE,
97          HConstants.DEFAULT_MAX_FILE_SIZE);
98      // Invented config.  Add to hbase-*.xml if other than default compression.
99      final String defaultCompression = conf.get("hfile.compression",
100         Compression.Algorithm.NONE.getName());
101     final boolean compactionExclude = conf.getBoolean(
102         "hbase.mapreduce.hfileoutputformat.compaction.exclude", false);
103 
104     // create a map from column family to the compression algorithm
105     final Map<byte[], String> compressionMap = createFamilyCompressionMap(conf);
106     final Map<byte[], String> bloomTypeMap = createFamilyBloomMap(conf);
107     final Map<byte[], String> blockSizeMap = createFamilyBlockSizeMap(conf);
108 
109     String dataBlockEncodingStr = conf.get(DATABLOCK_ENCODING_CONF_KEY);
110     final HFileDataBlockEncoder encoder;
111     if (dataBlockEncodingStr == null) {
112       encoder = NoOpDataBlockEncoder.INSTANCE;
113     } else {
114       try {
115         encoder = new HFileDataBlockEncoderImpl(DataBlockEncoding
116             .valueOf(dataBlockEncodingStr));
117       } catch (IllegalArgumentException ex) {
118         throw new RuntimeException(
119             "Invalid data block encoding type configured for the param "
120                 + DATABLOCK_ENCODING_CONF_KEY + " : " + dataBlockEncodingStr);
121       }
122     }
123 
124     return new RecordWriter<ImmutableBytesWritable, KeyValue>() {
125       // Map of families to writers and how much has been output on the writer.
126       private final Map<byte [], WriterLength> writers =
127         new TreeMap<byte [], WriterLength>(Bytes.BYTES_COMPARATOR);
128       private byte [] previousRow = HConstants.EMPTY_BYTE_ARRAY;
129       private final byte [] now = Bytes.toBytes(System.currentTimeMillis());
130       private boolean rollRequested = false;
131 
132       public void write(ImmutableBytesWritable row, KeyValue kv)
133       throws IOException {
134         // null input == user explicitly wants to flush
135         if (row == null && kv == null) {
136           rollWriters();
137           return;
138         }
139 
140         byte [] rowKey = kv.getRow();
141         long length = kv.getLength();
142         byte [] family = kv.getFamily();
143         WriterLength wl = this.writers.get(family);
144 
145         // If this is a new column family, verify that the directory exists
146         if (wl == null) {
147           fs.mkdirs(new Path(outputdir, Bytes.toString(family)));
148         }
149 
150         // If any of the HFiles for the column families has reached
151         // maxsize, we need to roll all the writers
152         if (wl != null && wl.written + length >= maxsize) {
153           this.rollRequested = true;
154         }
155 
156         // This can only happen once a row is finished though
157         if (rollRequested && Bytes.compareTo(this.previousRow, rowKey) != 0) {
158           rollWriters();
159         }
160 
161         // create a new HLog writer, if necessary
162         if (wl == null || wl.writer == null) {
163           wl = getNewWriter(family, conf);
164         }
165 
166         // we now have the proper HLog writer. full steam ahead
167         kv.updateLatestStamp(this.now);
168         wl.writer.append(kv);
169         wl.written += length;
170 
171         // Copy the row so we know when a row transition.
172         this.previousRow = rowKey;
173       }
174 
175       private void rollWriters() throws IOException {
176         for (WriterLength wl : this.writers.values()) {
177           if (wl.writer != null) {
178             LOG.info("Writer=" + wl.writer.getPath() +
179                 ((wl.written == 0)? "": ", wrote=" + wl.written));
180             close(wl.writer);
181           }
182           wl.writer = null;
183           wl.written = 0;
184         }
185         this.rollRequested = false;
186       }
187 
188       /* Create a new StoreFile.Writer.
189        * @param family
190        * @return A WriterLength, containing a new StoreFile.Writer.
191        * @throws IOException
192        */
193       private WriterLength getNewWriter(byte[] family, Configuration conf)
194           throws IOException {
195         WriterLength wl = new WriterLength();
196         Path familydir = new Path(outputdir, Bytes.toString(family));
197         String compression = compressionMap.get(family);
198         compression = compression == null ? defaultCompression : compression;
199         String bloomTypeStr = bloomTypeMap.get(family);
200         BloomType bloomType = BloomType.NONE;
201         if (bloomTypeStr != null) {
202           bloomType = BloomType.valueOf(bloomTypeStr);
203         }
204         String blockSizeString = blockSizeMap.get(family);
205         int blockSize = blockSizeString == null ? HConstants.DEFAULT_BLOCKSIZE
206             : Integer.parseInt(blockSizeString);
207         Configuration tempConf = new Configuration(conf);
208         tempConf.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0.0f);
209         wl.writer = new StoreFile.WriterBuilder(conf, new CacheConfig(tempConf), fs, blockSize)
210             .withOutputDir(familydir)
211             .withCompression(AbstractHFileWriter.compressionByName(compression))
212             .withBloomType(bloomType)
213             .withComparator(KeyValue.COMPARATOR)
214             .withDataBlockEncoder(encoder)
215             .withChecksumType(HStore.getChecksumType(conf))
216             .withBytesPerChecksum(HStore.getBytesPerChecksum(conf))
217             .build();
218 
219         this.writers.put(family, wl);
220         return wl;
221       }
222 
223       private void close(final StoreFile.Writer w) throws IOException {
224         if (w != null) {
225           w.appendFileInfo(StoreFile.BULKLOAD_TIME_KEY,
226               Bytes.toBytes(System.currentTimeMillis()));
227           w.appendFileInfo(StoreFile.BULKLOAD_TASK_KEY,
228               Bytes.toBytes(context.getTaskAttemptID().toString()));
229           w.appendFileInfo(StoreFile.MAJOR_COMPACTION_KEY,
230               Bytes.toBytes(true));
231           w.appendFileInfo(StoreFile.EXCLUDE_FROM_MINOR_COMPACTION_KEY,
232               Bytes.toBytes(compactionExclude));
233           w.appendTrackedTimestampsToMetadata();
234           w.close();
235         }
236       }
237 
238       public void close(TaskAttemptContext c)
239       throws IOException, InterruptedException {
240         for (WriterLength wl: this.writers.values()) {
241           close(wl.writer);
242         }
243       }
244     };
245   }
246 
247   /*
248    * Data structure to hold a Writer and amount of data written on it.
249    */
250   static class WriterLength {
251     long written = 0;
252     StoreFile.Writer writer = null;
253   }
254 
255   /**
256    * Return the start keys of all of the regions in this table,
257    * as a list of ImmutableBytesWritable.
258    */
259   private static List<ImmutableBytesWritable> getRegionStartKeys(HTable table)
260   throws IOException {
261     byte[][] byteKeys = table.getStartKeys();
262     ArrayList<ImmutableBytesWritable> ret =
263       new ArrayList<ImmutableBytesWritable>(byteKeys.length);
264     for (byte[] byteKey : byteKeys) {
265       ret.add(new ImmutableBytesWritable(byteKey));
266     }
267     return ret;
268   }
269 
270   /**
271    * Write out a {@link SequenceFile} that can be read by
272    * {@link TotalOrderPartitioner} that contains the split points in startKeys.
273    */
274   private static void writePartitions(Configuration conf, Path partitionsPath,
275       List<ImmutableBytesWritable> startKeys) throws IOException {
276     LOG.info("Writing partition information to " + partitionsPath);
277     if (startKeys.isEmpty()) {
278       throw new IllegalArgumentException("No regions passed");
279     }
280 
281     // We're generating a list of split points, and we don't ever
282     // have keys < the first region (which has an empty start key)
283     // so we need to remove it. Otherwise we would end up with an
284     // empty reducer with index 0
285     TreeSet<ImmutableBytesWritable> sorted =
286       new TreeSet<ImmutableBytesWritable>(startKeys);
287 
288     ImmutableBytesWritable first = sorted.first();
289     if (!first.equals(HConstants.EMPTY_BYTE_ARRAY)) {
290       throw new IllegalArgumentException(
291           "First region of table should have empty start key. Instead has: "
292           + Bytes.toStringBinary(first.get()));
293     }
294     sorted.remove(first);
295 
296     // Write the actual file
297     FileSystem fs = partitionsPath.getFileSystem(conf);
298     SequenceFile.Writer writer = SequenceFile.createWriter(fs,
299         conf, partitionsPath, ImmutableBytesWritable.class, NullWritable.class);
300 
301     try {
302       for (ImmutableBytesWritable startKey : sorted) {
303         writer.append(startKey, NullWritable.get());
304       }
305     } finally {
306       writer.close();
307     }
308   }
309 
310   /**
311    * Configure a MapReduce Job to perform an incremental load into the given
312    * table. This
313    * <ul>
314    *   <li>Inspects the table to configure a total order partitioner</li>
315    *   <li>Uploads the partitions file to the cluster and adds it to the DistributedCache</li>
316    *   <li>Sets the number of reduce tasks to match the current number of regions</li>
317    *   <li>Sets the output key/value class to match HFileOutputFormat's requirements</li>
318    *   <li>Sets the reducer up to perform the appropriate sorting (either KeyValueSortReducer or
319    *     PutSortReducer)</li>
320    * </ul>
321    * The user should be sure to set the map output value class to either KeyValue or Put before
322    * running this function.
323    */
324   public static void configureIncrementalLoad(Job job, HTable table)
325   throws IOException {
326     Configuration conf = job.getConfiguration();
327 
328     job.setOutputKeyClass(ImmutableBytesWritable.class);
329     job.setOutputValueClass(KeyValue.class);
330     job.setOutputFormatClass(HFileOutputFormat.class);
331 
332     // Based on the configured map output class, set the correct reducer to properly
333     // sort the incoming values.
334     // TODO it would be nice to pick one or the other of these formats.
335     if (KeyValue.class.equals(job.getMapOutputValueClass())) {
336       job.setReducerClass(KeyValueSortReducer.class);
337     } else if (Put.class.equals(job.getMapOutputValueClass())) {
338       job.setReducerClass(PutSortReducer.class);
339     } else if (Text.class.equals(job.getMapOutputValueClass())) {
340       job.setReducerClass(TextSortReducer.class);
341     } else {
342       LOG.warn("Unknown map output value type:" + job.getMapOutputValueClass());
343     }
344 
345     conf.setStrings("io.serializations", conf.get("io.serializations"),
346         KeyValueSerialization.class.getName());
347 
348     // Use table's region boundaries for TOP split points.
349     LOG.info("Looking up current regions for table " + Bytes.toString(table.getTableName()));
350     List<ImmutableBytesWritable> startKeys = getRegionStartKeys(table);
351     LOG.info("Configuring " + startKeys.size() + " reduce partitions " +
352         "to match current region count");
353     job.setNumReduceTasks(startKeys.size());
354 
355     configurePartitioner(job, startKeys);
356     // Set compression algorithms based on column families
357     configureCompression(table, conf);
358     configureBloomType(table, conf);
359     configureBlockSize(table, conf);
360 
361     TableMapReduceUtil.addDependencyJars(job);
362     TableMapReduceUtil.initCredentials(job);
363     LOG.info("Incremental table " + Bytes.toString(table.getTableName()) + " output configured.");
364   }
365 
366   private static void configureBlockSize(HTable table, Configuration conf) throws IOException {
367     StringBuilder blockSizeConfigValue = new StringBuilder();
368     HTableDescriptor tableDescriptor = table.getTableDescriptor();
369     if(tableDescriptor == null){
370       // could happen with mock table instance
371       return;
372     }
373     Collection<HColumnDescriptor> families = tableDescriptor.getFamilies();
374     int i = 0;
375     for (HColumnDescriptor familyDescriptor : families) {
376       if (i++ > 0) {
377         blockSizeConfigValue.append('&');
378       }
379       blockSizeConfigValue.append(URLEncoder.encode(
380           familyDescriptor.getNameAsString(), "UTF-8"));
381       blockSizeConfigValue.append('=');
382       blockSizeConfigValue.append(URLEncoder.encode(
383           String.valueOf(familyDescriptor.getBlocksize()), "UTF-8"));
384     }
385     // Get rid of the last ampersand
386     conf.set(BLOCK_SIZE_CONF_KEY, blockSizeConfigValue.toString());
387   }
388 
389   /**
390    * Run inside the task to deserialize column family to compression algorithm
391    * map from the
392    * configuration.
393    *
394    * Package-private for unit tests only.
395    *
396    * @return a map from column family to the name of the configured compression
397    *         algorithm
398    */
399   static Map<byte[], String> createFamilyCompressionMap(Configuration conf) {
400     return createFamilyConfValueMap(conf, COMPRESSION_CONF_KEY);
401   }
402 
403   private static Map<byte[], String> createFamilyBloomMap(Configuration conf) {
404     return createFamilyConfValueMap(conf, BLOOM_TYPE_CONF_KEY);
405   }
406 
407   private static Map<byte[], String> createFamilyBlockSizeMap(Configuration conf) {
408     return createFamilyConfValueMap(conf, BLOCK_SIZE_CONF_KEY);
409   }
410 
411   /**
412    * Run inside the task to deserialize column family to given conf value map.
413    *
414    * @param conf
415    * @param confName
416    * @return a map of column family to the given configuration value
417    */
418   private static Map<byte[], String> createFamilyConfValueMap(Configuration conf, String confName) {
419     Map<byte[], String> confValMap = new TreeMap<byte[], String>(Bytes.BYTES_COMPARATOR);
420     String confVal = conf.get(confName, "");
421     for (String familyConf : confVal.split("&")) {
422       String[] familySplit = familyConf.split("=");
423       if (familySplit.length != 2) {
424         continue;
425       }
426       try {
427         confValMap.put(URLDecoder.decode(familySplit[0], "UTF-8").getBytes(),
428             URLDecoder.decode(familySplit[1], "UTF-8"));
429       } catch (UnsupportedEncodingException e) {
430         // will not happen with UTF-8 encoding
431         throw new AssertionError(e);
432       }
433     }
434     return confValMap;
435   }
436 
437   /**
438    * Configure <code>job</code> with a TotalOrderPartitioner, partitioning against
439    * <code>splitPoints</code>. Cleans up the partitions file after job exists.
440    */
441   static void configurePartitioner(Job job, List<ImmutableBytesWritable> splitPoints)
442       throws IOException {
443 
444     // create the partitions file
445     FileSystem fs = FileSystem.get(job.getConfiguration());
446     Path partitionsPath = new Path("/tmp", "partitions_" + UUID.randomUUID());
447     fs.makeQualified(partitionsPath);
448     fs.deleteOnExit(partitionsPath);
449     writePartitions(job.getConfiguration(), partitionsPath, splitPoints);
450 
451     // configure job to use it
452     job.setPartitionerClass(TotalOrderPartitioner.class);
453     TotalOrderPartitioner.setPartitionFile(job.getConfiguration(), partitionsPath);
454   }
455 
456   /**
457    * Serialize column family to compression algorithm map to configuration.
458    * Invoked while configuring the MR job for incremental load.
459    *
460    * Package-private for unit tests only.
461    *
462    * @throws IOException
463    *           on failure to read column family descriptors
464    */
465   @edu.umd.cs.findbugs.annotations.SuppressWarnings(
466       value="RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
467   static void configureCompression(HTable table, Configuration conf) throws IOException {
468     StringBuilder compressionConfigValue = new StringBuilder();
469     HTableDescriptor tableDescriptor = table.getTableDescriptor();
470     if(tableDescriptor == null){
471       // could happen with mock table instance
472       return;
473     }
474     Collection<HColumnDescriptor> families = tableDescriptor.getFamilies();
475     int i = 0;
476     for (HColumnDescriptor familyDescriptor : families) {
477       if (i++ > 0) {
478         compressionConfigValue.append('&');
479       }
480       compressionConfigValue.append(URLEncoder.encode(familyDescriptor.getNameAsString(), "UTF-8"));
481       compressionConfigValue.append('=');
482       compressionConfigValue.append(URLEncoder.encode(familyDescriptor.getCompression().getName(), "UTF-8"));
483     }
484     // Get rid of the last ampersand
485     conf.set(COMPRESSION_CONF_KEY, compressionConfigValue.toString());
486   }
487 
488   /**
489    * Serialize column family to bloom type map to configuration.
490    * Invoked while configuring the MR job for incremental load.
491    *
492    * @throws IOException
493    *           on failure to read column family descriptors
494    */
495   static void configureBloomType(HTable table, Configuration conf) throws IOException {
496     HTableDescriptor tableDescriptor = table.getTableDescriptor();
497     if (tableDescriptor == null) {
498       // could happen with mock table instance
499       return;
500     }
501     StringBuilder bloomTypeConfigValue = new StringBuilder();
502     Collection<HColumnDescriptor> families = tableDescriptor.getFamilies();
503     int i = 0;
504     for (HColumnDescriptor familyDescriptor : families) {
505       if (i++ > 0) {
506         bloomTypeConfigValue.append('&');
507       }
508       bloomTypeConfigValue.append(URLEncoder.encode(familyDescriptor.getNameAsString(), "UTF-8"));
509       bloomTypeConfigValue.append('=');
510       String bloomType = familyDescriptor.getBloomFilterType().toString();
511       if (bloomType == null) {
512         bloomType = HColumnDescriptor.DEFAULT_BLOOMFILTER;
513       }
514       bloomTypeConfigValue.append(URLEncoder.encode(bloomType, "UTF-8"));
515     }
516     conf.set(BLOOM_TYPE_CONF_KEY, bloomTypeConfigValue.toString());
517   }
518 }