module.js 17 KB

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