使用Grafana监控K8S中的异常Pod

工作中要维护多个K8S集群,发现运行异常的Pod要及时介入处理。

想到一个思路:使用Grafana将异常的Pod通过图表的方式显示出来。

这里用到了一个Grafana插件,Grafana-Infinity,关于这个插件的使用可以参考玩转Grafana-Infinity插件使用

思路

通过Python脚本采集K8S集群中运行异常的Pod信息,包括命名空间、状态、重启次数、运行时长等。然后将这些数据通过http接口,以JSON格式的方式暴露出来,数据供Infinity来消费。

完整脚本

脚本很简单,读者可以根据实际情况修改,

python 复制代码
import re
import json

import ansible_runner

from flask import Flask, request


def get_abnormal_pod(ip):
    response = {}
    data = []
    modules_args = "kubectl get pod --no-headers -A | grep -E -v -i 'running|completed'"
    ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
    pattern = re.compile(r"\s{2,}")

    try:
        runner_obj = ansible_runner.run(private_data_dir="/opt/jsonsource/abnormal_pod",
                                        inventory='/opt/jsonsource/abnormal_pod/inventory',
                                        host_pattern=ip,
                                        quiet=True,
                                        module='shell',
                                        module_args=modules_args)
        for line in runner_obj.stdout.readlines():
            # remove the ANSI escape sequences
            new_line = ansi_escape.sub('', line)
            resource_list = pattern.split(new_line)
            
            # 加保护,防止Grafana的Table panel显示异常
            if 'FAILED' in resource_list[0]:
                return {'data': [{'namespace': '正常', 'name': '正常', 'status': '正常',
                      'restarts': '正常', 'age': '正常'}]}

            ns_resource_detail = {}
            if len(resource_list) == 6:
                ns_resource_detail["namespace"] = resource_list[0]
                ns_resource_detail["name"] = resource_list[1]
                ns_resource_detail["status"] = resource_list[3]
                ns_resource_detail["restarts"] = resource_list[4]
                ns_resource_detail["age"] = resource_list[5].strip('\n')
                data.append(ns_resource_detail)
        response['data'] = data
    except:
        print("There is a exception")

    return response


app = Flask(__name__)

@app.route('/items')
def items():
    k8s_name_ip = {}
    k8s_name_ip['prod'] = '10.10.0.2'
    k8s_name_ip['demo'] = '10.11.0.2'
    k8s_name_ip['test'] = '10.12.0.2'

    cluster_name = request.args.get("tag")

    if cluster_name in k8s_name_ip:
        ip = k8s_name_ip[cluster_name]
        return get_abnormal_pod(ip)

    # 保护,防止返回错误数据
    return {'data': [{'namespace': '仅支持指定平台', 'name': '仅支持指定平台', 'status': '仅支持指定平台',
                      'restarts': '仅支持指定平台', 'age': '仅支持指定平台'}]}


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=3111)

因为脚本运行的服务器不能直接访问K8S,这里使用了Ansible来远程执行。Inventory文件内容如下,

bash 复制代码
10.10.0.2
10.11.0.2
10.12.0.2

配置Grafana

新开一个Panel,类型选择"Table",数据源选择"Infinity"。

这里有个技巧,参照上面的Python脚本,

python 复制代码
cluster_name = request.args.get("tag")

集群的控制服务器IP通过查询参数"tag"传递,在配置"Infinity"插件时,要给"URL"配置一个查询参数,

这样我们就可以在Grafana上自由切换来显示不同环境的Pod运行状态。

显示效果

这样便可以通过Grafana上的一个单一Panel监控多个K8S集群的运行异常Pod。

相关推荐
星辰徐哥4 小时前
本地视频预览别只自己看:把Remotion动效项目发给客户远程验收
docker·ai·node.js·html·音视频·react·remotion
正仪5 小时前
kubernetes中list-watch机制
云原生·容器·kubernetes
cui_hao_nan7 小时前
从零搭建 Kubernetes 集群:Ubuntu + kubeadm 完整实战
ubuntu·容器·kubernetes
fb_123457 小时前
Docker入门-第3章-容器镜像深度解析
运维·docker·容器
IT摆渡者9 小时前
基于 Docker 部署 Nextcloud 私有云盘(外挂 Windows 共享)项目实践
运维·docker·容器
Jeromefromhk9 小时前
我把所有服务搬上 Kubernetes,又全部搬了回来
kubernetes·devops
墨香幽梦客11 小时前
Kubernetes+Istio实现CRM系统弹性伸缩:服务网格下的流量治理与熔断策略
容器·kubernetes·istio
新时代牛马11 小时前
单机 docker run 管不住了?从编排需求、期望状态到调度/自愈闭环讲透
运维·docker·容器
binqian11 小时前
Docker Desktop(WSL2 后端)三层网络互通技术文档
网络·docker·容器
LuiChun12 小时前
与精神病患者的日常探讨20260913
docker