graphiteImportCtrl.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'app/core/utils/kbn'
  5. ],
  6. function (angular, _, kbn) {
  7. 'use strict';
  8. var module = angular.module('grafana.controllers');
  9. module.controller('GraphiteImportCtrl', function($scope, datasourceSrv, dashboardSrv, $location) {
  10. $scope.options = {};
  11. $scope.init = function() {
  12. $scope.datasources = [];
  13. _.each(datasourceSrv.getAll(), function(ds) {
  14. if (ds.type === 'graphite') {
  15. $scope.options.sourceName = ds.name;
  16. $scope.datasources.push(ds.name);
  17. }
  18. });
  19. };
  20. $scope.listAll = function() {
  21. datasourceSrv.get($scope.options.sourceName).then(function(datasource) {
  22. $scope.datasource = datasource;
  23. $scope.datasource.listDashboards('').then(function(results) {
  24. $scope.dashboards = results;
  25. }, function(err) {
  26. var message = err.message || err.statusText || 'Error';
  27. $scope.appEvent('alert-error', ['Failed to load dashboard list from graphite', message]);
  28. });
  29. });
  30. };
  31. $scope.import = function(dashName) {
  32. $scope.datasource.loadDashboard(dashName).then(function(results) {
  33. if (!results.data || !results.data.state) {
  34. throw { message: 'no dashboard state received from graphite' };
  35. }
  36. graphiteToGrafanaTranslator(results.data.state, $scope.datasource.name);
  37. }, function(err) {
  38. var message = err.message || err.statusText || 'Error';
  39. $scope.appEvent('alert-error', ['Failed to load dashboard from graphite', message]);
  40. });
  41. };
  42. function graphiteToGrafanaTranslator(state, datasource) {
  43. var graphsPerRow = 2;
  44. var rowHeight = 300;
  45. var rowTemplate;
  46. var currentRow;
  47. var panel;
  48. rowTemplate = {
  49. title: '',
  50. panels: [],
  51. height: rowHeight
  52. };
  53. currentRow = angular.copy(rowTemplate);
  54. var newDashboard = dashboardSrv.create({});
  55. newDashboard.rows = [];
  56. newDashboard.title = state.name;
  57. newDashboard.rows.push(currentRow);
  58. _.each(state.graphs, function(graph, index) {
  59. if (currentRow.panels.length === graphsPerRow) {
  60. currentRow = angular.copy(rowTemplate);
  61. newDashboard.rows.push(currentRow);
  62. }
  63. panel = {
  64. type: 'graph',
  65. span: 12 / graphsPerRow,
  66. title: graph[1].title,
  67. targets: [],
  68. datasource: datasource,
  69. id: index + 1
  70. };
  71. _.each(graph[1].target, function(target) {
  72. panel.targets.push({ target: target });
  73. });
  74. currentRow.panels.push(panel);
  75. });
  76. window.grafanaImportDashboard = newDashboard;
  77. $location.path('/dashboard-import/' + kbn.slugifyForUrl(newDashboard.title));
  78. }
  79. });
  80. });