module.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. * @param number segment The segment count, (0 based)
  101. * @param number query_id The id of the query, generated on the first run and passed back when
  102. * this call is made recursively for more segments
  103. */
  104. $scope.get_data = function(segment, query_id) {
  105. if (_.isUndefined(segment)) {
  106. segment = 0;
  107. }
  108. delete $scope.panel.error;
  109. // Make sure we have everything for the request to complete
  110. if(dashboard.indices.length === 0) {
  111. return;
  112. }
  113. var _range = $scope.get_time_range();
  114. var _interval = $scope.get_interval(_range);
  115. if ($scope.panel.auto_int) {
  116. $scope.panel.interval = kbn.secondsToHms(
  117. kbn.calculate_interval(_range.from,_range.to,$scope.panel.resolution,0)/1000);
  118. }
  119. $scope.panelMeta.loading = true;
  120. var request = $scope.ejs.Request().indices(dashboard.indices[segment]);
  121. $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries);
  122. // Build the query
  123. _.each($scope.panel.queries.ids, function(id) {
  124. var query = $scope.ejs.FilteredQuery(
  125. querySrv.getEjsObj(id),
  126. filterSrv.getBoolFilter(filterSrv.ids)
  127. );
  128. var facet = $scope.ejs.DateHistogramFacet(id);
  129. if($scope.panel.mode === 'count') {
  130. facet = facet.field($scope.panel.time_field);
  131. } else {
  132. if(_.isNull($scope.panel.value_field)) {
  133. $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
  134. return;
  135. }
  136. facet = facet.keyField($scope.panel.time_field).valueField($scope.panel.value_field);
  137. }
  138. facet = facet.interval(_interval).facetFilter($scope.ejs.QueryFilter(query));
  139. request = request.facet(facet).size(0);
  140. });
  141. // Populate the inspector panel
  142. $scope.populate_modal(request);
  143. // Then run it
  144. var results = request.doSearch();
  145. // Populate scope when we have results
  146. results.then(function(results) {
  147. $scope.panelMeta.loading = false;
  148. if(segment === 0) {
  149. $scope.hits = 0;
  150. $scope.data = [];
  151. query_id = $scope.query_id = new Date().getTime();
  152. }
  153. // Check for error and abort if found
  154. if(!(_.isUndefined(results.error))) {
  155. $scope.panel.error = $scope.parse_error(results.error);
  156. return;
  157. }
  158. // Convert facet ids to numbers
  159. var facetIds = _.map(_.keys(results.facets),function(k){return parseInt(k, 10);});
  160. // Make sure we're still on the same query/queries
  161. if($scope.query_id === query_id && _.difference(facetIds, $scope.panel.queries.ids).length === 0) {
  162. var i = 0,
  163. time_series,
  164. hits;
  165. _.each($scope.panel.queries.ids, function(id) {
  166. var query_results = results.facets[id];
  167. // we need to initialize the data variable on the first run,
  168. // and when we are working on the first segment of the data.
  169. if(_.isUndefined($scope.data[i]) || segment === 0) {
  170. time_series = new timeSeries.ZeroFilled(
  171. _interval,
  172. // range may be false
  173. _range && _range.from,
  174. _range && _range.to
  175. );
  176. hits = 0;
  177. } else {
  178. time_series = $scope.data[i].time_series;
  179. hits = $scope.data[i].hits;
  180. }
  181. // push each entry into the time series, while incrementing counters
  182. _.each(query_results.entries, function(entry) {
  183. time_series.addValue(entry.time, entry[$scope.panel.mode]);
  184. hits += entry.count; // The series level hits counter
  185. $scope.hits += entry.count; // Entire dataset level hits counter
  186. });
  187. $scope.data[i] = {
  188. time_series: time_series,
  189. info: querySrv.list[id],
  190. data: time_series.getFlotPairs(),
  191. hits: hits
  192. };
  193. i++;
  194. });
  195. // Tell the histogram directive to render.
  196. $scope.$emit('render');
  197. // If we still have segments left, get them
  198. if(segment < dashboard.indices.length-1) {
  199. $scope.get_data(segment+1,query_id);
  200. }
  201. }
  202. });
  203. };
  204. // function $scope.zoom
  205. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  206. $scope.zoom = function(factor) {
  207. var _now = Date.now();
  208. var _range = filterSrv.timeRange('min');
  209. var _timespan = (_range.to.valueOf() - _range.from.valueOf());
  210. var _center = _range.to.valueOf() - _timespan/2;
  211. var _to = (_center + (_timespan*factor)/2);
  212. var _from = (_center - (_timespan*factor)/2);
  213. // If we're not already looking into the future, don't.
  214. if(_to > Date.now() && _range.to < Date.now()) {
  215. var _offset = _to - Date.now();
  216. _from = _from - _offset;
  217. _to = Date.now();
  218. }
  219. if(factor > 1) {
  220. filterSrv.removeByType('time');
  221. }
  222. filterSrv.set({
  223. type:'time',
  224. from:moment.utc(_from),
  225. to:moment.utc(_to),
  226. field:$scope.panel.time_field
  227. });
  228. dashboard.refresh();
  229. };
  230. // I really don't like this function, too much dom manip. Break out into directive?
  231. $scope.populate_modal = function(request) {
  232. $scope.inspector = angular.toJson(JSON.parse(request.toString()),true);
  233. };
  234. $scope.set_refresh = function (state) {
  235. $scope.refresh = state;
  236. };
  237. $scope.close_edit = function() {
  238. if($scope.refresh) {
  239. $scope.get_data();
  240. }
  241. $scope.refresh = false;
  242. $scope.$emit('render');
  243. };
  244. })
  245. .directive('histogramChart', function(dashboard, filterSrv, $rootScope) {
  246. return {
  247. restrict: 'A',
  248. template: '<div></div>',
  249. link: function(scope, elem, attrs, ctrl) {
  250. // Receive render events
  251. scope.$on('render',function(){
  252. render_panel();
  253. });
  254. // Re-render if the window is resized
  255. angular.element(window).bind('resize', function(){
  256. render_panel();
  257. });
  258. // Function for rendering panel
  259. function render_panel() {
  260. // IE doesn't work without this
  261. elem.css({height:scope.panel.height||scope.row.height});
  262. // Populate from the query service
  263. try {
  264. _.each(scope.data,function(series) {
  265. series.label = series.info.alias;
  266. series.color = series.info.color;
  267. });
  268. } catch(e) {return;}
  269. // Set barwidth based on specified interval
  270. var barwidth = kbn.interval_to_seconds(scope.panel.interval)*1000;
  271. var scripts = $LAB.script("common/lib/panels/jquery.flot.js").wait()
  272. .script("common/lib/panels/jquery.flot.time.js")
  273. .script("common/lib/panels/jquery.flot.stack.js")
  274. .script("common/lib/panels/jquery.flot.selection.js")
  275. .script("common/lib/panels/timezone.js");
  276. // Populate element. Note that jvectormap appends, does not replace.
  277. scripts.wait(function(){
  278. var stack = scope.panel.stack ? true : null;
  279. // Populate element
  280. try {
  281. var options = {
  282. legend: { show: false },
  283. series: {
  284. //stackpercent: scope.panel.stack ? scope.panel.percentage : false,
  285. stack: scope.panel.percentage ? null : stack,
  286. lines: {
  287. show: scope.panel.lines,
  288. fill: scope.panel.fill/10,
  289. lineWidth: scope.panel.linewidth,
  290. steps: false
  291. },
  292. bars: {
  293. show: scope.panel.bars,
  294. fill: 1,
  295. barWidth: barwidth/1.8,
  296. zero: false,
  297. lineWidth: 0
  298. },
  299. points: {
  300. show: scope.panel.points,
  301. fill: 1,
  302. fillColor: false,
  303. radius: 5
  304. },
  305. shadowSize: 1
  306. },
  307. yaxis: {
  308. show: scope.panel['y-axis'],
  309. min: 0,
  310. max: scope.panel.percentage && scope.panel.stack ? 100 : null,
  311. },
  312. xaxis: {
  313. timezone: scope.panel.timezone,
  314. show: scope.panel['x-axis'],
  315. mode: "time",
  316. min: _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(),
  317. max: _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(),
  318. timeformat: time_format(scope.panel.interval),
  319. label: "Datetime",
  320. },
  321. grid: {
  322. backgroundColor: null,
  323. borderWidth: 0,
  324. hoverable: true,
  325. color: '#c8c8c8'
  326. }
  327. };
  328. if(scope.panel.interactive) {
  329. options.selection = { mode: "x", color: '#666' };
  330. }
  331. scope.plot = $.plot(elem, scope.data, options);
  332. } catch(e) {
  333. elem.text(e);
  334. }
  335. });
  336. }
  337. function time_format(interval) {
  338. var _int = kbn.interval_to_seconds(interval);
  339. if(_int >= 2628000) {
  340. return "%m/%y";
  341. }
  342. if(_int >= 86400) {
  343. return "%m/%d/%y";
  344. }
  345. if(_int >= 60) {
  346. return "%H:%M<br>%m/%d";
  347. }
  348. return "%H:%M:%S";
  349. }
  350. function tt(x, y, contents) {
  351. // If the tool tip already exists, don't recreate it, just update it
  352. var tooltip = $('#pie-tooltip').length ? $('#pie-tooltip') : $('<div id="pie-tooltip"></div>');
  353. tooltip.html(contents).css({
  354. position: 'absolute',
  355. top : y + 5,
  356. left : x + 5,
  357. color : "#c8c8c8",
  358. padding : '10px',
  359. 'font-size': '11pt',
  360. 'font-weight' : 200,
  361. 'background-color': '#1f1f1f',
  362. 'border-radius': '5px',
  363. }).appendTo("body");
  364. }
  365. elem.bind("plothover", function (event, pos, item) {
  366. if (item) {
  367. tt(pos.pageX, pos.pageY,
  368. "<div style='vertical-align:middle;display:inline-block;background:"+
  369. item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  370. item.datapoint[1].toFixed(0) + " @ " +
  371. moment(item.datapoint[0]).format('MM/DD HH:mm:ss'));
  372. } else {
  373. $("#pie-tooltip").remove();
  374. }
  375. });
  376. elem.bind("plotselected", function (event, ranges) {
  377. var _id = filterSrv.set({
  378. type : 'time',
  379. from : moment.utc(ranges.xaxis.from),
  380. to : moment.utc(ranges.xaxis.to),
  381. field : scope.panel.time_field
  382. });
  383. dashboard.refresh();
  384. });
  385. }
  386. };
  387. })
  388. .service('timeSeries', function () {
  389. /**
  390. * Certain graphs require 0 entries to be specified for them to render
  391. * properly (like the line graph). So with this we will caluclate all of
  392. * the expected time measurements, and fill the missing ones in with 0
  393. * @param date start The start time for the result set
  394. * @param date end The end time for the result set
  395. * @param integer interval The length between measurements, in es interval
  396. * notation (1m, 30s, 1h, 15d)
  397. */
  398. var undef;
  399. function base10Int(val) {
  400. return parseInt(val, 10);
  401. }
  402. this.ZeroFilled = function (interval, start, end) {
  403. // the expected differenece between readings.
  404. this.interval_ms = base10Int(kbn.interval_to_seconds(interval)) * 1000;
  405. // will keep all values here, keyed by their time
  406. this._data = {};
  407. if (start) {
  408. this.addValue(start, null);
  409. }
  410. if (end) {
  411. this.addValue(end, null);
  412. }
  413. };
  414. /**
  415. * Add a row
  416. * @param int time The time for the value, in
  417. * @param any value The value at this time
  418. */
  419. this.ZeroFilled.prototype.addValue = function (time, value) {
  420. if (time instanceof Date) {
  421. time = Math.floor(time.getTime() / 1000)*1000;
  422. } else {
  423. time = base10Int(time);
  424. }
  425. if (!isNaN(time)) {
  426. this._data[time] = (value === undef ? 0 : value);
  427. }
  428. };
  429. /**
  430. * return the rows in the format:
  431. * [ [time, value], [time, value], ... ]
  432. * @return array
  433. */
  434. this.ZeroFilled.prototype.getFlotPairs = function () {
  435. // var startTime = performance.now();
  436. var times = _.map(_.keys(this._data), base10Int).sort(),
  437. result = [];
  438. _.each(times, function (time, i, times) {
  439. var next, expected_next, prev, expected_prev;
  440. // check for previous measurement
  441. if (i > 0) {
  442. prev = times[i - 1];
  443. expected_prev = time - this.interval_ms;
  444. if (prev < expected_prev) {
  445. result.push([expected_prev, 0]);
  446. }
  447. }
  448. // add the current time
  449. result.push([ time, this._data[time] ]);
  450. // check for next measurement
  451. if (times.length > i) {
  452. next = times[i + 1];
  453. expected_next = time + this.interval_ms;
  454. if (next > expected_next) {
  455. result.push([expected_next, 0]);
  456. }
  457. }
  458. }, this);
  459. // console.log(Math.round((performance.now() - startTime)*100)/100, 'ms to get', result.length, 'pairs');
  460. return result;
  461. };
  462. });