Memory Tracker of memory management practice of graph database NebulaGraph

The memory management of the database is an important module in the design of the database kernel, and the measurable and controllable memory is an important guarantee for the stability of the database. Similarly, memory management is also critical to the graph database NebulaGraph.

The multi-degree relational query feature of the graph database often makes the execution layer of the graph database have a huge demand for memory. This article mainly introduces the new feature Memory Tracker introduced in NebulaGraph v3.4. It is hoped that through the introduction of the Memory Tracker module, fine-grained memory usage control can be achieved, the risk of graphd and storaged being OOM killed by the system will be reduced, and the performance of the NebulaGraph graph database will be improved. Kernel stability.

Note: In order to keep the correspondence with the code, some words in this article are directly used in English, eg reserve memory quota.

available memory

Before the introduction of Memory Tracker, here is the relevant background knowledge: available memory.

Process available memory

Here, we briefly introduce how the system judges the available memory in each mode.

physical machine mode

The database kernel will read the system directory /proc/meminfoto determine the actual memory and remaining memory of the current environment. Memory Tracker regards "actual physical memory" as "the maximum memory that a process can use";

Container/cgroup mode

There is a configuration item in nebula-graphd.confthe file FLAG_containerizedto determine whether the database is running on the container. After setting FLAG_containerized(the default is false) to true, the kernel will read the files under the relevant cgroup path to determine how much memory the current process can use; cgroup has two versions, v1 and v2, here we take v2 as an example;

FLAG Defaults explain
FLAG_cgroup_v2_memory_max_path /sys/fs/cgroup/memory.max Determine maximum memory usage by read path
FLAG_cgroup_v2_memory_current_path /sys/fs/cgroup/memory.current 通过读取路径确定当前内存使用量

举个例子,在单台机器上分别控制 graphd 和 storaged 的内存额度。你可以通过以下步骤:

step1:设置 FLAG_containerized=true

step2:创建 /sys/fs/cgroup/graphd//sys/fs/cgroup/storaged/,并配置各自目录下的 memory.max

step3:在 etc/nebula-graphd.confetc/nebula-storaged.conf 添加相关配置

--containerized=true
--cgroup_v2_controllers=/sys/fs/cgroup/graphd/cgroup.controllers
--cgroup_v2_memory_stat_path=/sys/fs/cgroup/graphd/memory.stat
--cgroup_v2_memory_max_path=/sys/fs/cgroup/graphd/memory.max
--cgroup_v2_memory_current_path=/sys/fs/cgroup/graphd/memory.current

Memory Tracker 可用内存

在获取“进程可用内存”以后,系统需要将其换算成 Memory Tracker 可 track 的内存,“进程可用内存”与“Memory Tracker 可用内存”有一个换算公式;

memtracker_limit = ( total - FLAGS_memory_tracker_untracked_reserved_memory_mb ) * FLAGS_memory_tracker_limit_ratio

usable_memory

FLAG 默认值 解释 支持动态改
memory_tracker_untracked_reserved_memory_mb 50 M Memory Tracker 会管理通过 new/delete 申请的内存,但进程除了通过此种方式申请内存外,还可能存在其他方式占用的内存;比如通过调用底层的 malloc/free 申请,这些内存通过此 flag 控制,在计算时会扣除此部分未被 track 的内存。 Yes
memory_tracker_limit_ratio 0.8 指定 Memory Tracker 可以使用的内存比例,在一些场景,我们可能需要调小来防止 OOM。 Yes

这里来详细展开说下 memory_tracker_limit_ratio 的使用:

  • 在混合部署环境中,存在多个 graphd 或 storaged 混合部署是需要调小。比如 graphd 只占用 50% 内存,则需在 nebula-graphd.conf 中将其手动改成 0.5;
  • 取值范围:memory_tracker_limit_ratio 除了 (0,1] 取值范围外,还额外定义了两个特殊值:
    • 2:通过数据库内核感知当前系统运行环境的可用内存,动态调整可用内存。由于此种方式非实时,有一定的概率会感知不精准;
    • 3:limit 将被设成一个极大值,起到关闭 Memory Tracker 的效果;

Memory Tracker 的设计与实现方案

下面,讲下 Memory Tracker 的设计与实现。整体的 Memory Tracker 设计,包含 Global new/delete operatorMemoryStatssystem mallocLimiter 等几个子模块。这个部分着重介绍下 Global new/delete operator 和 MemoryStats 模块。

memory_tracker

Global new/delete operator

Memory Tracker 通过 overload 全局 new/delete operator,接管内存的申请和释放,从而做到在进行真正的内存分配之前,进行内存额度分配的管理。这个过程分解为两个步骤:

  • 第一步:通过 MemoryStats 进行内存申请的汇报;
  • 第二步:调用 jemalloc 发生真正的内存分配行为;

jemalloc:Memory Tracker 不改变底层的 malloc 机制,仍然使用 jemalloc 进行内存的申请和释放;

MemoryStats

全局的内存使用情况统计,通过 GlobalMemoryStats 和 ThreadMemoryStats 分别对全局内存和线程内部内存进行管理;

ThreadMemoryStats

thread_local 变量,执行引擎线程在各自的 ThreadMemoryStats 中维护线程的 MemoryStats,包括“内存 Reservation 信息”和“是否允许抛异常的 throwOnMemoryExceeded”;

  • Reservation

每个线程 reserve 了 1 MB 的内存 quota,从而避免频繁地向 GlobalMemoryStats 索要额度。不管是申请还是返还时,ThreadMemoryStats 都会以一个较大的内存块作为与全局交换的单位。

alloc:在本地 reserved 1 MB 内存用完了,才问全局要下一个 1 MB。通过此种方式来尽可能降低向全局 quota 申请内存的频率;

dealloc:返还的内存先加到线程的 reserved 中,当 reserve quota 超过 1 MB 时,还掉 1 MB,剩下的自己留着;

 // Memory stats for each thread.
 struct ThreadMemoryStats {
   ThreadMemoryStats();
   ~ThreadMemoryStats();
 
   // reserved bytes size in current thread
   int64_t reserved;
   bool throwOnMemoryExceeded{false};
 };
  • throwOnMemoryExceeded  

线程在遇到超过内存额度时,是否 throw 异常。只有在设置 throwOnMemoryExceeded 为 true 时,才会 throw std::bad_alloc。需要关闭 throw std::bad_alloc 场景见 Catch std::bac_alloc 章节。

GlobalMemoryStats

全局内存额度,维护了 limit 和 used 变量。

  • limit:通过运行环境和配置信息,换算得到 Memory Tracker 可管理的最大内存。limit 同 Limiter 模块的作用,详细内存换算见上文“Memory Tracker 可用内存”章节;

  • used:原子变量,汇总所有线程汇报上来的已使用内存(包括线程 reserved 的部分)。如果 used + try_to_alloc > limit,且在 throwOnMemoryExceeded 为 true 时,则会抛异常std::bac_alloc

Catch std::bac_alloc

由于 Memory Tracker overload new/delete 会影响所有线程,包括三方线程。此时,throw bad_alloc 在一些第三方线程可能出现非预期行为。为了杜绝此类问题发生,我们采用在代码路径上主动开启内存检测,选择在算子、RPC 等模块主动开启内存检测;

算子的内存检测

在 graph/storage 的各个算子中,添加 try...catch (在当前线程进行计算/分配内存) 和 thenError (通过 folly::Executor 异步提交的计算任务),感知 Memory Tracker 抛出 std::bac_alloc。数据库再通过 Status 返回错误码,使查询失败;

在进行一些内存调试时,可通过打开 nebula-graphd.conf 文件中的 FLAGS_memory_tracker_detail_log 配置项,并调小 memory_tracker_detail_log_interval_ms 观察查询前后的内存使用情况;

folly::future 异步执行

thenValue([this](StorageRpcResponse<GetNeighborsResponse>&& resp) {
    memory::MemoryCheckGuard guard;
    // memory tracker turned on code scope
    return handleResponse(resp);
})
.thenError(folly::tag_t<std::bad_alloc>{},
    [](const std::bad_alloc&) {
    // handle memory exceed
})

同步执行

memory::MemoryCheckGuard guard; \
try {
    // ...
} catch (std::bad_alloc & e) { \
    // handle memory exceed
}

RPC 的内存检测

RPC 主要解决 Request/Response 对象的序列化/反序列化的内存额度控制问题,由于 storaged reponse 返回的数据均封装在 DataSet 数据结构中,所以问题转化为:DataSet 的序列化、反序列化过程中的内存检测。

序列化:DataSet 的对象构造在 NebulaGraph 算子返回结果逻辑中,默认情况下,已经开启内存检测;

反序列化:通过 MemoryCheckGuard 显式开启,在 StorageClientBase::getResponse's onError 可捕获异常;

错误码

为了便于分辨哪个模块发生问题,NebulaGraph 中还添加了相关错误码,分别表示 graphd 和 storaged 发生 memory exceeded 异常:

E_GRAPH_MEMORY_EXCEEDED = -2600, // Graph memory exceeded
E_STORAGE_MEMORY_EXCEEDED = -3600, // Storage memory exceeded

延伸阅读


谢谢你读完本文 (///▽///)

Guess you like

Origin juejin.im/post/7234058578801688613