module.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. * query :: an array of objects as such: {query: 'somequery', label 'legent text'}.
  10. this is usually populated by a stringquery panel wher the query and label
  11. parameter are the same
  12. * auto_int :: Auto calculate data point interval?
  13. * resolution :: If auto_int is enables, shoot for this many data points, rounding to
  14. sane intervals
  15. * interval :: Datapoint interval in elasticsearch date math format (eg 1d, 1w, 1y, 5y)
  16. * fill :: Only applies to line charts. Level of area shading from 0-10
  17. * linewidth :: Only applies to line charts. How thick the line should be in pixels
  18. While the editor only exposes 0-10, this can be any numeric value.
  19. Set to 0 and you'll get something like a scatter plot
  20. * timezone :: This isn't totally functional yet. Currently only supports browser and utc.
  21. browser will adjust the x-axis labels to match the timezone of the user's
  22. browser
  23. * spyable :: Dislay the 'eye' icon that show the last elasticsearch query
  24. * zoomlinks :: Show the zoom links?
  25. * bars :: Show bars in the chart
  26. * stack :: Stack multiple queries. This generally a crappy way to represent things.
  27. You probably should just use a line chart without stacking
  28. * points :: Should circles at the data points on the chart
  29. * lines :: Line chart? Sweet.
  30. * legend :: Show the legend?
  31. * x-axis :: Show x-axis labels and grid lines
  32. * y-axis :: Show y-axis labels and grid lines
  33. * interactive :: Allow drag to select time range
  34. */
  35. 'use strict';
  36. angular.module('kibana.histogram', [])
  37. .controller('histogram', function($scope, eventBus, querySrv, dashboard, filterSrv) {
  38. // Set and populate defaults
  39. var _d = {
  40. status : "Stable",
  41. group : "default",
  42. mode : 'count',
  43. time_field : '@timestamp',
  44. queries : [],
  45. value_field : null,
  46. auto_int : true,
  47. resolution : 100,
  48. interval : '5m',
  49. fill : 0,
  50. linewidth : 3,
  51. timezone : 'browser', // browser, utc or a standard timezone
  52. spyable : true,
  53. zoomlinks : true,
  54. bars : true,
  55. stack : true,
  56. points : false,
  57. lines : false,
  58. legend : true,
  59. 'x-axis' : true,
  60. 'y-axis' : true,
  61. percentage : false,
  62. interactive : true,
  63. };
  64. _.defaults($scope.panel,_d);
  65. $scope.init = function() {
  66. $scope.querySrv = querySrv;
  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.panel.loading = true;
  84. var _segment = _.isUndefined(segment) ? 0 : segment;
  85. var request = $scope.ejs.Request().indices(dashboard.indices[_segment]);
  86. // Build the query
  87. _.each(querySrv.ids, function(id) {
  88. var query = $scope.ejs.FilteredQuery(
  89. querySrv.getEjsObj(id),
  90. filterSrv.getBoolFilter(filterSrv.ids)
  91. );
  92. var facet = $scope.ejs.DateHistogramFacet(id);
  93. if($scope.panel.mode === 'count') {
  94. facet = facet.field($scope.panel.time_field);
  95. } else {
  96. if(_.isNull($scope.panel.value_field)) {
  97. $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
  98. return;
  99. }
  100. facet = facet.keyField($scope.panel.time_field).valueField($scope.panel.value_field);
  101. }
  102. facet = facet.interval($scope.panel.interval).facetFilter($scope.ejs.QueryFilter(query));
  103. request = request.facet(facet).size(0);
  104. });
  105. // Populate the inspector panel
  106. $scope.populate_modal(request);
  107. // Then run it
  108. var results = request.doSearch();
  109. // Populate scope when we have results
  110. results.then(function(results) {
  111. $scope.panel.loading = false;
  112. if(_segment === 0) {
  113. $scope.hits = 0;
  114. $scope.data = [];
  115. query_id = $scope.query_id = new Date().getTime();
  116. }
  117. // Check for error and abort if found
  118. if(!(_.isUndefined(results.error))) {
  119. $scope.panel.error = $scope.parse_error(results.error);
  120. return;
  121. }
  122. // Convert facet ids to numbers
  123. var facetIds = _.map(_.keys(results.facets),function(k){return parseInt(k, 10);});
  124. // Make sure we're still on the same query/queries
  125. if($scope.query_id === query_id &&
  126. _.intersection(facetIds,querySrv.ids).length === querySrv.ids.length
  127. ) {
  128. var i = 0;
  129. var data, hits;
  130. _.each(querySrv.ids, function(id) {
  131. var v = results.facets[id];
  132. // Null values at each end of the time range ensure we see entire range
  133. if(_.isUndefined($scope.data[i]) || _segment === 0) {
  134. data = [];
  135. if(filterSrv.idsByType('time').length > 0) {
  136. data = [[_range.from.getTime(), null],[_range.to.getTime(), null]];
  137. }
  138. hits = 0;
  139. } else {
  140. data = $scope.data[i].data;
  141. hits = $scope.data[i].hits;
  142. }
  143. // Assemble segments
  144. var segment_data = [];
  145. _.each(v.entries, function(v, k) {
  146. segment_data.push([v.time,v[$scope.panel.mode]]);
  147. hits += v.count; // The series level hits counter
  148. $scope.hits += v.count; // Entire dataset level hits counter
  149. });
  150. data.splice.apply(data,[1,0].concat(segment_data)); // Join histogram data
  151. // Create the flot series object
  152. var series = {
  153. data: {
  154. info: querySrv.list[id],
  155. data: data,
  156. hits: hits
  157. },
  158. };
  159. $scope.data[i] = series.data;
  160. i++;
  161. });
  162. // Tell the histogram directive to render.
  163. $scope.$emit('render');
  164. // If we still have segments left, get them
  165. if(_segment < dashboard.indices.length-1) {
  166. $scope.get_data(_segment+1,query_id);
  167. }
  168. }
  169. });
  170. };
  171. // function $scope.zoom
  172. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  173. $scope.zoom = function(factor) {
  174. var _now = Date.now();
  175. var _range = filterSrv.timeRange('min');
  176. var _timespan = (_range.to.valueOf() - _range.from.valueOf());
  177. var _center = _range.to.valueOf() - _timespan/2;
  178. var _to = (_center + (_timespan*factor)/2);
  179. var _from = (_center - (_timespan*factor)/2);
  180. // If we're not already looking into the future, don't.
  181. if(_to > Date.now() && _range.to < Date.now()) {
  182. var _offset = _to - Date.now();
  183. _from = _from - _offset;
  184. _to = Date.now();
  185. }
  186. if(factor > 1) {
  187. filterSrv.removeByType('time');
  188. }
  189. filterSrv.set({
  190. type:'time',
  191. from:moment.utc(_from),
  192. to:moment.utc(_to),
  193. field:$scope.panel.time_field
  194. });
  195. dashboard.refresh();
  196. };
  197. // I really don't like this function, too much dom manip. Break out into directive?
  198. $scope.populate_modal = function(request) {
  199. $scope.modal = {
  200. title: "Inspector",
  201. body : "<h5>Last Elasticsearch Query</h5><pre>"+
  202. 'curl -XGET '+config.elasticsearch+'/'+dashboard.indices+"/_search?pretty -d'\n"+
  203. angular.toJson(JSON.parse(request.toString()),true)+
  204. "'</pre>",
  205. };
  206. };
  207. $scope.set_refresh = function (state) {
  208. $scope.refresh = state;
  209. };
  210. $scope.close_edit = function() {
  211. if($scope.refresh) {
  212. $scope.get_data();
  213. }
  214. $scope.refresh = false;
  215. $scope.$emit('render');
  216. };
  217. })
  218. .directive('histogramChart', function(dashboard, eventBus, filterSrv, $rootScope) {
  219. return {
  220. restrict: 'A',
  221. template: '<div></div>',
  222. link: function(scope, elem, attrs, ctrl) {
  223. // Receive render events
  224. scope.$on('render',function(){
  225. render_panel();
  226. });
  227. // Re-render if the window is resized
  228. angular.element(window).bind('resize', function(){
  229. render_panel();
  230. });
  231. // Function for rendering panel
  232. function render_panel() {
  233. // IE doesn't work without this
  234. elem.css({height:scope.panel.height||scope.row.height});
  235. // Populate from the query service
  236. try {
  237. _.each(scope.data,function(series) {
  238. series.label = series.info.alias;
  239. series.color = series.info.color;
  240. });
  241. } catch(e) {return;}
  242. // Set barwidth based on specified interval
  243. var barwidth = kbn.interval_to_seconds(scope.panel.interval)*1000;
  244. var scripts = $LAB.script("common/lib/panels/jquery.flot.js").wait()
  245. .script("common/lib/panels/jquery.flot.time.js")
  246. .script("common/lib/panels/jquery.flot.stack.js")
  247. .script("common/lib/panels/jquery.flot.selection.js")
  248. .script("common/lib/panels/timezone.js");
  249. // Populate element. Note that jvectormap appends, does not replace.
  250. scripts.wait(function(){
  251. var stack = scope.panel.stack ? true : null;
  252. // Populate element
  253. try {
  254. var options = {
  255. legend: { show: false },
  256. series: {
  257. stackpercent: scope.panel.stack ? scope.panel.percentage : false,
  258. stack: scope.panel.percentage ? null : stack,
  259. lines: {
  260. show: scope.panel.lines,
  261. fill: scope.panel.fill/10,
  262. lineWidth: scope.panel.linewidth,
  263. steps: false
  264. },
  265. bars: { show: scope.panel.bars, fill: 1, barWidth: barwidth/1.8 },
  266. points: { show: scope.panel.points, fill: 1, fillColor: false, radius: 5},
  267. shadowSize: 1
  268. },
  269. yaxis: {
  270. show: scope.panel['y-axis'],
  271. min: 0,
  272. max: scope.panel.percentage && scope.panel.stack ? 100 : null,
  273. color: "#c8c8c8"
  274. },
  275. xaxis: {
  276. timezone: scope.panel.timezone,
  277. show: scope.panel['x-axis'],
  278. mode: "time",
  279. timeformat: time_format(scope.panel.interval),
  280. label: "Datetime",
  281. color: "#c8c8c8",
  282. },
  283. grid: {
  284. backgroundColor: null,
  285. borderWidth: 0,
  286. borderColor: '#eee',
  287. color: "#eee",
  288. hoverable: true,
  289. },
  290. colors: ['#86B22D','#BF6730','#1D7373','#BFB930','#BF3030','#77207D']
  291. };
  292. if(scope.panel.interactive) {
  293. options.selection = { mode: "x", color: '#aaa' };
  294. }
  295. scope.plot = $.plot(elem, scope.data, options);
  296. // Work around for missing legend at initialization.
  297. if(!scope.$$phase) {
  298. scope.$apply();
  299. }
  300. } catch(e) {
  301. elem.text(e);
  302. }
  303. });
  304. }
  305. function time_format(interval) {
  306. var _int = kbn.interval_to_seconds(interval);
  307. if(_int >= 2628000) {
  308. return "%m/%y";
  309. }
  310. if(_int >= 86400) {
  311. return "%m/%d/%y";
  312. }
  313. if(_int >= 60) {
  314. return "%H:%M<br>%m/%d";
  315. }
  316. return "%H:%M:%S";
  317. }
  318. function tt(x, y, contents) {
  319. // If the tool tip already exists, don't recreate it, just update it
  320. var tooltip = $('#pie-tooltip').length ?
  321. $('#pie-tooltip') : $('<div id="pie-tooltip"></div>');
  322. tooltip.html(contents).css({
  323. position: 'absolute',
  324. top : y + 5,
  325. left : x + 5,
  326. color : "#c8c8c8",
  327. padding : '10px',
  328. 'font-size': '11pt',
  329. 'font-weight' : 200,
  330. 'background-color': '#1f1f1f',
  331. 'border-radius': '5px',
  332. }).appendTo("body");
  333. }
  334. elem.bind("plothover", function (event, pos, item) {
  335. if (item) {
  336. tt(pos.pageX, pos.pageY,
  337. "<div style='vertical-align:middle;display:inline-block;background:"+
  338. item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  339. item.datapoint[1].toFixed(0) + " @ " +
  340. moment(item.datapoint[0]).format('MM/DD HH:mm:ss'));
  341. } else {
  342. $("#pie-tooltip").remove();
  343. }
  344. });
  345. elem.bind("plotselected", function (event, ranges) {
  346. var _id = filterSrv.set({
  347. type : 'time',
  348. from : moment.utc(ranges.xaxis.from),
  349. to : moment.utc(ranges.xaxis.to),
  350. field : scope.panel.time_field
  351. });
  352. dashboard.refresh();
  353. });
  354. }
  355. };
  356. });