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.io.hfile;
19  
20  import java.io.ByteArrayOutputStream;
21  import java.io.IOException;
22  import java.nio.ByteBuffer;
23  import java.util.zip.Checksum;
24  
25  import org.apache.hadoop.fs.Path;
26  import org.apache.hadoop.hbase.util.ByteBufferUtils;
27  import org.apache.hadoop.hbase.util.Bytes;
28  import org.apache.hadoop.hbase.util.ChecksumType;
29  
30  /**
31   * Utility methods to compute and validate checksums.
32   */
33  public class ChecksumUtil {
34  
35    /** This is used to reserve space in a byte buffer */
36    private static byte[] DUMMY_VALUE = new byte[128 * HFileBlock.CHECKSUM_SIZE];
37  
38    /** 
39     * This is used by unit tests to make checksum failures throw an 
40     * exception instead of returning null. Returning a null value from 
41     * checksum validation will cause the higher layer to retry that 
42     * read with hdfs-level checksums. Instead, we would like checksum 
43     * failures to cause the entire unit test to fail.
44     */
45    private static boolean generateExceptions = false;
46  
47    /**
48     * Generates a checksum for all the data in indata. The checksum is
49     * written to outdata.
50     * @param indata input data stream
51     * @param startOffset starting offset in the indata stream from where to
52     *                    compute checkums from
53     * @param endOffset ending offset in the indata stream upto
54     *                   which checksums needs to be computed
55     * @param outdata the output buffer where checksum values are written
56     * @param outOffset the starting offset in the outdata where the
57     *                  checksum values are written
58     * @param checksumType type of checksum
59     * @param bytesPerChecksum number of bytes per checksum value
60     */
61    static void generateChecksums(byte[] indata,
62      int startOffset, int endOffset, 
63      byte[] outdata, int outOffset,
64      ChecksumType checksumType,
65      int bytesPerChecksum) throws IOException {
66  
67      if (checksumType == ChecksumType.NULL) {
68        return; // No checkums for this block.
69      }
70  
71      Checksum checksum = checksumType.getChecksumObject();
72      int bytesLeft = endOffset - startOffset;
73      int chunkNum = 0;
74  
75      while (bytesLeft > 0) {
76        // generate the checksum for one chunk
77        checksum.reset();
78        int count = Math.min(bytesLeft, bytesPerChecksum);
79        checksum.update(indata, startOffset, count);
80  
81        // write the checksum value to the output buffer.
82        int cksumValue = (int)checksum.getValue();
83        outOffset = Bytes.putInt(outdata, outOffset, cksumValue);
84        chunkNum++;
85        startOffset += count;
86        bytesLeft -= count;
87      }
88    }
89  
90    /**
91     * Validates that the data in the specified HFileBlock matches the
92     * checksum.  Generates the checksum for the data and
93     * then validate that it matches the value stored in the header.
94     * If there is a checksum mismatch, then return false. Otherwise
95     * return true.
96     * The header is extracted from the specified HFileBlock while the
97     * data-to-be-verified is extracted from 'data'.
98     */
99    static boolean validateBlockChecksum(Path path, HFileBlock block, 
100     byte[] data, int hdrSize) throws IOException {
101 
102     // If this is an older version of the block that does not have
103     // checksums, then return false indicating that checksum verification
104     // did not succeed. Actually, this methiod should never be called
105     // when the minorVersion is 0, thus this is a defensive check for a
106     // cannot-happen case. Since this is a cannot-happen case, it is
107     // better to return false to indicate a checksum validation failure.
108     if (!block.getHFileContext().isUseHBaseChecksum()) {
109       return false;
110     }
111 
112     // Get a checksum object based on the type of checksum that is
113     // set in the HFileBlock header. A ChecksumType.NULL indicates that 
114     // the caller is not interested in validating checksums, so we
115     // always return true.
116     ChecksumType cktype = ChecksumType.codeToType(block.getChecksumType());
117     if (cktype == ChecksumType.NULL) {
118       return true; // No checkums validations needed for this block.
119     }
120     Checksum checksumObject = cktype.getChecksumObject();
121     checksumObject.reset();
122 
123     // read in the stored value of the checksum size from the header.
124     int bytesPerChecksum = block.getBytesPerChecksum();
125 
126     // bytesPerChecksum is always larger than the size of the header
127     if (bytesPerChecksum < hdrSize) {
128       String msg = "Unsupported value of bytesPerChecksum. " +
129                    " Minimum is " + hdrSize + 
130                    " but the configured value is " + bytesPerChecksum;
131       HFile.LOG.warn(msg);
132       return false;   // cannot happen case, unable to verify checksum
133     }
134     // Extract the header and compute checksum for the header.
135     ByteBuffer hdr = block.getBufferWithHeader();
136     if (hdr.hasArray()) {
137       checksumObject.update(hdr.array(), hdr.arrayOffset(), hdrSize);
138     } else {
139       checksumObject.update(ByteBufferUtils.toBytes(hdr, 0, hdrSize), 0, hdrSize);
140     }
141 
142     int off = hdrSize;
143     int consumed = hdrSize;
144     int bytesLeft = block.getOnDiskDataSizeWithHeader() - off;
145     int cksumOffset = block.getOnDiskDataSizeWithHeader();
146     
147     // validate each chunk
148     while (bytesLeft > 0) {
149       int thisChunkSize = bytesPerChecksum - consumed;
150       int count = Math.min(bytesLeft, thisChunkSize);
151       checksumObject.update(data, off, count);
152 
153       int storedChecksum = Bytes.toInt(data, cksumOffset);
154       if (storedChecksum != (int)checksumObject.getValue()) {
155         String msg = "File " + path +
156                      " Stored checksum value of " + storedChecksum +
157                      " at offset " + cksumOffset +
158                      " does not match computed checksum " +
159                      checksumObject.getValue() +
160                      ", total data size " + data.length +
161                      " Checksum data range offset " + off + " len " + count +
162                      HFileBlock.toStringHeader(block.getBufferReadOnly());
163         HFile.LOG.warn(msg);
164         if (generateExceptions) {
165           throw new IOException(msg); // this is only for unit tests
166         } else {
167           return false;               // checksum validation failure
168         }
169       }
170       cksumOffset += HFileBlock.CHECKSUM_SIZE;
171       bytesLeft -= count; 
172       off += count;
173       consumed = 0;
174       checksumObject.reset();
175     }
176     return true; // checksum is valid
177   }
178 
179   /**
180    * Returns the number of bytes needed to store the checksums for
181    * a specified data size
182    * @param datasize number of bytes of data
183    * @param bytesPerChecksum number of bytes in a checksum chunk
184    * @return The number of bytes needed to store the checksum values
185    */
186   static long numBytes(long datasize, int bytesPerChecksum) {
187     return numChunks(datasize, bytesPerChecksum) * 
188                      HFileBlock.CHECKSUM_SIZE;
189   }
190 
191   /**
192    * Returns the number of checksum chunks needed to store the checksums for
193    * a specified data size
194    * @param datasize number of bytes of data
195    * @param bytesPerChecksum number of bytes in a checksum chunk
196    * @return The number of checksum chunks
197    */
198   static long numChunks(long datasize, int bytesPerChecksum) {
199     long numChunks = datasize/bytesPerChecksum;
200     if (datasize % bytesPerChecksum != 0) {
201       numChunks++;
202     }
203     return numChunks;
204   }
205 
206   /**
207    * Write dummy checksums to the end of the specified bytes array
208    * to reserve space for writing checksums later
209    * @param baos OutputStream to write dummy checkum values
210    * @param numBytes Number of bytes of data for which dummy checksums
211    *                 need to be generated
212    * @param bytesPerChecksum Number of bytes per checksum value
213    */
214   static void reserveSpaceForChecksums(ByteArrayOutputStream baos,
215     int numBytes, int bytesPerChecksum) throws IOException {
216     long numChunks = numChunks(numBytes, bytesPerChecksum);
217     long bytesLeft = numChunks * HFileBlock.CHECKSUM_SIZE;
218     while (bytesLeft > 0) {
219       long count = Math.min(bytesLeft, DUMMY_VALUE.length);
220       baos.write(DUMMY_VALUE, 0, (int)count);
221       bytesLeft -= count;
222     }
223   }
224 
225   /**
226    * Mechanism to throw an exception in case of hbase checksum
227    * failure. This is used by unit tests only.
228    * @param value Setting this to true will cause hbase checksum
229    *              verification failures to generate exceptions.
230    */
231   public static void generateExceptionForChecksumFailureForTest(boolean value) {
232     generateExceptions = value;
233   }
234 }
235