Source: modules/services/outbound/externalip/service.js

/**
 * Service External IP.
 *
 * Service checks for external IP (WAN) address to provide a
 * more or less stable URL for mobile clients to access data
 * at the ALARMiator Server
 *
 * @link   URL
 * @file   This files defines Service Externalip.
 * @author Jens Dinstühler.
 * @since  1.0.0
 */
 
// Logging
var log4js = require('log4js');
log4js.configure({
    appenders: { mylogger: { type:"dateFile", filename: "logs/modules/outbound/externalip/externalip.log" }, console: { type:"console" } },
    categories: { default: { appenders:["mylogger", "console"], level:"ALL" } }
});
const logger = log4js.getLogger("default");

// required for external IP check
const publicIp = require('public-ip');

// required for database access
const mysql = require('mysql');


// Read global config
// Create connection to database
var config = require('../../../../config/config.js');

// Create db connection
const db = mysql.createConnection (config.databaseOptions);
// Connect to database
db.connect((err) => {
    if (err) {
        throw err;
    } else {
        logger.info(`${svcName} | Connected to database `, config.databaseOptions.database);
        updateExternalP();
    }
});
global.db = db;

// Get arguments main application sent during startup
var args = process.argv.slice(2); // Get arguments main application sent during startup
const orgId = args[1]; // Set organizationID this service instance is active for
const ibSvcId = args[2]; // Set ibSvcId this service instance has in database (needed for reading the instance configuration from database)
const svcName = 'EXTERNALIP-' + args[0];

// Send startup-message to console
logger.info(`${svcName} | organization ${orgId} | service instance id ${ibSvcId} | starting up .. `); // Send startup-message to console/log




//
//
//  Service specific implementation
//
//
/**
 * Function reads the configuration key/value pairs from database
 * 
 * @param ibSvcId - id of the service in db table services_inbound_store
 */
function readModuleConfiguration(ibSvcId, callback) {
    var funcResult = true;
    let query = "SELECT keyword, value FROM services_inbound_config WHERE keyword LIKE 'outbound.externalip%' AND svcInstanceId = " + ibSvcId;
    db.query(query, (err, result) => {
      if (err) {
        logger.error(`${svcName} | cannot read module configuration from database`);
        funcResult = false;
      } else {
        if (result.length > 0) {
          result.forEach(element => {
            if (element.keyword === 'outbound.externalip.port') port = element.value;
          });
        } else {
          funcResult = false;
        }
      }
      callback(funcResult);
    });
}


function updateExternalP() {
    (async () => {
            var ipv4 = await publicIp.v4()
            logger.info(`${svcName} | external IP v4 (WAN): ` + ipv4);
            setExternalIPInDatabase(ipv4);
        })();
}

function setExternalIPInDatabase(ipaddress) {

    // Check if external IP Address is available at database configuration table
    let query = "SELECT * FROM `configuration` WHERE keyword = 'outbound.externalip'";
    db.query(query, (err, result) => {
        if (err) {
            // error reading external ip from database
            logger.error(`${svcName} | Error updating external ip address in database`);
            return null;
        } else {
            if (result.length > 0) {
                // entry existing, update this entry
                let query = "UPDATE `configuration` SET value = '" + ipaddress + "', lastupdate = NOW() WHERE id = " + result[0].id;
                db.query(query, (errQuery2, result2) => {
                    if (errQuery2) {
                        // Errror loading organizations
                        logger.error(`${svcName} | Error updating external ip address in database`);
                        return null;
                    } else {
                        logger.info(`${svcName} | updated external ip address in database successfully`);
                    }
                })
            } else {
                // no entry existing, create new entry
                let query = "INSERT INTO `configuration` (keyword, value) VALUES ('outbound.externalip', '" + ipaddress + "');";
                db.query(query, (errQuery2, result2) => {
                    if (errQuery2) {
                        // Errror loading organizations
                        logger.error(`${svcName} | Error updating external ip address in database`);
                        return null;
                    } else {
                        logger.info(`${svcName} | set external ip address in database successfully`);
                    }
                })
            }
        }
    });
}

// Start check every 2 Minutes
var minutes = 2, the_interval = minutes * 60 * 1000;
setInterval(function() {
  logger.info(`${svcName} | Starting External IP (WAN) Check`);
  updateExternalP();
}, the_interval);

//
//
// GENERIC Keep-alive Service Functionality (--don't change--)
//
//
process.on('message', (m) => {
  if (m == 'stop') {
      logger.info(`${svcName} | ${args} | ${m} | Service termination command recieved from host`);
      stalker.close();
      process.exit();
  } else if(m == 'healthcheck') {
      process.send('{"state":"1", "pid":"' + process.pid + '"}');
  }
});