UNPKG

@itentialopensource/adapter-sevone

Version:
1,357 lines (1,223 loc) 1.1 MB
/* @copyright Itential, LLC 2019 (pre-modifications) */ // Set globals /* global log */ /* eslint no-loop-func:warn */ /* eslint consistent-return:warn */ /* eslint import/no-dynamic-require:warn */ /* eslint object-curly-newline: warn */ /* eslint no-underscore-dangle: warn */ /* eslint camelcase: warn */ /* eslint default-param-last: warn */ /* Required libraries. */ const path = require('path'); /* Fetch in the other needed components for the this Adaptor */ const AdapterBaseCl = require(path.join(__dirname, 'adapterBase.js')); let sevArray = [ { value: 0, name: 'emergency' }, { value: 1, name: 'alert' }, { value: 2, name: 'critical' }, { value: 3, name: 'error' }, { value: 4, name: 'warning' }, { value: 5, name: 'notice' }, { value: 6, name: 'info' }, { value: 7, name: 'debug' } ]; /* * INTERNAL FUNCTION: countAlerts takes in an array of alerts and counts * the number of critical, warning and notices and then returns an * object with the counts and the array of alerts */ function countAlerts(alertResp) { const sevArrayCount = sevArray; const retResp = alertResp; const alertArray = alertResp.response; // initialize the counts to 0 for (let s = 0; s < sevArrayCount.length; s += 1) { sevArrayCount[s].count = 0; } // go through the alerts that were returned for (let i = 0; i < alertArray.length; i += 1) { // go through the severities we know about for (let s = 0; s < sevArrayCount.length; s += 1) { // if a match is found add the count and severity type if (alertArray[i].severity === sevArrayCount[s].value) { sevArrayCount[s].count += 1; alertArray[i].severityType = sevArrayCount[s].name; } } } retResp.response = { counts: sevArrayCount, alerts: alertArray }; return (retResp); } /* * INTERNAL FUNCTION: add the type to the alert information based on severity */ function addAlertTypes(alertResp) { const retResp = alertResp; const alertArray = alertResp.response; // go through the alerts that were returned for (let i = 0; i < alertArray.length; i += 1) { // go through the severities we know about for (let s = 0; s < sevArray.length; s += 1) { // if a match is found add the severity type if (alertArray[i].severity === sevArray[s].value) { alertArray[i].severityType = sevArray[s].name; } } } return (retResp); } /* * INTERNAL FUNCTION: analyzeIndicators takes in an array of indicator data and * finds KPI information (min, max, etc) */ function analyzeIndicators(indicatorData) { // set up analyzed const analyzed = { number: 0, min: null, max: null, avg: null, last: null, data: indicatorData.response }; const retResp = indicatorData; // if no indicator data return the default if (!indicatorData || !indicatorData.response) { retResp.response = analyzed; return retResp; } // set the number of indicator data analyzed.number = indicatorData.response.length; let totalNum = 0; let lastTime = 0; // go through to get the min and max data for (let i = 0; i < indicatorData.response.length; i += 1) { // seed the min and max if (i === 0) { analyzed.min = Number(indicatorData.response[i].value); analyzed.max = Number(indicatorData.response[i].value); analyzed.last = Number(indicatorData.response[i].value); lastTime = Number(indicatorData.response[i].time); } else { if (Number(analyzed.min) > Number(indicatorData.response[i].value)) { // reset the min if the new number is less analyzed.min = Number(indicatorData.response[i].value); } if (Number(analyzed.max) < Number(indicatorData.response[i].value)) { // reset the max if the new number is greater analyzed.max = Number(indicatorData.response[i].value); } if (Number(lastTime) < Number(indicatorData.response[i].time)) { // reset the last time if the new number came after analyzed.last = Number(indicatorData.response[i].value); lastTime = Number(indicatorData.response[i].time); } } // add the value to the holder so we can get the average totalNum += Number(indicatorData.response[i].value); } // set the average analyzed.avg = totalNum / analyzed.number; // return the result retResp.response = analyzed; return retResp; } /** * This is the adapter/interface into SevOne */ /* GENERAL ADAPTER FUNCTIONS */ class SevOne extends AdapterBaseCl { /** * SevOne Adapter * @constructor */ constructor(prongid, properties) { // Instantiate the AdapterBase super class super(prongid, properties); /* Working on changing the way we do Emit methods due to size and time constrainsts const restFunctionNames = this.getWorkflowFunctions(); // Dynamically bind emit functions for (let i = 0; i < restFunctionNames.length; i += 1) { // Bind function to have name fnNameEmit for fnName const version = restFunctionNames[i].match(/__v[0-9]+/); const baseFnName = restFunctionNames[i].replace(/__v[0-9]+/, ''); const fnNameEmit = version ? `${baseFnName}Emit${version}` : `${baseFnName}Emit`; this[fnNameEmit] = function (...args) { // extract the callback const callback = args[args.length - 1]; // slice the callback from args so we can insert our own const functionArgs = args.slice(0, args.length - 1); // create a random name for the listener const eventName = `${restFunctionNames[i]}:${Math.random().toString(36)}`; // tell the calling class to start listening callback({ event: eventName, status: 'received' }); // store parent for use of this context later const parent = this; // store emission function const func = function (val, err) { parent.removeListener(eventName, func); parent.emit(eventName, val, err); }; // Use apply to call the function in a specific context this[restFunctionNames[i]].apply(this, functionArgs.concat([func])); // eslint-disable-line prefer-spread }; } */ // Uncomment if you have things to add to the constructor like using your own properties. // Otherwise the constructor in the adapterBase will be used. // Capture my own properties - they need to be defined in propertiesSchema.json // Capture the severities if they were defined as properties if (this.allProps && this.allProps.severities) { sevArray = this.allProps.severities; } } /** * @callback healthCallback * @param {Object} reqObj - the request to send into the healthcheck * @param {Callback} callback - The results of the call */ healthCheck(reqObj, callback) { // you can modify what is passed into the healthcheck by changing things in the newReq let newReq = null; if (reqObj) { newReq = Object.assign(...reqObj); } super.healthCheck(newReq, callback); } /** * @iapGetAdapterWorkflowFunctions */ iapGetAdapterWorkflowFunctions(inIgnore) { let myIgnore = [ 'healthCheck', 'iapGetAdapterWorkflowFunctions', 'hasEntities', 'getAuthorization' ]; if (!inIgnore && Array.isArray(inIgnore)) { myIgnore = inIgnore; } else if (!inIgnore && typeof inIgnore === 'string') { myIgnore = [inIgnore]; } // The generic adapter functions should already be ignored (e.g. healthCheck) // you can add specific methods that you do not want to be workflow functions to ignore like below // myIgnore.push('myMethodNotInWorkflow'); return super.iapGetAdapterWorkflowFunctions(myIgnore); } /** * iapUpdateAdapterConfiguration is used to update any of the adapter configuration files. This * allows customers to make changes to adapter configuration without having to be on the * file system. * * @function iapUpdateAdapterConfiguration * @param {string} configFile - the name of the file being updated (required) * @param {Object} changes - an object containing all of the changes = formatted like the configuration file (required) * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional) * @param {string} type - the type of entity file to change, (action, schema, mock) (optional) * @param {string} action - the action to be changed, if an action, schema or mock data file (optional) * @param {boolean} replace - true to replace entire mock data, false to merge/append * @param {Callback} callback - The results of the call */ iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, replace, callback) { const meth = 'adapter-iapUpdateAdapterConfiguration'; const origin = `${this.id}-${meth}`; log.trace(origin); super.iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, replace, callback); } /** * @summary Suspends adapter * * @function iapSuspendAdapter * @param {Callback} callback - callback function */ iapSuspendAdapter(mode, callback) { const meth = 'adapter-iapSuspendAdapter'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapSuspendAdapter(mode, callback); } catch (error) { log.error(`${origin}: ${error}`); return callback(null, error); } } /** * @summary Unsuspends adapter * * @function iapUnsuspendAdapter * @param {Callback} callback - callback function */ iapUnsuspendAdapter(callback) { const meth = 'adapter-iapUnsuspendAdapter'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapUnsuspendAdapter(callback); } catch (error) { log.error(`${origin}: ${error}`); return callback(null, error); } } /** * @summary Get the Adapter Queue * * @function iapGetAdapterQueue * @param {Callback} callback - callback function */ iapGetAdapterQueue(callback) { const meth = 'adapter-iapGetAdapterQueue'; const origin = `${this.id}-${meth}`; log.trace(origin); return super.iapGetAdapterQueue(callback); } /* SCRIPT CALLS */ /** * See if the API path provided is found in this adapter * * @function iapFindAdapterPath * @param {string} apiPath - the api path to check on * @param {Callback} callback - The results of the call */ iapFindAdapterPath(apiPath, callback) { const meth = 'adapter-iapFindAdapterPath'; const origin = `${this.id}-${meth}`; log.trace(origin); super.iapFindAdapterPath(apiPath, callback); } /** * @summary Runs troubleshoot scripts for adapter * * @function iapTroubleshootAdapter * @param {Object} props - the connection, healthcheck and authentication properties * * @param {Callback} callback - The results of the call */ iapTroubleshootAdapter(props, callback) { const meth = 'adapter-iapTroubleshootAdapter'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapTroubleshootAdapter(props, this, callback); } catch (error) { log.error(`${origin}: ${error}`); return callback(null, error); } } /** * @summary runs healthcheck script for adapter * * @function iapRunAdapterHealthcheck * @param {Adapter} adapter - adapter instance to troubleshoot * @param {Callback} callback - callback function */ iapRunAdapterHealthcheck(callback) { const meth = 'adapter-iapRunAdapterHealthcheck'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapRunAdapterHealthcheck(this, callback); } catch (error) { log.error(`${origin}: ${error}`); return callback(null, error); } } /** * @summary runs connectivity check script for adapter * * @function iapRunAdapterConnectivity * @param {Callback} callback - callback function */ iapRunAdapterConnectivity(callback) { const meth = 'adapter-iapRunAdapterConnectivity'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapRunAdapterConnectivity(callback); } catch (error) { log.error(`${origin}: ${error}`); return callback(null, error); } } /** * @summary runs basicGet script for adapter * * @function iapRunAdapterBasicGet * @param {number} maxCalls - how many GET endpoints to test (optional) * @param {Callback} callback - callback function */ iapRunAdapterBasicGet(maxCalls, callback) { const meth = 'adapter-iapRunAdapterBasicGet'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapRunAdapterBasicGet(maxCalls, callback); } catch (error) { log.error(`${origin}: ${error}`); return callback(null, error); } } /** * @summary moves entites into Mongo DB * * @function iapMoveAdapterEntitiesToDB * @param {getCallback} callback - a callback function to return the result (Generics) * or the error */ iapMoveAdapterEntitiesToDB(callback) { const meth = 'adapter-iapMoveAdapterEntitiesToDB'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapMoveAdapterEntitiesToDB(callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * @summary Deactivate adapter tasks * * @function iapDeactivateTasks * * @param {Array} tasks - List of tasks to deactivate * @param {Callback} callback */ iapDeactivateTasks(tasks, callback) { const meth = 'adapter-iapDeactivateTasks'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapDeactivateTasks(tasks, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * @summary Activate adapter tasks that have previously been deactivated * * @function iapActivateTasks * * @param {Array} tasks - List of tasks to activate * @param {Callback} callback */ iapActivateTasks(tasks, callback) { const meth = 'adapter-iapActivateTasks'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapActivateTasks(tasks, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /* CACHE CALLS */ /** * @summary Populate the cache for the given entities * * @function iapPopulateEntityCache * @param {String/Array of Strings} entityType - the entity type(s) to populate * @param {Callback} callback - whether the cache was updated or not for each entity type * * @returns status of the populate */ iapPopulateEntityCache(entityTypes, callback) { const meth = 'adapter-iapPopulateEntityCache'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapPopulateEntityCache(entityTypes, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * @summary Retrieves data from cache for specified entity type * * @function iapRetrieveEntitiesCache * @param {String} entityType - entity of which to retrieve * @param {Object} options - settings of which data to return and how to return it * @param {Callback} callback - the data if it was retrieved */ iapRetrieveEntitiesCache(entityType, options, callback) { const meth = 'adapter-iapCheckEiapRetrieveEntitiesCachentityCached'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapRetrieveEntitiesCache(entityType, options, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /* BROKER CALLS */ /** * @summary Determines if this adapter supports any in a list of entities * * @function hasEntities * @param {String} entityType - the entity type to check for * @param {Array} entityList - the list of entities we are looking for * * @param {Callback} callback - A map where the entity is the key and the * value is true or false */ hasEntities(entityType, entityList, callback) { const meth = 'adapter-hasEntities'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.hasEntities(entityType, entityList, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * @summary Get Appliance that match the deviceName * * @function getDevice * @param {String} deviceName - the deviceName to find (required) * * @param {getCallback} callback - a callback function to return the result * (appliance) or the error */ getDevice(deviceName, callback) { const meth = 'adapter-getDevice'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.getDevice(deviceName, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * @summary Get Appliances that match the filter * * @function getDevicesFiltered * @param {Object} options - the data to use to filter the appliances (optional) * * @param {getCallback} callback - a callback function to return the result * (appliances) or the error */ getDevicesFiltered(options, callback) { const meth = 'adapter-getDevicesFiltered'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.getDevicesFiltered(options, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * @summary Gets the status for the provided appliance * * @function isAlive * @param {String} deviceName - the deviceName of the appliance. (required) * * @param {configCallback} callback - callback function to return the result * (appliance isAlive) or the error */ isAlive(deviceName, callback) { const meth = 'adapter-isAlive'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.isAlive(deviceName, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * @summary Gets a config for the provided Appliance * * @function getConfig * @param {String} deviceName - the deviceName of the appliance. (required) * @param {String} format - the desired format of the config. (optional) * * @param {configCallback} callback - callback function to return the result * (appliance config) or the error */ getConfig(deviceName, format, callback) { const meth = 'adapter-getConfig'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.getConfig(deviceName, format, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * @summary Gets the device count from the system * * @function iapGetDeviceCount * * @param {getCallback} callback - callback function to return the result * (count) or the error */ iapGetDeviceCount(callback) { const meth = 'adapter-iapGetDeviceCount'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapGetDeviceCount(callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /* GENERIC ADAPTER REQUEST - allows extension of adapter without new calls being added */ /** * Makes the requested generic call * * @function iapExpandedGenericAdapterRequest * @param {Object} metadata - metadata for the call (optional). * Can be a stringified Object. * @param {String} uriPath - the path of the api call - do not include the host, port, base path or version (optional) * @param {String} restMethod - the rest method (GET, POST, PUT, PATCH, DELETE) (optional) * @param {Object} pathVars - the parameters to be put within the url path (optional). * Can be a stringified Object. * @param {Object} queryData - the parameters to be put on the url (optional). * Can be a stringified Object. * @param {Object} requestBody - the body to add to the request (optional). * Can be a stringified Object. * @param {Object} addlHeaders - additional headers to be put on the call (optional). * Can be a stringified Object. * @param {getCallback} callback - a callback function to return the result (Generics) * or the error */ iapExpandedGenericAdapterRequest(metadata, uriPath, restMethod, pathVars, queryData, requestBody, addlHeaders, callback) { const meth = 'adapter-iapExpandedGenericAdapterRequest'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.iapExpandedGenericAdapterRequest(metadata, uriPath, restMethod, pathVars, queryData, requestBody, addlHeaders, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * Makes the requested generic call * * @function genericAdapterRequest * @param {String} uriPath - the path of the api call - do not include the host, port, base path or version (required) * @param {String} restMethod - the rest method (GET, POST, PUT, PATCH, DELETE) (required) * @param {Object} queryData - the parameters to be put on the url (optional). * Can be a stringified Object. * @param {Object} requestBody - the body to add to the request (optional). * Can be a stringified Object. * @param {Object} addlHeaders - additional headers to be put on the call (optional). * Can be a stringified Object. * @param {getCallback} callback - a callback function to return the result (Generics) * or the error */ genericAdapterRequest(uriPath, restMethod, queryData, requestBody, addlHeaders, callback) { const meth = 'adapter-genericAdapterRequest'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.genericAdapterRequest(uriPath, restMethod, queryData, requestBody, addlHeaders, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /** * Makes the requested generic call with no base path or version * * @function genericAdapterRequestNoBasePath * @param {String} uriPath - the path of the api call - do not include the host, port, base path or version (required) * @param {String} restMethod - the rest method (GET, POST, PUT, PATCH, DELETE) (required) * @param {Object} queryData - the parameters to be put on the url (optional). * Can be a stringified Object. * @param {Object} requestBody - the body to add to the request (optional). * Can be a stringified Object. * @param {Object} addlHeaders - additional headers to be put on the call (optional). * Can be a stringified Object. * @param {getCallback} callback - a callback function to return the result (Generics) * or the error */ genericAdapterRequestNoBasePath(uriPath, restMethod, queryData, requestBody, addlHeaders, callback) { const meth = 'adapter-genericAdapterRequestNoBasePath'; const origin = `${this.id}-${meth}`; log.trace(origin); try { return super.genericAdapterRequestNoBasePath(uriPath, restMethod, queryData, requestBody, addlHeaders, callback); } catch (err) { log.error(`${origin}: ${err}`); return callback(null, err); } } /* INVENTORY CALLS */ /** * @summary run the adapter lint script to return the results. * * @function iapRunAdapterLint * @param {Callback} callback - callback function */ iapRunAdapterLint(callback) { const meth = 'adapter-iapRunAdapterLint'; const origin = `${this.id}-${meth}`; log.trace(origin); return super.iapRunAdapterLint(callback); } /** * @summary run the adapter test scripts (baseunit and unit) to return the results. * can not run integration as there can be implications with that. * * @function iapRunAdapterTests * @param {Callback} callback - callback function */ iapRunAdapterTests(callback) { const meth = 'adapter-iapRunAdapterTests'; const origin = `${this.id}-${meth}`; log.trace(origin); return super.iapRunAdapterTests(callback); } /** * @summary provide inventory information abbout the adapter * * @function iapGetAdapterInventory * @param {Callback} callback - callback function */ iapGetAdapterInventory(callback) { const meth = 'adapter-iapGetAdapterInventory'; const origin = `${this.id}-${meth}`; log.trace(origin); return super.iapGetAdapterInventory(callback); } /** * @callback healthCallback * @param {Object} result - the result of the get request (contains an id and a status) */ /** * @callback getCallback * @param {Object} result - the result of the get request (entity/ies) * @param {String} error - any error that occurred */ /** * @callback createCallback * @param {Object} item - the newly created entity * @param {String} error - any error that occurred */ /** * @callback updateCallback * @param {String} status - the status of the update action * @param {String} error - any error that occurred */ /** * @callback deleteCallback * @param {String} status - the status of the delete action * @param {String} error - any error that occurred */ /* SEVONE SPECIFIC CALLS - ALERTS */ /** * @summary Call to get the alerts from SevOne. If a alertId is provided it will retrieve the * specific alert. Otherwise it will retrieve all the alerts. * * @function getAlerts * @param {String} alertId - the id of a specific alert to get. (optional) * @param {uriOptions} uriOptions - optional paramters to pass on uri of the request (optional). * Can be a stringified Object. * all: page, size * one: none * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlerts(alertId, uriOptions, callback) { const meth = 'adapter-getAlerts'; const origin = `${this.id}-${meth}`; log.trace(origin); if (this.suspended && this.suspendMode === 'error') { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'AD.600', [], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } try { // set up the request object - payload, uriPathVars, uriQuery, uriOptions, addlHeaders const reqObj = { uriOptions }; // add the alert id if provided if (alertId) { reqObj.uriPathVars = [alertId]; } // Make the call - identifyRequest(entity, action, requestObj, returnDataFlag, callback) return this.requestHandlerInst.identifyRequest('alert', 'getAlerts', reqObj, true, (result, error) => { // if we received an error or their is no response on the results return an error if (error) { return callback(null, error); } if (!Object.hasOwnProperty.call(result, 'response')) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', ['getAlerts'], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } // return the response return callback(addAlertTypes(result)); }); } catch (ex) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } } /** * @summary Call to get the alerts from SevOne. If a alertId is provided it will retrieve the * specific alert. Otherwise it will retrieve all the alerts. * * @function getAlertsById * @param {String} alertId - the id of a specific alert to get. (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsById(alertId, callback) { const meth = 'adapter-getAlertsById'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; return this.getAlerts(alertId, opts, callback); } /** * @summary Call to get the alerts from SevOne based on the criteria provided in the query * parameters * * @function getAlertsFiltered * @param {Object} filterObj - the filter to be used (optional). * Can be a stringified Object. * @param {uriOptions} uriOptions - optional paramters to pass on uri of the request (optional). * Can be a stringified Object. * all: page, size * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsFiltered(filterObj, uriOptions, callback) { const meth = 'adapter-getAlertsFiltered'; const origin = `${this.id}-${meth}`; log.trace(origin); if (this.suspended && this.suspendMode === 'error') { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'AD.600', [], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } try { // if the filter object is null or empty just call getAlerts if (!filterObj || Object.keys(filterObj).length === 0) { return this.getAlerts(null, uriOptions, callback); } const newFilter = filterObj; // Make sure what is supposed to be an array, is an array if (Object.hasOwnProperty.call(newFilter, 'assignedTo') && newFilter.assignedTo.constructor !== Array) { newFilter.assignedTo = [newFilter.assignedTo]; } if (Object.hasOwnProperty.call(newFilter, 'deviceId') && newFilter.deviceId.constructor !== Array) { newFilter.deviceId = [newFilter.deviceId]; } if (Object.hasOwnProperty.call(newFilter, 'componentId') && newFilter.componentId.constructor !== Array) { newFilter.componentId = [newFilter.componentId]; } if (Object.hasOwnProperty.call(newFilter, 'pollId') && newFilter.pollId.constructor !== Array) { newFilter.pollId = [newFilter.pollId]; } if (Object.hasOwnProperty.call(newFilter, 'thresholdId') && newFilter.thresholdId.constructor !== Array) { newFilter.thresholdId = [newFilter.thresholdId]; } // set up the request object - payload, uriPathVars, uriQuery, uriOptions, addlHeaders const reqObj = { payload: newFilter, uriOptions }; // Make the call - identifyRequest(entity, action, requestObj, returnDataFlag, callback) return this.requestHandlerInst.identifyRequest('alert', 'getAlertsFiltered', reqObj, true, (result, error) => { // if we received an error or their is no response on the results return an error if (error) { return callback(null, error); } if (!Object.hasOwnProperty.call(result, 'response')) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', ['getAlertsFiltered'], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } // return the response return callback(addAlertTypes(result)); }); } catch (ex) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } } /** * @summary Returns the alerts from the provided SevOne instance for the provided Device. * * @function getAlertsForDevice * @param {String} deviceId - the device id of the device to retrive alerts for (optional) * @param {String} deviceName - the name of the device to retrive alerts for (optional) * @param {String} ipAddr - returns the device for the specific ip address (optional) * @param {uriOptions} uriOptions - optional paramters to pass on uri of the request (optional). * Can be a stringified Object. * one: page, size, Alert status * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsForDevice(deviceId, deviceName, ipAddr, uriOptions, callback) { const meth = 'adapter-getAlertsForDevice'; const origin = `${this.id}-${meth}`; log.trace(origin); if (this.suspended && this.suspendMode === 'error') { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'AD.600', [], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } try { // if we have the device id if (deviceId) { // set up the request object - payload, uriPathVars, uriQuery, uriOptions, addlHeaders const reqObj = { uriPathVars: [deviceId], uriOptions }; // Make the call - identifyRequest(entity, action, requestObj, returnDataFlag, callback) return this.requestHandlerInst.identifyRequest('alert', 'getAlertsForDevice', reqObj, true, (result, error) => { // if we received an error or their is no response on the results return an error if (error) { return callback(null, error); } if (!Object.hasOwnProperty.call(result, 'response')) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', ['getAlertsForDevice'], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } // return the response return callback(addAlertTypes(result)); }); } if (!deviceName && !ipAddr) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['device criteria'], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } // need to get the device id and then make the call return this.getDevicesForNameorIP(deviceName, ipAddr, uriOptions, (devices, aerror) => { // if we received an error or their is no response on the results return an error if (aerror) { return callback(null, aerror); } // if we did not get devices back if (!devices || !devices.response || !Array.isArray(devices.response)) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unable to locate Device: $VARIABLE$', [`${deviceName}:${ipAddr}`], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } // set up the request object - payload, uriPathVars, uriQuery, uriOptions, addlHeaders const reqObj = { uriPathVars: [devices.response[0].id], uriOptions }; // Make the call - identifyRequest(entity, action, requestObj, returnDataFlag, callback) return this.requestHandlerInst.identifyRequest('alert', 'getAlertsForDevice', reqObj, true, (result, error) => { // if we received an error or their is no response on the results return an error if (error) { return callback(null, error); } if (!Object.hasOwnProperty.call(result, 'response')) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', ['getAlertsForDevice'], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } // return the response return callback(addAlertTypes(result)); }); }); } catch (ex) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } } /** * @summary Returns the alerts from the provided SevOne instance for the provided Device. * * @function getAlertsForDeviceById * @param {String} deviceId - the device id of the device to retrive alerts for (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsForDeviceById(deviceId, callback) { const meth = 'adapter-getAlertsForDeviceById'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; return this.getAlertsForDevice(deviceId, null, null, opts, callback); } /** * @summary Returns the alerts from the provided SevOne instance for the provided Device. * * @function getAlertsForDeviceByName * @param {String} deviceName - the name of the device to retrive alerts for (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsForDeviceByName(deviceName, callback) { const meth = 'adapter-getAlertsForDeviceByName'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; return this.getAlertsForDevice(null, deviceName, null, opts, callback); } /** * @summary Returns the alerts from the provided SevOne instance for the provided Device. * * @function getAlertsForDeviceByIp * @param {String} ipAddr - returns the device for the specific ip address (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsForDeviceByIp(ipAddr, callback) { const meth = 'adapter-getAlertsForDeviceByIp'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; return this.getAlertsForDevice(null, null, ipAddr, opts, callback); } /** * @summary Returns the count of alerts from the provided SevOne instance for the provided Device * * @function getAlertCountsForDevice * @param {String} deviceId - the device id of the device to retrive alerts for (optional) * @param {String} deviceName - the name of the device to retrive alerts for (optional) * @param {String} ipAddr - returns the device for the specific ip address (optional) * @param {getCallback} callback - a callback function to return the result * (Alert Counts) or the error */ getAlertCountsForDevice(deviceId, deviceName, ipAddr, callback) { const meth = 'adapter-getAlertCountsForDevice'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; // get the alerts for the device return this.getAlertsForDevice(deviceId, deviceName, ipAddr, opts, (alertResp, aerror) => { if (aerror) { return callback(null, aerror); } // count the alerts that we got back return callback(countAlerts(alertResp)); }); } /** * @summary Returns the count of alerts from the provided SevOne instance for the provided Device * * @function getAlertCountsForDeviceById * @param {String} deviceId - the device id of the device to retrive alerts for (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertCountsForDeviceById(deviceId, callback) { const meth = 'adapter-getAlertCountsForDeviceById'; const origin = `${this.id}-${meth}`; log.trace(origin); return this.getAlertCountsForDevice(deviceId, null, null, callback); } /** * @summary Returns the count of alerts from the provided SevOne instance for the provided Device * * @function getAlertCountsForDeviceByName * @param {String} deviceName - the name of the device to retrive alerts for (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertCountsForDeviceByName(deviceName, callback) { const meth = 'adapter-getAlertCountsForDeviceByName'; const origin = `${this.id}-${meth}`; log.trace(origin); return this.getAlertCountsForDevice(null, deviceName, null, callback); } /** * @summary Returns the count of alerts from the provided SevOne instance for the provided Device * * @function getAlertCountsForDeviceByIp * @param {String} ipAddr - returns the device for the specific ip address (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertCountsForDeviceByIp(ipAddr, callback) { const meth = 'adapter-getAlertCountsForDeviceByIp'; const origin = `${this.id}-${meth}`; log.trace(origin); return this.getAlertCountsForDevice(null, null, ipAddr, callback); } /** * @summary Returns alerts for the provided device from SevOne that are within the provided * time range * * @function getAlertsForDeviceWithRange * @param {String} deviceId - the specific device to return alerts for (required) * @param {String} deviceName - the name of the device to retrive alerts for (optional) * @param {String} ipAddr - returns the device for the specific ip address (optional) * @param {String} startTime - alerts that occured after this time (optional) * @param {String} endTime - alerts that occured before this time (optional) * @param {uriOptions} uriOptions - optional paramters to pass on uri of the request (optional). * Can be a stringified Object. * all: page, size * @param {getCallback} callback - a callback function to return the result */ getAlertsForDeviceWithRange(deviceId, deviceName, ipAddr, startTime, endTime, uriOptions, callback) { const meth = 'adapter-getAlertsForDeviceWithRange'; const origin = `${this.id}-${meth}`; log.trace(origin); if (this.suspended && this.suspendMode === 'error') { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'AD.600', [], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } try { // verify the device id and the component id as they are required. if (!deviceId && !deviceName && !ipAddr) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['device criteria'], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } // if no times then just get the alerts for the device if (!startTime && !endTime) { return this.getAlertsForDevice(deviceId, deviceName, ipAddr, uriOptions, callback); } // set up the default alert filter object const alertObj = { timespanBetween: { startTime: 0, endTime: new Date().getTime() } }; // if we have the device id if (deviceId) { // add the device to the alert filter object alertObj.deviceId = [deviceId]; if (startTime > 0) { alertObj.timespanBetween.startTime = startTime; } if (endTime > 0) { alertObj.timespanBetween.endTime = endTime; } // real call to get alerts return this.getAlertsFiltered(alertObj, uriOptions, callback); } // need to get the device id and then make the call return this.getDevicesForNameorIP(deviceName, ipAddr, uriOptions, (devices, aerror) => { if (aerror) { return callback(null, aerror); } // if we did not get devices back if (!devices || !devices.response || !Array.isArray(devices.response)) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unable to locate Device: $VARIABLE$', [`${deviceName}:${ipAddr}`], null, null, null); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } // add the device to the alert filter object alertObj.deviceId = [devices.response[0].id]; if (startTime > 0) { alertObj.timespanBetween.startTime = startTime; } if (endTime > 0) { alertObj.timespanBetween.endTime = endTime; } // real call to get alerts return this.getAlertsFiltered(alertObj, uriOptions, callback); }); } catch (ex) { const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex); log.error(`${origin}: ${errorObj.IAPerror.displayString}`); return callback(null, errorObj); } } /** * @summary Returns alerts for the provided device from SevOne that are within the provided * time range * * @function getAlertsForDeviceWithRangeById * @param {String} deviceId - the device id of the device to retrive alerts for (optional) * @param {String} startTime - alerts that occured after this time (optional) * @param {String} endTime - alerts that occured before this time (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsForDeviceWithRangeById(deviceId, startTime, endTime, callback) { const meth = 'adapter-getAlertsForDeviceWithRangeById'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; return this.getAlertsForDeviceWithRange(deviceId, null, null, startTime, endTime, opts, callback); } /** * @summary Returns alerts for the provided device from SevOne that are within the provided * time range * * @function getAlertsForDeviceWithRangeByName * @param {String} deviceName - the name of the device to retrive alerts for (optional) * @param {String} startTime - alerts that occured after this time (optional) * @param {String} endTime - alerts that occured before this time (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsForDeviceWithRangeByName(deviceName, startTime, endTime, callback) { const meth = 'adapter-getAlertsForDeviceWithRangeByName'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; return this.getAlertsForDeviceWithRange(null, deviceName, null, startTime, endTime, opts, callback); } /** * @summary Returns alerts for the provided device from SevOne that are within the provided * time range * * @function getAlertsForDeviceWithRangeByIp * @param {String} ipAddr - returns the device for the specific ip address (optional) * @param {String} startTime - alerts that occured after this time (optional) * @param {String} endTime - alerts that occured before this time (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsForDeviceWithRangeByIp(ipAddr, startTime, endTime, callback) { const meth = 'adapter-getAlertsForDeviceWithRangeByIp'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; return this.getAlertsForDeviceWithRange(null, null, ipAddr, startTime, endTime, opts, callback); } /** * @summary Returns alerts for the provided device from SevOne that are within the last day * * @function getAlertsForDeviceForDayById * @param {String} deviceId - the device id of the device to retrive alerts for (optional) * @param {getCallback} callback - a callback function to return the result * (Alerts) or the error */ getAlertsForDeviceForDayById(deviceId, callback) { const meth = 'adapter-getAlertsForDeviceForDayById'; const origin = `${this.id}-${meth}`; log.trace(origin); const opts = { size: 10000, sortBy: 'severity' }; const curr = new Date(); const end = curr.getTime(); const start = end - (24 * 60 * 60 * 1000); return this.getAlertsForDeviceWithRange(deviceId, null, null, start, end, opts, callback); } /** * @summary Returns alerts for the provide