module.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. angular.module('kibana.parallelcoordinates', [])
  2. .controller('parallelcoordinates', function ($scope, eventBus) {
  3. $scope.activeDocs = [];
  4. // Set and populate defaults
  5. var _d = {
  6. query : "*",
  7. size : 100, // Per page
  8. pages : 5, // Pages available
  9. offset : 0,
  10. sort : ['@timestamp','desc'],
  11. group : "default",
  12. style : {'font-size': '9pt'},
  13. fields : [],
  14. sortable: true,
  15. spyable: true
  16. }
  17. _.defaults($scope.panel, _d)
  18. $scope.init = function () {
  19. $scope.set_listeners($scope.panel.group);
  20. // Now that we're all setup, request the time from our group
  21. eventBus.broadcast($scope.$id,$scope.panel.group,"get_time")
  22. //and get the currently selected fields
  23. eventBus.broadcast($scope.$id,$scope.panel.group,"get_fields")
  24. };
  25. $scope.set_listeners = function(group) {
  26. eventBus.register($scope,'time',function(event,time) {
  27. $scope.panel.offset = 0;
  28. set_time(time)
  29. });
  30. eventBus.register($scope,'query',function(event,query) {
  31. $scope.panel.offset = 0;
  32. $scope.panel.query = _.isArray(query) ? query[0] : query;
  33. $scope.get_data();
  34. });
  35. eventBus.register($scope,'sort', function(event,sort){
  36. $scope.panel.sort = _.clone(sort);
  37. $scope.get_data();
  38. });
  39. eventBus.register($scope,'selected_fields', function(event, fields) {
  40. $scope.panel.fields = _.clone(fields)
  41. $scope.$emit('render');
  42. });
  43. };
  44. $scope.get_data = function (segment,query_id) {
  45. // Make sure we have everything for the request to complete
  46. if (_.isUndefined($scope.panel.index) || _.isUndefined($scope.time))
  47. return;
  48. var _segment = _.isUndefined(segment) ? 0 : segment
  49. $scope.segment = _segment;
  50. $scope.panel.loading = true;
  51. var request = $scope.ejs.Request().indices($scope.panel.index[_segment])
  52. .query(ejs.FilteredQuery(
  53. ejs.QueryStringQuery($scope.panel.query || '*'),
  54. ejs.RangeFilter($scope.time.field)
  55. .from($scope.time.from)
  56. .to($scope.time.to)
  57. )
  58. )
  59. .size($scope.panel.size*$scope.panel.pages)
  60. .sort($scope.panel.sort[0],$scope.panel.sort[1]);
  61. $scope.populate_modal(request);
  62. var results = request.doSearch();
  63. // Populate scope when we have results
  64. results.then(function (results) {
  65. $scope.panel.loading = false;
  66. if(_segment === 0) {
  67. $scope.hits = 0;
  68. $scope.data = [];
  69. query_id = $scope.query_id = new Date().getTime()
  70. }
  71. // Check for error and abort if found
  72. if(!(_.isUndefined(results.error))) {
  73. $scope.panel.error = $scope.parse_error(results.error);
  74. return;
  75. }
  76. // Check that we're still on the same query, if not stop
  77. if($scope.query_id === query_id) {
  78. $scope.data= $scope.data.concat(_.map(results.hits.hits, function(hit) {
  79. return flatten_json(hit['_source']);
  80. }));
  81. $scope.hits += results.hits.total;
  82. // Sort the data
  83. $scope.data = _.sortBy($scope.data, function(v){
  84. return v[$scope.panel.sort[0]]
  85. });
  86. // Reverse if needed
  87. if($scope.panel.sort[1] == 'desc')
  88. $scope.data.reverse();
  89. // Keep only what we need for the set
  90. $scope.data = $scope.data.slice(0,$scope.panel.size * $scope.panel.pages)
  91. } else {
  92. return;
  93. }
  94. $scope.$emit('render')
  95. });
  96. };
  97. // I really don't like this function, too much dom manip. Break out into directive?
  98. $scope.populate_modal = function (request) {
  99. $scope.modal = {
  100. title: "Inspector",
  101. body: "<h5>Last Elasticsearch Query</h5><pre>" + 'curl -XGET ' + config.elasticsearch + '/' + $scope.panel.index + "/_search?pretty -d'\n" + angular.toJson(JSON.parse(request.toString()), true) + "'</pre>"
  102. }
  103. };
  104. function set_time(time) {
  105. $scope.time = time;
  106. $scope.panel.index = _.isUndefined(time.index) ? $scope.panel.index : time.index
  107. $scope.get_data();
  108. }
  109. $scope.$watch('activeDocs', function(v) {
  110. eventBus.broadcast($scope.$id,$scope.panel.group,"table_documents",
  111. {query:$scope.panel.query,docs:$scope.activeDocs});
  112. });
  113. })
  114. .directive('parallelcoordinates', function () {
  115. return {
  116. restrict: 'A',
  117. link: function (scope, elem, attrs) {
  118. //used to store a variety of directive-level variables
  119. var directive = {};
  120. scope.initializing = false;
  121. /**
  122. * Initialize the panels if new, or render existing panels
  123. */
  124. scope.init_or_render = function() {
  125. if (typeof directive.svg === 'undefined') {
  126. //prevent duplicate initialization steps, if render is called again
  127. //before the svg is setup
  128. if (!scope.initializing) {
  129. init_panel();
  130. }
  131. } else {
  132. render_panel();
  133. }
  134. };
  135. /**
  136. * Receive render events
  137. */
  138. scope.$on('render', function () {
  139. scope.init_or_render();
  140. });
  141. /**
  142. * On window resize, re-render the panel
  143. */
  144. angular.element(window).bind('resize', function () {
  145. scope.init_or_render();
  146. });
  147. /**
  148. * Load the various panel-specific scripts then initialize
  149. * the svg and set appropriate D3 settings
  150. */
  151. function init_panel() {
  152. directive.m = [80, 100, 80, 100];
  153. directive.w = $(elem[0]).width() - directive.m[1] - directive.m[3];
  154. directive.h = $(elem[0]).height() - directive.m[0] - directive.m[2];
  155. scope.initializing = true;
  156. // Using LABjs, wait until all scripts are loaded before rendering panel
  157. var scripts = $LAB.script("common/lib/d3.v3.min.js?rand="+Math.floor(Math.random()*10000));
  158. scripts.wait(function () {
  159. directive.x = d3.scale.ordinal().domain(scope.panel.fields).rangePoints([0, directive.w]);
  160. directive.y = {};
  161. directive.line = d3.svg.line().interpolate('cardinal');
  162. directive.axis = d3.svg.axis().orient("left");
  163. var viewbox = "0 0 " + (directive.w + directive.m[1] + directive.m[3]) + " " + (directive.h + directive.m[0] + directive.m[2]);
  164. directive.svg = d3.select(elem[0]).append("svg")
  165. .attr("width", "100%")
  166. .attr("height", "100%")
  167. .attr("viewbox", viewbox)
  168. .append("svg:g")
  169. .attr("transform", "translate(" + directive.m[3] + "," + directive.m[0] + ")");
  170. // Add foreground lines.
  171. directive.foreground = directive.svg.append("svg:g")
  172. .attr("class", "foreground");
  173. scope.initializing = false;
  174. render_panel();
  175. });
  176. }
  177. // Returns the path for a given data point.
  178. function path(d) {
  179. return directive.line(scope.panel.fields.map(function(p) { return [directive.x(p), directive.y[p](d[p])]; }));
  180. }
  181. // Handles a brush event, toggling the display of foreground lines.
  182. function brush() {
  183. var actives = scope.panel.fields.filter(function(p) { return !directive.y[p].brush.empty(); }),
  184. extents = actives.map(function(p) { return directive.y[p].brush.extent(); });
  185. //.fade class hides the "inactive" lines, helps speed up rendering significantly
  186. directive.foregroundLines.classed("fade", function(d) {
  187. return !actives.every(function(p, i) {
  188. var pointValue;
  189. if (directive.ordinals[p] === true) {
  190. pointValue = directive.y[p](d[p]);
  191. } else {
  192. pointValue = d[p];
  193. }
  194. var inside = extents[i][0] <= pointValue && pointValue <= extents[i][1];
  195. return inside;
  196. });
  197. });
  198. //activeDocs contains the actual doc records for selected lines.
  199. //will be broadcast out to the table
  200. var activeDocs = _.filter(scope.data, function(v) {
  201. return actives.every(function(p,i) {
  202. var inside = extents[i][0] <= v[p] && v[p] <= extents[i][1];
  203. return inside;
  204. });
  205. })
  206. scope.$apply(function() {
  207. scope.activeDocs = activeDocs;
  208. });
  209. }
  210. //Drag functions are used for dragging the axis aroud
  211. function dragstart(d) {
  212. directive.i = scope.panel.fields.indexOf(d);
  213. }
  214. function drag(d) {
  215. directive.x.range()[directive.i] = d3.event.x;
  216. scope.panel.fields.sort(function(a, b) { return directive.x(a) - directive.x(b); });
  217. directive.foregroundLines.attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  218. directive.traits.attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  219. directive.brushes.attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  220. directive.axisLines.attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  221. directive.foregroundLines.attr("d", path);
  222. }
  223. function dragend(d) {
  224. directive.x.domain(scope.panel.fields).rangePoints([0, directive.w]);
  225. var t = d3.transition().duration(500);
  226. t.selectAll(".trait").attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  227. t.selectAll(".axis").attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  228. t.selectAll(".brush").attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  229. t.selectAll(".foregroundlines").attr("d", path);
  230. }
  231. /**
  232. * Render updates to the SVG. Typically happens when the data changes (time, query)
  233. * or when new options are selected
  234. */
  235. function render_panel() {
  236. //update the svg if the size has changed
  237. directive.w = $(elem[0]).width() - directive.m[1] - directive.m[3];
  238. directive.h = $(elem[0]).height() - directive.m[0] - directive.m[2];
  239. directive.svg.attr("viewbox", "0 0 " + (directive.w + directive.m[1] + directive.m[3]) + " " + (directive.h + directive.m[0] + directive.m[2]));
  240. directive.x = d3.scale.ordinal().domain(scope.panel.fields).rangePoints([0, directive.w]);
  241. directive.y = {};
  242. directive.line = d3.svg.line().interpolate('cardinal');
  243. directive.axis = d3.svg.axis().orient("left").ticks(5);
  244. directive.ordinals = {};
  245. scope.panel.fields.forEach(function(d) {
  246. var firstField = scope.data[0][d];
  247. if (_.isString(firstField)) {
  248. if (isValidDate(new Date(firstField))) {
  249. //convert date timestamps to actual dates
  250. _.map(scope.data, function(v) {
  251. v[d] = new Date(v[d]);
  252. });
  253. var extents = d3.extent(scope.data, function(p) { return p[d]; });
  254. directive.y[d] = d3.time.scale()
  255. .domain([extents[0],extents[1]])
  256. .range([directive.h, 0]);
  257. } else {
  258. directive.ordinals[d] = true;
  259. var value = function(v) { return v[d]; };
  260. var values = _.map(_.uniq(scope.data, value),value);
  261. directive.y[d] = d3.scale.ordinal()
  262. .domain(values)
  263. .rangePoints([directive.h, 0]);
  264. }
  265. } else if (_.isNumber(firstField)) {
  266. directive.y[d] = d3.scale.linear()
  267. .domain(d3.extent(scope.data, function(p) { return +p[d]; }))
  268. .range([directive.h, 0]);
  269. } else if (_.isDate(firstField)) {
  270. //this section is only used after timestamps have been parsed into actual date objects...
  271. //avoids reparsing
  272. var extents = d3.extent(scope.data, function(p) { return p[d]; });
  273. directive.y[d] = d3.time.scale()
  274. .domain([extents[0],extents[1]])
  275. .range([directive.h, 0]);
  276. }
  277. directive.y[d].brush = d3.svg.brush()
  278. .y(directive.y[d])
  279. .on("brush", brush);
  280. });
  281. //setup the colors for the lines
  282. setColors();
  283. //pull out the actively selected columns for rendering the axis/lines
  284. var activeData = _.map(scope.data, function(d) {
  285. var t = {};
  286. _.each(scope.panel.fields, function(f) {
  287. t[f] = d[f];
  288. });
  289. return t;
  290. });
  291. //Lines
  292. directive.foregroundLines = directive.foreground
  293. .selectAll(".foregroundlines")
  294. .data(activeData, function(d, i){
  295. var id = "";
  296. _.each(d, function(v) {
  297. id += i + "_" + v;
  298. });
  299. return id;
  300. });
  301. directive.foregroundLines
  302. .enter().append("svg:path")
  303. .attr("d", path)
  304. .attr("class", "foregroundlines")
  305. .attr("style", function(d) {
  306. return "stroke:" + directive.colors(d[scope.panel.fields[0]]) + ";";
  307. });
  308. directive.foregroundLines.exit().remove();
  309. //Axis group
  310. directive.traits = directive.svg.selectAll(".trait")
  311. .data(scope.panel.fields, String);
  312. directive.traits
  313. .enter().append("svg:g")
  314. .attr("class", "trait")
  315. .attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  316. directive.traits
  317. .exit().remove();
  318. //brushes used to select lines
  319. directive.brushes = directive.svg.selectAll(".brush")
  320. .data(scope.panel.fields, String);
  321. directive.brushes
  322. .enter()
  323. .append("svg:g")
  324. .attr("class", "brush")
  325. .each(function(d) {
  326. d3.select(this)
  327. .call(directive.y[d].brush)
  328. .attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  329. })
  330. .selectAll("rect")
  331. .attr("x", -8)
  332. .attr("width", 16);
  333. //this section is repeated because enter() only works on "new" data, but we always need to
  334. //update the brushes if things change. This just calls the brushing function, so it doesn't
  335. //affect currently active rects
  336. directive.brushes
  337. .each(function(d) {
  338. d3.select(this)
  339. .call(directive.y[d].brush)
  340. .attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  341. });
  342. directive.brushes
  343. .exit().remove();
  344. //vertical axis and labels
  345. directive.axisLines = directive.svg.selectAll(".axis")
  346. .data(scope.panel.fields, String);
  347. directive.axisLines
  348. .enter()
  349. .append("svg:g")
  350. .attr("class", "axis")
  351. .each(function(d) {
  352. d3.select(this)
  353. .call(directive.axis.scale(directive.y[d]))
  354. .attr("transform", function(d) { return "translate(" + directive.x(d) + ")"; });
  355. }).call(d3.behavior.drag()
  356. .origin(function(d) { return {x: directive.x(d)}; })
  357. .on("dragstart", dragstart)
  358. .on("drag", drag)
  359. .on("dragend", dragend))
  360. .append("svg:text")
  361. .attr("text-anchor", "middle")
  362. .attr("y", -9)
  363. .text(String);
  364. directive.axisLines
  365. .exit().remove();
  366. //Simulate a dragend in case there is new data and we need to rearrange
  367. dragend();
  368. }
  369. function setColors() {
  370. var firstPanelField = scope.data[0][scope.panel.fields[0]];
  371. var extents = d3.extent(scope.data, function(p) { return p[scope.panel.fields[0]]; });
  372. if (_.isString(firstPanelField)) {
  373. var value = function(v) { return v[firstPanelField]; };
  374. var values = _.map(_.uniq(scope.data, value),value);
  375. values = scope.data;
  376. directive.colors = d3.scale.ordinal()
  377. .domain(values)
  378. .range(d3.range(values.length).map(d3.scale.linear()
  379. .domain([0, values.length - 1])
  380. .range(["red", "blue"])
  381. .interpolate(d3.interpolateLab)));
  382. } else if (_.isNumber(firstPanelField)) {
  383. directive.colors = d3.scale.linear()
  384. .domain([extents[0],extents[1]])
  385. .range(["#4580FF", "#FF9245"]);
  386. } else if (_.isDate(firstPanelField)) {
  387. directive.colors = d3.time.scale()
  388. .domain([extents[0],extents[1]])
  389. .range(["#4580FF", "#FF9245"]);
  390. }
  391. }
  392. function isValidDate(d) {
  393. if ( Object.prototype.toString.call(d) !== "[object Date]" )
  394. return false;
  395. return !isNaN(d.getTime());
  396. }
  397. }
  398. };
  399. });