-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathclickhouse.rs
More file actions
2346 lines (2230 loc) · 96.8 KB
/
Copy pathclickhouse.rs
File metadata and controls
2346 lines (2230 loc) · 96.8 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
use crate::{
common::RelativeDateTime,
interpreter::{
ClickHouseAvailableQuirks, ClickHouseQuirks,
options::{ClickHouseOptions, LogsOrder},
},
};
use anyhow::{Error, Result};
use chrono::{DateTime, Local};
use chrono_tz::Tz;
use clickhouse_rs::{
Block, Options, Pool,
types::{ColumnType, Complex, Enum8, Enum16, FromSql, Query, SqlType},
};
use futures_util::StreamExt;
use std::collections::HashMap;
use std::str::FromStr;
// TODO:
// - implement parsing using serde
// - replace clickhouse_rs::client_info::write() (with extend crate) to change the client name
// - escape parameters
pub type Columns = Block<Complex>;
// clickhouse-rs reads an Enum column as its bare integer (FromSql drops the name mapping) and a
// UUID as uuid::Uuid, so block.get::<String> fails on both; resolve the enum name from the Vec
// carried by the column type and format the UUID. String and LowCardinality(String) fall through
// to a plain String read (get coerces LC).
pub fn column_as_string<K: ColumnType>(block: &Block<K>, row: usize, name: &str) -> Result<String> {
let column = block
.columns()
.iter()
.find(|c| c.name() == name)
.ok_or_else(|| Error::msg(format!("Cannot get {name} column")))?;
fn name_of<T: PartialEq + ToString>(values: &[(String, T)], v: T) -> String {
values
.iter()
.find(|(_, k)| *k == v)
.map_or_else(|| v.to_string(), |(name, _)| name.clone())
}
Ok(match column.sql_type() {
SqlType::Enum8(values) => name_of(&values, block.get::<Enum8, _>(row, name)?.internal()),
SqlType::Enum16(values) => name_of(&values, block.get::<Enum16, _>(row, name)?.internal()),
SqlType::Uuid => block.get::<uuid::Uuid, _>(row, name)?.to_string(),
_ => block.get::<String, _>(row, name)?,
})
}
pub struct ClickHouse {
pub quirks: ClickHouseQuirks,
// Server has use_shared_merge_tree_log_pipeline enabled (SharedMergeTree-backed system.*_log).
// When true, system.*_log reads do not need clusterAllReplicas(): one replica sees all rows.
shared_log_pipeline: bool,
options: ClickHouseOptions,
pool: Pool,
}
#[derive(Debug, PartialEq, Clone)]
#[allow(clippy::upper_case_acronyms)]
pub enum TraceType {
CPU,
Real,
Memory,
MemorySample,
JemallocSample,
ProfileEvent,
MemoryAllocatedWithoutCheck,
}
#[derive(Debug, Clone)]
pub struct TextLogArguments {
pub query_ids: Option<Vec<String>>,
pub logger_names: Option<Vec<String>>,
pub hostname: Option<String>,
pub message_filter: Option<String>,
pub max_level: Option<String>,
pub start: DateTime<Local>,
pub end: RelativeDateTime,
}
#[derive(Debug, Clone)]
pub struct PerfettoQueryScope {
pub query_ids: Option<Vec<String>>,
pub start: DateTime<Local>,
pub end: DateTime<Local>,
}
#[derive(Default)]
pub struct ClickHouseServerCPU {
pub count: u64,
pub user: u64,
pub system: u64,
}
/// NOTE: Likely misses threads for IO
#[derive(Default)]
pub struct ClickHouseServerThreadPools {
pub merges_mutations: u64,
pub fetches: u64,
pub common: u64,
pub moves: u64,
pub schedule: u64,
pub buffer_flush: u64,
pub distributed: u64,
pub message_broker: u64,
pub backups: u64,
pub io: u64,
pub remote_io: u64,
pub queries: u64,
}
#[derive(Default)]
pub struct ClickHouseServerThreads {
pub os_total: u64,
pub os_runnable: u64,
pub tcp: u64,
pub http: u64,
pub interserver: u64,
pub pools: ClickHouseServerThreadPools,
}
#[derive(Default)]
pub struct ClickHouseServerMemory {
pub os_total: u64,
pub resident: u64,
pub tracked: u64,
pub tables: u64,
pub caches: u64,
pub queries: u64,
pub merges_mutations: u64,
pub active_merges: u64,
pub async_inserts: u64,
pub dictionaries: u64,
pub primary_keys: u64,
pub fragmentation: u64,
pub index_granularity: u64,
pub io: u64,
}
/// May have duplicated accounting (due to bridges and stuff)
#[derive(Default)]
pub struct ClickHouseServerNetwork {
pub send_bytes: u64,
pub receive_bytes: u64,
}
#[derive(Default)]
pub struct ClickHouseServerUptime {
pub _os: u64,
pub server: u64,
}
/// May does not take into account some block devices (due to filter by sd*/nvme*/vd*)
#[derive(Default)]
pub struct ClickHouseServerBlockDevices {
pub read_bytes: u64,
pub write_bytes: u64,
}
#[derive(Default)]
pub struct ClickHouseServerStorages {
pub buffer_bytes: u64,
// Replace with bytes once [1] will be merged.
//
// [1]: https://github.com/ClickHouse/ClickHouse/pull/50238
pub distributed_insert_files: u64,
pub total_rows: u64,
pub total_bytes: u64,
}
#[derive(Default)]
pub struct ClickHouseServerRows {
pub selected: u64,
pub inserted: u64,
}
#[derive(Default)]
pub struct ClickHouseServerSummary {
pub queries: u64,
pub merges: u64,
pub mutations: u64,
pub replication_queue: u64,
pub replication_queue_tries: u64,
pub replication_max_absolute_delay: u64,
pub fetches: u64,
pub servers: u64,
pub rows: ClickHouseServerRows,
pub storages: ClickHouseServerStorages,
pub uptime: ClickHouseServerUptime,
pub memory: ClickHouseServerMemory,
pub cpu: ClickHouseServerCPU,
pub threads: ClickHouseServerThreads,
pub network: ClickHouseServerNetwork,
pub blkdev: ClickHouseServerBlockDevices,
pub update_interval: u64,
}
pub struct QueryMetricRow {
pub host_name: String,
pub timestamp_ns: u64,
pub memory_usage: i64,
pub peak_memory_usage: i64,
pub profile_events: HashMap<String, u64>,
}
pub struct MetricLogRow {
pub timestamp_ns: u64,
pub profile_events: HashMap<String, u64>,
pub current_metrics: HashMap<String, i64>,
}
// Lookup by column index: by-name lookup is a linear scan in clickhouse-rs,
// which is quadratic over ~2K ProfileEvent_*/CurrentMetric_* columns.
fn metric_columns<'a, K: ColumnType>(block: &'a Block<K>, prefix: &str) -> Vec<(usize, &'a str)> {
block
.columns()
.iter()
.enumerate()
.filter_map(|(idx, c)| c.name().strip_prefix(prefix).map(|name| (idx, name)))
.collect()
}
fn block_timestamp_ns<K: ColumnType>(block: &Block<K>, i: usize, log: &str) -> Option<u64> {
match block.get::<DateTime<Tz>, _>(i, "event_time_microseconds") {
Ok(dt) => Some(dt.with_timezone(&Local).timestamp_nanos_opt().unwrap_or(0) as u64),
Err(e) => {
log::warn!("Perfetto: {} row {} event_time_microseconds: {}", log, i, e);
None
}
}
}
pub fn parse_query_metric_log_block<K: ColumnType>(block: &Block<K>) -> Vec<QueryMetricRow> {
let pe_columns = metric_columns(block, "ProfileEvent_");
let mut rows = Vec::with_capacity(block.row_count());
for i in 0..block.row_count() {
let mut profile_events = HashMap::new();
for &(idx, name) in &pe_columns {
let value: u64 = block.get(i, idx).unwrap_or(0);
if value != 0 {
profile_events.insert(name.to_string(), value);
}
}
let Some(ts_ns) = block_timestamp_ns(block, i, "query_metric_log") else {
continue;
};
rows.push(QueryMetricRow {
host_name: block.get(i, "host_name").unwrap_or_default(),
timestamp_ns: ts_ns,
memory_usage: block.get(i, "memory_usage").unwrap_or(0),
peak_memory_usage: block.get(i, "peak_memory_usage").unwrap_or(0),
profile_events,
});
}
rows
}
pub fn parse_metric_log_block<K: ColumnType>(block: &Block<K>) -> Vec<MetricLogRow> {
let pe_columns = metric_columns(block, "ProfileEvent_");
let cm_columns = metric_columns(block, "CurrentMetric_");
let mut rows = Vec::with_capacity(block.row_count());
for i in 0..block.row_count() {
let Some(ts_ns) = block_timestamp_ns(block, i, "metric_log") else {
continue;
};
let mut profile_events = HashMap::new();
for &(idx, name) in &pe_columns {
let value: u64 = block.get(i, idx).unwrap_or(0);
if value != 0 {
profile_events.insert(name.to_string(), value);
}
}
let mut current_metrics = HashMap::new();
for &(idx, name) in &cm_columns {
let value: i64 = block.get(i, idx).unwrap_or(0);
if value != 0 {
current_metrics.insert(name.to_string(), value);
}
}
rows.push(MetricLogRow {
timestamp_ns: ts_ns,
profile_events,
current_metrics,
});
}
rows
}
fn collect_values<'b, T: FromSql<'b>>(block: &'b Columns, column: &str) -> Vec<T> {
return (0..block.row_count())
.map(|i| block.get(i, column).unwrap())
.collect();
}
const CHDIG_CLIENT_NAME: [&str; 2] = ["chdig", env!("CARGO_PKG_VERSION")];
fn get_client_name() -> String {
return CHDIG_CLIENT_NAME.join("-");
}
impl ClickHouse {
pub async fn new(options: ClickHouseOptions) -> Result<Self> {
let url = format!(
"{}&client_name={}",
options.url.clone().unwrap(),
get_client_name()
);
let connect_options: Options = Options::from_str(&url)?.with_setting(
"storage_system_stack_trace_pipe_read_timeout_ms",
1000,
/* is_important= */ false,
);
let pool = Pool::new(connect_options);
let mut handle = pool.get_handle().await.map_err(|e| {
Error::msg(format!(
"Cannot connect to ClickHouse at {} ({})",
options.url_safe, e
))
})?;
let version = if let Some(override_version) = &options.server_version {
override_version.clone()
} else {
let version = handle
.query("SELECT version()")
.fetch_all()
.await?
.get::<String, _>(0, 0)?;
// Get VERSION_DESCRIBE from system.build_options for full version info (only build_options
// include version prefix, i.e. -stable/-testing)
handle
.query("SELECT value FROM system.build_options WHERE name = 'VERSION_DESCRIBE'")
.fetch_all()
.await?
.get::<String, _>(0, 0)
.unwrap_or_else(|_| version.clone())
};
let quirks = ClickHouseQuirks::new(version);
// SMT-backed system.*_log (ClickHouse Cloud) exposes all replicas' rows through any single
// replica, so clusterAllReplicas() is pure overhead there. The setting is off by default
// and on self-hosted clusters, so we silently fall back to the cluster-wrapped path.
let shared_log_pipeline = handle
.query(
"SELECT value FROM system.server_settings \
WHERE name = 'use_shared_merge_tree_log_pipeline'",
)
.fetch_all()
.await
.ok()
.filter(|block| block.row_count() > 0)
.and_then(|block| block.get::<String, _>(0, 0).ok())
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false);
if shared_log_pipeline {
log::info!(
"SharedMergeTree log pipeline detected, skipping clusterAllReplicas() for system.*_log"
);
}
return Ok(ClickHouse {
quirks,
shared_log_pipeline,
options,
pool,
});
}
pub fn version(&self) -> String {
return self.quirks.get_version();
}
pub async fn get_slow_query_log(
&self,
filter: &String,
start: RelativeDateTime,
end: RelativeDateTime,
limit: u64,
selected_host: Option<&String>,
) -> Result<Columns> {
let dbtable = self.get_log_table_name("query_log");
let host_filter = self.get_log_host_filter_clause(selected_host);
return self
.execute(
format!(
r#"
WITH
{start} AS start_,
{end} AS end_,
slow_queries_ids AS (
SELECT DISTINCT initial_query_id
FROM {db_table}
WHERE
event_date BETWEEN toDate(start_) AND toDate(end_) AND
event_time BETWEEN toDateTime(start_) AND toDateTime(end_) AND
is_initial_query AND
/* To make query faster */
query_duration_ms > 1e3
{filter}
{internal}
{host_filter}
ORDER BY query_duration_ms DESC
LIMIT {limit}
)
SELECT
mapKeys(ProfileEvents) AS `ProfileEvents.Names`,
mapValues(ProfileEvents) AS `ProfileEvents.Values`,
mapKeys(Settings) AS `Settings.Names`,
mapValues(Settings) AS `Settings.Values`,
{peak_threads_usage} AS peak_threads_usage,
// Compatibility with system.processlist
memory_usage::Int64 AS peak_memory_usage,
query_duration_ms/1e3 AS elapsed,
user,
initial_user,
exception,
is_initial_query,
(exception_code = 394)::UInt8 AS is_cancelled,
initial_query_id,
query_id,
hostname as host_name,
current_database,
query_start_time_microseconds,
event_time_microseconds AS query_end_time_microseconds,
toValidUTF8(query) AS original_query,
normalizeQuery(query) AS normalized_query,
normalized_query_hash
FROM {db_table}
PREWHERE
event_date BETWEEN toDate(start_) AND toDate(end_) AND
event_time BETWEEN toDateTime(start_) AND toDateTime(end_) AND
type != 'QueryStart' AND
initial_query_id GLOBAL IN slow_queries_ids
"#,
start = start.to_sql_datetime_64().ok_or(Error::msg("Invalid start"))?,
end = end.to_sql_datetime_64().ok_or(Error::msg("Invalid end"))?,
db_table = dbtable,
peak_threads_usage = if self.quirks.has(ClickHouseAvailableQuirks::QueryLogPeakThreadsUsage) {
"peak_threads_usage"
} else {
"length(thread_ids)"
},
internal = self.get_internal_filter_clause(),
filter = if !filter.is_empty() {
format!("AND (client_hostname LIKE '{0}' OR log_comment LIKE '{0}' OR os_user LIKE '{0}' OR user LIKE '{0}' OR initial_user LIKE '{0}' OR client_name LIKE '{0}' OR query_id LIKE '{0}' OR query LIKE '{0}' OR current_database LIKE '{0}' OR toString(normalized_query_hash) LIKE '{0}')", &filter)
} else {
"".to_string()
},
host_filter = host_filter,
)
.as_str(),
)
.await;
}
pub async fn get_last_query_log(
&self,
filter: &String,
start: RelativeDateTime,
end: RelativeDateTime,
limit: u64,
selected_host: Option<&String>,
) -> Result<Columns> {
// TODO:
// - propagate sort order from the table
// - distributed_group_by_no_merge=2 is broken for this query with WINDOW function
let dbtable = self.get_log_table_name("query_log");
let host_filter = self.get_log_host_filter_clause(selected_host);
return self
.execute(
format!(
r#"
WITH
{start} AS start_,
{end} AS end_,
last_queries_ids AS (
SELECT DISTINCT initial_query_id
FROM {db_table}
WHERE
event_date BETWEEN toDate(start_) AND toDate(end_) AND
event_time BETWEEN toDateTime(start_) AND toDateTime(end_) AND
is_initial_query
{filter}
{internal}
{host_filter}
ORDER BY event_date DESC, event_time DESC
LIMIT {limit}
)
SELECT
mapKeys(ProfileEvents) AS `ProfileEvents.Names`,
mapValues(ProfileEvents) AS `ProfileEvents.Values`,
mapKeys(Settings) AS `Settings.Names`,
mapValues(Settings) AS `Settings.Values`,
{peak_threads_usage} AS peak_threads_usage,
// Compatibility with system.processlist
memory_usage::Int64 AS peak_memory_usage,
query_duration_ms/1e3 AS elapsed,
user,
initial_user,
exception,
is_initial_query,
(exception_code = 394)::UInt8 AS is_cancelled,
initial_query_id,
query_id,
hostname as host_name,
current_database,
query_start_time_microseconds,
event_time_microseconds AS query_end_time_microseconds,
toValidUTF8(query) AS original_query,
normalizeQuery(query) AS normalized_query,
normalized_query_hash
FROM {db_table}
PREWHERE
event_date BETWEEN toDate(start_) AND toDate(end_) AND
event_time BETWEEN toDateTime(start_) AND toDateTime(end_) AND
type != 'QueryStart' AND
initial_query_id GLOBAL IN last_queries_ids
"#,
start = start.to_sql_datetime_64().ok_or(Error::msg("Invalid start"))?,
end = end.to_sql_datetime_64().ok_or(Error::msg("Invalid end"))?,
db_table = dbtable,
peak_threads_usage = if self.quirks.has(ClickHouseAvailableQuirks::QueryLogPeakThreadsUsage) {
"peak_threads_usage"
} else {
"length(thread_ids)"
},
internal = self.get_internal_filter_clause(),
filter = if !filter.is_empty() {
format!("AND (client_hostname LIKE '{0}' OR log_comment LIKE '{0}' OR os_user LIKE '{0}' OR user LIKE '{0}' OR initial_user LIKE '{0}' OR client_name LIKE '{0}' OR query_id LIKE '{0}' OR query LIKE '{0}' OR current_database LIKE '{0}' OR toString(normalized_query_hash) LIKE '{0}')", &filter)
} else {
"".to_string()
},
host_filter = host_filter,
)
.as_str(),
)
.await;
}
pub async fn get_processlist(
&self,
filter: String,
limit: u64,
selected_host: Option<&String>,
) -> Result<Columns> {
let dbtable = self.get_live_table_name("processes");
let host_filter = self.get_host_filter_clause(selected_host);
return self
.execute(
format!(
r#"
SELECT
mapKeys(ProfileEvents) AS `ProfileEvents.Names`,
mapValues(ProfileEvents) AS `ProfileEvents.Values`,
mapKeys(Settings) AS `Settings.Names`,
mapValues(Settings) AS `Settings.Values`,
{peak_threads_usage} AS peak_threads_usage,
peak_memory_usage,
elapsed / {q} AS elapsed,
user,
initial_user,
'' AS exception,
is_initial_query,
is_cancelled,
initial_query_id,
query_id,
hostName() AS host_name,
{current_database} AS current_database,
/* NOTE: now64()/elapsed does not have enough precision to handle starting
* time properly, while this column is used for querying system.text_log,
* and it should be the smallest time that we are looking for */
(now64(6) - elapsed - 1) AS query_start_time_microseconds,
now64(6) AS query_end_time_microseconds,
toValidUTF8(query) AS original_query,
normalizeQuery(query) AS normalized_query,
normalizedQueryHash(query) AS normalized_query_hash
FROM {}
WHERE 1
{filter}
{internal}
{host_filter}
LIMIT {limit}
"#,
dbtable,
q = if self.quirks.has(ClickHouseAvailableQuirks::ProcessesElapsed) {
10
} else {
1
},
current_database = if self.quirks.has(ClickHouseAvailableQuirks::ProcessesCurrentDatabase) {
// This is required for EXPLAIN (available since 20.6),
// so EXPLAIN with non-default current_database will be broken from processes view.
"'default'"
} else {
"current_database"
},
internal = self.get_internal_filter_clause(),
filter = if !filter.is_empty() {
format!("AND (client_hostname LIKE '{0}' OR Settings['log_comment'] LIKE '{0}' OR os_user LIKE '{0}' OR user LIKE '{0}' OR initial_user LIKE '{0}' OR client_name LIKE '{0}' OR query_id LIKE '{0}' OR query LIKE '{0}' OR current_database LIKE '{0}' OR toString(normalizedQueryHash(query)) LIKE '{0}')", &filter)
} else {
"".to_string()
},
peak_threads_usage = if self.quirks.has(ClickHouseAvailableQuirks::ProcessesPeakThreadsUsage) {
"peak_threads_usage"
} else {
"length(thread_ids)"
},
host_filter = host_filter,
)
.as_str(),
)
.await;
}
pub async fn get_summary(
&self,
selected_host: Option<&String>,
) -> Result<ClickHouseServerSummary> {
let host_filter = self.get_host_filter_clause(selected_host);
let host_where = if host_filter.is_empty() {
String::new()
} else {
format!(" WHERE {}", &host_filter[4..]) // Remove leading "AND "
};
let memory_index_granularity_trait = if self.quirks.has(ClickHouseAvailableQuirks::AsynchronousMetricsTotalIndexGranularityBytesInMemoryAllocated) {
format!("(SELECT sum(index_granularity_bytes_in_memory_allocated) FROM {}{}) AS memory_index_granularity_", self.get_live_table_name("parts"), host_where)
} else {
"0::UInt64 AS memory_index_granularity_".to_string()
};
// NOTE: metrics (but not all of them) are deltas, so chdig do not need to reimplement this logic by itself.
let block = self
.execute(
&format!(
r#"
WITH
-- memory detalization
(SELECT sum(CAST(value AS UInt64)) FROM {metrics} WHERE metric = 'MemoryTracking' {host_filter_and}) AS memory_tracked_,
(SELECT sum(CAST(value AS UInt64)) FROM {metrics} WHERE metric = 'MergesMutationsMemoryTracking' {host_filter_and}) AS memory_merges_mutations_,
(SELECT sum(total_bytes) FROM {tables} WHERE engine IN ('Join','Memory','Buffer','Set') {host_filter_and}) AS memory_tables_,
(SELECT sum(CAST(value AS UInt64)) FROM {asynchronous_metrics} WHERE metric LIKE '%CacheBytes' AND metric NOT LIKE '%Filesystem%' {host_filter_and}) AS memory_async_metrics_caches_,
(SELECT sum(CAST(value AS UInt64)) FROM {metrics} WHERE
metric NOT LIKE '%Filesystem%' AND
(metric LIKE '%CacheBytes' OR metric IN ('IcebergMetadataFilesCacheSize', 'VectorSimilarityIndexCacheSize'))
{host_filter_and}
) AS memory_metrics_caches_,
(SELECT sum(CAST(memory_usage AS UInt64)) FROM {processes} {host_filter_where}) AS memory_queries_,
(SELECT sum(CAST(memory_usage AS UInt64)) FROM {merges} {host_filter_where}) AS memory_active_merges_,
(SELECT sum(bytes_allocated) FROM {dictionaries} {host_filter_where}) AS memory_dictionaries_,
(SELECT sum(total_bytes) FROM {async_inserts} {host_filter_where}) AS memory_async_inserts_,
{memory_index_granularity_trait},
(SELECT count() FROM {one} {host_filter_where}) AS servers_,
(SELECT count() FROM {replication_queue} {host_filter_where}) AS replication_queue_,
(SELECT sum(num_tries) FROM {replication_queue} {host_filter_where}) AS replication_queue_tries_,
(SELECT [sum(total_rows), sum(total_bytes)] FROM (
SELECT
if(engine LIKE 'Shared%', max(total_rows), sum(total_rows)) AS total_rows,
if(engine LIKE 'Shared%', max(total_bytes), sum(total_bytes)) AS total_bytes
FROM {tables}
WHERE has_own_data = 1 {host_filter_and}
GROUP BY database, name, engine
)) AS storage_totals_
SELECT
assumeNotNull(memory_tracked_) AS memory_tracked,
assumeNotNull(memory_merges_mutations_) AS memory_merges_mutations,
assumeNotNull(memory_tables_) AS memory_tables,
assumeNotNull(memory_async_metrics_caches_) + assumeNotNull(memory_metrics_caches_) AS memory_caches,
assumeNotNull(memory_queries_) AS memory_queries,
assumeNotNull(memory_active_merges_) AS memory_active_merges,
assumeNotNull(memory_dictionaries_) AS memory_dictionaries,
assumeNotNull(memory_async_inserts_) AS memory_async_inserts,
assumeNotNull(servers_) AS servers,
assumeNotNull(replication_queue_) AS replication_queue,
assumeNotNull(replication_queue_tries_) AS replication_queue_tries,
assumeNotNull(storage_totals_[1])::UInt64 AS storage_total_rows,
assumeNotNull(storage_totals_[2])::UInt64 AS storage_total_bytes,
max2(assumeNotNull(memory_index_granularity_), asynchronous_metrics.memory_index_granularity)::UInt64 AS memory_index_granularity,
asynchronous_metrics.*,
events.*,
metrics.*
FROM
(
WITH
-- exclude MD/LVM
metric LIKE '%_sd%' OR metric LIKE '%_nvme%' OR metric LIKE '%_vd%' AS is_disk,
metric LIKE '%vlan%' AS is_vlan
-- NOTE: cast should be after aggregation function since the type is Float64
SELECT
CAST(minIf(value, metric == 'OSUptime') AS UInt64) AS os_uptime,
CAST(min(uptime()) AS UInt64) AS uptime,
-- memory
CAST(coalesce(sumIfOrNull(value, metric == 'CGroupMemoryTotal' and value > 0), sumIf(value, metric == 'OSMemoryTotal')) AS UInt64) AS os_memory_total,
CAST(sumIf(value, metric == 'MemoryResident') AS UInt64) AS memory_resident,
-- May differs from primary_key_bytes_in_memory_allocated from
-- system.parts, since it takes into account only active parts
CAST(sumIf(value,
metric == 'TotalPrimaryKeyBytesInMemoryAllocated'
OR metric == 'TotalProjectionPrimaryKeyBytesInMemoryAllocated'
) AS UInt64) AS memory_primary_keys,
CAST(sumIf(value,
metric == 'TotalIndexGranularityBytesInMemoryAllocated'
OR metric == 'TotalProjectionIndexGranularityBytesInMemoryAllocated'
) AS UInt64) AS memory_index_granularity,
CAST((
sumIf(value, metric == 'jemalloc.resident') -
sumIf(value, metric == 'jemalloc.allocated')
) AS UInt64) AS memory_fragmentation,
-- cpu
CAST(
max2(
countIf(metric LIKE 'CPUFrequencyMHz%'),
sumIf(value, metric = 'CGroupMaxCPU')
)
AS UInt64) AS cpu_count,
CAST(
max2(
sumIf(value, metric LIKE 'OSUserTimeCPU%'),
sumIf(value, metric = 'OSUserTime')
)
AS UInt64) AS cpu_user,
CAST(
max2(
sumIf(value, metric LIKE 'OSSystemTimeCPU%'),
sumIf(value, metric = 'OSSystemTime')
)
AS UInt64) AS cpu_system,
-- threads detalization
CAST(sumIf(value, metric = 'HTTPThreads') AS UInt64) AS threads_http,
CAST(sumIf(value, metric = 'TCPThreads') AS UInt64) AS threads_tcp,
CAST(sumIf(value, metric = 'OSThreadsTotal') AS UInt64) AS threads_os_total,
CAST(sumIf(value, metric = 'OSThreadsRunnable') AS UInt64) AS threads_os_runnable,
CAST(sumIf(value, metric = 'InterserverThreads') AS UInt64) AS threads_interserver,
-- network
CAST(sumIf(value, metric LIKE 'NetworkSendBytes%' AND NOT is_vlan) AS UInt64) AS net_send_bytes,
CAST(sumIf(value, metric LIKE 'NetworkReceiveBytes%' AND NOT is_vlan) AS UInt64) AS net_receive_bytes,
-- block devices
CAST(sumIf(value, metric LIKE 'BlockReadBytes%' AND is_disk) AS UInt64) AS block_read_bytes,
CAST(sumIf(value, metric LIKE 'BlockWriteBytes%' AND is_disk) AS UInt64) AS block_write_bytes,
-- replication
CAST(maxIf(value, metric == 'ReplicasMaxAbsoluteDelay') AS UInt64) AS replication_max_absolute_delay,
-- update intervals
CAST(anyLastIf(value, metric == 'AsynchronousMetricsUpdateInterval') AS UInt64) AS metrics_update_interval
FROM {asynchronous_metrics}
{host_filter_where}
) as asynchronous_metrics,
(
SELECT
sumIf(CAST(value AS UInt64), event == 'IOBufferAllocBytes') AS memory_io,
sumIf(CAST(value AS UInt64), event == 'SelectedRows') AS selected_rows,
sumIf(CAST(value AS UInt64), event == 'InsertedRows') AS inserted_rows
FROM {events}
{host_filter_where}
) as events,
(
SELECT
sumIf(CAST(value AS UInt64), metric == 'Query') AS queries,
sumIf(CAST(value AS UInt64), metric == 'Merge') AS merges,
sumIf(CAST(value AS UInt64), metric == 'PartMutation') AS mutations,
sumIf(CAST(value AS UInt64), metric == 'ReplicatedFetch') AS fetches,
sumIf(CAST(value AS UInt64), metric == 'StorageBufferBytes') AS storage_buffer_bytes,
sumIf(CAST(value AS UInt64), metric == 'DistributedFilesToInsert') AS storage_distributed_insert_files,
sumIf(CAST(value AS UInt64), metric == 'BackgroundMergesAndMutationsPoolTask') AS threads_merges_mutations,
sumIf(CAST(value AS UInt64), metric == 'BackgroundFetchesPoolTask') AS threads_fetches,
sumIf(CAST(value AS UInt64), metric == 'BackgroundCommonPoolTask') AS threads_common,
sumIf(CAST(value AS UInt64), metric == 'BackgroundMovePoolTask') AS threads_moves,
sumIf(CAST(value AS UInt64), metric == 'BackgroundSchedulePoolTask') AS threads_schedule,
sumIf(CAST(value AS UInt64), metric == 'BackgroundBufferFlushSchedulePoolTask') AS threads_buffer_flush,
sumIf(CAST(value AS UInt64), metric == 'BackgroundDistributedSchedulePoolTask') AS threads_distributed,
sumIf(CAST(value AS UInt64), metric == 'BackgroundMessageBrokerSchedulePoolTask') AS threads_message_broker,
sumIf(CAST(value AS UInt64), metric IN (
'BackupThreadsActive',
'RestoreThreadsActive',
'BackupsIOThreadsActive'
)) AS threads_backups,
sumIf(CAST(value AS UInt64), metric IN (
'DiskObjectStorageAsyncThreadsActive',
'ThreadPoolRemoteFSReaderThreadsActive',
'StorageS3ThreadsActive'
)) AS threads_remote_io,
sumIf(CAST(value AS UInt64), metric IN (
'IOThreadsActive',
'IOWriterThreadsActive',
'IOPrefetchThreadsActive',
'MarksLoaderThreadsActive'
)) AS threads_io,
sumIf(CAST(value AS UInt64), metric IN (
'QueryPipelineExecutorThreadsActive',
'QueryThread',
'AggregatorThreadsActive',
'StorageDistributedThreadsActive',
'DestroyAggregatesThreadsActive'
)) AS threads_queries
FROM {metrics}
{host_filter_where}
) as metrics
SETTINGS enable_global_with_statement=0
"#,
metrics=self.get_live_table_name("metrics"),
events=self.get_live_table_name("events"),
tables=self.get_live_table_name("tables"),
processes=self.get_live_table_name("processes"),
merges=self.get_live_table_name("merges"),
async_inserts=self.get_live_table_name("asynchronous_inserts"),
replication_queue=self.get_live_table_name("replication_queue"),
dictionaries=self.get_live_table_name("dictionaries"),
asynchronous_metrics=self.get_live_table_name("asynchronous_metrics"),
one=self.get_live_table_name("one"),
memory_index_granularity_trait=memory_index_granularity_trait,
host_filter_where=host_where,
host_filter_and=host_filter,
)
)
.await?;
let get = |key: &str| {
// By subquery.column
if let Ok(value) = block.get::<u64, _>(0, key) {
return value;
}
let parts = key.split(".").collect::<Vec<&str>>();
assert!(parts.len() <= 2);
// By column
return block.get::<u64, _>(0, parts[parts.len() - 1]).expect(key);
};
return Ok(ClickHouseServerSummary {
queries: get("metrics.queries"),
merges: get("metrics.merges"),
mutations: get("metrics.mutations"),
replication_queue: get("replication_queue"),
replication_queue_tries: get("replication_queue_tries"),
replication_max_absolute_delay: get(
"asynchronous_metrics.replication_max_absolute_delay",
),
fetches: get("metrics.fetches"),
servers: get("servers"),
uptime: ClickHouseServerUptime {
_os: get("asynchronous_metrics.os_uptime"),
server: get("asynchronous_metrics.uptime"),
},
rows: ClickHouseServerRows {
selected: get("events.selected_rows"),
inserted: get("events.inserted_rows"),
},
storages: ClickHouseServerStorages {
buffer_bytes: get("metrics.storage_buffer_bytes"),
distributed_insert_files: get("metrics.storage_distributed_insert_files"),
total_rows: get("storage_total_rows"),
total_bytes: get("storage_total_bytes"),
},
memory: ClickHouseServerMemory {
os_total: get("asynchronous_metrics.os_memory_total"),
resident: get("asynchronous_metrics.memory_resident"),
tracked: get("memory_tracked"),
merges_mutations: get("memory_merges_mutations"),
tables: get("memory_tables"),
caches: get("memory_caches"),
queries: get("memory_queries"),
active_merges: get("memory_active_merges"),
async_inserts: get("memory_async_inserts"),
dictionaries: get("memory_dictionaries"),
primary_keys: get("asynchronous_metrics.memory_primary_keys"),
fragmentation: get("asynchronous_metrics.memory_fragmentation"),
index_granularity: get("memory_index_granularity"),
io: get("events.memory_io"),
},
cpu: ClickHouseServerCPU {
count: get("asynchronous_metrics.cpu_count"),
user: get("asynchronous_metrics.cpu_user"),
system: get("asynchronous_metrics.cpu_system"),
},
threads: ClickHouseServerThreads {
os_total: get("asynchronous_metrics.threads_os_total"),
os_runnable: get("asynchronous_metrics.threads_os_runnable"),
http: get("asynchronous_metrics.threads_http"),
tcp: get("asynchronous_metrics.threads_tcp"),
interserver: get("asynchronous_metrics.threads_interserver"),
pools: ClickHouseServerThreadPools {
merges_mutations: get("metrics.threads_merges_mutations"),
fetches: get("metrics.threads_fetches"),
common: get("metrics.threads_common"),
moves: get("metrics.threads_moves"),
schedule: get("metrics.threads_schedule"),
buffer_flush: get("metrics.threads_buffer_flush"),
distributed: get("metrics.threads_distributed"),
message_broker: get("metrics.threads_message_broker"),
backups: get("metrics.threads_backups"),
io: get("metrics.threads_io"),
remote_io: get("metrics.threads_remote_io"),
queries: get("metrics.threads_queries"),
},
},
network: ClickHouseServerNetwork {
send_bytes: get("asynchronous_metrics.net_send_bytes"),
receive_bytes: get("asynchronous_metrics.net_receive_bytes"),
},
blkdev: ClickHouseServerBlockDevices {
read_bytes: get("asynchronous_metrics.block_read_bytes"),
write_bytes: get("asynchronous_metrics.block_write_bytes"),
},
update_interval: get("asynchronous_metrics.metrics_update_interval"),
});
}
pub async fn kill_query(&self, query_id: &str) -> Result<()> {
let query = if let Some(cluster) = &self.options.cluster {
format!(
"KILL QUERY ON CLUSTER {} WHERE query_id = '{}' SYNC",
cluster, query_id
)
} else {
format!("KILL QUERY WHERE query_id = '{}' SYNC", query_id)
};
return self.execute_simple(&query).await;
}
pub async fn execute_query(&self, database: &str, query: &str) -> Result<()> {
self.execute_simple(&format!("USE {}", database)).await?;
return self.execute_simple(query).await;
}
pub async fn explain_syntax(
&self,
database: &str,
query: &str,
settings: &HashMap<String, String>,
) -> Result<Vec<String>> {
return self
.explain("SYNTAX", database, query, Some(settings))
.await;
}
pub async fn explain_plan(&self, database: &str, query: &str) -> Result<Vec<String>> {
return self.explain("PLAN actions=1", database, query, None).await;
}
pub async fn explain_pipeline(&self, database: &str, query: &str) -> Result<Vec<String>> {
return self.explain("PIPELINE", database, query, None).await;
}
pub async fn explain_pipeline_graph(&self, database: &str, query: &str) -> Result<Vec<String>> {
return self
.explain("PIPELINE graph=1", database, query, None)
.await;
}
// NOTE: can we benefit from json=1?
pub async fn explain_plan_indexes(&self, database: &str, query: &str) -> Result<Vec<String>> {
return self.explain("PLAN indexes=1", database, query, None).await;
}
pub async fn show_create_table(&self, database: &str, table: &str) -> Result<String> {
let result = self
.execute(&format!("SHOW CREATE TABLE {}.{}", database, table))
.await?;
let statement: String = collect_values(&result, "statement")
.into_iter()
.next()
.unwrap_or_default();
return Ok(statement);
}
async fn explain(
&self,
what: &str,
database: &str,
query: &str,
settings: Option<&HashMap<String, String>>,
) -> Result<Vec<String>> {
self.execute_simple(&format!("USE {}", database)).await?;
// The query's own settings are passed through the protocol rather than
// appended as a SETTINGS clause: the query may already carry its own
// SETTINGS, and a second one would be dropped from EXPLAIN SYNTAX output.
let mut explain = Query::new(format!("EXPLAIN {} {}", what, query));
if let Some(settings) = settings {
for (name, value) in settings {
explain = explain.with_setting(name, value.as_str(), false);
}
}
return Ok(collect_values(&self.execute(explain).await?, "explain"));
}
/// Stream the text_log rows block-by-block into `on_block` (see
/// execute_for_each() for the semantics).