graphiteImportCtrl.js 2.7 KB

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