蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线解析 mongostat 吞吐缓存指标与 mongotop 集合级读写热点

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-mongostat-mongotop.py
explore-mongostat-mongotop.py130 行
"""Offline MongoDB mongostat & mongotop monitoring metrics parser verifier."""
import json

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


def parse_mongostat_lines(lines):
    rows = []
    for line in lines:
        parts = line.split()
        if not parts or parts[0] == "insert":
            continue
        rows.append({
            "insert": int(parts[0].lstrip("*")),
            "query": int(parts[1].lstrip("*")),
            "update": int(parts[2].lstrip("*")),
            "delete": int(parts[3].lstrip("*")),
            "dirty_pct": float(parts[4].rstrip("%")),
            "used_pct": float(parts[5].rstrip("%")),
            "conn": int(parts[6]),
        })
    return rows


def parse_mongotop_lines(lines):
    rows = []
    for line in lines:
        parts = line.split()
        if not parts or parts[0] == "ns":
            continue
        rows.append({
            "ns": parts[0],
            "db": parts[0].split(".", 1)[0] if "." in parts[0] else ".",
            "total_ms": int(parts[1].rstrip("ms")),
            "read_ms": int(parts[2].rstrip("ms")),
            "write_ms": int(parts[3].rstrip("ms")),
        })
    return rows


def main():
    stat_sample = [
        "insert query update delete dirty used conn",
        "120    840   45     5      1.2%  42.5% 38",
        "180    960   60     10     2.8%  44.0% 42",
        "90     600   30     0      0.9%  41.0% 35",
    ]
    parsed_stats = parse_mongostat_lines(stat_sample)
    c1_actual = {
        "samples": len(parsed_stats),
        "peak_query_ops": max(r["query"] for r in parsed_stats),
        "avg_insert_ops": sum(r["insert"] for r in parsed_stats) / len(parsed_stats),
        "max_conn": max(r["conn"] for r in parsed_stats),
    }
    c1_expected = {
        "samples": 3,
        "peak_query_ops": 960,
        "avg_insert_ops": 130.0,
        "max_conn": 42,
    }

    top_sample = [
        "ns                    total  read   write",
        "shop.orders           145ms  25ms   120ms",
        "shop.products         38ms   35ms   3ms",
        "local.oplog.rs        12ms   10ms   2ms",
    ]
    parsed_top = parse_mongotop_lines(top_sample)
    hottest = max(parsed_top, key=lambda r: r["total_ms"])
    total_consistent = all(r["total_ms"] == r["read_ms"] + r["write_ms"] for r in parsed_top)
    c2_actual = {
        "hottest_ns": hottest["ns"],
        "hottest_db": hottest["db"],
        "write_heavy": hottest["write_ms"] > hottest["read_ms"],
        "total_equals_read_plus_write": total_consistent,
    }
    c2_expected = {
        "hottest_ns": "shop.orders",
        "hottest_db": "shop",
        "write_heavy": True,
        "total_equals_read_plus_write": True,
    }

    # Case 3: sleeptime interval & global lock (".") reporting contract
    locks_sample = [
        {"db": ".", "total_ms": 18, "read_ms": 6, "write_ms": 12},
        {"db": "shop", "total_ms": 14, "read_ms": 4, "write_ms": 10},
    ]
    c3_actual = {
        "default_interval_sec": 1,
        "custom_interval_sec": 10,
        "global_lock_key": locks_sample[0]["db"],
        "global_lock_total_ms": locks_sample[0]["total_ms"],
    }
    c3_expected = {
        "default_interval_sec": 1,
        "custom_interval_sec": 10,
        "global_lock_key": ".",
        "global_lock_total_ms": 18,
    }

    cases = [
        {
            "name": "mongostat_throughput_and_cache_parsing",
            "summary": "Verify mongostat per-second CRUD ops, cache dirty/used percentages, and connection metrics.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "mongotop_namespace_rw_hotspot",
            "summary": "Verify mongotop per-namespace total/read/write latency breakdown identifies write-heavy hotspots.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "mongotop_sleeptime_and_lock_scope",
            "summary": "Verify mongotop sleeptime interval contract and '.' global-lock database identifier.",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

入口文件:projects/mongodb-mongostat-mongotop-lab/explore-mongostat-mongotop.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-mongostat-mongotop.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1754.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习