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: make action's node.js runtime version configurable (#158)
Date Mon, 20 Aug 2018 19:03:58 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 c7f50a7  make action's node.js runtime version configurable (#158)
c7f50a7 is described below

commit c7f50a7635162cda83a6a4a6cb5c24e99240d027
Author: Jason Peterson <jasonpet@us.ibm.com>
AuthorDate: Mon Aug 20 15:03:56 2018 -0400

    make action's node.js runtime version configurable (#158)
---
 Dockerfile                  |  4 +-
 action/alarmWebAction.js    | 37 +++++++++---------
 action/lib/common.js        | 73 ++++++++++++++++++++---------------
 action/lib/config.js        | 13 +++++++
 installCatalog.sh           |  9 +++--
 package.json                |  4 +-
 provider/lib/authHandler.js | 13 +++++++
 provider/lib/health.js      | 18 +++------
 provider/lib/sanitizer.js   | 58 +++++++++++-----------------
 provider/lib/utils.js       | 94 ++++++++++++++++++++++++---------------------
 10 files changed, 173 insertions(+), 150 deletions(-)

diff --git a/Dockerfile b/Dockerfile
index 87d6a86..f823a5f 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -14,8 +14,8 @@ RUN apt-get update --fix-missing && \
   apt-get install -y nodejs
 
 # only package.json
-ADD package.json /alarmsTrigger/
-RUN cd /alarmsTrigger; npm install
+ADD package.json /
+RUN cd / && npm install --production
 
 # App
 ADD provider/. /alarmsTrigger/
diff --git a/action/alarmWebAction.js b/action/alarmWebAction.js
index 0963ce4..8383578 100644
--- a/action/alarmWebAction.js
+++ b/action/alarmWebAction.js
@@ -1,21 +1,25 @@
-var CronJob = require('cron').CronJob;
-var moment = require('moment');
-
+const CronJob = require('cron').CronJob;
+const moment = require('moment');
 const common = require('./lib/common');
 const Database = require('./lib/Database');
 
 function main(params) {
 
-    if (!params.authKey) {
-        return common.sendError(400, 'no authKey parameter was provided');
-    }
     if (!params.triggerName) {
         return common.sendError(400, 'no trigger name parameter was provided');
     }
 
     var triggerParts = common.parseQName(params.triggerName);
-    var triggerID = `${params.authKey}/${triggerParts.namespace}/${triggerParts.name}`;
-    var triggerURL = `https://${params.apihost}/api/v1/namespaces/${triggerParts.namespace}/triggers/${triggerParts.name}`;
+    var triggerData = {
+        apikey: params.authKey,
+        name: triggerParts.name,
+        namespace: triggerParts.namespace,
+        additionalData: common.constructObject(params.additionalData),
+    };
+    var triggerID = `${triggerData.namespace}/${triggerData.name}`;
+    if (triggerData.apikey) {
+        triggerID = `${triggerData.apikey}/${triggerID}`;
+    }
 
     var workers = params.workers instanceof Array ? params.workers : [];
     var deleteAfterFireArray = ['false', 'true', 'rules'];
@@ -28,9 +32,6 @@ function main(params) {
         }
 
         var newTrigger = {
-            apikey: params.authKey,
-            name: triggerParts.name,
-            namespace: triggerParts.namespace,
             payload: params.trigger_payload || {},
             maxTriggers: params.maxTriggers || -1,
             status: {
@@ -38,6 +39,7 @@ function main(params) {
                 'dateChanged': Date.now()
             }
         };
+        Object.assign(newTrigger, triggerData);
 
         if (params.fireOnce) {
             if (!params.date) {
@@ -127,7 +129,7 @@ function main(params) {
         }
 
         return new Promise(function (resolve, reject) {
-            common.verifyTriggerAuth(triggerURL, params.authKey, false)
+            common.verifyTriggerAuth(triggerData, false)
             .then(() => {
                 db = new Database(params.DB_URL, params.DB_NAME);
                 return db.getWorkerID(workers);
@@ -152,7 +154,7 @@ function main(params) {
     }
     else if (params.__ow_method === "get") {
         return new Promise(function (resolve, reject) {
-            common.verifyTriggerAuth(triggerURL, params.authKey, false)
+            common.verifyTriggerAuth(triggerData, false)
             .then(() => {
                 db = new Database(params.DB_URL, params.DB_NAME);
                 return db.getTrigger(triggerID);
@@ -201,7 +203,7 @@ function main(params) {
         return new Promise(function (resolve, reject) {
             var updatedParams = {};
 
-            common.verifyTriggerAuth(triggerURL, params.authKey, false)
+            common.verifyTriggerAuth(triggerData, false)
             .then(() => {
                 db = new Database(params.DB_URL, params.DB_NAME);
                 return db.getTrigger(triggerID);
@@ -212,7 +214,7 @@ function main(params) {
                 }
 
                 if (params.trigger_payload) {
-                    updatedParams.payload = common.constructPayload(params.trigger_payload);
+                    updatedParams.payload = common.constructObject(params.trigger_payload,
true);
                 }
 
                 if (trigger.date) {
@@ -311,7 +313,7 @@ function main(params) {
     else if (params.__ow_method === "delete") {
 
         return new Promise(function (resolve, reject) {
-            common.verifyTriggerAuth(triggerURL, params.authKey, true)
+            common.verifyTriggerAuth(triggerData, true)
             .then(() => {
                 db = new Database(params.DB_URL, params.DB_NAME);
                 return db.getTrigger(triggerID);
@@ -361,10 +363,7 @@ function validateDate(date, paramName, startDate) {
 function hasSecondsGranularity(cron) {
 
     var fields = (cron + '').trim().split(/\s+/);
-
     return fields.length > 5 && fields[fields.length - 6] !== '0';
 }
 
 exports.main = main;
-
-
diff --git a/action/lib/common.js b/action/lib/common.js
index b2c613e..9480fb5 100644
--- a/action/lib/common.js
+++ b/action/lib/common.js
@@ -1,4 +1,6 @@
 const request = require('request');
+const openwhisk = require('openwhisk');
+const config = require('./config');
 
 function requestHelper(url, input, method) {
 
@@ -45,33 +47,33 @@ function createWebParams(rawParams) {
     delete webparams.apihost;
 
     webparams.triggerName = triggerName;
+    config.addAdditionalData(webparams);
 
     return webparams;
 }
 
-function verifyTriggerAuth(triggerURL, authKey, isDelete) {
-    var auth = authKey.split(':');
+function verifyTriggerAuth(triggerData, isDelete) {
+    var owConfig = config.getOpenWhiskConfig(triggerData);
+    var ow = openwhisk(owConfig);
 
     return new Promise(function(resolve, reject) {
-
-        request({
-            method: 'get',
-            url: triggerURL,
-            auth: {
-                user: auth[0],
-                pass: auth[1]
-            },
-            rejectUnauthorized: false
-        }, function(err, response) {
-            if (err) {
-                reject(sendError(400, 'Trigger authentication request failed.', err.message));
-            }
-            else if(response.statusCode >= 400 && !(isDelete && response.statusCode
=== 404)) {
-                reject(sendError(response.statusCode, 'Trigger authentication request failed.'));
-            }
-            else {
-                resolve();
-            }
+        ow.triggers.get(triggerData.name)
+        .then(() => {
+            resolve();
+        })
+        .catch(err => {
+           if (err.statusCode) {
+               var statusCode = err.statusCode;
+               if (!(isDelete && statusCode === 404)) {
+                   reject(sendError(statusCode, 'Trigger authentication request failed.'));
+               }
+               else {
+                   resolve();
+               }
+           }
+           else {
+               reject(sendError(400, 'Trigger authentication request failed.', err.message));
+           }
         });
     });
 }
@@ -104,18 +106,27 @@ function sendError(statusCode, error, message) {
     };
 }
 
-function constructPayload(payload) {
-
-    var updatedPayload;
-    if (payload) {
-        if (typeof payload === 'string') {
-            updatedPayload = {payload: payload};
+function constructObject(data, isPayload) {
+    var jsonObject;
+    if (data) {
+        if (typeof data === 'string') {
+            if (isPayload) {
+                jsonObject = {payload: data};
+            }
+            else {
+                try {
+                    jsonObject = JSON.parse(data);
+                }
+                catch (e) {
+                    console.log('error parsing ' + data);
+                }
+            }
         }
-        if (typeof payload === 'object') {
-            updatedPayload = payload;
+        if (typeof data === 'object') {
+            jsonObject = data;
         }
     }
-    return updatedPayload;
+    return jsonObject;
 }
 
 
@@ -125,5 +136,5 @@ module.exports = {
     'verifyTriggerAuth': verifyTriggerAuth,
     'parseQName': parseQName,
     'sendError': sendError,
-    'constructPayload': constructPayload
+    'constructObject': constructObject
 };
diff --git a/action/lib/config.js b/action/lib/config.js
new file mode 100644
index 0000000..550f42a
--- /dev/null
+++ b/action/lib/config.js
@@ -0,0 +1,13 @@
+function getOpenWhiskConfig(triggerData) {
+    return {ignore_certs: true, namespace: triggerData.namespace, api_key: triggerData.apikey};
+}
+
+function addAdditionalData(params) {
+    //insert code here to store additional trigger data in the database
+    //for example, params.additionalData = {dateCreated: Date.now()};
+}
+
+module.exports = {
+    'addAdditionalData': addAdditionalData,
+    'getOpenWhiskConfig': getOpenWhiskConfig
+};
diff --git a/installCatalog.sh b/installCatalog.sh
index 9261716..ca6c150 100755
--- a/installCatalog.sh
+++ b/installCatalog.sh
@@ -23,6 +23,7 @@ DB_NAME="${4}alarmservice"
 APIHOST="$5"
 WORKERS="$6"
 LIMIT_CRON_FIELDS="${LIMIT_CRON_FIELDS}"
+ACTION_RUNTIME_VERSION=${ACTION_RUNTIME_VERSION:="nodejs:6"}
 
 # If the auth key file exists, read the key in the file. Otherwise, take the
 # first argument as the key itself.
@@ -64,18 +65,18 @@ fi
 cp -f alarmFeed_package.json package.json
 zip -r alarmFeed.zip lib package.json alarm.js
 
-$WSK_CLI -i --apihost "$EDGEHOST" action update --kind nodejs:6 --auth "$AUTH" alarms/alarm
"$PACKAGE_HOME/action/alarmFeed.zip" \
+$WSK_CLI -i --apihost "$EDGEHOST" action update --kind "$ACTION_RUNTIME_VERSION" --auth "$AUTH"
alarms/alarm "$PACKAGE_HOME/action/alarmFeed.zip" \
      -a description 'Fire trigger when alarm occurs' \
      -a parameters '[ {"name":"cron", "required":true}, {"name":"startDate", "required":false},
{"name":"stopDate", "required":false} ]' \
      -a feed true
 
-$WSK_CLI -i --apihost "$EDGEHOST" action update --kind nodejs:6 --auth "$AUTH" alarms/once
"$PACKAGE_HOME/action/alarmFeed.zip" \
+$WSK_CLI -i --apihost "$EDGEHOST" action update --kind "$ACTION_RUNTIME_VERSION" --auth "$AUTH"
alarms/once "$PACKAGE_HOME/action/alarmFeed.zip" \
      -a description 'Fire trigger once when alarm occurs' \
      -a parameters '[ {"name":"date", "required":true}, {"name":"deleteAfterFire", "required":false}
]' \
      -a feed true \
      -p fireOnce true
 
-$WSK_CLI -i --apihost "$EDGEHOST" action update --kind nodejs:6 --auth "$AUTH" alarms/interval
"$PACKAGE_HOME/action/alarmFeed.zip" \
+$WSK_CLI -i --apihost "$EDGEHOST" action update --kind "$ACTION_RUNTIME_VERSION" --auth "$AUTH"
alarms/interval "$PACKAGE_HOME/action/alarmFeed.zip" \
      -a description 'Fire trigger at specified interval' \
      -a parameters '[ {"name":"minutes", "required":true}, {"name":"startDate", "required":false},
{"name":"stopDate", "required":false} ]' \
      -a feed true \
@@ -106,7 +107,7 @@ fi
 
 zip -r alarmWebAction.zip lib package.json alarmWebAction.js node_modules
 
-$WSK_CLI -i --apihost "$EDGEHOST" action update --kind nodejs:6 --auth "$AUTH" alarmsWeb/alarmWebAction
"$PACKAGE_HOME/action/alarmWebAction.zip" \
+$WSK_CLI -i --apihost "$EDGEHOST" action update --kind "$ACTION_RUNTIME_VERSION" --auth "$AUTH"
alarmsWeb/alarmWebAction "$PACKAGE_HOME/action/alarmWebAction.zip" \
     -a description 'Create/Delete a trigger in alarms provider Database' \
     --web true
 
diff --git a/package.json b/package.json
index 7b89d74..e922b06 100755
--- a/package.json
+++ b/package.json
@@ -16,9 +16,9 @@
     "json-stringify-safe": "^5.0.1",
     "http-status-codes": "^1.0.5",
     "request-promise": "^1.0.2",
-    "redis":"^2.7.1",
+    "redis": "^2.7.1",
     "bluebird": "^3.5.0",
     "systeminformation": "^3.19.0",
     "long-timeout": "^0.1.1"
   }
-}
\ No newline at end of file
+}
diff --git a/provider/lib/authHandler.js b/provider/lib/authHandler.js
new file mode 100644
index 0000000..9e25242
--- /dev/null
+++ b/provider/lib/authHandler.js
@@ -0,0 +1,13 @@
+function handleAuth(triggerData) {
+
+    var auth = triggerData.apikey.split(':');
+    return Promise.resolve({
+        user: auth[0],
+        pass: auth[1]
+    });
+
+}
+
+module.exports = {
+    'handleAuth': handleAuth
+};
diff --git a/provider/lib/health.js b/provider/lib/health.js
index 98246a6..e0210ca 100644
--- a/provider/lib/health.js
+++ b/provider/lib/health.js
@@ -1,6 +1,5 @@
 var si = require('systeminformation');
 var v8 = require('v8');
-var request = require('request');
 var _ = require('lodash');
 
 module.exports = function(logger, utils) {
@@ -46,8 +45,6 @@ module.exports = function(logger, utils) {
     this.monitor = function(apikey) {
         var method = 'monitor';
 
-        var auth = apikey.split(':');
-
         if (triggerName) {
             monitorStatus = Object.assign({}, utils.monitorStatus);
             utils.monitorStatus = {};
@@ -64,11 +61,12 @@ module.exports = function(logger, utils) {
             utils.sanitizer.deleteTriggerFromDB(existingID, 0);
 
             //delete the trigger
-            var dataTrigger = {
+            var triggerData = {
+                apikey: apikey,
                 uri: utils.uriHost + '/api/v1/namespaces/_/triggers/' + triggerName,
                 triggerID: existingID
             };
-            utils.sanitizer.deleteTrigger(dataTrigger, auth, 0)
+            utils.sanitizer.deleteTrigger(triggerData, 0)
             .then((info) => {
                 logger.info(method, existingID, info);
             })
@@ -90,7 +88,7 @@ module.exports = function(logger, utils) {
 
         var triggerURL = utils.uriHost + '/api/v1/namespaces/_/triggers/' + triggerName;
         var triggerID = `${apikey}/_/${triggerName}`;
-        createTrigger(triggerURL, auth)
+        createTrigger(triggerURL, apikey)
         .then((info) => {
             logger.info(method, triggerID, info);
             var newTrigger = createAlarmTrigger(triggerID, apikey, alarmType);
@@ -132,17 +130,13 @@ module.exports = function(logger, utils) {
         return newTrigger;
     }
 
-    function createTrigger(triggerURL, auth) {
+    function createTrigger(triggerURL, apikey) {
         var method = 'createTrigger';
 
         return new Promise(function(resolve, reject) {
-            request({
+            utils.authRequest({apikey: apikey}, {
                 method: 'put',
                 uri: triggerURL,
-                auth: {
-                    user: auth[0],
-                    pass: auth[1]
-                },
                 json: true,
                 body: {}
             }, function (error, response) {
diff --git a/provider/lib/sanitizer.js b/provider/lib/sanitizer.js
index 31f8f79..982cfab 100644
--- a/provider/lib/sanitizer.js
+++ b/provider/lib/sanitizer.js
@@ -1,6 +1,6 @@
-var request = require('request');
 
-module.exports = function(logger, triggerDB, uriHost) {
+
+module.exports = function(logger, utils) {
 
     var self = this;
 
@@ -8,9 +8,9 @@ module.exports = function(logger, triggerDB, uriHost) {
         var method = 'deleteTriggerFromDB';
 
         //delete from database
-        triggerDB.get(triggerID, function (err, existing) {
+        utils.db.get(triggerID, function (err, existing) {
             if (!err) {
-                triggerDB.destroy(existing._id, existing._rev, function (err) {
+                utils.db.destroy(existing._id, existing._rev, function (err) {
                     if (err) {
                         if (err.statusCode === 409 && retryCount < 5) {
                             setTimeout(function () {
@@ -32,19 +32,13 @@ module.exports = function(logger, triggerDB, uriHost) {
         });
     };
 
-    this.deleteTriggerAndRules = function(dataTrigger) {
+    this.deleteTriggerAndRules = function(triggerData) {
         var method = 'deleteTriggerAndRules';
 
-        var triggerIdentifier = dataTrigger.triggerID;
-        var auth = dataTrigger.apikey.split(':');
-
-        request({
+        var triggerIdentifier = triggerData.triggerID;
+        utils.authRequest(triggerData, {
             method: 'get',
-            uri: dataTrigger.uri,
-            auth: {
-                user: auth[0],
-                pass: auth[1]
-            },
+            uri: triggerData.uri
         }, function(error, response, body) {
             logger.info(method, triggerIdentifier, 'http get request, STATUS:', response
? response.statusCode : undefined);
 
@@ -53,7 +47,7 @@ module.exports = function(logger, triggerDB, uriHost) {
             }
             else {
                 //delete the trigger
-                self.deleteTrigger(dataTrigger, auth, 0)
+                self.deleteTrigger(triggerData, 0)
                 .then((info) => {
                     logger.info(method, triggerIdentifier, info);
                     if (body) {
@@ -61,8 +55,8 @@ module.exports = function(logger, triggerDB, uriHost) {
                             var jsonBody = JSON.parse(body);
                             for (var rule in jsonBody.rules) {
                                 var qualifiedName = rule.split('/');
-                                var uri = uriHost + '/api/v1/namespaces/' + qualifiedName[0]
+ '/rules/' + qualifiedName[1];
-                                self.deleteRule(rule, uri, auth, 0);
+                                var uri = utils.uriHost + '/api/v1/namespaces/' + qualifiedName[0]
+ '/rules/' + qualifiedName[1];
+                                self.deleteRule(triggerData, rule, uri, 0);
                             }
                         }
                         catch (err) {
@@ -77,26 +71,22 @@ module.exports = function(logger, triggerDB, uriHost) {
         });
     };
 
-    this.deleteTrigger = function(dataTrigger, auth, retryCount) {
+    this.deleteTrigger = function(triggerData, retryCount) {
         var method = 'deleteTrigger';
 
         return new Promise(function(resolve, reject) {
 
-            var triggerIdentifier = dataTrigger.triggerID;
-            request({
+            var triggerIdentifier = triggerData.triggerID;
+            utils.authRequest(triggerData, {
                 method: 'delete',
-                uri: dataTrigger.uri,
-                auth: {
-                    user: auth[0],
-                    pass: auth[1]
-                },
+                uri: triggerData.uri
             }, function (error, response) {
                 logger.info(method, triggerIdentifier, 'http delete request, STATUS:', response
? response.statusCode : undefined);
                 if (error || response.statusCode >= 400) {
                     if (!error && response.statusCode === 409 && retryCount
< 5) {
                         logger.info(method, 'attempting to delete trigger again', triggerIdentifier,
'Retry Count:', (retryCount + 1));
                         setTimeout(function () {
-                            self.deleteTrigger(dataTrigger, auth, (retryCount + 1))
+                            self.deleteTrigger(triggerData, (retryCount + 1))
                             .then(info => {
                                 resolve(info);
                             })
@@ -115,23 +105,19 @@ module.exports = function(logger, triggerDB, uriHost) {
         });
     };
 
-    this.deleteRule = function(rule, uri, auth, retryCount) {
+    this.deleteRule = function(triggerData, rule, uri, retryCount) {
         var method = 'deleteRule';
 
-        request({
+        utils.authRequest(triggerData, {
             method: 'delete',
-            uri: uri,
-            auth: {
-                user: auth[0],
-                pass: auth[1]
-            },
+            uri: uri
         }, function(error, response) {
             logger.info(method, rule, 'http delete rule request, STATUS:', response ? response.statusCode
: undefined);
             if (error || response.statusCode >= 400) {
                 if (!error && response.statusCode === 409 && retryCount <
5) {
                     logger.info(method, 'attempting to delete rule again', rule, 'Retry Count:',
(retryCount + 1));
                     setTimeout(function () {
-                        self.deleteRule(rule, uri, auth, (retryCount + 1));
+                        self.deleteRule(triggerData, rule, uri, (retryCount + 1));
                     }, 1000);
                 } else {
                     logger.error(method, rule, 'rule delete request failed');
@@ -147,7 +133,7 @@ module.exports = function(logger, triggerDB, uriHost) {
         var method = 'deleteTriggerFeed';
 
         return new Promise(function(resolve, reject) {
-            triggerDB.get(triggerID, function (err, existing) {
+            utils.db.get(triggerID, function (err, existing) {
                 if (!err) {
                     var updatedTrigger = existing;
                     var status = {
@@ -157,7 +143,7 @@ module.exports = function(logger, triggerDB, uriHost) {
                     };
                     updatedTrigger.status = status;
 
-                    triggerDB.insert(updatedTrigger, triggerID, function (err) {
+                    utils.db.insert(updatedTrigger, triggerID, function (err) {
                         if (err) {
                             reject(err);
                         }
diff --git a/provider/lib/utils.js b/provider/lib/utils.js
index 9aa7d95..e443d49 100644
--- a/provider/lib/utils.js
+++ b/provider/lib/utils.js
@@ -6,6 +6,7 @@ var DateAlarm = require('./dateAlarm.js');
 var CronAlarm = require('./cronAlarm.js');
 var IntervalAlarm = require('./intervalAlarm.js');
 var Sanitizer = require('./sanitizer');
+var authHandler = require('./authHandler');
 
 module.exports = function(logger, triggerDB, redisClient) {
 
@@ -29,7 +30,7 @@ module.exports = function(logger, triggerDB, redisClient) {
     this.redisKey = redisKeyPrefix + '_' + this.worker;
     this.redisField = constants.REDIS_FIELD;
     this.uriHost ='https://' + this.routerHost;
-    this.sanitizer = new Sanitizer(logger, triggerDB, this.uriHost);
+    this.sanitizer = new Sanitizer(logger, this);
     this.monitorStatus = {};
 
     function createTrigger(triggerIdentifier, newTrigger) {
@@ -63,45 +64,40 @@ module.exports = function(logger, triggerDB, redisClient) {
         return alarm.scheduleAlarm(triggerIdentifier, callback);
     }
 
-    function fireTrigger(dataTrigger) {
+    function fireTrigger(triggerData) {
         var method = 'fireTrigger';
 
-        var triggerIdentifier = dataTrigger.triggerID;
-        var auth = dataTrigger.apikey.split(':');
+        var triggerIdentifier = triggerData.triggerID;
 
         logger.info(method, 'Alarm fired for', triggerIdentifier, 'attempting to fire trigger');
-        postTrigger(dataTrigger, auth, 0)
+        postTrigger(triggerData, 0)
         .then(triggerId => {
             logger.info(method, 'Trigger', triggerId, 'was successfully fired');
-            handleFiredTrigger(dataTrigger);
+            handleFiredTrigger(triggerData);
         })
         .catch(err => {
             logger.error(method, err);
-            handleFiredTrigger(dataTrigger);
+            handleFiredTrigger(triggerData);
         });
     }
 
-    function postTrigger(dataTrigger, auth, retryCount, throttleCount) {
+    function postTrigger(triggerData, retryCount, throttleCount) {
         var method = 'postTrigger';
 
         return new Promise(function(resolve, reject) {
 
             // only manage trigger fires if they are not infinite
-            if (dataTrigger.maxTriggers && dataTrigger.maxTriggers !== -1) {
-                dataTrigger.triggersLeft--;
+            if (triggerData.maxTriggers && triggerData.maxTriggers !== -1) {
+                triggerData.triggersLeft--;
             }
 
-            request({
+            self.authRequest(triggerData, {
                 method: 'post',
-                uri: dataTrigger.uri,
-                auth: {
-                    user: auth[0],
-                    pass: auth[1]
-                },
-                json: dataTrigger.payload
+                uri: triggerData.uri,
+                json: triggerData.payload
             }, function(error, response) {
                 try {
-                    var triggerIdentifier = dataTrigger.triggerID;
+                    var triggerIdentifier = triggerData.triggerID;
                     logger.info(method, triggerIdentifier, 'http post request, STATUS:',
response ? response.statusCode : undefined);
 
                     if (error || response.statusCode >= 400) {
@@ -109,8 +105,8 @@ module.exports = function(logger, triggerDB, redisClient) {
                         var throttleCounter = throttleCount || 0;
 
                         // only manage trigger fires if they are not infinite
-                        if (dataTrigger.maxTriggers && dataTrigger.maxTriggers !==
-1) {
-                            dataTrigger.triggersLeft++;
+                        if (triggerData.maxTriggers && triggerData.maxTriggers !==
-1) {
+                            triggerData.triggersLeft++;
                         }
 
                         if (!error && shouldDisableTrigger(response.statusCode))
{
@@ -124,7 +120,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 () {
-                                    postTrigger(dataTrigger, auth, (retryCount + 1), throttleCounter)
+                                    postTrigger(triggerData, (retryCount + 1), throttleCounter)
                                     .then(triggerId => {
                                         resolve(triggerId);
                                     })
@@ -172,27 +168,27 @@ module.exports = function(logger, triggerDB, redisClient) {
         return monitor && self.monitorStatus.triggerName === triggerName;
     }
 
-    function handleFiredTrigger(dataTrigger) {
+    function handleFiredTrigger(triggerData) {
         var method = 'handleFiredTrigger';
 
-        if (isMonitoringTrigger(dataTrigger.monitor, dataTrigger.name)) {
+        if (isMonitoringTrigger(triggerData.monitor, triggerData.name)) {
             self.monitorStatus.triggerFired = "success";
         }
 
-        var triggerIdentifier = dataTrigger.triggerID;
-        if (dataTrigger.date) {
-            if (dataTrigger.deleteAfterFire && dataTrigger.deleteAfterFire !== 'false')
{
+        var triggerIdentifier = triggerData.triggerID;
+        if (triggerData.date) {
+            if (triggerData.deleteAfterFire && triggerData.deleteAfterFire !== 'false')
{
 
                 //delete trigger feed from database
                 self.sanitizer.deleteTriggerFeed(triggerIdentifier);
 
                 //check if trigger and all associated rules should be deleted
-                if (dataTrigger.deleteAfterFire === 'rules') {
-                    self.sanitizer.deleteTriggerAndRules(dataTrigger);
+                if (triggerData.deleteAfterFire === 'rules') {
+                    self.sanitizer.deleteTriggerAndRules(triggerData);
                 }
                 else {
-                    var auth = dataTrigger.apikey.split(':');
-                    self.sanitizer.deleteTrigger(dataTrigger, auth, 0)
+                    var auth = triggerData.apikey.split(':');
+                    self.sanitizer.deleteTrigger(triggerData, 0)
                     .then(info => {
                         logger.info(method, triggerIdentifier, info);
                     })
@@ -206,18 +202,18 @@ module.exports = function(logger, triggerDB, redisClient) {
                 logger.info(method, 'the fire once date has expired, disabled', triggerIdentifier);
             }
         }
-        else if (dataTrigger.stopDate) {
+        else if (triggerData.stopDate) {
             //check if the next scheduled trigger is after the stop date
-            if (dataTrigger.cronHandle && dataTrigger.cronHandle.nextDate().isAfter(new
Date(dataTrigger.stopDate))) {
+            if (triggerData.cronHandle && triggerData.cronHandle.nextDate().isAfter(new
Date(triggerData.stopDate))) {
                 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())) {
+            else if (triggerData.minutes && (Date.now() + (triggerData.minutes *
1000 * 60) > new Date(triggerData.stopDate).getTime())) {
                 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) {
+        else if (triggerData.maxTriggers && triggerData.triggersLeft === 0) {
             disableTrigger(triggerIdentifier, undefined, 'Automatically disabled after reaching
max triggers');
             logger.warn(method, 'no more triggers left, disabled', triggerIdentifier);
         }
@@ -287,18 +283,13 @@ module.exports = function(logger, triggerDB, redisClient) {
                         //check if trigger still exists in whisk db
                         var namespace = doc.namespace;
                         var name = doc.name;
-                        var apikey = doc.apikey;
                         var uri = self.uriHost + '/api/v1/namespaces/' + namespace + '/triggers/'
+ name;
-                        var auth = apikey.split(':');
 
                         logger.info(method, 'Checking if trigger', triggerIdentifier, 'still
exists');
-                        request({
+                        var cachedTrigger = self.triggers[triggerIdentifier] = {apikey: doc.apikey,
additionalData: doc.additionalData};
+                        self.authRequest(cachedTrigger, {
                             method: 'get',
-                            url: uri,
-                            auth: {
-                                user: auth[0],
-                                pass: auth[1]
-                            }
+                            url: uri
                         }, function (error, response) {
                             //disable trigger in database if trigger is dead
                             if (!error && shouldDisableTrigger(response.statusCode))
{
@@ -308,8 +299,8 @@ module.exports = function(logger, triggerDB, redisClient) {
                             }
                             else {
                                 createTrigger(triggerIdentifier, doc)
-                                .then(cachedTrigger => {
-                                    self.triggers[triggerIdentifier] = cachedTrigger;
+                                .then(newTrigger => {
+                                    Object.assign(cachedTrigger, newTrigger);
                                     logger.info(method, triggerIdentifier, 'created successfully');
                                     if (cachedTrigger.intervalHandle && shouldFireTrigger(cachedTrigger))
{
                                         try {
@@ -364,6 +355,7 @@ module.exports = function(logger, triggerDB, redisClient) {
                     if ((!doc.status || doc.status.active === true) && (!doc.monitor
|| doc.monitor === self.host)) {
                         createTrigger(triggerIdentifier, doc)
                         .then(cachedTrigger => {
+                            cachedTrigger.additionalData = doc.additionalData;
                             self.triggers[triggerIdentifier] = cachedTrigger;
                             logger.info(method, triggerIdentifier, 'created successfully');
 
@@ -505,4 +497,18 @@ module.exports = function(logger, triggerDB, redisClient) {
         }
     }
 
+    this.authRequest = function(triggerData, options, cb) {
+        var method = 'authRequest';
+
+        authHandler.handleAuth(triggerData)
+        .then(auth => {
+            options.auth = auth;
+            request(options, cb);
+        })
+        .catch(err => {
+            logger.error(method, err);
+            request(options, cb);
+        });
+    };
+
 };


Mime
View raw message