module.js 20 KB

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