15 MGR 管理面:模块、balancer 与观测


 TL;DR
MGR 是 Ceph 的管理面:它跑 30 多个 Python 模块,做 balancer、dashboard、告警与编排。本章讲 active/standby 两个角色怎么切换、PyModule 的加载与「每模块一线程」的模型、GIL 约束、模块能拿到哪些状态与接口,附 v22 对照表。
难度 中等

前十四章讲的都是数据面:客户端怎么读写、MON 怎么记事、PG 怎么恢复、
CRUSH 怎么放置、RBD 怎么翻译块写。

这一章讲管理面。Ceph 集群的很多「聪明事」都不在数据路径上:
数据放偏了谁去搬、OSD 满了谁去报警、用户要个 Web 界面谁去提供、
MDS 卡住了谁去诊断——这些全是 MGR 干的。

MGR 不是一个算法,它是一个跑 Python 模块的平台。

读完你应该能回答:

  1. MGR 有几个角色?active 和 standby 是两个进程还是一个进程的两个状态?
  2. 集群里 MGR 主备切换时,旧 active 是怎么下线的?
  3. 一个 Python 模块是怎么被 MGR 发现、加载、启动的?
  4. 每个模块跑在哪个线程里?GIL 带来了什么约束?
  5. 模块能拿到哪些集群状态?能改哪些东西?
  6. 模块怎么声明自己的 CLI 命令?C++ 侧怎么把它接到 ceph 命令行上?
  7. balancer 的「plan → optimize → show → rm」是怎么走的?它改的是什么?
  8. dashboard 和 prometheus 两种模块,在框架里是同一种东西吗?

本文所有行号基于 /work/cwork/ceph(v22.0.0 标签,commit 90b50e9b879,2026-10-28)。

15.1 先看全景

15.1.1 一句话定义

MGR 是 Ceph 的单点管理进程:它订阅 MON 的集群状态,把状态喂给一批
Python 模块,再把模块的请求转成对集群的操作。

规模先感受一下:

部分 位置 规模
C++ 框架 src/mgr/ 2.2 万行
Python 模块 src/pybind/mgr/ 20 万行,39 个模块目录

框架是 C++,模块是 Python。 这个分工是理解本章所有设计的关键。

15.1.2 三层结构

graph TD MON["MON<br/>集群状态"] MGR["ceph-mgr 进程"] CLI["ceph 命令行"] PY["Python 模块<br/>balancer / dashboard / prometheus ..."] DAEMON["OSD / MDS / RGW"] MON -->|"MgrMap / OSDMap / PGMap"| MGR CLI -->|"管理 socket"| MGR MGR <-->|"PyModule 接口"| PY MGR -->|"send_command"| DAEMON PY -->|"serve() / handle_command()"| MGR

四层:

  1. MON:状态的源头。MON 产生 MgrMap、OSDMap、PGMap、FSMap、
    ServiceMap,推给 MGR。
  2. ceph-mgr 进程:C++ 框架。它持有状态,管理线程与模块,把 CLI 请求
    路由到模块。
  3. Python 模块:真正干活的人。balancer 算数据分布、dashboard 起 Web
    服务、prometheus 采指标。
  4. 其他 daemon:模块通过 send_command 让 OSD/MDS/RGW 干活。

15.1.3 v22 的一件大事:balancer 已经不在 C++ 里了

老文章讲 balancer,一律指向 src/mgr/Balancer.cc。v22 里这个文件
不存在了
——src/mgr/ 下没有任何 balancer/ 子目录。

balancer 现在是纯 Python:src/pybind/mgr/balancer/module.py,1681 行。

这件事的来龙去脉是 Ceph 十年里最大的一次架构调整:把「集群管理」这件事
从 C++ 搬到 Python
。搬过去的理由很直接——管理逻辑需要频繁改,而 C++ 改一次
要重编整个 ceph-mgr;Python 改完重启模块即可。

代价是:GIL(下一节讲)和性能(balancer 算 upmap 是纯 Python 跑
在全量 PG 上)。Ceph 的应对是把 balancer 改成「先算 plan,人工确认,再执行」
的两段式——见 15.6 节。

15.2 进程结构:一个进程,两个角色

15.2.1 MgrStandby 是壳,Mgr 是芯

ceph-mgr 这个进程启动时是 standby(备用):

class MgrStandby : public Dispatcher,

(src/mgr/MgrStandby.h:35)

它持有一个 std::shared_ptr<Mgr> active_mgr(src/mgr/MgrStandby.h:61)——
这个指针为空时它是 standby,非空时它是 active。

所以「主备」不是两个进程,是一个进程里的两种状态。每个 MGR 节点都跑
standby,等着 MON 告诉它「你该当 active 了」。

15.2.2 谁是 active:看 MgrMap

判定逻辑在 MgrStandby::handle_mgr_map(src/mgr/MgrStandby.cc:452):

void MgrStandby::handle_mgr_map(ref_t<MMgrMap> mmap)
{
  auto &map = mmap->get_map();
  const bool active_in_map = map.active_gid == monc.get_global_id();

map.active_gid 就是裁决结果。MON 决定谁是 active,MGR 只是照着执行。

往下是三条分支:

if (active_in_map) {
  if (!active_mgr) {
    dout(1) << "Activating!" << dendl;
    active_mgr.reset(new Mgr(&monc, map, &py_module_registry,
                             client_messenger.get(), &objecter,
         clog, audit_clog));
    active_mgr->background_init(new LambdaContext(
          [this](int r){
            // Advertise our active-ness ASAP instead of waiting for
            // next tick.
            std::lock_guard l(lock);
            send_beacon();
          }));

从 standby 升到 active 时:新建一个 Mgr 对象、后台初始化它,然后
立刻发 beacon(不等下一个 tick),让别人马上知道它已经是 active 了。

降级分支:

} else if (active_mgr != nullptr) {
  derr << "I was active but no longer am" << dendl;
  respawn();
}

曾经是 active、现在不是了 → 直接 respawn()。

第三个分支是 standby 模式:

} else {
  if (map.active_gid != 0 && map.active_name != g_conf()->name.get_id()) {
    // I am the standby and someone else is active, start modules
    // in standby mode to do redirects if needed
    if (!py_module_registry.is_standby_running() &&
 g_conf().get_val<bool>("mgr_standby_modules")) {
      py_module_registry.standby_start(monc, finisher);
    }
  }
}

standby 也能跑模块——只要开了 mgr_standby_modules。但这些模块跑在
「standby 模式」下,只能做重定向这类辅助工作,不能改集群状态。

15.2.3 respawn:execv 重启自己

respawn() 的实现(src/mgr/MgrStandby.cc:399)值得单独看——它不是
exit() 再起一个新进程,而是用 execv 把当前进程原地替换掉:

char exe_path[PATH_MAX] = "";
if (readlink(PROCPREFIX "/proc/self/exe", exe_path, PATH_MAX-1) == -1) {
  ...
} else {
  dout(1) << "respawning with exe " << exe_path << dendl;
  strcpy(exe_path, PROCPREFIX "/proc/self/exe");
}
...
unblock_all_signals(NULL);
execv(exe_path, new_argv);

为什么要这么狠?因为 active ↔ standby 的切换涉及大量 C++ 对象的生命周期,
与其小心翼翼地拆,不如整个进程重来。execv 保留了 PID,外部看起来像是
「这个进程重启了一下」。

respawn() 上面还留了一段给未来人的警告注释:

// --- WARNING TO FUTURE COPY/PASTERS ---
// You must also add a call like
//
//   ceph_pthread_setname(pthread_self(), "ceph-mgr");
//
// to main() so that /proc/$pid/stat field 2 contains "(ceph-mgr)"
// instead of "(exe)", so that killall (and log rotation) will work.

/proc/$pid/stat 的第二个字段是进程名——不设对的话 killall ceph-mgr
和日志轮转都会失灵。这种坑只有真正读过代码的人才会知道。

15.2.4 standby 的心跳:beacon

standby 定期发 beacon(src/mgr/MgrStandby.cc:300),让 MON 和别的节点
知道「我还活着,而且状态如何」。active 刚升上去时也会立刻发一次(上面那段
background_init 的回调里)。

15.3 Python 模块框架

这是本章的核心。C++ 框架和 Python 模块之间的接口只有几个方法,
但每个方法背后的设计都不简单。

15.3.1 一个模块长什么样

Python 侧所有模块都继承 MgrModule(src/pybind/mgr/mgr_module.py:1096):

class MgrModule(ceph_module.BaseMgrModule, MgrModuleLoggingMixin):

ceph_module.BaseMgrModule 是 C++ 侧的基类(定义在 src/mgr/BaseMgrModule.cc,
头文件 src/mgr/BaseMgrModule.h 只有 7 行——类型对象本体在 .cc 里)。

一个最小模块长这样:

from mgr_module import MgrModule

class Module(MgrModule):
    MODULE_OPTIONS = [
        Option(name='foo', type='str', default='bar', desc='...'),
    ]

    def serve(self):
        # 阻塞直到 shutdown() 被调用
        while True:
            time.sleep(1)

    def shutdown(self):
        pass

serve() 是模块的主循环,必须阻塞。 shutdown() 负责让它退出。

15.3.2 C++ 侧:PyModule 负责「发现与装配」

PyModule(src/mgr/PyModule.h:66)代表「一个被加载的 Python 模块」。
它有四个状态位(src/mgr/PyModule.h:74-89),每一个都对应一个独立的问题:

// Did the MgrMap identify this module as one that should run?
bool enabled = false;

// Did the MgrMap flag this module as always on?
bool always_on = false;

// Did we successfully import this python module and look up symbols?
bool loaded = false;

// Did the module identify itself as being able to run?
bool can_run = false;

// Did the module encounter an unexpected error while running?
bool failed = false;

enabled / always_on 是「要不要跑」,loaded / can_run 是「能不能跑」,
failed 是「跑挂了」。
这四个位分开,是因为失败的方式不止一种:
模块没导入(loaded=false)、模块导入了但没实现 serve()(can_run=false)、
模块跑了但抛异常(failed=true)。

加载的主流程在 PyModule::load(src/mgr/PyModule.cc:363),它内部依次调:

步 函数 位置 干什么
1 load_notify_types :544 读 Python 侧的 notify 类型定义
2 load_options :633 读 MODULE_OPTIONS,注册成配置项
3 load_commands :585 读 COMMANDS,注册成 CLI 命令

load_commands(src/mgr/PyModule.cc:585)是「Python 模块怎么变成
ceph xxx 命令」的关键:它把 Python 侧声明的命令表读出来,翻译成 C++ 的
ModuleCommand(src/mgr/PyModule.h:55):

class ModuleCommand {
public:
  std::string cmdstring;
  std::string helpstring;
  std::string perm;
  bool polling;

  // Call the ActivePyModule of this name to handle the command
  std::string module_name;
};

perm 是权限(r / w / rw),polling 表示这是一个「轮询型」命令
(输出是持续刷新的),module_name 告诉框架「这个命令要转给哪个模块」。

PyModule::load_subclass_of(src/mgr/PyModule.cc:749)负责找到
Python 类本身——它按类名在模块里找,找不到就报错并把模块标成不可运行。

15.3.3 线程模型:每个模块一个 OS 线程

这是 MGR 最容易被误解的一点。

每个 Python 模块跑在自己的 OS 线程里,而 Python 的 serve() 是阻塞的。
C++ 侧靠 PyModuleRunner(src/mgr/PyModuleRunner.h:30)实现:

class PyModuleRunner
{
  ...
  class PyModuleRunnerThread : public Thread
  ...
};

线程体在 PyModuleRunner::PyModuleRunnerThread::entry(src/mgr/PyModuleRunner.cc:113)。

线程名的截断有点意思(src/mgr/PyModuleRunner.h:79-81):

// Shortened name for use as thread name, because thread names
// ...
thread_name = py_module->get_name().substr(0, 15);

线程名最长 15 个字符(Linux 的 comm 字段限制),所以长模块名会被截断。
ceph mgr module ls 看到的名字和 top -H 看到的可能不一样。

15.3.4 GIL:v22 的硬约束

线程模型带来一个绕不开的问题:Python 的 GIL。

MGR 的做法是每个模块一个线程状态(thread state),而不是共享一个:

int PyModuleRunner::serve()
{
  ceph_assert(pClassInstance != nullptr);

  // This method is called from a separate OS thread (i.e. a thread not
  // created by Python), so tell Gil to wrap this in a new thread state.
  Gil gil(py_module->pMyThreadState, true);
  ...
  auto pValue = PyObject_CallMethod(pClassInstance,
      const_cast<char*>("serve"), nullptr);

(src/mgr/PyModuleRunner.cc:40-52)

Gil 类在 src/mgr/Gil.h:64,它的析构函数会释放 GIL。所以模块的
serve() 运行时是不持 GIL 的——这正是它能并发跑多个模块的原因。

但 GIL 的老规矩还在,文件顶上就写着警告(src/mgr/Gil.h:56):

// Do *not* nest these, as a second GIL acquire will deadlock (see

不要嵌套获取 GIL——第二次获取会死锁。

Gil.h 里还写清了锁的顺序(src/mgr/Gil.h:79-81):

// 1. do not acquire locks when holding the GIL, use a without_gil or
//    without_gil_t to guard the code which acquires non-gil locks.

持 GIL 时不要拿别的锁。这条规矩是 MGR 模块开发里最容易踩的坑之一:
在 Python 模块里调一个会拿 C++ 锁的接口,同时又持有 GIL,就可能死锁。

15.3.5 ActivePyModule:命令怎么落到模块上

命令的处理在 ActivePyModule::handle_command(src/mgr/ActivePyModule.cc:255)。
ActivePyModule 继承自 PyModuleRunner,多了一个 per-module 的 Finisher
(src/mgr/ActivePyModule.h:54):

Finisher finisher; // per active module finisher to execute commands

每个模块有自己的命令执行队列——所以一个模块的命令不会阻塞别的模块。

Python 侧对应的方法在 src/pybind/mgr/mgr_module.py:2119:

def handle_command(self,
                   inbuf: str,
                   cmd: Dict[str, Any]) -> Union[HandleCommandResult,
                                                 Tuple[int, str, str]]:
    """
    Called by ceph-mgr to request the plugin to handle one
    of the commands that it declared in self.COMMANDS
    ...
    """

返回的是 (状态码, outbuf, outs) 三元组:outbuf 是二进制数据,
outs 是给人看的文本。

15.3.6 Python 侧怎么声明命令:CLICommand 装饰器

老文章讲 MGR 命令,提的都是 COMMANDS = [...] 这种老式列表。v22 里
推荐写法是装饰器(src/pybind/mgr/mgr_module.py:415):

class CLICommandBase(object):
    COMMANDS: Dict[str, 'CLICommandBase'] = {}

    def __init__(self,
                 prefix: str,
                 perm: str = 'rw',
                 poll: bool = False):
        self.prefix = prefix
        self.perm = perm
        self.poll = poll
        self.func = None
        ...

类名别名在 src/pybind/mgr/mgr_module.py:579:

CLICommand = CLICommandBase

用法:

class Module(MgrModule):
    @CLICommand('do-something', perm='r')
    def do_something(self, arg: str) -> Tuple[int, str, str]:
        return 0, '', 'ok'

装饰器做的事:从函数签名里抽出参数、读 docstring 当帮助文本、用
inspect.getfullargspec 拿类型注解,然后注册进 COMMANDS 字典。
src/mgr/PyModule.cc:487 的 walk_dict_list 就是遍历这个字典的辅助函数。

15.4 模块能拿到什么

一个模块能碰到的东西,决定了它能做什么。

15.4.1 ClusterState:只读的状态快照

ClusterState(src/mgr/ClusterState.h:36)是 MGR 持有的集群状态:

class ClusterState
{
  MonClient *monc;
  Objecter *objecter;
  FSMap fsmap;
  ServiceMap servicemap;
  ...
  MgrMap mgr_map;
  ...
  std::map<int64_t,unsigned> existing_pools; ///< pools that exist, and pg_num, as of PGMap epoch
  PGMap pg_map;
  PGMap::Incremental pending_inc;

  bufferlist health_json;
  bufferlist mon_status_json;

(src/mgr/ClusterState.h:36-52)

里面有:FSMap(MDS 的)、ServiceMap(RGW 的)、MgrMap(模块启用状态)、
PGMap(PG 分布)、以及两份 JSON(health_json、mon_status_json)。

各 daemon 的状态是按需拉取的,不是全量推给 MGR。DaemonServer
(src/mgr/DaemonServer.cc:204 初始化)负责管理这块:

void DaemonServer::fetch_missing_metadata(const DaemonKey& key,

(src/mgr/DaemonServer.cc:578)

模块想要某个 daemon 的状态,就发请求过去要,拿到后缓存。

15.4.2 配置:模块自己的配置项

模块在 MODULE_OPTIONS 里声明的配置项,会被框架注册成
mgr/<模块名>/<选项名> 这样的配置路径。

MODULE_OPTIONS = [
    Option(name='mode',
           type='str',
           default='upmap',
           enum_allowed=['none', 'crush-compat', 'upmap', 'read', 'upmap-read'],
           desc='...'),
]

(src/pybind/mgr/balancer/module.py:245)

读写接口在 Python 侧:

方法 位置
get_module_option src/pybind/mgr/mgr_module.py:2199
set_module_option src/pybind/mgr/mgr_module.py:2252
get_module_option_ex(读别的模块的) src/pybind/mgr/mgr_module.py:2206
set_module_option_ex src/pybind/mgr/mgr_module.py:2263

C++ 侧的实现(src/mgr/BaseMgrModule.cc:482 / :515)最终落到
ActivePyModules::get_config(src/mgr/ActivePyModules.cc:690)和
set_config(:821)。

15.4.3 KV 存储:模块自己的小数据库

模块需要一个持久化的地方存状态,用的是 set_kv / get_kv
(src/pybind/mgr/mgr_module.py:1319 / :1331)。

底层是一个 SQLite 数据库,schema 由模块自己定义:

def create_skeleton_schema(self, db: sqlite3.Connection) -> None:

(src/pybind/mgr/mgr_module.py:1297)

框架还提供 exclusive_db_access / exclusive_db_cursor 上下文管理器
(src/pybind/mgr/mgr_module.py:1449 / :1457),保证并发访问时
不打架。

15.4.4 send_command:让别的 daemon 干活

模块要执行真正的集群操作,靠 send_command
(src/pybind/mgr/mgr_module.py:2016),C++ 侧在
src/mgr/BaseMgrModule.cc:115:

ceph_send_command(BaseMgrModule *self, PyObject *args, PyObject *kwargs)

这是 balancer 改 upmap、orchestrator 编排的底层通道。

15.4.5 notify:模块之间的广播

ActivePyModule::notify(src/mgr/ActivePyModule.cc:58)让一个模块
给所有模块发通知。Python 侧是 notify(src/pybind/mgr/mgr_module.py:1484)。

典型用途:OSD 上下线了、OSDMap 变了,模块要知道哪些数据需要重新平衡。

广播的实现是 ActivePyModules::notify_all(src/mgr/ActivePyModules.cc:605)。

15.5 balancer:最典型的模块

balancer 是「MGR 到底能干什么」的最佳样本。

15.5.1 模块骨架

class Module(MgrModule):
    MODULE_OPTIONS = [
        ...
    ]

(src/pybind/mgr/balancer/module.py:243、:245)

balancer 的配置项里最能说明问题的是 mode:

Option(name='mode',
       type='str',
       default='upmap',
       enum_allowed=['none', 'crush-compat', 'upmap', 'read', 'upmap-read'],

(src/pybind/mgr/balancer/module.py:307)

五种模式:

模式 干什么
none 不做
crush-compat 用兼容 CRUSH 权重的办法(老办法)
upmap 用 pg-upmap(现代办法)
read 只调读取分布,不动数据
upmap-read 只看 upmap 的效果

15.5.2 plan:先算,不动

balancer 的流程是两段式的:先算出一个 plan(一份「建议怎么搬」的
清单),人确认后再执行。

def plan_optimize(self, plan: str, pools: List[str] = []) -> Tuple[int, str, str]:
    """
    Run optimizer to create a new plan
    """
    # The GIL can be release by the active balancer, so disallow when active
    if self.active:
        return (-errno.EINVAL, '', 'Balancer enabled, disable to optimize manually')
    if self.optimizing:
        return (-errno.EINVAL, '', 'Balancer finishing up....try again')

(src/pybind/mgr/balancer/module.py:588)

注意第一句注释:「GIL can be release by the active balancer」——
自动 balancer 跑的时候会释放 GIL(不阻塞别的模块),这时候人手动
plan optimize 就会被拒绝。这正是 15.3.4 那条 GIL 约束的体现。

算完存进 self.plans,可以用 plan_show(:621)看、
plan_rm(:631)删、plan_reset(:640)清空。

15.5.3 upmap:balancer 改的到底是什么

balancer 改的是 pg-upmap——一个「PG 到 OSD 的映射覆盖表」。

src/librbd/... 不对,是 OSD 侧的 OSDMap 里的东西。balancer 生成的
命令长这样(src/pybind/mgr/balancer/module.py:115-126):

for pgid in incdump.get('old_pg_upmap_items', []):
    ls.append('ceph osd rm-pg-upmap-items %s' % pgid)
for item in incdump.get('new_pg_upmap_items', []):
    ...
    ls.append('ceph osd pg-upmap-items %s %s' % ...)
for item in incdump.get('new_pg_upmap_primaries', []):
    ls.append('ceph osd pg-upmap-primary %s %s' % (item['pgid'], item['primary_osd']))

这四个操作正是第 05 章讲过的 OSDMap 里的三个成员
(pg_upmap_items / pg_upmap_primaries,见 src/osd/OSDMap.h:542-543)
加上它们的删除版本。

upmap 的意义:CRUSH 算出来的是「按权重和故障域算的理想位置」,
upmap 是在这个结果上手工覆盖。balancer 用它来消掉 CRUSH 的不完美
(比如 12 盘 3 副本的机架不均衡)。

balancer 还有两个调优项:

Option(name='upmap_max_optimizations',
       ...
Option(name='upmap_max_deviation',

(src/pybind/mgr/balancer/module.py:315、:320)

15.5.4 execute:执行计划

真正落地在 Module.execute(src/pybind/mgr/balancer/module.py:1506)。
它把 plan 里的 upmap 变更翻译成 ceph osd pg-upmap-* 命令,通过
send_command 发给 MON。

注意分工:balancer 只负责「算出该搬哪儿」,真正改 OSDMap 的是 MON
(MON 是唯一能改 OSDMap 的角色)。

15.6 dashboard 与 prometheus:两种模块形态

不是所有模块都长一个样。至少三种形态:

15.6.1 dashboard:起一个 Web 服务

class Module(MgrModule, CherryPyConfig):

(src/pybind/mgr/dashboard/module.py:249)

def serve(self):

(src/pybind/mgr/dashboard/module.py:351)

dashboard 在 serve() 里起一个 CherryPy HTTP 服务,然后阻塞。它是唯一
一个用 serve() 起服务而不是跑循环
的典型。

它还有个特点:除了 MGR 模块,它还自己起一个独立的进程(RocksDB 存
dashboard 的配置),以及一个前端静态资源服务。

15.6.2 prometheus:暴露一个抓取端点

class Module(MgrModule, OrchestratorClientMixin):

(src/pybind/mgr/prometheus/module.py:732)

def serve(self) -> None:

(src/pybind/mgr/prometheus/module.py:2522)

prometheus 也起服务,但目的相反:让 Prometheus 来拉指标,而不是模块
把指标推出去。它的 collect(src/pybind/mgr/prometheus/module.py:2347)负责把 Ceph 的 perf counter 翻译成
Prometheus 的文本格式。

15.6.3 只跑不服务:最常见的形态

大多数模块是第三种:serve() 里一个 while True: sleep(...) 循环,
靠 notify 被唤醒干活。比如 alerts、pg_autoscaler、devicehealth。

15.7 观测:MGR 怎么看集群的健康

15.7.1 perf counter

MGR 收集每个 daemon 的 perf counter,存成 DaemonPerfCounters
(src/mgr/DaemonPerfCounters.h:31):

// Performance counters for one daemon
class DaemonPerfCounters
{
  ...
  std::map<std::string, PerfCounterInstance> instances;

  void update(const MMgrReport& report);

模块通过 get_counter_latest(src/pybind/mgr/mgr_module.py:2355)读。

C++ 侧的批量转换在 ActivePyModules::with_perf_counters
(src/mgr/ActivePyModules.cc:942)。

15.7.2 daemon health

模块可以给 daemon 报健康状态。C++ 侧的入口是
ceph_set_health_checks(src/mgr/BaseMgrModule.cc:258):

ceph_set_health_checks(BaseMgrModule *self, PyObject *args)

健康指标的类型定义在 src/mgr/DaemonHealthMetric.h:14:

enum class daemon_metric : uint8_t {

15.7.3 线程监控

每个模块的线程都被 ThreadMonitor(src/mgr/ThreadMonitor.h)盯着,
用来发现「模块卡死」这类问题。

15.7.4 模块自己的存活指标

PyModule::perf_counter_build(src/mgr/PyModule.cc:823)会给每个模块
建一组 perf counter,其中 l_pym_alive 在 serve() 的入口置 1、出口置 0
(src/mgr/PyModuleRunner.cc:46、:78)。

所以「模块活着吗」这件事,是可以用 perf counter 直接回答的。

15.8 动手

15.8.1 看有哪些模块

# 列出所有可用模块和它们的状态
ceph mgr module ls

# 看某个模块的详细状态
ceph mgr module details balancer

输出里能看到每个模块的 enabled / always_on / running——
对应 15.3.2 节那几个状态位。

15.8.2 启停模块

ceph mgr module enable balancer
ceph mgr module disable balancer

# 关掉的模块不会加载,也不会占线程
ceph mgr module ls | grep balancer

15.8.3 模块的命令

# 模块声明的命令会直接出现在 ceph 命令行里
ceph balancer status
ceph balancer mode
ceph osd set-require-min-compat-client

模块的命令和 MON/OSD 的命令是同一套命令行——这就是 PyModule::load_commands
(src/mgr/PyModule.cc:585)干的事。

15.8.4 跑一遍 balancer 的两段式

# 1. 算一个 plan(不执行)
ceph balancer optimize pg-compute-please-move

# 2. 看 plan
ceph balancer show pg-compute-please-move

# 3. 满意就执行
ceph balancer execute pg-compute-please-move

# 4. 不满意就删
ceph balancer rm pg-compute-please-move

第 1 步在 balancer 自动开着的时候会失败——这正是 15.5.2 节那句注释
「GIL can be release by the active balancer」的现实后果:

ceph balancer off
ceph balancer optimize my-plan

15.8.5 看模块的配置项

# 模块的选项挂在 mgr/<模块名>/ 下面
ceph config show mgr/balancer | head -20

# 改一个
ceph config set mgr/balancer mode crush-compat

15.8.6 找 MGR 的线程

# 每个模块一个线程,名字是模块名(截断到 15 字符)
top -H -p $(pgrep ceph-mgr)

# 或者从 perf counter 看
ceph daemon $(hostname) mgr dump | head -40

15.8.7 用 GDB 看模块加载

gdb --args ceph-mgr -p /tmp/mgr.pid
(gdb) b PyModule::load
(gdb) b PyModule::load_commands
(gdb) continue

在 load_commands 停下时,p module_name 能看到正在处理哪个模块。

15.9 小结

MGR 是一个跑 Python 模块的平台,不是某个具体算法。

  • 两个角色一个进程:MgrStandby 是壳(src/mgr/MgrStandby.h:35),
    Mgr 是芯。谁当 active 由 MON 的 MgrMap.active_gid 决定
    (src/mgr/MgrStandby.cc:452)。
  • 切换用 execv 重启自己(src/mgr/MgrStandby.cc:399,execv 调用在 :439)——不拆对象,
    整个进程重来,PID 不变。
  • standby 也能跑模块,但只能做重定向这类辅助工作
    (mgr_standby_modules 配置)。
  • 每个模块一个 OS 线程(PyModuleRunner,src/mgr/PyModuleRunner.h:30),
    线程名截断到 15 字符。
  • GIL 不可嵌套(src/mgr/Gil.h:56);持 GIL 时不拿别的锁
    (src/mgr/Gil.h:79-81)。模块的 serve() 运行时是不持 GIL 的。
  • 模块能拿到:ClusterState(OSDMap/PGMap/FSMap/ServiceMap)、
    自己的配置项、一个 SQLite KV 库、send_command 通道、notify 广播。
  • 命令怎么进来:Python 侧用 @CLICommand 装饰器声明
    (src/pybind/mgr/mgr_module.py:415、:579),C++ 侧
    PyModule::load_commands(src/mgr/PyModule.cc:585)读出来注册进
    ceph 命令行;执行走 ActivePyModule::handle_command
    (src/mgr/ActivePyModule.cc:255),每个模块有自己的 Finisher。
  • balancer 已经搬到 Python(src/pybind/mgr/balancer/module.py),
    流程是 plan → optimize → show → execute 两段式,改的是 pg-upmap。

下一章(16 纠删码:插件、编码分片与恢复)
讲另一种「用更少的盘换更高冗余」的办法:纠删码。

15.10 v22 对照表

老文章里通常这么写 v22(本树)实际是
MGR 是纯 C++ 写的 框架 C++(2.2 万行),模块 Python(20 万行)
balancer 在 src/mgr/Balancer.cc 没有这个文件。balancer 是 src/pybind/mgr/balancer/module.py(1681 行)
MGR 有 active 和 standby 两个进程 一个进程两个状态:MgrStandby 持 active_mgr 指针(MgrStandby.h:61)
主的选举在 MGR 里做 MON 决定,MGR 照 MgrMap.active_gid 执行(src/mgr/MgrStandby.cc:456)
主备切换是优雅重启 execv 重启自己(src/mgr/MgrStandby.cc:399),PID 不变
standby 什么都不干 可以跑「standby 模式」的模块做重定向(mgr_standby_modules)
所有模块跑在一个线程里 每模块一个 OS 线程(PyModuleRunner),命令走 per-module Finisher
Python 模块有 GIL 所以是串行的 每个模块有独立 thread state,serve() 期间不持 GIL(src/mgr/PyModuleRunner.cc:48)
可以随便嵌套获取 GIL 会死锁(src/mgr/Gil.h:56 明确写了不要嵌套)
模块用 COMMANDS = [...] 声明命令 推荐用 @CLICommand 装饰器(src/pybind/mgr/mgr_module.py:415、:579)
模块配置写在配置文件里 模块选项注册成 mgr/<模块名>/<选项名> 配置路径
模块自己管持久化 框架给每个模块一个 SQLite 库(set_kv / get_kv)
ceph balancer status 直接改数据 两段式:optimize 只算 plan,execute 才执行(src/pybind/mgr/balancer/module.py:588、:1506)
balancer 改 CRUSH 权重 改 pg-upmap(pg_upmap_items / pg_upmap_primaries)
MGR 把整个集群状态都缓存下来 按需拉取:DaemonServer::fetch_missing_metadata(src/mgr/DaemonServer.cc:578)
dashboard 是一个 Web 应用 是 MGR 模块 + CherryPy,在 serve() 里起服务(src/pybind/mgr/dashboard/module.py:351)
MGR 模块都是同一种东西 至少三种形态:跑循环的、起 Web 服务的、暴露抓取端点的

15.11 相关阅读与源码入口

C++ 框架

  • src/mgr/MgrStandby.h / .cc — standby 壳、active 切换、execv respawn
  • src/mgr/Mgr.h / .cc — active 主体
  • src/mgr/PyModule.h / .cc — 模块加载、MODULE_OPTIONS / COMMANDS 读取
  • src/mgr/PyModuleRunner.h / .cc — 每模块一线程
  • src/mgr/ActivePyModule.h / .cc — 命令处理、notify
  • src/mgr/ActivePyModules.cc — 模块集合、配置、KV、perf counter
  • src/mgr/BaseMgrModule.cc — Python 可见的 C++ 接口(方法表在 :1602)
  • src/mgr/Gil.h — GIL 管理与锁顺序约定
  • src/mgr/ClusterState.h — 集群状态快照
  • src/mgr/DaemonServer.cc — daemon 元数据按需拉取
  • src/mgr/DaemonPerfCounters.h — perf counter 缓存
  • src/mgr/ThreadMonitor.h — 模块线程监控

Python 侧

  • src/pybind/mgr/mgr_module.py — MgrModule 基类(:1096)、
    CLICommand 装饰器(:415、:579)
  • src/pybind/mgr/balancer/module.py — balancer 全貌
  • src/pybind/mgr/dashboard/module.py — Web 服务形态
  • src/pybind/mgr/prometheus/module.py — 指标抓取形态
  • src/pybind/mgr/alerts/、pg_autoscaler/、orchestrator/ 等 39 个模块目录

相关章节


文章作者: growdu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 growdu !
  目录