You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by mi...@apache.org on 2018/09/21 16:03:15 UTC
[7/7] impala git commit: IMPALA-7556: part 1: handle different file
systems via polymorphism
IMPALA-7556: part 1: handle different file systems via polymorphism
This commit reorganizes some parts of the ScanRange class.
File operations are handled through the abstract FileReader
class. The interface supports positional read that will
be needed by IMPALA-5843. The concrete file operations are
implemented in sub-classes LocalFileReader and
HdfsFileReader.
File reader classes are responsible for setting counters and
metrics related to file operations.
The core logic haven't been changed significantly, but quite
a lot code fragments were relocated.
Testing: Debug exhaustive tests passed
Change-Id: Ia3d3d2d774075008285230606b992603d5be1a82
Reviewed-on: http://gerrit.cloudera.org:8080/11444
Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
Tested-by: Impala Public Jenkins <im...@cloudera.com>
Project: http://git-wip-us.apache.org/repos/asf/impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/impala/commit/d7b8275e
Tree: http://git-wip-us.apache.org/repos/asf/impala/tree/d7b8275e
Diff: http://git-wip-us.apache.org/repos/asf/impala/diff/d7b8275e
Branch: refs/heads/master
Commit: d7b8275ed04581c4b9bef60ae0abdb7201661618
Parents: ad3e1c9
Author: Zoltan Borok-Nagy <bo...@cloudera.com>
Authored: Tue Sep 11 19:06:50 2018 +0200
Committer: Impala Public Jenkins <im...@cloudera.com>
Committed: Fri Sep 21 15:59:16 2018 +0000
----------------------------------------------------------------------
be/src/runtime/io/CMakeLists.txt | 3 +
be/src/runtime/io/disk-io-mgr.h | 1 +
be/src/runtime/io/file-reader.cc | 31 +++
be/src/runtime/io/file-reader.h | 90 +++++++
be/src/runtime/io/hdfs-file-reader.cc | 295 +++++++++++++++++++++++
be/src/runtime/io/hdfs-file-reader.h | 84 +++++++
be/src/runtime/io/local-file-reader.cc | 112 +++++++++
be/src/runtime/io/local-file-reader.h | 45 ++++
be/src/runtime/io/request-context.h | 1 +
be/src/runtime/io/request-ranges.h | 122 +++-------
be/src/runtime/io/scan-range.cc | 354 ++++------------------------
11 files changed, 738 insertions(+), 400 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/CMakeLists.txt b/be/src/runtime/io/CMakeLists.txt
index 4c8199f..bb26ef0 100644
--- a/be/src/runtime/io/CMakeLists.txt
+++ b/be/src/runtime/io/CMakeLists.txt
@@ -29,6 +29,9 @@ add_library(Io
error-converter.cc
request-context.cc
scan-range.cc
+ file-reader.cc
+ hdfs-file-reader.cc
+ local-file-reader.cc
)
add_dependencies(Io gen-deps)
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/disk-io-mgr.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/disk-io-mgr.h b/be/src/runtime/io/disk-io-mgr.h
index 35d11b9..d5c7643 100644
--- a/be/src/runtime/io/disk-io-mgr.h
+++ b/be/src/runtime/io/disk-io-mgr.h
@@ -360,6 +360,7 @@ class DiskIoMgr : public CacheLineAligned {
/// BEGIN: private members that are accessed by other io:: classes
friend class DiskQueue;
friend class ScanRange;
+ friend class HdfsFileReader;
/// Write the specified range to disk and calls writer_context->WriteDone() when done.
/// Responsible for opening and closing the file that is written.
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/file-reader.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/file-reader.cc b/be/src/runtime/io/file-reader.cc
new file mode 100644
index 0000000..81ef090
--- /dev/null
+++ b/be/src/runtime/io/file-reader.cc
@@ -0,0 +1,31 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "gutil/strings/substitute.h"
+#include "runtime/io/file-reader.h"
+
+#include "common/names.h"
+
+namespace impala {
+namespace io {
+
+string FileReader::DebugString() const {
+ return Substitute("bytes_read=$0", bytes_read_);
+}
+
+}
+}
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/file-reader.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/file-reader.h b/be/src/runtime/io/file-reader.h
new file mode 100644
index 0000000..40f2a5c
--- /dev/null
+++ b/be/src/runtime/io/file-reader.h
@@ -0,0 +1,90 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include <string>
+
+#include "util/spinlock.h"
+
+#include "common/status.h"
+
+namespace impala {
+namespace io {
+
+class DiskIoMgr;
+class RequestContext;
+class ScanRange;
+
+/// Abstract class that provides interface for file operations
+/// Child classes implement these operations for the local file system
+/// and for HDFS.
+/// A FileReader object is owned by a single ScanRange object, and
+/// a ScanRange object only has a single FileReader object.
+class FileReader {
+public:
+ FileReader(ScanRange* scan_range) : scan_range_(scan_range) {}
+ virtual ~FileReader() {}
+
+ /// Returns number of bytes read by this file reader.
+ int bytes_read() const { return bytes_read_; }
+
+ /// Opens file that is associated with 'scan_range_'.
+ /// 'use_file_handle_cache' currently only used by HdfsFileReader.
+ virtual Status Open(bool use_file_handle_cache) = 0;
+
+ /// Reads bytes from given position ('file_offset'). Tries to read
+ /// 'bytes_to_read' amount of bytes. 'bytes_read' contains the number of
+ /// bytes actually read. 'eosr' is set to true when end of file has reached,
+ /// or the file reader has read all the bytes needed by 'scan_range_'.
+ virtual Status ReadFromPos(int64_t file_offset, uint8_t* buffer,
+ int64_t bytes_to_read, int64_t* bytes_read, bool* eosr) = 0;
+
+ /// ***Currently only for HDFS***
+ /// Returns a pointer to a cached buffer that contains the contents of the file.
+ virtual void* CachedFile() = 0;
+
+ /// Closes the file associated with 'scan_range_'. It doesn't have effect on other
+ /// scan ranges.
+ virtual void Close() = 0;
+
+ /// Reset internal bookkeeping, e.g. how many bytes have been read.
+ virtual void ResetState() { bytes_read_ = 0; }
+
+ // Debug string of this file reader.
+ virtual std::string DebugString() const;
+
+ SpinLock& lock() { return lock_; }
+protected:
+ /// Lock that should be taken during fs calls. Only one thread (the disk reading
+ /// thread) calls into fs at a time so this lock does not have performance impact.
+ /// This lock only serves to coordinate cleanup. Specifically it serves to ensure
+ /// that the disk threads are finished with FS calls before scan_range_->is_cancelled_
+ /// is set to true and cleanup starts.
+ /// If this lock and scan_range_->lock_ need to be taken, scan_range_->lock_ must be
+ /// taken first.
+ SpinLock lock_;
+
+ /// The scan range this file reader serves.
+ ScanRange* const scan_range_;
+
+ /// Number of bytes read by this reader.
+ int bytes_read_ = 0;
+};
+
+}
+}
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/hdfs-file-reader.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/hdfs-file-reader.cc b/be/src/runtime/io/hdfs-file-reader.cc
new file mode 100644
index 0000000..ea61b6a
--- /dev/null
+++ b/be/src/runtime/io/hdfs-file-reader.cc
@@ -0,0 +1,295 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <algorithm>
+
+#include "gutil/strings/substitute.h"
+#include "runtime/io/disk-io-mgr-internal.h"
+#include "runtime/io/hdfs-file-reader.h"
+#include "runtime/io/request-context.h"
+#include "runtime/io/request-ranges.h"
+#include "util/hdfs-util.h"
+#include "util/impalad-metrics.h"
+
+#include "common/names.h"
+
+DEFINE_bool(use_hdfs_pread, false, "Enables using hdfsPread() instead of hdfsRead() "
+ "when performing HDFS read operations. This is necessary to use HDFS hedged reads "
+ "(assuming the HDFS client is configured to do so).");
+
+#ifndef NDEBUG
+DECLARE_int32(stress_disk_read_delay_ms);
+#endif
+
+namespace impala {
+namespace io {
+
+HdfsFileReader::~HdfsFileReader() {
+ DCHECK(exclusive_hdfs_fh_ == nullptr) << "File was not closed.";
+}
+
+Status HdfsFileReader::Open(bool use_file_handle_cache) {
+ unique_lock<SpinLock> hdfs_lock(lock_);
+ RETURN_IF_ERROR(scan_range_->cancel_status_);
+
+ if (exclusive_hdfs_fh_ != nullptr) return Status::OK();
+ // With file handle caching, the reader does not maintain its own
+ // hdfs file handle. File handle caching is only used for local files,
+ // so s3 and remote filesystems should obtain an exclusive file handle
+ // for each scan range.
+ if (use_file_handle_cache && expected_local_) return Status::OK();
+ auto io_mgr = scan_range_->io_mgr_;
+ // Get a new exclusive file handle.
+ exclusive_hdfs_fh_ = io_mgr->GetExclusiveHdfsFileHandle(hdfs_fs_,
+ scan_range_->file_string(), scan_range_->mtime(), scan_range_->reader_);
+ if (exclusive_hdfs_fh_ == nullptr) {
+ return Status(TErrorCode::DISK_IO_ERROR,
+ GetHdfsErrorMsg("Failed to open HDFS file ", *scan_range_->file_string()));
+ }
+ if (hdfsSeek(hdfs_fs_, exclusive_hdfs_fh_->file(), scan_range_->offset_) != 0) {
+ // Destroy the file handle
+ io_mgr->ReleaseExclusiveHdfsFileHandle(exclusive_hdfs_fh_);
+ exclusive_hdfs_fh_ = nullptr;
+ return Status(TErrorCode::DISK_IO_ERROR,
+ Substitute("Error seeking to $0 in file: $1 $2", scan_range_->offset(),
+ *scan_range_->file_string(), GetHdfsErrorMsg("")));
+ }
+ ImpaladMetrics::IO_MGR_NUM_OPEN_FILES->Increment(1L);
+ return Status::OK();
+}
+
+Status HdfsFileReader::ReadFromPos(int64_t file_offset, uint8_t* buffer,
+ int64_t bytes_to_read, int64_t* bytes_read, bool* eosr) {
+ DCHECK(scan_range_->read_in_flight());
+ DCHECK_GE(bytes_to_read, 0);
+ // Delay before acquiring the lock, to allow triggering IMPALA-6587 race.
+#ifndef NDEBUG
+ if (FLAGS_stress_disk_read_delay_ms > 0) {
+ SleepForMs(FLAGS_stress_disk_read_delay_ms);
+ }
+#endif
+ unique_lock<SpinLock> hdfs_lock(lock_);
+ RETURN_IF_ERROR(scan_range_->cancel_status_);
+
+ auto io_mgr = scan_range_->io_mgr_;
+ auto request_context = scan_range_->reader_;
+ *eosr = false;
+ *bytes_read = 0;
+
+ CachedHdfsFileHandle* borrowed_hdfs_fh = nullptr;
+ hdfsFile hdfs_file;
+
+ // If the reader has an exclusive file handle, use it. Otherwise, borrow
+ // a file handle from the cache.
+ if (exclusive_hdfs_fh_ != nullptr) {
+ hdfs_file = exclusive_hdfs_fh_->file();
+ } else {
+ borrowed_hdfs_fh = io_mgr->GetCachedHdfsFileHandle(hdfs_fs_,
+ scan_range_->file_string(),
+ scan_range_->mtime(), request_context);
+ if (borrowed_hdfs_fh == nullptr) {
+ return Status(TErrorCode::DISK_IO_ERROR,
+ GetHdfsErrorMsg("Failed to open HDFS file ", *scan_range_->file_string()));
+ }
+ hdfs_file = borrowed_hdfs_fh->file();
+ }
+
+ int64_t max_chunk_size = scan_range_->MaxReadChunkSize();
+ Status status = Status::OK();
+ {
+ ScopedTimer<MonotonicStopWatch> req_context_read_timer(
+ scan_range_->reader_->read_timer_);
+ while (*bytes_read < bytes_to_read) {
+ int chunk_size = min(bytes_to_read - *bytes_read, max_chunk_size);
+ DCHECK_GT(chunk_size, 0);
+ // The hdfsRead() length argument is an int.
+ DCHECK_LE(chunk_size, numeric_limits<int>::max());
+ int current_bytes_read = -1;
+ // bytes_read_ is only updated after the while loop
+ int64_t position_in_file = file_offset + *bytes_read;
+
+ // ReadFromPosInternal() might fail due to a bad file handle.
+ // If that was the case, allow for a retry to fix it.
+ status = ReadFromPosInternal(hdfs_file, position_in_file,
+ borrowed_hdfs_fh != nullptr, buffer + *bytes_read, chunk_size,
+ ¤t_bytes_read);
+
+ // Retry if:
+ // - first read was not successful
+ // and
+ // - used a borrowed file handle
+ if (!status.ok() && borrowed_hdfs_fh != nullptr) {
+ // The error may be due to a bad file handle. Reopen the file handle and retry.
+ // Exclude this time from the read timers.
+ req_context_read_timer.Stop();
+ RETURN_IF_ERROR(io_mgr->ReopenCachedHdfsFileHandle(hdfs_fs_,
+ scan_range_->file_string(), scan_range_->mtime(),
+ request_context, &borrowed_hdfs_fh));
+ hdfs_file = borrowed_hdfs_fh->file();
+ req_context_read_timer.Start();
+ status = ReadFromPosInternal(hdfs_file, position_in_file,
+ borrowed_hdfs_fh != nullptr, buffer + *bytes_read, chunk_size,
+ ¤t_bytes_read);
+ }
+ if (!status.ok()) {
+ break;
+ }
+ DCHECK_GT(current_bytes_read, -1);
+ if (current_bytes_read == 0) {
+ // No more bytes in the file. The scan range went past the end.
+ *eosr = true;
+ break;
+ }
+ *bytes_read += current_bytes_read;
+
+ // Collect and accumulate statistics
+ GetHdfsStatistics(hdfs_file);
+ }
+ }
+
+ if (borrowed_hdfs_fh != nullptr) {
+ io_mgr->ReleaseCachedHdfsFileHandle(scan_range_->file_string(), borrowed_hdfs_fh);
+ }
+ if (!status.ok())
+ return status;
+ bytes_read_ += *bytes_read;
+ DCHECK_LE(bytes_read_, scan_range_->len());
+ if (bytes_read_ == scan_range_->len()) *eosr = true;
+ return Status::OK();
+}
+
+Status HdfsFileReader::ReadFromPosInternal(hdfsFile hdfs_file, int64_t position_in_file,
+ bool is_borrowed_fh, uint8_t* buffer, int64_t chunk_size, int* bytes_read) {
+ // For file handles from the cache, any of the below file operations may fail
+ // due to a bad file handle.
+ if (FLAGS_use_hdfs_pread) {
+ *bytes_read = hdfsPread(hdfs_fs_, hdfs_file, position_in_file, buffer, chunk_size);
+ if (*bytes_read == -1) {
+ return Status(TErrorCode::DISK_IO_ERROR,
+ GetHdfsErrorMsg("Error reading from HDFS file: ",
+ *scan_range_->file_string()));
+ }
+ } else {
+ // If the file handle is borrowed, it may not be at the appropriate
+ // location. Seek to the appropriate location.
+ if (is_borrowed_fh) {
+ if (hdfsSeek(hdfs_fs_, hdfs_file, position_in_file) != 0) {
+ return Status(TErrorCode::DISK_IO_ERROR,
+ Substitute("Error seeking to $0 in file: $1: $2",
+ position_in_file, *scan_range_->file_string(), GetHdfsErrorMsg("")));
+ }
+ }
+ *bytes_read = hdfsRead(hdfs_fs_, hdfs_file, buffer, chunk_size);
+ if (*bytes_read == -1) {
+ return Status(TErrorCode::DISK_IO_ERROR,
+ GetHdfsErrorMsg("Error reading from HDFS file: ",
+ *scan_range_->file_string()));
+ }
+ }
+ return Status::OK();
+}
+
+void* HdfsFileReader::CachedFile() {
+ {
+ unique_lock<SpinLock> hdfs_lock(lock_);
+ DCHECK(exclusive_hdfs_fh_ != nullptr);
+ cached_buffer_ = hadoopReadZero(exclusive_hdfs_fh_->file(),
+ scan_range_->io_mgr_->cached_read_options(), scan_range_->len());
+ }
+ if (cached_buffer_ == nullptr) return nullptr;
+ bytes_read_ = hadoopRzBufferLength(cached_buffer_);
+ return const_cast<void*>(hadoopRzBufferGet(cached_buffer_));
+}
+
+void HdfsFileReader::Close() {
+ unique_lock<SpinLock> hdfs_lock(lock_);
+ if (exclusive_hdfs_fh_ != nullptr) {
+ GetHdfsStatistics(exclusive_hdfs_fh_->file());
+
+ if (scan_range_->external_buffer_tag_ ==
+ ScanRange::ExternalBufferTag::CACHED_BUFFER) {
+ hadoopRzBufferFree(exclusive_hdfs_fh_->file(), cached_buffer_);
+ cached_buffer_ = nullptr;
+ scan_range_->external_buffer_tag_ = ScanRange::ExternalBufferTag::NO_BUFFER;
+ }
+
+ // Destroy the file handle.
+ scan_range_->io_mgr_->ReleaseExclusiveHdfsFileHandle(exclusive_hdfs_fh_);
+ exclusive_hdfs_fh_ = nullptr;
+ ImpaladMetrics::IO_MGR_NUM_OPEN_FILES->Increment(-1L);
+ }
+
+ if (FLAGS_use_hdfs_pread && IsHdfsPath(scan_range_->file())) {
+ // Update Hedged Read Metrics.
+ // We call it only if the --use_hdfs_pread flag is set, to avoid having the
+ // libhdfs client malloc and free a hdfsHedgedReadMetrics object unnecessarily
+ // otherwise. 'hedged_metrics' is only set upon success.
+ // We also avoid calling hdfsGetHedgedReadMetrics() when the file is not on HDFS
+ // (see HDFS-13417).
+ struct hdfsHedgedReadMetrics* hedged_metrics;
+ int success = hdfsGetHedgedReadMetrics(hdfs_fs_, &hedged_metrics);
+ if (success == 0) {
+ ImpaladMetrics::HEDGED_READ_OPS->SetValue(hedged_metrics->hedgedReadOps);
+ ImpaladMetrics::HEDGED_READ_OPS_WIN->SetValue(
+ hedged_metrics->hedgedReadOpsWin);
+ hdfsFreeHedgedReadMetrics(hedged_metrics);
+ }
+ }
+
+ if (num_remote_bytes_ > 0) {
+ scan_range_->reader_->num_remote_ranges_.Add(1L);
+ if (expected_local_) {
+ scan_range_->reader_->unexpected_remote_bytes_.Add(num_remote_bytes_);
+ VLOG_FILE << "Unexpected remote HDFS read of "
+ << PrettyPrinter::Print(num_remote_bytes_, TUnit::BYTES)
+ << " for file '" << *scan_range_->file_string() << "'";
+ }
+ }
+}
+
+void HdfsFileReader::GetHdfsStatistics(hdfsFile hdfs_file) {
+ struct hdfsReadStatistics* stats;
+ if (IsHdfsPath(scan_range_->file())) {
+ int success = hdfsFileGetReadStatistics(hdfs_file, &stats);
+ if (success == 0) {
+ scan_range_->reader_->bytes_read_local_.Add(stats->totalLocalBytesRead);
+ scan_range_->reader_->bytes_read_short_circuit_.Add(
+ stats->totalShortCircuitBytesRead);
+ scan_range_->reader_->bytes_read_dn_cache_.Add(stats->totalZeroCopyBytesRead);
+ if (stats->totalLocalBytesRead != stats->totalBytesRead) {
+ num_remote_bytes_ += stats->totalBytesRead - stats->totalLocalBytesRead;
+ }
+ hdfsFileFreeReadStatistics(stats);
+ }
+ hdfsFileClearReadStatistics(hdfs_file);
+ }
+}
+
+void HdfsFileReader::ResetState() {
+ FileReader::ResetState();
+ num_remote_bytes_ = 0;
+}
+
+string HdfsFileReader::DebugString() const {
+ return FileReader::DebugString() + Substitute(
+ " exclusive_hdfs_fh=$0 num_remote_bytes=$1",
+ exclusive_hdfs_fh_, num_remote_bytes_);
+}
+
+}
+}
+
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/hdfs-file-reader.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/hdfs-file-reader.h b/be/src/runtime/io/hdfs-file-reader.h
new file mode 100644
index 0000000..3b3642b
--- /dev/null
+++ b/be/src/runtime/io/hdfs-file-reader.h
@@ -0,0 +1,84 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include "common/hdfs.h"
+#include "runtime/io/file-reader.h"
+
+namespace impala {
+namespace io {
+
+/// File reader class for HDFS.
+class HdfsFileReader : public FileReader {
+public:
+ HdfsFileReader(ScanRange* scan_range, hdfsFS hdfs_fs, bool expected_local) :
+ FileReader(scan_range), hdfs_fs_(hdfs_fs), expected_local_(expected_local) {
+ }
+
+ ~HdfsFileReader();
+
+ virtual Status Open(bool use_file_handle_cache) override;
+ virtual Status ReadFromPos(int64_t file_offset, uint8_t* buffer,
+ int64_t bytes_to_read, int64_t* bytes_read, bool* eosr) override;
+ /// Reads from the DN cache. On success, sets cached_buffer_ to the DN
+ /// buffer and returns a pointer to the underlying raw buffer.
+ /// Returns nullptr if the data is not cached.
+ virtual void* CachedFile() override;
+ virtual void Close() override;
+ virtual void ResetState() override;
+ virtual std::string DebugString() const override;
+private:
+ Status ReadFromPosInternal(hdfsFile hdfs_file, int64_t position_in_file,
+ bool is_borrowed_fh, uint8_t* buffer, int64_t chunk_size, int* bytes_read);
+ void GetHdfsStatistics(hdfsFile hdfs_file);
+
+ /// Hadoop filesystem that contains the file being read.
+ hdfsFS const hdfs_fs_;
+
+ /// The hdfs file handle is stored here in three cases:
+ /// 1. The file handle cache is off (max_cached_file_handles == 0).
+ /// 2. The scan range is using hdfs caching.
+ /// -OR-
+ /// 3. The hdfs file is expected to be remote (expected_local_ == false)
+ /// In each case, the scan range gets a new ExclusiveHdfsFileHandle at Open(),
+ /// owns it exclusively, and destroys it in Close().
+ ExclusiveHdfsFileHandle* exclusive_hdfs_fh_ = nullptr;
+
+ /// If true, we expect the reads to be a local read. Note that if this is false,
+ /// it does not necessarily mean we expect the read to be remote, and that we never
+ /// create scan ranges where some of the range is expected to be remote and some of it
+ /// local.
+ /// TODO: we can do more with this
+ const bool expected_local_;
+
+ /// Total number of bytes read remotely. This is necessary to maintain a count of
+ /// the number of remote scan ranges. Since IO statistics can be collected multiple
+ /// times for a scan range, it is necessary to keep some state about whether this
+ /// scan range has already been counted as remote. There is also a requirement to
+ /// log the number of unexpected remote bytes for a scan range. To solve both
+ /// requirements, maintain num_remote_bytes_ on the ScanRange and push it to the
+ /// reader_ once at the close of the scan range.
+ int64_t num_remote_bytes_ = 0;
+
+ /// Non-NULL if a cached read succeeded. Then all the bytes for the file are in
+ /// this buffer.
+ hadoopRzBuffer* cached_buffer_ = nullptr;
+};
+
+}
+}
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/local-file-reader.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/local-file-reader.cc b/be/src/runtime/io/local-file-reader.cc
new file mode 100644
index 0000000..47c025b
--- /dev/null
+++ b/be/src/runtime/io/local-file-reader.cc
@@ -0,0 +1,112 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <algorithm>
+#include <stdio.h>
+
+#include "runtime/io/local-file-reader.h"
+#include "runtime/io/request-ranges.h"
+#include "util/impalad-metrics.h"
+
+#include "common/names.h"
+
+#ifndef NDEBUG
+DECLARE_int32(stress_disk_read_delay_ms);
+#endif
+
+namespace impala {
+namespace io {
+
+Status LocalFileReader::Open(bool use_file_handle_cache) {
+ unique_lock<SpinLock> fs_lock(lock_);
+ RETURN_IF_ERROR(scan_range_->cancel_status_);
+
+ if (file_ != nullptr)
+ return Status::OK();
+
+ file_ = fopen(scan_range_->file(), "r");
+ if (file_ == nullptr) {
+ return Status(TErrorCode::DISK_IO_ERROR,
+ Substitute("Could not open file: $0: $1", *scan_range_->file_string(),
+ GetStrErrMsg()));
+ }
+ ImpaladMetrics::IO_MGR_NUM_OPEN_FILES->Increment(1L);
+ return Status::OK();
+}
+
+Status LocalFileReader::ReadFromPos(int64_t file_offset, uint8_t* buffer,
+ int64_t bytes_to_read, int64_t* bytes_read, bool* eosr) {
+ DCHECK(scan_range_->read_in_flight());
+ DCHECK_GE(bytes_to_read, 0);
+ // Delay before acquiring the lock, to allow triggering IMPALA-6587 race.
+#ifndef NDEBUG
+ if (FLAGS_stress_disk_read_delay_ms > 0) {
+ SleepForMs(FLAGS_stress_disk_read_delay_ms);
+ }
+#endif
+ unique_lock<SpinLock> fs_lock(lock_);
+ RETURN_IF_ERROR(scan_range_->cancel_status_);
+
+ *eosr = false;
+ *bytes_read = 0;
+
+ DCHECK(file_ != nullptr);
+ if (fseek(file_, file_offset, SEEK_SET) == -1) {
+ fclose(file_);
+ file_ = nullptr;
+ return Status(TErrorCode::DISK_IO_ERROR,
+ Substitute("Could not seek to $0 "
+ "for file: $1: $2", scan_range_->offset(),
+ *scan_range_->file_string(), GetStrErrMsg()));
+ }
+ *bytes_read = fread(buffer, 1, bytes_to_read, file_);
+ DCHECK_GE(*bytes_read, 0);
+ DCHECK_LE(*bytes_read, bytes_to_read);
+ if (*bytes_read < bytes_to_read) {
+ if (ferror(file_) != 0) {
+ return Status(TErrorCode::DISK_IO_ERROR,
+ Substitute("Error reading from $0"
+ "at byte offset: $1: $2", file_,
+ file_offset, GetStrErrMsg()));
+ }
+ // On Linux, we should only get partial reads from block devices on error or eof.
+ DCHECK(feof(file_) != 0);
+ *eosr = true;
+ }
+ bytes_read_ += *bytes_read;
+ DCHECK_LE(bytes_read_, scan_range_->len());
+ if (bytes_read_ == scan_range_->len()) *eosr = true;
+ return Status::OK();
+}
+
+void* LocalFileReader::CachedFile() {
+ DCHECK(false);
+ return nullptr;
+}
+
+void LocalFileReader::Close() {
+ unique_lock<SpinLock> fs_lock(lock_);
+ if (file_ == nullptr) return;
+ fclose(file_);
+ file_ = nullptr;
+ ImpaladMetrics::IO_MGR_NUM_OPEN_FILES->Increment(-1L);
+ return;
+}
+
+}
+}
+
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/local-file-reader.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/local-file-reader.h b/be/src/runtime/io/local-file-reader.h
new file mode 100644
index 0000000..d8eedd1
--- /dev/null
+++ b/be/src/runtime/io/local-file-reader.h
@@ -0,0 +1,45 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include "common/hdfs.h"
+#include "runtime/io/file-reader.h"
+
+namespace impala {
+namespace io {
+
+/// File reader class for the local file system.
+/// It uses the standard C APIs from stdio.h
+class LocalFileReader : public FileReader {
+public:
+ LocalFileReader(ScanRange* scan_range) : FileReader(scan_range) {}
+ ~LocalFileReader() {}
+
+ virtual Status Open(bool use_file_handle_cache) override;
+ virtual Status ReadFromPos(int64_t file_offset, uint8_t* buffer,
+ int64_t bytes_to_read, int64_t* bytes_read, bool* eosr) override;
+ /// We don't cache files of the local file system.
+ virtual void* CachedFile() override;
+ virtual void Close() override;
+private:
+ /// Points to a C FILE object between calls to Open() and Close(), otherwise nullptr.
+ FILE* file_ = nullptr;
+};
+
+}
+}
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/request-context.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/request-context.h b/be/src/runtime/io/request-context.h
index ab09fb1..0fcbca3 100644
--- a/be/src/runtime/io/request-context.h
+++ b/be/src/runtime/io/request-context.h
@@ -185,6 +185,7 @@ class RequestContext {
friend class DiskQueue;
friend class DiskIoMgr;
friend class ScanRange;
+ friend class HdfsFileReader;
enum State {
/// Reader is initialized and maps to a client
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/request-ranges.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/request-ranges.h b/be/src/runtime/io/request-ranges.h
index 3bdacfd..3bf55d6 100644
--- a/be/src/runtime/io/request-ranges.h
+++ b/be/src/runtime/io/request-ranges.h
@@ -36,6 +36,7 @@ namespace io {
class DiskIoMgr;
class DiskQueue;
class ExclusiveHdfsFileHandle;
+class FileReader;
class RequestContext;
class ScanRange;
@@ -66,6 +67,7 @@ class BufferDescriptor {
DISALLOW_COPY_AND_ASSIGN(BufferDescriptor);
/// This class is tightly coupled with ScanRange. Making them friends is easiest.
friend class ScanRange;
+ friend class HdfsFileReader;
/// Create a buffer descriptor for a range and data buffer.
BufferDescriptor(ScanRange* scan_range, uint8_t* buffer, int64_t buffer_len);
@@ -191,6 +193,7 @@ struct BufferOpts {
private:
friend class ScanRange;
+ friend class HdfsFileReader;
BufferOpts(
bool try_cache, int64_t mtime, uint8_t* client_buffer, int64_t client_buffer_len)
@@ -237,6 +240,7 @@ class ScanRange : public RequestRange {
void* meta_data() const { return meta_data_; }
bool try_cache() const { return try_cache_; }
+ bool read_in_flight() const { return read_in_flight_; }
bool expected_local() const { return expected_local_; }
/// Returns the next buffer for this scan range. buffer is an output parameter.
@@ -265,6 +269,8 @@ class ScanRange : public RequestRange {
int64_t mtime() const { return mtime_; }
+ int BytesRead() const;
+
private:
DISALLOW_COPY_AND_ASSIGN(ScanRange);
@@ -274,6 +280,8 @@ class ScanRange : public RequestRange {
friend class DiskQueue;
friend class DiskIoMgr;
friend class RequestContext;
+ friend class HdfsFileReader;
+ friend class LocalFileReader;
// Tag for the buffer associated with range. See external_buffer_tag_ for details.
enum class ExternalBufferTag { CLIENT_BUFFER, CACHED_BUFFER, NO_BUFFER };
@@ -281,11 +289,11 @@ class ScanRange : public RequestRange {
/// Initialize internal fields
void InitInternal(DiskIoMgr* io_mgr, RequestContext* reader);
- /// Reads from the DN cache. On success, sets cached_buffer_ to the DN buffer
- /// and *read_succeeded to true.
+ /// If data is cached, returns ok() and * read_succeeded is set to true. Also enqueues
+ /// a ready buffer from the cached data.
/// If the data is not cached, returns ok() and *read_succeeded is set to false.
/// Returns a non-ok status if it ran into a non-continuable error.
- /// The reader lock must be held by the caller.
+ /// The reader lock must be held by the caller.
Status ReadFromCache(const boost::unique_lock<boost::mutex>& reader_lock,
bool* read_succeeded) WARN_UNUSED_RESULT;
@@ -303,7 +311,7 @@ class ScanRange : public RequestRange {
/// Cleans up a buffer that was not returned to the client.
/// Either ReturnBuffer() or CleanUpBuffer() is called for every BufferDescriptor.
/// The caller must hold 'lock_' via 'scan_range_lock'.
- /// This function may acquire 'hdfs_lock_'
+ /// This function may acquire 'file_reader_->lock()'
void CleanUpBuffer(const boost::unique_lock<boost::mutex>& scan_range_lock,
std::unique_ptr<BufferDescriptor> buffer);
@@ -325,6 +333,17 @@ class ScanRange : public RequestRange {
ExternalBufferTag external_buffer_tag() const { return external_buffer_tag_; }
+ /// If non-OK, this scan range has been cancelled. This status is the reason for
+ /// cancellation - CANCELLED_INTERNALLY if cancelled without error, or another status
+ /// if an error caused cancellation. Note that a range can be cancelled without
+ /// cancelling the owning context. This means that ranges can be cancelled or hit errors
+ /// without aborting all scan ranges.
+ //
+ /// Writers must hold both 'lock_' and 'file_reader_->lock()'. Readers must hold either
+ /// 'lock_' or 'file_reader_->lock()'. This prevents the range from being cancelled
+ /// while any thread is inside a critical section.
+ Status cancel_status_;
+
/// END: private members that are accessed by other io:: classes
/////////////////////////////////////////
@@ -337,33 +356,6 @@ class ScanRange : public RequestRange {
/// Maximum length in bytes for hdfsRead() calls.
int64_t MaxReadChunkSize() const;
- /// Opens the file for this range. This function only modifies state in this range.
- /// If 'use_file_handle_cache' is true and this is a local hdfs file, then this scan
- /// range will not maintain an exclusive file handle. It will borrow an hdfs file
- /// handle from the file handle cache for each Read(), so Open() does nothing.
- /// If 'use_file_handle_cache' is false or this is a remote hdfs file or this is
- /// a local OS file, Open() will open a file handle on the scan range for
- /// exclusive use by this scan range. The scan range is the exclusive owner of the
- /// file handle, and the file handle is destroyed in Close().
- /// All local OS files are opened using normal OS file APIs.
- ///
- /// If an error is encountered during opening, returns a status describing the error.
- /// If the scan range was cancelled, returns the reason for cancellation. Otherwise, on
- /// success, returns OK.
- Status Open(bool use_file_handle_cache) WARN_UNUSED_RESULT;
-
- /// Closes the file for this range. This function only modifies state in this range.
- void Close();
-
- /// Reads from this range into 'buffer', which has length 'buffer_len' bytes. Returns
- /// the number of bytes read. The read position in this scan range is updated.
- ///
- /// If an error is encountered during reading, returns a status describing the error.
- /// If the scan range was cancelled, returns the reason for cancellation. Otherwise, on
- /// success, returns OK.
- Status Read(uint8_t* buffer, int64_t buffer_len, int64_t* bytes_read,
- bool* eosr) WARN_UNUSED_RESULT;
-
/// Get the read statistics from the Hdfs file handle and aggregate them to
/// the RequestContext. This clears the statistics on this file handle.
/// It is safe to pass hdfsFile by value, as hdfsFile's underlying type is a
@@ -414,50 +406,23 @@ class ScanRange : public RequestRange {
/// Last modified time of the file associated with the scan range. Set in Reset().
int64_t mtime_;
- /// Total number of bytes read remotely. This is necessary to maintain a count of
- /// the number of remote scan ranges. Since IO statistics can be collected multiple
- /// times for a scan range, it is necessary to keep some state about whether this
- /// scan range has already been counted as remote. There is also a requirement to
- /// log the number of unexpected remote bytes for a scan range. To solve both
- /// requirements, maintain num_remote_bytes_ on the ScanRange and push it to the
- /// reader_ once at the close of the scan range.
- int64_t num_remote_bytes_;
-
DiskIoMgr* io_mgr_ = nullptr;
/// Reader/owner of the scan range
RequestContext* reader_ = nullptr;
- /// File handle either to hdfs or local fs (FILE*)
- /// The hdfs file handle is stored here in three cases:
- /// 1. The file handle cache is off (max_cached_file_handles == 0).
- /// 2. The scan range is using hdfs caching.
- /// -OR-
- /// 3. The hdfs file is expected to be remote (expected_local_ == false)
- /// In each case, the scan range gets a new ExclusiveHdfsFileHandle at Open(),
- /// owns it exclusively, and destroys it in Close().
- union {
- FILE* local_file_ = nullptr;
- ExclusiveHdfsFileHandle* exclusive_hdfs_fh_;
- };
-
/// Tagged union that holds a buffer for the cases when there is a buffer allocated
/// externally from DiskIoMgr that is associated with the scan range.
ExternalBufferTag external_buffer_tag_;
- union {
- /// Valid if the 'external_buffer_tag_' is CLIENT_BUFFER.
- struct {
- /// Client-provided buffer to read the whole scan range into.
- uint8_t* data;
-
- /// Length of the client-provided buffer.
- int64_t len;
- } client_buffer_;
-
- /// Valid and non-NULL if the external_buffer_tag_ is CACHED_BUFFER, which means
- /// that a cached read succeeded and all the bytes for the range are in this buffer.
- struct hadoopRzBuffer* cached_buffer_ = nullptr;
- };
+
+ /// Valid if the 'external_buffer_tag_' is CLIENT_BUFFER.
+ struct {
+ /// Client-provided buffer to read the whole scan range into.
+ uint8_t* data;
+
+ /// Length of the client-provided buffer.
+ int64_t len;
+ } client_buffer_;
/// The number of buffers that have been returned to a client via GetNext() that have
/// not yet been returned with ReturnBuffer().
@@ -469,9 +434,6 @@ class ScanRange : public RequestRange {
/// RequestContext::lock_ must be taken first.
boost::mutex lock_;
- /// Number of bytes read so far for this scan range
- int bytes_read_;
-
/// Buffers to read into, used if the 'external_buffer_tag_' is NO_BUFFER. These are
/// initially populated when the client calls AllocateBuffersForRange() and
/// and are used to read scanned data into. Buffers are taken from this vector for
@@ -513,24 +475,8 @@ class ScanRange : public RequestRange {
/// cancelled.
ConditionVariable buffer_ready_cv_;
- /// Lock that should be taken during hdfs calls. Only one thread (the disk reading
- /// thread) calls into hdfs at a time so this lock does not have performance impact.
- /// This lock only serves to coordinate cleanup. Specifically it serves to ensure
- /// that the disk threads are finished with HDFS calls before is_cancelled_ is set
- /// to true and cleanup starts.
- /// If this lock and lock_ need to be taken, lock_ must be taken first.
- boost::mutex hdfs_lock_;
-
- /// If non-OK, this scan range has been cancelled. This status is the reason for
- /// cancellation - CANCELLED_INTERNALLY if cancelled without error, or another status
- /// if an error caused cancellation. Note that a range can be cancelled without
- /// cancelling the owning context. This means that ranges can be cancelled or hit errors
- /// without aborting all scan ranges.
- //
- /// Writers must hold both 'lock_' and 'hdfs_lock_'. Readers must hold either 'lock_'
- /// or 'hdfs_lock_'. This prevents the range from being cancelled while any thread
- /// is inside a critical section.
- Status cancel_status_;
+ /// Polymorphic object that is responsible for doing file operations.
+ std::unique_ptr<FileReader> file_reader_;
};
/// Used to specify data to be written to a file and offset.
http://git-wip-us.apache.org/repos/asf/impala/blob/d7b8275e/be/src/runtime/io/scan-range.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/io/scan-range.cc b/be/src/runtime/io/scan-range.cc
index 12037ca..aaef6b4 100644
--- a/be/src/runtime/io/scan-range.cc
+++ b/be/src/runtime/io/scan-range.cc
@@ -18,6 +18,8 @@
#include "runtime/exec-env.h"
#include "runtime/io/disk-io-mgr.h"
#include "runtime/io/disk-io-mgr-internal.h"
+#include "runtime/io/hdfs-file-reader.h"
+#include "runtime/io/local-file-reader.h"
#include "util/error-util.h"
#include "util/hdfs-util.h"
@@ -26,10 +28,6 @@
using namespace impala;
using namespace impala::io;
-DEFINE_bool(use_hdfs_pread, false, "Enables using hdfsPread() instead of hdfsRead() "
- "when performing HDFS read operations. This is necessary to use HDFS hedged reads "
- "(assuming the HDFS client is configured to do so).");
-
// TODO: Run perf tests and empirically settle on the most optimal default value for the
// read buffer size. Currently setting it as 128k for the same reason as for S3, i.e.
// due to JNI array allocation and memcpy overhead, 128k was emperically found to have the
@@ -37,10 +35,6 @@ DEFINE_bool(use_hdfs_pread, false, "Enables using hdfsPread() instead of hdfsRea
DEFINE_int64(adls_read_chunk_size, 128 * 1024, "The maximum read chunk size to use when "
"reading from ADLS.");
-#ifndef NDEBUG
-DECLARE_int32(stress_disk_read_delay_ms);
-#endif
-
// Implementation of the ScanRange functionality. Each ScanRange contains a queue
// of ready buffers. For each ScanRange, there is only a single producer and
// consumer thread, i.e. only one disk thread will push to a scan range at
@@ -169,8 +163,13 @@ unique_ptr<BufferDescriptor> ScanRange::GetUnusedBuffer(
return result;
}
+int ScanRange::BytesRead() const {
+ DCHECK(file_reader_ != nullptr);
+ return file_reader_->bytes_read();
+}
+
ReadOutcome ScanRange::DoRead(int disk_id) {
- int64_t bytes_remaining = len_ - bytes_read_;
+ int64_t bytes_remaining = len_ - BytesRead();
DCHECK_GT(bytes_remaining, 0);
unique_ptr<BufferDescriptor> buffer_desc;
@@ -199,14 +198,15 @@ ReadOutcome ScanRange::DoRead(int disk_id) {
// No locks in this section. Only working on local vars. We don't want to hold a
// lock across the read call.
- Status read_status = Open(is_file_handle_caching_enabled());
+ Status read_status = file_reader_->Open(is_file_handle_caching_enabled());
if (read_status.ok()) {
COUNTER_ADD_IF_NOT_NULL(reader_->active_read_thread_counter_, 1L);
COUNTER_BITOR_IF_NOT_NULL(reader_->disks_accessed_bitmap_, 1LL << disk_id);
- read_status = Read(buffer_desc->buffer_, buffer_desc->buffer_len_,
- &buffer_desc->len_, &buffer_desc->eosr_);
- buffer_desc->scan_range_offset_ = bytes_read_ - buffer_desc->len_;
+ read_status = file_reader_->ReadFromPos(offset_ + BytesRead(), buffer_desc->buffer_,
+ min(len() - BytesRead(), buffer_desc->buffer_len_), &buffer_desc->len_,
+ &buffer_desc->eosr_);
+ buffer_desc->scan_range_offset_ = BytesRead() - buffer_desc->len_;
COUNTER_ADD_IF_NOT_NULL(reader_->bytes_read_counter_, buffer_desc->len_);
COUNTER_ADD_IF_NOT_NULL(reader_->active_read_thread_counter_, -1L);
@@ -224,7 +224,7 @@ ReadOutcome ScanRange::DoRead(int disk_id) {
// threads.
CancelInternal(read_status, true);
// No more reads for this scan range - we can close it.
- Close();
+ file_reader_->Close();
return ReadOutcome::CANCELLED;
}
@@ -235,7 +235,7 @@ ReadOutcome ScanRange::DoRead(int disk_id) {
if (!EnqueueReadyBuffer(move(buffer_desc))) return ReadOutcome::CANCELLED;
if (eosr) {
// No more reads for this scan range - we can close it.
- Close();
+ file_reader_->Close();
return ReadOutcome::SUCCESS_EOSR;
}
return ReadOutcome::SUCCESS_NO_EOSR;
@@ -258,7 +258,7 @@ void ScanRange::CleanUpBuffer(
// Close the scan range if there are no more buffers in the reader and no more buffers
// will be returned to readers in future. Close() is idempotent so it is ok to call
// multiple times during cleanup so long as the range is actually finished.
- Close();
+ file_reader_->Close();
}
}
@@ -291,7 +291,7 @@ void ScanRange::CancelInternal(const Status& status, bool read_error) {
// threads are in critical sections.
unique_lock<mutex> scan_range_lock(lock_);
{
- unique_lock<mutex> hdfs_lock(hdfs_lock_);
+ unique_lock<SpinLock> fs_lock(file_reader_->lock());
DCHECK(Validate()) << DebugString();
// If already cancelled, preserve the original reason for cancellation. Most of the
// cleanup is not required if already cancelled, but we need to set
@@ -317,7 +317,7 @@ void ScanRange::CancelInternal(const Status& status, bool read_error) {
// For cached buffers, we can't close the range until the cached buffer is returned.
// Close() is called from ScanRange::CleanUpBufferLocked().
- if (external_buffer_tag_ != ExternalBufferTag::CACHED_BUFFER) Close();
+ if (external_buffer_tag_ != ExternalBufferTag::CACHED_BUFFER) file_reader_->Close();
}
void ScanRange::WaitForInFlightRead() {
@@ -327,22 +327,21 @@ void ScanRange::WaitForInFlightRead() {
string ScanRange::DebugString() const {
stringstream ss;
- ss << "file=" << file_ << " disk_id=" << disk_id_ << " offset=" << offset_
- << " len=" << len_ << " bytes_read=" << bytes_read_
- << " cancel_status=" << cancel_status_.GetDetail()
+ ss << "file=" << file_ << " disk_id=" << disk_id_ << " offset=" << offset_;
+ if (file_reader_) ss << " " << file_reader_->DebugString();
+ ss << " cancel_status=" << cancel_status_.GetDetail()
<< " buffer_queue=" << ready_buffers_.size()
<< " num_buffers_in_readers=" << num_buffers_in_reader_.Load()
<< " unused_iomgr_buffers=" << unused_iomgr_buffers_.size()
<< " unused_iomgr_buffer_bytes=" << unused_iomgr_buffer_bytes_
- << " blocked_on_buffer=" << blocked_on_buffer_
- << " hdfs_file=" << exclusive_hdfs_fh_;
+ << " blocked_on_buffer=" << blocked_on_buffer_;
return ss.str();
}
bool ScanRange::Validate() {
- if (bytes_read_ > len_) {
+ if (BytesRead() > len_) {
LOG(ERROR) << "Bytes read tracking is wrong. Shouldn't read past the scan range."
- << " bytes_read_=" << bytes_read_ << " len_=" << len_;
+ << " bytes_read_=" << BytesRead() << " len_=" << len_;
return false;
}
if (!cancel_status_.ok() && !ready_buffers_.empty()) {
@@ -375,11 +374,9 @@ bool ScanRange::Validate() {
ScanRange::ScanRange()
: RequestRange(RequestType::READ),
- num_remote_bytes_(0),
external_buffer_tag_(ExternalBufferTag::NO_BUFFER) {}
ScanRange::~ScanRange() {
- DCHECK(exclusive_hdfs_fh_ == nullptr) << "File was not closed.";
DCHECK(external_buffer_tag_ != ExternalBufferTag::CACHED_BUFFER)
<< "Cached buffer was not released.";
DCHECK(!read_in_flight_);
@@ -397,14 +394,17 @@ void ScanRange::Reset(hdfsFS fs, const char* file, int64_t len, int64_t offset,
DCHECK(buffer_opts.client_buffer_ == nullptr ||
buffer_opts.client_buffer_len_ >= len_);
fs_ = fs;
+ if (fs_) {
+ file_reader_ = make_unique<HdfsFileReader>(this, fs_, expected_local);
+ } else {
+ file_reader_ = make_unique<LocalFileReader>(this);
+ }
file_ = file;
len_ = len;
offset_ = offset;
disk_id_ = disk_id;
try_cache_ = buffer_opts.try_cache_;
mtime_ = buffer_opts.mtime_;
- expected_local_ = expected_local;
- num_remote_bytes_ = 0;
meta_data_ = meta_data;
if (buffer_opts.client_buffer_ != nullptr) {
external_buffer_tag_ = ExternalBufferTag::CLIENT_BUFFER;
@@ -413,127 +413,24 @@ void ScanRange::Reset(hdfsFS fs, const char* file, int64_t len, int64_t offset,
} else {
external_buffer_tag_ = ExternalBufferTag::NO_BUFFER;
}
+ expected_local_ = expected_local;
io_mgr_ = nullptr;
reader_ = nullptr;
- exclusive_hdfs_fh_ = nullptr;
}
void ScanRange::InitInternal(DiskIoMgr* io_mgr, RequestContext* reader) {
- DCHECK(exclusive_hdfs_fh_ == nullptr);
- DCHECK(local_file_ == nullptr);
DCHECK(!read_in_flight_);
io_mgr_ = io_mgr;
reader_ = reader;
- local_file_ = nullptr;
- exclusive_hdfs_fh_ = nullptr;
- bytes_read_ = 0;
unused_iomgr_buffer_bytes_ = 0;
iomgr_buffer_cumulative_bytes_used_ = 0;
cancel_status_ = Status::OK();
eosr_queued_ = false;
blocked_on_buffer_ = false;
+ file_reader_->ResetState();
DCHECK(Validate()) << DebugString();
}
-Status ScanRange::Open(bool use_file_handle_cache) {
- unique_lock<mutex> hdfs_lock(hdfs_lock_);
- RETURN_IF_ERROR(cancel_status_);
-
- if (fs_ != nullptr) {
- if (exclusive_hdfs_fh_ != nullptr) return Status::OK();
- // With file handle caching, the scan range does not maintain its own
- // hdfs file handle. File handle caching is only used for local files,
- // so s3 and remote filesystems should obtain an exclusive file handle
- // for each scan range.
- if (use_file_handle_cache && expected_local_) return Status::OK();
- // Get a new exclusive file handle.
- exclusive_hdfs_fh_ = io_mgr_->GetExclusiveHdfsFileHandle(fs_, file_string(),
- mtime(), reader_);
- if (exclusive_hdfs_fh_ == nullptr) {
- return Status(TErrorCode::DISK_IO_ERROR,
- GetHdfsErrorMsg("Failed to open HDFS file ", file_));
- }
-
- if (hdfsSeek(fs_, exclusive_hdfs_fh_->file(), offset_) != 0) {
- // Destroy the file handle
- io_mgr_->ReleaseExclusiveHdfsFileHandle(exclusive_hdfs_fh_);
- exclusive_hdfs_fh_ = nullptr;
- return Status(TErrorCode::DISK_IO_ERROR,
- Substitute("Error seeking to $0 in file: $1 $2", offset_, file_,
- GetHdfsErrorMsg("")));
- }
- } else {
- if (local_file_ != nullptr) return Status::OK();
-
- local_file_ = fopen(file(), "r");
- if (local_file_ == nullptr) {
- return Status(TErrorCode::DISK_IO_ERROR, Substitute("Could not open file: $0: $1",
- file_, GetStrErrMsg()));
- }
- if (fseek(local_file_, offset_, SEEK_SET) == -1) {
- fclose(local_file_);
- local_file_ = nullptr;
- return Status(TErrorCode::DISK_IO_ERROR, Substitute("Could not seek to $0 "
- "for file: $1: $2", offset_, file_, GetStrErrMsg()));
- }
- }
- ImpaladMetrics::IO_MGR_NUM_OPEN_FILES->Increment(1L);
- return Status::OK();
-}
-
-void ScanRange::Close() {
- unique_lock<mutex> hdfs_lock(hdfs_lock_);
- bool closed_file = false;
- if (fs_ != nullptr) {
- if (exclusive_hdfs_fh_ != nullptr) {
- GetHdfsStatistics(exclusive_hdfs_fh_->file());
-
- if (external_buffer_tag_ == ExternalBufferTag::CACHED_BUFFER) {
- hadoopRzBufferFree(exclusive_hdfs_fh_->file(), cached_buffer_);
- cached_buffer_ = nullptr;
- external_buffer_tag_ = ExternalBufferTag::NO_BUFFER;
- }
-
- // Destroy the file handle.
- io_mgr_->ReleaseExclusiveHdfsFileHandle(exclusive_hdfs_fh_);
- exclusive_hdfs_fh_ = nullptr;
- closed_file = true;
- }
-
- if (FLAGS_use_hdfs_pread && IsHdfsPath(file())) {
- // Update Hedged Read Metrics.
- // We call it only if the --use_hdfs_pread flag is set, to avoid having the
- // libhdfs client malloc and free a hdfsHedgedReadMetrics object unnecessarily
- // otherwise. 'hedged_metrics' is only set upon success.
- // We also avoid calling hdfsGetHedgedReadMetrics() when the file is not on HDFS
- // (see HDFS-13417).
- struct hdfsHedgedReadMetrics* hedged_metrics;
- int success = hdfsGetHedgedReadMetrics(fs_, &hedged_metrics);
- if (success == 0) {
- ImpaladMetrics::HEDGED_READ_OPS->SetValue(hedged_metrics->hedgedReadOps);
- ImpaladMetrics::HEDGED_READ_OPS_WIN->SetValue(hedged_metrics->hedgedReadOpsWin);
- hdfsFreeHedgedReadMetrics(hedged_metrics);
- }
- }
-
- if (num_remote_bytes_ > 0) {
- reader_->num_remote_ranges_.Add(1L);
- if (expected_local_) {
- reader_->unexpected_remote_bytes_.Add(num_remote_bytes_);
- VLOG_FILE << "Unexpected remote HDFS read of "
- << PrettyPrinter::Print(num_remote_bytes_, TUnit::BYTES)
- << " for file '" << file_ << "'";
- }
- }
- } else {
- if (local_file_ == nullptr) return;
- fclose(local_file_);
- local_file_ = nullptr;
- closed_file = true;
- }
- if (closed_file) ImpaladMetrics::IO_MGR_NUM_OPEN_FILES->Increment(-1L);
-}
-
int64_t ScanRange::MaxReadChunkSize() const {
// S3 InputStreams don't support DIRECT_READ (i.e. java.nio.ByteBuffer read()
// interface). So, hdfsRead() needs to allocate a Java byte[] and copy the data out.
@@ -553,185 +450,36 @@ int64_t ScanRange::MaxReadChunkSize() const {
return numeric_limits<int>::max();
}
-// TODO: how do we best use the disk here. e.g. is it good to break up a
-// 1MB read into 8 128K reads?
-// TODO: look at linux disk scheduling
-Status ScanRange::Read(
- uint8_t* buffer, int64_t buffer_len, int64_t* bytes_read, bool* eosr) {
- DCHECK(read_in_flight_);
- // Delay before acquiring the lock, to allow triggering IMPALA-6587 race.
-#ifndef NDEBUG
- if (FLAGS_stress_disk_read_delay_ms > 0) {
- SleepForMs(FLAGS_stress_disk_read_delay_ms);
- }
-#endif
- unique_lock<mutex> hdfs_lock(hdfs_lock_);
- RETURN_IF_ERROR(cancel_status_);
-
- *eosr = false;
- *bytes_read = 0;
- // Read until the end of the scan range or the end of the buffer.
- int bytes_to_read = min(len_ - bytes_read_, buffer_len);
- DCHECK_GE(bytes_to_read, 0);
-
- if (fs_ != nullptr) {
- CachedHdfsFileHandle* borrowed_hdfs_fh = nullptr;
- hdfsFile hdfs_file;
-
- // If the scan range has an exclusive file handle, use it. Otherwise, borrow
- // a file handle from the cache.
- if (exclusive_hdfs_fh_ != nullptr) {
- hdfs_file = exclusive_hdfs_fh_->file();
- } else {
- borrowed_hdfs_fh = io_mgr_->GetCachedHdfsFileHandle(fs_, file_string(),
- mtime(), reader_);
- if (borrowed_hdfs_fh == nullptr) {
- return Status(TErrorCode::DISK_IO_ERROR,
- GetHdfsErrorMsg("Failed to open HDFS file ", file_));
- }
- hdfs_file = borrowed_hdfs_fh->file();
- }
-
- int64_t max_chunk_size = MaxReadChunkSize();
- Status status = Status::OK();
- {
- ScopedTimer<MonotonicStopWatch> req_context_read_timer(reader_->read_timer_);
- while (*bytes_read < bytes_to_read) {
- int chunk_size = min(bytes_to_read - *bytes_read, max_chunk_size);
- DCHECK_GE(chunk_size, 0);
- // The hdfsRead() length argument is an int.
- DCHECK_LE(chunk_size, numeric_limits<int>::max());
- int current_bytes_read = -1;
- // bytes_read_ is only updated after the while loop
- int64_t position_in_file = offset_ + bytes_read_ + *bytes_read;
- int num_retries = 0;
- while (true) {
- status = Status::OK();
- // For file handles from the cache, any of the below file operations may fail
- // due to a bad file handle. In each case, record the error, but allow for a
- // retry to fix it.
- if (FLAGS_use_hdfs_pread) {
- current_bytes_read = hdfsPread(fs_, hdfs_file, position_in_file,
- buffer + *bytes_read, chunk_size);
- if (current_bytes_read == -1) {
- status = Status(TErrorCode::DISK_IO_ERROR,
- GetHdfsErrorMsg("Error reading from HDFS file: ", file_));
- }
- } else {
- // If the file handle is borrowed, it may not be at the appropriate
- // location. Seek to the appropriate location.
- bool seek_failed = false;
- if (borrowed_hdfs_fh != nullptr) {
- if (hdfsSeek(fs_, hdfs_file, position_in_file) != 0) {
- status = Status(TErrorCode::DISK_IO_ERROR,
- Substitute("Error seeking to $0 in file: $1: $2", position_in_file,
- file_, GetHdfsErrorMsg("")));
- seek_failed = true;
- }
- }
- if (!seek_failed) {
- current_bytes_read = hdfsRead(fs_, hdfs_file, buffer + *bytes_read,
- chunk_size);
- if (current_bytes_read == -1) {
- status = Status(TErrorCode::DISK_IO_ERROR,
- GetHdfsErrorMsg("Error reading from HDFS file: ", file_));
- }
- }
- }
-
- // Do not retry:
- // - if read was successful (current_bytes_read != -1)
- // - or if already retried once
- // - or if this not using a borrowed file handle
- DCHECK_LE(num_retries, 1);
- if (current_bytes_read != -1 || borrowed_hdfs_fh == nullptr ||
- num_retries == 1) {
- break;
- }
- // The error may be due to a bad file handle. Reopen the file handle and retry.
- // Exclude this time from the read timers.
- req_context_read_timer.Stop();
- ++num_retries;
- RETURN_IF_ERROR(io_mgr_->ReopenCachedHdfsFileHandle(fs_, file_string(),
- mtime(), reader_, &borrowed_hdfs_fh));
- hdfs_file = borrowed_hdfs_fh->file();
- req_context_read_timer.Start();
- }
- if (!status.ok()) break;
- if (current_bytes_read == 0) {
- // No more bytes in the file. The scan range went past the end.
- *eosr = true;
- break;
- }
- *bytes_read += current_bytes_read;
-
- // Collect and accumulate statistics
- GetHdfsStatistics(hdfs_file);
- }
- }
-
- if (borrowed_hdfs_fh != nullptr) {
- io_mgr_->ReleaseCachedHdfsFileHandle(file_string(), borrowed_hdfs_fh);
- }
- if (!status.ok()) return status;
- } else {
- DCHECK(local_file_ != nullptr);
- *bytes_read = fread(buffer, 1, bytes_to_read, local_file_);
- DCHECK_GE(*bytes_read, 0);
- DCHECK_LE(*bytes_read, bytes_to_read);
- if (*bytes_read < bytes_to_read) {
- if (ferror(local_file_) != 0) {
- return Status(TErrorCode::DISK_IO_ERROR, Substitute("Error reading from $0"
- "at byte offset: $1: $2", file_, offset_ + bytes_read_, GetStrErrMsg()));
- } else {
- // On Linux, we should only get partial reads from block devices on error or eof.
- DCHECK(feof(local_file_) != 0);
- *eosr = true;
- }
- }
- }
- bytes_read_ += *bytes_read;
- DCHECK_LE(bytes_read_, len_);
- if (bytes_read_ == len_) *eosr = true;
- return Status::OK();
-}
-
Status ScanRange::ReadFromCache(
const unique_lock<mutex>& reader_lock, bool* read_succeeded) {
DCHECK(reader_lock.mutex() == &reader_->lock_ && reader_lock.owns_lock());
DCHECK(try_cache_);
- DCHECK_EQ(bytes_read_, 0);
+ DCHECK_EQ(BytesRead(), 0);
*read_succeeded = false;
- Status status = Open(false);
+ Status status = file_reader_->Open(false);
if (!status.ok()) return status;
// Cached reads not supported on local filesystem.
if (fs_ == nullptr) return Status::OK();
+ // Check cancel status.
{
- unique_lock<mutex> hdfs_lock(hdfs_lock_);
+ unique_lock<mutex> lock(lock_);
RETURN_IF_ERROR(cancel_status_);
-
- DCHECK(exclusive_hdfs_fh_ != nullptr);
- DCHECK(external_buffer_tag_ == ExternalBufferTag::NO_BUFFER);
- cached_buffer_ =
- hadoopReadZero(exclusive_hdfs_fh_->file(), io_mgr_->cached_read_options(), len());
- if (cached_buffer_ != nullptr) {
- external_buffer_tag_ = ExternalBufferTag::CACHED_BUFFER;
- }
}
+
+ DCHECK(external_buffer_tag_ == ExternalBufferTag::NO_BUFFER);
+ void* buffer = file_reader_->CachedFile();
+ if (buffer != nullptr) external_buffer_tag_ = ExternalBufferTag::CACHED_BUFFER;
// Data was not cached, caller will fall back to normal read path.
if (external_buffer_tag_ != ExternalBufferTag::CACHED_BUFFER) {
VLOG_QUERY << "Cache read failed for scan range: " << DebugString()
<< ". Switching to disk read path.";
// Clean up the scan range state before re-issuing it.
- Close();
+ file_reader_->Close();
return Status::OK();
}
-
- // Cached read returned a buffer, verify we read the correct amount of data.
- void* buffer = const_cast<void*>(hadoopRzBufferGet(cached_buffer_));
- int32_t bytes_read = hadoopRzBufferLength(cached_buffer_);
+ int bytes_read = BytesRead();
// A partial read can happen when files are truncated.
// TODO: If HDFS ever supports partially cached blocks, we'll have to distinguish
// between errors and partially cached blocks here.
@@ -740,7 +488,7 @@ Status ScanRange::ReadFromCache(
<< len() << " bytes, but read " << bytes_read << ". Switching to disk read path.";
// Close the scan range. 'read_succeeded' is still false, so the caller will fall back
// to non-cached read of this scan range.
- Close();
+ file_reader_->Close();
return Status::OK();
}
@@ -751,30 +499,12 @@ Status ScanRange::ReadFromCache(
desc->len_ = bytes_read;
desc->scan_range_offset_ = 0;
desc->eosr_ = true;
- bytes_read_ = bytes_read;
EnqueueReadyBuffer(move(desc));
COUNTER_ADD_IF_NOT_NULL(reader_->bytes_read_counter_, bytes_read);
*read_succeeded = true;
return Status::OK();
}
-void ScanRange::GetHdfsStatistics(hdfsFile hdfs_file) {
- struct hdfsReadStatistics* stats;
- if (IsHdfsPath(file())) {
- int success = hdfsFileGetReadStatistics(hdfs_file, &stats);
- if (success == 0) {
- reader_->bytes_read_local_.Add(stats->totalLocalBytesRead);
- reader_->bytes_read_short_circuit_.Add(stats->totalShortCircuitBytesRead);
- reader_->bytes_read_dn_cache_.Add(stats->totalZeroCopyBytesRead);
- if (stats->totalLocalBytesRead != stats->totalBytesRead) {
- num_remote_bytes_ += stats->totalBytesRead - stats->totalLocalBytesRead;
- }
- hdfsFileFreeReadStatistics(stats);
- }
- hdfsFileClearReadStatistics(hdfs_file);
- }
-}
-
BufferDescriptor::BufferDescriptor(ScanRange* scan_range,
uint8_t* buffer, int64_t buffer_len)
: scan_range_(scan_range),