module.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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: { show: scope.panel.bars, fill: 1, barWidth: barwidth/1.8, zero: false },
  293. points: { show: scope.panel.points, fill: 1, fillColor: false, radius: 5},
  294. shadowSize: 1
  295. },
  296. yaxis: {
  297. show: scope.panel['y-axis'],
  298. min: 0,
  299. max: scope.panel.percentage && scope.panel.stack ? 100 : null,
  300. },
  301. xaxis: {
  302. timezone: scope.panel.timezone,
  303. show: scope.panel['x-axis'],
  304. mode: "time",
  305. min: _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(),
  306. max: _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(),
  307. timeformat: time_format(scope.panel.interval),
  308. label: "Datetime",
  309. },
  310. grid: {
  311. backgroundColor: null,
  312. borderWidth: 0,
  313. hoverable: true,
  314. color: '#c8c8c8'
  315. }
  316. };
  317. if(scope.panel.interactive) {
  318. options.selection = { mode: "x", color: '#666' };
  319. }
  320. scope.plot = $.plot(elem, scope.data, options);
  321. } catch(e) {
  322. elem.text(e);
  323. }
  324. });
  325. }
  326. function time_format(interval) {
  327. var _int = kbn.interval_to_seconds(interval);
  328. if(_int >= 2628000) {
  329. return "%m/%y";
  330. }
  331. if(_int >= 86400) {
  332. return "%m/%d/%y";
  333. }
  334. if(_int >= 60) {
  335. return "%H:%M<br>%m/%d";
  336. }
  337. return "%H:%M:%S";
  338. }
  339. function tt(x, y, contents) {
  340. // If the tool tip already exists, don't recreate it, just update it
  341. var tooltip = $('#pie-tooltip').length
  342. ? $('#pie-tooltip')
  343. : $('<div id="pie-tooltip"></div>');
  344. tooltip.html(contents).css({
  345. position: 'absolute',
  346. top : y + 5,
  347. left : x + 5,
  348. color : "#c8c8c8",
  349. padding : '10px',
  350. 'font-size': '11pt',
  351. 'font-weight' : 200,
  352. 'background-color': '#1f1f1f',
  353. 'border-radius': '5px',
  354. }).appendTo("body");
  355. }
  356. elem.bind("plothover", function (event, pos, item) {
  357. if (item) {
  358. tt(pos.pageX, pos.pageY,
  359. "<div style='vertical-align:middle;display:inline-block;background:"+
  360. item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  361. item.datapoint[1].toFixed(0) + " @ " +
  362. moment(item.datapoint[0]).format('MM/DD HH:mm:ss'));
  363. } else {
  364. $("#pie-tooltip").remove();
  365. }
  366. });
  367. elem.bind("plotselected", function (event, ranges) {
  368. var _id = filterSrv.set({
  369. type : 'time',
  370. from : moment.utc(ranges.xaxis.from),
  371. to : moment.utc(ranges.xaxis.to),
  372. field : scope.panel.time_field
  373. });
  374. dashboard.refresh();
  375. });
  376. }
  377. };
  378. })
  379. .service('timeSeries', function () {
  380. /**
  381. * Certain graphs require 0 entries to be specified for them to render
  382. * properly (like the line graph). So with this we will caluclate all of
  383. * the expected time measurements, and fill the missing ones in with 0
  384. * @param date start The start time for the result set
  385. * @param date end The end time for the result set
  386. * @param integer interval The length between measurements, in es interval
  387. * notation (1m, 30s, 1h, 15d)
  388. */
  389. var undef;
  390. function base10Int(val) {
  391. return parseInt(val, 10);
  392. }
  393. this.ZeroFilled = function (interval, start, end) {
  394. // the expected differenece between readings.
  395. this.interval_ms = base10Int(kbn.interval_to_seconds(interval)) * 1000;
  396. // will keep all values here, keyed by their time
  397. this._data = {};
  398. if (start) {
  399. this.addValue(start, null);
  400. }
  401. if (end) {
  402. this.addValue(end, null);
  403. }
  404. }
  405. /**
  406. * Add a row
  407. * @param int time The time for the value, in
  408. * @param any value The value at this time
  409. */
  410. this.ZeroFilled.prototype.addValue = function (time, value) {
  411. if (time instanceof Date) {
  412. time = Math.floor(time.getTime() / 1000)*1000;
  413. } else {
  414. time = base10Int(time);
  415. }
  416. if (!isNaN(time)) {
  417. this._data[time] = (value === undef ? 0 : value);
  418. }
  419. };
  420. /**
  421. * return the rows in the format:
  422. * [ [time, value], [time, value], ... ]
  423. * @return array
  424. */
  425. this.ZeroFilled.prototype.getFlotPairs = function () {
  426. // var startTime = performance.now();
  427. var times = _.map(_.keys(this._data), base10Int).sort()
  428. , result = []
  429. , i
  430. , next
  431. , expected_next;
  432. for(i = 0; i < times.length; i++) {
  433. result.push([ times[i], this._data[times[i]] ]);
  434. next = times[i + 1];
  435. expected_next = times[i] + this.interval_ms;
  436. for(; times.length > i && next > expected_next; expected_next+= this.interval_ms) {
  437. /**
  438. * since we don't know how the server will round subsequent segments
  439. * we have to recheck for blanks each time.
  440. */
  441. // this._data[expected_next] = 0;
  442. result.push([expected_next, 0]);
  443. }
  444. }
  445. // console.log(Math.round((performance.now() - startTime)*100)/100, 'ms to get', result.length, 'pairs');
  446. return result;
  447. };
  448. });