feat: add session expiry deletion script and scheduler

This commit is contained in:
wancat committed 2023-08-23 12:22:15 +08:00
1 parent 8e63284211
commit 22060070b9
8 files changed
+94 -3

No files matched your search

+15
View File
@@ -65,3 +65,18 @@ export async function attachContainer(container, { token }) {
return execOutput.socket
}
export async function deleteContainer(id) {
const container = engine.getContainer(id)
if (!container) {
return
}
try {
await container.stop()
await container.remove({
force: true,
})
} catch (error) {
console.log(error)
}
}
+28
View File
@@ -0,0 +1,28 @@
import schedule from 'node-schedule'
import config from '../config.js'
import Session from '../models/session.js'
import { deleteContainer } from './docker.js'
export async function removeExpired() {
// Find all sessions that are containerId is not null and lastActivityAt is
// less than the current time minus the expiry time
console.log('Checking for expired sessions')
const sessions = await Session.find({
containerId: { $ne: null },
lastActivityAt: { $lt: new Date(Date.now() - config.expiry) },
})
await Promise.all(
sessions.map(async (session) => {
console.log('Expiring session: ', session._id, session.containerId)
await deleteContainer(session.containerId)
session.status = 'deactive'
session.containerId = null
await session.save()
})
)
console.log('Done checking for expired sessions')
}
export default function expiryRemovalScheduler() {
schedule.scheduleJob('*/5 * * * *', removeExpired)
}