module.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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) {
  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. $scope.get_data = function(segment,query_id) {
  76. delete $scope.panel.error;
  77. // Make sure we have everything for the request to complete
  78. if(dashboard.indices.length === 0) {
  79. return;
  80. }
  81. var _range = $scope.range = filterSrv.timeRange('min');
  82. if ($scope.panel.auto_int) {
  83. $scope.panel.interval = kbn.secondsToHms(
  84. kbn.calculate_interval(_range.from,_range.to,$scope.panel.resolution,0)/1000);
  85. }
  86. $scope.panelMeta.loading = true;
  87. var _segment = _.isUndefined(segment) ? 0 : segment;
  88. var request = $scope.ejs.Request().indices(dashboard.indices[_segment]);
  89. $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries);
  90. // Build the query
  91. _.each($scope.panel.queries.ids, function(id) {
  92. var query = $scope.ejs.FilteredQuery(
  93. querySrv.getEjsObj(id),
  94. filterSrv.getBoolFilter(filterSrv.ids)
  95. );
  96. var facet = $scope.ejs.DateHistogramFacet(id);
  97. if($scope.panel.mode === 'count') {
  98. facet = facet.field($scope.panel.time_field);
  99. } else {
  100. if(_.isNull($scope.panel.value_field)) {
  101. $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
  102. return;
  103. }
  104. facet = facet.keyField($scope.panel.time_field).valueField($scope.panel.value_field);
  105. }
  106. facet = facet.interval($scope.panel.interval).facetFilter($scope.ejs.QueryFilter(query));
  107. request = request.facet(facet).size(0);
  108. });
  109. // Populate the inspector panel
  110. $scope.populate_modal(request);
  111. // Then run it
  112. var results = request.doSearch();
  113. // Populate scope when we have results
  114. results.then(function(results) {
  115. $scope.panelMeta.loading = false;
  116. if(_segment === 0) {
  117. $scope.hits = 0;
  118. $scope.data = [];
  119. query_id = $scope.query_id = new Date().getTime();
  120. }
  121. // Check for error and abort if found
  122. if(!(_.isUndefined(results.error))) {
  123. $scope.panel.error = $scope.parse_error(results.error);
  124. return;
  125. }
  126. // Convert facet ids to numbers
  127. var facetIds = _.map(_.keys(results.facets),function(k){return parseInt(k, 10);});
  128. // Make sure we're still on the same query/queries
  129. if($scope.query_id === query_id &&
  130. _.intersection(facetIds,$scope.panel.queries.ids).length === $scope.panel.queries.ids.length
  131. ) {
  132. var i = 0;
  133. var data, hits;
  134. _.each($scope.panel.queries.ids, function(id) {
  135. var v = results.facets[id];
  136. // Null values at each end of the time range ensure we see entire range
  137. if(_.isUndefined($scope.data[i]) || _segment === 0) {
  138. data = [];
  139. if(filterSrv.idsByType('time').length > 0) {
  140. data = [[_range.from.getTime(), null],[_range.to.getTime(), null]];
  141. //data = [];
  142. }
  143. hits = 0;
  144. } else {
  145. data = $scope.data[i].data;
  146. hits = $scope.data[i].hits;
  147. }
  148. // Assemble segments
  149. var segment_data = [];
  150. _.each(v.entries, function(v, k) {
  151. segment_data.push([v.time,v[$scope.panel.mode]]);
  152. hits += v.count; // The series level hits counter
  153. $scope.hits += v.count; // Entire dataset level hits counter
  154. });
  155. data.splice.apply(data,[1,0].concat(segment_data)); // Join histogram data
  156. // Create the flot series object
  157. var series = {
  158. data: {
  159. info: querySrv.list[id],
  160. data: data,
  161. hits: hits
  162. },
  163. };
  164. $scope.data[i] = series.data;
  165. i++;
  166. });
  167. // Tell the histogram directive to render.
  168. $scope.$emit('render');
  169. // If we still have segments left, get them
  170. if(_segment < dashboard.indices.length-1) {
  171. $scope.get_data(_segment+1,query_id);
  172. }
  173. }
  174. });
  175. };
  176. // function $scope.zoom
  177. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  178. $scope.zoom = function(factor) {
  179. var _now = Date.now();
  180. var _range = filterSrv.timeRange('min');
  181. var _timespan = (_range.to.valueOf() - _range.from.valueOf());
  182. var _center = _range.to.valueOf() - _timespan/2;
  183. var _to = (_center + (_timespan*factor)/2);
  184. var _from = (_center - (_timespan*factor)/2);
  185. // If we're not already looking into the future, don't.
  186. if(_to > Date.now() && _range.to < Date.now()) {
  187. var _offset = _to - Date.now();
  188. _from = _from - _offset;
  189. _to = Date.now();
  190. }
  191. if(factor > 1) {
  192. filterSrv.removeByType('time');
  193. }
  194. filterSrv.set({
  195. type:'time',
  196. from:moment.utc(_from),
  197. to:moment.utc(_to),
  198. field:$scope.panel.time_field
  199. });
  200. dashboard.refresh();
  201. };
  202. // I really don't like this function, too much dom manip. Break out into directive?
  203. $scope.populate_modal = function(request) {
  204. $scope.inspector = angular.toJson(JSON.parse(request.toString()),true);
  205. };
  206. $scope.set_refresh = function (state) {
  207. $scope.refresh = state;
  208. };
  209. $scope.close_edit = function() {
  210. if($scope.refresh) {
  211. $scope.get_data();
  212. }
  213. $scope.refresh = false;
  214. $scope.$emit('render');
  215. };
  216. })
  217. .directive('histogramChart', function(dashboard, filterSrv, $rootScope) {
  218. return {
  219. restrict: 'A',
  220. template: '<div></div>',
  221. link: function(scope, elem, attrs, ctrl) {
  222. // Receive render events
  223. scope.$on('render',function(){
  224. render_panel();
  225. });
  226. // Re-render if the window is resized
  227. angular.element(window).bind('resize', function(){
  228. render_panel();
  229. });
  230. // Function for rendering panel
  231. function render_panel() {
  232. // IE doesn't work without this
  233. elem.css({height:scope.panel.height||scope.row.height});
  234. // Populate from the query service
  235. try {
  236. _.each(scope.data,function(series) {
  237. series.label = series.info.alias;
  238. series.color = series.info.color;
  239. });
  240. } catch(e) {return;}
  241. // Set barwidth based on specified interval
  242. var barwidth = kbn.interval_to_seconds(scope.panel.interval)*1000;
  243. var scripts = $LAB.script("common/lib/panels/jquery.flot.js").wait()
  244. .script("common/lib/panels/jquery.flot.time.js")
  245. .script("common/lib/panels/jquery.flot.stack.js")
  246. .script("common/lib/panels/jquery.flot.selection.js")
  247. .script("common/lib/panels/timezone.js");
  248. // Populate element. Note that jvectormap appends, does not replace.
  249. scripts.wait(function(){
  250. var stack = scope.panel.stack ? true : null;
  251. // Populate element
  252. try {
  253. var options = {
  254. legend: { show: false },
  255. series: {
  256. //stackpercent: scope.panel.stack ? scope.panel.percentage : false,
  257. stack: scope.panel.percentage ? null : stack,
  258. lines: {
  259. show: scope.panel.lines,
  260. fill: scope.panel.fill/10,
  261. lineWidth: scope.panel.linewidth,
  262. steps: false
  263. },
  264. bars: { show: scope.panel.bars, fill: 1, barWidth: barwidth/1.8, zero: false },
  265. points: { show: scope.panel.points, fill: 1, fillColor: false, radius: 5},
  266. shadowSize: 1
  267. },
  268. yaxis: {
  269. show: scope.panel['y-axis'],
  270. min: 0,
  271. max: scope.panel.percentage && scope.panel.stack ? 100 : null,
  272. },
  273. xaxis: {
  274. timezone: scope.panel.timezone,
  275. show: scope.panel['x-axis'],
  276. mode: "time",
  277. min: _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(),
  278. max: _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(),
  279. timeformat: time_format(scope.panel.interval),
  280. label: "Datetime",
  281. },
  282. grid: {
  283. backgroundColor: null,
  284. borderWidth: 0,
  285. hoverable: true,
  286. color: '#c8c8c8'
  287. }
  288. };
  289. if(scope.panel.interactive) {
  290. options.selection = { mode: "x", color: '#666' };
  291. }
  292. scope.plot = $.plot(elem, scope.data, options);
  293. } catch(e) {
  294. elem.text(e);
  295. }
  296. });
  297. }
  298. function time_format(interval) {
  299. var _int = kbn.interval_to_seconds(interval);
  300. if(_int >= 2628000) {
  301. return "%m/%y";
  302. }
  303. if(_int >= 86400) {
  304. return "%m/%d/%y";
  305. }
  306. if(_int >= 60) {
  307. return "%H:%M<br>%m/%d";
  308. }
  309. return "%H:%M:%S";
  310. }
  311. function tt(x, y, contents) {
  312. // If the tool tip already exists, don't recreate it, just update it
  313. var tooltip = $('#pie-tooltip').length ?
  314. $('#pie-tooltip') : $('<div id="pie-tooltip"></div>');
  315. tooltip.html(contents).css({
  316. position: 'absolute',
  317. top : y + 5,
  318. left : x + 5,
  319. color : "#c8c8c8",
  320. padding : '10px',
  321. 'font-size': '11pt',
  322. 'font-weight' : 200,
  323. 'background-color': '#1f1f1f',
  324. 'border-radius': '5px',
  325. }).appendTo("body");
  326. }
  327. elem.bind("plothover", function (event, pos, item) {
  328. if (item) {
  329. tt(pos.pageX, pos.pageY,
  330. "<div style='vertical-align:middle;display:inline-block;background:"+
  331. item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  332. item.datapoint[1].toFixed(0) + " @ " +
  333. moment(item.datapoint[0]).format('MM/DD HH:mm:ss'));
  334. } else {
  335. $("#pie-tooltip").remove();
  336. }
  337. });
  338. elem.bind("plotselected", function (event, ranges) {
  339. var _id = filterSrv.set({
  340. type : 'time',
  341. from : moment.utc(ranges.xaxis.from),
  342. to : moment.utc(ranges.xaxis.to),
  343. field : scope.panel.time_field
  344. });
  345. dashboard.refresh();
  346. });
  347. }
  348. };
  349. });