TimeSrv.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Libraries
  2. import _ from 'lodash';
  3. // Utils
  4. import kbn from 'app/core/utils/kbn';
  5. import coreModule from 'app/core/core_module';
  6. import { dateMath } from '@grafana/data';
  7. // Types
  8. import { TimeRange, RawTimeRange, TimeZone } from '@grafana/data';
  9. import { ITimeoutService, ILocationService } from 'angular';
  10. import { ContextSrv } from 'app/core/services/context_srv';
  11. import { DashboardModel } from '../state/DashboardModel';
  12. import { toUtc, dateTime, isDateTime } from '@grafana/data';
  13. import { getZoomedTimeRange } from 'app/core/utils/timePicker';
  14. export class TimeSrv {
  15. time: any;
  16. refreshTimer: any;
  17. refresh: any;
  18. oldRefresh: boolean;
  19. dashboard: Partial<DashboardModel>;
  20. timeAtLoad: any;
  21. private autoRefreshBlocked: boolean;
  22. /** @ngInject */
  23. constructor(
  24. $rootScope: any,
  25. private $timeout: ITimeoutService,
  26. private $location: ILocationService,
  27. private timer: any,
  28. private contextSrv: ContextSrv
  29. ) {
  30. // default time
  31. this.time = { from: '6h', to: 'now' };
  32. $rootScope.$on('zoom-out', this.zoomOut.bind(this));
  33. $rootScope.$on('$routeUpdate', this.routeUpdated.bind(this));
  34. document.addEventListener('visibilitychange', () => {
  35. if (this.autoRefreshBlocked && document.visibilityState === 'visible') {
  36. this.autoRefreshBlocked = false;
  37. this.refreshDashboard();
  38. }
  39. });
  40. }
  41. init(dashboard: Partial<DashboardModel>) {
  42. this.timer.cancelAll();
  43. this.dashboard = dashboard;
  44. this.time = dashboard.time;
  45. this.refresh = dashboard.refresh;
  46. this.initTimeFromUrl();
  47. this.parseTime();
  48. // remember time at load so we can go back to it
  49. this.timeAtLoad = _.cloneDeep(this.time);
  50. if (this.refresh) {
  51. this.setAutoRefresh(this.refresh);
  52. }
  53. }
  54. private parseTime() {
  55. // when absolute time is saved in json it is turned to a string
  56. if (_.isString(this.time.from) && this.time.from.indexOf('Z') >= 0) {
  57. this.time.from = dateTime(this.time.from).utc();
  58. }
  59. if (_.isString(this.time.to) && this.time.to.indexOf('Z') >= 0) {
  60. this.time.to = dateTime(this.time.to).utc();
  61. }
  62. }
  63. private parseUrlParam(value: any) {
  64. if (value.indexOf('now') !== -1) {
  65. return value;
  66. }
  67. if (value.length === 8) {
  68. return toUtc(value, 'YYYYMMDD');
  69. }
  70. if (value.length === 15) {
  71. return toUtc(value, 'YYYYMMDDTHHmmss');
  72. }
  73. if (!isNaN(value)) {
  74. const epoch = parseInt(value, 10);
  75. return toUtc(epoch);
  76. }
  77. return null;
  78. }
  79. private initTimeFromUrl() {
  80. const params = this.$location.search();
  81. if (params.from) {
  82. this.time.from = this.parseUrlParam(params.from) || this.time.from;
  83. }
  84. if (params.to) {
  85. this.time.to = this.parseUrlParam(params.to) || this.time.to;
  86. }
  87. // if absolute ignore refresh option saved to dashboard
  88. if (params.to && params.to.indexOf('now') === -1) {
  89. this.refresh = false;
  90. this.dashboard.refresh = false;
  91. }
  92. // but if refresh explicitly set then use that
  93. if (params.refresh) {
  94. this.refresh = params.refresh || this.refresh;
  95. }
  96. }
  97. private routeUpdated() {
  98. const params = this.$location.search();
  99. if (params.left) {
  100. return; // explore handles this;
  101. }
  102. const urlRange = this.timeRangeForUrl();
  103. // check if url has time range
  104. if (params.from && params.to) {
  105. // is it different from what our current time range?
  106. if (params.from !== urlRange.from || params.to !== urlRange.to) {
  107. // issue update
  108. this.initTimeFromUrl();
  109. this.setTime(this.time, true);
  110. }
  111. } else if (this.timeHasChangedSinceLoad()) {
  112. this.setTime(this.timeAtLoad, true);
  113. }
  114. }
  115. private timeHasChangedSinceLoad() {
  116. return this.timeAtLoad && (this.timeAtLoad.from !== this.time.from || this.timeAtLoad.to !== this.time.to);
  117. }
  118. setAutoRefresh(interval: any) {
  119. this.dashboard.refresh = interval;
  120. this.cancelNextRefresh();
  121. if (interval) {
  122. const intervalMs = kbn.interval_to_ms(interval);
  123. this.refreshTimer = this.timer.register(
  124. this.$timeout(() => {
  125. this.startNextRefreshTimer(intervalMs);
  126. this.refreshDashboard();
  127. }, intervalMs)
  128. );
  129. }
  130. // update url inside timeout to so that a digest happens after (called from react)
  131. this.$timeout(() => {
  132. const params = this.$location.search();
  133. if (interval) {
  134. params.refresh = interval;
  135. this.$location.search(params);
  136. } else if (params.refresh) {
  137. delete params.refresh;
  138. this.$location.search(params);
  139. }
  140. });
  141. }
  142. refreshDashboard() {
  143. this.dashboard.timeRangeUpdated(this.timeRange());
  144. }
  145. private startNextRefreshTimer(afterMs: number) {
  146. this.cancelNextRefresh();
  147. this.refreshTimer = this.timer.register(
  148. this.$timeout(() => {
  149. this.startNextRefreshTimer(afterMs);
  150. if (this.contextSrv.isGrafanaVisible()) {
  151. this.refreshDashboard();
  152. } else {
  153. this.autoRefreshBlocked = true;
  154. }
  155. }, afterMs)
  156. );
  157. }
  158. private cancelNextRefresh() {
  159. this.timer.cancel(this.refreshTimer);
  160. }
  161. setTime(time: RawTimeRange, fromRouteUpdate?: boolean) {
  162. _.extend(this.time, time);
  163. // disable refresh if zoom in or zoom out
  164. if (isDateTime(time.to)) {
  165. this.oldRefresh = this.dashboard.refresh || this.oldRefresh;
  166. this.setAutoRefresh(false);
  167. } else if (this.oldRefresh && this.oldRefresh !== this.dashboard.refresh) {
  168. this.setAutoRefresh(this.oldRefresh);
  169. this.oldRefresh = null;
  170. }
  171. // update url
  172. if (fromRouteUpdate !== true) {
  173. const urlRange = this.timeRangeForUrl();
  174. const urlParams = this.$location.search();
  175. urlParams.from = urlRange.from;
  176. urlParams.to = urlRange.to;
  177. this.$location.search(urlParams);
  178. }
  179. this.$timeout(this.refreshDashboard.bind(this), 0);
  180. }
  181. timeRangeForUrl() {
  182. const range = this.timeRange().raw;
  183. if (isDateTime(range.from)) {
  184. range.from = range.from.valueOf().toString();
  185. }
  186. if (isDateTime(range.to)) {
  187. range.to = range.to.valueOf().toString();
  188. }
  189. return range;
  190. }
  191. timeRange(): TimeRange {
  192. // make copies if they are moment (do not want to return out internal moment, because they are mutable!)
  193. const raw = {
  194. from: isDateTime(this.time.from) ? dateTime(this.time.from) : this.time.from,
  195. to: isDateTime(this.time.to) ? dateTime(this.time.to) : this.time.to,
  196. };
  197. const timezone: TimeZone = this.dashboard ? this.dashboard.getTimezone() : undefined;
  198. return {
  199. from: dateMath.parse(raw.from, false, timezone),
  200. to: dateMath.parse(raw.to, true, timezone),
  201. raw: raw,
  202. };
  203. }
  204. zoomOut(e: any, factor: number) {
  205. const range = this.timeRange();
  206. const { from, to } = getZoomedTimeRange(range, factor);
  207. this.setTime({ from: toUtc(from), to: toUtc(to) });
  208. }
  209. }
  210. let singleton: TimeSrv;
  211. export function setTimeSrv(srv: TimeSrv) {
  212. singleton = srv;
  213. }
  214. export function getTimeSrv(): TimeSrv {
  215. return singleton;
  216. }
  217. coreModule.service('timeSrv', TimeSrv);