ClickHouse/dbms/include/DB/DataStreams/UnionBlockInputStream.h

335 lines
9.7 KiB
C
Raw Normal View History

2012-01-10 22:11:51 +00:00
#pragma once
#include <list>
#include <queue>
#include <Poco/Thread.h>
2012-01-10 22:11:51 +00:00
#include <Yandex/logger_useful.h>
2012-01-10 22:11:51 +00:00
2013-05-03 02:25:50 +00:00
#include <DB/Common/ConcurrentBoundedQueue.h>
2012-01-10 22:11:51 +00:00
#include <DB/DataStreams/IProfilingBlockInputStream.h>
namespace DB
{
using Poco::SharedPtr;
/** Объединяет несколько источников в один.
* Блоки из разных источников перемежаются друг с другом произвольным образом.
* Можно указать количество потоков (max_threads),
* в которых будет выполняться получение данных из разных источников.
*
* Устроено так:
* - есть набор источников, из которых можно вынимать блоки;
* - есть набор потоков, которые могут одновременно вынимать блоки из разных источников;
* - "свободные" источники (с которыми сейчас не работает никакой поток) кладутся в очередь источников;
* - когда поток берёт источник для обработки, он удаляет его из очереди источников,
* вынимает из него блок, и затем кладёт источник обратно в очередь источников;
* - полученные блоки складываются в ограниченную очередь готовых блоков;
* - основной поток вынимает готовые блоки из очереди готовых блоков.
2012-01-10 22:11:51 +00:00
*/
class UnionBlockInputStream : public IProfilingBlockInputStream
{
class Thread;
2012-01-10 22:11:51 +00:00
public:
UnionBlockInputStream(BlockInputStreams inputs_, unsigned max_threads_ = 1)
: max_threads(std::min(inputs_.size(), static_cast<size_t>(max_threads_))),
output_queue(max_threads), exhausted_inputs(0), finish(false),
pushed_end_of_output_queue(false), all_read(false), log(&Logger::get("UnionBlockInputStream"))
2012-01-10 22:11:51 +00:00
{
children.insert(children.end(), inputs_.begin(), inputs_.end());
2012-06-24 23:17:06 +00:00
2012-01-10 22:11:51 +00:00
for (size_t i = 0; i < inputs_.size(); ++i)
2012-06-24 23:17:06 +00:00
{
input_queue.push(InputData());
input_queue.back().in = inputs_[i];
input_queue.back().i = i;
2012-06-24 23:17:06 +00:00
}
2012-01-10 22:11:51 +00:00
}
2012-10-20 02:10:47 +00:00
String getName() const { return "UnionBlockInputStream"; }
String getID() const
{
std::stringstream res;
res << "Union(";
Strings children_ids(children.size());
for (size_t i = 0; i < children.size(); ++i)
children_ids[i] = children[i]->getID();
/// Порядок не имеет значения.
std::sort(children_ids.begin(), children_ids.end());
for (size_t i = 0; i < children_ids.size(); ++i)
res << (i == 0 ? "" : ", ") << children_ids[i];
res << ")";
return res.str();
}
2013-09-13 20:33:09 +00:00
2012-10-20 02:10:47 +00:00
~UnionBlockInputStream()
{
2013-09-14 05:14:22 +00:00
try
{
if (!all_read)
cancel();
if (!is_cancelled)
{
for (ThreadsData::iterator it = threads_data.begin(); it != threads_data.end(); ++it)
it->thread->join();
}
2013-09-14 05:14:22 +00:00
}
catch (...)
{
LOG_ERROR(log, "Exception while destroying UnionBlockInputStream.");
}
2012-10-20 02:10:47 +00:00
}
/** Отличается от реализации по-умолчанию тем, что пытается остановить все источники,
* пропуская отвалившиеся по эксепшену.
*/
void cancel()
{
2012-11-10 05:13:46 +00:00
if (!__sync_bool_compare_and_swap(&is_cancelled, false, true))
return;
finish = true;
for (BlockInputStreams::iterator it = children.begin(); it != children.end(); ++it)
{
if (IProfilingBlockInputStream * child = dynamic_cast<IProfilingBlockInputStream *>(&**it))
{
try
{
child->cancel();
}
catch (...)
{
2013-09-14 07:43:45 +00:00
LOG_ERROR(log, "Exception while cancelling " << child->getName());
}
}
}
LOG_TRACE(log, "Waiting for threads to finish");
/// Вынем всё, что есть в очереди готовых данных.
OutputData res;
while (output_queue.tryPop(res))
;
/** В этот момент, запоздавшие потоки ещё могут вставить в очередь какие-нибудь блоки, но очередь не переполнится.
* PS. Может быть, для переменной finish нужен барьер?
*/
for (ThreadsData::iterator it = threads_data.begin(); it != threads_data.end(); ++it)
it->thread->join();
LOG_TRACE(log, "Waited for threads to finish");
}
2012-10-20 02:10:47 +00:00
protected:
2012-01-10 22:11:51 +00:00
Block readImpl()
{
OutputData res;
if (all_read)
return res.block;
2012-10-20 02:10:47 +00:00
/// Запускаем потоки, если это ещё не было сделано.
if (threads_data.empty())
2012-01-10 22:11:51 +00:00
{
threads_data.resize(max_threads);
for (ThreadsData::iterator it = threads_data.begin(); it != threads_data.end(); ++it)
2012-06-22 18:27:40 +00:00
{
it->runnable = new Thread(*this);
it->thread = new Poco::Thread;
it->thread->start(*it->runnable);
2012-01-10 22:11:51 +00:00
}
}
2012-06-24 23:17:06 +00:00
/// Будем ждать, пока будет готов следующий блок или будет выкинуто исключение.
output_queue.pop(res);
2012-01-10 22:11:51 +00:00
if (res.exception)
res.exception->rethrow();
if (!res.block)
all_read = true;
return res.block;
2012-01-10 22:11:51 +00:00
}
2013-09-13 20:33:09 +00:00
void readSuffixImpl()
{
if (!all_read && !is_cancelled)
throw Exception("readSuffixImpl called before all data is read", ErrorCodes::LOGICAL_ERROR);
2013-11-29 15:04:07 +00:00
/// Может быть, в очереди есть ещё эксепшен.
OutputData res;
while (output_queue.tryPop(res) && res.exception)
res.exception->rethrow();
2013-09-13 20:33:09 +00:00
}
private:
2012-01-10 22:11:51 +00:00
/// Данные отдельного источника
struct InputData
2012-01-10 22:11:51 +00:00
{
BlockInputStreamPtr in;
size_t i; /// Порядковый номер источника (для отладки).
};
2012-01-10 22:11:51 +00:00
/// Данные отдельного потока
struct ThreadData
{
SharedPtr<Poco::Thread> thread;
SharedPtr<Thread> runnable;
2012-01-10 22:11:51 +00:00
};
class Thread : public Poco::Runnable
2012-01-10 22:11:51 +00:00
{
public:
Thread(UnionBlockInputStream & parent_) : parent(parent_) {}
void run()
2012-01-10 22:11:51 +00:00
{
ExceptionPtr exception;
try
{
loop();
}
catch (...)
{
exception = cloneCurrentException();
}
if (exception)
{
try
{
parent.cancel();
}
catch (...)
{
/** Если не удалось попросить остановиться одного или несколько источников.
* (например, разорвано соединение при распределённой обработке запроса)
* - то пофиг.
*/
}
/// Отдаём эксепшен в основной поток.
parent.output_queue.push(exception);
}
}
void loop()
{
while (!parent.finish) /// Может потребоваться прекратить работу раньше, чем все источники иссякнут.
{
InputData input;
/// Выбираем следующий источник.
{
Poco::ScopedLock<Poco::FastMutex> lock(parent.mutex);
/// Если свободных источников нет, то этот поток больше не нужен. (Но другие потоки могут работать со своими источниками.)
if (parent.input_queue.empty())
break;
input = parent.input_queue.front();
/// Убираем источник из очереди доступных источников.
parent.input_queue.pop();
}
/// Основная работа.
Block block = input.in->read();
{
Poco::ScopedLock<Poco::FastMutex> lock(parent.mutex);
/// Если этот источник ещё не иссяк, то положим полученный блок в очередь готовых.
if (block)
{
parent.input_queue.push(input);
parent.output_queue.push(block);
}
else
{
++parent.exhausted_inputs;
/// Если все источники иссякли.
if (parent.exhausted_inputs == parent.children.size())
{
parent.finish = true;
break;
}
}
}
}
if (parent.finish)
{
Poco::ScopedLock<Poco::FastMutex> lock(parent.mutex);
/// Отдаём в основной поток пустой блок, что означает, что данных больше нет.
if (!parent.pushed_end_of_output_queue)
{
parent.pushed_end_of_output_queue = true;
parent.output_queue.push(OutputData());
}
}
2012-01-10 22:11:51 +00:00
}
private:
UnionBlockInputStream & parent;
};
unsigned max_threads;
/// Потоки.
typedef std::list<ThreadData> ThreadsData;
ThreadsData threads_data;
/// Очередь доступных источников, которые не заняты каким-либо потоком в данный момент.
typedef std::queue<InputData> InputQueue;
InputQueue input_queue;
/// Блок или эксепшен.
struct OutputData
{
Block block;
ExceptionPtr exception;
OutputData() {}
OutputData(Block & block_) : block(block_) {}
OutputData(ExceptionPtr & exception_) : exception(exception_) {}
};
/// Очередь готовых блоков. Также туда можно положить эксепшен вместо блока.
typedef ConcurrentBoundedQueue<OutputData> OutputQueue;
OutputQueue output_queue;
/// Для операций с очередями.
Poco::FastMutex mutex;
/// Сколько источников иссякло.
size_t exhausted_inputs;
/// Завершить работу потоков (раньше, чем иссякнут источники).
volatile bool finish;
/// Положили ли в output_queue пустой блок.
bool pushed_end_of_output_queue;
bool all_read;
Logger * log;
2012-01-10 22:11:51 +00:00
};
}