linear_time.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with this
  4. * work for additional information regarding copyright ownership. The ASF
  5. * licenses this file to you under the Apache License, Version 2.0 (the
  6. * "License"); you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations under
  15. * the License.
  16. */
  17. var App = require('app');
  18. var string_utils = require('utils/string_utils');
  19. /**
  20. * @class
  21. *
  22. * This is a view which GETs data from a URL and shows it as a time based line
  23. * graph. Time is shown on the X axis with data series shown on Y axis. It
  24. * optionally also has the ability to auto refresh itself over a given time
  25. * interval.
  26. *
  27. * This is an abstract class which is meant to be extended.
  28. *
  29. * Extending classes should override the following:
  30. * <ul>
  31. * <li>url - from where the data can be retrieved
  32. * <li>title - Title to be displayed when showing the chart
  33. * <li>id - which uniquely identifies this chart in any page
  34. * <li>#transformToSeries(jsonData) - function to map server data into graph
  35. * series
  36. * </ul>
  37. *
  38. * Extending classes could optionally override the following:
  39. * <ul>
  40. * <li>#colorForSeries(series) - function to get custom colors per series
  41. * </ul>
  42. *
  43. * @extends Ember.Object
  44. * @extends Ember.View
  45. */
  46. App.ChartLinearTimeView = Ember.View.extend({
  47. templateName: require('templates/main/charts/linear_time'),
  48. /**
  49. * The URL from which data can be retrieved.
  50. *
  51. * This property must be provided for the graph to show properly.
  52. *
  53. * @type String
  54. * @default null
  55. */
  56. url: null,
  57. /**
  58. * A unique ID for this chart.
  59. *
  60. * @type String
  61. * @default null
  62. */
  63. id: null,
  64. /**
  65. * Title to be shown under the chart.
  66. *
  67. * @type String
  68. * @default null
  69. */
  70. title: null,
  71. /**
  72. * @private
  73. *
  74. * @type Rickshaw.Graph
  75. * @default null
  76. */
  77. _graph: null,
  78. _popupGraph: null,
  79. _seriesProperties: null,
  80. popupSuffix: '-popup',
  81. isPopup: false,
  82. /**
  83. * Color palette used for this chart
  84. *
  85. * @private
  86. * @type String[]
  87. */
  88. _paletteScheme: [ 'rgba(181,182,169,0.4)', 'rgba(133,135,114,0.4)',
  89. 'rgba(120,95,67,0.4)', 'rgba(150,85,126,0.4)',
  90. 'rgba(70,130,180,0.4)', 'rgba(0,255,204,0.4)',
  91. 'rgba(255,105,180,0.4)', 'rgba(101,185,172,0.4)',
  92. 'rgba(115,192,58,0.4)', 'rgba(203,81,58,0.4)' ].reverse(),
  93. init: function () {
  94. this._super();
  95. },
  96. selector: function () {
  97. return '#' + this.get('elementId');
  98. }.property('elementId'),
  99. didInsertElement: function () {
  100. this._super();
  101. this.loadData();
  102. this.registerGraph();
  103. },
  104. registerGraph: function(){
  105. var graph = {
  106. name: this.get('title'),
  107. id: this.get('elementId'),
  108. popupId: this.get('id')
  109. };
  110. App.router.get('updateController.graphs').push(graph);
  111. },
  112. loadData: function() {
  113. var validUrl = this.get('url');
  114. if (validUrl) {
  115. var hash = {};
  116. hash.url = validUrl;
  117. hash.type = 'GET';
  118. hash.dataType = 'json';
  119. hash.contentType = 'application/json; charset=utf-8';
  120. hash.context = this;
  121. hash.success = this._refreshGraph;
  122. hash.error = function (xhr, textStatus, errorThrown) {
  123. this._showMessage('warn', 'Error', 'There was a problem getting data for the chart (' + textStatus + ': ' + errorThrown + ')');
  124. }
  125. jQuery.ajax(hash);
  126. }
  127. },
  128. /**
  129. * Shows a yellow warning message in place of the chart.
  130. *
  131. * @param type Can be any of 'warn', 'error', 'info', 'success'
  132. * @param title Bolded title for the message
  133. * @param message String representing the message
  134. * @type: Function
  135. */
  136. _showMessage: function(type, title, message){
  137. var chartOverlayId = '#' + this.id + '-chart';
  138. if (this.get('isPopup')) {
  139. chartOverlayId += this.get('popupSuffix');
  140. }
  141. var typeClass;
  142. switch (type) {
  143. case 'error':
  144. typeClass = 'alert-error';
  145. break;
  146. case 'success':
  147. typeClass = 'alert-success';
  148. break;
  149. case 'info':
  150. typeClass = 'alert-info';
  151. break;
  152. default:
  153. typeClass = '';
  154. break;
  155. }
  156. $(chartOverlayId).html('');
  157. $(chartOverlayId).append('<div class=\"alert '+typeClass+'\"><strong>'+title+'</strong> '+message+'</div>');
  158. },
  159. /**
  160. * Transforms the JSON data retrieved from the server into the series
  161. * format that Rickshaw.Graph understands.
  162. *
  163. * The series object is generally in the following format: [ { name :
  164. * "Series 1", data : [ { x : 0, y : 0 }, { x : 1, y : 1 } ] } ]
  165. *
  166. * Extending classes should override this method.
  167. *
  168. * @param jsonData
  169. * Data retrieved from the server
  170. * @type: Function
  171. *
  172. */
  173. transformToSeries: function (jsonData) {
  174. return [ {
  175. name: "Series 1",
  176. data: [ {
  177. x: 0,
  178. y: 0
  179. }, {
  180. x: 1,
  181. y: 1
  182. } ]
  183. } ]
  184. },
  185. /**
  186. * Provides the formatter to use in displaying Y axis.
  187. *
  188. * The default is Rickshaw.Fixtures.Number.formatKMBT which shows 10K,
  189. * 300M etc.
  190. *
  191. * @type Function
  192. */
  193. yAxisFormatter: function(y) {
  194. var value = Rickshaw.Fixtures.Number.formatKMBT(y);
  195. if (value == '') return '0';
  196. value = String(value);
  197. var c = value[value.length - 1];
  198. if (!isNaN(parseInt(c))) {
  199. // c is digit
  200. value = parseFloat(value).toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
  201. }
  202. else {
  203. // c in not digit
  204. value = parseFloat(value.substr(0, value.length - 1)).toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + c;
  205. }
  206. return value;
  207. },
  208. /**
  209. * Provides the color (in any HTML color format) to use for a particular
  210. * series.
  211. *
  212. * @param series
  213. * Series for which color is being requested
  214. * @return color String. Returning null allows this chart to pick a color
  215. * from palette.
  216. * @default null
  217. * @type Function
  218. */
  219. colorForSeries: function (series) {
  220. return null;
  221. },
  222. /**
  223. * @private
  224. *
  225. * Refreshes the graph with the latest JSON data.
  226. *
  227. * @type Function
  228. */
  229. _refreshGraph: function (jsonData) {
  230. var seriesData = this.transformToSeries(jsonData);
  231. if (seriesData instanceof Array && seriesData.length>0) {
  232. //if graph opened as modal popup
  233. var popup_path = $(".modal-graph-line .modal-body #" + this.id + "-container" + this.get('popupSuffix'));
  234. if(popup_path.length) {
  235. popup_path.children().each(function () {
  236. $(this).children().remove();
  237. });
  238. this.set('isPopup', true);
  239. }
  240. else {
  241. $("#" + this.id + "-container").children().each(function (index, value) {
  242. $(value).children().remove();
  243. });
  244. }
  245. this.draw(seriesData);
  246. }
  247. else {
  248. this._showMessage('info', 'No Data', 'There was no data available.');
  249. }
  250. },
  251. /**
  252. * Returns a custom time unit for the graph's X axis. This is needed
  253. * as Rickshaw's default time X axis uses UTC time, which can be confusing
  254. * for users expecting locale specific time. This value defaults to
  255. * App.ChartLinearTimeView.FifteenMinuteTimeUnit.
  256. *
  257. * If <code>null</code> is returned, Rickshaw's default time unit is used.
  258. *
  259. * @type Function
  260. * @return Rickshaw.Fixtures.Time
  261. * @default App.ChartLinearTimeView.FifteenMinuteTimeUnit
  262. */
  263. localeTimeUnit: function(){
  264. return App.ChartLinearTimeView.FifteenMinuteTimeUnit;
  265. },
  266. /**
  267. * @private
  268. *
  269. * When a graph is given a particular width and height,the lines are drawn
  270. * in a slightly bigger area thereby chopping off some of the UI. Hence
  271. * after the rendering, we adjust the SVGs size in the DOM to compensate.
  272. *
  273. * Opened https://github.com/shutterstock/rickshaw/issues/141
  274. *
  275. * @type Function
  276. */
  277. _adjustSVGHeight: function () {
  278. if (this._graph && this._graph.element
  279. && this._graph.element.firstChild) {
  280. var svgElement = this._graph.element.firstChild;
  281. svgElement.setAttribute('height', $(this._graph.element).height()
  282. + "px");
  283. svgElement.setAttribute('width', $(this._graph.element).width()
  284. + "px");
  285. }
  286. },
  287. draw: function(seriesData) {
  288. var isPopup = this.get('isPopup');
  289. var p = '';
  290. if (isPopup) {
  291. p = this.get('popupSuffix');
  292. }
  293. var palette = new Rickshaw.Color.Palette({
  294. scheme: this._paletteScheme
  295. });
  296. var self = this;
  297. var series_min_length = 100000000;
  298. seriesData.forEach(function (series, index) {
  299. series.color = /*this.colorForSeries(series) ||*/ palette.color();
  300. series.stroke = 'rgba(0,0,0,0.3)';
  301. if (isPopup) {
  302. // calculate statistic data for popup legend
  303. var avg = 0;
  304. var min = Number.MAX_VALUE;
  305. var max = Number.MIN_VALUE;
  306. for (var i = 0; i < series.data.length; i++) {
  307. avg += series.data[i]['y'];
  308. if (series.data[i]['y'] < min) {
  309. min = series.data[i]['y'];
  310. }
  311. else {
  312. if (series.data[i]['y'] > max) {
  313. max = series.data[i]['y'];
  314. }
  315. }
  316. }
  317. series.name = string_utils.pad(series.name, 30, '&nbsp;', 2) + string_utils.pad('min', 5, '&nbsp;', 3) + string_utils.pad(this.get('yAxisFormatter')(min), 12, '&nbsp;', 3) + string_utils.pad('avg', 5, '&nbsp;', 3) + string_utils.pad(this.get('yAxisFormatter')(avg/series.data.length), 12, '&nbsp;', 3) + string_utils.pad('max', 12, '&nbsp;', 3) + string_utils.pad(this.get('yAxisFormatter')(max), 5, '&nbsp;', 3);
  318. }
  319. if (series.data.length < series_min_length) {
  320. series_min_length = series.data.length;
  321. }
  322. }.bind(this));
  323. seriesData.forEach(function(series, index) {
  324. if (series.data.length > series_min_length) {
  325. series.data.length = series_min_length;
  326. }
  327. });
  328. var chartId = "#" + this.id + "-chart" + p;
  329. var chartOverlayId = "#" + this.id + "-container" + p;
  330. var xaxisElementId = "#" + this.id + "-xaxis" + p;
  331. var yaxisElementId = "#" + this.id + "-yaxis" + p;
  332. var legendElementId = "#" + this.id + "-legend" + p;
  333. var timelineElementId = "#" + this.id + "-timeline" + p;
  334. var chartElement = document.querySelector(chartId);
  335. var overlayElement = document.querySelector(chartOverlayId);
  336. var xaxisElement = document.querySelector(xaxisElementId);
  337. var yaxisElement = document.querySelector(yaxisElementId);
  338. var legendElement = document.querySelector(legendElementId);
  339. var timelineElement = document.querySelector(timelineElementId);
  340. var _graph = new Rickshaw.Graph({
  341. height: 150,
  342. element: chartElement,
  343. series: seriesData,
  344. interpolation: 'step-after',
  345. stroke: true,
  346. renderer: 'area',
  347. strokeWidth: 1
  348. });
  349. _graph.renderer.unstack = false;
  350. xAxis = new Rickshaw.Graph.Axis.Time({
  351. graph: _graph,
  352. timeUnit: this.localeTimeUnit()
  353. });
  354. yAxis = new Rickshaw.Graph.Axis.Y({
  355. tickFormat: this.yAxisFormatter,
  356. element: yaxisElement,
  357. graph: _graph
  358. });
  359. var legend = new Rickshaw.Graph.Legend({
  360. graph: _graph,
  361. element: legendElement
  362. });
  363. if (!isPopup) {
  364. overlayElement.addEventListener('mousemove', function () {
  365. $(xaxisElement).removeClass('hide');
  366. $(legendElement).removeClass('hide');
  367. $(chartElement).children("div").removeClass('hide');
  368. });
  369. overlayElement.addEventListener('mouseout', function () {
  370. $(legendElement).addClass('hide');
  371. });
  372. _graph.onUpdate(function () {
  373. $(legendElement).addClass('hide');
  374. });
  375. }
  376. var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
  377. graph: _graph,
  378. legend: legend
  379. });
  380. var order = new Rickshaw.Graph.Behavior.Series.Order({
  381. graph: _graph,
  382. legend: legend
  383. });
  384. var annotator = new Rickshaw.Graph.Annotate({
  385. graph: _graph,
  386. element: timelineElement
  387. });
  388. _graph.render();
  389. if (isPopup) {
  390. var self = this;
  391. var hoverDetail = new Rickshaw.Graph.HoverDetail({
  392. graph: _graph,
  393. yFormatter:function (y) {
  394. return self.yAxisFormatter(y);
  395. },
  396. xFormatter:function (x) {
  397. return (new Date(x)).toLocaleTimeString();
  398. },
  399. formatter:function (series, x, y, formattedX, formattedY, d) {
  400. return formattedY + '<br />' + formattedX;
  401. }
  402. });
  403. }
  404. if (isPopup) {
  405. var self = this;
  406. // In popup save selected metrics and show only them after data update
  407. _graph.series.forEach(function(series, index) {
  408. if (self.get('_seriesProperties') !== null && self.get('_seriesProperties')[index] !== null) {
  409. if(self.get('_seriesProperties')[self.get('_seriesProperties').length - index - 1].length > 1) {
  410. $('#'+self.get('id')+'-container'+self.get('popupSuffix')+' a.action:eq('+(self.get('_seriesProperties').length - index - 1)+')').parent('li').addClass('disabled');
  411. series.disable();
  412. }
  413. }
  414. });
  415. _graph.update();
  416. $('#'+self.get('id')+'-container'+self.get('popupSuffix')+' a.action').click(function() {
  417. var series = new Array();
  418. $('#'+self.get('id')+'-container'+self.get('popupSuffix')+' a.action').each(function(index, v) {
  419. series[index] = v.parentNode.classList;
  420. });
  421. self.set('_seriesProperties', series);
  422. });
  423. this.set('_popupGraph', _graph);
  424. }
  425. else {
  426. this.set('_graph', _graph);
  427. }
  428. this.set('isPopup', false);
  429. },
  430. showGraphInPopup: function() {
  431. this.set('isPopup', true);
  432. var self = this;
  433. App.ModalPopup.show({
  434. template: Ember.Handlebars.compile([
  435. '<div class="modal-backdrop"></div><div class="modal modal-graph-line" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal-label" aria-hidden="true">',
  436. '<div class="modal-header">',
  437. '<a class="close" {{action onClose target="view"}}>x</a>',
  438. '<h3 id="modal-label">',
  439. '{{#if headerClass}}{{view headerClass}}',
  440. '{{else}}{{header}}{{/if}}',
  441. '</h3>',
  442. '</div>',
  443. '<div class="modal-body">',
  444. '{{#if bodyClass}}{{view bodyClass}}',
  445. '{{else}}'+
  446. '<div id="'+this.get('id')+'-container'+this.get('popupSuffix')+'" class="chart-container chart-container'+this.get('popupSuffix')+'">'+
  447. '<div id="'+this.get('id')+'-yaxis'+this.get('popupSuffix')+'" class="'+this.get('id')+'-yaxis chart-y-axis"></div>'+
  448. '<div id="'+this.get('id')+'-xaxis'+this.get('popupSuffix')+'" class="'+this.get('id')+'-xaxis chart-x-axis"></div>'+
  449. '<div id="'+this.get('id')+'-legend'+this.get('popupSuffix')+'" class="'+this.get('id')+'-legend chart-legend"></div>'+
  450. '<div id="'+this.get('id')+'-chart'+this.get('popupSuffix')+'" class="'+this.get('id')+'-chart chart"></div>'+
  451. '<div id="'+this.get('id')+'-title'+this.get('popupSuffix')+'" class="'+this.get('id')+'-title chart-title">{{view.title}}</div>'+
  452. '<div id="'+this.get('id')+'-timeline'+this.get('popupSuffix')+'" class="'+this.get('id')+'-timeline timeline"></div>'+
  453. '</div>'+
  454. '{{/if}}',
  455. '</div>',
  456. '<div class="modal-footer">',
  457. '{{#if view.primary}}<a class="btn btn-success" {{action onPrimary target="view"}}>{{view.primary}}</a>{{/if}}',
  458. '</div>',
  459. '</div>'
  460. ].join('\n')),
  461. header: this.get('title'),
  462. primary: 'OK',
  463. onPrimary: function() {
  464. this.hide();
  465. self.set('isPopup', false);
  466. }
  467. });
  468. Ember.run.next(function() {
  469. self.loadData();
  470. });
  471. }
  472. });
  473. /**
  474. * A formatter which will turn a number into computer storage sizes of the
  475. * format '23 GB' etc.
  476. *
  477. * @type Function
  478. */
  479. App.ChartLinearTimeView.BytesFormatter = function (y) {
  480. if (y == 0) return '0 B';
  481. var value = Rickshaw.Fixtures.Number.formatBase1024KMGTP(y);
  482. if (!y || y.length < 1) {
  483. value = '0 B';
  484. }
  485. else {
  486. if ("number" == typeof value) {
  487. value = String(value);
  488. }
  489. if ("string" == typeof value) {
  490. value = value.replace(/\.\d+/, ''); // Remove decimal part
  491. // Either it ends with digit or ends with character
  492. value = value.replace(/(\d$)/, '$1 '); // Ends with digit like '120'
  493. value = value.replace(/([a-zA-Z]$)/, ' $1'); // Ends with character like
  494. // '120M'
  495. value = value + 'B'; // Append B to make B, MB, GB etc.
  496. }
  497. }
  498. return value;
  499. };
  500. /**
  501. * A formatter which will turn a number into percentage display like '42%'
  502. *
  503. * @type Function
  504. */
  505. App.ChartLinearTimeView.PercentageFormatter = function (percentage) {
  506. var value = percentage;
  507. if (!value || value.length < 1) {
  508. value = '0 %';
  509. } else {
  510. value = value.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + '%';
  511. }
  512. return value;
  513. };
  514. /**
  515. * A formatter which will turn elapsed time into display time like '50 ms',
  516. * '5s', '10 m', '3 hr' etc. Time is expected to be provided in milliseconds.
  517. *
  518. * @type Function
  519. */
  520. App.ChartLinearTimeView.TimeElapsedFormatter = function (millis) {
  521. var value = millis;
  522. if (!value || value.length < 1) {
  523. value = '0 ms';
  524. } else if ("number" == typeof millis) {
  525. var seconds = millis > 1000 ? Math.round(millis / 1000) : 0;
  526. var minutes = seconds > 60 ? Math.round(seconds / 60) : 0;
  527. var hours = minutes > 60 ? Math.round(minutes / 60) : 0;
  528. var days = hours > 24 ? Math.round(hours / 24) : 0;
  529. if (days > 0) {
  530. value = days + ' d';
  531. } else if (hours > 0) {
  532. value = hours + ' hr';
  533. } else if (minutes > 0) {
  534. value = minutes + ' m';
  535. } else if (seconds > 0) {
  536. value = seconds + ' s';
  537. } else if (millis > 0) {
  538. value = millis.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + ' ms';
  539. } else {
  540. value = millis.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + ' ms';
  541. }
  542. }
  543. return value;
  544. };
  545. /**
  546. * A time unit which can be used for showing 15 minute intervals on X axis.
  547. *
  548. * @type Rickshaw.Fixtures.Time
  549. */
  550. App.ChartLinearTimeView.FifteenMinuteTimeUnit = {
  551. name: '15 minute',
  552. seconds: 60 * 15,
  553. formatter: function (d) {
  554. return d.toLocaleString().match(/(\d+:\d+):/)[1];
  555. }
  556. };