module.js 13 KB

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