StorageReplicatedMergeTree.cpp 130.5 KB
Newer Older
1 2 3
#include <zkutil/Types.h>
#include <zkutil/KeeperException.h>

4
#include <DB/Core/FieldVisitors.h>
5

6
#include <DB/Storages/ColumnsDescription.h>
M
Merge  
Michael Kolupaev 已提交
7
#include <DB/Storages/StorageReplicatedMergeTree.h>
M
Merge  
Michael Kolupaev 已提交
8
#include <DB/Storages/MergeTree/ReplicatedMergeTreeBlockOutputStream.h>
9
#include <DB/Storages/MergeTree/ReplicatedMergeTreeQuorumEntry.h>
10
#include <DB/Storages/MergeTree/MergeList.h>
A
Merge  
Andrey Mironov 已提交
11
#include <DB/Storages/MergeTree/MergeTreeWhereOptimizer.h>
12
#include <DB/Storages/MergeTree/ReplicatedMergeTreeAddress.h>
A
Merge  
Alexey Milovidov 已提交
13
#include <DB/Storages/MergeTree/ReshardingWorker.h>
14

15 16
#include <DB/Databases/IDatabase.h>

M
Merge  
Michael Kolupaev 已提交
17
#include <DB/Parsers/formatAST.h>
18
#include <DB/Parsers/ASTInsertQuery.h>
19
#include <DB/Parsers/ASTSelectQuery.h>
A
Alexey Milovidov 已提交
20
#include <DB/Parsers/queryToString.h>
21

M
Merge  
Michael Kolupaev 已提交
22
#include <DB/IO/ReadBufferFromString.h>
23
#include <DB/IO/Operators.h>
24

M
Merge  
Michael Kolupaev 已提交
25
#include <DB/Interpreters/InterpreterAlterQuery.h>
26
#include <DB/Interpreters/PartLog.h>
27

28
#include <DB/DataStreams/AddingConstColumnBlockInputStream.h>
29 30 31
#include <DB/DataStreams/RemoteBlockInputStream.h>
#include <DB/DataStreams/NullBlockOutputStream.h>
#include <DB/DataStreams/copyData.h>
32

33
#include <DB/Common/Macros.h>
34
#include <DB/Common/VirtualColumnUtils.h>
A
Merge  
Alexey Milovidov 已提交
35
#include <DB/Common/formatReadable.h>
36
#include <DB/Common/setThreadName.h>
37
#include <DB/Common/escapeForFileName.h>
38
#include <DB/Common/StringUtils.h>
39

40
#include <Poco/DirectoryIterator.h>
M
Merge  
Michael Kolupaev 已提交
41

42
#include <DB/Common/ThreadPool.h>
A
Merge  
Alexey Milovidov 已提交
43 44

#include <ext/range.hpp>
A
Alexey Milovidov 已提交
45 46
#include <ext/scope_guard.hpp>

A
Merge  
Alexey Milovidov 已提交
47 48 49 50 51 52
#include <cfenv>
#include <ctime>
#include <thread>
#include <future>


53 54 55 56 57 58 59 60
namespace ProfileEvents
{
	extern const Event ReplicatedPartMerges;
	extern const Event ReplicatedPartFailedFetches;
	extern const Event ReplicatedPartFetchesOfMerged;
	extern const Event ObsoleteReplicatedParts;
	extern const Event ReplicatedPartFetches;
}
61

M
Merge  
Michael Kolupaev 已提交
62 63 64
namespace DB
{

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
namespace ErrorCodes
{
	extern const int NO_ZOOKEEPER;
	extern const int INCORRECT_DATA;
	extern const int INCOMPATIBLE_COLUMNS;
	extern const int REPLICA_IS_ALREADY_EXIST;
	extern const int NO_SUCH_REPLICA;
	extern const int NO_REPLICA_HAS_PART;
	extern const int LOGICAL_ERROR;
	extern const int TOO_MANY_UNEXPECTED_DATA_PARTS;
	extern const int ABORTED;
	extern const int REPLICA_IS_NOT_IN_QUORUM;
	extern const int TABLE_IS_READ_ONLY;
	extern const int NOT_FOUND_NODE;
	extern const int NO_ACTIVE_REPLICAS;
	extern const int LEADERSHIP_CHANGED;
	extern const int TABLE_IS_READ_ONLY;
	extern const int TABLE_WAS_NOT_DROPPED;
	extern const int PARTITION_ALREADY_EXISTS;
	extern const int TOO_MUCH_RETRIES_TO_FETCH_PARTS;
	extern const int RECEIVED_ERROR_FROM_REMOTE_IO_SERVER;
	extern const int PARTITION_DOESNT_EXIST;
A
Merge  
Alexey Milovidov 已提交
87 88 89 90 91 92
	extern const int INCONSISTENT_TABLE_ACCROSS_SHARDS;
	extern const int INSUFFICIENT_SPACE_FOR_RESHARDING;
	extern const int RESHARDING_NO_WORKER;
	extern const int INVALID_PARTITIONS_INTERVAL;
	extern const int RESHARDING_INVALID_PARAMETERS;
	extern const int INVALID_SHARD_WEIGHT;
A
Merge  
Alexey Arno 已提交
93
	extern const int DUPLICATE_SHARD_PATHS;
94
	extern const int RESHARDING_COORDINATOR_DELETED;
A
Merge  
Alexey Arno 已提交
95 96 97 98
	extern const int RESHARDING_NO_SUCH_COORDINATOR;
	extern const int RESHARDING_NO_COORDINATOR_MEMBERSHIP;
	extern const int RESHARDING_ALREADY_SUBSCRIBED;
	extern const int RESHARDING_INVALID_QUERY;
99
	extern const int RWLOCK_NO_SUCH_LOCK;
A
Merge  
Alexey Arno 已提交
100
	extern const int NO_SUCH_BARRIER;
101 102
	extern const int CHECKSUM_DOESNT_MATCH;
	extern const int BAD_SIZE_OF_FILE_IN_DATA_PART;
103
	extern const int UNFINISHED;
104
	extern const int METADATA_MISMATCH;
105
	extern const int RESHARDING_NULLABLE_SHARDING_KEY;
106 107
}

M
Merge  
Michael Kolupaev 已提交
108

A
Merge  
Alexey Milovidov 已提交
109 110
static const auto QUEUE_UPDATE_ERROR_SLEEP_MS 	= 1 * 1000;
static const auto MERGE_SELECTING_SLEEP_MS		= 5 * 1000;
M
Merge  
Michael Kolupaev 已提交
111

F
f1yegor 已提交
112 113 114 115 116 117
/** Some data numbers are assigned to the data blocks that are integers.
  * For blocks added in the usual way (INSERT), numbers are allocated in ascending order.
  * Merges are made for the range of block numbers on a numeric line
  *  if the block numbers `x`, `z` are involved in the merge, and there is a block with the number `y` that `x < y < z`, then the block with the number `y` is also involved in the merge.
  * This is required to save the properties of some operations that can be performed during a merge - for example, in CollapsingMergeTree.
  * In particular, this allows during the merge to know that in one part all the data was added earlier than all the data in the other part.
118
  *
F
f1yegor 已提交
119 120 121 122 123 124
  * Occasionally there is a need to add to the table some obviously old part of data,
  *  so that it is perceived as old in the logic of CollapsingMergeTree.
  * You can add such a part of data with a special ATTACH request.
  * And in this case, we need to allocate to this part numbers smaller than the numbers of all the other parts.
  * In this regard, the numbers of the regular parts added by INSERT do not start from zero, but from a larger number,
  *  and smaller numbers are considered "reserved".
125
  *
F
f1yegor 已提交
126 127 128 129 130 131
  * Why is this number 200?
  * The fact is that previously negative block numbers were not supported.
  * And also, the merge is done that way so that when you increase the number of parts, insertion of new parts slows down on purpose,
  *  until mergers have time to reduce the number of parts; and it was calculated for about 200 pieces.
  * So, when you insert all the parts from the other table into the table, 200 numbers are sure enough.
  * In turn, this number is chosen almost at random.
132
  */
133
extern const Int64 RESERVED_BLOCK_NUMBERS = 200;
M
Merge  
Michael Kolupaev 已提交
134

M
Merge  
Michael Kolupaev 已提交
135

F
f1yegor 已提交
136 137 138 139
/** There are three places for each part, where it should be
  * 1. In the RAM, MergeTreeData::data_parts, all_data_parts.
  * 2. In the file system (FS), the directory with the data of the table.
  * 3. in ZooKeeper (ZK).
140
  *
F
f1yegor 已提交
141 142 143 144 145 146 147 148 149 150
  * When adding a part, it must be added immediately to these three places.
  * This is done like this
  * - [FS] first write the part into a temporary directory on the file system;
  * - [FS] rename the temporary part to the result on the file system;
  * - [RAM] immediately afterwards add it to the `data_parts`, and remove from `data_parts` any parts covered by this one;
  * - [RAM] also set the `Transaction` object, which in case of an exception (in next point),
  *   rolls back the changes in `data_parts` (from the previous point) back;
  * - [ZK] then send a transaction (multi) to add a part to ZooKeeper (and some more actions);
  * - [FS, ZK] by the way, removing the covered (old) parts from file system, from ZooKeeper and from `all_data_parts`
  *   is delayed, after a few minutes.
151
  *
F
f1yegor 已提交
152 153 154
  * There is no atomicity here.
  * It could be possible to achieve atomicity using undo/redo logs and a flag in `DataPart` when it is completely ready.
  * But it would be inconvenient - I would have to write undo/redo logs for each `Part` in ZK, and this would increase already large number of interactions.
155
  *
F
f1yegor 已提交
156 157 158 159 160
  * Instead, we are forced to work in a situation where at any time
  *  (from another thread, or after server restart), there may be an unfinished transaction.
  *  (note - for this the part should be in RAM)
  * From these cases the most frequent one is when the part is already in the data_parts, but it's not yet in ZooKeeper.
  * This case must be distinguished from the case where such a situation is achieved due to some kind of damage to the state.
161
  *
F
f1yegor 已提交
162 163 164 165
  * Do this with the threshold for the time.
  * If the part is young enough, its lack in ZooKeeper will be perceived optimistically - as if it just did not have time to be added there
  *  - as if the transaction has not yet been executed, but will soon be executed.
  * And if the part is old, its absence in ZooKeeper will be perceived as an unfinished transaction that needs to be rolled back.
166
  *
F
f1yegor 已提交
167 168
  * PS. Perhaps it would be better to add a flag to the DataPart that a part is inserted into ZK.
  * But here it's too easy to get confused with the consistency of this flag.
169
  */
170
extern const int MAX_AGE_OF_LOCAL_PART_THAT_WASNT_ADDED_TO_ZOOKEEPER = 5 * 60;
171 172


A
Merge  
Alexey Milovidov 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
void StorageReplicatedMergeTree::setZooKeeper(zkutil::ZooKeeperPtr zookeeper)
{
	std::lock_guard<std::mutex> lock(current_zookeeper_mutex);
	current_zookeeper = zookeeper;
}

zkutil::ZooKeeperPtr StorageReplicatedMergeTree::tryGetZooKeeper()
{
	std::lock_guard<std::mutex> lock(current_zookeeper_mutex);
	return current_zookeeper;
}

zkutil::ZooKeeperPtr StorageReplicatedMergeTree::getZooKeeper()
{
	auto res = tryGetZooKeeper();
	if (!res)
		throw Exception("Cannot get ZooKeeper", ErrorCodes::NO_ZOOKEEPER);
	return res;
}


M
Merge  
Michael Kolupaev 已提交
194 195 196
StorageReplicatedMergeTree::StorageReplicatedMergeTree(
	const String & zookeeper_path_,
	const String & replica_name_,
M
Merge  
Michael Kolupaev 已提交
197
	bool attach,
M
Merge  
Michael Kolupaev 已提交
198 199
	const String & path_, const String & database_name_, const String & name_,
	NamesAndTypesListPtr columns_,
200
	const NamesAndTypesList & materialized_columns_,
201 202
	const NamesAndTypesList & alias_columns_,
	const ColumnDefaults & column_defaults_,
M
Merge  
Michael Kolupaev 已提交
203
	Context & context_,
M
Merge  
Michael Kolupaev 已提交
204 205 206 207
	ASTPtr & primary_expr_ast_,
	const String & date_column_name_,
	const ASTPtr & sampling_expression_,
	size_t index_granularity_,
A
Alexey Milovidov 已提交
208
	const MergeTreeData::MergingParams & merging_params_,
209
	bool has_force_restore_data_flag,
M
Merge  
Michael Kolupaev 已提交
210
	const MergeTreeSettings & settings_)
211
	: IStorage{materialized_columns_, alias_columns_, column_defaults_}, context(context_),
A
Merge  
Alexey Milovidov 已提交
212
	current_zookeeper(context.getZooKeeper()), database_name(database_name_),
M
Merge  
Michael Kolupaev 已提交
213 214 215
	table_name(name_), full_path(path_ + escapeForFileName(table_name) + '/'),
	zookeeper_path(context.getMacros().expand(zookeeper_path_)),
	replica_name(context.getMacros().expand(replica_name_)),
216 217
	data(database_name, table_name,
		full_path, columns_,
218 219
		materialized_columns_, alias_columns_, column_defaults_,
		context_, primary_expr_ast_, date_column_name_,
A
Merge  
Alexey Milovidov 已提交
220
		sampling_expression_, index_granularity_, merging_params_,
221
		settings_, database_name_ + "." + table_name, true, attach,
222
		[this] (const std::string & name) { enqueuePartForCheck(name); }),
223
	reader(data), writer(data, context), merger(data, context.getBackgroundPool()), fetcher(data), sharded_partition_uploader_client(*this),
224 225
	shutdown_event(false), part_check_thread(*this),
	log(&Logger::get(database_name + "." + table_name + " (StorageReplicatedMergeTree)"))
M
Merge  
Michael Kolupaev 已提交
226
{
227 228
	if (!zookeeper_path.empty() && zookeeper_path.back() == '/')
		zookeeper_path.resize(zookeeper_path.size() - 1);
M
Merge  
Michael Kolupaev 已提交
229 230 231 232
	replica_path = zookeeper_path + "/replicas/" + replica_name;

	bool skip_sanity_checks = false;

233
	try
M
Merge  
Michael Kolupaev 已提交
234
	{
A
Merge  
Alexey Milovidov 已提交
235
		if (current_zookeeper && current_zookeeper->exists(replica_path + "/flags/force_restore_data"))
236 237
		{
			skip_sanity_checks = true;
A
Merge  
Alexey Milovidov 已提交
238
			current_zookeeper->remove(replica_path + "/flags/force_restore_data");
M
Merge  
Michael Kolupaev 已提交
239

240 241 242
			LOG_WARNING(log, "Skipping the limits on severity of changes to data parts and columns (flag "
				<< replica_path << "/flags/force_restore_data).");
		}
243 244 245 246 247 248
		else if (has_force_restore_data_flag)
		{
			skip_sanity_checks = true;

			LOG_WARNING(log, "Skipping the limits on severity of changes to data parts and columns (flag force_restore_data).");
		}
249 250 251
	}
	catch (const zkutil::KeeperException & e)
	{
F
f1yegor 已提交
252
		/// Failed to connect to ZK (this became known when trying to perform the first operation).
253 254 255
		if (e.code == ZCONNECTIONLOSS)
		{
			tryLogCurrentException(__PRETTY_FUNCTION__);
A
Merge  
Alexey Milovidov 已提交
256
			current_zookeeper = nullptr;
257 258 259
		}
		else
			throw;
M
Merge  
Michael Kolupaev 已提交
260 261 262 263
	}

	data.loadDataParts(skip_sanity_checks);

A
Merge  
Alexey Milovidov 已提交
264
	if (!current_zookeeper)
M
Merge  
Michael Kolupaev 已提交
265
	{
M
Merge  
Michael Kolupaev 已提交
266 267 268
		if (!attach)
			throw Exception("Can't create replicated table without ZooKeeper", ErrorCodes::NO_ZOOKEEPER);

A
Alexey Milovidov 已提交
269
		/// Do not activate the replica. It will be readonly.
A
Merge  
Alexey Milovidov 已提交
270 271
		LOG_ERROR(log, "No ZooKeeper: table will be in readonly mode.");
		is_readonly = true;
M
Merge  
Michael Kolupaev 已提交
272 273 274
		return;
	}

M
Merge  
Michael Kolupaev 已提交
275 276
	if (!attach)
	{
A
Merge  
Alexey Milovidov 已提交
277 278 279
		if (!data.getDataParts().empty())
			throw Exception("Data directory for table already containing data parts - probably it was unclean DROP table or manual intervention. You must either clear directory by hand or use ATTACH TABLE instead of CREATE TABLE if you need to use that parts.", ErrorCodes::INCORRECT_DATA);

M
Merge  
Michael Kolupaev 已提交
280
		createTableIfNotExists();
M
Merge  
Michael Kolupaev 已提交
281

M
Merge  
Michael Kolupaev 已提交
282
		checkTableStructure(false, false);
M
Merge  
Michael Kolupaev 已提交
283
		createReplica();
M
Merge  
Michael Kolupaev 已提交
284 285 286
	}
	else
	{
M
Merge  
Michael Kolupaev 已提交
287
		checkTableStructure(skip_sanity_checks, true);
M
Merge  
Michael Kolupaev 已提交
288
		checkParts(skip_sanity_checks);
M
Merge  
Michael Kolupaev 已提交
289
	}
M
Merge  
Michael Kolupaev 已提交
290

291 292
	createNewZooKeeperNodes();

M
Merge  
Michael Kolupaev 已提交
293 294 295
	String unreplicated_path = full_path + "unreplicated/";
	if (Poco::File(unreplicated_path).exists())
	{
296 297 298
		unreplicated_data = std::make_unique<MergeTreeData>(
			database_name, table_name,
			unreplicated_path, columns_,
299
			materialized_columns_, alias_columns_, column_defaults_,
300
			context_, primary_expr_ast_,
A
Merge  
Alexey Milovidov 已提交
301
			date_column_name_, sampling_expression_, index_granularity_, merging_params_, settings_,
302
			database_name_ + "." + table_name + "[unreplicated]", /* require_part_metadata = */ false, /* attach = */ true);
303 304 305

		unreplicated_data->loadDataParts(skip_sanity_checks);

306 307 308 309 310 311 312
		if (unreplicated_data->getDataPartsVector().empty())
		{
			unreplicated_data.reset();
		}
		else
		{
			LOG_INFO(log, "Have unreplicated data");
313
			unreplicated_reader = std::make_unique<MergeTreeDataSelectExecutor>(*unreplicated_data);
P
proller 已提交
314
			unreplicated_merger = std::make_unique<MergeTreeDataMerger>(*unreplicated_data, context.getBackgroundPool());
315
		}
M
Merge  
Michael Kolupaev 已提交
316
	}
M
Merge  
Michael Kolupaev 已提交
317

A
Alexey Milovidov 已提交
318 319 320 321
	queue.initialize(
		zookeeper_path, replica_path,
		database_name + "." + table_name + " (ReplicatedMergeTreeQueue)",
		data.getDataParts(), current_zookeeper);
M
Merge  
Michael Kolupaev 已提交
322

323 324
	queue.pullLogsToQueue(current_zookeeper, nullptr);

A
Alexey Milovidov 已提交
325
	/// In this thread replica will be activated.
326
	restarting_thread = std::make_unique<ReplicatedMergeTreeRestartingThread>(*this);
M
Merge  
Michael Kolupaev 已提交
327 328
}

329

330 331 332 333
void StorageReplicatedMergeTree::createNewZooKeeperNodes()
{
	auto zookeeper = getZooKeeper();

A
Alexey Milovidov 已提交
334
	/// Working with quorum.
335 336 337 338
	zookeeper->createIfNotExists(zookeeper_path + "/quorum", "");
	zookeeper->createIfNotExists(zookeeper_path + "/quorum/last_part", "");
	zookeeper->createIfNotExists(zookeeper_path + "/quorum/failed_parts", "");

A
Alexey Milovidov 已提交
339
	/// Tracking lag of replicas.
340
	zookeeper->createIfNotExists(replica_path + "/min_unprocessed_insert_time", "");
341
	zookeeper->createIfNotExists(replica_path + "/max_processed_insert_time", "");
342 343 344
}


M
Merge  
Michael Kolupaev 已提交
345 346 347
StoragePtr StorageReplicatedMergeTree::create(
	const String & zookeeper_path_,
	const String & replica_name_,
M
Merge  
Michael Kolupaev 已提交
348
	bool attach,
M
Merge  
Michael Kolupaev 已提交
349 350
	const String & path_, const String & database_name_, const String & name_,
	NamesAndTypesListPtr columns_,
351
	const NamesAndTypesList & materialized_columns_,
352 353
	const NamesAndTypesList & alias_columns_,
	const ColumnDefaults & column_defaults_,
M
Merge  
Michael Kolupaev 已提交
354
	Context & context_,
M
Merge  
Michael Kolupaev 已提交
355 356 357 358
	ASTPtr & primary_expr_ast_,
	const String & date_column_name_,
	const ASTPtr & sampling_expression_,
	size_t index_granularity_,
A
Alexey Milovidov 已提交
359
	const MergeTreeData::MergingParams & merging_params_,
360
	bool has_force_restore_data_flag_,
M
Merge  
Michael Kolupaev 已提交
361 362
	const MergeTreeSettings & settings_)
{
363
	auto res = make_shared(
364 365
		zookeeper_path_, replica_name_, attach,
		path_, database_name_, name_,
366
		columns_, materialized_columns_, alias_columns_, column_defaults_,
367
		context_, primary_expr_ast_, date_column_name_,
A
Merge  
Alexey Milovidov 已提交
368
		sampling_expression_, index_granularity_,
369 370
		merging_params_, has_force_restore_data_flag_, settings_);
	StoragePtr res_ptr = res;
371

A
Merge  
Alexey Milovidov 已提交
372 373
	auto get_endpoint_holder = [&res](InterserverIOEndpointPtr endpoint)
	{
374
		return std::make_shared<InterserverIOEndpointHolder>(
375 376 377
			endpoint->getId(res->replica_path),
			endpoint,
			res->context.getInterserverIOHandler());
A
Merge  
Alexey Milovidov 已提交
378 379
	};

380
	if (res->tryGetZooKeeper())
M
Merge  
Michael Kolupaev 已提交
381
	{
A
Merge  
Alexey Milovidov 已提交
382
		{
383
			InterserverIOEndpointPtr endpoint = std::make_shared<DataPartsExchange::Service>(res->data, res_ptr);
A
Merge  
Alexey Milovidov 已提交
384 385 386
			res->endpoint_holder = get_endpoint_holder(endpoint);
		}

A
Alexey Milovidov 已提交
387
		/// Services for resharding.
A
Merge  
Alexey Milovidov 已提交
388 389

		{
390
			InterserverIOEndpointPtr endpoint = std::make_shared<RemoteDiskSpaceMonitor::Service>(res->context);
A
Merge  
Alexey Milovidov 已提交
391 392 393 394
			res->disk_space_monitor_endpoint_holder = get_endpoint_holder(endpoint);
		}

		{
395
			InterserverIOEndpointPtr endpoint = std::make_shared<ShardedPartitionUploader::Service>(res_ptr);
A
Merge  
Alexey Arno 已提交
396
			res->sharded_partition_uploader_endpoint_holder = get_endpoint_holder(endpoint);
A
Merge  
Alexey Milovidov 已提交
397 398 399
		}

		{
400
			InterserverIOEndpointPtr endpoint = std::make_shared<RemoteQueryExecutor::Service>(res->context);
A
Merge  
Alexey Milovidov 已提交
401 402
			res->remote_query_executor_endpoint_holder = get_endpoint_holder(endpoint);
		}
A
Merge  
Alexey Arno 已提交
403 404

		{
405
			InterserverIOEndpointPtr endpoint = std::make_shared<RemotePartChecker::Service>(res_ptr);
A
Merge  
Alexey Arno 已提交
406 407
			res->remote_part_checker_endpoint_holder = get_endpoint_holder(endpoint);
		}
M
Merge  
Michael Kolupaev 已提交
408
	}
409

410
	return res;
M
Merge  
Michael Kolupaev 已提交
411 412
}

A
Merge  
Alexey Milovidov 已提交
413

M
Merge  
Michael Kolupaev 已提交
414 415 416 417 418 419 420 421
static String formattedAST(const ASTPtr & ast)
{
	if (!ast)
		return "";
	std::stringstream ss;
	formatAST(*ast, ss, 0, false, true);
	return ss.str();
}
M
Merge  
Michael Kolupaev 已提交
422

A
Merge  
Alexey Milovidov 已提交
423

424 425
namespace
{
A
Alexey Milovidov 已提交
426 427
	/** The basic parameters of table engine for saving in ZooKeeper.
	  * Lets you verify that they match local ones.
428 429 430 431 432 433 434 435 436 437 438 439 440 441
	  */
	struct TableMetadata
	{
		const MergeTreeData & data;

		TableMetadata(const MergeTreeData & data_)
			: data(data_) {}

		void write(WriteBuffer & out) const
		{
			out << "metadata format version: 1" << "\n"
				<< "date column: " << data.date_column_name << "\n"
				<< "sampling expression: " << formattedAST(data.sampling_expression) << "\n"
				<< "index granularity: " << data.index_granularity << "\n"
A
Merge  
Alexey Milovidov 已提交
442
				<< "mode: " << static_cast<int>(data.merging_params.mode) << "\n"
A
Alexey Milovidov 已提交
443
				<< "sign column: " << data.merging_params.sign_column << "\n"
444 445 446 447 448 449 450 451 452 453 454 455 456
				<< "primary key: " << formattedAST(data.primary_expr_ast) << "\n";
		}

		String toString() const
		{
			String res;
			WriteBufferFromString out(res);
			write(out);
			return res;
		}

		void check(ReadBuffer & in) const
		{
F
f1yegor 已提交
457
			/// TODO Can be made less cumbersome.
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

			in >> "metadata format version: 1";

			in >> "\ndate column: ";
			String read_date_column_name;
			in >> read_date_column_name;

			if (read_date_column_name != data.date_column_name)
				throw Exception("Existing table metadata in ZooKeeper differs in date index column."
					" Stored in ZooKeeper: " + read_date_column_name + ", local: " + data.date_column_name,
					ErrorCodes::METADATA_MISMATCH);

			in >> "\nsampling expression: ";
			String read_sample_expression;
			String local_sample_expression = formattedAST(data.sampling_expression);
			in >> read_sample_expression;

			if (read_sample_expression != local_sample_expression)
				throw Exception("Existing table metadata in ZooKeeper differs in sample expression."
					" Stored in ZooKeeper: " + read_sample_expression + ", local: " + local_sample_expression,
					ErrorCodes::METADATA_MISMATCH);

			in >> "\nindex granularity: ";
			size_t read_index_granularity = 0;
			in >> read_index_granularity;

			if (read_index_granularity != data.index_granularity)
				throw Exception("Existing table metadata in ZooKeeper differs in index granularity."
					" Stored in ZooKeeper: " + DB::toString(read_index_granularity) + ", local: " + DB::toString(data.index_granularity),
					ErrorCodes::METADATA_MISMATCH);

			in >> "\nmode: ";
			int read_mode = 0;
			in >> read_mode;

A
Merge  
Alexey Milovidov 已提交
493
			if (read_mode != static_cast<int>(data.merging_params.mode))
494
				throw Exception("Existing table metadata in ZooKeeper differs in mode of merge operation."
A
Merge  
Alexey Milovidov 已提交
495 496
					" Stored in ZooKeeper: " + DB::toString(read_mode) + ", local: "
					+ DB::toString(static_cast<int>(data.merging_params.mode)),
497 498 499 500 501 502
					ErrorCodes::METADATA_MISMATCH);

			in >> "\nsign column: ";
			String read_sign_column;
			in >> read_sign_column;

A
Alexey Milovidov 已提交
503
			if (read_sign_column != data.merging_params.sign_column)
504
				throw Exception("Existing table metadata in ZooKeeper differs in sign column."
A
Alexey Milovidov 已提交
505
					" Stored in ZooKeeper: " + read_sign_column + ", local: " + data.merging_params.sign_column,
506 507 508 509 510 511 512
					ErrorCodes::METADATA_MISMATCH);

			in >> "\nprimary key: ";
			String read_primary_key;
			String local_primary_key = formattedAST(data.primary_expr_ast);
			in >> read_primary_key;

A
Alexey Milovidov 已提交
513 514
			/// NOTE: You can make a less strict check of match expressions so that tables do not break from small changes
			///    in formatAST code.
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
			if (read_primary_key != local_primary_key)
				throw Exception("Existing table metadata in ZooKeeper differs in primary key."
					" Stored in ZooKeeper: " + read_primary_key + ", local: " + local_primary_key,
					ErrorCodes::METADATA_MISMATCH);

			in >> "\n";
			assertEOF(in);
		}

		void check(const String & s) const
		{
			ReadBufferFromString in(s);
			check(in);
		}
	};
}


M
Merge  
Michael Kolupaev 已提交
533
void StorageReplicatedMergeTree::createTableIfNotExists()
M
Merge  
Michael Kolupaev 已提交
534
{
A
Merge  
Alexey Milovidov 已提交
535 536
	auto zookeeper = getZooKeeper();

M
Merge  
Michael Kolupaev 已提交
537 538
	if (zookeeper->exists(zookeeper_path))
		return;
M
Merge  
Michael Kolupaev 已提交
539

M
Merge  
Michael Kolupaev 已提交
540
	LOG_DEBUG(log, "Creating table " << zookeeper_path);
M
Merge  
Michael Kolupaev 已提交
541

M
Merge  
Michael Kolupaev 已提交
542 543
	zookeeper->createAncestors(zookeeper_path);

A
Alexey Milovidov 已提交
544
	/// We write metadata of table so that the replicas can check table parameters with them.
545
	String metadata = TableMetadata(data).toString();
M
Merge  
Michael Kolupaev 已提交
546

A
Alexey Milovidov 已提交
547 548
	auto acl = zookeeper->getDefaultACL();

M
Merge  
Michael Kolupaev 已提交
549
	zkutil::Ops ops;
550
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path, "",
551
		acl, zkutil::CreateMode::Persistent));
552
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/metadata", metadata,
553
		acl, zkutil::CreateMode::Persistent));
554
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/columns", ColumnsDescription<false>{
555 556 557
		data.getColumnsListNonMaterialized(), data.materialized_columns,
		data.alias_columns, data.column_defaults}.toString(),
		acl, zkutil::CreateMode::Persistent));
558
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/log", "",
559
		acl, zkutil::CreateMode::Persistent));
560
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/blocks", "",
561
		acl, zkutil::CreateMode::Persistent));
562
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/block_numbers", "",
563
		acl, zkutil::CreateMode::Persistent));
564
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/nonincrement_block_numbers", "",
565
		acl, zkutil::CreateMode::Persistent));
566
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/leader_election", "",
567
		acl, zkutil::CreateMode::Persistent));
568
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/temp", "",
569
		acl, zkutil::CreateMode::Persistent));
570
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/replicas", "",
571
		acl, zkutil::CreateMode::Persistent));
M
Merge  
Michael Kolupaev 已提交
572 573 574 575

	auto code = zookeeper->tryMulti(ops);
	if (code != ZOK && code != ZNODEEXISTS)
		throw zkutil::KeeperException(code);
M
Merge  
Michael Kolupaev 已提交
576
}
M
Merge  
Michael Kolupaev 已提交
577

A
Merge  
Alexey Milovidov 已提交
578

F
f1yegor 已提交
579
/** Verify that list of columns and table settings match those specified in ZK (/ metadata).
A
Alexey Milovidov 已提交
580
	* If not, throw an exception.
M
Merge  
Michael Kolupaev 已提交
581
	*/
M
Merge  
Michael Kolupaev 已提交
582
void StorageReplicatedMergeTree::checkTableStructure(bool skip_sanity_checks, bool allow_alter)
M
Merge  
Michael Kolupaev 已提交
583
{
A
Merge  
Alexey Milovidov 已提交
584 585
	auto zookeeper = getZooKeeper();

M
Merge  
Michael Kolupaev 已提交
586
	String metadata_str = zookeeper->get(zookeeper_path + "/metadata");
587
	TableMetadata(data).check(metadata_str);
M
Merge  
Michael Kolupaev 已提交
588 589

	zkutil::Stat stat;
590
	auto columns_desc = ColumnsDescription<true>::parse(zookeeper->get(zookeeper_path + "/columns", &stat));
591 592 593 594 595

	auto & columns = columns_desc.columns;
	auto & materialized_columns = columns_desc.materialized;
	auto & alias_columns = columns_desc.alias;
	auto & column_defaults = columns_desc.defaults;
M
Merge  
Michael Kolupaev 已提交
596
	columns_version = stat.version;
597

598 599 600 601
	if (columns != data.getColumnsListNonMaterialized() ||
		materialized_columns != data.materialized_columns ||
		alias_columns != data.alias_columns ||
		column_defaults != data.column_defaults)
M
Merge  
Michael Kolupaev 已提交
602
	{
603 604 605 606
		if (allow_alter &&
			(skip_sanity_checks ||
			 data.getColumnsListNonMaterialized().sizeOfDifference(columns) +
			 data.materialized_columns.sizeOfDifference(materialized_columns) <= 2))
M
Merge  
Michael Kolupaev 已提交
607
		{
M
Merge  
Michael Kolupaev 已提交
608
			LOG_WARNING(log, "Table structure in ZooKeeper is a little different from local table structure. Assuming ALTER.");
609

A
Alexey Milovidov 已提交
610
			/// Without any locks, because table has not been created yet.
611 612 613 614
			context.getDatabase(database_name)->alterTable(
				context, table_name,
				columns, materialized_columns, alias_columns, column_defaults, {});

615
			data.setColumnsList(columns);
616 617 618
			data.materialized_columns = std::move(materialized_columns);
			data.alias_columns = std::move(alias_columns);
			data.column_defaults = std::move(column_defaults);
M
Merge  
Michael Kolupaev 已提交
619
		}
M
Merge  
Michael Kolupaev 已提交
620
		else
M
Merge  
Michael Kolupaev 已提交
621
		{
622
			throw Exception("Table structure in ZooKeeper is too much different from local table structure.",
M
Merge  
Michael Kolupaev 已提交
623
							ErrorCodes::INCOMPATIBLE_COLUMNS);
M
Merge  
Michael Kolupaev 已提交
624
		}
M
Merge  
Michael Kolupaev 已提交
625 626
	}
}
M
Merge  
Michael Kolupaev 已提交
627

A
Merge  
Alexey Milovidov 已提交
628

F
f1yegor 已提交
629 630 631 632
/** If necessary, restore a part, replica itself adds a record for its receipt.
  * What time should I put for this entry in the queue? Time is taken into account when calculating lag of replica.
  * For these purposes, it makes sense to use creation time of missing part
  *  (that is, in calculating lag, it will be taken into account how old is the part we need to recover).
633 634 635 636 637
  */
static time_t tryGetPartCreateTime(zkutil::ZooKeeperPtr & zookeeper, const String & replica_path, const String & part_name)
{
	time_t res = 0;

A
Alexey Milovidov 已提交
638
	/// We get creation time of part, if it still exists (was not merged, for example).
639 640 641 642 643 644 645 646 647
	zkutil::Stat stat;
	String unused;
	if (zookeeper->tryGet(replica_path + "/parts/" + part_name, unused, &stat))
		res = stat.ctime / 1000;

	return res;
}


M
Merge  
Michael Kolupaev 已提交
648 649
void StorageReplicatedMergeTree::createReplica()
{
A
Merge  
Alexey Milovidov 已提交
650 651
	auto zookeeper = getZooKeeper();

M
Merge  
Michael Kolupaev 已提交
652
	LOG_DEBUG(log, "Creating replica " << replica_path);
M
Merge  
Michael Kolupaev 已提交
653

A
Alexey Milovidov 已提交
654
	/// Create an empty replica. We'll create `columns` node at the end - we'll use it as a sign that replica creation is complete.
A
Alexey Milovidov 已提交
655
	auto acl = zookeeper->getDefaultACL();
M
Merge  
Michael Kolupaev 已提交
656
	zkutil::Ops ops;
657 658 659 660 661 662
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(replica_path, "", acl, zkutil::CreateMode::Persistent));
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(replica_path + "/host", "", acl, zkutil::CreateMode::Persistent));
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(replica_path + "/log_pointer", "", acl, zkutil::CreateMode::Persistent));
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(replica_path + "/queue", "", acl, zkutil::CreateMode::Persistent));
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(replica_path + "/parts", "", acl, zkutil::CreateMode::Persistent));
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(replica_path + "/flags", "", acl, zkutil::CreateMode::Persistent));
663 664 665 666 667 668 669 670

	try
	{
		zookeeper->multi(ops);
	}
	catch (const zkutil::KeeperException & e)
	{
		if (e.code == ZNODEEXISTS)
671
			throw Exception("Replica " + replica_path + " already exists.", ErrorCodes::REPLICA_IS_ALREADY_EXIST);
672 673 674

		throw;
	}
M
Merge  
Michael Kolupaev 已提交
675

A
Alexey Milovidov 已提交
676 677
	/** You need to change the data of nodes/replicas to anything, so that the thread that removes old entries in the log,
	  *  stumbled over this change and does not delete the entries we have not yet read.
M
Merge  
Michael Kolupaev 已提交
678 679 680
	  */
	zookeeper->set(zookeeper_path + "/replicas", "last added replica: " + replica_name);

M
Merge  
Michael Kolupaev 已提交
681
	Strings replicas = zookeeper->getChildren(zookeeper_path + "/replicas");
M
Merge  
Michael Kolupaev 已提交
682

A
Alexey Milovidov 已提交
683 684
	/** "Reference" replica, from which we take information about the set of parts, queue and pointer to the log.
	  * Take random replica created earlier than this.
M
Merge  
Michael Kolupaev 已提交
685 686
	  */
	String source_replica;
M
Merge  
Michael Kolupaev 已提交
687

M
Merge  
Michael Kolupaev 已提交
688 689 690
	Stat stat;
	zookeeper->exists(replica_path, &stat);
	auto my_create_time = stat.czxid;
M
Merge  
Michael Kolupaev 已提交
691

M
Merge  
Michael Kolupaev 已提交
692 693
	std::random_shuffle(replicas.begin(), replicas.end());
	for (const String & replica : replicas)
M
Merge  
Michael Kolupaev 已提交
694
	{
M
Merge  
Michael Kolupaev 已提交
695 696 697 698 699 700 701 702
		if (!zookeeper->exists(zookeeper_path + "/replicas/" + replica, &stat))
			throw Exception("Replica " + zookeeper_path + "/replicas/" + replica + " was removed from right under our feet.",
							ErrorCodes::NO_SUCH_REPLICA);
		if (stat.czxid < my_create_time)
		{
			source_replica = replica;
			break;
		}
M
Merge  
Michael Kolupaev 已提交
703 704
	}

M
Merge  
Michael Kolupaev 已提交
705
	if (source_replica.empty())
M
Merge  
Michael Kolupaev 已提交
706
	{
M
Merge  
Michael Kolupaev 已提交
707
		LOG_INFO(log, "This is the first replica");
M
Merge  
Michael Kolupaev 已提交
708
	}
M
Merge  
Michael Kolupaev 已提交
709
	else
M
Merge  
Michael Kolupaev 已提交
710
	{
M
Merge  
Michael Kolupaev 已提交
711
		LOG_INFO(log, "Will mimic " << source_replica);
M
Merge  
Michael Kolupaev 已提交
712

M
Merge  
Michael Kolupaev 已提交
713
		String source_path = zookeeper_path + "/replicas/" + source_replica;
M
Merge  
Michael Kolupaev 已提交
714

A
Alexey Milovidov 已提交
715 716 717 718 719
		/** If the reference/master replica is not yet fully created, let's wait.
		  * NOTE: If something went wrong while creating it, we can hang around forever.
		  *    You can create an ephemeral node at the time of creation to make sure that the replica is created, and not abandoned.
		  *    The same can be done for the table. You can automatically delete a replica/table node,
		  *     if you see that it was not created up to the end, and the one who created it died.
M
Merge  
Michael Kolupaev 已提交
720 721 722 723 724
		  */
		while (!zookeeper->exists(source_path + "/columns"))
		{
			LOG_INFO(log, "Waiting for replica " << source_path << " to be fully created");

725
			zkutil::EventPtr event = std::make_shared<Poco::Event>();
M
Merge  
Michael Kolupaev 已提交
726 727 728 729 730 731 732 733 734
			if (zookeeper->exists(source_path + "/columns", nullptr, event))
			{
				LOG_WARNING(log, "Oops, a watch has leaked");
				break;
			}

			event->wait();
		}

A
Alexey Milovidov 已提交
735
		/// The order of the following three actions is important. Entries in the log can be duplicated, but they can not be lost.
M
Merge  
Michael Kolupaev 已提交
736

A
Alexey Milovidov 已提交
737
		/// Copy reference to the log from `reference/master` replica.
M
Merge  
Michael Kolupaev 已提交
738 739
		zookeeper->set(replica_path + "/log_pointer", zookeeper->get(source_path + "/log_pointer"));

A
Alexey Milovidov 已提交
740
		/// Let's remember the queue of the reference/master replica.
M
Merge  
Michael Kolupaev 已提交
741 742 743 744 745 746 747 748 749 750 751
		Strings source_queue_names = zookeeper->getChildren(source_path + "/queue");
		std::sort(source_queue_names.begin(), source_queue_names.end());
		Strings source_queue;
		for (const String & entry_name : source_queue_names)
		{
			String entry;
			if (!zookeeper->tryGet(source_path + "/queue/" + entry_name, entry))
				continue;
			source_queue.push_back(entry);
		}

A
Alexey Milovidov 已提交
752
		/// Add to the queue jobs to receive all the active parts that the reference/master replica has.
M
Merge  
Michael Kolupaev 已提交
753
		Strings parts = zookeeper->getChildren(source_path + "/parts");
754 755
		ActiveDataPartSet active_parts_set(parts);

M
Merge  
Michael Kolupaev 已提交
756 757 758 759 760 761 762
		Strings active_parts = active_parts_set.getParts();
		for (const String & name : active_parts)
		{
			LogEntry log_entry;
			log_entry.type = LogEntry::GET_PART;
			log_entry.source_replica = "";
			log_entry.new_part_name = name;
763
			log_entry.create_time = tryGetPartCreateTime(zookeeper, source_path, name);
764

M
Merge  
Michael Kolupaev 已提交
765 766 767 768
			zookeeper->create(replica_path + "/queue/queue-", log_entry.toString(), zkutil::CreateMode::PersistentSequential);
		}
		LOG_DEBUG(log, "Queued " << active_parts.size() << " parts to be fetched");

A
Alexey Milovidov 已提交
769
		/// Add content of the reference/master replica queue to the queue.
M
Merge  
Michael Kolupaev 已提交
770 771 772 773
		for (const String & entry : source_queue)
		{
			zookeeper->create(replica_path + "/queue/queue-", entry, zkutil::CreateMode::PersistentSequential);
		}
774

A
Alexey Milovidov 已提交
775
		/// It will then be loaded into the queue variable in `queue.initialize` method.
776

M
Merge  
Michael Kolupaev 已提交
777
		LOG_DEBUG(log, "Copied " << source_queue.size() << " queue entries");
M
Merge  
Michael Kolupaev 已提交
778
	}
M
Merge  
Michael Kolupaev 已提交
779

780 781 782 783 784 785
	zookeeper->create(replica_path + "/columns", ColumnsDescription<false>{
			data.getColumnsListNonMaterialized(),
			data.materialized_columns,
			data.alias_columns,
			data.column_defaults
		}.toString(), zkutil::CreateMode::Persistent);
M
Merge  
Michael Kolupaev 已提交
786
}
M
Merge  
Michael Kolupaev 已提交
787 788


M
Merge  
Michael Kolupaev 已提交
789
void StorageReplicatedMergeTree::checkParts(bool skip_sanity_checks)
M
Merge  
Michael Kolupaev 已提交
790
{
A
Merge  
Alexey Milovidov 已提交
791 792
	auto zookeeper = getZooKeeper();

M
Merge  
Michael Kolupaev 已提交
793
	Strings expected_parts_vec = zookeeper->getChildren(replica_path + "/parts");
M
Merge  
Michael Kolupaev 已提交
794

F
f1yegor 已提交
795
	/// Parts in ZK.
M
Merge  
Michael Kolupaev 已提交
796 797
	NameSet expected_parts(expected_parts_vec.begin(), expected_parts_vec.end());

M
Merge  
Michael Kolupaev 已提交
798
	MergeTreeData::DataParts parts = data.getAllDataParts();
M
Merge  
Michael Kolupaev 已提交
799

A
Alexey Milovidov 已提交
800
	/// Local parts that are not in ZK.
M
Merge  
Michael Kolupaev 已提交
801
	MergeTreeData::DataParts unexpected_parts;
M
Merge  
Michael Kolupaev 已提交
802

M
Merge  
Michael Kolupaev 已提交
803 804 805 806 807
	for (const auto & part : parts)
	{
		if (expected_parts.count(part->name))
			expected_parts.erase(part->name);
		else
M
Merge  
Michael Kolupaev 已提交
808
			unexpected_parts.insert(part);
M
Merge  
Michael Kolupaev 已提交
809 810
	}

A
Alexey Milovidov 已提交
811
	/// Which local parts to added into ZK.
M
Merge  
Michael Kolupaev 已提交
812
	MergeTreeData::DataPartsVector parts_to_add;
M
Merge  
Michael Kolupaev 已提交
813

A
Alexey Milovidov 已提交
814
	/// Which parts should be taken from other replicas.
M
Merge  
Michael Kolupaev 已提交
815 816
	Strings parts_to_fetch;

M
Merge  
Michael Kolupaev 已提交
817 818
	for (const String & missing_name : expected_parts)
	{
A
Alexey Milovidov 已提交
819
		/// If locally some part is missing, but there is a part covering it, you can replace it in ZK with the covering one.
M
Merge  
Michael Kolupaev 已提交
820
		auto containing = data.getActiveContainingPart(missing_name);
M
Merge  
Michael Kolupaev 已提交
821 822 823 824 825 826 827 828 829 830
		if (containing)
		{
			LOG_ERROR(log, "Ignoring missing local part " << missing_name << " because part " << containing->name << " exists");
			if (unexpected_parts.count(containing))
			{
				parts_to_add.push_back(containing);
				unexpected_parts.erase(containing);
			}
		}
		else
M
Merge  
Michael Kolupaev 已提交
831
		{
M
Merge  
Michael Kolupaev 已提交
832
			LOG_ERROR(log, "Fetching missing part " << missing_name);
M
Merge  
Michael Kolupaev 已提交
833
			parts_to_fetch.push_back(missing_name);
M
Merge  
Michael Kolupaev 已提交
834 835
		}
	}
M
Merge  
Michael Kolupaev 已提交
836

M
Merge  
Michael Kolupaev 已提交
837 838 839
	for (const String & name : parts_to_fetch)
		expected_parts.erase(name);

A
Alexey Milovidov 已提交
840 841 842
	/** To check the adequacy, for the parts that are in the FS, but not in ZK, we will only consider not the most recent parts.
	  * Because unexpected new parts usually arise only because they did not have time to enroll in ZK with a rough restart of the server.
	  * It also occurs from deduplicated parts that did not have time to retire.
843 844 845 846 847 848 849 850 851 852 853 854
	  */
	size_t unexpected_parts_nonnew = 0;
	for (const auto & part : unexpected_parts)
		if (part->level > 0 || part->right < RESERVED_BLOCK_NUMBERS)
			++unexpected_parts_nonnew;

	String sanity_report = "There are "
			+ toString(unexpected_parts.size()) + " unexpected parts ("
			+ toString(unexpected_parts_nonnew) + " of them is not just-written), "
			+ toString(parts_to_add.size()) + " unexpectedly merged parts, "
			+ toString(expected_parts.size()) + " missing obsolete parts, "
			+ toString(parts_to_fetch.size()) + " missing parts";
M
Merge  
Michael Kolupaev 已提交
855

A
Alexey Milovidov 已提交
856 857 858 859
	/** You can automatically synchronize data,
	  *  if the number of errors of each of the four types is no more than the corresponding thresholds,
	  *  or if the ratio of the total number of errors to the total number of parts (minimum - on the local file system or in ZK)
	  *  no more than some ratio (for example 5%).
860
	  *
A
Alexey Milovidov 已提交
861 862 863
	  * A large number of mismatches in the data on the file system and the expected data
	  *  may indicate a configuration error (the server accidentally connected as a replica not from that shard).
	  * In this case, the protection mechanism does not allow the server to start.
864 865 866
	  */

	size_t min_parts_local_or_expected = std::min(expected_parts_vec.size(), parts.size());
867
	size_t total_difference = parts_to_add.size() + unexpected_parts_nonnew + expected_parts.size() + parts_to_fetch.size();
868 869 870

	bool insane =
		(parts_to_add.size() > data.settings.replicated_max_unexpectedly_merged_parts
871
			|| unexpected_parts_nonnew > data.settings.replicated_max_unexpected_parts
872 873
			|| expected_parts.size() > data.settings.replicated_max_missing_obsolete_parts
			|| parts_to_fetch.size() > data.settings.replicated_max_missing_active_parts)
874
		&& (total_difference > min_parts_local_or_expected * data.settings.replicated_max_ratio_of_wrong_parts);
M
Merge  
Michael Kolupaev 已提交
875

876 877 878 879 880 881
	if (insane && !skip_sanity_checks)
		throw Exception("The local set of parts of table " + getTableName() + " doesn't look like the set of parts in ZooKeeper. "
			+ sanity_report, ErrorCodes::TOO_MANY_UNEXPECTED_DATA_PARTS);

	if (total_difference > 0)
		LOG_WARNING(log, sanity_report);
M
Merge  
Michael Kolupaev 已提交
882

A
Alexey Milovidov 已提交
883
	/// Add information to the ZK about the parts that cover the missing parts.
884
	for (const MergeTreeData::DataPartPtr & part : parts_to_add)
M
Merge  
Michael Kolupaev 已提交
885
	{
M
Merge  
Michael Kolupaev 已提交
886
		LOG_ERROR(log, "Adding unexpected local part to ZooKeeper: " << part->name);
M
Merge  
Michael Kolupaev 已提交
887

M
Merge  
Michael Kolupaev 已提交
888
		zkutil::Ops ops;
M
Merge  
Michael Kolupaev 已提交
889
		checkPartAndAddToZooKeeper(part, ops);
M
Merge  
Michael Kolupaev 已提交
890
		zookeeper->multi(ops);
M
Merge  
Michael Kolupaev 已提交
891
	}
M
Merge  
Michael Kolupaev 已提交
892

A
Alexey Milovidov 已提交
893
	/// Remove from ZK information about the parts covered by the newly added ones.
M
Merge  
Michael Kolupaev 已提交
894 895
	for (const String & name : expected_parts)
	{
M
Merge  
Michael Kolupaev 已提交
896 897 898
		LOG_ERROR(log, "Removing unexpectedly merged local part from ZooKeeper: " << name);

		zkutil::Ops ops;
899
		removePartFromZooKeeper(name, ops);
M
Merge  
Michael Kolupaev 已提交
900 901 902
		zookeeper->multi(ops);
	}

A
Alexey Milovidov 已提交
903
	/// Add to the queue job to pick up the missing parts from other replicas and remove from ZK the information that we have them.
M
Merge  
Michael Kolupaev 已提交
904 905 906 907 908 909
	for (const String & name : parts_to_fetch)
	{
		LOG_ERROR(log, "Removing missing part from ZooKeeper and queueing a fetch: " << name);

		LogEntry log_entry;
		log_entry.type = LogEntry::GET_PART;
M
Merge  
Michael Kolupaev 已提交
910
		log_entry.source_replica = "";
M
Merge  
Michael Kolupaev 已提交
911
		log_entry.new_part_name = name;
912
		log_entry.create_time = tryGetPartCreateTime(zookeeper, replica_path, name);
M
Merge  
Michael Kolupaev 已提交
913

F
f1yegor 已提交
914
		/// We assume that this occurs before the queue is loaded (queue.initialize).
M
Merge  
Michael Kolupaev 已提交
915
		zkutil::Ops ops;
916
		removePartFromZooKeeper(name, ops);
917
		ops.emplace_back(std::make_unique<zkutil::Op::Create>(
M
Merge  
Michael Kolupaev 已提交
918
			replica_path + "/queue/queue-", log_entry.toString(), zookeeper->getDefaultACL(), zkutil::CreateMode::PersistentSequential));
M
Merge  
Michael Kolupaev 已提交
919
		zookeeper->multi(ops);
M
Merge  
Michael Kolupaev 已提交
920 921
	}

A
Alexey Milovidov 已提交
922
	/// Remove extra local parts.
923
	for (const MergeTreeData::DataPartPtr & part : unexpected_parts)
M
Merge  
Michael Kolupaev 已提交
924
	{
M
Merge  
Michael Kolupaev 已提交
925
		LOG_ERROR(log, "Renaming unexpected part " << part->name << " to ignored_" + part->name);
M
Merge  
Michael Kolupaev 已提交
926
		data.renameAndDetachPart(part, "ignored_", true);
M
Merge  
Michael Kolupaev 已提交
927 928
	}
}
M
Merge  
Michael Kolupaev 已提交
929

A
Merge  
Alexey Milovidov 已提交
930

931 932
void StorageReplicatedMergeTree::checkPartAndAddToZooKeeper(
	const MergeTreeData::DataPartPtr & part, zkutil::Ops & ops, String part_name)
M
Merge  
Michael Kolupaev 已提交
933
{
A
Merge  
Alexey Milovidov 已提交
934 935
	auto zookeeper = getZooKeeper();

M
Merge  
Michael Kolupaev 已提交
936 937 938
	if (part_name.empty())
		part_name = part->name;

939
	check(part->columns);
M
Merge  
Michael Kolupaev 已提交
940
	int expected_columns_version = columns_version;
941

M
Merge  
Michael Kolupaev 已提交
942 943 944 945 946
	Strings replicas = zookeeper->getChildren(zookeeper_path + "/replicas");
	std::random_shuffle(replicas.begin(), replicas.end());
	String expected_columns_str = part->columns.toString();

	for (const String & replica : replicas)
M
Merge  
Michael Kolupaev 已提交
947
	{
M
Merge  
Michael Kolupaev 已提交
948 949
		zkutil::Stat stat_before, stat_after;
		String columns_str;
M
Merge  
Michael Kolupaev 已提交
950
		if (!zookeeper->tryGet(zookeeper_path + "/replicas/" + replica + "/parts/" + part_name + "/columns", columns_str, &stat_before))
M
Merge  
Michael Kolupaev 已提交
951 952 953
			continue;
		if (columns_str != expected_columns_str)
		{
M
Merge  
Michael Kolupaev 已提交
954
			LOG_INFO(log, "Not checking checksums of part " << part_name << " with replica " << replica
M
Merge  
Michael Kolupaev 已提交
955 956 957
				<< " because columns are different");
			continue;
		}
M
Merge  
Michael Kolupaev 已提交
958
		String checksums_str;
F
f1yegor 已提交
959 960
		/// Let's check that the node's version with the columns did not change while we were reading the checksums.
		/// This ensures that the columns and the checksum refer to the same data.
M
Merge  
Michael Kolupaev 已提交
961 962
		if (!zookeeper->tryGet(zookeeper_path + "/replicas/" + replica + "/parts/" + part_name + "/checksums", checksums_str) ||
			!zookeeper->exists(zookeeper_path + "/replicas/" + replica + "/parts/" + part_name + "/columns", &stat_after) ||
M
Merge  
Michael Kolupaev 已提交
963
			stat_before.version != stat_after.version)
M
Merge  
Michael Kolupaev 已提交
964
		{
M
Merge  
Michael Kolupaev 已提交
965
			LOG_INFO(log, "Not checking checksums of part " << part_name << " with replica " << replica
M
Merge  
Michael Kolupaev 已提交
966 967
				<< " because part changed while we were reading its checksums");
			continue;
M
Merge  
Michael Kolupaev 已提交
968
		}
M
Merge  
Michael Kolupaev 已提交
969 970 971

		auto checksums = MergeTreeData::DataPart::Checksums::parse(checksums_str);
		checksums.checkEqual(part->checksums, true);
M
Merge  
Michael Kolupaev 已提交
972 973
	}

M
Merge  
Michael Kolupaev 已提交
974
	if (zookeeper->exists(replica_path + "/parts/" + part_name))
M
Merge  
Michael Kolupaev 已提交
975
	{
M
Merge  
Michael Kolupaev 已提交
976
		LOG_ERROR(log, "checkPartAndAddToZooKeeper: node " << replica_path + "/parts/" + part_name << " already exists");
M
Merge  
Michael Kolupaev 已提交
977 978 979
		return;
	}

A
Alexey Milovidov 已提交
980 981
	auto acl = zookeeper->getDefaultACL();

982
	ops.emplace_back(std::make_unique<zkutil::Op::Check>(
983 984
		zookeeper_path + "/columns",
		expected_columns_version));
985
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(
M
Merge  
Michael Kolupaev 已提交
986
		replica_path + "/parts/" + part_name,
M
Merge  
Michael Kolupaev 已提交
987
		"",
A
Alexey Milovidov 已提交
988
		acl,
M
Merge  
Michael Kolupaev 已提交
989
		zkutil::CreateMode::Persistent));
990
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(
M
Merge  
Michael Kolupaev 已提交
991
		replica_path + "/parts/" + part_name + "/columns",
M
Merge  
Michael Kolupaev 已提交
992
		part->columns.toString(),
A
Alexey Milovidov 已提交
993
		acl,
M
Merge  
Michael Kolupaev 已提交
994
		zkutil::CreateMode::Persistent));
995
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(
M
Merge  
Michael Kolupaev 已提交
996
		replica_path + "/parts/" + part_name + "/checksums",
M
Merge  
Michael Kolupaev 已提交
997
		part->checksums.toString(),
A
Alexey Milovidov 已提交
998
		acl,
M
Merge  
Michael Kolupaev 已提交
999 1000 1001
		zkutil::CreateMode::Persistent));
}

A
Merge  
Alexey Milovidov 已提交
1002

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
void StorageReplicatedMergeTree::addNewPartToZooKeeper(const MergeTreeData::DataPartPtr & part, zkutil::Ops & ops, String part_name)
{
	auto zookeeper = getZooKeeper();

	if (part_name.empty())
		part_name = part->name;

	check(part->columns);

	auto acl = zookeeper->getDefaultACL();

1014
	ops.emplace_back(std::make_unique<zkutil::Op::Check>(
1015 1016
		zookeeper_path + "/columns",
		columns_version));
1017
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(
1018 1019 1020 1021
		replica_path + "/parts/" + part_name,
		"",
		acl,
		zkutil::CreateMode::Persistent));
1022
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(
1023 1024 1025 1026
		replica_path + "/parts/" + part_name + "/columns",
		part->columns.toString(),
		acl,
		zkutil::CreateMode::Persistent));
1027
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(
1028 1029 1030 1031 1032 1033 1034
		replica_path + "/parts/" + part_name + "/checksums",
		part->checksums.toString(),
		acl,
		zkutil::CreateMode::Persistent));
}


M
Merge  
Michael Kolupaev 已提交
1035
void StorageReplicatedMergeTree::pullLogsToQueue(zkutil::EventPtr next_update_event)
M
Merge  
Michael Kolupaev 已提交
1036
{
A
Alexey Milovidov 已提交
1037
	if (queue.pullLogsToQueue(getZooKeeper(), next_update_event))
M
Merge  
Michael Kolupaev 已提交
1038
	{
A
Alexey Milovidov 已提交
1039 1040
		if (queue_task_handle)
			queue_task_handle->wake();
M
Merge  
Michael Kolupaev 已提交
1041
	}
M
Merge  
Michael Kolupaev 已提交
1042 1043
}

A
Merge  
Alexey Milovidov 已提交
1044

1045
bool StorageReplicatedMergeTree::executeLogEntry(const LogEntry & entry)
M
Merge  
Michael Kolupaev 已提交
1046
{
M
Merge  
Michael Kolupaev 已提交
1047
	if (entry.type == LogEntry::DROP_RANGE)
M
Merge  
Michael Kolupaev 已提交
1048 1049 1050 1051
	{
		executeDropRange(entry);
		return true;
	}
M
Merge  
Michael Kolupaev 已提交
1052

M
Merge  
Michael Kolupaev 已提交
1053
	if (entry.type == LogEntry::GET_PART ||
M
Merge  
Michael Kolupaev 已提交
1054 1055
		entry.type == LogEntry::MERGE_PARTS ||
		entry.type == LogEntry::ATTACH_PART)
M
Merge  
Michael Kolupaev 已提交
1056
	{
A
Alexey Milovidov 已提交
1057
		/// If we already have this part or a part covering it, we do not need to do anything.
M
Merge  
Michael Kolupaev 已提交
1058
		MergeTreeData::DataPartPtr containing_part = data.getActiveContainingPart(entry.new_part_name);
M
Merge  
Michael Kolupaev 已提交
1059

A
Alexey Milovidov 已提交
1060
		/// Even if the part is locally, it (in exceptional cases) may not be in ZooKeeper. Let's check that it is there.
1061
		if (containing_part && getZooKeeper()->exists(replica_path + "/parts/" + containing_part->name))
M
Merge  
Michael Kolupaev 已提交
1062
		{
M
Merge  
Michael Kolupaev 已提交
1063
			if (!(entry.type == LogEntry::GET_PART && entry.source_replica == replica_name))
1064
				LOG_DEBUG(log, "Skipping action for part " << entry.new_part_name << " - part already exists.");
M
Merge  
Michael Kolupaev 已提交
1065
			return true;
M
Merge  
Michael Kolupaev 已提交
1066
		}
M
Merge  
Michael Kolupaev 已提交
1067 1068
	}

M
Merge  
Michael Kolupaev 已提交
1069
	if (entry.type == LogEntry::GET_PART && entry.source_replica == replica_name)
M
Merge  
Michael Kolupaev 已提交
1070
		LOG_WARNING(log, "Part " << entry.new_part_name << " from own log doesn't exist.");
M
Merge  
Michael Kolupaev 已提交
1071

A
Alexey Milovidov 已提交
1072
	/// Perhaps we don't need this part, because during write with quorum, the quorum has failed (see below about `/quorum/failed_parts`).
1073
	if (entry.quorum && getZooKeeper()->exists(zookeeper_path + "/quorum/failed_parts/" + entry.new_part_name))
1074 1075
	{
		LOG_DEBUG(log, "Skipping action for part " << entry.new_part_name << " because quorum for that part was failed.");
A
Alexey Milovidov 已提交
1076
		return true;    /// NOTE Deletion from `virtual_parts` is not done, but it is only necessary for merge.
1077 1078
	}

M
Merge  
Michael Kolupaev 已提交
1079 1080
	bool do_fetch = false;

M
Merge  
Michael Kolupaev 已提交
1081 1082
	if (entry.type == LogEntry::GET_PART)
	{
M
Merge  
Michael Kolupaev 已提交
1083
		do_fetch = true;
M
Merge  
Michael Kolupaev 已提交
1084
	}
M
Merge  
Michael Kolupaev 已提交
1085 1086 1087 1088
	else if (entry.type == LogEntry::ATTACH_PART)
	{
		do_fetch = !executeAttachPart(entry);
	}
M
Merge  
Michael Kolupaev 已提交
1089 1090
	else if (entry.type == LogEntry::MERGE_PARTS)
	{
1091 1092 1093 1094 1095 1096 1097 1098
		std::stringstream log_message;
		log_message << "Executing log entry to merge parts ";
		for (auto i : ext::range(0, entry.parts_to_merge.size()))
			log_message << (i != 0 ? ", " : "") << entry.parts_to_merge[i];
		log_message << " to " << entry.new_part_name;

		LOG_TRACE(log, log_message.rdbuf());

M
Merge  
Michael Kolupaev 已提交
1099
		MergeTreeData::DataPartsVector parts;
1100
		bool have_all_parts = true;
M
Merge  
Michael Kolupaev 已提交
1101 1102
		for (const String & name : entry.parts_to_merge)
		{
M
Merge  
Michael Kolupaev 已提交
1103
			MergeTreeData::DataPartPtr part = data.getActiveContainingPart(name);
M
Merge  
Michael Kolupaev 已提交
1104 1105 1106 1107 1108 1109 1110
			if (!part)
			{
				have_all_parts = false;
				break;
			}
			if (part->name != name)
			{
M
Merge  
Michael Kolupaev 已提交
1111 1112
				LOG_WARNING(log, "Part " << name << " is covered by " << part->name
					<< " but should be merged into " << entry.new_part_name << ". This shouldn't happen often.");
M
Merge  
Michael Kolupaev 已提交
1113 1114 1115
				have_all_parts = false;
				break;
			}
M
Merge  
Michael Kolupaev 已提交
1116 1117
			parts.push_back(part);
		}
M
Merge  
Michael Kolupaev 已提交
1118

M
Merge  
Michael Kolupaev 已提交
1119
		if (!have_all_parts)
M
Merge  
Michael Kolupaev 已提交
1120
		{
A
Alexey Milovidov 已提交
1121
			/// If you do not have all the necessary parts, try to take some already merged piece from someone.
M
Merge  
Michael Kolupaev 已提交
1122 1123
			do_fetch = true;
			LOG_DEBUG(log, "Don't have all parts for merge " << entry.new_part_name << "; will try to fetch it instead");
M
Merge  
Michael Kolupaev 已提交
1124
		}
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
		else if (entry.create_time + data.settings.prefer_fetch_merged_part_time_threshold <= time(nullptr))
		{
			/// If entry is old enough, and have enough size, and part are exists in any replica,
			///  then prefer fetching of merged part from replica.

			size_t sum_parts_size_in_bytes = 0;
			for (const auto & part : parts)
				sum_parts_size_in_bytes += part->size_in_bytes;

			if (sum_parts_size_in_bytes >= data.settings.prefer_fetch_merged_part_size_threshold)
			{
				String replica = findReplicaHavingPart(entry.new_part_name, true);	/// NOTE excessive ZK requests for same data later, may remove.
				if (!replica.empty())
				{
					do_fetch = true;
					LOG_DEBUG(log, "Preffering to fetch " << entry.new_part_name << " from replica");
				}
			}
		}

		if (!do_fetch)
M
Merge  
Michael Kolupaev 已提交
1146
		{
1147
			size_t estimated_space_for_merge = MergeTreeDataMerger::estimateDiskSpaceForMerge(parts);
1148

F
f1yegor 已提交
1149
			/// Can throw an exception.
1150
			DiskSpaceMonitor::ReservationPtr reserved_space = DiskSpaceMonitor::reserve(full_path, estimated_space_for_merge);
A
Merge  
Alexey Milovidov 已提交
1151

M
Merge  
Michael Kolupaev 已提交
1152
			auto table_lock = lockStructure(false);
1153

1154
			MergeList::EntryPtr merge_entry = context.getMergeList().insert(database_name, table_name, entry.new_part_name, parts);
M
Merge  
Michael Kolupaev 已提交
1155
			MergeTreeData::Transaction transaction;
A
Merge  
Alexey Arno 已提交
1156
			size_t aio_threshold = context.getSettings().min_bytes_to_use_direct_io;
1157

B
Bogdan Voronin 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166
			/// Logging
			PartLogElement elem;
			Stopwatch stopwatch;
			elem.event_time = time(0);

			elem.merged_from.reserve(parts.size());
			for (const auto & part : parts)
				elem.merged_from.push_back(part->name);

1167
			auto part = merger.mergePartsToTemporaryPart(
1168
				parts, entry.new_part_name, *merge_entry, aio_threshold, entry.create_time, reserved_space.get());
M
Merge  
Michael Kolupaev 已提交
1169

B
Bogdan Voronin 已提交
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
			std::shared_ptr<PartLog> part_log = context.getPartLog();
			if (part_log)
			{
				elem.event_type = PartLogElement::MERGE_PARTS;
				elem.size_in_bytes = part->size_in_bytes;

				elem.database_name = part->storage.getDatabaseName();
				elem.table_name = part->storage.getTableName();
				elem.part_name = part->name;

				elem.duration_ms = stopwatch.elapsed() / 1000000;

				part_log->add(elem);
			}
			part_log.reset();

M
Merge  
Michael Kolupaev 已提交
1186 1187
			zkutil::Ops ops;

1188 1189
			try
			{
A
Alexey Milovidov 已提交
1190
				/// Checksums are checked here and `ops` is filled. In fact, the part is added to ZK just below, when executing `multi`.
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
				checkPartAndAddToZooKeeper(part, ops, entry.new_part_name);
			}
			catch (const Exception & e)
			{
				if (e.code() == ErrorCodes::CHECKSUM_DOESNT_MATCH
					|| e.code() == ErrorCodes::BAD_SIZE_OF_FILE_IN_DATA_PART)
				{
					do_fetch = true;
					part->remove();

					LOG_ERROR(log, getCurrentExceptionMessage(false) << ". "
						"Data after merge is not byte-identical to data on another replicas. "
						"There could be several reasons: "
						"1. Using newer version of compression library after server update. "
						"2. Using another compression method. "
						"3. Non-deterministic compression algorithm (highly unlikely). "
						"4. Non-deterministic merge algorithm due to logical error in code. "
						"5. Data corruption in memory due to bug in code. "
						"6. Data corruption in memory due to hardware issue. "
1210
						"7. Manual modification of source data after server startup. "
1211 1212 1213
						"8. Manual modification of checksums stored in ZooKeeper. "
						"We will download merged part from replica to force byte-identical result.");
				}
1214 1215
				else
					throw;
1216
			}
M
Merge  
Michael Kolupaev 已提交
1217

1218 1219 1220
			if (!do_fetch)
			{
				merger.renameMergedTemporaryPart(parts, part, entry.new_part_name, &transaction);
1221
				getZooKeeper()->multi(ops);		/// After long merge, get fresh ZK handle, because previous session may be expired.
M
Merge  
Michael Kolupaev 已提交
1222

A
Alexey Milovidov 已提交
1223
				/** Removing old chunks from ZK and from the disk is delayed - see ReplicatedMergeTreeCleanupThread, clearOldParts.
1224
				  */
1225

A
Alexey Milovidov 已提交
1226 1227
				/** With `ZCONNECTIONLOSS` or `ZOPERATIONTIMEOUT`, we can inadvertently roll back local changes to the parts.
				  * This is not a problem, because in this case the merge will remain in the queue, and we will try again.
1228 1229 1230
				  */
				transaction.commit();
				merge_selecting_event.set();
M
Merge  
Michael Kolupaev 已提交
1231

1232 1233
				ProfileEvents::increment(ProfileEvents::ReplicatedPartMerges);
			}
M
Merge  
Michael Kolupaev 已提交
1234
		}
M
Merge  
Michael Kolupaev 已提交
1235 1236 1237 1238 1239
	}
	else
	{
		throw Exception("Unexpected log entry type: " + toString(static_cast<int>(entry.type)));
	}
M
Merge  
Michael Kolupaev 已提交
1240 1241 1242

	if (do_fetch)
	{
1243 1244
		String covering_part;
		String replica = findReplicaHavingCoveringPart(entry.new_part_name, true, covering_part);
M
Merge  
Michael Kolupaev 已提交
1245

1246
		if (replica.empty() && entry.type == LogEntry::ATTACH_PART)
M
Merge  
Michael Kolupaev 已提交
1247
		{
A
Alexey Milovidov 已提交
1248 1249
			/** If ATTACH - a piece may not be here, because the replica, on which the part is, still did not have time to attach it.
				* In that case, you need to wait for this.
1250
				*/
A
Merge  
Alexey Milovidov 已提交
1251

A
Alexey Milovidov 已提交
1252
			/// The part must be on the initiator replica.
1253 1254 1255
			if (entry.source_replica.empty() || entry.source_replica == replica_name)
				throw Exception("Logical error: no source replica specified for ATTACH_PART log entry;"
					" or trying to fetch part on source replica", ErrorCodes::LOGICAL_ERROR);
A
Merge  
Alexey Milovidov 已提交
1256

1257 1258
			throw Exception("No active replica has attached part " + entry.new_part_name + " or covering part yet", ErrorCodes::NO_REPLICA_HAS_PART);
		}
A
Merge  
Alexey Milovidov 已提交
1259

1260 1261
		try
		{
M
Merge  
Michael Kolupaev 已提交
1262 1263
			if (replica.empty())
			{
A
Alexey Milovidov 已提交
1264 1265 1266 1267
				/** If a part is to be written with a quorum and the quorum is not reached yet,
				  *  then (due to the fact that a part is impossible to download right now),
				  *  the quorum entry should be considered unsuccessful.
				  * TODO Complex code, extract separately.
1268 1269 1270 1271 1272 1273
				  */
				if (entry.quorum)
				{
					if (entry.type != LogEntry::GET_PART)
						throw Exception("Logical error: log entry with quorum but type is not GET_PART", ErrorCodes::LOGICAL_ERROR);

1274
					if (entry.block_id.empty())
1275
						throw Exception("Logical error: log entry with quorum has empty block_id", ErrorCodes::LOGICAL_ERROR);
1276

1277 1278 1279
					LOG_DEBUG(log, "No active replica has part " << entry.new_part_name << " which needs to be written with quorum."
						" Will try to mark that quorum as failed.");

A
Alexey Milovidov 已提交
1280 1281 1282 1283 1284 1285 1286
					/** Atomically:
					  * - if replicas do not become active;
					  * - if there is a `quorum` node with this part;
					  * - delete `quorum` node;
					  * - set `nonincrement_block_numbers` to resolve merges through the number of the lost part;
					  * - add a part to the list `quorum/failed_parts`;
					  * - if the part is not already removed from the list for deduplication `blocks/block_num`, then delete it;
1287
					  *
A
Alexey Milovidov 已提交
1288
					  * If something changes, then we will nothing - we'll get here again next time.
1289 1290
					  */

A
Alexey Milovidov 已提交
1291
					/** We collect the `host` node versions from the replicas.
F
f1yegor 已提交
1292 1293
					  * When the replica becomes active, it changes the value of host in the same transaction (with the creation of `is_active`).
					  * This will ensure that the replicas do not become active.
1294 1295
					  */

1296 1297
					auto zookeeper = getZooKeeper();

1298 1299 1300 1301 1302 1303 1304 1305 1306
					Strings replicas = zookeeper->getChildren(zookeeper_path + "/replicas");

					zkutil::Ops ops;

					for (size_t i = 0, size = replicas.size(); i < size; ++i)
					{
						Stat stat;
						String path = zookeeper_path + "/replicas/" + replicas[i] + "/host";
						zookeeper->get(path, &stat);
1307
						ops.emplace_back(std::make_unique<zkutil::Op::Check>(path, stat.version));
1308 1309
					}

A
Alexey Milovidov 已提交
1310
					/// We verify that while we were collecting versions, the replica with the necessary part did not come alive.
1311 1312
					replica = findReplicaHavingPart(entry.new_part_name, true);

A
Alexey Milovidov 已提交
1313 1314
					/// Also during this time a completely new replica could be created.
					/// But if a part does not appear on the old, then it can not be on the new one either.
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325

					if (replica.empty())
					{
						Stat quorum_stat;
						String quorum_path = zookeeper_path + "/quorum/status";
						String quorum_str = zookeeper->get(quorum_path, &quorum_stat);
						ReplicatedMergeTreeQuorumEntry quorum_entry;
						quorum_entry.fromString(quorum_str);

						if (quorum_entry.part_name == entry.new_part_name)
						{
1326
							ops.emplace_back(std::make_unique<zkutil::Op::Remove>(quorum_path, quorum_stat.version));
1327 1328 1329 1330 1331 1332 1333 1334 1335

							const auto partition_str = entry.new_part_name.substr(0, 6);
							ActiveDataPartSet::Part part_info;
							ActiveDataPartSet::parsePartName(entry.new_part_name, part_info);

							if (part_info.left != part_info.right)
								throw Exception("Logical error: log entry with quorum for part covering more than one block number",
									ErrorCodes::LOGICAL_ERROR);

1336 1337
							zookeeper->createIfNotExists(zookeeper_path + "/nonincrement_block_numbers/" + partition_str, "");

A
Alexey Milovidov 已提交
1338 1339
							auto acl = zookeeper->getDefaultACL();

1340
							ops.emplace_back(std::make_unique<zkutil::Op::Create>(
1341 1342
								zookeeper_path + "/nonincrement_block_numbers/" + partition_str + "/block-" + padIndex(part_info.left),
								"",
A
Alexey Milovidov 已提交
1343
								acl,
1344 1345
								zkutil::CreateMode::Persistent));

1346
							ops.emplace_back(std::make_unique<zkutil::Op::Create>(
1347 1348
								zookeeper_path + "/quorum/failed_parts/" + entry.new_part_name,
								"",
A
Alexey Milovidov 已提交
1349
								acl,
1350 1351
								zkutil::CreateMode::Persistent));

F
f1yegor 已提交
1352
							/// Deleting from `blocks`.
1353 1354
							if (zookeeper->exists(zookeeper_path + "/blocks/" + entry.block_id))
							{
1355 1356 1357
								ops.emplace_back(std::make_unique<zkutil::Op::Remove>(zookeeper_path + "/blocks/" + entry.block_id + "/number", -1));
								ops.emplace_back(std::make_unique<zkutil::Op::Remove>(zookeeper_path + "/blocks/" + entry.block_id + "/checksum", -1));
								ops.emplace_back(std::make_unique<zkutil::Op::Remove>(zookeeper_path + "/blocks/" + entry.block_id, -1));
1358 1359
							}

1360 1361 1362 1363 1364
							auto code = zookeeper->tryMulti(ops);

							if (code == ZOK)
							{
								LOG_DEBUG(log, "Marked quorum for part " << entry.new_part_name << " as failed.");
A
Alexey Milovidov 已提交
1365
								return true;    /// NOTE Deletion from `virtual_parts` is not done, but it is only necessary for merges.
1366 1367 1368 1369
							}
							else if (code == ZBADVERSION || code == ZNONODE || code == ZNODEEXISTS)
							{
								LOG_DEBUG(log, "State was changed or isn't expected when trying to mark quorum for part "
1370
									<< entry.new_part_name << " as failed. Code: " << zerror(code));
1371 1372 1373 1374 1375 1376 1377 1378
							}
							else
								throw zkutil::KeeperException(code);
						}
						else
						{
							LOG_WARNING(log, "No active replica has part " << entry.new_part_name
								<< ", but that part needs quorum and /quorum/status contains entry about another part " << quorum_entry.part_name
1379 1380
								<< ". It means that part was successfully written to " << entry.quorum
								<< " replicas, but then all of them goes offline."
1381 1382 1383 1384 1385 1386 1387 1388
								<< " Or it is a bug.");
						}
					}
				}

				if (replica.empty())
				{
					ProfileEvents::increment(ProfileEvents::ReplicatedPartFailedFetches);
1389
					throw Exception("No active replica has part " + entry.new_part_name + " or covering part", ErrorCodes::NO_REPLICA_HAS_PART);
1390
				}
M
Merge  
Michael Kolupaev 已提交
1391
			}
A
Merge  
Alexey Milovidov 已提交
1392

A
Alexey Milovidov 已提交
1393 1394
			if (!fetchPart(covering_part, zookeeper_path + "/replicas/" + replica, false, entry.quorum))
				return false;
M
Merge  
Michael Kolupaev 已提交
1395 1396 1397 1398 1399 1400

			if (entry.type == LogEntry::MERGE_PARTS)
				ProfileEvents::increment(ProfileEvents::ReplicatedPartFetchesOfMerged);
		}
		catch (...)
		{
A
Alexey Milovidov 已提交
1401 1402 1403
			/** If you can not download the part you need for some merge, it's better not to try to get other parts for this merge,
			  * but try to get already merged part. To do this, move the action to get the remaining parts
			  * for this merge at the end of the queue.
M
Merge  
Michael Kolupaev 已提交
1404 1405 1406
			  */
			try
			{
A
Alexey Milovidov 已提交
1407
				auto parts_for_merge = queue.moveSiblingPartsForMergeToEndOfQueue(entry.new_part_name);
M
Merge  
Michael Kolupaev 已提交
1408

A
Alexey Milovidov 已提交
1409
				if (!parts_for_merge.empty() && replica.empty())
M
Merge  
Michael Kolupaev 已提交
1410
				{
A
Alexey Milovidov 已提交
1411 1412
					LOG_INFO(log, "No active replica has part " << entry.new_part_name << ". Will fetch merged part instead.");
					return false;
M
Merge  
Michael Kolupaev 已提交
1413
				}
M
Merge  
Michael Kolupaev 已提交
1414

A
Alexey Milovidov 已提交
1415 1416
				/** If no active replica has a part, and there is no merge in the queue with its participation,
				  * check to see if any (active or inactive) replica has such a part or covering it.
1417
				  */
M
Merge  
Michael Kolupaev 已提交
1418 1419
				if (replica.empty())
					enqueuePartForCheck(entry.new_part_name);
M
Merge  
Michael Kolupaev 已提交
1420 1421 1422 1423 1424 1425 1426 1427 1428
			}
			catch (...)
			{
				tryLogCurrentException(__PRETTY_FUNCTION__);
			}

			throw;
		}
	}
M
Merge  
Michael Kolupaev 已提交
1429 1430

	return true;
M
Merge  
Michael Kolupaev 已提交
1431 1432
}

A
Merge  
Alexey Milovidov 已提交
1433

M
Merge  
Michael Kolupaev 已提交
1434
void StorageReplicatedMergeTree::executeDropRange(const StorageReplicatedMergeTree::LogEntry & entry)
M
Merge  
Michael Kolupaev 已提交
1435
{
M
Merge  
Michael Kolupaev 已提交
1436
	LOG_INFO(log, (entry.detach ? "Detaching" : "Removing") << " parts inside " << entry.new_part_name << ".");
M
Merge  
Michael Kolupaev 已提交
1437

1438
	queue.removeGetsAndMergesInRange(getZooKeeper(), entry.new_part_name);
M
Merge  
Michael Kolupaev 已提交
1439

M
Merge  
Michael Kolupaev 已提交
1440
	LOG_DEBUG(log, (entry.detach ? "Detaching" : "Removing") << " parts.");
M
Merge  
Michael Kolupaev 已提交
1441 1442
	size_t removed_parts = 0;

A
Alexey Milovidov 已提交
1443 1444 1445 1446
	/// Delete the parts contained in the range to be deleted.
	/// It's important that no old parts remain (after the merge), because otherwise,
	///  after adding a new replica, this new replica downloads them, but does not delete them.
	/// And, if you do not, the parts will come to life after the server is restarted.
F
f1yegor 已提交
1447
	/// Therefore, we use getAllDataParts.
1448
	auto parts = data.getAllDataParts();
M
Merge  
Michael Kolupaev 已提交
1449 1450 1451 1452
	for (const auto & part : parts)
	{
		if (!ActiveDataPartSet::contains(entry.new_part_name, part->name))
			continue;
1453

M
Merge  
Michael Kolupaev 已提交
1454 1455 1456
		LOG_DEBUG(log, "Removing part " << part->name);
		++removed_parts;

A
Alexey Milovidov 已提交
1457
		/// If you do not need to delete a part, it's more reliable to move the directory before making changes to ZooKeeper.
M
Merge  
Michael Kolupaev 已提交
1458 1459 1460
		if (entry.detach)
			data.renameAndDetachPart(part);

M
Merge  
Michael Kolupaev 已提交
1461
		zkutil::Ops ops;
1462
		removePartFromZooKeeper(part->name, ops);
1463
		auto code = getZooKeeper()->tryMulti(ops);
1464

A
Alexey Milovidov 已提交
1465 1466
		/// If the part is already removed (for example, because it was never added to ZK due to crash,
		/// see ReplicatedMergeTreeBlockOutputStream), then Ok.
1467 1468
		if (code != ZOK && code != ZNONODE)
			throw zkutil::KeeperException(code);
M
Merge  
Michael Kolupaev 已提交
1469

A
Alexey Milovidov 已提交
1470
		/// If the part needs to be removed, it is more reliable to delete the directory after the changes in ZooKeeper.
M
Merge  
Michael Kolupaev 已提交
1471
		if (!entry.detach)
M
Merge  
Michael Kolupaev 已提交
1472
			data.replaceParts({part}, {}, true);
M
Merge  
Michael Kolupaev 已提交
1473 1474
	}

M
Merge  
Michael Kolupaev 已提交
1475
	LOG_INFO(log, (entry.detach ? "Detached " : "Removed ") << removed_parts << " parts inside " << entry.new_part_name << ".");
M
Merge  
Michael Kolupaev 已提交
1476 1477
}

A
Merge  
Alexey Milovidov 已提交
1478

M
Merge  
Michael Kolupaev 已提交
1479 1480 1481 1482 1483 1484
bool StorageReplicatedMergeTree::executeAttachPart(const StorageReplicatedMergeTree::LogEntry & entry)
{
	String source_path = (entry.attach_unreplicated ? "unreplicated/" : "detached/") + entry.source_part_name;

	LOG_INFO(log, "Attaching part " << entry.source_part_name << " from " << source_path << " as " << entry.new_part_name);

M
Merge  
Michael Kolupaev 已提交
1485
	if (!Poco::File(data.getFullPath() + source_path).exists())
M
Merge  
Michael Kolupaev 已提交
1486
	{
M
Merge  
Michael Kolupaev 已提交
1487
		LOG_INFO(log, "No part at " << source_path << ". Will fetch it instead");
M
Merge  
Michael Kolupaev 已提交
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
		return false;
	}

	LOG_DEBUG(log, "Checking data");
	MergeTreeData::MutableDataPartPtr part = data.loadPartAndFixMetadata(source_path);

	zkutil::Ops ops;
	checkPartAndAddToZooKeeper(part, ops, entry.new_part_name);

	if (entry.attach_unreplicated && unreplicated_data)
	{
		MergeTreeData::DataPartPtr unreplicated_part = unreplicated_data->getPartIfExists(entry.source_part_name);
		if (unreplicated_part)
			unreplicated_data->detachPartInPlace(unreplicated_part);
		else
			LOG_WARNING(log, "Unreplicated part " << entry.source_part_name << " is already detached");
	}

1506
	getZooKeeper()->multi(ops);
M
Merge  
Michael Kolupaev 已提交
1507

A
Alexey Milovidov 已提交
1508
	/// NOTE: We can not use `renameTempPartAndAdd`, because the part is not temporary - if something goes wrong, you do not need to delete it.
M
Merge  
Michael Kolupaev 已提交
1509 1510 1511 1512 1513 1514 1515
	part->renameTo(entry.new_part_name);
	part->name = entry.new_part_name;
	ActiveDataPartSet::parsePartName(part->name, *part);

	data.attachPart(part);

	LOG_INFO(log, "Finished attaching part " << entry.new_part_name);
M
Merge  
Michael Kolupaev 已提交
1516

A
Alexey Milovidov 已提交
1517
	/// New parts with other data may appear at the place of the deleted parts.
M
Merge  
Michael Kolupaev 已提交
1518 1519
	context.resetCaches();

M
Merge  
Michael Kolupaev 已提交
1520 1521 1522
	return true;
}

A
Merge  
Alexey Milovidov 已提交
1523

M
Merge  
Michael Kolupaev 已提交
1524 1525
void StorageReplicatedMergeTree::queueUpdatingThread()
{
1526 1527
	setThreadName("ReplMTQueueUpd");

M
Merge  
Michael Kolupaev 已提交
1528 1529
	while (!shutdown_called)
	{
M
Merge  
Michael Kolupaev 已提交
1530 1531
		try
		{
M
Merge  
Michael Kolupaev 已提交
1532
			pullLogsToQueue(queue_updating_event);
1533
			queue_updating_event->wait();
M
Merge  
Michael Kolupaev 已提交
1534
		}
1535
		catch (const zkutil::KeeperException & e)
M
Merge  
Michael Kolupaev 已提交
1536 1537
		{
			if (e.code == ZINVALIDSTATE)
1538
				restarting_thread->wakeup();
M
Merge  
Michael Kolupaev 已提交
1539 1540

			tryLogCurrentException(__PRETTY_FUNCTION__);
1541
			queue_updating_event->tryWait(QUEUE_UPDATE_ERROR_SLEEP_MS);
M
Merge  
Michael Kolupaev 已提交
1542
		}
M
Merge  
Michael Kolupaev 已提交
1543 1544 1545
		catch (...)
		{
			tryLogCurrentException(__PRETTY_FUNCTION__);
1546
			queue_updating_event->tryWait(QUEUE_UPDATE_ERROR_SLEEP_MS);
M
Merge  
Michael Kolupaev 已提交
1547
		}
M
Merge  
Michael Kolupaev 已提交
1548
	}
M
Merge  
Michael Kolupaev 已提交
1549

1550
	LOG_DEBUG(log, "Queue updating thread finished");
M
Merge  
Michael Kolupaev 已提交
1551
}
M
Merge  
Michael Kolupaev 已提交
1552

A
Merge  
Alexey Milovidov 已提交
1553

1554
bool StorageReplicatedMergeTree::queueTask()
M
Merge  
Michael Kolupaev 已提交
1555
{
F
f1yegor 已提交
1556
	/// This object will mark the element of the queue as running.
1557
	ReplicatedMergeTreeQueue::SelectedEntry selected;
M
Merge  
Michael Kolupaev 已提交
1558

M
Merge  
Michael Kolupaev 已提交
1559 1560
	try
	{
1561
		selected = queue.selectEntryToProcess(merger, data);
M
Merge  
Michael Kolupaev 已提交
1562 1563 1564 1565 1566
	}
	catch (...)
	{
		tryLogCurrentException(__PRETTY_FUNCTION__);
	}
M
Merge  
Michael Kolupaev 已提交
1567

1568 1569
	LogEntryPtr & entry = selected.first;

M
Merge  
Michael Kolupaev 已提交
1570
	if (!entry)
M
Merge  
Michael Kolupaev 已提交
1571
		return false;
M
Merge  
Michael Kolupaev 已提交
1572

1573 1574
	time_t prev_attempt_time = entry->last_attempt_time;

1575
	bool res = queue.processEntry([this]{ return getZooKeeper(); }, entry, [&](LogEntryPtr & entry)
M
Merge  
Michael Kolupaev 已提交
1576
	{
1577
		try
M
Merge  
Michael Kolupaev 已提交
1578
		{
1579
			return executeLogEntry(*entry);
A
Alexey Milovidov 已提交
1580 1581 1582 1583
		}
		catch (const Exception & e)
		{
			if (e.code() == ErrorCodes::NO_REPLICA_HAS_PART)
1584
			{
A
Alexey Milovidov 已提交
1585
				/// If no one has the right part, probably not all replicas work; We will not write to log with Error level.
A
Alexey Milovidov 已提交
1586
				LOG_INFO(log, e.displayText());
1587
			}
A
Alexey Milovidov 已提交
1588 1589
			else if (e.code() == ErrorCodes::ABORTED)
			{
A
Alexey Milovidov 已提交
1590
				/// Interrupted merge or downloading a part is not an error.
A
Alexey Milovidov 已提交
1591 1592 1593 1594
				LOG_INFO(log, e.message());
			}
			else
				tryLogCurrentException(__PRETTY_FUNCTION__);
1595

A
Alexey Milovidov 已提交
1596 1597 1598
			/** This exception will be written to the queue element, and it can be looked up using `system.replication_queue` table.
			  * The thread that performs this action will sleep a few seconds after the exception.
			  * See `queue.processEntry` function.
1599
			  */
1600
			throw;
1601 1602 1603
		}
		catch (...)
		{
M
Merge  
Michael Kolupaev 已提交
1604
			tryLogCurrentException(__PRETTY_FUNCTION__);
1605
			throw;
M
Merge  
Michael Kolupaev 已提交
1606
		}
A
Alexey Milovidov 已提交
1607
	});
M
Merge  
Michael Kolupaev 已提交
1608

A
Alexey Milovidov 已提交
1609
	/// We will go to sleep if the processing fails and if we have already processed this record recently.
1610 1611
	bool need_sleep = !res && (entry->last_attempt_time - prev_attempt_time < 10);

F
f1yegor 已提交
1612
	/// If there was no exception, you do not need to sleep.
1613
	return !need_sleep;
M
Merge  
Michael Kolupaev 已提交
1614 1615
}

A
Merge  
Alexey Milovidov 已提交
1616

1617 1618 1619 1620
bool StorageReplicatedMergeTree::canMergeParts(
	const MergeTreeData::DataPartPtr & left,
	const MergeTreeData::DataPartPtr & right,
	MemoizedPartsThatCouldBeMerged * memo)
M
Merge  
Michael Kolupaev 已提交
1621
{
A
Alexey Milovidov 已提交
1622 1623 1624
	/** It can take a long time to determine whether it is possible to merge two adjacent parts.
	  * Two adjacent parts can be merged if all block numbers between their numbers are not used (abandoned).
	  * This means that another part can not be inserted between these parts.
A
Merge  
Alexey Milovidov 已提交
1625
	  *
A
Alexey Milovidov 已提交
1626 1627
	  * But if the numbers of adjacent blocks differ sufficiently strongly (usually if there are many "abandoned" blocks between them),
	  *  then too many readings are made from ZooKeeper to find out if it's possible to merge them.
A
Merge  
Alexey Milovidov 已提交
1628
	  *
A
Alexey Milovidov 已提交
1629 1630 1631
	  * Let's use a statement that if a couple of parts were possible to merge, and their merge is not yet planned,
	  *  then now they can be merged, and we will remember this state (if the parameter `memo` is specified),
	  *  not to make many times the same requests to ZooKeeper.
A
Merge  
Alexey Milovidov 已提交
1632
	  *
A
Alexey Milovidov 已提交
1633
	  * TODO I wonder how this is combined with DROP PARTITION and then ATTACH PARTITION.
A
Merge  
Alexey Milovidov 已提交
1634 1635
	  */

A
Alexey Milovidov 已提交
1636
	/// If any of the parts is already going to be merge into a larger one, do not agree to merge it.
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
	if (queue.partWillBeMergedOrMergesDisabled(left->name)
		|| (left.get() != right.get() && queue.partWillBeMergedOrMergesDisabled(right->name)))
		return false;

	auto key = std::make_pair(left->name, right->name);
	if (memo && memo->count(key))
		return true;

	String month_name = left->name.substr(0, 6);
	auto zookeeper = getZooKeeper();

A
Alexey Milovidov 已提交
1648 1649
	/// You can not merge parts, among which is a part for which the quorum is unsatisfied.
	/// Note: theoretically, this could be resolved. But this will make logic more complex.
1650 1651
	String quorum_node_value;
	if (zookeeper->tryGet(zookeeper_path + "/quorum/status", quorum_node_value))
A
Merge  
Alexey Milovidov 已提交
1652
	{
1653 1654
		ReplicatedMergeTreeQuorumEntry quorum_entry;
		quorum_entry.fromString(quorum_node_value);
1655

1656 1657
		ActiveDataPartSet::Part part_info;
		ActiveDataPartSet::parsePartName(quorum_entry.part_name, part_info);
A
Merge  
Alexey Milovidov 已提交
1658

1659 1660
		if (part_info.left != part_info.right)
			throw Exception("Logical error: part written with quorum covers more than one block numbers", ErrorCodes::LOGICAL_ERROR);
1661

1662 1663 1664
		if (left->right <= part_info.left && right->left >= part_info.right)
			return false;
	}
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679

	/// Won't merge last_part even if quorum is satisfied, because we gonna check if replica has this part
	/// on SELECT execution.
	String quorum_last_part;
	if (zookeeper->tryGet(zookeeper_path + "/quorum/last_part", quorum_last_part) && quorum_last_part.empty() == false)
	{
		ActiveDataPartSet::Part part_info;
		ActiveDataPartSet::parsePartName(quorum_last_part, part_info);

		if (part_info.left != part_info.right)
			throw Exception("Logical error: part written with quorum covers more than one block numbers", ErrorCodes::LOGICAL_ERROR);

		if (left->right <= part_info.left && right->left >= part_info.right)
			return false;
	}
1680

A
Alexey Milovidov 已提交
1681
	/// You can merge the parts, if all the numbers between them are abandoned - do not correspond to any blocks.
1682 1683
	for (Int64 number = left->right + 1; number <= right->left - 1; ++number)
	{
A
Alexey Milovidov 已提交
1684 1685 1686 1687 1688 1689
		/** For numbers before RESERVED_BLOCK_NUMBERS AbandonableLock is not used
			*  - these numbers can not be "abandoned" - that is, not used for parts.
			* These are the part numbers that were added using `ALTER ... ATTACH`.
			* They should go without a gap (for each number there should be a part).
			* We check that for all such numbers there are parts,
			*  otherwise, through the "holes" - missing parts, you can not merge.
1690
			*/
1691

1692 1693 1694 1695 1696 1697 1698
		if (number < RESERVED_BLOCK_NUMBERS)
		{
			if (!data.hasBlockNumberInMonth(number, left->month))
				return false;
		}
		else
		{
1699
			String path1 = zookeeper_path +	             "/block_numbers/" + month_name + "/block-" + padIndex(number);
1700
			String path2 = zookeeper_path + "/nonincrement_block_numbers/" + month_name + "/block-" + padIndex(number);
1701

1702 1703
			if (AbandonableLockInZooKeeper::check(path1, *zookeeper) != AbandonableLockInZooKeeper::ABANDONED &&
				AbandonableLockInZooKeeper::check(path2, *zookeeper) != AbandonableLockInZooKeeper::ABANDONED)
1704 1705
				return false;
		}
1706
	}
1707

1708 1709
	if (memo)
		memo->insert(key);
A
Merge  
Alexey Milovidov 已提交
1710

1711 1712
	return true;
}
1713

1714

1715 1716 1717
void StorageReplicatedMergeTree::mergeSelectingThread()
{
	setThreadName("ReplMTMergeSel");
A
Alexey Milovidov 已提交
1718
	LOG_DEBUG(log, "Merge selecting thread started");
1719 1720 1721 1722 1723 1724 1725 1726 1727

	bool need_pull = true;

	MemoizedPartsThatCouldBeMerged memoized_parts_that_could_be_merged;

	auto can_merge = [&memoized_parts_that_could_be_merged, this]
		(const MergeTreeData::DataPartPtr & left, const MergeTreeData::DataPartPtr & right) -> bool
	{
		return canMergeParts(left, right, &memoized_parts_that_could_be_merged);
A
Merge  
Alexey Milovidov 已提交
1728 1729
	};

M
Merge  
Michael Kolupaev 已提交
1730 1731
	while (!shutdown_called && is_leader_node)
	{
M
Michael Kolupaev 已提交
1732
		bool success = false;
M
Merge  
Michael Kolupaev 已提交
1733

M
Michael Kolupaev 已提交
1734
		try
M
Merge  
Michael Kolupaev 已提交
1735
		{
M
Merge  
Michael Kolupaev 已提交
1736 1737
			if (need_pull)
			{
A
Alexey Milovidov 已提交
1738 1739
				/// You need to load new entries into the queue before you select parts to merge.
				///  (so we know which parts are already going to be merged).
M
Merge  
Michael Kolupaev 已提交
1740 1741 1742 1743
				pullLogsToQueue();
				need_pull = false;
			}

A
Alexey Milovidov 已提交
1744 1745
			std::lock_guard<std::mutex> merge_selecting_lock(merge_selecting_mutex);

1746 1747 1748
			/** If many merges is already queued, then will queue only small enough merges.
			  * Otherwise merge queue could be filled with only large merges,
			  *  and in the same time, many small parts could be created and won't be merged.
1749
			  */
1750
			size_t merges_queued = queue.countMerges();
1751

1752
			if (merges_queued >= data.settings.max_replicated_merges_in_queue)
M
Michael Kolupaev 已提交
1753
			{
1754 1755 1756 1757
				LOG_TRACE(log, "Number of queued merges (" << merges_queued
					<< ") is greater than max_replicated_merges_in_queue ("
					<< data.settings.max_replicated_merges_in_queue << "), so won't select new parts to merge.");
			}
A
Alexey Milovidov 已提交
1758 1759 1760 1761
			else
			{
				MergeTreeData::DataPartsVector parts;
				String merged_name;
M
Merge  
Michael Kolupaev 已提交
1762

1763 1764 1765 1766 1767 1768 1769
				size_t max_parts_size_for_merge = merger.getMaxPartsSizeForMerge(data.settings.max_replicated_merges_in_queue, merges_queued);

				if (max_parts_size_for_merge > 0
					&& merger.selectPartsToMerge(
						parts, merged_name, false,
						max_parts_size_for_merge,
						can_merge)
A
Alexey Milovidov 已提交
1770 1771 1772 1773 1774
					&& createLogEntryToMergeParts(parts, merged_name))
				{
					success = true;
					need_pull = true;
				}
M
Merge  
Michael Kolupaev 已提交
1775 1776 1777 1778 1779 1780 1781
			}
		}
		catch (...)
		{
			tryLogCurrentException(__PRETTY_FUNCTION__);
		}

M
Merge  
Michael Kolupaev 已提交
1782
		if (shutdown_called || !is_leader_node)
M
Merge  
Michael Kolupaev 已提交
1783 1784
			break;

M
Merge  
Michael Kolupaev 已提交
1785
		if (!success)
M
Merge  
Michael Kolupaev 已提交
1786
			merge_selecting_event.tryWait(MERGE_SELECTING_SLEEP_MS);
M
Merge  
Michael Kolupaev 已提交
1787
	}
M
Merge  
Michael Kolupaev 已提交
1788

1789
	LOG_DEBUG(log, "Merge selecting thread finished");
M
Merge  
Michael Kolupaev 已提交
1790 1791
}

M
Merge  
Michael Kolupaev 已提交
1792

1793 1794 1795 1796 1797 1798 1799 1800
bool StorageReplicatedMergeTree::createLogEntryToMergeParts(
	const MergeTreeData::DataPartsVector & parts, const String & merged_name, ReplicatedMergeTreeLogEntryData * out_log_entry)
{
	auto zookeeper = getZooKeeper();

	bool all_in_zk = true;
	for (const auto & part : parts)
	{
A
Alexey Milovidov 已提交
1801
		/// If there is no information about part in ZK, we will not merge it.
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
		if (!zookeeper->exists(replica_path + "/parts/" + part->name))
		{
			all_in_zk = false;

			if (part->modification_time + MAX_AGE_OF_LOCAL_PART_THAT_WASNT_ADDED_TO_ZOOKEEPER < time(0))
			{
				LOG_WARNING(log, "Part " << part->name << " (that was selected for merge)"
					<< " with age " << (time(0) - part->modification_time)
					<< " seconds exists locally but not in ZooKeeper."
					<< " Won't do merge with that part and will check it.");
				enqueuePartForCheck(part->name);
			}
		}
	}
	if (!all_in_zk)
		return false;

	LogEntry entry;
	entry.type = LogEntry::MERGE_PARTS;
	entry.source_replica = replica_name;
	entry.new_part_name = merged_name;
	entry.create_time = time(0);

	for (const auto & part : parts)
		entry.parts_to_merge.push_back(part->name);

A
Alexey Milovidov 已提交
1828 1829
	String path_created = zookeeper->create(zookeeper_path + "/log/log-", entry.toString(), zkutil::CreateMode::PersistentSequential);
	entry.znode_name = path_created.substr(path_created.find_last_of('/') + 1);
1830 1831 1832 1833

	String month_name = parts[0]->name.substr(0, 6);
	for (size_t i = 0; i + 1 < parts.size(); ++i)
	{
A
Alexey Milovidov 已提交
1834
		/// Remove the unnecessary entries about non-existent blocks.
1835 1836
		for (Int64 number = std::max(RESERVED_BLOCK_NUMBERS, parts[i]->right + 1); number <= parts[i + 1]->left - 1; ++number)
		{
1837
			zookeeper->tryRemove(zookeeper_path +	           "/block_numbers/" + month_name + "/block-" + padIndex(number));
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
			zookeeper->tryRemove(zookeeper_path + "/nonincrement_block_numbers/" + month_name + "/block-" + padIndex(number));
		}
	}

	if (out_log_entry)
		*out_log_entry = entry;

	return true;
}


1849 1850 1851 1852
void StorageReplicatedMergeTree::removePartFromZooKeeper(const String & part_name, zkutil::Ops & ops)
{
	String part_path = replica_path + "/parts/" + part_name;

1853 1854 1855
	ops.emplace_back(std::make_unique<zkutil::Op::Remove>(part_path + "/checksums", -1));
	ops.emplace_back(std::make_unique<zkutil::Op::Remove>(part_path + "/columns", -1));
	ops.emplace_back(std::make_unique<zkutil::Op::Remove>(part_path, -1));
1856 1857 1858
}


M
Merge  
Michael Kolupaev 已提交
1859 1860
void StorageReplicatedMergeTree::removePartAndEnqueueFetch(const String & part_name)
{
A
Merge  
Alexey Milovidov 已提交
1861 1862
	auto zookeeper = getZooKeeper();

M
Merge  
Michael Kolupaev 已提交
1863 1864
	String part_path = replica_path + "/parts/" + part_name;

1865
	LogEntryPtr log_entry = std::make_shared<LogEntry>();
M
Merge  
Michael Kolupaev 已提交
1866
	log_entry->type = LogEntry::GET_PART;
1867
	log_entry->create_time = tryGetPartCreateTime(zookeeper, replica_path, part_name);
M
Merge  
Michael Kolupaev 已提交
1868 1869
	log_entry->source_replica = "";
	log_entry->new_part_name = part_name;
M
Merge  
Michael Kolupaev 已提交
1870 1871

	zkutil::Ops ops;
1872
	ops.emplace_back(std::make_unique<zkutil::Op::Create>(
M
Merge  
Michael Kolupaev 已提交
1873
		replica_path + "/queue/queue-", log_entry->toString(), zookeeper->getDefaultACL(),
M
Merge  
Michael Kolupaev 已提交
1874
		zkutil::CreateMode::PersistentSequential));
1875 1876 1877

	removePartFromZooKeeper(part_name, ops);

M
Merge  
Michael Kolupaev 已提交
1878 1879
	auto results = zookeeper->multi(ops);

1880
	String path_created = dynamic_cast<zkutil::Op::Create &>(*ops[0]).getPathCreated();
A
Alexey Milovidov 已提交
1881
	log_entry->znode_name = path_created.substr(path_created.find_last_of('/') + 1);
1882
	queue.insert(zookeeper, log_entry);
M
Merge  
Michael Kolupaev 已提交
1883 1884
}

A
Merge  
Alexey Milovidov 已提交
1885

M
Merge  
Michael Kolupaev 已提交
1886 1887
void StorageReplicatedMergeTree::becomeLeader()
{
1888 1889
	std::lock_guard<std::mutex> lock(leader_node_mutex);

1890 1891 1892
	if (shutdown_called)
		return;

M
Merge  
Michael Kolupaev 已提交
1893
	LOG_INFO(log, "Became leader");
M
Merge  
Michael Kolupaev 已提交
1894 1895 1896 1897
	is_leader_node = true;
	merge_selecting_thread = std::thread(&StorageReplicatedMergeTree::mergeSelectingThread, this);
}

A
Merge  
Alexey Milovidov 已提交
1898

M
Merge  
Michael Kolupaev 已提交
1899
String StorageReplicatedMergeTree::findReplicaHavingPart(const String & part_name, bool active)
M
Merge  
Michael Kolupaev 已提交
1900
{
A
Merge  
Alexey Milovidov 已提交
1901
	auto zookeeper = getZooKeeper();
M
Merge  
Michael Kolupaev 已提交
1902
	Strings replicas = zookeeper->getChildren(zookeeper_path + "/replicas");
M
Merge  
Michael Kolupaev 已提交
1903

1904
	/// Select replicas in uniformly random order.
M
Merge  
Michael Kolupaev 已提交
1905 1906 1907 1908
	std::random_shuffle(replicas.begin(), replicas.end());

	for (const String & replica : replicas)
	{
A
Alexey Milovidov 已提交
1909 1910 1911 1912
		/// We don't interested in ourself.
		if (replica == replica_name)
			continue;

M
Merge  
Michael Kolupaev 已提交
1913 1914
		if (zookeeper->exists(zookeeper_path + "/replicas/" + replica + "/parts/" + part_name) &&
			(!active || zookeeper->exists(zookeeper_path + "/replicas/" + replica + "/is_active")))
M
Merge  
Michael Kolupaev 已提交
1915
			return replica;
1916

A
Alexey Milovidov 已提交
1917
		/// Obviously, replica could become inactive or even vanish after return from this method.
M
Merge  
Michael Kolupaev 已提交
1918 1919
	}

1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
	return {};
}


String StorageReplicatedMergeTree::findReplicaHavingCoveringPart(const String & part_name, bool active, String & out_covering_part_name)
{
	auto zookeeper = getZooKeeper();
	Strings replicas = zookeeper->getChildren(zookeeper_path + "/replicas");

	/// Select replicas in uniformly random order.
	std::random_shuffle(replicas.begin(), replicas.end());

	for (const String & replica : replicas)
	{
A
Alexey Milovidov 已提交
1934 1935 1936
		if (replica == replica_name)
			continue;

1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
		if (active && !zookeeper->exists(zookeeper_path + "/replicas/" + replica + "/is_active"))
			continue;

		String largest_part_found;
		Strings parts = zookeeper->getChildren(zookeeper_path + "/replicas/" + replica + "/parts");
		for (const String & part_on_replica : parts)
		{
			if (part_on_replica == part_name || ActiveDataPartSet::contains(part_on_replica, part_name))
			{
				if (largest_part_found.empty()
					|| ActiveDataPartSet::contains(part_on_replica, largest_part_found))
				{
					largest_part_found = part_on_replica;
				}
			}
		}

		if (!largest_part_found.empty())
		{
			out_covering_part_name = largest_part_found;
A
Alexey Milovidov 已提交
1957
			return replica;
1958 1959 1960 1961
		}
	}

	return {};
M
Merge  
Michael Kolupaev 已提交
1962 1963
}

A
Merge  
Alexey Milovidov 已提交
1964

F
f1yegor 已提交
1965
/** If a quorum is tracked for a part, update information about it in ZK.
1966
  */
1967
void StorageReplicatedMergeTree::updateQuorum(const String & part_name)
1968
{
1969
	auto zookeeper = getZooKeeper();
1970

A
Alexey Milovidov 已提交
1971
	/// Information on which replicas a part has been added, if the quorum has not yet been reached.
1972
	const String quorum_status_path = zookeeper_path + "/quorum/status";
F
f1yegor 已提交
1973
	/// The name of the previous part for which the quorum was reached.
1974 1975
	const String quorum_last_part_path = zookeeper_path + "/quorum/last_part";

1976 1977 1978
	String value;
	zkutil::Stat stat;

A
Alexey Milovidov 已提交
1979
	/// If there is no node, then all quorum INSERTs have already reached the quorum, and nothing is needed.
1980 1981 1982 1983 1984 1985 1986
	while (zookeeper->tryGet(quorum_status_path, value, &stat))
	{
		ReplicatedMergeTreeQuorumEntry quorum_entry;
		quorum_entry.fromString(value);

		if (quorum_entry.part_name != part_name)
		{
F
f1yegor 已提交
1987
			/// The quorum has already been achieved. Moreover, another INSERT with a quorum has already started.
1988 1989 1990 1991 1992 1993 1994
			break;
		}

		quorum_entry.replicas.insert(replica_name);

		if (quorum_entry.replicas.size() >= quorum_entry.required_number_of_replicas)
		{
A
Alexey Milovidov 已提交
1995
			/// The quorum is reached. Delete the node, and update information about the last part that was successfully written with quorum.
1996 1997

			zkutil::Ops ops;
1998 1999
			ops.emplace_back(std::make_unique<zkutil::Op::Remove>(quorum_status_path, stat.version));
			ops.emplace_back(std::make_unique<zkutil::Op::SetData>(quorum_last_part_path, part_name, -1));
2000
			auto code = zookeeper->tryMulti(ops);
2001

2002 2003 2004 2005 2006
			if (code == ZOK)
			{
				break;
			}
			else if (code == ZNONODE)
2007
			{
A
Alexey Milovidov 已提交
2008
				/// The quorum has already been achieved.
2009 2010 2011 2012
				break;
			}
			else if (code == ZBADVERSION)
			{
A
Alexey Milovidov 已提交
2013
				/// Node was updated meanwhile. We must re-read it and repeat all the actions.
2014 2015 2016 2017 2018 2019 2020
				continue;
			}
			else
				throw zkutil::KeeperException(code, quorum_status_path);
		}
		else
		{
F
f1yegor 已提交
2021
			/// We update the node, registering there one more replica.
2022 2023
			auto code = zookeeper->trySet(quorum_status_path, quorum_entry.toString(), stat.version);

2024 2025 2026 2027 2028
			if (code == ZOK)
			{
				break;
			}
			else if (code == ZNONODE)
2029
			{
F
f1yegor 已提交
2030
				/// The quorum has already been achieved.
2031 2032 2033 2034
				break;
			}
			else if (code == ZBADVERSION)
			{
A
Alexey Milovidov 已提交
2035
				/// Node was updated meanwhile. We must re-read it and repeat all the actions.
2036 2037 2038 2039 2040 2041 2042 2043 2044
				continue;
			}
			else
				throw zkutil::KeeperException(code, quorum_status_path);
		}
	}
}


A
Alexey Milovidov 已提交
2045
bool StorageReplicatedMergeTree::fetchPart(const String & part_name, const String & replica_path, bool to_detached, size_t quorum)
M
Merge  
Michael Kolupaev 已提交
2046
{
A
Alexey Milovidov 已提交
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
	{
		std::lock_guard<std::mutex> lock(currently_fetching_parts_mutex);
		if (!currently_fetching_parts.insert(part_name).second)
		{
			LOG_DEBUG(log, "Part " << part_name << " is already fetching right now");
			return false;
		}
	}

	SCOPE_EXIT
P
proller 已提交
2057
	({
A
Alexey Milovidov 已提交
2058 2059
		std::lock_guard<std::mutex> lock(currently_fetching_parts_mutex);
		currently_fetching_parts.erase(part_name);
P
proller 已提交
2060
	});
A
Alexey Milovidov 已提交
2061

2062
	LOG_DEBUG(log, "Fetching part " << part_name << " from " << replica_path);
M
Merge  
Michael Kolupaev 已提交
2063

2064 2065 2066
	TableStructureReadLockPtr table_lock;
	if (!to_detached)
		table_lock = lockStructure(true);
M
Merge  
Michael Kolupaev 已提交
2067

2068
	ReplicatedMergeTreeAddress address(getZooKeeper()->get(replica_path + "/host"));
M
Merge  
Michael Kolupaev 已提交
2069

2070 2071 2072 2073
	Stopwatch stopwatch;
	PartLogElement elem;
	elem.event_time = time(0);

A
Alexey Milovidov 已提交
2074 2075
	MergeTreeData::MutableDataPartPtr part = fetcher.fetchPart(
		part_name, replica_path, address.host, address.replication_port, to_detached);
M
Merge  
Michael Kolupaev 已提交
2076

R
Ravengg 已提交
2077
	std::shared_ptr<PartLog> part_log = context.getPartLog();
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
	if (part_log)
	{
		elem.event_type = PartLogElement::DOWNLOAD_PART;
		elem.size_in_bytes = part->size_in_bytes;
		elem.duration_ms = stopwatch.elapsed() / 10000000;

		elem.database_name = part->storage.getDatabaseName();
		elem.table_name = part->storage.getTableName();
		elem.part_name = part->name;

		part_log->add(elem);
	}
R
Ravengg 已提交
2090
	part_log.reset();
2091

2092 2093 2094
	if (!to_detached)
	{
		zkutil::Ops ops;
A
Alexey Milovidov 已提交
2095 2096

		/** NOTE
F
f1yegor 已提交
2097
		  * Here, an error occurs if ALTER occurred with a change in the column type or column deletion,
A
Alexey Milovidov 已提交
2098 2099
		  *  and the part on remote server has not yet been modified.
		  * After a while, one of the following attempts to make `fetchPart` succeed.
A
Alexey Milovidov 已提交
2100
		  */
2101
		checkPartAndAddToZooKeeper(part, ops, part_name);
M
Merge  
Michael Kolupaev 已提交
2102

2103 2104
		MergeTreeData::Transaction transaction;
		auto removed_parts = data.renameTempPartAndReplace(part, nullptr, &transaction);
M
Merge  
Michael Kolupaev 已提交
2105

2106
		getZooKeeper()->multi(ops);
2107
		transaction.commit();
2108

A
Alexey Milovidov 已提交
2109 2110
		/** If a quorum is tracked for this part, you must update it.
		  * If you do not have time, in case of losing the session, when you restart the server - see the `ReplicatedMergeTreeRestartingThread::updateQuorumIfWeHavePart` method.
2111
		  */
2112 2113
		if (quorum)
			updateQuorum(part_name);
2114

2115
		merge_selecting_event.set();
M
Merge  
Michael Kolupaev 已提交
2116

2117 2118 2119 2120 2121 2122 2123
		for (const auto & removed_part : removed_parts)
		{
			LOG_DEBUG(log, "Part " << removed_part->name << " is rendered obsolete by fetching part " << part_name);
			ProfileEvents::increment(ProfileEvents::ObsoleteReplicatedParts);
		}
	}
	else
M
Michael Kolupaev 已提交
2124
	{
2125
		Poco::File(data.getFullPath() + "detached/tmp_" + part_name).renameTo(data.getFullPath() + "detached/" + part_name);
M
Michael Kolupaev 已提交
2126 2127
	}

M
Merge  
Michael Kolupaev 已提交
2128 2129
	ProfileEvents::increment(ProfileEvents::ReplicatedPartFetches);

2130
	LOG_DEBUG(log, "Fetched part " << part_name << " from " << replica_path << (to_detached ? " (to 'detached' directory)" : ""));
A
Alexey Milovidov 已提交
2131
	return true;
M
Merge  
Michael Kolupaev 已提交
2132
}
M
Merge  
Michael Kolupaev 已提交
2133

A
Merge  
Alexey Milovidov 已提交
2134

M
Merge  
Michael Kolupaev 已提交
2135 2136
void StorageReplicatedMergeTree::shutdown()
{
2137 2138 2139 2140 2141 2142
	/** This must be done before waiting for restarting_thread.
	  * Because restarting_thread will wait for finishing of tasks in background pool,
	  *  and parts are fetched in that tasks.
	  */
	fetcher.cancel();

2143
	if (restarting_thread)
M
Merge  
Michael Kolupaev 已提交
2144
	{
2145 2146
		restarting_thread->stop();
		restarting_thread.reset();
M
Merge  
Michael Kolupaev 已提交
2147
	}
M
Merge  
Michael Kolupaev 已提交
2148

2149 2150 2151 2152 2153
	if (endpoint_holder)
	{
		endpoint_holder->cancel();
		endpoint_holder = nullptr;
	}
A
Merge  
Alexey Milovidov 已提交
2154

2155 2156 2157 2158 2159
	if (disk_space_monitor_endpoint_holder)
	{
		disk_space_monitor_endpoint_holder->cancel();
		disk_space_monitor_endpoint_holder = nullptr;
	}
A
Merge  
Alexey Milovidov 已提交
2160
	disk_space_monitor_client.cancel();
A
Merge  
Alexey Milovidov 已提交
2161

2162 2163 2164 2165 2166
	if (sharded_partition_uploader_endpoint_holder)
	{
		sharded_partition_uploader_endpoint_holder->cancel();
		sharded_partition_uploader_endpoint_holder = nullptr;
	}
A
Merge  
Alexey Arno 已提交
2167
	sharded_partition_uploader_client.cancel();
A
Merge  
Alexey Milovidov 已提交
2168

2169 2170 2171 2172 2173
	if (remote_query_executor_endpoint_holder)
	{
		remote_query_executor_endpoint_holder->cancel();
		remote_query_executor_endpoint_holder = nullptr;
	}
A
Merge  
Alexey Milovidov 已提交
2174
	remote_query_executor_client.cancel();
A
Merge  
Alexey Arno 已提交
2175 2176 2177 2178 2179 2180

	if (remote_part_checker_endpoint_holder)
	{
		remote_part_checker_endpoint_holder->cancel();
		remote_part_checker_endpoint_holder = nullptr;
	}
M
Merge  
Michael Kolupaev 已提交
2181 2182 2183
}


M
Merge  
Michael Kolupaev 已提交
2184 2185 2186 2187 2188 2189 2190 2191
StorageReplicatedMergeTree::~StorageReplicatedMergeTree()
{
	try
	{
		shutdown();
	}
	catch(...)
	{
2192
		tryLogCurrentException(__PRETTY_FUNCTION__);
M
Merge  
Michael Kolupaev 已提交
2193 2194 2195
	}
}

A
Merge  
Alexey Milovidov 已提交
2196

M
Merge  
Michael Kolupaev 已提交
2197
BlockInputStreams StorageReplicatedMergeTree::read(
2198 2199 2200 2201 2202 2203 2204
	const Names & column_names,
	ASTPtr query,
	const Context & context,
	const Settings & settings,
	QueryProcessingStage::Enum & processed_stage,
	const size_t max_block_size,
	const unsigned threads)
M
Merge  
Michael Kolupaev 已提交
2205
{
F
f1yegor 已提交
2206 2207 2208 2209
	/** The table can have two kinds of data
	  * - replicated data;
	  * - old, non-replicable data - they lie separately and their integrity is not controlled.
	  * And the table engine provides the ability to use "virtual columns".
A
Alexey Milovidov 已提交
2210 2211
	  * One of them - `_replicated` allows you to determine which part of the data is read,
	  *  or, if used in WHERE, select data from only one part.
2212 2213
	  */

M
Merge  
Michael Kolupaev 已提交
2214 2215 2216 2217 2218 2219 2220 2221
	Names virt_column_names;
	Names real_column_names;
	for (const auto & it : column_names)
		if (it == "_replicated")
			virt_column_names.push_back(it);
		else
			real_column_names.push_back(it);

2222
	auto & select = typeid_cast<const ASTSelectQuery &>(*query);
A
Merge  
Andrey Mironov 已提交
2223 2224

	/// Try transferring some condition from WHERE to PREWHERE if enabled and viable
2225
	if (settings.optimize_move_to_prewhere && select.where_expression && !select.prewhere_expression && !select.final())
2226
		MergeTreeWhereOptimizer{query, context, data, real_column_names, log};
A
Merge  
Andrey Mironov 已提交
2227

M
Merge  
Michael Kolupaev 已提交
2228
	Block virtual_columns_block;
2229
	auto column = std::make_shared<ColumnUInt8>(2);
M
Merge  
Michael Kolupaev 已提交
2230 2231 2232
	ColumnPtr column_ptr = column;
	column->getData()[0] = 0;
	column->getData()[1] = 1;
2233
	virtual_columns_block.insert(ColumnWithTypeAndName(column_ptr, std::make_shared<DataTypeUInt8>(), "_replicated"));
M
Merge  
Michael Kolupaev 已提交
2234

A
Alexey Milovidov 已提交
2235
	/// If the `_replicated` column is requested, try indexing.
M
Merge  
Michael Kolupaev 已提交
2236
	if (!virt_column_names.empty())
2237
		VirtualColumnUtils::filterBlockWithQuery(query, virtual_columns_block, context);
M
Merge  
Michael Kolupaev 已提交
2238

2239
	std::multiset<UInt8> values = VirtualColumnUtils::extractSingleValueFromBlock<UInt8>(virtual_columns_block, "_replicated");
M
Merge  
Michael Kolupaev 已提交
2240

M
Merge  
Michael Kolupaev 已提交
2241 2242
	BlockInputStreams res;

M
Merge  
Michael Kolupaev 已提交
2243 2244
	size_t part_index = 0;

A
Alexey Milovidov 已提交
2245 2246 2247 2248
	/** The `parallel_replica_offset` and `parallel_replicas_count` settings allow you to read one part of the data from one replica, and the other from other replica.
	  * For replicated data, the data is broken by the same mechanism as the SAMPLE section.
	  * And for non-replicable data, since their integrity between replicas is not controlled,
	  *  from the first (settings.parallel_replica_offset == 0) replica all data is selected, and from the rest - none.
2249 2250
	  */

2251
	if ((settings.parallel_replica_offset == 0) && unreplicated_reader && values.count(0))
M
Merge  
Michael Kolupaev 已提交
2252
	{
2253 2254
		res = unreplicated_reader->read(real_column_names, query,
										context, settings, processed_stage,
2255
										max_block_size, threads, &part_index, 0);
M
Merge  
Michael Kolupaev 已提交
2256 2257 2258 2259 2260 2261

		for (auto & virtual_column : virt_column_names)
		{
			if (virtual_column == "_replicated")
			{
				for (auto & stream : res)
2262
					stream = std::make_shared<AddingConstColumnBlockInputStream<UInt8>>(stream, std::make_shared<DataTypeUInt8>(), 0, "_replicated");
M
Merge  
Michael Kolupaev 已提交
2263 2264 2265 2266
			}
		}
	}

M
Merge  
Michael Kolupaev 已提交
2267
	if (values.count(1))
M
Merge  
Michael Kolupaev 已提交
2268
	{
A
Alexey Milovidov 已提交
2269 2270 2271 2272
		/** The `select_sequential_consistency` setting has two meanings:
		  * 1. To throw an exception if on a replica there are not all parts which have been written down on quorum of remaining replicas.
		  * 2. Do not read parts that have not yet been written to the quorum of the replicas.
		  * For this you have to synchronously go to ZooKeeper.
2273 2274 2275 2276 2277
		  */
		Int64 max_block_number_to_read = 0;
		if (settings.select_sequential_consistency)
		{
			auto zookeeper = getZooKeeper();
A
Merge  
Alexey Milovidov 已提交
2278

2279 2280 2281
			String last_part;
			zookeeper->tryGet(zookeeper_path + "/quorum/last_part", last_part);

F
f1yegor 已提交
2282
			if (!last_part.empty() && !data.getPartIfExists(last_part))	/// TODO Disable replica for distributed queries.
2283 2284 2285
				throw Exception("Replica doesn't have part " + last_part + " which was successfully written to quorum of other replicas."
					" Send query to another replica or disable 'select_sequential_consistency' setting.", ErrorCodes::REPLICA_IS_NOT_IN_QUORUM);

A
Alexey Milovidov 已提交
2286
			if (last_part.empty())  /// If no part has been written with quorum.
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
			{
				String quorum_str;
				if (zookeeper->tryGet(zookeeper_path + "/quorum/status", quorum_str))
				{
					ReplicatedMergeTreeQuorumEntry quorum_entry;
					quorum_entry.fromString(quorum_str);
					ActiveDataPartSet::Part part_info;
					ActiveDataPartSet::parsePartName(quorum_entry.part_name, part_info);
					max_block_number_to_read = part_info.left - 1;
				}
			}
			else
			{
				ActiveDataPartSet::Part part_info;
				ActiveDataPartSet::parsePartName(last_part, part_info);
				max_block_number_to_read = part_info.right;
			}
		}

		auto res2 = reader.read(
			real_column_names, query, context, settings, processed_stage, max_block_size, threads, &part_index, max_block_number_to_read);
M
Merge  
Michael Kolupaev 已提交
2308 2309 2310 2311 2312 2313

		for (auto & virtual_column : virt_column_names)
		{
			if (virtual_column == "_replicated")
			{
				for (auto & stream : res2)
2314
					stream = std::make_shared<AddingConstColumnBlockInputStream<UInt8>>(stream, std::make_shared<DataTypeUInt8>(), 1, "_replicated");
M
Merge  
Michael Kolupaev 已提交
2315 2316 2317
			}
		}

M
Merge  
Michael Kolupaev 已提交
2318
		res.insert(res.end(), res2.begin(), res2.end());
M
Merge  
Michael Kolupaev 已提交
2319 2320 2321
	}

	return res;
M
Merge  
Michael Kolupaev 已提交
2322 2323
}

A
Merge  
Alexey Milovidov 已提交
2324

A
Merge  
Alexey Milovidov 已提交
2325
void StorageReplicatedMergeTree::assertNotReadonly() const
M
Merge  
Michael Kolupaev 已提交
2326
{
2327 2328
	if (is_readonly)
		throw Exception("Table is in readonly mode", ErrorCodes::TABLE_IS_READ_ONLY);
A
Merge  
Alexey Milovidov 已提交
2329 2330 2331 2332 2333 2334
}


BlockOutputStreamPtr StorageReplicatedMergeTree::write(ASTPtr query, const Settings & settings)
{
	assertNotReadonly();
M
Merge  
Michael Kolupaev 已提交
2335

M
Merge  
Michael Kolupaev 已提交
2336
	String insert_id;
M
Merge  
Michael Kolupaev 已提交
2337 2338 2339
	if (query)
		if (ASTInsertQuery * insert = typeid_cast<ASTInsertQuery *>(&*query))
			insert_id = insert->insert_id;
M
Merge  
Michael Kolupaev 已提交
2340

2341
	return std::make_shared<ReplicatedMergeTreeBlockOutputStream>(*this, insert_id,
2342
		settings.insert_quorum, settings.insert_quorum_timeout.totalMilliseconds());
M
Merge  
Michael Kolupaev 已提交
2343
}
M
Merge  
Michael Kolupaev 已提交
2344

A
Merge  
Alexey Milovidov 已提交
2345

2346
bool StorageReplicatedMergeTree::optimize(const String & partition, bool final, const Settings & settings)
M
Merge  
Michael Kolupaev 已提交
2347
{
A
Alexey Milovidov 已提交
2348
	/// If there is nonreplicated data, then merge them first.
2349 2350 2351 2352
	if (unreplicated_data)
	{
		std::lock_guard<std::mutex> lock(unreplicated_mutex);
		unreplicated_data->clearOldParts();
M
Merge  
Michael Kolupaev 已提交
2353

2354 2355 2356
		MergeTreeData::DataPartsVector parts;
		String merged_name;
		auto always_can_merge = [](const MergeTreeData::DataPartPtr & a, const MergeTreeData::DataPartPtr & b) { return true; };
M
Merge  
Michael Kolupaev 已提交
2357

2358
		if (unreplicated_merger->selectPartsToMerge(parts, merged_name, true, 0, always_can_merge))
2359
		{
2360
			MergeList::EntryPtr merge_entry = context.getMergeList().insert(database_name, table_name, merged_name, parts);
M
Merge  
Michael Kolupaev 已提交
2361

B
Bogdan Voronin 已提交
2362 2363 2364 2365 2366 2367 2368 2369 2370
			/// Logging
			PartLogElement elem;
			Stopwatch stopwatch;
			elem.event_time = time(0);

			elem.merged_from.reserve(parts.size());
			for (const auto & part : parts)
				elem.merged_from.push_back(part->name);

2371 2372
			auto new_part = unreplicated_merger->mergePartsToTemporaryPart(
				parts, merged_name, *merge_entry, settings.min_bytes_to_use_direct_io, time(0));
M
Merge  
Michael Kolupaev 已提交
2373

2374
			unreplicated_merger->renameMergedTemporaryPart(parts, new_part, merged_name, nullptr);
B
Bogdan Voronin 已提交
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389

			std::shared_ptr<PartLog> part_log = context.getPartLog();
			if (part_log)
			{
				elem.event_type = PartLogElement::MERGE_PARTS;
				elem.size_in_bytes = new_part->size_in_bytes;

				elem.database_name = new_part->storage.getDatabaseName();
				elem.table_name = new_part->storage.getTableName();
				elem.part_name = new_part->name;

				elem.duration_ms = stopwatch.elapsed() / 1000000;

				part_log->add(elem);
			}
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
			return true;
		}
	}

	assertNotReadonly();

	if (!is_leader_node)
		throw Exception("Method OPTIMIZE for ReplicatedMergeTree could be called only on leader replica", ErrorCodes::NOT_IMPLEMENTED);

	auto can_merge = [this]
		(const MergeTreeData::DataPartPtr & left, const MergeTreeData::DataPartPtr & right)
	{
		return canMergeParts(left, right, nullptr);
	};

	pullLogsToQueue();

	ReplicatedMergeTreeLogEntryData merge_entry;
	{
		std::lock_guard<std::mutex> merge_selecting_lock(merge_selecting_mutex);

		MergeTreeData::DataPartsVector parts;
		String merged_name;

		size_t disk_space = DiskSpaceMonitor::getUnreservedFreeSpace(full_path);
M
Merge  
Michael Kolupaev 已提交
2415

2416
		bool selected = false;
2417

2418 2419
		if (partition.empty())
		{
2420
			selected = merger.selectPartsToMerge(parts, merged_name, false, data.settings.max_bytes_to_merge_at_max_space_in_pool, can_merge);
2421 2422 2423 2424 2425 2426
		}
		else
		{
			DayNum_t month = MergeTreeData::getMonthFromName(partition);
			selected = merger.selectAllPartsToMergeWithinPartition(parts, merged_name, disk_space, can_merge, month, final);
		}
2427

2428 2429 2430 2431 2432 2433
		if (!selected)
			return false;

		if (!createLogEntryToMergeParts(parts, merged_name, &merge_entry))
			return false;
	}
2434

2435
	waitForAllReplicasToProcessLogEntry(merge_entry);
M
Merge  
Michael Kolupaev 已提交
2436 2437 2438
	return true;
}

A
Merge  
Alexey Milovidov 已提交
2439

M
Merge  
Michael Kolupaev 已提交
2440
void StorageReplicatedMergeTree::alter(const AlterCommands & params,
A
Merge  
Alexey Milovidov 已提交
2441
	const String & database_name, const String & table_name, const Context & context)
M
Merge  
Michael Kolupaev 已提交
2442
{
A
Merge  
Alexey Milovidov 已提交
2443 2444
	assertNotReadonly();

M
Merge  
Michael Kolupaev 已提交
2445 2446 2447
	LOG_DEBUG(log, "Doing ALTER");

	int new_columns_version;
P
proller 已提交
2448
	String new_columns_str;
M
Merge  
Michael Kolupaev 已提交
2449 2450 2451
	zkutil::Stat stat;

	{
P
proller 已提交
2452 2453
		/// Just to read current structure. Alter will be done in separate thread.
		auto table_lock = lockStructure(false);
M
Merge  
Michael Kolupaev 已提交
2454

2455 2456
		if (is_readonly)
			throw Exception("Can't ALTER readonly table", ErrorCodes::TABLE_IS_READ_ONLY);
M
Merge  
Michael Kolupaev 已提交
2457

M
Merge  
Michael Kolupaev 已提交
2458 2459
		data.checkAlter(params);

2460 2461 2462 2463
		for (const AlterCommand & param : params)
			if (param.type == AlterCommand::MODIFY_PRIMARY_KEY)
				throw Exception("Modification of primary key is not supported for replicated tables", ErrorCodes::NOT_IMPLEMENTED);

P
proller 已提交
2464 2465 2466 2467
		NamesAndTypesList new_columns = data.getColumnsListNonMaterialized();
		NamesAndTypesList new_materialized_columns = data.materialized_columns;
		NamesAndTypesList new_alias_columns = data.alias_columns;
		ColumnDefaults new_column_defaults = data.column_defaults;
2468
		params.apply(new_columns, new_materialized_columns, new_alias_columns, new_column_defaults);
M
Merge  
Michael Kolupaev 已提交
2469

2470 2471 2472 2473
		new_columns_str = ColumnsDescription<false>{
			new_columns, new_materialized_columns,
			new_alias_columns, new_column_defaults
		}.toString();
M
Merge  
Michael Kolupaev 已提交
2474

F
f1yegor 已提交
2475
		/// Do ALTER.
2476
		getZooKeeper()->set(zookeeper_path + "/columns", new_columns_str, -1, &stat);
M
Merge  
Michael Kolupaev 已提交
2477 2478 2479 2480 2481 2482

		new_columns_version = stat.version;
	}

	LOG_DEBUG(log, "Updated columns in ZooKeeper. Waiting for replicas to apply changes.");

2483
	/// Wait until all replicas will apply ALTER.
M
Merge  
Michael Kolupaev 已提交
2484

2485
	/// Subscribe to change of columns, to finish waiting if someone will do another ALTER.
2486
	if (!getZooKeeper()->exists(zookeeper_path + "/columns", &stat, alter_query_event))
M
Merge  
Michael Kolupaev 已提交
2487
		throw Exception(zookeeper_path + "/columns doesn't exist", ErrorCodes::NOT_FOUND_NODE);
2488

M
Merge  
Michael Kolupaev 已提交
2489 2490 2491 2492 2493 2494 2495
	if (stat.version != new_columns_version)
	{
		LOG_WARNING(log, zookeeper_path + "/columns changed before this ALTER finished; "
			"overlapping ALTER-s are fine but use caution with nontransitive changes");
		return;
	}

2496
	Strings replicas = getZooKeeper()->getChildren(zookeeper_path + "/replicas");
2497 2498 2499 2500 2501 2502

	std::set<String> inactive_replicas;
	std::set<String> timed_out_replicas;

	time_t replication_alter_columns_timeout = context.getSettingsRef().replication_alter_columns_timeout;

M
Merge  
Michael Kolupaev 已提交
2503 2504 2505 2506 2507 2508
	for (const String & replica : replicas)
	{
		LOG_DEBUG(log, "Waiting for " << replica << " to apply changes");

		while (!shutdown_called)
		{
2509
			/// Replica could be inactive.
2510
			if (!getZooKeeper()->exists(zookeeper_path + "/replicas/" + replica + "/is_active"))
2511 2512 2513 2514 2515 2516 2517 2518
			{
				LOG_WARNING(log, "Replica " << replica << " is not active during ALTER query."
					" ALTER will be done asynchronously when replica becomes active.");

				inactive_replicas.emplace(replica);
				break;
			}

M
Merge  
Michael Kolupaev 已提交
2519 2520
			String replica_columns_str;

2521
			/// Replica could has been removed.
2522
			if (!getZooKeeper()->tryGet(zookeeper_path + "/replicas/" + replica + "/columns", replica_columns_str, &stat))
M
Merge  
Michael Kolupaev 已提交
2523 2524 2525 2526 2527 2528 2529
			{
				LOG_WARNING(log, replica << " was removed");
				break;
			}

			int replica_columns_version = stat.version;

2530
			/// The ALTER has been successfully applied.
M
Merge  
Michael Kolupaev 已提交
2531 2532 2533
			if (replica_columns_str == new_columns_str)
				break;

2534
			if (!getZooKeeper()->exists(zookeeper_path + "/columns", &stat))
M
Merge  
Michael Kolupaev 已提交
2535
				throw Exception(zookeeper_path + "/columns doesn't exist", ErrorCodes::NOT_FOUND_NODE);
2536

M
Merge  
Michael Kolupaev 已提交
2537 2538 2539 2540 2541 2542 2543
			if (stat.version != new_columns_version)
			{
				LOG_WARNING(log, zookeeper_path + "/columns changed before ALTER finished; "
					"overlapping ALTER-s are fine but use caution with nontransitive changes");
				return;
			}

2544
			if (!getZooKeeper()->exists(zookeeper_path + "/replicas/" + replica + "/columns", &stat, alter_query_event))
M
Merge  
Michael Kolupaev 已提交
2545 2546 2547 2548 2549 2550 2551 2552
			{
				LOG_WARNING(log, replica << " was removed");
				break;
			}

			if (stat.version != replica_columns_version)
				continue;

2553 2554 2555
			if (!replication_alter_columns_timeout)
			{
				alter_query_event->wait();
2556
				/// Everything is fine.
2557 2558 2559
			}
			else if (alter_query_event->tryWait(replication_alter_columns_timeout * 1000))
			{
2560
				/// Everything is fine.
2561 2562 2563 2564 2565 2566 2567
			}
			else
			{
				LOG_WARNING(log, "Timeout when waiting for replica " << replica << " to apply ALTER."
					" ALTER will be done asynchronously.");

				timed_out_replicas.emplace(replica);
2568
				break;
2569
			}
M
Merge  
Michael Kolupaev 已提交
2570 2571 2572
		}

		if (shutdown_called)
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
			throw Exception("Alter is not finished because table shutdown was called. Alter will be done after table restart.",
				ErrorCodes::UNFINISHED);

		if (!inactive_replicas.empty() || !timed_out_replicas.empty())
		{
			std::stringstream exception_message;
			exception_message << "Alter is not finished because";

			if (!inactive_replicas.empty())
			{
				exception_message << " some replicas are inactive right now";

				for (auto it = inactive_replicas.begin(); it != inactive_replicas.end(); ++it)
					exception_message << (it == inactive_replicas.begin() ? ": " : ", ") << *it;
			}

			if (!timed_out_replicas.empty() && !inactive_replicas.empty())
				exception_message << " and";

			if (!timed_out_replicas.empty())
			{
				exception_message << " timeout when waiting for some replicas";

				for (auto it = timed_out_replicas.begin(); it != timed_out_replicas.end(); ++it)
					exception_message << (it == timed_out_replicas.begin() ? ": " : ", ") << *it;

				exception_message << " (replication_alter_columns_timeout = " << replication_alter_columns_timeout << ")";
			}

			exception_message << ". Alter will be done asynchronously.";

			throw Exception(exception_message.str(), ErrorCodes::UNFINISHED);
		}
M
Merge  
Michael Kolupaev 已提交
2606 2607 2608 2609 2610
	}

	LOG_DEBUG(log, "ALTER finished");
}

M
Merge  
Michael Kolupaev 已提交
2611

F
f1yegor 已提交
2612
/// The name of an imaginary part covering all possible parts in the specified month with numbers in the specified range.
M
Merge  
Michael Kolupaev 已提交
2613 2614
static String getFakePartNameForDrop(const String & month_name, UInt64 left, UInt64 right)
{
F
f1yegor 已提交
2615
	/// The date range is all month long.
A
Merge  
Alexey Arno 已提交
2616
	const auto & lut = DateLUT::instance();
2617
	time_t start_time = lut.YYYYMMDDToDate(parse<UInt32>(month_name + "01"));
M
Merge  
Michael Kolupaev 已提交
2618 2619 2620
	DayNum_t left_date = lut.toDayNum(start_time);
	DayNum_t right_date = DayNum_t(static_cast<size_t>(left_date) + lut.daysInMonth(start_time) - 1);

A
Alexey Milovidov 已提交
2621
	/// Level - `right-left+1`: part could not have been formed as a result of such or more mergers.
2622
	/// TODO This is not true for parts after ATTACH.
M
Merge  
Michael Kolupaev 已提交
2623 2624 2625
	return ActiveDataPartSet::getPartName(left_date, right_date, left, right, right - left + 1);
}

A
Merge  
Alexey Milovidov 已提交
2626

2627
void StorageReplicatedMergeTree::dropUnreplicatedPartition(const Field & partition, const bool detach, const Settings & settings)
M
Merge  
Michael Kolupaev 已提交
2628
{
A
Merge  
Andrey Mironov 已提交
2629 2630 2631
	if (!unreplicated_data)
		return;

A
Alexey Milovidov 已提交
2632 2633
	/// Asks to complete merges and does not allow them to start.
	/// This protects against the "revival" of data for a remote partition after the completion of the merge.
2634
	auto merge_blocker = unreplicated_merger->cancel();
A
Merge  
Andrey Mironov 已提交
2635 2636 2637 2638 2639 2640 2641 2642 2643
	auto structure_lock = lockStructure(true);

	const DayNum_t month = MergeTreeData::getMonthDayNum(partition);

	size_t removed_parts = 0;
	MergeTreeData::DataParts parts = unreplicated_data->getDataParts();

	for (const auto & part : parts)
	{
A
Merge  
Alexey Milovidov 已提交
2644
		if (part->month != month)
A
Merge  
Andrey Mironov 已提交
2645 2646 2647 2648 2649
			continue;

		LOG_DEBUG(log, "Removing unreplicated part " << part->name);
		++removed_parts;

2650 2651 2652 2653
		if (detach)
			unreplicated_data->renameAndDetachPart(part, "");
		else
			unreplicated_data->replaceParts({part}, {}, false);
A
Merge  
Andrey Mironov 已提交
2654 2655
	}

2656
	LOG_INFO(log, (detach ? "Detached " : "Removed ") << removed_parts << " unreplicated parts inside " << applyVisitor(FieldVisitorToString(), partition) << ".");
A
Merge  
Andrey Mironov 已提交
2657 2658 2659
}


2660 2661
void StorageReplicatedMergeTree::dropPartition(
	ASTPtr query, const Field & field, bool detach, bool unreplicated, const Settings & settings)
A
Merge  
Andrey Mironov 已提交
2662 2663 2664
{
	if (unreplicated)
	{
2665
		dropUnreplicatedPartition(field, detach, settings);
A
Merge  
Andrey Mironov 已提交
2666 2667 2668
		return;
	}

A
Merge  
Alexey Milovidov 已提交
2669 2670
	assertNotReadonly();

A
Merge  
Alexey Milovidov 已提交
2671
	String month_name = MergeTreeData::getMonthName(field);
M
Merge  
Michael Kolupaev 已提交
2672 2673

	if (!is_leader_node)
2674
	{
F
f1yegor 已提交
2675
		/// Proxy request to the leader.
2676

2677
		auto live_replicas = getZooKeeper()->getChildren(zookeeper_path + "/leader_election");
2678 2679 2680
		if (live_replicas.empty())
			throw Exception("No active replicas", ErrorCodes::NO_ACTIVE_REPLICAS);

2681
		std::sort(live_replicas.begin(), live_replicas.end());
2682
		const auto leader = getZooKeeper()->get(zookeeper_path + "/leader_election/" + live_replicas.front());
2683 2684 2685 2686

		if (leader == replica_name)
			throw Exception("Leader was suddenly changed or logical error.", ErrorCodes::LEADERSHIP_CHANGED);

2687
		ReplicatedMergeTreeAddress leader_address(getZooKeeper()->get(zookeeper_path + "/replicas/" + leader + "/host"));
2688 2689 2690 2691 2692 2693 2694

		auto new_query = query->clone();
		auto & alter = typeid_cast<ASTAlterQuery &>(*new_query);

		alter.database = leader_address.database;
		alter.table = leader_address.table;

F
f1yegor 已提交
2695
		/// NOTE Works only if there is access from the default user without a password. You can fix it by adding a parameter to the server config.
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708

		Connection connection(
			leader_address.host,
			leader_address.queries_port,
			leader_address.database,
			"", "", "ClickHouse replica");

		RemoteBlockInputStream stream(connection, formattedAST(new_query), &settings);
		NullBlockOutputStream output;

		copyData(stream, output);
		return;
	}
M
Merge  
Michael Kolupaev 已提交
2709

2710 2711
	auto number_and_exists = data.getMinBlockNumberForMonth(data.getMonthFromName(month_name));

A
Alexey Milovidov 已提交
2712 2713
	/// Even if there is no data in the partition, you still need to mark the range for deletion.
	/// - Because before executing DETACH, tasks for downloading parts to this partition can be executed.
2714
	Int64 left = number_and_exists.second ? number_and_exists.first : RESERVED_BLOCK_NUMBERS;
2715

A
Alexey Milovidov 已提交
2716 2717 2718 2719 2720
	/** Let's skip one number in `block_numbers` for the month being deleted, and we will only delete parts until this number.
	  * This prohibits merges of deleted parts with the new inserted data.
	  * Invariant: merges of deleted parts with other parts do not appear in the log.
	  * NOTE: If you need to similarly support a `DROP PART` request, you will have to think of some new mechanism for it,
	  *     to guarantee this invariant.
M
Merge  
Michael Kolupaev 已提交
2721
	  */
A
Merge  
Alexey Milovidov 已提交
2722
	Int64 right;
M
Merge  
Michael Kolupaev 已提交
2723 2724

	{
A
Merge  
Alexey Arno 已提交
2725
		AbandonableLockInZooKeeper block_number_lock = allocateBlockNumber(month_name);
M
Merge  
Michael Kolupaev 已提交
2726 2727 2728 2729
		right = block_number_lock.getNumber();
		block_number_lock.unlock();
	}

F
f1yegor 已提交
2730
	/// This should never happen.
M
Merge  
Michael Kolupaev 已提交
2731
	if (right == 0)
2732
		throw Exception("Logical error: newly allocated block number is zero", ErrorCodes::LOGICAL_ERROR);
M
Merge  
Michael Kolupaev 已提交
2733 2734
	--right;

2735
	String fake_part_name = getFakePartNameForDrop(month_name, left, right);
M
Merge  
Michael Kolupaev 已提交
2736

A
Alexey Milovidov 已提交
2737 2738
	/** Forbid to choose the parts to be deleted for merging.
	  * Invariant: after the `DROP_RANGE` entry appears in the log, merge of deleted pieces will not appear in the log.
M
Merge  
Michael Kolupaev 已提交
2739 2740
	  */
	{
2741
		std::lock_guard<std::mutex> merge_selecting_lock(merge_selecting_mutex);
A
Alexey Milovidov 已提交
2742
		queue.disableMergesInRange(fake_part_name);
M
Merge  
Michael Kolupaev 已提交
2743 2744
	}

2745 2746
	LOG_DEBUG(log, "Disabled merges in range " << left << " - " << right << " for month " << month_name);

F
f1yegor 已提交
2747
	/// Finally, having achieved the necessary invariants, you can put an entry in the log.
A
Merge  
Alexey Arno 已提交
2748 2749 2750 2751 2752
	LogEntry entry;
	entry.type = LogEntry::DROP_RANGE;
	entry.source_replica = replica_name;
	entry.new_part_name = fake_part_name;
	entry.detach = detach;
2753
	String log_znode_path = getZooKeeper()->create(zookeeper_path + "/log/log-", entry.toString(), zkutil::CreateMode::PersistentSequential);
A
Merge  
Alexey Arno 已提交
2754 2755
	entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1);
	entry.create_time = time(0);
A
Merge  
Alexey Milovidov 已提交
2756

F
f1yegor 已提交
2757
	/// If necessary, wait until the operation is performed on itself or on all replicas.
A
Merge  
Alexey Arno 已提交
2758 2759 2760 2761 2762 2763 2764
	if (settings.replication_alter_partitions_sync != 0)
	{
		if (settings.replication_alter_partitions_sync == 1)
			waitForReplicaToProcessLogEntry(replica_name, entry);
		else
			waitForAllReplicasToProcessLogEntry(entry);
	}
A
Merge  
Alexey Milovidov 已提交
2765
}
A
Merge  
Alexey Milovidov 已提交
2766

A
Merge  
Alexey Arno 已提交
2767

2768
void StorageReplicatedMergeTree::attachPartition(ASTPtr query, const Field & field, bool unreplicated, bool attach_part, const Settings & settings)
M
Merge  
Michael Kolupaev 已提交
2769
{
A
Merge  
Alexey Milovidov 已提交
2770 2771
	assertNotReadonly();

A
Merge  
Alexey Milovidov 已提交
2772
	String partition;
M
Merge  
Michael Kolupaev 已提交
2773

A
Merge  
Alexey Milovidov 已提交
2774
	if (attach_part)
A
Merge  
Alexey Milovidov 已提交
2775
		partition = field.safeGet<String>();
A
Merge  
Alexey Milovidov 已提交
2776 2777
	else
		partition = MergeTreeData::getMonthName(field);
M
Merge  
Michael Kolupaev 已提交
2778 2779 2780

	String source_dir = (unreplicated ? "unreplicated/" : "detached/");

A
Alexey Milovidov 已提交
2781
	/// Let's compose a list of parts that should be added.
M
Merge  
Michael Kolupaev 已提交
2782 2783 2784 2785 2786 2787 2788 2789 2790
	Strings parts;
	if (attach_part)
	{
		parts.push_back(partition);
	}
	else
	{
		LOG_DEBUG(log, "Looking for parts for partition " << partition << " in " << source_dir);
		ActiveDataPartSet active_parts;
2791 2792

		std::set<String> part_names;
M
Merge  
Michael Kolupaev 已提交
2793 2794 2795 2796 2797
		for (Poco::DirectoryIterator it = Poco::DirectoryIterator(full_path + source_dir); it != Poco::DirectoryIterator(); ++it)
		{
			String name = it.name();
			if (!ActiveDataPartSet::isPartDirectory(name))
				continue;
2798
			if (!startsWith(name, partition))
M
Merge  
Michael Kolupaev 已提交
2799 2800 2801
				continue;
			LOG_DEBUG(log, "Found part " << name);
			active_parts.add(name);
2802
			part_names.insert(name);
M
Merge  
Michael Kolupaev 已提交
2803 2804 2805
		}
		LOG_DEBUG(log, active_parts.size() << " of them are active");
		parts = active_parts.getParts();
2806

A
Alexey Milovidov 已提交
2807
		/// Inactive parts rename so they can not be attached in case of repeated ATTACH.
2808 2809 2810 2811 2812 2813
		for (const auto & name : part_names)
		{
			String containing_part = active_parts.getContainingPart(name);
			if (!containing_part.empty() && containing_part != name)
				Poco::File(full_path + source_dir + name).renameTo(full_path + source_dir + "inactive_" + name);
		}
M
Merge  
Michael Kolupaev 已提交
2814 2815
	}

A
Alexey Milovidov 已提交
2816
	/// Synchronously check that added parts exist and are not spoiled at least on this replica. We will write checksums.txt if it does not exist.
M
Merge  
Michael Kolupaev 已提交
2817 2818 2819 2820 2821 2822 2823
	LOG_DEBUG(log, "Checking parts");
	for (const String & part : parts)
	{
		LOG_DEBUG(log, "Checking part " << part);
		data.loadPartAndFixMetadata(source_dir + part);
	}

A
Alexey Milovidov 已提交
2824 2825
	/// Select maximum free numbers to blocks to be added, less than RESERVED_BLOCK_NUMBERS.
	/// NOTE: The free numbers check does not synchronize. You can not perform multiple ATTACH/DETACH/DROP requests at the same time.
A
Merge  
Alexey Milovidov 已提交
2826
	Int64 min_used_number = RESERVED_BLOCK_NUMBERS;
2827
	DayNum_t month = MergeTreeData::getMonthFromPartPrefix(partition);
M
Merge  
Michael Kolupaev 已提交
2828

2829
	auto num_and_exists = data.getMinBlockNumberForMonth(month);
2830
	if (num_and_exists.second && num_and_exists.first < min_used_number)
2831
		min_used_number = num_and_exists.first;
M
Merge  
Michael Kolupaev 已提交
2832

A
Alexey Milovidov 已提交
2833
	/// Add entries to the log.
M
Merge  
Michael Kolupaev 已提交
2834 2835 2836 2837 2838 2839 2840 2841
	std::reverse(parts.begin(), parts.end());
	std::list<LogEntry> entries;
	zkutil::Ops ops;
	for (const String & part_name : parts)
	{
		ActiveDataPartSet::Part part;
		ActiveDataPartSet::parsePartName(part_name, part);
		part.left = part.right = --min_used_number;
2842
		part.level = 0;		/// previous level has no sense after attach.
M
Merge  
Michael Kolupaev 已提交
2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
		String new_part_name = ActiveDataPartSet::getPartName(part.left_date, part.right_date, part.left, part.right, part.level);

		LOG_INFO(log, "Will attach " << part_name << " as " << new_part_name);

		entries.emplace_back();
		LogEntry & entry = entries.back();
		entry.type = LogEntry::ATTACH_PART;
		entry.source_replica = replica_name;
		entry.source_part_name = part_name;
		entry.new_part_name = new_part_name;
		entry.attach_unreplicated = unreplicated;
2854 2855
		entry.create_time = time(0);

2856
		ops.emplace_back(std::make_unique<zkutil::Op::Create>(
2857
			zookeeper_path + "/log/log-", entry.toString(), getZooKeeper()->getDefaultACL(), zkutil::CreateMode::PersistentSequential));
M
Merge  
Michael Kolupaev 已提交
2858 2859
	}

A
Merge  
Alexey Milovidov 已提交
2860
	LOG_DEBUG(log, "Adding attaches to log");
A
Merge  
Alexey Milovidov 已提交
2861

2862
	getZooKeeper()->multi(ops);
2863

F
f1yegor 已提交
2864
	/// If necessary, wait until the operation is performed on itself or on all replicas.
2865
	if (settings.replication_alter_partitions_sync != 0)
M
Merge  
Michael Kolupaev 已提交
2866
	{
2867 2868 2869
		size_t i = 0;
		for (LogEntry & entry : entries)
		{
2870
			String log_znode_path = dynamic_cast<zkutil::Op::Create &>(*ops[i]).getPathCreated();
2871 2872 2873 2874 2875 2876
			entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1);

			if (settings.replication_alter_partitions_sync == 1)
				waitForReplicaToProcessLogEntry(replica_name, entry);
			else
				waitForAllReplicasToProcessLogEntry(entry);
M
Merge  
Michael Kolupaev 已提交
2877

2878 2879
			++i;
		}
M
Merge  
Michael Kolupaev 已提交
2880
	}
M
Merge  
Michael Kolupaev 已提交
2881 2882
}

2883 2884 2885
bool StorageReplicatedMergeTree::checkTableCanBeDropped() const
{
	/// Consider only synchronized data
2886
	context.checkTableCanBeDropped(database_name, table_name, getData().getTotalCompressedSize());
2887 2888
	return true;
}
A
Merge  
Alexey Milovidov 已提交
2889

M
Merge  
Michael Kolupaev 已提交
2890 2891
void StorageReplicatedMergeTree::drop()
{
2892 2893
	{
		auto zookeeper = tryGetZooKeeper();
A
Merge  
Alexey Milovidov 已提交
2894

2895 2896
		if (is_readonly || !zookeeper)
			throw Exception("Can't drop readonly replicated table (need to drop data in ZooKeeper as well)", ErrorCodes::TABLE_IS_READ_ONLY);
M
Merge  
Michael Kolupaev 已提交
2897

2898
		// checkTableCanBeDropped(); // uncomment to feel yourself safe
2899

2900
		shutdown();
M
Merge  
Michael Kolupaev 已提交
2901

2902 2903
		if (zookeeper->expired())
			throw Exception("Table was not dropped because ZooKeeper session has expired.", ErrorCodes::TABLE_WAS_NOT_DROPPED);
2904

2905 2906 2907
		LOG_INFO(log, "Removing replica " << replica_path);
		replica_is_active_node = nullptr;
		zookeeper->tryRemoveRecursive(replica_path);
M
Merge  
Michael Kolupaev 已提交
2908

A
Alexey Milovidov 已提交
2909
		/// Check that `zookeeper_path` exists: it could have been deleted by another replica after execution of previous line.
2910 2911 2912 2913 2914 2915
		Strings replicas;
		if (zookeeper->tryGetChildren(zookeeper_path + "/replicas", replicas) == ZOK && replicas.empty())
		{
			LOG_INFO(log, "Removing table " << zookeeper_path << " (this might take several minutes)");
			zookeeper->tryRemoveRecursive(zookeeper_path);
		}
M
Merge  
Michael Kolupaev 已提交
2916
	}
M
Merge  
Michael Kolupaev 已提交
2917 2918

	data.dropAllData();
M
Merge  
Michael Kolupaev 已提交
2919 2920
}

A
Merge  
Alexey Milovidov 已提交
2921

M
Merge  
Michael Kolupaev 已提交
2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933
void StorageReplicatedMergeTree::rename(const String & new_path_to_db, const String & new_database_name, const String & new_table_name)
{
	std::string new_full_path = new_path_to_db + escapeForFileName(new_table_name) + '/';

	data.setPath(new_full_path, true);
	if (unreplicated_data)
		unreplicated_data->setPath(new_full_path + "unreplicated/", false);

	database_name = new_database_name;
	table_name = new_table_name;
	full_path = new_full_path;

F
f1yegor 已提交
2934
	/// TODO: You can update names of loggers.
M
Merge  
Michael Kolupaev 已提交
2935 2936
}

A
Merge  
Alexey Milovidov 已提交
2937

2938 2939 2940 2941 2942 2943 2944 2945
bool StorageReplicatedMergeTree::existsNodeCached(const std::string & path)
{
	{
		std::lock_guard<std::mutex> lock(existing_nodes_cache_mutex);
		if (existing_nodes_cache.count(path))
			return true;
	}

2946
	bool res = getZooKeeper()->exists(path);
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957

	if (res)
	{
		std::lock_guard<std::mutex> lock(existing_nodes_cache_mutex);
		existing_nodes_cache.insert(path);
	}

	return res;
}


M
Merge  
Michael Kolupaev 已提交
2958 2959
AbandonableLockInZooKeeper StorageReplicatedMergeTree::allocateBlockNumber(const String & month_name)
{
A
Merge  
Alexey Milovidov 已提交
2960 2961
	auto zookeeper = getZooKeeper();

M
Merge  
Michael Kolupaev 已提交
2962
	String month_path = zookeeper_path + "/block_numbers/" + month_name;
2963
	if (!existsNodeCached(month_path))
M
Merge  
Michael Kolupaev 已提交
2964
	{
A
Alexey Milovidov 已提交
2965 2966
		/// Create a node in `block_numbers` for the month and skip over it N = RESERVED_BLOCK_NUMBERS of increment values.
		/// It is necessary that in the future, if needed, you can add data to the beginning.
M
Merge  
Michael Kolupaev 已提交
2967 2968
		zkutil::Ops ops;
		auto acl = zookeeper->getDefaultACL();
2969
		ops.emplace_back(std::make_unique<zkutil::Op::Create>(month_path, "", acl, zkutil::CreateMode::Persistent));
M
Merge  
Michael Kolupaev 已提交
2970
		for (size_t i = 0; i < RESERVED_BLOCK_NUMBERS; ++i)
M
Merge  
Michael Kolupaev 已提交
2971
		{
2972 2973
			ops.emplace_back(std::make_unique<zkutil::Op::Create>(month_path + "/skip_increment", "", acl, zkutil::CreateMode::Persistent));
			ops.emplace_back(std::make_unique<zkutil::Op::Remove>(month_path + "/skip_increment", -1));
M
Merge  
Michael Kolupaev 已提交
2974
		}
A
Alexey Milovidov 已提交
2975
		/// Ignore the errors - it could not work if someone else executed this line before us.
M
Merge  
Michael Kolupaev 已提交
2976 2977 2978 2979 2980 2981 2982 2983
		zookeeper->tryMulti(ops);
	}

	return AbandonableLockInZooKeeper(
		zookeeper_path + "/block_numbers/" + month_name + "/block-",
		zookeeper_path + "/temp", *zookeeper);
}

A
Merge  
Alexey Milovidov 已提交
2984

2985
void StorageReplicatedMergeTree::waitForAllReplicasToProcessLogEntry(const ReplicatedMergeTreeLogEntryData & entry)
M
Merge  
Michael Kolupaev 已提交
2986
{
M
Merge  
Michael Kolupaev 已提交
2987 2988
	LOG_DEBUG(log, "Waiting for all replicas to process " << entry.znode_name);

2989
	Strings replicas = getZooKeeper()->getChildren(zookeeper_path + "/replicas");
A
Merge  
Alexey Milovidov 已提交
2990 2991 2992 2993 2994 2995 2996
	for (const String & replica : replicas)
		waitForReplicaToProcessLogEntry(replica, entry);

	LOG_DEBUG(log, "Finished waiting for all replicas to process " << entry.znode_name);
}


2997
void StorageReplicatedMergeTree::waitForReplicaToProcessLogEntry(const String & replica, const ReplicatedMergeTreeLogEntryData & entry)
A
Merge  
Alexey Milovidov 已提交
2998
{
2999 3000
	String entry_str = entry.toString();
	String log_node_name;
M
Merge  
Michael Kolupaev 已提交
3001

A
Alexey Milovidov 已提交
3002 3003 3004
	/** Two types of entries can be passed to this function
	  * 1. (more often) From `log` directory - a common log, from where replicas copy entries to their queue.
	  * 2. From the `queue` directory of one of the replicas.
3005
	  *
A
Alexey Milovidov 已提交
3006 3007
	  * The problem is that the numbers (`sequential` node) of the queue elements in `log` and in `queue` do not match.
	  * (And the numbers of the same log element for different replicas do not match in the `queue`.)
3008
	  *
A
Alexey Milovidov 已提交
3009
	  * Therefore, you should consider these cases separately.
3010
	  */
M
Merge  
Michael Kolupaev 已提交
3011

A
Alexey Milovidov 已提交
3012 3013
	/** First, you need to wait until replica takes `queue` element from the `log` to its queue,
	  *  if it has not been done already (see the `pullLogsToQueue` function).
3014
	  *
A
Alexey Milovidov 已提交
3015
	  * To do this, check its node `log_pointer` - the maximum number of the element taken from `log` + 1.
3016 3017
	  */

3018
	if (startsWith(entry.znode_name, "log-"))
A
Merge  
Alexey Milovidov 已提交
3019
	{
A
Alexey Milovidov 已提交
3020
		/** In this case, just take the number from the node name `log-xxxxxxxxxx`.
3021
		  */
M
Merge  
Michael Kolupaev 已提交
3022

3023 3024
		UInt64 log_index = parse<UInt64>(entry.znode_name.substr(entry.znode_name.size() - 10));
		log_node_name = entry.znode_name;
M
Merge  
Michael Kolupaev 已提交
3025

3026 3027
		LOG_DEBUG(log, "Waiting for " << replica << " to pull " << log_node_name << " to queue");

A
Alexey Milovidov 已提交
3028
		/// Let's wait until entry gets into the replica queue.
3029 3030
		while (true)
		{
3031
			zkutil::EventPtr event = std::make_shared<Poco::Event>();
3032

3033
			String log_pointer = getZooKeeper()->get(zookeeper_path + "/replicas/" + replica + "/log_pointer", nullptr, event);
3034 3035 3036
			if (!log_pointer.empty() && parse<UInt64>(log_pointer) > log_index)
				break;

3037
			event->wait();
3038
		}
A
Merge  
Alexey Milovidov 已提交
3039
	}
3040
	else if (startsWith(entry.znode_name, "queue-"))
3041
	{
A
Alexey Milovidov 已提交
3042 3043
		/** In this case, the number of `log` node is unknown. You need look through everything from `log_pointer` to the end,
		  *  looking for a node with the same content. And if we do not find it - then the replica has already taken this entry in its queue.
3044 3045
		  */

3046
		String log_pointer = getZooKeeper()->get(zookeeper_path + "/replicas/" + replica + "/log_pointer");
M
Merge  
Michael Kolupaev 已提交
3047

3048
		Strings log_entries = getZooKeeper()->getChildren(zookeeper_path + "/log");
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
		UInt64 log_index = 0;
		bool found = false;

		for (const String & log_entry_name : log_entries)
		{
			log_index = parse<UInt64>(log_entry_name.substr(log_entry_name.size() - 10));

			if (!log_pointer.empty() && log_index < parse<UInt64>(log_pointer))
				continue;

			String log_entry_str;
3060
			bool exists = getZooKeeper()->tryGet(zookeeper_path + "/log/" + log_entry_name, log_entry_str);
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072
			if (exists && entry_str == log_entry_str)
			{
				found = true;
				log_node_name = log_entry_name;
				break;
			}
		}

		if (found)
		{
			LOG_DEBUG(log, "Waiting for " << replica << " to pull " << log_node_name << " to queue");

A
Alexey Milovidov 已提交
3073
			/// Let's wait until the entry gets into the replica queue.
3074 3075
			while (true)
			{
3076
				zkutil::EventPtr event = std::make_shared<Poco::Event>();
3077

3078
				String log_pointer = getZooKeeper()->get(zookeeper_path + "/replicas/" + replica + "/log_pointer", nullptr, event);
3079 3080 3081
				if (!log_pointer.empty() && parse<UInt64>(log_pointer) > log_index)
					break;

3082
				event->wait();
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
			}
		}
	}
	else
		throw Exception("Logical error: unexpected name of log node: " + entry.znode_name, ErrorCodes::LOGICAL_ERROR);

	if (!log_node_name.empty())
		LOG_DEBUG(log, "Looking for node corresponding to " << log_node_name << " in " << replica << " queue");
	else
		LOG_DEBUG(log, "Looking for corresponding node in " << replica << " queue");

F
f1yegor 已提交
3094
	/** Second - find the corresponding entry in the queue of the specified replica.
A
Alexey Milovidov 已提交
3095
	  * Its number may match neither the `log` node nor the `queue` node of the current replica (for us).
F
f1yegor 已提交
3096
	  * Therefore, we search by comparing the content.
3097
	  */
M
Merge  
Michael Kolupaev 已提交
3098

3099
	Strings queue_entries = getZooKeeper()->getChildren(zookeeper_path + "/replicas/" + replica + "/queue");
3100
	String queue_entry_to_wait_for;
M
Merge  
Michael Kolupaev 已提交
3101

A
Merge  
Alexey Milovidov 已提交
3102 3103 3104
	for (const String & entry_name : queue_entries)
	{
		String queue_entry_str;
3105
		bool exists = getZooKeeper()->tryGet(zookeeper_path + "/replicas/" + replica + "/queue/" + entry_name, queue_entry_str);
3106
		if (exists && queue_entry_str == entry_str)
M
Merge  
Michael Kolupaev 已提交
3107
		{
3108
			queue_entry_to_wait_for = entry_name;
A
Merge  
Alexey Milovidov 已提交
3109
			break;
M
Merge  
Michael Kolupaev 已提交
3110
		}
A
Merge  
Alexey Milovidov 已提交
3111
	}
M
Merge  
Michael Kolupaev 已提交
3112

F
f1yegor 已提交
3113
	/// While looking for the record, it has already been executed and deleted.
3114 3115
	if (queue_entry_to_wait_for.empty())
	{
A
Alexey Milovidov 已提交
3116
		LOG_DEBUG(log, "No corresponding node found. Assuming it has been already processed." " Found " << queue_entries.size() << " nodes.");
A
Merge  
Alexey Milovidov 已提交
3117
		return;
3118 3119 3120
	}

	LOG_DEBUG(log, "Waiting for " << queue_entry_to_wait_for << " to disappear from " << replica << " queue");
M
Merge  
Michael Kolupaev 已提交
3121

F
f1yegor 已提交
3122
	/// Third - wait until the entry disappears from the replica queue.
3123
	getZooKeeper()->waitForDisappear(zookeeper_path + "/replicas/" + replica + "/queue/" + queue_entry_to_wait_for);
M
Merge  
Michael Kolupaev 已提交
3124 3125 3126
}


3127
void StorageReplicatedMergeTree::getStatus(Status & res, bool with_zk_fields)
3128
{
A
Merge  
Alexey Milovidov 已提交
3129
	auto zookeeper = tryGetZooKeeper();
A
Merge  
Alexey Milovidov 已提交
3130

3131
	res.is_leader = is_leader_node;
3132
	res.is_readonly = is_readonly;
3133
	res.is_session_expired = !zookeeper || zookeeper->expired();
3134

A
Alexey Milovidov 已提交
3135
	res.queue = queue.getStatus();
3136
	res.parts_to_check = part_check_thread.size();
3137 3138 3139 3140 3141 3142

	res.zookeeper_path = zookeeper_path;
	res.replica_name = replica_name;
	res.replica_path = replica_path;
	res.columns_version = columns_version;

3143
	if (res.is_session_expired || !with_zk_fields)
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
	{
		res.log_max_index = 0;
		res.log_pointer = 0;
		res.total_replicas = 0;
		res.active_replicas = 0;
	}
	else
	{
		auto log_entries = zookeeper->getChildren(zookeeper_path + "/log");

3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
		if (log_entries.empty())
		{
			res.log_max_index = 0;
		}
		else
		{
			const String & last_log_entry = *std::max_element(log_entries.begin(), log_entries.end());
			res.log_max_index = parse<UInt64>(last_log_entry.substr(strlen("log-")));
		}

		String log_pointer_str = zookeeper->get(replica_path + "/log_pointer");
		res.log_pointer = log_pointer_str.empty() ? 0 : parse<UInt64>(log_pointer_str);
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176

		auto all_replicas = zookeeper->getChildren(zookeeper_path + "/replicas");
		res.total_replicas = all_replicas.size();

		res.active_replicas = 0;
		for (const String & replica : all_replicas)
			if (zookeeper->exists(zookeeper_path + "/replicas/" + replica + "/is_active"))
				++res.active_replicas;
	}
}

3177

3178 3179 3180
void StorageReplicatedMergeTree::getQueue(LogEntriesData & res, String & replica_name_)
{
	replica_name_ = replica_name;
A
Alexey Milovidov 已提交
3181
	queue.getEntries(res);
3182 3183 3184
}


3185
void StorageReplicatedMergeTree::getReplicaDelays(time_t & out_absolute_delay, time_t & out_relative_delay)
3186
{
3187 3188
	assertNotReadonly();

A
Alexey Milovidov 已提交
3189
	/** Absolute delay - the lag of the current replica from real time.
3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202
	  */

	time_t min_unprocessed_insert_time = 0;
	time_t max_processed_insert_time = 0;
	queue.getInsertTimes(min_unprocessed_insert_time, max_processed_insert_time);

	time_t current_time = time(0);
	out_absolute_delay = 0;
	out_relative_delay = 0;

	if (min_unprocessed_insert_time)
		out_absolute_delay = current_time - min_unprocessed_insert_time;

A
Alexey Milovidov 已提交
3203 3204
	/** Relative delay is the maximum difference of absolute delay from any other replica,
	  *  (if this replica lags behind any other live replica, or zero, otherwise).
F
f1yegor 已提交
3205
	  * Calculated only if the absolute delay is large enough.
3206 3207 3208 3209 3210 3211 3212 3213
	  */

	if (out_absolute_delay < static_cast<time_t>(data.settings.min_relative_delay_to_yield_leadership))
		return;

	auto zookeeper = getZooKeeper();

	time_t max_replicas_unprocessed_insert_time = 0;
3214 3215
	bool have_replica_with_nothing_unprocessed = false;

3216 3217 3218 3219 3220 3221 3222
	Strings replicas = zookeeper->getChildren(zookeeper_path + "/replicas");

	for (const auto & replica : replicas)
	{
		if (replica == replica_name)
			continue;

A
Alexey Milovidov 已提交
3223
		/// Skip dead replicas.
3224 3225 3226
		if (!zookeeper->exists(zookeeper_path + "/replicas/" + replica + "/is_active"))
			continue;

3227 3228 3229 3230 3231
		String value;
		if (!zookeeper->tryGet(zookeeper_path + "/replicas/" + replica + "/min_unprocessed_insert_time", value))
			continue;

		time_t replica_time = value.empty() ? 0 : parse<time_t>(value);
3232 3233 3234

		if (replica_time == 0)
		{
A
Alexey Milovidov 已提交
3235
			/** Note
F
f1yegor 已提交
3236
			  * The conclusion that the replica does not lag may be incorrect,
A
Alexey Milovidov 已提交
3237 3238 3239 3240
			  *  because the information about `min_unprocessed_insert_time` is taken
			  *  only from that part of the log that has been moved to the queue.
			  * If the replica for some reason has stalled `queueUpdatingThread`,
			  *  then `min_unprocessed_insert_time` will be incorrect.
3241 3242
			  */

3243 3244 3245 3246
			have_replica_with_nothing_unprocessed = true;
			break;
		}

3247 3248 3249
		if (replica_time > max_replicas_unprocessed_insert_time)
			max_replicas_unprocessed_insert_time = replica_time;
	}
3250

3251 3252 3253
	if (have_replica_with_nothing_unprocessed)
		out_relative_delay = out_absolute_delay;
	else if (max_replicas_unprocessed_insert_time > min_unprocessed_insert_time)
3254
		out_relative_delay = max_replicas_unprocessed_insert_time - min_unprocessed_insert_time;
3255 3256 3257
}


3258
void StorageReplicatedMergeTree::fetchPartition(const Field & partition, const String & from_, const Settings & settings)
3259
{
3260 3261
	String partition_str = MergeTreeData::getMonthName(partition);

3262
	String from = from_;
3263 3264
	if (from.back() == '/')
		from.resize(from.size() - 1);
3265

3266 3267
	LOG_INFO(log, "Will fetch partition " << partition_str << " from shard " << from_);

A
Alexey Milovidov 已提交
3268 3269
	/** Let's check that there is no such partition in the `detached` directory (where we will write the downloaded parts).
	  * Unreliable (there is a race condition) - such a partition may appear a little later.
3270 3271 3272
	  */
	Poco::DirectoryIterator dir_end;
	for (Poco::DirectoryIterator dir_it{data.getFullPath() + "detached/"}; dir_it != dir_end; ++dir_it)
3273
		if (startsWith(dir_it.name(), partition_str))
3274
			throw Exception("Detached partition " + partition_str + " already exists.", ErrorCodes::PARTITION_ALREADY_EXISTS);
3275

3276
	zkutil::Strings replicas;
3277
	zkutil::Strings active_replicas;
3278
	String best_replica;
3279

3280 3281
	{
		auto zookeeper = getZooKeeper();
3282

F
f1yegor 已提交
3283
		/// List of replicas of source shard.
3284
		replicas = zookeeper->getChildren(from + "/replicas");
3285

F
f1yegor 已提交
3286
		/// Leave only active replicas.
3287
		active_replicas.reserve(replicas.size());
3288

3289 3290 3291
		for (const String & replica : replicas)
			if (zookeeper->exists(from + "/replicas/" + replica + "/is_active"))
				active_replicas.push_back(replica);
3292

3293 3294
		if (active_replicas.empty())
			throw Exception("No active replicas for shard " + from, ErrorCodes::NO_ACTIVE_REPLICAS);
3295

A
Alexey Milovidov 已提交
3296 3297 3298 3299 3300
		/** You must select the best (most relevant) replica.
		* This is a replica with the maximum `log_pointer`, then with the minimum `queue` size.
		* NOTE This is not exactly the best criteria. It does not make sense to download old partitions,
		*  and it would be nice to be able to choose the replica closest by network.
		* NOTE Of course, there are data races here. You can solve it by retrying.
3301 3302 3303
		*/
		Int64 max_log_pointer = -1;
		UInt64 min_queue_size = std::numeric_limits<UInt64>::max();
3304

3305
		for (const String & replica : active_replicas)
3306
		{
3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
			String current_replica_path = from + "/replicas/" + replica;

			String log_pointer_str = zookeeper->get(current_replica_path + "/log_pointer");
			Int64 log_pointer = log_pointer_str.empty() ? 0 : parse<UInt64>(log_pointer_str);

			zkutil::Stat stat;
			zookeeper->get(current_replica_path + "/queue", &stat);
			size_t queue_size = stat.numChildren;

			if (log_pointer > max_log_pointer
				|| (log_pointer == max_log_pointer && queue_size < min_queue_size))
			{
				max_log_pointer = log_pointer;
				min_queue_size = queue_size;
				best_replica = replica;
			}
3323 3324 3325 3326 3327 3328 3329 3330 3331
		}
	}

	if (best_replica.empty())
		throw Exception("Logical error: cannot choose best replica.", ErrorCodes::LOGICAL_ERROR);

	LOG_INFO(log, "Found " << replicas.size() << " replicas, " << active_replicas.size() << " of them are active."
		<< " Selected " << best_replica << " to fetch from.");

3332 3333
	String best_replica_path = from + "/replicas/" + best_replica;

A
Alexey Milovidov 已提交
3334
	/// Let's find out which parts are on the best replica.
3335

A
Alexey Milovidov 已提交
3336 3337 3338
	/** Trying to download these parts.
	  * Some of them could be deleted due to the merge.
	  * In this case, update the information about the available parts and try again.
3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350
	  */

	unsigned try_no = 0;
	Strings missing_parts;
	do
	{
		if (try_no)
			LOG_INFO(log, "Some of parts (" << missing_parts.size() << ") are missing. Will try to fetch covering parts.");

		if (try_no >= 5)
			throw Exception("Too much retries to fetch parts from " + best_replica_path, ErrorCodes::TOO_MUCH_RETRIES_TO_FETCH_PARTS);

3351
		Strings parts = getZooKeeper()->getChildren(best_replica_path + "/parts");
3352 3353 3354 3355 3356 3357 3358
		ActiveDataPartSet active_parts_set(parts);
		Strings parts_to_fetch;

		if (missing_parts.empty())
		{
			parts_to_fetch = active_parts_set.getParts();

A
Alexey Milovidov 已提交
3359
			/// Leaving only the parts of the desired partition.
3360 3361
			Strings parts_to_fetch_partition;
			for (const String & part : parts_to_fetch)
3362
				if (startsWith(part, partition_str))
3363 3364 3365
					parts_to_fetch_partition.push_back(part);

			parts_to_fetch = std::move(parts_to_fetch_partition);
3366 3367 3368

			if (parts_to_fetch.empty())
				throw Exception("Partition " + partition_str + " on " + best_replica_path + " doesn't exist", ErrorCodes::PARTITION_DOESNT_EXIST);
3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
		}
		else
		{
			for (const String & missing_part : missing_parts)
			{
				String containing_part = active_parts_set.getContainingPart(missing_part);
				if (!containing_part.empty())
					parts_to_fetch.push_back(containing_part);
				else
					LOG_WARNING(log, "Part " << missing_part << " on replica " << best_replica_path << " has been vanished.");
			}
		}

		LOG_INFO(log, "Parts to fetch: " << parts_to_fetch.size());

		missing_parts.clear();
		for (const String & part : parts_to_fetch)
		{
			try
			{
3389
				fetchPart(part, best_replica_path, true, 0);
3390 3391 3392 3393 3394 3395 3396 3397 3398 3399
			}
			catch (const DB::Exception & e)
			{
				if (e.code() != ErrorCodes::RECEIVED_ERROR_FROM_REMOTE_IO_SERVER)
					throw;

				LOG_INFO(log, e.displayText());
				missing_parts.push_back(part);
			}
		}
3400

3401 3402
		++try_no;
	} while (!missing_parts.empty());
3403 3404 3405
}


3406
void StorageReplicatedMergeTree::freezePartition(const Field & partition, const String & with_name, const Settings & settings)
3407
{
A
Alexey Milovidov 已提交
3408
	/// The prefix can be arbitrary. Not necessarily a month - you can specify only a year.
3409 3410 3411 3412
	String prefix = partition.getType() == Field::Types::UInt64
		? toString(partition.get<UInt64>())
		: partition.safeGet<String>();

3413
	data.freezePartition(prefix, with_name);
3414
	if (unreplicated_data)
3415
		unreplicated_data->freezePartition(prefix, with_name);
3416 3417
}

3418

A
Merge  
Alexey Arno 已提交
3419 3420 3421
void StorageReplicatedMergeTree::reshardPartitions(ASTPtr query, const String & database_name,
	const Field & first_partition, const Field & last_partition,
	const WeightedZooKeeperPaths & weighted_zookeeper_paths,
A
Merge  
Alexey Arno 已提交
3422
	const ASTPtr & sharding_key_expr, bool do_copy, const Field & coordinator,
A
Merge  
Alexey Milovidov 已提交
3423 3424 3425 3426
	const Settings & settings)
{
	auto & resharding_worker = context.getReshardingWorker();
	if (!resharding_worker.isStarted())
A
Merge  
Alexey Arno 已提交
3427
		throw Exception{"Resharding background thread is not running", ErrorCodes::RESHARDING_NO_WORKER};
A
Merge  
Alexey Milovidov 已提交
3428

3429
	bool has_coordinator = !coordinator.isNull();
A
Merge  
Alexey Arno 已提交
3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444
	std::string coordinator_id;
	UInt64 block_number = 0;

	/// List of local partitions that need to be resharded.
	ReshardingWorker::PartitionList partition_list;

	/// The aforementioned list comprises:
	/// - first, the list of partitions that are to be resharded on more than one
	/// shard. Given any such partition, a job runs on each shard under the supervision
	/// of a coordinator;
	/// - second, the list of partitions that are to be resharded only on this shard.
	/// The iterator below indicates the beginning of the list of these so-called
	/// uncoordinated partitions.
	ReshardingWorker::PartitionList::const_iterator uncoordinated_begin;

A
Merge  
Alexey Arno 已提交
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
	std::string dumped_coordinator_state;

	auto handle_exception = [&](const std::string & msg = "")
	{
		try
		{
			/// Before jobs are submitted, errors and cancellations are both
			/// considered as errors.
			resharding_worker.setStatus(coordinator_id, ReshardingWorker::STATUS_ERROR, msg);
			dumped_coordinator_state = resharding_worker.dumpCoordinatorState(coordinator_id);
		}
		catch (...)
		{
			tryLogCurrentException(__PRETTY_FUNCTION__);
		}
	};

A
Merge  
Alexey Arno 已提交
3462
	try
A
Merge  
Alexey Arno 已提交
3463
	{
3464 3465 3466 3467 3468
		zkutil::RWLock deletion_lock;

		if (has_coordinator)
		{
			coordinator_id = coordinator.get<const String &>();
A
Alexey Arno 已提交
3469
			deletion_lock = resharding_worker.createDeletionLock(coordinator_id);
3470 3471 3472 3473
		}

		zkutil::RWLock::Guard<zkutil::RWLock::Read, zkutil::RWLock::NonBlocking> guard{deletion_lock};
		if (!deletion_lock.ownsLock())
A
Merge  
Alexey Arno 已提交
3474
			throw Exception{"Coordinator has been deleted", ErrorCodes::RESHARDING_COORDINATOR_DELETED};
3475 3476 3477 3478

		if (has_coordinator)
			block_number = resharding_worker.subscribe(coordinator_id, queryToString(query));

3479
		NameAndTypePair column_desc = ITableDeclaration::getColumn(sharding_key_expr->getColumnName());
3480
		if (column_desc.type->isNullable())
3481 3482
			throw Exception{"Sharding key must not be nullable", ErrorCodes::RESHARDING_NULLABLE_SHARDING_KEY};

A
Merge  
Alexey Arno 已提交
3483
		for (const auto & weighted_path : weighted_zookeeper_paths)
A
Merge  
Alexey Arno 已提交
3484 3485 3486
		{
			UInt64 weight = weighted_path.second;
			if (weight == 0)
A
Merge  
Alexey Arno 已提交
3487
				throw Exception{"Shard has invalid weight", ErrorCodes::INVALID_SHARD_WEIGHT};
A
Merge  
Alexey Arno 已提交
3488
		}
A
Merge  
Alexey Arno 已提交
3489

A
Merge  
Alexey Arno 已提交
3490 3491 3492 3493 3494 3495 3496
		{
			std::vector<std::string> all_paths;
			all_paths.reserve(weighted_zookeeper_paths.size());
			for (const auto & weighted_path : weighted_zookeeper_paths)
				all_paths.push_back(weighted_path.first);
			std::sort(all_paths.begin(), all_paths.end());
			if (std::adjacent_find(all_paths.begin(), all_paths.end()) != all_paths.end())
A
Merge  
Alexey Arno 已提交
3497
				throw Exception{"Shard paths must be distinct", ErrorCodes::DUPLICATE_SHARD_PATHS};
A
Merge  
Alexey Arno 已提交
3498
		}
A
Merge  
Alexey Milovidov 已提交
3499

A
Merge  
Alexey Arno 已提交
3500 3501
		DayNum_t first_partition_num = !first_partition.isNull() ? MergeTreeData::getMonthDayNum(first_partition) : DayNum_t();
		DayNum_t last_partition_num = !last_partition.isNull() ? MergeTreeData::getMonthDayNum(last_partition) : DayNum_t();
A
Merge  
Alexey Milovidov 已提交
3502

A
Merge  
Alexey Arno 已提交
3503 3504 3505
		if (first_partition_num && last_partition_num)
		{
			if (first_partition_num > last_partition_num)
A
Merge  
Alexey Arno 已提交
3506
				throw Exception{"Invalid interval of partitions", ErrorCodes::INVALID_PARTITIONS_INTERVAL};
A
Merge  
Alexey Arno 已提交
3507
		}
A
Merge  
Alexey Milovidov 已提交
3508

A
Merge  
Alexey Arno 已提交
3509
		if (!first_partition_num && last_partition_num)
A
Merge  
Alexey Arno 已提交
3510
			throw Exception{"Received invalid parameters for resharding", ErrorCodes::RESHARDING_INVALID_PARAMETERS};
A
Merge  
Alexey Milovidov 已提交
3511

A
Merge  
Alexey Arno 已提交
3512
		bool include_all = !first_partition_num;
A
Merge  
Alexey Milovidov 已提交
3513

A
Alexey Milovidov 已提交
3514
		/// Make a list of local partitions that need to be resharded.
A
Merge  
Alexey Arno 已提交
3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
		std::set<std::string> unique_partition_list;
		const MergeTreeData::DataParts & data_parts = data.getDataParts();
		for (MergeTreeData::DataParts::iterator it = data_parts.cbegin(); it != data_parts.cend(); ++it)
		{
			const MergeTreeData::DataPartPtr & current_part = *it;
			DayNum_t month = current_part->month;
			if (include_all || ((month >= first_partition_num) && (month <= last_partition_num)))
				unique_partition_list.insert(MergeTreeData::getMonthName(month));
		}

		partition_list.assign(unique_partition_list.begin(), unique_partition_list.end());

		if (partition_list.empty())
		{
3529
			if (!has_coordinator)
A
Merge  
Alexey Arno 已提交
3530
				throw Exception{"No existing partition found", ErrorCodes::PARTITION_DOESNT_EXIST};
A
Merge  
Alexey Arno 已提交
3531 3532 3533
		}
		else
		{
F
f1yegor 已提交
3534
			/// Ensure that the local and replicated table structures match.
A
Merge  
Alexey Arno 已提交
3535 3536
			enforceShardsConsistency(weighted_zookeeper_paths);

F
f1yegor 已提交
3537
			/// Verify that there is enough free space for all tasks locally and on all replicas.
A
Merge  
Alexey Arno 已提交
3538 3539 3540 3541 3542
			auto replica_to_space_info = gatherReplicaSpaceInfo(weighted_zookeeper_paths);
			for (const auto & partition : partition_list)
			{
				size_t partition_size = data.getPartitionSize(partition);
				if (!checkSpaceForResharding(replica_to_space_info, partition_size))
A
Merge  
Alexey Arno 已提交
3543 3544
					throw Exception{"Insufficient space available for resharding operation "
						"on partition " + partition, ErrorCodes::INSUFFICIENT_SPACE_FOR_RESHARDING};
A
Merge  
Alexey Arno 已提交
3545 3546 3547
			}
		}

3548
		if (has_coordinator)
A
Merge  
Alexey Arno 已提交
3549 3550 3551 3552 3553
		{
			size_t old_node_count = resharding_worker.getNodeCount(coordinator_id);
			resharding_worker.addPartitions(coordinator_id, partition_list);
			resharding_worker.waitForCheckCompletion(coordinator_id);

3554 3555
			/// At this point, all the performers know exactly the number of partitions
			/// that are to be processed.
A
Merge  
Alexey Arno 已提交
3556 3557 3558

			auto count = resharding_worker.getPartitionCount(coordinator_id);
			if (count == 0)
A
Merge  
Alexey Arno 已提交
3559
				throw Exception{"No existing partition found", ErrorCodes::PARTITION_DOESNT_EXIST};
A
Merge  
Alexey Arno 已提交
3560 3561 3562 3563 3564 3565 3566 3567 3568

			if (partition_list.empty())
			{
				/// We have no partitions, so we opt out.
				resharding_worker.unsubscribe(coordinator_id);
			}

			resharding_worker.waitForOptOutCompletion(coordinator_id, old_node_count);

3569 3570
			/// At this point, all the performers that actually have some partitions
			/// are in a coherent state.
A
Merge  
Alexey Arno 已提交
3571 3572 3573 3574 3575 3576 3577 3578

			if (partition_list.empty())
				return;

			if (resharding_worker.getNodeCount(coordinator_id) == 1)
			{
				/// Degenerate case: we are the only participating node.
				/// All our jobs are uncoordinated.
A
Alexey Arno 已提交
3579
				deletion_lock.release();
A
Merge  
Alexey Arno 已提交
3580 3581 3582 3583 3584 3585 3586 3587 3588
				resharding_worker.deleteCoordinator(coordinator_id);
				uncoordinated_begin = partition_list.cbegin();
			}
			else
			{
				/// Split the list of partitions into a list of coordinated jobs
				/// and a list of uncoordinated jobs.
				uncoordinated_begin = resharding_worker.categorizePartitions(coordinator_id, partition_list);
			}
A
Merge  
Alexey Milovidov 已提交
3589

A
Merge  
Alexey Arno 已提交
3590 3591 3592
			if (uncoordinated_begin == partition_list.cbegin())
			{
				coordinator_id.clear();
3593
				has_coordinator = false;
A
Merge  
Alexey Arno 已提交
3594 3595 3596 3597 3598 3599 3600
			}
		}
		else
		{
			/// All our jobs are uncoordinated.
			uncoordinated_begin = partition_list.cbegin();
		}
A
Merge  
Alexey Milovidov 已提交
3601

A
Merge  
Alexey Arno 已提交
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612
		/// First, submit coordinated background resharding jobs.
		for (auto it = partition_list.cbegin(); it != uncoordinated_begin; ++it)
		{
			ReshardingJob job;
			job.database_name = database_name;
			job.table_name = getTableName();
			job.partition = *it;
			job.paths = weighted_zookeeper_paths;
			job.sharding_key_expr = sharding_key_expr;
			job.coordinator_id = coordinator_id;
			job.block_number = block_number;
A
Merge  
Alexey Arno 已提交
3613
			job.do_copy = do_copy;
A
Merge  
Alexey Milovidov 已提交
3614

A
Merge  
Alexey Arno 已提交
3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
			resharding_worker.submitJob(job);
		}

		/// Then, submit uncoordinated background resharding jobs.
		for (auto it = uncoordinated_begin; it != partition_list.cend(); ++it)
		{
			ReshardingJob job;
			job.database_name = database_name;
			job.table_name = getTableName();
			job.partition = *it;
			job.paths = weighted_zookeeper_paths;
			job.sharding_key_expr = sharding_key_expr;
A
Merge  
Alexey Arno 已提交
3627
			job.do_copy = do_copy;
A
Merge  
Alexey Arno 已提交
3628 3629 3630 3631 3632

			resharding_worker.submitJob(job);
		}
	}
	catch (const Exception & ex)
A
Merge  
Alexey Milovidov 已提交
3633
	{
3634
		if (has_coordinator)
A
Merge  
Alexey Arno 已提交
3635 3636 3637 3638 3639 3640
		{
			if ((ex.code() == ErrorCodes::RESHARDING_NO_SUCH_COORDINATOR) ||
				(ex.code() == ErrorCodes::RESHARDING_NO_COORDINATOR_MEMBERSHIP) ||
				(ex.code() == ErrorCodes::RESHARDING_ALREADY_SUBSCRIBED) ||
				(ex.code() == ErrorCodes::RESHARDING_INVALID_QUERY))
			{
3641 3642 3643 3644 3645 3646
				/// Any of these errors occurs only when a user attempts to send
				/// manually a query ALTER TABLE ... RESHARD ... that specifies
				/// the parameter COORDINATE WITH, in spite of the fact that no user
				/// should ever use this parameter. Since taking into account such
				/// errors may botch an ongoing distributed resharding job, we
				/// intentionally ignore them.
A
Merge  
Alexey Arno 已提交
3647
			}
3648
			else if ((ex.code() == ErrorCodes::RWLOCK_NO_SUCH_LOCK) ||
A
Merge  
Alexey Arno 已提交
3649
				(ex.code() == ErrorCodes::NO_SUCH_BARRIER) ||
3650
				(ex.code() == ErrorCodes::RESHARDING_COORDINATOR_DELETED))
3651
			{
3652 3653
				/// For any reason the coordinator has disappeared. So obviously
				/// we don't have any means to notify other nodes of an error.
A
Merge  
Alexey Arno 已提交
3654
			}
3655 3656 3657 3658
			else if (ex.code() == ErrorCodes::RESHARDING_COORDINATOR_DELETED)
			{
				/// nothing here
			}
A
Merge  
Alexey Arno 已提交
3659
			else
3660
			{
A
Merge  
Alexey Arno 已提交
3661
				handle_exception(ex.message());
3662 3663
				LOG_ERROR(log, dumped_coordinator_state);
			}
A
Merge  
Alexey Arno 已提交
3664 3665 3666
		}

		throw;
A
Merge  
Alexey Milovidov 已提交
3667
	}
A
Merge  
Alexey Arno 已提交
3668 3669 3670 3671 3672 3673 3674 3675 3676
	catch (const std::exception & ex)
	{
		if (has_coordinator)
		{
			handle_exception(ex.what());
			LOG_ERROR(log, dumped_coordinator_state);
		}
		throw;
	}
A
Merge  
Alexey Arno 已提交
3677 3678
	catch (...)
	{
3679
		if (has_coordinator)
A
Merge  
Alexey Arno 已提交
3680
		{
A
Merge  
Alexey Arno 已提交
3681 3682
			handle_exception();
			LOG_ERROR(log, dumped_coordinator_state);
A
Merge  
Alexey Arno 已提交
3683 3684 3685
		}
		throw;
	}
A
Merge  
Alexey Milovidov 已提交
3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698
}

void StorageReplicatedMergeTree::enforceShardsConsistency(const WeightedZooKeeperPaths & weighted_zookeeper_paths)
{
	const auto & columns = getColumnsList();

	auto zookeeper = getZooKeeper();

	for (const auto & weighted_path : weighted_zookeeper_paths)
	{
		auto columns_str = zookeeper->get(weighted_path.first + "/columns");
		auto columns_desc = ColumnsDescription<true>::parse(columns_str);

3699
		if (!std::equal(columns.begin(), columns.end(), columns_desc.columns.begin()))
A
Merge  
Alexey Arno 已提交
3700
			throw Exception{"Table is inconsistent accross shards", ErrorCodes::INCONSISTENT_TABLE_ACCROSS_SHARDS};
A
Merge  
Alexey Milovidov 已提交
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714
	}
}

StorageReplicatedMergeTree::ReplicaToSpaceInfo
StorageReplicatedMergeTree::gatherReplicaSpaceInfo(const WeightedZooKeeperPaths & weighted_zookeeper_paths)
{
	struct TaskInfo
	{
		TaskInfo(const std::string & replica_path_,
			const ReplicatedMergeTreeAddress & address_)
			: replica_path(replica_path_), address(address_)
		{
		}

3715 3716 3717 3718 3719 3720
		TaskInfo(const TaskInfo &) = delete;
		TaskInfo & operator=(const TaskInfo &) = delete;

		TaskInfo(TaskInfo &&) = default;
		TaskInfo & operator=(TaskInfo &&) = default;

A
Merge  
Alexey Milovidov 已提交
3721 3722 3723 3724 3725 3726 3727 3728 3729
		std::string replica_path;
		ReplicatedMergeTreeAddress address;
	};

	using TaskInfoList = std::vector<TaskInfo>;
	TaskInfoList task_info_list;

	ReplicaToSpaceInfo replica_to_space_info;

F
f1yegor 已提交
3730
	/// Now we check for free space on the remote replicas.
A
Merge  
Alexey Milovidov 已提交
3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
	UInt64 total_weight = 0;
	for (const auto & weighted_path : weighted_zookeeper_paths)
	{
		UInt64 weight = weighted_path.second;
		total_weight += weight;
	}

	auto & local_space_info = replica_to_space_info[replica_path];
	local_space_info.factor = 1.1;
	local_space_info.available_size = DiskSpaceMonitor::getUnreservedFreeSpace(full_path);

	for (const auto & weighted_path : weighted_zookeeper_paths)
	{
3744 3745
		auto zookeeper = getZooKeeper();

A
Merge  
Alexey Milovidov 已提交
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766
		const auto & path = weighted_path.first;
		UInt64 weight = weighted_path.second;

		long double factor = (weight / static_cast<long double>(total_weight)) * 1.1;

		auto children = zookeeper->getChildren(path + "/replicas");
		for (const auto & child : children)
		{
			const std::string child_replica_path = path + "/replicas/" + child;
			if (child_replica_path != replica_path)
			{
				replica_to_space_info[child_replica_path].factor = factor;

				auto host = zookeeper->get(child_replica_path + "/host");
				ReplicatedMergeTreeAddress host_desc(host);

				task_info_list.emplace_back(child_replica_path, host_desc);
			}
		}
	}

3767
	ThreadPool pool(task_info_list.size());
A
Merge  
Alexey Milovidov 已提交
3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779

	using Tasks = std::vector<std::packaged_task<size_t()> >;
	Tasks tasks(task_info_list.size());

	try
	{
		for (size_t i = 0; i < task_info_list.size(); ++i)
		{
			const auto & entry = task_info_list[i];
			const auto & replica_path = entry.replica_path;
			const auto & address = entry.address;

A
Merge  
Alexey Arno 已提交
3780
			InterserverIOEndpointLocation location{replica_path, address.host, address.replication_port};
A
Merge  
Alexey Milovidov 已提交
3781

A
Merge  
Alexey Arno 已提交
3782 3783
			tasks[i] = Tasks::value_type{std::bind(&RemoteDiskSpaceMonitor::Client::getFreeSpace,
				&disk_space_monitor_client, location)};
A
Merge  
Alexey Milovidov 已提交
3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807
			pool.schedule([i, &tasks]{ tasks[i](); });
		}
	}
	catch (...)
	{
		pool.wait();
		throw;
	}

	pool.wait();

	for (size_t i = 0; i < task_info_list.size(); ++i)
	{
		size_t remote_available_size = tasks[i].get_future().get();
		const auto & remote_replica_path = task_info_list[i].replica_path;
		replica_to_space_info.at(remote_replica_path).available_size = remote_available_size;
	}

	return replica_to_space_info;
}

bool StorageReplicatedMergeTree::checkSpaceForResharding(const ReplicaToSpaceInfo & replica_to_space_info,
	size_t partition_size) const
{
A
Alexey Milovidov 已提交
3808
	/// Safe multiplication.
A
Merge  
Alexey Milovidov 已提交
3809 3810 3811 3812 3813 3814 3815 3816
	auto scale_size = [](size_t size, long double factor)
	{
		feclearexcept(FE_OVERFLOW);
		feclearexcept(FE_UNDERFLOW);

		long double result = static_cast<long double>(size) * factor;

		if ((fetestexcept(FE_OVERFLOW) != 0) || (fetestexcept(FE_UNDERFLOW) != 0))
A
Merge  
Alexey Arno 已提交
3817
			throw Exception{"StorageReplicatedMergeTree: floating point exception triggered", ErrorCodes::LOGICAL_ERROR};
A
Merge  
Alexey Milovidov 已提交
3818
		if (result > static_cast<long double>(std::numeric_limits<size_t>::max()))
A
Merge  
Alexey Arno 已提交
3819
			throw Exception{"StorageReplicatedMergeTree: integer overflow", ErrorCodes::LOGICAL_ERROR};
A
Merge  
Alexey Milovidov 已提交
3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833

		return static_cast<size_t>(result);
	};

	for (const auto & entry : replica_to_space_info)
	{
		const auto & info = entry.second;
		size_t required_size = scale_size(partition_size, info.factor);
		if (info.available_size < required_size)
			return false;
	}

	return true;
}
3834

M
Merge  
Michael Kolupaev 已提交
3835
}