module.js 12 KB

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