腾讯云 - 异常费用监测
2024-09-07
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.billing.v20180709 import billing_client, models
import json
from datetime import datetime, timedelta
# 读取配置文件
config_path = "/root/.tccli/default.credential"
try:
with open(config_path, 'r') as file:
data = file.read()
except FileNotFoundError as e:
print("Error opening config file:", e)
exit(1)
# 解析配置文件内容
try:
conf = json.loads(data)
except json.JSONDecodeError as e:
print("Error parsing config file:", e)
exit(1)
cred = credential.Credential(conf['secretId'], conf['secretKey'])
http_profile = HttpProfile()
http_profile.endpoint = "billing.tencentcloudapi.com"
client_profile = ClientProfile()
client_profile.httpProfile = http_profile
client = billing_client.BillingClient(cred, "", client_profile)
offset = 0 # 初始偏移量
limit = 100 # 每页数量
page_num = 1
aggregate_data = {} # 用于存储聚合结果 tencent_bill_info{ResourceId="faas-training-datase-1312767721",ResourceName="faas-training-datase",PayModeName="按量计费",BusinessCodeName="COS 对象存储"} 0.00003171
aggregate_data_item = {} # 用于存储聚合结果 tencent_bill_info{ResourceId="faas-training-datase-1312767721",ResourceName="faas-training-datase",PayModeName="按量计费",BusinessCodeName="COS 对象存储"} 0.00003171
# 获取昨天的日期
yesterday = datetime.now() - timedelta(days=1)
while True:
req = models.DescribeBillDetailRequest()
req.Offset = offset
req.Limit = limit
# 设置开始时间为昨天的 00:00:00
req.BeginTime = yesterday.strftime("%Y-%m-%d 00:00:00")
# 设置结束时间为昨天的 23:59:59
req.EndTime = yesterday.strftime("%Y-%m-%d 23:59:59")
# req.BeginTime = "2024-06-03 00:00:00" # 设置开始时间
# req.EndTime = "2024-06-03 23:59:59" # 设置结束时间
req.NeedRecordNum = 1
response = client.DescribeBillDetail(req)
# 处理当前页的数据
for item in response.DetailSet:
pay_mode_name = item.PayModeName
resource_id = item.ResourceId
resource_name = item.ResourceName
business_code_name = item.BusinessCodeName # 获取 BusinessCodeName
item_code_name = item.ComponentSet[0].ItemCodeName
key = (resource_id, resource_name, business_code_name, pay_mode_name) # 创建包含 resource_id 和 business_code_name 的元组
key_item = (business_code_name, pay_mode_name, item_code_name) # 创建包含 resource_id 和 business_code_name 的元组
real_cost = float(item.ComponentSet[0].RealCost)
if key in aggregate_data:
aggregate_data[key] += real_cost
else:
aggregate_data[key] = real_cost
if key_item in aggregate_data_item:
aggregate_data_item[key_item] += real_cost
else:
aggregate_data_item[key_item] = real_cost
# 判断是否还有下一页数据
if offset >= response.Total:
break
offset += limit # 更新偏移量
# 打开文件或创建新文件
with open('/opt/node_exporter/metadata-prod/tencent-bill.prom', 'w') as file:
# 打印聚合结果并写入文件
for key, total_cost in aggregate_data.items():
resource_id, resource_name, business_code_name, pay_mode_name = key # 解包元组获取 resource_id 和 business_code_name
total_cost = format(total_cost, '.8f')
output = f'tencent_bill_info{{ResourceId="{resource_id}",ResourceName="{resource_name}",PayModeName="{pay_mode_name}",BusinessCodeName="{business_code_name}"}} {total_cost}'
print(output) # 打印到控制台
file.write(output + '\n') # 写入文件
with open('/opt/node_exporter/metadata-prod/tencent-bill-item.prom', 'w') as file:
# 打印聚合结果并写入文件
for key_item, total_cost in aggregate_data_item.items():
business_code_name, pay_mode_name, item_code_name = key_item # 解包元组获取 resource_id 和 business_code_name
total_cost = format(total_cost, '.8f')
output = f'tencent_bill_item_info{{ItemCodeName="{item_code_name}",PayModeName="{pay_mode_name}",BusinessCodeName="{business_code_name}"}} {total_cost}'
print(output) # 打印到控制台
file.write(output + '\n') # 写入文件