module.js 13 KB

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