module.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. $scope.index = time.index || $scope.index
  215. $scope.get_data();
  216. }
  217. })
  218. .directive('histogramChart', function(eventBus) {
  219. return {
  220. restrict: 'A',
  221. link: function(scope, elem, attrs, ctrl) {
  222. // Receive render events
  223. scope.$on('render',function(){
  224. render_panel();
  225. });
  226. // Re-render if the window is resized
  227. angular.element(window).bind('resize', function(){
  228. render_panel();
  229. });
  230. // Function for rendering panel
  231. function render_panel() {
  232. // Set barwidth based on specified interval
  233. var barwidth = interval_to_seconds(scope.panel.interval)*1000
  234. var scripts = $LAB.script("common/lib/panels/jquery.flot.js")
  235. .script("common/lib/panels/jquery.flot.time.js")
  236. .script("common/lib/panels/jquery.flot.stack.js")
  237. .script("common/lib/panels/jquery.flot.selection.js")
  238. .script("common/lib/panels/timezone.js")
  239. // Populate element. Note that jvectormap appends, does not replace.
  240. scripts.wait(function(){
  241. var stack = scope.panel.stack ? true : null;
  242. // Populate element
  243. try {
  244. scope.plot = $.plot(elem, scope.data, {
  245. legend: { show: false },
  246. series: {
  247. stack: stack,
  248. lines: {
  249. show: scope.panel.lines,
  250. fill: scope.panel.fill/10,
  251. lineWidth: scope.panel.linewidth,
  252. steps: false
  253. },
  254. bars: { show: scope.panel.bars, fill: 1, barWidth: barwidth/1.8 },
  255. points: { show: scope.panel.points, fill: 1, fillColor: false, radius: 5},
  256. shadowSize: 1
  257. },
  258. yaxis: { show: scope.panel['y-axis'], min: 0, color: "#c8c8c8" },
  259. xaxis: {
  260. timezone: scope.panel.timezone,
  261. show: scope.panel['x-axis'],
  262. mode: "time",
  263. timeformat: time_format(scope.panel.interval),
  264. label: "Datetime",
  265. color: "#c8c8c8",
  266. },
  267. selection: {
  268. mode: "x",
  269. color: '#ccc'
  270. },
  271. grid: {
  272. backgroundColor: '#272b30',
  273. borderWidth: 0,
  274. borderColor: '#eee',
  275. color: "#eee",
  276. hoverable: true,
  277. },
  278. colors: ['#86B22D','#BF6730','#1D7373','#BFB930','#BF3030','#77207D']
  279. })
  280. // Work around for missing legend at initialization
  281. if(!scope.$$phase)
  282. scope.$apply()
  283. } catch(e) {
  284. elem.text(e)
  285. }
  286. })
  287. }
  288. function time_format(interval) {
  289. var _int = interval_to_seconds(interval)
  290. if(_int >= 2628000)
  291. return "%m/%y"
  292. if(_int >= 86400)
  293. return "%m/%d/%y"
  294. if(_int >= 60)
  295. return "%H:%M<br>%m/%d"
  296. else
  297. return "%H:%M:%S"
  298. }
  299. function tt(x, y, contents) {
  300. // If the tool tip already exists, don't recreate it, just update it
  301. var tooltip = $('#pie-tooltip').length ?
  302. $('#pie-tooltip') : $('<div id="pie-tooltip"></div>');
  303. tooltip.html(contents).css({
  304. position: 'absolute',
  305. top : y + 5,
  306. left : x + 5,
  307. color : "#c8c8c8",
  308. padding : '10px',
  309. 'font-size': '11pt',
  310. 'font-weight' : 200,
  311. 'background-color': '#1f1f1f',
  312. 'border-radius': '5px',
  313. }).appendTo("body");
  314. }
  315. elem.bind("plothover", function (event, pos, item) {
  316. if (item) {
  317. tt(pos.pageX, pos.pageY,
  318. "<div style='vertical-align:middle;display:inline-block;background:"+item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  319. item.datapoint[1].toFixed(0) + " @ " +
  320. moment(item.datapoint[0]).format('MM/DD HH:mm:ss'));
  321. } else {
  322. $("#pie-tooltip").remove();
  323. }
  324. });
  325. elem.bind("plotselected", function (event, ranges) {
  326. scope.time.from = moment(ranges.xaxis.from);
  327. scope.time.to = moment(ranges.xaxis.to)
  328. eventBus.broadcast(scope.$id,scope.panel.group,'set_time',scope.time)
  329. });
  330. }
  331. };
  332. })