1
#include "source/extensions/resource_monitors/fixed_heap/fixed_heap_monitor.h"
2

            
3
#include "envoy/extensions/resource_monitors/fixed_heap/v3/fixed_heap.pb.h"
4

            
5
#include "source/common/common/assert.h"
6
#include "source/common/memory/stats.h"
7
#include "source/common/runtime/runtime_features.h"
8

            
9
namespace Envoy {
10
namespace Extensions {
11
namespace ResourceMonitors {
12
namespace FixedHeapMonitor {
13

            
14
2
uint64_t MemoryStatsReader::reservedHeapBytes() { return Memory::Stats::totalCurrentlyReserved(); }
15

            
16
2
uint64_t MemoryStatsReader::unmappedHeapBytes() { return Memory::Stats::totalPageHeapUnmapped(); }
17

            
18
2
uint64_t MemoryStatsReader::freeMappedHeapBytes() { return Memory::Stats::totalPageHeapFree(); }
19

            
20
2
uint64_t MemoryStatsReader::allocatedHeapBytes() {
21
2
  return Memory::Stats::totalCurrentlyAllocated();
22
2
}
23

            
24
FixedHeapMonitor::FixedHeapMonitor(
25
    const envoy::extensions::resource_monitors::fixed_heap::v3::FixedHeapConfig& config,
26
    std::unique_ptr<MemoryStatsReader> stats)
27
5
    : max_heap_(config.max_heap_size_bytes()), stats_(std::move(stats)) {
28
5
  ASSERT(max_heap_ > 0);
29
5
}
30

            
31
4
void FixedHeapMonitor::updateResourceUsage(Server::ResourceUpdateCallbacks& callbacks) {
32

            
33
4
  size_t used = 0;
34
4
  if (Runtime::runtimeFeatureEnabled("envoy.reloadable_features.fixed_heap_use_allocated")) {
35
2
    used = stats_->allocatedHeapBytes();
36
2
  } else {
37
2
    const size_t physical = stats_->reservedHeapBytes();
38
2
    const size_t unmapped = stats_->unmappedHeapBytes();
39
2
    const size_t free_mapped = stats_->freeMappedHeapBytes();
40
2
    ASSERT(physical >= (unmapped + free_mapped));
41
2
    used = physical - unmapped - free_mapped;
42
2
  };
43

            
44
4
  Server::ResourceUsage usage;
45
4
  usage.resource_pressure_ = used / static_cast<double>(max_heap_);
46

            
47
4
  ENVOY_LOG_MISC(trace, "FixedHeapMonitor: used={}, max_heap={}, pressure={}", used, max_heap_,
48
4
                 usage.resource_pressure_);
49

            
50
4
  callbacks.onSuccess(usage);
51
4
}
52

            
53
} // namespace FixedHeapMonitor
54
} // namespace ResourceMonitors
55
} // namespace Extensions
56
} // namespace Envoy