All checks were successful
CI Monitor MIflow / build-image (push) Successful in 44s
85 lines
2.5 KiB
TypeScript
85 lines
2.5 KiB
TypeScript
import pLimit from "p-limit"
|
||
|
||
import managePipelineEvent from "../controllers/managePipelineEvent"
|
||
import db from "../db"
|
||
import service from "../service"
|
||
import { DB } from "../types/db"
|
||
import { sec2minStr } from "../utils/timeTools"
|
||
|
||
/**
|
||
* 执行监控任务
|
||
* @param {DB.Monitor} monitor - 监控项
|
||
* @returns {Promise<void>}
|
||
*/
|
||
const doMonitor = async (monitor: DB.Monitor): Promise<void> => {
|
||
const { project_id, pipeline_id, api_key, stage, receiver, variable } =
|
||
monitor
|
||
// 获取Job列表
|
||
const jobList = await service.gitlab.pipeline.getJobs(
|
||
Number(project_id),
|
||
Number(pipeline_id)
|
||
)
|
||
// 是否所有Stage关联的Job都成功了
|
||
const isAllSuccess = jobList
|
||
.filter((job) => job.stage === stage)
|
||
.every((job) => job.status === "success")
|
||
// 没全部成功跳过
|
||
if (!isAllSuccess) return
|
||
// 先删除监控
|
||
await db.monitor.del(monitor.id)
|
||
// 获取最新的执行时长
|
||
const pipelineDetail = await service.gitlab.pipeline.getDetail(
|
||
Number(project_id),
|
||
Number(pipeline_id)
|
||
)
|
||
if (pipelineDetail) {
|
||
variable["duration"] = sec2minStr(pipelineDetail.duration)
|
||
}
|
||
// 获取机器人消息
|
||
const robotMsg = managePipelineEvent.genLarkRobotMsgContent(variable)
|
||
// 发送消息
|
||
await service.message.byUserIdList(receiver, robotMsg, api_key)
|
||
// 记录日志
|
||
await db.notify.create({ ...variable })
|
||
}
|
||
|
||
/**
|
||
* 移除超过24小时的监控项
|
||
* @async
|
||
* @function removeOverTimeMonitor
|
||
* @returns {Promise<void>} 无返回值
|
||
* @description 该函数从数据库中获取所有监控项,并移除创建时间超过24小时的监控项。
|
||
*/
|
||
const removeOverTimeMonitor = async (): Promise<void> => {
|
||
const fullMonitorList = await db.monitor.getFullList()
|
||
const now = Date.now()
|
||
await Promise.all(
|
||
fullMonitorList.map(async (monitor) => {
|
||
const createdAtTimestamp = new Date(monitor.created_at).getTime()
|
||
if (now - createdAtTimestamp > 24 * 60 * 60 * 1000) {
|
||
await db.monitor.del(monitor.id)
|
||
}
|
||
})
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 监控任务的主函数
|
||
* @returns {Promise<void>}
|
||
*/
|
||
const monitorJob = async (): Promise<void> => {
|
||
// 获取全部监控项
|
||
const fullMonitorList = await db.monitor.getFullList()
|
||
if (fullMonitorList.length === 0) return
|
||
// 并发限制
|
||
const limit = pLimit(3)
|
||
// 并发处理
|
||
await Promise.all(
|
||
fullMonitorList.map((monitor) => limit(() => doMonitor(monitor)))
|
||
)
|
||
// 移除超过24小时的监控项
|
||
await removeOverTimeMonitor()
|
||
}
|
||
|
||
export default monitorJob
|