module.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /*
  2. ## Histogram
  3. ### Parameters
  4. * auto_int :: Auto calculate data point interval?
  5. * resolution :: If auto_int is enables, shoot for this many data points, rounding to
  6. sane intervals
  7. * interval :: Datapoint interval in elasticsearch date math format (eg 1d, 1w, 1y, 5y)
  8. * fill :: Only applies to line charts. Level of area shading from 0-10
  9. * linewidth :: Only applies to line charts. How thick the line should be in pixels
  10. While the editor only exposes 0-10, this can be any numeric value.
  11. Set to 0 and you'll get something like a scatter plot
  12. * timezone :: This isn't totally functional yet. Currently only supports browser and utc.
  13. browser will adjust the x-axis labels to match the timezone of the user's
  14. browser
  15. * spyable :: Dislay the 'eye' icon that show the last elasticsearch query
  16. * zoomlinks :: Show the zoom links?
  17. * bars :: Show bars in the chart
  18. * stack :: Stack multiple queries. This generally a crappy way to represent things.
  19. You probably should just use a line chart without stacking
  20. * points :: Should circles at the data points on the chart
  21. * lines :: Line chart? Sweet.
  22. * legend :: Show the legend?
  23. * x-axis :: Show x-axis labels and grid lines
  24. * y-axis :: Show y-axis labels and grid lines
  25. * interactive :: Allow drag to select time range
  26. */
  27. define([
  28. 'angular',
  29. 'app',
  30. 'jquery',
  31. 'underscore',
  32. 'kbn',
  33. 'moment',
  34. './timeSeries',
  35. 'jquery.flot',
  36. 'jquery.flot.pie',
  37. 'jquery.flot.selection',
  38. 'jquery.flot.time',
  39. 'jquery.flot.stack',
  40. 'jquery.flot.stackpercent'
  41. ],
  42. function (angular, app, $, _, kbn, moment, timeSeries) {
  43. 'use strict';
  44. var module = angular.module('kibana.panels.histogram', []);
  45. app.useModule(module);
  46. module.controller('histogram', function($scope, querySrv, dashboard, filterSrv) {
  47. $scope.panelMeta = {
  48. modals : [
  49. {
  50. description: "Inspect",
  51. icon: "icon-info-sign",
  52. partial: "app/partials/inspector.html",
  53. show: $scope.panel.spyable
  54. }
  55. ],
  56. editorTabs : [
  57. {
  58. title:'Queries',
  59. src:'app/partials/querySelect.html'
  60. }
  61. ],
  62. status : "Stable",
  63. description : "A bucketed time series chart of the current query or queries. Uses the "+
  64. "Elasticsearch date_histogram facet. If using time stamped indices this panel will query"+
  65. " them sequentially to attempt to apply the lighest possible load to your Elasticsearch cluster"
  66. };
  67. // Set and populate defaults
  68. var _d = {
  69. mode : 'count',
  70. time_field : '@timestamp',
  71. queries : {
  72. mode : 'all',
  73. ids : []
  74. },
  75. value_field : null,
  76. auto_int : true,
  77. resolution : 100,
  78. interval : '5m',
  79. intervals : ['auto','1s','1m','5m','10m','30m','1h','3h','12h','1d','1w','1M','1y'],
  80. fill : 0,
  81. linewidth : 3,
  82. timezone : 'browser', // browser, utc or a standard timezone
  83. spyable : true,
  84. zoomlinks : true,
  85. bars : true,
  86. stack : true,
  87. points : false,
  88. lines : false,
  89. legend : true,
  90. 'x-axis' : true,
  91. 'y-axis' : true,
  92. percentage : false,
  93. interactive : true,
  94. options : true,
  95. tooltip : {
  96. value_type: 'cumulative',
  97. query_as_alias: false
  98. }
  99. };
  100. _.defaults($scope.panel,_d);
  101. $scope.init = function() {
  102. // Hide view options by default
  103. $scope.options = false;
  104. $scope.$on('refresh',function(){
  105. $scope.get_data();
  106. });
  107. $scope.get_data();
  108. };
  109. $scope.set_interval = function(interval) {
  110. if(interval !== 'auto') {
  111. $scope.panel.auto_int = false;
  112. $scope.panel.interval = interval;
  113. } else {
  114. $scope.panel.auto_int = true;
  115. }
  116. };
  117. $scope.interval_label = function(interval) {
  118. return $scope.panel.auto_int && interval === $scope.panel.interval ? interval+" (auto)" : interval;
  119. };
  120. /**
  121. * The time range effecting the panel
  122. * @return {[type]} [description]
  123. */
  124. $scope.get_time_range = function () {
  125. var range = $scope.range = filterSrv.timeRange('last');
  126. return range;
  127. };
  128. $scope.get_interval = function () {
  129. var interval = $scope.panel.interval,
  130. range;
  131. if ($scope.panel.auto_int) {
  132. range = $scope.get_time_range();
  133. if (range) {
  134. interval = kbn.secondsToHms(
  135. kbn.calculate_interval(range.from, range.to, $scope.panel.resolution, 0) / 1000
  136. );
  137. }
  138. }
  139. $scope.panel.interval = interval || '10m';
  140. return $scope.panel.interval;
  141. };
  142. /**
  143. * Fetch the data for a chunk of a queries results. Multiple segments occur when several indicies
  144. * need to be consulted (like timestamped logstash indicies)
  145. *
  146. * The results of this function are stored on the scope's data property. This property will be an
  147. * array of objects with the properties info, time_series, and hits. These objects are used in the
  148. * render_panel function to create the historgram.
  149. *
  150. * @param {number} segment The segment count, (0 based)
  151. * @param {number} query_id The id of the query, generated on the first run and passed back when
  152. * this call is made recursively for more segments
  153. */
  154. $scope.get_data = function(segment, query_id) {
  155. if (_.isUndefined(segment)) {
  156. segment = 0;
  157. }
  158. delete $scope.panel.error;
  159. // Make sure we have everything for the request to complete
  160. if(dashboard.indices.length === 0) {
  161. return;
  162. }
  163. var _range = $scope.get_time_range();
  164. var _interval = $scope.get_interval(_range);
  165. if ($scope.panel.auto_int) {
  166. $scope.panel.interval = kbn.secondsToHms(
  167. kbn.calculate_interval(_range.from,_range.to,$scope.panel.resolution,0)/1000);
  168. }
  169. $scope.panelMeta.loading = true;
  170. var request = $scope.ejs.Request().indices(dashboard.indices[segment]);
  171. $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries);
  172. var queries = querySrv.getQueryObjs($scope.panel.queries.ids);
  173. // Build the query
  174. _.each(queries, function(q) {
  175. var query = $scope.ejs.FilteredQuery(
  176. querySrv.toEjsObj(q),
  177. filterSrv.getBoolFilter(filterSrv.ids)
  178. );
  179. var facet = $scope.ejs.DateHistogramFacet(q.id);
  180. if($scope.panel.mode === 'count') {
  181. facet = facet.field($scope.panel.time_field);
  182. } else {
  183. if(_.isNull($scope.panel.value_field)) {
  184. $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
  185. return;
  186. }
  187. facet = facet.keyField($scope.panel.time_field).valueField($scope.panel.value_field);
  188. }
  189. facet = facet.interval(_interval).facetFilter($scope.ejs.QueryFilter(query));
  190. request = request.facet(facet).size(0);
  191. });
  192. // Populate the inspector panel
  193. $scope.populate_modal(request);
  194. // Then run it
  195. var results = request.doSearch();
  196. // Populate scope when we have results
  197. results.then(function(results) {
  198. $scope.panelMeta.loading = false;
  199. if(segment === 0) {
  200. $scope.hits = 0;
  201. $scope.data = [];
  202. query_id = $scope.query_id = new Date().getTime();
  203. }
  204. // Check for error and abort if found
  205. if(!(_.isUndefined(results.error))) {
  206. $scope.panel.error = $scope.parse_error(results.error);
  207. return;
  208. }
  209. // Make sure we're still on the same query/queries
  210. if($scope.query_id === query_id) {
  211. var i = 0,
  212. time_series,
  213. hits;
  214. _.each(queries, function(q) {
  215. var query_results = results.facets[q.id];
  216. // we need to initialize the data variable on the first run,
  217. // and when we are working on the first segment of the data.
  218. if(_.isUndefined($scope.data[i]) || segment === 0) {
  219. time_series = new timeSeries.ZeroFilled({
  220. interval: _interval,
  221. start_date: _range && _range.from,
  222. end_date: _range && _range.to,
  223. fill_style: 'minimal'
  224. });
  225. hits = 0;
  226. } else {
  227. time_series = $scope.data[i].time_series;
  228. hits = $scope.data[i].hits;
  229. }
  230. // push each entry into the time series, while incrementing counters
  231. _.each(query_results.entries, function(entry) {
  232. time_series.addValue(entry.time, entry[$scope.panel.mode]);
  233. hits += entry.count; // The series level hits counter
  234. $scope.hits += entry.count; // Entire dataset level hits counter
  235. });
  236. $scope.data[i] = {
  237. info: q,
  238. time_series: time_series,
  239. hits: hits
  240. };
  241. i++;
  242. });
  243. // Tell the histogram directive to render.
  244. $scope.$emit('render');
  245. // If we still have segments left, get them
  246. if(segment < dashboard.indices.length-1) {
  247. $scope.get_data(segment+1,query_id);
  248. }
  249. }
  250. });
  251. };
  252. // function $scope.zoom
  253. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  254. $scope.zoom = function(factor) {
  255. var _range = filterSrv.timeRange('last');
  256. var _timespan = (_range.to.valueOf() - _range.from.valueOf());
  257. var _center = _range.to.valueOf() - _timespan/2;
  258. var _to = (_center + (_timespan*factor)/2);
  259. var _from = (_center - (_timespan*factor)/2);
  260. // If we're not already looking into the future, don't.
  261. if(_to > Date.now() && _range.to < Date.now()) {
  262. var _offset = _to - Date.now();
  263. _from = _from - _offset;
  264. _to = Date.now();
  265. }
  266. if(factor > 1) {
  267. filterSrv.removeByType('time');
  268. }
  269. filterSrv.set({
  270. type:'time',
  271. from:moment.utc(_from).toDate(),
  272. to:moment.utc(_to).toDate(),
  273. field:$scope.panel.time_field
  274. });
  275. };
  276. // I really don't like this function, too much dom manip. Break out into directive?
  277. $scope.populate_modal = function(request) {
  278. $scope.inspector = angular.toJson(JSON.parse(request.toString()),true);
  279. };
  280. $scope.set_refresh = function (state) {
  281. $scope.refresh = state;
  282. };
  283. $scope.close_edit = function() {
  284. if($scope.refresh) {
  285. $scope.get_data();
  286. }
  287. $scope.refresh = false;
  288. $scope.$emit('render');
  289. };
  290. $scope.render = function() {
  291. $scope.$emit('render');
  292. };
  293. });
  294. module.directive('histogramChart', function(dashboard, filterSrv) {
  295. return {
  296. restrict: 'A',
  297. template: '<div></div>',
  298. link: function(scope, elem) {
  299. // Receive render events
  300. scope.$on('render',function(){
  301. render_panel();
  302. });
  303. // Re-render if the window is resized
  304. angular.element(window).bind('resize', function(){
  305. render_panel();
  306. });
  307. // Function for rendering panel
  308. function render_panel() {
  309. // IE doesn't work without this
  310. elem.css({height:scope.panel.height || scope.row.height});
  311. // Populate from the query service
  312. try {
  313. _.each(scope.data, function(series) {
  314. series.label = series.info.alias;
  315. series.color = series.info.color;
  316. });
  317. } catch(e) {return;}
  318. // Set barwidth based on specified interval
  319. var barwidth = kbn.interval_to_ms(scope.panel.interval);
  320. var stack = scope.panel.stack ? true : null;
  321. // Populate element
  322. try {
  323. var options = {
  324. legend: { show: false },
  325. series: {
  326. stackpercent: scope.panel.stack ? scope.panel.percentage : false,
  327. stack: scope.panel.percentage ? null : stack,
  328. lines: {
  329. show: scope.panel.lines,
  330. // Silly, but fixes bug in stacked percentages
  331. fill: scope.panel.fill === 0 ? 0.001 : scope.panel.fill/10,
  332. lineWidth: scope.panel.linewidth,
  333. steps: false
  334. },
  335. bars: {
  336. show: scope.panel.bars,
  337. fill: 1,
  338. barWidth: barwidth/1.8,
  339. zero: false,
  340. lineWidth: 0
  341. },
  342. points: {
  343. show: scope.panel.points,
  344. fill: 1,
  345. fillColor: false,
  346. radius: 5
  347. },
  348. shadowSize: 1
  349. },
  350. yaxis: {
  351. show: scope.panel['y-axis'],
  352. min: 0,
  353. max: scope.panel.percentage && scope.panel.stack ? 100 : null,
  354. },
  355. xaxis: {
  356. timezone: scope.panel.timezone,
  357. show: scope.panel['x-axis'],
  358. mode: "time",
  359. min: _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(),
  360. max: _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(),
  361. timeformat: time_format(scope.panel.interval),
  362. label: "Datetime",
  363. ticks: elem.width()/100
  364. },
  365. grid: {
  366. backgroundColor: null,
  367. borderWidth: 0,
  368. hoverable: true,
  369. color: '#c8c8c8'
  370. }
  371. };
  372. if(scope.panel.interactive) {
  373. options.selection = { mode: "x", color: '#666' };
  374. }
  375. // when rendering stacked bars, we need to ensure each point that has data is zero-filled
  376. // so that the stacking happens in the proper order
  377. var required_times = [];
  378. if (scope.data.length > 1) {
  379. required_times = Array.prototype.concat.apply([], _.map(scope.data, function (query) {
  380. return query.time_series.getOrderedTimes();
  381. }));
  382. required_times = _.uniq(required_times.sort(function (a, b) {
  383. // decending numeric sort
  384. return a-b;
  385. }), true);
  386. }
  387. for (var i = 0; i < scope.data.length; i++) {
  388. scope.data[i].data = scope.data[i].time_series.getFlotPairs(required_times);
  389. }
  390. scope.plot = $.plot(elem, scope.data, options);
  391. } catch(e) {
  392. // Nothing to do here
  393. }
  394. }
  395. function time_format(interval) {
  396. var _int = kbn.interval_to_seconds(interval);
  397. if(_int >= 2628000) {
  398. return "%m/%y";
  399. }
  400. if(_int >= 86400) {
  401. return "%m/%d/%y";
  402. }
  403. if(_int >= 60) {
  404. return "%H:%M<br>%m/%d";
  405. }
  406. return "%H:%M:%S";
  407. }
  408. var $tooltip = $('<div>');
  409. elem.bind("plothover", function (event, pos, item) {
  410. var group, value;
  411. if (item) {
  412. if (item.series.info.alias || scope.panel.tooltip.query_as_alias) {
  413. group = '<small style="font-size:0.9em;">' +
  414. '<i class="icon-circle" style="color:'+item.series.color+';"></i>' + ' ' +
  415. (item.series.info.alias || item.series.info.query)+
  416. '</small><br>';
  417. } else {
  418. group = kbn.query_color_dot(item.series.color, 15) + ' ';
  419. }
  420. if (scope.panel.stack && scope.panel.tooltip.value_type === 'individual') {
  421. value = item.datapoint[1] - item.datapoint[2];
  422. } else {
  423. value = item.datapoint[1];
  424. }
  425. $tooltip
  426. .html(
  427. group + value + " @ " + moment(item.datapoint[0]).format('MM/DD HH:mm:ss')
  428. )
  429. .place_tt(pos.pageX, pos.pageY);
  430. } else {
  431. $tooltip.detach();
  432. }
  433. });
  434. elem.bind("plotselected", function (event, ranges) {
  435. filterSrv.set({
  436. type : 'time',
  437. from : moment.utc(ranges.xaxis.from).toDate(),
  438. to : moment.utc(ranges.xaxis.to).toDate(),
  439. field : scope.panel.time_field
  440. });
  441. });
  442. }
  443. };
  444. });
  445. });