You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kudu.apache.org by da...@apache.org on 2018/06/22 22:28:18 UTC
[1/3] kudu git commit: KUDU-2260: Log block manager should handle
null bytes in metadata on crash
Repository: kudu
Updated Branches:
refs/heads/master c7918e87b -> f6e8fe6c6
KUDU-2260: Log block manager should handle null bytes in metadata on crash
On ext4 with data=ordered (the default), it's possible for a write to
persist an increase to the filesize without persisting the actual data.
In this case, the file will contain null bytes at the end. In the LBM,
we considered this case to be corruption if there were enough null bytes
(>= 8) for a PB container record length and length checksum. However,
it's safe to call this an incomplete record and truncate the file at the
end of the last complete record.
This patch changes the P container reader code to return
Status::Incomplete if it encounters this situation. This will cause the
LBM to repair the container metadata appropriately.
Two regression tests, at the PB container file and LBM layers, are
included.
Change-Id: I0af5c9dbbe28afe7a179595ad20392b99cde2a1b
Reviewed-on: http://gerrit.cloudera.org:8080/10777
Tested-by: Kudu Jenkins
Reviewed-by: Adar Dembo <ad...@cloudera.com>
Project: http://git-wip-us.apache.org/repos/asf/kudu/repo
Commit: http://git-wip-us.apache.org/repos/asf/kudu/commit/009cfe23
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/009cfe23
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/009cfe23
Branch: refs/heads/master
Commit: 009cfe23ab37e8c8ac5949f365ab424f34a4f520
Parents: c7918e8
Author: Will Berkeley <wd...@apache.org>
Authored: Tue Jun 19 17:13:02 2018 -0700
Committer: Will Berkeley <wd...@gmail.com>
Committed: Fri Jun 22 17:58:01 2018 +0000
----------------------------------------------------------------------
src/kudu/consensus/log_util.cc | 27 ----------------
src/kudu/fs/log_block_manager-test.cc | 50 +++++++++++++++++-------------
src/kudu/util/pb_util-test.cc | 34 ++++++++++++++++++++
src/kudu/util/pb_util.cc | 43 +++++++++++++++++++++++--
src/kudu/util/slice.cc | 20 ++++++++++++
src/kudu/util/slice.h | 11 +++++++
6 files changed, 134 insertions(+), 51 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/kudu/blob/009cfe23/src/kudu/consensus/log_util.cc
----------------------------------------------------------------------
diff --git a/src/kudu/consensus/log_util.cc b/src/kudu/consensus/log_util.cc
index 07fba47..0f0fd23 100644
--- a/src/kudu/consensus/log_util.cc
+++ b/src/kudu/consensus/log_util.cc
@@ -454,33 +454,6 @@ Status ReadableLogSegment::ReadHeaderMagicAndHeaderLength(uint32_t *len) {
return Status::OK();
}
-namespace {
-
-// We don't run TSAN on this function because it makes it really slow and causes some
-// test timeouts. This is only used on local buffers anyway, so we don't lose much
-// by not checking it.
-ATTRIBUTE_NO_SANITIZE_THREAD
-bool IsAllZeros(const Slice& s) {
- // Walk a pointer through the slice instead of using s[i]
- // since this is way faster in debug mode builds. We also do some
- // manual unrolling for the same purpose.
- const uint8_t* p = &s[0];
- int rem = s.size();
-
- while (rem >= 8) {
- if (UNALIGNED_LOAD64(p) != 0) return false;
- rem -= 8;
- p += 8;
- }
-
- while (rem > 0) {
- if (*p++ != '\0') return false;
- rem--;
- }
- return true;
-}
-} // anonymous namespace
-
Status ReadableLogSegment::ParseHeaderMagicAndHeaderLength(const Slice &data,
uint32_t *parsed_len) {
RETURN_NOT_OK_PREPEND(data.check_size(kLogSegmentHeaderMagicAndHeaderLength),
http://git-wip-us.apache.org/repos/asf/kudu/blob/009cfe23/src/kudu/fs/log_block_manager-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/fs/log_block_manager-test.cc b/src/kudu/fs/log_block_manager-test.cc
index d93d8aa..3dc79e8 100644
--- a/src/kudu/fs/log_block_manager-test.cc
+++ b/src/kudu/fs/log_block_manager-test.cc
@@ -622,33 +622,39 @@ TEST_F(LogBlockManagerTest, TestMetadataTruncation) {
uint64_t good_meta_size;
ASSERT_OK(env_->GetFileSize(metadata_path, &good_meta_size));
- // First, add an extra byte to the end of the metadata file. This makes the
- // trailing "record" of the metadata file corrupt, but doesn't cause data
+ // First, add extra null bytes to the end of the metadata file. This makes
+ // the trailing "record" of the metadata file corrupt, but doesn't cause data
// loss. The result is that the container will automatically truncate the
// metadata file back to its correct size.
- {
- RWFileOptions opts;
- opts.mode = Env::OPEN_EXISTING;
- unique_ptr<RWFile> file;
- ASSERT_OK(env_->NewRWFile(opts, metadata_path, &file));
- ASSERT_OK(file->Truncate(good_meta_size + 1));
- }
-
+ // We'll do this with 1, 8, and 128 extra bytes-- the first case is too few
+ // bytes to be a valid record, while the second is too few but is enough for
+ // a data length and its checksum, and the third is too long for a record.
+ // The 8- and 128-byte cases are regression tests for KUDU-2260.
uint64_t cur_meta_size;
- ASSERT_OK(env_->GetFileSize(metadata_path, &cur_meta_size));
- ASSERT_EQ(good_meta_size + 1, cur_meta_size);
+ for (const auto num_bytes : {1, 8, 128}) {
+ {
+ RWFileOptions opts;
+ opts.mode = Env::OPEN_EXISTING;
+ unique_ptr<RWFile> file;
+ ASSERT_OK(env_->NewRWFile(opts, metadata_path, &file));
+ ASSERT_OK(file->Truncate(good_meta_size + num_bytes));
+ }
- // Reopen the metadata file. We will still see all of our blocks. The size of
- // the metadata file will be restored back to its previous value.
- ASSERT_OK(ReopenBlockManager());
- ASSERT_OK(bm_->GetAllBlockIds(&block_ids));
- ASSERT_EQ(4, block_ids.size());
- ASSERT_OK(bm_->OpenBlock(last_block_id, &block));
- ASSERT_OK(block->Close());
+ ASSERT_OK(env_->GetFileSize(metadata_path, &cur_meta_size));
+ ASSERT_EQ(good_meta_size + num_bytes, cur_meta_size);
- // Check that the file was truncated back to its previous size by the system.
- ASSERT_OK(env_->GetFileSize(metadata_path, &cur_meta_size));
- ASSERT_EQ(good_meta_size, cur_meta_size);
+ // Reopen the metadata file. We will still see all of our blocks. The size of
+ // the metadata file will be restored back to its previous value.
+ ASSERT_OK(ReopenBlockManager());
+ ASSERT_OK(bm_->GetAllBlockIds(&block_ids));
+ ASSERT_EQ(4, block_ids.size());
+ ASSERT_OK(bm_->OpenBlock(last_block_id, &block));
+ ASSERT_OK(block->Close());
+
+ // Check that the file was truncated back to its previous size by the system.
+ ASSERT_OK(env_->GetFileSize(metadata_path, &cur_meta_size));
+ ASSERT_EQ(good_meta_size, cur_meta_size);
+ }
// Delete the first block we created. This necessitates writing to the
// metadata file of the originally-written container, since we append a
http://git-wip-us.apache.org/repos/asf/kudu/blob/009cfe23/src/kudu/util/pb_util-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/pb_util-test.cc b/src/kudu/util/pb_util-test.cc
index ddead1b..a942e9a 100644
--- a/src/kudu/util/pb_util-test.cc
+++ b/src/kudu/util/pb_util-test.cc
@@ -363,6 +363,40 @@ TEST_P(TestPBContainerVersions, TestPartialRecord) {
ASSERT_OK(pb_file.Close());
}
+// KUDU-2260: Test handling extra null bytes at the end of file. This can
+// occur, for example, on ext4 in default data=ordered mode when a write
+// increases the filesize but the system crashes before the actual data is
+// persisted.
+TEST_P(TestPBContainerVersions, TestExtraNullBytes) {
+ ASSERT_OK(CreateKnownGoodContainerFileWithVersion(version_));
+ uint64_t known_good_size;
+ ASSERT_OK(env_->GetFileSize(path_, &known_good_size));
+ for (const auto extra_bytes : {1, 8, 128}) {
+ ASSERT_OK(TruncateFile(path_, known_good_size + extra_bytes));
+
+ unique_ptr<RandomAccessFile> file;
+ ASSERT_OK(env_->NewRandomAccessFile(path_, &file));
+ ReadablePBContainerFile pb_file(std::move(file));
+ ASSERT_OK(pb_file.Open());
+ ProtoContainerTestPB test_pb;
+ // Read the first good PB. Trouble starts at the second.
+ ASSERT_OK(pb_file.ReadNextPB(&test_pb));
+ Status s = pb_file.ReadNextPB(&test_pb);
+ // Loop to verify that the same response is repeatably returned.
+ for (int i = 0; i < 2; i++) {
+ ASSERT_TRUE(version_ == 1 ? s.IsCorruption() : s.IsIncomplete()) << s.ToString();
+ if (extra_bytes < 8) {
+ ASSERT_STR_CONTAINS(s.ToString(), "File size not large enough to be valid");
+ } else if (version_ == 1) {
+ ASSERT_STR_CONTAINS(s.ToString(), "Length and data checksum does not match");
+ } else {
+ ASSERT_STR_CONTAINS(s.ToString(), "rest of file is NULL bytes");
+ }
+ }
+ ASSERT_OK(pb_file.Close());
+ }
+}
+
// Test that it is possible to append after a partial write if we truncate the
// partial record. This is only fully supported in V2+.
TEST_P(TestPBContainerVersions, TestAppendAfterPartialWrite) {
http://git-wip-us.apache.org/repos/asf/kudu/blob/009cfe23/src/kudu/util/pb_util.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/pb_util.cc b/src/kudu/util/pb_util.cc
index a943f68..1c072d6 100644
--- a/src/kudu/util/pb_util.cc
+++ b/src/kudu/util/pb_util.cc
@@ -23,6 +23,7 @@
#include "kudu/util/pb_util.h"
+#include <algorithm>
#include <cstddef>
#include <deque>
#include <initializer_list>
@@ -31,7 +32,6 @@
#include <ostream>
#include <string>
#include <unordered_set>
-#include <utility>
#include <vector>
#include <boost/optional/optional.hpp>
@@ -55,8 +55,8 @@
#include "kudu/gutil/strings/escaping.h"
#include "kudu/gutil/strings/fastmem.h"
#include "kudu/gutil/strings/substitute.h"
-#include "kudu/util/coding-inl.h"
#include "kudu/util/coding.h"
+#include "kudu/util/coding-inl.h"
#include "kudu/util/crc.h"
#include "kudu/util/debug/sanitizer_scopes.h"
#include "kudu/util/debug/trace_event.h"
@@ -253,6 +253,33 @@ Status CacheFileSize(ReadableFileType* reader,
return Status::OK();
}
+template<typename ReadableFileType>
+Status RestOfFileIsAllZeros(ReadableFileType* reader,
+ uint64_t filesize,
+ uint64_t offset,
+ bool* all_zeros) {
+ DCHECK(reader);
+ DCHECK_GE(filesize, offset);
+ DCHECK(all_zeros);
+ constexpr uint64_t max_to_read = 4 * 1024 * 1024; // 4 MiB.
+ faststring buf;
+ while (true) {
+ uint64_t to_read = std::min(max_to_read, filesize - offset);
+ if (to_read == 0) {
+ break;
+ }
+ buf.resize(to_read);
+ RETURN_NOT_OK(reader->Read(offset, Slice(buf)));
+ offset += to_read;
+ if (!IsAllZeros(buf)) {
+ *all_zeros = false;
+ return Status::OK();
+ }
+ }
+ *all_zeros = true;
+ return Status::OK();
+}
+
// Read and parse a message of the specified format at the given offset in the
// format documented in pb_util.h. 'offset' is an in-out parameter and will be
// updated with the new offset on success. On failure, 'offset' is not modified.
@@ -283,6 +310,18 @@ Status ReadPBStartingAt(ReadableFileType* reader, int version,
// Versions >= 2 have an individual checksum for the data length.
if (version >= 2) {
+ // KUDU-2260: If the length and checksum data are all 0's, and the rest of
+ // the file is all 0's, then it's an incomplete record, not corruption.
+ // This can happen e.g. on ext4 in the default data=ordered mode, when the
+ // filesize metadata is updated but the new data is not persisted.
+ // See https://plus.google.com/+KentonVarda/posts/JDwHfAiLGNQ.
+ if (IsAllZeros(length_and_cksum_buf)) {
+ bool all_zeros;
+ RETURN_NOT_OK(RestOfFileIsAllZeros(reader, file_size, tmp_offset, &all_zeros));
+ if (all_zeros) {
+ return Status::Incomplete("incomplete write of PB: rest of file is NULL bytes");
+ }
+ }
Slice length_checksum(length_and_cksum_buf.data() + sizeof(uint32_t), kPBContainerChecksumLen);
RETURN_NOT_OK_PREPEND(ParseAndCompareChecksum(length_checksum.data(), { length }),
CHECKSUM_ERR_MSG("Data length checksum does not match",
http://git-wip-us.apache.org/repos/asf/kudu/blob/009cfe23/src/kudu/util/slice.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/slice.cc b/src/kudu/util/slice.cc
index 5d672ae..775d54a 100644
--- a/src/kudu/util/slice.cc
+++ b/src/kudu/util/slice.cc
@@ -74,4 +74,24 @@ std::string Slice::ToDebugString(size_t max_len) const {
return ret;
}
+bool IsAllZeros(const Slice& s) {
+ // Walk a pointer through the slice instead of using s[i]
+ // since this is way faster in debug mode builds. We also do some
+ // manual unrolling for the same purpose.
+ const uint8_t* p = &s[0];
+ int rem = s.size();
+
+ while (rem >= 8) {
+ if (UNALIGNED_LOAD64(p) != 0) return false;
+ rem -= 8;
+ p += 8;
+ }
+
+ while (rem > 0) {
+ if (*p++ != '\0') return false;
+ rem--;
+ }
+ return true;
+}
+
} // namespace kudu
http://git-wip-us.apache.org/repos/asf/kudu/blob/009cfe23/src/kudu/util/slice.h
----------------------------------------------------------------------
diff --git a/src/kudu/util/slice.h b/src/kudu/util/slice.h
index 72ad305..d34c744 100644
--- a/src/kudu/util/slice.h
+++ b/src/kudu/util/slice.h
@@ -23,6 +23,9 @@
#include "kudu/gutil/strings/stringpiece.h"
#include "kudu/util/faststring.h"
#endif
+#ifdef KUDU_HEADERS_NO_STUBS
+#include "kudu/gutil/port.h"
+#endif
#include "kudu/util/kudu_export.h"
namespace kudu {
@@ -295,6 +298,14 @@ inline int Slice::compare(const Slice& b) const {
return r;
}
+// We don't run TSAN on this function because it makes it really slow and causes some
+// test timeouts. This is only used on local buffers anyway, so we don't lose much
+// by not checking it.
+#ifdef KUDU_HEADERS_NO_STUBS
+ATTRIBUTE_NO_SANITIZE_THREAD
+#endif
+bool IsAllZeros(const Slice& s);
+
/// @brief STL map whose keys are Slices.
///
/// An example of usage:
[2/3] kudu git commit: [consensus] update UnsafeChangeConfig()
signature
Posted by da...@apache.org.
[consensus] update UnsafeChangeConfig() signature
While testing various scenarios involving kudu CLI's
'remote_replica unsafe_change_config' sub-command, it turned out that
tserver might end up trying to respond with invalid value of
TabletServerErrorPB::Code. In that case, a tserver built in DEBUG
configuration would crash with the following stack trace:
../nptl/sysdeps/unix/sysv/linux/raise.c:64
assertion=0x7fb4eab7c4f8
"::kudu::tserver::TabletServerErrorPB_Code_IsValid(value)",
file=0x7fb4eab7c531 "src/kudu/tserver/tserver.pb.h",
line=<value optimized out>, function=<value optimized out>) at assert.c:96
assertion=0x7fb4eab7c4f8
"::kudu::tserver::TabletServerErrorPB_Code_IsValid(value)",
file=0x7fb4eab7c531 "src/kudu/tserver/tserver.pb.h", line=2623,
function=0x7fb4eab7c586 "void kudu::tserver::TabletServerErrorPB::set_code(
::kudu::tserver::TabletServerErrorPB_Code)") at assert.c:105
kudu::tserver::TabletServerErrorPB_Code) ()
at src/kudu/tserver/tserver.pb.h:2623
kudu::tserver::TabletServerErrorPB*,
kudu::Status const&, kudu::tserver::TabletServerErrorPB_Code,
kudu::rpc::RpcContext*) ()
at src/kudu/tserver/tablet_service.cc:370
kudu::consensus::UnsafeChangeConfigRequestPB const*,
kudu::consensus::UnsafeChangeConfigResponsePB*,
kudu::rpc::RpcContext*) () at src/kudu/tserver/tablet_service.cc:1060
This changelist fixes the issue, 'unifying' the signatures of the
RaftConsensus::{ChangeConfig,BulkChangeConfig,UpdateChangeConfig}()
methods.
Change-Id: Id266dd72ef5e44e9b4e2ce9df10694bce8cfe2fb
Reviewed-on: http://gerrit.cloudera.org:8080/10141
Tested-by: Alexey Serbin <as...@cloudera.com>
Reviewed-by: Mike Percy <mp...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/kudu/repo
Commit: http://git-wip-us.apache.org/repos/asf/kudu/commit/f1e652b2
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/f1e652b2
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/f1e652b2
Branch: refs/heads/master
Commit: f1e652b23c2bd76033868fe6a30484cb30098649
Parents: 009cfe2
Author: Alexey Serbin <as...@cloudera.com>
Authored: Fri Apr 20 18:37:25 2018 -0700
Committer: Alexey Serbin <as...@cloudera.com>
Committed: Fri Jun 22 18:05:06 2018 +0000
----------------------------------------------------------------------
src/kudu/consensus/raft_consensus.cc | 22 ++++++++++------------
src/kudu/consensus/raft_consensus.h | 2 +-
src/kudu/tserver/tablet_service.cc | 10 ++++++----
3 files changed, 17 insertions(+), 17 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/kudu/blob/f1e652b2/src/kudu/consensus/raft_consensus.cc
----------------------------------------------------------------------
diff --git a/src/kudu/consensus/raft_consensus.cc b/src/kudu/consensus/raft_consensus.cc
index 68f1859..b4ef789 100644
--- a/src/kudu/consensus/raft_consensus.cc
+++ b/src/kudu/consensus/raft_consensus.cc
@@ -1886,8 +1886,9 @@ Status RaftConsensus::BulkChangeConfig(const BulkChangeConfigRequestPB& req,
return Status::OK();
}
-Status RaftConsensus::UnsafeChangeConfig(const UnsafeChangeConfigRequestPB& req,
- TabletServerErrorPB::Code* error_code) {
+Status RaftConsensus::UnsafeChangeConfig(
+ const UnsafeChangeConfigRequestPB& req,
+ boost::optional<tserver::TabletServerErrorPB::Code>* error_code) {
if (PREDICT_FALSE(!req.has_new_config())) {
*error_code = TabletServerErrorPB::INVALID_CONFIG;
return Status::InvalidArgument("Request must contain 'new_config' argument "
@@ -1960,6 +1961,7 @@ Status RaftConsensus::UnsafeChangeConfig(const UnsafeChangeConfigRequestPB& req,
// in the committed config, it is rare and a replica without itself
// in the latest config is definitely not caught up with the latest leader's log.
if (!IsRaftConfigVoter(peer_uuid(), new_config)) {
+ *error_code = TabletServerErrorPB::INVALID_CONFIG;
return Status::InvalidArgument(Substitute("Local replica uuid $0 is not "
"a VOTER in the new config, "
"rejecting the unsafe config "
@@ -1985,13 +1987,12 @@ Status RaftConsensus::UnsafeChangeConfig(const UnsafeChangeConfigRequestPB& req,
// Prepare the consensus request as if the request is being generated
// from a different leader.
ConsensusRequestPB consensus_req;
- ConsensusResponsePB consensus_resp;
consensus_req.set_caller_uuid(req.caller_id());
// Bumping up the term for the consensus request being generated.
// This makes this request appear to come from a new leader that
// the local replica doesn't know about yet. If the local replica
// happens to be the leader, this will cause it to step down.
- int64_t new_term = current_term + 1;
+ const int64_t new_term = current_term + 1;
consensus_req.set_caller_term(new_term);
consensus_req.mutable_preceding_id()->CopyFrom(preceding_opid);
consensus_req.set_committed_index(last_committed_index);
@@ -2018,14 +2019,11 @@ Status RaftConsensus::UnsafeChangeConfig(const UnsafeChangeConfigRequestPB& req,
<< "COMMITTED CONFIG: " << SecureShortDebugString(committed_config)
<< "NEW CONFIG: " << SecureShortDebugString(new_config);
- s = Update(&consensus_req, &consensus_resp);
- if (!s.ok() || consensus_resp.has_error()) {
- *error_code = TabletServerErrorPB::UNKNOWN_ERROR;
- }
- if (s.ok() && consensus_resp.has_error()) {
- s = StatusFromPB(consensus_resp.error().status());
- }
- return s;
+ ConsensusResponsePB consensus_resp;
+ return Update(&consensus_req, &consensus_resp).AndThen([&consensus_resp]{
+ return consensus_resp.has_error()
+ ? StatusFromPB(consensus_resp.error().status()) : Status::OK();
+ });
}
void RaftConsensus::Stop() {
http://git-wip-us.apache.org/repos/asf/kudu/blob/f1e652b2/src/kudu/consensus/raft_consensus.h
----------------------------------------------------------------------
diff --git a/src/kudu/consensus/raft_consensus.h b/src/kudu/consensus/raft_consensus.h
index 33e8196..f84a71e 100644
--- a/src/kudu/consensus/raft_consensus.h
+++ b/src/kudu/consensus/raft_consensus.h
@@ -274,7 +274,7 @@ class RaftConsensus : public std::enable_shared_from_this<RaftConsensus>,
// Implement an UnsafeChangeConfig() request.
Status UnsafeChangeConfig(const UnsafeChangeConfigRequestPB& req,
- tserver::TabletServerErrorPB::Code* error_code);
+ boost::optional<tserver::TabletServerErrorPB::Code>* error_code);
// Returns the last OpId (either received or committed, depending on the
// 'type' argument) that the Consensus implementation knows about.
http://git-wip-us.apache.org/repos/asf/kudu/blob/f1e652b2/src/kudu/tserver/tablet_service.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tserver/tablet_service.cc b/src/kudu/tserver/tablet_service.cc
index 89dbf95..4cf88ea 100644
--- a/src/kudu/tserver/tablet_service.cc
+++ b/src/kudu/tserver/tablet_service.cc
@@ -1086,11 +1086,13 @@ void ConsensusServiceImpl::UnsafeChangeConfig(const UnsafeChangeConfigRequestPB*
}
shared_ptr<RaftConsensus> consensus;
- if (!GetConsensusOrRespond(replica, resp, context, &consensus)) return;
- TabletServerErrorPB::Code error_code;
- Status s = consensus->UnsafeChangeConfig(*req, &error_code);
+ if (!GetConsensusOrRespond(replica, resp, context, &consensus)) {
+ return;
+ }
+ boost::optional<TabletServerErrorPB::Code> error_code;
+ const Status s = consensus->UnsafeChangeConfig(*req, &error_code);
if (PREDICT_FALSE(!s.ok())) {
- SetupErrorAndRespond(resp->mutable_error(), s, error_code, context);
+ HandleErrorResponse(req, resp, context, error_code, s);
return;
}
context->RespondSuccess();
[3/3] kudu git commit: Synchronizer::WaitFor thread-safety
Posted by da...@apache.org.
Synchronizer::WaitFor thread-safety
WaitFor's implementation previously was not thread safe in the case that
the waiter deallocated the Synchronizer after receiving a timeout.
Change-Id: I9565a50839ffd23b5bac6986a6fdee41ac21aa3a
Reviewed-on: http://gerrit.cloudera.org:8080/10783
Reviewed-by: Adar Dembo <ad...@cloudera.com>
Tested-by: Kudu Jenkins
Project: http://git-wip-us.apache.org/repos/asf/kudu/repo
Commit: http://git-wip-us.apache.org/repos/asf/kudu/commit/f6e8fe6c
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/f6e8fe6c
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/f6e8fe6c
Branch: refs/heads/master
Commit: f6e8fe6c6bb6dd83e6485bc1b56364b11b250e94
Parents: f1e652b
Author: Dan Burkert <da...@apache.org>
Authored: Thu Jun 21 11:49:39 2018 -0700
Committer: Dan Burkert <da...@apache.org>
Committed: Fri Jun 22 22:15:55 2018 +0000
----------------------------------------------------------------------
src/kudu/util/CMakeLists.txt | 1 +
src/kudu/util/async_util-test.cc | 129 ++++++++++++++++++++++++++++++++++
src/kudu/util/async_util.h | 71 +++++++++++--------
3 files changed, 170 insertions(+), 31 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/kudu/blob/f6e8fe6c/src/kudu/util/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/src/kudu/util/CMakeLists.txt b/src/kudu/util/CMakeLists.txt
index 044660c..743e1af 100644
--- a/src/kudu/util/CMakeLists.txt
+++ b/src/kudu/util/CMakeLists.txt
@@ -331,6 +331,7 @@ target_link_libraries(protoc-gen-insertions gutil protobuf protoc ${KUDU_BASE_LI
#######################################
set(KUDU_TEST_LINK_LIBS kudu_util gutil ${KUDU_MIN_TEST_LIBS})
+ADD_KUDU_TEST(async_util-test)
ADD_KUDU_TEST(atomic-test)
ADD_KUDU_TEST(bit-util-test)
ADD_KUDU_TEST(bitmap-test)
http://git-wip-us.apache.org/repos/asf/kudu/blob/f6e8fe6c/src/kudu/util/async_util-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/async_util-test.cc b/src/kudu/util/async_util-test.cc
new file mode 100644
index 0000000..5cb7a63
--- /dev/null
+++ b/src/kudu/util/async_util-test.cc
@@ -0,0 +1,129 @@
+// 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 "kudu/util/async_util.h"
+
+#include <unistd.h>
+
+#include <functional>
+#include <thread>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "kudu/gutil/basictypes.h"
+#include "kudu/gutil/callback.h"
+#include "kudu/util/monotime.h"
+#include "kudu/util/status.h"
+#include "kudu/util/test_macros.h"
+#include "kudu/util/test_util.h"
+
+using std::thread;
+using std::vector;
+
+namespace kudu {
+
+class AsyncUtilTest : public KuduTest {
+ public:
+ AsyncUtilTest() {
+ // Set up an alarm to fail the test in case of deadlock.
+ alarm(30);
+ }
+ ~AsyncUtilTest() {
+ // Disable the alarm on test exit.
+ alarm(0);
+ }
+};
+
+// Test completing the synchronizer through each of the APIs it exposes.
+TEST_F(AsyncUtilTest, TestSynchronizerCompletion) {
+ Synchronizer sync;
+
+ {
+ auto waiter = thread([sync] {
+ ignore_result(sync.Wait());
+ });
+ SleepFor(MonoDelta::FromMilliseconds(5));
+ sync.StatusCB(Status::OK());
+ waiter.join();
+ }
+ sync.Reset();
+ {
+ auto cb = sync.AsStatusCallback();
+ auto waiter = thread([sync] {
+ ignore_result(sync.Wait());
+ });
+ SleepFor(MonoDelta::FromMilliseconds(5));
+ cb.Run(Status::OK());
+ waiter.join();
+ }
+ sync.Reset();
+ {
+ auto cb = sync.AsStdStatusCallback();
+ auto waiter = thread([sync] {
+ ignore_result(sync.Wait());
+ });
+ SleepFor(MonoDelta::FromMilliseconds(5));
+ cb(Status::OK());
+ waiter.join();
+ }
+}
+
+TEST_F(AsyncUtilTest, TestSynchronizerMultiWait) {
+ Synchronizer sync;
+ vector<thread> waiters;
+ for (int i = 0; i < 5; i++) {
+ waiters.emplace_back([sync] {
+ ignore_result(sync.Wait());
+ });
+ }
+ SleepFor(MonoDelta::FromMilliseconds(5));
+ sync.StatusCB(Status::OK());
+
+ for (auto& waiter : waiters) {
+ waiter.join();
+ }
+}
+
+TEST_F(AsyncUtilTest, TestSynchronizerTimedWait) {
+ thread waiter;
+ {
+ Synchronizer sync;
+ auto cb = sync.AsStatusCallback();
+ waiter = thread([cb] {
+ SleepFor(MonoDelta::FromMilliseconds(5));
+ cb.Run(Status::OK());
+ });
+ ASSERT_OK(sync.WaitFor(MonoDelta::FromMilliseconds(1000)));
+ }
+ waiter.join();
+
+ {
+ Synchronizer sync;
+ auto cb = sync.AsStatusCallback();
+ waiter = thread([cb] {
+ SleepFor(MonoDelta::FromMilliseconds(1000));
+ cb.Run(Status::OK());
+ });
+ ASSERT_TRUE(sync.WaitFor(MonoDelta::FromMilliseconds(5)).IsTimedOut());
+ }
+
+ // Waiting on the thread gives TSAN to check that no thread safety issues
+ // occurred.
+ waiter.join();
+}
+} // namespace kudu
http://git-wip-us.apache.org/repos/asf/kudu/blob/f6e8fe6c/src/kudu/util/async_util.h
----------------------------------------------------------------------
diff --git a/src/kudu/util/async_util.h b/src/kudu/util/async_util.h
index 727b7f7..338c6c2 100644
--- a/src/kudu/util/async_util.h
+++ b/src/kudu/util/async_util.h
@@ -16,10 +16,11 @@
// under the License.
//
// Utility functions which are handy when doing async/callback-based programming.
-#ifndef KUDU_UTIL_ASYNC_UTIL_H
-#define KUDU_UTIL_ASYNC_UTIL_H
+
+#pragma once
#include <functional>
+#include <memory>
#include "kudu/gutil/bind.h"
#include "kudu/gutil/macros.h"
@@ -32,59 +33,67 @@ namespace kudu {
// Simple class which can be used to make async methods synchronous.
// For example:
// Synchronizer s;
-// SomeAsyncMethod(s.callback());
+// SomeAsyncMethod(s.AsStatusCallback());
// CHECK_OK(s.Wait());
+//
+// The lifetime of the synchronizer is decoupled from the callback it produces.
+// If the callback outlives the synchronizer then executing it will be a no-op.
+// Callers must be careful not to allow the callback to be destructed without
+// completing it, otherwise the thread waiting on the synchronizer will block
+// indefinitely.
class Synchronizer {
public:
Synchronizer()
- : l_(1) {
+ : data_(std::make_shared<Data>()) {
}
void StatusCB(const Status& status) {
- s_ = status;
- l_.CountDown();
+ Data::Callback(std::weak_ptr<Data>(data_), status);
}
StatusCallback AsStatusCallback() {
- // Synchronizers are often declared on the stack, so it doesn't make
- // sense for a callback to take a reference to its synchronizer.
- //
- // Note: this means the returned callback _must_ go out of scope before
- // its synchronizer.
- return Bind(&Synchronizer::StatusCB, Unretained(this));
+ return Bind(Data::Callback, std::weak_ptr<Data>(data_));
}
StdStatusCallback AsStdStatusCallback() {
- // Synchronizers are often declared on the stack, so it doesn't make
- // sense for a callback to take a reference to its synchronizer.
- //
- // Note: this means the returned callback _must_ go out of scope before
- // its synchronizer.
- return std::bind(&Synchronizer::StatusCB, this, std::placeholders::_1);
+ return std::bind(Data::Callback, std::weak_ptr<Data>(data_), std::placeholders::_1);
}
- Status Wait() {
- l_.Wait();
- return s_;
+ Status Wait() const {
+ data_->latch.Wait();
+ return data_->status;
}
- Status WaitFor(const MonoDelta& delta) {
- if (PREDICT_FALSE(!l_.WaitFor(delta))) {
- return Status::TimedOut("Timed out while waiting for the callback to be called.");
+ Status WaitFor(const MonoDelta& delta) const {
+ if (PREDICT_FALSE(!data_->latch.WaitFor(delta))) {
+ return Status::TimedOut("timed out while waiting for the callback to be called");
}
- return s_;
+ return data_->status;
}
void Reset() {
- l_.Reset(1);
+ data_->latch.Reset(1);
}
private:
- Status s_;
- CountDownLatch l_;
- DISALLOW_COPY_AND_ASSIGN(Synchronizer);
-};
+ struct Data {
+ Data() : latch(1) {
+ }
+ static void Callback(std::weak_ptr<Data> weak, const Status& status) {
+ auto ptr = weak.lock();
+ if (ptr) {
+ ptr->status = status;
+ ptr->latch.CountDown();
+ }
+ }
+
+ Status status;
+ CountDownLatch latch;
+ DISALLOW_COPY_AND_ASSIGN(Data);
+ };
+
+ std::shared_ptr<Data> data_;
+};
} // namespace kudu
-#endif /* KUDU_UTIL_ASYNC_UTIL_H */