module.js 20 KB

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