module.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. * interval :: Generated automatically. Tells ES how to bucket the data points
  11. * fill :: Only applies to line charts. Level of area shading from 0-10
  12. * linewidth :: Only applies to line charts. How thick the line should be in pixels
  13. While the editor only exposes 0-10, this can be any numeric value.
  14. Set to 0 and you'll get something like a scatter plot
  15. * timezone :: This isn't totally functional yet. Currently only supports browser and utc.
  16. browser will adjust the x-axis labels to match the timezone of the user's
  17. browser
  18. * spyable :: Dislay the 'eye' icon that show the last elasticsearch query
  19. * zoomlinks :: Show the zoom links?
  20. * bars :: Show bars in the chart
  21. * stack :: Stack multiple queries. This generally a crappy way to represent things.
  22. You probably should just use a line chart without stacking
  23. * points :: Should circles at the data points on the chart
  24. * lines :: Line chart? Sweet.
  25. * legend :: Show the legend?
  26. * x-axis :: Show x-axis labels and grid lines
  27. * y-axis :: Show y-axis labels and grid lines
  28. ### Group Events
  29. #### Receives
  30. * time :: An object containing the time range to use and the index(es) to query
  31. * query :: An Array of queries, even if its only one
  32. #### Sends
  33. * get_time :: On panel initialization get time range to query
  34. */
  35. angular.module('kibana.histogram', [])
  36. .controller('histogram', function($scope, eventBus) {
  37. // Set and populate defaults
  38. var _d = {
  39. group : "default",
  40. query : [ {query: "*", label:"Query"} ],
  41. interval : secondsToHms(calculate_interval($scope.from,$scope.to,40,0)/1000),
  42. fill : 3,
  43. linewidth : 3,
  44. timezone : 'browser', // browser, utc or a standard timezone
  45. spyable : true,
  46. zoomlinks : true,
  47. bars : true,
  48. stack : true,
  49. points : false,
  50. lines : false,
  51. legend : true,
  52. 'x-axis' : true,
  53. 'y-axis' : true,
  54. }
  55. _.defaults($scope.panel,_d)
  56. $scope.init = function() {
  57. eventBus.register($scope,'time', function(event,time){$scope.set_time(time)});
  58. // Consider eliminating the check for array, this should always be an array
  59. eventBus.register($scope,'query', function(event, query) {
  60. if(_.isArray(query)) {
  61. $scope.panel.query = _.map(query,function(q) {
  62. return {query: q, label: q};
  63. })
  64. } else {
  65. $scope.panel.query[0] = {query: query, label: query}
  66. }
  67. $scope.get_data();
  68. });
  69. // Now that we're all setup, request the time from our group if we don't
  70. // have it yet
  71. if(_.isUndefined($scope.time))
  72. eventBus.broadcast($scope.$id,$scope.panel.group,'get_time')
  73. }
  74. $scope.remove_query = function(q) {
  75. $scope.panel.query = _.without($scope.panel.query,q);
  76. $scope.get_data();
  77. }
  78. $scope.add_query = function(label,query) {
  79. if(!(_.isArray($scope.panel.query)))
  80. $scope.panel.query = new Array();
  81. $scope.panel.query.unshift({
  82. query: query,
  83. label: label,
  84. });
  85. $scope.get_data();
  86. }
  87. $scope.get_data = function(segment,query_id) {
  88. delete $scope.panel.error
  89. // Make sure we have everything for the request to complete
  90. if(_.isUndefined($scope.panel.index) || _.isUndefined($scope.time))
  91. return
  92. $scope.panel.loading = true;
  93. var _segment = _.isUndefined(segment) ? 0 : segment
  94. var request = $scope.ejs.Request().indices($scope.panel.index[_segment]);
  95. // Build the question part of the query
  96. var queries = [];
  97. _.each($scope.panel.query, function(v) {
  98. queries.push($scope.ejs.FilteredQuery(
  99. ejs.QueryStringQuery(v.query || '*'),
  100. ejs.RangeFilter($scope.time.field)
  101. .from($scope.time.from)
  102. .to($scope.time.to))
  103. )
  104. });
  105. // Build the facet part, injecting the query in as a facet filter
  106. _.each(queries, function(v) {
  107. request = request
  108. .facet($scope.ejs.DateHistogramFacet("chart"+_.indexOf(queries,v))
  109. .field($scope.time.field)
  110. .interval($scope.panel.interval)
  111. .facetFilter($scope.ejs.QueryFilter(v))
  112. ).size(0)
  113. })
  114. // Populate the inspector panel
  115. $scope.populate_modal(request);
  116. // Then run it
  117. var results = request.doSearch();
  118. // Populate scope when we have results
  119. results.then(function(results) {
  120. $scope.panel.loading = false;
  121. if(_segment == 0) {
  122. $scope.hits = 0;
  123. $scope.data = [];
  124. query_id = $scope.query_id = new Date().getTime();
  125. }
  126. // Check for error and abort if found
  127. if(!(_.isUndefined(results.error))) {
  128. $scope.panel.error = $scope.parse_error(results.error);
  129. return;
  130. }
  131. // Make sure we're still on the same query
  132. if($scope.query_id === query_id) {
  133. var i = 0;
  134. _.each(results.facets, function(v, k) {
  135. // Null values at each end of the time range ensure we see entire range
  136. if(_.isUndefined($scope.data[i]) || _segment == 0) {
  137. var data = [[$scope.time.from.getTime(), null],[$scope.time.to.getTime(), null]];
  138. var hits = 0;
  139. } else {
  140. var data = $scope.data[i].data
  141. var 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['count']])
  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. label: $scope.panel.query[i].label || "query"+(parseInt(i)+1),
  155. data: data,
  156. hits: hits
  157. },
  158. };
  159. if (!(_.isUndefined($scope.panel.query[i].color)))
  160. series.data.color = $scope.panel.query[i].color;
  161. $scope.data[i] = series.data
  162. i++;
  163. });
  164. // Tell the histogram directive to render.
  165. $scope.$emit('render')
  166. // If we still have segments left, get them
  167. if(_segment < $scope.panel.index.length-1) {
  168. $scope.get_data(_segment+1,query_id)
  169. }
  170. }
  171. });
  172. }
  173. // function $scope.zoom
  174. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  175. $scope.zoom = function(factor) {
  176. eventBus.broadcast($scope.$id,$scope.panel.group,'zoom',factor)
  177. }
  178. // I really don't like this function, too much dom manip. Break out into directive?
  179. $scope.populate_modal = function(request) {
  180. $scope.modal = {
  181. title: "Inspector",
  182. body : "<h5>Last Elasticsearch Query</h5><pre>"+
  183. 'curl -XGET '+config.elasticsearch+'/'+$scope.panel.index+"/_search?pretty -d'\n"+
  184. angular.toJson(JSON.parse(request.toString()),true)+
  185. "'</pre>",
  186. }
  187. }
  188. $scope.set_time = function(time) {
  189. $scope.time = time;
  190. $scope.panel.index = _.isUndefined(time.index) ? $scope.panel.index : time.index
  191. $scope.panel.interval = secondsToHms(
  192. calculate_interval(time.from,time.to,50,0)/1000);
  193. $scope.get_data();
  194. }
  195. })
  196. .directive('histogramChart', function(eventBus) {
  197. return {
  198. restrict: 'A',
  199. link: function(scope, elem, attrs, ctrl) {
  200. var height = scope.panel.height || scope.row.height;
  201. // Receive render events
  202. scope.$on('render',function(){
  203. render_panel();
  204. });
  205. // Re-render if the window is resized
  206. angular.element(window).bind('resize', function(){
  207. render_panel();
  208. });
  209. // Function for rendering panel
  210. function render_panel() {
  211. // Set barwidth based on specified interval
  212. var barwidth = interval_to_seconds(scope.panel.interval)*1000
  213. var scripts = $LAB.script("common/lib/panels/jquery.flot.js")
  214. .script("common/lib/panels/jquery.flot.time.js")
  215. .script("common/lib/panels/jquery.flot.stack.js")
  216. .script("common/lib/panels/jquery.flot.selection.js")
  217. .script("common/lib/panels/timezone.js")
  218. // Populate element. Note that jvectormap appends, does not replace.
  219. scripts.wait(function(){
  220. var stack = scope.panel.stack ? true : null;
  221. // Populate element
  222. try {
  223. scope.plot = $.plot(elem, scope.data, {
  224. legend: { show: false },
  225. series: {
  226. stack: stack,
  227. lines: {
  228. show: scope.panel.lines,
  229. fill: scope.panel.fill/10,
  230. lineWidth: scope.panel.linewidth,
  231. steps: false
  232. },
  233. bars: { show: scope.panel.bars, fill: 1, barWidth: barwidth/1.8 },
  234. points: { show: scope.panel.points, fill: 1, fillColor: false, radius: 5},
  235. shadowSize: 1
  236. },
  237. yaxis: { show: scope.panel['y-axis'], min: 0, color: "#000" },
  238. xaxis: {
  239. timezone: scope.panel.timezone,
  240. show: scope.panel['x-axis'],
  241. mode: "time",
  242. timeformat: time_format(scope.panel.interval),
  243. label: "Datetime",
  244. color: "#000",
  245. },
  246. selection: {
  247. mode: "x",
  248. color: '#999'
  249. },
  250. grid: {
  251. backgroundColor: '#fff',
  252. borderWidth: 0,
  253. borderColor: '#eee',
  254. color: "#eee",
  255. hoverable: true,
  256. },
  257. colors: ['#86B22D','#BF6730','#1D7373','#BFB930','#BF3030','#77207D']
  258. })
  259. // Work around for missing legend at initialization
  260. if(!scope.$$phase)
  261. scope.$apply()
  262. } catch(e) {
  263. elem.text(e)
  264. }
  265. })
  266. }
  267. function time_format(interval) {
  268. var _int = interval_to_seconds(interval)
  269. if(_int >= 2628000)
  270. return "%m/%y"
  271. if(_int >= 86400)
  272. return "%m/%d/%y"
  273. if(_int >= 60)
  274. return "%H:%M<br>%m/%d"
  275. else
  276. return "%H:%M:%S"
  277. }
  278. function tt(x, y, contents) {
  279. var tooltip = $('#pie-tooltip').length ?
  280. $('#pie-tooltip') : $('<div id="pie-tooltip"></div>');
  281. //var tooltip = $('#pie-tooltip')
  282. tooltip.html(contents).css({
  283. position: 'absolute',
  284. top : y + 5,
  285. left : x + 5,
  286. color : "#000",
  287. border : '2px solid #000',
  288. padding : '10px',
  289. 'font-size': '11pt',
  290. 'font-weight' : 200,
  291. 'background-color': '#FFF',
  292. 'border-radius': '10px',
  293. }).appendTo("body");
  294. }
  295. elem.bind("plothover", function (event, pos, item) {
  296. if (item) {
  297. tt(pos.pageX, pos.pageY,
  298. "<div style='vertical-align:middle;display:inline-block;background:"+item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  299. item.datapoint[1].toFixed(0) + " @ " +
  300. new Date(item.datapoint[0]).format('mm/dd HH:MM:ss'));
  301. } else {
  302. $("#pie-tooltip").remove();
  303. }
  304. });
  305. elem.bind("plotselected", function (event, ranges) {
  306. scope.time.from = new Date(ranges.xaxis.from);
  307. scope.time.to = new Date(ranges.xaxis.to)
  308. eventBus.broadcast(scope.$id,scope.panel.group,'set_time',scope.time)
  309. });
  310. }
  311. };
  312. })