scripted_gen_and_save.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* global _ */
  2. /*
  3. * Complex scripted dashboard
  4. * This script generates a dashboard object that Grafana can load. It also takes a number of user
  5. * supplied URL parameters (in the ARGS variable)
  6. *
  7. * Return a dashboard object, or a function
  8. *
  9. * For async scripts, return a function, this function must take a single callback function as argument,
  10. * call this callback function with the dashboard object (look at scripted_async.js for an example)
  11. */
  12. 'use strict';
  13. // accessible variables in this scope
  14. var window, document, ARGS, $, jQuery, moment, kbn, services, _;
  15. // default datasource
  16. var datasource = services.datasourceSrv.default;
  17. // get datasource used for saving dashboards
  18. var dashboardDB = services.datasourceSrv.getGrafanaDB();
  19. var targets = [];
  20. function getTargets(path) {
  21. return datasource.metricFindQuery(path + '.*').then(function(result) {
  22. if (!result) {
  23. return null;
  24. }
  25. if (targets.length === 10) {
  26. return null;
  27. }
  28. var promises = _.map(result, function(metric) {
  29. if (metric.expandable) {
  30. return getTargets(path + "." + metric.text);
  31. }
  32. else {
  33. targets.push(path + '.' + metric.text);
  34. }
  35. return null;
  36. });
  37. return services.$q.all(promises);
  38. });
  39. }
  40. function createDashboard(target, index) {
  41. // Intialize a skeleton with nothing but a rows array and service object
  42. var dashboard = { rows : [] };
  43. dashboard.title = 'Scripted dash ' + index;
  44. dashboard.time = {
  45. from: "now-6h",
  46. to: "now"
  47. };
  48. dashboard.rows.push({
  49. title: 'Chart',
  50. height: '300px',
  51. panels: [
  52. {
  53. title: 'Events',
  54. type: 'graph',
  55. span: 12,
  56. targets: [ {target: target} ]
  57. }
  58. ]
  59. });
  60. return dashboard;
  61. }
  62. function saveDashboard(dashboard) {
  63. var model = services.dashboardSrv.create(dashboard);
  64. dashboardDB.saveDashboard(model);
  65. }
  66. return function(callback) {
  67. getTargets('apps').then(function() {
  68. console.log('targets: ', targets);
  69. _.each(targets, function(target, index) {
  70. var dashboard = createDashboard(target, index);
  71. saveDashboard(dashboard);
  72. if (index === targets.length - 1) {
  73. callback(dashboard);
  74. }
  75. });
  76. });
  77. };