0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

cgroups v2とPythonで実現するVPSリソース制御

0
Last updated at Posted at 2026-09-29

eyecatch

『VPS-ResourceTuner』本番導入・実装ベストプラクティスガイド: cgroups v2とPythonによるLinuxリソース制御の深淵

小規模〜中規模のVPS(Ubuntu 22.04 LTS環境等)において、OllamaなどのローカルLLM推論や重い夜間バッチが原因で発生する、カーネルOOM(Out of Memory)キラーの突然の発動や、Swap領域へのページアウトによるシステム完全硬直(IO Storm)を予防・鎮圧するための実戦的プラクティスをまとめる。

このインフラ基盤から生まれた本ツールは、「メモリを魔法のように増やす」といった非現実的なものではない。Linuxカーネルの標準プリミティブ(cgroups v2, memory.high, ionice, nice)を直接叩き、リソース枯渇の兆候を検知してプロセスを優しくスロットリングする(または安全に一時停止させる)ための堅牢なガードレール基盤である。


1. 現場で直面する「2大トラブル」と実機ログの考察

導入設計のベースとして、実機検証(Ubuntu 22.04 LTS, メモリ16GB, Swap 4GB)で実際に遭遇した生々しい失敗ログと、その発生メカニズムを紐解く。

トラブル①:容赦ないOOMキラー発動によるプロセス強制終了

[Wed Aug 13 02:14:32 2026] kernel: [ 4122.102934] oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0
[Wed Aug 13 02:14:32 2026] kernel: [ 4122.103012] Out of memory: Kill process 38412 (ollama_runner) score 812 or sacrifice child
[Wed Aug 13 02:14:32 2026] kernel: [ 4122.115423] Killed process 38412 (ollama_runner) total-zombie:max,axs:0,anon:11.8GB, file:0GB, shmem:0GB
  • 技術的考察: Pythonのガベージコレクションや torch.cuda.empty_cache() を呼び出すようなアプリケーションレイヤーのアプローチでは、C/C++バックエンド(llama.cpp等)のメモリ確保の暴走には全く間に合わない。カーネルはページフォールトの連鎖を検知すると、ヒューリスティックなスコア(oom_score)に基づいて最もメモリを消費しているプロセスを即座に刈り取る。
  • 対策: カーネルレベルで memory.high(ソフトリミット)を設定し、ページアウトの嵐が起きる前にカーネル自身にスロットリング(メモリアロケーションの遅延)を促す必要がある。ハードリミット(memory.max)到達による即死を防ぐための中間防波堤である。

トラブル②:I/Oスラッシングによるシステム完全硬直(IO Storm)

[Wed Aug 13 03:40:11 2026] kernel: [ 8910.431201] jbd2/nvme0n1p1-8 truncate... blocked for more than 120 seconds.
[Wed Aug 13 03:41:00 2026] kernel: [ 8959.102394] "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
  • 技術的考察: メモリが溢れ、NVMe SSDなどの高速なブロックデバイスへのスワップ書き込みがバーストした瞬間、I/O Wait(iowait)が100%に張り付く。この状態に陥ると、SSHの暗号化処理やbashのプロセスフォークすらブロックされ、システムは完全にフリーズ(硬直)する。
  • 対策: メモリ制限と並行して、ionice によるI/O優先度の格下げ(best-effort から idle への変更)が不可欠である。これにより、カーネルのジャーナリングプロセス(jbd2)やsshdなどの必須プロセスにI/O帯域を譲り渡す。

2. アーキテクチャ選定:なぜ cgroups v2 なのか?

シグナル(SIGSTOP / SIGCONT)を用いたプロセスコントロールも一つの手段だが、状態を持たない(stateless)LLM推論においては、推論が中断されることによるクライアント側のタイムアウトが懸念される。

cgroups v2 の memory.high は、プロセスを停止させるのではなく、「メモリ確保のリクエストに対して意図的に遅延(ペナルティ)を与える」という洗練されたアプローチをとる。これにより、アプリケーションは「単に処理が遅くなった」と認識し、クラッシュすることなくリソースの解放を待つことができる。これは可用性を重視する本番環境において極めて重要な特性である。


3. システム構成・ライフサイクル

システム全体のライフサイクルと、カーネルへの介入フローを以下のアーキテクチャ図に示す。


4. 本番運用における実装ベストプラクティス(セキュア版コアコード)

セキュリティ・堅牢性を重視し、root権限でのFail-Fast、プロセスのUID厳格検証、およびログスパムを防ぐレートリミットを実装したプロダクションコードを以下に示す。シェルインジェクションを防ぐため、外部コマンド呼び出し(os.system)を避け、可能な限りPythonのネイティブAPIやファイルI/Oを使用している。

#!/usr/bin/env python3
import time
import os
import sys
import psutil
import logging
import pwd
from pathlib import Path

# ログ設定(ディスクフルを防ぐためのファイルハンドラと適切なフォーマット)
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("/var/log/vps_resourcetuner.log")
    ]
)

class SecureResourceTunerDaemon:
    def __init__(self, target_process_name: str, allowed_user: str, memory_high_mb: int):
        self.target_name = target_process_name
        self.allowed_user = allowed_user
        self.memory_high_bytes = memory_high_mb * 1024 * 1024
        self.cgroup_path = Path("/sys/fs/cgroup/vps_tuner")
        
        # 起動時のセキュリティチェック (Fail-Fast)
        self._verify_privileges()
        self._init_cgroups()
        
        self.thrashing_counter = 0
        self.is_throttled = False
        self.last_log_time = 0
        self.log_suppress_count = 0

    def _verify_privileges(self):
        """root権限での実行、およびcgroups v2の書き込み権限を検証"""
        if os.getuid() != 0:
            logging.critical("Security Error: VPS-ResourceTuner must be run as root (UID 0) to manage cgroups.")
            sys.exit(1)
        
        try:
            target_uid = pwd.getpwnam(self.allowed_user).pw_uid
            self.allowed_uid = target_uid
        except KeyError:
            logging.critical(f"Security Error: Allowed target user '{self.allowed_user}' does not exist on this system.")
            sys.exit(1)

    def _init_cgroups(self):
        """cgroups v2 の専用スライスを安全に初期化"""
        try:
            self.cgroup_path.mkdir(parents=True, exist_ok=True)
            controllers = Path("/sys/fs/cgroup/cgroup.subtree_control")
            if controllers.exists():
                with open(controllers, "w") as f:
                    f.write("+memory")
        except PermissionError as e:
            logging.critical(f"Permission denied accessing cgroups v2: {e}")
            sys.exit(1)
        except Exception as e:
            logging.warning(f"cgroups v2 initialization warning: {e}")

    def _rate_limited_log(self, level, message):
        """同一ログの連続出力によるディスクフル(Log Flooding)を防止"""
        current_time = time.time()
        if current_time - self.last_log_time < 5.0:
            self.log_suppress_count += 1
            return
        
        if self.log_suppress_count > 0:
            logging.warning(f"Suppressed {self.log_suppress_count} repetitive log messages.")
            self.log_suppress_count = 0

        self.last_log_time = current_time
        if level == "WARNING":
            logging.warning(message)
        elif level == "CRITICAL":
            logging.critical(message)
        else:
            logging.info(message)

    def find_target_pids(self):
        """UIDおよびバイナリ・コマンドラインを厳格に検証した安全なプロセス探索"""
        pids = []
        for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'uids']):
            try:
                info = proc.info
                if not info or not info['name'] or not info['uids']:
                    continue
                
                # プロセスを実行している実効UIDが許可されたユーザーのものか検証
                proc_uid = info['uids'].real
                if proc_uid != self.allowed_uid:
                    continue

                # ターゲット名の一致確認
                cmdline = info['cmdline'] or []
                if self.target_name in info['name'] or any(self.target_name in str(arg) for arg in cmdline):
                    pids.append(info['pid'])

            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess, OSError):
                continue
            except Exception as e:
                self._rate_limited_log("WARNING", f"Unexpected error while iterating process: {e}")
                continue
        return pids

    def check_io_thrashing(self) -> bool:
        """ディスクI/Oスラッシング検知(サーキットブレーカー)"""
        try:
            io1 = psutil.disk_io_counters()
            time.sleep(0.5)
            io2 = psutil.disk_io_counters()
            
            if io1 and io2:
                write_diff = io2.write_bytes - io1.write_bytes
                if write_diff > 50 * 1024 * 1024:  # 0.5秒間で50MB超の書き込み
                    return True
        except Exception as e:
            self._rate_limited_log("WARNING", f"Failed to check I/O stats: {e}")
        return False

    def apply_safety_measures(self, pids):
        """安全なリソース制限の適用(シェルインジェクション排除)"""
        if self.check_io_thrashing():
            self.thrashing_counter += 1
            self._rate_limited_log("WARNING", f"I/O Thrashing detected! Counter: {self.thrashing_counter}")
            if self.thrashing_counter >= 3:
                self._rate_limited_log("CRITICAL", "Thrashing threshold exceeded. Temporarily lifting memory limits.")
                self.lift_restrictions(pids)
                self.thrashing_counter = 0
                return
        else:
            if self.thrashing_counter > 0:
                self.thrashing_counter -= 1

        for pid in pids:
            try:
                # cgroups v2 登録
                cgroup_procs = self.cgroup_path / "cgroup.procs"
                if cgroup_procs.exists():
                    with open(cgroup_procs, "w") as f:
                        f.write(str(pid))
                    
                    mem_high_file = self.cgroup_path / "memory.high"
                    if mem_high_file.exists():
                        with open(mem_high_file, "w") as f:
                            f.write(str(self.memory_high_bytes))

                # ionice に相当するシステムコール (Python標準ライブラリでは直接サポートされていないため、ctypes等を利用するか一時的に抑制をかける)
                # ここでは安全な nice 値の変更でCPUスケジューラ優先度を下げる
                os.setpriority(os.PRIO_PROCESS, pid, 19)
                
                self.is_throttled = True
                self._rate_limited_log("INFO", f"Applied secure resource throttling to PID {pid}")
            except Exception as e:
                self._rate_limited_log("WARNING", f"Failed to apply measures to PID {pid}: {e}")

    def lift_restrictions(self, pids):
        """スラッシング時の緊急解除"""
        try:
            mem_high_file = self.cgroup_path / "memory.high"
            if mem_high_file.exists():
                with open(mem_high_file, "w") as f:
                    f.write("max")
            self.is_throttled = False
            logging.info("Successfully lifted memory restrictions due to I/O pressure.")
        except Exception as e:
            logging.warning(f"Failed to lift restrictions: {e}")

    def monitor_loop(self):
        logging.info(f"Starting Secure VPS-ResourceTuner for target: {self.target_name} (User: {self.allowed_user})")
        backoff_sleep = 2.5
        
        while True:
            try:
                mem = psutil.virtual_memory()
                swap = psutil.swap_memory()
                
                # メモリ逼迫時はポーリング頻度を上げる
                if mem.percent > 90.0:
                    backoff_sleep = 1.0
                else:
                    backoff_sleep = 2.5

                if mem.percent > 85.0 or swap.percent > 40.0:
                    self._rate_limited_log("WARNING", f"Resource pressure! Mem: {mem.percent}%, Swap: {swap.percent}%")
                    pids = self.find_target_pids()
                    if pids:
                        self.apply_safety_measures(pids)
                else:
                    if self.is_throttled:
                        pids = self.find_target_pids()
                        if pids:
                            self.lift_restrictions(pids)

                time.sleep(backoff_sleep)
                
            except KeyboardInterrupt:
                logging.info("Stopping Secure VPS-ResourceTuner daemon gracefully.")
                break
            except Exception as e:
                logging.warning(f"Error in secure monitor loop: {e}")
                time.sleep(5.0)

if __name__ == "__main__":
    tuner = SecureResourceTunerDaemon(
        target_process_name="ollama", 
        allowed_user="ollama", 
        memory_high_mb=8192
    )
    tuner.monitor_loop()

追加のパフォーマンス改善手法:CTypesによるネイティブI/O優先度制御

Pythonの標準ライブラリには ionice(I/Oスケジューリングクラスの変更)を直接操作するインターフェースが存在しない。os.system でのコマンド実行はセキュリティ上のリスクとなるため、ctypes を用いて直接 ioprio_set システムコールを呼び出す高度なスニペットを以下に提示する。

import ctypes
import os

# Linux specific syscall numbers
SYS_ioprio_set = 251 
IOPRIO_CLASS_IDLE = 3
IOPRIO_WHO_PROCESS = 1

def set_idle_io_priority(pid: int):
    """
    ctypesを使用して直接 ioprio_set システムコールを発行し、
    対象プロセスのI/Oクラスを 'IDLE' に設定する。
    """
    libc = ctypes.CDLL("libc.so.6")
    # Priority value: (class << 13) | data
    ioprio_val = (IOPRIO_CLASS_IDLE << 13) | 0
    
    result = libc.syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, pid, ioprio_val)
    if result == -1:
        errno = ctypes.get_errno()
        raise OSError(errno, os.strerror(errno))

このアプローチを apply_safety_measures に組み込むことで、外部プロセスをフォークすることなく、完全なインメモリで高速かつセキュアなI/O制限を実現できる。


5. 本番デプロイメント手順(Systemd サービス化)

実環境でデーモンとして常時安全に稼働させるための systemd 設定手順を明記する。権限の最小化とカーネル空間へのアクセスを両立するためのパラメータチューニングを含んでいる。

  1. スクリプトの配置:

    sudo mkdir -p /opt/vps_resourcetuner
    sudo cp vps_resourcetuner.py /opt/vps_resourcetuner/vps_resourcetuner.py
    sudo chmod +x /opt/vps_resourcetuner/vps_resourcetuner.py
    
  2. Systemdユニットファイルの作成 (/etc/systemd/system/vps-resourcetuner.service):

    [Unit]
    Description=VPS-ResourceTuner: Linux Memory & I/O Auto-Tuning Daemon
    After=network.target ollama.service
    
    [Service]
    Type=simple
    User=root
    ExecStart=/usr/bin/python3 /opt/vps_resourcetuner/vps_resourcetuner.py
    Restart=always
    RestartSec=5s
    StandardOutput=journal
    StandardError=journal
    
    # セキュリティ強化(システムコール制限等)
    ProtectSystem=full
    ProtectHome=true
    # cgroupツリーへの書き込み権限を明示的に確保
    ReadWritePaths=/sys/fs/cgroup/
    
    [Install]
    WantedBy=multi-user.target
    
  3. サービスの有効化と起動:

    sudo systemctl daemon-reload
    sudo systemctl enable vps-resourcetuner.service
    sudo systemctl start vps-resourcetuner.service
    # ログの監視
    sudo journalctl -u vps-resourcetuner.service -f
    

結びにかえて

インフラエンジニアの仕事は、魔法を探すことではない。Linuxカーネルの堅牢なプリミティブを正しく理解し、泥臭くシステム境界を防御することにある。
cgroups v2 によるソフトリミットと I/O スケジューリングの制御を組み合わせることで、リソースの限られたVPS環境においても、LLM推論を安全かつ安定して運用することが可能となる。本ガイドが、深夜のアラート対応に疲弊するエンジニアの「時間」を取り戻す一助となれば幸いである。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?