TimeSrv.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 getTimeWindow(time: string, timeWindow: string) {
  81. const valueTime = parseInt(time, 10);
  82. let timeWindowMs;
  83. if (timeWindow.match(/^\d+$/) && parseInt(timeWindow, 10)) {
  84. // when time window specified in ms
  85. timeWindowMs = parseInt(timeWindow, 10);
  86. } else {
  87. timeWindowMs = kbn.interval_to_ms(timeWindow);
  88. }
  89. return {
  90. from: toUtc(valueTime - timeWindowMs / 2),
  91. to: toUtc(valueTime + timeWindowMs / 2),
  92. };
  93. }
  94. private initTimeFromUrl() {
  95. const params = this.$location.search();
  96. if (params.time && params['time.window']) {
  97. this.time = this.getTimeWindow(params.time, params['time.window']);
  98. }
  99. if (params.from) {
  100. this.time.from = this.parseUrlParam(params.from) || this.time.from;
  101. }
  102. if (params.to) {
  103. this.time.to = this.parseUrlParam(params.to) || this.time.to;
  104. }
  105. // if absolute ignore refresh option saved to dashboard
  106. if (params.to && params.to.indexOf('now') === -1) {
  107. this.refresh = false;
  108. this.dashboard.refresh = false;
  109. }
  110. // but if refresh explicitly set then use that
  111. if (params.refresh) {
  112. this.refresh = params.refresh || this.refresh;
  113. }
  114. }
  115. private routeUpdated() {
  116. const params = this.$location.search();
  117. if (params.left) {
  118. return; // explore handles this;
  119. }
  120. const urlRange = this.timeRangeForUrl();
  121. // check if url has time range
  122. if (params.from && params.to) {
  123. // is it different from what our current time range?
  124. if (params.from !== urlRange.from || params.to !== urlRange.to) {
  125. // issue update
  126. this.initTimeFromUrl();
  127. this.setTime(this.time, true);
  128. }
  129. } else if (this.timeHasChangedSinceLoad()) {
  130. this.setTime(this.timeAtLoad, true);
  131. }
  132. }
  133. private timeHasChangedSinceLoad() {
  134. return this.timeAtLoad && (this.timeAtLoad.from !== this.time.from || this.timeAtLoad.to !== this.time.to);
  135. }
  136. setAutoRefresh(interval: any) {
  137. this.dashboard.refresh = interval;
  138. this.cancelNextRefresh();
  139. if (interval) {
  140. const intervalMs = kbn.interval_to_ms(interval);
  141. this.refreshTimer = this.timer.register(
  142. this.$timeout(() => {
  143. this.startNextRefreshTimer(intervalMs);
  144. this.refreshDashboard();
  145. }, intervalMs)
  146. );
  147. }
  148. // update url inside timeout to so that a digest happens after (called from react)
  149. this.$timeout(() => {
  150. const params = this.$location.search();
  151. if (interval) {
  152. params.refresh = interval;
  153. this.$location.search(params);
  154. } else if (params.refresh) {
  155. delete params.refresh;
  156. this.$location.search(params);
  157. }
  158. });
  159. }
  160. refreshDashboard() {
  161. this.dashboard.timeRangeUpdated(this.timeRange());
  162. }
  163. private startNextRefreshTimer(afterMs: number) {
  164. this.cancelNextRefresh();
  165. this.refreshTimer = this.timer.register(
  166. this.$timeout(() => {
  167. this.startNextRefreshTimer(afterMs);
  168. if (this.contextSrv.isGrafanaVisible()) {
  169. this.refreshDashboard();
  170. } else {
  171. this.autoRefreshBlocked = true;
  172. }
  173. }, afterMs)
  174. );
  175. }
  176. private cancelNextRefresh() {
  177. this.timer.cancel(this.refreshTimer);
  178. }
  179. setTime(time: RawTimeRange, fromRouteUpdate?: boolean) {
  180. _.extend(this.time, time);
  181. // disable refresh if zoom in or zoom out
  182. if (isDateTime(time.to)) {
  183. this.oldRefresh = this.dashboard.refresh || this.oldRefresh;
  184. this.setAutoRefresh(false);
  185. } else if (this.oldRefresh && this.oldRefresh !== this.dashboard.refresh) {
  186. this.setAutoRefresh(this.oldRefresh);
  187. this.oldRefresh = null;
  188. }
  189. // update url
  190. if (fromRouteUpdate !== true) {
  191. const urlRange = this.timeRangeForUrl();
  192. const urlParams = this.$location.search();
  193. urlParams.from = urlRange.from;
  194. urlParams.to = urlRange.to;
  195. this.$location.search(urlParams);
  196. }
  197. this.$timeout(this.refreshDashboard.bind(this), 0);
  198. }
  199. timeRangeForUrl() {
  200. const range = this.timeRange().raw;
  201. if (isDateTime(range.from)) {
  202. range.from = range.from.valueOf().toString();
  203. }
  204. if (isDateTime(range.to)) {
  205. range.to = range.to.valueOf().toString();
  206. }
  207. return range;
  208. }
  209. timeRange(): TimeRange {
  210. // make copies if they are moment (do not want to return out internal moment, because they are mutable!)
  211. const raw = {
  212. from: isDateTime(this.time.from) ? dateTime(this.time.from) : this.time.from,
  213. to: isDateTime(this.time.to) ? dateTime(this.time.to) : this.time.to,
  214. };
  215. const timezone: TimeZone = this.dashboard ? this.dashboard.getTimezone() : undefined;
  216. return {
  217. from: dateMath.parse(raw.from, false, timezone),
  218. to: dateMath.parse(raw.to, true, timezone),
  219. raw: raw,
  220. };
  221. }
  222. zoomOut(e: any, factor: number) {
  223. const range = this.timeRange();
  224. const { from, to } = getZoomedTimeRange(range, factor);
  225. this.setTime({ from: toUtc(from), to: toUtc(to) });
  226. }
  227. shiftTime(e: any, direction: number) {
  228. const range = this.timeRange();
  229. const { from, to } = getShiftedTimeRange(direction, range);
  230. this.setTime({
  231. from: toUtc(from),
  232. to: toUtc(to),
  233. });
  234. }
  235. }
  236. let singleton: TimeSrv;
  237. export function setTimeSrv(srv: TimeSrv) {
  238. singleton = srv;
  239. }
  240. export function getTimeSrv(): TimeSrv {
  241. return singleton;
  242. }
  243. coreModule.service('timeSrv', TimeSrv);