graphiteImportCtrl.js 2.6 KB

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