module.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. * interval :: Datapoint interval in elasticsearch date math format (eg 1d, 1w, 1y, 5y)
  12. * fill :: Only applies to line charts. Level of area shading from 0-10
  13. * linewidth :: Only applies to line charts. How thick the line should be in pixels
  14. While the editor only exposes 0-10, this can be any numeric value.
  15. Set to 0 and you'll get something like a scatter plot
  16. * timezone :: This isn't totally functional yet. Currently only supports browser and utc.
  17. browser will adjust the x-axis labels to match the timezone of the user's
  18. browser
  19. * spyable :: Dislay the 'eye' icon that show the last elasticsearch query
  20. * zoomlinks :: Show the zoom links?
  21. * bars :: Show bars in the chart
  22. * stack :: Stack multiple queries. This generally a crappy way to represent things.
  23. You probably should just use a line chart without stacking
  24. * points :: Should circles at the data points on the chart
  25. * lines :: Line chart? Sweet.
  26. * legend :: Show the legend?
  27. * x-axis :: Show x-axis labels and grid lines
  28. * y-axis :: Show y-axis labels and grid lines
  29. ### Group Events
  30. #### Receives
  31. * time :: An object containing the time range to use and the index(es) to query
  32. * query :: An Array of queries, even if its only one
  33. #### Sends
  34. * get_time :: On panel initialization get time range to query
  35. */
  36. angular.module('kibana.histogram', [])
  37. .controller('histogram', function($scope, eventBus) {
  38. // Set and populate defaults
  39. var _d = {
  40. group : "default",
  41. query : [ {query: "*", label:"Query"} ],
  42. mode : 'count',
  43. value_field: null,
  44. auto_int : true,
  45. interval : '5m',
  46. fill : 3,
  47. linewidth : 3,
  48. timezone : 'browser', // browser, utc or a standard timezone
  49. spyable : true,
  50. zoomlinks : true,
  51. bars : true,
  52. stack : true,
  53. points : false,
  54. lines : false,
  55. legend : true,
  56. 'x-axis' : true,
  57. 'y-axis' : true,
  58. }
  59. _.defaults($scope.panel,_d)
  60. $scope.init = function() {
  61. eventBus.register($scope,'time', function(event,time){$scope.set_time(time)});
  62. // Consider eliminating the check for array, this should always be an array
  63. eventBus.register($scope,'query', function(event, query) {
  64. if(_.isArray(query)) {
  65. $scope.panel.query = _.map(query,function(q) {
  66. return {query: q, label: q};
  67. })
  68. } else {
  69. $scope.panel.query[0] = {query: query, label: query}
  70. }
  71. $scope.get_data();
  72. });
  73. // Now that we're all setup, request the time from our group if we don't
  74. // have it yet
  75. if(_.isUndefined($scope.time))
  76. eventBus.broadcast($scope.$id,$scope.panel.group,'get_time')
  77. }
  78. $scope.remove_query = function(q) {
  79. $scope.panel.query = _.without($scope.panel.query,q);
  80. $scope.get_data();
  81. }
  82. $scope.add_query = function(label,query) {
  83. if(!(_.isArray($scope.panel.query)))
  84. $scope.panel.query = new Array();
  85. $scope.panel.query.unshift({
  86. query: query,
  87. label: label,
  88. });
  89. $scope.get_data();
  90. }
  91. $scope.get_data = function(segment,query_id) {
  92. delete $scope.panel.error
  93. // Make sure we have everything for the request to complete
  94. if(_.isUndefined($scope.index) || _.isUndefined($scope.time))
  95. return
  96. if ($scope.panel.auto_int)
  97. $scope.panel.interval = secondsToHms(calculate_interval($scope.time.from,$scope.time.to,50,0)/1000);
  98. $scope.panel.loading = true;
  99. var _segment = _.isUndefined(segment) ? 0 : segment
  100. var request = $scope.ejs.Request().indices($scope.index[_segment]);
  101. // Build the question part of the query
  102. var queries = [];
  103. _.each($scope.panel.query, function(v) {
  104. queries.push($scope.ejs.FilteredQuery(
  105. ejs.QueryStringQuery(v.query || '*'),
  106. ejs.RangeFilter($scope.time.field)
  107. .from($scope.time.from)
  108. .to($scope.time.to))
  109. )
  110. });
  111. // Build the facet part, injecting the query in as a facet filter
  112. _.each(queries, function(v) {
  113. var facet = $scope.ejs.DateHistogramFacet("chart"+_.indexOf(queries,v))
  114. if($scope.panel.mode === 'count') {
  115. facet = facet.field($scope.time.field)
  116. } else {
  117. if(_.isNull($scope.panel.value_field)) {
  118. $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
  119. return
  120. }
  121. facet = facet.keyField($scope.time.field).valueField($scope.panel.value_field)
  122. }
  123. facet = facet.interval($scope.panel.interval).facetFilter($scope.ejs.QueryFilter(v))
  124. request = request.facet(facet).size(0)
  125. })
  126. // Populate the inspector panel
  127. $scope.populate_modal(request);
  128. // Then run it
  129. var results = request.doSearch();
  130. // Populate scope when we have results
  131. results.then(function(results) {
  132. $scope.panel.loading = false;
  133. if(_segment == 0) {
  134. $scope.hits = 0;
  135. $scope.data = [];
  136. query_id = $scope.query_id = new Date().getTime();
  137. }
  138. // Check for error and abort if found
  139. if(!(_.isUndefined(results.error))) {
  140. $scope.panel.error = $scope.parse_error(results.error);
  141. return;
  142. }
  143. // Make sure we're still on the same query
  144. if($scope.query_id === query_id) {
  145. var i = 0;
  146. _.each(results.facets, function(v, k) {
  147. // Null values at each end of the time range ensure we see entire range
  148. if(_.isUndefined($scope.data[i]) || _segment == 0) {
  149. var data = [[$scope.time.from.getTime(), null],[$scope.time.to.getTime(), null]];
  150. var hits = 0;
  151. } else {
  152. var data = $scope.data[i].data
  153. var hits = $scope.data[i].hits
  154. }
  155. // Assemble segments
  156. var segment_data = [];
  157. _.each(v.entries, function(v, k) {
  158. segment_data.push([v['time'],v[$scope.panel.mode]])
  159. hits += v['count']; // The series level hits counter
  160. $scope.hits += v['count']; // Entire dataset level hits counter
  161. });
  162. data.splice.apply(data,[1,0].concat(segment_data)) // Join histogram data
  163. // Create the flot series object
  164. var series = {
  165. data: {
  166. label: $scope.panel.query[i].label || "query"+(parseInt(i)+1),
  167. data: data,
  168. hits: hits
  169. },
  170. };
  171. if (!(_.isUndefined($scope.panel.query[i].color)))
  172. series.data.color = $scope.panel.query[i].color;
  173. $scope.data[i] = series.data
  174. i++;
  175. });
  176. // Tell the histogram directive to render.
  177. $scope.$emit('render')
  178. // If we still have segments left, get them
  179. if(_segment < $scope.index.length-1) {
  180. $scope.get_data(_segment+1,query_id)
  181. }
  182. }
  183. });
  184. }
  185. // function $scope.zoom
  186. // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
  187. $scope.zoom = function(factor) {
  188. eventBus.broadcast($scope.$id,$scope.panel.group,'zoom',factor);
  189. }
  190. // I really don't like this function, too much dom manip. Break out into directive?
  191. $scope.populate_modal = function(request) {
  192. $scope.modal = {
  193. title: "Inspector",
  194. body : "<h5>Last Elasticsearch Query</h5><pre>"+
  195. 'curl -XGET '+config.elasticsearch+'/'+$scope.index+"/_search?pretty -d'\n"+
  196. angular.toJson(JSON.parse(request.toString()),true)+
  197. "'</pre>",
  198. }
  199. }
  200. $scope.set_refresh = function (state) {
  201. $scope.refresh = state;
  202. }
  203. $scope.close_edit = function() {
  204. if($scope.refresh)
  205. $scope.get_data();
  206. $scope.refresh = false;
  207. $scope.$emit('render');
  208. }
  209. $scope.set_time = function(time) {
  210. $scope.time = time;
  211. // Should I be storing the index on the panel? It causes errors if the index
  212. // goes away. Hmmm.
  213. $scope.index = time.index || $scope.index
  214. // Only calculate interval if auto_int is set, otherwise don't touch it
  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: "#000" },
  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: "#000",
  266. },
  267. selection: {
  268. mode: "x",
  269. color: '#ccc'
  270. },
  271. grid: {
  272. backgroundColor: '#fff',
  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 : "#000",
  308. border : '1px solid #000',
  309. padding : '10px',
  310. 'font-size': '11pt',
  311. 'font-weight' : 200,
  312. 'background-color': '#FFF',
  313. 'border-radius': '10px',
  314. }).appendTo("body");
  315. }
  316. elem.bind("plothover", function (event, pos, item) {
  317. if (item) {
  318. tt(pos.pageX, pos.pageY,
  319. "<div style='vertical-align:middle;display:inline-block;background:"+item.series.color+";height:15px;width:15px;border-radius:10px;'></div> "+
  320. item.datapoint[1].toFixed(0) + " @ " +
  321. new Date(item.datapoint[0]).format('mm/dd HH:MM:ss'));
  322. } else {
  323. $("#pie-tooltip").remove();
  324. }
  325. });
  326. elem.bind("plotselected", function (event, ranges) {
  327. scope.time.from = new Date(ranges.xaxis.from);
  328. scope.time.to = new Date(ranges.xaxis.to)
  329. eventBus.broadcast(scope.$id,scope.panel.group,'set_time',scope.time)
  330. });
  331. }
  332. };
  333. })