如何基于 Prometheus exporter 监控 OPcache 命中率?

解读

在国内一线互联网公司与云托管厂商的 WordPress 面试中,OPcache 命中率是衡量 PHP 性能的核心指标之一。
Prometheus 作为云原生监控的事实标准,需要可观测性数据标准化、低侵入、可横向扩展。
题目要求“基于 Prometheus exporter”而非简单装个插件,意味着候选人必须:

  1. 理解 OPcache 内核指标(命中率、内存占用、重启次数等)
  2. 能把 PHP 运行时数据转成 Prometheus 文本格式
  3. 兼顾 WordPress 场景下的多站点、容器化、CI/CD落地细节
  4. 回答中体现安全、性能、可维护性三板斧,否则会被追问到挂

知识点

  • OPcache 四项黄金指标:hits、misses、hit_rate、oom_restarts
  • Prometheus 文本协议:以换行分隔的 key{label="value"} timestamp 格式,必须返回 Content-Type: text/plain; version=0.0.4
  • PHP 内置函数:opcache_get_status(false) 与 opcache_get_configuration(),注意 false 参数禁止获取脚本列表,防止敏感路径泄露
  • WordPress Hook 注入:在 init 或 rest_api_init 阶段注册路由,/metrics 端点需加 permission_callback 返回 current_user_can('manage_options'),避免未授权访问
  • 容器 sidecar 模式:把 exporter 写成单文件 PHP CLI,监听 0.0.0.0:9256,与 WordPress 解耦,方便水平扩 Pod
  • 多站点兼容:使用 $_SERVER['HTTP_HOST'] 作为 label,避免指标串扰
  • CI/CD 集成:在 Dockerfile 里用 multi-stage 把 exporter 复制到最终镜像,不引入 Composer 依赖,减少攻击面
  • 告警规则:hit_rate < 95% 持续 5 分钟则触发 Page,需排除 opcache.reset 刚执行后的抖动
  • 性能调优:指标采集 < 5 ms,使用 opcache.enable_cli=1 防止 CLI 模式 miss;对高并发场景加 APCu 缓存中间结果,降低重复计算

答案

  1. 编写最小 Prometheus exporter:
    新建 opcache_exporter.php,CLI 模式启动,监听 9256 端口。
    核心逻辑:

    $status = opcache_get_status(false);
    $hits   = $status['opcache_statistics']['hits'];
    $misses = $status['opcache_statistics']['misses'];
    $rate   = $hits / ($hits + $misses) * 100;
    echo "opcache_hit_rate{site=\"{$host}\"} {$rate}\n";
    echo "opcache_hits_total{site=\"{$host}\"} {$hits}\n";
    echo "opcache_misses_total{site=\"{$host}\"} {$misses}\n";
    

    返回 HTTP 200 并设置 Content-Type 为 text/plain; version=0.0.4

  2. 接入 WordPress(可选):
    若客户禁止额外进程,可在主题或插件里注册 REST 路由:

    add_action('rest_api_init', function () {
        register_rest_route('prom/v1', '/metrics', [
            'methods'  => 'GET',
            'permission_callback' => '__return_true', // 已用 IP 白名单或网关鉴权
            'callback' => 'opcache_metrics',
        ]);
    });
    

    回调函数同样拼装文本格式,禁止输出任何调试信息,防止破坏协议

  3. 部署与采集:

    • 容器环境:把 exporter 打包成 10 MB 以内的 distroless 镜像,非 root 用户运行,端口 9256
    • 传统主机:用 systemd 托管,PrivateTmp=true,限制 Capability
    • Prometheus job 配置:
      - job_name: 'wordpress-opcache'
        static_configs:
        - targets: ['pod-ip:9256']
        relabel_configs:
        - source_labels: [__meta_kubernetes_pod_name]
          target_label: pod
      
  4. 告警与大盘:

    • 记录规则:
      - record: wordpress:opcache:hit_rate5m
        expr: avg_over_time(opcache_hit_rate[5m])
      
    • 告警规则:
      - alert: OPcacheLowHitRate
        expr: wordpress:opcache:hit_rate5m < 95
        for: 5m
        annotations:
          summary: "站点 {{ $labels.site }} OPcache 命中率低于 95%"
      
    • Grafana 面板:增加 oom_restarts 折线,结合 container_memory_working_set_bytes 联合排查内存不足
  5. 安全加固:

    • 指标端点仅对内网开放,Ingress 加 WAF 规则阻断外网
    • 禁止输出脚本路径、key 名等敏感 label
    • 定期旋转容器镜像,使用 chainguard 或官方 php-fpm-alpine 最新补丁版本

拓展思考

  • 如果站点启用 Zend OPcache Preloading,命中率会瞬间逼近 100%,但内存占用上升,如何设计动态基线告警?
  • 在 多节点 Kubernetes 场景,每个 Pod 的 exporter 实例独立,如何聚合出“站点级”命中率而不重复计算?
  • 当 WordPress 使用 Batcache + Memcached 时,OPcache 命中率下降是否一定代表性能劣化?如何结合请求级别 trace 给出业务视角结论?
  • 国内部分云厂商限制 1024 以下端口,如何通过 Unix Domain Socket 让 exporter 与 nginx 同机通信,同时让 Prometheus 使用 node-exporter 的 textfile 收集器间接拉取?