获取Harbor镜像仓库指定Project的容量使用并进行企业微信告警
简单说明
在镜像仓库的维护中,有时我们需要根据镜像仓库的使用情况进行及时的告警和扩容,避免镜像仓库容量满载时再进行扩容,这样会造成业务的阻塞。
这里我们使用Python简单写一个实现获取镜像仓库指定项目(也可以配置多个project)的容量使用情况,并且当容量达到设置的阈值,进行企业微信告警。
代码
$ cat alert_harbor_project.py
# -*- coding: utf-8 -*-
# author: yuhaohao
# describe:
# 获取指定镜像仓库的容量配额以及已使用容量
# 当容量利用率或者使用空间达到预定的阈值时, 进行企业微信的告警
import requests
from requests.auth import HTTPBasicAuth
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def send_wechat_alert(webhook_url, message):
headers = {"Content-Type": "application/json"}
payload = {
"msgtype": "markdown",
"markdown": {
"content": message
}
}
try:
response = requests.post(webhook_url, json=payload, headers=headers)
if response.status_code == 200:
print("告警发送成功")
else:
print(f"告警发送失败: {response.text}")
except Exception as e:
print(f"发送告警异常: {e}")
if __name__ == '__main__':
# 配置项
HARBOR_URL = "https://registry.test.com" # 替换成你实际的地址
PROJECT_NAME = "test"
USERNAME = "test" # 替换成实际用户名
PASSWORD = "test" # 替换成实际密码
WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=a18hjhhbjhjhjyuyuhu-a452-8b11b7e677b4" # 替换为企业微信的key
# 请求 headers
headers = {
"Accept": "application/json"
}
# API: 获取项目信息(包括 quota 使用情况)
url = f"{HARBOR_URL}/api/v2.0/projects/{PROJECT_NAME}/summary"
response = requests.get(url, headers=headers, auth=HTTPBasicAuth(USERNAME, PASSWORD), verify=False)
if response.status_code == 200:
data = response.json()
quota = data.get("quota", {}).get("hard", {}).get("storage")
used = data.get("quota", {}).get("used", {}).get("storage")
if quota and used:
used_gb = round(used / (1024 ** 3), 2)
quota_gb = round(quota / (1024 ** 3), 2)
availd_gb = round((quota_gb - used_gb), 2)
used_rate = used_gb / quota_gb
print(f"项目 {PROJECT_NAME} 已使用存储: {used_gb} GiB / {quota_gb} GiB")
if used_gb / quota_gb > 0.95 or availd_gb < 400:
message = (
f"### <font color=\"red\">**⚠️ 镜像仓库容量告警**</font>\n"
f"> **Project名称:** {PROJECT_NAME}\n"
f"> **总容量:** {quota_gb}GB\n"
f"> **已用容量:** {used_gb}GB\n"
f"> **剩余容量:** {availd_gb}GB\n"
f"> **容量使用率:** {used_rate:.2%}\n"
f"> **请及时清理镜像或进行扩容!!!**"
)
send_wechat_alert(WEBHOOK_URL, message)
else:
print("未获取到有效的存储配额信息")
else:
print(f"获取失败,状态码: {response.status_code}, 响应: {response.text}")

浙公网安备 33010602011771号