Feat: Auto cleanup old devices/flows when Subnet Config is updated

This commit is contained in:
ypratama committed 2026-09-04 11:01:40 +07:00
1 parent 8a73d266d8
commit 64f77187d8
2 files changed
+37 -1

No files matched your search

+36
View File
@@ -239,6 +239,27 @@ router.get('/agents/:uuid/subnets', async (req, res) => {
// ─── PUT /api/dashboard/agents/:uuid/subnets ─────────────────────────────────
// Simpan konfigurasi subnet yang diizinkan untuk agent tertentu
// Body: { allowed_subnets: ["192.168.1", "10.21"] }
function ipToLong(ip) {
return ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
}
function ipMatchesSubnets(ip, subnets) {
if (!subnets || subnets.length === 0) return true;
if (!ip) return false;
return subnets.some(subnet => {
if (subnet.includes('/')) {
try {
const [range, bitsStr] = subnet.split('/');
const bits = parseInt(bitsStr, 10);
if (isNaN(bits) || bits < 0 || bits > 32) return false;
const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
return (ipToLong(ip) & mask) === (ipToLong(range) & mask);
} catch (e) { return false; }
} else { return ip === subnet; }
});
}
// PUT /api/dashboard/agents/:uuid/subnets
router.put('/agents/:uuid/subnets', async (req, res) => {
try {
const allowedRoles = ['SUPER_ADMIN', 'TENANT_ADMIN', 'COMPANY_ADMIN'];
@@ -251,6 +272,21 @@ router.put('/agents/:uuid/subnets', async (req, res) => {
{ uuid: req.params.uuid },
{ $set: { allowed_subnets: subnets, subnets_updated_at: new Date() } }
);
// Auto-cleanup background task
if (subnets.length > 0) {
setTimeout(async () => {
try {
const ips = await db.collection('devicestats').distinct('ip_address', { agent_uuid: req.params.uuid });
const invalidIps = ips.filter(ip => !ipMatchesSubnets(ip, subnets));
if (invalidIps.length > 0) {
await db.collection('devicestats').deleteMany({ agent_uuid: req.params.uuid, ip_address: { $in: invalidIps } });
await db.collection('flows').deleteMany({ agent_uuid: req.params.uuid, src_ip: { $in: invalidIps } });
}
} catch (e) { console.error('Auto-cleanup error:', e); }
}, 100);
}
res.json({ ok: true, data: { allowed_subnets: subnets } });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });