module.js 13 KB

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