forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathInterpreterSystemQuery.cpp
More file actions
2351 lines (2147 loc) · 95.9 KB
/
InterpreterSystemQuery.cpp
File metadata and controls
2351 lines (2147 loc) · 95.9 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 <algorithm>
#include <csignal>
#include <filesystem>
#include <variant>
#include <unistd.h>
#include <Access/AccessControl.h>
#include <Access/Common/AllowedClientHosts.h>
#include <Access/ContextAccess.h>
#include <BridgeHelper/CatBoostLibraryBridgeHelper.h>
#include <Columns/ColumnString.h>
#include <Core/ServerSettings.h>
#include <Core/Settings.h>
#include <DataTypes/DataTypeString.h>
#include <Databases/DDLDependencyVisitor.h>
#include <Databases/DatabaseFactory.h>
#include <Databases/DatabaseReplicated.h>
#include <Databases/enableAllExperimentalSettings.h>
#include <Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h>
#include <Formats/FormatSchemaInfo.h>
#include <Functions/UserDefined/ExternalUserDefinedExecutableFunctionsLoader.h>
#include <Interpreters/ActionLocksManager.h>
#include <Interpreters/AsynchronousInsertQueue.h>
#include <Interpreters/AsynchronousMetricLog.h>
#include <Interpreters/Cache/FileCache.h>
#include <Interpreters/Cache/FileCacheFactory.h>
#include <Interpreters/Context.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Interpreters/EmbeddedDictionaries.h>
#include <Interpreters/ExternalDictionariesLoader.h>
#include <Interpreters/InterpreterCreateQuery.h>
#include <Interpreters/InterpreterFactory.h>
#include <Interpreters/InterpreterRenameQuery.h>
#include <Interpreters/InterpreterSystemQuery.h>
#include <Interpreters/JIT/CompiledExpressionCache.h>
#include <Interpreters/NormalizeSelectWithUnionQueryVisitor.h>
#include <Interpreters/SessionLog.h>
#include <Interpreters/TransactionLog.h>
#include <Interpreters/executeDDLQueryOnCluster.h>
#include <Interpreters/InstrumentationManager.h>
#include <Interpreters/executeQuery.h>
#include <Parsers/ASTCreateQuery.h>
#include <Parsers/ASTSetQuery.h>
#include <Parsers/ASTSystemQuery.h>
#include <Parsers/ParserCreateQuery.h>
#include <Parsers/parseQuery.h>
#include <Processors/Executors/PullingPipelineExecutor.h>
#include <Processors/Sources/SourceFromSingleChunk.h>
#include <QueryPipeline/QueryPipeline.h>
#include <Storages/Cache/ObjectStorageListObjectsCache.h>
#include <Storages/Freeze.h>
#include <Storages/MaterializedView/RefreshTask.h>
#include <Storages/ObjectStorage/Azure/Configuration.h>
#include <Storages/ObjectStorage/HDFS/Configuration.h>
#include <Storages/ObjectStorage/S3/Configuration.h>
#include <Storages/ObjectStorage/StorageObjectStorage.h>
#include <Storages/StorageDistributed.h>
#include <Storages/StorageFactory.h>
#include <Storages/StorageFile.h>
#include <Storages/StorageMaterializedView.h>
#include <Storages/StorageReplicatedMergeTree.h>
#include <Storages/StorageURL.h>
#include <base/coverage.h>
#include <Common/getRandomASCIIString.h>
#include <Common/ActionLock.h>
#include <Common/CurrentMetrics.h>
#include <Common/DNSResolver.h>
#include <Common/FailPoint.h>
#include <Common/HostResolvePool.h>
#include <Common/ShellCommand.h>
#include <Common/ThreadFuzzer.h>
#include <Common/ThreadPool.h>
#include <Common/escapeForFileName.h>
#include <Common/getNumberOfCPUCoresToUse.h>
#include <Common/logger_useful.h>
#include <Common/typeid_cast.h>
#if USE_PROTOBUF
#include <Formats/ProtobufSchemas.h>
#endif
#if USE_PARQUET
#include <Processors/Formats/Impl/ParquetFileMetaDataCache.h>
#endif
#if USE_AWS_S3
#include <IO/S3/Client.h>
#endif
#if USE_JEMALLOC
#include <Common/Jemalloc.h>
#endif
#include "config.h"
namespace CurrentMetrics
{
extern const Metric RestartReplicaThreads;
extern const Metric RestartReplicaThreadsActive;
extern const Metric RestartReplicaThreadsScheduled;
extern const Metric MergeTreePartsLoaderThreads;
extern const Metric MergeTreePartsLoaderThreadsActive;
extern const Metric MergeTreePartsLoaderThreadsScheduled;
}
namespace DB
{
namespace Setting
{
extern const SettingsUInt64 keeper_max_retries;
extern const SettingsUInt64 keeper_retry_initial_backoff_ms;
extern const SettingsUInt64 keeper_retry_max_backoff_ms;
extern const SettingsSeconds lock_acquire_timeout;
extern const SettingsSeconds receive_timeout;
extern const SettingsMaxThreads max_threads;
extern const SettingsUInt64 max_parser_backtracks;
extern const SettingsUInt64 max_parser_depth;
extern const SettingsSetOperationMode union_default_mode;
}
namespace ServerSetting
{
extern const ServerSettingsDouble cannot_allocate_thread_fault_injection_probability;
}
namespace ErrorCodes
{
extern const int ACCESS_DENIED;
extern const int LOGICAL_ERROR;
extern const int BAD_ARGUMENTS;
extern const int CANNOT_KILL;
extern const int NOT_IMPLEMENTED;
extern const int TIMEOUT_EXCEEDED;
extern const int TABLE_WAS_NOT_DROPPED;
extern const int ABORTED;
extern const int SUPPORT_IS_DISABLED;
extern const int TOO_DEEP_RECURSION;
extern const int UNSUPPORTED_METHOD;
}
namespace ActionLocks
{
extern const StorageActionBlockType PartsMerge;
extern const StorageActionBlockType PartsFetch;
extern const StorageActionBlockType PartsSend;
extern const StorageActionBlockType ReplicationQueue;
extern const StorageActionBlockType DistributedSend;
extern const StorageActionBlockType PartsTTLMerge;
extern const StorageActionBlockType PartsMove;
extern const StorageActionBlockType PullReplicationLog;
extern const StorageActionBlockType Cleanup;
extern const StorageActionBlockType ViewRefresh;
}
namespace
{
/// Sequentially tries to execute all commands and throws exception with info about failed commands
void executeCommandsAndThrowIfError(std::vector<std::function<void()>> commands)
{
ExecutionStatus result(0);
for (auto & command : commands)
{
try
{
command();
}
catch (...)
{
ExecutionStatus current_result = ExecutionStatus::fromCurrentException();
if (result.code == 0)
result.code = current_result.code;
if (!current_result.message.empty())
{
if (!result.message.empty())
result.message += '\n';
result.message += current_result.message;
}
}
}
if (result.code != 0)
throw Exception::createDeprecated(result.message, result.code);
}
AccessType getRequiredAccessType(StorageActionBlockType action_type)
{
if (action_type == ActionLocks::PartsMerge)
return AccessType::SYSTEM_MERGES;
if (action_type == ActionLocks::PartsFetch)
return AccessType::SYSTEM_FETCHES;
if (action_type == ActionLocks::PartsSend)
return AccessType::SYSTEM_REPLICATED_SENDS;
if (action_type == ActionLocks::ReplicationQueue)
return AccessType::SYSTEM_REPLICATION_QUEUES;
if (action_type == ActionLocks::DistributedSend)
return AccessType::SYSTEM_DISTRIBUTED_SENDS;
if (action_type == ActionLocks::PartsTTLMerge)
return AccessType::SYSTEM_TTL_MERGES;
if (action_type == ActionLocks::PartsMove)
return AccessType::SYSTEM_MOVES;
if (action_type == ActionLocks::PullReplicationLog)
return AccessType::SYSTEM_PULLING_REPLICATION_LOG;
if (action_type == ActionLocks::Cleanup)
return AccessType::SYSTEM_CLEANUP;
if (action_type == ActionLocks::ViewRefresh)
return AccessType::SYSTEM_VIEWS;
throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown action type: {}", std::to_string(action_type));
}
constexpr std::string_view table_is_not_replicated = "Table {} is not replicated";
}
/// Implements SYSTEM [START|STOP] <something action from ActionLocks>
void InterpreterSystemQuery::startStopAction(StorageActionBlockType action_type, bool start)
{
auto manager = getContext()->getActionLocksManager();
manager->cleanExpired();
auto access = getContext()->getAccess();
auto required_access_type = getRequiredAccessType(action_type);
if (volume_ptr && action_type == ActionLocks::PartsMerge)
{
access->checkAccess(required_access_type);
volume_ptr->setAvoidMergesUserOverride(!start);
}
else if (table_id)
{
access->checkAccess(required_access_type, table_id.database_name, table_id.table_name);
auto table = DatabaseCatalog::instance().tryGetTable(table_id, getContext());
if (table)
{
if (start)
{
manager->remove(table, action_type);
table->onActionLockRemove(action_type);
}
else
manager->add(table, action_type);
}
}
else
{
for (auto & elem : DatabaseCatalog::instance().getDatabases(GetDatabasesOptions{.with_datalake_catalogs = false}))
{
startStopActionInDatabase(action_type, start, elem.first, elem.second, getContext(), log);
}
}
}
void InterpreterSystemQuery::startStopActionInDatabase(StorageActionBlockType action_type, bool start,
const String & database_name, const DatabasePtr & database,
const ContextPtr & local_context, LoggerPtr log)
{
auto manager = local_context->getActionLocksManager();
auto access = local_context->getAccess();
auto required_access_type = getRequiredAccessType(action_type);
for (auto iterator = database->getTablesIterator(local_context); iterator->isValid(); iterator->next())
{
StoragePtr table = iterator->table();
if (!table)
continue;
if (!access->isGranted(required_access_type, database_name, iterator->name()))
{
LOG_INFO(log, "Access {} denied, skipping {}.{}", toString(required_access_type), database_name, iterator->name());
continue;
}
if (start)
{
manager->remove(table, action_type);
table->onActionLockRemove(action_type);
}
else
manager->add(table, action_type);
}
}
InterpreterSystemQuery::InterpreterSystemQuery(const ASTPtr & query_ptr_, ContextMutablePtr context_)
: WithMutableContext(context_), query_ptr(query_ptr_->clone()), log(getLogger("InterpreterSystemQuery"))
{
}
BlockIO InterpreterSystemQuery::execute()
{
auto & query = query_ptr->as<ASTSystemQuery &>();
if (!query.cluster.empty())
{
DDLQueryOnClusterParams params;
params.access_to_check = getRequiredAccessForDDLOnCluster();
return executeDDLQueryOnCluster(query_ptr, getContext(), params);
}
using Type = ASTSystemQuery::Type;
/// Use global context with fresh system profile settings
auto system_context = Context::createCopy(getContext()->getGlobalContext());
/// Don't check for constraints when changing profile. It was accepted before (for example it might include
/// some experimental settings)
bool check_constraints = false;
system_context->setCurrentProfile(getContext()->getSystemProfileName(), check_constraints);
/// Make canonical query for simpler processing
if (query.type == Type::RELOAD_DICTIONARY)
{
if (query.database)
query.setTable(query.getDatabase() + "." + query.getTable());
}
else if (query.table)
{
table_id = getContext()->resolveStorageID(StorageID(query.getDatabase(), query.getTable()), Context::ResolveOrdinary);
}
BlockIO result;
volume_ptr = {};
if (!query.storage_policy.empty() && !query.volume.empty())
volume_ptr = getContext()->getStoragePolicy(query.storage_policy)->getVolumeByName(query.volume);
switch (query.type)
{
case Type::SHUTDOWN:
{
getContext()->checkAccess(AccessType::SYSTEM_SHUTDOWN);
if (kill(0, SIGTERM))
throw ErrnoException(ErrorCodes::CANNOT_KILL, "System call kill(0, SIGTERM) failed");
break;
}
case Type::KILL:
{
getContext()->checkAccess(AccessType::SYSTEM_SHUTDOWN);
/// Exit with the same code as it is usually set by shell when process is terminated by SIGKILL.
/// It's better than doing 'raise' or 'kill', because they have no effect for 'init' process (with pid = 0, usually in Docker).
LOG_INFO(log, "Exit immediately as the SYSTEM KILL command has been issued.");
_exit(128 + SIGKILL);
// break; /// unreachable
}
case Type::SUSPEND:
{
getContext()->checkAccess(AccessType::SYSTEM_SHUTDOWN);
auto command = fmt::format("kill -STOP {0} && sleep {1} && kill -CONT {0}", getpid(), query.seconds);
LOG_DEBUG(log, "Will run {}", command);
auto res = ShellCommand::execute(command);
res->in.close();
WriteBufferFromOwnString out;
copyData(res->out, out);
copyData(res->err, out);
if (!out.str().empty())
LOG_DEBUG(log, "The command {} returned output: {}", command, out.str());
res->wait();
break;
}
case Type::SYNC_FILE_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_SYNC_FILE_CACHE);
LOG_DEBUG(log, "Will perform 'sync' syscall (it can take time).");
sync();
break;
}
case Type::CLEAR_DNS_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_DNS_CACHE);
DNSResolver::instance().dropCache();
HostResolversPool::instance().dropCache();
/// Reinitialize clusters to update their resolved_addresses
system_context->reloadClusterConfig();
break;
}
case Type::CLEAR_CONNECTIONS_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_CONNECTIONS_CACHE);
HTTPConnectionPools::instance().dropCache();
break;
}
case Type::PREWARM_MARK_CACHE:
{
prewarmMarkCache();
break;
}
case Type::PREWARM_PRIMARY_INDEX_CACHE:
{
prewarmPrimaryIndexCache();
break;
}
case Type::CLEAR_MARK_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_MARK_CACHE);
system_context->clearMarkCache();
break;
case Type::CLEAR_ICEBERG_METADATA_CACHE:
#if USE_AVRO
getContext()->checkAccess(AccessType::SYSTEM_DROP_ICEBERG_METADATA_CACHE);
system_context->clearIcebergMetadataFilesCache();
break;
#else
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "The server was compiled without the support for AVRO");
#endif
case Type::CLEAR_PRIMARY_INDEX_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_PRIMARY_INDEX_CACHE);
system_context->clearPrimaryIndexCache();
break;
case Type::CLEAR_UNCOMPRESSED_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_UNCOMPRESSED_CACHE);
system_context->clearUncompressedCache();
break;
case Type::CLEAR_INDEX_MARK_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_MARK_CACHE);
system_context->clearIndexMarkCache();
break;
case Type::CLEAR_INDEX_UNCOMPRESSED_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_UNCOMPRESSED_CACHE);
system_context->clearIndexUncompressedCache();
break;
case Type::CLEAR_VECTOR_SIMILARITY_INDEX_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_VECTOR_SIMILARITY_INDEX_CACHE);
system_context->clearVectorSimilarityIndexCache();
break;
case Type::CLEAR_TEXT_INDEX_DICTIONARY_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_TEXT_INDEX_DICTIONARY_CACHE);
system_context->clearTextIndexDictionaryBlockCache();
break;
case Type::CLEAR_TEXT_INDEX_HEADER_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_TEXT_INDEX_HEADER_CACHE);
system_context->clearTextIndexHeaderCache();
break;
case Type::CLEAR_TEXT_INDEX_POSTINGS_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_TEXT_INDEX_POSTINGS_CACHE);
system_context->clearTextIndexPostingsCache();
break;
case Type::CLEAR_TEXT_INDEX_CACHES:
getContext()->checkAccess(AccessType::SYSTEM_DROP_TEXT_INDEX_CACHES);
system_context->clearTextIndexDictionaryBlockCache();
system_context->clearTextIndexHeaderCache();
system_context->clearTextIndexPostingsCache();
break;
case Type::CLEAR_MMAP_CACHE:
getContext()->checkAccess(AccessType::SYSTEM_DROP_MMAP_CACHE);
system_context->clearMMappedFileCache();
break;
case Type::CLEAR_QUERY_CONDITION_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_QUERY_CONDITION_CACHE);
getContext()->clearQueryConditionCache();
break;
}
case Type::CLEAR_QUERY_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_QUERY_CACHE);
getContext()->clearQueryResultCache(query.query_result_cache_tag);
break;
}
case Type::DROP_PARQUET_METADATA_CACHE:
{
#if USE_PARQUET
getContext()->checkAccess(AccessType::SYSTEM_DROP_PARQUET_METADATA_CACHE);
ParquetFileMetaDataCache::instance()->clear();
break;
#else
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "The server was compiled without the support for Parquet");
#endif
}
case Type::CLEAR_COMPILED_EXPRESSION_CACHE:
#if USE_EMBEDDED_COMPILER
getContext()->checkAccess(AccessType::SYSTEM_DROP_COMPILED_EXPRESSION_CACHE);
if (auto * cache = CompiledExpressionCacheFactory::instance().tryGetCache())
cache->clear();
break;
#else
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "The server was compiled without the support for JIT compilation");
#endif
case Type::CLEAR_S3_CLIENT_CACHE:
#if USE_AWS_S3
getContext()->checkAccess(AccessType::SYSTEM_DROP_S3_CLIENT_CACHE);
S3::ClientCacheRegistry::instance().clearCacheForAll();
break;
#else
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "The server was compiled without the support for AWS S3");
#endif
case Type::DROP_OBJECT_STORAGE_LIST_OBJECTS_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_OBJECT_STORAGE_LIST_OBJECTS_CACHE);
ObjectStorageListObjectsCache::instance().clear();
break;
}
case Type::CLEAR_FILESYSTEM_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_FILESYSTEM_CACHE);
const auto user_id = FileCache::getCommonUser().user_id;
if (query.filesystem_cache_name.empty())
{
for (const auto & cache_data : FileCacheFactory::instance().getUniqueInstances())
{
if (!cache_data->cache->isInitialized())
continue;
cache_data->cache->removeAllReleasable(user_id);
}
}
else
{
auto cache = FileCacheFactory::instance().getByName(query.filesystem_cache_name)->cache;
if (cache->isInitialized())
{
if (query.key_to_drop.empty())
{
cache->removeAllReleasable(user_id);
}
else
{
auto key = FileCacheKey::fromKeyString(query.key_to_drop);
if (query.offset_to_drop.has_value())
cache->removeFileSegment(key, query.offset_to_drop.value(), user_id);
else
cache->removeKey(key, user_id);
}
}
}
break;
}
case Type::SYNC_FILESYSTEM_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_SYNC_FILESYSTEM_CACHE);
ColumnsDescription columns{NamesAndTypesList{
{"cache_name", std::make_shared<DataTypeString>()},
{"path", std::make_shared<DataTypeString>()},
{"size", std::make_shared<DataTypeUInt64>()},
}};
Block sample_block;
for (const auto & column : columns)
sample_block.insert({column.type->createColumn(), column.type, column.name});
MutableColumns res_columns = sample_block.cloneEmptyColumns();
auto fill_data = [&](const std::string & cache_name, const FileCachePtr & cache, const std::vector<FileSegment::Info> & file_segments)
{
for (const auto & file_segment : file_segments)
{
size_t i = 0;
const auto path = cache->getFileSegmentPath(
file_segment.key, file_segment.offset, file_segment.kind,
FileCache::UserInfo(file_segment.user_id, file_segment.user_weight));
res_columns[i++]->insert(cache_name);
res_columns[i++]->insert(path);
res_columns[i++]->insert(file_segment.downloaded_size);
}
};
if (query.filesystem_cache_name.empty())
{
for (const auto & cache_data : FileCacheFactory::instance().getUniqueInstances())
{
auto file_segments = cache_data->cache->sync();
fill_data(cache_data->cache->getName(), cache_data->cache, file_segments);
}
}
else
{
auto cache = FileCacheFactory::instance().getByName(query.filesystem_cache_name)->cache;
auto file_segments = cache->sync();
fill_data(query.filesystem_cache_name, cache, file_segments);
}
size_t num_rows = res_columns[0]->size();
auto source = std::make_shared<SourceFromSingleChunk>(std::make_shared<const Block>(std::move(sample_block)), Chunk(std::move(res_columns), num_rows));
result.pipeline = QueryPipeline(std::move(source));
break;
}
case Type::CLEAR_DISK_METADATA_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_FILESYSTEM_CACHE);
auto metadata = getContext()->getDisk(query.disk)->getMetadataStorage();
if (metadata)
metadata->dropCache();
break;
}
case Type::CLEAR_PAGE_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_PAGE_CACHE);
system_context->clearPageCache();
break;
}
case Type::CLEAR_SCHEMA_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_SCHEMA_CACHE);
std::unordered_set<String> caches_to_drop;
if (query.schema_cache_storage.empty())
caches_to_drop = {"FILE", "S3", "HDFS", "URL", "AZURE"};
else
caches_to_drop = {query.schema_cache_storage};
if (caches_to_drop.contains("FILE"))
StorageFile::getSchemaCache(getContext()).clear();
#if USE_AWS_S3
if (caches_to_drop.contains("S3"))
StorageObjectStorage::getSchemaCache(getContext(), StorageS3Configuration::type_name).clear();
#endif
#if USE_HDFS
if (caches_to_drop.contains("HDFS"))
StorageObjectStorage::getSchemaCache(getContext(), StorageHDFSConfiguration::type_name).clear();
#endif
if (caches_to_drop.contains("URL"))
StorageURL::getSchemaCache(getContext()).clear();
#if USE_AZURE_BLOB_STORAGE
if (caches_to_drop.contains("AZURE"))
StorageObjectStorage::getSchemaCache(getContext(), StorageAzureConfiguration::type_name).clear();
#endif
break;
}
case Type::CLEAR_FORMAT_SCHEMA_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_FORMAT_SCHEMA_CACHE);
std::unordered_set<String> caches_to_drop;
if (query.schema_cache_format.empty())
caches_to_drop = {"Protobuf", "Files"};
else
caches_to_drop = {query.schema_cache_format};
#if USE_PROTOBUF
if (caches_to_drop.contains("Protobuf"))
ProtobufSchemas::instance().clear();
#endif
if (caches_to_drop.contains("Files"))
{
fs::path format_schema_cached_dir = fs::path(system_context->getFormatSchemaPath()) / FormatSchemaInfo::CACHE_DIR_NAME;
if (fs::exists(format_schema_cached_dir))
{
size_t count = 0;
for (const auto & entry : fs::directory_iterator(format_schema_cached_dir))
{
if (entry.is_regular_file())
{
fs::remove(entry.path());
count++;
}
}
LOG_INFO(log, "Cleared format schema cache files {}", count);
}
}
break;
}
case Type::RELOAD_DICTIONARY:
{
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_DICTIONARY);
auto & external_dictionaries_loader = system_context->getExternalDictionariesLoader();
external_dictionaries_loader.reloadDictionary(query.getTable(), getContext());
ExternalDictionariesLoader::resetAll();
break;
}
case Type::RELOAD_DICTIONARIES:
{
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_DICTIONARY);
executeCommandsAndThrowIfError({
[&] { system_context->getExternalDictionariesLoader().reloadAllTriedToLoad(); },
[&] { system_context->getEmbeddedDictionaries().reload(); }
});
ExternalDictionariesLoader::resetAll();
break;
}
case Type::RELOAD_MODEL:
{
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_MODEL);
auto bridge_helper = std::make_unique<CatBoostLibraryBridgeHelper>(getContext(), query.target_model);
bridge_helper->removeModel();
break;
}
case Type::RELOAD_MODELS:
{
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_MODEL);
auto bridge_helper = std::make_unique<CatBoostLibraryBridgeHelper>(getContext());
bridge_helper->removeAllModels();
break;
}
case Type::RELOAD_FUNCTION:
{
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_FUNCTION);
auto & external_user_defined_executable_functions_loader = system_context->getExternalUserDefinedExecutableFunctionsLoader();
external_user_defined_executable_functions_loader.reloadFunction(query.target_function);
break;
}
case Type::RELOAD_FUNCTIONS:
{
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_FUNCTION);
auto & external_user_defined_executable_functions_loader = system_context->getExternalUserDefinedExecutableFunctionsLoader();
external_user_defined_executable_functions_loader.reloadAllTriedToLoad();
break;
}
case Type::RELOAD_EMBEDDED_DICTIONARIES:
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_EMBEDDED_DICTIONARIES);
system_context->getEmbeddedDictionaries().reload();
break;
case Type::RELOAD_CONFIG:
{
if (system_context->getApplicationType() == Context::ApplicationType::LOCAL)
throw Exception::createDeprecated("SYSTEM RELOAD CONFIG query is not supported in clickhouse-local", ErrorCodes::UNSUPPORTED_METHOD);
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_CONFIG);
system_context->reloadConfig();
break;
}
case Type::RELOAD_USERS:
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_USERS);
system_context->getAccessControl().reload(AccessControl::ReloadMode::ALL);
break;
case Type::RELOAD_ASYNCHRONOUS_METRICS:
{
getContext()->checkAccess(AccessType::SYSTEM_RELOAD_ASYNCHRONOUS_METRICS);
auto * asynchronous_metrics = system_context->getAsynchronousMetrics();
if (asynchronous_metrics)
asynchronous_metrics->update(std::chrono::system_clock::now(), /*force_update*/ true);
break;
}
case Type::RECONNECT_ZOOKEEPER:
{
getContext()->checkAccess(AccessType::SYSTEM_RECONNECT_ZOOKEEPER);
system_context->reconnectZooKeeper("triggered via SYSTEM RECONNECT ZOOKEEPER command");
break;
}
case Type::STOP_MERGES:
startStopAction(ActionLocks::PartsMerge, false);
break;
case Type::START_MERGES:
startStopAction(ActionLocks::PartsMerge, true);
break;
case Type::STOP_TTL_MERGES:
startStopAction(ActionLocks::PartsTTLMerge, false);
break;
case Type::START_TTL_MERGES:
startStopAction(ActionLocks::PartsTTLMerge, true);
break;
case Type::STOP_MOVES:
startStopAction(ActionLocks::PartsMove, false);
break;
case Type::START_MOVES:
startStopAction(ActionLocks::PartsMove, true);
break;
case Type::STOP_FETCHES:
startStopAction(ActionLocks::PartsFetch, false);
break;
case Type::START_FETCHES:
startStopAction(ActionLocks::PartsFetch, true);
break;
case Type::STOP_REPLICATED_SENDS:
startStopAction(ActionLocks::PartsSend, false);
break;
case Type::START_REPLICATED_SENDS:
startStopAction(ActionLocks::PartsSend, true);
break;
case Type::STOP_REPLICATION_QUEUES:
startStopAction(ActionLocks::ReplicationQueue, false);
break;
case Type::START_REPLICATION_QUEUES:
startStopAction(ActionLocks::ReplicationQueue, true);
break;
case Type::STOP_DISTRIBUTED_SENDS:
startStopAction(ActionLocks::DistributedSend, false);
break;
case Type::START_DISTRIBUTED_SENDS:
startStopAction(ActionLocks::DistributedSend, true);
break;
case Type::STOP_PULLING_REPLICATION_LOG:
startStopAction(ActionLocks::PullReplicationLog, false);
break;
case Type::START_PULLING_REPLICATION_LOG:
startStopAction(ActionLocks::PullReplicationLog, true);
break;
case Type::STOP_CLEANUP:
startStopAction(ActionLocks::Cleanup, false);
break;
case Type::START_CLEANUP:
startStopAction(ActionLocks::Cleanup, true);
break;
case Type::START_VIEW:
case Type::START_VIEWS:
startStopAction(ActionLocks::ViewRefresh, true);
break;
case Type::STOP_VIEW:
case Type::STOP_VIEWS:
startStopAction(ActionLocks::ViewRefresh, false);
break;
case Type::START_REPLICATED_VIEW:
for (const auto & task : getRefreshTasks())
task->startReplicated();
break;
case Type::STOP_REPLICATED_VIEW:
for (const auto & task : getRefreshTasks())
task->stopReplicated("SYSTEM STOP REPLICATED VIEW");
break;
case Type::REFRESH_VIEW:
for (const auto & task : getRefreshTasks())
task->run();
break;
case Type::WAIT_VIEW:
for (const auto & task : getRefreshTasks())
task->wait();
break;
case Type::CANCEL_VIEW:
for (const auto & task : getRefreshTasks())
task->cancel();
break;
case Type::TEST_VIEW:
for (const auto & task : getRefreshTasks())
task->setFakeTime(query.fake_time_for_view);
break;
case Type::DROP_REPLICA:
dropReplica(query);
break;
case Type::DROP_DATABASE_REPLICA:
dropDatabaseReplica(query);
break;
case Type::SYNC_REPLICA:
syncReplica(query);
break;
case Type::SYNC_DATABASE_REPLICA:
syncReplicatedDatabase(query);
break;
case Type::REPLICA_UNREADY:
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Not implemented");
case Type::REPLICA_READY:
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Not implemented");
case Type::SYNC_TRANSACTION_LOG:
syncTransactionLog();
break;
case Type::FLUSH_DISTRIBUTED:
flushDistributed(query);
break;
case Type::RESTART_REPLICAS:
restartReplicas(system_context);
break;
case Type::RESTART_REPLICA:
restartReplica(table_id, system_context);
break;
case Type::RESTORE_REPLICA:
restoreReplica();
break;
case Type::RESTORE_DATABASE_REPLICA:
restoreDatabaseReplica(query);
break;
case Type::WAIT_LOADING_PARTS:
waitLoadingParts();
break;
case Type::RESTART_DISK:
restartDisk(query.disk);
case Type::FLUSH_LOGS:
{
getContext()->checkAccess(AccessType::SYSTEM_FLUSH_LOGS);
auto system_logs = getContext()->getSystemLogs();
system_logs.flush(query.tables);
break;
}
case Type::STOP_LISTEN:
{
if (system_context->getApplicationType() == Context::ApplicationType::LOCAL)
throw Exception::createDeprecated("SYSTEM STOP LISTEN query is not supported in clickhouse-local", ErrorCodes::UNSUPPORTED_METHOD);
getContext()->checkAccess(AccessType::SYSTEM_LISTEN);
getContext()->stopServers(query.server_type);
break;
}
case Type::START_LISTEN:
{
if (system_context->getApplicationType() == Context::ApplicationType::LOCAL)
throw Exception::createDeprecated("SYSTEM START LISTEN query is not supported in clickhouse-local", ErrorCodes::UNSUPPORTED_METHOD);
getContext()->checkAccess(AccessType::SYSTEM_LISTEN);
getContext()->startServers(query.server_type);
break;
}
case Type::FLUSH_ASYNC_INSERT_QUEUE:
{
getContext()->checkAccess(AccessType::SYSTEM_FLUSH_ASYNC_INSERT_QUEUE);
auto * queue = getContext()->tryGetAsynchronousInsertQueue();
if (!queue)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Cannot flush asynchronous insert queue because it is not initialized");
std::vector<StorageID> tables;
for (const auto & [database, table]: query.tables)
tables.push_back(getContext()->resolveStorageID({database, table}, Context::ResolveOrdinary));
queue->flush(tables);
break;
}
case Type::STOP_THREAD_FUZZER:
getContext()->checkAccess(AccessType::SYSTEM_THREAD_FUZZER);
ThreadFuzzer::stop();
CannotAllocateThreadFaultInjector::setFaultProbability(0);
break;
case Type::START_THREAD_FUZZER:
getContext()->checkAccess(AccessType::SYSTEM_THREAD_FUZZER);
ThreadFuzzer::start();
CannotAllocateThreadFaultInjector::setFaultProbability(getContext()->getServerSettings()[ServerSetting::cannot_allocate_thread_fault_injection_probability]);
break;
case Type::UNFREEZE:
{
getContext()->checkAccess(AccessType::SYSTEM_UNFREEZE);
/// The result contains information about deleted parts as a table. It is for compatibility with ALTER TABLE UNFREEZE query.
result = Unfreezer(getContext()).systemUnfreeze(query.backup_name);
break;
}
#if USE_LIBFIU
case Type::ENABLE_FAILPOINT:
{
getContext()->checkAccess(AccessType::SYSTEM_FAILPOINT);
FailPointInjection::enableFailPoint(query.fail_point_name);
break;
}
case Type::DISABLE_FAILPOINT:
{
getContext()->checkAccess(AccessType::SYSTEM_FAILPOINT);
FailPointInjection::disableFailPoint(query.fail_point_name);
break;
}
case Type::WAIT_FAILPOINT:
{
getContext()->checkAccess(AccessType::SYSTEM_FAILPOINT);
if (query.fail_point_action == ASTSystemQuery::FailPointAction::PAUSE)
{
LOG_TRACE(log, "Waiting for failpoint {} to pause", query.fail_point_name);
FailPointInjection::waitForPause(query.fail_point_name);
LOG_TRACE(log, "Failpoint {} has paused", query.fail_point_name);
}
else
{
LOG_TRACE(log, "Waiting for failpoint {} to resume", query.fail_point_name);
FailPointInjection::waitForResume(query.fail_point_name);
LOG_TRACE(log, "Failpoint {} has resumed", query.fail_point_name);
}
break;
}
case Type::NOTIFY_FAILPOINT:
{
getContext()->checkAccess(AccessType::SYSTEM_FAILPOINT);
LOG_TRACE(log, "Notifying failpoint {}", query.fail_point_name);
FailPointInjection::notifyFailPoint(query.fail_point_name);
break;
}
#else // USE_LIBFIU
case Type::ENABLE_FAILPOINT:
case Type::DISABLE_FAILPOINT:
case Type::WAIT_FAILPOINT:
case Type::NOTIFY_FAILPOINT:
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "The server was compiled without FIU support");
#endif // USE_LIBFIU
case Type::RESET_COVERAGE:
{
getContext()->checkAccess(AccessType::SYSTEM);
resetCoverage();
break;
}
case Type::LOAD_PRIMARY_KEY: {
loadPrimaryKeys();
break;
}
case Type::UNLOAD_PRIMARY_KEY:
{
unloadPrimaryKeys();
break;
}
#if USE_XRAY
case Type::INSTRUMENT_ADD:
{
getContext()->checkAccess(AccessType::SYSTEM_INSTRUMENT_ADD);
instrumentWithXRay(true, query);
break;
}
case Type::INSTRUMENT_REMOVE:
{
getContext()->checkAccess(AccessType::SYSTEM_INSTRUMENT_REMOVE);
instrumentWithXRay(false, query);
break;
}
#else
case Type::INSTRUMENT_ADD:
case Type::INSTRUMENT_REMOVE:
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "The server was compiled without XRay support");
#endif
#if USE_JEMALLOC
case Type::JEMALLOC_PURGE:
{
getContext()->checkAccess(AccessType::SYSTEM_JEMALLOC);
Jemalloc::purgeArenas();
break;
}
case Type::JEMALLOC_ENABLE_PROFILE:
{