module.js 13 KB

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