Repository: louislam/uptime-kuma
File: server/monitor-types/snmp.js (JavaScript)

Code before:

class SNMPMonitorType extends MonitorType {
    name = "snmp";

    /**
     * Checks the SNMP value against the condition and control value.
     * @param {object} monitor The monitor object associated with the check.
     * @param {object} heartbeat The heartbeat object to update.
     * @param {object} _server Unused server object.
     */
    async check(monitor, heartbeat, _server) {

        log.debug("monitor", `SNMP: Community String: ${monitor.snmpCommunityString}`);
        log.debug("monitor", `SNMP: OID: ${monitor.snmpOid}`);
        log.debug("monitor", `SNMP: Version: ${monitor.snmpVersion}`);
        log.debug("monitor", `SNMP: Condition: ${monitor.snmpCondition}`);
        log.debug("monitor", `SNMP: Control Value: ${monitor.snmpControlValue}`);

        const options = {
            port: monitor.port || '161',
            retries: monitor.maxretries,
            timeout: 1000,
            version: getKey(snmp.Version, monitor.snmpVersion) || snmp.Version2c,
        };

        function getKey(obj, value) {
            return Object.keys(obj).find(key => obj[key] === value) || null;
        }

        try {
            const session = snmp.createSession(monitor.hostname, monitor.snmpCommunityString, options);

            // Handle errors during session creation
            session.on('error', (error) => {
                heartbeat.status = DOWN;
                heartbeat.msg = `SNMP: Error creating SNMP session: ${error.message}`;
                log.debug("monitor", `SNMP: ${heartbeat.msg}`);
            });

            const varbinds = await new Promise((resolve, reject) => {
                session.get([monitor.snmpOid], (error, varbinds) => {
                    if (error) {
                        reject(error);
                    } else {
                        log.debug("monitor", `SNMP: Received varbinds: Type: ${getKey(snmp.ObjectType, varbinds[0].type)}, Value: ${varbinds[0].value}`); // Log the received varbinds for debugging
                        resolve(varbinds);
                    }
                });
            });

            if (varbinds.length === 0 || getKey(snmp.ObjectType, varbinds[0].type) === 'NoSuchInstance') {

Review comment (suggestion):
please don't declare functions in functions ^^
Also:
why is this needed? (I don't quite understand the `smnp.ObjectType` part)
=> please explain why you are doing as a comment

Code after:

class SNMPMonitorType extends MonitorType {
    name = "snmp";

    /**
     * @inheritdoc
     */
    async check(monitor, heartbeat, _server) {
        let session;
        try {
            const sessionOptions = {
                port: monitor.port || "161",
                retries: monitor.maxretries,
                timeout: monitor.timeout * 1000,
                version: snmp.Version[monitor.snmpVersion],
            };
            session = snmp.createSession(monitor.hostname, monitor.radiusPassword, sessionOptions);

            // Handle errors during session creation
            session.on("error", (error) => {
                throw new Error(`Error creating SNMP session: ${error.message}`);
            });

            const varbinds = await new Promise((resolve, reject) => {
                session.get([ monitor.snmpOid ], (error, varbinds) => {
                    error ? reject(error) : resolve(varbinds);
                });
            });
            log.debug("monitor", `SNMP: Received varbinds (Type: ${snmp.ObjectType[varbinds[0].type]} Value: ${varbinds[0].value})`);

            if (varbinds.length === 0) {
                throw new Error(`No varbinds returned from SNMP session (OID: ${monitor.snmpOid})`);
            }

            if (varbinds[0].type === snmp.ObjectType.NoSuchInstance) {
                throw new Error(`The SNMP query returned that no instance exists for OID ${monitor.snmpOid}`);
            }

            // We restrict querying to one OID per monitor, therefore `varbinds[0]` will always contain the value we're interested in.
            const value = varbinds[0].value;

            const { status, response } = await evaluateJsonQuery(value, monitor.jsonPath, monitor.jsonPathOperator, monitor.expectedValue);

            if (status) {
                heartbeat.status = UP;
                heartbeat.msg = `JSON query passes (comparing ${response} ${monitor.jsonPathOperator} ${monitor.expectedValue})`;
            } else {
                throw new Error(`JSON query does not pass (comparing ${response} ${monitor.jsonPathOperator} ${monitor.expectedValue})`);
            }
        } finally {
            if (session) {