openwhisk-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From csantan...@apache.org
Subject [incubator-openwhisk-package-alarms] branch master updated: loosen restrictions on redis values (#149)
Date Wed, 09 May 2018 12:46:50 GMT
This is an automated email from the ASF dual-hosted git repository.

csantanapr pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-openwhisk-package-alarms.git


The following commit(s) were added to refs/heads/master by this push:
     new 70a5b11  loosen restrictions on redis values (#149)
70a5b11 is described below

commit 70a5b11f5648187f7d79068b2579d4bfc629c7e7
Author: Jason Peterson <jasonpet@us.ibm.com>
AuthorDate: Wed May 9 08:46:48 2018 -0400

    loosen restrictions on redis values (#149)
---
 provider/lib/active.js    |   4 +-
 provider/lib/constants.js |   4 +-
 provider/lib/health.js    |  19 ++---
 provider/lib/sanitizer.js |  14 +--
 provider/lib/utils.js     | 213 +++++++++++++++++++++++-----------------------
 5 files changed, 126 insertions(+), 128 deletions(-)

diff --git a/provider/lib/active.js b/provider/lib/active.js
index 25a8a6b..1e90bb2 100644
--- a/provider/lib/active.js
+++ b/provider/lib/active.js
@@ -28,10 +28,10 @@ module.exports = function(logger, utils) {
           var activeHost = query === 'true' ? utils.host : redundantHost;
           if (utils.activeHost !== activeHost) {
               if (utils.redisClient) {
-                  utils.redisClient.hsetAsync(utils.redisHash, utils.redisKey, activeHost)
+                  utils.redisClient.hsetAsync(utils.redisKey, utils.redisField, activeHost)
                   .then(() => {
                       response.active = 'swapping';
-                      utils.redisClient.publish(utils.redisHash, activeHost);
+                      utils.redisClient.publish(utils.redisKey, activeHost);
                       logger.info(method, 'Active host swap in progress');
                       res.send(response);
                   })
diff --git a/provider/lib/constants.js b/provider/lib/constants.js
index 5352696..dca9352 100644
--- a/provider/lib/constants.js
+++ b/provider/lib/constants.js
@@ -2,7 +2,7 @@ const TRIGGER_DB_SUFFIX = 'alarmservice';
 const DEFAULT_MAX_TRIGGERS = -1;
 const RETRY_ATTEMPTS = 10;
 const RETRY_DELAY = 1000; //in milliseconds
-const REDIS_KEY = 'active';
+const REDIS_FIELD = 'active';
 const FILTERS_DESIGN_DOC = 'triggerFilters';
 const VIEWS_DESIGN_DOC = 'triggerViews';
 const TRIGGERS_BY_WORKER = 'triggers_by_worker';
@@ -14,7 +14,7 @@ module.exports = {
     DEFAULT_MAX_TRIGGERS: DEFAULT_MAX_TRIGGERS,
     RETRY_ATTEMPTS: RETRY_ATTEMPTS,
     RETRY_DELAY: RETRY_DELAY,
-    REDIS_KEY: REDIS_KEY,
+    REDIS_FIELD: REDIS_FIELD,
     FILTERS_DESIGN_DOC: FILTERS_DESIGN_DOC,
     VIEWS_DESIGN_DOC: VIEWS_DESIGN_DOC,
     TRIGGERS_BY_WORKER: TRIGGERS_BY_WORKER,
diff --git a/provider/lib/health.js b/provider/lib/health.js
index 19874c2..98246a6 100644
--- a/provider/lib/health.js
+++ b/provider/lib/health.js
@@ -13,7 +13,6 @@ module.exports = function(logger, utils) {
     var alarmTypes = ['interval', 'date', 'cron'];
     var alarmTypeIndex = 0;
     var monitorStages = ['triggerStarted', 'triggerFired', 'triggerStopped'];
-    var healthMonitor = this;
 
     // Health Logic
     this.health = function (req, res) {
@@ -91,18 +90,18 @@ module.exports = function(logger, utils) {
 
         var triggerURL = utils.uriHost + '/api/v1/namespaces/_/triggers/' + triggerName;
         var triggerID = `${apikey}/_/${triggerName}`;
-        healthMonitor.createTrigger(triggerURL, auth)
+        createTrigger(triggerURL, auth)
         .then((info) => {
             logger.info(method, triggerID, info);
-            var newTrigger = healthMonitor.createAlarmTrigger(triggerID, apikey, alarmType);
-            healthMonitor.createTriggerInDB(triggerID, newTrigger);
+            var newTrigger = createAlarmTrigger(triggerID, apikey, alarmType);
+            createTriggerInDB(triggerID, newTrigger);
         })
         .catch(err => {
             logger.error(method, triggerID, err);
         });
     };
 
-    this.createAlarmTrigger = function(triggerID, apikey, alarmType) {
+    function createAlarmTrigger(triggerID, apikey, alarmType) {
         var method = 'createAlarmTrigger';
 
         var newTrigger = {
@@ -131,9 +130,9 @@ module.exports = function(logger, utils) {
         }
 
         return newTrigger;
-    };
+    }
 
-    this.createTrigger = function(triggerURL, auth) {
+    function createTrigger(triggerURL, auth) {
         var method = 'createTrigger';
 
         return new Promise(function(resolve, reject) {
@@ -155,9 +154,9 @@ module.exports = function(logger, utils) {
                 }
             });
         });
-    };
+    }
 
-    this.createTriggerInDB = function(triggerID, newTrigger) {
+    function createTriggerInDB (triggerID, newTrigger) {
         var method = 'createTriggerInDB';
 
         utils.db.insert(newTrigger, triggerID, function (err) {
@@ -168,6 +167,6 @@ module.exports = function(logger, utils) {
                 logger.error(method, triggerID, err);
             }
         });
-    };
+    }
 
 };
diff --git a/provider/lib/sanitizer.js b/provider/lib/sanitizer.js
index 3553010..31f8f79 100644
--- a/provider/lib/sanitizer.js
+++ b/provider/lib/sanitizer.js
@@ -2,7 +2,7 @@ var request = require('request');
 
 module.exports = function(logger, triggerDB, uriHost) {
 
-    var sanitizer = this;
+    var self = this;
 
     this.deleteTriggerFromDB = function(triggerID, retryCount) {
         var method = 'deleteTriggerFromDB';
@@ -14,7 +14,7 @@ module.exports = function(logger, triggerDB, uriHost) {
                     if (err) {
                         if (err.statusCode === 409 && retryCount < 5) {
                             setTimeout(function () {
-                                sanitizer.deleteTriggerFromDB(triggerID, (retryCount + 1));
+                                self.deleteTriggerFromDB(triggerID, (retryCount + 1));
                             }, 1000);
                         }
                         else {
@@ -53,7 +53,7 @@ module.exports = function(logger, triggerDB, uriHost) {
             }
             else {
                 //delete the trigger
-                sanitizer.deleteTrigger(dataTrigger, auth, 0)
+                self.deleteTrigger(dataTrigger, auth, 0)
                 .then((info) => {
                     logger.info(method, triggerIdentifier, info);
                     if (body) {
@@ -62,7 +62,7 @@ module.exports = function(logger, triggerDB, uriHost) {
                             for (var rule in jsonBody.rules) {
                                 var qualifiedName = rule.split('/');
                                 var uri = uriHost + '/api/v1/namespaces/' + qualifiedName[0]
+ '/rules/' + qualifiedName[1];
-                                sanitizer.deleteRule(rule, uri, auth, 0);
+                                self.deleteRule(rule, uri, auth, 0);
                             }
                         }
                         catch (err) {
@@ -96,7 +96,7 @@ module.exports = function(logger, triggerDB, uriHost) {
                     if (!error && response.statusCode === 409 && retryCount
< 5) {
                         logger.info(method, 'attempting to delete trigger again', triggerIdentifier,
'Retry Count:', (retryCount + 1));
                         setTimeout(function () {
-                            sanitizer.deleteTrigger(dataTrigger, auth, (retryCount + 1))
+                            self.deleteTrigger(dataTrigger, auth, (retryCount + 1))
                             .then(info => {
                                 resolve(info);
                             })
@@ -131,7 +131,7 @@ module.exports = function(logger, triggerDB, uriHost) {
                 if (!error && response.statusCode === 409 && retryCount <
5) {
                     logger.info(method, 'attempting to delete rule again', rule, 'Retry Count:',
(retryCount + 1));
                     setTimeout(function () {
-                        sanitizer.deleteRule(rule, uri, auth, (retryCount + 1));
+                        self.deleteRule(rule, uri, auth, (retryCount + 1));
                     }, 1000);
                 } else {
                     logger.error(method, rule, 'rule delete request failed');
@@ -172,7 +172,7 @@ module.exports = function(logger, triggerDB, uriHost) {
             });
         })
         .then(triggerID => {
-            sanitizer.deleteTriggerFromDB(triggerID, 0);
+            self.deleteTriggerFromDB(triggerID, 0);
         })
         .catch(err => {
             logger.error(method, triggerID, 'an error occurred while deleting the trigger
feed', err);
diff --git a/provider/lib/utils.js b/provider/lib/utils.js
index 28b2f08..108973f 100644
--- a/provider/lib/utils.js
+++ b/provider/lib/utils.js
@@ -9,6 +9,14 @@ var Sanitizer = require('./sanitizer');
 
 module.exports = function(logger, triggerDB, redisClient) {
 
+    var retryDelay = constants.RETRY_DELAY;
+    var retryAttempts = constants.RETRY_ATTEMPTS;
+    var filterDDName = constants.FILTERS_DESIGN_DOC;
+    var viewDDName = constants.VIEWS_DESIGN_DOC;
+    var triggersByWorker = constants.TRIGGERS_BY_WORKER;
+    var redisKeyPrefix = process.env.REDIS_KEY_PREFIX || triggerDB.config.db;
+    var self = this;
+
     this.triggers = {};
     this.endpointAuth = process.env.ENDPOINT_AUTH;
     this.routerHost = process.env.ROUTER_HOST || 'localhost';
@@ -17,34 +25,27 @@ module.exports = function(logger, triggerDB, redisClient) {
     this.activeHost = 'host0'; //default value on init (will be updated for existing redis)
     this.db = triggerDB;
     this.redisClient = redisClient;
-    this.redisHash = triggerDB.config.db + '_' + this.worker;
-    this.redisKey = constants.REDIS_KEY;
+    this.redisKey = redisKeyPrefix + '_' + this.worker;
+    this.redisField = constants.REDIS_FIELD;
     this.uriHost ='https://' + this.routerHost;
     this.sanitizer = new Sanitizer(logger, triggerDB, this.uriHost);
     this.monitorStatus = {};
 
-    var retryDelay = constants.RETRY_DELAY;
-    var retryAttempts = constants.RETRY_ATTEMPTS;
-    var filterDDName = constants.FILTERS_DESIGN_DOC;
-    var viewDDName = constants.VIEWS_DESIGN_DOC;
-    var triggersByWorker = constants.TRIGGERS_BY_WORKER;
-    var utils = this;
-
-    this.createTrigger = function(triggerIdentifier, newTrigger) {
+    function createTrigger(triggerIdentifier, newTrigger) {
         var method = 'createTrigger';
 
         var callback = function onTick() {
-            var triggerHandle = utils.triggers[triggerIdentifier];
-            if (triggerHandle && utils.shouldFireTrigger(triggerHandle) &&
utils.hasTriggersRemaining(triggerHandle)) {
+            var triggerHandle = self.triggers[triggerIdentifier];
+            if (triggerHandle && shouldFireTrigger(triggerHandle) && hasTriggersRemaining(triggerHandle))
{
                 try {
-                    utils.fireTrigger(triggerHandle);
+                    fireTrigger(triggerHandle);
                 } catch (e) {
                     logger.error(method, 'Exception occurred while firing trigger', triggerIdentifier,
e);
                 }
             }
         };
 
-        newTrigger.uri = utils.uriHost + '/api/v1/namespaces/' + newTrigger.namespace + '/triggers/'
+ newTrigger.name;
+        newTrigger.uri = self.uriHost + '/api/v1/namespaces/' + newTrigger.namespace + '/triggers/'
+ newTrigger.name;
         newTrigger.triggerID = triggerIdentifier;
 
         var alarm;
@@ -59,27 +60,27 @@ module.exports = function(logger, triggerDB, redisClient) {
         }
 
         return alarm.scheduleAlarm(triggerIdentifier, callback);
-    };
+    }
 
-    this.fireTrigger = function(dataTrigger) {
+    function fireTrigger(dataTrigger) {
         var method = 'fireTrigger';
 
         var triggerIdentifier = dataTrigger.triggerID;
         var auth = dataTrigger.apikey.split(':');
 
         logger.info(method, 'Alarm fired for', triggerIdentifier, 'attempting to fire trigger');
-        utils.postTrigger(dataTrigger, auth, 0)
+        postTrigger(dataTrigger, auth, 0)
         .then(triggerId => {
             logger.info(method, 'Trigger', triggerId, 'was successfully fired');
-            utils.handleFiredTrigger(dataTrigger);
+            handleFiredTrigger(dataTrigger);
         })
         .catch(err => {
             logger.error(method, err);
-            utils.handleFiredTrigger(dataTrigger);
+            handleFiredTrigger(dataTrigger);
         });
-    };
+    }
 
-    this.postTrigger = function(dataTrigger, auth, retryCount, throttleCount) {
+    function postTrigger(dataTrigger, auth, retryCount, throttleCount) {
         var method = 'postTrigger';
 
         return new Promise(function(resolve, reject) {
@@ -111,10 +112,10 @@ module.exports = function(logger, triggerDB, redisClient) {
                             dataTrigger.triggersLeft++;
                         }
 
-                        if (!error && utils.shouldDisableTrigger(response.statusCode))
{
+                        if (!error && shouldDisableTrigger(response.statusCode))
{
                             //disable trigger
                             var message = 'Automatically disabled after receiving a ' + response.statusCode
+ ' status code when firing the trigger';
-                            utils.disableTrigger(triggerIdentifier, response.statusCode,
message);
+                            disableTrigger(triggerIdentifier, response.statusCode, message);
                             reject('Disabled trigger ' + triggerIdentifier + ' due to status
code: ' + response.statusCode);
                         }
                         else {
@@ -122,7 +123,7 @@ module.exports = function(logger, triggerDB, redisClient) {
                                 throttleCounter = response && response.statusCode
=== HttpStatus.TOO_MANY_REQUESTS ? throttleCounter + 1 : throttleCounter;
                                 logger.info(method, 'attempting to fire trigger again', triggerIdentifier,
'Retry Count:', (retryCount + 1));
                                 setTimeout(function () {
-                                    utils.postTrigger(dataTrigger, auth, (retryCount + 1),
throttleCounter)
+                                    postTrigger(dataTrigger, auth, (retryCount + 1), throttleCounter)
                                     .then(triggerId => {
                                         resolve(triggerId);
                                     })
@@ -133,7 +134,7 @@ module.exports = function(logger, triggerDB, redisClient) {
                             } else {
                                 if (throttleCounter === retryAttempts) {
                                     var msg = 'Automatically disabled after continuously
receiving a 429 status code when firing the trigger';
-                                    utils.disableTrigger(triggerIdentifier, 429, msg);
+                                    disableTrigger(triggerIdentifier, 429, msg);
                                     reject('Disabled trigger ' + triggerIdentifier + ' due
to status code: 429');
                                 }
                                 else {
@@ -151,30 +152,30 @@ module.exports = function(logger, triggerDB, redisClient) {
                 }
             });
         });
-    };
+    }
 
-    this.shouldDisableTrigger = function(statusCode) {
+    function shouldDisableTrigger(statusCode) {
         return ((statusCode >= 400 && statusCode < 500) &&
             [HttpStatus.REQUEST_TIMEOUT, HttpStatus.TOO_MANY_REQUESTS].indexOf(statusCode)
=== -1);
-    };
+    }
 
-    this.shouldFireTrigger = function(trigger) {
-        return trigger.monitor || utils.activeHost === utils.host;
-    };
+    function shouldFireTrigger(trigger) {
+        return trigger.monitor || self.activeHost === self.host;
+    }
 
-    this.hasTriggersRemaining = function(trigger) {
+    function hasTriggersRemaining(trigger) {
         return !trigger.maxTriggers || trigger.maxTriggers === -1 || trigger.triggersLeft
> 0;
-    };
+    }
 
-    this.isMonitoringTrigger = function(monitor, triggerName) {
-        return monitor && utils.monitorStatus.triggerName === triggerName;
-    };
+    function isMonitoringTrigger(monitor, triggerName) {
+        return monitor && self.monitorStatus.triggerName === triggerName;
+    }
 
-    this.handleFiredTrigger = function(dataTrigger) {
+    function handleFiredTrigger(dataTrigger) {
         var method = 'handleFiredTrigger';
 
-        if (utils.isMonitoringTrigger(dataTrigger.monitor, dataTrigger.name)) {
-            utils.monitorStatus.triggerFired = "success";
+        if (isMonitoringTrigger(dataTrigger.monitor, dataTrigger.name)) {
+            self.monitorStatus.triggerFired = "success";
         }
 
         var triggerIdentifier = dataTrigger.triggerID;
@@ -182,15 +183,15 @@ module.exports = function(logger, triggerDB, redisClient) {
             if (dataTrigger.deleteAfterFire && dataTrigger.deleteAfterFire !== 'false')
{
 
                 //delete trigger feed from database
-                utils.sanitizer.deleteTriggerFeed(triggerIdentifier);
+                self.sanitizer.deleteTriggerFeed(triggerIdentifier);
 
                 //check if trigger and all associated rules should be deleted
                 if (dataTrigger.deleteAfterFire === 'rules') {
-                    utils.sanitizer.deleteTriggerAndRules(dataTrigger);
+                    self.sanitizer.deleteTriggerAndRules(dataTrigger);
                 }
                 else {
                     var auth = dataTrigger.apikey.split(':');
-                    utils.sanitizer.deleteTrigger(dataTrigger, auth, 0)
+                    self.sanitizer.deleteTrigger(dataTrigger, auth, 0)
                     .then(info => {
                         logger.info(method, triggerIdentifier, info);
                     })
@@ -200,28 +201,28 @@ module.exports = function(logger, triggerDB, redisClient) {
                 }
             }
             else {
-                utils.disableTrigger(triggerIdentifier, undefined, 'Automatically disabled
after firing once');
+                disableTrigger(triggerIdentifier, undefined, 'Automatically disabled after
firing once');
                 logger.info(method, 'the fire once date has expired, disabled', triggerIdentifier);
             }
         }
         else if (dataTrigger.stopDate) {
             //check if the next scheduled trigger is after the stop date
             if (dataTrigger.cronHandle && dataTrigger.cronHandle.nextDate().isAfter(new
Date(dataTrigger.stopDate))) {
-                utils.disableTrigger(triggerIdentifier, undefined, 'Automatically disabled
after firing last scheduled cron trigger');
+                disableTrigger(triggerIdentifier, undefined, 'Automatically disabled after
firing last scheduled cron trigger');
                 logger.info(method, 'last scheduled cron trigger before stop date, disabled',
triggerIdentifier);
             }
             else if (dataTrigger.minutes && (Date.now() + (dataTrigger.minutes *
1000 * 60) > new Date(dataTrigger.stopDate).getTime())) {
-                utils.disableTrigger(triggerIdentifier, undefined, 'Automatically disabled
after firing last scheduled interval trigger');
+                disableTrigger(triggerIdentifier, undefined, 'Automatically disabled after
firing last scheduled interval trigger');
                 logger.info(method, 'last scheduled interval trigger before stop date, disabled',
triggerIdentifier);
             }
         }
         else if (dataTrigger.maxTriggers && dataTrigger.triggersLeft === 0) {
-            utils.disableTrigger(triggerIdentifier, undefined, 'Automatically disabled after
reaching max triggers');
+            disableTrigger(triggerIdentifier, undefined, 'Automatically disabled after reaching
max triggers');
             logger.warn(method, 'no more triggers left, disabled', triggerIdentifier);
         }
-    };
+    }
 
-    this.disableTrigger = function(triggerIdentifier, statusCode, message) {
+    function disableTrigger(triggerIdentifier, statusCode, message) {
         var method = 'disableTrigger';
 
         triggerDB.get(triggerIdentifier, function (err, existing) {
@@ -248,45 +249,45 @@ module.exports = function(logger, triggerDB, redisClient) {
             else {
                 logger.info(method, 'could not find', triggerIdentifier, 'in database');
                 //make sure it is already stopped
-                utils.stopTrigger(triggerIdentifier);
+                stopTrigger(triggerIdentifier);
             }
         });
-    };
+    }
 
-    this.stopTrigger = function (triggerIdentifier) {
+    function stopTrigger(triggerIdentifier) {
         var method = 'stopTrigger';
 
-        if (utils.triggers[triggerIdentifier]) {
-            if (utils.triggers[triggerIdentifier].cronHandle) {
-                utils.triggers[triggerIdentifier].cronHandle.stop();
+        if (self.triggers[triggerIdentifier]) {
+            if (self.triggers[triggerIdentifier].cronHandle) {
+                self.triggers[triggerIdentifier].cronHandle.stop();
             }
-            else if (utils.triggers[triggerIdentifier].intervalHandle) {
-                lt.clearInterval(utils.triggers[triggerIdentifier].intervalHandle);
+            else if (self.triggers[triggerIdentifier].intervalHandle) {
+                lt.clearInterval(self.triggers[triggerIdentifier].intervalHandle);
             }
-            delete utils.triggers[triggerIdentifier];
+            delete self.triggers[triggerIdentifier];
             logger.info(method, 'trigger', triggerIdentifier, 'successfully deleted from
memory');
         }
-    };
+    }
 
     this.initAllTriggers = function() {
         var method = 'initAllTriggers';
 
         //follow the trigger DB
-        utils.setupFollow('now');
+        setupFollow('now');
 
         logger.info(method, 'resetting system from last state');
-        triggerDB.view(viewDDName, triggersByWorker, {reduce: false, include_docs: true,
key: utils.worker}, function(err, body) {
+        triggerDB.view(viewDDName, triggersByWorker, {reduce: false, include_docs: true,
key: self.worker}, function(err, body) {
             if (!err) {
                 body.rows.forEach(function (trigger) {
                     var triggerIdentifier = trigger.id;
                     var doc = trigger.doc;
 
-                    if (!(triggerIdentifier in utils.triggers) && !doc.monitor) {
+                    if (!(triggerIdentifier in self.triggers) && !doc.monitor) {
                         //check if trigger still exists in whisk db
                         var namespace = doc.namespace;
                         var name = doc.name;
                         var apikey = doc.apikey;
-                        var uri = utils.uriHost + '/api/v1/namespaces/' + namespace + '/triggers/'
+ name;
+                        var uri = self.uriHost + '/api/v1/namespaces/' + namespace + '/triggers/'
+ name;
                         var auth = apikey.split(':');
 
                         logger.info(method, 'Checking if trigger', triggerIdentifier, 'still
exists');
@@ -299,19 +300,19 @@ module.exports = function(logger, triggerDB, redisClient) {
                             }
                         }, function (error, response) {
                             //disable trigger in database if trigger is dead
-                            if (!error && utils.shouldDisableTrigger(response.statusCode))
{
+                            if (!error && shouldDisableTrigger(response.statusCode))
{
                                 var message = 'Automatically disabled after receiving a '
+ response.statusCode + ' status code on trigger initialization';
-                                utils.disableTrigger(triggerIdentifier, response.statusCode,
message);
+                                disableTrigger(triggerIdentifier, response.statusCode, message);
                                 logger.error(method, 'trigger', triggerIdentifier, 'has been
disabled due to status code:', response.statusCode);
                             }
                             else {
-                                utils.createTrigger(triggerIdentifier, doc)
+                                createTrigger(triggerIdentifier, doc)
                                 .then(cachedTrigger => {
-                                    utils.triggers[triggerIdentifier] = cachedTrigger;
+                                    self.triggers[triggerIdentifier] = cachedTrigger;
                                     logger.info(method, triggerIdentifier, 'created successfully');
-                                    if (cachedTrigger.intervalHandle && utils.shouldFireTrigger(cachedTrigger))
{
+                                    if (cachedTrigger.intervalHandle && shouldFireTrigger(cachedTrigger))
{
                                         try {
-                                            utils.fireTrigger(cachedTrigger);
+                                            fireTrigger(cachedTrigger);
                                         } catch (e) {
                                             logger.error(method, 'Exception occurred while
firing trigger', triggerIdentifier, e);
                                         }
@@ -319,7 +320,7 @@ module.exports = function(logger, triggerDB, redisClient) {
                                 })
                                 .catch(err => {
                                     var message = 'Automatically disabled after receiving
error on trigger initialization: ' + err;
-                                    utils.disableTrigger(triggerIdentifier, undefined, message);
+                                    disableTrigger(triggerIdentifier, undefined, message);
                                     logger.error(method, 'Disabled trigger', triggerIdentifier,
err);
                                 });
                             }
@@ -332,7 +333,7 @@ module.exports = function(logger, triggerDB, redisClient) {
         });
     };
 
-    this.setupFollow = function(seq) {
+    function setupFollow(seq) {
         var method = 'setupFollow';
 
         try {
@@ -340,7 +341,7 @@ module.exports = function(logger, triggerDB, redisClient) {
                 since: seq,
                 include_docs: true,
                 filter: filterDDName + '/' + triggersByWorker,
-                query_params: {worker: utils.worker}
+                query_params: {worker: self.worker}
             });
 
             feed.on('change', (change) => {
@@ -349,29 +350,29 @@ module.exports = function(logger, triggerDB, redisClient) {
 
                 logger.info(method, 'got change for trigger', triggerIdentifier);
 
-                if (utils.triggers[triggerIdentifier]) {
+                if (self.triggers[triggerIdentifier]) {
                     if (doc.status && doc.status.active === false) {
-                        utils.stopTrigger(triggerIdentifier);
-                        if (utils.isMonitoringTrigger(doc.monitor, doc.name)) {
-                            utils.monitorStatus.triggerStopped = "success";
+                        stopTrigger(triggerIdentifier);
+                        if (isMonitoringTrigger(doc.monitor, doc.name)) {
+                            self.monitorStatus.triggerStopped = "success";
                         }
                     }
                 }
                 else {
                     //ignore changes to disabled triggers
-                    if ((!doc.status || doc.status.active === true) && (!doc.monitor
|| doc.monitor === utils.host)) {
-                        utils.createTrigger(triggerIdentifier, doc)
+                    if ((!doc.status || doc.status.active === true) && (!doc.monitor
|| doc.monitor === self.host)) {
+                        createTrigger(triggerIdentifier, doc)
                         .then(cachedTrigger => {
-                            utils.triggers[triggerIdentifier] = cachedTrigger;
+                            self.triggers[triggerIdentifier] = cachedTrigger;
                             logger.info(method, triggerIdentifier, 'created successfully');
 
-                            if (utils.isMonitoringTrigger(cachedTrigger.monitor, cachedTrigger.name))
{
-                                utils.monitorStatus.triggerStarted = "success";
+                            if (isMonitoringTrigger(cachedTrigger.monitor, cachedTrigger.name))
{
+                                self.monitorStatus.triggerStarted = "success";
                             }
 
-                            if (cachedTrigger.intervalHandle && utils.shouldFireTrigger(cachedTrigger))
{
+                            if (cachedTrigger.intervalHandle && shouldFireTrigger(cachedTrigger))
{
                                 try {
-                                    utils.fireTrigger(cachedTrigger);
+                                    fireTrigger(cachedTrigger);
                                 } catch (e) {
                                     logger.error(method, 'Exception occurred while firing
trigger', triggerIdentifier, e);
                                 }
@@ -379,7 +380,7 @@ module.exports = function(logger, triggerDB, redisClient) {
                         })
                         .catch(err => {
                             var message = 'Automatically disabled after receiving error on
trigger creation: ' + err;
-                            utils.disableTrigger(triggerIdentifier, undefined, message);
+                            disableTrigger(triggerIdentifier, undefined, message);
                             logger.error(method, 'Disabled trigger', triggerIdentifier, err);
                         });
                     }
@@ -395,12 +396,12 @@ module.exports = function(logger, triggerDB, redisClient) {
         catch (err) {
             logger.error(method, err);
         }
-    };
+    }
 
     this.authorize = function(req, res, next) {
         var method = 'authorize';
 
-        if (utils.endpointAuth) {
+        if (self.endpointAuth) {
             if (!req.headers.authorization) {
                 res.set('www-authenticate', 'Basic realm="Private"');
                 res.status(HttpStatus.UNAUTHORIZED);
@@ -409,24 +410,24 @@ module.exports = function(logger, triggerDB, redisClient) {
 
             var parts = req.headers.authorization.split(' ');
             if (parts[0].toLowerCase() !== 'basic' || !parts[1]) {
-                return utils.sendError(method, HttpStatus.BAD_REQUEST, 'Malformed request,
basic authentication expected', res);
+                return sendError(method, HttpStatus.BAD_REQUEST, 'Malformed request, basic
authentication expected', res);
             }
 
             var auth = new Buffer(parts[1], 'base64').toString();
             auth = auth.match(/^([^:]*):(.*)$/);
             if (!auth) {
-                return utils.sendError(method, HttpStatus.BAD_REQUEST, 'Malformed request,
authentication invalid', res);
+                return sendError(method, HttpStatus.BAD_REQUEST, 'Malformed request, authentication
invalid', res);
             }
 
             var uuid = auth[1];
             var key = auth[2];
-            var endpointAuth = utils.endpointAuth.split(':');
+            var endpointAuth = self.endpointAuth.split(':');
             if (endpointAuth[0] === uuid && endpointAuth[1] === key) {
                 next();
             }
             else {
                 logger.warn(method, 'Invalid key');
-                return utils.sendError(method, HttpStatus.UNAUTHORIZED, 'Invalid key', res);
+                return sendError(method, HttpStatus.UNAUTHORIZED, 'Invalid key', res);
             }
         }
         else {
@@ -434,10 +435,10 @@ module.exports = function(logger, triggerDB, redisClient) {
         }
     };
 
-    this.sendError = function(method, code, message, res) {
+    function sendError(method, code, message, res) {
         logger.error(method, message);
         res.status(code).json({error: message});
-    };
+    }
 
     this.initRedis = function() {
         var method = 'initRedis';
@@ -449,10 +450,8 @@ module.exports = function(logger, triggerDB, redisClient) {
 
                 //create a subscriber client that listens for requests to perform swap
                 subscriber.on('message', function (channel, message) {
-                    if (message === 'host0' || message === 'host1') {
-                        logger.info(method, message, 'set to active host in channel', channel);
-                        utils.activeHost = message;
-                    }
+                    logger.info(method, message, 'set to active host in channel', channel);
+                    self.activeHost = message;
                 });
 
                 subscriber.on('error', function (err) {
@@ -460,19 +459,19 @@ module.exports = function(logger, triggerDB, redisClient) {
                     reject(err);
                 });
 
-                subscriber.subscribe(utils.redisHash);
+                subscriber.subscribe(self.redisKey);
 
-                redisClient.hgetAsync(utils.redisHash, utils.redisKey)
+                redisClient.hgetAsync(self.redisKey, self.redisField)
                 .then(activeHost => {
-                    return utils.initActiveHost(activeHost);
+                    return initActiveHost(activeHost);
                 })
                 .then(() => {
                     process.on('SIGTERM', function onSigterm() {
-                        if (utils.activeHost === utils.host) {
-                            var redundantHost = utils.host === 'host0' ? 'host1' : 'host0';
-                            utils.redisClient.hsetAsync(utils.redisHash, utils.redisKey,
redundantHost)
+                        if (self.activeHost === self.host) {
+                            var redundantHost = self.host === 'host0' ? 'host1' : 'host0';
+                            self.redisClient.hsetAsync(self.redisKey, self.redisField, redundantHost)
                             .then(() => {
-                                utils.redisClient.publish(utils.redisHash, redundantHost);
+                                self.redisClient.publish(self.redisKey, redundantHost);
                             })
                             .catch(err => {
                                 logger.error(method, err);
@@ -491,18 +490,18 @@ module.exports = function(logger, triggerDB, redisClient) {
         });
     };
 
-    this.initActiveHost = function(activeHost) {
+    function initActiveHost(activeHost) {
         var method = 'initActiveHost';
 
         if (activeHost === null) {
             //initialize redis key with active host
-            logger.info(method, 'redis hset', utils.redisHash, utils.redisKey, utils.activeHost);
-            return redisClient.hsetAsync(utils.redisHash, utils.redisKey, utils.activeHost);
+            logger.info(method, 'redis hset', self.redisKey, self.redisField, self.activeHost);
+            return redisClient.hsetAsync(self.redisKey, self.redisField, self.activeHost);
         }
         else {
-            utils.activeHost = activeHost;
+            self.activeHost = activeHost;
             return Promise.resolve();
         }
-    };
+    }
 
 };

-- 
To stop receiving notification emails like this one, please contact
csantanapr@apache.org.

Mime
View raw message