001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.io;
019
020import java.io.Closeable;
021import java.io.IOException;
022import java.util.concurrent.atomic.AtomicInteger;
023import org.apache.hadoop.fs.FSDataInputStream;
024import org.apache.hadoop.fs.FileStatus;
025import org.apache.hadoop.fs.FileSystem;
026import org.apache.hadoop.fs.Path;
027import org.apache.hadoop.hbase.fs.HFileSystem;
028import org.apache.hadoop.hbase.util.FSUtils;
029import org.apache.hadoop.hdfs.client.HdfsDataInputStream;
030import org.apache.yetus.audience.InterfaceAudience;
031
032import org.apache.hbase.thirdparty.com.google.common.io.Closeables;
033
034/**
035 * Wrapper for input stream(s) that takes care of the interaction of FS and HBase checksums, as well
036 * as closing streams. Initialization is not thread-safe, but normal operation is; see method
037 * comments.
038 */
039@InterfaceAudience.Private
040public class FSDataInputStreamWrapper implements Closeable {
041
042  private final HFileSystem hfs;
043  private final Path path;
044  private final FileLink link;
045  private final boolean doCloseStreams;
046  private final boolean dropBehind;
047  private final long readahead;
048
049  /**
050   * Two stream handles, one with and one without FS-level checksum. HDFS checksum setting is on FS
051   * level, not single read level, so you have to keep two FS objects and two handles open to
052   * interleave different reads freely, which is very sad. This is what we do: 1) First, we need to
053   * read the trailer of HFile to determine checksum parameters. We always use FS checksum to do
054   * that, so ctor opens {@link #stream}. 2.1) After that, if HBase checksum is not used, we'd just
055   * always use {@link #stream}; 2.2) If HBase checksum can be used, we'll open
056   * {@link #streamNoFsChecksum}, and close {@link #stream}. User MUST call prepareForBlockReader
057   * for that to happen; if they don't, (2.1) will be the default. 3) The users can call
058   * {@link #shouldUseHBaseChecksum()}, and pass its result to {@link #getStream(boolean)} to get
059   * stream (if Java had out/pointer params we could return both in one call). This stream is
060   * guaranteed to be set. 4) The first time HBase checksum fails, one would call
061   * {@link #fallbackToFsChecksum(int)}. That will take lock, and open {@link #stream}. While this
062   * is going on, others will continue to use the old stream; if they also want to fall back,
063   * they'll also call {@link #fallbackToFsChecksum(int)}, and block until {@link #stream} is set.
064   * 5) After some number of checksumOk() calls, we will go back to using HBase checksum. We will
065   * have 2 handles; however we presume checksums fail so rarely that we don't care.
066   */
067  private volatile FSDataInputStream stream = null;
068  private volatile FSDataInputStream streamNoFsChecksum = null;
069  private final Object streamNoFsChecksumFirstCreateLock = new Object();
070
071  // The configuration states that we should validate hbase checksums
072  private boolean useHBaseChecksumConfigured;
073
074  // Record the current state of this reader with respect to
075  // validating checkums in HBase. This is originally set the same
076  // value as useHBaseChecksumConfigured, but can change state as and when
077  // we encounter checksum verification failures.
078  private volatile boolean useHBaseChecksum;
079
080  // In the case of a checksum failure, do these many succeeding
081  // reads without hbase checksum verification.
082  private AtomicInteger hbaseChecksumOffCount = new AtomicInteger(-1);
083
084  private final static ReadStatistics readStatistics = new ReadStatistics();
085
086  private static class ReadStatistics {
087    long totalBytesRead;
088    long totalLocalBytesRead;
089    long totalShortCircuitBytesRead;
090    long totalZeroCopyBytesRead;
091  }
092
093  protected Path readerPath;
094
095  // used to avoid redundant metadata lookups when opening the read stream.
096  private final FileStatus fileStatus;
097
098  public FSDataInputStreamWrapper(FileSystem fs, Path path) throws IOException {
099    this(fs, path, false, -1L);
100  }
101
102  public FSDataInputStreamWrapper(FileSystem fs, Path path, boolean dropBehind, long readahead)
103    throws IOException {
104    this(fs, path, dropBehind, readahead, null);
105  }
106
107  public FSDataInputStreamWrapper(FileSystem fs, Path path, boolean dropBehind, long readahead,
108    FileStatus fileStatus) throws IOException {
109    this(fs, null, path, dropBehind, readahead, fileStatus);
110  }
111
112  public FSDataInputStreamWrapper(FileSystem fs, FileLink link, boolean dropBehind, long readahead)
113    throws IOException {
114    this(fs, link, null, dropBehind, readahead, null);
115  }
116
117  private FSDataInputStreamWrapper(FileSystem fs, FileLink link, Path path, boolean dropBehind,
118    long readahead, FileStatus fileStatus) throws IOException {
119    assert (path == null) != (link == null);
120    this.path = path;
121    this.link = link;
122    this.doCloseStreams = true;
123    this.dropBehind = dropBehind;
124    this.readahead = readahead;
125    this.fileStatus = fileStatus;
126    // If the fs is not an instance of HFileSystem, then create an instance of HFileSystem
127    // that wraps over the specified fs. In this case, we will not be able to avoid
128    // checksumming inside the filesystem.
129    this.hfs = (fs instanceof HFileSystem) ? (HFileSystem) fs : new HFileSystem(fs);
130
131    // Initially we are going to read the tail block. Open the reader w/FS checksum.
132    this.useHBaseChecksumConfigured = this.useHBaseChecksum = false;
133    this.stream = (link != null) ? link.open(hfs) : FSUtils.openForRead(hfs, path, fileStatus);
134    this.readerPath = this.stream.getWrappedStream() instanceof FileLink.FileLinkInputStream
135      ? ((FileLink.FileLinkInputStream) this.stream.getWrappedStream()).getCurrentPath()
136      : path;
137    setStreamOptions(stream);
138  }
139
140  private void setStreamOptions(FSDataInputStream in) {
141    try {
142      in.setDropBehind(dropBehind);
143    } catch (Exception e) {
144      // Skipped.
145    }
146    if (readahead >= 0) {
147      try {
148        in.setReadahead(readahead);
149      } catch (Exception e) {
150        // Skipped.
151      }
152    }
153  }
154
155  /**
156   * Prepares the streams for block reader. NOT THREAD SAFE. Must be called once, after any reads
157   * finish and before any other reads start (what happens in reality is we read the tail, then call
158   * this based on what's in the tail, then read blocks).
159   * @param forceNoHBaseChecksum Force not using HBase checksum.
160   */
161  public void prepareForBlockReader(boolean forceNoHBaseChecksum) throws IOException {
162    if (hfs == null) return;
163    assert this.stream != null && !this.useHBaseChecksumConfigured;
164    boolean useHBaseChecksum =
165      !forceNoHBaseChecksum && hfs.useHBaseChecksum() && (hfs.getNoChecksumFs() != hfs);
166
167    if (useHBaseChecksum) {
168      FileSystem fsNc = hfs.getNoChecksumFs();
169      this.streamNoFsChecksum =
170        (link != null) ? link.open(fsNc) : FSUtils.openForRead(fsNc, path, fileStatus);
171      setStreamOptions(streamNoFsChecksum);
172      this.useHBaseChecksumConfigured = this.useHBaseChecksum = useHBaseChecksum;
173      // Close the checksum stream; we will reopen it if we get an HBase checksum failure.
174      this.stream.close();
175      this.stream = null;
176    }
177  }
178
179  /** For use in tests. */
180  public FSDataInputStreamWrapper(FSDataInputStream fsdis) {
181    this(fsdis, fsdis);
182  }
183
184  /** For use in tests. */
185  public FSDataInputStreamWrapper(FSDataInputStream fsdis, FSDataInputStream noChecksum) {
186    doCloseStreams = false;
187    stream = fsdis;
188    streamNoFsChecksum = noChecksum;
189    path = null;
190    link = null;
191    hfs = null;
192    fileStatus = null;
193    useHBaseChecksumConfigured = useHBaseChecksum = false;
194    dropBehind = false;
195    readahead = 0;
196  }
197
198  /** Returns Whether we are presently using HBase checksum. */
199  public boolean shouldUseHBaseChecksum() {
200    return this.useHBaseChecksum;
201  }
202
203  /**
204   * Get the stream to use. Thread-safe.
205   * @param useHBaseChecksum must be the value that shouldUseHBaseChecksum has returned at some
206   *                         point in the past, otherwise the result is undefined.
207   */
208  public FSDataInputStream getStream(boolean useHBaseChecksum) {
209    return useHBaseChecksum ? this.streamNoFsChecksum : this.stream;
210  }
211
212  /**
213   * Read from non-checksum stream failed, fall back to FS checksum. Thread-safe.
214   * @param offCount For how many checksumOk calls to turn off the HBase checksum.
215   */
216  public FSDataInputStream fallbackToFsChecksum(int offCount) throws IOException {
217    // checksumOffCount is speculative, but let's try to reset it less.
218    boolean partOfConvoy = false;
219    if (this.stream == null) {
220      synchronized (streamNoFsChecksumFirstCreateLock) {
221        partOfConvoy = (this.stream != null);
222        if (!partOfConvoy) {
223          this.stream =
224            (link != null) ? link.open(hfs) : FSUtils.openForRead(hfs, path, fileStatus);
225        }
226      }
227    }
228    if (!partOfConvoy) {
229      this.useHBaseChecksum = false;
230      this.hbaseChecksumOffCount.set(offCount);
231    }
232    return this.stream;
233  }
234
235  /** Report that checksum was ok, so we may ponder going back to HBase checksum. */
236  public void checksumOk() {
237    if (
238      this.useHBaseChecksumConfigured && !this.useHBaseChecksum
239        && (this.hbaseChecksumOffCount.getAndDecrement() < 0)
240    ) {
241      // The stream we need is already open (because we were using HBase checksum in the past).
242      assert this.streamNoFsChecksum != null;
243      this.useHBaseChecksum = true;
244    }
245  }
246
247  private void updateInputStreamStatistics(FSDataInputStream stream) {
248    // If the underlying file system is HDFS, update read statistics upon close.
249    if (stream instanceof HdfsDataInputStream) {
250      /**
251       * Because HDFS ReadStatistics is calculated per input stream, it is not feasible to update
252       * the aggregated number in real time. Instead, the metrics are updated when an input stream
253       * is closed.
254       */
255      HdfsDataInputStream hdfsDataInputStream = (HdfsDataInputStream) stream;
256      synchronized (readStatistics) {
257        readStatistics.totalBytesRead +=
258          hdfsDataInputStream.getReadStatistics().getTotalBytesRead();
259        readStatistics.totalLocalBytesRead +=
260          hdfsDataInputStream.getReadStatistics().getTotalLocalBytesRead();
261        readStatistics.totalShortCircuitBytesRead +=
262          hdfsDataInputStream.getReadStatistics().getTotalShortCircuitBytesRead();
263        readStatistics.totalZeroCopyBytesRead +=
264          hdfsDataInputStream.getReadStatistics().getTotalZeroCopyBytesRead();
265      }
266    }
267  }
268
269  public static long getTotalBytesRead() {
270    synchronized (readStatistics) {
271      return readStatistics.totalBytesRead;
272    }
273  }
274
275  public static long getLocalBytesRead() {
276    synchronized (readStatistics) {
277      return readStatistics.totalLocalBytesRead;
278    }
279  }
280
281  public static long getShortCircuitBytesRead() {
282    synchronized (readStatistics) {
283      return readStatistics.totalShortCircuitBytesRead;
284    }
285  }
286
287  public static long getZeroCopyBytesRead() {
288    synchronized (readStatistics) {
289      return readStatistics.totalZeroCopyBytesRead;
290    }
291  }
292
293  /** CloseClose stream(s) if necessary. */
294  @Override
295  public void close() {
296    if (!doCloseStreams) {
297      return;
298    }
299    updateInputStreamStatistics(this.streamNoFsChecksum);
300    // we do not care about the close exception as it is for reading, no data loss issue.
301    Closeables.closeQuietly(streamNoFsChecksum);
302
303    updateInputStreamStatistics(stream);
304    Closeables.closeQuietly(stream);
305  }
306
307  public HFileSystem getHfs() {
308    return this.hfs;
309  }
310
311  /**
312   * This will free sockets and file descriptors held by the stream only when the stream implements
313   * org.apache.hadoop.fs.CanUnbuffer. NOT THREAD SAFE. Must be called only when all the clients
314   * using this stream to read the blocks have finished reading. If by chance the stream is
315   * unbuffered and there are clients still holding this stream for read then on next client read
316   * request a new socket will be opened by Datanode without client knowing about it and will serve
317   * its read request. Note: If this socket is idle for some time then the DataNode will close the
318   * socket and the socket will move into CLOSE_WAIT state and on the next client request on this
319   * stream, the current socket will be closed and a new socket will be opened to serve the
320   * requests.
321   */
322  public void unbuffer() {
323    // todo: it may make sense to always unbuffer both streams. we'd need to carefully
324    // research the usages to know if that is safe. for now just do the current.
325    FSDataInputStream stream = this.getStream(this.shouldUseHBaseChecksum());
326    if (stream != null) {
327      stream.unbuffer();
328    }
329  }
330
331  public Path getReaderPath() {
332    return readerPath;
333  }
334
335  // For tests
336  void setShouldUseHBaseChecksum() {
337    useHBaseChecksumConfigured = true;
338    useHBaseChecksum = true;
339  }
340}