forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathObjectStorageQueueMetadata.cpp
More file actions
1390 lines (1213 loc) · 48.2 KB
/
Copy pathObjectStorageQueueMetadata.cpp
File metadata and controls
1390 lines (1213 loc) · 48.2 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 <IO/Operators.h>
#include <IO/ReadBufferFromString.h>
#include <Common/SipHash.h>
#include <Core/BackgroundSchedulePool.h>
#include <Core/Settings.h>
#include <IO/ReadHelpers.h>
#include <Interpreters/Context.h>
#include <Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h>
#include <Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h>
#include <Storages/ObjectStorageQueue/ObjectStorageQueueIFileMetadata.h>
#include <Storages/ObjectStorageQueue/ObjectStorageQueueOrderedFileMetadata.h>
#include <Storages/ObjectStorageQueue/ObjectStorageQueueUnorderedFileMetadata.h>
#include <Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h>
#include <Storages/StorageSnapshot.h>
#include <base/sleep.h>
#include <Common/CurrentThread.h>
#include <Common/ZooKeeper/ZooKeeper.h>
#include <Common/getRandomASCIIString.h>
#include <Common/randomSeed.h>
#include <Common/DNSResolver.h>
#include <Interpreters/DDLTask.h>
#include <shared_mutex>
#include <Core/ServerUUID.h>
namespace ProfileEvents
{
extern const Event ObjectStorageQueueCleanupMaxSetSizeOrTTLMicroseconds;
extern const Event ObjectStorageQueueLockLocalFileStatusesMicroseconds;
};
namespace CurrentMetrics
{
extern const Metric ObjectStorageQueueRegisteredServers;
};
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int BAD_ARGUMENTS;
extern const int REPLICA_ALREADY_EXISTS;
extern const int SUPPORT_IS_DISABLED;
}
namespace Setting
{
extern const SettingsBool cloud_mode;
extern const SettingsBool s3queue_migrate_old_metadata_to_buckets;
}
namespace ObjectStorageQueueSetting
{
extern const ObjectStorageQueueSettingsObjectStorageQueueMode mode;
}
namespace
{
UInt64 getCurrentTime()
{
return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
size_t generateRescheduleInterval(size_t min, size_t max)
{
/// Use more or less random interval for unordered mode cleanup task.
/// So that distributed processing cleanup tasks would not schedule cleanup at the same time.
pcg64 rng(randomSeed());
return min + rng() % (max - min + 1);
}
}
class ObjectStorageQueueMetadata::LocalFileStatuses
{
public:
LocalFileStatuses() = default;
FileStatuses getAll() const
{
auto lk = lock();
return file_statuses;
}
FileStatusPtr get(const std::string & filename, bool create)
{
auto lk = lock();
auto it = file_statuses.find(filename);
if (it == file_statuses.end())
{
if (create)
it = file_statuses.emplace(filename, std::make_shared<FileStatus>()).first;
else
throw Exception(ErrorCodes::BAD_ARGUMENTS, "File status for {} doesn't exist", filename);
}
return it->second;
}
bool remove(const std::string & filename, bool if_exists)
{
auto lk = lock();
auto it = file_statuses.find(filename);
if (it == file_statuses.end())
{
if (if_exists)
return false;
throw Exception(ErrorCodes::BAD_ARGUMENTS, "File status for {} doesn't exist", filename);
}
file_statuses.erase(it);
return true;
}
private:
FileStatuses file_statuses;
mutable std::mutex mutex;
std::unique_lock<std::mutex> lock() const
{
auto timer = DB::CurrentThread::getProfileEvents().timer(ProfileEvents::ObjectStorageQueueLockLocalFileStatusesMicroseconds);
return std::unique_lock(mutex);
}
};
ObjectStorageQueueMetadata::ObjectStorageQueueMetadata(
ObjectStorageType storage_type_,
const std::string & zookeeper_name_,
const fs::path & zookeeper_path_,
const ObjectStorageQueueTableMetadata & table_metadata_,
size_t cleanup_interval_min_ms_,
size_t cleanup_interval_max_ms_,
bool use_persistent_processing_nodes_,
size_t persistent_processing_nodes_ttl_seconds_,
size_t keeper_multiread_batch_size_)
: table_metadata(table_metadata_)
, storage_type(storage_type_)
, mode(table_metadata.getMode())
, zookeeper_name(zookeeper_name_)
, zookeeper_path(zookeeper_path_)
, keeper_multiread_batch_size(keeper_multiread_batch_size_)
, cleanup_interval_min_ms(cleanup_interval_min_ms_)
, cleanup_interval_max_ms(cleanup_interval_max_ms_)
, use_persistent_processing_nodes(use_persistent_processing_nodes_)
, persistent_processing_node_ttl_seconds(persistent_processing_nodes_ttl_seconds_)
, buckets_num(table_metadata_.getBucketsNum())
, log(getLogger(fmt::format(
"StorageObjectStorageQueue({}{})",
zookeeper_name_ == zkutil::DEFAULT_ZOOKEEPER_NAME ? "" : zookeeper_name_ + ":",
zookeeper_path_.string())))
, local_file_statuses(std::make_shared<LocalFileStatuses>())
{
LOG_TRACE(
log, "Mode: {}, buckets: {}, processing threads: {}, result buckets num: {}",
table_metadata.mode, table_metadata.buckets.load(),
table_metadata.processing_threads_num.load(), buckets_num);
}
ObjectStorageQueueMetadata::~ObjectStorageQueueMetadata()
{
shutdown();
}
zkutil::ZooKeeperPtr ObjectStorageQueueMetadata::getZooKeeper(LoggerPtr /* log */, const String & zookeeper_name)
{
// Keep the log parameter to match upstream signature; not used in this build.
auto context = Context::getGlobalContextInstance();
return context->getDefaultOrAuxiliaryZooKeeper(zookeeper_name);
}
void ObjectStorageQueueMetadata::startup()
{
if (startup_called.exchange(true))
return;
if (!task
&& mode == ObjectStorageQueueMode::UNORDERED
&& (table_metadata.tracked_files_limit || table_metadata.tracked_files_ttl_sec))
{
task = Context::getGlobalContextInstance()->getSchedulePool().createTask(
"ObjectStorageQueueCleanupFunc",
[this] { cleanupThreadFunc(); });
task->activate();
task->scheduleAfter(
generateRescheduleInterval(
cleanup_interval_min_ms, cleanup_interval_max_ms));
}
if (!update_registry_thread)
update_registry_thread = std::make_unique<ThreadFromGlobalPool>([this](){ updateRegistryFunc(); });
}
void ObjectStorageQueueMetadata::shutdown()
{
shutdown_called = true;
if (task)
task->deactivate();
if (update_registry_thread && update_registry_thread->joinable())
update_registry_thread->join();
}
ObjectStorageQueueMetadata::FileStatuses ObjectStorageQueueMetadata::getFileStatuses() const
{
return local_file_statuses->getAll();
}
ObjectStorageQueueMetadata::FileMetadataPtr ObjectStorageQueueMetadata::getFileMetadata(
const std::string & path,
ObjectStorageQueueOrderedFileMetadata::BucketInfoPtr bucket_info)
{
chassert(metadata_ref_count);
auto file_status = local_file_statuses->get(path, /* create */true);
switch (mode)
{
case ObjectStorageQueueMode::ORDERED:
return std::make_shared<ObjectStorageQueueOrderedFileMetadata>(
zookeeper_path,
path,
file_status,
bucket_info,
buckets_num,
table_metadata.loading_retries,
*metadata_ref_count,
use_persistent_processing_nodes,
zookeeper_name,
log);
case ObjectStorageQueueMode::UNORDERED:
return std::make_shared<ObjectStorageQueueUnorderedFileMetadata>(
zookeeper_path,
path,
file_status,
table_metadata.loading_retries,
*metadata_ref_count,
use_persistent_processing_nodes,
zookeeper_name,
log);
}
}
bool ObjectStorageQueueMetadata::useBucketsForProcessing() const
{
return mode == ObjectStorageQueueMode::ORDERED && (buckets_num > 1);
}
ObjectStorageQueueMetadata::Bucket ObjectStorageQueueMetadata::getBucketForPath(const std::string & path) const
{
return ObjectStorageQueueOrderedFileMetadata::getBucketForPath(path, buckets_num);
}
ObjectStorageQueueOrderedFileMetadata::BucketHolderPtr
ObjectStorageQueueMetadata::tryAcquireBucket(const Bucket & bucket, const Processor & processor)
{
return ObjectStorageQueueOrderedFileMetadata::tryAcquireBucket(zookeeper_path, bucket, processor, zookeeper_name, log);
}
void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, const ContextPtr & context)
{
bool is_initial_query = !context->isDDLOrOnClusterInternal() ||
(context->getZooKeeperMetadataTransaction() && context->getZooKeeperMetadataTransaction()->isInitialQuery());
const fs::path alter_settings_lock_path = zookeeper_path / "alter_settings_lock";
zkutil::EphemeralNodeHolder::Ptr alter_settings_lock;
auto zookeeper = getZooKeeper(log, zookeeper_name);
if (is_initial_query)
{
/// We will retry taking alter_settings_lock for the duration of 5 seconds.
/// Do we need to add a setting for this?
const size_t num_tries = 100;
for (size_t i = 0; i < num_tries; ++i)
{
alter_settings_lock = zkutil::EphemeralNodeHolder::tryCreate(alter_settings_lock_path, *zookeeper, toString(getCurrentTime()));
if (alter_settings_lock)
break;
if (i == num_tries - 1)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Failed to take alter setting lock");
sleepForMilliseconds(50);
}
}
Coordination::Stat stat;
auto metadata_str = zookeeper->get(fs::path(zookeeper_path) / "metadata", &stat);
auto metadata_from_zk = ObjectStorageQueueTableMetadata::parse(metadata_str);
auto new_table_metadata{table_metadata};
for (const auto & change : changes)
{
if (!ObjectStorageQueueTableMetadata::isStoredInKeeper(change.name))
continue;
if (change.name == "processing_threads_num")
{
const auto value = change.value.safeGet<UInt64>();
if (table_metadata.processing_threads_num == value)
{
LOG_TRACE(log, "Setting `processing_threads_num` already equals {}. "
"Will do nothing", value);
continue;
}
new_table_metadata.processing_threads_num = value;
}
else if (change.name == "loading_retries")
{
const auto value = change.value.safeGet<UInt64>();
if (table_metadata.loading_retries == value)
{
LOG_TRACE(log, "Setting `loading_retries` already equals {}. "
"Will do nothing", value);
continue;
}
new_table_metadata.loading_retries = value;
}
else if (change.name == "after_processing")
{
const auto value = ObjectStorageQueueTableMetadata::actionFromString(change.value.safeGet<String>());
if (table_metadata.after_processing == value)
{
LOG_TRACE(log, "Setting `after_processing` already equals {}. "
"Will do nothing", value);
continue;
}
new_table_metadata.after_processing = value;
}
else if (change.name == "tracked_files_limit")
{
const auto value = change.value.safeGet<UInt64>();
if (table_metadata.tracked_files_limit == value)
{
LOG_TRACE(log, "Setting `tracked_files_limit` already equals {}. "
"Will do nothing", value);
continue;
}
new_table_metadata.tracked_files_limit = value;
}
else if (change.name == "tracked_file_ttl_sec")
{
const auto value = change.value.safeGet<UInt64>();
if (table_metadata.tracked_files_ttl_sec == value)
{
LOG_TRACE(log, "Setting `tracked_file_ttl_sec` already equals {}. "
"Will do nothing", value);
continue;
}
new_table_metadata.tracked_files_ttl_sec = value;
}
else if (change.name == "buckets")
{
if (mode != ObjectStorageQueueMode::ORDERED)
{
throw Exception(
ErrorCodes::SUPPORT_IS_DISABLED,
"Changing `buckets` setting is allowed only for Ordered mode");
}
if (!context->getSettingsRef()[Setting::s3queue_migrate_old_metadata_to_buckets])
{
throw Exception(
ErrorCodes::SUPPORT_IS_DISABLED,
"Changing `buckets` setting is allowed only for migration of old metadata structure. "
"To allow migration set s3queue_migrate_old_metadata_to_buckets = 1");
}
const auto value = change.value.safeGet<UInt64>();
if (table_metadata.buckets == value)
{
LOG_TRACE(log, "Setting `buckets` already equals {}. "
"Will do nothing", value);
continue;
}
if (table_metadata.buckets > 1)
{
throw Exception(
ErrorCodes::SUPPORT_IS_DISABLED,
"It is not allowed to modify `buckets` settings "
"when it is already set to a non-zero value");
}
migrateToBucketsInKeeper(value);
new_table_metadata.buckets = value;
}
else
{
throw Exception(ErrorCodes::LOGICAL_ERROR, "Setting `{}` is not changeable", change.name);
}
}
const auto new_metadata_str = new_table_metadata.toString();
LOG_TRACE(log, "New metadata: {}", new_metadata_str);
const fs::path table_metadata_path = zookeeper_path / "metadata";
/// Here we intentionally do not add zk retries,
/// because we modify metadata under ephemeral metadata lock,
/// so we do not want to retry if it expires.
if (is_initial_query)
zookeeper->set(table_metadata_path, new_metadata_str, stat.version);
table_metadata.syncChangeableSettings(new_table_metadata);
}
void ObjectStorageQueueMetadata::migrateToBucketsInKeeper(size_t value)
{
chassert(table_metadata.buckets == 0 || table_metadata.buckets == 1);
chassert(buckets_num == 1, "Buckets: " + toString(buckets_num));
ObjectStorageQueueOrderedFileMetadata::migrateToBuckets(
zookeeper_path,
value,
/* prev_value */table_metadata.buckets,
zookeeper_name);
buckets_num = value;
table_metadata.buckets = value;
}
ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper(
const String & zookeeper_name,
const fs::path & zookeeper_path,
const ObjectStorageQueueSettings & settings,
const ColumnsDescription & columns,
const std::string & format,
const ContextPtr & context,
bool is_attach,
LoggerPtr log)
{
ObjectStorageQueueTableMetadata table_metadata(settings, columns, format);
std::vector<std::string> metadata_paths;
size_t buckets_num = 0;
if (settings[ObjectStorageQueueSetting::mode] == ObjectStorageQueueMode::ORDERED)
{
buckets_num = table_metadata.getBucketsNum();
if (buckets_num == 0)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot have zero values of `processing_threads_num` and `buckets`");
LOG_TRACE(log, "Local buckets num: {}", buckets_num);
metadata_paths = ObjectStorageQueueOrderedFileMetadata::getMetadataPaths(buckets_num);
}
else
{
metadata_paths = ObjectStorageQueueUnorderedFileMetadata::getMetadataPaths();
}
const auto table_metadata_path = zookeeper_path / "metadata";
auto zookeeper = getZooKeeper(log, zookeeper_name);
bool warned = false;
zookeeper->createAncestors(zookeeper_path);
for (size_t i = 0; i < 1000; ++i)
{
if (zookeeper->exists(table_metadata_path))
{
const auto metadata_str = zookeeper->get(table_metadata_path);
const auto metadata_from_zk = ObjectStorageQueueTableMetadata::parse(metadata_str);
LOG_TRACE(log, "Metadata in keeper: {}", metadata_str);
table_metadata.adjustFromKeeper(metadata_from_zk);
table_metadata.checkEquals(metadata_from_zk);
return table_metadata;
}
const auto & settings_ref = context->getSettingsRef();
if (!warned && settings_ref[Setting::cloud_mode]
&& table_metadata.getMode() == ObjectStorageQueueMode::ORDERED
&& table_metadata.buckets <= 1 && table_metadata.processing_threads_num <= 1)
{
const std::string message = "Ordered mode in cloud without "
"either `buckets`>1 or `processing_threads_num`>1 (works as `buckets` if it's not specified) "
"will not work properly. Please specify them in the CREATE query. See documentation for more details.";
if (is_attach)
{
LOG_WARNING(log, "{}", message);
warned = true;
}
else
{
throw Exception(ErrorCodes::BAD_ARGUMENTS, "{}", message);
}
}
Coordination::Requests requests;
requests.emplace_back(zkutil::makeCreateRequest(zookeeper_path, "", zkutil::CreateMode::Persistent));
requests.emplace_back(zkutil::makeCreateRequest(
table_metadata_path, table_metadata.toString(), zkutil::CreateMode::Persistent));
for (const auto & path : metadata_paths)
{
const auto zk_path = zookeeper_path / path;
requests.emplace_back(zkutil::makeCreateRequest(zk_path, "", zkutil::CreateMode::Persistent));
}
if (!table_metadata.last_processed_path.empty())
{
std::atomic<size_t> noop = 0;
ObjectStorageQueueOrderedFileMetadata(
zookeeper_path,
table_metadata.last_processed_path,
std::make_shared<FileStatus>(),
/* bucket_info */nullptr,
buckets_num,
table_metadata.loading_retries,
noop,
/* use_persistent_processing_nodes */false, /// Processing nodes will not be created.
zookeeper_name,
log).prepareProcessedAtStartRequests(requests, zookeeper);
}
Coordination::Responses responses;
auto code = zookeeper->tryMulti(requests, responses);
if (code == Coordination::Error::ZNODEEXISTS)
{
auto exception = zkutil::KeeperMultiException(code, requests, responses);
LOG_INFO(log, "Got code `{}` for path: {}. "
"It looks like the table {} was created by another server at the same moment, "
"will retry",
code, exception.getPathForFirstFailedOp(), zookeeper_path.string());
continue;
}
if (code != Coordination::Error::ZOK)
zkutil::KeeperMultiException::check(code, requests, responses);
return table_metadata;
}
throw Exception(
ErrorCodes::REPLICA_ALREADY_EXISTS,
"Cannot create table, because it is created concurrently every time or because "
"of wrong zookeeper path or because of logical error");
}
namespace
{
struct Info
{
std::string hostname;
std::string table_id;
std::string server_uuid;
size_t version = 1;
bool operator ==(const Info & other) const
{
return hostname == other.hostname && table_id == other.table_id
&& (version == 0 || other.version == 0 || server_uuid == other.server_uuid);
}
static Info create(const StorageID & storage_id)
{
Info self;
self.hostname = DNSResolver::instance().getHostName();
self.table_id = storage_id.hasUUID() ? toString(storage_id.uuid) : storage_id.getFullTableName();
self.server_uuid = toString(ServerUUID::get());
return self;
}
UInt128 hash() const
{
SipHash hash;
hash.update(hostname);
hash.update(table_id);
hash.update(server_uuid);
return hash.get128();
}
std::string serialize() const
{
WriteBufferFromOwnString buf;
buf << version << "\n";
buf << hostname << "\n";
buf << table_id << "\n";
if (version >= 1)
buf << server_uuid << "\n";
return buf.str();
}
static Info deserialize(const std::string & str)
{
ReadBufferFromString buf(str);
Info info;
buf >> info.version >> "\n";
buf >> info.hostname >> "\n";
buf >> info.table_id >> "\n";
if (info.version >= 1)
buf >> info.server_uuid >> "\n";
return info;
}
};
}
void ObjectStorageQueueMetadata::registerActive(const StorageID & storage_id)
{
const auto id = getProcessorID(storage_id);
const auto table_path = zookeeper_path / "registry" / id;
const auto self = Info::create(storage_id);
auto zk_client = getZooKeeper();
auto code = zk_client->tryCreate(
table_path,
self.serialize(),
zkutil::CreateMode::Ephemeral);
if (code != Coordination::Error::ZOK
&& code != Coordination::Error::ZNODEEXISTS)
throw zkutil::KeeperException(code);
LOG_TRACE(log, "Added {} to active registry ({})", self.table_id, id);
}
void ObjectStorageQueueMetadata::registerNonActive(const StorageID & storage_id, bool & created_new_metadata)
{
const auto registry_path = zookeeper_path / "registry";
const auto self = Info::create(storage_id);
const auto drop_lock_path = zookeeper_path / "drop";
Coordination::Error code;
const size_t max_tries = 1000;
for (size_t i = 0; i < max_tries; ++i)
{
Coordination::Stat stat;
std::string registry_str;
auto zk_client = getZooKeeper();
bool supports_remove_recursive = zk_client->isFeatureEnabled(DB::KeeperFeatureFlag::REMOVE_RECURSIVE);
Coordination::Requests requests;
Coordination::Responses responses;
if (zk_client->tryGet(registry_path, registry_str, &stat))
{
created_new_metadata = false;
Strings registered;
splitInto<','>(registered, registry_str);
for (const auto & elem : registered)
{
if (elem.empty())
continue;
auto info = Info::deserialize(elem);
if (info == self)
{
LOG_TRACE(log, "Table {} is already registered", self.table_id);
return;
}
}
auto new_registry_str = registry_str + "," + self.serialize();
requests.push_back(zkutil::makeSetRequest(registry_path, new_registry_str, stat.version));
}
else
{
created_new_metadata = true;
requests.push_back(zkutil::makeCreateRequest(
registry_path,
self.serialize(),
zkutil::CreateMode::Persistent));
if (!supports_remove_recursive)
zkutil::addCheckNotExistsRequest(requests, *zk_client, drop_lock_path);
}
code = zk_client->tryMulti(requests, responses);
if (code == Coordination::Error::ZOK)
{
LOG_TRACE(log, "Added {} to registry", self.table_id);
return;
}
if ((code == Coordination::Error::ZBADVERSION
|| code == Coordination::Error::ZNODEEXISTS
|| code == Coordination::Error::ZNONODE
|| code == Coordination::Error::ZSESSIONEXPIRED) && (i < max_tries - 1))
{
continue;
}
zkutil::KeeperMultiException::check(code, requests, responses);
}
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot register in keeper. Last error: {}", code);
}
Strings ObjectStorageQueueMetadata::getRegistered(bool active)
{
const auto registry_path = zookeeper_path / "registry";
auto zk_client = getZooKeeper();
Strings registered;
if (active)
{
auto code = zk_client->tryGetChildren(registry_path, registered);
if (code != Coordination::Error::ZOK && code != Coordination::Error::ZNONODE)
throw zkutil::KeeperException(code);
}
else
{
std::string registry_str;
if (zk_client->tryGet(registry_path, registry_str))
splitInto<','>(registered, registry_str);
}
return registered;
}
void ObjectStorageQueueMetadata::unregisterActive(const StorageID & storage_id)
{
const auto zk_client = getZooKeeper();
const auto registry_path = zookeeper_path / "registry";
const auto table_path = registry_path / getProcessorID(storage_id);
auto code = zk_client->tryRemove(table_path);
if (code == Coordination::Error::ZOK)
{
LOG_TRACE(
log, "Table '{}' has been removed from the active registry "
"(table path: {})",
storage_id.getNameForLogs(), table_path);
}
else
{
LOG_DEBUG(
log,
"Cannot remove table '{}' from the active registry, reason: {} "
"(table path: {})",
storage_id.getNameForLogs(),
Coordination::errorMessage(code),
table_path);
}
}
void ObjectStorageQueueMetadata::unregisterNonActive(const StorageID & storage_id, bool remove_metadata_if_no_registered)
{
const auto registry_path = zookeeper_path / "registry";
const auto drop_lock_path = zookeeper_path / "drop";
const auto self = Info::create(storage_id);
Coordination::Error code = Coordination::Error::ZOK;
bool allow_remove_recursive = true;
for (size_t i = 0; i < 1000; ++i)
{
Coordination::Requests requests;
Coordination::Responses responses;
size_t count = 0;
bool supports_remove_recursive = true;
zkutil::ZooKeeperPtr zk_client;
try
{
zk_client = getZooKeeper();
supports_remove_recursive = allow_remove_recursive && zk_client->isFeatureEnabled(DB::KeeperFeatureFlag::REMOVE_RECURSIVE);
Coordination::Stat stat;
std::string registry_str;
bool node_exists = zk_client->tryGet(registry_path, registry_str, &stat);
if (!node_exists)
{
LOG_WARNING(log, "Cannot unregister: registry does not exist");
chassert(false);
return;
}
Strings registered;
splitInto<','>(registered, registry_str);
bool found = false;
std::string new_registry_str;
for (const auto & elem : registered)
{
if (elem.empty())
continue;
auto info = Info::deserialize(elem);
if (info == self)
found = true;
else
{
if (!new_registry_str.empty())
new_registry_str += ",";
new_registry_str += elem;
count += 1;
}
}
if (!found)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot unregister: table '{}' is not registered", self.table_id);
LOG_TRACE(log, "Registered count: {}, remove metadata: {}", count, remove_metadata_if_no_registered);
if (remove_metadata_if_no_registered && count == 0)
{
LOG_TRACE(log, "Removing all metadata in keeper by path: {}", zookeeper_path.string());
if (supports_remove_recursive)
{
requests.push_back(zkutil::makeCheckRequest(registry_path, stat.version));
requests.push_back(zkutil::makeRemoveRecursiveRequest(*zk_client, zookeeper_path, /*remove_nodes_limit=*/10000));
}
else
{
requests.push_back(zkutil::makeCheckRequest(registry_path, stat.version));
requests.push_back(zkutil::makeCreateRequest(drop_lock_path, "", zkutil::CreateMode::Ephemeral));
}
code = zk_client->tryMulti(requests, responses);
}
else
{
code = zk_client->trySet(registry_path, new_registry_str, stat.version);
}
}
catch (const zkutil::KeeperMultiException & e)
{
if (Coordination::isHardwareError(e.code))
{
LOG_TEST(log, "Lost connection to zookeeper, will retry");
continue;
}
throw;
}
catch (const zkutil::KeeperException & e)
{
if (Coordination::isHardwareError(e.code))
{
LOG_TEST(log, "Lost connection to zookeeper, will retry");
continue;
}
throw;
}
if (code == Coordination::Error::ZOK)
{
LOG_TRACE(log, "Table '{}' has been removed from the registry", self.table_id);
if (!supports_remove_recursive && remove_metadata_if_no_registered && count == 0)
{
/// Take a drop lock and do recursive remove as a separate request.
/// In case of unsupported "remove_recursive" feature, it will
/// do getChildren and remove them one by one.
auto drop_lock = zkutil::EphemeralNodeHolder::existing(drop_lock_path, *zk_client);
try
{
zk_client->removeRecursive(zookeeper_path);
}
catch (const zkutil::KeeperMultiException & e)
{
if (Coordination::isHardwareError(e.code))
{
LOG_TEST(log, "Lost connection to zookeeper, will retry");
continue;
}
throw;
}
catch (const zkutil::KeeperException & e)
{
if (Coordination::isHardwareError(e.code))
{
LOG_TEST(log, "Lost connection to zookeeper, will retry");
continue;
}
throw;
}
}
return;
}
if (!responses.empty() && supports_remove_recursive && code == Coordination::Error::ZNOTEMPTY) /// potentiall we reached RemoveRecursive node limit, let's try without it
{
allow_remove_recursive = false;
continue;
}
if (Coordination::isHardwareError(code)
|| code == Coordination::Error::ZBADVERSION)
continue;
if (!responses.empty())
{
zkutil::KeeperMultiException::check(code, requests, responses);
}
throw zkutil::KeeperException(code);
}
if (Coordination::isHardwareError(code))
throw zkutil::KeeperException(code);
else
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot unregister in keeper. Last error: {}", code);
}
class ObjectStorageQueueMetadata::ServersHashRing
{
public:
ServersHashRing(size_t total_nodes_, LoggerPtr log_) : total_nodes(total_nodes_), log(log_) {}
void rebuild(const NameSet & servers)
{
virtual_nodes.clear();
if (servers.empty())
return;
size_t virtual_nodes_num = std::max<size_t>(1, total_nodes / servers.size());
for (const auto & server : servers)
{
for (size_t i = 0; i < virtual_nodes_num; ++i)
virtual_nodes.emplace(hash(server + DB::toString(i)), server);
LOG_TRACE(log, "Adding node {}, virtual_nodes: {}", server, virtual_nodes_num);
}
nodes_num = servers.size();
}
std::string chooseServer(const UInt128 & hash) const
{
if (virtual_nodes.empty())
return {};
auto it = virtual_nodes.lower_bound(hash);
if (it == virtual_nodes.end())
it = virtual_nodes.begin();
return it->second;
}
size_t size() const { return nodes_num; }
template<typename... Args>
static UInt128 hash(Args... args)
{
auto hash = SipHash();
(hash.update(args), ...);
return hash.get128();
}
private:
const size_t total_nodes;
LoggerPtr log;
std::map<UInt128, std::string> virtual_nodes;
size_t nodes_num;
};
std::string ObjectStorageQueueMetadata::getProcessorID(const StorageID & storage_id)
{
return toString(Info::create(storage_id).hash());
}
void ObjectStorageQueueMetadata::filterOutForProcessor(Strings & paths, const StorageID & storage_id) const
{
std::shared_lock lock(active_servers_mutex);
if (active_servers.empty() || !active_servers_hash_ring)
return;
const auto self = getProcessorID(storage_id);
Strings result;
for (auto & path : paths)
{
const auto chosen = active_servers_hash_ring->chooseServer(ServersHashRing::hash(path));
if (chosen == self)
result.emplace_back(std::move(path));
else
LOG_TEST(log, "Will skip file {}: it should be processed by {} (self {})", path, chosen, self);
}
paths = std::move(result);
}
void ObjectStorageQueueMetadata::updateRegistryFunc()
{
try
{
zkutil::EventPtr wait_event = std::make_shared<Poco::Event>();
while (!shutdown_called.load())
{
try
{
updateRegistry(getRegistered(/* active */true));
}
catch (const Coordination::Exception & e)
{
if (Coordination::isHardwareError(e.code))
{
LOG_INFO(
log, "Lost ZooKeeper connection, will try to connect again: {}",
DB::getCurrentExceptionMessage(true));
sleepForSeconds(1);
}
else
{
DB::tryLogCurrentException(log);
chassert(false);
}
continue;
}
catch (...)
{
DB::tryLogCurrentException(log);
chassert(false);
}
if (shutdown_called.load())