Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disagg: Reduce the number of threads created for handling disaggregated requests (release-8.1) #9402

Merged
merged 6 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions dbms/src/Common/UniThreadPool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@ void ThreadPoolImpl<Thread>::setQueueSize(size_t value)
jobs.reserve(queue_size);
}

template <typename Thread>
size_t ThreadPoolImpl<Thread>::getQueueSize() const
{
std::lock_guard lock(mutex);
return queue_size;
}


template <typename Thread>
template <typename ReturnType>
Expand Down Expand Up @@ -198,6 +205,14 @@ void ThreadPoolImpl<Thread>::scheduleOrThrow(
scheduleImpl<void>(std::move(job), priority, wait_microseconds, propagate_opentelemetry_tracing_context);
}

template <typename Thread>
std::future<void> ThreadPoolImpl<Thread>::scheduleWithFuture(Job job, uint64_t wait_timeout_us)
{
auto task = std::make_shared<std::packaged_task<void()>>(std::move(job));
scheduleImpl<void>([task]() { (*task)(); }, /*priority*/ 0, wait_timeout_us);
return task->get_future();
}

template <typename Thread>
void ThreadPoolImpl<Thread>::wait()
{
Expand Down
7 changes: 7 additions & 0 deletions dbms/src/Common/UniThreadPool.h
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,21 @@ class ThreadPoolImpl
void scheduleOrThrowOnError(Job job, ssize_t priority = 0);

/// Similar to scheduleOrThrowOnError(...). Wait for specified amount of time and schedule a job or return false.
/// If wait_microseconds is zero, it means never wait.
bool trySchedule(Job job, ssize_t priority = 0, uint64_t wait_microseconds = 0) noexcept;

/// Similar to scheduleOrThrowOnError(...). Wait for specified amount of time and schedule a job or throw an exception.
/// If wait_microseconds is zero, it means never wait.
void scheduleOrThrow(
Job job,
ssize_t priority = 0,
uint64_t wait_microseconds = 0,
bool propagate_opentelemetry_tracing_context = true);

/// Wrap job with std::packaged_task<void> and returns a std::future<void> object to check if the task has finished or thrown an exception.
/// If wait_microseconds is zero, it means never wait.
std::future<void> scheduleWithFuture(Job job, uint64_t wait_timeout_us = 0);

/// Wait for all currently active jobs to be done.
/// You may call schedule and wait many times in arbitrary order.
/// If any thread was throw an exception, first exception will be rethrown from this method,
Expand All @@ -104,6 +110,7 @@ class ThreadPoolImpl
void setMaxFreeThreads(size_t value);
void setQueueSize(size_t value);
size_t getMaxThreads() const;
size_t getQueueSize() const;

std::unique_ptr<ThreadPoolWaitGroup<Thread>> waitGroup()
{
Expand Down
83 changes: 70 additions & 13 deletions dbms/src/IO/IOThreadPools.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@
namespace DB
{

namespace io_pool_details
namespace IOPoolHelper
{

struct S3FileCacheTrait
{
};
Expand All @@ -30,28 +29,86 @@ struct DataStoreS3Trait
{
};

struct RemoteReadTaskTrait
struct RNWritePageCacheTrait
{
};

struct RNPreparerTrait
struct WNEstablishDisaggTaskTrait
{
};

struct RNWritePageCacheTrait
struct BuildReadTaskForWNTrait
{
};
struct BuildReadTaskForWNTableTrait
{
};
struct BuildReadTaskTrait
{
};

struct WNEstablishDisaggTaskTrait
// FutureContainer will wait for all futures finished automatically.
class FutureContainer
{
public:
FutureContainer(const LoggerPtr & log_, size_t reserve_size = 0)
: log(log_)
{
futures.reserve(reserve_size);
}

~FutureContainer() { waitFinish(); }

void add(std::future<void> && f) { futures.push_back(std::move(f)); }

// Get the results of all futures.
// If exceptions happened, rethrow the first exception.
void getAllResults()
{
std::exception_ptr first_exception;
for (auto & f : futures)
{
try
{
f.get();
}
catch (...)
{
if (!first_exception)
first_exception = std::current_exception();
tryLogCurrentException(log);
}
}

if (first_exception)
std::rethrow_exception(first_exception);
}

private:
// Just wait futures finished. Don't care about the results.
void waitFinish()
{
for (auto & f : futures)
if (f.valid())
f.wait();
}
std::vector<std::future<void>> futures;
LoggerPtr log;
};
} // namespace io_pool_details

} // namespace IOPoolHelper

// TODO: Move these out.
using DataStoreS3Pool = IOThreadPool<io_pool_details::DataStoreS3Trait>;
using S3FileCachePool = IOThreadPool<io_pool_details::S3FileCacheTrait>;
using RNRemoteReadTaskPool = IOThreadPool<io_pool_details::RemoteReadTaskTrait>;
using RNPagePreparerPool = IOThreadPool<io_pool_details::RNPreparerTrait>;
using RNWritePageCachePool = IOThreadPool<io_pool_details::RNWritePageCacheTrait>;
using WNEstablishDisaggTaskPool = IOThreadPool<io_pool_details::WNEstablishDisaggTaskTrait>;
using DataStoreS3Pool = IOThreadPool<IOPoolHelper::DataStoreS3Trait>;
using S3FileCachePool = IOThreadPool<IOPoolHelper::S3FileCacheTrait>;
using RNWritePageCachePool = IOThreadPool<IOPoolHelper::RNWritePageCacheTrait>;
using WNEstablishDisaggTaskPool = IOThreadPool<IOPoolHelper::WNEstablishDisaggTaskTrait>;

// The call chain is `buildReadTaskForWriteNode => buildReadTaskForWriteNodeTable => buildRNReadSegmentTask`.
// Each of them will use the corresponding thread pool.
// Cannot share one thread pool. Because in extreme cases, if the previous function exhausts all threads,
// the subsequent functions will wait for idle threads, causing a deadlock.
using BuildReadTaskForWNPool = IOThreadPool<IOPoolHelper::BuildReadTaskForWNTrait>;
using BuildReadTaskForWNTablePool = IOThreadPool<IOPoolHelper::BuildReadTaskForWNTableTrait>;
using BuildReadTaskPool = IOThreadPool<IOPoolHelper::BuildReadTaskTrait>;
} // namespace DB
195 changes: 195 additions & 0 deletions dbms/src/IO/tests/gtest_io_thread.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// Copyright 2024 PingCAP, Inc.
//
// Licensed 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 <IO/IOThreadPools.h>
#include <gtest/gtest.h>

#include <array>
#include <exception>
#include <ext/scope_guard.h>
#include <future>
#include <random>

namespace DB::tests
{
namespace
{
using SPtr = std::shared_ptr<std::atomic<int>>;
using WPtr = std::weak_ptr<std::atomic<int>>;

void buildReadTasks(bool throw_in_build_read_tasks, bool throw_in_build_task, WPtr wp, SPtr invalid_count)
{
auto async_build_read_task = [=]() {
return BuildReadTaskPool::get().scheduleWithFuture([=]() {
std::random_device rd;
std::mt19937 gen(rd());
auto sleep_ms = gen() % 100 + 1; // 1~100
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));

if (auto sp = wp.lock(); sp)
sp->fetch_add(1);
else
invalid_count->fetch_add(1);

if (throw_in_build_task)
throw Exception("From build_read_task");
});
};

IOPoolHelper::FutureContainer futures(Logger::get("buildReadTasks"));
for (int i = 0; i < 10; i++)
{
futures.add(async_build_read_task());
if (i >= 5 && throw_in_build_read_tasks)
throw Exception("From buildReadTasks");
}
futures.getAllResults();
}

void buildReadTasksForTables(
bool throw_in_build_read_tasks_for_tables,
bool throw_in_build_read_tasks,
bool throw_in_build_task,
WPtr wp,
SPtr invalid_count)
{
auto async_build_read_tasks_for_table = [=]() {
return BuildReadTaskForWNTablePool::get().scheduleWithFuture(
[=]() { buildReadTasks(throw_in_build_read_tasks, throw_in_build_task, wp, invalid_count); });
};

IOPoolHelper::FutureContainer futures(Logger::get("buildReadTasksForTables"));
for (int i = 0; i < 10; i++)
{
futures.add(async_build_read_tasks_for_table());
if (i >= 5 && throw_in_build_read_tasks_for_tables)
throw Exception("From buildReadTasksForTables");
}
futures.getAllResults();
}

void buildReadTasksForWNs(
bool throw_in_build_read_tasks_for_wns,
bool throw_in_build_read_tasks_for_tables,
bool throw_in_build_read_tasks,
bool throw_in_build_task)
{
auto log = Logger::get("buildReadTasksForWNs");
LOG_INFO(
log,
"throw_in_build_read_tasks_for_wns={}, "
"throw_in_build_read_tasks_for_tables={}, throw_in_build_read_tasks={}, throw_in_build_task={}",
throw_in_build_read_tasks_for_wns,
throw_in_build_read_tasks_for_tables,
throw_in_build_read_tasks,
throw_in_build_task);
auto sp = std::make_shared<std::atomic<int>>(0);
auto invalid_count = std::make_shared<std::atomic<int>>(0);
// Use weak_ptr to simulate capture by reference.
auto async_build_tasks_for_wn = [wp = WPtr{sp},
invalid_count,
throw_in_build_read_tasks_for_tables,
throw_in_build_read_tasks,
throw_in_build_task]() {
return BuildReadTaskForWNPool::get().scheduleWithFuture([=]() {
buildReadTasksForTables(
throw_in_build_read_tasks_for_tables,
throw_in_build_read_tasks,
throw_in_build_task,
wp,
invalid_count);
});
};

try
{
IOPoolHelper::FutureContainer futures(log);
SCOPE_EXIT({
if (!throw_in_build_read_tasks_for_wns && !throw_in_build_read_tasks_for_tables
&& !throw_in_build_read_tasks)
ASSERT_EQ(*sp, 10 * 10 * 10);
ASSERT_EQ(*invalid_count, 0);
});
for (int i = 0; i < 10; i++)
{
futures.add(async_build_tasks_for_wn());
if (i >= 5 && throw_in_build_read_tasks_for_wns)
throw Exception("From buildReadTasksForWNs");
}
futures.getAllResults();
}
catch (...)
{
tryLogCurrentException(log);
}
}
} // namespace

TEST(IOThreadPool, TaskChain)
{
constexpr std::array<bool, 2> arr{false, true};
for (auto a : arr)
for (auto b : arr)
for (auto c : arr)
for (auto d : arr)
buildReadTasksForWNs(a, b, c, d);
}

TEST(IOThreadPool, WaitTimeout)
{
auto & thread_pool = BuildReadTaskPool::get();
const auto queue_size = thread_pool.getQueueSize();
std::atomic<bool> stop_flag{false};
IOPoolHelper::FutureContainer futures(Logger::get());
auto loop_until_stop = [&]() {
while (!stop_flag)
std::this_thread::sleep_for(std::chrono::seconds(1));
};
for (size_t i = 0; i < queue_size; ++i)
{
auto f = thread_pool.scheduleWithFuture(loop_until_stop);
futures.add(std::move(f));
}
ASSERT_EQ(thread_pool.active(), queue_size);

auto try_result = thread_pool.trySchedule(loop_until_stop);
ASSERT_FALSE(try_result);

try
{
auto f = thread_pool.scheduleWithFuture(loop_until_stop);
futures.add(std::move(f));
FAIL() << "Should throw exception.";
}
catch (Exception & e)
{
ASSERT_TRUE(e.message().starts_with("Cannot schedule a task: no free thread (timeout=0)"));
}

try
{
auto f = thread_pool.scheduleWithFuture(loop_until_stop, 10000);
futures.add(std::move(f));
FAIL() << "Should throw exception.";
}
catch (Exception & e)
{
ASSERT_TRUE(e.message().starts_with("Cannot schedule a task: no free thread (timeout=10000)"));
}

stop_flag.store(true);
futures.getAllResults();
}
} // namespace DB::tests
Loading