diff --git a/v2/index.html b/v2/index.html index 00c4da7..fb5ec5a 100644 --- a/v2/index.html +++ b/v2/index.html @@ -19,54 +19,13 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - +
@@ -75,10 +34,10 @@
-
+
- + \ No newline at end of file diff --git a/v2/src/app/app.js b/v2/src/app/app.js index a1db00e..22593f6 100644 --- a/v2/src/app/app.js +++ b/v2/src/app/app.js @@ -1,55 +1,69 @@ -var app = angular.module('compass', [ - 'compass.login', - 'compass.services', - 'compass.topnav', - 'compass.wizard', - 'compass.cluster', - 'compass.clusterlist', - 'compass.monitoring', - 'compass.server', - 'compass.userSetting', - 'compass.userProfile', - 'ui.router', - 'ui.bootstrap', - //'compassAppDev', - 'ngAnimate' -]); +define([ + 'angular', + 'login', + 'services', + 'appDev', + 'clusterList', + 'cluster', + 'monitoring', + 'wizard', + 'topnav', + 'server', + 'userProfile', + 'charts', + 'userSetting', + 'findservers' +], function(ng) { + 'use strict'; + var compassModule = ng.module('app', [ + 'compass.login', + 'compass.services', + // 'compassAppDev', + 'compass.clusterlist', + 'compass.cluster', + 'compass.wizard', + 'compass.topnav', + 'compass.server', + 'compass.userProfile', + 'compass.userSetting', + 'compass.monitoring', + 'compass.charts', + 'compass.findservers' + ]); + compassModule.constant('settings', { + apiUrlBase: '/api', + metadataUrlBase: 'data', + //monitoringUrlBase: 'http://metrics-api/monit/api/v1' + monitoringUrlBase: '/monit/api/v1' + }); + compassModule.config(function($stateProvider, $urlRouterProvider) { + compassModule.stateProvider = $stateProvider; + $urlRouterProvider.otherwise('/login'); + }); + compassModule.run(function($rootScope, $state, authService) { + $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) { + if (toState.authenticate && !authService.isAuthenticated) { + // User isn't authenticated + $state.transitionTo("login"); + event.preventDefault(); + } + }); + }); + compassModule.controller('appController', function($scope, authService, $state) { + $scope.currentUser = null; + $scope.isAuthenticated = authService.isAuthenticated; + $scope.state = $state; -app.constant('settings', { - apiUrlBase: '/api', - metadataUrlBase: 'data', - //monitoringUrlBase: 'http://metrics-api/monit/api/v1' - monitoringUrlBase: '/monit/api/v1' -}); + $scope.$watch(function() { + return authService.isAuthenticated + }, function(val) { + $scope.isAuthenticated = authService.isAuthenticated; + }) -app.config(function($stateProvider, $urlRouterProvider) { - app.stateProvider = $stateProvider; - $urlRouterProvider.otherwise('/login'); -}); - -app.run(function($rootScope, $state, authService) { - $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) { - if (toState.authenticate && !authService.isAuthenticated) { - // User isn't authenticated + $scope.logout = function() { + authService.isAuthenticated = false; $state.transitionTo("login"); - event.preventDefault(); } }); -}); -app.controller('appController', function($scope, authService, $state) { - $scope.currentUser = null; - $scope.isAuthenticated = authService.isAuthenticated; - $scope.state = $state; - - $scope.$watch(function() { - return authService.isAuthenticated - }, function(val) { - $scope.isAuthenticated = authService.isAuthenticated; - }) - - $scope.logout = function() { - authService.isAuthenticated = false; - $state.transitionTo("login"); - } -}); +}); \ No newline at end of file diff --git a/v2/src/app/appDev.js b/v2/src/app/appDev.js index 4a98e7e..e79157e 100644 --- a/v2/src/app/appDev.js +++ b/v2/src/app/appDev.js @@ -1,4 +1,5 @@ -var compassAppDev = angular.module('compassAppDev', ['compass', 'ngMockE2E']); +define(['angular','angularMocks'],function(){ +var compassAppDev = angular.module('compassAppDev', ['ngMockE2E']); compassAppDev.run(function($httpBackend, settings, $http) { var progressPercent = 0; @@ -1738,4 +1739,5 @@ compassAppDev.run(function($httpBackend, settings, $http) { }]; return [200, metricData, {}]; }); +}); }); \ No newline at end of file diff --git a/v2/src/app/cluster/cluster.js b/v2/src/app/cluster/cluster.js index 7a12145..1e9eed5 100644 --- a/v2/src/app/cluster/cluster.js +++ b/v2/src/app/cluster/cluster.js @@ -1,304 +1,307 @@ -angular.module('compass.cluster', [ - 'ui.router', - 'ui.bootstrap', - 'compass.charts', - 'ngAnimate', - 'ngTable', - 'angular-rickshaw' -]) +define(['angular'], function() { + var clusterModule = angular.module('compass.cluster', [ + //'ui.router', + //'ui.bootstrap', + //'compass.charts', + //'ngAnimate', + //'ngTable', + //'angular-rickshaw' + ]); -.config(function($stateProvider, $urlRouterProvider) { - $stateProvider - .state('cluster', { - url: '/cluster/{id}', - controller: 'clusterCtrl', - templateUrl: 'src/app/cluster/cluster.tpl.html', - authenticate: true, - resolve: { - clusterhostsData: function($stateParams, $q, dataService) { - var clusterId = $stateParams.id; - var deferred = $q.defer(); - dataService.getClusterHosts(clusterId).success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; - } - } - }) - .state('cluster.overview', { - url: '/overview', - controller: 'clusterProgressCtrl', - templateUrl: 'src/app/cluster/cluster-overview.tpl.html', - authenticate: true - }) - .state('cluster.config', { - url: '/config', - controller: 'configurationCtrl', - templateUrl: 'src/app/cluster/cluster-config.tpl.html', - authenticate: true - }) - .state('cluster.config.security', { - url: '/security', - templateUrl: 'src/app/cluster/cluster-security.tpl.html', - authenticate: true - }) - .state('cluster.config.network', { - url: '/network', - templateUrl: 'src/app/cluster/cluster-network.tpl.html', - authenticate: true - }) - .state('cluster.config.partition', { - url: '/partition', - templateUrl: 'src/app/cluster/cluster-partition.tpl.html', - authenticate: true - }) - .state('cluster.config.roles', { - url: '/roles', - templateUrl: 'src/app/cluster/cluster-roles.tpl.html', - authenticate: true - }) - .state('cluster.log', { - url: '/log', - controller: "clusterLogCtrl", - templateUrl: 'src/app/cluster/cluster-log.tpl.html', - authenticate: true - }); -}) - -.controller('clusterCtrl', function($scope, $state, dataService, $stateParams) { - $scope.clusterId = $stateParams.id; - $scope.state = $state; - - dataService.getClusterById($scope.clusterId).success(function(data) { - $scope.clusterInfo = data; - }); - -}).directive('clusternav', function($timeout) { - return { - restrict: 'EAC', - templateUrl: 'src/app/cluster/cluster-nav.tpl.html', - link: function($scope, elem, attrs) { - $timeout(function() { - $('.nav-list ul a').on('click touchend', function(e) { - var el = $(this); - var link = el.attr('href'); - window.location = link; - }); - }, 0); - - elem.bind('$destroy', function() { - $('.nav-list ul a').off('click touchend'); - }); - } - } -}) - -.controller('clusterLogCtrl', function() { - -}) - -.controller('clusterProgressCtrl', function($scope, dataService, $stateParams, $filter, ngTableParams, $timeout, $modal, clusterhostsData) { - var clusterId = $stateParams.id; - var progressTimer; - var fireTimer = true; - $scope.hosts = clusterhostsData; - - var getClusterProgress = function() { - dataService.getClusterProgress(clusterId).success(function(data) { - $scope.clusterProgress = data; - if (fireTimer) { - progressTimer = $timeout(getClusterProgress, 5000); - } - }); - }; - - getClusterProgress(); - - dataService.getServerColumns().success(function(data) { - $scope.server_columns = data.progress; - }); - - - $scope.tableParams = new ngTableParams({ - page: 1, // show first page - count: $scope.hosts.length + 1 // count per page - }, { - counts: [], // hide count-per-page box - total: $scope.hosts.length, // length of data - getData: function($defer, params) { - // use build-in angular filter - var orderedData = params.sorting() ? - $filter('orderBy')($scope.hosts, params.orderBy()) : $scope.hosts; - - $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); - } - }); - - $scope.deleteHost = function(index) { - dataService.deleteHost($scope.hosts[index].id) - $scope.hosts.splice(index, 1); - $scope.tableParams.reload(); - }; - - $scope.selectAllServers = function(flag) { - if (flag) { - angular.forEach($scope.hosts, function(sv) { - sv.selected = true; - }) - } else { - angular.forEach($scope.hosts, function(sv) { - sv.selected = false; - }) - } - }; - - $scope.openDeleteHostModal = function(index) { - var modalInstance = $modal.open({ - templateUrl: 'deleteHostConfirm.html', - controller: deleteHostModalCtrl, - resolve: { - host: function() { - return $scope.hosts[index]; - } - } - }); - - modalInstance.result.then(function() { - // ok - $scope.deleteHost(index); - }, function() { - // cancel - }); - }; - - $scope.$on('$destroy', function() { - fireTimer = false; - $timeout.cancel(progressTimer); - }); - -}) - -.controller('createClusterCtrl', ['$scope', '$state', '$modal', '$log', 'dataService', 'wizardFactory','$rootScope', - function($scope, $state, $modal, $log, dataService, wizardFactory,$rootScope) { - dataService.getAdapters().success(function(data) { - $scope.allAdapters = data; - $scope.cluster = {}; - - $scope.open = function(size) { - var modalInstance = $modal.open({ - templateUrl: 'createClusterModal.html', - controller: ClusterModalCtrl, - size: size, - resolve: { - allAdapters: function() { - return $scope.allAdapters; - }, - cluster: function() { - return $scope.cluster; - } - } - }); - modalInstance.result.then(function(cluster) { - $scope.cluster = cluster; - var postClusterData = { - "name": cluster.name, - "adapter_id": cluster.adapter.id, - "os_id": cluster.os.id - }; - if (cluster.flavor) { - postClusterData.flavor_id = cluster.flavor.id; - } - dataService.createCluster(postClusterData).success(function(data, status) { - $scope.clusters.push(data); - $rootScope.$emit('clusters',$scope.clusters); - wizardFactory.setClusterInfo(data); - angular.forEach($scope.allAdapters, function(adapter) { - if (adapter.id == $scope.cluster.adapter_id) { - wizardFactory.setAdapter(adapter); - } - }) - $state.go('wizard', { - "id": data.id, - "config": "true" + clusterModule.config(function($stateProvider, $urlRouterProvider) { + $stateProvider + .state('cluster', { + url: '/cluster/{id}', + controller: 'clusterCtrl', + templateUrl: 'src/app/cluster/cluster.tpl.html', + authenticate: true, + resolve: { + clusterhostsData: function($stateParams, $q, dataService) { + var clusterId = $stateParams.id; + var deferred = $q.defer(); + dataService.getClusterHosts(clusterId).success(function(data) { + deferred.resolve(data); }); - $scope.cluster = {}; - }); - }, function() { - // modal cancelled - }); - }; - }); - } -]) - -.controller('configurationCtrl', function($scope, dataService, $stateParams, $filter, ngTableParams, clusterhostsData) { - var clusterId = $stateParams.id; - $scope.partitionarray = []; - dataService.getClusterConfig(clusterId).success(function(data) { - $scope.configuration = data; - - - angular.forEach($scope.configuration.os_config.partition, function(value, key) { - $scope.partitionarray.push({ - "name": key, - "number": value.percentage + return deferred.promise; + } + } + }) + .state('cluster.overview', { + url: '/overview', + controller: 'clusterProgressCtrl', + templateUrl: 'src/app/cluster/cluster-overview.tpl.html', + authenticate: true + }) + .state('cluster.config', { + url: '/config', + controller: 'configurationCtrl', + templateUrl: 'src/app/cluster/cluster-config.tpl.html', + authenticate: true + }) + .state('cluster.config.security', { + url: '/security', + templateUrl: 'src/app/cluster/cluster-security.tpl.html', + authenticate: true + }) + .state('cluster.config.network', { + url: '/network', + templateUrl: 'src/app/cluster/cluster-network.tpl.html', + authenticate: true + }) + .state('cluster.config.partition', { + url: '/partition', + templateUrl: 'src/app/cluster/cluster-partition.tpl.html', + authenticate: true + }) + .state('cluster.config.roles', { + url: '/roles', + templateUrl: 'src/app/cluster/cluster-roles.tpl.html', + authenticate: true + }) + .state('cluster.log', { + url: '/log', + controller: "clusterLogCtrl", + templateUrl: 'src/app/cluster/cluster-log.tpl.html', + authenticate: true }); + }); + + clusterModule.controller('clusterCtrl', function($scope, $state, dataService, $stateParams) { + $scope.clusterId = $stateParams.id; + $scope.state = $state; + + dataService.getClusterById($scope.clusterId).success(function(data) { + $scope.clusterInfo = data; }); }); + clusterModule.directive('clusternav', function($timeout) { + return { + restrict: 'EAC', + templateUrl: 'src/app/cluster/cluster-nav.tpl.html', + link: function($scope, elem, attrs) { + $timeout(function() { + $('.nav-list ul a').on('click touchend', function(e) { + var el = $(this); + var link = el.attr('href'); + window.location = link; + }); + }, 0); - dataService.getServerColumns().success(function(data) { - $scope.server_columns = data.roles; - }); - - $scope.hosts = clusterhostsData; - - $scope.tableParams = new ngTableParams({ - page: 1, // show first page - count: $scope.hosts.length + 1 // count per page - }, { - counts: [], // hide count-per-page box - total: $scope.hosts.length, // length of data - getData: function($defer, params) { - // use build-in angular filter - var orderedData = params.sorting() ? - $filter('orderBy')($scope.hosts, params.orderBy()) : $scope.hosts; - - $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); + elem.bind('$destroy', function() { + $('.nav-list ul a').off('click touchend'); + }); + } } }); -}) -var ClusterModalCtrl = function($scope, $modalInstance, allAdapters, cluster) { - $scope.allAdapters = allAdapters; - $scope.cluster = cluster; + clusterModule.controller('clusterLogCtrl', function() { - $scope.updateSelectedAdapter = function() { - angular.forEach($scope.allAdapters, function(adapter) { - if (adapter.id == $scope.cluster.adapter.id) { - $scope.supported_oses = adapter.supported_oses; - $scope.flavors = adapter.flavors; + }); + + clusterModule.controller('clusterProgressCtrl', function($scope, dataService, $stateParams, $filter, ngTableParams, $timeout, $modal, clusterhostsData) { + var clusterId = $stateParams.id; + var progressTimer; + var fireTimer = true; + $scope.hosts = clusterhostsData; + + var getClusterProgress = function() { + dataService.getClusterProgress(clusterId).success(function(data) { + $scope.clusterProgress = data; + if (fireTimer) { + progressTimer = $timeout(getClusterProgress, 5000); + } + }); + }; + + getClusterProgress(); + + dataService.getServerColumns().success(function(data) { + $scope.server_columns = data.progress; + }); + + + $scope.tableParams = new ngTableParams({ + page: 1, // show first page + count: $scope.hosts.length + 1 // count per page + }, { + counts: [], // hide count-per-page box + total: $scope.hosts.length, // length of data + getData: function($defer, params) { + // use build-in angular filter + var orderedData = params.sorting() ? + $filter('orderBy')($scope.hosts, params.orderBy()) : $scope.hosts; + + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } - }) + }); + + $scope.deleteHost = function(index) { + dataService.deleteHost($scope.hosts[index].id) + $scope.hosts.splice(index, 1); + $scope.tableParams.reload(); + }; + + $scope.selectAllServers = function(flag) { + if (flag) { + angular.forEach($scope.hosts, function(sv) { + sv.selected = true; + }) + } else { + angular.forEach($scope.hosts, function(sv) { + sv.selected = false; + }) + } + }; + + $scope.openDeleteHostModal = function(index) { + var modalInstance = $modal.open({ + templateUrl: 'deleteHostConfirm.html', + controller: deleteHostModalCtrl, + resolve: { + host: function() { + return $scope.hosts[index]; + } + } + }); + + modalInstance.result.then(function() { + // ok + $scope.deleteHost(index); + }, function() { + // cancel + }); + }; + + $scope.$on('$destroy', function() { + fireTimer = false; + $timeout.cancel(progressTimer); + }); + + }); + + clusterModule.controller('createClusterCtrl', ['$scope', '$state', '$modal', '$log', 'dataService', 'wizardFactory', '$rootScope', + function($scope, $state, $modal, $log, dataService, wizardFactory, $rootScope) { + dataService.getAdapters().success(function(data) { + $scope.allAdapters = data; + $scope.cluster = {}; + + $scope.open = function(size) { + var modalInstance = $modal.open({ + templateUrl: 'createClusterModal.html', + controller: ClusterModalCtrl, + size: size, + resolve: { + allAdapters: function() { + return $scope.allAdapters; + }, + cluster: function() { + return $scope.cluster; + } + } + }); + modalInstance.result.then(function(cluster) { + $scope.cluster = cluster; + var postClusterData = { + "name": cluster.name, + "adapter_id": cluster.adapter.id, + "os_id": cluster.os.id + }; + if (cluster.flavor) { + postClusterData.flavor_id = cluster.flavor.id; + } + dataService.createCluster(postClusterData).success(function(data, status) { + $scope.clusters.push(data); + $rootScope.$emit('clusters', $scope.clusters); + wizardFactory.setClusterInfo(data); + angular.forEach($scope.allAdapters, function(adapter) { + if (adapter.id == $scope.cluster.adapter_id) { + wizardFactory.setAdapter(adapter); + } + }) + $state.go('wizard', { + "id": data.id, + "config": "true" + }); + $scope.cluster = {}; + }); + }, function() { + // modal cancelled + }); + }; + }); + } + ]); + + clusterModule.controller('configurationCtrl', function($scope, dataService, $stateParams, $filter, ngTableParams, clusterhostsData) { + var clusterId = $stateParams.id; + $scope.partitionarray = []; + dataService.getClusterConfig(clusterId).success(function(data) { + $scope.configuration = data; + + + angular.forEach($scope.configuration.os_config.partition, function(value, key) { + $scope.partitionarray.push({ + "name": key, + "number": value.percentage + }); + }); + + }); + + dataService.getServerColumns().success(function(data) { + $scope.server_columns = data.roles; + }); + + $scope.hosts = clusterhostsData; + + $scope.tableParams = new ngTableParams({ + page: 1, // show first page + count: $scope.hosts.length + 1 // count per page + }, { + counts: [], // hide count-per-page box + total: $scope.hosts.length, // length of data + getData: function($defer, params) { + // use build-in angular filter + var orderedData = params.sorting() ? + $filter('orderBy')($scope.hosts, params.orderBy()) : $scope.hosts; + + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); + } + }); + }); + + var ClusterModalCtrl = function($scope, $modalInstance, allAdapters, cluster) { + $scope.allAdapters = allAdapters; + $scope.cluster = cluster; + + $scope.updateSelectedAdapter = function() { + angular.forEach($scope.allAdapters, function(adapter) { + if (adapter.id == $scope.cluster.adapter.id) { + $scope.supported_oses = adapter.supported_oses; + $scope.flavors = adapter.flavors; + } + }) + }; + + $scope.ok = function() { + $scope.result = 'ok'; + $modalInstance.close($scope.cluster); + }; + + $scope.cancel = function() { + $modalInstance.dismiss('cancel'); + $scope.result = 'cancel'; + }; }; - $scope.ok = function() { - $scope.result = 'ok'; - $modalInstance.close($scope.cluster); + var deleteHostModalCtrl = function($scope, $modalInstance, host) { + $scope.host = host; + $scope.ok = function() { + $modalInstance.close(); + }; + $scope.cancel = function() { + $modalInstance.dismiss('cancel'); + }; }; - - $scope.cancel = function() { - $modalInstance.dismiss('cancel'); - $scope.result = 'cancel'; - }; -}; - -var deleteHostModalCtrl = function($scope, $modalInstance, host) { - $scope.host = host; - $scope.ok = function() { - $modalInstance.close(); - }; - $scope.cancel = function() { - $modalInstance.dismiss('cancel'); - }; -} +}); \ No newline at end of file diff --git a/v2/src/app/cluster/clusterlist.js b/v2/src/app/cluster/clusterlist.js index 4136f4f..cf7b972 100644 --- a/v2/src/app/cluster/clusterlist.js +++ b/v2/src/app/cluster/clusterlist.js @@ -1,69 +1,74 @@ -var app = angular.module('compass.clusterlist', [ - 'ui.router', - 'ui.bootstrap', - 'ngTable' -]) +define(['angular'], function() { + var clusterlistModule = angular.module('compass.clusterlist', [ + //'ui.router', + //'ui.bootstrap', + //'ngTable' + ]); -.config(function($stateProvider, $urlRouterProvider) { - $stateProvider - .state('clusterList', { - url: '/clusterlist', - controller: 'clustersListCtrl', - templateUrl: 'src/app/cluster/cluster-all.tpl.html', - authenticate: true, - resolve: { - allClusterData: function($q, dataService) { - var deferred = $q.defer(); - dataService.getClusters().success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; + clusterlistModule.config(function($stateProvider, $urlRouterProvider) { + $stateProvider + .state('clusterList', { + url: '/clusterlist', + controller: 'clustersListCtrl', + templateUrl: 'src/app/cluster/cluster-all.tpl.html', + authenticate: true, + resolve: { + allClusterData: function($q, dataService) { + var deferred = $q.defer(); + dataService.getClusters().success(function(data) { + deferred.resolve(data); + }); + return deferred.promise; + } } + }); + }); + + clusterlistModule.controller('clustersListCtrl', function($scope, $state, ngTableParams, $filter, dataService, allClusterData) { + $scope.clusters = allClusterData; + angular.forEach($scope.clusters, function(cluster) { + dataService.getClusterProgress(cluster.id).success(function(data) { + cluster.progress = data.status; + cluster.state = data.state; + }); + }); + + var data = $scope.clusters; + $scope.tableParams = new ngTableParams({ + page: 1, // show first page + count: 10, // count per page + }, { + total: data.length, // length of data + getData: function($defer, params) { + // use build-in angular filter + var orderedData = params.sorting() ? + $filter('orderBy')(data, params.orderBy()) : + data; + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } }); -}) -.controller('clustersListCtrl', function($scope, $state, ngTableParams, $filter, dataService, allClusterData) { - $scope.clusters = allClusterData - angular.forEach($scope.clusters, function(cluster) { - dataService.getClusterProgress(cluster.id).success(function(data) { - cluster.progress = data.status; - cluster.state = data.state; - }); - }); + $scope.goToCluster = function(id, state) { + if (state == "UNINITIALIZED") { + $state.go("wizard", { + "id": id, + "config": "true" + }); + } else { + $state.go("cluster.overview", { + "id": id + }); + } + }; - var data = $scope.clusters; - $scope.tableParams = new ngTableParams({ - page: 1, // show first page - count: 10, // count per page - }, { - total: data.length, // length of data - getData: function($defer, params) { - // use build-in angular filter - var orderedData = params.sorting() ? - $filter('orderBy')(data, params.orderBy()) : - data; - $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); + //button alerts + + $scope.alert = function(text) { + alert('delete?'); } - }); - - $scope.goToCluster = function(id, state) { - if (state == "UNINITIALIZED") { - $state.go("wizard", {"id": id, "config": "true"}); - } else { - $state.go("cluster.overview", { - "id": id - }); + $scope.export = function(text) { + alert('export?'); } - }; - //button alerts - - $scope.alert = function(text) { - alert('delete?'); - } - $scope.export = function(text) { - alert('export?'); - } - -}); + }); +}) \ No newline at end of file diff --git a/v2/src/app/login/login.js b/v2/src/app/login/login.js index 081932f..828af7d 100644 --- a/v2/src/app/login/login.js +++ b/v2/src/app/login/login.js @@ -1,59 +1,61 @@ -angular.module('compass.login', [ - 'compass.services', - 'ui.router', - 'ui.bootstrap' -]) +define(['uiRouter'], function() { + 'use strict'; + var loginModule = angular.module('compass.login', [ + 'ui.router', + 'ui.bootstrap' + ]); + loginModule.config(function config($stateProvider) { + $stateProvider + .state('login', { + url: '/login', + controller: 'loginCtrl', + templateUrl: 'src/app/login/login.tpl.html', + authenticate: false + }); + }); -.config(function config($stateProvider) { - $stateProvider - .state('login', { - url: '/login', - controller: 'loginCtrl', - templateUrl: 'src/app/login/login.tpl.html', - authenticate: false - }); -}) - -.controller('loginCtrl', function($scope, authService, $state) { - $scope.alerts = []; - - $scope.login = function() { + loginModule.controller('loginCtrl', function($scope, authService, $state) { $scope.alerts = []; - var credentials = { - "email": $scope.email, - "password": $scope.password + + $scope.login = function() { + $scope.alerts = []; + var credentials = { + "email": $scope.email, + "password": $scope.password + }; + authService.login(credentials).success(function(data) { + authService.isAuthenticated = true; + $state.transitionTo("clusterList"); + }).error(function(response) { + console.log(response); + $scope.alerts.push(response); + }) }; - authService.login(credentials).success(function(data) { - authService.isAuthenticated = true; - $state.transitionTo("clusterList"); - }).error(function(response) { - console.log(response); - $scope.alerts.push(response); - }) - }; - $scope.closeAlert = function() { - $scope.alerts = []; - }; + $scope.closeAlert = function() { + $scope.alerts = []; + }; -}) + }); -.directive('setFocus', function() { - return function(scope, element){ element[0].focus();}; -}) + loginModule.directive('setFocus', function() { + return function(scope, element) { + element[0].focus(); + }; + }); -.directive('ngEnter', function() { - return function(scope, element, attrs) { - element.bind("keydown keypress", function(event) { - if(event.which === 13) { // 13 is enter key + loginModule.directive('ngEnter', function() { + return function(scope, element, attrs) { + element.bind("keydown keypress", function(event) { + if (event.which === 13) { // 13 is enter key - if(scope.email.trim() !="" && scope.password.trim() != "") - { - scope.$eval(attrs.ngEnter); + if (scope.email.trim() != "" && scope.password.trim() != "") { + scope.$eval(attrs.ngEnter); + } + + event.preventDefault(); } - - event.preventDefault(); - } - }); - }; -}); + }); + }; + }); +}); \ No newline at end of file diff --git a/v2/src/app/monitoring/monitoring.js b/v2/src/app/monitoring/monitoring.js index 5c5159d..4a13774 100644 --- a/v2/src/app/monitoring/monitoring.js +++ b/v2/src/app/monitoring/monitoring.js @@ -1,176 +1,178 @@ -angular.module('compass.monitoring', [ - 'ui.router', - 'ui.bootstrap', - 'compass.charts', - 'ngAnimate', - 'angular-rickshaw', - 'nvd3ChartDirectives', - 'ui.tree' -]) +define(['angularAnimate', 'angularRickshaw', 'angularUiTree', 'nvd3Directive'], function() { -.config(function($stateProvider, $urlRouterProvider) { - $stateProvider - .state('cluster.monitoring', { - url: '/monitoring', - templateUrl: 'src/app/monitoring/cluster-monitoring.tpl.html', - authenticate: true - }) - .state('cluster.monitoring.overview', { - url: '/overview', - controller: 'moniOverviewCtrl', - templateUrl: 'src/app/monitoring/overview.tpl.html', - authenticate: true - }) - .state('cluster.monitoring.topology', { - url: '/topology', - controller: 'topologyCtrl', - templateUrl: 'src/app/monitoring/topology.tpl.html', - authenticate: true - }) - .state('cluster.monitoring.alerts', { - url: '/alerts', - controller: 'alertsCtrl', - templateUrl: 'src/app/monitoring/alerts.tpl.html', - authenticate: true - }) - .state('cluster.monitoring.metrics', { - url: '/metrics', - controller: 'metricsCtrl', - templateUrl: 'src/app/monitoring/metrics.tpl.html', - authenticate: true - }) - .state('cluster.monitoring.charts', { - url: '/charts', - templateUrl: 'src/app/monitoring/charts.tpl.html', - authenticate: true - }) -}) + var monitoringModule = angular.module('compass.monitoring', [ + 'ui.router', + 'ui.bootstrap', + 'compass.charts', + 'ngAnimate', + 'angular-rickshaw', + 'nvd3ChartDirectives', + 'ui.tree' + ]); -.controller('moniOverviewCtrl', function($scope, dataService, $stateParams) { - var clusterId = $stateParams.id; - - $scope.goDash = function(locs) { - //alert(locs); - setTimeout(function() { - document.getElementById('dashboards').src = "/dash/#/dashboard/file/" + locs; - }, 600); - } - - $scope.moniOverviewData = []; - dataService.monitorOverview(clusterId).success(function(data) { - $scope.moniOverviewData = data; - }).error(function(response) { - // TODO: error handle + monitoringModule.config(function($stateProvider, $urlRouterProvider) { + $stateProvider + .state('cluster.monitoring', { + url: '/monitoring', + templateUrl: 'src/app/monitoring/cluster-monitoring.tpl.html', + authenticate: true + }) + .state('cluster.monitoring.overview', { + url: '/overview', + controller: 'moniOverviewCtrl', + templateUrl: 'src/app/monitoring/overview.tpl.html', + authenticate: true + }) + .state('cluster.monitoring.topology', { + url: '/topology', + controller: 'topologyCtrl', + templateUrl: 'src/app/monitoring/topology.tpl.html', + authenticate: true + }) + .state('cluster.monitoring.alerts', { + url: '/alerts', + controller: 'alertsCtrl', + templateUrl: 'src/app/monitoring/alerts.tpl.html', + authenticate: true + }) + .state('cluster.monitoring.metrics', { + url: '/metrics', + controller: 'metricsCtrl', + templateUrl: 'src/app/monitoring/metrics.tpl.html', + authenticate: true + }) + .state('cluster.monitoring.charts', { + url: '/charts', + templateUrl: 'src/app/monitoring/charts.tpl.html', + authenticate: true + }) }); -}) + monitoringModule.controller('moniOverviewCtrl', function($scope, dataService, $stateParams) { + var clusterId = $stateParams.id; -.controller('topologyCtrl', function($scope, dataService, $stateParams) { - var clusterId = $stateParams.id; + $scope.goDash = function(locs) { + //alert(locs); + setTimeout(function() { + document.getElementById('dashboards').src = "/dash/#/dashboard/file/" + locs; + }, 600); + } - $scope.physicalTopoData = {}; - $scope.physicalTopoDataReady = "false"; + $scope.moniOverviewData = []; + dataService.monitorOverview(clusterId).success(function(data) { + $scope.moniOverviewData = data; + }).error(function(response) { + // TODO: error handle + }); - dataService.monitorTopology(clusterId).success(function(data) { - $scope.physicalTopoData = data; - $scope.physicalTopoDataReady = "true"; - }).error(function(response) { - // TODO: error handling }); + monitoringModule.controller('topologyCtrl', function($scope, dataService, $stateParams) { + var clusterId = $stateParams.id; - $scope.logicalTopoData = {}; - $scope.logicalTopoDataReady = "false"; + $scope.physicalTopoData = {}; + $scope.physicalTopoDataReady = "false"; + + dataService.monitorTopology(clusterId).success(function(data) { + $scope.physicalTopoData = data; + $scope.physicalTopoDataReady = "true"; + }).error(function(response) { + // TODO: error handling + }); + + + $scope.logicalTopoData = {}; + $scope.logicalTopoDataReady = "false"; + + dataService.monitorServiceTopology(clusterId).success(function(data) { + $scope.logicalTopoData = data; + $scope.logicalTopoDataReady = "true"; + }).error(function(response) { + // TODO: error handling + }); - dataService.monitorServiceTopology(clusterId).success(function(data) { - $scope.logicalTopoData = data; - $scope.logicalTopoDataReady = "true"; - }).error(function(response) { - // TODO: error handling }); -}) + monitoringModule.controller('alertsCtrl', function($scope, dataService, $stateParams) { + var clusterId = $stateParams.id; -.controller('alertsCtrl', function($scope, dataService, $stateParams) { - var clusterId = $stateParams.id; + $scope.alerts = []; + $scope.alertDataReady = "false"; - $scope.alerts = []; - $scope.alertDataReady = "false"; + dataService.monitorAlarms(clusterId).success(function(data) { + $scope.alerts = data; + $scope.alertDataReady = "true"; + }).error(function(response) { + //TODO: error handling + }); - dataService.monitorAlarms(clusterId).success(function(data) { - $scope.alerts = data; - $scope.alertDataReady = "true"; - }).error(function(response) { - //TODO: error handling }); -}) - -.controller('metricsCtrl', function($scope, dataService, $stateParams) { - var clusterId = $stateParams.id; - - $scope.metricsTree = []; - dataService.monitorMetricsTree().success(function(data) { - $scope.metricsTree = data; - }).error(function(response) { - // TODO - }); - - $scope.metrics = []; - dataService.monitorMetrics().success(function(data) { - $scope.metrics = data; - }).error(function(response) { - // TODO - }); - - $scope.metricsData = []; - $scope.generate = function(node) { - console.log(node); - - dataService.monitorClusterMetric(clusterId, node.title).success(function(data) { - $scope.metricsData = data; + monitoringModule.controller('metricsCtrl', function($scope, dataService, $stateParams) { + var clusterId = $stateParams.id; + $scope.metricsTree = []; + dataService.monitorMetricsTree().success(function(data) { + $scope.metricsTree = data; }).error(function(response) { // TODO }); - }; + $scope.metrics = []; + dataService.monitorMetrics().success(function(data) { + $scope.metrics = data; + }).error(function(response) { + // TODO + }); - // For Angular UI Tree - $scope.toggle = function(scope) { - scope.toggle(); - }; + $scope.metricsData = []; + $scope.generate = function(node) { + console.log(node); - var getRootNodesScope = function() { - return angular.element(document.getElementById("tree-root")).scope(); - }; + dataService.monitorClusterMetric(clusterId, node.title).success(function(data) { + $scope.metricsData = data; - $scope.collapseAll = function() { - var scope = getRootNodesScope(); - scope.collapseAll(); - }; + }).error(function(response) { + // TODO + }); - $scope.expandAll = function() { - var scope = getRootNodesScope(); - scope.expandAll(); - }; + }; - // For NVD3 Line Chart - $scope.xAxisTickFormatFunction = function() { - return function(d) { - return d3.time.format('%x')(new Date(d)); - } - }; + // For Angular UI Tree + $scope.toggle = function(scope) { + scope.toggle(); + }; - $scope.toolTipContentFunction = function() { - return function(key, x, y, e, graph) { - return 'Super New Tooltip' + - '

' + key + '

' + - '

' + y + ' at ' + x + '

' - } - }; + var getRootNodesScope = function() { + return angular.element(document.getElementById("tree-root")).scope(); + }; - /* + $scope.collapseAll = function() { + var scope = getRootNodesScope(); + scope.collapseAll(); + }; + + $scope.expandAll = function() { + var scope = getRootNodesScope(); + scope.expandAll(); + }; + + // For NVD3 Line Chart + $scope.xAxisTickFormatFunction = function() { + return function(d) { + return d3.time.format('%x')(new Date(d)); + } + }; + + $scope.toolTipContentFunction = function() { + return function(key, x, y, e, graph) { + return 'Super New Tooltip' + + '

' + key + '

' + + '

' + y + ' at ' + x + '

' + } + }; + + /* // customize stack/line chart colors $scope.colorFunction = function() { var colors = ["#68bc31", "#2091cf", "#6fb3e0", "#fee074", "#f89406", "#af4e96"]; @@ -180,4 +182,5 @@ angular.module('compass.monitoring', [ } */ -}) \ No newline at end of file + }) +}); \ No newline at end of file diff --git a/v2/src/app/server/server.js b/v2/src/app/server/server.js index dd47c0a..235be04 100644 --- a/v2/src/app/server/server.js +++ b/v2/src/app/server/server.js @@ -1,121 +1,123 @@ -angular.module('compass.server', [ - 'ui.router', - 'ui.bootstrap', - 'compass.charts', - 'compass.findservers', - 'ngTable' -]) +define(['uiRouter', 'uiBootstrap', 'angularTable'], function() { + var serverModule = angular.module('compass.server', [ + 'ui.router', + 'ui.bootstrap', + 'compass.charts', + 'compass.findservers', + 'ngTable' + ]); -.config(function config($stateProvider) { - $stateProvider - .state('serverList', { - url: '/serverlist', - controller: 'serverCtrl', - templateUrl: 'src/app/server/server-list.tpl.html', - authenticate: true, - resolve: { - machinesHostsData: function($q, dataService) { - var deferred = $q.defer(); - dataService.getAllMachineHosts().success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; - } - } - }); -}) - -.controller('serverCtrl', function($scope, dataService, $filter, ngTableParams, sortingService, machinesHostsData) { - $scope.hideunselected = ''; - $scope.search = {}; - $scope.allservers = machinesHostsData; - $scope.foundResults = []; - - dataService.getServerColumns().success(function(data) { - $scope.server_columns = data.machines_hosts; - }); - - $scope.tableParams = new ngTableParams({ - page: 1, // show first page - count: $scope.allservers.length + 1 // count per page - }, { - counts: [], // hide count-per-page box - total: $scope.allservers.length, // length of data - getData: function($defer, params) { - var reverse = false; - var orderBy = params.orderBy()[0]; - var orderBySort = ""; - var orderByColumn = ""; - - if (orderBy) { - orderByColumn = orderBy.substring(1); - orderBySort = orderBy.substring(0, 1); - if (orderBySort == "+") { - reverse = false; - } else { - reverse = true; - } - } - - var orderedData = params.sorting() ? - $filter('orderBy')($scope.allservers, function(item) { - if (orderByColumn == "switch_ip") { - return sortingService.ipAddressPre(item.switch_ip); - } else { - return item[orderByColumn]; + serverModule.config(function config($stateProvider) { + $stateProvider + .state('serverList', { + url: '/serverlist', + controller: 'serverCtrl', + templateUrl: 'src/app/server/server-list.tpl.html', + authenticate: true, + resolve: { + machinesHostsData: function($q, dataService) { + var deferred = $q.defer(); + dataService.getAllMachineHosts().success(function(data) { + deferred.resolve(data); + }); + return deferred.promise; } - }, reverse) : $scope.allservers; - - $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); - } + } + }); }); - $scope.selectAllServers = function(flag) { - if (flag) { - angular.forEach($scope.allservers, function(sv) { - sv.selected = true; - }) - } else { - angular.forEach($scope.allservers, function(sv) { - sv.selected = false; - }) - } - }; + serverModule.controller('serverCtrl', function($scope, dataService, $filter, ngTableParams, sortingService, machinesHostsData) { + $scope.hideunselected = ''; + $scope.search = {}; + $scope.allservers = machinesHostsData; + $scope.foundResults = []; - $scope.hideUnselected = function() { - if ($scope.hideunselected) { - $scope.search.selected = true; - } else { - delete $scope.search.selected; - } - }; - - $scope.reloadServers = function() { - dataService.getAllMachineHosts().success(function(data) { - $scope.allservers = data; - $scope.tableParams.$params.count = $scope.allservers.length; - $scope.tableParams.reload(); + dataService.getServerColumns().success(function(data) { + $scope.server_columns = data.machines_hosts; }); - }; - // add newly found servers at the top if allservers array - $scope.$watch('foundResults', function(newResults, oldResults) { - if (newResults != oldResults) { - for (var i = 0; i < newResults.length; i++) { - var sv = $filter('filter')($scope.allservers, newResults[i].mac, true); - if (sv.length == 0) { - newResults[i].machine_id = newResults[i].id; - delete newResults[i]['id']; - newResults[i].new = true; - $scope.allservers.unshift(newResults[i]); + $scope.tableParams = new ngTableParams({ + page: 1, // show first page + count: $scope.allservers.length + 1 // count per page + }, { + counts: [], // hide count-per-page box + total: $scope.allservers.length, // length of data + getData: function($defer, params) { + var reverse = false; + var orderBy = params.orderBy()[0]; + var orderBySort = ""; + var orderByColumn = ""; + + if (orderBy) { + orderByColumn = orderBy.substring(1); + orderBySort = orderBy.substring(0, 1); + if (orderBySort == "+") { + reverse = false; + } else { + reverse = true; + } } - } - if ($scope.tableParams) { + var orderedData = params.sorting() ? + $filter('orderBy')($scope.allservers, function(item) { + if (orderByColumn == "switch_ip") { + return sortingService.ipAddressPre(item.switch_ip); + } else { + return item[orderByColumn]; + } + }, reverse) : $scope.allservers; + + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); + } + }); + + $scope.selectAllServers = function(flag) { + if (flag) { + angular.forEach($scope.allservers, function(sv) { + sv.selected = true; + }) + } else { + angular.forEach($scope.allservers, function(sv) { + sv.selected = false; + }) + } + }; + + $scope.hideUnselected = function() { + if ($scope.hideunselected) { + $scope.search.selected = true; + } else { + delete $scope.search.selected; + } + }; + + $scope.reloadServers = function() { + dataService.getAllMachineHosts().success(function(data) { + $scope.allservers = data; $scope.tableParams.$params.count = $scope.allservers.length; $scope.tableParams.reload(); - } - } - }, true); + }); + }; -}) + // add newly found servers at the top if allservers array + $scope.$watch('foundResults', function(newResults, oldResults) { + if (newResults != oldResults) { + for (var i = 0; i < newResults.length; i++) { + var sv = $filter('filter')($scope.allservers, newResults[i].mac, true); + if (sv.length == 0) { + newResults[i].machine_id = newResults[i].id; + delete newResults[i]['id']; + newResults[i].new = true; + $scope.allservers.unshift(newResults[i]); + } + } + + if ($scope.tableParams) { + $scope.tableParams.$params.count = $scope.allservers.length; + $scope.tableParams.reload(); + } + } + }, true); + + }); +}); \ No newline at end of file diff --git a/v2/src/app/services.js b/v2/src/app/services.js index af7f7d7..07a288e 100644 --- a/v2/src/app/services.js +++ b/v2/src/app/services.js @@ -1,167 +1,165 @@ -angular.module('compass.services', []) +define(['angular'], function() { + var servicesModule = angular.module('compass.services', []); + // stateService is used for dynamically add/edit state +/* .service('stateService', ['$state', + function($state) { + this.addStates = function(pendingStates) { + var existingStates = $state.get(); // get all the current existing states + var alreadyExist = false; // flag - if the pending state is already in the states -// stateService is used for dynamically add/edit state -/* -.service('stateService', ['$state', - function($state) { - this.addStates = function(pendingStates) { - var existingStates = $state.get(); // get all the current existing states - var alreadyExist = false; // flag - if the pending state is already in the states - - angular.forEach(pendingStates, function(pst) { - angular.forEach(existingStates, function(est) { - if (pst.name == est.name) { - alreadyExist = true; - } - }); - if (!alreadyExist) { - app.stateProvider.state(pst.name, { - url: pst.url, - //controller: pst.controller, - templateUrl: 'src/app/monitoring/' + pst.url.substring(1) + '.tpl.html' + angular.forEach(pendingStates, function(pst) { + angular.forEach(existingStates, function(est) { + if (pst.name == est.name) { + alreadyExist = true; + } }); - } - alreadyExist = false; - }); - } - } -]) -*/ - -// dataService is used for http calls -.service('dataService', ['$http', 'settings', - function($http, settings) { - - this.login = function(user) { - return $http.post(settings.apiUrlBase + '/users/login', angular.toJson(user)); - }; - - this.getWizardPreConfig = function() { - return $http.get(settings.metadataUrlBase + '/config.json'); - }; - - this.getWizardSteps = function() { - return $http.get(settings.metadataUrlBase + '/wizard_steps.json'); - }; - - this.getAdapterConfig = function() { - return $http.get(settings.metadataUrlBase + '/adapter_config'); - }; - - this.getAllMachineHosts = function(os) { - if (os) { - return $http.get(settings.apiUrlBase + '/switches-machines-hosts?os_id=' + os); - } else { - return $http.get(settings.apiUrlBase + '/switches-machines-hosts'); + if (!alreadyExist) { + app.stateProvider.state(pst.name, { + url: pst.url, + //controller: pst.controller, + templateUrl: 'src/app/monitoring/' + pst.url.substring(1) + '.tpl.html' + }); + } + alreadyExist = false; + }); } - }; + } + ]) +*/ + // dataService is used for http calls + servicesModule.service('dataService', ['$http', 'settings', //settings is global constant + function($http, settings) { - this.getSwitches = function() { - return $http.get(settings.apiUrlBase + '/switches'); - }; + this.login = function(user) { + return $http.post(settings.apiUrlBase + '/users/login', angular.toJson(user)); + }; - this.getSwitchById = function(id) { - return $http.get(settings.apiUrlBase + '/switches/' + id); - }; + this.getWizardPreConfig = function() { + return $http.get(settings.metadataUrlBase + '/config.json'); + }; - this.postSwitches = function(sw) { - return $http.post(settings.apiUrlBase + '/switches', angular.toJson(sw)); - }; + this.getWizardSteps = function() { + return $http.get(settings.metadataUrlBase + '/wizard_steps.json'); + }; - this.putSwitches = function(id, sw) { - return $http.put(settings.apiUrlBase + '/switches/' + id, angular.toJson(sw)); - }; + this.getAdapterConfig = function() { + return $http.get(settings.metadataUrlBase + '/adapter_config'); + }; - /* + this.getAllMachineHosts = function(os) { + if (os) { + return $http.get(settings.apiUrlBase + '/switches-machines-hosts?os_id=' + os); + } else { + return $http.get(settings.apiUrlBase + '/switches-machines-hosts'); + } + }; + + this.getSwitches = function() { + return $http.get(settings.apiUrlBase + '/switches'); + }; + + this.getSwitchById = function(id) { + return $http.get(settings.apiUrlBase + '/switches/' + id); + }; + + this.postSwitches = function(sw) { + return $http.post(settings.apiUrlBase + '/switches', angular.toJson(sw)); + }; + + this.putSwitches = function(id, sw) { + return $http.put(settings.apiUrlBase + '/switches/' + id, angular.toJson(sw)); + }; + + /* this.postSwitchFilters = function(filters) { return $http.post(settings.apiUrlBase + '/switch-filters', angular.toJson(filters)); }; */ - this.putSwitchFilters = function(id, filters) { - return $http.put(settings.apiUrlBase + '/switch-filters/' + id, angular.toJson(filters)); - }; + this.putSwitchFilters = function(id, filters) { + return $http.put(settings.apiUrlBase + '/switch-filters/' + id, angular.toJson(filters)); + }; - this.postSwitchAction = function(id, action) { - return $http.post(settings.apiUrlBase + '/switches/' + id + '/action', angular.toJson(action)); - }; + this.postSwitchAction = function(id, action) { + return $http.post(settings.apiUrlBase + '/switches/' + id + '/action', angular.toJson(action)); + }; - this.getSwitchMachines = function(id) { - return $http.get(settings.apiUrlBase + '/switches/' + id + '/machines'); - }; + this.getSwitchMachines = function(id) { + return $http.get(settings.apiUrlBase + '/switches/' + id + '/machines'); + }; - this.getServerColumns = function() { - return $http.get(settings.metadataUrlBase + '/machine_host_columns.json'); - }; + this.getServerColumns = function() { + return $http.get(settings.metadataUrlBase + '/machine_host_columns.json'); + }; - this.getMonitoringNav = function() { - return $http.get(settings.metadataUrlBase + '/monitoring_nav.json'); - }; + this.getMonitoringNav = function() { + return $http.get(settings.metadataUrlBase + '/monitoring_nav.json'); + }; - this.getAdapters = function() { - return $http.get(settings.apiUrlBase + '/adapters'); - }; + this.getAdapters = function() { + return $http.get(settings.apiUrlBase + '/adapters'); + }; - this.getAdapter = function(id) { - return $http.get(settings.apiUrlBase + '/adapters/' + id); - }; + this.getAdapter = function(id) { + return $http.get(settings.apiUrlBase + '/adapters/' + id); + }; - this.createCluster = function(cluster) { - return $http.post(settings.apiUrlBase + '/clusters', angular.toJson(cluster)); - }; + this.createCluster = function(cluster) { + return $http.post(settings.apiUrlBase + '/clusters', angular.toJson(cluster)); + }; - this.createUser = function(newUser) { - return $http.post(settings.apiUrlBase + '/users', angular.toJson(newUser)); - }; + this.createUser = function(newUser) { + return $http.post(settings.apiUrlBase + '/users', angular.toJson(newUser)); + }; - this.getUserSetting = function() { - return $http.get(settings.apiUrlBase + '/users'); - }; + this.getUserSetting = function() { + return $http.get(settings.apiUrlBase + '/users'); + }; - this.getUserLog = function() { - return $http.get(settings.apiUrlBase + '/users/logs'); - } - this.getClusters = function() { - return $http.get(settings.apiUrlBase + '/clusters'); - }; + this.getUserLog = function() { + return $http.get(settings.apiUrlBase + '/users/logs'); + } + this.getClusters = function() { + return $http.get(settings.apiUrlBase + '/clusters'); + }; - this.getClusterById = function(id) { - return $http.get(settings.apiUrlBase + '/clusters/' + id); - }; + this.getClusterById = function(id) { + return $http.get(settings.apiUrlBase + '/clusters/' + id); + }; - this.getClusterProgress = function(id) { - return $http.get(settings.apiUrlBase + '/clusters/' + id + '/state'); - }; + this.getClusterProgress = function(id) { + return $http.get(settings.apiUrlBase + '/clusters/' + id + '/state'); + }; - this.getClusterConfig = function(id) { - return $http.get(settings.apiUrlBase + '/clusters/' + id + '/config'); - }; + this.getClusterConfig = function(id) { + return $http.get(settings.apiUrlBase + '/clusters/' + id + '/config'); + }; - this.updateClusterConfig = function(id, config) { - return $http.put(settings.apiUrlBase + '/clusters/' + id + '/config', angular.toJson(config)); - }; + this.updateClusterConfig = function(id, config) { + return $http.put(settings.apiUrlBase + '/clusters/' + id + '/config', angular.toJson(config)); + }; - this.getClusterMetadata = function(id) { - return $http.get(settings.apiUrlBase + '/clusters/' + id + '/metadata'); - }; + this.getClusterMetadata = function(id) { + return $http.get(settings.apiUrlBase + '/clusters/' + id + '/metadata'); + }; - this.getSubnetConfig = function() { - return $http.get(settings.apiUrlBase + '/subnets'); - }; + this.getSubnetConfig = function() { + return $http.get(settings.apiUrlBase + '/subnets'); + }; - this.postSubnetConfig = function(subnet_config) { - return $http.post(settings.apiUrlBase + '/subnets', angular.toJson(subnet_config)); - }; + this.postSubnetConfig = function(subnet_config) { + return $http.post(settings.apiUrlBase + '/subnets', angular.toJson(subnet_config)); + }; - this.putSubnetConfig = function(id, subnet_config) { - return $http.put(settings.apiUrlBase + '/subnets/' + id, angular.toJson(subnet_config)); - }; + this.putSubnetConfig = function(id, subnet_config) { + return $http.put(settings.apiUrlBase + '/subnets/' + id, angular.toJson(subnet_config)); + }; - this.deleteSubnet = function(id) { - return $http.delete(settings.apiUrlBase + '/subnets/' + id); - }; + this.deleteSubnet = function(id) { + return $http.delete(settings.apiUrlBase + '/subnets/' + id); + }; - // keep routing table for later use - /* + // keep routing table for later use + /* this.postRoutingTable = function(id, routing_table) { return $http.post(settings.apiUrlBase + '/clusters/' + id + '/routing-table', angular.toJson(routing_table)); }; @@ -171,233 +169,233 @@ angular.module('compass.services', []) }; */ - this.getTimezones = function() { - return $http.get(settings.metadataUrlBase + '/timezone.json'); - }; + this.getTimezones = function() { + return $http.get(settings.metadataUrlBase + '/timezone.json'); + }; - this.postClusterActions = function(id, actions) { - return $http.post(settings.apiUrlBase + '/clusters/' + id + '/action', angular.toJson(actions)); - }; + this.postClusterActions = function(id, actions) { + return $http.post(settings.apiUrlBase + '/clusters/' + id + '/action', angular.toJson(actions)); + }; - this.putHost = function(id, config) { - return $http.put(settings.apiUrlBase + '/hosts/' + id, angular.toJson(config)); - }; + this.putHost = function(id, config) { + return $http.put(settings.apiUrlBase + '/hosts/' + id, angular.toJson(config)); + }; - this.postHostNetwork = function(id, network) { - return $http.post(settings.apiUrlBase + '/hosts/' + id + '/networks', angular.toJson(network)); - }; + this.postHostNetwork = function(id, network) { + return $http.post(settings.apiUrlBase + '/hosts/' + id + '/networks', angular.toJson(network)); + }; - this.putHostNetwork = function(id, networkId, network) { - return $http.put(settings.apiUrlBase + '/hosts/' + id + '/networks/' + networkId, angular.toJson(network)); - }; + this.putHostNetwork = function(id, networkId, network) { + return $http.put(settings.apiUrlBase + '/hosts/' + id + '/networks/' + networkId, angular.toJson(network)); + }; - this.getClusterHosts = function(clusterId, hostId) { - return $http.get(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts'); - }; + this.getClusterHosts = function(clusterId, hostId) { + return $http.get(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts'); + }; - this.updateClusterHost = function(clusterId, hostId, data) { - return $http.put(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts/' + hostId, angular.toJson(data)); - }; + this.updateClusterHost = function(clusterId, hostId, data) { + return $http.put(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts/' + hostId, angular.toJson(data)); + }; - this.updateClusterHostConfig = function(clusterId, hostId, config) { - return $http.put(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts/' + hostId + '/config', angular.toJson(config)); - }; + this.updateClusterHostConfig = function(clusterId, hostId, config) { + return $http.put(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts/' + hostId + '/config', angular.toJson(config)); + }; - this.getClusterHostProgress = function(clusterId, hostId) { - return $http.get(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts/' + hostId + '/state'); - }; + this.getClusterHostProgress = function(clusterId, hostId) { + return $http.get(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts/' + hostId + '/state'); + }; - this.deleteHost = function(id) { - return $http.delete(settings.apiUrlBase + '/hosts/' + id); - }; -/* + this.deleteHost = function(id) { + return $http.delete(settings.apiUrlBase + '/hosts/' + id); + }; + /* this.deleteHost = function(clusterId, hostId) { return $http.delete(settings.apiUrlBase + '/clusters/' + clusterId + '/hosts/' + hostId); }; */ - this.monitorHosts = function(id) { - // This differ from the main hosts API because it has status/alert information - // /monit/api/cluster//hosts - return $http.get(settings.monitoringUrlBase + '/clusters/' + id + '/hosts'); - }; + this.monitorHosts = function(id) { + // This differ from the main hosts API because it has status/alert information + // /monit/api/cluster//hosts + return $http.get(settings.monitoringUrlBase + '/clusters/' + id + '/hosts'); + }; -/* this.monitorProxy = function(px_url) { + /* this.monitorProxy = function(px_url) { // Leave for now may delete later // /monit/api/proxy/ return $http.get(settings.monitoringUrlBase + '/proxy/' + px_url); }; */ - this.monitorMetrics = function() { - // This returns a flat json list of metrics currently or historically have been collected - // /monit/api/metrics - return $http.get(settings.monitoringUrlBase + '/metrics'); - }; + this.monitorMetrics = function() { + // This returns a flat json list of metrics currently or historically have been collected + // /monit/api/metrics + return $http.get(settings.monitoringUrlBase + '/metrics'); + }; - this.monitorMetricsTree = function() { - // This will also order the metrics in a tree - // /monit/api/metricstree - return $http.get(settings.monitoringUrlBase + '/metricstree'); - }; + this.monitorMetricsTree = function() { + // This will also order the metrics in a tree + // /monit/api/metricstree + return $http.get(settings.monitoringUrlBase + '/metricstree'); + }; - this.monitorHostMetric = function(clusterId, hostName, metricName) { - // Returns a single metric for a cluster host - // /monit/api/cluster//host//metric/ - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/hosts/' + hostName + '/metric/' + metricName); - }; + this.monitorHostMetric = function(clusterId, hostName, metricName) { + // Returns a single metric for a cluster host + // /monit/api/cluster//host//metric/ + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/hosts/' + hostName + '/metric/' + metricName); + }; - this.monitorHostGroupMetric = function(clusterId, groupName, metricName) { - // Returns a single metric for a cluster hostgroup - // /monit/api/cluster//hostgroup//metric/ - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/hostgroups/' + groupName + '/metric/' + metricName); - }; + this.monitorHostGroupMetric = function(clusterId, groupName, metricName) { + // Returns a single metric for a cluster hostgroup + // /monit/api/cluster//hostgroup//metric/ + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/hostgroups/' + groupName + '/metric/' + metricName); + }; - this.monitorClusterMetric = function(clusterId, metricName) { - // Returns a single metric for a cluster hostgroup - // /monit/api/cluster//metric/ - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/metrics/' + metricName); - }; + this.monitorClusterMetric = function(clusterId, metricName) { + // Returns a single metric for a cluster hostgroup + // /monit/api/cluster//metric/ + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/metrics/' + metricName); + }; - this.monitorAlarms = function(clusterId) { - // Returns all alarm data for a cluster host - // /monit/api/cluster//alarms - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/alarms'); - }; + this.monitorAlarms = function(clusterId) { + // Returns all alarm data for a cluster host + // /monit/api/cluster//alarms + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/alarms'); + }; - this.monitorEvents = function(id) { - // Reurns all event data for a cluster host - // /monit/api/cluster//events - return $http.get(settings.monitoringUrlBase + '/clusters/' + id + '/events'); - }; + this.monitorEvents = function(id) { + // Reurns all event data for a cluster host + // /monit/api/cluster//events + return $http.get(settings.monitoringUrlBase + '/clusters/' + id + '/events'); + }; - this.monitorTopology = function(clusterId) { - // Returns a nested json of networks and servers - // /monit/api/cluster//topology - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/topology'); - }; + this.monitorTopology = function(clusterId) { + // Returns a nested json of networks and servers + // /monit/api/cluster//topology + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/topology'); + }; - this.monitorServiceTopology = function(clusterId) { - // Returns a nested json of servers, roles and metrics - // /monit/api/cluster//servicetopology - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/servicetopology'); - }; + this.monitorServiceTopology = function(clusterId) { + // Returns a nested json of servers, roles and metrics + // /monit/api/cluster//servicetopology + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/servicetopology'); + }; - this.monitorOverview = function(clusterId) { - // Returns a nested json for constructing the overview page - // /monit/api/cluster//overview - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/overview'); - }; + this.monitorOverview = function(clusterId) { + // Returns a nested json for constructing the overview page + // /monit/api/cluster//overview + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/overview'); + }; - this.monitorUsers = function(clusterId) { - // Returns a flat json list of all cluster users - // /monit/api/cluster//users - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/users'); - }; + this.monitorUsers = function(clusterId) { + // Returns a flat json list of all cluster users + // /monit/api/cluster//users + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/users'); + }; - this.monitorUser = function(clusterId, userName) { - // Returns json information on a particliar user - // /monit/api/cluster//user/ - return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/user' + userName); - }; - } -]) - -.service('sortingService', function() { - this.ipAddressPre = function(a) { - var m = a.split("."), - x = ""; - - for (var i = 0; i < m.length; i++) { - var item = m[i]; - if (item.length == 1) { - x += "00" + item; - } else if (item.length == 2) { - x += "0" + item; - } else { - x += item; - } + this.monitorUser = function(clusterId, userName) { + // Returns json information on a particliar user + // /monit/api/cluster//user/ + return $http.get(settings.monitoringUrlBase + '/clusters/' + clusterId + '/user' + userName); + }; } - return x; - }; -}) + ]) + servicesModule.service('sortingService', function() { + this.ipAddressPre = function(a) { + var m = a.split("."), + x = ""; -.factory('wizardFactory', [ - - function() { - var wizard = {}; - wizard.init = function() { - wizard.cluster = {}; - wizard.steps = []; - wizard.commit = {}; - wizard.servers = []; - wizard.allServers = []; - //wizard.adapter = {}; // - wizard.generalConfig = {}; - wizard.subnetworks = []; - wizard.routingtable = []; - wizard.generalConfig = {}; - wizard.interfaces = {}; - wizard.partition = {}; - wizard.server_credentials = {}; - wizard.service_credentials = {}; - wizard.console_credentials = {}; - wizard.network_mapping = {}; + for (var i = 0; i < m.length; i++) { + var item = m[i]; + if (item.length == 1) { + x += "00" + item; + } else if (item.length == 2) { + x += "0" + item; + } else { + x += item; + } + } + return x; }; + }) - wizard.init(); - wizard.preConfig = function(config) { - //wizard.setClusterInfo(config.cluster); - wizard.setInterfaces(config.interface); - wizard.setGeneralConfig(config.general); - wizard.setPartition(config.partition); - wizard.setServerCredentials(config.server_credentials); - wizard.setServiceCredentials(config.service_credentials); - wizard.setConsoleCredentials(config.console_credentials); - wizard.setNetworkMapping(config.network_mapping); - }; + servicesModule.factory('wizardFactory', [ - wizard.setClusterInfo = function(cluster) { - wizard.cluster = cluster; - }; + function() { + var wizard = {}; + wizard.init = function() { + wizard.cluster = {}; + wizard.steps = []; + wizard.commit = {}; + wizard.servers = []; + wizard.allServers = []; + //wizard.adapter = {}; // + wizard.generalConfig = {}; + wizard.subnetworks = []; + wizard.routingtable = []; + wizard.generalConfig = {}; + wizard.interfaces = {}; + wizard.partition = {}; + wizard.server_credentials = {}; + wizard.service_credentials = {}; + wizard.console_credentials = {}; + wizard.network_mapping = {}; + }; - wizard.getClusterInfo = function() { - return angular.copy(wizard.cluster); - }; + wizard.init(); - wizard.setSteps = function(steps) { - wizard.steps = steps; - }; + wizard.preConfig = function(config) { + //wizard.setClusterInfo(config.cluster); + wizard.setInterfaces(config.interface); + wizard.setGeneralConfig(config.general); + wizard.setPartition(config.partition); + wizard.setServerCredentials(config.server_credentials); + wizard.setServiceCredentials(config.service_credentials); + wizard.setConsoleCredentials(config.console_credentials); + wizard.setNetworkMapping(config.network_mapping); + }; - wizard.getSteps = function() { - return angular.copy(wizard.steps); - }; + wizard.setClusterInfo = function(cluster) { + wizard.cluster = cluster; + }; - wizard.setCommitState = function(commitState) { - wizard.commit = commitState; - }; + wizard.getClusterInfo = function() { + return angular.copy(wizard.cluster); + }; - wizard.getCommitState = function() { - return wizard.commit; - }; + wizard.setSteps = function(steps) { + wizard.steps = steps; + }; - wizard.setAllMachinesHost = function(server) { - wizard.allServers = server; - }; + wizard.getSteps = function() { + return angular.copy(wizard.steps); + }; - wizard.getAllMachinesHost = function() { - return angular.copy(wizard.allServers); - }; + wizard.setCommitState = function(commitState) { + wizard.commit = commitState; + }; - wizard.setServers = function(servers) { - wizard.servers = servers; - }; + wizard.getCommitState = function() { + return wizard.commit; + }; - wizard.getServers = function() { - return angular.copy(wizard.servers); - }; -/* + wizard.setAllMachinesHost = function(server) { + wizard.allServers = server; + }; + + wizard.getAllMachinesHost = function() { + return angular.copy(wizard.allServers); + }; + + wizard.setServers = function(servers) { + wizard.servers = servers; + }; + + wizard.getServers = function() { + return angular.copy(wizard.servers); + }; + /* wizard.setAdapter = function(adapter) { //// wizard.adapter = adapter; }; @@ -406,24 +404,24 @@ angular.module('compass.services', []) return angular.copy(wizard.adapter); }; */ - wizard.setGeneralConfig = function(config) { - wizard.generalConfig = config; - }; + wizard.setGeneralConfig = function(config) { + wizard.generalConfig = config; + }; - wizard.getGeneralConfig = function() { - return angular.copy(wizard.generalConfig); - }; + wizard.getGeneralConfig = function() { + return angular.copy(wizard.generalConfig); + }; - wizard.setSubnetworks = function(subnetworks) { - wizard.subnetworks = subnetworks; - }; + wizard.setSubnetworks = function(subnetworks) { + wizard.subnetworks = subnetworks; + }; - wizard.getSubnetworks = function() { - return angular.copy(wizard.subnetworks); - }; + wizard.getSubnetworks = function() { + return angular.copy(wizard.subnetworks); + }; - // keey routing table for later use - /* + // keey routing table for later use + /* wizard.setRoutingTable = function(routingTb) { wizard.routingtable = routingTb; }; @@ -433,71 +431,72 @@ angular.module('compass.services', []) }; */ - wizard.setInterfaces = function(interfaces) { - wizard.interfaces = interfaces; - }; + wizard.setInterfaces = function(interfaces) { + wizard.interfaces = interfaces; + }; - wizard.getInterfaces = function() { - return angular.copy(wizard.interfaces); - }; + wizard.getInterfaces = function() { + return angular.copy(wizard.interfaces); + }; - wizard.setPartition = function(partition) { - wizard.partition = partition; - }; + wizard.setPartition = function(partition) { + wizard.partition = partition; + }; - wizard.getPartition = function() { - return angular.copy(wizard.partition); - }; + wizard.getPartition = function() { + return angular.copy(wizard.partition); + }; - wizard.setServerCredentials = function(credentials) { - wizard.server_credentials = credentials; - }; + wizard.setServerCredentials = function(credentials) { + wizard.server_credentials = credentials; + }; - wizard.getServerCredentials = function() { - return angular.copy(wizard.server_credentials); + wizard.getServerCredentials = function() { + return angular.copy(wizard.server_credentials); + } + wizard.setServiceCredentials = function(credentials) { + wizard.service_credentials = credentials; + }; + + wizard.getServiceCredentials = function() { + return angular.copy(wizard.service_credentials); + }; + + wizard.setConsoleCredentials = function(credentials) { + wizard.console_credentials = credentials; + }; + + wizard.getConsoleCredentials = function() { + return angular.copy(wizard.console_credentials); + }; + + wizard.setNetworkMapping = function(mapping) { + wizard.network_mapping = mapping; + }; + + wizard.getNetworkMapping = function() { + return angular.copy(wizard.network_mapping); + }; + + return wizard; } - wizard.setServiceCredentials = function(credentials) { - wizard.service_credentials = credentials; - }; + ]) - wizard.getServiceCredentials = function() { - return angular.copy(wizard.service_credentials); - }; - - wizard.setConsoleCredentials = function(credentials) { - wizard.console_credentials = credentials; - }; - - wizard.getConsoleCredentials = function() { - return angular.copy(wizard.console_credentials); - }; - - wizard.setNetworkMapping = function(mapping) { - wizard.network_mapping = mapping; - }; - - wizard.getNetworkMapping = function() { - return angular.copy(wizard.network_mapping); - }; - - return wizard; - } -]) - -.service('authService', ['$http', 'dataService', - function($http, dataService) { - this.isAuthenticated = false; - - this.setLogin = function(isLogin) { - this.isAuthenticated = isLogin; - } - - this.login = function(user) { - return dataService.login(user); - }; - - this.logout = function() { + servicesModule.service('authService', ['$http', 'dataService', + function($http, dataService) { this.isAuthenticated = false; - }; - } -]) + + this.setLogin = function(isLogin) { + this.isAuthenticated = isLogin; + } + + this.login = function(user) { + return dataService.login(user); + }; + + this.logout = function() { + this.isAuthenticated = false; + }; + } + ]) +}) \ No newline at end of file diff --git a/v2/src/app/topnav/topnav.js b/v2/src/app/topnav/topnav.js index a5749ee..cf92ed4 100644 --- a/v2/src/app/topnav/topnav.js +++ b/v2/src/app/topnav/topnav.js @@ -1,18 +1,21 @@ -angular.module('compass.topnav', [ - 'ui.router', - 'ui.bootstrap' -]) +define(['angular'], function() { + var topNavModule = angular.module('compass.topnav', [ + 'ui.router', + 'ui.bootstrap' + ]); -.controller('topnavCtrl', function($scope, $http, dataService, $rootScope) { - // get all clusters - dataService.getClusters().success(function(data) { - $scope.clusters = data; + topNavModule.controller('topnavCtrl', function($scope, $http, dataService, $rootScope) { + // get all clusters + dataService.getClusters().success(function(data) { + $scope.clusters = data; + }); + $rootScope.$on('clusters', function(event, data) { + $scope.clusters = data; + }); }); - $rootScope.$on('clusters', function(event, data) { - $scope.clusters = data; - }) -}).directive('topnav', function() { - return { - templateUrl: 'src/app/topnav/topnav.tpl.html' - }; -}); + topNavModule.directive('topnav', function() { + return { + templateUrl: 'src/app/topnav/topnav.tpl.html' + }; + }); +}); \ No newline at end of file diff --git a/v2/src/app/user/user-setting.html b/v2/src/app/user/user-setting.html index b371834..13f41de 100644 --- a/v2/src/app/user/user-setting.html +++ b/v2/src/app/user/user-setting.html @@ -163,6 +163,7 @@ + diff --git a/v2/src/app/user/userprofile.js b/v2/src/app/user/userprofile.js index 1d92544..ea3d661 100644 --- a/v2/src/app/user/userprofile.js +++ b/v2/src/app/user/userprofile.js @@ -1,17 +1,18 @@ -var app = angular.module('compass.userProfile', [ - 'ui.router', - 'ui.bootstrap' -]) +define(['angular'], function() { + var userProfileModule = angular.module('compass.userProfile', [ + 'ui.router', + 'ui.bootstrap' + ]); -.config(function($stateProvider, $urlRouterProvider) { - $stateProvider - .state('userProfile', { - url: '/userProfile', - //controller: 'userProfileCtrl', - templateUrl: 'src/app/user/user-profile.html', - authenticate: true, - //resolve: {} - }); + userProfileModule.config(function($stateProvider, $urlRouterProvider) { + $stateProvider + .state('userProfile', { + url: '/userProfile', + //controller: 'userProfileCtrl', + templateUrl: 'src/app/user/user-profile.html', + authenticate: true, + //resolve: {} + }); + }); }) - //combine usersetting and userprofile into a single file? \ No newline at end of file diff --git a/v2/src/app/user/usersetting.js b/v2/src/app/user/usersetting.js index 741e360..09bf306 100644 --- a/v2/src/app/user/usersetting.js +++ b/v2/src/app/user/usersetting.js @@ -1,86 +1,44 @@ -var app = angular.module('compass.userSetting', [ - 'ui.router', - 'ui.bootstrap', - 'ngTable', - 'ngBootstrap' -]) +define(['ngBsDaterangepicker', 'uiRouter', 'uiBootstrap', 'angularTable'], function() { + 'use strict'; -.config(function($stateProvider, $urlRouterProvider) { - $stateProvider - .state('userSetting', { - url: '/userSetting', - controller: 'userSettingCtrl', - templateUrl: 'src/app/user/user-setting.html', - authenticate: true, - resolve: { - userSettingData: function($q, dataService) { - var deferred = $q.defer(); - dataService.getUserSetting().success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; - }, - userLogData: function($q, dataService) { - var deferred = $q.defer(); - dataService.getUserLog().success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; + var userSettingModule = angular.module('compass.userSetting', [ + 'ui.router', + 'ui.bootstrap', + 'ngTable', + 'ngBootstrap' + ]); + + userSettingModule.config(function($stateProvider, $urlRouterProvider) { + $stateProvider + .state('userSetting', { + url: '/userSetting', + controller: 'userSettingCtrl', + templateUrl: 'src/app/user/user-setting.html', + authenticate: true, + resolve: { + userSettingData: function($q, dataService) { + var deferred = $q.defer(); + dataService.getUserSetting().success(function(data) { + deferred.resolve(data); + }); + return deferred.promise; + }, + userLogData: function($q, dataService) { + var deferred = $q.defer(); + dataService.getUserLog().success(function(data) { + deferred.resolve(data); + }); + return deferred.promise; + } } - } - }); - -}) - -.controller('userSettingCtrl', function($scope, $state, ngTableParams, $filter, dataService, userSettingData, $modal) { - $scope.userSetting = userSettingData; - var data = userSettingData; - $scope.tableParams = new ngTableParams({ - page: 1, - count: 10, - }, { - total: data.length, - getData: function($defer, params) { - var orderedData = params.sorting() ? - $filter('orderBy')(data, params.orderBy()) : - data; - $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); - } - }); - - $scope.edit = function() { - alert("Edit User?") - }; - $scope.delete = function() { - alert("Delete User?") - }; - - - $scope.newUser = {}; - $scope.open = function(size) { - var modalInstance = $modal.open({ - templateUrl: 'userSettingModal.html', - controller: UserModalCtrl, - resolve: { - newUser: function() { - return $scope.newUser; - } - } - }); - modalInstance.result.then(function(newUser) { - $scope.newUser = newUser; - dataService.createUser(newUser).success(function(data, status) { - $scope.userSetting.push(newUser); - $scope.tableParams.reload(); }); - $scope.newUser = {}; - }, function() { - // modal cancelled - }); - }; - dataService.getUserLog().success(function(data) { - $scope.userParams = new ngTableParams({ + }); + + userSettingModule.controller('userSettingCtrl', function($scope, $state, ngTableParams, $filter, dataService, userSettingData, $modal) { + $scope.userSetting = userSettingData; + var data = userSettingData; + $scope.tableParams = new ngTableParams({ page: 1, count: 10, }, { @@ -92,54 +50,100 @@ var app = angular.module('compass.userSetting', [ $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } }); - }); -}) -.directive('match', function() { - return { - require: 'ngModel', - restrict: 'A', - scope: { - match: '=' - }, - link: function(scope, elem, attrs, ctrl) { - scope.$watch(function() { - return (ctrl.$pristine && angular.isUndefined(ctrl.$modelValue)) || scope.match === ctrl.$modelValue; - }, function(currentValue) { - ctrl.$setValidity('match', currentValue); + $scope.edit = function() { + alert("Edit User?") + }; + $scope.delete = function() { + alert("Delete User?") + }; + + + $scope.newUser = {}; + $scope.open = function(size) { + var modalInstance = $modal.open({ + templateUrl: 'userSettingModal.html', + controller: UserModalCtrl, + resolve: { + newUser: function() { + return $scope.newUser; + } + } }); - } - }; -}); + modalInstance.result.then(function(newUser) { + $scope.newUser = newUser; + dataService.createUser(newUser).success(function(data, status) { + $scope.userSetting.push(newUser); + $scope.tableParams.reload(); + }); -app.filter('timeStampFilter', function () { - return function(items, dateRange) { - if (items !== undefined) { - var filtered = []; - var startDate = dateRange.startDate; - var endDate = dateRange.endDate; - for (var i = 0; i < items.length; i++) { - var item = items[i]; - var standardTime = moment(item.timestamp); - if (moment(standardTime).isAfter(startDate) && moment(standardTime).isBefore(endDate)) { - filtered.push(item); - } - } - return filtered; - } - }; -}) + $scope.newUser = {}; + }, function() { + // modal cancelled + }); + }; + dataService.getUserLog().success(function(data) { + $scope.userParams = new ngTableParams({ + page: 1, + count: 10, + }, { + total: data.length, + getData: function($defer, params) { + var orderedData = params.sorting() ? + $filter('orderBy')(data, params.orderBy()) : + data; + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); + } + }); + }); + }); -var UserModalCtrl = function($scope, $modalInstance, newUser) { - $scope.newUser = newUser; + userSettingModule.directive('match', function() { + return { + require: 'ngModel', + restrict: 'A', + scope: { + match: '=' + }, + link: function(scope, elem, attrs, ctrl) { + scope.$watch(function() { + return (ctrl.$pristine && angular.isUndefined(ctrl.$modelValue)) || scope.match === ctrl.$modelValue; + }, function(currentValue) { + ctrl.$setValidity('match', currentValue); + }); + } + }; + }); - $scope.ok = function() { - $scope.result = 'ok'; - $modalInstance.close($scope.newUser); - }; + userSettingModule.filter('timeStampFilter', function() { + return function(items, dateRange) { + if (items !== undefined) { + var filtered = []; + var startDate = dateRange.startDate; + var endDate = dateRange.endDate; + for (var i = 0; i < items.length; i++) { + var item = items[i]; + var standardTime = moment(item.timestamp); + if (moment(standardTime).isAfter(startDate) && moment(standardTime).isBefore(endDate)) { + filtered.push(item); + } + } + return filtered; + } + }; + }); - $scope.cancel = function() { - $modalInstance.dismiss('cancel'); - $scope.result = 'cancel'; + var UserModalCtrl = function($scope, $modalInstance, newUser) { + $scope.newUser = newUser; + + $scope.ok = function() { + $scope.result = 'ok'; + $modalInstance.close($scope.newUser); + }; + + $scope.cancel = function() { + $modalInstance.dismiss('cancel'); + $scope.result = 'cancel'; + }; }; -}; \ No newline at end of file +}); \ No newline at end of file diff --git a/v2/src/app/wizard/wizard.js b/v2/src/app/wizard/wizard.js index e8e3e2f..0adc038 100644 --- a/v2/src/app/wizard/wizard.js +++ b/v2/src/app/wizard/wizard.js @@ -1,507 +1,507 @@ -angular.module('compass.wizard', [ - 'ui.router', - 'ui.bootstrap', - 'ngTable', - 'compass.charts', - 'compass.findservers', - 'ngDragDrop', - 'ngTouch', - 'angularSpinner', - 'ngAnimate' -]) - -.config(function config($stateProvider) { - $stateProvider - .state('wizard', { - url: '/wizard/{id}?config', - controller: 'wizardCtrl', - templateUrl: 'src/app/wizard/wizard.tpl.html', - authenticate: true, - resolve: { - clusterData: function($stateParams, $q, dataService) { - var clusterId = $stateParams.id; - var deferred = $q.defer(); - dataService.getClusterById(clusterId).success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; - }, - machinesHostsData: function($q, dataService, clusterData) { - var deferred = $q.defer(); - dataService.getAllMachineHosts(clusterData.os_id).success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; - }, - wizardStepsData: function($q, dataService) { - var deferred = $q.defer(); - dataService.getWizardSteps().success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; - }, - clusterConfigData: function($stateParams, $q, dataService) { - var clusterId = $stateParams.id; - var deferred = $q.defer(); - dataService.getClusterConfig(clusterId).success(function(data) { - deferred.resolve(data); - }); - return deferred.promise; +define(['uiRouter', 'angularTable', 'angularDragDrop', 'angularTouch', 'ngSpinner', 'angularAnimate'], function() { + var wizardModule = angular.module('compass.wizard', [ + 'ui.router', + 'ui.bootstrap', + 'ngTable', + //'compass.charts', + //'compass.findservers', + 'ngDragDrop', + 'ngTouch', + 'angularSpinner', + 'ngAnimate' + ]); + wizardModule.config(function config($stateProvider) { + $stateProvider + .state('wizard', { + url: '/wizard/{id}?config', + controller: 'wizardCtrl', + templateUrl: 'src/app/wizard/wizard.tpl.html', + authenticate: true, + resolve: { + clusterData: function($stateParams, $q, dataService) { + var clusterId = $stateParams.id; + var deferred = $q.defer(); + dataService.getClusterById(clusterId).success(function(data) { + deferred.resolve(data); + }); + return deferred.promise; + }, + machinesHostsData: function($q, dataService, clusterData) { + var deferred = $q.defer(); + dataService.getAllMachineHosts(clusterData.os_id).success(function(data) { + deferred.resolve(data); + }); + return deferred.promise; + }, + wizardStepsData: function($q, dataService) { + var deferred = $q.defer(); + dataService.getWizardSteps().success(function(data) { + deferred.resolve(data); + }); + return deferred.promise; + }, + clusterConfigData: function($stateParams, $q, dataService) { + var clusterId = $stateParams.id; + var deferred = $q.defer(); + dataService.getClusterConfig(clusterId).success(function(data) { + deferred.resolve(data); + }); + return deferred.promise; + } } - } - }); -}) - -.controller('wizardCtrl', function($scope, dataService, wizardFactory, $stateParams, $state, $modal, clusterData, machinesHostsData, wizardStepsData, clusterConfigData, usSpinnerService) { - $scope.loading = false; - $scope.clusterId = $stateParams.id; - $scope.cluster = clusterData; - wizardFactory.setClusterInfo($scope.cluster); - wizardFactory.setAllMachinesHost(machinesHostsData); - - var oldConfig = clusterConfigData; - - $scope.$on('loading',function(event,data){ - $scope.loading = data; + }); }); - // get pre-config data for wizard - if ($stateParams.config == "true") { - dataService.getWizardPreConfig().success(function(data) { - wizardFactory.preConfig(data); - - if (oldConfig.os_config) { - if (oldConfig.os_config.general) { - wizardFactory.setGeneralConfig(oldConfig.os_config.general); - } - if (oldConfig.os_config.partition) { - wizardFactory.setPartition(oldConfig.os_config.partition); - } - if (oldConfig.os_config.server_credentials) { - wizardFactory.setServerCredentials(oldConfig.os_config.server_credentials); - } - } - if (oldConfig.package_config) { - if (oldConfig.package_config.security) { - if (oldConfig.package_config.security.service_credentials) { - wizardFactory.setServiceCredentials(oldConfig.package_config.security.service_credentials); - } - if (oldConfig.package_config.security.console_credentials) { - wizardFactory.setConsoleCredentials(oldConfig.package_config.security.console_credentials); - } - } - if (oldConfig.package_config.network_mapping) { - wizardFactory.setNetworkMapping(oldConfig.package_config.network_mapping); - } - } - - }); - } - - $scope.currentStep = 1; - $scope.maxStep = 1; - $scope.pendingStep = 1; - - // get the create-cluster-wizard steps for os, ts or os_and_ts - $scope.steps = wizardStepsData["os_and_ts"]; - wizardFactory.setSteps($scope.steps); - - // Watch commit state change - $scope.$watch(function() { + wizardModule.controller('wizardCtrl', function($scope, dataService, wizardFactory, $stateParams, $state, $modal, clusterData, machinesHostsData, wizardStepsData, clusterConfigData) { $scope.loading = false; - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { - if (newCommitState != oldCommitState && newCommitState.name == $scope.steps[$scope.currentStep - 1].name) { - if (newCommitState.state == "success") { - console.warn("### catch success in wizardCtrl ###", newCommitState, oldCommitState); - if (newCommitState.name == "review") { - $state.go("cluster.overview", { - 'id': $scope.cluster.id - }); - } - $scope.stepControl(goToPreviousStep = false); - if ($scope.currentStep > $scope.maxStep) { - $scope.maxStep = $scope.currentStep; - } - } else if (newCommitState.state == "error") { - console.warn("### catch error in wizardCtrl ###", newCommitState, oldCommitState); - $scope.openErrMessageModal(newCommitState.message); + $scope.clusterId = $stateParams.id; + $scope.cluster = clusterData; + wizardFactory.setClusterInfo($scope.cluster); + wizardFactory.setAllMachinesHost(machinesHostsData); - } else if (newCommitState.state == "goToPreviousStep") { - $scope.stepControl(goToPreviousStep = true); - if ($scope.currentStep > $scope.maxStep) { - $scope.maxStep = $scope.currentStep; + var oldConfig = clusterConfigData; + + $scope.$on('loading', function(event, data) { + $scope.loading = data; + }); + + // get pre-config data for wizard + if ($stateParams.config == "true") { + dataService.getWizardPreConfig().success(function(data) { + wizardFactory.preConfig(data); + + if (oldConfig.os_config) { + if (oldConfig.os_config.general) { + wizardFactory.setGeneralConfig(oldConfig.os_config.general); + } + if (oldConfig.os_config.partition) { + wizardFactory.setPartition(oldConfig.os_config.partition); + } + if (oldConfig.os_config.server_credentials) { + wizardFactory.setServerCredentials(oldConfig.os_config.server_credentials); + } } + if (oldConfig.package_config) { + if (oldConfig.package_config.security) { + if (oldConfig.package_config.security.service_credentials) { + wizardFactory.setServiceCredentials(oldConfig.package_config.security.service_credentials); + } + if (oldConfig.package_config.security.console_credentials) { + wizardFactory.setConsoleCredentials(oldConfig.package_config.security.console_credentials); + } + } + if (oldConfig.package_config.network_mapping) { + wizardFactory.setNetworkMapping(oldConfig.package_config.network_mapping); + } + } + + }); + } + + $scope.currentStep = 1; + $scope.maxStep = 1; + $scope.pendingStep = 1; + + // get the create-cluster-wizard steps for os, ts or os_and_ts + $scope.steps = wizardStepsData["os_and_ts"]; + wizardFactory.setSteps($scope.steps); + + // Watch commit state change + $scope.$watch(function() { + $scope.loading = false; + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { + if (newCommitState != oldCommitState && newCommitState.name == $scope.steps[$scope.currentStep - 1].name) { + if (newCommitState.state == "success") { + console.warn("### catch success in wizardCtrl ###", newCommitState, oldCommitState); + if (newCommitState.name == "review") { + $state.go("cluster.overview", { + 'id': $scope.cluster.id + }); + } + $scope.stepControl(goToPreviousStep = false); + if ($scope.currentStep > $scope.maxStep) { + $scope.maxStep = $scope.currentStep; + } + } else if (newCommitState.state == "error") { + console.warn("### catch error in wizardCtrl ###", newCommitState, oldCommitState); + $scope.openErrMessageModal(newCommitState.message); + + } else if (newCommitState.state == "goToPreviousStep") { + $scope.stepControl(goToPreviousStep = true); + if ($scope.currentStep > $scope.maxStep) { + $scope.maxStep = $scope.currentStep; + } + } + } + $scope.loading = false; + }); + + $scope.stepControl = function(goToPrevious) { + if ($scope.pendingStep <= $scope.maxStep + 1) { + var previousStepsIncomplete = false; + for (var i = 0; i < $scope.pendingStep - 1; i++) { + if ($scope.steps[i].state == "incomplete") { + previousStepsIncomplete = true; + break; + } + } + if (previousStepsIncomplete) { + var message = { + "message": "Please make sure pre-requisite steps are complete." + }; + alert(message.message); + } else { + $scope.updateStepProgress($scope.pendingStep, $scope.currentStep, goToPrevious); + $scope.currentStep = $scope.pendingStep; + } + } else { + var message = { + "message": "Please complete previous steps first" + }; + alert(message.message); + $scope.pendingStep = $scope.currentStep; } } - $scope.loading = false; - }); - $scope.stepControl = function(goToPrevious) { - if ($scope.pendingStep <= $scope.maxStep + 1) { - var previousStepsIncomplete = false; - for (var i = 0; i < $scope.pendingStep - 1; i++) { - if ($scope.steps[i].state == "incomplete") { - previousStepsIncomplete = true; + for (var i = 0; i < $scope.steps.length; i++) { + if ($scope.steps[i].name == 'network') { + $scope.networkStep = i; + } + if ($scope.steps[i].name == 'role_assign') { + $scope.roleAssignStep = i; + } + if ($scope.steps[i].name == 'network_mapping') { + $scope.networkMappingStep = i; + } + } + + // Updates CSS Classes on Step state change + $scope.updateStepProgress = function(newStep, oldStep, goToPrevious) { + $scope.steps[newStep - 1].state = "active"; + + if (goToPrevious) { + $scope.steps[oldStep - 1].state = ""; + } else { + $scope.steps[oldStep - 1].state = "complete"; + } + + $scope.steps[oldStep - 1].state = "complete"; + if ($scope.steps[newStep - 1].name == 'sv_selection') { + if ($scope.maxStep > $scope.networkStep) { + $scope.steps[$scope.networkStep].state = "incomplete"; + } + if ($scope.maxStep > $scope.roleAssignStep) { + $scope.steps[$scope.roleAssignStep].state = "incomplete"; + } + if ($scope.maxStep > $scope.networkMappingStep) { + $scope.steps[$scope.networkMappingStep].state = "incomplete"; + } + } + if (newStep == $scope.networkStep + 1) { + if ($scope.maxStep > $scope.networkMappingStep) { + $scope.steps[$scope.networkMappingStep].state = "incomplete"; + } + } + if (oldStep == $scope.steps.length) { + $scope.steps[$scope.steps.length - 1].state = ""; + } + }; + + $scope.triggerCommit = function(stepId, nextStep) { + var sendRequest = false; + if (nextStep > stepId) { + sendRequest = true; + } + if ($scope.steps[stepId - 1].name != "review") { + var commitState = { + "name": $scope.steps[stepId - 1].name, + "state": "triggered", + "sendRequest": sendRequest, + "message": {} + }; + wizardFactory.setCommitState(commitState); + } else { + $scope.stepControl(); + } + }; + + $scope.deploy = function() { + var wizard_complete = true; + for (var i = 0; i < $scope.steps.length - 1; i++) { + if ($scope.steps[i].state != "complete") { + wizard_complete = false; break; } } - if (previousStepsIncomplete) { - var message = { - "message": "Please make sure pre-requisite steps are complete." - }; - alert(message.message); - } else { - $scope.updateStepProgress($scope.pendingStep, $scope.currentStep, goToPrevious); - $scope.currentStep = $scope.pendingStep; - } - } else { - var message = { - "message": "Please complete previous steps first" - }; - alert(message.message); - $scope.pendingStep = $scope.currentStep; - } - } - - for (var i = 0; i < $scope.steps.length; i++) { - if ($scope.steps[i].name == 'network') { - $scope.networkStep = i; - } - if ($scope.steps[i].name == 'role_assign') { - $scope.roleAssignStep = i; - } - if ($scope.steps[i].name == 'network_mapping') { - $scope.networkMappingStep = i; - } - } - - // Updates CSS Classes on Step state change - $scope.updateStepProgress = function(newStep, oldStep, goToPrevious) { - $scope.steps[newStep - 1].state = "active"; - - if (goToPrevious) { - $scope.steps[oldStep - 1].state = ""; - } else { - $scope.steps[oldStep - 1].state = "complete"; - } - - $scope.steps[oldStep - 1].state = "complete"; - if ($scope.steps[newStep - 1].name == 'sv_selection') { - if ($scope.maxStep > $scope.networkStep) { - $scope.steps[$scope.networkStep].state = "incomplete"; - } - if ($scope.maxStep > $scope.roleAssignStep) { - $scope.steps[$scope.roleAssignStep].state = "incomplete"; - } - if ($scope.maxStep > $scope.networkMappingStep) { - $scope.steps[$scope.networkMappingStep].state = "incomplete"; - } - } - if (newStep == $scope.networkStep + 1) { - if ($scope.maxStep > $scope.networkMappingStep) { - $scope.steps[$scope.networkMappingStep].state = "incomplete"; - } - } - if (oldStep == $scope.steps.length) { - $scope.steps[$scope.steps.length - 1].state = ""; - } - }; - - $scope.triggerCommit = function(stepId, nextStep) { - var sendRequest = false; - if (nextStep > stepId) { - sendRequest = true; - } - if ($scope.steps[stepId - 1].name != "review") { - var commitState = { - "name": $scope.steps[stepId - 1].name, - "state": "triggered", - "sendRequest": sendRequest, - "message": {} - }; - wizardFactory.setCommitState(commitState); - } else { - $scope.stepControl(); - } - }; - - $scope.deploy = function() { - var wizard_complete = true; - for (var i = 0; i < $scope.steps.length - 1; i++) { - if ($scope.steps[i].state != "complete") { - wizard_complete = false; - break; - } - } - if (wizard_complete) { - var commitState = { - "name": "review", - "state": "triggered", - "message": "" - }; - wizardFactory.setCommitState(commitState); - } - }; - - $scope.stepForward = function() { - $scope.pendingStep = $scope.currentStep + 1;; - $scope.triggerCommit($scope.currentStep,$scope.pendingStep); - }; - - // go to previous step - $scope.stepBackward = function() { - $scope.pendingStep = $scope.currentStep - 1; - $scope.triggerCommit($scope.currentStep,$scope.pendingStep); - }; - - // go to step by stepId - $scope.skipForward = function(stepId) { - if ($scope.currentStep != stepId) { - $scope.pendingStep = stepId; - $scope.triggerCommit($scope.currentStep, stepId); - } - }; - - $scope.openErrMessageModal = function(message) { - var modalInstance = $modal.open({ - templateUrl: "messagemodal.html", - controller: wizardModalInstanceCtrl, - resolve: { - warning: function() { - return message; - } - } - }); - modalInstance.result.then(function() { - - }, function() { - console.log("modal dismissed") - }) - }; - - dataService.getSubnetConfig().success(function(data) { - wizardFactory.setSubnetworks(data); - }); -}) - -.animation('.fade-animation', function() { - return { - enter: function(element, done) { - element.css('display', 'none'); - element.fadeIn(500, done); - return function() { - element.stop(); - } - }, - leave: function(element, done) { - element.fadeOut(500, done) - return function() { - element.stop(); - } - } - } -}) - -.controller('svSelectCtrl', function($scope, wizardFactory, dataService, $filter, ngTableParams, sortingService) { - $scope.hideunselected = ''; - $scope.search = {}; - - var cluster = wizardFactory.getClusterInfo(); - - $scope.allservers = wizardFactory.getAllMachinesHost(); - - $scope.tableParams = new ngTableParams({ - page: 1, // show first page - count: $scope.allservers.length // count per page - }, { - counts: [], // hide count-per-page box - total: $scope.allservers.length, // length of data - getData: function($defer, params) { - var reverse = false; - var orderBy = params.orderBy()[0]; - var orderBySort = ""; - var orderByColumn = ""; - - if (orderBy) { - orderByColumn = orderBy.substring(1); - orderBySort = orderBy.substring(0, 1); - if (orderBySort == "+") { - reverse = false; - } else { - reverse = true; - } - } - - var orderedData = params.sorting() ? - $filter('orderBy')($scope.allservers, function(item) { - if (orderByColumn == "switch_ip") { - return sortingService.ipAddressPre(item.switch_ip); - } else { - return item[orderByColumn]; - } - }, reverse) : $scope.allservers; - - $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); - } - }); - - - $scope.selectAllServers = function(flag) { - if (flag) { - angular.forEach($scope.allservers, function(sv) { - sv.selected = true; - }) - } else { - angular.forEach($scope.allservers, function(sv) { - sv.selected = false; - }) - } - }; - - dataService.getServerColumns().success(function(data) { - $scope.server_columns = data.showall; - }); - - $scope.hideUnselected = function() { - if ($scope.hideunselected) { - $scope.search.selected = true; - } else { - delete $scope.search.selected; - } - }; - - $scope.ifPreSelect = function(server) { - if (server.clusters) { - angular.forEach(server.clusters, function(svCluster) { - if (svCluster.id == cluster.id) { - server.selected = true; - } - }) - } - }; - - $scope.$watch(function() { - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { - if (newCommitState !== undefined) { - if (newCommitState.name == "sv_selection" && newCommitState.state == "triggered") { - $scope.commit(); - } - } - }); - - $scope.commit = function() { - $scope.$emit("loading",true); - var selectedServers = []; - var noSelection = true; - angular.forEach($scope.allservers, function(sv) { - if (sv.selected) { - noSelection = false; - selectedServers.push(sv); - } - }) - if (noSelection) { - var message = { - "message": "Please select at least one server" - } - var commitState = { - "name": "sv_selection", - "state": "error", - "message": message - }; - wizardFactory.setCommitState(commitState); - } else { - var addHostsAction = { - "add_hosts": { - "machines": [] - } - }; - angular.forEach($scope.allservers, function(server) { - if (server.selected) { - if (server.reinstallos === undefined) { - addHostsAction.add_hosts.machines.push({ - "machine_id": server.machine_id - }); - } else { - addHostsAction.add_hosts.machines.push({ - "machine_id": server.machine_id, - "reinstall_os": server.reinstallos - }); - } - } - }); - - // add hosts - dataService.postClusterActions(cluster.id, addHostsAction).success(function(data) { + if (wizard_complete) { var commitState = { - "name": "sv_selection", - "state": "success", + "name": "review", + "state": "triggered", "message": "" }; wizardFactory.setCommitState(commitState); - wizardFactory.setAllMachinesHost($scope.allservers); + } + }; - }).error(function(response) { - var commitState = { - "name": "sv_selection", - "state": "success", - "message": response - }; - wizardFactory.setCommitState(commitState); - }); - //wizardFactory.setServers(selectedServers); - } - }; + $scope.stepForward = function() { + $scope.pendingStep = $scope.currentStep + 1;; + $scope.triggerCommit($scope.currentStep, $scope.pendingStep); + }; - // add newly found servers at the top if allservers array - $scope.$watch('foundResults', function(newResults, oldResults) { - if (newResults != oldResults) { - for (var i = 0; i < newResults.length; i++) { - var sv = $filter('filter')($scope.allservers, newResults[i].mac, true); - if (sv.length == 0) { - newResults[i].machine_id = newResults[i].id; - delete newResults[i]['id']; - newResults[i].new = true; - $scope.allservers.unshift(newResults[i]); + // go to previous step + $scope.stepBackward = function() { + $scope.pendingStep = $scope.currentStep - 1; + $scope.triggerCommit($scope.currentStep, $scope.pendingStep); + }; + + // go to step by stepId + $scope.skipForward = function(stepId) { + if ($scope.currentStep != stepId) { + $scope.pendingStep = stepId; + $scope.triggerCommit($scope.currentStep, stepId); + } + }; + + $scope.openErrMessageModal = function(message) { + var modalInstance = $modal.open({ + templateUrl: "messagemodal.html", + controller: wizardModalInstanceCtrl, + resolve: { + warning: function() { + return message; + } } - } + }); + modalInstance.result.then(function() { - if ($scope.tableParams) { - $scope.tableParams.$params.count = $scope.allservers.length; - $scope.tableParams.reload(); - } - } - }, true); + }, function() { + console.log("modal dismissed") + }) + }; -}) - -.controller('globalCtrl', function($scope, wizardFactory, dataService, $q) { - var cluster = wizardFactory.getClusterInfo(); - - $scope.general = wizardFactory.getGeneralConfig(); - - if (!$scope.general["dns_servers"]) { - $scope.general["dns_servers"] = [""]; - } - if (!$scope.general["search_path"]) { - $scope.general["search_path"] = [""]; - } - if (!$scope.general["no_proxy"]) { - $scope.general["no_proxy"] = [""]; - } - - $scope.addValue = function(key) { - $scope.general[key].push(""); - }; - - dataService.getTimezones().success(function(data) { - $scope.timezones = data; + dataService.getSubnetConfig().success(function(data) { + wizardFactory.setSubnetworks(data); + }); }); - //For Routing Table Section - //keep routing table for later use - /* + wizardModule.animation('.fade-animation', function() { + return { + enter: function(element, done) { + element.css('display', 'none'); + element.fadeIn(500, done); + return function() { + element.stop(); + } + }, + leave: function(element, done) { + element.fadeOut(500, done) + return function() { + element.stop(); + } + } + } + }); + + wizardModule.controller('svSelectCtrl', function($scope, wizardFactory, dataService, $filter, ngTableParams, sortingService) { + $scope.hideunselected = ''; + $scope.search = {}; + + var cluster = wizardFactory.getClusterInfo(); + + $scope.allservers = wizardFactory.getAllMachinesHost(); + + $scope.tableParams = new ngTableParams({ + page: 1, // show first page + count: $scope.allservers.length // count per page + }, { + counts: [], // hide count-per-page box + total: $scope.allservers.length, // length of data + getData: function($defer, params) { + var reverse = false; + var orderBy = params.orderBy()[0]; + var orderBySort = ""; + var orderByColumn = ""; + + if (orderBy) { + orderByColumn = orderBy.substring(1); + orderBySort = orderBy.substring(0, 1); + if (orderBySort == "+") { + reverse = false; + } else { + reverse = true; + } + } + + var orderedData = params.sorting() ? + $filter('orderBy')($scope.allservers, function(item) { + if (orderByColumn == "switch_ip") { + return sortingService.ipAddressPre(item.switch_ip); + } else { + return item[orderByColumn]; + } + }, reverse) : $scope.allservers; + + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); + } + }); + + + $scope.selectAllServers = function(flag) { + if (flag) { + angular.forEach($scope.allservers, function(sv) { + sv.selected = true; + }) + } else { + angular.forEach($scope.allservers, function(sv) { + sv.selected = false; + }) + } + }; + + dataService.getServerColumns().success(function(data) { + $scope.server_columns = data.showall; + }); + + $scope.hideUnselected = function() { + if ($scope.hideunselected) { + $scope.search.selected = true; + } else { + delete $scope.search.selected; + } + }; + + $scope.ifPreSelect = function(server) { + if (server.clusters) { + angular.forEach(server.clusters, function(svCluster) { + if (svCluster.id == cluster.id) { + server.selected = true; + } + }) + } + }; + + $scope.$watch(function() { + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { + if (newCommitState !== undefined) { + if (newCommitState.name == "sv_selection" && newCommitState.state == "triggered") { + $scope.commit(); + } + } + }); + + $scope.commit = function() { + $scope.$emit("loading", true); + var selectedServers = []; + var noSelection = true; + angular.forEach($scope.allservers, function(sv) { + if (sv.selected) { + noSelection = false; + selectedServers.push(sv); + } + }) + if (noSelection) { + var message = { + "message": "Please select at least one server" + } + var commitState = { + "name": "sv_selection", + "state": "error", + "message": message + }; + wizardFactory.setCommitState(commitState); + } else { + var addHostsAction = { + "add_hosts": { + "machines": [] + } + }; + angular.forEach($scope.allservers, function(server) { + if (server.selected) { + if (server.reinstallos === undefined) { + addHostsAction.add_hosts.machines.push({ + "machine_id": server.machine_id + }); + } else { + addHostsAction.add_hosts.machines.push({ + "machine_id": server.machine_id, + "reinstall_os": server.reinstallos + }); + } + } + }); + + // add hosts + dataService.postClusterActions(cluster.id, addHostsAction).success(function(data) { + var commitState = { + "name": "sv_selection", + "state": "success", + "message": "" + }; + wizardFactory.setCommitState(commitState); + wizardFactory.setAllMachinesHost($scope.allservers); + + }).error(function(response) { + var commitState = { + "name": "sv_selection", + "state": "success", + "message": response + }; + wizardFactory.setCommitState(commitState); + }); + //wizardFactory.setServers(selectedServers); + } + }; + + // add newly found servers at the top if allservers array + $scope.$watch('foundResults', function(newResults, oldResults) { + if (newResults != oldResults) { + for (var i = 0; i < newResults.length; i++) { + var sv = $filter('filter')($scope.allservers, newResults[i].mac, true); + if (sv.length == 0) { + newResults[i].machine_id = newResults[i].id; + delete newResults[i]['id']; + newResults[i].new = true; + $scope.allservers.unshift(newResults[i]); + } + } + + if ($scope.tableParams) { + $scope.tableParams.$params.count = $scope.allservers.length; + $scope.tableParams.reload(); + } + } + }, true); + + }); + + wizardModule.controller('globalCtrl', function($scope, wizardFactory, dataService, $q) { + var cluster = wizardFactory.getClusterInfo(); + + $scope.general = wizardFactory.getGeneralConfig(); + + if (!$scope.general["dns_servers"]) { + $scope.general["dns_servers"] = [""]; + } + if (!$scope.general["search_path"]) { + $scope.general["search_path"] = [""]; + } + if (!$scope.general["no_proxy"]) { + $scope.general["no_proxy"] = [""]; + } + + $scope.addValue = function(key) { + $scope.general[key].push(""); + }; + + dataService.getTimezones().success(function(data) { + $scope.timezones = data; + }); + + //For Routing Table Section + //keep routing table for later use + /* $scope.routingtable = wizardFactory.getRoutingTable(); $scope.addRoute = function() { $scope.routingtable.push({}); @@ -517,62 +517,62 @@ angular.module('compass.wizard', [ }, true); */ - $scope.$watch(function() { - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { + $scope.$watch(function() { + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { - if (newCommitState !== undefined) { - if (newCommitState.name == "os_global" && newCommitState.state == "triggered") { - $scope.commit(newCommitState.sendRequest); + if (newCommitState !== undefined) { + if (newCommitState.name == "os_global" && newCommitState.state == "triggered") { + $scope.commit(newCommitState.sendRequest); + } } - } - }); + }); - $scope.commit = function(sendRequest) { - if (!sendRequest) { - var commitState = { - "name": "os_global", - "state": "goToPreviousStep", - "message": "" - }; - wizardFactory.setCommitState(commitState); - return; - } - $scope.$emit("loading",true); - var os_global_general = { - "os_config": { - "general": $scope.general - } - }; - if ($scope.generalForm.$valid) { - dataService.updateClusterConfig(cluster.id, os_global_general).success(function(configData) { - wizardFactory.setGeneralConfig($scope.general); + $scope.commit = function(sendRequest) { + if (!sendRequest) { var commitState = { "name": "os_global", - "state": "success", + "state": "goToPreviousStep", "message": "" }; wizardFactory.setCommitState(commitState); - }).error(function(response) { - var commitState = { - "name": "os_global", - "state": "error", - "message": response - }; - wizardFactory.setCommitState(commitState); - }); - } else { - var message = { - "message": "The required(*) fields can not be empty !" + return; + } + $scope.$emit("loading", true); + var os_global_general = { + "os_config": { + "general": $scope.general + } + }; + if ($scope.generalForm.$valid) { + dataService.updateClusterConfig(cluster.id, os_global_general).success(function(configData) { + wizardFactory.setGeneralConfig($scope.general); + var commitState = { + "name": "os_global", + "state": "success", + "message": "" + }; + wizardFactory.setCommitState(commitState); + }).error(function(response) { + var commitState = { + "name": "os_global", + "state": "error", + "message": response + }; + wizardFactory.setCommitState(commitState); + }); + } else { + var message = { + "message": "The required(*) fields can not be empty !" + } + $scope.openErrMessageModal(message); } - $scope.openErrMessageModal(message); - } - }; + }; - // keey routing table for later use - /* + // keey routing table for later use + /* $scope.updateRoutingTable = function() { var routingCount = $scope.routingtable.length; var routingTable = []; @@ -602,29 +602,733 @@ angular.module('compass.wizard', [ }) }; */ -}) - -.controller('networkCtrl', function($scope, $timeout, wizardFactory, dataService, $filter, ngTableParams, sortingService, $q, $modal) { - var cluster = wizardFactory.getClusterInfo(); - $scope.subnetworks = wizardFactory.getSubnetworks(); - $scope.interfaces = wizardFactory.getInterfaces(); - //$scope.servers = wizardFactory.getServers(); - - dataService.getServerColumns().success(function(data) { - $scope.server_columns = data.showless; }); - dataService.getClusterHosts(cluster.id).success(function(data) { - $scope.servers = data; + wizardModule.controller('networkCtrl', function($scope, $timeout, wizardFactory, dataService, $filter, ngTableParams, sortingService, $q, $modal) { + var cluster = wizardFactory.getClusterInfo(); + $scope.subnetworks = wizardFactory.getSubnetworks(); + $scope.interfaces = wizardFactory.getInterfaces(); + //$scope.servers = wizardFactory.getServers(); - // Assume all hosts in the same cluster have same interface settings - if ($scope.servers[0].networks) { - if (Object.keys($scope.servers[0].networks).length != 0) { - $scope.interfaces = $scope.servers[0].networks; - wizardFactory.setInterfaces($scope.interfaces); + dataService.getServerColumns().success(function(data) { + $scope.server_columns = data.showless; + }); + + dataService.getClusterHosts(cluster.id).success(function(data) { + $scope.servers = data; + + // Assume all hosts in the same cluster have same interface settings + if ($scope.servers[0].networks) { + if (Object.keys($scope.servers[0].networks).length != 0) { + $scope.interfaces = $scope.servers[0].networks; + wizardFactory.setInterfaces($scope.interfaces); + } + } + + $scope.tableParams = new ngTableParams({ + page: 1, // show first page + count: $scope.servers.length + 1 // count per page + }, { + counts: [], // hide count-per-page box + total: $scope.servers.length, // length of data + getData: function($defer, params) { + var reverse = false; + var orderBy = params.orderBy()[0]; + var orderBySort = ""; + var orderByColumn = ""; + + if (orderBy) { + orderByColumn = orderBy.substring(1); + orderBySort = orderBy.substring(0, 1); + if (orderBySort == "+") { + reverse = false; + } else { + reverse = true; + } + } + + var orderedData = params.sorting() ? + $filter('orderBy')($scope.servers, function(item) { + if (orderByColumn == "switch_ip") { + return sortingService.ipAddressPre(item.switch_ip); + } else { + return item[orderByColumn]; + } + }, reverse) : $scope.servers; + $scope.servers = orderedData; + + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); + } + }); + }); + + $scope.addInterface = function(newInterface) { + var isExist = false; + if (newInterface) { + angular.forEach($scope.interfaces, function(value, key) { + if (key == newInterface.name) { + isExist = true; + alert("This interface already exists. Please try another one"); + } + }) + if (!isExist) { + $scope.interfaces[newInterface.name] = { + "subnet_id": parseInt(newInterface.subnet_id), + "is_mgmt": false + } + } + $scope.newInterface = {}; + } + }; + + $scope.deleteInterface = function(delInterface) { + delete $scope.interfaces[delInterface]; + angular.forEach($scope.servers, function(sv) { + delete sv.networks[delInterface]; + }) + }; + + $scope.$watch(function() { + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { + if (newCommitState !== undefined) { + if (newCommitState.name == "network" && newCommitState.state == "triggered") { + $scope.commit(newCommitState.sendRequest); + } + } + }); + + $scope.commit = function(sendRequest) { + if (!sendRequest) { + var commitState = { + "name": "network", + "state": "goToPreviousStep", + "message": "" + }; + wizardFactory.setCommitState(commitState); + return; + } + $scope.$emit("loading", true); + wizardFactory.setInterfaces($scope.interfaces); + + + var interfaceCount = Object.keys($scope.interfaces).length; + if (interfaceCount == 0) { + alert("Please add interface"); + } else { + var hostnamePromises = []; + var hostNetworkPromises = []; + + angular.forEach($scope.servers, function(server) { + var hostname = { + "name": server["hostname"] + }; + // update hostname + var updateHostname = dataService.putHost(server.id, hostname).then(function(hostData) { + // success callback + }, function(response) { + // error callback + return $q.reject(response); + }); + hostnamePromises.push(updateHostname); + + angular.forEach(server.networks, function(value, key) { + var network = { + "interface": key, + "ip": value.ip, + "subnet_id": parseInt($scope.interfaces[key].subnet_id), + "is_mgmt": $scope.interfaces[key].is_mgmt, + "is_promiscuous": $scope.interfaces[key].is_promiscuous + }; + if (value.id === undefined) { + // post host network + var updateNetwork = dataService.postHostNetwork(server.id, network).then(function(networkData) { + // success callback + var interface = networkData.data.interface; + var networkId = networkData.data.id; + server.networks[interface].id = networkId; + }, function(response) { + // error callback + return $q.reject(response); + // keep this part for later use + /* + if(response.status == 409) { // if (host_id, interface) already exists + var updateNetwork = dataService.putHostNetwork(server.id, value.id, network).then(function(networkData) { + // success callback + }, function(response) { + // error callback + return $q.reject(response); + }); + hostNetworkPromises.push(updateNetwork); + } + */ + }); + hostNetworkPromises.push(updateNetwork); + } else { + // put host network + var updateNetwork = dataService.putHostNetwork(server.id, value.id, network).then(function(networkData) { + // success callback + }, function(response) { + // error callback + return $q.reject(response); + }); + hostNetworkPromises.push(updateNetwork); + } + }); + }); + + $q.all(hostnamePromises.concat(hostNetworkPromises)).then(function() { + // update hostname and network for all hosts successfully + wizardFactory.setServers($scope.servers); + var commitState = { + "name": "network", + "state": "success", + "message": "" + }; + wizardFactory.setCommitState(commitState); + }, function(response) { + wizardFactory.setServers($scope.servers); + var commitState = { + "name": "network", + "state": "error", + "message": response.data + }; + console.info(response.data); + wizardFactory.setCommitState(commitState); + }); + + } + }; + + $scope.openAddSubnetModal = function() { + var modalInstance = $modal.open({ + templateUrl: "addSubnetModal.html", + controller: addSubnetModalInstanceCtrl, + resolve: { + subnets: function() { + return $scope.subnetworks; + } + } + }); + modalInstance.result.then(function(subnets) { + $scope.subnetworks = []; + angular.forEach(subnets, function(subnet) { + $scope.subnetworks.push(subnet); + }); + }, function() { + console.log("modal dismissed") + }) + }; + + + $scope.autofill = function(alertFade) { + // Autofill IP for each interface + angular.forEach($scope.interfaces, function(value, key) { + var ip_start = $("#" + key + "-ipstart").val(); + var interval = parseInt($("#" + key + "-increase-num").val()); + $scope.fillIPBySequence(ip_start, interval, key); + }) + // Autofill hostname + var hostname_rule = $("#hostname-rule").val(); + $scope.fillHostname(hostname_rule); + $scope.networkAlerts = [{ + msg: 'Autofill Done!' + }]; + if (alertFade) { + $timeout(function() { + $scope.networkAlerts = []; + }, alertFade); + } + }; + + $scope.fillHostname = function(rule) { + if (rule) { + switch (rule) { + case "host": + var server_index = 1; + angular.forEach($scope.servers, function(server) { + server.hostname = "host-" + server_index; + server_index++; + }) + break; + case "switch_ip": + angular.forEach($scope.servers, function(server) { + server.hostname = server.switch_ip.replace(/\./g, "-") + "-p" + server.port; + }) + break; + } + } + }; + + $scope.fillIPBySequence = function(ipStart, interval, interface) { + if (ipStart == "") + return; + var ipStartParts = ipStart.split("."); + var ipParts = ipStartParts.map(function(x) { + return parseInt(x); + }); + + angular.forEach($scope.servers, function(server) { + if (ipParts[3] > 255) { + ipParts[3] = ipParts[3] - 256; + ipParts[2]++; + } + if (ipParts[2] > 255) { + ipParts[2] = ipParts[2] - 256; + ipParts[1]++; + } + if (ipParts[1] > 255) { + ipParts[1] = ipParts[1] - 256; + ipParts[0]++; + } + if (ipParts[0] > 255) { + server.networks[interface].ip = ""; + return; + } else { + var ip = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + "." + ipParts[3] + server.networks[interface].ip = ip; + ipParts[3] = ipParts[3] + interval; + } + }) + } + }); + + wizardModule.controller('partitionCtrl', function($scope, wizardFactory, dataService) { + var cluster = wizardFactory.getClusterInfo(); + $scope.partition = wizardFactory.getPartition(); + $scope.partitionInforArray = []; + $scope.duplicated = false; + $scope.duplicatedIndexArray = []; + + angular.forEach($scope.partition, function(value, key) { + $scope.partitionInforArray.push({ + "name": key, + "percentage": value.percentage, + "max_size": value.max_size + }); + }); + + + /*$scope.addPartition = function() { + var mount_point = $scope.newPartition.mount_point; + $scope.partition[mount_point] = {}; + $scope.partition[mount_point].percentage = $scope.newPartition.percentage; + $scope.partition[mount_point].max_size = $scope.newPartition.max_size; + $scope.newPartition = {}; + };*/ + + $scope.addPartition = function() { + var newRowExist = false; + angular.forEach($scope.partitionInforArray, function(partitionInfo) { + if (partitionInfo.name == "") { + newRowExist = true; + } + + }); + if (newRowExist == false && $scope.duplicated == false) { + $scope.partitionInforArray.push({ + "name": "", + "percentage": 0, + "max_size": 0 + }) + } + + } + + $scope.deletePartition = function(index) { + var emptyRowIndex = -1; // no empty row + if ($scope.partitionInforArray.length <= 2) { + if ($scope.partitionInforArray[0]['name'] == "") { + emptyRowIndex = 0; + } else if ($scope.partitionInforArray[1]['name'] == "") { + emptyRowIndex = 1; + } + + if (emptyRowIndex == index || emptyRowIndex == -1) { + $scope.partitionInforArray.splice(index, 1); + } + + } else { + $scope.partitionInforArray.splice(index, 1); + } + if ($scope.duplicatedIndexArray.indexOf(index) >= 0) { + $scope.duplicated = false; + + } + }; + + $scope.$watch('partitionInforArray', function() { + $scope.partitionarray = []; + var total = 0; + angular.forEach($scope.partitionInforArray, function(partitionInfo) { + total += parseFloat(partitionInfo.percentage); + $scope.partitionarray.push({ + "name": partitionInfo.name, + "number": partitionInfo.percentage + }); + }); + $scope.partitionarray.push({ + "name": "others", + "number": 100 - total + }) + }, true); + + $scope.mount_point_change = function(index, name) { + var duplicatedIndexContainer = []; + $scope.duplicatedIndexArray = []; + var count = 0; + $scope.duplicated = false; + var numberOfNames = 0; + angular.forEach($scope.partitionInforArray, function(partitionInfo) { + + if (partitionInfo.name == name) { + numberOfNames++; + duplicatedIndexContainer.push(count); + } + count++; + }); + if (numberOfNames > 1) { + $scope.duplicated = true; + $scope.duplicatedIndexArray = angular.copy(duplicatedIndexContainer); } } + $scope.$watch(function() { + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { + if (newCommitState !== undefined) { + if (newCommitState.name == "partition" && newCommitState.state == "triggered") { + $scope.commit(newCommitState.sendRequest); + } + } + }); + + $scope.commit = function(sendRequest) { + if (!sendRequest) { + var commitState = { + "name": "partition", + "state": "goToPreviousStep", + "message": "" + }; + wizardFactory.setCommitState(commitState); + return; + } + $scope.$emit("loading", true); + if ($scope.duplicated == true) { + var message = { + "message": "Mount Point cannot be the same" + } + var commitState = { + "name": "partition", + "state": "error", + "message": message + }; + wizardFactory.setCommitState(commitState); + + } else { + var newPartition = {}; + var data = {}; + angular.forEach($scope.partitionInforArray, function(partitionInfo) { + newPartition[partitionInfo['name']] = {}; + newPartition[partitionInfo['name']]['percentage'] = partitionInfo['percentage']; + newPartition[partitionInfo['name']]['max_size'] = partitionInfo['max_size']; + }); + $scope.partition = angular.copy(newPartition); + var os_partition = { + "os_config": { + "partition": $scope.partition + } + }; + + dataService.updateClusterConfig(cluster.id, os_partition).success(function(configData) { + wizardFactory.setPartition(configData["os_config"]["partition"]); + var commitState = { + "name": "partition", + "state": "success", + "message": "" + }; + wizardFactory.setCommitState(commitState); + }).error(function(response) { + var commitState = { + "name": "partition", + "state": "error", + "message": response + }; + wizardFactory.setCommitState(commitState); + }); + } + }; + }) + + wizardModule.controller('securityCtrl', function($scope, wizardFactory, dataService) { + var cluster = wizardFactory.getClusterInfo(); + $scope.server_credentials = wizardFactory.getServerCredentials(); + $scope.service_credentials = wizardFactory.getServiceCredentials(); + $scope.console_credentials = wizardFactory.getConsoleCredentials(); + + $scope.mSave = function() { + $scope.originalMangementData = angular.copy($scope.console_credentials); + } + $scope.sSave = function() { + $scope.originalServiceData = angular.copy($scope.service_credentials); + } + + $scope.mSave(); + $scope.sSave(); + + var keyLength_service_credentials = Object.keys($scope.service_credentials).length; + $scope.editServiceMode = []; + $scope.editServiceMode.length = keyLength_service_credentials; + + var keyLength_console_credentials = Object.keys($scope.console_credentials).length; + $scope.editMgntMode = []; + $scope.editMgntMode.length = keyLength_console_credentials; + + $scope.$watch(function() { + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { + if (newCommitState !== undefined) { + if (newCommitState.name == "security" && newCommitState.state == "triggered") { + $scope.commit(newCommitState.sendRequest); + } + } + }); + + $scope.mgmtAccordion = {}; + + $scope.$watch('mgmtAccordion', function(val) { + if ($scope.mgmtAccordion.open == true) { + $scope.mSave(); + } else if ($scope.mgmtAccordion.open == false) { + $scope.mReset(); + $scope.mcloseAll(); + } + }, true) + + $scope.mcloseAll = function() { + for (var i = 0; i < $scope.editMgntMode.length; i++) { + if ($scope.editMgntMode[i] == true) { + $scope.editMgntMode[i] = false; + } else {} + } + } + + $scope.mEdit = function(index) { + for (var i = 0; i < $scope.editMgntMode.length; i++) { + if (i != index) { + $scope.editMgntMode[i] = false; + } else { + $scope.editMgntMode[i] = true; + } + } + $scope.mReset(); + } + + $scope.mReset = function() { + $scope.console_credentials = angular.copy($scope.originalMangementData); + } + + // Service Credentials + $scope.serviceAccordion = {}; + + $scope.$watch('serviceAccordion', function(val) { + if ($scope.serviceAccordion.open == true) { + $scope.sSave(); + } else if ($scope.serviceAccordion.open == false) { + $scope.sReset(); + $scope.scloseAll(); + } + }, true) + + $scope.scloseAll = function() { + for (var i = 0; i < $scope.editServiceMode.length; i++) { + if ($scope.editServiceMode[i] == true) { + $scope.editServiceMode[i] = false; + } else {} + } + } + + $scope.sEdit = function(index) { + for (var i = 0; i < $scope.editServiceMode.length; i++) { + if (i != index) { + $scope.editServiceMode[i] = false; + } else { + $scope.editServiceMode[i] = true; + } + } + $scope.sReset(); + } + + $scope.sReset = function() { + $scope.service_credentials = angular.copy($scope.originalServiceData); + } + + $scope.commit = function(sendRequest) { + if (!sendRequest) { + var commitState = { + "name": "security", + "state": "goToPreviousStep", + "message": "" + }; + wizardFactory.setCommitState(commitState); + return; + } + $scope.$emit("loading", true); + var securityData = { + "os_config": { + "server_credentials": { + "username": $scope.server_credentials.username, + "password": $scope.server_credentials.password + } + }, + "package_config": { + "security": { + "service_credentials": $scope.service_credentials, + "console_credentials": $scope.console_credentials + } + } + }; + dataService.updateClusterConfig(cluster.id, securityData).success(function(data) { + var commitState = { + "name": "security", + "state": "success", + "message": "" + }; + wizardFactory.setCommitState(commitState); + }).error(function(response) { + var commitState = { + "name": "security", + "state": "error", + "message": response + }; + wizardFactory.setCommitState(commitState); + }); + }; + }); + + wizardModule.controller('roleAssignCtrl', function($scope, wizardFactory, dataService, $filter, ngTableParams, sortingService, $q) { + var cluster = wizardFactory.getClusterInfo(); + $scope.servers = wizardFactory.getServers(); + var colors = ['#8EA16C', '#C2CF30', '#FEC700', '#FF8900', '#D3432B', '#BB2952', '#8E1E5F', '#DE4AB6', '#9900EC', '#3A1AA8', '#3932FE', '#278BC0', '#35B9F6', '#91E0CB', '#42BC6A', '#5B4141']; + + $scope.existingRoles = []; + $scope.realRole = []; + + dataService.getServerColumns().success(function(data) { + $scope.server_columns = data.showless; + }); + + dataService.getClusterById(cluster.id).success(function(data) { + // wizardFactory.setAdapter(data); + $scope.roles = data.flavor.roles; + angular.forEach($scope.roles, function(role, role_key) { + role.color = colors[role_key]; + $scope.roles[role_key].dragChannel = role_key; + $scope.realRole.push(role_key); + }); + angular.forEach($scope.servers, function(value, key) { + $scope.existingRoles.push(angular.copy($scope.realRole)); + $scope.servers[key].dropChannel = $scope.existingRoles[key].toString(); + angular.forEach($scope.servers[key].roles, function(server_role, server_role_key) { + $scope.server_role = ""; + angular.forEach($scope.roles, function(role, role_key) { + if (server_role.display_name == $scope.roles[role_key].display_name) { + $scope.server_role = role_key; + } + }); + server_role.color = colors[$scope.server_role]; + }); + }); + $scope.checkExistRolesDrag(); + }); + + $scope.selectAllServers = function(flag) { + if (flag) { + angular.forEach($scope.servers, function(sv) { + sv.checked = true; + }); + } else { + angular.forEach($scope.servers, function(sv) { + sv.checked = false; + }); + } + }; + + $scope.removeRole = function(server, role) { + var serverIndex = $scope.servers.indexOf(server); + var roleIndex = $scope.servers[serverIndex].roles.indexOf(role); + $scope.servers[serverIndex].roles.splice(roleIndex, 1); + angular.forEach($scope.roles, function(role_value, role_key) { + if (role.display_name == $scope.roles[role_key].display_name) { + $scope.existingRoles[serverIndex].splice(role_key, 1, role_key) + } + }); + $scope.servers[serverIndex].dropChannel = $scope.existingRoles[serverIndex].toString(); + }; + + $scope.assignRole = function(role) { + var serverChecked = false; + for (var i = 0; i < $scope.servers.length; i++) { + if ($scope.servers[i].checked) { + serverChecked = true; + } + } + if (!serverChecked) { + alert("Please select at least one server"); + } else { + // get selected servers and assign role to them + for (var i = 0; i < $scope.servers.length; i++) { + if ($scope.servers[i].checked) { + var roleExist = $scope.checkRoleExist($scope.servers[i].roles, role); + if (!roleExist) { + $scope.servers[i].roles.push(role); + } + } + } + } + }; + + // Assume all servers have not been assigned any roles before calling this function + $scope.autoAssignRoles = function() { + var roles = angular.copy($scope.roles); + var svIndex = 0; + angular.forEach(roles, function(newrole) { + var i = 0; + var loopStep = 0; + while (i < newrole.count && loopStep < $scope.servers.length) { + if (svIndex >= $scope.servers.length) { + svIndex = 0; + } + var roleExist = $scope.checkRoleExist($scope.servers[svIndex].roles, newrole); + if (!roleExist) { + $scope.servers[svIndex].roles.push(newrole); + i++; + loopStep = 0; + } else { + loopStep++; + } + svIndex++; + } + }); + }; + + $scope.checkRoleExist = function(existingRoles, newRole) { + var roleExist = false; + angular.forEach(existingRoles, function(existingRole) { + if (existingRole.name == newRole.name) { + roleExist = true; + } + }) + return roleExist; + }; + + $scope.$watch('roles', function(roles) { + var count = 0; + angular.forEach(roles, function(role) { + count += role.count; + }) + $scope.rolesTotalCount = count; + }, true); $scope.tableParams = new ngTableParams({ page: 1, // show first page count: $scope.servers.length + 1 // count per page @@ -660,1178 +1364,476 @@ angular.module('compass.wizard', [ $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } }); - }); - $scope.addInterface = function(newInterface) { - var isExist = false; - if (newInterface) { - angular.forEach($scope.interfaces, function(value, key) { - if (key == newInterface.name) { - isExist = true; - alert("This interface already exists. Please try another one"); - } - }) - if (!isExist) { - $scope.interfaces[newInterface.name] = { - "subnet_id": parseInt(newInterface.subnet_id), - "is_mgmt": false + $scope.$watch(function() { + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { + if (newCommitState !== undefined) { + if (newCommitState.name == "role_assign" && newCommitState.state == "triggered") { + $scope.commit(newCommitState.sendRequest); } } - $scope.newInterface = {}; - } - }; + }); - $scope.deleteInterface = function(delInterface) { - delete $scope.interfaces[delInterface]; - angular.forEach($scope.servers, function(sv) { - delete sv.networks[delInterface]; - }) - }; - - $scope.$watch(function() { - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { - if (newCommitState !== undefined) { - if (newCommitState.name == "network" && newCommitState.state == "triggered") { - $scope.commit(newCommitState.sendRequest); - } - } - }); - - $scope.commit = function(sendRequest) { - if (!sendRequest) { - var commitState = { - "name": "network", - "state": "goToPreviousStep", - "message": "" - }; - wizardFactory.setCommitState(commitState); - return; - } - $scope.$emit("loading",true); - wizardFactory.setInterfaces($scope.interfaces); - - - var interfaceCount = Object.keys($scope.interfaces).length; - if (interfaceCount == 0) { - alert("Please add interface"); - } else { - var hostnamePromises = []; - var hostNetworkPromises = []; - - angular.forEach($scope.servers, function(server) { - var hostname = { - "name": server["hostname"] + $scope.commit = function(sendRequest) { + if (!sendRequest) { + var commitState = { + "name": "role_assign", + "state": "goToPreviousStep", + "message": "" }; - // update hostname - var updateHostname = dataService.putHost(server.id, hostname).then(function(hostData) { + wizardFactory.setCommitState(commitState); + return; + } + $scope.$emit("loading", true); + var promises = []; + angular.forEach($scope.servers, function(server) { + var roles = []; + angular.forEach(server.roles, function(role) { + roles.push(role.name); + }); + var data = { + "roles": roles + }; + var updateRoles = dataService.updateClusterHost(cluster.id, server.id, data).then(function(configData) { // success callback }, function(response) { // error callback return $q.reject(response); }); - hostnamePromises.push(updateHostname); - - angular.forEach(server.networks, function(value, key) { - var network = { - "interface": key, - "ip": value.ip, - "subnet_id": parseInt($scope.interfaces[key].subnet_id), - "is_mgmt": $scope.interfaces[key].is_mgmt, - "is_promiscuous": $scope.interfaces[key].is_promiscuous - }; - if (value.id === undefined) { - // post host network - var updateNetwork = dataService.postHostNetwork(server.id, network).then(function(networkData) { - // success callback - var interface = networkData.data.interface; - var networkId = networkData.data.id; - server.networks[interface].id = networkId; - }, function(response) { - // error callback - return $q.reject(response); - // keep this part for later use - /* - if(response.status == 409) { // if (host_id, interface) already exists - var updateNetwork = dataService.putHostNetwork(server.id, value.id, network).then(function(networkData) { - // success callback - }, function(response) { - // error callback - return $q.reject(response); - }); - hostNetworkPromises.push(updateNetwork); - } - */ - }); - hostNetworkPromises.push(updateNetwork); - } else { - // put host network - var updateNetwork = dataService.putHostNetwork(server.id, value.id, network).then(function(networkData) { - // success callback - }, function(response) { - // error callback - return $q.reject(response); - }); - hostNetworkPromises.push(updateNetwork); - } - }); + promises.push(updateRoles); }); - $q.all(hostnamePromises.concat(hostNetworkPromises)).then(function() { - // update hostname and network for all hosts successfully + if ($scope.ha_vip) { + var config = { + "package_config": { + "ha_vip": $scope.ha_vip + } + } + var updateHAVIP = dataService.updateClusterConfig(cluster.id, config).then(function(configData) { + // success callback + }, function(response) { + // error callback + return $q.reject(response); + }); + promises.push(updateHAVIP); + } + + $q.all(promises).then(function() { wizardFactory.setServers($scope.servers); var commitState = { - "name": "network", + "name": "role_assign", "state": "success", "message": "" }; wizardFactory.setCommitState(commitState); }, function(response) { - wizardFactory.setServers($scope.servers); + console.log("promises error", response); var commitState = { - "name": "network", + "name": "role_assign", "state": "error", "message": response.data }; - console.info(response.data); wizardFactory.setCommitState(commitState); }); + }; - } - }; + $scope.onDrop = function($event, server) { + $scope.dragKey = $scope.servers.indexOf(server); + }; - $scope.openAddSubnetModal = function() { - var modalInstance = $modal.open({ - templateUrl: "addSubnetModal.html", - controller: addSubnetModalInstanceCtrl, - resolve: { - subnets: function() { - return $scope.subnetworks; - } - } - }); - modalInstance.result.then(function(subnets) { - $scope.subnetworks = []; - angular.forEach(subnets, function(subnet) { - $scope.subnetworks.push(subnet); - }); - }, function() { - console.log("modal dismissed") - }) - }; - - - $scope.autofill = function(alertFade) { - // Autofill IP for each interface - angular.forEach($scope.interfaces, function(value, key) { - var ip_start = $("#" + key + "-ipstart").val(); - var interval = parseInt($("#" + key + "-increase-num").val()); - $scope.fillIPBySequence(ip_start, interval, key); - }) - // Autofill hostname - var hostname_rule = $("#hostname-rule").val(); - $scope.fillHostname(hostname_rule); - $scope.networkAlerts = [{ - msg: 'Autofill Done!' - }]; - if (alertFade) { - $timeout(function() { - $scope.networkAlerts = []; - }, alertFade); - } - }; - - $scope.fillHostname = function(rule) { - if (rule) { - switch (rule) { - case "host": - var server_index = 1; - angular.forEach($scope.servers, function(server) { - server.hostname = "host-" + server_index; - server_index++; - }) - break; - case "switch_ip": - angular.forEach($scope.servers, function(server) { - server.hostname = server.switch_ip.replace(/\./g, "-") + "-p" + server.port; - }) - break; - } - } - }; - - $scope.fillIPBySequence = function(ipStart, interval, interface) { - if (ipStart == "") - return; - var ipStartParts = ipStart.split("."); - var ipParts = ipStartParts.map(function(x) { - return parseInt(x); - }); - - angular.forEach($scope.servers, function(server) { - if (ipParts[3] > 255) { - ipParts[3] = ipParts[3] - 256; - ipParts[2]++; - } - if (ipParts[2] > 255) { - ipParts[2] = ipParts[2] - 256; - ipParts[1]++; - } - if (ipParts[1] > 255) { - ipParts[1] = ipParts[1] - 256; - ipParts[0]++; - } - if (ipParts[0] > 255) { - server.networks[interface].ip = ""; - return; + $scope.dropSuccessHandler = function($event, role_value, key) { + var roleExist = $scope.checkRoleExist($scope.servers[$scope.dragKey].roles, role_value); + if (!roleExist) { + $scope.servers[$scope.dragKey].roles.push(role_value); } else { - var ip = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + "." + ipParts[3] - server.networks[interface].ip = ip; - ipParts[3] = ipParts[3] + interval; + console.log("role exists"); } - }) - } -}) + $scope.checkExistRolesDrag(); + }; -.controller('partitionCtrl', function($scope, wizardFactory, dataService) { - var cluster = wizardFactory.getClusterInfo(); - $scope.partition = wizardFactory.getPartition(); - $scope.partitionInforArray = []; - $scope.duplicated = false; - $scope.duplicatedIndexArray = []; - - angular.forEach($scope.partition, function(value, key) { - $scope.partitionInforArray.push({ - "name": key, - "percentage": value.percentage, - "max_size": value.max_size - }); + $scope.checkExistRolesDrag = function() { + angular.forEach($scope.servers, function(value, key) { + angular.forEach($scope.servers[key].roles, function(server_role, server_role_key) { + angular.forEach($scope.roles, function(role, role_key) { + if ($scope.servers[key].roles[server_role_key].display_name == $scope.roles[role_key].display_name) { + $scope.existingRoles[key].splice(role_key, 1, "p"); + } + }); + }); + $scope.servers[key].dropChannel = $scope.existingRoles[key].toString(); + }); + }; }); + wizardModule.controller('networkMappingCtrl', function($scope, wizardFactory, dataService) { + var cluster = wizardFactory.getClusterInfo(); + $scope.interfaces = wizardFactory.getInterfaces(); + $scope.original_networking = wizardFactory.getNetworkMapping(); + $scope.pendingInterface = ""; - /*$scope.addPartition = function() { - var mount_point = $scope.newPartition.mount_point; - $scope.partition[mount_point] = {}; - $scope.partition[mount_point].percentage = $scope.newPartition.percentage; - $scope.partition[mount_point].max_size = $scope.newPartition.max_size; - $scope.newPartition = {}; - };*/ + $scope.onDrop = function($event, key) { + $scope.pendingInterface = key; + }; - $scope.addPartition = function() { - var newRowExist = false; - angular.forEach($scope.partitionInforArray, function(partitionInfo) { - if (partitionInfo.name == "") { - newRowExist = true; - } - - }); - if (newRowExist == false && $scope.duplicated == false) { - $scope.partitionInforArray.push({ - "name": "", - "percentage": 0, - "max_size": 0 - }) - } - - } - - $scope.deletePartition = function(index) { - var emptyRowIndex = -1; // no empty row - if ($scope.partitionInforArray.length <= 2) { - if ($scope.partitionInforArray[0]['name'] == "") { - emptyRowIndex = 0; - } else if ($scope.partitionInforArray[1]['name'] == "") { - emptyRowIndex = 1; - } - - if (emptyRowIndex == index || emptyRowIndex == -1) { - $scope.partitionInforArray.splice(index, 1); - } - - } else { - $scope.partitionInforArray.splice(index, 1); - } - if ($scope.duplicatedIndexArray.indexOf(index) >= 0) { - $scope.duplicated = false; - - } - }; - - $scope.$watch('partitionInforArray', function() { - $scope.partitionarray = []; - var total = 0; - angular.forEach($scope.partitionInforArray, function(partitionInfo) { - total += parseFloat(partitionInfo.percentage); - $scope.partitionarray.push({ - "name": partitionInfo.name, - "number": partitionInfo.percentage - }); - }); - $scope.partitionarray.push({ - "name": "others", - "number": 100 - total + angular.forEach($scope.interfaces, function(value, key) { + $scope.interfaces[key].dropChannel = "E"; }) - }, true); - $scope.mount_point_change = function(index, name) { - var duplicatedIndexContainer = []; - $scope.duplicatedIndexArray = []; - var count = 0; - $scope.duplicated = false; - var numberOfNames = 0; - angular.forEach($scope.partitionInforArray, function(partitionInfo) { + $scope.networking = {}; + angular.forEach($scope.original_networking, function(value, key) { + $scope.networking[key] = {}; + $scope.networking[key].mapping_interface = value; + if (key == "public") { + $scope.networking[key].dragChannel = "P"; + } else + $scope.networking[key].dragChannel = "E"; + }) - if (partitionInfo.name == name) { - numberOfNames++; - duplicatedIndexContainer.push(count); + $scope.dropSuccessHandler = function($event, key, dict) { + dict[key].mapping_interface = $scope.pendingInterface; + }; + + angular.forEach($scope.interfaces, function(value, key) { + // The interface with promisc mode is required to be set as Public Network + if (value.is_promiscuous) { + $scope.networking["public"].mapping_interface = key; + $scope.interfaces[key].dropChannel = "P"; + } + // The interface marked as management is required to be set as Management Network + if (value.is_mgmt) { + $scope.networking["management"].mapping_interface = key; } - count++; }); - if (numberOfNames > 1) { - $scope.duplicated = true; - $scope.duplicatedIndexArray = angular.copy(duplicatedIndexContainer); - } - } - $scope.$watch(function() { - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { - if (newCommitState !== undefined) { - if (newCommitState.name == "partition" && newCommitState.state == "triggered") { - $scope.commit(newCommitState.sendRequest); + $scope.$watch(function() { + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { + if (newCommitState !== undefined) { + if (newCommitState.name == "network_mapping" && newCommitState.state == "triggered") { + $scope.commit(newCommitState.sendRequest); + } } - } - }); + }); - $scope.commit = function(sendRequest) { - if (!sendRequest) { - var commitState = { - "name": "partition", - "state": "goToPreviousStep", - "message": "" - }; - wizardFactory.setCommitState(commitState); - return; - } - $scope.$emit("loading",true); - if ($scope.duplicated == true) { - var message = { - "message": "Mount Point cannot be the same" + $scope.commit = function(sendRequest) { + if (!sendRequest) { + var commitState = { + "name": "network_mapping", + "state": "goToPreviousStep", + "message": "" + }; + wizardFactory.setCommitState(commitState); + return; } - var commitState = { - "name": "partition", - "state": "error", - "message": message - }; - wizardFactory.setCommitState(commitState); - } else { - var newPartition = {}; - var data = {}; - angular.forEach($scope.partitionInforArray, function(partitionInfo) { - newPartition[partitionInfo['name']] = {}; - newPartition[partitionInfo['name']]['percentage'] = partitionInfo['percentage']; - newPartition[partitionInfo['name']]['max_size'] = partitionInfo['max_size']; + $scope.$emit("loading", true); + var networks = {}; + angular.forEach($scope.networking, function(value, key) { + networks[key] = value.mapping_interface; }); - $scope.partition = angular.copy(newPartition); - var os_partition = { - "os_config": { - "partition": $scope.partition + var network_mapping = { + "package_config": { + "network_mapping": networks } }; - - dataService.updateClusterConfig(cluster.id, os_partition).success(function(configData) { - wizardFactory.setPartition(configData["os_config"]["partition"]); + dataService.updateClusterConfig(cluster.id, network_mapping).success(function(data) { + wizardFactory.setNetworkMapping(networks); var commitState = { - "name": "partition", + "name": "network_mapping", "state": "success", "message": "" }; wizardFactory.setCommitState(commitState); }).error(function(response) { var commitState = { - "name": "partition", + "name": "network_mapping", "state": "error", "message": response }; wizardFactory.setCommitState(commitState); }); - } - }; -}) - -.controller('securityCtrl', function($scope, wizardFactory, dataService) { - var cluster = wizardFactory.getClusterInfo(); - $scope.server_credentials = wizardFactory.getServerCredentials(); - $scope.service_credentials = wizardFactory.getServiceCredentials(); - $scope.console_credentials = wizardFactory.getConsoleCredentials(); - - $scope.mSave = function() { - $scope.originalMangementData = angular.copy($scope.console_credentials); - } - $scope.sSave = function() { - $scope.originalServiceData = angular.copy($scope.service_credentials); - } - - $scope.mSave(); - $scope.sSave(); - - var keyLength_service_credentials = Object.keys($scope.service_credentials).length; - $scope.editServiceMode = []; - $scope.editServiceMode.length = keyLength_service_credentials; - - var keyLength_console_credentials = Object.keys($scope.console_credentials).length; - $scope.editMgntMode = []; - $scope.editMgntMode.length = keyLength_console_credentials; - - $scope.$watch(function() { - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { - if (newCommitState !== undefined) { - if (newCommitState.name == "security" && newCommitState.state == "triggered") { - $scope.commit(newCommitState.sendRequest); - } - } - }); - - $scope.mgmtAccordion = {}; - - $scope.$watch('mgmtAccordion', function(val) { - if ($scope.mgmtAccordion.open == true) { - $scope.mSave(); - } else if ($scope.mgmtAccordion.open == false) { - $scope.mReset(); - $scope.mcloseAll(); - } - }, true) - - $scope.mcloseAll = function() { - for (var i = 0; i < $scope.editMgntMode.length; i++) { - if ($scope.editMgntMode[i] == true) { - $scope.editMgntMode[i] = false; - } else {} - } - } - - $scope.mEdit = function(index) { - for (var i = 0; i < $scope.editMgntMode.length; i++) { - if (i != index) { - $scope.editMgntMode[i] = false; - } else { - $scope.editMgntMode[i] = true; - } - } - $scope.mReset(); - } - - $scope.mReset = function() { - $scope.console_credentials = angular.copy($scope.originalMangementData); - } - - // Service Credentials - $scope.serviceAccordion = {}; - - $scope.$watch('serviceAccordion', function(val) { - if ($scope.serviceAccordion.open == true) { - $scope.sSave(); - } else if ($scope.serviceAccordion.open == false) { - $scope.sReset(); - $scope.scloseAll(); - } - }, true) - - $scope.scloseAll = function() { - for (var i = 0; i < $scope.editServiceMode.length; i++) { - if ($scope.editServiceMode[i] == true) { - $scope.editServiceMode[i] = false; - } else {} - } - } - - $scope.sEdit = function(index) { - for (var i = 0; i < $scope.editServiceMode.length; i++) { - if (i != index) { - $scope.editServiceMode[i] = false; - } else { - $scope.editServiceMode[i] = true; - } - } - $scope.sReset(); - } - - $scope.sReset = function() { - $scope.service_credentials = angular.copy($scope.originalServiceData); - } - - $scope.commit = function(sendRequest) { - if (!sendRequest) { - var commitState = { - "name": "security", - "state": "goToPreviousStep", - "message": "" - }; - wizardFactory.setCommitState(commitState); - return; - } - $scope.$emit("loading",true); - var securityData = { - "os_config": { - "server_credentials": { - "username": $scope.server_credentials.username, - "password": $scope.server_credentials.password - } - }, - "package_config": { - "security": { - "service_credentials": $scope.service_credentials, - "console_credentials": $scope.console_credentials - } - } }; - dataService.updateClusterConfig(cluster.id, securityData).success(function(data) { - var commitState = { - "name": "security", - "state": "success", - "message": "" - }; - wizardFactory.setCommitState(commitState); - }).error(function(response) { - var commitState = { - "name": "security", - "state": "error", - "message": response - }; - wizardFactory.setCommitState(commitState); - }); - }; -}) - -.controller('roleAssignCtrl', function($scope, wizardFactory, dataService, $filter, ngTableParams, sortingService, $q) { - var cluster = wizardFactory.getClusterInfo(); - $scope.servers = wizardFactory.getServers(); - var colors = ['#8EA16C', '#C2CF30', '#FEC700', '#FF8900', '#D3432B', '#BB2952', '#8E1E5F', '#DE4AB6', '#9900EC', '#3A1AA8', '#3932FE', '#278BC0', '#35B9F6', '#91E0CB', '#42BC6A', '#5B4141']; - - $scope.existingRoles = []; - $scope.realRole = []; - - dataService.getServerColumns().success(function(data) { - $scope.server_columns = data.showless; - }); - - dataService.getClusterById(cluster.id).success(function(data) { - // wizardFactory.setAdapter(data); - $scope.roles = data.flavor.roles; - angular.forEach($scope.roles, function(role, role_key) { - role.color = colors[role_key]; - $scope.roles[role_key].dragChannel = role_key; - $scope.realRole.push(role_key); - }); - angular.forEach($scope.servers, function(value, key) { - $scope.existingRoles.push(angular.copy($scope.realRole)); - $scope.servers[key].dropChannel = $scope.existingRoles[key].toString(); - angular.forEach($scope.servers[key].roles, function(server_role, server_role_key) { - $scope.server_role = ""; - angular.forEach($scope.roles, function(role, role_key) { - if (server_role.display_name == $scope.roles[role_key].display_name) { - $scope.server_role = role_key; - } - }); - server_role.color = colors[$scope.server_role]; - }); - }); - $scope.checkExistRolesDrag(); - }); - - $scope.selectAllServers = function(flag) { - if (flag) { - angular.forEach($scope.servers, function(sv) { - sv.checked = true; - }); - } else { - angular.forEach($scope.servers, function(sv) { - sv.checked = false; - }); - } - }; - - $scope.removeRole = function(server, role) { - var serverIndex = $scope.servers.indexOf(server); - var roleIndex = $scope.servers[serverIndex].roles.indexOf(role); - $scope.servers[serverIndex].roles.splice(roleIndex, 1); - angular.forEach($scope.roles, function(role_value, role_key) { - if (role.display_name == $scope.roles[role_key].display_name) { - $scope.existingRoles[serverIndex].splice(role_key, 1, role_key) - } - }); - $scope.servers[serverIndex].dropChannel = $scope.existingRoles[serverIndex].toString(); - }; - - $scope.assignRole = function(role) { - var serverChecked = false; - for (var i = 0; i < $scope.servers.length; i++) { - if ($scope.servers[i].checked) { - serverChecked = true; - } - } - if (!serverChecked) { - alert("Please select at least one server"); - } else { - // get selected servers and assign role to them - for (var i = 0; i < $scope.servers.length; i++) { - if ($scope.servers[i].checked) { - var roleExist = $scope.checkRoleExist($scope.servers[i].roles, role); - if (!roleExist) { - $scope.servers[i].roles.push(role); - } - } - } - } - }; - - // Assume all servers have not been assigned any roles before calling this function - $scope.autoAssignRoles = function() { - var roles = angular.copy($scope.roles); - var svIndex = 0; - angular.forEach(roles, function(newrole) { - var i = 0; - var loopStep = 0; - while (i < newrole.count && loopStep < $scope.servers.length) { - if (svIndex >= $scope.servers.length) { - svIndex = 0; - } - var roleExist = $scope.checkRoleExist($scope.servers[svIndex].roles, newrole); - if (!roleExist) { - $scope.servers[svIndex].roles.push(newrole); - i++; - loopStep = 0; - } else { - loopStep++; - } - svIndex++; - } - }); - }; - - $scope.checkRoleExist = function(existingRoles, newRole) { - var roleExist = false; - angular.forEach(existingRoles, function(existingRole) { - if (existingRole.name == newRole.name) { - roleExist = true; - } - }) - return roleExist; - }; - - $scope.$watch('roles', function(roles) { - var count = 0; - angular.forEach(roles, function(role) { - count += role.count; - }) - $scope.rolesTotalCount = count; - }, true); - $scope.tableParams = new ngTableParams({ - page: 1, // show first page - count: $scope.servers.length + 1 // count per page - }, { - counts: [], // hide count-per-page box - total: $scope.servers.length, // length of data - getData: function($defer, params) { - var reverse = false; - var orderBy = params.orderBy()[0]; - var orderBySort = ""; - var orderByColumn = ""; - - if (orderBy) { - orderByColumn = orderBy.substring(1); - orderBySort = orderBy.substring(0, 1); - if (orderBySort == "+") { - reverse = false; - } else { - reverse = true; - } - } - - var orderedData = params.sorting() ? - $filter('orderBy')($scope.servers, function(item) { - if (orderByColumn == "switch_ip") { - return sortingService.ipAddressPre(item.switch_ip); - } else { - return item[orderByColumn]; - } - }, reverse) : $scope.servers; - $scope.servers = orderedData; - - $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); - } - }); - - $scope.$watch(function() { - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { - if (newCommitState !== undefined) { - if (newCommitState.name == "role_assign" && newCommitState.state == "triggered") { - $scope.commit(newCommitState.sendRequest); - } - } - }); - - $scope.commit = function(sendRequest) { - if (!sendRequest) { - var commitState = { - "name": "role_assign", - "state": "goToPreviousStep", - "message": "" - }; - wizardFactory.setCommitState(commitState); - return; - } - $scope.$emit("loading",true); - var promises = []; - angular.forEach($scope.servers, function(server) { - var roles = []; - angular.forEach(server.roles, function(role) { - roles.push(role.name); - }); - var data = { - "roles": roles - }; - var updateRoles = dataService.updateClusterHost(cluster.id, server.id, data).then(function(configData) { - // success callback - }, function(response) { - // error callback - return $q.reject(response); - }); - promises.push(updateRoles); - }); - - if ($scope.ha_vip) { - var config = { - "package_config": { - "ha_vip": $scope.ha_vip - } - } - var updateHAVIP = dataService.updateClusterConfig(cluster.id, config).then(function(configData) { - // success callback - }, function(response) { - // error callback - return $q.reject(response); - }); - promises.push(updateHAVIP); - } - - $q.all(promises).then(function() { - wizardFactory.setServers($scope.servers); - var commitState = { - "name": "role_assign", - "state": "success", - "message": "" - }; - wizardFactory.setCommitState(commitState); - }, function(response) { - console.log("promises error", response); - var commitState = { - "name": "role_assign", - "state": "error", - "message": response.data - }; - wizardFactory.setCommitState(commitState); - }); - }; - - $scope.onDrop = function($event, server) { - $scope.dragKey = $scope.servers.indexOf(server); - }; - - $scope.dropSuccessHandler = function($event, role_value, key) { - var roleExist = $scope.checkRoleExist($scope.servers[$scope.dragKey].roles, role_value); - if (!roleExist) { - $scope.servers[$scope.dragKey].roles.push(role_value); - } else { - console.log("role exists"); - } - $scope.checkExistRolesDrag(); - }; - - $scope.checkExistRolesDrag = function() { - angular.forEach($scope.servers, function(value, key) { - angular.forEach($scope.servers[key].roles, function(server_role, server_role_key) { - angular.forEach($scope.roles, function(role, role_key) { - if ($scope.servers[key].roles[server_role_key].display_name == $scope.roles[role_key].display_name) { - $scope.existingRoles[key].splice(role_key, 1, "p"); - } - }); - }); - $scope.servers[key].dropChannel = $scope.existingRoles[key].toString(); - }); - }; -}) - -.controller('networkMappingCtrl', function($scope, wizardFactory, dataService) { - var cluster = wizardFactory.getClusterInfo(); - $scope.interfaces = wizardFactory.getInterfaces(); - $scope.original_networking = wizardFactory.getNetworkMapping(); - $scope.pendingInterface = ""; - - $scope.onDrop = function($event, key) { - $scope.pendingInterface = key; - }; - - angular.forEach($scope.interfaces, function(value, key) { - $scope.interfaces[key].dropChannel = "E"; }) - $scope.networking = {}; - angular.forEach($scope.original_networking, function(value, key) { - $scope.networking[key] = {}; - $scope.networking[key].mapping_interface = value; - if (key == "public") { - $scope.networking[key].dragChannel = "P"; - } else - $scope.networking[key].dragChannel = "E"; - }) + wizardModule.controller('reviewCtrl', function($scope, wizardFactory, dataService, $filter, ngTableParams, sortingService) { + var cluster = wizardFactory.getClusterInfo(); + $scope.servers = wizardFactory.getServers(); + $scope.interfaces = wizardFactory.getInterfaces(); + $scope.partition = wizardFactory.getPartition(); + $scope.network_mapping = wizardFactory.getNetworkMapping(); + $scope.server_credentials = wizardFactory.getServerCredentials(); + $scope.service_credentials = wizardFactory.getServiceCredentials(); + $scope.console_credentials = wizardFactory.getConsoleCredentials(); + $scope.global_config = wizardFactory.getGeneralConfig(); - $scope.dropSuccessHandler = function($event, key, dict) { - dict[key].mapping_interface = $scope.pendingInterface; - }; - - angular.forEach($scope.interfaces, function(value, key) { - // The interface with promisc mode is required to be set as Public Network - if (value.is_promiscuous) { - $scope.networking["public"].mapping_interface = key; - $scope.interfaces[key].dropChannel = "P"; - } - // The interface marked as management is required to be set as Management Network - if (value.is_mgmt) { - $scope.networking["management"].mapping_interface = key; - } - }); - - $scope.$watch(function() { - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { - if (newCommitState !== undefined) { - if (newCommitState.name == "network_mapping" && newCommitState.state == "triggered") { - $scope.commit(newCommitState.sendRequest); - } - } - }); - - $scope.commit = function(sendRequest) { - if (!sendRequest) { - var commitState = { - "name": "network_mapping", - "state": "goToPreviousStep", - "message": "" - }; - wizardFactory.setCommitState(commitState); - return; - } - - $scope.$emit("loading",true); - var networks = {}; - angular.forEach($scope.networking, function(value, key) { - networks[key] = value.mapping_interface; + dataService.getServerColumns().success(function(data) { + $scope.server_columns = data.review; }); - var network_mapping = { - "package_config": { - "network_mapping": networks + + $scope.tabs = [{ + title: 'Database & Queue', + url: 'service.tpl.html' + }, { + title: 'Keystone User', + url: 'console.tpl.html' + }, { + title: 'Server', + url: 'server.tpl.html' + }]; + + $scope.currentTab = $scope.tabs[0].url; + + $scope.onClickTab = function(tab) { + $scope.currentTab = tab.url; + } + + $scope.isActiveTab = function(tabUrl) { + return tabUrl == $scope.currentTab; + } + + $scope.tableParams = new ngTableParams({ + page: 1, // show first page + count: $scope.servers.length + 1 // count per page + }, { + counts: [], // hide count-per-page box + total: $scope.servers.length, // length of data + getData: function($defer, params) { + var reverse = false; + var orderBy = params.orderBy()[0]; + var orderBySort = ""; + var orderByColumn = ""; + + if (orderBy) { + orderByColumn = orderBy.substring(1); + orderBySort = orderBy.substring(0, 1); + if (orderBySort == "+") { + reverse = false; + } else { + reverse = true; + } + } + + var orderedData = params.sorting() ? + $filter('orderBy')($scope.servers, function(item) { + if (orderByColumn == "switch_ip") { + return sortingService.ipAddressPre(item.switch_ip); + } else { + return item[orderByColumn]; + } + }, reverse) : $scope.servers; + + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } - }; - dataService.updateClusterConfig(cluster.id, network_mapping).success(function(data) { - wizardFactory.setNetworkMapping(networks); - var commitState = { - "name": "network_mapping", - "state": "success", - "message": "" - }; - wizardFactory.setCommitState(commitState); - }).error(function(response) { - var commitState = { - "name": "network_mapping", - "state": "error", - "message": response - }; - wizardFactory.setCommitState(commitState); }); - }; -}) -.controller('reviewCtrl', function($scope, wizardFactory, dataService, $filter, ngTableParams, sortingService) { - var cluster = wizardFactory.getClusterInfo(); - $scope.servers = wizardFactory.getServers(); - $scope.interfaces = wizardFactory.getInterfaces(); - $scope.partition = wizardFactory.getPartition(); - $scope.network_mapping = wizardFactory.getNetworkMapping(); - $scope.server_credentials = wizardFactory.getServerCredentials(); - $scope.service_credentials = wizardFactory.getServiceCredentials(); - $scope.console_credentials = wizardFactory.getConsoleCredentials(); - $scope.global_config = wizardFactory.getGeneralConfig(); - - dataService.getServerColumns().success(function(data) { - $scope.server_columns = data.review; - }); - - $scope.tabs = [{ - title: 'Database & Queue', - url: 'service.tpl.html' - }, { - title: 'Keystone User', - url: 'console.tpl.html' - }, { - title: 'Server', - url: 'server.tpl.html' - }]; - - $scope.currentTab = $scope.tabs[0].url; - - $scope.onClickTab = function(tab) { - $scope.currentTab = tab.url; - } - - $scope.isActiveTab = function(tabUrl) { - return tabUrl == $scope.currentTab; - } - - $scope.tableParams = new ngTableParams({ - page: 1, // show first page - count: $scope.servers.length + 1 // count per page - }, { - counts: [], // hide count-per-page box - total: $scope.servers.length, // length of data - getData: function($defer, params) { - var reverse = false; - var orderBy = params.orderBy()[0]; - var orderBySort = ""; - var orderByColumn = ""; - - if (orderBy) { - orderByColumn = orderBy.substring(1); - orderBySort = orderBy.substring(0, 1); - if (orderBySort == "+") { - reverse = false; - } else { - reverse = true; + $scope.$watch(function() { + return wizardFactory.getCommitState() + }, function(newCommitState, oldCommitState) { + if (newCommitState !== undefined) { + if (newCommitState.name == "review" && newCommitState.state == "triggered") { + $scope.commit(); } } - - var orderedData = params.sorting() ? - $filter('orderBy')($scope.servers, function(item) { - if (orderByColumn == "switch_ip") { - return sortingService.ipAddressPre(item.switch_ip); - } else { - return item[orderByColumn]; - } - }, reverse) : $scope.servers; - - $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); - } - }); - - $scope.$watch(function() { - return wizardFactory.getCommitState() - }, function(newCommitState, oldCommitState) { - if (newCommitState !== undefined) { - if (newCommitState.name == "review" && newCommitState.state == "triggered") { - $scope.commit(); - } - } - }); - - $scope.commit = function() { - var reviewAction = { - "review": { - "hosts": [] - } - }; - var deployAction = { - "deploy": { - "hosts": [] - } - }; - angular.forEach($scope.servers, function(server) { - reviewAction.review.hosts.push(server.id); - deployAction.deploy.hosts.push(server.id); }); - dataService.postClusterActions(cluster.id, reviewAction).success(function(data) { - dataService.postClusterActions(cluster.id, deployAction).success(function(data) { - var commitState = { - "name": "review", - "state": "success", - "message": "" - }; - wizardFactory.setCommitState(commitState); + $scope.commit = function() { + var reviewAction = { + "review": { + "hosts": [] + } + }; + var deployAction = { + "deploy": { + "hosts": [] + } + }; + angular.forEach($scope.servers, function(server) { + reviewAction.review.hosts.push(server.id); + deployAction.deploy.hosts.push(server.id); + }); + + dataService.postClusterActions(cluster.id, reviewAction).success(function(data) { + dataService.postClusterActions(cluster.id, deployAction).success(function(data) { + var commitState = { + "name": "review", + "state": "success", + "message": "" + }; + wizardFactory.setCommitState(commitState); + }).error(function(data) { + console.warn("Deploy hosts error: ", data); + }); }).error(function(data) { - console.warn("Deploy hosts error: ", data); - }); - }).error(function(data) { - console.warn("Review hosts error: ", data); - }) - //TODO: error handling - }; + console.warn("Review hosts error: ", data); + }) + //TODO: error handling + }; - $scope.returnStep = function(reviewName) { - for (var i = 0; i < $scope.steps.length; i++) { - if (reviewName == $scope.steps[i].name) { - $scope.skipForward(i + 1); - } - } - }; - -}) - -.directive('ngKeypress', function() { - return function(scope, element, attrs) { - element.bind("keydown keypress", function(event) { - if (event.which === 9) { // 9 is tab key - var current = attrs.position; - var result = current.split('_'); - var next = result[0] + "_" + (parseInt(result[1]) + 1); - if ($("input[data-position=" + next + "]").length) { - - $("input[data-position=" + next + "]").focus(); - } else { - $(".btn-next").focus(); + $scope.returnStep = function(reviewName) { + for (var i = 0; i < $scope.steps.length; i++) { + if (reviewName == $scope.steps[i].name) { + $scope.skipForward(i + 1); } - event.preventDefault(); } - }); - }; -}) + }; -//Used for roles panel on Role Assignment page -.directive("rolepanelscroll", function($window) { - return function(scope, element, attrs) { - angular.element($window).bind("scroll", function() { - var window_top = this.pageYOffset; - var sticky_anchor_elem = angular.element($('#sticky-anchor')); - if(sticky_anchor_elem.length != 0) { - var div_top = sticky_anchor_elem.offset().top; - if (window_top > div_top) { - $('.role-panel').addClass('stick'); - } else { - $('.role-panel').removeClass('stick'); - } - scope.$apply(); - } - }); - }; -}); - -var wizardModalInstanceCtrl = function($scope, $modalInstance, warning) { - $scope.warning = warning; - - $scope.ok = function() { - $modalInstance.close(); - }; -}; - -var addSubnetModalInstanceCtrl = function($scope, $modalInstance, $q, subnets, dataService, $filter) { - $scope.subnetworks = angular.copy(subnets); - $scope.subnetAllValid = true; - - angular.forEach($scope.subnetworks, function(subnet) { - subnet['valid'] = true; }); - var allValid = function() { - var invalid = 0; - angular.forEach($scope.subnetworks, function(subnet) { - if (subnet['valid'] == false) { - invalid = 1; - } - }); - if (invalid == 0) { - $scope.subnetAllValid = true; - } else { + wizardModule.directive('ngKeypress', function() { + return function(scope, element, attrs) { + element.bind("keydown keypress", function(event) { + if (event.which === 9) { // 9 is tab key + var current = attrs.position; + var result = current.split('_'); + var next = result[0] + "_" + (parseInt(result[1]) + 1); + if ($("input[data-position=" + next + "]").length) { - $scope.subnetAllValid = false; - } - } - $scope.subnet_change = function(index, subnet) { - var subnetRegExp = /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}(\/){1}([0-9]|[0-2][0-9]|3[0-2])$/; - var valid = subnetRegExp.test(subnet); - $scope.subnetworks[index]['valid'] = valid; - allValid(); + $("input[data-position=" + next + "]").focus(); + } else { + $(".btn-next").focus(); + } + event.preventDefault(); + } + }); + }; + }); + + //Used for roles panel on Role Assignment page + wizardModule.directive("rolepanelscroll", function($window) { + return function(scope, element, attrs) { + angular.element($window).bind("scroll", function() { + var window_top = this.pageYOffset; + var sticky_anchor_elem = angular.element($('#sticky-anchor')); + if (sticky_anchor_elem.length != 0) { + var div_top = sticky_anchor_elem.offset().top; + if (window_top > div_top) { + $('.role-panel').addClass('stick'); + } else { + $('.role-panel').removeClass('stick'); + } + scope.$apply(); + } + }); + }; + }); + + var wizardModalInstanceCtrl = function($scope, $modalInstance, warning) { + $scope.warning = warning; + + $scope.ok = function() { + $modalInstance.close(); + }; }; - $scope.ok = function() { - var newsubnetworks = []; - var promises = []; + + var addSubnetModalInstanceCtrl = function($scope, $modalInstance, $q, subnets, dataService, $filter) { + $scope.subnetworks = angular.copy(subnets); + $scope.subnetAllValid = true; + angular.forEach($scope.subnetworks, function(subnet) { - var requestData = { - "subnet": subnet.subnet - } - if (subnet.id === undefined) { - // post subnetworks - var updateSubnetConfig = dataService.postSubnetConfig(requestData).then(function(subnetData) { - newsubnetworks.push(subnetData.data); - }, function(response) { - return $q.reject(response); - }); - promises.push(updateSubnetConfig); + subnet['valid'] = true; + }); + + var allValid = function() { + var invalid = 0; + angular.forEach($scope.subnetworks, function(subnet) { + if (subnet['valid'] == false) { + invalid = 1; + } + }); + if (invalid == 0) { + $scope.subnetAllValid = true; } else { - // put subnetworks - var updateSubnetConfig = dataService.putSubnetConfig(subnet.id, requestData).then(function(subnetData) { - newsubnetworks.push(subnetData.data); - }, function(response) { - return $q.reject(response); - }); - promises.push(updateSubnetConfig); + + $scope.subnetAllValid = false; } - }); - - $q.all(promises).then(function() { - $scope.subnetworks = newsubnetworks; - for (var i = 0; i < subnets.length && i < $scope.subnetworks.length; i++) { - $scope.subnetworks[i].$$hashKey = subnets[i].$$hashKey; - } - $modalInstance.close($scope.subnetworks); - }, function(response) { - console.log("promises error", response); - $scope.alerts = []; - $scope.alerts.push({ - "message": response - }); - }); - }; - - $scope.cancel = function() { - - $scope.subnetworks = $filter('filter')($scope.subnetworks, { - valid: true - }, true); - $modalInstance.dismiss('cancel'); - - }; - - $scope.closeAlert = function() { - $scope.alerts = []; - }; - - $scope.addSubnetwork = function() { - $scope.subnetworks.push({ - valid: false - }); - allValid(); - }; - - $scope.removeSubnetwork = function(index) { - dataService.deleteSubnet($scope.subnetworks[index].id).success(function(data) { - $scope.subnetworks.splice(index, 1); - }).error(function(response) { - $scope.alerts = []; - $scope.alerts.push({ - "message": response - }); - }); - allValid(); - }; - - $scope.$watch('subnetworks', function() { - if ($scope.subnetworks.length == 0) { - $scope.subnetworks.push({}); } - }, true); + $scope.subnet_change = function(index, subnet) { + var subnetRegExp = /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}(\/){1}([0-9]|[0-2][0-9]|3[0-2])$/; + var valid = subnetRegExp.test(subnet); + $scope.subnetworks[index]['valid'] = valid; + allValid(); + }; -}; + $scope.ok = function() { + var newsubnetworks = []; + var promises = []; + angular.forEach($scope.subnetworks, function(subnet) { + var requestData = { + "subnet": subnet.subnet + } + if (subnet.id === undefined) { + // post subnetworks + var updateSubnetConfig = dataService.postSubnetConfig(requestData).then(function(subnetData) { + newsubnetworks.push(subnetData.data); + }, function(response) { + return $q.reject(response); + }); + promises.push(updateSubnetConfig); + } else { + // put subnetworks + var updateSubnetConfig = dataService.putSubnetConfig(subnet.id, requestData).then(function(subnetData) { + newsubnetworks.push(subnetData.data); + }, function(response) { + return $q.reject(response); + }); + promises.push(updateSubnetConfig); + } + }); + + $q.all(promises).then(function() { + $scope.subnetworks = newsubnetworks; + for (var i = 0; i < subnets.length && i < $scope.subnetworks.length; i++) { + $scope.subnetworks[i].$$hashKey = subnets[i].$$hashKey; + } + $modalInstance.close($scope.subnetworks); + }, function(response) { + console.log("promises error", response); + $scope.alerts = []; + $scope.alerts.push({ + "message": response + }); + }); + }; + + $scope.cancel = function() { + + $scope.subnetworks = $filter('filter')($scope.subnetworks, { + valid: true + }, true); + $modalInstance.dismiss('cancel'); + + }; + + $scope.closeAlert = function() { + $scope.alerts = []; + }; + + $scope.addSubnetwork = function() { + $scope.subnetworks.push({ + valid: false + }); + allValid(); + }; + + $scope.removeSubnetwork = function(index) { + dataService.deleteSubnet($scope.subnetworks[index].id).success(function(data) { + $scope.subnetworks.splice(index, 1); + }).error(function(response) { + $scope.alerts = []; + $scope.alerts.push({ + "message": response + }); + }); + allValid(); + }; + + $scope.$watch('subnetworks', function() { + if ($scope.subnetworks.length == 0) { + $scope.subnetworks.push({}); + } + }, true); + + }; +}); \ No newline at end of file diff --git a/v2/src/app/wizard/wizard.tpl.html b/v2/src/app/wizard/wizard.tpl.html index fdc2c72..67d70b6 100644 --- a/v2/src/app/wizard/wizard.tpl.html +++ b/v2/src/app/wizard/wizard.tpl.html @@ -3,7 +3,7 @@
    @@ -26,7 +26,7 @@
    -
    +
diff --git a/v2/src/bootstrap.js b/v2/src/bootstrap.js new file mode 100644 index 0000000..3186513 --- /dev/null +++ b/v2/src/bootstrap.js @@ -0,0 +1,6 @@ +define(['angular', 'app/app'], function(ng) { + 'use strict'; + ng.element(document).ready(function() { + ng.bootstrap(document, ['app']); + }) +}); \ No newline at end of file diff --git a/v2/src/common/charts.js b/v2/src/common/charts.js index e9b800f..05aa9e4 100644 --- a/v2/src/common/charts.js +++ b/v2/src/common/charts.js @@ -1,258 +1,212 @@ -angular.module('compass.charts', []) +define(['angular', 'ganttChart'], function(angular, ganttChart) { + var chartsModule = angular.module('compass.charts', []); -.directive('piechart', function() { - return { - restrict: 'E', - scope: { - piedata: '=' - }, - link: function(scope, element, attrs) { - var piedata = scope.piedata; + chartsModule.directive('piechart', function() { + return { + restrict: 'E', + scope: { + piedata: '=' + }, + link: function(scope, element, attrs) { + var piedata = scope.piedata; - var width = 300, - height = 250, - radius = Math.min(width, height) / 2; - //var color = d3.scale.category20(); - var color = d3.scale.ordinal() - .range(["#fee188", "#cb6fd7", "#9abc32", "#f79263", "#6fb3e0", "#d53f40", "#1F77B4"]); + var width = 300, + height = 250, + radius = Math.min(width, height) / 2; + //var color = d3.scale.category20(); + var color = d3.scale.ordinal() + .range(["#fee188", "#cb6fd7", "#9abc32", "#f79263", "#6fb3e0", "#d53f40", "#1F77B4"]); - var svg = d3.select("piechart").append("svg") - .attr("width", width) - .attr("height", height) - .append("g") - .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); + var svg = d3.select("piechart").append("svg") + .attr("width", width) + .attr("height", height) + .append("g") + .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); - var arc = d3.svg.arc() - .outerRadius(radius - 10) - .innerRadius(0); + var arc = d3.svg.arc() + .outerRadius(radius - 10) + .innerRadius(0); - scope.$watch('piedata', function(val) { - piedata = val; + scope.$watch('piedata', function(val) { + piedata = val; - svg.selectAll('g.arc').remove(); + svg.selectAll('g.arc').remove(); - var pie = d3.layout.pie() - .sort(null) - .value(function(d) { - return d.number; - }); - - piedata.forEach(function(d) { - d.number = +d.number; - }); - - var g = svg.selectAll(".arc") - .data(pie(piedata)) - .enter().append("g") - .attr("class", "arc"); - - g.append("path") - .attr("d", arc) - .attr('stroke', '#fff') - .attr('stroke-width', '3') - .style("fill", function(d) { - return color(d.data.name); - }); - - g.append("text") - .attr("transform", function(d) { - return "translate(" + arc.centroid(d) + ")"; - }) - .attr("dy", ".35em") - .style("text-anchor", "middle") - .text(function(d) { - return d.data.name; - }); - - }, true) - } - } -}) - -.directive('hostprogressbar', function(dataService, $timeout) { - return { - restrict: 'E', - scope: { - hostid: '=', - clusterid: '=', - clusterstate: '=', - progressdata: '@' - }, - templateUrl: "src/common/progressbar.tpl.html", - link: function(scope, element, attrs) { - var hostId = scope.hostid; - var clusterId = scope.clusterid; - var clusterState = scope.clusterstate; - var progress = 0; - var progressTimer; - var fireTimer = true; - scope.progressdata = 0; - scope.progressSeverity = "INFO"; - var getProgress = function(num) { - dataService.getClusterHostProgress(clusterId, hostId).then(function(progressData) { - //success - progress = parseInt(eval(progressData.data.percentage * 100)); - scope.progressdata = progress; - if (fireTimer && progress < 100 && num != 1) { - progressTimer = $timeout(getProgress, 5000); - } - scope.message = progressData.data.message; - scope.progressSeverity = progressData.data.severity; - }, function(response) { - - }) - }; - - scope.$watch('clusterstate', function(val) { - if (clusterState != "SUCCESSFUL" && clusterState != "ERROR") { - $timeout(getProgress, 1000); - } else { - getProgress(1); - } - }); - - element.bind('$destroy', function() { - fireTimer = false; - $timeout.cancel(progressTimer); - }); - } - } -}) - -.directive('circlepacking', function() { - return { - restrict: 'EAC', - scope: { - data: '=', - dataready: '=', - id: '@' - }, - link: function(scope, elem, attrs) { - scope.$watch('dataready', function(newVal, oldVal) { - if (newVal != oldVal) { - if (newVal == "true") { - drawCircleGraph(); - } - } - }, true); - - function drawCircleGraph() { - - var elemId = scope.id; - var data = scope.data; - - var w = 600, - h = 600, - r = 550, - x = d3.scale.linear().range([0, r]), - y = d3.scale.linear().range([0, r]), - node, - root; - - var pack = d3.layout.pack() - .size([r, r]) - .value(function(d) { - if (d.children === undefined || d.children.length == 0) { - return 500; - } else { - return undefined; - } - }) - - var vis = d3.select("#" + elemId).append("svg:svg", "h2") - .attr("width", w) - .attr("height", h) - .append("svg:g") - .attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")"); - - node = root = data; - - var nodes = pack.nodes(root); - - vis.selectAll("circle") - .data(nodes) - .enter().append("svg:circle") - .attr("class", function(d) { - return d.children ? "parent" : "child"; - }) - .attr("cx", function(d) { - return d.x; - }) - .attr("cy", function(d) { - return d.y; - }) - .attr("r", function(d) { - return d.r; - }) - .attr("depth", function(d) { - return d.depth; - }) - .on("click", function(d) { - return zoom(node == d ? root : d); - }) - .on("contextmenu", function(d) { - //stop showing browser menu - d3.event.preventDefault(); - }) - .on("mouseover", function(d) { - //console.log("mouseover ", d) - }); - - vis.selectAll("text") - .data(nodes) - .enter().append("svg:text") - .attr("class", function(d) { - return d.children ? "parent" : "child"; - }) - .attr("x", function(d) { - return d.x; - }) - .attr("y", function(d) { - if (d.depth == 0 || d.depth == 1) { - return y(d.y + d.r + 20); - } else if (d.depth == 2 || d.depth == 3) { - return y(d.y + d.r + 5); - } else { - return y(d.y); - } - //return d.children ? d.y + d.r + 10 : d.y; - }) - .attr("dy", ".35em") - .attr("text-anchor", "middle") - .style("display", function(d) { - return d.r > 30 ? "block" : "none"; - }) - .text(function(d) { - return d.name; - }); - - d3.select(window).on("click", function() { - zoom(root); - }); - - - function zoom(d, i) { - var k = r / d.r / 2; - x.domain([d.x - d.r, d.x + d.r]); - y.domain([d.y - d.r, d.y + d.r]); - - var t = vis.transition() - .duration(d3.event.altKey ? 7500 : 750); - - t.selectAll("circle") - .attr("cx", function(d) { - return x(d.x); - }) - .attr("cy", function(d) { - return y(d.y); - }) - .attr("r", function(d) { - return k * d.r; + var pie = d3.layout.pie() + .sort(null) + .value(function(d) { + return d.number; }); - t.selectAll("text") + piedata.forEach(function(d) { + d.number = +d.number; + }); + + var g = svg.selectAll(".arc") + .data(pie(piedata)) + .enter().append("g") + .attr("class", "arc"); + + g.append("path") + .attr("d", arc) + .attr('stroke', '#fff') + .attr('stroke-width', '3') + .style("fill", function(d) { + return color(d.data.name); + }); + + g.append("text") + .attr("transform", function(d) { + return "translate(" + arc.centroid(d) + ")"; + }) + .attr("dy", ".35em") + .style("text-anchor", "middle") + .text(function(d) { + return d.data.name; + }); + + }, true) + } + } + }); + + chartsModule.directive('hostprogressbar', function(dataService, $timeout) { + return { + restrict: 'E', + scope: { + hostid: '=', + clusterid: '=', + clusterstate: '=', + progressdata: '@' + }, + templateUrl: "src/common/progressbar.tpl.html", + link: function(scope, element, attrs) { + var hostId = scope.hostid; + var clusterId = scope.clusterid; + var clusterState = scope.clusterstate; + var progress = 0; + var progressTimer; + var fireTimer = true; + scope.progressdata = 0; + scope.progressSeverity = "INFO"; + var getProgress = function(num) { + dataService.getClusterHostProgress(clusterId, hostId).then(function(progressData) { + //success + progress = parseInt(eval(progressData.data.percentage * 100)); + scope.progressdata = progress; + if (fireTimer && progress < 100 && num != 1) { + progressTimer = $timeout(getProgress, 5000); + } + scope.message = progressData.data.message; + scope.progressSeverity = progressData.data.severity; + }, function(response) { + + }) + }; + + scope.$watch('clusterstate', function(val) { + if (clusterState != "SUCCESSFUL" && clusterState != "ERROR") { + $timeout(getProgress, 1000); + } else { + getProgress(1); + } + }); + + element.bind('$destroy', function() { + fireTimer = false; + $timeout.cancel(progressTimer); + }); + } + } + }); + + chartsModule.directive('circlepacking', function() { + return { + restrict: 'EAC', + scope: { + data: '=', + dataready: '=', + id: '@' + }, + link: function(scope, elem, attrs) { + scope.$watch('dataready', function(newVal, oldVal) { + if (newVal != oldVal) { + if (newVal == "true") { + drawCircleGraph(); + } + } + }, true); + + function drawCircleGraph() { + + var elemId = scope.id; + var data = scope.data; + + var w = 600, + h = 600, + r = 550, + x = d3.scale.linear().range([0, r]), + y = d3.scale.linear().range([0, r]), + node, + root; + + var pack = d3.layout.pack() + .size([r, r]) + .value(function(d) { + if (d.children === undefined || d.children.length == 0) { + return 500; + } else { + return undefined; + } + }) + + var vis = d3.select("#" + elemId).append("svg:svg", "h2") + .attr("width", w) + .attr("height", h) + .append("svg:g") + .attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")"); + + node = root = data; + + var nodes = pack.nodes(root); + + vis.selectAll("circle") + .data(nodes) + .enter().append("svg:circle") + .attr("class", function(d) { + return d.children ? "parent" : "child"; + }) + .attr("cx", function(d) { + return d.x; + }) + .attr("cy", function(d) { + return d.y; + }) + .attr("r", function(d) { + return d.r; + }) + .attr("depth", function(d) { + return d.depth; + }) + .on("click", function(d) { + return zoom(node == d ? root : d); + }) + .on("contextmenu", function(d) { + //stop showing browser menu + d3.event.preventDefault(); + }) + .on("mouseover", function(d) { + //console.log("mouseover ", d) + }); + + vis.selectAll("text") + .data(nodes) + .enter().append("svg:text") + .attr("class", function(d) { + return d.children ? "parent" : "child"; + }) .attr("x", function(d) { - return x(d.x); + return d.x; }) .attr("y", function(d) { if (d.depth == 0 || d.depth == 1) { @@ -262,372 +216,415 @@ angular.module('compass.charts', []) } else { return y(d.y); } - - //return d.children ? y(d.y + d.r + 10) : y(d.y); + //return d.children ? d.y + d.r + 10 : d.y; }) + .attr("dy", ".35em") + .attr("text-anchor", "middle") .style("display", function(d) { - return k * d.r > 30 ? "block" : "none"; - }); - - node = d; - d3.event.stopPropagation(); - } - } - - } - }; -}) - -.directive('treechart', function() { - return { - restrict: 'EAC', - scope: { - data: '=', - dataready: '=', - id: '@' - }, - link: function(scope, elem, attrs) { - scope.$watch('dataready', function(newVal, oldVal) { - if (newVal != oldVal) { - if (newVal == "true") { - drawTree(); - } - } - }, true); - - function drawTree() { - var elemId = scope.id, - tree = d3.layout.tree(); - - var margin = { - top: 0, - right: 120, - bottom: 0, - left: 130 - }; - - // calculate servers count - var serverCount = 0; - var treeNodes = tree.nodes(scope.data).reverse(); - treeNodes.forEach(function(d) { - if (d.depth == 2) - serverCount++; - }); - - var serversHeight = serverCount * 68; - if (serversHeight < 500) { - serversHeight = 500; - } - - var width = 1000 - margin.right - margin.left, - height = serversHeight - margin.top - margin.bottom; - tree.size([height, width]); - - imgWidth = 163; - imgHeight = 32; - - var i = 0, - duration = 750, - root = scope.data; - - var diagonal = d3.svg.diagonal() - .projection(function(d) { - return [d.y, d.x]; - }); - - var svg = d3.select("#" + elemId).append("svg") - .attr("width", width + margin.right + margin.left) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - root.x0 = height / 2; - root.y0 = 0; - - update(root); - - d3.select(self.frameElement).style("height", "600px"); - - function update(source) { - - // Compute the new tree layout. - var nodes = tree.nodes(root).reverse(), - links = tree.links(nodes); - - // Normalize for fixed-depth. - nodes.forEach(function(d) { - d.y = d.depth * 300; - }); - - // Update the nodes… - var node = svg.selectAll("g.node") - .data(nodes, function(d) { - return d.id || (d.id = ++i); - }); - - // Enter any new nodes at the parent's previous position. - var nodeEnter = node.enter().append("g") - .attr("class", "node") - .attr("transform", function(d) { - var transX = parseFloat(source.y0) - 10; - var transY = parseFloat(source.x0) - imgHeight / 2; - return "translate(" + transX + "," + transY + ")"; - }) - .attr("width", imgWidth) - .attr("height", imgHeight) - .on("click", click); - - nodeEnter.append("image") - .attr("xlink:href", function(d) { - if (d.depth == 0) - return "assets/img/router.png"; - else if (d.depth == 1) - return "assets/img/switch1.png"; - else - return "assets/img/server1.png"; - }) - .attr("width", imgWidth) - .attr("height", imgHeight); - - nodeEnter.append("rect") - .attr("width", imgWidth) - .attr("height", imgHeight) - .attr("data-state", function(d) { - return d.state - }) - .style("opacity", function(d) { - if (d.depth == 0) - return 0; - else - return 0.3; - }); - - nodeEnter.append("text") - .attr("x", function(d) { - if (d.depth == 0) - return -5; - else - return d.children || d._children ? -8 : imgWidth + 10; - }) - .attr("y", function(d) { - if (d.depth == 0) - return imgHeight / 2; - else if (d.depth == 1) - return 6; - else - return imgHeight / 2; - }) - .attr("dy", ".25em") - .attr("text-anchor", function(d) { - return d.children || d._children ? "end" : "start"; + return d.r > 30 ? "block" : "none"; }) .text(function(d) { return d.name; - }) - .style("font-size", "15px") - .style("fill-opacity", 1e-6); - - // Transition nodes to their new position. - var nodeUpdate = node.transition() - .duration(duration) - .attr("transform", function(d) { - var transX = parseFloat(d.y) - 10; - var transY = parseFloat(d.x) - imgHeight / 2; - return "translate(" + transX + "," + transY + ")"; }); - nodeUpdate.select("text") - .style("fill-opacity", 1); - - // Transition exiting nodes to the parent's new position. - var nodeExit = node.exit().transition() - .duration(duration) - .attr("transform", function(d) { - var transX = parseFloat(source.y) - 10; - var transY = parseFloat(source.x) - imgHeight / 2; - return "translate(" + transX + "," + transY + ")"; - }) - .remove(); - - nodeExit.select("circle") - .attr("r", 1e-6); - - nodeExit.select("text") - .style("fill-opacity", 1e-6); - - // Update the links… - var link = svg.selectAll("path.link") - .data(links, function(d) { - return d.target.id; - }); - - // Enter any new links at the parent's previous position. - link.enter().insert("path", "g") - .attr("class", "link") - .attr("d", function(d) { - var o = { - x: source.x0, - y: source.y0 - }; - return diagonal({ - source: o, - target: o - }); - }); - - // Transition links to their new position. - link.transition() - .duration(duration) - .attr("d", diagonal); - - // Transition exiting nodes to the parent's new position. - link.exit().transition() - .duration(duration) - .attr("d", function(d) { - var o = { - x: source.x, - y: source.y - }; - return diagonal({ - source: o, - target: o - }); - }) - .remove(); - - // Stash the old positions for transition. - nodes.forEach(function(d) { - d.x0 = d.x; - d.y0 = d.y; + d3.select(window).on("click", function() { + zoom(root); }); - } - // Toggle children on click. - function click(d) { - if (d.children) { - d._children = d.children; - d.children = null; - } else { - d.children = d._children; - d._children = null; + + function zoom(d, i) { + var k = r / d.r / 2; + x.domain([d.x - d.r, d.x + d.r]); + y.domain([d.y - d.r, d.y + d.r]); + + var t = vis.transition() + .duration(d3.event.altKey ? 7500 : 750); + + t.selectAll("circle") + .attr("cx", function(d) { + return x(d.x); + }) + .attr("cy", function(d) { + return y(d.y); + }) + .attr("r", function(d) { + return k * d.r; + }); + + t.selectAll("text") + .attr("x", function(d) { + return x(d.x); + }) + .attr("y", function(d) { + if (d.depth == 0 || d.depth == 1) { + return y(d.y + d.r + 20); + } else if (d.depth == 2 || d.depth == 3) { + return y(d.y + d.r + 5); + } else { + return y(d.y); + } + + //return d.children ? y(d.y + d.r + 10) : y(d.y); + }) + .style("display", function(d) { + return k * d.r > 30 ? "block" : "none"; + }); + + node = d; + d3.event.stopPropagation(); } - update(d); - } - } - } - } -}) - -app.directive('ganttchart', function() { - return { - restrict: 'E', - scope: { - data: '=', - dataready: '=' - }, - template: '
' - + '' - + '' - + '' - + '' - + '
' - + '
', - // BUG: svg not appended initially if using templateUrl - //templateUrl: "src/common/ganttchart.tpl.html", - link: function(scope, element, attrs) { - scope.$watch('dataready', function(newVal, oldVal) { - if (newVal != oldVal) { - if (newVal == "true") { - drawChart(); - } - } - }, true); - - function drawChart () { - var tasks = scope.data; - var hostnames = []; - - angular.forEach(tasks, function(task) { - if(hostnames.indexOf(task) == -1) { - hostnames.push(task.name); - } - }); - - //var hostnames = scope.hosts; - var taskStatus = { - "SUCCESSFUL": "bar-successful", - "CRITICAL": "bar-failed", - "WARNING": "bar-warning", - "UNKNOWN": "bar-unknown" - }; - - tasks.sort(function(a, b) { - return a.endDate - b.endDate; - }); - var maxDate = tasks[tasks.length - 1].endDate; - tasks.sort(function(a, b) { - return a.startDate - b.startDate; - }); - var minDate = tasks[0].startDate; - - var format = "%H:%M"; - var timeDomainString = "1day"; - - var gantt = d3.gantt().taskTypes(hostnames).taskStatus(taskStatus).tickFormat(format).height(450).width(800); - - scope.changeTimeDomain = function(timeDomainString) { - this.timeDomainString = timeDomainString; - switch (timeDomainString) { - case "1hr": - format = "%H:%M:%S"; - gantt.timeDomain([d3.time.hour.offset(getEndDate(), -1), getEndDate()]); - break; - case "3hr": - format = "%H:%M"; - gantt.timeDomain([d3.time.hour.offset(getEndDate(), -3), getEndDate()]); - break; - - case "6hr": - format = "%H:%M"; - gantt.timeDomain([d3.time.hour.offset(getEndDate(), -6), getEndDate()]); - break; - - case "1day": - format = "%H:%M"; - gantt.timeDomain([d3.time.day.offset(getEndDate(), -1), getEndDate()]); - break; - - case "1week": - format = "%a %H:%M"; - gantt.timeDomain([d3.time.day.offset(getEndDate(), -7), getEndDate()]); - break; - default: - format = "%H:%M" - - } - gantt.tickFormat(format); - gantt.redraw(tasks); - } - - gantt.timeDomainMode("fixed"); - scope.changeTimeDomain(timeDomainString); - - gantt(tasks); - - - - function getEndDate() { - var lastEndDate = Date.now(); - if (tasks.length > 0) { - lastEndDate = tasks[tasks.length - 1].endDate; - } - - return lastEndDate; } } + }; + }); + chartsModule.directive('treechart', function() { + return { + restrict: 'EAC', + scope: { + data: '=', + dataready: '=', + id: '@' + }, + link: function(scope, elem, attrs) { + scope.$watch('dataready', function(newVal, oldVal) { + if (newVal != oldVal) { + if (newVal == "true") { + drawTree(); + } + } + }, true); + + function drawTree() { + var elemId = scope.id, + tree = d3.layout.tree(); + + var margin = { + top: 0, + right: 120, + bottom: 0, + left: 130 + }; + + // calculate servers count + var serverCount = 0; + var treeNodes = tree.nodes(scope.data).reverse(); + treeNodes.forEach(function(d) { + if (d.depth == 2) + serverCount++; + }); + + var serversHeight = serverCount * 68; + if (serversHeight < 500) { + serversHeight = 500; + } + + var width = 1000 - margin.right - margin.left, + height = serversHeight - margin.top - margin.bottom; + tree.size([height, width]); + + imgWidth = 163; + imgHeight = 32; + + var i = 0, + duration = 750, + root = scope.data; + + var diagonal = d3.svg.diagonal() + .projection(function(d) { + return [d.y, d.x]; + }); + + var svg = d3.select("#" + elemId).append("svg") + .attr("width", width + margin.right + margin.left) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + root.x0 = height / 2; + root.y0 = 0; + + update(root); + + d3.select(self.frameElement).style("height", "600px"); + + function update(source) { + + // Compute the new tree layout. + var nodes = tree.nodes(root).reverse(), + links = tree.links(nodes); + + // Normalize for fixed-depth. + nodes.forEach(function(d) { + d.y = d.depth * 300; + }); + + // Update the nodes… + var node = svg.selectAll("g.node") + .data(nodes, function(d) { + return d.id || (d.id = ++i); + }); + + // Enter any new nodes at the parent's previous position. + var nodeEnter = node.enter().append("g") + .attr("class", "node") + .attr("transform", function(d) { + var transX = parseFloat(source.y0) - 10; + var transY = parseFloat(source.x0) - imgHeight / 2; + return "translate(" + transX + "," + transY + ")"; + }) + .attr("width", imgWidth) + .attr("height", imgHeight) + .on("click", click); + + nodeEnter.append("image") + .attr("xlink:href", function(d) { + if (d.depth == 0) + return "assets/img/router.png"; + else if (d.depth == 1) + return "assets/img/switch1.png"; + else + return "assets/img/server1.png"; + }) + .attr("width", imgWidth) + .attr("height", imgHeight); + + nodeEnter.append("rect") + .attr("width", imgWidth) + .attr("height", imgHeight) + .attr("data-state", function(d) { + return d.state + }) + .style("opacity", function(d) { + if (d.depth == 0) + return 0; + else + return 0.3; + }); + + nodeEnter.append("text") + .attr("x", function(d) { + if (d.depth == 0) + return -5; + else + return d.children || d._children ? -8 : imgWidth + 10; + }) + .attr("y", function(d) { + if (d.depth == 0) + return imgHeight / 2; + else if (d.depth == 1) + return 6; + else + return imgHeight / 2; + }) + .attr("dy", ".25em") + .attr("text-anchor", function(d) { + return d.children || d._children ? "end" : "start"; + }) + .text(function(d) { + return d.name; + }) + .style("font-size", "15px") + .style("fill-opacity", 1e-6); + + // Transition nodes to their new position. + var nodeUpdate = node.transition() + .duration(duration) + .attr("transform", function(d) { + var transX = parseFloat(d.y) - 10; + var transY = parseFloat(d.x) - imgHeight / 2; + return "translate(" + transX + "," + transY + ")"; + }); + + nodeUpdate.select("text") + .style("fill-opacity", 1); + + // Transition exiting nodes to the parent's new position. + var nodeExit = node.exit().transition() + .duration(duration) + .attr("transform", function(d) { + var transX = parseFloat(source.y) - 10; + var transY = parseFloat(source.x) - imgHeight / 2; + return "translate(" + transX + "," + transY + ")"; + }) + .remove(); + + nodeExit.select("circle") + .attr("r", 1e-6); + + nodeExit.select("text") + .style("fill-opacity", 1e-6); + + // Update the links… + var link = svg.selectAll("path.link") + .data(links, function(d) { + return d.target.id; + }); + + // Enter any new links at the parent's previous position. + link.enter().insert("path", "g") + .attr("class", "link") + .attr("d", function(d) { + var o = { + x: source.x0, + y: source.y0 + }; + return diagonal({ + source: o, + target: o + }); + }); + + // Transition links to their new position. + link.transition() + .duration(duration) + .attr("d", diagonal); + + // Transition exiting nodes to the parent's new position. + link.exit().transition() + .duration(duration) + .attr("d", function(d) { + var o = { + x: source.x, + y: source.y + }; + return diagonal({ + source: o, + target: o + }); + }) + .remove(); + + // Stash the old positions for transition. + nodes.forEach(function(d) { + d.x0 = d.x; + d.y0 = d.y; + }); + } + + // Toggle children on click. + function click(d) { + if (d.children) { + d._children = d.children; + d.children = null; + } else { + d.children = d._children; + d._children = null; + } + update(d); + } + } + } } - } + }); -}) \ No newline at end of file + chartsModule.directive('ganttchart', function() { + return { + restrict: 'E', + scope: { + data: '=', + dataready: '=' + }, + template: '
' + '' + '' + '' + '' + '
' + '
', + // BUG: svg not appended initially if using templateUrl + //templateUrl: "src/common/ganttchart.tpl.html", + link: function(scope, element, attrs) { + scope.$watch('dataready', function(newVal, oldVal) { + if (newVal != oldVal) { + if (newVal == "true") { + drawChart(); + } + } + }, true); + + function drawChart() { + var tasks = scope.data; + var hostnames = []; + + angular.forEach(tasks, function(task) { + if (hostnames.indexOf(task) == -1) { + hostnames.push(task.name); + } + }); + + //var hostnames = scope.hosts; + var taskStatus = { + "SUCCESSFUL": "bar-successful", + "CRITICAL": "bar-failed", + "WARNING": "bar-warning", + "UNKNOWN": "bar-unknown" + }; + + tasks.sort(function(a, b) { + return a.endDate - b.endDate; + }); + var maxDate = tasks[tasks.length - 1].endDate; + tasks.sort(function(a, b) { + return a.startDate - b.startDate; + }); + var minDate = tasks[0].startDate; + + var format = "%H:%M"; + var timeDomainString = "1day"; + + //var gantt = d3.gantt().taskTypes(hostnames).taskStatus(taskStatus).tickFormat(format).height(450).width(800); + + var gantt = ganttChart().taskTypes(hostnames).taskStatus(taskStatus).tickFormat(format).height(450).width(800); + scope.changeTimeDomain = function(timeDomainString) { + this.timeDomainString = timeDomainString; + switch (timeDomainString) { + case "1hr": + format = "%H:%M:%S"; + gantt.timeDomain([d3.time.hour.offset(getEndDate(), -1), getEndDate()]); + break; + case "3hr": + format = "%H:%M"; + gantt.timeDomain([d3.time.hour.offset(getEndDate(), -3), getEndDate()]); + break; + + case "6hr": + format = "%H:%M"; + gantt.timeDomain([d3.time.hour.offset(getEndDate(), -6), getEndDate()]); + break; + + case "1day": + format = "%H:%M"; + gantt.timeDomain([d3.time.day.offset(getEndDate(), -1), getEndDate()]); + break; + + case "1week": + format = "%a %H:%M"; + gantt.timeDomain([d3.time.day.offset(getEndDate(), -7), getEndDate()]); + break; + default: + format = "%H:%M" + + } + gantt.tickFormat(format); + gantt.redraw(tasks); + } + + gantt.timeDomainMode("fixed"); + scope.changeTimeDomain(timeDomainString); + + gantt(tasks); + + + + function getEndDate() { + var lastEndDate = Date.now(); + if (tasks.length > 0) { + lastEndDate = tasks[tasks.length - 1].endDate; + } + + return lastEndDate; + } + + } + + } + } + + }); +}); \ No newline at end of file diff --git a/v2/src/common/findservers/findservers.js b/v2/src/common/findservers/findservers.js index 967f7c7..f975269 100644 --- a/v2/src/common/findservers/findservers.js +++ b/v2/src/common/findservers/findservers.js @@ -1,201 +1,203 @@ -angular.module('compass.findservers', []) -.directive('switchrow', function(dataService, $timeout) { - return { - restrict: 'A', - scope: { - polling: '=', - switchinfo: '=', - result: '=', - machines: '=' - }, - link: function(scope, element, attrs) { - var checkSwitchTimer; - var checkSwitchCount = 0; - //var pollingTriggered = scope.polling; - var fireTimer = true; +define(['angular'], function() { + var findserversModule = angular.module('compass.findservers', []); + findserversModule.directive('switchrow', function(dataService, $timeout) { + return { + restrict: 'A', + scope: { + polling: '=', + switchinfo: '=', + result: '=', + machines: '=' + }, + link: function(scope, element, attrs) { + var checkSwitchTimer; + var checkSwitchCount = 0; + //var pollingTriggered = scope.polling; + var fireTimer = true; - var getMachines = function() { - dataService.getSwitchMachines(scope.switchinfo.id).success(function(data) { - scope.polling = false; - scope.result = "success"; - scope.machines = data; - }).error(function(data) { - scope.polling = false; - scope.result = "error"; - }) - }; - - // check switch state 15 times with the interval of 2 sec - var checkSwitchState = function() { - checkSwitchCount++; - dataService.getSwitchById(scope.switchinfo.id).success(function(data) { - if (data.state == "under_monitoring") { - getMachines(); - } else if (data.state === "initialized" || data.state === "repolling") - if (fireTimer && checkSwitchCount < 15) { - checkSwitchTimer = $timeout(checkSwitchState, 2000); - } else { - scope.polling = false; - scope.result = "error"; - } else { + var getMachines = function() { + dataService.getSwitchMachines(scope.switchinfo.id).success(function(data) { + scope.polling = false; + scope.result = "success"; + scope.machines = data; + }).error(function(data) { scope.polling = false; scope.result = "error"; - } - }) - }; + }) + }; - scope.$watch('polling', function(newval, oldval) { - if (newval != oldval) { - if (newval == true) { - checkSwitchCount = 0; - fireTimer = true; + // check switch state 15 times with the interval of 2 sec + var checkSwitchState = function() { + checkSwitchCount++; + dataService.getSwitchById(scope.switchinfo.id).success(function(data) { + if (data.state == "under_monitoring") { + getMachines(); + } else if (data.state === "initialized" || data.state === "repolling") + if (fireTimer && checkSwitchCount < 15) { + checkSwitchTimer = $timeout(checkSwitchState, 2000); + } else { + scope.polling = false; + scope.result = "error"; + } else { + scope.polling = false; + scope.result = "error"; + } + }) + }; - var findingAction = { - "find_machines": null - }; - dataService.postSwitchAction(scope.switchinfo.id, findingAction).success(function(data) { - checkSwitchState(); - }) - } - } - }) + scope.$watch('polling', function(newval, oldval) { + if (newval != oldval) { + if (newval == true) { + checkSwitchCount = 0; + fireTimer = true; - element.bind('$destroy', function() { - fireTimer = false; - $timeout.cancel(checkSwitchTimer); - }); - } - } -}) - -.directive('findservers', function(dataService, $modal, $log) { - return { - restrict: 'E', - scope: { - newFoundServers: '=results' - }, - templateUrl: "src/common/findservers/find-new-servers.tpl.html", - link: function(scope, element, attrs) { - scope.switches = []; - scope.newFoundServers = []; - scope.isFindingNewServers = false; - - dataService.getSwitches().success(function(data) { - scope.switches = data; - }); - - scope.modifySwitchModal = function(index) { - var modalInstance = $modal.open({ - templateUrl: 'modifySwitchModal.html', - controller: modifySwitchModalInstanceCtrl, - resolve: { - targetSwitch: function() { - return scope.switches[index]; + var findingAction = { + "find_machines": null + }; + dataService.postSwitchAction(scope.switchinfo.id, findingAction).success(function(data) { + checkSwitchState(); + }) } } + }) + + element.bind('$destroy', function() { + fireTimer = false; + $timeout.cancel(checkSwitchTimer); + }); + } + } + }); + + findserversModule.directive('findservers', function(dataService, $modal, $log) { + return { + restrict: 'E', + scope: { + newFoundServers: '=results' + }, + templateUrl: "src/common/findservers/find-new-servers.tpl.html", + link: function(scope, element, attrs) { + scope.switches = []; + scope.newFoundServers = []; + scope.isFindingNewServers = false; + + dataService.getSwitches().success(function(data) { + scope.switches = data; }); - modalInstance.result.then(function(targetSwitch) { - scope.alerts = []; - dataService.putSwitches(targetSwitch.id,targetSwitch).success(function() { + scope.modifySwitchModal = function(index) { + var modalInstance = $modal.open({ + templateUrl: 'modifySwitchModal.html', + controller: modifySwitchModalInstanceCtrl, + resolve: { + targetSwitch: function() { + return scope.switches[index]; + } + } + }); - scope.switches[index] = angular.copy(targetSwitch); + modalInstance.result.then(function(targetSwitch) { + scope.alerts = []; + dataService.putSwitches(targetSwitch.id, targetSwitch).success(function() { + + scope.switches[index] = angular.copy(targetSwitch); + + }).error(function(response) { + scope.alerts[0] = response; + }); + }, function() { + $log.info('Modal dismissed at: ' + new Date()); + }); + }; + + scope.selectAllSwitches = function(flag) { + if (flag) { + angular.forEach(scope.switches, function(sv) { + sv.selected = true; + }) + } else { + angular.forEach(scope.switches, function(sv) { + sv.selected = false; + }) + } + }; + + scope.findServers = function() { + var swSelection = false; + angular.forEach(scope.switches, function(sw) { + if (sw.selected) { + swSelection = true; + } + }); + if (!swSelection) { + alert("Please select at least one switch"); + } else { + scope.isFindingNewServers = true; + scope.newFoundServers = []; + angular.forEach(scope.switches, function(sw) { + if (sw.selected) { + sw.result = ""; + sw.finished = false; + sw.polling = true; + } + }); + } + }; + + scope.$watch('switches', function(val) { + var totalResultReady = true; + if (scope.isFindingNewServers) { + angular.forEach(scope.switches, function(sw) { + if (sw.selected && !sw.finished) { + if (sw.result == "success") { + scope.newFoundServers = scope.newFoundServers.concat(angular.copy(sw.machines)); + sw.finished = true; + } else if (sw.result == "error") { + sw.finished = true; + } else { + totalResultReady = false; + } + } + }); + if (totalResultReady) { + scope.isFindingNewServers = false; + } + } + }, true); + + + scope.newswitch = {} + scope.newswitch.credentials = {}; + scope.alerts = []; + + scope.addSwitch = function() { + scope.alerts = []; + dataService.postSwitches(scope.newswitch).success(function(switchData) { + + scope.newswitch = {}; + + + scope.switches.push(switchData); }).error(function(response) { scope.alerts[0] = response; }); - }, function() { - $log.info('Modal dismissed at: ' + new Date()); - }); - }; + }; - scope.selectAllSwitches = function(flag) { - if (flag) { - angular.forEach(scope.switches, function(sv) { - sv.selected = true; - }) - } else { - angular.forEach(scope.switches, function(sv) { - sv.selected = false; - }) - } - }; + scope.closeAlert = function() { + scope.alerts = []; + }; + } + }; + }); + var modifySwitchModalInstanceCtrl = function($scope, $modalInstance, targetSwitch) { + $scope.targetSwitch = angular.copy(targetSwitch); + $scope.ok = function() { + $modalInstance.close($scope.targetSwitch); + }; - scope.findServers = function() { - var swSelection = false; - angular.forEach(scope.switches, function(sw) { - if (sw.selected) { - swSelection = true; - } - }); - if (!swSelection) { - alert("Please select at least one switch"); - } else { - scope.isFindingNewServers = true; - scope.newFoundServers = []; - angular.forEach(scope.switches, function(sw) { - if (sw.selected) { - sw.result = ""; - sw.finished = false; - sw.polling = true; - } - }); - } - }; - - scope.$watch('switches', function(val) { - var totalResultReady = true; - if (scope.isFindingNewServers) { - angular.forEach(scope.switches, function(sw) { - if (sw.selected && !sw.finished) { - if (sw.result == "success") { - scope.newFoundServers = scope.newFoundServers.concat(angular.copy(sw.machines)); - sw.finished = true; - } else if (sw.result == "error") { - sw.finished = true; - } else { - totalResultReady = false; - } - } - }); - if (totalResultReady) { - scope.isFindingNewServers = false; - } - } - }, true); - - - scope.newswitch = {} - scope.newswitch.credentials = {}; - scope.alerts = []; - - scope.addSwitch = function() { - scope.alerts = []; - dataService.postSwitches(scope.newswitch).success(function(switchData) { - - scope.newswitch = {}; - - - scope.switches.push(switchData); - - }).error(function(response) { - scope.alerts[0] = response; - }); - }; - - scope.closeAlert = function() { - scope.alerts = []; - }; - } + $scope.cancel = function() { + $modalInstance.dismiss('cancel'); + }; }; -}) -var modifySwitchModalInstanceCtrl = function ($scope, $modalInstance,targetSwitch) { - $scope.targetSwitch = angular.copy(targetSwitch); - $scope.ok = function () { - $modalInstance.close($scope.targetSwitch); - }; - - $scope.cancel = function () { - $modalInstance.dismiss('cancel'); - }; -}; +}); \ No newline at end of file diff --git a/v2/src/common/gantt-chart-d3v2.js b/v2/src/common/gantt-chart-d3v2.js index 63a82f2..0414270 100644 --- a/v2/src/common/gantt-chart-d3v2.js +++ b/v2/src/common/gantt-chart-d3v2.js @@ -2,220 +2,232 @@ * @author Dimitry Kudrayvtsev * @version 2.0 */ +define(['d3'], function() { + d3.gantt = function() { + var FIT_TIME_DOMAIN_MODE = "fit"; + var FIXED_TIME_DOMAIN_MODE = "fixed"; -d3.gantt = function() { - var FIT_TIME_DOMAIN_MODE = "fit"; - var FIXED_TIME_DOMAIN_MODE = "fixed"; - - var margin = { - top : 20, - right : 40, - bottom : 20, - left : 150 - }; - var timeDomainStart = d3.time.day.offset(new Date(),-3); - var timeDomainEnd = d3.time.hour.offset(new Date(),+3); - var timeDomainMode = FIT_TIME_DOMAIN_MODE;// fixed or fit - var taskTypes = []; - var taskStatus = []; - var height = document.body.clientHeight - margin.top - margin.bottom-5; - var width = document.body.clientWidth - margin.right - margin.left-5; + var margin = { + top: 20, + right: 40, + bottom: 20, + left: 150 + }; + var timeDomainStart = d3.time.day.offset(new Date(), -3); + var timeDomainEnd = d3.time.hour.offset(new Date(), +3); + var timeDomainMode = FIT_TIME_DOMAIN_MODE; // fixed or fit + var taskTypes = []; + var taskStatus = []; + var height = document.body.clientHeight - margin.top - margin.bottom - 5; + var width = document.body.clientWidth - margin.right - margin.left - 5; - var tickFormat = "%H:%M"; + var tickFormat = "%H:%M"; - var keyFunction = function(d) { - return d.startDate + d.name + d.endDate; - }; + var keyFunction = function(d) { + return d.startDate + d.name + d.endDate; + }; - var rectTransform = function(d) { - return "translate(" + x(d.startDate) + "," + y(d.name) + ")"; - }; + var rectTransform = function(d) { + return "translate(" + x(d.startDate) + "," + y(d.name) + ")"; + }; - var x = d3.time.scale().domain([ timeDomainStart, timeDomainEnd ]).range([ 0, width ]).clamp(true); + var x = d3.time.scale().domain([timeDomainStart, timeDomainEnd]).range([0, width]).clamp(true); - var y = d3.scale.ordinal().domain(taskTypes).rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1); - - var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.time.format(tickFormat)).tickSubdivide(true) - .tickSize(8).tickPadding(8); + var y = d3.scale.ordinal().domain(taskTypes).rangeRoundBands([0, height - margin.top - margin.bottom], .1); - var yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0); + var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.time.format(tickFormat)).tickSubdivide(true) + .tickSize(8).tickPadding(8); - var initTimeDomain = function() { - if (timeDomainMode === FIT_TIME_DOMAIN_MODE) { - if (tasks === undefined || tasks.length < 1) { - timeDomainStart = d3.time.day.offset(new Date(), -3); - timeDomainEnd = d3.time.hour.offset(new Date(), +3); - return; - } - tasks.sort(function(a, b) { - return a.endDate - b.endDate; - }); - timeDomainEnd = tasks[tasks.length - 1].endDate; - tasks.sort(function(a, b) { - return a.startDate - b.startDate; - }); - timeDomainStart = tasks[0].startDate; - } - }; + var yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0); - var initAxis = function() { - x = d3.time.scale().domain([ timeDomainStart, timeDomainEnd ]).range([ 0, width ]).clamp(true); - y = d3.scale.ordinal().domain(taskTypes).rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1); - xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.time.format(tickFormat)).tickSubdivide(true) - .tickSize(8).tickPadding(8); + var initTimeDomain = function() { + if (timeDomainMode === FIT_TIME_DOMAIN_MODE) { + if (tasks === undefined || tasks.length < 1) { + timeDomainStart = d3.time.day.offset(new Date(), -3); + timeDomainEnd = d3.time.hour.offset(new Date(), +3); + return; + } + tasks.sort(function(a, b) { + return a.endDate - b.endDate; + }); + timeDomainEnd = tasks[tasks.length - 1].endDate; + tasks.sort(function(a, b) { + return a.startDate - b.startDate; + }); + timeDomainStart = tasks[0].startDate; + } + }; - yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0); - }; - - function gantt(tasks) { - - initTimeDomain(); - initAxis(); - - var svg = d3.select("ganttchart") - .append("svg") - .attr("class", "chart") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("class", "gantt-chart") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .attr("transform", "translate(" + margin.left + ", " + margin.top + ")"); - - svg.selectAll(".chart") - .data(tasks, keyFunction).enter() - .append("rect") - .attr("rx", 5) - .attr("ry", 5) - .attr("class", function(d){ - if(taskStatus[d.status] == null){ return "bar";} - return taskStatus[d.status]; - }) - .attr("y", 0) - .attr("transform", rectTransform) - .attr("height", function(d) { return y.rangeBand(); }) - .attr("width", function(d) { - return (x(d.endDate) - x(d.startDate)); - }); - - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0, " + (height - margin.top - margin.bottom) + ")") - .transition() - .call(xAxis); - - svg.append("g").attr("class", "y axis").transition().call(yAxis); - - return gantt; + var initAxis = function() { + x = d3.time.scale().domain([timeDomainStart, timeDomainEnd]).range([0, width]).clamp(true); + y = d3.scale.ordinal().domain(taskTypes).rangeRoundBands([0, height - margin.top - margin.bottom], .1); + xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.time.format(tickFormat)).tickSubdivide(true) + .tickSize(8).tickPadding(8); - }; - - gantt.redraw = function(tasks) { + yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0); + }; - initTimeDomain(); - initAxis(); - - var svg = d3.select("svg"); + function gantt(tasks) { - var ganttChartGroup = svg.select(".gantt-chart"); - var rect = ganttChartGroup.selectAll("rect").data(tasks, keyFunction); - - rect.enter() - .insert("rect",":first-child") - .attr("rx", 5) - .attr("ry", 5) - .attr("class", function(d){ - if(taskStatus[d.status] == null){ return "bar";} - return taskStatus[d.status]; - }) - .transition() - .attr("y", 0) - .attr("transform", rectTransform) - .attr("height", function(d) { return y.rangeBand(); }) - .attr("width", function(d) { - return (x(d.endDate) - x(d.startDate)); - }); + initTimeDomain(); + initAxis(); - rect.transition() - .attr("transform", rectTransform) - .attr("height", function(d) { return y.rangeBand(); }) - .attr("width", function(d) { - return (x(d.endDate) - x(d.startDate)); - }); - - rect.exit().remove(); + var svg = d3.select("ganttchart") + .append("svg") + .attr("class", "chart") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("class", "gantt-chart") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .attr("transform", "translate(" + margin.left + ", " + margin.top + ")"); - svg.select(".x").transition().call(xAxis); - svg.select(".y").transition().call(yAxis); - - return gantt; - }; + svg.selectAll(".chart") + .data(tasks, keyFunction).enter() + .append("rect") + .attr("rx", 5) + .attr("ry", 5) + .attr("class", function(d) { + if (taskStatus[d.status] == null) { + return "bar"; + } + return taskStatus[d.status]; + }) + .attr("y", 0) + .attr("transform", rectTransform) + .attr("height", function(d) { + return y.rangeBand(); + }) + .attr("width", function(d) { + return (x(d.endDate) - x(d.startDate)); + }); + + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0, " + (height - margin.top - margin.bottom) + ")") + .transition() + .call(xAxis); + + svg.append("g").attr("class", "y axis").transition().call(yAxis); + + return gantt; + + }; + + gantt.redraw = function(tasks) { + + initTimeDomain(); + initAxis(); + + var svg = d3.select("svg"); + + var ganttChartGroup = svg.select(".gantt-chart"); + var rect = ganttChartGroup.selectAll("rect").data(tasks, keyFunction); + + rect.enter() + .insert("rect", ":first-child") + .attr("rx", 5) + .attr("ry", 5) + .attr("class", function(d) { + if (taskStatus[d.status] == null) { + return "bar"; + } + return taskStatus[d.status]; + }) + .transition() + .attr("y", 0) + .attr("transform", rectTransform) + .attr("height", function(d) { + return y.rangeBand(); + }) + .attr("width", function(d) { + return (x(d.endDate) - x(d.startDate)); + }); + + rect.transition() + .attr("transform", rectTransform) + .attr("height", function(d) { + return y.rangeBand(); + }) + .attr("width", function(d) { + return (x(d.endDate) - x(d.startDate)); + }); + + rect.exit().remove(); + + svg.select(".x").transition().call(xAxis); + svg.select(".y").transition().call(yAxis); + + return gantt; + }; + + gantt.margin = function(value) { + if (!arguments.length) + return margin; + margin = value; + return gantt; + }; + + gantt.timeDomain = function(value) { + if (!arguments.length) + return [timeDomainStart, timeDomainEnd]; + timeDomainStart = +value[0], timeDomainEnd = +value[1]; + return gantt; + }; + + /** + * @param {string} + * vale The value can be "fit" - the domain fits the data or + * "fixed" - fixed domain. + */ + gantt.timeDomainMode = function(value) { + if (!arguments.length) + return timeDomainMode; + timeDomainMode = value; + return gantt; + + }; + + gantt.taskTypes = function(value) { + if (!arguments.length) + return taskTypes; + taskTypes = value; + return gantt; + }; + + gantt.taskStatus = function(value) { + if (!arguments.length) + return taskStatus; + taskStatus = value; + return gantt; + }; + + gantt.width = function(value) { + if (!arguments.length) + return width; + width = +value; + return gantt; + }; + + gantt.height = function(value) { + if (!arguments.length) + return height; + height = +value; + return gantt; + }; + + gantt.tickFormat = function(value) { + if (!arguments.length) + return tickFormat; + tickFormat = value; + return gantt; + }; - gantt.margin = function(value) { - if (!arguments.length) - return margin; - margin = value; - return gantt; - }; - gantt.timeDomain = function(value) { - if (!arguments.length) - return [ timeDomainStart, timeDomainEnd ]; - timeDomainStart = +value[0], timeDomainEnd = +value[1]; - return gantt; - }; - /** - * @param {string} - * vale The value can be "fit" - the domain fits the data or - * "fixed" - fixed domain. - */ - gantt.timeDomainMode = function(value) { - if (!arguments.length) - return timeDomainMode; - timeDomainMode = value; return gantt; - }; - - gantt.taskTypes = function(value) { - if (!arguments.length) - return taskTypes; - taskTypes = value; - return gantt; - }; - - gantt.taskStatus = function(value) { - if (!arguments.length) - return taskStatus; - taskStatus = value; - return gantt; - }; - - gantt.width = function(value) { - if (!arguments.length) - return width; - width = +value; - return gantt; - }; - - gantt.height = function(value) { - if (!arguments.length) - return height; - height = +value; - return gantt; - }; - - gantt.tickFormat = function(value) { - if (!arguments.length) - return tickFormat; - tickFormat = value; - return gantt; - }; - - - - return gantt; -}; \ No newline at end of file + return d3.gantt; +}) \ No newline at end of file diff --git a/v2/src/main.js b/v2/src/main.js new file mode 100644 index 0000000..054ad55 --- /dev/null +++ b/v2/src/main.js @@ -0,0 +1,127 @@ +require.config({ + baseUrl: "src", + paths: { + 'jquery': '../vendor/jquery/jquery-1.11.1.min', + 'twitterBootstrap': '../vendor/bootstrap/js/bootstrap.min', + 'angular': '../vendor/angular/angular.min', + 'uiRouter': '../vendor/angular-ui-router/angular-ui-router.min', + 'angularMocks': '../vendor/angular/angular-mocks', + 'angularTouch': '../vendor/angular/angular-touch', + 'uiBootstrap': '../vendor/angular-bootstrap/ui-bootstrap-tpls-0.11.0.min', + 'angularTable': '../vendor/ng-table/ng-table.min', + 'angularDragDrop': '../vendor/angular-dragdrop/draganddrop', + 'spin': '../vendor/angular-spinner/spin.min', + 'ngSpinner': '../vendor/angular-spinner/angular-spinner.min', + 'angularAnimate': '../vendor/angular/angular-animate.min', + 'd3': '../vendor/d3/d3.min', + 'nvD3': '../vendor/nvd3/nv.d3.min', + 'ganttChart':'common/gantt-chart-d3v2', + 'rickshaw': '../vendor/rickshaw/rickshaw.min', + 'angularRickshaw': '../vendor/angular-rickshaw/rickshaw.min', + 'moment': '../vendor/angular-daterangepicker/moment.min', + 'daterangepicker': '../vendor/angular-daterangepicker/daterangepicker', + 'ngBsDaterangepicker': '../vendor/angular-daterangepicker/ng-bs-daterangepicker', + 'angularUiTree': '../vendor/angular-ui-tree/angular-ui-tree.min', + 'nvd3Directive': '../vendor/angular-nvd3/angularjs-nvd3-directives.min', + + + 'login': 'app/login/login', + 'services': 'app/services', + 'appDev': 'app/appDev', + 'clusterList': 'app/cluster/clusterList', + 'cluster': 'app/cluster/cluster', + 'wizard': 'app/wizard/wizard', + 'topnav': 'app/topnav/topnav', + 'server': 'app/server/server', + 'userProfile': 'app/user/userprofile', + 'userSetting': 'app/user/usersetting', + 'monitoring': 'app/monitoring/monitoring', + 'charts': 'common/charts', + 'findservers': 'common/findservers/findservers' + }, + shim: { + "jquery": { + exports: "jquery" + }, + "twitterBootstrap": { + deps: ["jquery"], + exports: "twitterBootstrap" + }, + "angular": { + deps: ['jquery'], + exports: "angular" + }, + "angularTable": { + deps: ["angular"], + exports: "angularTable" + }, + "angularMocks": { + deps: ["angular"], + exports: "angularMocks" + }, + "angularTouch": { + deps: ["angular"], + exports: "angularTouch" + }, + "uiBootstrap": { + deps: ["angular"], + exports: "uiBootstrap" + }, + "angularDragDrop": { + deps: ["angular"], + exports: "angularDragDrop" + }, + "uiRouter": { + deps: ["angular"], + exports: "uiRouter" + + }, + "spin": { + //deps:["angular"], + exports: "spin" + }, + "ngSpinner": { + deps: ["angular", "spin"], // may depends on angularspin + exports: "ngSpinner" + }, + "angularAnimate": { + deps: ["angular"], + exports: "angularAnimate" + }, + "d3": { + exports: "d3" + }, + "nvD3": { + deps: ["d3"], + exports: "nvD3" + }, + "nvd3Directive": { + deps: ["nvD3"], + exports: "nvd3Directive" + }, + "rickshaw": { + exports: "rickshaw" + }, + "angularUiTree": { + deps: ["angular"], + exports: "angularUiTree" + }, + "angularRickshaw": { + deps: ["angular", "rickshaw", "d3"], + exports: "angularRickshaw" + }, + "moment": { + exports: "moment" + }, + "daterangepicker": { + deps: ["twitterBootstrap", "angular", "moment"], + exports: "daterangepicker" + }, + "ngBsDaterangepicker": { + deps: ["daterangepicker"], + exports: "ngBsDaterangepicker" + } + }, + + deps: ['./bootstrap'] +}); \ No newline at end of file diff --git a/v2/vendor/require.js b/v2/vendor/require.js new file mode 100755 index 0000000..be103a7 --- /dev/null +++ b/v2/vendor/require.js @@ -0,0 +1,36 @@ +/* + RequireJS 2.1.15 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. + Available via the MIT or new BSD license. + see: http://github.com/jrburke/requirejs for details +*/ +var requirejs,require,define; +(function(ba){function G(b){return"[object Function]"===K.call(b)}function H(b){return"[object Array]"===K.call(b)}function v(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(G(l)){if(this.events.error&&this.map.isDefine||g.onError!==ca)try{f=i.execCb(c,l,b,f)}catch(d){a=d}else f=i.execCb(c,l,b,f);this.map.isDefine&&void 0===f&&((b=this.module)?f=b.exports:this.usingExports&& +(f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=l;this.exports=f;if(this.map.isDefine&&!this.ignore&&(r[c]=f,g.onResourceLoad))g.onResourceLoad(i,this.map,this.depMaps);y(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a= +this.map,b=a.id,d=p(a.prefix);this.depMaps.push(d);q(d,"defined",u(this,function(f){var l,d;d=m(aa,this.map.id);var e=this.map.name,P=this.map.parentMap?this.map.parentMap.name:null,n=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(e=f.normalize(e,function(a){return c(a,P,!0)})||""),f=p(a.prefix+"!"+e,this.map.parentMap),q(f,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),d=m(h,f.id)){this.depMaps.push(f); +if(this.events.error)d.on("error",u(this,function(a){this.emit("error",a)}));d.enable()}}else d?(this.map.url=i.nameToUrl(d),this.load()):(l=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),l.error=u(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(h,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),l.fromText=u(this,function(f,c){var d=a.name,e=p(d),P=M;c&&(f=c);P&&(M=!1);s(e);t(j.config,b)&&(j.config[d]=j.config[b]);try{g.exec(f)}catch(h){return w(C("fromtexteval", +"fromText eval for "+b+" failed: "+h,h,[b]))}P&&(M=!0);this.depMaps.push(e);i.completeLoad(d);n([d],l)}),f.load(a.name,n,l,j))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){V[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,u(this,function(a,b){var c,f;if("string"===typeof a){a=p(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=m(L,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;q(a,"defined",u(this,function(a){this.defineDep(b, +a);this.check()}));this.errback&&q(a,"error",u(this,this.errback))}c=a.id;f=h[c];!t(L,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,u(this,function(a){var b=m(h,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:j,contextName:b,registry:h,defined:r,urlFetched:S,defQueue:A,Module:Z,makeModuleMap:p, +nextTick:g.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=j.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(j[b]||(j[b]={}),U(j[b],a,!0,!0)):j[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(aa[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);b[c]=a}),j.shim=b);a.packages&&v(a.packages,function(a){var b, +a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(j.paths[b]=a.location);j.pkgs[b]=a.name+"/"+(a.main||"main").replace(ia,"").replace(Q,"")});B(h,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=p(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ba,arguments));return b||a.exports&&da(a.exports)}},makeRequire:function(a,e){function j(c,d,m){var n,q;e.enableBuildCallback&&(d&&G(d))&&(d.__requireJsBuild= +!0);if("string"===typeof c){if(G(d))return w(C("requireargs","Invalid require call"),m);if(a&&t(L,c))return L[c](h[a.id]);if(g.get)return g.get(i,c,a,j);n=p(c,a,!1,!0);n=n.id;return!t(r,n)?w(C("notloaded",'Module name "'+n+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[n]}J();i.nextTick(function(){J();q=s(p(null,a));q.skipMap=e.skipMap;q.init(c,d,m,{enabled:!0});D()});return j}e=e||{};U(j,{isBrowser:z,toUrl:function(b){var d,e=b.lastIndexOf("."),k=b.split("/")[0];if(-1!== +e&&(!("."===k||".."===k)||1e.attachEvent.toString().indexOf("[native code"))&&!Y?(M=!0,e.attachEvent("onreadystatechange",b.onScriptLoad)): +(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)),e.src=d,J=e,D?y.insertBefore(e,D):y.appendChild(e),J=null,e;if(ea)try{importScripts(d),b.completeLoad(c)}catch(m){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,m,[c]))}};z&&!q.skipDataMain&&T(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(I=b.getAttribute("data-main"))return s=I,q.baseUrl||(E=s.split("/"),s=E.pop(),O=E.length?E.join("/")+"/":"./",q.baseUrl= +O),s=s.replace(Q,""),g.jsExtRegExp.test(s)&&(s=I),q.deps=q.deps?q.deps.concat(s):[s],!0});define=function(b,c,d){var e,g;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(ka,"").replace(la,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(M){if(!(e=J))N&&"interactive"===N.readyState||T(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return N=b}),e=N;e&&(b|| +(b=e.getAttribute("data-requiremodule")),g=F[e.getAttribute("data-requirecontext")])}(g?g.defQueue:R).push([b,c,d])};define.amd={jQuery:!0};g.exec=function(b){return eval(b)};g(q)}})(this);