module.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. ## Table
  3. ### Parameters
  4. * size :: Number of events per page to show
  5. * pages :: Number of pages to show. size * pages = number of cached events.
  6. Bigger = more memory usage byh the browser
  7. * offset :: Position from which to start in the array of hits
  8. * sort :: An array with 2 elements. sort[0]: field, sort[1]: direction ('asc' or 'desc')
  9. * style :: hash of css properties
  10. * fields :: columns to show in table
  11. * overflow :: 'height' or 'min-height' controls wether the row will expand (min-height) to
  12. to fit the table, or if the table will scroll to fit the row (height)
  13. * trimFactor :: If line is > this many characters, divided by the number of columns, trim it.
  14. * sortable :: Allow sorting?
  15. * spyable :: Show the 'eye' icon that reveals the last ES query for this panel
  16. */
  17. define([
  18. 'angular',
  19. 'app',
  20. 'underscore',
  21. 'kbn',
  22. 'moment',
  23. // 'text!./pagination.html',
  24. // 'text!partials/querySelect.html'
  25. ],
  26. function (angular, app, _, kbn, moment) {
  27. 'use strict';
  28. var module = angular.module('kibana.panels.table', []);
  29. app.useModule(module);
  30. module.controller('table', function($rootScope, $scope, fields, querySrv, dashboard, filterSrv) {
  31. $scope.panelMeta = {
  32. modals : [
  33. {
  34. description: "Inspect",
  35. icon: "icon-info-sign",
  36. partial: "app/partials/inspector.html",
  37. show: $scope.panel.spyable
  38. }
  39. ],
  40. editorTabs : [
  41. {
  42. title:'Paging',
  43. src: 'app/panels/table/pagination.html'
  44. },
  45. {
  46. title:'Queries',
  47. src: 'app/partials/querySelect.html'
  48. }
  49. ],
  50. status: "Stable",
  51. description: "A paginated table of records matching your query or queries. Click on a row to "+
  52. "expand it and review all of the fields associated with that document. <p>"
  53. };
  54. // Set and populate defaults
  55. var _d = {
  56. status : "Stable",
  57. queries : {
  58. mode : 'all',
  59. ids : []
  60. },
  61. size : 100, // Per page
  62. pages : 5, // Pages available
  63. offset : 0,
  64. sort : ['_score','desc'],
  65. group : "default",
  66. style : {'font-size': '9pt'},
  67. overflow: 'min-height',
  68. fields : [],
  69. highlight : [],
  70. sortable: true,
  71. header : true,
  72. paging : true,
  73. field_list: true,
  74. trimFactor: 300,
  75. normTimes : true,
  76. spyable : true
  77. };
  78. _.defaults($scope.panel,_d);
  79. $scope.init = function () {
  80. $scope.Math = Math;
  81. $scope.$on('refresh',function(){$scope.get_data();});
  82. $scope.fields = fields;
  83. $scope.get_data();
  84. };
  85. $scope.percent = kbn.to_percent;
  86. $scope.toggle_micropanel = function(field,groups) {
  87. var docs = _.map($scope.data,function(_d){return _d.kibana._source;});
  88. var topFieldValues = kbn.top_field_values(docs,field,10,groups);
  89. $scope.micropanel = {
  90. field: field,
  91. grouped: groups,
  92. values : topFieldValues.counts,
  93. hasArrays : topFieldValues.hasArrays,
  94. related : kbn.get_related_fields(docs,field),
  95. count: _.countBy(docs,function(doc){return _.contains(_.keys(doc),field);})['true']
  96. };
  97. };
  98. $scope.micropanelColor = function(index) {
  99. var _c = ['bar-success','bar-warning','bar-danger','bar-info','bar-primary'];
  100. return index > _c.length ? '' : _c[index];
  101. };
  102. $scope.set_sort = function(field) {
  103. if($scope.panel.sort[0] === field) {
  104. $scope.panel.sort[1] = $scope.panel.sort[1] === 'asc' ? 'desc' : 'asc';
  105. } else {
  106. $scope.panel.sort[0] = field;
  107. }
  108. $scope.get_data();
  109. };
  110. $scope.toggle_field = function(field) {
  111. if (_.indexOf($scope.panel.fields,field) > -1) {
  112. $scope.panel.fields = _.without($scope.panel.fields,field);
  113. } else {
  114. $scope.panel.fields.push(field);
  115. }
  116. };
  117. $scope.toggle_highlight = function(field) {
  118. if (_.indexOf($scope.panel.highlight,field) > -1) {
  119. $scope.panel.highlight = _.without($scope.panel.highlight,field);
  120. } else {
  121. $scope.panel.highlight.push(field);
  122. }
  123. };
  124. $scope.toggle_details = function(row) {
  125. row.kibana.details = row.kibana.details ? false : true;
  126. row.kibana.view = row.kibana.view || 'table';
  127. //row.kibana.details = !row.kibana.details ? $scope.without_kibana(row) : false;
  128. };
  129. $scope.page = function(page) {
  130. $scope.panel.offset = page*$scope.panel.size;
  131. $scope.get_data();
  132. };
  133. $scope.build_search = function(field,value,negate) {
  134. var query;
  135. // This needs to be abstracted somewhere
  136. if(_.isArray(value)) {
  137. query = "(" + _.map(value,function(v){return angular.toJson(v);}).join(" AND ") + ")";
  138. } else if (_.isUndefined(value)) {
  139. query = '*';
  140. negate = !negate;
  141. } else {
  142. query = angular.toJson(value);
  143. }
  144. $scope.panel.offset = 0;
  145. filterSrv.set({type:'field',field:field,query:query,mandate:(negate ? 'mustNot':'must')});
  146. };
  147. $scope.fieldExists = function(field,mandate) {
  148. filterSrv.set({type:'exists',field:field,mandate:mandate});
  149. };
  150. $scope.get_data = function(segment,query_id) {
  151. $scope.panel.error = false;
  152. // Make sure we have everything for the request to complete
  153. if(dashboard.indices.length === 0) {
  154. return;
  155. }
  156. $scope.panelMeta.loading = true;
  157. $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries);
  158. var _segment = _.isUndefined(segment) ? 0 : segment;
  159. $scope.segment = _segment;
  160. var request = $scope.ejs.Request().indices(dashboard.indices[_segment]);
  161. var boolQuery = $scope.ejs.BoolQuery();
  162. _.each($scope.panel.queries.ids,function(id) {
  163. boolQuery = boolQuery.should(querySrv.getEjsObj(id));
  164. });
  165. request = request.query(
  166. $scope.ejs.FilteredQuery(
  167. boolQuery,
  168. filterSrv.getBoolFilter(filterSrv.ids)
  169. ))
  170. .highlight(
  171. $scope.ejs.Highlight($scope.panel.highlight)
  172. .fragmentSize(2147483647) // Max size of a 32bit unsigned int
  173. .preTags('@start-highlight@')
  174. .postTags('@end-highlight@')
  175. )
  176. .size($scope.panel.size*$scope.panel.pages)
  177. .sort($scope.panel.sort[0],$scope.panel.sort[1]);
  178. $scope.populate_modal(request);
  179. var results = request.doSearch();
  180. // Populate scope when we have results
  181. results.then(function(results) {
  182. $scope.panelMeta.loading = false;
  183. if(_segment === 0) {
  184. $scope.hits = 0;
  185. $scope.data = [];
  186. query_id = $scope.query_id = new Date().getTime();
  187. }
  188. // Check for error and abort if found
  189. if(!(_.isUndefined(results.error))) {
  190. $scope.panel.error = $scope.parse_error(results.error);
  191. return;
  192. }
  193. // Check that we're still on the same query, if not stop
  194. if($scope.query_id === query_id) {
  195. $scope.data= $scope.data.concat(_.map(results.hits.hits, function(hit) {
  196. var _h = _.clone(hit);
  197. //_h._source = kbn.flatten_json(hit._source);
  198. //_h.highlight = kbn.flatten_json(hit.highlight||{});
  199. _h.kibana = {
  200. _source : kbn.flatten_json(hit._source),
  201. highlight : kbn.flatten_json(hit.highlight||{})
  202. };
  203. return _h;
  204. }));
  205. $scope.hits += results.hits.total;
  206. // Sort the data
  207. $scope.data = _.sortBy($scope.data, function(v){
  208. if(!_.isUndefined(v.sort)) {
  209. return v.sort[0];
  210. } else {
  211. return 0;
  212. }
  213. });
  214. // Reverse if needed
  215. if($scope.panel.sort[1] === 'desc') {
  216. $scope.data.reverse();
  217. }
  218. // Keep only what we need for the set
  219. $scope.data = $scope.data.slice(0,$scope.panel.size * $scope.panel.pages);
  220. } else {
  221. return;
  222. }
  223. // If we're not sorting in reverse chrono order, query every index for
  224. // size*pages results
  225. // Otherwise, only get size*pages results then stop querying
  226. if (($scope.data.length < $scope.panel.size*$scope.panel.pages ||
  227. !((_.contains(filterSrv.timeField(),$scope.panel.sort[0])) && $scope.panel.sort[1] === 'desc')) &&
  228. _segment+1 < dashboard.indices.length) {
  229. $scope.get_data(_segment+1,$scope.query_id);
  230. }
  231. });
  232. };
  233. $scope.populate_modal = function(request) {
  234. $scope.inspector = angular.toJson(JSON.parse(request.toString()),true);
  235. };
  236. $scope.without_kibana = function (row) {
  237. var _c = _.clone(row);
  238. delete _c.kibana;
  239. return _c;
  240. };
  241. $scope.set_refresh = function (state) {
  242. $scope.refresh = state;
  243. };
  244. $scope.close_edit = function() {
  245. if($scope.refresh) {
  246. $scope.get_data();
  247. }
  248. $scope.refresh = false;
  249. };
  250. $scope.locate = function(obj, path) {
  251. path = path.split('.');
  252. var arrayPattern = /(.+)\[(\d+)\]/;
  253. for (var i = 0; i < path.length; i++) {
  254. var match = arrayPattern.exec(path[i]);
  255. if (match) {
  256. obj = obj[match[1]][parseInt(match[2],10)];
  257. } else {
  258. obj = obj[path[i]];
  259. }
  260. }
  261. return obj;
  262. };
  263. });
  264. // This also escapes some xml sequences
  265. module.filter('tableHighlight', function() {
  266. return function(text) {
  267. if (!_.isUndefined(text) && !_.isNull(text) && text.toString().length > 0) {
  268. return text.toString().
  269. replace(/&/g, '&amp;').
  270. replace(/</g, '&lt;').
  271. replace(/>/g, '&gt;').
  272. replace(/\r?\n/g, '<br/>').
  273. replace(/@start-highlight@/g, '<code class="highlight">').
  274. replace(/@end-highlight@/g, '</code>');
  275. }
  276. return '';
  277. };
  278. });
  279. module.filter('tableTruncate', function() {
  280. return function(text,length,factor) {
  281. if (!_.isUndefined(text) && !_.isNull(text) && text.toString().length > 0) {
  282. return text.length > length/factor ? text.substr(0,length/factor)+'...' : text;
  283. }
  284. return '';
  285. };
  286. });
  287. module.filter('tableJson', function() {
  288. var json;
  289. return function(text,prettyLevel) {
  290. if (!_.isUndefined(text) && !_.isNull(text) && text.toString().length > 0) {
  291. json = angular.toJson(text,prettyLevel > 0 ? true : false);
  292. json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  293. if(prettyLevel > 1) {
  294. /* jshint maxlen: false */
  295. json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
  296. var cls = 'number';
  297. if (/^"/.test(match)) {
  298. if (/:$/.test(match)) {
  299. cls = 'key strong';
  300. } else {
  301. cls = '';
  302. }
  303. } else if (/true|false/.test(match)) {
  304. cls = 'boolean';
  305. } else if (/null/.test(match)) {
  306. cls = 'null';
  307. }
  308. return '<span class="' + cls + '">' + match + '</span>';
  309. });
  310. }
  311. return json;
  312. }
  313. return '';
  314. };
  315. });
  316. // WIP
  317. module.filter('tableFieldFormat', function(fields){
  318. return function(text,field,event,scope) {
  319. var type;
  320. if(
  321. !_.isUndefined(fields.mapping[event._index]) &&
  322. !_.isUndefined(fields.mapping[event._index][event._type])
  323. ) {
  324. type = fields.mapping[event._index][event._type][field]['type'];
  325. if(type === 'date' && scope.panel.normTimes) {
  326. return moment(text).format('YYYY-MM-DD HH:mm:ss');
  327. }
  328. }
  329. return text;
  330. };
  331. });
  332. });