ClickHouse/src/Storages/StorageTinyLog.cpp

503 lines
15 KiB
C++
Raw Normal View History

2016-10-25 06:49:24 +00:00
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
2016-10-25 06:49:24 +00:00
2012-06-25 00:17:19 +00:00
#include <map>
2020-09-18 19:25:56 +00:00
#include <cassert>
2015-01-25 05:07:51 +00:00
#include <Poco/Util/XMLConfiguration.h>
2012-06-25 00:17:19 +00:00
#include <Common/escapeForFileName.h>
#include <Common/Exception.h>
2019-12-23 16:57:16 +00:00
#include <Common/typeid_cast.h>
2012-06-25 00:17:19 +00:00
2020-02-14 14:28:33 +00:00
#include <IO/ReadBufferFromFileBase.h>
#include <IO/WriteBufferFromFileBase.h>
2019-12-23 16:57:16 +00:00
#include <Compression/CompressionFactory.h>
2018-12-28 18:15:26 +00:00
#include <Compression/CompressedReadBuffer.h>
#include <Compression/CompressedWriteBuffer.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteHelpers.h>
2012-06-25 00:17:19 +00:00
#include <DataTypes/NestedUtils.h>
2012-08-29 18:49:54 +00:00
#include <DataStreams/IBlockInputStream.h>
#include <DataStreams/IBlockOutputStream.h>
2015-01-18 08:25:56 +00:00
#include <Columns/ColumnArray.h>
2012-08-29 18:49:54 +00:00
#include <Interpreters/Context.h>
2020-02-14 14:28:33 +00:00
#include <Interpreters/evaluateConstantExpression.h>
#include <Parsers/ASTLiteral.h>
2019-07-03 13:17:19 +00:00
#include <Storages/CheckResults.h>
2020-02-14 14:28:33 +00:00
#include <Storages/StorageFactory.h>
#include <Storages/StorageTinyLog.h>
#include "StorageLogSettings.h"
#include <Processors/Sources/SourceWithProgress.h>
#include <Processors/Pipe.h>
2017-07-27 23:23:13 +00:00
#define DBMS_STORAGE_LOG_DATA_FILE_EXTENSION ".bin"
2012-06-25 00:17:19 +00:00
namespace DB
{
namespace ErrorCodes
{
extern const int DUPLICATE_COLUMN;
extern const int INCORRECT_FILE_NAME;
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
}
2012-06-25 00:17:19 +00:00
class TinyLogSource final : public SourceWithProgress
2012-06-25 00:17:19 +00:00
{
2015-01-18 08:25:56 +00:00
public:
static Block getHeader(const NamesAndTypesList & columns)
{
Block res;
for (const auto & name_type : columns)
res.insert({ name_type.type->createColumn(), name_type.type, name_type.name });
return Nested::flatten(res);
}
TinyLogSource(size_t block_size_, const NamesAndTypesList & columns_, StorageTinyLog & storage_, size_t max_read_buffer_size_)
: SourceWithProgress(getHeader(columns_))
, block_size(block_size_), columns(columns_), storage(storage_), lock(storage_.rwlock)
, max_read_buffer_size(max_read_buffer_size_) {}
String getName() const override { return "TinyLog"; }
2015-01-18 08:25:56 +00:00
protected:
Chunk generate() override;
2020-02-18 07:53:16 +00:00
2015-01-18 08:25:56 +00:00
private:
size_t block_size;
NamesAndTypesList columns;
StorageTinyLog & storage;
std::shared_lock<std::shared_mutex> lock;
2020-02-18 07:53:16 +00:00
bool is_finished = false;
size_t max_read_buffer_size;
struct Stream
{
2019-12-23 16:57:16 +00:00
Stream(const DiskPtr & disk, const String & data_path, size_t max_read_buffer_size_)
2019-12-26 14:28:22 +00:00
: plain(disk->readFile(data_path, std::min(max_read_buffer_size_, disk->getFileSize(data_path)))),
compressed(*plain)
{
}
std::unique_ptr<ReadBuffer> plain;
CompressedReadBuffer compressed;
};
using FileStreams = std::map<String, std::unique_ptr<Stream>>;
FileStreams streams;
using DeserializeState = IDataType::DeserializeBinaryBulkStatePtr;
using DeserializeStates = std::map<String, DeserializeState>;
DeserializeStates deserialize_states;
2019-02-10 15:17:45 +00:00
void readData(const String & name, const IDataType & type, IColumn & column, UInt64 limit);
2015-01-18 08:25:56 +00:00
};
class TinyLogBlockOutputStream final : public IBlockOutputStream
2015-01-18 08:25:56 +00:00
{
public:
explicit TinyLogBlockOutputStream(StorageTinyLog & storage_, const StorageMetadataPtr & metadata_snapshot_)
: storage(storage_), metadata_snapshot(metadata_snapshot_), lock(storage_.rwlock)
{
}
~TinyLogBlockOutputStream() override
{
try
{
if (!done)
{
/// Rollback partial writes.
streams.clear();
storage.file_checker.repair();
}
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
Block getHeader() const override { return metadata_snapshot->getSampleBlock(); }
void write(const Block & block) override;
void writeSuffix() override;
2015-04-02 23:58:26 +00:00
2015-01-18 08:25:56 +00:00
private:
StorageTinyLog & storage;
StorageMetadataPtr metadata_snapshot;
std::unique_lock<std::shared_mutex> lock;
bool done = false;
struct Stream
{
Stream(const DiskPtr & disk, const String & data_path, CompressionCodecPtr codec, size_t max_compress_block_size) :
2019-12-26 14:28:22 +00:00
plain(disk->writeFile(data_path, max_compress_block_size, WriteMode::Append)),
compressed(*plain, std::move(codec), max_compress_block_size)
{
}
std::unique_ptr<WriteBuffer> plain;
CompressedWriteBuffer compressed;
void finalize()
{
compressed.next();
2020-01-10 21:42:26 +00:00
plain->finalize();
}
};
using FileStreams = std::map<String, std::unique_ptr<Stream>>;
FileStreams streams;
using SerializeState = IDataType::SerializeBinaryBulkStatePtr;
using SerializeStates = std::map<String, SerializeState>;
SerializeStates serialize_states;
using WrittenStreams = std::set<String>;
IDataType::OutputStreamGetter createStreamGetter(const String & name, WrittenStreams & written_streams);
void writeData(const String & name, const IDataType & type, const IColumn & column, WrittenStreams & written_streams);
2015-01-18 08:25:56 +00:00
};
2012-06-25 00:17:19 +00:00
Chunk TinyLogSource::generate()
2012-06-25 00:17:19 +00:00
{
Block res;
2020-02-18 07:53:16 +00:00
if (is_finished || (!streams.empty() && streams.begin()->second->compressed.eof()))
{
/** Close the files (before destroying the object).
* When many sources are created, but simultaneously reading only a few of them,
* buffers don't waste memory.
*/
2020-02-18 07:53:16 +00:00
is_finished = true;
streams.clear();
return {};
}
2019-12-31 00:41:03 +00:00
/// if there are no files in the folder, it means that the table is empty
if (storage.disk->isDirectoryEmpty(storage.table_path))
return {};
for (const auto & name_type : columns)
{
MutableColumnPtr column = name_type.type->createColumn();
try
{
readData(name_type.name, *name_type.type, *column, block_size);
}
catch (Exception & e)
{
e.addMessage("while reading column " + name_type.name + " at " + fullPath(storage.disk, storage.table_path));
throw;
}
if (!column->empty())
res.insert(ColumnWithTypeAndName(std::move(column), name_type.type, name_type.name));
}
if (!res || streams.begin()->second->compressed.eof())
{
2020-02-18 07:53:16 +00:00
is_finished = true;
streams.clear();
}
auto flatten = Nested::flatten(res);
return Chunk(flatten.getColumns(), flatten.rows());
2012-06-25 00:17:19 +00:00
}
void TinyLogSource::readData(const String & name, const IDataType & type, IColumn & column, UInt64 limit)
2012-08-29 18:49:54 +00:00
{
IDataType::DeserializeBinaryBulkSettings settings; /// TODO Use avg_value_size_hint.
settings.getter = [&] (const IDataType::SubstreamPath & path) -> ReadBuffer *
{
String stream_name = IDataType::getFileNameForStream(name, path);
if (!streams.count(stream_name))
streams[stream_name] = std::make_unique<Stream>(storage.disk, storage.files[stream_name].data_file_path, max_read_buffer_size);
return &streams[stream_name]->compressed;
};
if (deserialize_states.count(name) == 0)
type.deserializeBinaryBulkStatePrefix(settings, deserialize_states[name]);
type.deserializeBinaryBulkWithMultipleStreams(column, limit, settings, deserialize_states[name]);
2012-08-29 18:49:54 +00:00
}
IDataType::OutputStreamGetter TinyLogBlockOutputStream::createStreamGetter(
const String & name,
WrittenStreams & written_streams)
2012-08-29 18:49:54 +00:00
{
return [&] (const IDataType::SubstreamPath & path) -> WriteBuffer *
{
String stream_name = IDataType::getFileNameForStream(name, path);
if (!written_streams.insert(stream_name).second)
return nullptr;
const auto & columns = metadata_snapshot->getColumns();
if (!streams.count(stream_name))
streams[stream_name] = std::make_unique<Stream>(
storage.disk,
storage.files[stream_name].data_file_path,
columns.getCodecOrDefault(name),
storage.max_compress_block_size);
return &streams[stream_name]->compressed;
};
}
void TinyLogBlockOutputStream::writeData(const String & name, const IDataType & type, const IColumn & column, WrittenStreams & written_streams)
{
IDataType::SerializeBinaryBulkSettings settings;
settings.getter = createStreamGetter(name, written_streams);
if (serialize_states.count(name) == 0)
type.serializeBinaryBulkStatePrefix(settings, serialize_states[name]);
type.serializeBinaryBulkWithMultipleStreams(column, 0, 0, settings, serialize_states[name]);
2012-06-25 00:17:19 +00:00
}
2013-09-15 01:40:29 +00:00
void TinyLogBlockOutputStream::writeSuffix()
{
if (done)
return;
2015-04-02 23:58:26 +00:00
/// If nothing was written - leave the table in initial state.
if (streams.empty())
{
done = true;
return;
}
WrittenStreams written_streams;
IDataType::SerializeBinaryBulkSettings settings;
for (const auto & column : getHeader())
{
auto it = serialize_states.find(column.name);
if (it != serialize_states.end())
{
settings.getter = createStreamGetter(column.name, written_streams);
column.type->serializeBinaryBulkStateSuffix(settings, it->second);
}
}
/// Finish write.
2017-12-11 18:19:35 +00:00
for (auto & stream : streams)
stream.second->finalize();
Strings column_files;
for (auto & pair : streams)
column_files.push_back(storage.files[pair.first].data_file_path);
for (const auto & file : column_files)
storage.file_checker.update(file);
storage.file_checker.save();
2013-09-15 01:40:29 +00:00
streams.clear();
done = true;
2013-09-15 01:40:29 +00:00
}
2012-06-25 00:17:19 +00:00
void TinyLogBlockOutputStream::write(const Block & block)
{
2020-06-17 14:32:25 +00:00
metadata_snapshot->check(block, true);
/// The set of written offset columns so that you do not write shared columns for nested structures multiple times
WrittenStreams written_streams;
2012-06-25 00:17:19 +00:00
for (size_t i = 0; i < block.columns(); ++i)
{
const ColumnWithTypeAndName & column = block.safeGetByPosition(i);
writeData(column.name, *column.type, *column.column, written_streams);
}
2012-06-25 00:17:19 +00:00
}
StorageTinyLog::StorageTinyLog(
DiskPtr disk_,
const String & relative_path_,
2019-12-04 16:06:55 +00:00
const StorageID & table_id_,
const ColumnsDescription & columns_,
2019-08-24 21:20:20 +00:00
const ConstraintsDescription & constraints_,
bool attach,
size_t max_compress_block_size_)
2019-12-04 16:06:55 +00:00
: IStorage(table_id_)
, disk(std::move(disk_))
, table_path(relative_path_)
2019-12-04 16:06:55 +00:00
, max_compress_block_size(max_compress_block_size_)
, file_checker(disk, table_path + "sizes.json")
2020-05-30 21:57:37 +00:00
, log(&Poco::Logger::get("StorageTinyLog"))
2012-06-25 00:17:19 +00:00
{
2020-06-19 15:39:41 +00:00
StorageInMemoryMetadata storage_metadata;
storage_metadata.setColumns(columns_);
storage_metadata.setConstraints(constraints_);
setInMemoryMetadata(storage_metadata);
2019-08-24 21:20:20 +00:00
2019-10-25 19:07:47 +00:00
if (relative_path_.empty())
throw Exception("Storage " + getName() + " requires data path", ErrorCodes::INCORRECT_FILE_NAME);
if (!attach)
{
/// create directories if they do not exist
disk->createDirectories(table_path);
}
else
{
try
{
file_checker.repair();
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
2020-06-19 15:39:41 +00:00
for (const auto & col : storage_metadata.getColumns().getAllPhysical())
addFiles(col.name, *col.type);
if (!attach)
for (const auto & file : files)
file_checker.setEmpty(file.second.data_file_path);
2012-08-29 18:49:54 +00:00
}
void StorageTinyLog::addFiles(const String & column_name, const IDataType & type)
2012-08-29 18:49:54 +00:00
{
if (files.end() != files.find(column_name))
throw Exception("Duplicate column with name " + column_name + " in constructor of StorageTinyLog.",
ErrorCodes::DUPLICATE_COLUMN);
2020-09-18 11:37:58 +00:00
IDataType::StreamCallback stream_callback = [&] (const IDataType::SubstreamPath & substream_path, const IDataType & /* substream_type */)
{
String stream_name = IDataType::getFileNameForStream(column_name, substream_path);
if (!files.count(stream_name))
{
ColumnData column_data;
files.insert(std::make_pair(stream_name, column_data));
files[stream_name].data_file_path = table_path + stream_name + DBMS_STORAGE_LOG_DATA_FILE_EXTENSION;
}
};
IDataType::SubstreamPath substream_path;
type.enumerateStreams(stream_callback, substream_path);
2012-06-25 00:17:19 +00:00
}
2020-04-07 14:05:51 +00:00
void StorageTinyLog::rename(const String & new_path_to_table_data, const StorageID & new_table_id)
2012-06-25 00:17:19 +00:00
{
2020-09-18 19:25:56 +00:00
assert(table_path != new_path_to_table_data);
{
std::unique_lock<std::shared_mutex> lock(rwlock);
disk->moveDirectory(table_path, new_path_to_table_data);
table_path = new_path_to_table_data;
file_checker.setPath(table_path + "sizes.json");
2012-06-25 00:17:19 +00:00
for (auto & file : files)
file.second.data_file_path = table_path + fileName(file.second.data_file_path);
}
2020-04-07 14:05:51 +00:00
renameInMemory(new_table_id);
2012-06-25 00:17:19 +00:00
}
2020-08-03 13:54:14 +00:00
Pipe StorageTinyLog::read(
const Names & column_names,
const StorageMetadataPtr & metadata_snapshot,
SelectQueryInfo & /*query_info*/,
const Context & context,
QueryProcessingStage::Enum /*processed_stage*/,
const size_t max_block_size,
2017-12-01 21:13:25 +00:00
const unsigned /*num_streams*/)
2012-06-25 00:17:19 +00:00
{
2020-06-19 17:17:13 +00:00
metadata_snapshot->check(column_names, getVirtuals(), getStorageID());
2020-04-05 23:57:24 +00:00
// When reading, we lock the entire storage, because we only have one file
// per column and can't modify it concurrently.
2020-08-03 13:54:14 +00:00
return Pipe(std::make_shared<TinyLogSource>(
max_block_size, Nested::collect(metadata_snapshot->getColumns().getAllPhysical().addTypes(column_names)), *this, context.getSettingsRef().max_read_buffer_size));
2012-06-25 00:17:19 +00:00
}
BlockOutputStreamPtr StorageTinyLog::write(const ASTPtr & /*query*/, const StorageMetadataPtr & metadata_snapshot, const Context & /*context*/)
2012-06-25 00:17:19 +00:00
{
return std::make_shared<TinyLogBlockOutputStream>(*this, metadata_snapshot);
2012-06-25 00:17:19 +00:00
}
2019-07-03 13:17:19 +00:00
CheckResults StorageTinyLog::checkData(const ASTPtr & /* query */, const Context & /* context */)
{
std::shared_lock<std::shared_mutex> lock(rwlock);
return file_checker.check();
}
2020-06-18 10:29:13 +00:00
void StorageTinyLog::truncate(
2020-06-18 16:10:47 +00:00
const ASTPtr &, const StorageMetadataPtr & metadata_snapshot, const Context &, TableExclusiveLockHolder &)
2018-04-21 00:35:20 +00:00
{
std::unique_lock<std::shared_mutex> lock(rwlock);
disk->clearDirectory(table_path);
2018-04-21 00:35:20 +00:00
2018-06-09 15:48:22 +00:00
files.clear();
file_checker = FileChecker{disk, table_path + "sizes.json"};
2018-04-21 00:35:20 +00:00
for (const auto & column : metadata_snapshot->getColumns().getAllPhysical())
2018-04-21 00:35:20 +00:00
addFiles(column.name, *column.type);
}
2020-01-22 11:30:11 +00:00
void StorageTinyLog::drop()
{
std::unique_lock<std::shared_mutex> lock(rwlock);
2020-01-22 11:30:11 +00:00
if (disk->exists(table_path))
disk->removeRecursive(table_path);
files.clear();
}
void registerStorageTinyLog(StorageFactory & factory)
{
StorageFactory::StorageFeatures features{
.supports_settings = true
};
factory.registerStorage("TinyLog", [](const StorageFactory::Arguments & args)
{
if (!args.engine_args.empty())
throw Exception(
"Engine " + args.engine_name + " doesn't support any arguments (" + toString(args.engine_args.size()) + " given)",
ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
String disk_name = getDiskName(*args.storage_def);
DiskPtr disk = args.context.getDisk(disk_name);
2020-02-14 14:28:33 +00:00
return StorageTinyLog::create(
2020-02-14 14:28:33 +00:00
disk, args.relative_data_path, args.table_id, args.columns, args.constraints,
args.attach, args.context.getSettings().max_compress_block_size);
}, features);
}
2012-06-25 00:17:19 +00:00
}