forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathDatabaseReplicated.cpp
More file actions
2411 lines (2032 loc) · 102 KB
/
Copy pathDatabaseReplicated.cpp
File metadata and controls
2411 lines (2032 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <Core/UUID.h>
#include <DataTypes/DataTypeString.h>
#include <atomic>
#include <tuple>
#include <utility>
#include <Backups/IRestoreCoordination.h>
#include <Backups/RestorerFromBackup.h>
#include <Core/ServerSettings.h>
#include <Core/Settings.h>
#include <Databases/DDLDependencyVisitor.h>
#include <Databases/DatabaseFactory.h>
#include <Databases/DatabaseReplicated.h>
#include <Databases/DatabaseReplicatedWorker.h>
#include <Databases/TablesDependencyGraph.h>
#include <Databases/enableAllExperimentalSettings.h>
#include <IO/ReadBufferFromFile.h>
#include <IO/ReadBufferFromString.h>
#include <IO/ReadHelpers.h>
#include <IO/ReadSettings.h>
#include <IO/SharedThreadPools.h>
#include <IO/WriteHelpers.h>
#include <Interpreters/Cluster.h>
#include <Interpreters/Context.h>
#include <Interpreters/DDLTask.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Interpreters/InterpreterCreateQuery.h>
#include <Interpreters/InterpreterSetQuery.h>
#include <Interpreters/NormalizeSelectWithUnionQueryVisitor.h>
#include <Interpreters/ReplicatedDatabaseQueryStatusSource.h>
#include <Interpreters/evaluateConstantExpression.h>
#include <Interpreters/executeDDLQueryOnCluster.h>
#include <Interpreters/executeQuery.h>
#include <Parsers/ASTAlterQuery.h>
#include <Parsers/ASTDeleteQuery.h>
#include <Parsers/ASTUpdateQuery.h>
#include <Parsers/ASTDropQuery.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ParserCreateQuery.h>
#include <Parsers/parseQuery.h>
#include <Processors/Sinks/EmptySink.h>
#include <Storages/AlterCommands.h>
#include <Storages/StorageKeeperMap.h>
#include <base/chrono_io.h>
#include <base/defines.h>
#include <base/getFQDNOrHostName.h>
#include <Common/Exception.h>
#include <Common/FailPoint.h>
#include <Common/Macros.h>
#include <Common/OpenTelemetryTraceContext.h>
#include <Common/PoolId.h>
#include <Common/SipHash.h>
#include <Common/ZooKeeper/IKeeper.h>
#include <Common/ZooKeeper/KeeperException.h>
#include <Common/ZooKeeper/Types.h>
#include <Common/ZooKeeper/ZooKeeper.h>
#include <Common/threadPoolCallbackRunner.h>
#include <Common/thread_local_rng.h>
namespace DB
{
namespace Setting
{
extern const SettingsUInt64 database_replicated_allow_replicated_engine_arguments;
extern const SettingsBool database_replicated_always_detach_permanently;
extern const SettingsUInt64 max_parser_backtracks;
extern const SettingsUInt64 max_parser_depth;
extern const SettingsUInt64 max_query_size;
extern const SettingsDistributedDDLOutputMode distributed_ddl_output_mode;
extern const SettingsInt64 distributed_ddl_task_timeout;
extern const SettingsBool throw_on_unsupported_query_inside_transaction;
extern const SettingsSetOperationMode union_default_mode;
}
namespace ServerSetting
{
extern const ServerSettingsBool database_replicated_allow_detach_permanently;
extern const ServerSettingsUInt32 max_database_replicated_create_table_thread_pool_size;
}
namespace DatabaseReplicatedSetting
{
extern const DatabaseReplicatedSettingsString collection_name;
extern const DatabaseReplicatedSettingsFloat max_broken_tables_ratio;
extern const DatabaseReplicatedSettingsUInt64 max_replication_lag_to_enqueue;
extern const DatabaseReplicatedSettingsNonZeroUInt64 logs_to_keep;
}
namespace ErrorCodes
{
extern const int NO_ZOOKEEPER;
extern const int LOGICAL_ERROR;
extern const int BAD_ARGUMENTS;
extern const int REPLICA_ALREADY_EXISTS;
extern const int DATABASE_REPLICATION_FAILED;
extern const int UNKNOWN_DATABASE;
extern const int UNKNOWN_TABLE;
extern const int NOT_IMPLEMENTED;
extern const int INCORRECT_QUERY;
extern const int ALL_CONNECTION_TRIES_FAILED;
extern const int NO_ACTIVE_REPLICAS;
extern const int CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT;
extern const int CANNOT_RESTORE_TABLE;
extern const int QUERY_IS_PROHIBITED;
extern const int SUPPORT_IS_DISABLED;
extern const int ASYNC_LOAD_CANCELED;
extern const int SYNTAX_ERROR;
}
namespace FailPoints
{
extern const char database_replicated_startup_pause[];
}
static constexpr const char * REPLICATED_DATABASE_MARK = "DatabaseReplicated";
static constexpr const char * DROPPED_MARK = "DROPPED";
static constexpr const char * FIRST_REPLICA_DATABASE_NAME = "first_replica_database_name";
ZooKeeperPtr DatabaseReplicated::getZooKeeper() const
{
return getContext()->getZooKeeper();
}
static inline String getHostID(ContextPtr global_context, const UUID & db_uuid, bool secure)
{
UInt16 port = secure ? global_context->getTCPPortSecure().value_or(DBMS_DEFAULT_SECURE_PORT) : global_context->getTCPPort();
return Cluster::Address::toString(getFQDNOrHostName(), port) + ':' + toString(db_uuid);
}
// Return <address, port, uuid>
static inline std::tuple<String, UInt16, UUID> parseHostID(const String & content)
{
auto pos = content.find_last_of(':');
if (pos == std::string::npos || pos + 1 >= content.size())
throw Exception(ErrorCodes::SYNTAX_ERROR, "Invalid host ID '{}'", content);
auto [address, port] = Cluster::Address::fromString(content.substr(0, pos));
UUID db_uuid;
if (!tryParse(db_uuid, content.substr(pos + 1)))
throw Exception(ErrorCodes::SYNTAX_ERROR, "Invalid host ID '{}'", content);
return {address, port, db_uuid};
}
static inline UInt64 getMetadataHash(const String & table_name, const String & metadata)
{
SipHash hash;
hash.update(table_name);
hash.update(metadata);
return hash.get64();
}
DatabaseReplicated::~DatabaseReplicated() = default;
DatabaseReplicated::DatabaseReplicated(
const String & name_,
const String & metadata_path_,
UUID uuid,
const String & zookeeper_path_,
const String & shard_name_,
const String & replica_name_,
DatabaseReplicatedSettings db_settings_,
ContextPtr context_)
: DatabaseAtomic(name_, metadata_path_, uuid, "DatabaseReplicated (" + name_ + ")", context_)
, zookeeper_path(zookeeper_path_)
, shard_name(shard_name_)
, replica_name(replica_name_)
, db_settings(std::move(db_settings_))
, tables_metadata_digest(0)
{
LOG_INFO(log, "DatabaseReplicatedSettings {}", db_settings.toString());
if (zookeeper_path.empty() || shard_name.empty() || replica_name.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "ZooKeeper path, shard and replica names must be non-empty");
if (shard_name.contains('/') || replica_name.contains('/'))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Shard and replica names should not contain '/'");
if (shard_name.contains('|') || replica_name.contains('|'))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Shard and replica names should not contain '|'");
if (zookeeper_path.back() == '/')
zookeeper_path.resize(zookeeper_path.size() - 1);
/// If zookeeper chroot prefix is used, path should start with '/', because chroot concatenates without it.
if (zookeeper_path.front() != '/')
zookeeper_path = "/" + zookeeper_path;
if (!db_settings[DatabaseReplicatedSetting::collection_name].value.empty())
fillClusterAuthInfo(db_settings[DatabaseReplicatedSetting::collection_name].value, context_->getConfigRef());
replica_group_name = context_->getConfigRef().getString("replica_group_name", "");
if (!replica_group_name.empty() && database_name.starts_with(DatabaseReplicated::ALL_GROUPS_CLUSTER_PREFIX))
{
auto constexpr message_format_string = "There's a Replicated database with a name starting from '{}', "
"and replica_group_name is configured. It may cause collisions in cluster names.";
context_->addOrUpdateWarningMessage(
Context::WarningType::REPLICATED_DB_WITH_ALL_GROUPS_CLUSTER_PREFIX,
PreformattedMessage::create(message_format_string, ALL_GROUPS_CLUSTER_PREFIX));
}
}
String DatabaseReplicated::getFullReplicaName(const String & shard, const String & replica)
{
return shard + '|' + replica;
}
String DatabaseReplicated::getFullReplicaName() const
{
return getFullReplicaName(shard_name, replica_name);
}
std::pair<String, String> DatabaseReplicated::parseFullReplicaName(const String & name)
{
String shard;
String replica;
auto pos = name.find('|');
if (pos == std::string::npos || name.find('|', pos + 1) != std::string::npos)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Incorrect replica identifier: {}", name);
shard = name.substr(0, pos);
replica = name.substr(pos + 1);
return {shard, replica};
}
ClusterPtr DatabaseReplicated::tryGetCluster() const
{
std::lock_guard lock{mutex};
if (cluster)
return cluster;
/// Database is probably not created or not initialized yet, it's ok to return nullptr
if (is_readonly)
return cluster;
try
{
/// A quick fix for stateless tests with DatabaseReplicated. Its ZK
/// node can be destroyed at any time. If another test lists
/// system.clusters to get client command line suggestions, it will
/// get an error when trying to get the info about DB from ZK.
/// Just ignore these inaccessible databases. A good example of a
/// failing test is `01526_client_start_and_exit`.
cluster = getClusterImpl();
}
catch (...)
{
tryLogCurrentException(log);
}
return cluster;
}
ClusterPtr DatabaseReplicated::tryGetAllGroupsCluster() const
{
std::lock_guard lock{mutex};
if (replica_group_name.empty())
return nullptr;
if (cluster_all_groups)
return cluster_all_groups;
/// Database is probably not created or not initialized yet, it's ok to return nullptr
if (is_readonly)
return cluster_all_groups;
try
{
cluster_all_groups = getClusterImpl(/*all_groups*/ true);
}
catch (...)
{
tryLogCurrentException(log);
}
return cluster_all_groups;
}
void DatabaseReplicated::setCluster(ClusterPtr && new_cluster, bool all_groups)
{
std::lock_guard lock{mutex};
if (all_groups)
cluster_all_groups = std::move(new_cluster);
else
cluster = std::move(new_cluster);
}
ClusterPtr DatabaseReplicated::getClusterImpl(bool all_groups) const
{
Strings unfiltered_hosts;
Strings hosts;
Strings host_ids;
auto zookeeper = getContext()->getZooKeeper();
constexpr int max_retries = 10;
int iteration = 0;
bool success = false;
while (++iteration <= max_retries)
{
host_ids.resize(0);
Coordination::Stat stat;
unfiltered_hosts = zookeeper->getChildren(zookeeper_path + "/replicas", &stat);
if (unfiltered_hosts.empty())
throw Exception(ErrorCodes::NO_ACTIVE_REPLICAS, "No replicas of database {} found. "
"It's possible if the first replica is not fully created yet "
"or if the last replica was just dropped or due to logical error", zookeeper_path);
if (all_groups)
{
hosts = unfiltered_hosts;
}
else
{
hosts.clear();
std::vector<String> paths;
for (const auto & host : unfiltered_hosts)
paths.push_back(zookeeper_path + "/replicas/" + host + "/replica_group");
auto replica_groups = zookeeper->tryGet(paths);
for (size_t i = 0; i < paths.size(); ++i)
{
if (replica_groups[i].data == replica_group_name)
hosts.push_back(unfiltered_hosts[i]);
}
}
Int32 cversion = stat.cversion;
::sort(hosts.begin(), hosts.end());
std::vector<String> host_paths;
host_paths.reserve(hosts.size());
host_ids.reserve(hosts.size());
for (const auto & host : hosts)
host_paths.emplace_back(zookeeper_path + "/replicas/" + host);
auto host_result = zookeeper->tryGet(host_paths);
success = true;
for (size_t i = 0; i < hosts.size(); ++i)
{
auto & res = host_result[i];
if (res.error != Coordination::Error::ZOK)
success = false;
host_ids.emplace_back(std::move(res.data));
}
zookeeper->get(zookeeper_path + "/replicas", &stat);
if (cversion != stat.cversion)
success = false;
if (success)
break;
}
if (!success)
throw Exception(ErrorCodes::ALL_CONNECTION_TRIES_FAILED, "Cannot get consistent cluster snapshot,"
"because replicas are created or removed concurrently");
LOG_TRACE(log, "Got a list of hosts after {} iterations. All hosts: [{}], filtered: [{}], ids: [{}]", iteration,
fmt::join(unfiltered_hosts, ", "), fmt::join(hosts, ", "), fmt::join(host_ids, ", "));
assert(!hosts.empty());
assert(hosts.size() == host_ids.size());
String current_shard;
std::vector<std::vector<DatabaseReplicaInfo>> shards;
for (size_t i = 0; i < hosts.size(); ++i)
{
const auto & id = host_ids[i];
if (id == DROPPED_MARK)
continue;
auto [shard, replica] = parseFullReplicaName(hosts[i]);
auto pos = id.rfind(':');
String host_port = id.substr(0, pos);
if (shard != current_shard)
{
current_shard = shard;
shards.emplace_back();
}
String hostname = unescapeForFileName(host_port);
shards.back().push_back(DatabaseReplicaInfo{std::move(hostname), std::move(shard), std::move(replica)});
}
if (shards.empty())
throw Exception(ErrorCodes::ALL_CONNECTION_TRIES_FAILED, "No active replicas");
UInt16 default_port;
if (cluster_auth_info.cluster_secure_connection)
default_port = getContext()->getTCPPortSecure().value_or(DBMS_DEFAULT_SECURE_PORT);
else
default_port = getContext()->getTCPPort();
bool treat_local_as_remote = false;
bool treat_local_port_as_remote = getContext()->getApplicationType() == Context::ApplicationType::LOCAL;
String cluster_name = TSA_SUPPRESS_WARNING_FOR_READ(database_name); /// FIXME
if (all_groups)
cluster_name = ALL_GROUPS_CLUSTER_PREFIX + cluster_name;
ClusterConnectionParameters params{
cluster_auth_info.cluster_username,
cluster_auth_info.cluster_password,
default_port,
treat_local_as_remote,
treat_local_port_as_remote,
cluster_auth_info.cluster_secure_connection,
/* bind_host= */ "",
Priority{1},
cluster_name,
cluster_auth_info.cluster_secret};
return std::make_shared<Cluster>(getContext()->getSettingsRef(), shards, params);
}
ReplicasInfo DatabaseReplicated::tryGetReplicasInfo(const ClusterPtr & cluster_) const
{
Strings paths;
paths.emplace_back(fs::path(zookeeper_path) / "max_log_ptr");
const auto & addresses_with_failover = cluster_->getShardsAddresses();
const auto & shards_info = cluster_->getShardsInfo();
for (size_t shard_index = 0; shard_index < shards_info.size(); ++shard_index)
{
for (const auto & replica : addresses_with_failover[shard_index])
{
String full_name = getFullReplicaName(replica.database_shard_name, replica.database_replica_name);
paths.emplace_back(fs::path(zookeeper_path) / "replicas" / full_name / "active");
paths.emplace_back(fs::path(zookeeper_path) / "replicas" / full_name / "log_ptr");
}
}
try
{
auto current_zookeeper = getZooKeeper();
auto zk_res = current_zookeeper->tryGet(paths);
auto max_log_ptr_zk = zk_res[0];
if (max_log_ptr_zk.error != Coordination::Error::ZOK)
throw Coordination::Exception(max_log_ptr_zk.error);
UInt32 max_log_ptr = parse<UInt32>(max_log_ptr_zk.data);
ReplicasInfo replicas_info;
replicas_info.resize((zk_res.size() - 1) / 2);
size_t global_replica_index = 0;
for (size_t shard_index = 0; shard_index < shards_info.size(); ++shard_index)
{
for (const auto & replica : addresses_with_failover[shard_index])
{
auto replica_active = zk_res[2 * global_replica_index + 1];
auto replica_log_ptr = zk_res[2 * global_replica_index + 2];
UInt64 recovery_time = 0;
{
std::lock_guard lock(ddl_worker_mutex);
if (replica.is_local && ddl_worker)
recovery_time = ddl_worker->getCurrentInitializationDurationMs();
}
replicas_info[global_replica_index] = ReplicaInfo{
.is_active = replica_active.error == Coordination::Error::ZOK,
.unsynced_after_recovery = ddl_worker && ddl_worker->isUnsyncedAfterRecovery(),
.replication_lag = replica_log_ptr.error != Coordination::Error::ZNONODE ? std::optional(max_log_ptr - parse<UInt32>(replica_log_ptr.data)) : std::nullopt,
.recovery_time = recovery_time,
};
++global_replica_index;
}
}
return replicas_info;
}
catch (...)
{
tryLogCurrentException(log);
return {};
}
}
void DatabaseReplicated::fillClusterAuthInfo(String collection_name, const Poco::Util::AbstractConfiguration & config_ref)
{
const auto & config_prefix = fmt::format("named_collections.{}", collection_name);
if (!config_ref.has(config_prefix))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "There is no collection named `{}` in config", collection_name);
cluster_auth_info.cluster_username = config_ref.getString(config_prefix + ".cluster_username", "");
cluster_auth_info.cluster_password = config_ref.getString(config_prefix + ".cluster_password", "");
cluster_auth_info.cluster_secret = config_ref.getString(config_prefix + ".cluster_secret", "");
cluster_auth_info.cluster_secure_connection = config_ref.getBool(config_prefix + ".cluster_secure_connection", false);
}
void DatabaseReplicated::tryConnectToZooKeeperAndInitDatabase(LoadingStrictnessLevel mode)
{
try
{
if (!getContext()->hasZooKeeper())
{
throw Exception(ErrorCodes::NO_ZOOKEEPER, "Can't create replicated database without ZooKeeper");
}
auto current_zookeeper = getContext()->getZooKeeper();
if (!current_zookeeper->exists(zookeeper_path))
{
/// Create new database, multiple nodes can execute it concurrently
createDatabaseNodesInZooKeeper(current_zookeeper);
}
replica_path = fs::path(zookeeper_path) / "replicas" / getFullReplicaName();
bool is_create_query = mode == LoadingStrictnessLevel::CREATE;
String replica_host_id;
bool replica_exists_in_zk = current_zookeeper->tryGet(replica_path, replica_host_id);
LOG_TEST(log, "Replica {} exists in Keeper {}", replica_path, replica_exists_in_zk);
if (replica_exists_in_zk)
{
if (replica_host_id == DROPPED_MARK && !is_create_query)
{
LOG_WARNING(log, "Database {} exists locally, but marked dropped in ZooKeeper ({}). "
"Will not try to start it up", getDatabaseName(), replica_path);
is_probably_dropped = true;
return;
}
String host_id = getHostID(getContext(), db_uuid, cluster_auth_info.cluster_secure_connection);
String host_id_default = getHostID(getContext(), db_uuid, false);
if (replica_host_id != host_id && replica_host_id != host_id_default)
{
UUID uuid_in_keeper = UUIDHelpers::Nil;
try
{
uuid_in_keeper = std::get<2>(parseHostID(replica_host_id));
}
catch (const Exception & e)
{
LOG_WARNING(log, "Failed to parse host_id {} in zookeeper, error {}", replica_host_id, e.what());
}
if (uuid_in_keeper != db_uuid)
throw Exception(
ErrorCodes::REPLICA_ALREADY_EXISTS,
"Replica {} of shard {} of replicated database at {} already exists. Replica host ID: '{}', current host ID: '{}'",
replica_name,
shard_name,
zookeeper_path,
replica_host_id,
host_id);
// After restarting, InterserverIOAddress might change (e.g: config updated, `getFQDNOrHostName` returns a different one)
// If the UUID in the keeper is the same as the current server UUID, we will update the host_id in keeper
LOG_INFO(
log,
"Replicated database replica: {}, shard {}, zk_path: {} already exists with the same UUID, replica host ID: '{}', "
"current host ID: '{}', will set the host_id to the current host ID",
replica_name,
shard_name,
zookeeper_path,
replica_host_id,
host_id);
current_zookeeper->set(replica_path, host_id, -1);
createEmptyLogEntry(current_zookeeper);
}
/// Before 24.6 we always created host_id with insecure port, even if cluster_auth_info.cluster_secure_connection was true.
/// So not to break compatibility, we need to update host_id to secure one if cluster_auth_info.cluster_secure_connection is true.
if (host_id != host_id_default && replica_host_id == host_id_default)
{
current_zookeeper->set(replica_path, host_id, -1);
createEmptyLogEntry(current_zookeeper);
}
/// Check that replica_group_name in ZooKeeper matches the local one and change it if necessary.
String zk_replica_group_name;
if (!current_zookeeper->tryGet(replica_path + "/replica_group", zk_replica_group_name))
{
/// Replica groups were introduced in 23.10, so the node might not exist
current_zookeeper->create(replica_path + "/replica_group", replica_group_name, zkutil::CreateMode::Persistent);
if (!replica_group_name.empty())
createEmptyLogEntry(current_zookeeper);
}
else if (zk_replica_group_name != replica_group_name)
{
current_zookeeper->set(replica_path + "/replica_group", replica_group_name, -1);
createEmptyLogEntry(current_zookeeper);
}
/// Needed to mark all the queries
/// in the range (max log ptr at replica ZooKeeper nodes creation, max log ptr after replica recovery] as successful.
String max_log_ptr_at_creation_str;
if (current_zookeeper->tryGet(replica_path + "/max_log_ptr_at_creation", max_log_ptr_at_creation_str))
max_log_ptr_at_creation = parse<UInt32>(max_log_ptr_at_creation_str);
}
if (is_create_query)
{
/// Create replica nodes in ZooKeeper. If newly initialized nodes already exist, reuse them.
createReplicaNodesInZooKeeper(current_zookeeper);
}
else if (!replica_exists_in_zk)
{
/// It's not CREATE query, but replica does not exist. Probably it was dropped.
/// Do not create anything, continue as readonly.
LOG_WARNING(log, "Database {} exists locally, but its replica does not exist in ZooKeeper ({}). "
"Assuming it was dropped, will not try to start it up", getDatabaseName(), replica_path);
is_probably_dropped = true;
return;
}
/// If not exist, create a node with the database name for introspection.
/// Technically, the database may have different names on different replicas, but this is not a usual case and we only save the first one
auto db_name_path = fs::path(zookeeper_path) / FIRST_REPLICA_DATABASE_NAME;
auto error_code = current_zookeeper->trySet(db_name_path, getDatabaseName());
if (error_code == Coordination::Error::ZNONODE)
current_zookeeper->tryCreate(db_name_path, getDatabaseName(), zkutil::CreateMode::Persistent);
is_readonly = false;
}
catch (...)
{
if (mode < LoadingStrictnessLevel::FORCE_ATTACH)
throw;
/// It's server startup, ignore error.
/// Worker thread will try to setup ZooKeeper connection
tryLogCurrentException(log);
}
}
bool DatabaseReplicated::createDatabaseNodesInZooKeeper(const zkutil::ZooKeeperPtr & current_zookeeper)
{
current_zookeeper->createAncestors(zookeeper_path);
Coordination::Requests ops;
ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path, REPLICATED_DATABASE_MARK, zkutil::CreateMode::Persistent));
ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/log", "", zkutil::CreateMode::Persistent));
ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/replicas", "", zkutil::CreateMode::Persistent));
ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/counter", "", zkutil::CreateMode::Persistent));
/// We create and remove counter/cnt- node to increment sequential number of counter/ node and make log entry numbers start from 1.
/// New replicas are created with log pointer equal to 0 and log pointer is a number of the last executed entry.
/// It means that we cannot have log entry with number 0.
ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/counter/cnt-", "", zkutil::CreateMode::Persistent));
ops.emplace_back(zkutil::makeRemoveRequest(zookeeper_path + "/counter/cnt-", -1));
ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/metadata", "", zkutil::CreateMode::Persistent));
ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/max_log_ptr", "1", zkutil::CreateMode::Persistent));
auto logs_to_keep = db_settings[DatabaseReplicatedSetting::logs_to_keep];
ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/logs_to_keep", std::to_string(logs_to_keep), zkutil::CreateMode::Persistent));
Coordination::Responses responses;
auto res = current_zookeeper->tryMulti(ops, responses);
if (res == Coordination::Error::ZOK)
return true; /// Created new database (it's the first replica)
if (res == Coordination::Error::ZNODEEXISTS)
return false; /// Database exists, we will add new replica
/// Other codes are unexpected, will throw
zkutil::KeeperMultiException::check(res, ops, responses);
UNREACHABLE();
}
bool DatabaseReplicated::looksLikeReplicatedDatabasePath(const ZooKeeperPtr & current_zookeeper, const String & path)
{
Coordination::Stat stat;
String maybe_database_mark;
if (!current_zookeeper->tryGet(path, maybe_database_mark, &stat))
return false;
if (maybe_database_mark.starts_with(REPLICATED_DATABASE_MARK))
return true;
if (!maybe_database_mark.empty())
return false;
/// Old versions did not have REPLICATED_DATABASE_MARK. Check specific nodes exist and add mark.
Coordination::Requests ops;
ops.emplace_back(zkutil::makeCheckRequest(path + "/log", -1));
ops.emplace_back(zkutil::makeCheckRequest(path + "/replicas", -1));
ops.emplace_back(zkutil::makeCheckRequest(path + "/counter", -1));
ops.emplace_back(zkutil::makeCheckRequest(path + "/metadata", -1));
ops.emplace_back(zkutil::makeCheckRequest(path + "/max_log_ptr", -1));
ops.emplace_back(zkutil::makeCheckRequest(path + "/logs_to_keep", -1));
ops.emplace_back(zkutil::makeSetRequest(path, REPLICATED_DATABASE_MARK, stat.version));
Coordination::Responses responses;
auto res = current_zookeeper->tryMulti(ops, responses);
if (res == Coordination::Error::ZOK)
return true;
/// Recheck database mark (just in case of concurrent update).
if (!current_zookeeper->tryGet(path, maybe_database_mark, &stat))
return false;
return maybe_database_mark.starts_with(REPLICATED_DATABASE_MARK);
}
void DatabaseReplicated::createEmptyLogEntry(const ZooKeeperPtr & current_zookeeper)
{
/// On replica creation add empty entry to log. Can be used to trigger some actions on other replicas (e.g. update cluster info).
DDLLogEntry entry{};
DatabaseReplicatedDDLWorker::enqueueQueryImpl(current_zookeeper, entry, this, true);
}
bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, SyncReplicaMode mode)
{
chassert(mode == SyncReplicaMode::DEFAULT || mode == SyncReplicaMode::STRICT);
{
std::lock_guard lock{ddl_worker_mutex};
if (!ddl_worker || is_probably_dropped)
return false;
}
if (mode == SyncReplicaMode::DEFAULT)
return ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms);
Stopwatch elapsed;
while (true)
{
UInt64 elapsed_ms = elapsed.elapsedMilliseconds();
if (elapsed_ms > timeout_ms)
return false;
if (ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms))
return true;
UInt32 our_log_ptr = ddl_worker->getLogPointer();
UInt32 max_log_ptr = parse<UInt32>(getZooKeeper()->get(fs::path(zookeeper_path) / "max_log_ptr"));
bool became_synced = our_log_ptr + db_settings[DatabaseReplicatedSetting::max_replication_lag_to_enqueue] >= max_log_ptr;
if (became_synced)
return true;
/// max_log_ptr might be increased while we were waiting - retry until replication lag is below the threshold
}
}
void DatabaseReplicated::createReplicaNodesInZooKeeper(const zkutil::ZooKeeperPtr & current_zookeeper)
{
if (!looksLikeReplicatedDatabasePath(current_zookeeper, zookeeper_path))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Cannot add new database replica: provided path {} "
"already contains some data and it does not look like Replicated database path.", zookeeper_path);
/// Write host name to replica_path, it will protect from multiple replicas with the same name
const auto host_id = getHostID(getContext(), db_uuid, cluster_auth_info.cluster_secure_connection);
const std::vector<String> check_paths = {
replica_path,
replica_path + "/replica_group",
replica_path + "/digest",
};
bool nodes_exist = true;
auto check_responses = current_zookeeper->tryGet(check_paths);
for (size_t i = 0; i < check_responses.size(); ++i)
{
const auto response = check_responses[i];
if (response.error == Coordination::Error::ZNONODE)
{
nodes_exist = false;
break;
}
if (response.error != Coordination::Error::ZOK)
{
throw zkutil::KeeperException::fromPath(response.error, check_paths[i]);
}
}
if (nodes_exist)
{
const std::vector<String> expected_data = {
host_id,
replica_group_name,
"0",
};
for (size_t i = 0; i != expected_data.size(); ++i)
{
if (check_responses[i].data != expected_data[i])
{
throw Exception(
ErrorCodes::REPLICA_ALREADY_EXISTS,
"Replica node {} in ZooKeeper already exists and contains unexpected value: {}",
quoteString(check_paths[i]), quoteString(check_responses[i].data));
}
}
LOG_DEBUG(log, "Newly initialized replica nodes found in ZooKeeper, reusing them");
createEmptyLogEntry(current_zookeeper);
return;
}
for (int attempts = 10; attempts > 0; --attempts)
{
Coordination::Stat stat;
const String max_log_ptr_str = current_zookeeper->get(zookeeper_path + "/max_log_ptr", &stat);
const Coordination::Requests ops = {
zkutil::makeCreateRequest(replica_path, host_id, zkutil::CreateMode::Persistent),
zkutil::makeCreateRequest(replica_path + "/log_ptr", "0", zkutil::CreateMode::Persistent),
zkutil::makeCreateRequest(replica_path + "/digest", "0", zkutil::CreateMode::Persistent),
zkutil::makeCreateRequest(replica_path + "/replica_group", replica_group_name, zkutil::CreateMode::Persistent),
/// Previously, this method was not idempotent and max_log_ptr_at_creation could be stored in memory.
/// we need to store max_log_ptr_at_creation in ZooKeeper to make this method idempotent during replica creation.
zkutil::makeCreateRequest(replica_path + "/max_log_ptr_at_creation", max_log_ptr_str, zkutil::CreateMode::Persistent),
zkutil::makeCheckRequest(zookeeper_path + "/max_log_ptr", stat.version),
};
Coordination::Responses ops_responses;
const auto code = current_zookeeper->tryMulti(ops, ops_responses);
if (code == Coordination::Error::ZOK)
{
max_log_ptr_at_creation = parse<UInt32>(max_log_ptr_str);
createEmptyLogEntry(current_zookeeper);
return;
}
if (attempts == 1)
{
zkutil::KeeperMultiException::check(code, ops, ops_responses);
}
}
}
void DatabaseReplicated::beforeLoadingMetadata(ContextMutablePtr context_, LoadingStrictnessLevel mode)
{
DatabaseAtomic::beforeLoadingMetadata(context_, mode);
tryConnectToZooKeeperAndInitDatabase(mode);
}
UInt64 DatabaseReplicated::getMetadataHash(const String & table_name) const
{
return DB::getMetadataHash(table_name, readMetadataFile(table_name));
}
LoadTaskPtr DatabaseReplicated::startupDatabaseAsync(AsyncLoader & async_loader, LoadJobSet startup_after, LoadingStrictnessLevel mode)
{
auto base = DatabaseAtomic::startupDatabaseAsync(async_loader, std::move(startup_after), mode);
auto job = makeLoadJob(
base->goals(),
TablesLoaderBackgroundStartupPoolId,
fmt::format("startup Replicated database {}", getDatabaseName()),
[this] (AsyncLoader &, const LoadJobPtr &)
{
UInt64 digest = 0;
{
std::lock_guard lock{mutex};
for (const auto & table : tables)
digest += getMetadataHash(table.first);
LOG_DEBUG(log, "Calculated metadata digest of {} tables: {}", tables.size(), digest);
}
{
std::lock_guard lock{metadata_mutex};
chassert(!tables_metadata_digest);
tables_metadata_digest = digest;
}
if (is_probably_dropped)
{
LOG_TRACE(log, "Cannot startup database {} because it is probably dropped.", getDatabaseName());
return;
}
FailPointInjection::pauseFailPoint(FailPoints::database_replicated_startup_pause);
std::lock_guard lock{ddl_worker_mutex};
initDDLWorkerUnlocked();
});
std::scoped_lock lock(mutex);
startup_replicated_database_task = makeLoadTask(async_loader, {job});
return startup_replicated_database_task;
}
void DatabaseReplicated::waitDatabaseStarted() const
{
LoadTaskPtr task;
{
std::scoped_lock lock(mutex);
task = startup_replicated_database_task;
}
if (task)
waitLoad(currentPoolOr(TablesLoaderForegroundPoolId), task);
}
void DatabaseReplicated::stopLoading()
{
LoadTaskPtr stop_startup_replicated_database;
{
std::scoped_lock lock(mutex);
stop_startup_replicated_database.swap(startup_replicated_database_task);
}
stop_startup_replicated_database.reset();
DatabaseAtomic::stopLoading();
}
void DatabaseReplicated::initDDLWorkerUnlocked()
{
chassert(!ddl_worker);
chassert(!is_probably_dropped.load());
chassert(!ddl_worker_initialized.load());
ddl_worker = std::make_unique<DatabaseReplicatedDDLWorker>(this, getContext());
ddl_worker->startup();
ddl_worker_initialized = true;
}
void DatabaseReplicated::restoreTablesMetadataInKeeper()
{
auto zookeeper = getZooKeeper();
auto local_context = getContext();
std::vector<std::string> tables_metadata_in_zk;
Coordination::Stat entity_name_stat;
const String metadata_node_path = zookeeper_path + "/metadata";
const auto error_code = zookeeper->tryGetChildren(metadata_node_path, tables_metadata_in_zk, &entity_name_stat);
if (error_code != Coordination::Error::ZOK)
throw Coordination::Exception::fromPath(error_code, metadata_node_path);
if (!tables_metadata_in_zk.empty())
{
LOG_INFO(log, "Table metadata in '{}' was restored by another replica", metadata_node_path);
return;
}
auto txn = std::make_shared<ZooKeeperMetadataTransaction>(zookeeper, zookeeper_path, true, "");
UInt64 tables_digest{};
for (auto existing_tables_it = getTablesIterator(local_context, {}, /*skip_not_loaded=*/false); existing_tables_it->isValid();
existing_tables_it->next())
{
const String table_name = existing_tables_it->name();
LOG_TEST(log, "Restoring metadata in Keeper of table {}", table_name);
assert(!ddl_worker || !ddl_worker->isCurrentlyActive());
const String statement = getObjectDefinitionFromCreateQuery(getCreateTableQuery(table_name, local_context));
const String table_metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name);
txn->addOp(zkutil::makeCreateRequest(table_metadata_zk_path, statement, zkutil::CreateMode::Persistent));
tables_digest += DB::getMetadataHash(table_name, statement);
}
txn->addOp(zkutil::makeSetRequest(metadata_node_path, "", entity_name_stat.version));
txn->addOp(zkutil::makeSetRequest(replica_path + "/digest", toString(tables_digest), -1));
{
std::lock_guard lock{metadata_mutex};
tables_metadata_digest = tables_digest;
if (!checkDigestValid(local_context))
throw Exception(ErrorCodes::LOGICAL_ERROR, "Digest does not match");
}
txn->commit();
}
void DatabaseReplicated::reinitializeDDLWorker()
{
std::lock_guard lock{ddl_worker_mutex};
if (is_probably_dropped.exchange(false, std::memory_order_relaxed))
{
LOG_TRACE(log, "Flag is_probably_dropped is being reset to restore database metadata in keeper.");
}
if (ddl_worker)
{
LOG_TRACE(log, "Resetting DDL worker.");
ddl_worker->shutdown();
{
ddl_worker_initialized = false;
ddl_worker = nullptr;
}
}
LOG_TRACE(log, "Initializing DDL worker to restore database metadata in keeper.");
initDDLWorkerUnlocked();
}
ASTPtr DatabaseReplicated::tryGetCreateOrAttachTableQuery(const String & name, ContextPtr local_context) const
{
auto res = tryGetCreateTableQuery(name, local_context);
auto & create = res->as<ASTCreateQuery &>();
create.attach = false;
if (create.is_materialized_view_with_inner_table())
create.attach = true;
if (create.storage && create.storage->engine && (create.storage->engine->name == "TimeSeries"))
create.attach = true;
return res;
}
void DatabaseReplicated::tryCompareLocalAndZooKeeperTablesAndDumpDiffForDebugOnly(const ContextPtr & local_context) const
{
UInt32 max_log_ptr{};
auto table_name_to_metadata_in_zk = tryGetConsistentMetadataSnapshot(getZooKeeper(), max_log_ptr);
auto table_names_local = getAllTableNames(local_context);
if (table_name_to_metadata_in_zk.size() != table_names_local.size())
{
LOG_ERROR(log, "Amount of tables in coordinator {} differs from number of tables locally {}",
table_name_to_metadata_in_zk.size(), table_names_local.size());
}