graphiteImport.js 2.6 KB

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