module.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*jshint globalstrict:true */
  2. /*global angular:true */
  3. /*
  4. ## Histogram
  5. A bucketted time series representation of the current query or queries. Note that this
  6. panel uses facetting. I tried to make it safe by using sequential/serial querying but,
  7. yeah, you should know that it uses facetting. It should be pretty safe.
  8. ### Parameters
  9. * auto_int :: Auto calculate data point interval?
  10. * resolution :: If auto_int is enables, shoot for this many data points, rounding to
  11. sane intervals
  12. * interval :: Datapoint interval in elasticsearch date math format (eg 1d, 1w, 1y, 5y)
  13. * fill :: Only applies to line charts. Level of area shading from 0-10
  14. * linewidth :: Only applies to line charts. How thick the line should be in pixels
  15. While the editor only exposes 0-10, this can be any numeric value.
  16. Set to 0 and you'll get something like a scatter plot
  17. * timezone :: This isn't totally functional yet. Currently only supports browser and utc.
  18. browser will adjust the x-axis labels to match the timezone of the user's
  19. browser
  20. * spyable :: Dislay the 'eye' icon that show the last elasticsearch query
  21. * zoomlinks :: Show the zoom links?
  22. * bars :: Show bars in the chart
  23. * stack :: Stack multiple queries. This generally a crappy way to represent things.
  24. You probably should just use a line chart without stacking
  25. * points :: Should circles at the data points on the chart
  26. * lines :: Line chart? Sweet.
  27. * legend :: Show the legend?
  28. * x-axis :: Show x-axis labels and grid lines
  29. * y-axis :: Show y-axis labels and grid lines
  30. * interactive :: Allow drag to select time range
  31. */
  32. 'use strict';
  33. angular.module('kibana.histogram', [])
  34. .controller('histogram', function($scope, eventBus, querySrv, dashboard, filterSrv) {
  35. // Set and populate defaults
  36. var _d = {
  37. status : "Stable",
  38. mode : 'count',
  39. time_field : '@timestamp',
  40. queries : {
  41. mode : 'all',
  42. ids : []
  43. },
  44. value_field : null,
  45. auto_int : true,
  46. resolution : 100,
  47. interval : '5m',
  48. fill : 0,
  49. linewidth : 3,
  50. timezone : 'browser', // browser, utc or a standard timezone
  51. spyable : true,
  52. zoomlinks : true,
  53. bars : true,
  54. stack : true,
  55. points : false,
  56. lines : false,
  57. legend : true,
  58. 'x-axis' : true,
  59. 'y-axis' : true,
  60. percentage : false,
  61. interactive : true,
  62. };
  63. _.defaults($scope.panel,_d);
  64. $scope.init = function() {
  65. $scope.$on('refresh',function(){
  66. $scope.get_data();
  67. });
  68. $scope.get_data();
  69. };
  70. $scope.get_data = function(segment,query_id) {
  71. delete $scope.panel.error;
  72. // Make sure we have everything for the request to complete
  73. if(dashboard.indices.length === 0) {
  74. return;
  75. }
  76. var _range = $scope.range = filterSrv.timeRange('min');
  77. if ($scope.panel.auto_int) {
  78. $scope.panel.interval = kbn.secondsToHms(
  79. kbn.calculate_interval(_range.from,_range.to,$scope.panel.resolution,0)/1000);
  80. }
  81. $scope.panel.loading = true;
  82. var _segment = _.isUndefined(segment) ? 0 : segment;
  83. var request = $scope.ejs.Request().indices(dashboard.indices[_segment]);
  84. $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries);
  85. // Build the query
  86. _.each($scope.panel.queries.ids, function(id) {
  87. var query = $scope.ejs.FilteredQuery(
  88. querySrv.getEjsObj(id),
  89. filterSrv.getBoolFilter(filterSrv.ids)
  90. );
  91. var facet = $scope.ejs.DateHistogramFacet(id);
  92. if($scope.panel.mode === 'count') {
  93. facet = facet.field($scope.panel.time_field);
  94. } else {
  95. if(_.isNull($scope.panel.value_field)) {
  96. $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
  97. return;
  98. }
  99. facet = facet.keyField($scope.panel.time_field).valueField($scope.panel.value_field);
  100. }
  101. facet = facet.interval($scope.panel.interval).facetFilter($scope.ejs.QueryFilter(query));
  102. request = request.facet(facet).size(0);
  103. });
  104. // Populate the inspector panel
  105. $scope.populate_modal(request);
  106. // Then run it
  107. var results = request.doSearch();
  108. // Populate scope when we have results
  109. results.then(function(results) {
  110. $scope.panel.loading = false;
  111. if(_segment === 0) {
  112. $scope.hits = 0;
  113. $scope.data = [];
  114. query_id = $scope.query_id = new Date().getTime();
  115. }
  116. // Check for error and abort if found
  117. if(!(_.isUndefined(results.error))) {
  118. $scope.panel.error = $scope.parse_error(results.error);
  119. return;
  120. }
  121. // Convert facet ids to numbers
  122. var facetIds = _.map(_.keys(results.facets),function(k){return parseInt(k, 10);});
  123. // Make sure we're still on the same query/queries
  124. if($scope.query_id === query_id &&
  125. _.intersection(facetIds,$scope.panel.queries.ids).length === $scope.panel.queries.ids.length
  126. ) {
  127. var i = 0;
  128. var data, hits;
  129. _.each($scope.panel.queries.ids, function(id) {
  130. var v = results.facets[id];
  131. // Null values at each end of the time range ensure we see entire range
  132. if(_.isUndefined($scope.data[i]) || _segment === 0) {
  133. data = [];
  134. if(filterSrv.idsByType('time').length > 0) {
  135. data = [[_range.from.getTime(), null],[_range.to.getTime(), null]];
  136. }
  137. hits = 0;
  138. } else {
  139. data = $scope.data[i].data;
  140. hits = $scope.data[i].hits;
  141. }
  142. // Assemble segments
  143. var segment_data = [];
  144. _.each(v.entries, function(v, k) {
  145. segment_data.push([v.time,v[$scope.panel.mode]]);
  146. hits += v.count; // The series level hits counter
  147. $scope.hits += v.count; // Entire dataset level hits counter
  148. });
  149. data.splice.apply(data,[1,0].concat(segment_data)); // Join histogram data
  150. // Create the flot series object
  151. var series = {
  152. data: {
  153. info: querySrv.list[id],
  154. data: data,
  155. hits: hits
  156. },
  157. };
  158. $scope.data[i] = series.data;
  159. i++;
  160. });
  161. // Tell the histogram directive to render.
  162. $scope.$emit('render');
  163. // If we still have segments left, get them
  164. if(_segment < dashboard.indices.length-1) {
  165. $scope.get_data(_segment+1,query_id);
  166. }
  167. }
  168. });
  169. };
  170. // function $scope.zoom
  171. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  172. $scope.zoom = function(factor) {
  173. var _now = Date.now();
  174. var _range = filterSrv.timeRange('min');
  175. var _timespan = (_range.to.valueOf() - _range.from.valueOf());
  176. var _center = _range.to.valueOf() - _timespan/2;
  177. var _to = (_center + (_timespan*factor)/2);
  178. var _from = (_center - (_timespan*factor)/2);
  179. // If we're not already looking into the future, don't.
  180. if(_to > Date.now() && _range.to < Date.now()) {
  181. var _offset = _to - Date.now();
  182. _from = _from - _offset;
  183. _to = Date.now();
  184. }
  185. if(factor > 1) {
  186. filterSrv.removeByType('time');
  187. }
  188. filterSrv.set({
  189. type:'time',
  190. from:moment.utc(_from),
  191. to:moment.utc(_to),
  192. field:$scope.panel.time_field
  193. });
  194. dashboard.refresh();
  195. };
  196. // I really don't like this function, too much dom manip. Break out into directive?
  197. $scope.populate_modal = function(request) {
  198. $scope.modal = {
  199. title: "Inspector",
  200. body : "<h5>Last Elasticsearch Query</h5><pre>"+
  201. 'curl -XGET '+config.elasticsearch+'/'+dashboard.indices+"/_search?pretty -d'\n"+
  202. angular.toJson(JSON.parse(request.toString()),true)+
  203. "'</pre>",
  204. };
  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, eventBus, 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 },
  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. color: "#c8c8c8"
  273. },
  274. xaxis: {
  275. timezone: scope.panel.timezone,
  276. show: scope.panel['x-axis'],
  277. mode: "time",
  278. timeformat: time_format(scope.panel.interval),
  279. label: "Datetime",
  280. color: "#c8c8c8",
  281. },
  282. grid: {
  283. backgroundColor: null,
  284. borderWidth: 0,
  285. borderColor: '#eee',
  286. color: "#eee",
  287. hoverable: true,
  288. }
  289. };
  290. if(scope.panel.interactive) {
  291. options.selection = { mode: "x", color: '#666' };
  292. }
  293. scope.plot = $.plot(elem, scope.data, options);
  294. } catch(e) {
  295. elem.text(e);
  296. }
  297. });
  298. }
  299. function time_format(interval) {
  300. var _int = kbn.interval_to_seconds(interval);
  301. if(_int >= 2628000) {
  302. return "%m/%y";
  303. }
  304. if(_int >= 86400) {
  305. return "%m/%d/%y";
  306. }
  307. if(_int >= 60) {
  308. return "%H:%M<br>%m/%d";
  309. }
  310. return "%H:%M:%S";
  311. }
  312. function tt(x, y, contents) {
  313. // If the tool tip already exists, don't recreate it, just update it
  314. var tooltip = $('#pie-tooltip').length ?
  315. $('#pie-tooltip') : $('<div id="pie-tooltip"></div>');
  316. tooltip.html(contents).css({
  317. position: 'absolute',
  318. top : y + 5,
  319. left : x + 5,
  320. color : "#c8c8c8",
  321. padding : '10px',
  322. 'font-size': '11pt',
  323. 'font-weight' : 200,
  324. 'background-color': '#1f1f1f',
  325. 'border-radius': '5px',
  326. }).appendTo("body");
  327. }
  328. elem.bind("plothover", function (event, pos, item) {
  329. if (item) {
  330. tt(pos.pageX, pos.pageY,
  331. "<div style='vertical-align:middle;display:inline-block;background:"+
  332. item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  333. item.datapoint[1].toFixed(0) + " @ " +
  334. moment(item.datapoint[0]).format('MM/DD HH:mm:ss'));
  335. } else {
  336. $("#pie-tooltip").remove();
  337. }
  338. });
  339. elem.bind("plotselected", function (event, ranges) {
  340. var _id = filterSrv.set({
  341. type : 'time',
  342. from : moment.utc(ranges.xaxis.from),
  343. to : moment.utc(ranges.xaxis.to),
  344. field : scope.panel.time_field
  345. });
  346. dashboard.refresh();
  347. });
  348. }
  349. };
  350. });