Kagome
Polkadot Runtime Engine in C++17
metrics_watcher.cpp
Go to the documentation of this file.
1 
6 #include "metrics_watcher.hpp"
7 
8 namespace {
9  constexpr auto storageSizeMetricName = "kagome_storage_size";
10 } // namespace
11 
12 namespace kagome::metrics {
13  namespace fs = boost::filesystem;
14 
16  std::shared_ptr<application::AppStateManager> app_state_manager,
17  const application::AppConfiguration &app_config,
18  std::shared_ptr<application::ChainSpec> chain_spec)
19  : storage_path_(app_config.databasePath(chain_spec->id())) {
20  BOOST_ASSERT(app_state_manager);
21 
22  // Metrics
24 
25  metrics_registry_->registerGaugeFamily(
26  storageSizeMetricName, "Consumption of disk space by storage");
28  metrics_registry_->registerGaugeMetric(storageSizeMetricName);
29 
30  app_state_manager->takeControl(*this);
31  }
32 
34  return true;
35  }
36 
38  thread_ = std::thread([this] {
39  while (not shutdown_requested_) {
40  auto storage_size_res = measure_storage_size();
41  if (storage_size_res.has_value()) {
42  metric_storage_size_->set(storage_size_res.value());
43  }
44 
45  // Granulated waiting
46  for (auto i = 0; i < 30; ++i) {
47  std::this_thread::sleep_for(std::chrono::seconds(1));
48  if (shutdown_requested_) break;
49  }
50  }
51  });
52 
53  return true;
54  }
55 
57  shutdown_requested_ = true;
58  if (thread_.joinable()) {
59  thread_.join();
60  }
61  }
62 
63  outcome::result<uintmax_t> MetricsWatcher::measure_storage_size() {
64  boost::system::error_code ec;
65 
66  fs::directory_entry entry(storage_path_);
67 
68  if (not fs::is_directory(storage_path_, ec)) {
69  if (ec) {
70  return ec;
71  }
72  return boost::system::errc::invalid_argument;
73  }
74 
75  uintmax_t total_size = 0;
76  for (fs::recursive_directory_iterator it(entry, ec);
77  it != fs::recursive_directory_iterator();
78  it.increment(ec)) {
79  if (!ec) {
80  const auto &dir_entry = *it;
81  auto size = fs::file_size(dir_entry, ec);
82  if (!ec) {
83  total_size += size;
84  }
85  }
86  }
87 
88  return outcome::success(total_size);
89  }
90 
91 } // namespace kagome::metrics
outcome::result< uintmax_t > measure_storage_size()
virtual void set(double val)=0
Set the gauge to the given value.
MetricsWatcher(std::shared_ptr< application::AppStateManager > app_state_manager, const application::AppConfiguration &app_config, std::shared_ptr< application::ChainSpec > chain_spec)
metrics::RegistryPtr metrics_registry_
RegistryPtr createRegistry()
boost::filesystem::path storage_path_