ClickHouse/dbms/src/Server/TCPHandler.cpp

750 lines
22 KiB
C++
Raw Normal View History

2012-03-19 12:57:56 +00:00
#include <iomanip>
2013-01-13 22:13:54 +00:00
#include <Poco/Net/NetException.h>
2012-03-09 15:46:52 +00:00
#include <Yandex/Revision.h>
#include <statdaemons/Stopwatch.h>
#include <DB/Core/ErrorCodes.h>
2012-05-16 18:32:32 +00:00
#include <DB/Core/Progress.h>
2012-03-09 15:46:52 +00:00
2012-03-11 08:52:56 +00:00
#include <DB/IO/CompressedReadBuffer.h>
#include <DB/IO/CompressedWriteBuffer.h>
#include <DB/IO/ReadBufferFromPocoSocket.h>
#include <DB/IO/WriteBufferFromPocoSocket.h>
2012-03-09 15:46:52 +00:00
#include <DB/IO/copyData.h>
2012-10-20 05:54:35 +00:00
#include <DB/DataStreams/AsynchronousBlockInputStream.h>
#include <DB/DataStreams/NativeBlockInputStream.h>
#include <DB/DataStreams/NativeBlockOutputStream.h>
2012-03-09 15:46:52 +00:00
#include <DB/Interpreters/executeQuery.h>
#include <DB/Storages/StorageMemory.h>
#include <DB/Common/ExternalTable.h>
2012-03-09 15:46:52 +00:00
#include "TCPHandler.h"
namespace DB
{
void TCPHandler::runImpl()
{
2013-09-14 05:14:22 +00:00
connection_context = *server.global_context;
2012-08-02 17:33:31 +00:00
connection_context.setSessionContext(connection_context);
2012-07-26 20:16:57 +00:00
2013-09-14 05:14:22 +00:00
Settings global_settings = server.global_context->getSettings();
2012-08-16 18:02:15 +00:00
socket().setReceiveTimeout(global_settings.receive_timeout);
socket().setSendTimeout(global_settings.send_timeout);
socket().setNoDelay(true);
2012-05-21 06:49:05 +00:00
in = new ReadBufferFromPocoSocket(socket());
out = new WriteBufferFromPocoSocket(socket());
2013-08-10 09:04:45 +00:00
try
{
receiveHello();
}
catch (const Exception & e) /// Типично при неправильном имени пользователя, пароле, адресе.
2013-08-10 09:04:45 +00:00
{
if (e.code() == ErrorCodes::CLIENT_HAS_CONNECTED_TO_WRONG_PORT)
{
LOG_DEBUG(log, "Client has connected to wrong port.");
return;
}
2013-08-10 09:04:45 +00:00
try
{
/// Пытаемся отправить информацию об ошибке клиенту.
sendException(e);
}
catch (...) {}
throw;
}
2012-05-30 06:46:57 +00:00
2014-08-12 09:35:15 +00:00
/// При соединении может быть указана БД по умолчанию.
2012-05-30 06:46:57 +00:00
if (!default_database.empty())
{
2012-08-02 17:33:31 +00:00
if (!connection_context.isDatabaseExist(default_database))
2012-05-30 06:46:57 +00:00
{
Exception e("Database " + default_database + " doesn't exist", ErrorCodes::UNKNOWN_DATABASE);
LOG_ERROR(log, "Code: " << e.code() << ", e.displayText() = " << e.displayText()
2012-05-30 06:46:57 +00:00
<< ", Stack trace:\n\n" << e.getStackTrace().toString());
sendException(e);
return;
}
2012-08-02 17:33:31 +00:00
connection_context.setCurrentDatabase(default_database);
2012-05-30 06:46:57 +00:00
}
2012-05-21 06:49:05 +00:00
sendHello();
2012-03-09 15:46:52 +00:00
connection_context.setProgressCallback([this] (const Progress & value) { return this->updateProgress(value); });
2012-08-16 17:50:54 +00:00
while (1)
2012-03-09 15:46:52 +00:00
{
2012-08-16 17:50:54 +00:00
/// Ждём пакета от клиента. При этом, каждые POLL_INTERVAL сек. проверяем, не требуется ли завершить работу.
while (!static_cast<ReadBufferFromPocoSocket &>(*in).poll(global_settings.poll_interval * 1000000) && !Daemon::instance().isCancelled())
2012-08-16 17:50:54 +00:00
;
/// Если требуется завершить работу, или клиент отсоединился.
if (Daemon::instance().isCancelled() || in->eof())
2012-08-16 17:50:54 +00:00
break;
2012-03-19 12:57:56 +00:00
Stopwatch watch;
2012-05-09 08:16:09 +00:00
state.reset();
2012-12-06 17:32:48 +00:00
/** Исключение во время выполнения запроса (его надо отдать по сети клиенту).
2013-01-13 22:13:54 +00:00
* Клиент сможет его принять, если оно не произошло во время отправки другого пакета и клиент ещё не разорвал соединение.
2012-12-06 17:32:48 +00:00
*/
SharedPtr<Exception> exception;
2012-05-08 05:42:05 +00:00
try
{
/// Восстанавливаем контекст запроса.
query_context = connection_context;
/** Если Query - обрабатываем. Если Ping или Cancel - возвращаемся в начало.
* Могут прийти настройки на отдельный запрос, которые модифицируют query_context.
*/
if (!receivePacket())
continue;
2012-05-08 05:42:05 +00:00
/// Получить блоки временных таблиц
if (client_revision >= DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES)
readData(global_settings);
/// Очищаем, так как, получая данные внешних таблиц, мы получили пустой блок.
/// А значит, stream помечен как cancelled и читать из него нельзя.
2014-04-08 07:31:51 +00:00
state.block_in = nullptr;
state.maybe_compressed_in = nullptr; /// Для более корректного учёта MemoryTracker-ом.
2012-05-17 19:15:53 +00:00
/// Обрабатываем Query
state.io = executeQuery(state.query, query_context, false, state.stage);
if (state.io.out)
2014-11-08 23:54:03 +00:00
state.need_receive_data_for_insert = true;
2012-05-09 15:15:45 +00:00
after_check_cancelled.restart();
after_send_progress.restart();
2012-05-21 06:49:05 +00:00
/// Запрос требует приёма данных от клиента?
2014-11-08 23:54:03 +00:00
if (state.need_receive_data_for_insert)
processInsertQuery(global_settings);
2012-05-21 06:49:05 +00:00
else
processOrdinaryQuery();
sendEndOfStream();
2012-12-06 17:32:48 +00:00
state.reset();
2012-03-19 12:57:56 +00:00
}
catch (const Exception & e)
2012-03-19 12:57:56 +00:00
{
LOG_ERROR(log, "Code: " << e.code() << ", e.displayText() = " << e.displayText() << ", e.what() = " << e.what()
2012-05-08 05:42:05 +00:00
<< ", Stack trace:\n\n" << e.getStackTrace().toString());
2012-12-06 17:32:48 +00:00
exception = e.clone();
2012-05-28 19:34:55 +00:00
if (e.code() == ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT)
throw;
2012-05-08 05:42:05 +00:00
}
2013-01-13 22:13:54 +00:00
catch (const Poco::Net::NetException & e)
{
/** Сюда мы можем попадать, если была ошибка в соединении с клиентом,
* или в соединении с удалённым сервером, который использовался для обработки запроса.
* Здесь не получается отличить эти два случая.
* Хотя в одном из них, мы должны отправить эксепшен клиенту, а в другом - не можем.
* Будем пытаться отправить эксепшен клиенту в любом случае - см. ниже.
*/
2013-01-13 22:13:54 +00:00
LOG_ERROR(log, "Poco::Net::NetException. Code: " << ErrorCodes::POCO_EXCEPTION << ", e.code() = " << e.code()
<< ", e.displayText() = " << e.displayText() << ", e.what() = " << e.what());
2014-04-09 19:27:49 +00:00
exception = new Exception(e.displayText(), ErrorCodes::POCO_EXCEPTION);
2013-01-13 22:13:54 +00:00
}
catch (const Poco::Exception & e)
2012-05-08 05:42:05 +00:00
{
LOG_ERROR(log, "Poco::Exception. Code: " << ErrorCodes::POCO_EXCEPTION << ", e.code() = " << e.code()
<< ", e.displayText() = " << e.displayText() << ", e.what() = " << e.what());
2014-04-09 19:27:49 +00:00
exception = new Exception(e.displayText(), ErrorCodes::POCO_EXCEPTION);
2012-05-08 05:42:05 +00:00
}
2013-01-13 22:13:54 +00:00
catch (const std::exception & e)
2012-05-08 05:42:05 +00:00
{
LOG_ERROR(log, "std::exception. Code: " << ErrorCodes::STD_EXCEPTION << ", e.what() = " << e.what());
2012-12-06 17:32:48 +00:00
exception = new Exception(e.what(), ErrorCodes::STD_EXCEPTION);
2012-05-08 05:42:05 +00:00
}
catch (...)
{
LOG_ERROR(log, "Unknown exception. Code: " << ErrorCodes::UNKNOWN_EXCEPTION);
2012-12-06 17:32:48 +00:00
exception = new Exception("Unknown exception", ErrorCodes::UNKNOWN_EXCEPTION);
2012-03-19 12:57:56 +00:00
}
2012-03-09 15:46:52 +00:00
bool network_error = false;
2013-01-13 22:13:54 +00:00
try
{
if (exception)
2013-01-13 22:13:54 +00:00
sendException(*exception);
}
catch (...)
{
/** Не удалось отправить информацию об эксепшене клиенту. */
network_error = true;
LOG_WARNING(log, "Client has gone away.");
2013-01-13 22:13:54 +00:00
}
2012-12-06 21:13:50 +00:00
2013-01-13 22:13:54 +00:00
try
{
state.reset();
}
catch (...)
2012-12-06 17:32:48 +00:00
{
2013-01-13 22:13:54 +00:00
/** В процессе обработки запроса было исключение, которое мы поймали и, возможно, отправили клиенту.
* При уничтожении конвейера выполнения запроса, было второе исключение.
* Например, конвейер мог выполняться в нескольких потоках, и в каждом из них могло возникнуть исключение.
* Проигнорируем его.
*/
2012-12-06 17:32:48 +00:00
}
2012-05-08 05:42:05 +00:00
2012-03-09 15:46:52 +00:00
watch.stop();
2012-03-19 12:57:56 +00:00
LOG_INFO(log, std::fixed << std::setprecision(3)
<< "Processed in " << watch.elapsedSeconds() << " sec.");
if (network_error)
break;
2012-03-19 12:57:56 +00:00
}
2012-03-11 08:52:56 +00:00
}
void TCPHandler::readData(const Settings & global_settings)
2012-05-21 06:49:05 +00:00
{
while (1)
{
/// Ждём пакета от клиента. При этом, каждые POLL_INTERVAL сек. проверяем, не требуется ли завершить работу.
while (!static_cast<ReadBufferFromPocoSocket &>(*in).poll(global_settings.poll_interval * 1000000) && !Daemon::instance().isCancelled())
;
/// Если требуется завершить работу, или клиент отсоединился.
if (Daemon::instance().isCancelled() || in->eof())
return;
if (!receivePacket())
break;
}
}
void TCPHandler::processInsertQuery(const Settings & global_settings)
{
/** Сделано выше остальных строк, чтобы в случае, когда функция writePrefix кидает эксепшен,
* клиент получил эксепшен до того, как начнёт отправлять данные.
*/
state.io.out->writePrefix();
/// Отправляем клиенту блок - структура таблицы.
Block block = state.io.out_sample;
sendData(block);
readData(global_settings);
2012-08-08 19:45:34 +00:00
state.io.out->writeSuffix();
2012-05-21 06:49:05 +00:00
}
void TCPHandler::processOrdinaryQuery()
{
/// Вынимаем результат выполнения запроса, если есть, и пишем его в сеть.
if (state.io.in)
{
/// Отправим блок-заголовок, чтобы клиент мог подготовить формат вывода
if (state.io.in_sample && client_revision >= DBMS_MIN_REVISION_WITH_HEADER_BLOCK)
sendData(state.io.in_sample);
2013-09-13 20:33:09 +00:00
2012-10-20 05:54:35 +00:00
AsynchronousBlockInputStream async_in(state.io.in);
async_in.readPrefix();
2012-05-30 03:30:29 +00:00
2012-10-20 05:54:35 +00:00
std::stringstream query_pipeline;
async_in.dumpTree(query_pipeline);
LOG_DEBUG(log, "Query pipeline:\n" << query_pipeline.rdbuf());
2012-05-21 06:49:05 +00:00
2012-07-21 07:02:55 +00:00
Stopwatch watch;
2012-05-21 06:49:05 +00:00
while (true)
{
2012-10-20 05:54:35 +00:00
Block block;
2012-10-20 05:54:35 +00:00
while (true)
{
if (isQueryCancelled())
2012-10-20 05:54:35 +00:00
{
/// Получен пакет с просьбой прекратить выполнение запроса.
async_in.cancel();
2012-10-20 05:54:35 +00:00
break;
}
else
2012-10-20 06:40:55 +00:00
{
if (state.progress.rows && after_send_progress.elapsed() / 1000 >= query_context.getSettingsRef().interactive_delay)
{
/// Прошло некоторое время и есть прогресс.
after_send_progress.restart();
sendProgress();
}
if (async_in.poll(query_context.getSettingsRef().interactive_delay / 1000))
{
/// Есть следующий блок результата.
block = async_in.read();
break;
}
}
2012-10-20 05:54:35 +00:00
}
/** Если закончились данные, то отправим данные профайлинга и тотальные значения до
* последнего нулевого блока, чтобы иметь возможность использовать
* эту информацию в выводе суффикса output stream'а.
* Если запрос был прерван, то вызывать методы sendTotals и другие нельзя,
* потому что мы прочитали ещё не все данные, и в это время могут производиться какие-то
* вычисления в других потоках.
*/
if (!block && !isQueryCancelled())
{
sendTotals();
sendExtremes();
2013-05-22 14:57:43 +00:00
sendProfileInfo();
sendProgress();
}
sendData(block);
2012-05-21 06:49:05 +00:00
if (!block)
break;
}
2012-07-21 07:02:55 +00:00
async_in.readSuffix();
2013-09-13 20:33:09 +00:00
2012-07-21 07:02:55 +00:00
watch.stop();
logProfileInfo(watch, *state.io.in);
}
}
2013-05-22 14:57:43 +00:00
void TCPHandler::sendProfileInfo()
{
if (client_revision < DBMS_MIN_REVISION_WITH_PROFILING_PACKET)
return;
2013-05-22 14:57:43 +00:00
if (const IProfilingBlockInputStream * input = dynamic_cast<const IProfilingBlockInputStream *>(&*state.io.in))
{
writeVarUInt(Protocol::Server::ProfileInfo, *out);
input->getInfo().write(*out);
out->next();
}
}
void TCPHandler::sendTotals()
{
if (client_revision < DBMS_MIN_REVISION_WITH_TOTALS_EXTREMES)
return;
if (IProfilingBlockInputStream * input = dynamic_cast<IProfilingBlockInputStream *>(&*state.io.in))
{
const Block & totals = input->getTotals();
if (totals)
{
initBlockOutput();
writeVarUInt(Protocol::Server::Totals, *out);
if (client_revision >= DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES)
writeStringBinary("", *out);
2013-09-06 23:43:11 +00:00
state.block_out->write(totals);
state.maybe_compressed_out->next();
out->next();
}
}
}
void TCPHandler::sendExtremes()
{
if (client_revision < DBMS_MIN_REVISION_WITH_TOTALS_EXTREMES)
return;
if (const IProfilingBlockInputStream * input = dynamic_cast<const IProfilingBlockInputStream *>(&*state.io.in))
{
const Block & extremes = input->getExtremes();
if (extremes)
{
initBlockOutput();
writeVarUInt(Protocol::Server::Extremes, *out);
if (client_revision >= DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES)
writeStringBinary("", *out);
state.block_out->write(extremes);
state.maybe_compressed_out->next();
out->next();
}
}
}
2012-07-21 07:02:55 +00:00
void TCPHandler::logProfileInfo(Stopwatch & watch, IBlockInputStream & in)
{
/// Выведем информацию о том, сколько считано строк и байт.
size_t rows = 0;
size_t bytes = 0;
2012-08-23 23:49:28 +00:00
in.getLeafRowsBytes(rows, bytes);
2012-07-21 07:02:55 +00:00
if (rows != 0)
{
LOG_INFO(log, std::fixed << std::setprecision(3)
2012-07-23 06:19:17 +00:00
<< "Read " << rows << " rows, " << bytes / 1048576.0 << " MiB in " << watch.elapsedSeconds() << " sec., "
<< static_cast<size_t>(rows / watch.elapsedSeconds()) << " rows/sec., " << bytes / 1048576.0 / watch.elapsedSeconds() << " MiB/sec.");
2012-05-21 06:49:05 +00:00
}
2013-08-28 20:47:22 +00:00
QuotaForIntervals & quota = query_context.getQuota();
if (!quota.empty())
LOG_INFO(log, "Quota:\n" << quota.toString());
2012-05-21 06:49:05 +00:00
}
void TCPHandler::receiveHello()
2012-05-16 18:03:00 +00:00
{
/// Получить hello пакет.
UInt64 packet_type = 0;
String client_name;
UInt64 client_version_major = 0;
UInt64 client_version_minor = 0;
2013-08-10 09:04:45 +00:00
String user = "default";
String password;
2012-05-16 18:03:00 +00:00
2012-05-21 06:49:05 +00:00
readVarUInt(packet_type, *in);
2012-05-16 18:03:00 +00:00
if (packet_type != Protocol::Client::Hello)
{
/** Если случайно обратились по протоколу HTTP на порт, предназначенный для внутреннего TCP-протокола,
* то вместо номера пакета будет G (GET) или P (POST), в большинстве случаев.
*/
if (packet_type == 'G' || packet_type == 'P')
{
writeString("HTTP/1.0 400 Bad Request\r\n\r\n"
"Port " + server.config().getString("tcp_port") + " is for clickhouse-client program.\r\n"
"You must use port " + server.config().getString("http_port") + " for HTTP"
+ (server.config().getBool("use_olap_http_server", false)
? "\r\n or port " + server.config().getString("olap_http_port") + " for OLAPServer compatibility layer.\r\n"
: ".\r\n"),
*out);
throw Exception("Client has connected to wrong port", ErrorCodes::CLIENT_HAS_CONNECTED_TO_WRONG_PORT);
}
else
throw Exception("Unexpected packet from client", ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT);
}
2012-05-16 18:03:00 +00:00
2012-05-21 06:49:05 +00:00
readStringBinary(client_name, *in);
readVarUInt(client_version_major, *in);
readVarUInt(client_version_minor, *in);
readVarUInt(client_revision, *in);
2012-05-30 06:46:57 +00:00
readStringBinary(default_database, *in);
2012-05-16 18:03:00 +00:00
2013-08-10 09:04:45 +00:00
if (client_revision >= DBMS_MIN_REVISION_WITH_USER_PASSWORD)
{
readStringBinary(user, *in);
readStringBinary(password, *in);
}
2012-05-16 18:20:45 +00:00
LOG_DEBUG(log, "Connected " << client_name
<< " version " << client_version_major
2012-05-16 18:03:00 +00:00
<< "." << client_version_minor
<< "." << client_revision
2012-05-30 06:46:57 +00:00
<< (!default_database.empty() ? ", database: " + default_database : "")
2013-08-10 09:04:45 +00:00
<< (!user.empty() ? ", user: " + user : "")
2013-01-13 21:02:41 +00:00
<< ".");
2013-08-10 09:04:45 +00:00
connection_context.setUser(user, password, socket().peerAddress().host(), "");
2012-05-16 18:03:00 +00:00
}
2012-05-21 06:49:05 +00:00
void TCPHandler::sendHello()
2012-03-11 08:52:56 +00:00
{
2012-05-21 06:49:05 +00:00
writeVarUInt(Protocol::Server::Hello, *out);
writeStringBinary(DBMS_NAME, *out);
writeVarUInt(DBMS_VERSION_MAJOR, *out);
writeVarUInt(DBMS_VERSION_MINOR, *out);
writeVarUInt(Revision::get(), *out);
out->next();
2012-03-11 08:52:56 +00:00
}
2012-05-17 19:15:53 +00:00
2012-05-21 06:49:05 +00:00
bool TCPHandler::receivePacket()
2012-03-11 08:52:56 +00:00
{
UInt64 packet_type = 0;
readVarUInt(packet_type, *in);
2012-03-11 08:52:56 +00:00
// std::cerr << "Packet: " << packet_type << std::endl;
2012-03-19 12:57:56 +00:00
switch (packet_type)
{
case Protocol::Client::Query:
if (!state.empty())
throw Exception("Unexpected packet Query received from client", ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT);
receiveQuery();
return true;
case Protocol::Client::Data:
if (state.empty())
throw Exception("Unexpected packet Data received from client", ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT);
return receiveData();
case Protocol::Client::Ping:
writeVarUInt(Protocol::Server::Pong, *out);
out->next();
return false;
2012-05-17 19:15:53 +00:00
case Protocol::Client::Cancel:
return false;
2012-10-20 06:40:55 +00:00
case Protocol::Client::Hello:
throw Exception("Unexpected packet " + String(Protocol::Client::toString(packet_type)) + " received from client",
ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT);
default:
throw Exception("Unknown packet from client", ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT);
2012-03-09 15:46:52 +00:00
}
}
2012-05-17 19:15:53 +00:00
2012-05-21 06:49:05 +00:00
void TCPHandler::receiveQuery()
2012-03-11 08:52:56 +00:00
{
UInt64 stage = 0;
UInt64 compression = 0;
state.is_empty = false;
if (client_revision < DBMS_MIN_REVISION_WITH_STRING_QUERY_ID)
{
UInt64 query_id_int;
readIntBinary(query_id_int, *in);
state.query_id = "";
2014-02-27 22:57:32 +00:00
}
else
readStringBinary(state.query_id, *in);
query_context.setCurrentQueryId(state.query_id);
2012-03-11 08:52:56 +00:00
/// Настройки на отдельный запрос.
if (client_revision >= DBMS_MIN_REVISION_WITH_PER_QUERY_SETTINGS)
{
query_context.getSettingsRef().deserialize(*in);
}
2012-05-21 06:49:05 +00:00
readVarUInt(stage, *in);
2012-05-09 13:12:38 +00:00
state.stage = QueryProcessingStage::Enum(stage);
2012-03-11 08:52:56 +00:00
2012-05-21 06:49:05 +00:00
readVarUInt(compression, *in);
2012-03-11 08:52:56 +00:00
state.compression = Protocol::Compression::Enum(compression);
2012-05-21 06:49:05 +00:00
readStringBinary(state.query, *in);
2012-03-19 12:57:56 +00:00
LOG_DEBUG(log, "Query ID: " << state.query_id);
LOG_DEBUG(log, "Query: " << state.query);
LOG_DEBUG(log, "Requested stage: " << QueryProcessingStage::toString(stage));
2012-03-11 08:52:56 +00:00
}
2012-05-21 06:49:05 +00:00
bool TCPHandler::receiveData()
{
initBlockInput();
/// Имя временной таблицы для записи данных, по умолчанию пустая строка
String external_table_name;
if (client_revision >= DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES)
readStringBinary(external_table_name, *in);
/// Прочитать из сети один блок и записать его
Block block = state.block_in->read();
if (block)
{
/// Если запрос на вставку, то данные нужно писать напрямую в state.io.out.
/// Иначе пишем блоки во временную таблицу external_table_name.
2014-11-08 23:54:03 +00:00
if (!state.need_receive_data_for_insert)
{
StoragePtr storage;
/// Если такой таблицы не существовало, создаем ее.
if (!(storage = query_context.tryGetExternalTable(external_table_name)))
{
NamesAndTypesListPtr columns = new NamesAndTypesList(block.getColumnsList());
storage = StorageMemory::create(external_table_name, columns);
query_context.addExternalTable(external_table_name, storage);
}
/// Данные будем писать напрямую в таблицу.
state.io.out = storage->write(ASTPtr());
}
if (block)
state.io.out->write(block);
return true;
}
else
return false;
}
void TCPHandler::initBlockInput()
2012-03-11 08:52:56 +00:00
{
2012-03-19 12:57:56 +00:00
if (!state.block_in)
{
2012-05-21 06:49:05 +00:00
if (state.compression == Protocol::Compression::Enable)
state.maybe_compressed_in = new CompressedReadBuffer(*in);
else
state.maybe_compressed_in = in;
2012-03-19 12:57:56 +00:00
state.block_in = new NativeBlockInputStream(
2012-03-19 12:57:56 +00:00
*state.maybe_compressed_in,
query_context.getDataTypeFactory(),
client_revision);
2012-03-19 12:57:56 +00:00
}
}
void TCPHandler::initBlockOutput()
{
if (!state.block_out)
2012-03-19 12:57:56 +00:00
{
if (state.compression == Protocol::Compression::Enable)
state.maybe_compressed_out = new CompressedWriteBuffer(*out);
else
state.maybe_compressed_out = out;
state.block_out = new NativeBlockOutputStream(
*state.maybe_compressed_out,
client_revision);
2012-03-19 12:57:56 +00:00
}
}
2012-03-11 08:52:56 +00:00
2012-05-21 06:49:05 +00:00
bool TCPHandler::isQueryCancelled()
2012-05-09 08:16:09 +00:00
{
2012-05-09 16:55:56 +00:00
if (state.is_cancelled || state.sent_all_data)
2012-05-09 15:50:42 +00:00
return true;
2012-10-20 05:54:35 +00:00
if (after_check_cancelled.elapsed() / 1000 < query_context.getSettingsRef().interactive_delay)
2012-05-09 15:15:45 +00:00
return false;
after_check_cancelled.restart();
2012-10-20 05:54:35 +00:00
2012-05-09 08:16:09 +00:00
/// Во время выполнения запроса, единственный пакет, который может прийти от клиента - это остановка выполнения запроса.
if (static_cast<ReadBufferFromPocoSocket &>(*in).poll(0))
2012-05-09 08:16:09 +00:00
{
UInt64 packet_type = 0;
2012-05-21 06:49:05 +00:00
readVarUInt(packet_type, *in);
2012-05-09 08:16:09 +00:00
switch (packet_type)
{
case Protocol::Client::Cancel:
if (state.empty())
throw Exception("Unexpected packet Cancel received from client", ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT);
LOG_INFO(log, "Query was cancelled.");
2012-05-09 15:50:42 +00:00
state.is_cancelled = true;
2012-05-09 08:16:09 +00:00
return true;
default:
throw Exception("Unknown packet from client", ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT);
}
}
return false;
}
2012-05-21 06:49:05 +00:00
void TCPHandler::sendData(Block & block)
2012-03-19 12:57:56 +00:00
{
initBlockOutput();
2012-03-11 08:52:56 +00:00
2012-05-21 06:49:05 +00:00
writeVarUInt(Protocol::Server::Data, *out);
if (client_revision >= DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES)
writeStringBinary("", *out);
2012-05-21 06:49:05 +00:00
state.block_out->write(block);
state.maybe_compressed_out->next();
out->next();
2012-03-19 12:57:56 +00:00
}
2012-05-21 06:49:05 +00:00
2012-05-30 06:46:57 +00:00
void TCPHandler::sendException(const Exception & e)
2012-03-19 12:57:56 +00:00
{
2012-05-21 06:49:05 +00:00
writeVarUInt(Protocol::Server::Exception, *out);
2012-05-30 06:46:57 +00:00
writeException(e, *out);
2012-05-21 06:49:05 +00:00
out->next();
2012-03-19 12:57:56 +00:00
}
2012-05-21 06:49:05 +00:00
void TCPHandler::sendEndOfStream()
2012-05-08 11:19:00 +00:00
{
2012-07-15 21:43:04 +00:00
state.sent_all_data = true;
2012-05-21 06:49:05 +00:00
writeVarUInt(Protocol::Server::EndOfStream, *out);
out->next();
2012-05-08 11:19:00 +00:00
}
2012-05-21 06:49:05 +00:00
void TCPHandler::updateProgress(const Progress & value)
2012-03-19 12:57:56 +00:00
{
state.progress.incrementPiecewiseAtomically(value);
}
2012-05-09 15:15:45 +00:00
void TCPHandler::sendProgress()
{
2012-05-21 06:49:05 +00:00
writeVarUInt(Protocol::Server::Progress, *out);
Progress increment = state.progress.fetchAndResetPiecewiseAtomically();
increment.write(*out, client_revision);
2012-05-21 06:49:05 +00:00
out->next();
2012-03-11 08:52:56 +00:00
}
2012-03-09 15:46:52 +00:00
void TCPHandler::run()
{
try
{
runImpl();
LOG_INFO(log, "Done processing connection.");
}
catch (Exception & e)
2012-08-02 18:02:57 +00:00
{
LOG_ERROR(log, "Code: " << e.code() << ", e.displayText() = " << e.displayText() << ", e.what() = " << e.what()
2012-08-02 18:02:57 +00:00
<< ", Stack trace:\n\n" << e.getStackTrace().toString());
}
2012-03-09 15:46:52 +00:00
catch (Poco::Exception & e)
{
2012-08-02 18:02:57 +00:00
std::stringstream message;
message << "Poco::Exception. Code: " << ErrorCodes::POCO_EXCEPTION << ", e.code() = " << e.code()
<< ", e.displayText() = " << e.displayText() << ", e.what() = " << e.what();
/// Таймаут - не ошибка.
if (!strcmp(e.what(), "Timeout"))
{
LOG_DEBUG(log, message.rdbuf());
}
else
{
LOG_ERROR(log, message.rdbuf());
}
2012-03-09 15:46:52 +00:00
}
catch (std::exception & e)
{
2012-08-02 18:02:57 +00:00
LOG_ERROR(log, "std::exception. Code: " << ErrorCodes::STD_EXCEPTION << ". " << e.what());
2012-03-09 15:46:52 +00:00
}
catch (...)
{
2012-08-02 18:02:57 +00:00
LOG_ERROR(log, "Unknown exception. Code: " << ErrorCodes::UNKNOWN_EXCEPTION << ".");
2012-03-09 15:46:52 +00:00
}
}
}