python实现采集yarn队列资源使用百分比,暴露为prometheus的exporter格式,进行yarn队列资源监控

python脚本实现,访问官方提供的地址,获取队列资源使用指标,并将指标进行json解析,之后再转换为prometheus认识的数据格式,暴露于端口下
#coding=utf-8

'''
通过访问官方提供的yarn restful api界面,获取yarn资源指标
分析json取的所需指标
以pormetheus的数据格式将指标暴露在指定端口下

入参:yarn的ip:port export暴露的机器IP(建议为本机IP) export暴露的端口号
'''

import prometheus_client
from prometheus_client import Gauge
from prometheus_client.core import CollectorRegistry
from flask import Response, Flask

import json
import urllib.request
import sys


hjson = json.loads('{}')

app = Flask(__name__)

REGISTRY = CollectorRegistry(auto_describe=False)

usememory_percentage_temp = Gauge(
    name='vcores_percentage',
    documentation= 'vcores_percentage',
    labelnames=['queue_name'],
    registry=REGISTRY)
usevCores_percentage_temp = Gauge(
   'memory_percentage',
    'memory_percentage',
    labelnames=['queue_name'],
    registry=REGISTRY)

def getMetric(ipport):

    html = urllib.request.urlopen(r'http://'+ipport+'/ws/v1/cluster/scheduler')

    data = html.read().decode("utf-8")

    global hjson
    hjson = json.loads(data)
    queuelist = []
    coresList = []
    memList = []

  # 不同版本,json格式不一样,需要具体解析
    for i in range(0,len(hjson['scheduler']['schedulerInfo']['rootQueue']['childQueues']['queue'])):
        queuename = hjson['scheduler']['schedulerInfo']['rootQueue']['childQueues']['queue'][i]['queueName']
        usevCores = hjson['scheduler']['schedulerInfo']['rootQueue']['childQueues']['queue'][i]['usedResources']['vCores']
        usermemory = hjson['scheduler']['schedulerInfo']['rootQueue']['childQueues']['queue'][i]['usedResources']['memory']
        maxvCores = hjson['scheduler']['schedulerInfo']['rootQueue']['childQueues']['queue'][i]['maxResources']['vCores']
        maxmemory = hjson['scheduler']['schedulerInfo']['rootQueue']['childQueues']['queue'][i]['maxResources']['memory']
        usermemory_percentage = 0.0000
        usevCores_percentage = 0.0000
        if(maxvCores != 0):
            usevCores_percentage = round(usevCores/maxvCores,4)
        if(maxmemory != 0):
            usermemory_percentage = round(usermemory/maxmemory,4)
        queuelist.append(queuename.split(".")[1])
        coresList.append(float(usevCores_percentage))
        memList.append(float(usermemory_percentage))

    for i in range(0,len(hjson['scheduler']['schedulerInfo']['rootQueue']['childQueues']['queue'])):
        usememory_percentage_temp.labels(queue_name=str(queuelist[i])).set(float(memList[i]))
        usevCores_percentage_temp.labels(queue_name=str(queuelist[i])).set(float(coresList[i]))





@app.route('/metrics')
def r_value():
    return Response(prometheus_client.generate_latest(REGISTRY),
                    mimetype="text/plain")


@app.route('/')
def index():
    return "yarn metric address: ip:port/metrics"



if __name__ == "__main__":
	#yarn的ip和端口
    # yarn_ipport = str(sys.argv[1])
    #展示的ip,建议本机ip
    # showIp = str(sys.argv[2])
    #展示的端口
    # showPort = int(sys.argv[3])

	#yarn的ip和端口
    yarn_ipport = "127.0.0.1:8001"
    #展示的ip,建议本机ipx
    showIp = "localhost"
    #展示的端口
    showPort = 8000
    getMetric(yarn_ipport)

    app.run(host=showIp,port=showPort,debug=True)

效果图如下

在这里插入图片描述

<think>我们正在讨论如何监控Apache YARN资源使用情况,特别是收集运行中应用程序的资源使用信息。 根据引用[1]和[2],YARN是一个资源管理系统,负责为应用程序分配资源。因此,监控资源使用情况对于集群管理至关重要。 监控YARN资源使用情况的方法: 1. 使用YARN自带的Web UI:ResourceManager提供了一个Web界面,可以查看集群的整体资源使用情况,以及各个应用程序的资源使用情况。 2. 使用命令行工具:YARN提供了命令行工具(如`yarn application`和`yarn node`)来获取应用程序和节点的资源使用信息。 3. 通过REST API:ResourceManager提供了REST API,可以编程方式获取资源使用信息。 4. 使用监控工具:如Apache Ambari、Cloudera Manager等,它们提供了图形化界面和告警功能。 5. 收集日志和指标:YARN监控系统(如Prometheus、Grafana)集成,通过暴露的指标(例如通过JMX)进行监控。 具体到收集运行中应用程序的资源使用情况: - 对于单个应用程序,可以通过ResourceManager的Web UI查看,或者使用命令行工具`yarn application -status <ApplicationId>`。 - 对于节点级别的资源使用,可以使用`yarn node -list`查看所有节点,然后使用`yarn node -status <NodeId>`查看具体节点的资源使用情况。 - 通过REST API,可以获取JSON格式的数据,便于进一步处理。例如,获取所有运行中应用程序的资源使用:`http://<rm-http-address>:<port>/ws/v1/cluster/apps?state=RUNNING` 此外,引用[3]提到YARN的调度器会根据策略分配资源,因此监控调度队列资源使用情况也很重要。 下面是一个使用REST API获取运行中应用程序资源使用情况的示例(使用curl): ```bash curl -X GET "http://<ResourceManager_Address>:8088/ws/v1/cluster/apps?state=RUNNING" ``` 返回的JSON中会包含每个应用程序的资源使用信息,如分配的内存、CPU等。 为了持续监控,可以将这些API集成到监控系统中,定期收集数据并展示。 注意:在实际操作中,需要替换<ResourceManager_Address>为实际的ResourceManager主机地址。 相关问题: 1. 如何通过YARN REST API获取特定应用程序的详细资源使用情况? 2. YARN资源监控中常用的指标有哪些? 3. 如何配置YARN以将监控数据导出到外部监控系统(如Prometheus)?</think>### Apache YARN 资源监控方法详解 要监控 Apache YARN资源使用情况并收集运行中应用的资源信息,可通过以下方法实现: #### 1. **YARN Web UI 监控** - 访问 ResourceManager Web UI(默认端口 8088): - 查看集群总资源:`/cluster`页面显示总内存/CPU及使用率 - 实时应用监控:`/cluster/apps`页面展示所有应用资源使用明细 - 节点级监控:`/cluster/nodes`显示各节点资源分配情况 - 特点:提供可视化界面,适合快速查看[^2] #### 2. **命令行工具** ```bash # 查看所有运行中应用资源使用 yarn application -list -appStates RUNNING # 获取具体应用资源详情 yarn application -status <ApplicationID> # 监控节点资源 yarn node -list ``` 输出包含关键指标: - `Memory Used`:已用内存 - `VCores Used`:已用虚拟核数 - `Containers Running`:运行容器数 #### 3. **REST API 数据采集** ResourceManager 提供 REST API 获取结构化数据: ```bash # 获取所有运行中应用JSON数据 curl http://<RM-Address>:8088/ws/v1/cluster/apps?states=RUNNING # 获取节点资源详情 curl http://<RM-Address>:8088/ws/v1/cluster/nodes ``` 关键响应字段: ```json { "apps": { "app": [ { "allocatedMB": 2048, // 分配内存(MB) "allocatedVCores": 2, // 分配vCores "runningContainers": 3, // 运行容器数 "elapsedTime": 120450 // 运行时长(ms) } ] } } ``` #### 4. **监控系统集成** - **Prometheus + Grafana**: - 通过[YARN JMX Exporter](https://github.com/prometheus/jmx_exporter)收集指标 - 关键指标示例: - `yarn_cluster_memory_used`:集群已用内存 - `yarn_app_vcores_used`:应用CPU核使用 - **Ambari/Cloudera Manager**: - 提供预置YARN监控仪表盘 - 支持历史数据回溯和阈值告警 #### 5. **日志分析** - ResourceManager 日志(`yarn-yarn-resourcemanager-*.log`): - 记录资源分配决策事件 - 包含应用资源申请/释放时间戳 - 使用ELK或Splunk进行日志聚合分析 #### 6. **高级监控技巧** - **资源预留监控**:通过`yarn.scheduler.capacity.<queue>.reservations`参数跟踪资源预留状态 - **队列监控**:使用`yarn queue -status <queue-name>`查看队列资源分配 - **容器生命周期追踪**:监控`ContainerLaunchContext`事件获取容器资源使用峰值 > **关键监控指标**: > - **集群级**:总内存/CPU使用率、待处理容器数 > - **应用级**:AM资源消耗、容器分配成功率 > - **节点级**:物理内存 vs 虚拟内存使用比 通过组合这些方法,可实现从实时监控到历史分析的完整资源监控体系,满足调度优化[^3]和容量规划需求。 --- ### 相关问题 1. **如何设置 YARN 资源使用的告警阈值?** 2. **YARN 容器资源超用(OOM)的监控和诊断方法有哪些?** 3. **如何比较不同调度器(FIFO/Capacity/Fair)的资源监控差异?** 4. **YARN 资源监控数据如何用于集群容量规划?** 5. **在 Kubernetes 上部署 YARN 时,资源监控有哪些特殊注意事项?**
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值