|
|
@@ -40,6 +40,39 @@ export async function checkExpiredInstances(
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+/**
|
|
|
+ * Delete instance records that have been in 'terminated' status for over 24 hours.
|
|
|
+ * Also cleans up associated rdp_sessions to avoid FK constraint issues.
|
|
|
+ */
|
|
|
+export async function cleanupTerminatedInstances(): Promise<void> {
|
|
|
+ const db = getDb();
|
|
|
+ const cutoff = Math.floor(Date.now() / 1000) - 24 * 3600;
|
|
|
+
|
|
|
+ const rows = db
|
|
|
+ .prepare(
|
|
|
+ `SELECT id, ec2_instance_id FROM instances
|
|
|
+ WHERE status = 'terminated' AND created_at < ?`,
|
|
|
+ )
|
|
|
+ .all(cutoff) as { id: number; ec2_instance_id: string }[];
|
|
|
+
|
|
|
+ if (rows.length === 0) return;
|
|
|
+
|
|
|
+ const deleteRdp = db.prepare('DELETE FROM rdp_sessions WHERE instance_id = ?');
|
|
|
+ const deleteInstance = db.prepare('DELETE FROM instances WHERE id = ?');
|
|
|
+
|
|
|
+ const tx = db.transaction(() => {
|
|
|
+ for (const row of rows) {
|
|
|
+ deleteRdp.run(row.id);
|
|
|
+ deleteInstance.run(row.id);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ tx();
|
|
|
+
|
|
|
+ console.log(
|
|
|
+ `[Lifetime_Timer] 已清理 ${rows.length} 条已销毁实例记录`,
|
|
|
+ );
|
|
|
+}
|
|
|
+
|
|
|
/**
|
|
|
* Start the cron job that checks for expired instances every minute.
|
|
|
*/
|
|
|
@@ -49,6 +82,10 @@ export function startLifetimeTimer(): void {
|
|
|
checkExpiredInstances().catch((err) => {
|
|
|
console.error('[Lifetime_Timer] 检查过期实例时出错:', err.message);
|
|
|
});
|
|
|
+ // Clean up terminated instance records older than 24 hours
|
|
|
+ cleanupTerminatedInstances().catch((err) => {
|
|
|
+ console.error('[Lifetime_Timer] 清理已销毁实例记录时出错:', err.message);
|
|
|
+ });
|
|
|
// Clean up logs older than 30 days
|
|
|
try {
|
|
|
const db = getDb();
|