kill-on-idle.js 1.14 KB
const MODULE_NAME = 'KILL-ON-IDLE';

const moment = require('moment');
const config = require('komodo-sdk/config');
const logger = require('tektrans-logger');

const maxIdleMs = (config.kill_on_idle && config.kill_on_idle.max_idle_ms) || 60 * 1000;

let lastIncomingTs = new Date();

const touch = () => {
    lastIncomingTs = new Date();
};
exports.touch = touch;

const getDisabled = () => !config.kill_on_idle || config.kill_on_idle.disable;
exports.getDisabled = getDisabled;

const killOnIdle = () => {
    if (getDisabled()) {
        return;
    }

    const ageMs = new Date() - lastIncomingTs;

    if (ageMs > maxIdleMs) {
        logger.warn(`${MODULE_NAME} 74A43DF4: Idle deadline exceeded. Terminating`, {
            lastIncomingTs: moment(lastIncomingTs).format('YYYY-MM-DD HH:mm:ss'),
            ageMs,
            maxIdleMs,
        });

        process.exit(1);
    }
};

const init = () => {
    if (getDisabled()) {
        return;
    }

    touch();

    logger.verbose(`${MODULE_NAME} CF75F9CE: Registering kill on idle checker`, {
        maxIdleMs,
    });

    setInterval(() => {
        killOnIdle();
    }, 2 * 1000);
};
exports.init = init;