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    private boolean logBadLines;
61  
62    protected ImportTsv.TsvParser parser;
63  
64    protected Configuration conf;
65  
66    protected String cellVisibilityExpr;
67  
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     logBadLines = context.getConfiguration().getBoolean(ImportTsv.LOG_BAD_LINES_CONF_KEY, false);
134     hfileOutPath = conf.get(ImportTsv.BULK_OUTPUT_CONF_KEY);
135   }
136 
137   /**
138    * Convert a line of TSV text into an HBase table row.
139    */
140   @Override
141   public void map(LongWritable offset, Text value,
142     Context context)
143   throws IOException {
144     byte[] lineBytes = value.getBytes();
145 
146     try {
147       ImportTsv.TsvParser.ParsedLine parsed = parser.parse(
148           lineBytes, value.getLength());
149       ImmutableBytesWritable rowKey =
150         new ImmutableBytesWritable(lineBytes,
151             parsed.getRowKeyOffset(),
152             parsed.getRowKeyLength());
153       // Retrieve timestamp if exists
154       ts = parsed.getTimestamp(ts);
155       cellVisibilityExpr = parsed.getCellVisibility();
156       ttl = parsed.getCellTTL();
157 
158       Put put = new Put(rowKey.copyBytes());
159       for (int i = 0; i < parsed.getColumnCount(); i++) {
160         if (i == parser.getRowKeyColumnIndex() || i == parser.getTimestampKeyColumnIndex()
161             || i == parser.getAttributesKeyColumnIndex() || i == parser.getCellVisibilityColumnIndex()
162             || i == parser.getCellTTLColumnIndex()) {
163           continue;
164         }
165         populatePut(lineBytes, parsed, put, i);
166       }
167       context.write(rowKey, put);
168     } catch (ImportTsv.TsvParser.BadTsvLineException|IllegalArgumentException badLine) {
169       if (logBadLines) {
170         System.err.println(value);
171       }
172       System.err.println("Bad line at offset: " + offset.get() + ":\n" + badLine.getMessage());
173       if (skipBadLines) {
174         incrementBadLineCount(1);
175         return;
176       }
177       throw new IOException(badLine);
178     } catch (InterruptedException e) {
179       e.printStackTrace();
180     }
181   }
182 
183   protected void populatePut(byte[] lineBytes, ImportTsv.TsvParser.ParsedLine parsed, Put put,
184       int i) throws BadTsvLineException, IOException {
185     Cell cell = null;
186     if (hfileOutPath == null) {
187       cell = new KeyValue(lineBytes, parsed.getRowKeyOffset(), parsed.getRowKeyLength(),
188           parser.getFamily(i), 0, parser.getFamily(i).length, parser.getQualifier(i), 0,
189           parser.getQualifier(i).length, ts, KeyValue.Type.Put, lineBytes,
190           parsed.getColumnOffset(i), parsed.getColumnLength(i));
191       if (cellVisibilityExpr != null) {
192         // We won't be validating the expression here. The Visibility CP will do
193         // the validation
194         put.setCellVisibility(new CellVisibility(cellVisibilityExpr));
195       }
196       if (ttl > 0) {
197         put.setTTL(ttl);
198       }
199     } else {
200       // Creating the KV which needs to be directly written to HFiles. Using the Facade
201       // KVCreator for creation of kvs.
202       List<Tag> tags = new ArrayList<Tag>();
203       if (cellVisibilityExpr != null) {
204         tags.addAll(kvCreator.getVisibilityExpressionResolver()
205           .createVisibilityExpTags(cellVisibilityExpr));
206       }
207       // Add TTL directly to the KV so we can vary them when packing more than one KV
208       // into puts
209       if (ttl > 0) {
210         tags.add(new Tag(TagType.TTL_TAG_TYPE, Bytes.toBytes(ttl)));
211       }
212       cell = this.kvCreator.create(lineBytes, parsed.getRowKeyOffset(), parsed.getRowKeyLength(),
213           parser.getFamily(i), 0, parser.getFamily(i).length, parser.getQualifier(i), 0,
214           parser.getQualifier(i).length, ts, lineBytes, parsed.getColumnOffset(i),
215           parsed.getColumnLength(i), tags);
216     }
217     put.add(cell);
218   }
219 }