View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.mapreduce;
19  
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.List;
23  
24  import org.apache.hadoop.hbase.classification.InterfaceAudience;
25  import org.apache.hadoop.hbase.classification.InterfaceStability;
26  import org.apache.hadoop.conf.Configuration;
27  import org.apache.hadoop.hbase.Cell;
28  import org.apache.hadoop.hbase.KeyValue;
29  import org.apache.hadoop.hbase.Tag;
30  import org.apache.hadoop.hbase.TagType;
31  import org.apache.hadoop.hbase.client.Put;
32  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
33  import org.apache.hadoop.hbase.mapreduce.ImportTsv.TsvParser.BadTsvLineException;
34  import org.apache.hadoop.hbase.security.visibility.CellVisibility;
35  import org.apache.hadoop.hbase.util.Base64;
36  import org.apache.hadoop.hbase.util.Bytes;
37  import org.apache.hadoop.io.LongWritable;
38  import org.apache.hadoop.io.Text;
39  import org.apache.hadoop.mapreduce.Counter;
40  import org.apache.hadoop.mapreduce.Mapper;
41  
42  /**
43   * Write table content out to files in hdfs.
44   */
45  @InterfaceAudience.Public
46  @InterfaceStability.Stable
47  public class TsvImporterMapper
48  extends Mapper<LongWritable, Text, ImmutableBytesWritable, Put>
49  {
50  
51    /** Timestamp for all inserted rows */
52    protected long ts;
53  
54    /** Column seperator */
55    private String separator;
56  
57    /** Should skip bad lines */
58    private boolean skipBadLines;
59    private Counter badLineCount;
60  
61    protected ImportTsv.TsvParser parser;
62  
63    protected Configuration conf;
64  
65    @InterfaceStability.Unstable
66    protected String cellVisibilityExpr;
67    @InterfaceStability.Unstable
68    protected long ttl;
69  
70    protected CellCreator kvCreator;
71  
72    private String hfileOutPath;
73  
74    public long getTs() {
75      return ts;
76    }
77  
78    public boolean getSkipBadLines() {
79      return skipBadLines;
80    }
81  
82    public Counter getBadLineCount() {
83      return badLineCount;
84    }
85  
86    public void incrementBadLineCount(int count) {
87      this.badLineCount.increment(count);
88    }
89  
90    /**
91     * Handles initializing this class with objects specific to it (i.e., the parser).
92     * Common initialization that might be leveraged by a subsclass is done in
93     * <code>doSetup</code>. Hence a subclass may choose to override this method
94     * and call <code>doSetup</code> as well before handling it's own custom params.
95     *
96     * @param context
97     */
98    @Override
99    protected void setup(Context context) {
100     doSetup(context);
101 
102     conf = context.getConfiguration();
103     parser = new ImportTsv.TsvParser(conf.get(ImportTsv.COLUMNS_CONF_KEY),
104                            separator);
105     if (parser.getRowKeyColumnIndex() == -1) {
106       throw new RuntimeException("No row key column specified");
107     }
108     this.kvCreator = new CellCreator(conf);
109   }
110 
111   /**
112    * Handles common parameter initialization that a subclass might want to leverage.
113    * @param context
114    */
115   protected void doSetup(Context context) {
116     Configuration conf = context.getConfiguration();
117 
118     // If a custom separator has been used,
119     // decode it back from Base64 encoding.
120     separator = conf.get(ImportTsv.SEPARATOR_CONF_KEY);
121     if (separator == null) {
122       separator = ImportTsv.DEFAULT_SEPARATOR;
123     } else {
124       separator = new String(Base64.decode(separator));
125     }
126     // Should never get 0 as we are setting this to a valid value in job
127     // configuration.
128     ts = conf.getLong(ImportTsv.TIMESTAMP_CONF_KEY, 0);
129 
130     skipBadLines = context.getConfiguration().getBoolean(
131         ImportTsv.SKIP_LINES_CONF_KEY, true);
132     badLineCount = context.getCounter("ImportTsv", "Bad Lines");
133     hfileOutPath = conf.get(ImportTsv.BULK_OUTPUT_CONF_KEY);
134   }
135 
136   /**
137    * Convert a line of TSV text into an HBase table row.
138    */
139   @Override
140   public void map(LongWritable offset, Text value,
141     Context context)
142   throws IOException {
143     byte[] lineBytes = value.getBytes();
144 
145     try {
146       ImportTsv.TsvParser.ParsedLine parsed = parser.parse(
147           lineBytes, value.getLength());
148       ImmutableBytesWritable rowKey =
149         new ImmutableBytesWritable(lineBytes,
150             parsed.getRowKeyOffset(),
151             parsed.getRowKeyLength());
152       // Retrieve timestamp if exists
153       ts = parsed.getTimestamp(ts);
154       cellVisibilityExpr = parsed.getCellVisibility();
155       ttl = parsed.getCellTTL();
156 
157       Put put = new Put(rowKey.copyBytes());
158       for (int i = 0; i < parsed.getColumnCount(); i++) {
159         if (i == parser.getRowKeyColumnIndex() || i == parser.getTimestampKeyColumnIndex()
160             || i == parser.getAttributesKeyColumnIndex() || i == parser.getCellVisibilityColumnIndex()
161             || i == parser.getCellTTLColumnIndex()) {
162           continue;
163         }
164         populatePut(lineBytes, parsed, put, i);
165       }
166       context.write(rowKey, put);
167     } catch (ImportTsv.TsvParser.BadTsvLineException badLine) {
168       if (skipBadLines) {
169         System.err.println(
170             "Bad line at offset: " + offset.get() + ":\n" +
171             badLine.getMessage());
172         incrementBadLineCount(1);
173         return;
174       } else {
175         throw new IOException(badLine);
176       }
177     } catch (IllegalArgumentException e) {
178       if (skipBadLines) {
179         System.err.println(
180             "Bad line at offset: " + offset.get() + ":\n" +
181             e.getMessage());
182         incrementBadLineCount(1);
183         return;
184       } else {
185         throw new IOException(e);
186       }
187     } catch (InterruptedException e) {
188       e.printStackTrace();
189     }
190   }
191 
192   protected void populatePut(byte[] lineBytes, ImportTsv.TsvParser.ParsedLine parsed, Put put,
193       int i) throws BadTsvLineException, IOException {
194     Cell cell = null;
195     if (hfileOutPath == null) {
196       cell = new KeyValue(lineBytes, parsed.getRowKeyOffset(), parsed.getRowKeyLength(),
197           parser.getFamily(i), 0, parser.getFamily(i).length, parser.getQualifier(i), 0,
198           parser.getQualifier(i).length, ts, KeyValue.Type.Put, lineBytes,
199           parsed.getColumnOffset(i), parsed.getColumnLength(i));
200       if (cellVisibilityExpr != null) {
201         // We won't be validating the expression here. The Visibility CP will do
202         // the validation
203         put.setCellVisibility(new CellVisibility(cellVisibilityExpr));
204       }
205       if (ttl > 0) {
206         put.setTTL(ttl);
207       }
208     } else {
209       // Creating the KV which needs to be directly written to HFiles. Using the Facade
210       // KVCreator for creation of kvs.
211       List<Tag> tags = new ArrayList<Tag>();
212       if (cellVisibilityExpr != null) {
213         tags.addAll(kvCreator.getVisibilityExpressionResolver()
214           .createVisibilityExpTags(cellVisibilityExpr));
215       }
216       // Add TTL directly to the KV so we can vary them when packing more than one KV
217       // into puts
218       if (ttl > 0) {
219         tags.add(new Tag(TagType.TTL_TAG_TYPE, Bytes.toBytes(ttl)));
220       }
221       cell = this.kvCreator.create(lineBytes, parsed.getRowKeyOffset(), parsed.getRowKeyLength(),
222           parser.getFamily(i), 0, parser.getFamily(i).length, parser.getQualifier(i), 0,
223           parser.getQualifier(i).length, ts, lineBytes, parsed.getColumnOffset(i),
224           parsed.getColumnLength(i), tags);
225     }
226     put.add(cell);
227   }
228 }