module.js 13 KB

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