module.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /*jshint globalstrict:true */
  2. /*global angular:true */
  3. /*
  4. ## Histogram
  5. ### Parameters
  6. * auto_int :: Auto calculate data point interval?
  7. * resolution :: If auto_int is enables, shoot for this many data points, rounding to
  8. sane intervals
  9. * interval :: Datapoint interval in elasticsearch date math format (eg 1d, 1w, 1y, 5y)
  10. * fill :: Only applies to line charts. Level of area shading from 0-10
  11. * linewidth :: Only applies to line charts. How thick the line should be in pixels
  12. While the editor only exposes 0-10, this can be any numeric value.
  13. Set to 0 and you'll get something like a scatter plot
  14. * timezone :: This isn't totally functional yet. Currently only supports browser and utc.
  15. browser will adjust the x-axis labels to match the timezone of the user's
  16. browser
  17. * spyable :: Dislay the 'eye' icon that show the last elasticsearch query
  18. * zoomlinks :: Show the zoom links?
  19. * bars :: Show bars in the chart
  20. * stack :: Stack multiple queries. This generally a crappy way to represent things.
  21. You probably should just use a line chart without stacking
  22. * points :: Should circles at the data points on the chart
  23. * lines :: Line chart? Sweet.
  24. * legend :: Show the legend?
  25. * x-axis :: Show x-axis labels and grid lines
  26. * y-axis :: Show y-axis labels and grid lines
  27. * interactive :: Allow drag to select time range
  28. */
  29. 'use strict';
  30. angular.module('kibana.histogram', [])
  31. .controller('histogram', function($scope, querySrv, dashboard, filterSrv, timeSeries) {
  32. $scope.panelMeta = {
  33. editorTabs : [
  34. {title:'Queries', src:'partials/querySelect.html'}
  35. ],
  36. status : "Stable",
  37. description : "A bucketed time series chart of the current query or queries. Uses the "+
  38. "Elasticsearch date_histogram facet. If using time stamped indices this panel will query"+
  39. " them sequentially to attempt to apply the lighest possible load to your Elasticsearch cluster"
  40. };
  41. // Set and populate defaults
  42. var _d = {
  43. mode : 'count',
  44. time_field : '@timestamp',
  45. queries : {
  46. mode : 'all',
  47. ids : []
  48. },
  49. value_field : null,
  50. auto_int : true,
  51. resolution : 100,
  52. interval : '5m',
  53. fill : 0,
  54. linewidth : 3,
  55. timezone : 'browser', // browser, utc or a standard timezone
  56. spyable : true,
  57. zoomlinks : true,
  58. bars : true,
  59. stack : true,
  60. points : false,
  61. lines : false,
  62. legend : true,
  63. 'x-axis' : true,
  64. 'y-axis' : true,
  65. percentage : false,
  66. interactive : true,
  67. tooltip : {
  68. value_type: 'cumulative',
  69. query_as_alias: false
  70. }
  71. };
  72. _.defaults($scope.panel,_d);
  73. $scope.init = function() {
  74. $scope.$on('refresh',function(){
  75. $scope.get_data();
  76. });
  77. $scope.get_data();
  78. };
  79. /**
  80. * The time range effecting the panel
  81. * @return {[type]} [description]
  82. */
  83. $scope.get_time_range = function () {
  84. var range = $scope.range = filterSrv.timeRange('min');
  85. return range;
  86. };
  87. $scope.get_interval = function () {
  88. var interval = $scope.panel.interval,
  89. range;
  90. if ($scope.panel.auto_int) {
  91. range = $scope.get_time_range();
  92. if (range) {
  93. interval = kbn.secondsToHms(
  94. kbn.calculate_interval(range.from, range.to, $scope.panel.resolution, 0) / 1000
  95. );
  96. }
  97. }
  98. $scope.panel.interval = interval || '10m';
  99. return $scope.panel.interval;
  100. };
  101. /**
  102. * Fetch the data for a chunk of a queries results. Multiple segments occur when several indicies
  103. * need to be consulted (like timestamped logstash indicies)
  104. *
  105. * The results of this function are stored on the scope's data property. This property will be an
  106. * array of objects with the properties info, time_series, and hits. These objects are used in the
  107. * render_panel function to create the historgram.
  108. *
  109. * @param {number} segment The segment count, (0 based)
  110. * @param {number} query_id The id of the query, generated on the first run and passed back when
  111. * this call is made recursively for more segments
  112. */
  113. $scope.get_data = function(segment, query_id) {
  114. if (_.isUndefined(segment)) {
  115. segment = 0;
  116. }
  117. delete $scope.panel.error;
  118. // Make sure we have everything for the request to complete
  119. if(dashboard.indices.length === 0) {
  120. return;
  121. }
  122. var _range = $scope.get_time_range();
  123. var _interval = $scope.get_interval(_range);
  124. if ($scope.panel.auto_int) {
  125. $scope.panel.interval = kbn.secondsToHms(
  126. kbn.calculate_interval(_range.from,_range.to,$scope.panel.resolution,0)/1000);
  127. }
  128. $scope.panelMeta.loading = true;
  129. var request = $scope.ejs.Request().indices(dashboard.indices[segment]);
  130. $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries);
  131. // Build the query
  132. _.each($scope.panel.queries.ids, function(id) {
  133. var query = $scope.ejs.FilteredQuery(
  134. querySrv.getEjsObj(id),
  135. filterSrv.getBoolFilter(filterSrv.ids)
  136. );
  137. var facet = $scope.ejs.DateHistogramFacet(id);
  138. if($scope.panel.mode === 'count') {
  139. facet = facet.field($scope.panel.time_field);
  140. } else {
  141. if(_.isNull($scope.panel.value_field)) {
  142. $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
  143. return;
  144. }
  145. facet = facet.keyField($scope.panel.time_field).valueField($scope.panel.value_field);
  146. }
  147. facet = facet.interval(_interval).facetFilter($scope.ejs.QueryFilter(query));
  148. request = request.facet(facet).size(0);
  149. });
  150. // Populate the inspector panel
  151. $scope.populate_modal(request);
  152. // Then run it
  153. var results = request.doSearch();
  154. // Populate scope when we have results
  155. results.then(function(results) {
  156. $scope.panelMeta.loading = false;
  157. if(segment === 0) {
  158. $scope.hits = 0;
  159. $scope.data = [];
  160. query_id = $scope.query_id = new Date().getTime();
  161. }
  162. // Check for error and abort if found
  163. if(!(_.isUndefined(results.error))) {
  164. $scope.panel.error = $scope.parse_error(results.error);
  165. return;
  166. }
  167. // Convert facet ids to numbers
  168. var facetIds = _.map(_.keys(results.facets),function(k){return parseInt(k, 10);});
  169. // Make sure we're still on the same query/queries
  170. if($scope.query_id === query_id && _.difference(facetIds, $scope.panel.queries.ids).length === 0) {
  171. var i = 0,
  172. time_series,
  173. hits;
  174. _.each($scope.panel.queries.ids, function(id) {
  175. var query_results = results.facets[id];
  176. // we need to initialize the data variable on the first run,
  177. // and when we are working on the first segment of the data.
  178. if(_.isUndefined($scope.data[i]) || segment === 0) {
  179. time_series = new timeSeries.ZeroFilled({
  180. interval: _interval,
  181. start_date: _range && _range.from,
  182. end_date: _range && _range.to,
  183. fill_style: 'minimal'
  184. });
  185. hits = 0;
  186. } else {
  187. time_series = $scope.data[i].time_series;
  188. hits = $scope.data[i].hits;
  189. }
  190. // push each entry into the time series, while incrementing counters
  191. _.each(query_results.entries, function(entry) {
  192. time_series.addValue(entry.time, entry[$scope.panel.mode]);
  193. hits += entry.count; // The series level hits counter
  194. $scope.hits += entry.count; // Entire dataset level hits counter
  195. });
  196. $scope.data[i] = {
  197. info: querySrv.list[id],
  198. time_series: time_series,
  199. hits: hits
  200. };
  201. i++;
  202. });
  203. // Tell the histogram directive to render.
  204. $scope.$emit('render');
  205. // If we still have segments left, get them
  206. if(segment < dashboard.indices.length-1) {
  207. $scope.get_data(segment+1,query_id);
  208. }
  209. }
  210. });
  211. };
  212. // function $scope.zoom
  213. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  214. $scope.zoom = function(factor) {
  215. var _now = Date.now();
  216. var _range = filterSrv.timeRange('min');
  217. var _timespan = (_range.to.valueOf() - _range.from.valueOf());
  218. var _center = _range.to.valueOf() - _timespan/2;
  219. var _to = (_center + (_timespan*factor)/2);
  220. var _from = (_center - (_timespan*factor)/2);
  221. // If we're not already looking into the future, don't.
  222. if(_to > Date.now() && _range.to < Date.now()) {
  223. var _offset = _to - Date.now();
  224. _from = _from - _offset;
  225. _to = Date.now();
  226. }
  227. if(factor > 1) {
  228. filterSrv.removeByType('time');
  229. }
  230. filterSrv.set({
  231. type:'time',
  232. from:moment.utc(_from),
  233. to:moment.utc(_to),
  234. field:$scope.panel.time_field
  235. });
  236. dashboard.refresh();
  237. };
  238. // I really don't like this function, too much dom manip. Break out into directive?
  239. $scope.populate_modal = function(request) {
  240. $scope.inspector = angular.toJson(JSON.parse(request.toString()),true);
  241. };
  242. $scope.set_refresh = function (state) {
  243. $scope.refresh = state;
  244. };
  245. $scope.close_edit = function() {
  246. if($scope.refresh) {
  247. $scope.get_data();
  248. }
  249. $scope.refresh = false;
  250. $scope.$emit('render');
  251. };
  252. })
  253. .directive('histogramChart', function(dashboard, filterSrv, $rootScope) {
  254. return {
  255. restrict: 'A',
  256. template: '<div></div>',
  257. link: function(scope, elem, attrs, ctrl) {
  258. // Receive render events
  259. scope.$on('render',function(){
  260. render_panel();
  261. });
  262. // Re-render if the window is resized
  263. angular.element(window).bind('resize', function(){
  264. render_panel();
  265. });
  266. // Function for rendering panel
  267. function render_panel() {
  268. // IE doesn't work without this
  269. elem.css({height:scope.panel.height||scope.row.height});
  270. // Populate from the query service
  271. try {
  272. _.each(scope.data, function(series) {
  273. series.label = series.info.alias;
  274. series.color = series.info.color;
  275. });
  276. } catch(e) {return;}
  277. // Set barwidth based on specified interval
  278. var barwidth = kbn.interval_to_seconds(scope.panel.interval)*1000;
  279. var scripts = $LAB.script("common/lib/panels/jquery.flot.js").wait()
  280. .script("common/lib/panels/jquery.flot.time.js")
  281. .script("common/lib/panels/jquery.flot.stack.js")
  282. .script("common/lib/panels/jquery.flot.selection.js")
  283. .script("common/lib/panels/timezone.js");
  284. // Populate element. Note that jvectormap appends, does not replace.
  285. scripts.wait(function(){
  286. var stack = scope.panel.stack ? true : null;
  287. // Populate element
  288. try {
  289. var options = {
  290. legend: { show: false },
  291. series: {
  292. //stackpercent: scope.panel.stack ? scope.panel.percentage : false,
  293. stack: scope.panel.percentage ? null : stack,
  294. lines: {
  295. show: scope.panel.lines,
  296. fill: scope.panel.fill/10,
  297. lineWidth: scope.panel.linewidth,
  298. steps: false
  299. },
  300. bars: {
  301. show: scope.panel.bars,
  302. fill: 1,
  303. barWidth: barwidth/1.8,
  304. zero: false,
  305. lineWidth: 0
  306. },
  307. points: {
  308. show: scope.panel.points,
  309. fill: 1,
  310. fillColor: false,
  311. radius: 5
  312. },
  313. shadowSize: 1
  314. },
  315. yaxis: {
  316. show: scope.panel['y-axis'],
  317. min: 0,
  318. max: scope.panel.percentage && scope.panel.stack ? 100 : null,
  319. },
  320. xaxis: {
  321. timezone: scope.panel.timezone,
  322. show: scope.panel['x-axis'],
  323. mode: "time",
  324. min: _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(),
  325. max: _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(),
  326. timeformat: time_format(scope.panel.interval),
  327. label: "Datetime",
  328. },
  329. grid: {
  330. backgroundColor: null,
  331. borderWidth: 0,
  332. hoverable: true,
  333. color: '#c8c8c8'
  334. }
  335. };
  336. if(scope.panel.interactive) {
  337. options.selection = { mode: "x", color: '#666' };
  338. }
  339. // when rendering stacked bars, we need to ensure each point that has data is zero-filled
  340. // so that the stacking happens in the proper order
  341. var required_times = [];
  342. if (scope.data.length > 1) {
  343. required_times = _.uniq(Array.prototype.concat.apply([], _.map(scope.data, function (query) {
  344. return query.time_series.getOrderedTimes();
  345. })).sort(), true);
  346. }
  347. for (var i = 0; i < scope.data.length; i++) {
  348. scope.data[i].data = scope.data[i].time_series.getFlotPairs(required_times);
  349. }
  350. scope.plot = $.plot(elem, scope.data, options);
  351. } catch(e) {
  352. elem.text(e);
  353. }
  354. });
  355. }
  356. function time_format(interval) {
  357. var _int = kbn.interval_to_seconds(interval);
  358. if(_int >= 2628000) {
  359. return "%m/%y";
  360. }
  361. if(_int >= 86400) {
  362. return "%m/%d/%y";
  363. }
  364. if(_int >= 60) {
  365. return "%H:%M<br>%m/%d";
  366. }
  367. return "%H:%M:%S";
  368. }
  369. var $tooltip = $('<div>');
  370. elem.bind("plothover", function (event, pos, item) {
  371. var group, value;
  372. if (item) {
  373. if (item.series.info.alias || scope.panel.tooltip.query_as_alias) {
  374. group = '<small style="font-size:0.9em;">' +
  375. '<i class="icon-circle" style="color:'+item.series.color+';"></i>' + ' ' +
  376. (item.series.info.alias || item.series.info.query)+
  377. '</small><br>';
  378. } else {
  379. group = kbn.query_color_dot(item.series.color, 15) + ' ';
  380. }
  381. if (scope.panel.stack && scope.panel.tooltip.value_type === 'individual') {
  382. value = item.datapoint[1] - item.datapoint[2];
  383. } else {
  384. value = item.datapoint[1];
  385. }
  386. $tooltip
  387. .html(
  388. group + value + " @ " + moment(item.datapoint[0]).format('MM/DD HH:mm:ss')
  389. )
  390. .place_tt(pos.pageX, pos.pageY);
  391. } else {
  392. $tooltip.detach();
  393. }
  394. });
  395. elem.bind("plotselected", function (event, ranges) {
  396. var _id = filterSrv.set({
  397. type : 'time',
  398. from : moment.utc(ranges.xaxis.from),
  399. to : moment.utc(ranges.xaxis.to),
  400. field : scope.panel.time_field
  401. });
  402. dashboard.refresh();
  403. });
  404. }
  405. };
  406. })
  407. .service('timeSeries', function () {
  408. // map compatable parseInt
  409. function base10Int(val) {
  410. return parseInt(val, 10);
  411. }
  412. function getDatesTime(date) {
  413. return Math.floor(date.getTime() / 1000)*1000;
  414. }
  415. /**
  416. * Certain graphs require 0 entries to be specified for them to render
  417. * properly (like the line graph). So with this we will caluclate all of
  418. * the expected time measurements, and fill the missing ones in with 0
  419. * @param {object} opts An object specifying some/all of the options
  420. *
  421. * OPTIONS:
  422. * @opt {string} interval The interval notion describing the expected spacing between
  423. * each data point.
  424. * @opt {date} start_date (optional) The start point for the time series, setting this and the
  425. * end_date will ensure that the series streches to resemble the entire
  426. * expected result
  427. * @opt {date} end_date (optional) The end point for the time series, see start_date
  428. * @opt {string} fill_style Either "minimal", or "all" describing the strategy used to zero-fill
  429. * the series.
  430. */
  431. this.ZeroFilled = function (opts) {
  432. opts = _.defaults(opts, {
  433. interval: '10m',
  434. start_date: null,
  435. end_date: null,
  436. fill_style: 'minimal'
  437. });
  438. // the expected differenece between readings.
  439. this.interval_ms = base10Int(kbn.interval_to_seconds(opts.interval)) * 1000;
  440. // will keep all values here, keyed by their time
  441. this._data = {};
  442. this.start_time = opts.start_date && getDatesTime(opts.start_date);
  443. this.end_time = opts.end_date && getDatesTime(opts.end_date);
  444. this.opts = opts;
  445. };
  446. /**
  447. * Add a row
  448. * @param {int} time The time for the value, in
  449. * @param {any} value The value at this time
  450. */
  451. this.ZeroFilled.prototype.addValue = function (time, value) {
  452. if (time instanceof Date) {
  453. time = getDatesTime(time);
  454. } else {
  455. time = base10Int(time);
  456. }
  457. if (!isNaN(time)) {
  458. this._data[time] = (_.isUndefined(value) ? 0 : value);
  459. }
  460. this._cached_times = null;
  461. };
  462. /**
  463. * Get an array of the times that have been explicitly set in the series
  464. * @param {array} include (optional) list of timestamps to include in the response
  465. * @return {array} An array of integer times.
  466. */
  467. this.ZeroFilled.prototype.getOrderedTimes = function (include) {
  468. var times = _.map(_.keys(this._data), base10Int);
  469. if (_.isArray(include)) {
  470. times = times.concat(include);
  471. }
  472. return _.uniq(times.sort(), true);
  473. };
  474. /**
  475. * return the rows in the format:
  476. * [ [time, value], [time, value], ... ]
  477. *
  478. * Heavy lifting is done by _get(Min|All)FlotPairs()
  479. * @param {array} required_times An array of timestamps that must be in the resulting pairs
  480. * @return {array}
  481. */
  482. this.ZeroFilled.prototype.getFlotPairs = function (required_times) {
  483. var times = this.getOrderedTimes(required_times),
  484. strategy,
  485. pairs,
  486. pairs_empty;
  487. if(this.opts.fill_style === 'all') {
  488. strategy = this._getAllFlotPairs;
  489. } else {
  490. strategy = this._getMinFlotPairs;
  491. }
  492. pairs = _.reduce(
  493. times, // what
  494. strategy, // how
  495. [], // where
  496. this // context
  497. );
  498. // if the start and end of the pairs are inside either the start or end time,
  499. // add those times to the series with null values so the graph will stretch to contain them.
  500. if (this.start_time && (pairs.length === 0 || pairs[0][0] > this.start_time)) {
  501. pairs.unshift([this.start_time, null]);
  502. }
  503. if (this.end_time && (pairs.length === 0 || pairs[pairs.length - 1][0] < this.end_time)) {
  504. pairs.push([this.end_time, null]);
  505. }
  506. return pairs;
  507. };
  508. /**
  509. * ** called as a reduce stragegy in getFlotPairs() **
  510. * Fill zero's on either side of the current time, unless there is already a measurement there or
  511. * we are looking at an edge.
  512. * @return {array} An array of points to plot with flot
  513. */
  514. this.ZeroFilled.prototype._getMinFlotPairs = function (result, time, i, times) {
  515. var next, expected_next, prev, expected_prev;
  516. // check for previous measurement
  517. if (i > 0) {
  518. prev = times[i - 1];
  519. expected_prev = time - this.interval_ms;
  520. if (prev < expected_prev) {
  521. result.push([expected_prev, 0]);
  522. }
  523. }
  524. // add the current time
  525. result.push([ time, this._data[time] || 0 ]);
  526. // check for next measurement
  527. if (times.length > i) {
  528. next = times[i + 1];
  529. expected_next = time + this.interval_ms;
  530. if (next > expected_next) {
  531. result.push([expected_next, 0]);
  532. }
  533. }
  534. return result;
  535. };
  536. /**
  537. * ** called as a reduce stragegy in getFlotPairs() **
  538. * Fill zero's to the right of each time, until the next measurement is reached or we are at the
  539. * last measurement
  540. * @return {array} An array of points to plot with flot
  541. */
  542. this.ZeroFilled.prototype._getAllFlotPairs = function (result, time, i, times) {
  543. var next, expected_next;
  544. result.push([ times[i], this._data[times[i]] || 0 ]);
  545. next = times[i + 1];
  546. expected_next = times[i] + this.interval_ms;
  547. for(; times.length > i && next > expected_next; expected_next+= this.interval_ms) {
  548. result.push([expected_next, 0]);
  549. }
  550. return result;
  551. };
  552. });