module.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. ### Group Events
  32. #### Receives
  33. * time :: An object containing the time range to use and the index(es) to query
  34. * query :: An Array of queries, even if its only one
  35. #### Sends
  36. * get_time :: On panel initialization get time range to query
  37. */
  38. angular.module('kibana.histogram', [])
  39. .controller('histogram', function($scope, eventBus) {
  40. // Set and populate defaults
  41. var _d = {
  42. group : "default",
  43. query : [ {query: "*", label:"Query"} ],
  44. mode : 'count',
  45. value_field : null,
  46. auto_int : true,
  47. resolution : 100,
  48. interval : '5m',
  49. fill : 3,
  50. linewidth : 3,
  51. timezone : 'browser', // browser, utc or a standard timezone
  52. spyable : true,
  53. zoomlinks : true,
  54. bars : true,
  55. stack : true,
  56. points : false,
  57. lines : false,
  58. legend : true,
  59. 'x-axis' : true,
  60. 'y-axis' : true,
  61. }
  62. _.defaults($scope.panel,_d)
  63. $scope.init = function() {
  64. eventBus.register($scope,'time', function(event,time){$scope.set_time(time)});
  65. // Consider eliminating the check for array, this should always be an array
  66. eventBus.register($scope,'query', function(event, query) {
  67. if(_.isArray(query)) {
  68. $scope.panel.query = _.map(query,function(q) {
  69. return {query: q, label: q};
  70. })
  71. } else {
  72. $scope.panel.query[0] = {query: query, label: query}
  73. }
  74. $scope.get_data();
  75. });
  76. // Now that we're all setup, request the time from our group if we don't
  77. // have it yet
  78. if(_.isUndefined($scope.time))
  79. eventBus.broadcast($scope.$id,$scope.panel.group,'get_time')
  80. }
  81. $scope.remove_query = function(q) {
  82. $scope.panel.query = _.without($scope.panel.query,q);
  83. $scope.get_data();
  84. }
  85. $scope.add_query = function(label,query) {
  86. if(!(_.isArray($scope.panel.query)))
  87. $scope.panel.query = new Array();
  88. $scope.panel.query.unshift({
  89. query: query,
  90. label: label,
  91. });
  92. $scope.get_data();
  93. }
  94. $scope.get_data = function(segment,query_id) {
  95. delete $scope.panel.error
  96. // Make sure we have everything for the request to complete
  97. if(_.isUndefined($scope.index) || _.isUndefined($scope.time))
  98. return
  99. if ($scope.panel.auto_int)
  100. $scope.panel.interval = secondsToHms(calculate_interval($scope.time.from,$scope.time.to,$scope.panel.resolution,0)/1000);
  101. $scope.panel.loading = true;
  102. var _segment = _.isUndefined(segment) ? 0 : segment
  103. var request = $scope.ejs.Request().indices($scope.index[_segment]);
  104. // Build the question part of the query
  105. var queries = [];
  106. _.each($scope.panel.query, function(v) {
  107. queries.push($scope.ejs.FilteredQuery(
  108. ejs.QueryStringQuery(v.query || '*'),
  109. ejs.RangeFilter($scope.time.field)
  110. .from($scope.time.from)
  111. .to($scope.time.to))
  112. )
  113. });
  114. // Build the facet part, injecting the query in as a facet filter
  115. _.each(queries, function(v) {
  116. var facet = $scope.ejs.DateHistogramFacet("chart"+_.indexOf(queries,v))
  117. if($scope.panel.mode === 'count') {
  118. facet = facet.field($scope.time.field)
  119. } else {
  120. if(_.isNull($scope.panel.value_field)) {
  121. $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
  122. return
  123. }
  124. facet = facet.keyField($scope.time.field).valueField($scope.panel.value_field)
  125. }
  126. facet = facet.interval($scope.panel.interval).facetFilter($scope.ejs.QueryFilter(v))
  127. request = request.facet(facet).size(0)
  128. })
  129. // Populate the inspector panel
  130. $scope.populate_modal(request);
  131. // Then run it
  132. var results = request.doSearch();
  133. // Populate scope when we have results
  134. results.then(function(results) {
  135. $scope.panel.loading = false;
  136. if(_segment == 0) {
  137. $scope.hits = 0;
  138. $scope.data = [];
  139. query_id = $scope.query_id = new Date().getTime();
  140. }
  141. // Check for error and abort if found
  142. if(!(_.isUndefined(results.error))) {
  143. $scope.panel.error = $scope.parse_error(results.error);
  144. return;
  145. }
  146. // Make sure we're still on the same query
  147. if($scope.query_id === query_id) {
  148. var i = 0;
  149. _.each(results.facets, function(v, k) {
  150. // Null values at each end of the time range ensure we see entire range
  151. if(_.isUndefined($scope.data[i]) || _segment == 0) {
  152. var data = [[$scope.time.from.getTime(), null],[$scope.time.to.getTime(), null]];
  153. var hits = 0;
  154. } else {
  155. var data = $scope.data[i].data
  156. var hits = $scope.data[i].hits
  157. }
  158. // Assemble segments
  159. var segment_data = [];
  160. _.each(v.entries, function(v, k) {
  161. segment_data.push([v['time'],v[$scope.panel.mode]])
  162. hits += v['count']; // The series level hits counter
  163. $scope.hits += v['count']; // Entire dataset level hits counter
  164. });
  165. data.splice.apply(data,[1,0].concat(segment_data)) // Join histogram data
  166. // Create the flot series object
  167. var series = {
  168. data: {
  169. label: $scope.panel.query[i].label || "query"+(parseInt(i)+1),
  170. data: data,
  171. hits: hits
  172. },
  173. };
  174. if (!(_.isUndefined($scope.panel.query[i].color)))
  175. series.data.color = $scope.panel.query[i].color;
  176. $scope.data[i] = series.data
  177. i++;
  178. });
  179. // Tell the histogram directive to render.
  180. $scope.$emit('render')
  181. // If we still have segments left, get them
  182. if(_segment < $scope.index.length-1) {
  183. $scope.get_data(_segment+1,query_id)
  184. }
  185. }
  186. });
  187. }
  188. // function $scope.zoom
  189. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  190. $scope.zoom = function(factor) {
  191. eventBus.broadcast($scope.$id,$scope.panel.group,'zoom',factor);
  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. $scope.set_time = function(time) {
  213. $scope.time = time;
  214. // Should I be storing the index on the panel? It causes errors if the index
  215. // goes away. Hmmm.
  216. $scope.index = time.index || $scope.index
  217. // Only calculate interval if auto_int is set, otherwise don't touch it
  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")
  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. scope.plot = $.plot(elem, scope.data, {
  248. legend: { show: false },
  249. series: {
  250. stack: 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: { show: scope.panel['y-axis'], min: 0, color: "#000" },
  262. xaxis: {
  263. timezone: scope.panel.timezone,
  264. show: scope.panel['x-axis'],
  265. mode: "time",
  266. timeformat: time_format(scope.panel.interval),
  267. label: "Datetime",
  268. color: "#000",
  269. },
  270. selection: {
  271. mode: "x",
  272. color: '#ccc'
  273. },
  274. grid: {
  275. backgroundColor: '#fff',
  276. borderWidth: 0,
  277. borderColor: '#eee',
  278. color: "#eee",
  279. hoverable: true,
  280. },
  281. colors: ['#86B22D','#BF6730','#1D7373','#BFB930','#BF3030','#77207D']
  282. })
  283. // Work around for missing legend at initialization
  284. if(!scope.$$phase)
  285. scope.$apply()
  286. } catch(e) {
  287. elem.text(e)
  288. }
  289. })
  290. }
  291. function time_format(interval) {
  292. var _int = interval_to_seconds(interval)
  293. if(_int >= 2628000)
  294. return "%m/%y"
  295. if(_int >= 86400)
  296. return "%m/%d/%y"
  297. if(_int >= 60)
  298. return "%H:%M<br>%m/%d"
  299. else
  300. return "%H:%M:%S"
  301. }
  302. function tt(x, y, contents) {
  303. // If the tool tip already exists, don't recreate it, just update it
  304. var tooltip = $('#pie-tooltip').length ?
  305. $('#pie-tooltip') : $('<div id="pie-tooltip"></div>');
  306. tooltip.html(contents).css({
  307. position: 'absolute',
  308. top : y + 5,
  309. left : x + 5,
  310. color : "#000",
  311. border : '1px solid #000',
  312. padding : '10px',
  313. 'font-size': '11pt',
  314. 'font-weight' : 200,
  315. 'background-color': '#FFF',
  316. 'border-radius': '10px',
  317. }).appendTo("body");
  318. }
  319. elem.bind("plothover", function (event, pos, item) {
  320. if (item) {
  321. tt(pos.pageX, pos.pageY,
  322. "<div style='vertical-align:middle;display:inline-block;background:"+item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  323. item.datapoint[1].toFixed(0) + " @ " +
  324. new Date(item.datapoint[0]).format('mm/dd HH:MM:ss'));
  325. } else {
  326. $("#pie-tooltip").remove();
  327. }
  328. });
  329. elem.bind("plotselected", function (event, ranges) {
  330. scope.time.from = new Date(ranges.xaxis.from);
  331. scope.time.to = new Date(ranges.xaxis.to)
  332. eventBus.broadcast(scope.$id,scope.panel.group,'set_time',scope.time)
  333. });
  334. }
  335. };
  336. })