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.util.HashMap;
23  import java.util.Map;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.hbase.classification.InterfaceStability;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.hbase.HBaseConfiguration;
31  import org.apache.hadoop.hbase.TableName;
32  import org.apache.hadoop.hbase.client.Delete;
33  import org.apache.hadoop.hbase.client.HTable;
34  import org.apache.hadoop.hbase.client.Mutation;
35  import org.apache.hadoop.hbase.client.Put;
36  import org.apache.hadoop.hbase.client.Durability;
37  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
38  import org.apache.hadoop.hbase.util.Bytes;
39  import org.apache.hadoop.mapreduce.JobContext;
40  import org.apache.hadoop.mapreduce.OutputCommitter;
41  import org.apache.hadoop.mapreduce.OutputFormat;
42  import org.apache.hadoop.mapreduce.RecordWriter;
43  import org.apache.hadoop.mapreduce.TaskAttemptContext;
44  
45  /**
46   * <p>
47   * Hadoop output format that writes to one or more HBase tables. The key is
48   * taken to be the table name while the output value <em>must</em> be either a
49   * {@link Put} or a {@link Delete} instance. All tables must already exist, and
50   * all Puts and Deletes must reference only valid column families.
51   * </p>
52   *
53   * <p>
54   * Write-ahead logging (WAL) for Puts can be disabled by setting
55   * {@link #WAL_PROPERTY} to {@link #WAL_OFF}. Default value is {@link #WAL_ON}.
56   * Note that disabling write-ahead logging is only appropriate for jobs where
57   * loss of data due to region server failure can be tolerated (for example,
58   * because it is easy to rerun a bulk import).
59   * </p>
60   */
61  @InterfaceAudience.Public
62  @InterfaceStability.Stable
63  public class MultiTableOutputFormat extends OutputFormat<ImmutableBytesWritable, Mutation> {
64    /** Set this to {@link #WAL_OFF} to turn off write-ahead logging (WAL) */
65    public static final String WAL_PROPERTY = "hbase.mapreduce.multitableoutputformat.wal";
66    /** Property value to use write-ahead logging */
67    public static final boolean WAL_ON = true;
68    /** Property value to disable write-ahead logging */
69    public static final boolean WAL_OFF = false;
70    /**
71     * Record writer for outputting to multiple HTables.
72     */
73    protected static class MultiTableRecordWriter extends
74        RecordWriter<ImmutableBytesWritable, Mutation> {
75      private static final Log LOG = LogFactory.getLog(MultiTableRecordWriter.class);
76      Map<ImmutableBytesWritable, HTable> tables;
77      Configuration conf;
78      boolean useWriteAheadLogging;
79  
80      /**
81       * @param conf
82       *          HBaseConfiguration to used
83       * @param useWriteAheadLogging
84       *          whether to use write ahead logging. This can be turned off (
85       *          <tt>false</tt>) to improve performance when bulk loading data.
86       */
87      public MultiTableRecordWriter(Configuration conf,
88          boolean useWriteAheadLogging) {
89        LOG.debug("Created new MultiTableRecordReader with WAL "
90            + (useWriteAheadLogging ? "on" : "off"));
91        this.tables = new HashMap<ImmutableBytesWritable, HTable>();
92        this.conf = conf;
93        this.useWriteAheadLogging = useWriteAheadLogging;
94      }
95  
96      /**
97       * @param tableName
98       *          the name of the table, as a string
99       * @return the named table
100      * @throws IOException
101      *           if there is a problem opening a table
102      */
103     HTable getTable(ImmutableBytesWritable tableName) throws IOException {
104       if (!tables.containsKey(tableName)) {
105         LOG.debug("Opening HTable \"" + Bytes.toString(tableName.get())+ "\" for writing");
106         HTable table = new HTable(conf, TableName.valueOf(tableName.get()));
107         table.setAutoFlush(false, true);
108         tables.put(tableName, table);
109       }
110       return tables.get(tableName);
111     }
112 
113     @Override
114     public void close(TaskAttemptContext context) throws IOException {
115       for (HTable table : tables.values()) {
116         table.flushCommits();
117       }
118     }
119 
120     /**
121      * Writes an action (Put or Delete) to the specified table.
122      *
123      * @param tableName
124      *          the table being updated.
125      * @param action
126      *          the update, either a put or a delete.
127      * @throws IllegalArgumentException
128      *          if the action is not a put or a delete.
129      */
130     @Override
131     public void write(ImmutableBytesWritable tableName, Mutation action) throws IOException {
132       HTable table = getTable(tableName);
133       // The actions are not immutable, so we defensively copy them
134       if (action instanceof Put) {
135         Put put = new Put((Put) action);
136         put.setDurability(useWriteAheadLogging ? Durability.SYNC_WAL
137             : Durability.SKIP_WAL);
138         table.put(put);
139       } else if (action instanceof Delete) {
140         Delete delete = new Delete((Delete) action);
141         table.delete(delete);
142       } else
143         throw new IllegalArgumentException(
144             "action must be either Delete or Put");
145     }
146   }
147 
148   @Override
149   public void checkOutputSpecs(JobContext context) throws IOException,
150       InterruptedException {
151     // we can't know ahead of time if it's going to blow up when the user
152     // passes a table name that doesn't exist, so nothing useful here.
153   }
154 
155   @Override
156   public OutputCommitter getOutputCommitter(TaskAttemptContext context)
157       throws IOException, InterruptedException {
158     return new TableOutputCommitter();
159   }
160 
161   @Override
162   public RecordWriter<ImmutableBytesWritable, Mutation> getRecordWriter(TaskAttemptContext context)
163       throws IOException, InterruptedException {
164     Configuration conf = context.getConfiguration();
165     return new MultiTableRecordWriter(HBaseConfiguration.create(conf),
166         conf.getBoolean(WAL_PROPERTY, WAL_ON));
167   }
168 
169 }