TimeSrv.ts 7.3 KB

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