You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kudu.apache.org by ad...@apache.org on 2016/08/16 00:26:32 UTC
[1/4] kudu git commit: Memory tracking for result tracker
Repository: kudu
Updated Branches:
refs/heads/master 74210b254 -> 2c3fc7c27
Memory tracking for result tracker
This adds memory tracking to ResultTracker, making sure we account for
the memory as we cache responses for clients' requests.
Testing wise this adds memory consumption checks to rpc-stress-test.cc.
Original patch by David Alves.
Change-Id: I3b81dda41c8bc7f70380ce426142c34afe6f1625
Reviewed-on: http://gerrit.cloudera.org:8080/3627
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/0fb44093
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/0fb44093
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/0fb44093
Branch: refs/heads/master
Commit: 0fb44093fd64893d8333488fad763edc997393a7
Parents: 74210b2
Author: Todd Lipcon <to...@apache.org>
Authored: Fri Aug 12 14:57:24 2016 -0700
Committer: Todd Lipcon <to...@apache.org>
Committed: Mon Aug 15 19:39:25 2016 +0000
----------------------------------------------------------------------
src/kudu/rpc/result_tracker.cc | 66 ++++++++++++++++++++++++++++++--
src/kudu/rpc/result_tracker.h | 49 +++++++++++++++++++++---
src/kudu/rpc/rpc-stress-test.cc | 73 +++++++++++++++++++++++++++++++++---
src/kudu/rpc/rpc-test-base.h | 5 ++-
src/kudu/server/server_base.cc | 3 +-
src/kudu/util/test_util.cc | 41 ++++++++++++++++++++
src/kudu/util/test_util.h | 14 +++++++
7 files changed, 234 insertions(+), 17 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/kudu/blob/0fb44093/src/kudu/rpc/result_tracker.cc
----------------------------------------------------------------------
diff --git a/src/kudu/rpc/result_tracker.cc b/src/kudu/rpc/result_tracker.cc
index 61e5738..649ad15 100644
--- a/src/kudu/rpc/result_tracker.cc
+++ b/src/kudu/rpc/result_tracker.cc
@@ -22,6 +22,7 @@
#include "kudu/rpc/inbound_call.h"
#include "kudu/rpc/rpc_context.h"
#include "kudu/util/debug/trace_event.h"
+#include "kudu/util/mem_tracker.h"
#include "kudu/util/trace.h"
#include "kudu/util/pb_util.h"
@@ -29,14 +30,59 @@ namespace kudu {
namespace rpc {
using google::protobuf::Message;
+using kudu::MemTracker;
using rpc::InboundCall;
using std::move;
using std::lock_guard;
+using std::shared_ptr;
using std::string;
using std::unique_ptr;
using strings::Substitute;
using strings::SubstituteAndAppend;
+// This tracks the size changes of anything that has a memory_footprint() method.
+// It must be instantiated before the updates, and it makes sure that the MemTracker
+// is updated on scope exit.
+template <class T>
+struct ScopedMemTrackerUpdater {
+ ScopedMemTrackerUpdater(MemTracker* tracker_, const T* tracked_)
+ : tracker(tracker_),
+ tracked(tracked_),
+ memory_before(tracked->memory_footprint()),
+ cancelled(false) {
+ }
+
+ ~ScopedMemTrackerUpdater() {
+ if (cancelled) return;
+ tracker->Release(memory_before - tracked->memory_footprint());
+ }
+
+ void Cancel() {
+ cancelled = true;
+ }
+
+ MemTracker* tracker;
+ const T* tracked;
+ int64_t memory_before;
+ bool cancelled;
+};
+
+ResultTracker::ResultTracker(shared_ptr<MemTracker> mem_tracker)
+ : mem_tracker_(std::move(mem_tracker)),
+ clients_(ClientStateMap::key_compare(),
+ ClientStateMapAllocator(mem_tracker_)) {}
+
+ResultTracker::~ResultTracker() {
+ lock_guard<simple_spinlock> l(lock_);
+ // Release all the memory for the stuff we'll delete on destruction.
+ for (auto& client_state : clients_) {
+ for (auto& completion_record : client_state.second->completion_records) {
+ mem_tracker_->Release(completion_record.second->memory_footprint());
+ }
+ mem_tracker_->Release(client_state.second->memory_footprint());
+ }
+}
+
ResultTracker::RpcState ResultTracker::TrackRpc(const RequestIdPB& request_id,
Message* response,
RpcContext* context) {
@@ -47,20 +93,28 @@ ResultTracker::RpcState ResultTracker::TrackRpc(const RequestIdPB& request_id,
ResultTracker::RpcState ResultTracker::TrackRpcUnlocked(const RequestIdPB& request_id,
Message* response,
RpcContext* context) {
-
ClientState* client_state = ComputeIfAbsent(
&clients_,
request_id.client_id(),
- []{ return unique_ptr<ClientState>(new ClientState()); })->get();
+ [&]{
+ unique_ptr<ClientState> client_state(new ClientState(mem_tracker_));
+ mem_tracker_->Consume(client_state->memory_footprint());
+ return client_state;
+ })->get();
client_state->last_heard_from = MonoTime::Now();
auto result = ComputeIfAbsentReturnAbsense(
&client_state->completion_records,
request_id.seq_no(),
- []{ return unique_ptr<CompletionRecord>(new CompletionRecord()); });
+ [&]{
+ unique_ptr<CompletionRecord> completion_record(new CompletionRecord());
+ mem_tracker_->Consume(completion_record->memory_footprint());
+ return completion_record;
+ });
CompletionRecord* completion_record = result.first->get();
+ ScopedMemTrackerUpdater<CompletionRecord> cr_updater(mem_tracker_.get(), completion_record);
if (PREDICT_TRUE(result.second)) {
completion_record->state = RpcState::IN_PROGRESS;
@@ -111,6 +165,7 @@ ResultTracker::RpcState ResultTracker::TrackRpcOrChangeDriver(const RequestIdPB&
if (state != RpcState::IN_PROGRESS) return state;
CompletionRecord* completion_record = FindCompletionRecordOrDieUnlocked(request_id);
+ ScopedMemTrackerUpdater<CompletionRecord> updater(mem_tracker_.get(), completion_record);
// ... if we did find a CompletionRecord change the driver and return true.
completion_record->driver_attempt_no = request_id.attempt_no();
@@ -194,6 +249,7 @@ void ResultTracker::RecordCompletionAndRespond(const RequestIdPB& request_id,
lock_guard<simple_spinlock> l(lock_);
CompletionRecord* completion_record = FindCompletionRecordOrDieUnlocked(request_id);
+ ScopedMemTrackerUpdater<CompletionRecord> updater(mem_tracker_.get(), completion_record);
CHECK_EQ(completion_record->driver_attempt_no, request_id.attempt_no())
<< "Called RecordCompletionAndRespond() from an executor identified with an attempt number that"
@@ -233,13 +289,13 @@ void ResultTracker::FailAndRespondInternal(const RequestIdPB& request_id,
HandleOngoingRpcFunc func) {
lock_guard<simple_spinlock> l(lock_);
auto state_and_record = FindClientStateAndCompletionRecordOrNullUnlocked(request_id);
-
if (PREDICT_FALSE(state_and_record.first == nullptr)) {
LOG(FATAL) << "Couldn't find ClientState for request: " << request_id.ShortDebugString()
<< ". \nTracker state:\n" << ToStringUnlocked();
}
CompletionRecord* completion_record = state_and_record.second;
+ ScopedMemTrackerUpdater<CompletionRecord> cr_updater(mem_tracker_.get(), completion_record);
if (completion_record == nullptr) {
return;
@@ -272,8 +328,10 @@ void ResultTracker::FailAndRespondInternal(const RequestIdPB& request_id,
// delete the completion record.
if (completion_record->ongoing_rpcs.size() == 0
&& completion_record->state != RpcState::COMPLETED) {
+ cr_updater.Cancel();
unique_ptr<CompletionRecord> completion_record =
EraseKeyReturnValuePtr(&state_and_record.first->completion_records, seq_no);
+ mem_tracker_->Release(completion_record->memory_footprint());
}
}
http://git-wip-us.apache.org/repos/asf/kudu/blob/0fb44093/src/kudu/rpc/result_tracker.h
----------------------------------------------------------------------
diff --git a/src/kudu/rpc/result_tracker.h b/src/kudu/rpc/result_tracker.h
index a04cb07..86d87b2 100644
--- a/src/kudu/rpc/result_tracker.h
+++ b/src/kudu/rpc/result_tracker.h
@@ -16,6 +16,7 @@
// under the License.
#pragma once
+#include <functional>
#include <map>
#include <string>
#include <utility>
@@ -26,6 +27,8 @@
#include "kudu/rpc/request_tracker.h"
#include "kudu/rpc/rpc_header.pb.h"
#include "kudu/util/locks.h"
+#include "kudu/util/malloc.h"
+#include "kudu/util/mem_tracker.h"
#include "kudu/util/monotime.h"
namespace google {
@@ -139,7 +142,6 @@ class RpcContext;
//
// This class is thread safe.
//
-// TODO Memory bookkeeping.
// TODO Garbage collection.
class ResultTracker : public RefCountedThreadSafe<ResultTracker> {
public:
@@ -160,8 +162,8 @@ class ResultTracker : public RefCountedThreadSafe<ResultTracker> {
STALE
};
- ResultTracker() {}
- ~ResultTracker() {}
+ explicit ResultTracker(std::shared_ptr<kudu::MemTracker> mem_tracker);
+ ~ResultTracker();
// Tracks the RPC and returns its current state.
//
@@ -244,12 +246,39 @@ class ResultTracker : public RefCountedThreadSafe<ResultTracker> {
std::vector<OnGoingRpcInfo> ongoing_rpcs;
std::string ToString() const;
+
+ // Calculates the memory footprint of this struct.
+ int64_t memory_footprint() const {
+ return kudu_malloc_usable_size(this)
+ + (ongoing_rpcs.capacity() > 0 ? kudu_malloc_usable_size(ongoing_rpcs.data()) : 0)
+ + (response.get() != nullptr ? response->SpaceUsed() : 0);
+ }
};
// The state corresponding to a single client.
struct ClientState {
+ typedef MemTrackerAllocator<
+ std::pair<const SequenceNumber,
+ std::unique_ptr<CompletionRecord>>> CompletionRecordMapAllocator;
+ typedef std::map<SequenceNumber,
+ std::unique_ptr<CompletionRecord>,
+ std::less<SequenceNumber>,
+ CompletionRecordMapAllocator> CompletionRecordMap;
+
+ explicit ClientState(std::shared_ptr<MemTracker> mem_tracker)
+ : completion_records(CompletionRecordMap::key_compare(),
+ CompletionRecordMapAllocator(std::move(mem_tracker))) {}
+
MonoTime last_heard_from;
- std::map<SequenceNumber, std::unique_ptr<CompletionRecord>> completion_records;
+ CompletionRecordMap completion_records;
+
std::string ToString() const;
+
+ // Calculates the memory footprint of this struct.
+ // This calculation is shallow and doesn't account for the memory the nested data
+ // structures occupy.
+ int64_t memory_footprint() const {
+ return kudu_malloc_usable_size(this);
+ }
};
RpcState TrackRpcUnlocked(const RequestIdPB& request_id,
@@ -290,12 +319,22 @@ class ResultTracker : public RefCountedThreadSafe<ResultTracker> {
std::string ToStringUnlocked() const;
+ // The memory tracker that tracks this ResultTracker's memory consumption.
+ std::shared_ptr<kudu::MemTracker> mem_tracker_;
// Lock that protects access to 'clients_' and to the state contained in each
// ClientState.
// TODO consider a per-ClientState lock if we find this too coarse grained.
simple_spinlock lock_;
- std::map<std::string, std::unique_ptr<ClientState>> clients_;
+
+ typedef MemTrackerAllocator<std::pair<const std::string,
+ std::unique_ptr<ClientState>>> ClientStateMapAllocator;
+ typedef std::map<std::string,
+ std::unique_ptr<ClientState>,
+ std::less<std::string>,
+ ClientStateMapAllocator> ClientStateMap;
+
+ ClientStateMap clients_;
DISALLOW_COPY_AND_ASSIGN(ResultTracker);
};
http://git-wip-us.apache.org/repos/asf/kudu/blob/0fb44093/src/kudu/rpc/rpc-stress-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/rpc/rpc-stress-test.cc b/src/kudu/rpc/rpc-stress-test.cc
index b8dade1..2d1215e 100644
--- a/src/kudu/rpc/rpc-stress-test.cc
+++ b/src/kudu/rpc/rpc-stress-test.cc
@@ -31,10 +31,11 @@ namespace {
const char* kClientId = "test-client";
void AddRequestId(RpcController* controller,
+ const std::string& client_id,
ResultTracker::SequenceNumber sequence_number,
int64_t attempt_no) {
unique_ptr<RequestIdPB> request_id(new RequestIdPB());
- request_id->set_client_id(kClientId);
+ request_id->set_client_id(client_id);
request_id->set_seq_no(sequence_number);
request_id->set_attempt_no(attempt_no);
request_id->set_first_incomplete_seq_no(sequence_number);
@@ -191,7 +192,7 @@ class RpcStressTest : public RpcTestBase {
client_sleep_for_ms(client_sleep) {
req.set_value_to_add(value);
req.set_sleep_for_ms(server_sleep);
- AddRequestId(&controller, sequence_number, attempt_no);
+ AddRequestId(&controller, kClientId, sequence_number, attempt_no);
}
void Start() {
@@ -224,7 +225,7 @@ class RpcStressTest : public RpcTestBase {
ExactlyOnceResponsePB resp;
RequestTracker::SequenceNumber seq_no;
CHECK_OK(request_tracker_->NewSeqNo(&seq_no));
- AddRequestId(&controller, seq_no, 0);
+ AddRequestId(&controller, kClientId, seq_no, 0);
ASSERT_OK(proxy_->AddExactlyOnce(req, &resp, &controller));
ASSERT_EQ(resp.current_val(), expected_value);
request_tracker_->RpcCompleted(seq_no);
@@ -244,16 +245,30 @@ class RpcStressTest : public RpcTestBase {
// same sequence number as previous request.
TEST_F(RpcStressTest, TestExactlyOnceSemanticsAfterRpcCompleted) {
ExactlyOnceResponsePB original_resp;
+ int mem_consumption = mem_tracker_->consumption();
{
RpcController controller;
ExactlyOnceRequestPB req;
req.set_value_to_add(1);
// Assign id 0.
- AddRequestId(&controller, 0, 0);
+ AddRequestId(&controller, kClientId, 0, 0);
// Send the request the first time.
ASSERT_OK(proxy_->AddExactlyOnce(req, &original_resp, &controller));
+
+ // The incremental usage of a new client is the size of the response itself
+ // plus some fixed overhead for the client-tracking structure.
+ int expected_incremental_usage = original_resp.SpaceUsed() + 200;
+
+ // The consumption isn't immediately updated, since the MemTracker update
+ // happens after we call 'Respond' on the RPC.
+ int mem_consumption_after;
+ AssertEventually([&]() {
+ mem_consumption_after = mem_tracker_->consumption();
+ ASSERT_GT(mem_consumption_after - mem_consumption, expected_incremental_usage);
+ });
+ mem_consumption = mem_consumption_after;
}
// Now repeat the rpc 10 times, using the same sequence number, none of these should be executed
@@ -264,10 +279,32 @@ TEST_F(RpcStressTest, TestExactlyOnceSemanticsAfterRpcCompleted) {
ExactlyOnceRequestPB req;
req.set_value_to_add(1);
ExactlyOnceResponsePB resp;
- AddRequestId(&controller, 0, i + 1);
+ AddRequestId(&controller, kClientId, 0, i + 1);
ASSERT_OK(proxy_->AddExactlyOnce(req, &resp, &controller));
ASSERT_EQ(resp.current_val(), 1);
ASSERT_EQ(resp.current_time_micros(), original_resp.current_time_micros());
+ // Sleep to give the MemTracker time to update -- we don't expect any update,
+ // but if we had a bug here, we'd only see it with this sleep.
+ SleepFor(MonoDelta::FromMilliseconds(100));
+ // We shouldn't have consumed any more memory since the responses were cached.
+ ASSERT_EQ(mem_consumption, mem_tracker_->consumption());
+ }
+
+ // Making a new request, from a new client, should double the memory consumption.
+ {
+ RpcController controller;
+ ExactlyOnceRequestPB req;
+ ExactlyOnceResponsePB resp;
+ req.set_value_to_add(1);
+
+ // Assign id 0.
+ AddRequestId(&controller, "test-client2", 0, 0);
+
+ // Send the first request for this new client.
+ ASSERT_OK(proxy_->AddExactlyOnce(req, &resp, &controller));
+ AssertEventually([&]() {
+ ASSERT_EQ(mem_tracker_->consumption(), mem_consumption * 2);
+ });
}
}
@@ -313,7 +350,22 @@ TEST_F(RpcStressTest, TestExactlyOnceSemanticsWithConcurrentUpdaters) {
kNumThreads = 100;
}
- for (int i = 0; i < kNumIterations; i ++) {
+ ResultTracker::SequenceNumber sequence_number = 0;
+ int memory_consumption_initial = mem_tracker_->consumption();
+ int single_response_size = 0;
+
+ // Measure memory consumption for a single response from the same client.
+ {
+ RpcController controller;
+ ExactlyOnceRequestPB req;
+ ExactlyOnceResponsePB resp;
+ req.set_value_to_add(1);
+ AddRequestId(&controller, kClientId, sequence_number, 0);
+ ASSERT_OK(proxy_->AddExactlyOnce(req, &resp, &controller));
+ single_response_size = resp.SpaceUsed();
+ }
+
+ for (int i = 1; i <= kNumIterations; i ++) {
vector<unique_ptr<SimultaneousExactlyOnceAdder>> adders;
for (int j = 0; j < kNumThreads; j++) {
unique_ptr<SimultaneousExactlyOnceAdder> adder(
@@ -334,6 +386,15 @@ TEST_F(RpcStressTest, TestExactlyOnceSemanticsWithConcurrentUpdaters) {
ASSERT_EQ(adders[j]->resp.current_time_micros(), time_micros);
}
}
+
+ // Wait for the MemTracker to be updated.
+ // After all adders finished we should at least the size of one more response.
+ // The actual size depends of multiple factors, for instance, how many calls were "attached"
+ // (which is timing dependent) so we can't be more precise than this.
+ AssertEventually([&]() {
+ ASSERT_GT(mem_tracker_->consumption(),
+ memory_consumption_initial + single_response_size * i);
+ });
}
}
http://git-wip-us.apache.org/repos/asf/kudu/blob/0fb44093/src/kudu/rpc/rpc-test-base.h
----------------------------------------------------------------------
diff --git a/src/kudu/rpc/rpc-test-base.h b/src/kudu/rpc/rpc-test-base.h
index 7b82b08..9e4f00f 100644
--- a/src/kudu/rpc/rpc-test-base.h
+++ b/src/kudu/rpc/rpc-test-base.h
@@ -38,6 +38,7 @@
#include "kudu/rpc/service_if.h"
#include "kudu/rpc/service_pool.h"
#include "kudu/util/faststring.h"
+#include "kudu/util/mem_tracker.h"
#include "kudu/util/net/sockaddr.h"
#include "kudu/util/random.h"
#include "kudu/util/random_util.h"
@@ -458,7 +459,8 @@ class RpcTestBase : public KuduTest {
ASSERT_OK(server_messenger_->AddAcceptorPool(Sockaddr(), &pool));
ASSERT_OK(pool->Start(2));
*server_addr = pool->bind_address();
- result_tracker_.reset(new ResultTracker());
+ mem_tracker_ = MemTracker::CreateTracker(-1, "result_tracker");
+ result_tracker_.reset(new ResultTracker(mem_tracker_));
gscoped_ptr<ServiceIf> service(new ServiceClass(metric_entity_, result_tracker_));
service_name_ = service->service_name();
@@ -472,6 +474,7 @@ class RpcTestBase : public KuduTest {
string service_name_;
std::shared_ptr<Messenger> server_messenger_;
scoped_refptr<ServicePool> service_pool_;
+ std::shared_ptr<kudu::MemTracker> mem_tracker_;
scoped_refptr<ResultTracker> result_tracker_;
int n_worker_threads_;
int service_queue_length_;
http://git-wip-us.apache.org/repos/asf/kudu/blob/0fb44093/src/kudu/server/server_base.cc
----------------------------------------------------------------------
diff --git a/src/kudu/server/server_base.cc b/src/kudu/server/server_base.cc
index 19c9f6a..6010f23 100644
--- a/src/kudu/server/server_base.cc
+++ b/src/kudu/server/server_base.cc
@@ -93,7 +93,8 @@ ServerBase::ServerBase(string name, const ServerBaseOptions& options,
metric_namespace)),
rpc_server_(new RpcServer(options.rpc_opts)),
web_server_(new Webserver(options.webserver_opts)),
- result_tracker_(new rpc::ResultTracker()),
+ result_tracker_(new rpc::ResultTracker(shared_ptr<MemTracker>(
+ MemTracker::CreateTracker(-1, "result-tracker", mem_tracker_)))),
is_first_run_(false),
options_(options),
stop_metrics_logging_latch_(1) {
http://git-wip-us.apache.org/repos/asf/kudu/blob/0fb44093/src/kudu/util/test_util.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/test_util.cc b/src/kudu/util/test_util.cc
index 58be8ff..b26302a 100644
--- a/src/kudu/util/test_util.cc
+++ b/src/kudu/util/test_util.cc
@@ -18,6 +18,7 @@
#include <gflags/gflags.h>
#include <glog/logging.h>
+#include <gtest/gtest-spi.h>
#include "kudu/gutil/strings/strcat.h"
#include "kudu/gutil/strings/substitute.h"
@@ -180,4 +181,44 @@ string GetTestDataDirectory() {
return dir;
}
+void AssertEventually(const std::function<void(void)>& f,
+ const MonoDelta& timeout) {
+ MonoTime deadline = MonoTime::Now();
+ deadline.AddDelta(timeout);
+ int attempts = 0;
+
+ while (MonoTime::Now().ComesBefore(deadline)) {
+ // Capture any assertion failures within this scope (i.e. from their function)
+ // into 'results'
+ testing::TestPartResultArray results;
+ testing::ScopedFakeTestPartResultReporter reporter(
+ testing::ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
+ &results);
+ f();
+
+ // Determine whether their function produced any new test failure results.
+ bool has_failures = false;
+ for (int i = 0; i < results.size(); i++) {
+ has_failures |= results.GetTestPartResult(i).failed();
+ }
+ if (!has_failures) {
+ return;
+ }
+
+ // If they had failures, sleep and try again.
+ int sleep_ms = (attempts < 10) ? (1 << attempts) : 1000;
+ SleepFor(MonoDelta::FromMilliseconds(sleep_ms));
+ }
+
+ // If we ran out of time looping, run their function one more time
+ // without capturing its assertions. This way the assertions will
+ // propagate back out to the normal test reporter. Of course it's
+ // possible that it will pass on this last attempt, but that's OK
+ // too, since we aren't trying to be that strict about the deadline.
+ f();
+ if (testing::Test::HasFatalFailure()) {
+ ADD_FAILURE() << "Timed out waiting for assertion to pass.";
+ }
+}
+
} // namespace kudu
http://git-wip-us.apache.org/repos/asf/kudu/blob/0fb44093/src/kudu/util/test_util.h
----------------------------------------------------------------------
diff --git a/src/kudu/util/test_util.h b/src/kudu/util/test_util.h
index a545233..62dfe46 100644
--- a/src/kudu/util/test_util.h
+++ b/src/kudu/util/test_util.h
@@ -19,11 +19,13 @@
#ifndef KUDU_UTIL_TEST_UTIL_H
#define KUDU_UTIL_TEST_UTIL_H
+#include <functional>
#include <gtest/gtest.h>
#include <string>
#include "kudu/gutil/gscoped_ptr.h"
#include "kudu/util/env.h"
+#include "kudu/util/monotime.h"
#include "kudu/util/test_macros.h"
namespace kudu {
@@ -79,5 +81,17 @@ int SeedRandom();
// May only be called from within a gtest unit test.
std::string GetTestDataDirectory();
+// Wait until 'f()' succeeds without adding any GTest 'fatal failures'.
+// For example:
+//
+// AssertEventually([]() {
+// ASSERT_GT(ReadValueOfMetric(), 10);
+// });
+//
+// The function is run in a loop with exponential backoff, capped at once
+// a second.
+void AssertEventually(const std::function<void(void)>& f,
+ const MonoDelta& timeout = MonoDelta::FromSeconds(30));
+
} // namespace kudu
#endif
[3/4] kudu git commit: Improvements and corrections to Impala CREATE
TABLE examples
Posted by ad...@apache.org.
Improvements and corrections to Impala CREATE TABLE examples
Change-Id: I093972a7b806787a8c72634851796eebb5e1ae4c
Reviewed-on: http://gerrit.cloudera.org:8080/3376
Reviewed-by: Dan Burkert <da...@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/5a707994
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/5a707994
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/5a707994
Branch: refs/heads/master
Commit: 5a707994290e5d601985bf2f2ea6c822b6c0c330
Parents: 274dfb0
Author: Misty Stanley-Jones <mi...@apache.org>
Authored: Mon Jun 13 09:10:33 2016 -0700
Committer: Misty Stanley-Jones <mi...@apache.org>
Committed: Mon Aug 15 23:42:33 2016 +0000
----------------------------------------------------------------------
docs/kudu_impala_integration.adoc | 66 ++++++++++++++++++----------------
1 file changed, 36 insertions(+), 30 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/kudu/blob/5a707994/docs/kudu_impala_integration.adoc
----------------------------------------------------------------------
diff --git a/docs/kudu_impala_integration.adoc b/docs/kudu_impala_integration.adoc
index fb29bd8..16be5cd 100755
--- a/docs/kudu_impala_integration.adoc
+++ b/docs/kudu_impala_integration.adoc
@@ -372,7 +372,7 @@ CREATE TABLE my_first_table
id BIGINT,
name STRING
)
-DISTRIBUTE BY HASH (id) INTO 16 BUCKETS
+DISTRIBUTE BY HASH INTO 16 BUCKETS
TBLPROPERTIES(
'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
'kudu.table_name' = 'my_first_table',
@@ -404,6 +404,7 @@ property. In this example, the primary key columns are `ts` and `name`.
[source,sql]
----
CREATE TABLE new_table
+DISTRIBUTE BY HASH INTO 16 BUCKETS
TBLPROPERTIES(
'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
'kudu.table_name' = 'new_table',
@@ -430,8 +431,8 @@ like `SELECT name as new_name`.
Tables are divided into tablets which are each served by one or more tablet
servers. Ideally, tablets should split a table's data relatively equally. Kudu currently
has no mechanism for automatically (or manually) splitting a pre-existing tablet.
-Until this feature has been implemented, you must pre-split your table when you create
-it, When designing your table schema, consider primary keys that will allow you to
+Until this feature has been implemented, *you must pre-split your table when you create
+it*. When designing your table schema, consider primary keys that will allow you to
pre-split your table into tablets which grow at similar rates. You can provide split
points using a `DISTRIBUTE BY` clause when creating a table using Impala:
@@ -455,13 +456,13 @@ CREATE TABLE cust_behavior (
rating INT,
fulfilled_date BIGINT
)
-DISTRIBUTE BY RANGE(_id)
-SPLIT ROWS((1439560049342),
- (1439566253755),
- (1439572458168),
- (1439578662581),
- (1439584866994),
- (1439591071407))
+DISTRIBUTE BY RANGE (_id)
+ SPLIT ROWS((1439560049342),
+ (1439566253755),
+ (1439572458168),
+ (1439578662581),
+ (1439584866994),
+ (1439591071407))
TBLPROPERTIES(
'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
'kudu.table_name' = 'cust_behavior',
@@ -491,12 +492,13 @@ use the following SQL:
[source,sql]
----
-CREATE DATABASE impala_kudu
+CREATE DATABASE impala_kudu;
USE impala_kudu;
CREATE TABLE my_first_table (
id BIGINT,
name STRING
)
+DISTRIBUTE BY HASH INTO 4 BUCKETS
TBLPROPERTIES(
'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
'kudu.table_name' = 'my_first_table',
@@ -605,13 +607,13 @@ CREATE TABLE customers (
name STRING,
purchase_count int32,
)
-DISTRIBUTE BY RANGE(state)
-SPLIT ROWS(('al'),
- ('ak'),
- ('ar'),
- ...
- ('wv'),
- ('wy'))
+DISTRIBUTE BY RANGE (state)
+ SPLIT ROWS (('al'),
+ ('ak'),
+ ('ar'),
+ ...
+ ('wv'),
+ ('wy'))
TBLPROPERTIES(
'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
'kudu.table_name' = 'customers',
@@ -666,7 +668,7 @@ CREATE TABLE cust_behavior (
rating INT,
fulfilled_date BIGINT
)
-DISTRIBUTE BY HASH (id) INTO 16 BUCKETS
+DISTRIBUTE BY HASH INTO 16 BUCKETS
TBLPROPERTIES(
'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
'kudu.table_name' = 'cust_behavior',
@@ -701,14 +703,14 @@ CREATE TABLE customers (
name STRING,
purchase_count int32,
)
-DISTRIBUTE BY RANGE(state, name)
- SPLIT ROWS(('al', ''),
- ('al', 'm'),
- ('ak', ''),
- ('ak', 'm'),
- ...
- ('wy', ''),
- ('wy', 'm'))
+DISTRIBUTE BY RANGE (state, name)
+ SPLIT ROWS (('al', ''),
+ ('al', 'm'),
+ ('ak', ''),
+ ('ak', 'm'),
+ ...
+ ('wy', ''),
+ ('wy', 'm'))
TBLPROPERTIES(
'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
'kudu.table_name' = 'customers',
@@ -728,6 +730,10 @@ based upon the value of the `sku` string. Writes are spread across at least four
(and possibly up to 16). When you query for a contiguous range of `sku` values, you have a
good chance of only needing to read from a quarter of the tablets to fulfill the query.
+NOTE: By default, the entire primary key is hashed when you use `DISTRIBUTE BY HASH`.
+To hash on only part of the primary key, specify it by using syntax like `DISTRIBUTE
+BY HASH (id, sku)`.
+
[source,sql]
----
CREATE TABLE cust_behavior (
@@ -747,9 +753,9 @@ CREATE TABLE cust_behavior (
)
DISTRIBUTE BY HASH (id) INTO 4 BUCKETS,
RANGE (sku)
- SPLIT ROWS(('g'),
- ('o'),
- ('u'))
+ SPLIT ROWS (('g'),
+ ('o'),
+ ('u'))
TBLPROPERTIES(
'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
'kudu.table_name' = 'cust_behavior',
[4/4] kudu git commit: KUDU-526: use on-disk cmeta when loading
existing master state
Posted by ad...@apache.org.
KUDU-526: use on-disk cmeta when loading existing master state
The cmeta is populated when creating all new master state; we can trust it
when that master is restarted.
Note: this is a precondition for the migration from single-node to
multi-node master deployments.
Change-Id: I5b4c6d8b6adf696973445a6f9d1314ba9de27e70
Reviewed-on: http://gerrit.cloudera.org:8080/3786
Reviewed-by: Todd Lipcon <to...@apache.org>
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/2c3fc7c2
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/2c3fc7c2
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/2c3fc7c2
Branch: refs/heads/master
Commit: 2c3fc7c27f37ba3986f1d09eb79c7d4969c31f83
Parents: 5a70799
Author: Adar Dembo <ad...@cloudera.com>
Authored: Tue Jul 26 18:05:15 2016 -0700
Committer: Adar Dembo <ad...@cloudera.com>
Committed: Tue Aug 16 00:21:33 2016 +0000
----------------------------------------------------------------------
.../integration-tests/master_failover-itest.cc | 42 ++++++++++++++
.../master_replication-itest.cc | 13 +++++
src/kudu/master/sys_catalog.cc | 60 +++++++++++++-------
src/kudu/master/sys_catalog.h | 11 +---
4 files changed, 95 insertions(+), 31 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/kudu/blob/2c3fc7c2/src/kudu/integration-tests/master_failover-itest.cc
----------------------------------------------------------------------
diff --git a/src/kudu/integration-tests/master_failover-itest.cc b/src/kudu/integration-tests/master_failover-itest.cc
index 1a9b1b0..b1c31f5 100644
--- a/src/kudu/integration-tests/master_failover-itest.cc
+++ b/src/kudu/integration-tests/master_failover-itest.cc
@@ -27,10 +27,14 @@
#include "kudu/gutil/strings/substitute.h"
#include "kudu/gutil/strings/util.h"
#include "kudu/integration-tests/external_mini_cluster.h"
+#include "kudu/util/metrics.h"
#include "kudu/util/net/net_util.h"
#include "kudu/util/stopwatch.h"
#include "kudu/util/test_util.h"
+METRIC_DECLARE_entity(server);
+METRIC_DECLARE_histogram(handler_latency_kudu_consensus_ConsensusService_GetNodeInstance);
+
namespace kudu {
// Note: this test needs to be in the client namespace in order for
@@ -43,6 +47,7 @@ using sp::shared_ptr;
using std::string;
using std::vector;
using std::unique_ptr;
+using strings::Substitute;
class MasterFailoverTest : public KuduTest {
public:
@@ -322,5 +327,42 @@ TEST_F(MasterFailoverTest, TestKUDU1374) {
<< "Deadline elapsed before alter table completed";
}
+TEST_F(MasterFailoverTest, TestMasterUUIDResolution) {
+ // After a fresh start, the masters should have received RPCs asking for
+ // their UUIDs.
+ for (int i = 0; i < cluster_->num_masters(); i++) {
+ int64_t num_get_node_instances;
+ ASSERT_OK(cluster_->master(i)->GetInt64Metric(
+ &METRIC_ENTITY_server, "kudu.master",
+ &METRIC_handler_latency_kudu_consensus_ConsensusService_GetNodeInstance,
+ "total_count", &num_get_node_instances));
+
+ // Client-side timeouts may increase the number of calls beyond the raw
+ // number of masters.
+ ASSERT_GE(num_get_node_instances, cluster_->num_masters());
+ }
+
+ // Restart the masters. They should reuse one another's UUIDs from the cached
+ // consensus metadata instead of sending RPCs to discover them. See KUDU-526.
+ cluster_->Shutdown();
+ ASSERT_OK(cluster_->Restart());
+
+ // To determine whether the cached UUIDs were used, let's look at the number
+ // of GetNodeInstance() calls each master serviced. It should be zero.
+ for (int i = 0; i < cluster_->num_masters(); i++) {
+ ExternalMaster* master = cluster_->master(i);
+ int64_t num_get_node_instances;
+ ASSERT_OK(master->GetInt64Metric(
+ &METRIC_ENTITY_server, "kudu.master",
+ &METRIC_handler_latency_kudu_consensus_ConsensusService_GetNodeInstance,
+ "total_count", &num_get_node_instances));
+ EXPECT_EQ(0, num_get_node_instances) <<
+ Substitute(
+ "Following restart, master $0 has serviced $1 GetNodeInstance() calls",
+ master->bound_rpc_hostport().ToString(),
+ num_get_node_instances);
+ }
+}
+
} // namespace client
} // namespace kudu
http://git-wip-us.apache.org/repos/asf/kudu/blob/2c3fc7c2/src/kudu/integration-tests/master_replication-itest.cc
----------------------------------------------------------------------
diff --git a/src/kudu/integration-tests/master_replication-itest.cc b/src/kudu/integration-tests/master_replication-itest.cc
index 1307014..3356736 100644
--- a/src/kudu/integration-tests/master_replication-itest.cc
+++ b/src/kudu/integration-tests/master_replication-itest.cc
@@ -262,5 +262,18 @@ TEST_F(MasterReplicationTest, TestHeartbeatAcceptedByAnyMaster) {
MiniCluster::MatchMode::DO_NOT_MATCH_TSERVERS, &descs));
}
+TEST_F(MasterReplicationTest, TestMasterPeerSetsDontMatch) {
+ // Restart one master with an additional entry in --master_addresses. The
+ // discrepancy with the on-disk list of masters should trigger a failure.
+ cluster_->mini_master(0)->Shutdown();
+ vector<uint16_t> master_rpc_ports = opts_.master_rpc_ports;
+ master_rpc_ports.push_back(55555);
+ ASSERT_OK(cluster_->mini_master(0)->StartDistributedMaster(master_rpc_ports));
+ Status s = cluster_->mini_master(0)->WaitForCatalogManagerInit();
+ SCOPED_TRACE(s.ToString());
+ ASSERT_TRUE(s.IsInvalidArgument());
+ ASSERT_STR_CONTAINS(s.ToString(), "55555")
+}
+
} // namespace master
} // namespace kudu
http://git-wip-us.apache.org/repos/asf/kudu/blob/2c3fc7c2/src/kudu/master/sys_catalog.cc
----------------------------------------------------------------------
diff --git a/src/kudu/master/sys_catalog.cc b/src/kudu/master/sys_catalog.cc
index 35da4b6..0658cb3 100644
--- a/src/kudu/master/sys_catalog.cc
+++ b/src/kudu/master/sys_catalog.cc
@@ -17,9 +17,12 @@
#include "kudu/master/sys_catalog.h"
+#include <algorithm>
#include <gflags/gflags.h>
#include <glog/logging.h>
+#include <iterator>
#include <memory>
+#include <set>
#include "kudu/common/partial_row.h"
#include "kudu/common/partition.h"
@@ -32,6 +35,7 @@
#include "kudu/consensus/opid_util.h"
#include "kudu/consensus/quorum_util.h"
#include "kudu/fs/fs_manager.h"
+#include "kudu/gutil/strings/join.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/master/catalog_manager.h"
#include "kudu/master/master.h"
@@ -54,6 +58,7 @@ TAG_FLAG(sys_catalog_fail_during_write, unsafe);
using kudu::consensus::CONSENSUS_CONFIG_COMMITTED;
using kudu::consensus::ConsensusMetadata;
+using kudu::consensus::ConsensusStatePB;
using kudu::consensus::RaftConfigPB;
using kudu::consensus::RaftPeerPB;
using kudu::log::Log;
@@ -107,27 +112,41 @@ Status SysCatalogTable::Load(FsManager *fs_manager) {
return(Status::Corruption("Unexpected schema", metadata->schema().ToString()));
}
- // Allow for statically and explicitly assigning the consensus configuration and roles through
- // the master configuration on startup.
- //
- // TODO: The following assumptions need revisiting:
- // 1. We always believe the local config options for who is in the consensus configuration.
- // 2. We always want to look up all node's UUIDs on start (via RPC).
- // - TODO: Cache UUIDs. See KUDU-526.
if (master_->opts().IsDistributed()) {
- LOG(INFO) << "Configuring consensus for distributed operation...";
-
+ LOG(INFO) << "Verifying existing consensus state";
string tablet_id = metadata->tablet_id();
unique_ptr<ConsensusMetadata> cmeta;
RETURN_NOT_OK_PREPEND(ConsensusMetadata::Load(fs_manager, tablet_id,
fs_manager->uuid(), &cmeta),
"Unable to load consensus metadata for tablet " + tablet_id);
-
- RaftConfigPB config;
- RETURN_NOT_OK(SetupDistributedConfig(master_->opts(), &config));
- cmeta->set_committed_config(config);
- RETURN_NOT_OK_PREPEND(cmeta->Flush(),
- "Unable to persist consensus metadata for tablet " + tablet_id);
+ ConsensusStatePB cstate = cmeta->ToConsensusStatePB(CONSENSUS_CONFIG_COMMITTED);
+ RETURN_NOT_OK(consensus::VerifyConsensusState(
+ cstate, consensus::COMMITTED_QUORUM));
+
+ // Make sure the set of masters passed in at start time matches the set in
+ // the on-disk cmeta.
+ set<string> peer_addrs_from_opts;
+ for (const auto& hp : master_->opts().master_addresses) {
+ peer_addrs_from_opts.insert(hp.ToString());
+ }
+ set<string> peer_addrs_from_disk;
+ for (const auto& p : cstate.config().peers()) {
+ HostPort hp;
+ RETURN_NOT_OK(HostPortFromPB(p.last_known_addr(), &hp));
+ peer_addrs_from_disk.insert(hp.ToString());
+ }
+ vector<string> symm_diff;
+ std::set_symmetric_difference(peer_addrs_from_opts.begin(),
+ peer_addrs_from_opts.end(),
+ peer_addrs_from_disk.begin(),
+ peer_addrs_from_disk.end(),
+ std::back_inserter(symm_diff));
+ if (!symm_diff.empty()) {
+ string msg = Substitute(
+ "on-disk and provided master lists are different: $0",
+ JoinStrings(symm_diff, " "));
+ return Status::InvalidArgument(msg);
+ }
}
RETURN_NOT_OK(SetupTablet(metadata));
@@ -157,8 +176,8 @@ Status SysCatalogTable::CreateNew(FsManager *fs_manager) {
RaftConfigPB config;
if (master_->opts().IsDistributed()) {
- RETURN_NOT_OK_PREPEND(SetupDistributedConfig(master_->opts(), &config),
- "Failed to initialize distributed config");
+ RETURN_NOT_OK_PREPEND(CreateDistributedConfig(master_->opts(), &config),
+ "Failed to create new distributed Raft config");
} else {
config.set_opid_index(consensus::kInvalidOpIdIndex);
RaftPeerPB* peer = config.add_peers();
@@ -175,8 +194,8 @@ Status SysCatalogTable::CreateNew(FsManager *fs_manager) {
return SetupTablet(metadata);
}
-Status SysCatalogTable::SetupDistributedConfig(const MasterOptions& options,
- RaftConfigPB* committed_config) {
+Status SysCatalogTable::CreateDistributedConfig(const MasterOptions& options,
+ RaftConfigPB* committed_config) {
DCHECK(options.IsDistributed());
RaftConfigPB new_config;
@@ -206,9 +225,6 @@ Status SysCatalogTable::SetupDistributedConfig(const MasterOptions& options,
LOG(INFO) << peer.ShortDebugString()
<< " has no permanent_uuid. Determining permanent_uuid...";
RaftPeerPB new_peer = peer;
- // TODO: Use ConsensusMetadata to cache the results of these lookups so
- // we only require RPC access to the full consensus configuration on first startup.
- // See KUDU-526.
RETURN_NOT_OK_PREPEND(consensus::SetPermanentUuidForRemotePeer(master_->messenger(),
&new_peer),
Substitute("Unable to resolve UUID for peer $0",
http://git-wip-us.apache.org/repos/asf/kudu/blob/2c3fc7c2/src/kudu/master/sys_catalog.h
----------------------------------------------------------------------
diff --git a/src/kudu/master/sys_catalog.h b/src/kudu/master/sys_catalog.h
index efb2125..9d22ef9 100644
--- a/src/kudu/master/sys_catalog.h
+++ b/src/kudu/master/sys_catalog.h
@@ -134,15 +134,8 @@ class SysCatalogTable {
// Use the master options to generate a new consensus configuration.
// In addition, resolve all UUIDs of this consensus configuration.
- //
- // Note: The current node adds itself to the peers whether leader or
- // follower, depending on whether the Master options leader flag is
- // set. Even if the local node should be a follower, it should not be listed
- // in the Master options followers list, as it will add itself automatically.
- //
- // TODO: Revisit this whole thing when integrating leader election.
- Status SetupDistributedConfig(const MasterOptions& options,
- consensus::RaftConfigPB* committed_config);
+ Status CreateDistributedConfig(const MasterOptions& options,
+ consensus::RaftConfigPB* committed_config);
const scoped_refptr<tablet::TabletPeer>& tablet_peer() const {
return tablet_peer_;
[2/4] kudu git commit: Add docs for non-covering range partitioning
Posted by ad...@apache.org.
Add docs for non-covering range partitioning
Change-Id: I3b0fd7500c5399db9dcad617ae67fea247307353
Reviewed-on: http://gerrit.cloudera.org:8080/3796
Reviewed-by: Dan Burkert <da...@cloudera.com>
Tested-by: Misty Stanley-Jones <mi...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/kudu/repo
Commit: http://git-wip-us.apache.org/repos/asf/kudu/commit/274dfb05
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/274dfb05
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/274dfb05
Branch: refs/heads/master
Commit: 274dfb05944edef1fac3be78ea0c699b048c5b31
Parents: 0fb4409
Author: Misty Stanley-Jones <mi...@apache.org>
Authored: Wed Jul 27 12:19:52 2016 -0700
Committer: Misty Stanley-Jones <mi...@apache.org>
Committed: Mon Aug 15 22:10:56 2016 +0000
----------------------------------------------------------------------
docs/kudu_impala_integration.adoc | 55 ++++++++++
docs/schema_design.adoc | 193 +++++++++++++++++++--------------
2 files changed, 168 insertions(+), 80 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/kudu/blob/274dfb05/docs/kudu_impala_integration.adoc
----------------------------------------------------------------------
diff --git a/docs/kudu_impala_integration.adoc b/docs/kudu_impala_integration.adoc
index 793b402..fb29bd8 100755
--- a/docs/kudu_impala_integration.adoc
+++ b/docs/kudu_impala_integration.adoc
@@ -795,6 +795,61 @@ The example creates 16 buckets. You could also use `HASH (id, sku) INTO 16 BUCKE
However, a scan for `sku` values would almost always impact all 16 buckets, rather
than possibly being limited to 4.
+// Not ready for 0.10 but don't want to lose the work
+////
+
+.Non-Covering Range Partitions
+Kudu TODO:VERSION and higher supports the use of non-covering range partitions,
+which address scenarios like the following:
+
+- Without non-covering range partitions, in the case of time-series data or other
+ schemas which need to account for constantly-increasing primary keys, tablets
+ serving old data will be relatively fixed in size, while tablets receiving new
+ data will grow without bounds.
+
+- In cases where you want to partition data based on its category, such as sales
+ region or product type, without non-covering range partitions you must know all
+ of the partitions ahead of time or manually recreate your table if partitions
+ need to be added or removed, such as the introduction or elimination of a product
+ type.
+
+Non-covering range partitions have some caveats. Be sure to read the
+link:/docs/schema_design.html [Schema Design guide].
+
+This example creates a tablet per year (5 tablets total), for storing log data. It uses `RANGE BOUND`
+to ensure that the table only accepts data from 2011 to 2017. Keys outside of these
+ranges will be rejected.
+
+[source,sql]
+----
+CREATE TABLE sales_by_year (year INT32, sale_id INT32, amount INT32)
+PRIMARY KEY (sale_id, year)
+DISTRIBUTE BY RANGE (year)
+ RANGE BOUND ((2011), (2016))
+ SPLIT ROWS ((2012), (2013), (2014), (2015), (2016));
+----
+
+When records start coming in for 2017, they will be rejected. At that point, the `2017`
+range should be added. An `alter table add range partition` or `alter table drop range
+partition` operation allows you to add or drop a range partition.
+
+The next example creates a table per sales region. Data for regions other than `North
+America`, `Europe`, or `Asia` will be rejected. This example does not use explicit
+split rows, but the range bounds provide implicit split rows, so three tablets would
+be created. If a new range is added, a new tablet is created.
+
+[source,sql]
+----
+CREATE TABLE sales_by_region (region STRING, sale_id INT32, amount INT32)
+PRIMARY KEY (sale_id, region)
+DISTRIBUTE BY RANGE (region)
+ RANGE BOUND (("North America"), ("North America\0")),
+ RANGE BOUND (("Europe"), ("Europe\0")),
+ RANGE BOUND (("Asia"), ("Asia\0"));
+----
+
+////
+
[[partitioning_rules_of_thumb]]
==== Partitioning Rules of Thumb
http://git-wip-us.apache.org/repos/asf/kudu/blob/274dfb05/docs/schema_design.adoc
----------------------------------------------------------------------
diff --git a/docs/schema_design.adoc b/docs/schema_design.adoc
index 0851e44..1d3078f 100644
--- a/docs/schema_design.adoc
+++ b/docs/schema_design.adoc
@@ -41,89 +41,21 @@ be a new concept for those familiar with traditional relational databases. The
next sections discuss <<alter-schema,altering the schema>> of an existing table,
and <<known-limitations,known limitations>> with regard to schema design.
-[[column-design]]
-== Column Design
-
-A Kudu Table consists of one or more columns, each with a predefined type.
-Columns that are not part of the primary key may optionally be nullable.
-Supported column types include:
-
-* boolean
-* 8-bit signed integer
-* 16-bit signed integer
-* 32-bit signed integer
-* 64-bit signed integer
-* timestamp
-* single-precision (32-bit) IEEE-754 floating-point number
-* double-precision (64-bit) IEEE-754 floating-point number
-* UTF-8 encoded string
-* binary
-
-Kudu takes advantage of strongly-typed columns and a columnar on-disk storage
-format to provide efficient encoding and serialization. To make the most of these
-features, columns must be specified as the appropriate type, rather than
-simulating a 'schemaless' table using string or binary columns for data which
-may otherwise be structured. In addition to encoding, Kudu optionally allows
-compression to be specified on a per-column basis.
-
-[[encoding]]
-=== Column Encoding
-
-Each column in a Kudu table can be created with an encoding, based on the type
-of the column. Columns use plain encoding by default.
-
-.Encoding Types
-[options="header"]
-|===
-| Column Type | Encoding
-| integer, timestamp | plain, bitshuffle, run length
-| float | plain, bitshuffle
-| bool | plain, dictionary, run length
-| string, binary | plain, prefix, dictionary
-|===
-
-[[plain]]
-Plain Encoding:: Data is stored in its natural format. For example, `int32` values
-are stored as fixed-size 32-bit little-endian integers.
-
-[[bitshuffle]]
-Bitshuffle Encoding:: Data is rearranged to store the most significant bit of
-every value, followed by the second most significant bit of every value, and so
-on. Finally, the result is LZ4 compressed. Bitshuffle encoding is a good choice for
-columns that have many repeated values, or values that change by small amounts
-when sorted by primary key. The
-https://github.com/kiyo-masui/bitshuffle[bitshuffle] project has a good
-overview of performance and use cases.
-
-[[run-length]]
-Run Length Encoding:: _Runs_ (consecutive repeated values) are compressed in a
-column by storing only the value and the count. Run length encoding is effective
-for columns with many consecutive repeated values when sorted by primary key.
-
-[[dictionary]]
-Dictionary Encoding:: A dictionary of unique values is built, and each column value
-is encoded as its corresponding index in the dictionary. Dictionary encoding
-is effective for columns with low cardinality. If the column values of a given row set
-are unable to be compressed because the number of unique values is too high, Kudu will
-transparently fall back to plain encoding for that row set. This is evaluated during
-flush.
+== The Perfect Schema
-[[prefix]]
-Prefix Encoding:: Common prefixes are compressed in consecutive column values. Prefix
-encoding can be effective for values that share common prefixes, or the first
-column of the primary key, since rows are sorted by primary key within tablets.
+The perfect schema would accomplish the following:
-[[compression]]
-=== Column Compression
+- Data would be distributed in such a way that reads and writes are spread evenly
+ across tablet servers. This is impacted by the partition schema.
+- Tablets would grow at an even, predictable rate and load across tablets would remain
+ steady over time. This is most impacted by the partition schema.
+- Scans would read the minimum amount of data necessary to fulfill a query. This
+ is impacted mostly by primary key design, but partition design also plays a
+ role via partition pruning.
-Kudu allows per-column compression using LZ4, `snappy`, or `zlib` compression
-codecs. By default, columns are stored uncompressed. Consider using compression
-if reducing storage space is more important than raw scan performance.
-
-Every data set will compress differently, but in general LZ4 has the least effect on
-performance, while `zlib` will compress to the smallest data sizes.
-Bitshuffle-encoded columns are inherently compressed using LZ4, so it is not
-typically beneficial to apply additional compression on top of this encoding.
+The perfect schema depends on the characteristics of your data, what you need to do
+with it, and the topology of your cluster. Schema design is the single most important
+thing within your control to maximize the performance of your Kudu cluster.
[[primary-keys]]
== Primary Keys
@@ -209,6 +141,23 @@ should only include the `last_name` column. In that case, Kudu would guarantee t
customers with the same last name would fall into the same tablet, regardless of
the provided split rows.
+[[range-partition-management]]
+==== Range Partition Management
+
+Kudu 0.10 introduces the ability to specify bounded range partitions during
+table creation, and the ability add and drop range partitions on the fly. This is
+a good strategy for data which is always increasing, such as timestamps, or for
+categorical data, such as geographic regions.
+
+For example, during table creation, bounded range partitions can be
+added for the regions 'US-EAST', 'US-WEST', and 'EUROPE'. If you attempt to insert a
+row with a region that does not match an existing range partition, the insertion will
+fail. Later, when a new region is needed it can be efficiently added as part of an
+`ALTER TABLE` operation. This feature is particularly useful for timeseries data,
+since it allows new range partitions for the current period to be added as
+needed, and old partitions covering historical periods to be dropped if
+necessary.
+
[[hash-bucketing]]
=== Hash Bucketing
@@ -272,6 +221,90 @@ You can alter a table's schema in the following ways:
You cannot modify the partition schema after table creation.
+[[column-design]]
+== Column Design
+
+A Kudu Table consists of one or more columns, each with a predefined type.
+Columns that are not part of the primary key may optionally be nullable.
+Supported column types include:
+
+* boolean
+* 8-bit signed integer
+* 16-bit signed integer
+* 32-bit signed integer
+* 64-bit signed integer
+* timestamp
+* single-precision (32-bit) IEEE-754 floating-point number
+* double-precision (64-bit) IEEE-754 floating-point number
+* UTF-8 encoded string
+* binary
+
+Kudu takes advantage of strongly-typed columns and a columnar on-disk storage
+format to provide efficient encoding and serialization. To make the most of these
+features, columns must be specified as the appropriate type, rather than
+simulating a 'schemaless' table using string or binary columns for data which
+may otherwise be structured. In addition to encoding, Kudu optionally allows
+compression to be specified on a per-column basis.
+
+[[encoding]]
+=== Column Encoding
+
+Each column in a Kudu table can be created with an encoding, based on the type
+of the column. Columns use plain encoding by default.
+
+.Encoding Types
+[options="header"]
+|===
+| Column Type | Encoding
+| integer, timestamp | plain, bitshuffle, run length
+| float | plain, bitshuffle
+| bool | plain, dictionary, run length
+| string, binary | plain, prefix, dictionary
+|===
+
+[[plain]]
+Plain Encoding:: Data is stored in its natural format. For example, `int32` values
+are stored as fixed-size 32-bit little-endian integers.
+
+[[bitshuffle]]
+Bitshuffle Encoding:: Data is rearranged to store the most significant bit of
+every value, followed by the second most significant bit of every value, and so
+on. Finally, the result is LZ4 compressed. Bitshuffle encoding is a good choice for
+columns that have many repeated values, or values that change by small amounts
+when sorted by primary key. The
+https://github.com/kiyo-masui/bitshuffle[bitshuffle] project has a good
+overview of performance and use cases.
+
+[[run-length]]
+Run Length Encoding:: _Runs_ (consecutive repeated values) are compressed in a
+column by storing only the value and the count. Run length encoding is effective
+for columns with many consecutive repeated values when sorted by primary key.
+
+[[dictionary]]
+Dictionary Encoding:: A dictionary of unique values is built, and each column value
+is encoded as its corresponding index in the dictionary. Dictionary encoding
+is effective for columns with low cardinality. If the column values of a given row set
+are unable to be compressed because the number of unique values is too high, Kudu will
+transparently fall back to plain encoding for that row set. This is evaluated during
+flush.
+
+[[prefix]]
+Prefix Encoding:: Common prefixes are compressed in consecutive column values. Prefix
+encoding can be effective for values that share common prefixes, or the first
+column of the primary key, since rows are sorted by primary key within tablets.
+
+[[compression]]
+=== Column Compression
+
+Kudu allows per-column compression using LZ4, `snappy`, or `zlib` compression
+codecs. By default, columns are stored uncompressed. Consider using compression
+if reducing storage space is more important than raw scan performance.
+
+Every data set will compress differently, but in general LZ4 has the least effect on
+performance, while `zlib` will compress to the smallest data sizes.
+Bitshuffle-encoded columns are inherently compressed using LZ4, so it is not
+typically beneficial to apply additional compression on top of this encoding.
+
[[known-limitations]]
== Known Limitations