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  
19  package org.apache.hadoop.hbase.io.hfile;
20  
21  import java.io.DataOutputStream;
22  import java.io.IOException;
23  import java.net.InetSocketAddress;
24  import java.util.ArrayList;
25  import java.util.List;
26  
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.fs.FSDataOutputStream;
30  import org.apache.hadoop.fs.FileSystem;
31  import org.apache.hadoop.fs.Path;
32  import org.apache.hadoop.fs.permission.FsPermission;
33  import org.apache.hadoop.hbase.Cell;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.KeyValue;
36  import org.apache.hadoop.hbase.KeyValue.KVComparator;
37  import org.apache.hadoop.hbase.KeyValueUtil;
38  import org.apache.hadoop.hbase.io.compress.Compression;
39  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
40  import org.apache.hadoop.hbase.io.hfile.HFile.FileInfo;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.hbase.util.FSUtils;
43  import org.apache.hadoop.io.Writable;
44  
45  /**
46   * Common functionality needed by all versions of {@link HFile} writers.
47   */
48  @InterfaceAudience.Private
49  public abstract class AbstractHFileWriter implements HFile.Writer {
50  
51    /** The Cell previously appended. Becomes the last cell in the file.*/
52    protected Cell lastCell = null;
53  
54    protected int lastKeyLength = -1;
55  
56    /** FileSystem stream to write into. */
57    protected FSDataOutputStream outputStream;
58  
59    /** True if we opened the <code>outputStream</code> (and so will close it). */
60    protected final boolean closeOutputStream;
61  
62    /** A "file info" block: a key-value map of file-wide metadata. */
63    protected FileInfo fileInfo = new HFile.FileInfo();
64  
65    /** Total # of key/value entries, i.e. how many times add() was called. */
66    protected long entryCount = 0;
67  
68    /** Used for calculating the average key length. */
69    protected long totalKeyLength = 0;
70  
71    /** Used for calculating the average value length. */
72    protected long totalValueLength = 0;
73  
74    /** Total uncompressed bytes, maybe calculate a compression ratio later. */
75    protected long totalUncompressedBytes = 0;
76  
77    /** Key comparator. Used to ensure we write in order. */
78    protected final KVComparator comparator;
79  
80    /** Meta block names. */
81    protected List<byte[]> metaNames = new ArrayList<byte[]>();
82  
83    /** {@link Writable}s representing meta block data. */
84    protected List<Writable> metaData = new ArrayList<Writable>();
85  
86    /** First key in a block. */
87    protected byte[] firstKeyInBlock = null;
88  
89    /** May be null if we were passed a stream. */
90    protected final Path path;
91  
92  
93    /** Cache configuration for caching data on write. */
94    protected final CacheConfig cacheConf;
95  
96    /**
97     * Name for this object used when logging or in toString. Is either
98     * the result of a toString on stream or else name of passed file Path.
99     */
100   protected final String name;
101 
102   /**
103    * The data block encoding which will be used.
104    * {@link NoOpDataBlockEncoder#INSTANCE} if there is no encoding.
105    */
106   protected final HFileDataBlockEncoder blockEncoder;
107   
108   protected final HFileContext hFileContext;
109 
110   public AbstractHFileWriter(CacheConfig cacheConf,
111       FSDataOutputStream outputStream, Path path, 
112       KVComparator comparator, HFileContext fileContext) {
113     this.outputStream = outputStream;
114     this.path = path;
115     this.name = path != null ? path.getName() : outputStream.toString();
116     this.hFileContext = fileContext;
117     DataBlockEncoding encoding = hFileContext.getDataBlockEncoding();
118     if (encoding != DataBlockEncoding.NONE) {
119       this.blockEncoder = new HFileDataBlockEncoderImpl(encoding);
120     } else {
121       this.blockEncoder = NoOpDataBlockEncoder.INSTANCE;
122     }
123     this.comparator = comparator != null ? comparator
124         : KeyValue.COMPARATOR;
125 
126     closeOutputStream = path != null;
127     this.cacheConf = cacheConf;
128   }
129 
130   /**
131    * Add last bits of metadata to file info before it is written out.
132    */
133   protected void finishFileInfo() throws IOException {
134     if (lastCell != null) {
135       // Make a copy. The copy is stuffed into our fileinfo map. Needs a clean
136       // byte buffer. Won't take a tuple.
137       byte[] lastKey = new byte[lastKeyLength];
138       KeyValueUtil.appendKeyTo(lastCell, lastKey, 0);
139       fileInfo.append(FileInfo.LASTKEY, lastKey, false);
140     }
141 
142     // Average key length.
143     int avgKeyLen =
144         entryCount == 0 ? 0 : (int) (totalKeyLength / entryCount);
145     fileInfo.append(FileInfo.AVG_KEY_LEN, Bytes.toBytes(avgKeyLen), false);
146 
147     // Average value length.
148     int avgValueLen =
149         entryCount == 0 ? 0 : (int) (totalValueLength / entryCount);
150     fileInfo.append(FileInfo.AVG_VALUE_LEN, Bytes.toBytes(avgValueLen), false);
151   }
152 
153   /**
154    * Add to the file info. All added key/value pairs can be obtained using
155    * {@link HFile.Reader#loadFileInfo()}.
156    *
157    * @param k Key
158    * @param v Value
159    * @throws IOException in case the key or the value are invalid
160    */
161   @Override
162   public void appendFileInfo(final byte[] k, final byte[] v)
163       throws IOException {
164     fileInfo.append(k, v, true);
165   }
166 
167   /**
168    * Sets the file info offset in the trailer, finishes up populating fields in
169    * the file info, and writes the file info into the given data output. The
170    * reason the data output is not always {@link #outputStream} is that we store
171    * file info as a block in version 2.
172    *
173    * @param trailer fixed file trailer
174    * @param out the data output to write the file info to
175    * @throws IOException
176    */
177   protected final void writeFileInfo(FixedFileTrailer trailer, DataOutputStream out)
178   throws IOException {
179     trailer.setFileInfoOffset(outputStream.getPos());
180     finishFileInfo();
181     fileInfo.write(out);
182   }
183 
184   /**
185    * Checks that the given Cell's key does not violate the key order.
186    *
187    * @param cell Cell whose key to check.
188    * @return true if the key is duplicate
189    * @throws IOException if the key or the key order is wrong
190    */
191   protected boolean checkKey(final Cell cell) throws IOException {
192     boolean isDuplicateKey = false;
193 
194     if (cell == null) {
195       throw new IOException("Key cannot be null or empty");
196     }
197     if (lastCell != null) {
198       int keyComp = comparator.compareOnlyKeyPortion(lastCell, cell);
199 
200       if (keyComp > 0) {
201         throw new IOException("Added a key not lexically larger than"
202             + " previous. Current cell = " + cell + ", lastCell = " + lastCell);
203       } else if (keyComp == 0) {
204         isDuplicateKey = true;
205       }
206     }
207     return isDuplicateKey;
208   }
209 
210   /** Checks the given value for validity. */
211   protected void checkValue(final byte[] value, final int offset,
212       final int length) throws IOException {
213     if (value == null) {
214       throw new IOException("Value cannot be null");
215     }
216   }
217 
218   /**
219    * @return Path or null if we were passed a stream rather than a Path.
220    */
221   @Override
222   public Path getPath() {
223     return path;
224   }
225 
226   @Override
227   public String toString() {
228     return "writer=" + (path != null ? path.toString() : null) + ", name="
229         + name + ", compression=" + hFileContext.getCompression().getName();
230   }
231 
232   /**
233    * Sets remaining trailer fields, writes the trailer to disk, and optionally
234    * closes the output stream.
235    */
236   protected void finishClose(FixedFileTrailer trailer) throws IOException {
237     trailer.setMetaIndexCount(metaNames.size());
238     trailer.setTotalUncompressedBytes(totalUncompressedBytes+ trailer.getTrailerSize());
239     trailer.setEntryCount(entryCount);
240     trailer.setCompressionCodec(hFileContext.getCompression());
241 
242     trailer.serialize(outputStream);
243 
244     if (closeOutputStream) {
245       outputStream.close();
246       outputStream = null;
247     }
248   }
249 
250   public static Compression.Algorithm compressionByName(String algoName) {
251     if (algoName == null)
252       return HFile.DEFAULT_COMPRESSION_ALGORITHM;
253     return Compression.getCompressionAlgorithmByName(algoName);
254   }
255 
256   /** A helper method to create HFile output streams in constructors */
257   protected static FSDataOutputStream createOutputStream(Configuration conf,
258       FileSystem fs, Path path, InetSocketAddress[] favoredNodes) throws IOException {
259     FsPermission perms = FSUtils.getFilePermissions(fs, conf,
260         HConstants.DATA_FILE_UMASK_KEY);
261     return FSUtils.create(fs, path, perms, favoredNodes);
262   }
263 }