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. ### Group Events
  33. #### Receives
  34. * time :: An object containing the time range to use and the index(es) to query
  35. * query :: An Array of queries, even if its only one
  36. #### Sends
  37. * get_time :: On panel initialization get time range to query
  38. */
  39. angular.module('kibana.histogram', [])
  40. .controller('histogram', function($scope, eventBus, query, dashboard, filterSrv) {
  41. // Set and populate defaults
  42. var _d = {
  43. status : "Stable",
  44. group : "default",
  45. query : [ {query: "*", label:"Query"} ],
  46. mode : 'count',
  47. time_field : '@timestamp',
  48. value_field : null,
  49. auto_int : true,
  50. resolution : 100,
  51. interval : '5m',
  52. fill : 3,
  53. linewidth : 3,
  54. timezone : 'browser', // browser, utc or a standard timezone
  55. spyable : true,
  56. zoomlinks : true,
  57. bars : true,
  58. stack : true,
  59. points : false,
  60. lines : false,
  61. legend : true,
  62. 'x-axis' : true,
  63. 'y-axis' : true,
  64. percentage : false,
  65. interactive : true,
  66. }
  67. _.defaults($scope.panel,_d)
  68. $scope.init = function() {
  69. $scope.queries = query;
  70. $scope.$on('refresh',function(){
  71. $scope.get_data();
  72. })
  73. }
  74. $scope.get_data = function(segment,query_id) {
  75. delete $scope.panel.error
  76. // Make sure we have everything for the request to complete
  77. if(dashboard.indices.length == 0) {
  78. return
  79. }
  80. var _range = $scope.range = filterSrv.timeRange('min');
  81. if ($scope.panel.auto_int)
  82. $scope.panel.interval = secondsToHms(calculate_interval(_range.from,_range.to,$scope.panel.resolution,0)/1000);
  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($scope.queries.ids, function(id) {
  88. var query = $scope.ejs.FilteredQuery(
  89. ejs.QueryStringQuery($scope.queries.list[id].query || '*'),
  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);})
  124. // Make sure we're still on the same query/queries
  125. if($scope.query_id === query_id &&
  126. _.intersection(facetIds,query.ids).length == query.ids.length
  127. ) {
  128. var i = 0;
  129. _.each(query.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. var data = [[_range.from.getTime(), null],[_range.to.getTime(), null]];
  134. var hits = 0;
  135. } else {
  136. var data = $scope.data[i].data
  137. var hits = $scope.data[i].hits
  138. }
  139. // Assemble segments
  140. var segment_data = [];
  141. _.each(v.entries, function(v, k) {
  142. segment_data.push([v['time'],v[$scope.panel.mode]])
  143. hits += v['count']; // The series level hits counter
  144. $scope.hits += v['count']; // Entire dataset level hits counter
  145. });
  146. data.splice.apply(data,[1,0].concat(segment_data)) // Join histogram data
  147. // Create the flot series object
  148. var series = {
  149. data: {
  150. info: $scope.queries.list[id],
  151. data: data,
  152. hits: hits
  153. },
  154. };
  155. $scope.data[i] = series.data
  156. i++;
  157. });
  158. // Tell the histogram directive to render.
  159. $scope.$emit('render')
  160. // If we still have segments left, get them
  161. if(_segment < dashboard.indices.length-1) {
  162. $scope.get_data(_segment+1,query_id)
  163. }
  164. }
  165. });
  166. }
  167. // function $scope.zoom
  168. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  169. $scope.zoom = function(factor) {
  170. var _now = Date.now();
  171. var _range = filterSrv.timeRange('min');
  172. var _timespan = (_range.to.valueOf() - _range.from.valueOf());
  173. var _center = _range.to.valueOf() - _timespan/2
  174. var _to = (_center + (_timespan*factor)/2)
  175. var _from = (_center - (_timespan*factor)/2)
  176. // If we're not already looking into the future, don't.
  177. if(_to > Date.now() && _range.to < Date.now()) {
  178. var _offset = _to - Date.now()
  179. _from = _from - _offset
  180. _to = Date.now();
  181. }
  182. if(factor > 1) {
  183. filterSrv.removeByType('time')
  184. }
  185. filterSrv.set({
  186. type:'time',
  187. from:moment.utc(_from),
  188. to:moment.utc(_to),
  189. field:$scope.panel.time_field
  190. })
  191. dashboard.refresh();
  192. }
  193. // I really don't like this function, too much dom manip. Break out into directive?
  194. $scope.populate_modal = function(request) {
  195. $scope.modal = {
  196. title: "Inspector",
  197. body : "<h5>Last Elasticsearch Query</h5><pre>"+
  198. 'curl -XGET '+config.elasticsearch+'/'+$scope.index+"/_search?pretty -d'\n"+
  199. angular.toJson(JSON.parse(request.toString()),true)+
  200. "'</pre>",
  201. }
  202. }
  203. $scope.set_refresh = function (state) {
  204. $scope.refresh = state;
  205. }
  206. $scope.close_edit = function() {
  207. if($scope.refresh)
  208. $scope.get_data();
  209. $scope.refresh = false;
  210. $scope.$emit('render');
  211. }
  212. })
  213. .directive('histogramChart', function(dashboard, eventBus, filterSrv, $rootScope) {
  214. return {
  215. restrict: 'A',
  216. link: function(scope, elem, attrs, ctrl) {
  217. // Receive render events
  218. scope.$on('render',function(){
  219. render_panel();
  220. });
  221. // Re-render if the window is resized
  222. angular.element(window).bind('resize', function(){
  223. render_panel();
  224. });
  225. // Function for rendering panel
  226. function render_panel() {
  227. // Populate from the query service
  228. try {
  229. _.each(scope.data,function(series) {
  230. series.label = series.info.alias,
  231. series.color = series.info.color
  232. })
  233. } catch(e) {return}
  234. // Set barwidth based on specified interval
  235. var barwidth = interval_to_seconds(scope.panel.interval)*1000
  236. var scripts = $LAB.script("common/lib/panels/jquery.flot.js").wait()
  237. .script("common/lib/panels/jquery.flot.time.js")
  238. .script("common/lib/panels/jquery.flot.stack.js")
  239. .script("common/lib/panels/jquery.flot.selection.js")
  240. .script("common/lib/panels/timezone.js")
  241. // Populate element. Note that jvectormap appends, does not replace.
  242. scripts.wait(function(){
  243. var stack = scope.panel.stack ? true : null;
  244. // Populate element
  245. try {
  246. var options = {
  247. legend: { show: false },
  248. series: {
  249. stackpercent: scope.panel.stack ? scope.panel.percentage : false,
  250. stack: scope.panel.percentage ? null : stack,
  251. lines: {
  252. show: scope.panel.lines,
  253. fill: scope.panel.fill/10,
  254. lineWidth: scope.panel.linewidth,
  255. steps: false
  256. },
  257. bars: { show: scope.panel.bars, fill: 1, barWidth: barwidth/1.8 },
  258. points: { show: scope.panel.points, fill: 1, fillColor: false, radius: 5},
  259. shadowSize: 1
  260. },
  261. yaxis: {
  262. show: scope.panel['y-axis'],
  263. min: 0,
  264. max: scope.panel.percentage && scope.panel.stack ? 100 : null,
  265. color: "#c8c8c8"
  266. },
  267. xaxis: {
  268. timezone: scope.panel.timezone,
  269. show: scope.panel['x-axis'],
  270. mode: "time",
  271. timeformat: time_format(scope.panel.interval),
  272. label: "Datetime",
  273. color: "#c8c8c8",
  274. },
  275. grid: {
  276. backgroundColor: null,
  277. borderWidth: 0,
  278. borderColor: '#eee',
  279. color: "#eee",
  280. hoverable: true,
  281. },
  282. colors: ['#86B22D','#BF6730','#1D7373','#BFB930','#BF3030','#77207D']
  283. }
  284. if(scope.panel.interactive)
  285. options.selection = { mode: "x", color: '#aaa' };
  286. scope.plot = $.plot(elem, scope.data, options)
  287. // Work around for missing legend at initialization
  288. if(!scope.$$phase)
  289. scope.$apply()
  290. } catch(e) {
  291. elem.text(e)
  292. }
  293. })
  294. }
  295. function time_format(interval) {
  296. var _int = interval_to_seconds(interval)
  297. if(_int >= 2628000)
  298. return "%m/%y"
  299. if(_int >= 86400)
  300. return "%m/%d/%y"
  301. if(_int >= 60)
  302. return "%H:%M<br>%m/%d"
  303. else
  304. return "%H:%M:%S"
  305. }
  306. function tt(x, y, contents) {
  307. // If the tool tip already exists, don't recreate it, just update it
  308. var tooltip = $('#pie-tooltip').length ?
  309. $('#pie-tooltip') : $('<div id="pie-tooltip"></div>');
  310. tooltip.html(contents).css({
  311. position: 'absolute',
  312. top : y + 5,
  313. left : x + 5,
  314. color : "#c8c8c8",
  315. padding : '10px',
  316. 'font-size': '11pt',
  317. 'font-weight' : 200,
  318. 'background-color': '#1f1f1f',
  319. 'border-radius': '5px',
  320. }).appendTo("body");
  321. }
  322. elem.bind("plothover", function (event, pos, item) {
  323. if (item) {
  324. tt(pos.pageX, pos.pageY,
  325. "<div style='vertical-align:middle;display:inline-block;background:"+
  326. item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  327. item.datapoint[1].toFixed(0) + " @ " +
  328. moment(item.datapoint[0]).format('MM/DD HH:mm:ss'));
  329. } else {
  330. $("#pie-tooltip").remove();
  331. }
  332. });
  333. elem.bind("plotselected", function (event, ranges) {
  334. var _id = filterSrv.set({
  335. type : 'time',
  336. from : moment.utc(ranges.xaxis.from),
  337. to : moment.utc(ranges.xaxis.to),
  338. field : scope.panel.time_field
  339. })
  340. dashboard.refresh();
  341. });
  342. }
  343. };
  344. })