module.js 12 KB

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