graphiteImport.js 2.7 KB

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