linear_time.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. seriesData.forEach(function (series, index) {
  298. series.color = /*this.colorForSeries(series) ||*/ palette.color();
  299. series.stroke = 'rgba(0,0,0,0.3)';
  300. if (isPopup) {
  301. // calculate statistic data for popup legend
  302. var avg = 0;
  303. var min = Number.MAX_VALUE;
  304. var max = Number.MIN_VALUE;
  305. for (var i = 0; i < series.data.length; i++) {
  306. avg += series.data[i]['y'];
  307. if (series.data[i]['y'] < min) {
  308. min = series.data[i]['y'];
  309. }
  310. else {
  311. if (series.data[i]['y'] > max) {
  312. max = series.data[i]['y'];
  313. }
  314. }
  315. }
  316. 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);
  317. }
  318. }.bind(this));
  319. var chartId = "#" + this.id + "-chart" + p;
  320. var chartOverlayId = "#" + this.id + "-container" + p;
  321. var xaxisElementId = "#" + this.id + "-xaxis" + p;
  322. var yaxisElementId = "#" + this.id + "-yaxis" + p;
  323. var legendElementId = "#" + this.id + "-legend" + p;
  324. var timelineElementId = "#" + this.id + "-timeline" + p;
  325. var chartElement = document.querySelector(chartId);
  326. var overlayElement = document.querySelector(chartOverlayId);
  327. var xaxisElement = document.querySelector(xaxisElementId);
  328. var yaxisElement = document.querySelector(yaxisElementId);
  329. var legendElement = document.querySelector(legendElementId);
  330. var timelineElement = document.querySelector(timelineElementId);
  331. var _graph = new Rickshaw.Graph({
  332. height: 150,
  333. element: chartElement,
  334. series: seriesData,
  335. interpolation: 'step-after',
  336. stroke: true,
  337. renderer: 'area',
  338. strokeWidth: 1
  339. });
  340. _graph.renderer.unstack = false;
  341. xAxis = new Rickshaw.Graph.Axis.Time({
  342. graph: _graph,
  343. timeUnit: this.localeTimeUnit()
  344. });
  345. yAxis = new Rickshaw.Graph.Axis.Y({
  346. tickFormat: this.yAxisFormatter,
  347. element: yaxisElement,
  348. graph: _graph
  349. });
  350. var legend = new Rickshaw.Graph.Legend({
  351. graph: _graph,
  352. element: legendElement
  353. });
  354. if (!isPopup) {
  355. overlayElement.addEventListener('mousemove', function () {
  356. $(xaxisElement).removeClass('hide');
  357. $(legendElement).removeClass('hide');
  358. $(chartElement).children("div").removeClass('hide');
  359. });
  360. overlayElement.addEventListener('mouseout', function () {
  361. $(legendElement).addClass('hide');
  362. });
  363. _graph.onUpdate(function () {
  364. $(legendElement).addClass('hide');
  365. });
  366. }
  367. var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
  368. graph: _graph,
  369. legend: legend
  370. });
  371. var order = new Rickshaw.Graph.Behavior.Series.Order({
  372. graph: _graph,
  373. legend: legend
  374. });
  375. var annotator = new Rickshaw.Graph.Annotate({
  376. graph: _graph,
  377. element: timelineElement
  378. });
  379. _graph.render();
  380. if (isPopup) {
  381. var self = this;
  382. var hoverDetail = new Rickshaw.Graph.HoverDetail({
  383. graph: _graph,
  384. yFormatter:function (y) {
  385. return self.yAxisFormatter(y);
  386. },
  387. xFormatter:function (x) {
  388. return (new Date(x)).toLocaleTimeString();
  389. },
  390. formatter:function (series, x, y, formattedX, formattedY, d) {
  391. return formattedY + '<br />' + formattedX;
  392. }
  393. });
  394. }
  395. if (isPopup) {
  396. var self = this;
  397. // In popup save selected metrics and show only them after data update
  398. _graph.series.forEach(function(series, index) {
  399. if (self.get('_seriesProperties') !== null && self.get('_seriesProperties')[index] !== null) {
  400. if(self.get('_seriesProperties')[self.get('_seriesProperties').length - index - 1].length > 1) {
  401. $('#'+self.get('id')+'-container'+self.get('popupSuffix')+' a.action:eq('+(self.get('_seriesProperties').length - index - 1)+')').parent('li').addClass('disabled');
  402. series.disable();
  403. }
  404. }
  405. });
  406. _graph.update();
  407. $('#'+self.get('id')+'-container'+self.get('popupSuffix')+' a.action').click(function() {
  408. var series = new Array();
  409. $('#'+self.get('id')+'-container'+self.get('popupSuffix')+' a.action').each(function(index, v) {
  410. series[index] = v.parentNode.classList;
  411. });
  412. self.set('_seriesProperties', series);
  413. });
  414. this.set('_popupGraph', _graph);
  415. }
  416. else {
  417. this.set('_graph', _graph);
  418. }
  419. this.set('isPopup', false);
  420. },
  421. showGraphInPopup: function() {
  422. this.set('isPopup', true);
  423. var self = this;
  424. App.ModalPopup.show({
  425. template: Ember.Handlebars.compile([
  426. '<div class="modal-backdrop"></div><div class="modal modal-graph-line" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal-label" aria-hidden="true">',
  427. '<div class="modal-header">',
  428. '<a class="close" {{action onClose target="view"}}>x</a>',
  429. '<h3 id="modal-label">',
  430. '{{#if headerClass}}{{view headerClass}}',
  431. '{{else}}{{header}}{{/if}}',
  432. '</h3>',
  433. '</div>',
  434. '<div class="modal-body">',
  435. '{{#if bodyClass}}{{view bodyClass}}',
  436. '{{else}}'+
  437. '<div id="'+this.get('id')+'-container'+this.get('popupSuffix')+'" class="chart-container chart-container'+this.get('popupSuffix')+'">'+
  438. '<div id="'+this.get('id')+'-yaxis'+this.get('popupSuffix')+'" class="'+this.get('id')+'-yaxis chart-y-axis"></div>'+
  439. '<div id="'+this.get('id')+'-xaxis'+this.get('popupSuffix')+'" class="'+this.get('id')+'-xaxis chart-x-axis"></div>'+
  440. '<div id="'+this.get('id')+'-legend'+this.get('popupSuffix')+'" class="'+this.get('id')+'-legend chart-legend"></div>'+
  441. '<div id="'+this.get('id')+'-chart'+this.get('popupSuffix')+'" class="'+this.get('id')+'-chart chart"></div>'+
  442. '<div id="'+this.get('id')+'-title'+this.get('popupSuffix')+'" class="'+this.get('id')+'-title chart-title">{{view.title}}</div>'+
  443. '<div id="'+this.get('id')+'-timeline'+this.get('popupSuffix')+'" class="'+this.get('id')+'-timeline timeline"></div>'+
  444. '</div>'+
  445. '{{/if}}',
  446. '</div>',
  447. '<div class="modal-footer">',
  448. '{{#if view.primary}}<a class="btn btn-success" {{action onPrimary target="view"}}>{{view.primary}}</a>{{/if}}',
  449. '</div>',
  450. '</div>'
  451. ].join('\n')),
  452. header: this.get('title'),
  453. primary: 'OK',
  454. onPrimary: function() {
  455. this.hide();
  456. self.set('isPopup', false);
  457. }
  458. });
  459. Ember.run.next(function() {
  460. self.loadData();
  461. });
  462. }
  463. });
  464. /**
  465. * A formatter which will turn a number into computer storage sizes of the
  466. * format '23 GB' etc.
  467. *
  468. * @type Function
  469. */
  470. App.ChartLinearTimeView.BytesFormatter = function (y) {
  471. if (y == 0) return '0 B';
  472. var value = Rickshaw.Fixtures.Number.formatBase1024KMGTP(y);
  473. if (!y || y.length < 1) {
  474. value = '0 B';
  475. }
  476. else {
  477. if ("number" == typeof value) {
  478. value = String(value);
  479. }
  480. if ("string" == typeof value) {
  481. value = value.replace(/\.\d+/, ''); // Remove decimal part
  482. // Either it ends with digit or ends with character
  483. value = value.replace(/(\d$)/, '$1 '); // Ends with digit like '120'
  484. value = value.replace(/([a-zA-Z]$)/, ' $1'); // Ends with character like
  485. // '120M'
  486. value = value + 'B'; // Append B to make B, MB, GB etc.
  487. }
  488. }
  489. return value;
  490. };
  491. /**
  492. * A formatter which will turn a number into percentage display like '42%'
  493. *
  494. * @type Function
  495. */
  496. App.ChartLinearTimeView.PercentageFormatter = function (percentage) {
  497. var value = percentage;
  498. if (!value || value.length < 1) {
  499. value = '0 %';
  500. } else {
  501. value = value.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + '%';
  502. }
  503. return value;
  504. };
  505. /**
  506. * A formatter which will turn elapsed time into display time like '50 ms',
  507. * '5s', '10 m', '3 hr' etc. Time is expected to be provided in milliseconds.
  508. *
  509. * @type Function
  510. */
  511. App.ChartLinearTimeView.TimeElapsedFormatter = function (millis) {
  512. var value = millis;
  513. if (!value || value.length < 1) {
  514. value = '0 ms';
  515. } else if ("number" == typeof millis) {
  516. var seconds = millis > 1000 ? Math.round(millis / 1000) : 0;
  517. var minutes = seconds > 60 ? Math.round(seconds / 60) : 0;
  518. var hours = minutes > 60 ? Math.round(minutes / 60) : 0;
  519. var days = hours > 24 ? Math.round(hours / 24) : 0;
  520. if (days > 0) {
  521. value = days + ' d';
  522. } else if (hours > 0) {
  523. value = hours + ' hr';
  524. } else if (minutes > 0) {
  525. value = minutes + ' m';
  526. } else if (seconds > 0) {
  527. value = seconds + ' s';
  528. } else if (millis > 0) {
  529. value = millis.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + ' ms';
  530. } else {
  531. value = millis.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + ' ms';
  532. }
  533. }
  534. return value;
  535. };
  536. /**
  537. * A time unit which can be used for showing 15 minute intervals on X axis.
  538. *
  539. * @type Rickshaw.Fixtures.Time
  540. */
  541. App.ChartLinearTimeView.FifteenMinuteTimeUnit = {
  542. name: '15 minute',
  543. seconds: 60 * 15,
  544. formatter: function (d) {
  545. return d.toLocaleString().match(/(\d+:\d+):/)[1];
  546. }
  547. };