返回题库

cgroup 内存限制

Cgroup Memory Limit

专题
Systems & Architecture / 系统与架构
难度
L3
来源
MyntBit

题目详情

容器化中的资源隔离对高频交易基础设施至关重要,防止单一策略的内存泄漏破坏共享系统。OOM 控制器通过优先级排序强制严格资源限制,在内存压力下终止低优先级进程。

任务:实现 OOMController 类,通过 cgroup v2 接口设置内存限制和 OOM 优先级。setMemoryLimit() 配置最大内存,setOOMPriority() 设置进程优先级(-1000 到 1000),监控 /sys/fs/cgroup 下的 OOM 事件。

英文原题

Resource isolation via containerization is critical in high-frequency trading infrastructure to prevent single-strategy memory leaks from destabilizing shared systems. An Out-Of-Memory (OOM) controller enforces strict resource limits by prioritizing the termination of low-priority or high-consumption processes during contention. This simulation models the logic used by Linux cgroups to maintain system stability under heavy load.
Task
Implement a class MemoryController that manages a fixed amoun

解析

问题分析

容器环境(如 Docker)通常通过 cgroup 限制进程内存。应用应读取 cgroup 限制而非物理内存大小,以避免超额分配导致 OOM kill。

实现

size_t getMemoryLimit() {
    std::ifstream f("/sys/fs/cgroup/memory/memory.limit_in_bytes");
    size_t limit;
    f >> limit;
    // 未设置限制时值为 ~0ULL(接近全物理内存)
    if (limit > (1ULL << 50)) limit = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE);
    return limit;
}

复杂度与边界

  • 时间复杂度:O(1) 文件读取
  • 空间复杂度:O(1)
  • 边界条件:(1) cgroup v2 路径为 /sys/fs/cgroup/memory.max (2) 未限制时回退到物理内存 (3) 仅 Linux 有效

英文解析

Analysis

Container environments (such as Docker) typically limit process memory via cgroups. Applications should read cgroup limits rather than physical memory size to avoid over-allocation leading to OOM kill.

Solution

size_t getMemoryLimit() {
    std::ifstream f("/sys/fs/cgroup/memory/memory.limit_in_bytes");
    size_t limit;
    f >> limit;
    // When no limit is set, value is ~0ULL (close to all physical memory)
    if (limit > (1ULL << 50)) limit = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE);
    return limit;
}

Complexity & Edge Cases

  • Time complexity: O(1) file read
  • Space complexity: O(1)
  • Edge cases: (1) cgroup v2 path is /sys/fs/cgroup/memory.max (2) Falls back to physical memory when unlimited (3) Only effective on Linux

Verification

Read cgroup limit inside Docker container with memory constraint. Verify limit matches container setting. Test fallback to physical memory outside containers.

Key Considerations

Memory-aware allocation is critical for containerized trading systems. Reading cgroup limits prevents order book caches from exceeding container memory and triggering OOM kill - the most catastrophic failure mode in production trading.