diff --git a/server/app/model/classes/instance/instance.js b/server/app/model/classes/instance/instance.js index f536505f7..ba60f6be7 100755 --- a/server/app/model/classes/instance/instance.js +++ b/server/app/model/classes/instance/instance.js @@ -318,8 +318,8 @@ var InstanceSchema = new Schema({ }, subnetId: { type: String, - required: false, - trim: true + required: false, + trim: true }, vpcId: { type: String, @@ -342,7 +342,7 @@ var InstanceSchema = new Schema({ required: false, default: false }, - tagServer:{ + tagServer: { type: String, required: false, trim: true @@ -490,7 +490,13 @@ var InstancesDao = function() { err.status = 500; return callback(err); } else { - databaseCall.queryObj['$or'] = [{ "instanceState": "running" }, { "instanceState": "stopped" }, { "instanceState": "pending" }]; + databaseCall.queryObj['$or'] = [{ + "instanceState": "running" + }, { + "instanceState": "stopped" + }, { + "instanceState": "pending" + }]; Instances.paginate(databaseCall.queryObj, databaseCall.options, function(err, instances) { if (err) { logger.error(err); @@ -722,7 +728,7 @@ var InstancesDao = function() { }); }; - this.checkInstancesDependencyByFieldName = function(fieldName,id, callback) { + this.checkInstancesDependencyByFieldName = function(fieldName, id, callback) { logger.debug("Enter checkInstancesDependencyByFieldName (%s,)", id); var queryObj = { $or: [{ @@ -732,7 +738,7 @@ var InstancesDao = function() { }, { serviceIds: id }], - isDeleted:false + isDeleted: false } Instances.find(queryObj, function(err, data) { if (err) { @@ -1538,7 +1544,7 @@ var InstancesDao = function() { }; - this.insertDockerActionLog = function(instanceId, user,action,actionId, timestampStarted, callback) { + this.insertDockerActionLog = function(instanceId, user, action, actionId, timestampStarted, callback) { logger.debug("Enter insertDockerActionLog ", instanceId, user, timestampStarted); var log = { type: actionId, @@ -1708,8 +1714,8 @@ var InstancesDao = function() { return log; }; - this.insertInstanceStatusActionLog = function(instanceId,user,instanceState, timestampStarted, callback) { - logger.debug("Enter insertInstanceStatusActionLog ", instanceId,user,instanceState, timestampStarted); + this.insertInstanceStatusActionLog = function(instanceId, user, instanceState, timestampStarted, callback) { + logger.debug("Enter insertInstanceStatusActionLog ", instanceId, user, instanceState, timestampStarted); var log = { completed: true, success: true, @@ -1719,21 +1725,21 @@ var InstancesDao = function() { 'instance-State': instanceState } }; - if(instanceState === 'terminated'){ + if (instanceState === 'terminated') { log.type = ACTION_LOG_TYPES.TERMINATED.type; log.name = ACTION_LOG_TYPES.TERMINATED.name - }else if(instanceState === 'deleted'){ + } else if (instanceState === 'deleted') { log.type = ACTION_LOG_TYPES.DELETE.type; log.name = ACTION_LOG_TYPES.DELETE.name - }else if(instanceState === 'stopped'){ + } else if (instanceState === 'stopped') { log.type = ACTION_LOG_TYPES.STOP.type; log.name = ACTION_LOG_TYPES.STOP.name - }else if(instanceState === 'shutting-down'){ + } else if (instanceState === 'shutting-down') { log.type = ACTION_LOG_TYPES.SHUTDOWN.type; log.name = ACTION_LOG_TYPES.SHUTDOWN.name - }else{ + } else { log.type = ACTION_LOG_TYPES.START.type; - log.name = ACTION_LOG_TYPES.START.name + log.name = ACTION_LOG_TYPES.START.name } var logId = insertActionLog(instanceId, log, callback); log._id = logId; @@ -2128,16 +2134,16 @@ var InstancesDao = function() { this.updateInstanceStatus = function(instanceId, instance, callback) { var updateObj = {}; - if(instance.status && instance.status === 'shutting-down'){ + if (instance.status && instance.status === 'shutting-down') { updateObj['instanceState'] = instance.status; updateObj['isDeleted'] = true; - }else if(instance.state === 'terminated' || instance.state === 'shutting-down'){ + } else if (instance.state === 'terminated' || instance.state === 'shutting-down') { updateObj['instanceState'] = instance.state; updateObj['isDeleted'] = true; - }else{ + } else { updateObj['instanceState'] = instance.state; updateObj['isDeleted'] = false; - updateObj['subnetId']= instance.subnetId; + updateObj['subnetId'] = instance.subnetId; updateObj['instanceIP'] = instance.ip; updateObj['vpcId'] = instance.vpcId; updateObj['hostName'] = instance.hostName; @@ -2179,7 +2185,10 @@ var InstancesDao = function() { }; this.getAllTerminatedInstances = function(orgId, callback) { - Instances.find({ "orgId": orgId, "instanceState": "terminated" }, function(err, data) { + Instances.find({ + "orgId": orgId, + "instanceState": "terminated" + }, function(err, data) { if (err) { return callback(err, null); } else { @@ -2188,12 +2197,12 @@ var InstancesDao = function() { }); }; - this.updatedRoute53HostedZoneParam = function(instanceId,route53HostedZoneParams,callback){ + this.updatedRoute53HostedZoneParam = function(instanceId, route53HostedZoneParams, callback) { Instances.update({ "_id": ObjectId(instanceId) }, { $set: { - route53HostedParams:route53HostedZoneParams + route53HostedParams: route53HostedZoneParams } }, function(err, data) { if (err) { @@ -2204,6 +2213,18 @@ var InstancesDao = function() { callback(null, data); }); }; + + this.getInstancesByTagServer = function(tagServer, callback) { + Instances.find({ + "tagServer": tagServer + }, function(err, data) { + if (err) { + return callback(err, null); + } else { + callback(null, data); + } + }); + }; }; -module.exports = new InstancesDao(); +module.exports = new InstancesDao(); \ No newline at end of file diff --git a/server/app/model/classes/tasks/taskTypeChef.js b/server/app/model/classes/tasks/taskTypeChef.js index 834fbd34a..e48aae65c 100755 --- a/server/app/model/classes/tasks/taskTypeChef.js +++ b/server/app/model/classes/tasks/taskTypeChef.js @@ -57,7 +57,7 @@ chefTaskSchema.methods.getNodes = function() { }; // Instance Method :- run task -chefTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, blueprintIds, envId, paramOptions, onExecute, onComplete) { +chefTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, blueprintIds, envId, onExecute, onComplete) { logger.debug("chef appData: ", JSON.stringify(appData)); var self = this; @@ -192,14 +192,18 @@ chefTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, appDat //merging attributes Objects var attributeObj = {}; var objectArray = []; - for (var i = 0; i < self.attributes.length; i++) { - objectArray.push(self.attributes[i].jsonObj); + var attr = self.attributes; + if (self.botParams && self.botParams.cookbookAttributes) { + attr = self.botParams.cookbookAttributes; + } + for (var i = 0; i < attr.length; i++) { + objectArray.push(attr[i].jsonObj); } var instanceIds = this.nodeIds; - function getInstances(role, instanceIds, callback) { + function getInstances(role, instanceIds, tagServer, callback) { if (role) { configmgmtDao.getChefServerDetailsByOrgname(self.orgId, function(err, chefDetails) { if (err) { @@ -265,6 +269,19 @@ chefTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, appDat }); }); + } else if (tagServer) { + logger.debug('in tagServer',tagServer); + instancesDao.getInstancesByTagServer(tagServer, function(err, instances) { + if (err) { + logger.error(err); + if (typeof onExecute === 'function') { + onExecute(err, null); + } + return; + } + callback(null, instances); + }); + } else { if (!(instanceIds && instanceIds.length)) { @@ -289,7 +306,8 @@ chefTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, appDat } logger.debug('role ==>', self.role); - getInstances(self.role, instanceIds, function(err, instances) { + getInstances(self.role, instanceIds, self.botTagServer, function(err, instances) { + logger.debug("instance length ==>",instances.length); if (err) { logger.error(err); if (typeof onExecute === 'function') { @@ -1282,4 +1300,4 @@ chefTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, appDat var ChefTask = mongoose.model('chefTask', chefTaskSchema); -module.exports = ChefTask; +module.exports = ChefTask; \ No newline at end of file diff --git a/server/app/model/classes/tasks/taskTypeJenkins.js b/server/app/model/classes/tasks/taskTypeJenkins.js index 879cff47a..d1561248f 100755 --- a/server/app/model/classes/tasks/taskTypeJenkins.js +++ b/server/app/model/classes/tasks/taskTypeJenkins.js @@ -46,7 +46,7 @@ var jenkinsTaskSchema = taskTypeSchema.extend({ }); // Instance Method :- run task -jenkinsTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, nexusData, blueprintIds, envId, paramOptions, onExecute, onComplete) { +jenkinsTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, nexusData, blueprintIds, envId, onExecute, onComplete) { logger.debug("Choice Param in::: ", choiceParam); var self = this; // For now removed blueprint launch via jenkins, later will use this diff --git a/server/app/model/classes/tasks/taskTypeScript.js b/server/app/model/classes/tasks/taskTypeScript.js index 8cc9ab7c6..8158dbc07 100644 --- a/server/app/model/classes/tasks/taskTypeScript.js +++ b/server/app/model/classes/tasks/taskTypeScript.js @@ -34,11 +34,11 @@ var Cryptography = require('_pr/lib/utils/cryptography'); var scriptTaskSchema = taskTypeSchema.extend({ nodeIds: [String], scriptTypeName: String, - isSudo:{ - type:Boolean, - required:false, - default:false - }, + isSudo: { + type: Boolean, + required: false, + default: false + }, scriptDetails: [{ scriptId: { type: String, @@ -52,172 +52,211 @@ scriptTaskSchema.methods.getNodes = function() { return this.nodeIds; }; -scriptTaskSchema.methods.execute = function (userName, baseUrl, choiceParam, nexusData, blueprintIds, envId, paramOptions, onExecute, onComplete) { - var self = this; - var instanceIds = this.nodeIds; - var sudoFlag = this.isSudo; - var scriptDetails = this.scriptDetails; - var instanceResultList = []; - if (!(instanceIds && instanceIds.length)) { - if (typeof onExecute === 'function') { - onExecute({ - message: "Empty Instance List" - }, null); - } - return; - } - instancesDao.getInstances(instanceIds, function (err, instances) { - if (err) { - logger.error(err); - return; - } - for (var i = 0; i < instances.length; i++) { - (function (instance) { - var timestampStarted = new Date().getTime(); - var actionLog = instancesDao.insertOrchestrationActionLog(instance._id, null, userName, timestampStarted); - instance.tempActionLogId = actionLog._id; - var logsReferenceIds = [instance._id, actionLog._id]; - var instanceLog = { - actionId: actionLog._id, - instanceId: instance._id, - orgName: instance.orgName, - bgName: instance.bgName, - projectName: instance.projectName, - envName: instance.environmentName, - status: instance.instanceState, - actionStatus: "pending", - platformId: instance.platformId, - blueprintName: instance.blueprintData.blueprintName, - data: instance.runlist, - platform: instance.hardware.platform, - os: instance.hardware.os, - size: instance.instanceType, - user: userName, - createdOn: new Date().getTime(), - startedOn: new Date().getTime(), - providerType: instance.providerType, - action: "Script-Execution", - logs: [] - }; - if (!instance.instanceIP) { - var timestampEnded = new Date().getTime(); - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: true, - log: "Instance IP is not defined. Chef Client run failed", - timestamp: timestampEnded - }); - instancesDao.updateActionLog(instance._id, actionLog._id, false, timestampEnded); - instanceLog.endedOn = new Date().getTime(); - instanceLog.actionStatus = "failed"; - instanceLog.logs = { - err: true, - log: "Instance IP is not defined. Chef Client run failed", - timestamp: new Date().getTime() - }; - instanceLogModel.createOrUpdate(actionLog._id, instance._id, instanceLog, function(err, logData) { - if (err) { - logger.error("Failed to create or update instanceLog: ", err); - } - }); +scriptTaskSchema.methods.execute = function(userName, baseUrl, choiceParam, nexusData, blueprintIds, envId, onExecute, onComplete) { + var self = this; + var instanceIds = this.nodeIds; + var sudoFlag = this.isSudo; + var scriptDetails = this.scriptDetails; + var instanceResultList = []; - instanceOnCompleteHandler({ message: "Instance IP is not defined. Chef Client run failed" }, 1, instance._id, null, actionLog._id); - return; - } - credentialCryptography.decryptCredential(instance.credentials, function (err, decryptedCredentials) { - var sshOptions = { - username: decryptedCredentials.username, - host: instance.instanceIP, - port: 22 - } - if (decryptedCredentials.pemFileLocation) { - sshOptions.privateKey = decryptedCredentials.pemFileLocation; - } else { - sshOptions.password = decryptedCredentials.password; - } - for (var j = 0; j < scriptDetails.length; j++) { - (function (script) { - scriptService.getScriptById(script.scriptId, function (err, scripts) { - if (err) { - logger.error(err); - return; - } else if (!scripts.file) { - logger.debug("There is no script belong to instance : " + instance.instanceIP); - return; - } else { - if (scripts.type === 'Bash') { - executeBashScript(scripts, sshOptions, logsReferenceIds, script.scriptParameters,instanceLog); - } else { - return; - } - } - }) - })(scriptDetails[j]); - } - }); - })(instances[i]); - } - if (typeof onExecute === 'function') { - onExecute(null, { - instances: instances, - }); - } - }) - function instanceOnCompleteHandler(err, status, instanceId, executionId, actionId) { - var overallStatus = 0; - var result = { - instanceId: instanceId, - status: 'success' - } - if (actionId) { - result.actionId = actionId; - } - if (executionId) { - result.executionId = executionId; - } - if (err) { - result.status = 'failed'; - overallStatus = 1; - } else { - if (status === 0) { - result.status = 'success'; - } else { - result.status = 'failed'; - overallStatus = 1; - } - } - instanceResultList.push(result); - if (instanceResultList.length === scriptDetails.length) { - logger.debug('Type of onComplete: ' + typeof onComplete); - if (typeof onComplete === 'function') { - onComplete(null, overallStatus, { - instances: instanceResultList - }); - } - } - } - function executeBashScript(script, sshOptions, logsReferenceIds, scriptParameters,instanceLog) { - var fileName = uuid.v4() + '_'+script.fileName - var desPath = appConfig.scriptDir + fileName; - var sshExec = new SSHExec(sshOptions); - var cryptoConfig = appConfig.cryptoSettings; - var cryptography = new Cryptography(cryptoConfig.algorithm, cryptoConfig.password); - fileIo.writeFile(desPath, script.file, false, function (err) { - if (err) { - logger.error("Unable to write file"); - return; - } else { - var scp = new SCP(sshOptions); - scp.upload(desPath, '/tmp', function(err) { - if (err) { - var timestampEnded = new Date().getTime(); - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: true, - log: "Unable to upload script file " + script.name, - timestamp: timestampEnded - }); - instancesDao.updateActionLog(logsReferenceIds[0], logsReferenceIds[1], false, timestampEnded); + function getInstances(instanceIds, tagServer, callback) { + if (tagServer) { + logger.debug('in tagServer', tagServer); + instancesDao.getInstancesByTagServer(tagServer, function(err, instances) { + if (err) { + logger.error(err); + if (typeof onExecute === 'function') { + onExecute(err, null); + } + return; + } + callback(null, instances); + }); + + } else { + + if (!(instanceIds && instanceIds.length)) { + if (typeof onExecute === 'function') { + onExecute({ + message: "Empty Node List" + }, null); + } + return; + } + instancesDao.getInstances(instanceIds, function(err, instances) { + if (err) { + logger.error(err); + if (typeof onExecute === 'function') { + onExecute(err, null); + } + return; + } + callback(null, instances); + }); + } + } + + + getInstances(instanceIds, self.botTagServer, function(err, instances) { + if (err) { + logger.error(err); + return; + } + for (var i = 0; i < instances.length; i++) { + (function(instance) { + var timestampStarted = new Date().getTime(); + var actionLog = instancesDao.insertOrchestrationActionLog(instance._id, null, userName, timestampStarted); + instance.tempActionLogId = actionLog._id; + var logsReferenceIds = [instance._id, actionLog._id]; + var instanceLog = { + actionId: actionLog._id, + instanceId: instance._id, + orgName: instance.orgName, + bgName: instance.bgName, + projectName: instance.projectName, + envName: instance.environmentName, + status: instance.instanceState, + actionStatus: "pending", + platformId: instance.platformId, + blueprintName: instance.blueprintData.blueprintName, + data: instance.runlist, + platform: instance.hardware.platform, + os: instance.hardware.os, + size: instance.instanceType, + user: userName, + createdOn: new Date().getTime(), + startedOn: new Date().getTime(), + providerType: instance.providerType, + action: "Script-Execution", + logs: [] + }; + if (!instance.instanceIP) { + var timestampEnded = new Date().getTime(); + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: true, + log: "Instance IP is not defined. Chef Client run failed", + timestamp: timestampEnded + }); + instancesDao.updateActionLog(instance._id, actionLog._id, false, timestampEnded); + instanceLog.endedOn = new Date().getTime(); + instanceLog.actionStatus = "failed"; + instanceLog.logs = { + err: true, + log: "Instance IP is not defined. Chef Client run failed", + timestamp: new Date().getTime() + }; + instanceLogModel.createOrUpdate(actionLog._id, instance._id, instanceLog, function(err, logData) { + if (err) { + logger.error("Failed to create or update instanceLog: ", err); + } + }); + + instanceOnCompleteHandler({ + message: "Instance IP is not defined. Chef Client run failed" + }, 1, instance._id, null, actionLog._id); + return; + } + credentialCryptography.decryptCredential(instance.credentials, function(err, decryptedCredentials) { + var sshOptions = { + username: decryptedCredentials.username, + host: instance.instanceIP, + port: 22 + } + if (decryptedCredentials.pemFileLocation) { + sshOptions.privateKey = decryptedCredentials.pemFileLocation; + } else { + sshOptions.password = decryptedCredentials.password; + } + for (var j = 0; j < scriptDetails.length; j++) { + (function(script) { + scriptService.getScriptById(script.scriptId, function(err, scripts) { + if (err) { + logger.error(err); + return; + } else if (!scripts.file) { + logger.debug("There is no script belong to instance : " + instance.instanceIP); + return; + } else { + if (scripts.type === 'Bash') { + var params = script.scriptParameters; + if (self.botParams && self.botParams.scriptParams) { + params = self.botParams.scriptParams; + } + executeBashScript(scripts, sshOptions, logsReferenceIds, params, instanceLog); + } else { + return; + } + } + }) + })(scriptDetails[j]); + } + }); + })(instances[i]); + } + if (typeof onExecute === 'function') { + onExecute(null, { + instances: instances, + }); + } + }) + + function instanceOnCompleteHandler(err, status, instanceId, executionId, actionId) { + var overallStatus = 0; + var result = { + instanceId: instanceId, + status: 'success' + } + if (actionId) { + result.actionId = actionId; + } + if (executionId) { + result.executionId = executionId; + } + if (err) { + result.status = 'failed'; + overallStatus = 1; + } else { + if (status === 0) { + result.status = 'success'; + } else { + result.status = 'failed'; + overallStatus = 1; + } + } + instanceResultList.push(result); + if (instanceResultList.length === scriptDetails.length) { + logger.debug('Type of onComplete: ' + typeof onComplete); + if (typeof onComplete === 'function') { + onComplete(null, overallStatus, { + instances: instanceResultList + }); + } + } + } + + function executeBashScript(script, sshOptions, logsReferenceIds, scriptParameters, instanceLog) { + var fileName = uuid.v4() + '_' + script.fileName + var desPath = appConfig.scriptDir + fileName; + var sshExec = new SSHExec(sshOptions); + var cryptoConfig = appConfig.cryptoSettings; + var cryptography = new Cryptography(cryptoConfig.algorithm, cryptoConfig.password); + fileIo.writeFile(desPath, script.file, false, function(err) { + if (err) { + logger.error("Unable to write file"); + return; + } else { + var scp = new SCP(sshOptions); + scp.upload(desPath, '/tmp', function(err) { + if (err) { + var timestampEnded = new Date().getTime(); + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: true, + log: "Unable to upload script file " + script.name, + timestamp: timestampEnded + }); + instancesDao.updateActionLog(logsReferenceIds[0], logsReferenceIds[1], false, timestampEnded); instanceLog.endedOn = new Date().getTime(); instanceLog.actionStatus = "failed"; instanceLog.logs = { @@ -230,30 +269,30 @@ scriptTaskSchema.methods.execute = function (userName, baseUrl, choiceParam, nex logger.error("Failed to create or update instanceLog: ", err); } }); - instanceOnCompleteHandler(err, 1, logsReferenceIds[0], null, logsReferenceIds[1]); - return; - } - if(sudoFlag === true){ - var cmdLine = 'sudo bash /tmp/' + fileName; - }else{ - var cmdLine = 'bash /tmp/' + fileName; - } - if (scriptParameters.length > 0) { - for (var j = 0; j < scriptParameters.length; j++) { - var decryptedText = cryptography.decryptText(scriptParameters[j], cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding); - cmdLine = cmdLine + ' "' + decryptedText + '"'; - } - } - sshExec.exec(cmdLine, function (err, retCode) { - if (err) { - var timestampEnded = new Date().getTime(); - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: true, - log: 'Unable to run script ' + script.name, - timestamp: timestampEnded - }); - instancesDao.updateActionLog(logsReferenceIds[0], logsReferenceIds[1], false, timestampEnded); + instanceOnCompleteHandler(err, 1, logsReferenceIds[0], null, logsReferenceIds[1]); + return; + } + if (sudoFlag === true) { + var cmdLine = 'sudo bash /tmp/' + fileName; + } else { + var cmdLine = 'bash /tmp/' + fileName; + } + if (scriptParameters.length > 0) { + for (var j = 0; j < scriptParameters.length; j++) { + var decryptedText = cryptography.decryptText(scriptParameters[j], cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding); + cmdLine = cmdLine + ' "' + decryptedText + '"'; + } + } + sshExec.exec(cmdLine, function(err, retCode) { + if (err) { + var timestampEnded = new Date().getTime(); + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: true, + log: 'Unable to run script ' + script.name, + timestamp: timestampEnded + }); + instancesDao.updateActionLog(logsReferenceIds[0], logsReferenceIds[1], false, timestampEnded); instanceLog.endedOn = new Date().getTime(); instanceLog.actionStatus = "failed"; instanceLog.logs = { @@ -266,19 +305,19 @@ scriptTaskSchema.methods.execute = function (userName, baseUrl, choiceParam, nex logger.error("Failed to create or update instanceLog: ", err); } }); - instanceOnCompleteHandler(err, 1, logsReferenceIds[0], null, logsReferenceIds[1]); - removeScriptFile(desPath); - return; - } - if (retCode == 0) { - var timestampEnded = new Date().getTime(); - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: false, - log: 'Task execution success for script ' + script.name, - timestamp: timestampEnded - }); - instancesDao.updateActionLog(logsReferenceIds[0], logsReferenceIds[1], true, timestampEnded); + instanceOnCompleteHandler(err, 1, logsReferenceIds[0], null, logsReferenceIds[1]); + removeScriptFile(desPath); + return; + } + if (retCode == 0) { + var timestampEnded = new Date().getTime(); + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: false, + log: 'Task execution success for script ' + script.name, + timestamp: timestampEnded + }); + instancesDao.updateActionLog(logsReferenceIds[0], logsReferenceIds[1], true, timestampEnded); instanceLog.endedOn = new Date().getTime(); instanceLog.actionStatus = "success"; instanceLog.logs = { @@ -291,18 +330,18 @@ scriptTaskSchema.methods.execute = function (userName, baseUrl, choiceParam, nex logger.error("Failed to create or update instanceLog: ", err); } }); - instanceOnCompleteHandler(null, 0, logsReferenceIds[0], null, logsReferenceIds[1]); - removeScriptFile(desPath); - return; - } else { - instanceOnCompleteHandler(null, retCode, logsReferenceIds[0], null, logsReferenceIds[1]); - if (retCode === -5000) { - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: true, - log: 'Host Unreachable', - timestamp: new Date().getTime() - }); + instanceOnCompleteHandler(null, 0, logsReferenceIds[0], null, logsReferenceIds[1]); + removeScriptFile(desPath); + return; + } else { + instanceOnCompleteHandler(null, retCode, logsReferenceIds[0], null, logsReferenceIds[1]); + if (retCode === -5000) { + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: true, + log: 'Host Unreachable', + timestamp: new Date().getTime() + }); instanceLog.endedOn = new Date().getTime(); instanceLog.actionStatus = "failed"; instanceLog.logs = { @@ -315,15 +354,15 @@ scriptTaskSchema.methods.execute = function (userName, baseUrl, choiceParam, nex logger.error("Failed to create or update instanceLog: ", err); } }); - removeScriptFile(desPath); - return; - } else if (retCode === -5001) { - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: true, - log: 'Invalid credentials', - timestamp: new Date().getTime() - }); + removeScriptFile(desPath); + return; + } else if (retCode === -5001) { + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: true, + log: 'Invalid credentials', + timestamp: new Date().getTime() + }); instanceLog.endedOn = new Date().getTime(); instanceLog.actionStatus = "failed"; instanceLog.logs = { @@ -336,15 +375,15 @@ scriptTaskSchema.methods.execute = function (userName, baseUrl, choiceParam, nex logger.error("Failed to create or update instanceLog: ", err); } }); - removeScriptFile(desPath); - return; - } else { - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: true, - log: 'Unknown error occured. ret code = ' + retCode, - timestamp: new Date().getTime() - }); + removeScriptFile(desPath); + return; + } else { + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: true, + log: 'Unknown error occured. ret code = ' + retCode, + timestamp: new Date().getTime() + }); instanceLog.endedOn = new Date().getTime(); instanceLog.actionStatus = "failed"; instanceLog.logs = { @@ -357,17 +396,17 @@ scriptTaskSchema.methods.execute = function (userName, baseUrl, choiceParam, nex logger.error("Failed to create or update instanceLog: ", err); } }); - removeScriptFile(desPath); - return; - } - var timestampEnded = new Date().getTime(); - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: true, - log: 'Error in running script ' + script.name, - timestamp: timestampEnded - }); - instancesDao.updateActionLog(logsReferenceIds[0], logsReferenceIds[1], false, timestampEnded); + removeScriptFile(desPath); + return; + } + var timestampEnded = new Date().getTime(); + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: true, + log: 'Error in running script ' + script.name, + timestamp: timestampEnded + }); + instancesDao.updateActionLog(logsReferenceIds[0], logsReferenceIds[1], false, timestampEnded); instanceLog.endedOn = new Date().getTime(); instanceLog.actionStatus = "failed"; instanceLog.logs = { @@ -380,48 +419,48 @@ scriptTaskSchema.methods.execute = function (userName, baseUrl, choiceParam, nex logger.error("Failed to create or update instanceLog: ", err); } }); - removeScriptFile(desPath); - return; - } - }, function (stdOut) { - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: false, - log: stdOut.toString('ascii'), - timestamp: new Date().getTime() - }); + removeScriptFile(desPath); + return; + } + }, function(stdOut) { + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: false, + log: stdOut.toString('ascii'), + timestamp: new Date().getTime() + }); instanceLog.logs = { err: false, log: stdOut.toString('ascii'), timestamp: new Date().getTime() }; - instanceLogModel.createOrUpdate(logsReferenceIds[1], logsReferenceIds[0], instanceLog, function(err, logData) { + instanceLogModel.createOrUpdate(logsReferenceIds[1], logsReferenceIds[0], instanceLog, function(err, logData) { if (err) { logger.error("Failed to create or update instanceLog: ", err); } }); - }, function (stdErr) { - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: true, - log: stdErr.toString('ascii'), - timestamp: new Date().getTime() - }); + }, function(stdErr) { + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: true, + log: stdErr.toString('ascii'), + timestamp: new Date().getTime() + }); instanceLog.logs = { err: false, log: stdErr.toString('ascii'), timestamp: new Date().getTime() }; - instanceLogModel.createOrUpdate(logsReferenceIds[1], logsReferenceIds[0], instanceLog, function(err, logData) { + instanceLogModel.createOrUpdate(logsReferenceIds[1], logsReferenceIds[0], instanceLog, function(err, logData) { if (err) { logger.error("Failed to create or update instanceLog: ", err); } }); - }); - }) - }; - }); - }; + }); + }) + }; + }); + }; }; function removeScriptFile(filePath) { @@ -437,4 +476,4 @@ function removeScriptFile(filePath) { } var ScriptTask = mongoose.model('scriptTask', scriptTaskSchema); -module.exports = ScriptTask; +module.exports = ScriptTask; \ No newline at end of file diff --git a/server/app/model/classes/tasks/tasks.js b/server/app/model/classes/tasks/tasks.js index 8fa6112cc..2010ba457 100755 --- a/server/app/model/classes/tasks/tasks.js +++ b/server/app/model/classes/tasks/tasks.js @@ -138,7 +138,7 @@ taskSchema.plugin(mongoosePaginate); // Executes a task -taskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, blueprintIds, envId, paramOptions, callback, onComplete) { +taskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, blueprintIds, envId, callback, onComplete) { logger.debug('Executing'); var task; var self = this; @@ -159,7 +159,7 @@ taskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, b taskHistoryData.nodeIds = this.taskConfig.nodeIds; taskHistoryData.runlist = this.taskConfig.runlist; //taskHistoryData.attributes = this.taskConfig.attributes; - taskHistoryData.attributes = (!paramOptions) ? this.taskConfig.attributes : paramOptions; + taskHistoryData.attributes = (!self.botParams.cookbookAttributes) ? this.taskConfig.attributes : self.botParams.cookbookAttributes; } else if (this.taskType === TASK_TYPE.JENKINS_TASK) { task = new JenkinsTask(this.taskConfig); taskHistoryData.jenkinsServerId = this.taskConfig.jenkinsServerId; @@ -183,8 +183,9 @@ taskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, b } else if (this.taskType === TASK_TYPE.SCRIPT_TASK) { task = new ScriptTask(this.taskConfig); taskHistoryData.nodeIds = this.taskConfig.nodeIds; - //taskHistoryData.scriptDetails = this.taskConfig.scriptDetails; - taskHistoryData.scriptDetails = (!paramOptions) ? this.taskConfig.scriptDetails : paramOptions; + var scriptDetails = JSON.parse(JSON.stringify(this.taskConfig.scriptDetails)); + scriptDetails.scriptParameters = (!self.botParams.scriptParams) ? scriptDetails.scriptParameters : self.botParams.scriptParams; + taskHistoryData.scriptDetails = scriptDetails; } else { callback({ message: "Invalid Task Type" @@ -195,7 +196,9 @@ taskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, b var taskHistory = null; task.orgId = this.orgId; task.envId = this.envId; - task.execute(userName, baseUrl, choiceParam, appData, blueprintIds, envId, paramOptions, function(err, taskExecuteData, taskHistoryEntry) { + task.botParams = self.botParams; + task.botTagServer = self.botTagServer; + task.execute(userName, baseUrl, choiceParam, appData, blueprintIds, envId, function(err, taskExecuteData, taskHistoryEntry) { if (err) { callback(err, null); return; diff --git a/server/app/routes/v1.0/routes_tasks.js b/server/app/routes/v1.0/routes_tasks.js index da960ad3f..2ea675b8d 100755 --- a/server/app/routes/v1.0/routes_tasks.js +++ b/server/app/routes/v1.0/routes_tasks.js @@ -40,7 +40,7 @@ module.exports.setRoutes = function(app, sessionVerification) { app.get('/tasks/serviceDelivery', function(req, res) { var serviceDeliveryCheck = false; - if(req.query.serviceDeliveryCheck && + if (req.query.serviceDeliveryCheck && (req.query.serviceDeliveryCheck === 'true' || req.query.serviceDeliveryCheck === true)) { serviceDeliveryCheck = true; } @@ -53,7 +53,7 @@ module.exports.setRoutes = function(app, sessionVerification) { return; } res.status(200).send(tasks); - }); + }); }); app.delete('/tasks/serviceDelivery/:taskId', function(req, res) { @@ -70,7 +70,7 @@ module.exports.setRoutes = function(app, sessionVerification) { }); app.get('/tasks/history/list/all', function(req, res) { - logger.debug("------------------ ",JSON.stringify(TaskHistory)); + logger.debug("------------------ ", JSON.stringify(TaskHistory)); TaskHistory.listHistory(function(err, tHistories) { if (err) { res.status(500).send(errorResponses.db.error); @@ -132,6 +132,15 @@ module.exports.setRoutes = function(app, sessionVerification) { var hostProtocol = req.protocol + '://' + req.get('host'); var choiceParam = req.body.choiceParam; var appData = req.body.appData; + var scriptParams = req.body.scriptParams; + var cookbookAttributes = req.body.cookbookAttributes; + var botTagServer = req.body.tagServer; + + + logger.debug('reqbody ======>', JSON.stringify(req.body)); + + + /*Tasks.getTaskById(req.params.taskId, function(err, task) { if (err) { @@ -158,13 +167,28 @@ module.exports.setRoutes = function(app, sessionVerification) { }); */ - var attributes = req.body.attributes; - var scriptDetails = req.body.scriptDetails; var paramOptions = { - attributes : attributes, - scriptDetails : scriptDetails + cookbookAttributesP: cookbookAttributes, + scriptParams: scriptParams }; - taskService.executeTask(taskId, user, hostProtocol, choiceParam, appData, paramOptions, function(err, historyData) { + + // encrypting script bot params if any + if (paramOptions.scriptParams && paramOptions.scriptParams.length) { + var cryptoConfig = appConfig.cryptoSettings; + var cryptography = new Cryptography(cryptoConfig.algorithm, cryptoConfig.password); + var encryptedParams = []; + for (var i = 0; i < paramOptions.scriptParams.length; i++) { + var encryptedText = cryptography.encryptText(paramOptions.scriptParams[i], cryptoConfig.encryptionEncoding, + cryptoConfig.decryptionEncoding); + encryptedParams.push(encryptedText); + } + paramOptions.scriptParams = encryptedParams; + } + + + + + taskService.executeTask(taskId, user, hostProtocol, choiceParam, appData, paramOptions, botTagServer, function(err, historyData) { if (err === 404) { res.status(404).send("Task not found."); return; @@ -205,9 +229,9 @@ module.exports.setRoutes = function(app, sessionVerification) { return; } if (deleteCount) { - TaskHistory.removeByTaskId(req.params.taskId,function(err,removed){ - if(err){ - logger.error("Failed to remove history: ",err); + TaskHistory.removeByTaskId(req.params.taskId, function(err, removed) { + if (err) { + logger.error("Failed to remove history: ", err); } }); res.send({ @@ -526,21 +550,21 @@ module.exports.setRoutes = function(app, sessionVerification) { app.post('/tasks/:taskId/update', function(req, res) { var taskData = req.body.taskData; - if(taskData.taskType === 'script'){ + if (taskData.taskType === 'script') { Tasks.getTaskById(req.params.taskId, function(err, scriptTask) { if (err) { logger.error(err); res.status(500).send(errorResponses.db.error); return; } - encryptedParam(taskData.scriptDetails,scriptTask.taskConfig.scriptDetails, function (err, encryptedParam) { + encryptedParam(taskData.scriptDetails, scriptTask.taskConfig.scriptDetails, function(err, encryptedParam) { if (err) { logger.error(err); res.status(500).send("Failed to encrypted script parameters: ", err); return; } else { taskData.scriptDetails = encryptedParam; - Tasks.updateTaskById(req.params.taskId, taskData, function (err, updateCount) { + Tasks.updateTaskById(req.params.taskId, taskData, function(err, updateCount) { if (err) { logger.error(err); res.status(500).send(errorResponses.db.error); @@ -557,8 +581,8 @@ module.exports.setRoutes = function(app, sessionVerification) { } }) }); - }else { - Tasks.updateTaskById(req.params.taskId, taskData, function (err, updateCount) { + } else { + Tasks.updateTaskById(req.params.taskId, taskData, function(err, updateCount) { if (err) { logger.error(err); res.status(500).send(errorResponses.db.error); @@ -616,41 +640,39 @@ module.exports.setRoutes = function(app, sessionVerification) { }; -function encryptedParam(paramDetails,existingParams,callback){ +function encryptedParam(paramDetails, existingParams, callback) { var cryptoConfig = appConfig.cryptoSettings; var cryptography = new Cryptography(cryptoConfig.algorithm, cryptoConfig.password); var count = 0; var encryptedList = []; - for(var i = 0; i < paramDetails.length; i++){ - (function(param){ - if(param.scriptParameters.length > 0){ + for (var i = 0; i < paramDetails.length; i++) { + (function(param) { + if (param.scriptParameters.length > 0) { count++; - for(var j = 0; j < param.scriptParameters.length; j++){ - (function(scriptParameter){ - if(scriptParameter === ''){ + for (var j = 0; j < param.scriptParameters.length; j++) { + (function(scriptParameter) { + if (scriptParameter === '') { encryptedList.push(existingParams[i].scriptParameters[j]); - }else if(scriptParameter === existingParams[i].scriptParameters[j]){ + } else if (scriptParameter === existingParams[i].scriptParameters[j]) { encryptedList.push(scriptParameter); - }else { + } else { var encryptedText = cryptography.encryptText(scriptParameter, cryptoConfig.encryptionEncoding, cryptoConfig.decryptionEncoding); encryptedList.push(encryptedText); } - if(encryptedList.length === param.scriptParameters.length){ + if (encryptedList.length === param.scriptParameters.length) { param.scriptParameters = encryptedList; encryptedList = []; } })(param.scriptParameters[j]); } - }else{ + } else { count++; } - if(count === paramDetails.length){ - callback(null,paramDetails); + if (count === paramDetails.length) { + callback(null, paramDetails); return; } })(paramDetails[i]); } -} - - +} \ No newline at end of file diff --git a/server/app/services/taskService.js b/server/app/services/taskService.js index 324967e3b..118278f33 100644 --- a/server/app/services/taskService.js +++ b/server/app/services/taskService.js @@ -78,7 +78,7 @@ taskService.getChefTasksByOrgBgProjectAndEnvId = function getChefTasksByOrgBgPro }); }; -taskService.executeTask = function executeTask(taskId, user, hostProtocol, choiceParam, appData, paramOptions, callback) { +taskService.executeTask = function executeTask(taskId, user, hostProtocol, choiceParam, appData, paramOptions, botTagServer, callback) { if (appData) { appData['taskId'] = taskId; } @@ -89,9 +89,9 @@ taskService.executeTask = function executeTask(taskId, user, hostProtocol, choic return callback(error, null); } if (task) { - if(task.taskType.CHEF_TASK){ + if (task.taskType.CHEF_TASK) { paramOptions = paramOptions.attributes; - }else if(task.taskType.SCRIPT_TASK) { + } else if (task.taskType.SCRIPT_TASK) { paramOptions = paramOptions.scriptDetails; } @@ -99,7 +99,10 @@ taskService.executeTask = function executeTask(taskId, user, hostProtocol, choic if (task.blueprintIds && task.blueprintIds.length) { blueprintIds = task.blueprintIds; } - task.execute(user, hostProtocol, choiceParam, appData, blueprintIds, task.envId, paramOptions, function(err, taskRes, historyData) { + console.log(paramOptions); + task.botParams = paramOptions; + task.botTagServer = botTagServer; + task.execute(user, hostProtocol, choiceParam, appData, blueprintIds, task.envId, function(err, taskRes, historyData) { if (err) { var error = new Error('Failed to execute task.'); error.status = 500; @@ -172,7 +175,7 @@ taskService.getTaskActionList = function getTaskActionList(jsonData, callback) { "status": histories.docs[i].status, "instanceId": histories.docs[i].nodeIdsWithActionLog[p1].nodeId }; - var instanceName =""; + var instanceName = ""; if (instance && instance.length) { obj['instanceName'] = instance[0].name; } @@ -240,4 +243,4 @@ taskService.getTaskActionList = function getTaskActionList(jsonData, callback) { return callback(null, histories); } }); -}; +}; \ No newline at end of file