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.hfile;
019
020import java.io.IOException;
021import java.util.Optional;
022import org.apache.commons.lang3.mutable.MutableBoolean;
023import org.apache.hadoop.conf.Configuration;
024import org.apache.hadoop.fs.Path;
025import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
026import org.apache.yetus.audience.InterfaceAudience;
027import org.slf4j.Logger;
028import org.slf4j.LoggerFactory;
029
030/**
031 * Implementation of {@link HFile.Reader} to deal with pread.
032 */
033@InterfaceAudience.Private
034public class HFilePreadReader extends HFileReaderImpl {
035  private static final Logger LOG = LoggerFactory.getLogger(HFileReaderImpl.class);
036
037  private static final int WAIT_TIME_FOR_CACHE_INITIALIZATION = 10 * 60 * 1000;
038
039  public HFilePreadReader(ReaderContext context, HFileInfo fileInfo, CacheConfig cacheConf,
040    Configuration conf) throws IOException {
041    super(context, fileInfo, cacheConf, conf);
042    // master hosted regions, like the master procedures store wouldn't have a block cache
043    final MutableBoolean shouldCache = new MutableBoolean(cacheConf.getBlockCache().isPresent());
044    // Prefetch file blocks upon open if requested
045    if (shouldCache.booleanValue() && cacheConf.shouldPrefetchOnOpen()) {
046      PrefetchExecutor.request(path, new Runnable() {
047        @Override
048        public void run() {
049          long offset = 0;
050          long end = 0;
051          HFile.Reader prefetchStreamReader = null;
052          try {
053            cacheConf.getBlockCache().ifPresent(cache -> {
054              cache.waitForCacheInitialization(WAIT_TIME_FOR_CACHE_INITIALIZATION);
055              Optional<Boolean> result = cache.shouldCacheFile(path.getName());
056              shouldCache.setValue(result.isPresent() ? result.get().booleanValue() : true);
057            });
058            if (!shouldCache.booleanValue()) {
059              LOG.info("Prefetch skipped for file: {}", path);
060              return;
061            }
062
063            ReaderContext streamReaderContext = ReaderContextBuilder.newBuilder(context)
064              .withReaderType(ReaderContext.ReaderType.STREAM)
065              .withInputStreamWrapper(new FSDataInputStreamWrapper(context.getFileSystem(),
066                context.getInputStreamWrapper().getReaderPath()))
067              .build();
068            prefetchStreamReader =
069              new HFileStreamReader(streamReaderContext, fileInfo, cacheConf, conf);
070            end = getTrailer().getLoadOnOpenDataOffset();
071            if (LOG.isTraceEnabled()) {
072              LOG.trace("Prefetch start " + getPathOffsetEndStr(path, offset, end));
073            }
074            // Don't use BlockIterator here, because it's designed to read load-on-open section.
075            long onDiskSizeOfNextBlock = -1;
076            // if we are here, block cache is present anyways
077            BlockCache cache = cacheConf.getBlockCache().get();
078            boolean interrupted = false;
079            int blockCount = 0;
080            int dataBlockCount = 0;
081            while (offset < end) {
082              if (Thread.interrupted()) {
083                break;
084              }
085              // Some cache implementations can be persistent and resilient to restarts,
086              // so we check first if the block exists on its in-memory index, if so, we just
087              // update the offset and move on to the next block without actually going read all
088              // the way to the cache.
089              BlockCacheKey cacheKey = new BlockCacheKey(name, offset);
090              if (cache.isAlreadyCached(cacheKey).orElse(false)) {
091                // Right now, isAlreadyCached is only supported by BucketCache, which should
092                // always cache data blocks.
093                int size = cache.getBlockSize(cacheKey).orElse(0);
094                if (size > 0) {
095                  offset += size;
096                  LOG.debug("Found block of size {} for cache key {}. "
097                    + "Skipping prefetch, the block is already cached.", size, cacheKey);
098                  blockCount++;
099                  dataBlockCount++;
100                  continue;
101                } else {
102                  LOG.debug("Found block for cache key {}, but couldn't get its size. "
103                    + "Maybe the cache implementation doesn't support it? "
104                    + "We'll need to read the block from cache or file system. ", cacheKey);
105                }
106              } else {
107                LOG.debug("No entry in the backing map for cache key {}. ", cacheKey);
108              }
109              // Perhaps we got our block from cache? Unlikely as this may be, if it happens, then
110              // the internal-to-hfileblock thread local which holds the overread that gets the
111              // next header, will not have happened...so, pass in the onDiskSize gotten from the
112              // cached block. This 'optimization' triggers extremely rarely I'd say.
113              HFileBlock block = prefetchStreamReader.readBlock(offset, onDiskSizeOfNextBlock,
114                /* cacheBlock= */true, /* pread= */false, false, false, null, null, true);
115              try {
116                if (!cacheConf.isInMemory()) {
117                  if (!cache.blockFitsIntoTheCache(block).orElse(true)) {
118                    LOG.warn(
119                      "Interrupting prefetch for file {} because block {} of size {} "
120                        + "doesn't fit in the available cache space. isCacheEnabled: {}",
121                      path, cacheKey, block.getOnDiskSizeWithHeader(), cache.isCacheEnabled());
122                    interrupted = true;
123                    break;
124                  }
125                  if (!cacheConf.isHeapUsageBelowThreshold()) {
126                    LOG.warn(
127                      "Interrupting prefetch because heap usage is above the threshold: {} "
128                        + "configured via {}",
129                      cacheConf.getHeapUsageThreshold(), CacheConfig.PREFETCH_HEAP_USAGE_THRESHOLD);
130                    interrupted = true;
131                    break;
132                  }
133                }
134                onDiskSizeOfNextBlock = block.getNextBlockOnDiskSize();
135                offset += block.getOnDiskSizeWithHeader();
136                blockCount++;
137                if (block.getBlockType().isData()) {
138                  dataBlockCount++;
139                }
140              } finally {
141                // Ideally here the readBlock won't find the block in cache. We call this
142                // readBlock so that block data is read from FS and cached in BC. we must call
143                // returnBlock here to decrease the reference count of block.
144                block.release();
145              }
146            }
147            if (!interrupted) {
148              cacheConf.getBlockCache().get().notifyFileCachingCompleted(path, blockCount,
149                dataBlockCount, offset);
150            }
151          } catch (IOException e) {
152            // IOExceptions are probably due to region closes (relocation, etc.)
153            if (LOG.isTraceEnabled()) {
154              LOG.trace("Prefetch " + getPathOffsetEndStr(path, offset, end), e);
155            }
156          } catch (Throwable e) {
157            // Other exceptions are interesting
158            LOG.warn("Prefetch " + getPathOffsetEndStr(path, offset, end), e);
159          } finally {
160            if (prefetchStreamReader != null) {
161              try {
162                prefetchStreamReader.close(false);
163              } catch (IOException e) {
164                LOG.warn("Close prefetch stream reader failed, path: " + path, e);
165              }
166            }
167            PrefetchExecutor.complete(path);
168          }
169        }
170      });
171    }
172  }
173
174  /*
175   * Get the region name for the given file path. A HFile is always kept under the <region>/<column
176   * family>/<hfile>. To find the region for a given hFile, just find the name of the grandparent
177   * directory.
178   */
179  private static String getRegionName(Path path) {
180    return path.getParent().getParent().getName();
181  }
182
183  private static String getPathOffsetEndStr(final Path path, final long offset, final long end) {
184    return "path=" + path.toString() + ", offset=" + offset + ", end=" + end;
185  }
186
187  public void close(boolean evictOnClose) throws IOException {
188    PrefetchExecutor.cancel(path);
189    // Deallocate blocks in load-on-open section
190    this.fileInfo.close();
191    // Deallocate data blocks
192    cacheConf.getBlockCache().ifPresent(cache -> {
193      if (evictOnClose) {
194        int numEvicted = cache.evictBlocksByHfileName(name);
195        if (LOG.isTraceEnabled()) {
196          LOG.trace("On close, file= {} evicted= {} block(s)", name, numEvicted);
197        }
198      }
199    });
200    fsBlockReader.closeStreams();
201  }
202}