侧边栏壁纸
博主头像
一揽芳华 博主等级

行动起来,活在当下

  • 累计撰写 265 篇文章
  • 累计创建 24 个标签
  • 累计收到 4 条评论

目 录CONTENT

文章目录

2.8.监控mongodb

芳华是个男孩!
2024-10-14 / 0 评论 / 0 点赞 / 12 阅读 / 0 字
广告 广告

title: 2.8.监控mongodb
order: 13

icon: lightbulb

一、环境

主机名

IP地址

系统

说明

localhost

192.168.11.61

Ubuntu 20.04

docker安装的prometheus

test

192.168.11.62

Ubuntu 20.04

mongo版本4.2.5,Docker 版本 23.0.1

1、环境搭建

docker安装

docker-compose安装

mongodb

已经在监控nginx那节课安装好了

cd /data/mongodb

使用cat创建文件

cat >>docker-compose.yaml<<"EOF"
version: '3'
services:
  mongo:
    image: mongo:4.2.5
    container_name: mongo
    restart: always
    volumes:
      - /data/mongo/db:/data/db
    ports:
      - 27017:27017
    command: [--auth]
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: 123456
EOF

运行

docker-compose up -d

二、监控mongodb

1、创建监控用户

登陆mongodb创建监控用户,权限为“readAnyDatabase”,如果是cluster环境,需要有权限“clusterMonitor”

登录mongodb(docker安装的mongo)

docker exec -it mongo mongo admin

登录mongodb(yum和apt安装的mongo)

mongo admin

创建监控用户

> db.auth('root','123456')
1
> db.createUser({ user:'exporter',pwd:'password',roles:[ { role:'readAnyDatabase', db: 'admin'},{ role: "clusterMonitor", db: "admin" }]});
#测试 使用上面创建的用户信息进行连接。
> db.auth('exporter', 'password')
1
#表示成功
> exit

2、二进制安装(二选一)

mongodb_exporter地址:https://github.com/percona/mongodb_exporter/releases

或:https://github.com/prometheus/mysqld_exporter/releases

下载二进制包解压并放入/opt目录

wget https://github.com/percona/mongodb_exporter/releases/download/v0.37.0/mongodb_exporter-0.37.0.linux-amd64.tar.gz


tar xf mongodb_exporter-0.37.0.linux-amd64.tar.gz


mv mongodb_exporter-0.37.0.linux-amd64 /opt/prometheus/mongodb_exporter

创建用户

useradd -M -s /usr/sbin/nologin prometheus

更改exporter文件夹权限

chown prometheus:prometheus -R /opt/prometheus

创建 systemd 服务

mongodb_exporter.service

cat <<EOF >/usr/lib/systemd/system/mongodb_exporter.service
[Unit]
Description=mongodb_exporter
Documentation=https://github.com/percona/mongodb_exporter
After=network.target

[Service]
Type=simple
User=prometheus
Environment="MONGODB_URI=mongodb://exporter:password@localhost:27017/admin"
ExecStart=/opt/prometheus/mongodb_exporter/mongodb_exporter --log.level=error --collect-all --compatible-mode
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

启动 mongodb_exporter

systemctl daemon-reload

systemctl start mongodb_exporter.service

加入到开机自启动

systemctl enable mongodb_exporter.service

检查

systemctl status mongodb_exporter.service

启动不了检查日志

journalctl -u mongodb_exporter.service -f

3、docker安装(二选一)

docker直接运行

docker run -d --restart=always -p 9216:9216 -p 17001:17001 --restart=always --name=mongodb-exporter  bitnami/mongodb-exporter:latest --collect-all --compatible-mode --mongodb.uri=mongodb://exporter:password@192.168.11.62:27017/admin?ssl=false

docker-compose方式

cat >docker-compose.yaml <<EOF
version: '3.3'
services:
  mongodb_exporter:
    image: bitnami/mongodb-exporter:latest
    container_name: mongodb_exporter
    restart: always
    environment:
      MONGODB_URI: "mongodb://exporter:password@192.168.11.62:27017/admin?ssl=false"
    command:
      - '--collect-all'
      - '--compatible-mode'
    ports:
      - "9216:9216"
EOF

启动

docker-compose up -d

检查

docker ps
或:
docker logs -f mongodb_exporter

4、参数解释

Flag

含义

案例

-h, --help

显示上下文相关的帮助

--[no-]compatible-mode

启用旧的 mongodb-exporter 兼容指标

--[no-]discovering-mode

启用自动发现集合

--mongodb.collstats-colls

逗号分隔的 databases.collections 列表以获取 $collStats

--mongodb.collstats-colls=db1,db2.col2

--mongodb.indexstats-colls

逗号分隔的 databases.collections 列表以获取 $indexStats

--mongodb.indexstats-colls=db1.col1,db2.col2

--[no-]mongodb.direct-connect

是否应该进行直接连接。如果指定了多个主机或使用了 SRV URI,则直接连接无效

--[no-]mongodb.global-conn-pool

使用全局连接池而不是为每个 http 请求创建新池

--mongodb.uri

MongoDB 连接 URI ($MONGODB_URI)

--mongodb.uri=mongodb://user:pass@127.0.0.1:27017/admin?ssl=true

--web.listen-address

用于侦听 Web 界面和遥测的地址

--web.listen-address=":9216"

--web.telemetry-path

指标公开路径

--web.telemetry-path="/metrics"

--web.config

具有用于基本身份验证的 Prometheus TLS 配置的文件的路径

--web.config=STRING

--log.level

仅记录具有给定严重性或更高严重性的消息。有效级别:[调试、信息、警告、错误、致命]

--log.level="error"

--collector.diagnosticdata

启用从 getDiagnosticData 收集指标

--collector.replicasetstatus

启用从 replSetGetStatus 收集指标

--collector.dbstats

启用从 dbStats 收集指标

--collector.topmetrics

启用从 top admin command 收集指标

--collector.indexstats

启用从 $indexStats 收集指标

--collector.collstats

启用从 $collStats 收集指标

--collect-all

启用所有收集器。与指定所有 --collector. 相同

--collector.collstats-limit=0

如果有超过 个集合,请禁用 collstats、dbstats、topmetrics 和 indexstats 收集器。0=无限制

--metrics.overridedescendingindex

启用降序索引名称覆盖以将 -1 替换为 _DESC

--version

显示版本并退出

5、metrics地址

注:安装好Exporter后会暴露一个http://ip:端口/metrics的HTTP服务

名称

地址

备注

mongodb_exporter

http://192.168.11.62:9216/metrics

6、Prometheus配置

配置prometheus去采集(拉取)mongodb_exporter的监控样本数据

cd /data/docker-prometheus 

#在scrape_configs(搜刮配置):下面增加如下配置:

cat >> prometheus/prometheus.yml << "EOF"
  - job_name: 'mongodb_exporter'
    static_configs:
    - targets: ['192.168.11.62:9216']
      labels:
        instance: test服务器
EOF

重新加载配置

curl -X POST http://localhost:9090/-/reload

检查

7、常用的监控指标

mongodb_ss_connections{conn_type="available"} 可用的连接总数

mongodb_ss_mem_virtual
mongodb_ss_mem_resident



# 关于 server status
mongodb_up                                              # 服务器是否在线
mongodb_ss_ok{cl_id="", cl_role="mongod", rs_state="0"} # 服务器是否正常运行,取值为 1、0 。标签中记录了 Cluster、ReplicaSet 的信息
mongodb_ss_uptime                                       # 服务器的运行时长,单位为秒
mongodb_ss_connections{conn_type="current"}             # 客户端连接数

# 关于主机
mongodb_sys_cpu_num_cpus                                # 主机的 CPU 核数

# 关于 collection
mongodb_collstats_storageStats_count{database="xx", collection="xx"}  # collection 全部文档的数量
mongodb_collstats_storageStats_size                     # collection 全部文档的体积,单位 bytes
mongodb_collstats_storageStats_storageSize              # collection 全部文档占用的磁盘空间,默认会压缩
delta(mongodb_collstats_latencyStats_reads_ops[1m])     # collection 读操作的数量(每分钟)
delta(mongodb_collstats_latencyStats_reads_latency[1m]) # collection 读操作的延迟(每分钟),单位为微秒
mongodb_collstats_latencyStats_write_ops
mongodb_collstats_latencyStats_write_latency

# 关于 index
mongodb_collstats_storageStats_nindexes                 # collection 的 index 数量
mongodb_collstats_storageStats_totalIndexSize           # collection 的 index 占用的磁盘空间
delta(mongodb_indexstats_accesses_ops[1m])   # index 被访问次数

# 关于操作
delta(mongodb_ss_opcounters[1m])                        # 执行各种操作的数量
delta(mongodb_ss_opLatencies_latency[1m])               # 执行各种操作的延迟,单位为微秒
delta(mongodb_ss_metrics_document[1m])                  # 各种文档的变化数量

# 关于锁
delta(mongodb_ss_locks_acquireCount{lock_mode="w"}[1m]) # 新加锁的数量。R 表示共享锁,W 表示独占锁,r 表示意向共享锁,w 表示意向独占锁
mongodb_ss_globalLock_currentQueue{count_type="total"}  # 被锁阻塞的操作数

8、触发器配置

Prometheus配置

# 报警(触发器)配置
rule_files:
  - "alert.yml"  
  - "rules/*.yml"

mongodb触发器(告警规则)

因mongo单点,所以未配置复制触发器

cat >> prometheus/rules/mongodb.yml <<"EOF"
groups:
- name: PerconaMongodbExporter
  rules:
    - alert: MongodbDown
      expr: 'mongodb_up == 0'
      for: 0m
      labels:
        severity: critical
      annotations:
        summary: "MongoDB Down 容器: $labels.instance"
        description: "MongoDB 容器 is down, 当前值:{{ $value }}"

    - alert: MongodbNumberCursorsOpen
      expr: 'mongodb_ss_metrics_cursor_open{csr_type="total"} > 10 * 1000'
      for: 2m
      labels:
        severity: warning
      annotations:
        summary: "MongoDB 数字有标打开告警 容器: $labels.instance"
        description: "MongoDB 为客户端打开的游标过多 > 10k, 当前值:{{ $value }}"

    - alert: MongodbCursorsTimeouts
      expr: 'increase(mongodb_ss_metrics_cursor_timedOut[1m]) > 100'
      for: 2m
      labels:
        severity: warning
      annotations:
        summary: "MongoDB 游标超时 容器: $labels.instance"
        description: "太多游标超时, 当前值:{{ $value }}"

    - alert: MongodbTooManyConnections
      expr: 'avg by(instance) (rate(mongodb_ss_connections{conn_type="current"}[1m])) / avg by(instance) (sum (mongodb_ss_connections) by (instance)) * 100 > 80'
      for: 2m
      labels:
        severity: warning
      annotations:
        summary: "MongoDB 太多连接 容器: $labels.instance"
        description: "MongoDB 连接数 > 80%, 当前值:{{ $value }}"

    - alert: MongodbVirtualMemoryUsage
      expr: '(sum(mongodb_ss_mem_virtual) BY (instance) / sum(mongodb_ss_mem_resident) BY (instance)) > 3'
      for: 2m
      labels:
        severity: warning
      annotations:
        summary: "MongoDB虚拟内存使用告警 容器: $labels.instance"
        description: "虚拟内存使用过高, 当前值:{{ $value }}"
EOF

检查:

vim prometheus/alert.yml

检查配置

docker exec -it prometheus promtool check config /etc/prometheus/prometheus.yml

重新加载配置

curl -X POST http://localhost:9090/-/reload

检查

http://192.168.11.61:9090/alerts?search=

或:

http://192.168.11.61:9090/rules

8、dashboard

grafana展示prometheus从mongodb_exporter收集到的的数据

https://github.com/percona/grafana-dashboards/tree/main/dashboards/MongoDB

三、我的微信

如果安装碰到问题,可以随时加我微信,谢谢

0
广告 广告

评论区