-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathAsynchronousMetrics.cpp
1507 lines (1276 loc) · 51.6 KB
/
AsynchronousMetrics.cpp
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 <Interpreters/Aggregator.h>
#include <Interpreters/AsynchronousMetrics.h>
#include <Interpreters/AsynchronousMetricLog.h>
#include <Interpreters/JIT/CompiledExpressionCache.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Common/Exception.h>
#include <Common/setThreadName.h>
#include <Common/CurrentMetrics.h>
#include <Common/filesystemHelpers.h>
#include <Interpreters/Cache/FileCacheFactory.h>
#include <Interpreters/Cache/FileCache.h>
#include <Server/ProtocolServerAdapter.h>
#include <Storages/MarkCache.h>
#include <Storages/StorageMergeTree.h>
#include <Storages/MergeTree/MergeTreeMetadataCache.h>
#include <IO/UncompressedCache.h>
#include <IO/MMappedFileCache.h>
#include <IO/ReadHelpers.h>
#include <Databases/IDatabase.h>
#include <chrono>
#include "config.h"
#if USE_JEMALLOC
# include <jemalloc/jemalloc.h>
#endif
/// proton: starts
#include <Interpreters/DiskUtilChecker.h>
/// proton: ends
namespace DB
{
namespace ErrorCodes
{
extern const int CORRUPTED_DATA;
extern const int CANNOT_SYSCONF;
}
#if defined(OS_LINUX)
static constexpr size_t small_buffer_size = 4096;
static void openFileIfExists(const char * filename, std::optional<ReadBufferFromFilePRead> & out)
{
/// Ignoring time of check is not time of use cases, as procfs/sysfs files are fairly persistent.
std::error_code ec;
if (std::filesystem::is_regular_file(filename, ec))
out.emplace(filename, small_buffer_size);
}
static std::unique_ptr<ReadBufferFromFilePRead> openFileIfExists(const std::string & filename)
{
std::error_code ec;
if (std::filesystem::is_regular_file(filename, ec))
return std::make_unique<ReadBufferFromFilePRead>(filename, small_buffer_size);
return {};
}
#endif
AsynchronousMetrics::AsynchronousMetrics(
ContextPtr global_context_,
int update_period_seconds,
const ProtocolServerMetricsFunc & protocol_server_metrics_func_)
: WithContext(global_context_)
, update_period(update_period_seconds)
, protocol_server_metrics_func(protocol_server_metrics_func_)
, log(&Poco::Logger::get("AsynchronousMetrics"))
{
#if defined(OS_LINUX)
openFileIfExists("/proc/meminfo", meminfo);
openFileIfExists("/proc/loadavg", loadavg);
openFileIfExists("/proc/stat", proc_stat);
openFileIfExists("/proc/cpuinfo", cpuinfo);
openFileIfExists("/proc/sys/fs/file-nr", file_nr);
openFileIfExists("/proc/uptime", uptime);
openFileIfExists("/proc/net/dev", net_dev);
openSensors();
openBlockDevices();
openEDAC();
openSensorsChips();
#endif
}
#if defined(OS_LINUX)
void AsynchronousMetrics::openSensors()
{
LOG_TRACE(log, "Scanning /sys/class/thermal");
thermal.clear();
for (size_t thermal_device_index = 0;; ++thermal_device_index)
{
std::unique_ptr<ReadBufferFromFilePRead> file = openFileIfExists(fmt::format("/sys/class/thermal/thermal_zone{}/temp", thermal_device_index));
if (!file)
{
/// Sometimes indices are from zero sometimes from one.
if (thermal_device_index == 0)
continue;
else
break;
}
file->rewind();
Int64 temperature = 0;
try
{
readText(temperature, *file);
}
catch (const ErrnoException & e)
{
LOG_WARNING(
&Poco::Logger::get("AsynchronousMetrics"),
"Thermal monitor '{}' exists but could not be read, error {}.",
thermal_device_index,
e.getErrno());
continue;
}
thermal.emplace_back(std::move(file));
}
}
void AsynchronousMetrics::openBlockDevices()
{
LOG_TRACE(log, "Scanning /sys/block");
if (!std::filesystem::exists("/sys/block"))
return;
block_devices_rescan_delay.restart();
block_devs.clear();
for (const auto & device_dir : std::filesystem::directory_iterator("/sys/block"))
{
String device_name = device_dir.path().filename();
/// We are not interested in loopback devices.
if (device_name.starts_with("loop"))
continue;
std::unique_ptr<ReadBufferFromFilePRead> file = openFileIfExists(device_dir.path() / "stat");
if (!file)
continue;
block_devs[device_name] = std::move(file);
}
}
void AsynchronousMetrics::openEDAC()
{
LOG_TRACE(log, "Scanning /sys/devices/system/edac");
edac.clear();
for (size_t edac_index = 0;; ++edac_index)
{
String edac_correctable_file = fmt::format("/sys/devices/system/edac/mc/mc{}/ce_count", edac_index);
String edac_uncorrectable_file = fmt::format("/sys/devices/system/edac/mc/mc{}/ue_count", edac_index);
bool edac_correctable_file_exists = std::filesystem::exists(edac_correctable_file);
bool edac_uncorrectable_file_exists = std::filesystem::exists(edac_uncorrectable_file);
if (!edac_correctable_file_exists && !edac_uncorrectable_file_exists)
{
if (edac_index == 0)
continue;
else
break;
}
edac.emplace_back();
if (edac_correctable_file_exists)
edac.back().first = openFileIfExists(edac_correctable_file);
if (edac_uncorrectable_file_exists)
edac.back().second = openFileIfExists(edac_uncorrectable_file);
}
}
void AsynchronousMetrics::openSensorsChips()
{
LOG_TRACE(log, "Scanning /sys/class/hwmon");
hwmon_devices.clear();
for (size_t hwmon_index = 0;; ++hwmon_index)
{
String hwmon_name_file = fmt::format("/sys/class/hwmon/hwmon{}/name", hwmon_index);
if (!std::filesystem::exists(hwmon_name_file))
{
if (hwmon_index == 0)
continue;
else
break;
}
String hwmon_name;
ReadBufferFromFilePRead hwmon_name_in(hwmon_name_file, small_buffer_size);
readText(hwmon_name, hwmon_name_in);
std::replace(hwmon_name.begin(), hwmon_name.end(), ' ', '_');
for (size_t sensor_index = 0;; ++sensor_index)
{
String sensor_name_file = fmt::format("/sys/class/hwmon/hwmon{}/temp{}_label", hwmon_index, sensor_index);
String sensor_value_file = fmt::format("/sys/class/hwmon/hwmon{}/temp{}_input", hwmon_index, sensor_index);
bool sensor_name_file_exists = std::filesystem::exists(sensor_name_file);
bool sensor_value_file_exists = std::filesystem::exists(sensor_value_file);
/// Sometimes there are labels but there is no files with data or vice versa.
if (!sensor_name_file_exists && !sensor_value_file_exists)
{
if (sensor_index == 0)
continue;
else
break;
}
std::unique_ptr<ReadBufferFromFilePRead> file = openFileIfExists(sensor_value_file);
if (!file)
continue;
String sensor_name;
if (sensor_name_file_exists)
{
ReadBufferFromFilePRead sensor_name_in(sensor_name_file, small_buffer_size);
readText(sensor_name, sensor_name_in);
std::replace(sensor_name.begin(), sensor_name.end(), ' ', '_');
}
file->rewind();
Int64 temperature = 0;
try
{
readText(temperature, *file);
}
catch (const ErrnoException & e)
{
LOG_WARNING(
&Poco::Logger::get("AsynchronousMetrics"),
"Hardware monitor '{}', sensor '{}' exists but could not be read, error {}.",
hwmon_name,
sensor_name,
e.getErrno());
continue;
}
hwmon_devices[hwmon_name][sensor_name] = std::move(file);
}
}
}
#endif
void AsynchronousMetrics::start()
{
/// Update once right now, to make metrics available just after server start
/// (without waiting for asynchronous_metrics_update_period_s).
update(std::chrono::system_clock::now());
thread = std::make_unique<ThreadFromGlobalPool>([this] { run(); });
}
void AsynchronousMetrics::stop()
{
try
{
{
std::lock_guard lock{mutex};
quit = true;
}
wait_cond.notify_one();
if (thread)
{
thread->join();
thread.reset();
}
}
catch (...)
{
DB::tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
AsynchronousMetrics::~AsynchronousMetrics()
{
stop();
}
AsynchronousMetricValues AsynchronousMetrics::getValues() const
{
std::lock_guard lock{mutex};
return values;
}
static auto get_next_update_time(std::chrono::seconds update_period)
{
using namespace std::chrono;
const auto now = time_point_cast<seconds>(system_clock::now());
// Use seconds since the start of the hour, because we don't know when
// the epoch started, maybe on some weird fractional time.
const auto start_of_hour = time_point_cast<seconds>(time_point_cast<hours>(now));
const auto seconds_passed = now - start_of_hour;
// Rotate time forward by half a period -- e.g. if a period is a minute,
// we'll collect metrics on start of minute + 30 seconds. This is to
// achieve temporal separation with MetricTransmitter. Don't forget to
// rotate it back.
const auto rotation = update_period / 2;
const auto periods_passed = (seconds_passed + rotation) / update_period;
const auto seconds_next = (periods_passed + 1) * update_period - rotation;
const auto time_next = start_of_hour + seconds_next;
return time_next;
}
void AsynchronousMetrics::run()
{
setThreadName("AsyncMetrics");
while (true)
{
auto next_update_time = get_next_update_time(update_period);
{
// Wait first, so that the first metric collection is also on even time.
std::unique_lock lock{mutex};
if (wait_cond.wait_until(lock, next_update_time,
[this] { return quit; }))
{
break;
}
}
try
{
update(next_update_time);
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
}
template <typename Max, typename T>
static void calculateMax(Max & max, T x)
{
if (Max(x) > max)
max = x;
}
template <typename Max, typename Sum, typename T>
static void calculateMaxAndSum(Max & max, Sum & sum, T x)
{
sum += x;
if (Max(x) > max)
max = x;
}
#if USE_JEMALLOC
uint64_t updateJemallocEpoch()
{
uint64_t value = 0;
size_t size = sizeof(value);
mallctl("epoch", &value, &size, &value, size);
return value;
}
template <typename Value>
static Value saveJemallocMetricImpl(AsynchronousMetricValues & values,
const std::string & jemalloc_full_name,
const std::string & clickhouse_full_name)
{
Value value{};
size_t size = sizeof(value);
mallctl(jemalloc_full_name.c_str(), &value, &size, nullptr, 0);
values[clickhouse_full_name] = value;
return value;
}
template<typename Value>
static Value saveJemallocMetric(AsynchronousMetricValues & values,
const std::string & metric_name)
{
return saveJemallocMetricImpl<Value>(values,
fmt::format("stats.{}", metric_name),
fmt::format("jemalloc.{}", metric_name));
}
template<typename Value>
static Value saveAllArenasMetric(AsynchronousMetricValues & values,
const std::string & metric_name)
{
return saveJemallocMetricImpl<Value>(values,
fmt::format("stats.arenas.{}.{}", MALLCTL_ARENAS_ALL, metric_name),
fmt::format("jemalloc.arenas.all.{}", metric_name));
}
#endif
#if defined(OS_LINUX)
void AsynchronousMetrics::ProcStatValuesCPU::read(ReadBuffer & in)
{
readText(user, in);
skipWhitespaceIfAny(in, true);
readText(nice, in);
skipWhitespaceIfAny(in, true);
readText(system, in);
skipWhitespaceIfAny(in, true);
readText(idle, in);
skipWhitespaceIfAny(in, true);
readText(iowait, in);
skipWhitespaceIfAny(in, true);
readText(irq, in);
skipWhitespaceIfAny(in, true);
readText(softirq, in);
/// Just in case for old Linux kernels, we check if these values present.
if (!checkChar('\n', in))
{
skipWhitespaceIfAny(in, true);
readText(steal, in);
}
if (!checkChar('\n', in))
{
skipWhitespaceIfAny(in, true);
readText(guest, in);
}
if (!checkChar('\n', in))
{
skipWhitespaceIfAny(in, true);
readText(guest_nice, in);
}
skipToNextLineOrEOF(in);
}
AsynchronousMetrics::ProcStatValuesCPU
AsynchronousMetrics::ProcStatValuesCPU::operator-(const AsynchronousMetrics::ProcStatValuesCPU & other) const
{
ProcStatValuesCPU res{};
res.user = user - other.user;
res.nice = nice - other.nice;
res.system = system - other.system;
res.idle = idle - other.idle;
res.iowait = iowait - other.iowait;
res.irq = irq - other.irq;
res.softirq = softirq - other.softirq;
res.steal = steal - other.steal;
res.guest = guest - other.guest;
res.guest_nice = guest_nice - other.guest_nice;
return res;
}
AsynchronousMetrics::ProcStatValuesOther
AsynchronousMetrics::ProcStatValuesOther::operator-(const AsynchronousMetrics::ProcStatValuesOther & other) const
{
ProcStatValuesOther res{};
res.interrupts = interrupts - other.interrupts;
res.context_switches = context_switches - other.context_switches;
res.processes_created = processes_created - other.processes_created;
return res;
}
void AsynchronousMetrics::BlockDeviceStatValues::read(ReadBuffer & in)
{
skipWhitespaceIfAny(in, true);
readText(read_ios, in);
skipWhitespaceIfAny(in, true);
readText(read_merges, in);
skipWhitespaceIfAny(in, true);
readText(read_sectors, in);
skipWhitespaceIfAny(in, true);
readText(read_ticks, in);
skipWhitespaceIfAny(in, true);
readText(write_ios, in);
skipWhitespaceIfAny(in, true);
readText(write_merges, in);
skipWhitespaceIfAny(in, true);
readText(write_sectors, in);
skipWhitespaceIfAny(in, true);
readText(write_ticks, in);
skipWhitespaceIfAny(in, true);
readText(in_flight_ios, in);
skipWhitespaceIfAny(in, true);
readText(io_ticks, in);
skipWhitespaceIfAny(in, true);
readText(time_in_queue, in);
skipWhitespaceIfAny(in, true);
readText(discard_ops, in);
skipWhitespaceIfAny(in, true);
readText(discard_merges, in);
skipWhitespaceIfAny(in, true);
readText(discard_sectors, in);
skipWhitespaceIfAny(in, true);
readText(discard_ticks, in);
}
AsynchronousMetrics::BlockDeviceStatValues
AsynchronousMetrics::BlockDeviceStatValues::operator-(const AsynchronousMetrics::BlockDeviceStatValues & other) const
{
BlockDeviceStatValues res{};
res.read_ios = read_ios - other.read_ios;
res.read_merges = read_merges - other.read_merges;
res.read_sectors = read_sectors - other.read_sectors;
res.read_ticks = read_ticks - other.read_ticks;
res.write_ios = write_ios - other.write_ios;
res.write_merges = write_merges - other.write_merges;
res.write_sectors = write_sectors - other.write_sectors;
res.write_ticks = write_ticks - other.write_ticks;
res.in_flight_ios = in_flight_ios; /// This is current value, not total.
res.io_ticks = io_ticks - other.io_ticks;
res.time_in_queue = time_in_queue - other.time_in_queue;
res.discard_ops = discard_ops - other.discard_ops;
res.discard_merges = discard_merges - other.discard_merges;
res.discard_sectors = discard_sectors - other.discard_sectors;
res.discard_ticks = discard_ticks - other.discard_ticks;
return res;
}
AsynchronousMetrics::NetworkInterfaceStatValues
AsynchronousMetrics::NetworkInterfaceStatValues::operator-(const AsynchronousMetrics::NetworkInterfaceStatValues & other) const
{
NetworkInterfaceStatValues res{};
res.recv_bytes = recv_bytes - other.recv_bytes;
res.recv_packets = recv_packets - other.recv_packets;
res.recv_errors = recv_errors - other.recv_errors;
res.recv_drop = recv_drop - other.recv_drop;
res.send_bytes = send_bytes - other.send_bytes;
res.send_packets = send_packets - other.send_packets;
res.send_errors = send_errors - other.send_errors;
res.send_drop = send_drop - other.send_drop;
return res;
}
#endif
void AsynchronousMetrics::update(std::chrono::system_clock::time_point update_time)
{
Stopwatch watch;
AsynchronousMetricValues new_values;
auto current_time = std::chrono::system_clock::now();
auto time_after_previous_update [[maybe_unused]] = current_time - previous_update_time;
previous_update_time = update_time;
/// This is also a good indicator of system responsiveness.
new_values["Jitter"] = std::chrono::duration_cast<std::chrono::nanoseconds>(current_time - update_time).count() / 1e9;
{
if (auto mark_cache = getContext()->getMarkCache())
{
new_values["MarkCacheBytes"] = mark_cache->weight();
new_values["MarkCacheFiles"] = mark_cache->count();
}
}
{
if (auto uncompressed_cache = getContext()->getUncompressedCache())
{
new_values["UncompressedCacheBytes"] = uncompressed_cache->weight();
new_values["UncompressedCacheCells"] = uncompressed_cache->count();
}
}
{
if (auto index_mark_cache = getContext()->getIndexMarkCache())
{
new_values["IndexMarkCacheBytes"] = index_mark_cache->weight();
new_values["IndexMarkCacheFiles"] = index_mark_cache->count();
}
}
{
if (auto index_uncompressed_cache = getContext()->getIndexUncompressedCache())
{
new_values["IndexUncompressedCacheBytes"] = index_uncompressed_cache->weight();
new_values["IndexUncompressedCacheCells"] = index_uncompressed_cache->count();
}
}
{
if (auto mmap_cache = getContext()->getMMappedFileCache())
{
new_values["MMapCacheCells"] = mmap_cache->count();
}
}
{
auto caches = FileCacheFactory::instance().getAll();
for (const auto & [_, cache_data] : caches)
{
new_values["FilesystemCacheBytes"] = cache_data->cache->getUsedCacheSize();
new_values["FilesystemCacheFiles"] = cache_data->cache->getFileSegmentsNum();
}
}
#if USE_ROCKSDB
{
if (auto metadata_cache = getContext()->tryGetMergeTreeMetadataCache())
{
new_values["MergeTreeMetadataCacheSize"] = metadata_cache->getEstimateNumKeys();
}
}
#endif
#if USE_EMBEDDED_COMPILER
{
if (auto * compiled_expression_cache = CompiledExpressionCacheFactory::instance().tryGetCache())
{
new_values["CompiledExpressionCacheBytes"] = compiled_expression_cache->weight();
new_values["CompiledExpressionCacheCount"] = compiled_expression_cache->count();
}
}
#endif
new_values["Uptime"] = getContext()->getUptimeSeconds();
{
if (const auto stats = getHashTablesCacheStatistics())
{
new_values["HashTableStatsCacheEntries"] = stats->entries;
new_values["HashTableStatsCacheHits"] = stats->hits;
new_values["HashTableStatsCacheMisses"] = stats->misses;
}
}
#if defined(OS_LINUX) || defined(OS_FREEBSD)
MemoryStatisticsOS::Data memory_statistics_data = memory_stat.get();
#endif
#if USE_JEMALLOC
// 'epoch' is a special mallctl -- it updates the statistics. Without it, all
// the following calls will return stale values. It increments and returns
// the current epoch number, which might be useful to log as a sanity check.
auto epoch = updateJemallocEpoch();
new_values["jemalloc.epoch"] = epoch;
// Collect the statistics themselves.
saveJemallocMetric<size_t>(new_values, "allocated");
saveJemallocMetric<size_t>(new_values, "active");
saveJemallocMetric<size_t>(new_values, "metadata");
saveJemallocMetric<size_t>(new_values, "metadata_thp");
saveJemallocMetric<size_t>(new_values, "resident");
saveJemallocMetric<size_t>(new_values, "mapped");
saveJemallocMetric<size_t>(new_values, "retained");
saveJemallocMetric<size_t>(new_values, "background_thread.num_threads");
saveJemallocMetric<uint64_t>(new_values, "background_thread.num_runs");
saveJemallocMetric<uint64_t>(new_values, "background_thread.run_intervals");
saveAllArenasMetric<size_t>(new_values, "pactive");
[[maybe_unused]] size_t je_malloc_pdirty = saveAllArenasMetric<size_t>(new_values, "pdirty");
[[maybe_unused]] size_t je_malloc_pmuzzy = saveAllArenasMetric<size_t>(new_values, "pmuzzy");
saveAllArenasMetric<size_t>(new_values, "dirty_purged");
saveAllArenasMetric<size_t>(new_values, "muzzy_purged");
#endif
/// Process process memory usage according to OS
#if defined(OS_LINUX) || defined(OS_FREEBSD)
{
MemoryStatisticsOS::Data & data = memory_statistics_data;
new_values["MemoryVirtual"] = data.virt;
new_values["MemoryResident"] = data.resident;
#if !defined(OS_FREEBSD)
new_values["MemoryShared"] = data.shared;
#endif
new_values["MemoryCode"] = data.code;
new_values["MemoryDataAndStack"] = data.data_and_stack;
/// We must update the value of total_memory_tracker periodically.
/// Otherwise it might be calculated incorrectly - it can include a "drift" of memory amount.
/// See https://github.com/ClickHouse/ClickHouse/issues/10293
{
Int64 amount = total_memory_tracker.get();
Int64 peak = total_memory_tracker.getPeak();
Int64 rss = data.resident;
Int64 free_memory_in_allocator_arenas = 0;
#if USE_JEMALLOC
/// According to jemalloc man, pdirty is:
///
/// Number of pages within unused extents that are potentially
/// dirty, and for which madvise() or similar has not been called.
///
/// So they will be subtracted from RSS to make accounting more
/// accurate, since those pages are not really RSS but a memory
/// that can be used at anytime via jemalloc.
free_memory_in_allocator_arenas = je_malloc_pdirty * getPageSize();
#endif
/// proton : starts
new_values["MemoryTracker.Amount"] = amount;
new_values["MemoryTracker.Peak"] = peak;
Int64 difference = rss - amount;
/// Log only if difference is high (50MB). This is for convenience. The threshold is arbitrary.
if (difference >= 52'428'800 || difference <= -52'428'800)
LOG_INFO(log,
"MemoryTracking: was {}, peak {}, free memory in arenas {}, will set to {} (RSS), difference: {}",
ReadableSize(amount),
ReadableSize(peak),
ReadableSize(free_memory_in_allocator_arenas),
ReadableSize(rss),
ReadableSize(difference));
/// proton : ends
total_memory_tracker.setRSS(rss, free_memory_in_allocator_arenas);
}
}
#endif
#if defined(OS_LINUX)
if (loadavg)
{
try
{
loadavg->rewind();
Float64 loadavg1 = 0;
Float64 loadavg5 = 0;
Float64 loadavg15 = 0;
UInt64 threads_runnable = 0;
UInt64 threads_total = 0;
readText(loadavg1, *loadavg);
skipWhitespaceIfAny(*loadavg);
readText(loadavg5, *loadavg);
skipWhitespaceIfAny(*loadavg);
readText(loadavg15, *loadavg);
skipWhitespaceIfAny(*loadavg);
readText(threads_runnable, *loadavg);
assertChar('/', *loadavg);
readText(threads_total, *loadavg);
new_values["LoadAverage1"] = loadavg1;
new_values["LoadAverage5"] = loadavg5;
new_values["LoadAverage15"] = loadavg15;
new_values["OSThreadsRunnable"] = threads_runnable;
new_values["OSThreadsTotal"] = threads_total;
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
if (uptime)
{
try
{
uptime->rewind();
Float64 uptime_seconds = 0;
readText(uptime_seconds, *uptime);
new_values["OSUptime"] = uptime_seconds;
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
if (proc_stat)
{
try
{
proc_stat->rewind();
int64_t hz = sysconf(_SC_CLK_TCK);
if (-1 == hz)
throwFromErrno("Cannot call 'sysconf' to obtain system HZ", ErrorCodes::CANNOT_SYSCONF);
double multiplier = 1.0 / hz / (std::chrono::duration_cast<std::chrono::nanoseconds>(time_after_previous_update).count() / 1e9);
size_t num_cpus = 0;
ProcStatValuesOther current_other_values{};
ProcStatValuesCPU delta_values_all_cpus{};
while (!proc_stat->eof())
{
String name;
readStringUntilWhitespace(name, *proc_stat);
skipWhitespaceIfAny(*proc_stat);
if (name.starts_with("cpu"))
{
String cpu_num_str = name.substr(strlen("cpu"));
UInt64 cpu_num = 0;
if (!cpu_num_str.empty())
{
cpu_num = parse<UInt64>(cpu_num_str);
if (cpu_num > 1000000) /// Safety check, arbitrary large number, suitable for supercomputing applications.
throw Exception(ErrorCodes::CORRUPTED_DATA, "Too many CPUs (at least {}) in '/proc/stat' file", cpu_num);
if (proc_stat_values_per_cpu.size() <= cpu_num)
proc_stat_values_per_cpu.resize(cpu_num + 1);
}
ProcStatValuesCPU current_values{};
current_values.read(*proc_stat);
ProcStatValuesCPU & prev_values = !cpu_num_str.empty() ? proc_stat_values_per_cpu[cpu_num] : proc_stat_values_all_cpus;
if (!first_run)
{
ProcStatValuesCPU delta_values = current_values - prev_values;
String cpu_suffix;
if (!cpu_num_str.empty())
{
cpu_suffix = "CPU" + cpu_num_str;
++num_cpus;
}
else
delta_values_all_cpus = delta_values;
new_values["OSUserTime" + cpu_suffix] = delta_values.user * multiplier;
new_values["OSNiceTime" + cpu_suffix] = delta_values.nice * multiplier;
new_values["OSSystemTime" + cpu_suffix] = delta_values.system * multiplier;
new_values["OSIdleTime" + cpu_suffix] = delta_values.idle * multiplier;
new_values["OSIOWaitTime" + cpu_suffix] = delta_values.iowait * multiplier;
new_values["OSIrqTime" + cpu_suffix] = delta_values.irq * multiplier;
new_values["OSSoftIrqTime" + cpu_suffix] = delta_values.softirq * multiplier;
new_values["OSStealTime" + cpu_suffix] = delta_values.steal * multiplier;
new_values["OSGuestTime" + cpu_suffix] = delta_values.guest * multiplier;
new_values["OSGuestNiceTime" + cpu_suffix] = delta_values.guest_nice * multiplier;
}
prev_values = current_values;
}
else if (name == "intr")
{
readText(current_other_values.interrupts, *proc_stat);
skipToNextLineOrEOF(*proc_stat);
}
else if (name == "ctxt")
{
readText(current_other_values.context_switches, *proc_stat);
skipToNextLineOrEOF(*proc_stat);
}
else if (name == "processes")
{
readText(current_other_values.processes_created, *proc_stat);
skipToNextLineOrEOF(*proc_stat);
}
else if (name == "procs_running")
{
UInt64 processes_running = 0;
readText(processes_running, *proc_stat);
skipToNextLineOrEOF(*proc_stat);
new_values["OSProcessesRunning"] = processes_running;
}
else if (name == "procs_blocked")
{
UInt64 processes_blocked = 0;
readText(processes_blocked, *proc_stat);
skipToNextLineOrEOF(*proc_stat);
new_values["OSProcessesBlocked"] = processes_blocked;
}
else
skipToNextLineOrEOF(*proc_stat);
}
if (!first_run)
{
ProcStatValuesOther delta_values = current_other_values - proc_stat_values_other;
new_values["OSInterrupts"] = delta_values.interrupts;
new_values["OSContextSwitches"] = delta_values.context_switches;
new_values["OSProcessesCreated"] = delta_values.processes_created;
/// Also write values normalized to 0..1 by diving to the number of CPUs.
/// These values are good to be averaged across the cluster of non-uniform servers.
if (num_cpus)
{
new_values["OSUserTimeNormalized"] = delta_values_all_cpus.user * multiplier / num_cpus;
new_values["OSNiceTimeNormalized"] = delta_values_all_cpus.nice * multiplier / num_cpus;
new_values["OSSystemTimeNormalized"] = delta_values_all_cpus.system * multiplier / num_cpus;
new_values["OSIdleTimeNormalized"] = delta_values_all_cpus.idle * multiplier / num_cpus;
new_values["OSIOWaitTimeNormalized"] = delta_values_all_cpus.iowait * multiplier / num_cpus;
new_values["OSIrqTimeNormalized"] = delta_values_all_cpus.irq * multiplier / num_cpus;
new_values["OSSoftIrqTimeNormalized"] = delta_values_all_cpus.softirq * multiplier / num_cpus;
new_values["OSStealTimeNormalized"] = delta_values_all_cpus.steal * multiplier / num_cpus;
new_values["OSGuestTimeNormalized"] = delta_values_all_cpus.guest * multiplier / num_cpus;
new_values["OSGuestNiceTimeNormalized"] = delta_values_all_cpus.guest_nice * multiplier / num_cpus;
}
}
proc_stat_values_other = current_other_values;
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
if (meminfo)
{
try
{
meminfo->rewind();
uint64_t free_plus_cached_bytes = 0;
while (!meminfo->eof())
{
String name;
readStringUntilWhitespace(name, *meminfo);
skipWhitespaceIfAny(*meminfo, true);
uint64_t kb = 0;
readText(kb, *meminfo);
if (!kb)
{
skipToNextLineOrEOF(*meminfo);
continue;
}
skipWhitespaceIfAny(*meminfo, true);
/**
* Not all entries in /proc/meminfo contain the kB suffix, e.g.
* HugePages_Total: 0
* HugePages_Free: 0
* We simply skip such entries as they're not needed
*/
if (*meminfo->position() == '\n')
{
skipToNextLineOrEOF(*meminfo);
continue;
}
assertString("kB", *meminfo);
uint64_t bytes = kb * 1024;
if (name == "MemTotal:")
{
new_values["OSMemoryTotal"] = bytes;
}
else if (name == "MemFree:")
{
/// We cannot simply name this metric "Free", because it confuses users.
/// See https://www.linuxatemyram.com/
/// For convenience we also provide OSMemoryFreePlusCached, that should be somewhat similar to OSMemoryAvailable.
free_plus_cached_bytes += bytes;
new_values["OSMemoryFreeWithoutCached"] = bytes;
}
else if (name == "MemAvailable:")
{
new_values["OSMemoryAvailable"] = bytes;
}
else if (name == "Buffers:")
{
new_values["OSMemoryBuffers"] = bytes;
}
else if (name == "Cached:")
{
free_plus_cached_bytes += bytes;
new_values["OSMemoryCached"] = bytes;
}
else if (name == "SwapCached:")
{
new_values["OSMemorySwapCached"] = bytes;
}
skipToNextLineOrEOF(*meminfo);
}
new_values["OSMemoryFreePlusCached"] = free_plus_cached_bytes;
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);