diff --git a/client/cat3/main.html b/client/cat3/main.html index 17920467e..d7cfa2ac0 100644 --- a/client/cat3/main.html +++ b/client/cat3/main.html @@ -117,7 +117,6 @@ - diff --git a/client/cat3/src/clientRoutes.js b/client/cat3/src/clientRoutes.js index 538102361..778ee4db0 100644 --- a/client/cat3/src/clientRoutes.js +++ b/client/cat3/src/clientRoutes.js @@ -36,6 +36,7 @@ function routeConfig($stateProvider, $urlRouterProvider, $httpProvider, modulePe url: "/workzone", templateUrl: "src/partials/sections/dashboard/workzone/workzone.html", controller: "workzoneCtrl", + params:{filterView:{workzone:true}}, onEnter: function () { }, onExit: function () { @@ -57,6 +58,7 @@ function routeConfig($stateProvider, $urlRouterProvider, $httpProvider, modulePe url: "/design", templateUrl: "src/partials/sections/dashboard/design/design.html", controller: "designCtrl as desCtrl", + params:{filterView:{design:true}}, resolve: { auth: ["$q", function ($q) { var deferred = $q.defer(); @@ -74,6 +76,7 @@ function routeConfig($stateProvider, $urlRouterProvider, $httpProvider, modulePe url: "/CM/", templateUrl: "src/partials/sections/dashboard/analytics/analytics.html", controller: "analyticsCtrl as analytic", + params:{filterView:{analytics:true}}, resolve: { auth: ["$q", function ($q) { var deferred = $q.defer(); @@ -92,6 +95,7 @@ function routeConfig($stateProvider, $urlRouterProvider, $httpProvider, modulePe url: "/bots", templateUrl: "src/partials/sections/dashboard/bots/bots.html", controller: "botsCtrl as bts", + params:{filterView:{bots:true}}, resolve: { auth: ["$q", function ($q) { var deferred = $q.defer(); diff --git a/client/cat3/src/factory/workzoneServices.js b/client/cat3/src/factory/workzoneServices.js index 7a7622f18..72401f442 100644 --- a/client/cat3/src/factory/workzoneServices.js +++ b/client/cat3/src/factory/workzoneServices.js @@ -532,7 +532,7 @@ return $http.get(fullUrl(url),Auth.getHeaderObject()); }, getBotTypeList:function () { - var url ='/config-data/bot-type'; + var url ='/config-data/bots-type'; return $http.get(fullUrl(url),Auth.getHeaderObject()); }, getTaggingServer:function () { diff --git a/client/cat3/src/main.js b/client/cat3/src/main.js index ae79ed6fd..55ec51ab8 100644 --- a/client/cat3/src/main.js +++ b/client/cat3/src/main.js @@ -101,6 +101,9 @@ angularApp.controller('HeadNavigatorCtrl', ['$scope', '$rootScope', '$http', '$l $rootScope.analyticsBool = _permSet.analyticsBool; $rootScope.serviceBool = _permSet.serviceBool; }); + $scope.$watch(function() { + $rootScope.moduleSelection = $state.params; + }); $rootScope.$emit('SET_HEADER', $rootScope.appDetails); $scope.showLogoutConfirmationSection = false; $scope.logoutConfirmation = function () { diff --git a/client/cat3/src/partials/globals/header/header.scss b/client/cat3/src/partials/globals/header/header.scss index 481632dd3..e52098f80 100755 --- a/client/cat3/src/partials/globals/header/header.scss +++ b/client/cat3/src/partials/globals/header/header.scss @@ -18,6 +18,10 @@ .cursor { cursor:pointer; } + + .header-selected-item { + color: #40BAF1; + } .header-logo-image { height: 40px; diff --git a/client/cat3/src/partials/globals/header/headerDashboard.html b/client/cat3/src/partials/globals/header/headerDashboard.html index a908bfc07..5a07f691f 100644 --- a/client/cat3/src/partials/globals/header/headerDashboard.html +++ b/client/cat3/src/partials/globals/header/headerDashboard.html @@ -16,13 +16,13 @@
  • - WORKZONE + WORKZONE
  • - DESIGN + DESIGN
  • @@ -40,7 +40,7 @@
  • - BOTS + BOTS
  • diff --git a/client/cat3/src/partials/sections/dashboard/bots/botsCtrl.js b/client/cat3/src/partials/sections/dashboard/bots/botsCtrl.js index 34b9e2b0a..1249a53f6 100644 --- a/client/cat3/src/partials/sections/dashboard/bots/botsCtrl.js +++ b/client/cat3/src/partials/sections/dashboard/bots/botsCtrl.js @@ -13,7 +13,7 @@ url: "/library", templateUrl: "src/partials/sections/dashboard/bots/view/library.html", controller: "libraryCtrl as libr", - params:{filterView:{library:true}}, + parameters:{filterView:{library:true}}, resolve: { auth: ["$q", function ($q) { var deferred = $q.defer(); @@ -31,7 +31,7 @@ url: "/audittrail", templateUrl: "src/partials/sections/dashboard/bots/view/audittrail.html", controller: "audittrailCtrl as audit", - params:{filterView:{audittrail:true}}, + parameters:{filterView:{audittrail:true}}, resolve: { auth: ["$q", function ($q) { var deferred = $q.defer(); @@ -49,6 +49,8 @@ }]) .controller('botsCtrl',['$scope', '$rootScope', '$state', function ($scope, $rootScope, $state) { $state.go('dashboard.bots.library'); - $rootScope.stateItems = $state.params; + $scope.$watch(function() { + $rootScope.stateItems = $state.current.name; + }); }]); })(angular); \ No newline at end of file diff --git a/client/cat3/src/partials/sections/dashboard/bots/controller/audittrailCtrl.js b/client/cat3/src/partials/sections/dashboard/bots/controller/audittrailCtrl.js index 3ea895ba0..7c5a1c816 100644 --- a/client/cat3/src/partials/sections/dashboard/bots/controller/audittrailCtrl.js +++ b/client/cat3/src/partials/sections/dashboard/bots/controller/audittrailCtrl.js @@ -10,7 +10,7 @@ angular.module('dashboard.bots') .controller('audittrailCtrl',['$scope', '$rootScope', '$state', 'genericServices', 'confirmbox', 'workzoneServices', 'toastr', 'workzoneUIUtils', '$modal', function ($scope, $rootScope, $state, genSevs, confirmbox, workzoneServices, toastr, workzoneUIUtils, $modal) { - var treeNames = ['Bots','Audit Trail']; + var treeNames = ['BOTs','Audit Trail']; $rootScope.$emit('treeNameUpdate', treeNames); var audit=this; audit.gridOptions={ @@ -30,11 +30,11 @@ 'row.entity.taskType'+ 'row.entity.auditTrailConfig.executionType'+ 'row.entity.botType',cellTooltip: true}, - { name: 'BOT Name',displayName: 'BOT Name',field:'auditTrailConfig.name'}, + { name: 'BOT Name',displayName: 'BOT Name',field:'auditTrailConfig.name',cellTooltip: true}, { name: 'Status',field:'status', - cellTemplate:'' + - '' + - '', + cellTemplate:'' + + '' + + '', cellTooltip: true}, { name: 'Org',field:'masterDetails.orgName'}, { name: 'BU',field:'masterDetails.bgName'}, diff --git a/client/cat3/src/partials/sections/dashboard/bots/controller/libraryCtrl.js b/client/cat3/src/partials/sections/dashboard/bots/controller/libraryCtrl.js index 68f3f9857..3b622b85a 100644 --- a/client/cat3/src/partials/sections/dashboard/bots/controller/libraryCtrl.js +++ b/client/cat3/src/partials/sections/dashboard/bots/controller/libraryCtrl.js @@ -9,7 +9,7 @@ "use strict"; angular.module('dashboard.bots') .controller('libraryCtrl',['$scope', '$rootScope', '$state', 'genericServices', 'confirmbox', 'toastr', 'workzoneUIUtils', '$modal', function ($scope, $rootScope, $state, genSevs, confirmbox, toastr, workzoneUIUtils, $modal) { - var treeNames = ['Bots','Library']; + var treeNames = ['BOTs','Library']; $rootScope.$emit('treeNameUpdate', treeNames); var lib=this; $scope.totalBotsSelected = true; @@ -25,16 +25,18 @@ 'row.entity.taskType'+ 'row.entity.taskType'+ 'row.entity.botType',cellTooltip: true}, - { name: 'BOT Type',displayName: 'BOT Type',field:'botType'}, - { name: 'BOT Name',displayName: 'BOT Name',field:'name'}, - { name: 'Category',field:'botCategory'}, - { name: 'description',field:'shortDesc'}, + { name: 'BOT Type',displayName: 'BOT Type',field:'botType',cellTooltip: true}, + { name: 'BOT Name',displayName: 'BOT Name',field:'name',cellTooltip: true}, + { name: 'Category',field:'botCategory',cellTooltip: true}, + { name: 'description',field:'shortDesc',cellTooltip: true}, { name: 'Total Runs',field:'executionCount'}, { name: 'BOT History',displayName: 'BOT History',cellTemplate:'NA'+ ''}, { name: 'BOT Info',displayName: 'BOT Info',cellTemplate: ''}, - { name: 'BOT Action',displayName: 'BOT Action',cellTemplate:'' + + { name: 'BOT Action',displayName: 'BOT Action',cellTemplate: + '' + + '' + '' + '' } @@ -72,13 +74,53 @@ console.log('Modal Dismissed at ' + new Date()); }); }; + $scope.botSchedule = function() { + $modal.open({ + templateUrl: 'src/partials/sections/dashboard/bots/view/botSchedule.html', + controller: 'botScheduleCtrl', + backdrop: 'static', + keyboard: false, + resolve: { + items: function () { + return { + chefJenkScriptTaskObj:$scope.chefJenkScriptTaskObj, + type:$scope.type + } + } + } + }).result.then(function (chefEventDetails) { + $scope.isEventAvailable = true; + $scope.chefJenkScriptTaskObj = chefEventDetails; + var startTimeMinute,startTimeHour,dayOfWeek,selectedDayOfTheMonth,selectedMonth; + startTimeMinute = $scope.chefJenkScriptTaskObj.startTimeMinute; + startTimeHour = $scope.chefJenkScriptTaskObj.startTime; + dayOfWeek = $scope.chefJenkScriptTaskObj.dayOfWeek; + selectedDayOfTheMonth = $scope.chefJenkScriptTaskObj.selectedDayOfTheMonth; + selectedMonth = $scope.chefJenkScriptTaskObj.monthOfYear; + $scope.type = 'edit'; + $scope._isEventSelected = true; + + $scope.repeatPattern = 'Repeat Every -' + $scope.chefJenkScriptTaskObj.repeats; + $scope.cronDetails = { + cronStartOn : $scope.chefJenkScriptTaskObj.cronStart, + cronEndOn : $scope.chefJenkScriptTaskObj.cronEnd, + cronRepeatEvery : $scope.chefJenkScriptTaskObj.repeatBy, + cronFrequency: $scope.chefJenkScriptTaskObj.repeats, + cronTime: typeof startTimeHour !=='undefined'? startTimeHour : new Date().getHours() + ':' + typeof startTimeMinute !=='undefined'? startTimeMinute:new Date().getMinutes(), + cronDays: $scope.chefJenkScriptTaskObj.dayOfWeek, + cronMonth: $scope.chefJenkScriptTaskObj.monthOfYear + } + }, function () { + console.log('Dismiss time is ' + new Date()); + }); + }; $scope.deleteBotTask = function(task) { var modalOptions = { closeButtonText: 'Cancel', actionButtonText: 'Delete', actionButtonStyle: 'cat-btn-delete', headerText: 'Delete Bot', - bodyText: 'Are you sure you want to delete this bot?' + bodyText: 'Are you sure you want to delete this bots?' }; confirmbox.showModal({}, modalOptions).then(function() { var param={ @@ -109,7 +151,7 @@ actionButtonText: 'Delete', actionButtonStyle: 'cat-btn-delete', headerText: 'Delete Bot', - bodyText: 'Are you sure you want to delete this bot?' + bodyText: 'Are you sure you want to delete this bots?' }; confirmbox.showModal({}, modalOptions).then(function() { var param={ @@ -178,7 +220,7 @@ lib.summary = function() { $scope.botSummary=[]; var param={ - url:'/audit-trail/bot-summary' + url:'/audit-trail/bots-summary' }; genSevs.promiseGet(param).then(function (response) { $scope.botSummary = response; @@ -215,5 +257,92 @@ $scope.cancel= function() { $modalInstance.dismiss('cancel'); }; + }]).controller('botScheduleCtrl',['$scope', '$rootScope', 'genericServices', 'workzoneServices', 'toastr', '$modalInstance', 'items', '$timeout', function ($scope, $rootScope, genSevs, workzoneServices, toastr, $modalInstance, items, $timeout) { + console.log(items); + $scope.defaultSelection = function() { + $scope.repeatsType = 'Minutes';//default selection. + $scope.schedulerStartOn=moment(new Date()).format('MM/DD/YYYY'); + $scope.schedulerEndOn=moment(new Date()).format('MM/DD/YYYY'); + }; + if(items.type !== 'new'){ + if(items.chefJenkScriptTaskObj !==undefined){ + if(items.chefJenkScriptTaskObj.cronStartOn && items.chefJenkScriptTaskObj.cronEndOn) { + var newStartOn = parseInt(items.chefJenkScriptTaskObj.cronStartOn); + var newDate = new Date(newStartOn).toLocaleDateString(); + var datearray = newDate.split("/"); + var newdate = datearray[1] + '/' + datearray[0] + '/' + datearray[2]; + $scope.schedulerStartOn = newdate; + var newEndOn = parseInt(items.chefJenkScriptTaskObj.cronEndOn); + var newEndData = new Date(newEndOn).toLocaleDateString(); + var datearrayNew = newEndData.split("/"); + var newdateEnd = datearrayNew[1] + '/' + datearrayNew[0] + '/' + datearrayNew[2]; + $scope.schedulerEndOn = newdateEnd; + } else { + $scope.schedulerStartOn = items.chefJenkScriptTaskObj.cronStart; + $scope.schedulerEndOn = items.chefJenkScriptTaskObj.cronEnd; + } + + $scope.repeatBy = items.chefJenkScriptTaskObj.repeatBy || items.chefJenkScriptTaskObj.cronRepeatEvery.toString(); + $scope.repeatsType = items.chefJenkScriptTaskObj.repeats || items.chefJenkScriptTaskObj.cronFrequency; + $scope.timeEventType = items.chefJenkScriptTaskObj.startTime; + $scope.timeEventMinute = items.chefJenkScriptTaskObj.startTimeMinute; + $scope.weekOfTheDay = items.chefJenkScriptTaskObj.dayOfWeek; + $scope.currentDate = items.chefJenkScriptTaskObj.startDate; + $scope.selectedDayOfTheMonth = items.chefJenkScriptTaskObj.selectedDayOfTheMonth; + $scope.selectedMonth = items.chefJenkScriptTaskObj.monthOfYear; + } else { + $scope.defaultSelection(); + } + } else { + $scope.defaultSelection(); + } + + $scope.dateChange= function () { + var startDate = Date.parse($scope.schedulerStartOn); + var endDate = Date.parse($scope.schedulerEndOn); + if(startDate > endDate){ + $scope.validDateRange=true; + } else { + $scope.validDateRange=false; + } + + }; + + $scope.repeatCount = function(max, step) { + step = step || 1; + var input = []; + for (var i = 1; i <= max; i += step) { + input.push(i); + } + return input; + }; + $scope.isDaySelected = { + flag:true + } + + $scope.daysOfWeek = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]; + + $scope.monthOfYear = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; + $scope.cancel = function() { + $modalInstance.dismiss('cancel'); + }; + $scope.ok=function(){ + $scope.eventParams = { + repeats: $scope.repeatsType, + repeatBy: $scope.repeatBy, + cronStart: $scope.schedulerStartOn, + cronEnd: $scope.schedulerEndOn, + startTime: $scope.timeEventType, + startTimeMinute: $scope.timeEventMinute, + dayOfWeek: $scope.weekOfTheDay, + selectedDayOfTheMonth: $scope.selectedDayOfTheMonth, + monthOfYear: $scope.selectedMonth + }; + $modalInstance.close($scope.eventParams); + }; + + $scope.cancel = function() { + $modalInstance.dismiss('cancel'); + }; }]); })(angular); \ No newline at end of file diff --git a/client/cat3/src/partials/sections/dashboard/bots/view/botInfo.html b/client/cat3/src/partials/sections/dashboard/bots/view/botInfo.html index b16ae05ce..a82e48010 100644 --- a/client/cat3/src/partials/sections/dashboard/bots/view/botInfo.html +++ b/client/cat3/src/partials/sections/dashboard/bots/view/botInfo.html @@ -22,12 +22,23 @@
  • @@ -26,7 +26,7 @@
    Audit Trail - +
    @@ -38,4 +38,4 @@ - + \ No newline at end of file diff --git a/client/cat3/src/partials/sections/dashboard/bots/view/editParams.html b/client/cat3/src/partials/sections/dashboard/bots/view/editParams.html index 60d344947..ce379adb3 100644 --- a/client/cat3/src/partials/sections/dashboard/bots/view/editParams.html +++ b/client/cat3/src/partials/sections/dashboard/bots/view/editParams.html @@ -3,7 +3,7 @@
    - Add More +
    diff --git a/client/cat3/src/partials/sections/dashboard/design/view/blueprintCreate.html b/client/cat3/src/partials/sections/dashboard/design/view/blueprintCreate.html index 9e7e8d3f0..886049f3c 100755 --- a/client/cat3/src/partials/sections/dashboard/design/view/blueprintCreate.html +++ b/client/cat3/src/partials/sections/dashboard/design/view/blueprintCreate.html @@ -256,7 +256,7 @@
    -
    -
    "}else{IconSection="
    "}if(settings.icon==undefined){BoxSmall="
    "+settings.title+"

    "+settings.content+"

    "+IconSection+"
    "}else{BoxSmall="
    "+settings.title+"

    "+settings.content+"

    "+IconSection+"
    "}if(SmallBoxes==1){$("#divSmallBoxes").append(BoxSmall);SmallBoxesAnchos=$("#smallbox"+SmallBoxes).height()+40}else{var SmartExist=$(".SmallBox").size();if(SmartExist==0){$("#divSmallBoxes").append(BoxSmall);SmallBoxesAnchos=$("#smallbox"+SmallBoxes).height()+40}else{$("#divSmallBoxes").append(BoxSmall);$("#smallbox"+SmallBoxes).css("top",SmallBoxesAnchos);SmallBoxesAnchos=SmallBoxesAnchos+$("#smallbox"+SmallBoxes).height()+20;$(".SmallBox").each(function(index){if(index==0){$(this).css("top",20);heightPrev=$(this).height()+40;SmallBoxesAnchos=$(this).height()+40}else{$(this).css("top",heightPrev);heightPrev=heightPrev+$(this).height()+20;SmallBoxesAnchos=SmallBoxesAnchos+$(this).height()+20}})}}var ThisSmallBox=$("#smallbox"+SmallBoxes);if(settings.color==undefined){ThisSmallBox.css("background-color","#004d60")}else{ThisSmallBox.css("background-color",settings.color)}var ColorTimeInterval;if(settings.colors!=undefined&&settings.colors.length>0){ThisSmallBox.attr("colorcount","0");ColorTimeInterval=setInterval(function(){var ColorIndex=ThisSmallBox.attr("colorcount");ThisSmallBox.animate({backgroundColor:settings.colors[ColorIndex].color});if(ColorIndex-1){if(ver>=8){msg="You're using a recent copy of Windows Internet Explorer."}else{msg="You should upgrade your copy of Windows Internet Explorer."}}alert(msg)}function isIE8orlower(){var msg="0";var ver=getInternetExplorerVersion();if(ver>-1){if(ver>=9){msg=0}else{msg=1}}return msg}; \ No newline at end of file +$(document).ready(function(){$("body").append("
    ");$("body").append("
    ")});function SmartUnLoading(){$(".divMessageBox").fadeOut(300,function(){$(this).remove()});$(".LoadingBoxContainer").fadeOut(300,function(){$(this).remove()})}var ExistMsg=0,SmartMSGboxCount=0,PrevTop=0;(function($){$.SmartMessageBox=function(settings,callback){var SmartMSG,Content;settings=$.extend({title:"",content:"",NormalButton:undefined,ActiveButton:undefined,buttons:undefined,input:undefined,placeholder:"",options:undefined},settings);var PlaySound=0;PlaySound=1;if(isIE8orlower()==0){var audioElement=document.createElement("audio");audioElement.setAttribute("src","sound/messagebox.mp3");$.get();audioElement.addEventListener("load",function(){audioElement.play()},true);audioElement.pause();audioElement.play()}SmartMSGboxCount=SmartMSGboxCount+1;if(ExistMsg==0){ExistMsg=1;SmartMSG="
    ";$("body").append(SmartMSG);if(isIE8orlower()==1){$("#MsgBoxBack").addClass("MessageIE")}}var InputType="";var HasInput=0;if(settings.input!=undefined){HasInput=1;settings.input=settings.input.toLowerCase();switch(settings.input){case"text":InputType="

    ";break;case"password":InputType="

    ";break;case"select":if(settings.options==undefined){alert("For this type of input, the options parameter is required.")}else{InputType=""}break;default:alert("That type of input is not handled yet")}}Content="
    ";Content+="
    ";Content+=""+settings.title+"";Content+="

    "+settings.content+"

    ";Content+=InputType;Content+="
    ";if(settings.buttons==undefined){settings.buttons="[Accept]"}settings.buttons=$.trim(settings.buttons);settings.buttons=settings.buttons.split("");var Name="";var NumBottons=0;if(settings.NormalButton==undefined){settings.NormalButton="#232323"}if(settings.ActiveButton==undefined){settings.ActiveButton="#ed145b"}for(var i=0;i<=settings.buttons.length-1;i++){if(settings.buttons[i]=="["){Name=""}else{if(settings.buttons[i]=="]"){NumBottons=NumBottons+1;Name="";Content+=Name}else{Name+=settings.buttons[i]}}}Content+="
    ";Content+="
    ";Content+="
    ";if(SmartMSGboxCount>1){$(".MessageBoxContainer").hide();$(".MessageBoxContainer").css("z-index",99999)}$(".divMessageBox").append(Content);if(HasInput==1){$("#txt"+SmartMSGboxCount).focus()}$(".botTempo").hover(function(){var ThisID=$(this).attr("id")},function(){var ThisID=$(this).attr("id")});$(".botTempo").click(function(){var ThisID=$(this).attr("id");var MsgBoxID=ThisID.substr(ThisID.indexOf("-")+1);var Press=$.trim($(this).text());if(HasInput==1){if(typeof callback=="function"){var IDNumber=MsgBoxID.replace("Msg","");var Value=$("#txt"+IDNumber).val();if(callback){callback(Press,Value)}}}else{if(typeof callback=="function"){if(callback){callback(Press)}}}$("#"+MsgBoxID).addClass("animated fadeOut fast");SmartMSGboxCount=SmartMSGboxCount-1;if(SmartMSGboxCount==0){$("#MsgBoxBack").removeClass("fadeIn").addClass("fadeOut").delay(300).queue(function(){ExistMsg=0;$(this).remove()})}})}})(jQuery);var BigBoxes=0;(function($){$.bigBox=function(settings,callback){var boxBig,content;settings=$.extend({title:"",content:"",icon:undefined,number:undefined,color:undefined,sound:true,timeout:undefined,colortime:1500,colors:undefined},settings);if(settings.sound===true){if(isIE8orlower()==0){var audioElement=document.createElement("audio");if(navigator.userAgent.match("Firefox/")){audioElement.setAttribute("src","sound/bigbox.ogg")}else{audioElement.setAttribute("src","sound/bigbox.mp3")}$.get();audioElement.addEventListener("load",function(){audioElement.play()},true);audioElement.pause();audioElement.play()}}BigBoxes=BigBoxes+1;boxBig="
    ";boxBig+=""+settings.title+"";boxBig+="

    "+settings.content+"

    ";boxBig+="
    ";if(settings.icon==undefined){settings.icon="fa fa-cloud"}boxBig+="";boxBig+="
    ";boxBig+="
    ";if(settings.number!=undefined){boxBig+=settings.number}boxBig+="
    ";boxBig+="
    ";$("#divbigBoxes").append(boxBig);if(settings.color==undefined){settings.color="#004d60"}$("#bigBox"+BigBoxes).css("background-color",settings.color);$("#divMiniIcons").append("
    ");$("#miniIcon"+BigBoxes).bind("click",function(){var FrontBox=$(this).attr("id");var FrontBigBox=FrontBox.replace("miniIcon","bigBox");var FronBigBoxColor=FrontBox.replace("miniIcon","bigBoxColor");$(".cajita").each(function(index){var BackBox=$(this).attr("id");var BigBoxID=BackBox.replace("miniIcon","bigBox");$("#"+BigBoxID).css("z-index",9998)});$("#"+FrontBigBox).css("z-index",9999);$("#"+FronBigBoxColor).removeClass("animated fadeIn").delay(1).queue(function(){$(this).show();$(this).addClass("animated fadeIn");$(this).clearQueue()})});var ThisBigBoxCloseCross=$("#botClose"+BigBoxes);var ThisBigBox=$("#bigBox"+BigBoxes);var ThisMiniIcon=$("#miniIcon"+BigBoxes);var ColorTimeInterval;if(settings.colors!=undefined&&settings.colors.length>0){ThisBigBoxCloseCross.attr("colorcount","0");ColorTimeInterval=setInterval(function(){var ColorIndex=ThisBigBoxCloseCross.attr("colorcount");ThisBigBoxCloseCross.animate({backgroundColor:settings.colors[ColorIndex].color});ThisBigBox.animate({backgroundColor:settings.colors[ColorIndex].color});ThisMiniIcon.animate({backgroundColor:settings.colors[ColorIndex].color});if(ColorIndex"}else{IconSection="
    "}if(settings.icon==undefined){BoxSmall="
    "+settings.title+"

    "+settings.content+"

    "+IconSection+"
    "}else{BoxSmall="
    "+settings.title+"

    "+settings.content+"

    "+IconSection+"
    "}if(SmallBoxes==1){$("#divSmallBoxes").append(BoxSmall);SmallBoxesAnchos=$("#smallbox"+SmallBoxes).height()+40}else{var SmartExist=$(".SmallBox").size();if(SmartExist==0){$("#divSmallBoxes").append(BoxSmall);SmallBoxesAnchos=$("#smallbox"+SmallBoxes).height()+40}else{$("#divSmallBoxes").append(BoxSmall);$("#smallbox"+SmallBoxes).css("top",SmallBoxesAnchos);SmallBoxesAnchos=SmallBoxesAnchos+$("#smallbox"+SmallBoxes).height()+20;$(".SmallBox").each(function(index){if(index==0){$(this).css("top",20);heightPrev=$(this).height()+40;SmallBoxesAnchos=$(this).height()+40}else{$(this).css("top",heightPrev);heightPrev=heightPrev+$(this).height()+20;SmallBoxesAnchos=SmallBoxesAnchos+$(this).height()+20}})}}var ThisSmallBox=$("#smallbox"+SmallBoxes);if(settings.color==undefined){ThisSmallBox.css("background-color","#004d60")}else{ThisSmallBox.css("background-color",settings.color)}var ColorTimeInterval;if(settings.colors!=undefined&&settings.colors.length>0){ThisSmallBox.attr("colorcount","0");ColorTimeInterval=setInterval(function(){var ColorIndex=ThisSmallBox.attr("colorcount");ThisSmallBox.animate({backgroundColor:settings.colors[ColorIndex].color});if(ColorIndex-1){if(ver>=8){msg="You're using a recent copy of Windows Internet Explorer."}else{msg="You should upgrade your copy of Windows Internet Explorer."}}alert(msg)}function isIE8orlower(){var msg="0";var ver=getInternetExplorerVersion();if(ver>-1){if(ver>=9){msg=0}else{msg=1}}return msg}; \ No newline at end of file diff --git a/server/app/app.js b/server/app/app.js index 0d5796431..3f657ad76 100755 --- a/server/app/app.js +++ b/server/app/app.js @@ -219,6 +219,7 @@ cronTabManager.start(); catalystSync.executeScheduledInstances(); catalystSync.executeSerialScheduledTasks(); catalystSync.executeParallelScheduledTasks(); +catalystSync.executeScheduledBots(); server.listen(app.get('port'), function() { logger.debug('Express server listening on port ' + app.get('port')); }); \ No newline at end of file diff --git a/server/app/cronjobs/catalyst-scheduler/catalystScheduler.js b/server/app/cronjobs/catalyst-scheduler/catalystScheduler.js index 724081f6d..0cea183c5 100644 --- a/server/app/cronjobs/catalyst-scheduler/catalystScheduler.js +++ b/server/app/cronjobs/catalyst-scheduler/catalystScheduler.js @@ -1,6 +1,7 @@ var logger = require('_pr/logger')(module); var instancesDao = require('_pr/model/classes/instance/instance'); var taskDao = require('_pr/model/classes/tasks/tasks.js'); +var botsDao = require('_pr/model/bots/bots.js'); var schedulerService = require('_pr/services/schedulerService'); var async = require('async'); var cronTab = require('node-crontab'); @@ -86,6 +87,44 @@ catalystSync.executeParallelScheduledTasks = function executeParallelScheduledTa }); } +catalystSync.executeParallelScheduledTasks = function executeParallelScheduledTasks() { + taskDao.getScheduledTasks('PARALLEL',function(err, tasks) { + if (err) { + logger.error("Failed to fetch tasks: ", err); + return; + } + if (tasks && tasks.length) { + var parallelTaskList=[]; + for (var i = 0; i < tasks.length; i++) { + (function(task) { + if(task.cronJobId && task.cronJobId !== null){ + cronTab.cancelJob(task.cronJobId); + } + parallelTaskList.push(function(callback){schedulerService.executeParallelScheduledTasks(task,callback);}); + if(parallelTaskList.length === tasks.length){ + if(parallelTaskList.length > 0) { + async.parallel(parallelTaskList, function (err, results) { + if (err) { + logger.error(err); + return; + } + logger.debug("Task Scheduler Completed for Parallel"); + return; + }) + }else{ + logger.debug("There is no Parallel scheduled Task right now."); + return; + } + } + })(tasks[i]); + } + }else{ + logger.debug("There is no Parallel scheduled Task right now."); + return; + } + }); +} + catalystSync.executeSerialScheduledTasks = function executeSerialScheduledTasks() { taskDao.getScheduledTasks('SERIAL',function(err, tasks) { if (err) { @@ -135,6 +174,44 @@ catalystSync.executeSerialScheduledTasks = function executeSerialScheduledTasks( }); } +catalystSync.executeScheduledBots = function executeScheduledBots() { + botsDao.getScheduledBots(function(err, bots) { + if (err) { + logger.error("Failed to fetch bots: ", err); + return; + } + if (bots && bots.length) { + var botsList=[]; + for (var i = 0; i < bots.length; i++) { + (function(bot) { + if(bot.cronJobId && bot.cronJobId !== null){ + cronTab.cancelJob(bot.cronJobId); + } + botsList.push(function(callback){schedulerService.executeScheduledBots(bot,callback);}); + if(botsList.length === bots.length){ + if(botsList.length > 0) { + async.parallel(botsList, function (err, results) { + if (err) { + logger.error(err); + return; + } + logger.debug("Bots Scheduler Completed"); + return; + }) + }else{ + logger.debug("There is no scheduled Bots right now."); + return; + } + } + })(bots[i]); + } + }else{ + logger.debug("There is no scheduled Bots right now."); + return; + } + }); +} + function cancelOldCronJobs(ids){ if(ids.length > 0){ var count = 0; diff --git a/server/app/model/audit-trail/audit-trail.js b/server/app/model/audit-trail/audit-trail.js index 47debe2eb..b9fc9735d 100644 --- a/server/app/model/audit-trail/audit-trail.js +++ b/server/app/model/audit-trail/audit-trail.js @@ -24,6 +24,7 @@ var AuditTrailSchema = new BaseAuditTrail(); AuditTrailSchema.plugin(mongoosePaginate); AuditTrailSchema.statics.getAuditTrailList = function(auditTrailQuery,callback){ + auditTrailQuery.queryObj.isDeleted = false; AuditTrail.paginate(auditTrailQuery.queryObj, auditTrailQuery.options, function(err, auditTrailList) { if (err) { logger.error(err); @@ -59,6 +60,30 @@ AuditTrailSchema.statics.removeAuditTrails = function(queryObj,callback){ }); }; +AuditTrailSchema.statics.softRemoveAuditTrails = function(auditId,callback){ + AuditTrail.update({auditId:auditId},{$set:{isDeleted:true}},{multi:true}, function(err, sortDeleteAuditTrail) { + if (err) { + logger.error(err); + var error = new Error('Internal server error'); + error.status = 500; + return callback(error); + } + return callback(null, sortDeleteAuditTrail); + }); +}; + +AuditTrailSchema.statics.updateSoftRemoveAuditTrails = function(auditId,callback){ + AuditTrail.update({auditId:auditId},{$set:{isDeleted:false}},{multi:true}, function(err, sortDeleteAuditTrail) { + if (err) { + logger.error(err); + var error = new Error('Internal server error'); + error.status = 500; + return callback(error); + } + return callback(null, sortDeleteAuditTrail); + }); +}; + var AuditTrail = mongoose.model('auditTrails', AuditTrailSchema); module.exports = AuditTrail; diff --git a/server/app/model/audit-trail/base-audit-trail.js b/server/app/model/audit-trail/base-audit-trail.js index d44ee44f4..f8ef79ee5 100644 --- a/server/app/model/audit-trail/base-audit-trail.js +++ b/server/app/model/audit-trail/base-audit-trail.js @@ -116,6 +116,10 @@ var AuditTrailSchema = function AuditTrail() { type: String, trim:true, required:false + }, + isDeleted: { + type: Boolean, + default:false } }); }; diff --git a/server/app/model/blueprint/blueprint-types/instance-blueprint/aws-blueprint/aws-blueprint.js b/server/app/model/blueprint/blueprint-types/instance-blueprint/aws-blueprint/aws-blueprint.js index 117c0f495..d6747e94b 100755 --- a/server/app/model/blueprint/blueprint-types/instance-blueprint/aws-blueprint/aws-blueprint.js +++ b/server/app/model/blueprint/blueprint-types/instance-blueprint/aws-blueprint/aws-blueprint.js @@ -304,7 +304,7 @@ AWSInstanceBlueprintSchema.methods.launch = function (launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs', launchParams.auditTrailId, resultTaskExecution, function (err, auditTrail) { if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -378,7 +378,7 @@ AWSInstanceBlueprintSchema.methods.launch = function (launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs', launchParams.auditTrailId, resultTaskExecution, function (err, auditTrail) { if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -450,7 +450,7 @@ AWSInstanceBlueprintSchema.methods.launch = function (launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs', launchParams.auditTrailId, resultTaskExecution, function (err, auditTrail) { if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -503,7 +503,7 @@ AWSInstanceBlueprintSchema.methods.launch = function (launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs', launchParams.auditTrailId, resultTaskExecution, function (err, auditTrail) { if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -630,7 +630,7 @@ AWSInstanceBlueprintSchema.methods.launch = function (launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs', launchParams.auditTrailId, resultTaskExecution, function (err, auditTrail) { if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -654,102 +654,120 @@ AWSInstanceBlueprintSchema.methods.launch = function (launchParams, callback) { } logger.debug("Domain name is updated successfully"); }); - } - instancesDao.updateActionLog(instance.id, actionLog._id, true, timestampEnded); - launchParams.infraManager.getNode(instance.chefNodeName, function (err, nodeData) { - if (err) { - logger.error("Failed chef.getNode", err); - return; - } - instanceLog.platform = nodeData.automatic.platform; - instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function (err, logData) { - if (err) { - logger.error("Failed to create or update instanceLog: ", err); - } - }); - var hardwareData = {}; - hardwareData.architecture = nodeData.automatic.kernel.machine; - hardwareData.platform = nodeData.automatic.platform; - hardwareData.platformVersion = nodeData.automatic.platform_version; - hardwareData.memory = { - total: 'unknown', - free: 'unknown' + instanceLog.endedOn = new Date().getTime(); + instanceLog.actionStatus = "success"; + instanceLog.logs = { + err: false, + log: "Instance Bootstrapped successfully", + timestamp: new Date().getTime() }; - if (nodeData.automatic.memory) { - hardwareData.memory.total = nodeData.automatic.memory.total; - hardwareData.memory.free = nodeData.automatic.memory.free; + if (launchParams.auditTrailId !== null) { + var resultTaskExecution = { + actionStatus: "success", + status: "success", + endedOn: new Date().getTime() + } + auditTrailService.updateAuditTrail('BOTs', launchParams.auditTrailId, resultTaskExecution, function (err, auditTrail) { + if (err) { + logger.error("Failed to create or update bots Log: ", err); + } + }); } - hardwareData.os = instance.hardware.os; - instancesDao.setHardwareDetails(instance.id, hardwareData, function (err, updateData) { + instancesDao.updateActionLog(instance.id, actionLog._id, true, timestampEnded); + launchParams.infraManager.getNode(instance.chefNodeName, function (err, nodeData) { if (err) { - logger.error("Unable to set instance hardware details code (setHardwareDetails)", err); - } else { - logger.debug("Instance hardware details set successessfully"); + logger.error("Failed chef.getNode", err); + return; } - }); - //Checking docker status and updating - var _docker = new Docker(); - _docker.checkDockerStatus(instance.id, - function (err, retCode) { + instanceLog.platform = nodeData.automatic.platform; + instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function (err, logData) { if (err) { - logger.error("Failed _docker.checkDockerStatus", err); - res.send(500); - return; - //res.end('200'); - + logger.error("Failed to create or update instanceLog: ", err); } - logger.debug('Docker Check Returned:' + retCode); - if (retCode == '0') { - instancesDao.updateInstanceDockerStatus(instance.id, "success", '', function (data) { - logger.debug('Instance Docker Status set to Success'); - }); - + }); + var hardwareData = {}; + hardwareData.architecture = nodeData.automatic.kernel.machine; + hardwareData.platform = nodeData.automatic.platform; + hardwareData.platformVersion = nodeData.automatic.platform_version; + hardwareData.memory = { + total: 'unknown', + free: 'unknown' + }; + if (nodeData.automatic.memory) { + hardwareData.memory.total = nodeData.automatic.memory.total; + hardwareData.memory.free = nodeData.automatic.memory.free; + } + hardwareData.os = instance.hardware.os; + instancesDao.setHardwareDetails(instance.id, hardwareData, function (err, updateData) { + if (err) { + logger.error("Unable to set instance hardware details code (setHardwareDetails)", err); + } else { + logger.debug("Instance hardware details set successessfully"); } }); + //Checking docker status and updating + var _docker = new Docker(); + _docker.checkDockerStatus(instance.id, + function (err, retCode) { + if (err) { + logger.error("Failed _docker.checkDockerStatus", err); + res.send(500); + return; + //res.end('200'); + + } + logger.debug('Docker Check Returned:' + retCode); + if (retCode == '0') { + instancesDao.updateInstanceDockerStatus(instance.id, "success", '', function (data) { + logger.debug('Instance Docker Status set to Success'); + }); + + } + }); - }); + }); - } else { - instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function (err, updateData) { - if (err) { - logger.error("Unable to set instance bootstarp status code != 0", err); - } else { - logger.debug("Instance bootstrap status set to failed"); - } - }); - instanceLog.endedOn = new Date().getTime(); - instanceLog.actionStatus = "failed"; - instanceLog.logs = { - err: false, - log: "Bootstrap 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); - } - }); - if (launchParams.auditTrailId !== null) { - var resultTaskExecution = { - actionStatus: "failed", - status: "failed", - endedOn: new Date().getTime() - } - auditTrailService.updateAuditTrail('BOTs', launchParams.auditTrailId, resultTaskExecution, function (err, auditTrail) { + } else { + instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function (err, updateData) { if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Unable to set instance bootstarp status code != 0", err); + } else { + logger.debug("Instance bootstrap status set to failed"); } }); + instanceLog.endedOn = new Date().getTime(); + instanceLog.actionStatus = "failed"; + instanceLog.logs = { + err: false, + log: "Bootstrap 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); + } + }); + if (launchParams.auditTrailId !== null) { + var resultTaskExecution = { + actionStatus: "failed", + status: "failed", + endedOn: new Date().getTime() + } + auditTrailService.updateAuditTrail('BOTs', launchParams.auditTrailId, resultTaskExecution, function (err, auditTrail) { + if (err) { + logger.error("Failed to create or update bot Log: ", err); + } + }); + } + var timestampEnded = new Date().getTime(); + logsDao.insertLog({ + referenceId: logsReferenceIds, + err: false, + log: "Bootstrap Failed", + timestamp: timestampEnded + }); + instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded); } - var timestampEnded = new Date().getTime(); - logsDao.insertLog({ - referenceId: logsReferenceIds, - err: false, - log: "Bootstrap Failed", - timestamp: timestampEnded - }); - instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded); - } } diff --git a/server/app/model/blueprint/blueprint-types/instance-blueprint/azure-blueprint/azure-blueprint.js b/server/app/model/blueprint/blueprint-types/instance-blueprint/azure-blueprint/azure-blueprint.js index 4588aee93..24a811da5 100755 --- a/server/app/model/blueprint/blueprint-types/instance-blueprint/azure-blueprint/azure-blueprint.js +++ b/server/app/model/blueprint/blueprint-types/instance-blueprint/azure-blueprint/azure-blueprint.js @@ -404,7 +404,7 @@ azureInstanceBlueprintSchema.methods.launch = function(launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -533,7 +533,7 @@ azureInstanceBlueprintSchema.methods.launch = function(launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -574,7 +574,7 @@ azureInstanceBlueprintSchema.methods.launch = function(launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -650,7 +650,7 @@ azureInstanceBlueprintSchema.methods.launch = function(launchParams, callback) { } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } diff --git a/server/app/model/blueprint/blueprint-types/instance-blueprint/openstack-blueprint/openstack-blueprint.js b/server/app/model/blueprint/blueprint-types/instance-blueprint/openstack-blueprint/openstack-blueprint.js index 9d6878f7c..04485019f 100755 --- a/server/app/model/blueprint/blueprint-types/instance-blueprint/openstack-blueprint/openstack-blueprint.js +++ b/server/app/model/blueprint/blueprint-types/instance-blueprint/openstack-blueprint/openstack-blueprint.js @@ -300,7 +300,7 @@ openstackInstanceBlueprintSchema.methods.launch = function(launchParams, callbac } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -488,7 +488,7 @@ openstackInstanceBlueprintSchema.methods.launch = function(launchParams, callbac } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -524,7 +524,7 @@ openstackInstanceBlueprintSchema.methods.launch = function(launchParams, callbac } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -599,7 +599,7 @@ openstackInstanceBlueprintSchema.methods.launch = function(launchParams, callbac } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } diff --git a/server/app/model/blueprint/blueprint-types/instance-blueprint/vmware-blueprint/vmware-blueprint.js b/server/app/model/blueprint/blueprint-types/instance-blueprint/vmware-blueprint/vmware-blueprint.js index 242966f74..6233ada97 100755 --- a/server/app/model/blueprint/blueprint-types/instance-blueprint/vmware-blueprint/vmware-blueprint.js +++ b/server/app/model/blueprint/blueprint-types/instance-blueprint/vmware-blueprint/vmware-blueprint.js @@ -291,7 +291,7 @@ vmwareInstanceBlueprintSchema.methods.launch = function(launchParams, callback) } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -373,7 +373,7 @@ vmwareInstanceBlueprintSchema.methods.launch = function(launchParams, callback) } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -477,7 +477,7 @@ vmwareInstanceBlueprintSchema.methods.launch = function(launchParams, callback) } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -583,7 +583,7 @@ vmwareInstanceBlueprintSchema.methods.launch = function(launchParams, callback) } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } @@ -618,7 +618,7 @@ vmwareInstanceBlueprintSchema.methods.launch = function(launchParams, callback) } auditTrailService.updateAuditTrail('BOTs',launchParams.auditTrailId,resultTaskExecution,function(err,auditTrail){ if (err) { - logger.error("Failed to create or update bot Log: ", err); + logger.error("Failed to create or update bots Log: ", err); } }); } diff --git a/server/app/model/blueprint/blueprint.js b/server/app/model/blueprint/blueprint.js index 754d4f359..c0e9d50df 100755 --- a/server/app/model/blueprint/blueprint.js +++ b/server/app/model/blueprint/blueprint.js @@ -474,10 +474,11 @@ BlueprintSchema.statics.createNew = function (blueprintData, callback) { version: count, parentId: blueprintData.id, domainNameCheck: blueprintData.domainNameCheck, - shortDesc: blueprintData.shortDesc, - botType: blueprintData.botType, - serviceDeliveryCheck: blueprintData.serviceDeliveryCheck, - botCategory: blueprintData.botCategory + shortDesc:blueprintData.shortDesc, + botType:blueprintData.botType, + serviceDeliveryCheck:blueprintData.serviceDeliveryCheck, + botCategory:blueprintData.botCategory, + manualExecutionTime:blueprintData.manualExecutionTime }; var blueprint = new Blueprints(blueprintObj); logger.debug(blueprint); @@ -1423,9 +1424,9 @@ BlueprintSchema.statics.getBlueprintsByProviderId = function (providerId, callba }); }; -BlueprintSchema.statics.getBlueprintByOrgBgProjectProviderType = function (query, callback) { - console.log(JSON.stringify(query)); - Blueprints.paginate(query.queryObj, query.options, function (err, blueprints) { + +BlueprintSchema.statics.getBlueprintByOrgBgProjectProviderType = function(query, callback) { + Blueprints.paginate(query.queryObj, query.options, function(err, blueprints) { if (err) { logger.error("Failed to getBlueprintByOrgBgProjectProviderType", err); callback(err, null); diff --git a/server/app/model/bots/bots.js b/server/app/model/bots/bots.js new file mode 100644 index 000000000..319d807af --- /dev/null +++ b/server/app/model/bots/bots.js @@ -0,0 +1,343 @@ +/* + Copyright [2016] [Relevance Lab] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +var mongoose = require('mongoose'); +var ObjectId = require('mongoose').Types.ObjectId; +var mongoosePaginate = require('mongoose-paginate'); +var Schema = mongoose.Schema; + +var BotsSchema = new Schema ({ + botId: { + type: String, + trim: true, + required: true + }, + botName: { + type: String, + trim: true, + required: true + }, + botType: { + type: String, + trim: true, + required: true + }, + botCategory: { + type: String, + trim: true, + required: true + }, + botDesc: { + type: String, + trim: true, + required: true + }, + botsConfig:Schema.Types.Mixed, + runTimeParams:Schema.Types.Mixed, + masterDetails: { + orgName: { + type: String, + trim: true, + required: false + }, + orgId: { + type: String, + trim: true, + required: false + }, + bgName: { + type: String, + trim: true, + required: false + }, + bgId: { + type: String, + trim: true, + required: false + }, + projectName: { + type: String, + trim: true, + required: false + }, + projectId: { + type: String, + trim: true, + required: false + }, + envName: { + type: String, + trim: true, + required: false + }, + envId: { + type: String, + trim: true, + required: false + } + }, + botLinkedCategory: { + type: String, + trim: true, + required: false + }, + botLinkedSubCategory: { + type: String, + trim: true, + required: false + }, + manualExecutionTime: { + type: Number, + default: 10 + }, + executionCount: { + type: Number, + default: 0 + }, + isBotScheduled: { + type: Boolean, + default: false + }, + botScheduler:{ + cronStartOn: { + type: String, + required: false, + trim: true + }, + cronEndOn: { + type: String, + required: false, + trim: true + }, + cronPattern: { + type: String, + required: false, + trim: true + }, + cronRepeatEvery: { + type: Number, + required: false + }, + cronFrequency: { + type: String, + required: false, + trim: true + }, + cronMinute:{ + type: Number, + required: false, + trim: true + }, + cronHour:{ + type: Number, + required: false + }, + cronWeekDay:{ + type: Number, + required: false + }, + cronDate:{ + type: Number, + required: false + }, + cronMonth:{ + type: String, + required: false, + trim: true + }, + cronYear:{ + type: Number, + required: false + } + }, + cronJobId:{ + type: String, + required: false, + trim: true + }, + createdOn:{ + type: Number, + default: Date.now() + }, + isDeleted: { + type: Boolean, + default: false + }, +}); +BotsSchema.plugin(mongoosePaginate); + + +BotsSchema.statics.createNew = function(botsDetail,callback){ + var botsData = new Bots(botsDetail); + botsData.save(function(err, data) { + if (err) { + logger.error("createNew Failed", err, data); + callback(err,null); + return; + } + callback(null,data); + return; + }); +} +BotsSchema.statics.updateBotsDetail = function(botId,botsDetail,callback){ + Bots.update({botId:botId},{$set:botsDetail},{upsert:false}, function(err, updateBotDetail) { + if (err) { + logger.error(err); + var error = new Error('Internal server error'); + error.status = 500; + return callback(error); + } + return callback(null, updateBotDetail); + }); +}; + +BotsSchema.statics.getBotsList = function(botsQuery,callback){ + botsQuery.queryObj.isDeleted = false; + Bots.paginate(botsQuery.queryObj, botsQuery.options, function(err, botsList) { + if (err) { + logger.error(err); + var error = new Error('Internal server error'); + error.status = 500; + return callback(error); + } + return callback(null, botsList); + }); +}; + +BotsSchema.statics.getBotsById = function(botId,callback){ + Bots.find({botId:botId}, function(err, bots) { + if (err) { + logger.error(err); + var error = new Error('Internal server error'); + error.status = 500; + return callback(error); + }else if(bots.length > 0){ + return callback(null, bots); + }else{ + return callback(null, []); + } + }); +}; + +BotsSchema.statics.getAllBots = function(callback){ + Bots.find({isDeleted:false}, function(err, bots) { + if (err) { + logger.error(err); + var error = new Error('Internal server error'); + error.status = 500; + return callback(error); + }else if(bots.length > 0){ + return callback(null, bots); + }else{ + return callback(null, []); + } + }); +}; + +BotsSchema.statics.removeBotsById = function(botId,callback){ + Bots.remove({botId:botId}, function(err, bots) { + if (err) { + logger.error(err); + var error = new Error('Internal server error'); + error.status = 500; + return callback(error); + }else { + return callback(null, bots); + } + }); +}; + +BotsSchema.statics.removeSoftBotsById = function(botId,callback){ + Bots.update({botId:botId},{$set:{isDeleted:true}}, function(err, bots) { + if (err) { + logger.error(err); + var error = new Error('Internal server error'); + error.status = 500; + return callback(error); + }else { + return callback(null, bots); + } + }); +}; + +BotsSchema.statics.updateBotsExecutionCount = function updateBotsExecutionCount(botId,count,callback) { + Bots.update({ + botId: botId, + }, { + $set: { + executionCount: count + } + }, { + upsert: false + }, function (err, data) { + if (err) { + callback(err, null); + return; + } + callback(null, data); + }); +}; + +BotsSchema.statics.getScheduledBots = function getScheduledBots(callback) { + Bots.find({ + isBotScheduled: true + }, function (err, bots) { + if (err) { + logger.error(err); + return callback(err, null); + } + return callback(null, bots); + }) +} + +BotsSchema.statics.updateCronJobIdByBotId = function updateCronJobIdByBotId(botId, cronJobId, callback) { + Bots.update({ + "_id": new ObjectId(botId), + }, { + $set: { + cronJobId: cronJobId + } + }, { + upsert: false + }, function (err, data) { + if (err) { + callback(err, null); + return; + } + callback(null, data); + }); +}; + +BotsSchema.statics.updateBotsScheduler = function updateBotsScheduler(botId, callback) { + Bots.update({ + "_id": new ObjectId(botId), + }, { + $set: { + isBotBScheduled: false + } + }, { + upsert: false + }, function (err, data) { + if (err) { + callback(err, null); + return; + } + callback(null, data); + }); +}; + +var Bots = mongoose.model('bots', BotsSchema); +module.exports = Bots; diff --git a/server/app/model/classes/tasks/tasks.js b/server/app/model/classes/tasks/tasks.js index 17d65b945..03fb2d04a 100755 --- a/server/app/model/classes/tasks/tasks.js +++ b/server/app/model/classes/tasks/tasks.js @@ -368,31 +368,38 @@ taskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, b } else { self.lastTaskStatus = TASK_STATUS.FAILED; } + var resultTaskExecution = null; + if(taskHistoryData.taskType === TASK_TYPE.JENKINS_TASK){ + resultTaskExecution = { + "actionStatus":self.lastTaskStatus, + "status":self.lastTaskStatus, + "endedOn":self.timestampEnded, + "actionLogId":taskHistory.jenkinsServerId, + "auditTrailConfig.jenkinsBuildNumber":taskHistory.buildNumber, + "auditTrailConfig.jenkinsJobName":taskHistory.jobName + }; + }else{ + resultTaskExecution = { + "actionStatus":self.lastTaskStatus, + "status":self.lastTaskStatus, + "endedOn":self.timestampEnded, + "actionLogId":taskHistory.nodeIdsWithActionLog[0].actionLogId, + "auditTrailConfig.nodeIdsWithActionLog":taskHistory.nodeIdsWithActionLog + }; + } + if(auditTrailId !== null && resultTaskExecution !== null){ + auditTrailService.updateAuditTrail('BOTs',auditTrailId,resultTaskExecution,function(err,auditTrail){ + if (err) { + logger.error("Failed to create or update bots Log: ", err); + } + }); + } self.save(); //updating task history if (taskHistory) { taskHistory.timestampEnded = self.timestampEnded; taskHistory.status = self.lastTaskStatus; - var resultTaskExecution = null; - if(taskHistoryData.taskType === TASK_TYPE.JENKINS_TASK){ - resultTaskExecution = { - "actionStatus":self.lastTaskStatus, - "status":self.lastTaskStatus, - "endedOn":self.timestampEnded, - "actionLogId":taskHistory.jenkinsServerId, - "auditTrailConfig.jenkinsBuildNumber":taskHistory.buildNumber, - "auditTrailConfig.jenkinsJobName":taskHistory.jobName - }; - }else{ - resultTaskExecution = { - "actionStatus":self.lastTaskStatus, - "status":self.lastTaskStatus, - "endedOn":self.timestampEnded, - "actionLogId":taskHistory.nodeIdsWithActionLog[0].actionLogId, - "auditTrailConfig.nodeIdsWithActionLog":taskHistory.nodeIdsWithActionLog - }; - } if (resultData) { if (resultData.instancesResults && resultData.instancesResults.length) { taskHistory.executionResults = resultData.instancesResults; @@ -402,13 +409,6 @@ taskSchema.methods.execute = function(userName, baseUrl, choiceParam, appData, b } } - if(auditTrailId !== null && resultTaskExecution !== null){ - auditTrailService.updateAuditTrail('BOTs',auditTrailId,resultTaskExecution,function(err,auditTrail){ - if (err) { - logger.error("Failed to create or update bot Log: ", err); - } - }); - } taskHistory.save(); } diff --git a/server/app/routes/v1.0/routes.js b/server/app/routes/v1.0/routes.js index 420008cf0..99ae4e9f3 100755 --- a/server/app/routes/v1.0/routes.js +++ b/server/app/routes/v1.0/routes.js @@ -75,6 +75,7 @@ var fileUpload = require('./routes_fileUpload'); var settingWizard = require('./routes_setting_wizard'); var configData = require('./routes_config_data'); var monitors = require('./routes_monitors'); +var bots = require('./routes_bots'); /* * @TODO * Change app to router in internal routes files @@ -187,6 +188,8 @@ module.exports.setRoutes = function(app) { configData.setRoutes(app, sessionVerificationFunc); + bots.setRoutes(app, sessionVerificationFunc); + app.get('/', function(req, res) { res.redirect('/cat3'); diff --git a/server/app/routes/v1.0/routes_audit_trails.js b/server/app/routes/v1.0/routes_audit_trails.js index 4419edd8c..239101dec 100644 --- a/server/app/routes/v1.0/routes_audit_trails.js +++ b/server/app/routes/v1.0/routes_audit_trails.js @@ -47,7 +47,7 @@ module.exports.setRoutes = function(app, sessionVerificationFunc) { }) }); - app.get('/audit-trail/bot-summary', function(req,res){ + app.get('/audit-trail/bots-summary', function(req,res){ auditTrailService.getBOTsSummary(function(err,botSummary){ if(err){ logger.error(err); diff --git a/server/app/routes/v1.0/routes_blueprints.js b/server/app/routes/v1.0/routes_blueprints.js index f0020e1de..5f5da4246 100755 --- a/server/app/routes/v1.0/routes_blueprints.js +++ b/server/app/routes/v1.0/routes_blueprints.js @@ -24,546 +24,390 @@ var credentialcryptography = require('_pr/lib/credentialcryptography'); var fs = require('fs'); var blueprintService = require('_pr/services/blueprintService.js'); var auditTrailService = require('_pr/services/auditTrailService'); - -module.exports.setRoutes = function (app, sessionVerificationFunc) { - app.all('/blueprints/*', sessionVerificationFunc); - - app.get('/blueprints', function (req, res) { - var queryObj = { - serviceDeliveryCheck: req.query.serviceDeliveryCheck === "true" ? true : false, - actionStatus: req.query.actionStatus - } - blueprintService.getAllServiceDeliveryBlueprint(queryObj, function (err, data) { - if (err) { - return res.status(500).send(err); - } else { - return res.status(200).send(data); - } - }) - }); - app.delete('/blueprints/serviceDelivery/:blueprintId', function (req, res) { - blueprintService.deleteServiceDeliveryBlueprint(req.params.blueprintId, function (err, data) { - if (err) { - logger.error("Failed to delete ", err); - res.send(500, errorResponses.db.error); - return; - } - res.send(200, { - message: "deleted" - }); - }); - }); - - - // This post() Not in use - app.post('/blueprints', function (req, res) { - logger.debug("Enter post() for /blueprints"); - //validating if user has permission to save a blueprint - logger.debug('Verifying User permission set'); - var user = req.session.user; - var category = 'blueprints'; - var permissionto = 'create'; - var blueprintType = req.body.blueprintData.blueprintType; - usersDao.haspermission(user.cn, category, permissionto, null, req.session.user.permissionset, function (err, data) { - if (!err) { - logger.debug('Returned from haspermission : ' + data + ' : ' + (data == false)); - if (data == false) { - logger.debug('No permission to ' + permissionto + ' on ' + category); - res.send(401); - - return; - } - } else { - logger.error("Hit and error in haspermission:", err); - res.send(500); - return; - } - if (!req.body.blueprintData.runlist) { - req.body.blueprintData.runlist = []; - } - var blueprintData = { - orgId: req.body.blueprintData.orgId, - bgId: req.body.blueprintData.bgId, - projectId: req.body.blueprintData.projectId, - name: req.body.blueprintData.name, - appUrls: req.body.blueprintData.appUrls, - iconpath: req.body.blueprintData.iconpath, - templateId: req.body.blueprintData.templateId, - templateType: req.body.blueprintData.templateType, - users: req.body.blueprintData.users, - blueprintType: blueprintType, - id: req.body.blueprintData.id - }; - - var dockerData, instanceData, cloudFormationData; - - if (blueprintType === 'docker') { - - dockerData = { - dockerContainerPathsTitle: req.body.blueprintData.dockercontainerpathstitle, - dockerContainerPaths: req.body.blueprintData.dockercontainerpaths, - dockerLaunchParameters: req.body.blueprintData.dockerlaunchparameters, - dockerRepoName: req.body.blueprintData.dockerreponame, - dockerCompose: req.body.blueprintData.dockercompose, - dockerRepoTags: req.body.blueprintData.dockerrepotags, - dockerImageName: req.body.blueprintData.dockerimagename, - }; - blueprintData.dockerData = dockerData; - - } else if (blueprintType === 'instance_launch') { - instanceData = { - keyPairId: req.body.blueprintData.keyPairId, - securityGroupIds: req.body.blueprintData.securityGroupIds, - instanceType: req.body.blueprintData.instanceType, - instanceAmiid: req.body.blueprintData.instanceAmiid, - instanceUsername: 'root', - vpcId: req.body.blueprintData.vpcId, - region: req.body.blueprintData.region, - subnetId: req.body.blueprintData.subnetId, - imageId: req.body.blueprintData.imageId, - cloudProviderType: 'aws', - cloudProviderId: req.body.blueprintData.providerId, - infraManagerType: 'chef', - infraManagerId: req.body.blueprintData.chefServerId, - runlist: req.body.blueprintData.runlist - } - blueprintData.instanceData = instanceData; - } else if (blueprintType === 'aws_cf') { - - cloudFormationData = { - cloudProviderId: req.body.blueprintData.cftProviderId, - infraManagerType: 'chef', - infraManagerId: req.body.blueprintData.chefServerId, - runlist: req.body.blueprintData.runlist, - stackParameters: req.body.blueprintData.cftStackParameters, - //stackName: req.body.blueprintData.stackName, - templateFile: req.body.blueprintData.cftTemplateFile, - region: req.body.blueprintData.region, - //instanceUsername: req.body.blueprintData.cftInstanceUserName - instances: req.body.blueprintData.cftInstances - } - blueprintData.cloudFormationData = cloudFormationData; - } else { - res.send(400, { - message: "Invalid Blueprint Type" - }); - return; - } - - - if (!blueprintData.users || !blueprintData.users.length) { - res.send(400); - return; - } - - Blueprints.createNew(blueprintData, function (err, data) { - if (err) { - logger.error('error occured while saving blueorint', err); - res.send(500, { - message: "DB error" - }); - return; - } - res.send(data); - }); - logger.debug("Exit post() for /blueprints"); - }); - }); - app.get('/blueprints/:blueprintId', function (req, res) { - - blueprintService.getById(req.params.blueprintId, function (err, blueprint) { - if (err == 404) { - res.status(404).send({ - message: "Blueprint not found." - }); - return; - } else if (err) { - res.status(500).send({ - message: "Blueprint fetch failed" - }); - return; - } - - res.status(200).send(blueprint); - }); - - }); - app.get('/blueprints/:blueprintId/blueprintInfo', function (req, res) { - Blueprints.getBlueprintInfoById(req.params.blueprintId, function (err, blueprintInfo) { - if (err) { - res.status(500).send({ - code: 500, - errMessage: "Blueprint Info fetch failed" - }); - return; - } - res.status(200).send(blueprintInfo); - }); - - }); - app.post('/blueprints/:blueprintId/update', function (req, res) { - logger.debug("Enter /blueprints/%s/update", req.params.blueprintId); - - if (req.session.user.rolename === 'Consumer') { - res.send(401); - return; - } - - var blueprintUpdateData = req.body.blueprintUpdateData; - if (!blueprintUpdateData.runlist) { - blueprintUpdateData.runlist = []; - } - - //blueprintUpdateData.runlist.splice(0, 0, 'recipe[ohai]'); - - - Blueprints.getById(req.params.blueprintId, function (err, blueprint) { - if (err) { - logger.error("Failed to get blueprint versions ", err); - res.send(500, errorResponses.db.error); - return; - } - blueprint.update(blueprintUpdateData, function (err, updatedBlueprint) { - if (err) { - logger.error("Failed to update blueprint ", err); - res.send(500, errorResponses.db.error); - return; - } - var latestVersionData = updatedBlueprint.getLatestVersion(); - if (latestVersionData) { - res.send({ - version: latestVersionData.ver - }); - } else { - res.send(200); - } - - - }); - }); - - }); // end app.post('/blueprints/:blueprintId/update' ) - - app.get('/blueprints/:blueprintId/versions/:version', function (req, res) { - logger.debug("Enter /blueprints/%s/versions/%s", req.params.blueprintId, req.params.version); - - Blueprints.getById(req.params.blueprintId, function (err, blueprint) { - if (err) { - logger.error("Failed to get blueprint versions ", err); - res.send(500, errorResponses.db.error); - return; - } - logger.debug(blueprint); - - var versionData = blueprint.getVersionData(req.params.version); - res.send(200, versionData); - - - }); - - }); - - app.get('/blueprints/:blueprintId', function (req, res) { - logger.debug("Enter /blueprints/%s/versions/%s", req.params.blueprintId, req.params.version); - - Blueprints.getById(req.params.blueprintId, function (err, blueprint) { - if (err) { - logger.error("Failed to get blueprint versions ", err); - res.send(500, errorResponses.db.error); - return; - } - logger.debug(blueprint); - - res.send(200, blueprint); - - }); - - }); - - app.delete('/blueprints/:blueprintId', function (req, res) { - logger.debug("Enter /blueprints/delete/%s", req.params.blueprintId); - Blueprints.removeById(req.params.blueprintId, function (err, data) { - if (err) { - logger.error("Failed to delete blueprint ", err); - res.send(500, errorResponses.db.error); - return; - } - res.send(200, { - message: "deleted" - }); - }); - }); - - app.delete('/blueprints', function (req, res) { - var blueprintIds = req.body.blueprints; - logger.debug("Enter /blueprints/delete/%s", req.body.blueprints); - if (blueprintIds.length > 0) - Blueprints.removeByIds(blueprintIds, function (err, data) { - if (err) { - logger.error("Failed to delete blueprint ", err); - res.send(500, errorResponses.db.error); - return; - } - res.send(200, { - message: "deleted" - }); - }); - }); - - app.post('/blueprints/copy', function (req, res) { - var orgid = req.body.orgid; - var buid = req.body.buid; - var projid = req.body.projid; - var bluepirntIds = req.body.blueprints; - if (!orgid || !buid || !projid || !bluepirntIds) { - logger.error("Could not copy blueprint. Required data missing."); - res.send(500, 'Would require a ORG, BU and Project to copy'); - return; - } else { - Blueprints.copyByIds(bluepirntIds, orgid, buid, projid, function (err, data) { - res.status('200').send(data); - return; - }); - - } - }); - - //for testing - app.get('/blueprints/azure/tryssh/:ip', function (req, res) { - var azureCloud = new AzureCloud(); - azureCloud.trysshoninstance('Windows', req.params["ip"], 'testing', 'testing', function (err, data) { - logger.debug('Output:', data); - if (!err) { - logger.debug('about to send response'); - res.send(200); - return; - } else { - res.send(400, { - message: err - }); - return; - } - - }) - }); - - - app.get('/blueprints/:blueprintId/launch', function (req, res) { - logger.debug("Enter /blueprints/%s/launch -- ", req.params.blueprintId); - //verifying if the user has permission - logger.debug('Verifying User permission set for execute.'); - if (!req.query.envId) { - res.send(400, { - "message": "Invalid Environment Id" - }); - return; - } - var user = req.session.user; - var category = 'blueprints'; - var permissionto = 'execute'; - usersDao.haspermission(user.cn, category, permissionto, null, req.session.user.permissionset, function (err, data) { - if (!err) { - logger.debug('Returned from haspermission : launch ' + data + ' , Condition State : ' + (data == false)); - if (data == false) { - logger.debug('No permission to ' + permissionto + ' on ' + category); - res.send(401); - return; - } else { - - Blueprints.getById(req.params.blueprintId, function (err, blueprint) { - if (err) { - logger.error('Failed to getBlueprint. Error = ', err); - res.send(500, errorResponses.db.error); - return; - } - if (!blueprint) { - res.send(404, { - message: "Blueprint Does Not Exist" - }); - return; - } - var stackName = null; - var domainName = null; - var blueprintLaunchCount = 0; - if (blueprint.executionCount) { - blueprintLaunchCount = blueprint.executionCount + 1; - } else { - blueprintLaunchCount = 1; - } - Blueprints.updateBlueprintExecutionCount(blueprint._id, blueprintLaunchCount, function (err, data) { - if (err) { - logger.error("Error while updating Blueprint Execution Count"); - } - }); - if (blueprint.blueprintType === 'aws_cf' || blueprint.blueprintType === 'azure_arm') { - stackName = req.query.stackName; - if (!stackName) { - res.send(400, { - message: "Invalid stack name" - }); - return; - } - } - if (blueprint.domainNameCheck === true) { - domainName = req.query.domainName; - if (!domainName) { - res.send(400, { - message: "Invalid domainName" - }); - return; - } - } - var monitorId = null; - if (req.query.monitorId) { - monitorId = req.query.monitorId; - } - - var launchParams = { - envId: req.query.envId, - ver: req.query.version, - stackName: stackName, - domainName: domainName, - sessionUser: req.session.user.cn, - tagServer: req.query.tagServer, - monitorId: monitorId, - auditTrailId: null - }; - if (blueprint.serviceDeliveryCheck === true) { - var actionObj = { - auditType: 'BOTs', - auditCategory: 'Blueprint', - status: 'running', - action: 'BOTs Blueprint Execution', - actionStatus: 'running', - catUser: req.session.user.cn - }; - var auditTrailObj = { - name: blueprint.name, - type: blueprint.botType, - description: blueprint.shortDesc, - category: blueprint.botCategory, - executionType: blueprint.blueprintType, - manualExecutionTime: blueprint.manualExecutionTime, - nodeIdsWithActionLog: [] - }; - blueprint.envId = req.query.envId; - auditTrailService.insertAuditTrail(blueprint, auditTrailObj, actionObj, function (err, data) { - if (err) { - logger.error(err); - } - launchParams.auditTrailId = data._id; - blueprint.launch(launchParams, function (err, launchData) { - if (err) { - res.status(500).send({ - message: "Server Behaved Unexpectedly" - }); - return; - } - res.status(200).send(launchData) - }); - }); - } else { - blueprint.launch(launchParams, function (err, launchData) { - if (err) { - res.status(500).send({ - message: "Server Behaved Unexpectedly" - }); - return; - } - res.status(200).send(launchData) - }); - } - }); - } - } else { - logger.error("Hit and error in haspermission:", err); - res.send(500); - return; - } - return; - - }); // end haspermission - }); - // List blueprints w.r.t. org,bg and project - /** - * @api {get} /blueprints/organization/:orgId/businessgroup/:bgId/project/:projectId Request List of Blueprints - * @apiName GetBlueprints - * @apiGroup Blueprints - * - * @apiParam {string} orgId Organization unique ID. - * @apiParam {string} bgId BusinessGroup unique ID. - * @apiParam {string} projectId Project unique ID. - * - * - * @apiSuccessExample Success-Response: - * HTTP/1.1 200 OK - * [ - { - "_id": "56fca48a350326691735057b", - "orgId": "46d1da9a-d927-41dc-8e9e-7e926d927537", - "bgId": "7e3500f1-58f9-43e2-b9eb-347b2e4d129d", - "projectId": "b38ccedc-da2c-4e2c-a278-c66333564719", - "name": "Gobinda_WRL", - "templateId": "ubuntu_new", - "templateType": "ami", - "blueprintConfig": { - "_id": "56fca48a350326691735057a", - "infraManagerData": { - "versionsList": [ - { - "runlist": [], - "_id": "56fca48a3503266917350579", - "ver": "0.1" - } - ], - "_id": "56fca48a3503266917350578", - "latestVersion": "0.1" - }, - "infraManagerId": "965cdb20-0b8e-413b-bda6-3877a503549a", - "infraMangerType": "chef", - "cloudProviderData": { - "securityGroupIds": [ - "sg-eeff688b" - ], - "_id": "56fca48a3503266917350577", - "instanceCount": "1", - "instanceOS": "linux", - "imageId": "56fb5a7f9ee332570c311b63", - "subnetId": "subnet-d7df258e", - "vpcId": "vpc-bd815ad8", - "instanceUsername": "root", - "instanceAmiid": "ami-06116566", - "instanceType": "t2.micro", - "keyPairId": "56fb59bd9ee332570c311b31" - }, - "cloudProviderId": "56fb59bd9ee332570c311b30", - "cloudProviderType": "aws" - }, - "blueprintType": "instance_launch", - "__v": 0, - "users": [ - "superadmin" - ], - "appUrls": [] - } - ] - * - * @apiError Either orgId or bgId or projectId missing. - * @apiError Blueprint fetch failed. - * - * @apiErrorExample Error-Response: - * HTTP/1.1 400 Bad Request - * { - * "error": "Either orgId or bgId or projectId missing." - * } - * @apiErrorExample Error-Response: - * HTTP/1.1 500 Internal Server Error - * { - * "error": "Blueprint fetch failed." - * } - **/ - - +var bots = require('_pr/model/bots/bots.js'); +var botsService = require('_pr/services/botsService.js'); + +module.exports.setRoutes = function(app, sessionVerificationFunc) { + app.all('/blueprints/*', sessionVerificationFunc); + + app.get('/blueprints', function(req, res) { + var queryObj = { + serviceDeliveryCheck : req.query.serviceDeliveryCheck === "true" ? true:false, + actionStatus:req.query.actionStatus + } + blueprintService.getAllServiceDeliveryBlueprint(queryObj, function(err,data){ + if (err) { + return res.status(500).send(err); + } else { + return res.status(200).send(data); + } + }) + }); + app.delete('/blueprints/serviceDelivery/:blueprintId', function(req, res) { + blueprintService.deleteServiceDeliveryBlueprint(req.params.blueprintId, function(err, data) { + if (err) { + logger.error("Failed to delete ", err); + res.send(500, errorResponses.db.error); + return; + } + res.send(200, { + message: "deleted" + }); + }); + }); + + + // This post() Not in use + app.post('/blueprints', function(req, res) { + logger.debug("Enter post() for /blueprints"); + //validating if user has permission to save a blueprint + logger.debug('Verifying User permission set'); + var user = req.session.user; + var category = 'blueprints'; + var permissionto = 'create'; + var blueprintType = req.body.blueprintData.blueprintType; + usersDao.haspermission(user.cn, category, permissionto, null, req.session.user.permissionset, function(err, data) { + if (!err) { + logger.debug('Returned from haspermission : ' + data + ' : ' + (data == false)); + if (data == false) { + logger.debug('No permission to ' + permissionto + ' on ' + category); + res.send(401); + + return; + } + } else { + logger.error("Hit and error in haspermission:", err); + res.send(500); + return; + } + if (!req.body.blueprintData.runlist) { + req.body.blueprintData.runlist = []; + } + var blueprintData = { + orgId: req.body.blueprintData.orgId, + bgId: req.body.blueprintData.bgId, + projectId: req.body.blueprintData.projectId, + name: req.body.blueprintData.name, + appUrls: req.body.blueprintData.appUrls, + iconpath: req.body.blueprintData.iconpath, + templateId: req.body.blueprintData.templateId, + templateType: req.body.blueprintData.templateType, + users: req.body.blueprintData.users, + blueprintType: blueprintType, + id:req.body.blueprintData.id + }; + + var dockerData, instanceData, cloudFormationData; + + if (blueprintType === 'docker') { + + dockerData = { + dockerContainerPathsTitle: req.body.blueprintData.dockercontainerpathstitle, + dockerContainerPaths: req.body.blueprintData.dockercontainerpaths, + dockerLaunchParameters: req.body.blueprintData.dockerlaunchparameters, + dockerRepoName: req.body.blueprintData.dockerreponame, + dockerCompose: req.body.blueprintData.dockercompose, + dockerRepoTags: req.body.blueprintData.dockerrepotags, + dockerImageName: req.body.blueprintData.dockerimagename, + }; + blueprintData.dockerData = dockerData; + + } else if (blueprintType === 'instance_launch') { + instanceData = { + keyPairId: req.body.blueprintData.keyPairId, + securityGroupIds: req.body.blueprintData.securityGroupIds, + instanceType: req.body.blueprintData.instanceType, + instanceAmiid: req.body.blueprintData.instanceAmiid, + instanceUsername: 'root', + vpcId: req.body.blueprintData.vpcId, + region: req.body.blueprintData.region, + subnetId: req.body.blueprintData.subnetId, + imageId: req.body.blueprintData.imageId, + cloudProviderType: 'aws', + cloudProviderId: req.body.blueprintData.providerId, + infraManagerType: 'chef', + infraManagerId: req.body.blueprintData.chefServerId, + runlist: req.body.blueprintData.runlist + } + blueprintData.instanceData = instanceData; + } else if (blueprintType === 'aws_cf') { + + cloudFormationData = { + cloudProviderId: req.body.blueprintData.cftProviderId, + infraManagerType: 'chef', + infraManagerId: req.body.blueprintData.chefServerId, + runlist: req.body.blueprintData.runlist, + stackParameters: req.body.blueprintData.cftStackParameters, + //stackName: req.body.blueprintData.stackName, + templateFile: req.body.blueprintData.cftTemplateFile, + region: req.body.blueprintData.region, + //instanceUsername: req.body.blueprintData.cftInstanceUserName + instances: req.body.blueprintData.cftInstances + } + blueprintData.cloudFormationData = cloudFormationData; + } else { + res.send(400, { + message: "Invalid Blueprint Type" + }); + return; + } + + + if (!blueprintData.users || !blueprintData.users.length) { + res.send(400); + return; + } + + Blueprints.createNew(blueprintData, function(err, data) { + if (err) { + logger.error('error occured while saving blueorint', err); + res.send(500, { + message: "DB error" + }); + return; + } + res.send(data); + }); + logger.debug("Exit post() for /blueprints"); + }); + }); + app.get('/blueprints/:blueprintId', function(req, res) { + + blueprintService.getById(req.params.blueprintId, function(err, blueprint) { + if(err == 404){ + res.status(404).send({ + message: "Blueprint not found." + }); + return; + }else if (err) { + res.status(500).send({ + message: "Blueprint fetch failed" + }); + return; + } + + res.status(200).send(blueprint); + }); + + }); + app.get('/blueprints/:blueprintId/blueprintInfo', function(req, res) { + Blueprints.getBlueprintInfoById(req.params.blueprintId, function(err, blueprintInfo) { + if (err) { + res.status(500).send({ + code: 500, + errMessage: "Blueprint Info fetch failed" + }); + return; + } + res.status(200).send(blueprintInfo); + }); + + }); + app.post('/blueprints/:blueprintId/update', function(req, res) { + logger.debug("Enter /blueprints/%s/update", req.params.blueprintId); + + if (req.session.user.rolename === 'Consumer') { + res.send(401); + return; + } + + var blueprintUpdateData = req.body.blueprintUpdateData; + if (!blueprintUpdateData.runlist) { + blueprintUpdateData.runlist = []; + } + + //blueprintUpdateData.runlist.splice(0, 0, 'recipe[ohai]'); + + + Blueprints.getById(req.params.blueprintId, function(err, blueprint) { + if (err) { + logger.error("Failed to get blueprint versions ", err); + res.send(500, errorResponses.db.error); + return; + } + blueprint.update(blueprintUpdateData, function(err, updatedBlueprint) { + if (err) { + logger.error("Failed to update blueprint ", err); + res.send(500, errorResponses.db.error); + return; + } + if(blueprintUpdateData.serviceDeliveryCheck === true){ + Blueprints.getById(req.params.blueprintId, function(err, blueprintData) { + if (err) { + logger.error("Failed to get blueprint ", err); + return; + } else { + botsService.createNew(blueprintData, 'Blueprint', blueprintUpdateData.blueprintType, 'edit', function (err, data) { + logger.error("Error in creating bots entry." + err); + }); + } + }); + }else{ + botsService.removeSoftBotsById(req.params.blueprintId, function (err, data) { + if (err) { + logger.error("Error in updating bots entry." + err); + } + }); + } + var latestVersionData = updatedBlueprint.getLatestVersion(); + if (latestVersionData) { + res.send({ + version: latestVersionData.ver + }); + } else { + res.send(200); + } + + }); + }); + + }); // end app.post('/blueprints/:blueprintId/update' ) + + app.get('/blueprints/:blueprintId/versions/:version', function(req, res) { + logger.debug("Enter /blueprints/%s/versions/%s", req.params.blueprintId, req.params.version); + + Blueprints.getById(req.params.blueprintId, function(err, blueprint) { + if (err) { + logger.error("Failed to get blueprint versions ", err); + res.send(500, errorResponses.db.error); + return; + } + logger.debug(blueprint); + + var versionData = blueprint.getVersionData(req.params.version); + res.send(200, versionData); + + + }); + + }); + + app.get('/blueprints/:blueprintId', function(req, res) { + logger.debug("Enter /blueprints/%s/versions/%s", req.params.blueprintId, req.params.version); + + Blueprints.getById(req.params.blueprintId, function(err, blueprint) { + if (err) { + logger.error("Failed to get blueprint versions ", err); + res.send(500, errorResponses.db.error); + return; + } + logger.debug(blueprint); + + res.send(200, blueprint); + + }); + + }); + + app.delete('/blueprints/:blueprintId', function(req, res) { + logger.debug("Enter /blueprints/delete/%s", req.params.blueprintId); + Blueprints.removeById(req.params.blueprintId, function(err, data) { + if (err) { + logger.error("Failed to delete blueprint ", err); + res.send(500, errorResponses.db.error); + return; + } + bots.removeBotsById(req.params.blueprintId,function(err,botsData){ + if(err){ + logger.error("Failed to delete Bots ", err); + } + }); + auditTrailService.removeAuditTrailById(req.params.taskId,function(err,auditTrailData){ + if(err){ + logger.error("Failed to delete Audit Trail ", err); + } + }); + res.send(200, { + message: "deleted" + }); + }); + }); + + app.delete('/blueprints', function(req, res) { + var blueprintIds = req.body.blueprints; + logger.debug("Enter /blueprints/delete/%s", req.body.blueprints); + if(blueprintIds.length > 0) + Blueprints.removeByIds(blueprintIds, function(err, data) { + if (err) { + logger.error("Failed to delete blueprint ", err); + res.send(500, errorResponses.db.error); + return; + } + res.send(200, { + message: "deleted" + }); + }); + }); + + app.post('/blueprints/copy',function(req,res){ + var orgid = req.body.orgid; + var buid = req.body.buid; + var projid = req.body.projid; + var bluepirntIds = req.body.blueprints; + if(!orgid || !buid || !projid || !bluepirntIds){ + logger.error("Could not copy blueprint. Required data missing."); + res.send(500, 'Would require a ORG, BU and Project to copy'); + return; + }else{ + Blueprints.copyByIds(bluepirntIds,orgid,buid,projid,function(err,data){ + res.status('200').send(data); + return; + }); + + } + }); + + //for testing + app.get('/blueprints/azure/tryssh/:ip', function(req, res) { + var azureCloud = new AzureCloud(); + azureCloud.trysshoninstance('Windows', req.params["ip"], 'testing', 'testing', function(err, data) { + logger.debug('Output:', data); + if (!err) { + logger.debug('about to send response'); + res.send(200); + return; + } else { + res.send(400, { + message: err + }); + return; + } + + }) + }); + + app.get('/blueprints/:blueprintId/launch', function(req, res) { + logger.debug("Enter /blueprints/%s/launch -- ", req.params.blueprintId); + if (!req.query.envId) { + res.send(400, { + "message": "Invalid Environment Id" + }); + return; + } + var reqBody = { + userName:req.session.user.cn, + category:"blueprints", + permissionTo:"execute", + permissionSet:req.session.user.permissionset, + envId:req.query.envId, + monitorId:req.query.monitorId, + domainName:req.query.domainName, + stackName:req.query.stackName, + version:req.query.version, + tagServer:req.query.tagServer + } + blueprintService.launch(req.params.blueprintId,reqBody,function(err,data){ + if (err) { + res.status(500).send({ + message: "Server Behaved Unexpectedly" + }); + return; + }else{ + res.status(200).send(data); + return; + } + }); + }); app.get('/blueprints/organization/:orgId/businessgroup/:bgId/project/:projectId', function (req, res) { var orgId = req.params.orgId; var bgId = req.params.bgId; @@ -590,4 +434,4 @@ module.exports.setRoutes = function (app, sessionVerificationFunc) { res.status(200).send(blueprints); }); }); -}; \ No newline at end of file +}; diff --git a/server/app/routes/v1.0/routes_bots.js b/server/app/routes/v1.0/routes_bots.js new file mode 100644 index 000000000..4a741d0db --- /dev/null +++ b/server/app/routes/v1.0/routes_bots.js @@ -0,0 +1,128 @@ +/* + Copyright [2016] [Relevance Lab] + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +// The file contains all the end points for AppDeploy + +var logger = require('_pr/logger')(module); +var botsService = require('_pr/services/botsService.js'); +var appConfig = require('_pr/config'); +var Cryptography = require('_pr/lib/utils/cryptography'); + + +module.exports.setRoutes = function(app, sessionVerificationFunc) { + app.all('/bots/*', sessionVerificationFunc); + + app.get('/bots',function(req,res){ + var actionStatus = null; + if(req.query.actionStatus && req.query.actionStatus !== null){ + actionStatus = req.query.actionStatus; + } + botsService.getBotsList(req.query,actionStatus, function(err,data){ + if (err) { + return res.status(500).send(err); + } else { + return res.status(200).send(data); + } + }) + }); + + + app.delete('/bots/:botId',function(req,res){ + botsService.removeSoftBotsById(req.params.botId, function(err,data){ + if (err) { + return res.status(500).send(err); + } else { + return res.status(200).send(data); + } + }) + }); + + app.get('/bots/:botId/bots-history',function(req,res){ + botsService.getBotsHistory(req.params.botId, function(err,data){ + if (err) { + return res.status(500).send(err); + } else { + return res.status(200).send(data); + } + }) + }); + + app.post('/bots/:botId/execute',function(req,res){ + var reqBody = null; + if(req.body.category && req.body.category ==='Blueprints') { + if (!req.body.envId) { + res.send(400, { + "message": "Invalid Environment Id" + }); + return; + } + reqBody = { + userName: req.session.user.cn, + category: "blueprints", + permissionTo: "execute", + permissionSet: req.session.user.permissionset, + envId: req.body.envId, + monitorId: req.body.monitorId, + domainName: req.body.domainName, + stackName: req.body.stackName, + version: req.body.version, + tagServer: req.body.tagServer + } + }else{ + reqBody = { + userName: req.session.user.cn, + hostProtocol: req.protocol + '://' + req.get('host'), + choiceParam: req.body.choiceParam, + appData: req.body.appData, + tagServer: req.body.tagServer + } + var paramOptions = { + cookbookAttributes: req.body.cookbookAttributes, + scriptParams: req.body.scriptParams + }; + + 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; + } + reqBody.paramOptions=paramOptions; + } + if(reqBody !== null) { + botsService.executeBots(req.params.botId, reqBody, function (err, data) { + if (err) { + return res.status(500).send(err); + } else { + return res.status(200).send(data); + } + }) + } + }); + + app.put('/bots/:botId/scheduler',function(req,res){ + botsService.updateBotsScheduler(req.params.botId,req.body, function(err,data){ + if (err) { + return res.status(500).send(err); + } else { + return res.status(200).send(data); + } + }) + }); + +}; \ No newline at end of file diff --git a/server/app/routes/v1.0/routes_config_data.js b/server/app/routes/v1.0/routes_config_data.js index 1c6b79643..ceddfadd7 100644 --- a/server/app/routes/v1.0/routes_config_data.js +++ b/server/app/routes/v1.0/routes_config_data.js @@ -29,7 +29,7 @@ module.exports.setRoutes = function(app, sessionVerification) { }); // Bot Type List - app.get('/config-data/bot-type', function(req, res) { + app.get('/config-data/bots-type', function(req, res) { var botTypeList = appConfig.botTypeList; res.send(botTypeList); }); diff --git a/server/app/routes/v1.0/routes_organizations.js b/server/app/routes/v1.0/routes_organizations.js index 0099bed0d..0a852c9eb 100755 --- a/server/app/routes/v1.0/routes_organizations.js +++ b/server/app/routes/v1.0/routes_organizations.js @@ -54,6 +54,7 @@ var compositeBlueprintModel = require('_pr/model/composite-blueprints/composite- var Cryptography = require('_pr/lib/utils/cryptography'); var monitorsModel = require('_pr/model/monitors/monitors.js'); var catalystSync = require('_pr/cronjobs/catalyst-scheduler/catalystScheduler.js'); +var botsService = require('_pr/services/botsService.js'); module.exports.setRoutes = function(app, sessionVerification) { /* @@ -666,7 +667,7 @@ module.exports.setRoutes = function(app, sessionVerification) { // }); // return; // } - Blueprints.createNew(blueprintData, function(err, data) { + Blueprints.createNew(blueprintData, function(err, bluePrintData) { if (err) { logger.error('error occured while saving blueorint', err); res.status(500).send({ @@ -674,7 +675,26 @@ module.exports.setRoutes = function(app, sessionVerification) { }); return; } - + if(bluePrintData.serviceDeliveryCheck === true){ + masterUtil.getParticularProject(projectId, function(err, project) { + if (err) { + logger.error(err); + } else if (project.length > 0) { + bluePrintData.orgName = project[0].orgname; + bluePrintData.bgName = project[0].productgroupname; + bluePrintData.projectName = project[0].projectname; + botsService.createOrUpdateBots(bluePrintData, 'Blueprint', blueprintType, function (err, botsData) { + if(err) { + logger.error("Error in creating bots entry. " + err); + }else{ + logger.debug("Successfully added data for Bots.") + } + }); + } else { + logger.debug("Unable to find Project Information from project id:"); + } + }); + } res.send(data); }); @@ -1020,6 +1040,13 @@ module.exports.setRoutes = function(app, sessionVerification) { catalystSync.executeSerialScheduledTasks(); } }; + if(task.serviceDeliveryCheck === true){ + botsService.createOrUpdateBots(task,'Task',task.taskType,function(err,data){ + if(err) { + logger.error("Error in creating bots entry." + err); + } + }); + } res.send(task); logger.debug("Exit post() for /organizations/%s/businessGroups/%s/projects/%s/environments/%s/tasks", req.params.orgId, req.params.bgId, req.params.projectId, req.params.environments); }); @@ -1040,6 +1067,13 @@ module.exports.setRoutes = function(app, sessionVerification) { } }; + if(task.serviceDeliveryCheck === true){ + botsService.createOrUpdateBots(task,'Task',task.taskType,function(err,data){ + if(err) { + logger.error("Error in creating bots entry." + err); + } + }); + } res.send(task); logger.debug("Exit post() for /organizations/%s/businessGroups/%s/projects/%s/environments/%s/tasks", req.params.orgId, req.params.bgId, req.params.projectId, req.params.environments); }); diff --git a/server/app/routes/v1.0/routes_tasks.js b/server/app/routes/v1.0/routes_tasks.js index b8b48a41e..daa1cdffa 100755 --- a/server/app/routes/v1.0/routes_tasks.js +++ b/server/app/routes/v1.0/routes_tasks.js @@ -29,12 +29,13 @@ var apiUtil = require('_pr/lib/utils/apiUtil.js'); var Cryptography = require('_pr/lib/utils/cryptography'); var schedulerService = require('_pr/services/schedulerService'); var catalystSync = require('_pr/cronjobs/catalyst-scheduler/catalystScheduler.js'); - - +var botsService = require('_pr/services/botsService.js'); +var auditTrailService = require('_pr/services/auditTrailService.js'); +var cronTab = require('node-crontab'); var appConfig = require('_pr/config'); var uuid = require('node-uuid'); -var fileIo = require('_pr/lib/utils/fileio'); + module.exports.setRoutes = function(app, sessionVerification) { @@ -111,7 +112,6 @@ module.exports.setRoutes = function(app, sessionVerification) { app.post('/tasks/:taskId/run', function(req, res) { - var taskId = req.params.taskId; var user = req.session.user.cn; var hostProtocol = req.protocol + '://' + req.get('host'); @@ -184,6 +184,16 @@ module.exports.setRoutes = function(app, sessionVerification) { logger.error("Failed to remove history: ", err); } }); + botsService.removeBotsById(req.params.taskId,function(err,botsData){ + if(err){ + logger.error("Failed to delete Bots ", err); + } + }); + auditTrailService.removeAuditTrailById(req.params.taskId,function(err,auditTrailData){ + if(err){ + logger.error("Failed to delete Audit Trail ", err); + } + }); res.send({ deleteCount: deleteCount }); @@ -520,6 +530,8 @@ module.exports.setRoutes = function(app, sessionVerification) { if(taskData.taskScheduler && taskData.taskScheduler !== null && Object.keys(taskData.taskScheduler).length !== 0) { taskData.taskScheduler = apiUtil.createCronJobPattern(taskData.taskScheduler); taskData.isTaskScheduled = true; + }else{ + taskData.isTaskScheduled = false; } if(taskData.manualExecutionTime && taskData.manualExecutionTime !== null){ taskData.manualExecutionTime = parseInt(taskData.manualExecutionTime); @@ -553,7 +565,30 @@ module.exports.setRoutes = function(app, sessionVerification) { }else{ catalystSync.executeSerialScheduledTasks(); } - }; + }else if(scriptTask.cronJobId && scriptTask.cronJobId !== null){ + cronTab.cancelJob(scriptTask.cronJobId); + }else{ + logger.debug("There is no cron job associated with Task "); + } + if(taskData.serviceDeliveryCheck === true) { + Tasks.getTaskById(req.params.taskId, function (err, task) { + if (err) { + logger.error(err); + } else { + botsService.createOrUpdateBots(task, 'Task', task.taskType, function (err, data) { + if (err) { + logger.error("Error in creating bots entry." + err); + } + }); + } + }); + }else{ + botsService.removeSoftBotsById(req.params.taskId, function (err, data) { + if (err) { + logger.error("Error in updating bots entry." + err); + } + }); + } res.send({ updateCount: updateCount }); @@ -575,13 +610,29 @@ module.exports.setRoutes = function(app, sessionVerification) { return; } if (updateCount) { - if(taskData.isTaskScheduled === true){ - if(taskData.executionOrder === 'PARALLEL'){ - catalystSync.executeParallelScheduledTasks(); + Tasks.getTaskById(req.params.taskId, function (err, task) { + if (err) { + logger.error(err); + } + if (task.isTaskScheduled === true) { + if (taskData.executionOrder === 'PARALLEL') { + catalystSync.executeParallelScheduledTasks(); + } else { + catalystSync.executeSerialScheduledTasks(); + } + }else if(task.cronJobId && task.cronJobId !== null){ + cronTab.cancelJob(task.cronJobId); }else{ - catalystSync.executeSerialScheduledTasks(); + logger.debug("There is no cron job associated with Task "); + } + if (task.serviceDeliveryCheck === true) { + botsService.createOrUpdateBots(task, 'Task', task.taskType, function (err, data) { + if (err) { + logger.error("Error in creating bots entry." + err); + } + }); } - }; + }) res.send({ updateCount: updateCount }); diff --git a/server/app/services/auditTrailService.js b/server/app/services/auditTrailService.js index be0df8c7e..1aafa8f3e 100644 --- a/server/app/services/auditTrailService.js +++ b/server/app/services/auditTrailService.js @@ -19,8 +19,7 @@ var instanceAuditTrail = require('_pr/model/audit-trail/instance-audit-trail.js' var botAuditTrail = require('_pr/model/audit-trail/bot-audit-trail.js'); var containerAuditTrail = require('_pr/model/audit-trail/container-audit-trail.js'); var auditTrail = require('_pr/model/audit-trail/audit-trail.js'); -var blueprints = null; -var tasks = null; +var bots = require('_pr/model/bots/bots.js');; const errorType = 'auditTrailService'; @@ -176,26 +175,13 @@ auditTrailService.getAuditTrailActionLogs = function getAuditTrailActionLogs(act auditTrailService.getBOTsSummary = function getBOTsSummary(callback){ async.parallel({ totalNoOfBots: function(callback){ - blueprints = require('_pr/model/blueprint'); - tasks = require('_pr/model/classes/tasks/tasks.js'); - async.parallel({ - botsTask:function(callback){ - tasks.getAllServiceDeliveryTask('true',callback); - }, - botsBlueprint:function(callback){ - blueprints.getAllServiceDeliveryBlueprint('true',callback); - } - },function(err,results){ + bots.getAllBots(function(err,botsList){ if(err){ - logger.error(err); callback(err,null); - return; + }else { + callback(null, botsList.length); } - var totalNoOfBots = results.botsTask.length + results.botsBlueprint.length; - callback(null,totalNoOfBots); - return; - }) - + }); }, totalNoOfSuccessBots: function(callback){ var query={ @@ -205,8 +191,9 @@ auditTrailService.getBOTsSummary = function getBOTsSummary(callback){ auditTrail.getAuditTrails(query,function(err,data){ if(err){ callback(err,null); + }else { + callback(null, data.length); } - callback(null,data.length); }); }, @@ -218,8 +205,9 @@ auditTrailService.getBOTsSummary = function getBOTsSummary(callback){ auditTrail.getAuditTrails(query,function(err,data){ if(err){ callback(err,null); + }else { + callback(null, data.length); } - callback(null,data.length); }); }, @@ -258,8 +246,9 @@ auditTrailService.getBOTsSummary = function getBOTsSummary(callback){ auditTrail.getAuditTrails(query,function(err,data){ if(err){ callback(err,null); + }else { + callback(null, data.length); } - callback(null,data.length); }); } @@ -275,6 +264,50 @@ auditTrailService.getBOTsSummary = function getBOTsSummary(callback){ }) } +auditTrailService.getBotsAuditTrailHistory = function getBotsAuditTrailHistory(botId,callback){ + var query={ + auditType:'BOTs', + auditId:botId + }; + auditTrail.getAuditTrails(query,function(err,data){ + if(err){ + callback(err,null); + }else { + callback(null, data); + } + }); +} + +auditTrailService.softRemoveAuditTrailById = function softRemoveAuditTrailById(auditId,callback){ + auditTrail.softRemoveAuditTrails(auditId,function(err,data){ + if(err){ + return callback(err,null); + }else { + return callback(null, data); + } + }); +} + +auditTrailService.updateSoftRemoveAuditTrailById = function updateSoftRemoveAuditTrailById(auditId,callback){ + auditTrail.updateSoftRemoveAuditTrails(auditId,function(err,data){ + if(err){ + return callback(err,null); + }else { + return callback(null, data); + } + }); +} + +auditTrailService.removeAuditTrailById = function removeAuditTrailById(auditId,callback){ + auditTrail.removeAuditTrails({auditId:auditId},function(err,data){ + if(err){ + return callback(err,null); + }else { + return callback(null, data); + } + }); +} + function getExecutionTime(endTime,startTime){ var executionTimeInMS = endTime-startTime; diff --git a/server/app/services/blueprintService.js b/server/app/services/blueprintService.js index 663b35315..cc9370839 100644 --- a/server/app/services/blueprintService.js +++ b/server/app/services/blueprintService.js @@ -31,6 +31,10 @@ var vmImageDao = require('_pr/model/classes/masters/vmImage.js'); var Blueprints = require('_pr/model/blueprint'); var AWSKeyPair = require('_pr/model/classes/masters/cloudprovider/keyPair.js'); var auditTrail = require('_pr/model/audit-trail/audit-trail.js'); +var usersDao = require('_pr/model/users.js'); +var auditTrailService = require('_pr/services/auditTrailService'); +var bots = require('_pr/model/bots/bots.js'); +var botsService = require('_pr/services/botsService.js'); @@ -77,7 +81,128 @@ blueprintService.deleteServiceDeliveryBlueprint = function deleteServiceDelivery Blueprints.removeServiceDeliveryBlueprints(blueprintId, next); }, function (deleteTaskCheck, next) { - auditTrail.removeAuditTrails({auditId:blueprintId},next); + auditTrail.softRemoveAuditTrails({auditId:blueprintId},next); + } + ],function (err, results) { + if (err) { + callback(err, null); + return; + } + callback(null, results); + return; + }); +}; + +blueprintService.launch = function launch(blueprintId,reqBody, callback) { + async.waterfall([ + function (next) { + usersDao.haspermission(reqBody.userName, reqBody.category, reqBody.permissionTo, null, reqBody.permissionSet,next); + }, + function (launchPermission, next) { + if(launchPermission === true){ + Blueprints.getById(blueprintId,next); + }else{ + logger.debug('No permission to ' + reqBody.permissionTo + ' on ' + reqBody.category); + next({errCode:401,errMsg:'No permission to ' + reqBody.permissionTo + ' on ' + reqBody.category},null); + } + }, + function(blueprint,next){ + if(blueprint){ + var stackName = null,domainName = null,monitorId = null,blueprintLaunchCount = 0; + if(blueprint.executionCount) { + blueprintLaunchCount = blueprint.executionCount + 1; + }else{ + blueprintLaunchCount = 1; + } + Blueprints.updateBlueprintExecutionCount(blueprint._id,blueprintLaunchCount,function(err,data){ + if(err){ + logger.error("Error while updating Blueprint Execution Count"); + } + }); + if (blueprint.blueprintType === 'aws_cf' || blueprint.blueprintType === 'azure_arm') { + stackName = reqBody.stackName; + if (!stackName) { + next({errCode:400,errMsg:"Invalid stack name"},null); + } + } + if(blueprint.domainNameCheck === true) { + domainName = reqBody.domainName; + if (!domainName) { + next({errCode:400,errMsg:"Invalid Domain name"},null); + } + } + if (reqBody.monitorId && reqBody.monitorId !== null) { + monitorId = reqBody.monitorId; + } + if(blueprint.serviceDeliveryCheck === true){ + var actionObj={ + auditType:'BOTs', + auditCategory:'Blueprint', + status:'running', + action:'BOTs Blueprint Execution', + actionStatus:'running', + catUser:reqBody.userName + }; + var auditTrailObj = { + name:blueprint.name, + type:blueprint.botType, + description:blueprint.shortDesc, + category:blueprint.botCategory, + executionType:blueprint.blueprintType, + manualExecutionTime:blueprint.manualExecutionTime, + nodeIdsWithActionLog:[] + }; + blueprint.envId= reqBody.envId; + bots.getBotsById(blueprint._id,function(err,botData){ + if(err){ + logger.error(err); + }else if(botData.length > 0){ + var botExecutionCount = botData[0].executionCount + 1; + bots.updateBotsExecutionCount(blueprint._id,botExecutionCount,function(err,data){ + if(err){ + logger.error("Error while updating Bot Execution Count"); + } + }); + bots.updateBotsDetail(blueprint._id,{runTimeParams:reqBody},function(err,data){ + if(err){ + logger.error("Error while updating Bots Configuration"); + } + }); + }else{ + logger.debug("There is no Bots Data present in DB"); + } + }); + auditTrailService.insertAuditTrail(blueprint,auditTrailObj,actionObj,function(err,data){ + if(err){ + logger.error(err); + } + blueprint.launch({ + envId: reqBody.envId, + ver: reqBody.version, + stackName: stackName, + domainName: domainName, + sessionUser: reqBody.userName, + tagServer: reqBody.tagServer, + monitorId: monitorId, + auditTrailId: data._id + },next); + }); + }else{ + blueprint.launch({ + envId: reqBody.envId, + ver: reqBody.version, + stackName: stackName, + domainName: domainName, + sessionUser: reqBody.userName, + tagServer: reqBody.tagServer, + monitorId: monitorId, + auditTrailId: null + },next); + } + }else{ + logger.debug("Blueprint Does Not Exist"); + next({errCode:404,errMsg:"Blueprint Does Not Exist"},null); + } } ],function (err, results) { if (err) { diff --git a/server/app/services/botsService.js b/server/app/services/botsService.js new file mode 100644 index 000000000..8dbe63bf6 --- /dev/null +++ b/server/app/services/botsService.js @@ -0,0 +1,274 @@ + +/* + Copyright [2016] [Relevance Lab] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +var logger = require('_pr/logger')(module); +var bots = require('_pr/model/bots/bots.js'); +var async = require("async"); +var apiUtil = require('_pr/lib/utils/apiUtil.js'); +var taskService = require('_pr/services/taskService.js'); +var auditTrailService = require('_pr/services/auditTrailService.js'); +var blueprintService = require('_pr/services/blueprintService.js'); +var auditTrail = require('_pr/model/audit-trail/audit-trail.js'); +var catalystSync = require('_pr/cronjobs/catalyst-scheduler/catalystScheduler.js'); +var cronTab = require('node-crontab'); + +const errorType = 'botsService'; + +var botsService = module.exports = {}; + +botsService.createOrUpdateBots = function createOrUpdateBots(botsDetail,linkedCategory,linkedSubCategory,callback) { + logger.debug("In createOrUpdateBots...."); + var botsObj = { + botId: botsDetail._id, + botName:botsDetail.name, + botType: botsDetail.botType, + botCategory: botsDetail.botCategory, + botDesc: botsDetail.shortDesc, + masterDetails:{ + orgId: botsDetail.orgId, + orgName: botsDetail.orgName, + bgId: botsDetail.bgId, + bgName: botsDetail.bgName, + projectId: botsDetail.projectId, + projectName: botsDetail.projectName, + envId: botsDetail.envId ? botsDetail.envId : null, + envName: botsDetail.envName?botsDetail.envName: null + }, + botConfig:botsDetail.taskConfig ? botsDetail.taskConfig : null, + botLinkedCategory: linkedCategory, + botLinkedSubCategory:linkedSubCategory, + manualExecutionTime:botsDetail.manualExecutionTime, + createdOn: new Date().getTime() + }; + bots.getBotsById(botsDetail._id,function(err,data){ + if(err){ + callback(err,null); + return; + }else if(data.length === 0){ + bots.createNew(botsObj, function (err, saveBotsData) { + if (err) { + logger.error(err); + callback(err, null); + return; + } + callback(null, saveBotsData); + return; + }) + }else{ + botsObj.isDeleted = false; + bots.updateBotsDetail(botsObj.botId,botsObj,function(err,updateBotsData){ + if(err){ + logger.error(err); + callback(err,null); + return; + } + auditTrailService.updateSoftRemoveAuditTrailById(botsObj.botId,function(err,data){ + if(err){ + logger.error("Error in updating soft audit Trails"); + } + }) + callback(null,updateBotsData); + return; + }); + } + }); +} + +botsService.updateBotsScheduler = function updateBotsScheduler(botId,botObj,callback) { + if(botObj.botScheduler && botObj.botScheduler !== null && Object.keys(botObj.botScheduler).length !== 0) { + botObj.botScheduler = apiUtil.createCronJobPattern(botObj.botScheduler); + } + bots.updateBotsDetail(botId,botObj,function(err,data){ + if(err){ + logger.error(err); + callback(err,null); + return; + }else { + bots.getBotsById(botId, function (err, botsData) { + if (err) { + logger.error(err); + } else if(botData.length > 0){ + if (botsData[0].isBotScheduled === true) { + catalystSync.executeScheduledBots(); + } else if (botsData[0].cronJobId && botsData[0].cronJobId !== null) { + cronTab.cancelJob(botsData[0].cronJobId); + } else { + logger.debug("There is no cron job associated with Bot "); + } + } else{ + logger.debug("There is no Bots "); + } + }); + callback(null, data); + return; + } + }); +} + +botsService.getBotsList = function getBotsList(botsQuery,actionStatus,callback) { + var reqData = {}; + async.waterfall([ + function(next) { + apiUtil.paginationRequest(botsQuery, 'bots', next); + }, + function(paginationReq, next) { + paginationReq['searchColumns'] = ['botName', 'botType', 'botCategory', 'botLinkedCategory','botLinkedSubCategory', 'masterDetails.orgName', 'masterDetails.bgName', 'masterDetails.projectName', 'masterDetails.envName']; + reqData = paginationReq; + apiUtil.databaseUtil(paginationReq, next); + }, + function(queryObj, next) { + if(actionStatus !== null){ + var query = { + auditType: 'BOTs', + actionStatus: actionStatus, + auditCategory: 'Task' + }; + var botsIds = []; + auditTrail.getAuditTrails(query, function(err,botsAudits){ + if(err){ + next(err,null); + }else if (botsAudits.length > 0) { + var results = []; + for (var i = 0; i < botsAudits.length; i++) { + if (botsIds.indexOf(botsAudits[i].auditId) < 0) { + botsIds.push(botsAudits[i].auditId); + results.push(botsAudits[i].auditId); + } else { + results.push(botsAudits[i].auditId); + } + } + if (results.length === botsAudits.length) { + queryObj.queryObj.botId = {$in:botsIds}; + bots.getBotsList(queryObj, next); + } + } else { + queryObj.queryObj.botId = null; + bots.getBotsList(queryObj, next); + } + }); + }else{ + bots.getBotsList(queryObj, next); + } + }, + function(auditTrailList, next) { + apiUtil.paginationResponse(auditTrailList, reqData, next); + } + ],function(err, results) { + if (err){ + logger.error(err); + callback(err,null); + return; + } + callback(null,results) + return; + }); +} + +botsService.removeSoftBotsById = function removeSoftBotsById(botId,callback){ + async.waterfall([ + function(next){ + bots.getBotsById(botId,next); + }, + function(bots,next){ + if(bots.length > 0){ + async.parallel({ + bots:function(callback){ + if(bots[0].botLinkedCategory === 'Task'){ + taskService.deleteServiceDeliveryTask(botId, callback); + }else{ + blueprintService.deleteServiceDeliveryBlueprint(botId,callback) + } + }, + services: function(callback){ + bots.removeSoftBotsById(botId,callback); + } + },function(err,results){ + if(err){ + next(err,null); + }else{ + next(null,results); + } + }) + }else{ + next({errCode:400, errMsg:"Bots is not exist in DB"},null) + } + } + ],function(err,results){ + if(err){ + logger.error(err); + callback(err,null); + return; + }else{ + callback(null,results); + return; + } + }); +} +botsService.removeBotsById = function removeBotsById(botId,callback){ + bots.removeBotsById(botId,function(err,data){ + if(err){ + logger.error(err); + callback(err,null); + return; + } + callback(null,data); + return; + }); +} + +botsService.getBotsHistory = function getBotsHistory(botId,callback){ + auditTrailService.getBotsAuditTrailHistory(botId,function(err,data){ + if(err){ + logger.error(err); + callback(err,null); + return; + } + callback(null,data); + return; + }); +} + +botsService.executeBots = function executeBots(botId,reqBody,callback){ + async.waterfall([ + function(next){ + bots.getBotsById(botId,next); + }, + function(bots,next){ + if(bots.length > 0){ + if(bots[0].botLinkedCategory === 'Task'){ + taskService.executeTask(botId,reqBody.userName,reqBody.hostProtocol,reqBody.choiceParam,reqBody.appData,reqBody.paramOptions,reqBody.tagServer, callback); + }else{ + blueprintService.launch(botId,reqBody,callback) + } + }else{ + next({errCode:400, errMsg:"Bots is not exist in DB"},null) + } + } + ],function(err,results){ + if(err){ + logger.error(err); + callback(err,null); + return; + }else{ + callback(null,results); + return; + } + }); +} + + + diff --git a/server/app/services/schedulerService.js b/server/app/services/schedulerService.js index 7b10aefaf..58b8fe4ad 100644 --- a/server/app/services/schedulerService.js +++ b/server/app/services/schedulerService.js @@ -37,9 +37,11 @@ var azureCloud = require('_pr/lib/azure'); var fs = require('fs'); var providerService = require('_pr/services/providerService.js'); var taskService = require('_pr/services/taskService.js'); +var botsService = require('_pr/services/botsService.js'); var gcpProviderModel = require('_pr/model/v2.0/providers/gcp-providers'); var GCP = require('_pr/lib/gcp.js'); var crontab = require('node-crontab'); +var botsDao = require('_pr/model/bots/bots.js'); schedulerService.executeSchedulerForInstances = function executeSchedulerForInstances(instance,callback) { logger.debug("Instance Scheduler is started for Instance. "+instance.platformId); @@ -135,6 +137,40 @@ schedulerService.executeParallelScheduledTasks = function executeParallelSchedul } } +schedulerService.executeScheduledBots = function executeScheduledBots(bots,callback) { + logger.debug("Bots Scheduler is started for - "+bots.botName); + var currentDate = new Date(); + if(currentDate >= bots.botScheduler.cronEndOn){ + crontab.cancelJob(bots.cronJobId); + botsDao.updateBotScheduler(bots._id,function(err, updatedData) { + if (err) { + logger.error("Failed to update Bots Scheduler: ", err); + callback(err,null); + return; + } + logger.debug("Scheduler is ended on for Bots. "+bots.botName); + callback(null,updatedData); + return; + }); + }else{ + var cronJobId = cronTab.scheduleJob(bots.botScheduler.cronPattern, function () { + botsDao.updateCronJobIdByBotId(bots._id,cronJobId,function(err,data){ + if(err){ + logger.error("Error in updating cron job Ids. "+err); + } + }) + botsService.executeBots(bots._id,bots.botsConfig,function(err, historyData) { + if (err) { + logger.error("Failed to execute Bots.", err); + return; + } + logger.debug("Bots Execution Success for - ", bots.botName); + return; + }); + }); + } +} + schedulerService.executeSerialScheduledTasks = function executeSerialScheduledTasks(task,callback) { logger.debug("Task Scheduler is started for Serial Task. "+task.name); var currentDate = new Date(); diff --git a/server/app/services/taskService.js b/server/app/services/taskService.js index 6e057995e..1644e6886 100644 --- a/server/app/services/taskService.js +++ b/server/app/services/taskService.js @@ -16,6 +16,7 @@ var logger = require('_pr/logger')(module); var taskDao = require('_pr/model/classes/tasks/tasks.js'); +var bots = require('_pr/model/bots/bots.js'); var masterUtil = require('_pr/lib/utils/masterUtil.js'); var d4dModelNew = require('_pr/model/d4dmasters/d4dmastersmodelnew.js'); var TaskHistory = require('_pr/model/classes/tasks/taskHistory'); @@ -115,7 +116,7 @@ taskService.deleteServiceDeliveryTask = function deleteServiceDeliveryTask(taskI taskDao.removeServiceDeliveryTask(taskId, next); }, function (deleteTaskCheck, next) { - auditTrail.removeAuditTrails({auditId:taskId},next); + auditTrail.softRemoveAuditTrails({auditId:taskId},next); } ],function (err, results) { if (err) { @@ -143,7 +144,6 @@ taskService.executeTask = function executeTask(taskId, user, hostProtocol, choic } else if (task.taskType.SCRIPT_TASK) { paramOptions = paramOptions.scriptDetails; } - var blueprintIds = []; if (task.blueprintIds && task.blueprintIds.length) { blueprintIds = task.blueprintIds; @@ -181,6 +181,33 @@ taskService.executeTask = function executeTask(taskId, user, hostProtocol, choic manualExecutionTime:task.manualExecutionTime, nodeIdsWithActionLog:[] }; + bots.getBotsById(task._id,function(err,data){ + if(err){ + logger.error(err); + }else if(data.length > 0){ + var botExecutionCount = data[0].executionCount + 1; + bots.updateBotsExecutionCount(task._id,botExecutionCount,function(err,data){ + if(err){ + logger.error("Error while updating Bot Execution Count"); + } + }); + var reqBody = { + userName: user, + hostProtocol: hostProtocol, + choiceParam: choiceParam, + appData: appData, + tagServer: botTagServer, + paramOptions:paramOptions + } + bots.updateBotsDetail(task._id,{runTimeParams:reqBody},function(err,data){ + if(err){ + logger.error("Error while updating Bots Configuration"); + } + }); + }else{ + logger.debug("There is no BOTs data present in DB"); + } + }); auditTrailService.insertAuditTrail(task,auditTrailObj,actionObj,function(err,data) { if (err) { logger.error(err); @@ -188,32 +215,6 @@ taskService.executeTask = function executeTask(taskId, user, hostProtocol, choic auditTrailId = data._id; task.execute(user, hostProtocol, choiceParam, appData, blueprintIds, task.envId, auditTrailId, function (err, taskRes, historyData) { if (err) { - if (auditTrailId !== null) { - var resultTaskExecution = null; - if(task.taskType === 'jenkins'){ - resultTaskExecution = { - "actionStatus":'failed', - "status":'failed', - "endedOn":new Date().getTime(), - "actionLogId":historyData.jenkinsServerId, - "auditTrailConfig.jenkinsBuildNumber":historyData.buildNumber, - "auditTrailConfig.jenkinsJobName":historyData.jobName - }; - }else{ - resultTaskExecution = { - "actionStatus": 'failed', - "status": "failed", - "endedOn": new Date().getTime(), - "actionLogId": historyData.nodeIdsWithActionLog[0].actionLogId, - "auditTrailConfig.nodeIdsWithActionLog": historyData.nodeIdsWithActionLog - }; - } - auditTrailService.updateAuditTrail('BOTs', auditTrailId, resultTaskExecution, function (err, auditTrail) { - if (err) { - logger.error("Failed to create or update bot Log: ", err); - } - }); - } var error = new Error('Failed to execute task.'); error.status = 500; return callback(error, null); @@ -228,32 +229,6 @@ taskService.executeTask = function executeTask(taskId, user, hostProtocol, choic }else{ task.execute(user, hostProtocol, choiceParam, appData, blueprintIds, task.envId,auditTrailId,function(err, taskRes, historyData) { if (err) { - if(auditTrailId !== null) { - var resultTaskExecution = null; - if(task.taskType === 'jenkins'){ - resultTaskExecution = { - "actionStatus":'failed', - "status":'failed', - "endedOn":new Date().getTime(), - "actionLogId":historyData.jenkinsServerId, - "auditTrailConfig.jenkinsBuildNumber":historyData.buildNumber, - "auditTrailConfig.jenkinsJobName":historyData.jobName - }; - }else{ - resultTaskExecution = { - "actionStatus": 'failed', - "status": "failed", - "endedOn": new Date().getTime(), - "actionLogId": historyData.nodeIdsWithActionLog[0].actionLogId, - "auditTrailConfig.nodeIdsWithActionLog": historyData.nodeIdsWithActionLog - }; - } - auditTrailService.updateAuditTrail('BOTs', auditTrailId, resultTaskExecution, function (err, auditTrail) { - if (err) { - logger.error("Failed to create or update bot Log: ", err); - } - }); - } var error = new Error('Failed to execute task.'); error.status = 500; return callback(error, null); diff --git a/server/install.js b/server/install.js index 3ea196fd5..390085f4d 100755 --- a/server/install.js +++ b/server/install.js @@ -114,7 +114,8 @@ function getDefaultsConfig() { "chefNodes":"createdOn", "blueprints":"name", "compositeBlueprints":"name", - "containerLogs":"createdOn" + "containerLogs":"createdOn", + "bots":"createdOn" }, skip_Records : 1, max_record_limit : 200,