timeutil.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. package timeutil
  2. import (
  3. "errors"
  4. "fmt"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. )
  11. const (
  12. // SecsPerMin expresses the amount of seconds in a minute
  13. SecsPerMin = 60.0
  14. // SecsPerHour expresses the amount of seconds in a minute
  15. SecsPerHour = 3600.0
  16. // SecsPerDay expressed the amount of seconds in a day
  17. SecsPerDay = 86400.0
  18. // MinsPerHour expresses the amount of minutes in an hour
  19. MinsPerHour = 60.0
  20. // MinsPerDay expresses the amount of minutes in a day
  21. MinsPerDay = 1440.0
  22. // HoursPerDay expresses the amount of hours in a day
  23. HoursPerDay = 24.0
  24. // HoursPerMonth expresses the amount of hours in a month
  25. HoursPerMonth = 730.0
  26. // DaysPerMonth expresses the amount of days in a month
  27. DaysPerMonth = 30.42
  28. // Day expresses 24 hours
  29. Day = time.Hour * 24.0
  30. Week = Day * 7.0
  31. )
  32. // DurationString converts a duration to a Prometheus-compatible string in
  33. // terms of days, hours, minutes, or seconds.
  34. func DurationString(duration time.Duration) string {
  35. durSecs := int64(duration.Seconds())
  36. durStr := ""
  37. if durSecs > 0 {
  38. if durSecs%SecsPerDay == 0 {
  39. // convert to days
  40. durStr = fmt.Sprintf("%dd", durSecs/SecsPerDay)
  41. } else if durSecs%SecsPerHour == 0 {
  42. // convert to hours
  43. durStr = fmt.Sprintf("%dh", durSecs/SecsPerHour)
  44. } else if durSecs%SecsPerMin == 0 {
  45. // convert to mins
  46. durStr = fmt.Sprintf("%dm", durSecs/SecsPerMin)
  47. } else if durSecs > 0 {
  48. // default to secs, as long as duration is positive
  49. durStr = fmt.Sprintf("%ds", durSecs)
  50. }
  51. }
  52. return durStr
  53. }
  54. // DurationToPromOffsetString returns a Prometheus formatted string with leading offset or empty string if given a negative duration
  55. func DurationToPromOffsetString(duration time.Duration) string {
  56. dirStr := DurationString(duration)
  57. if dirStr != "" {
  58. dirStr = fmt.Sprintf("offset %s", dirStr)
  59. }
  60. return dirStr
  61. }
  62. // DurationOffsetStrings converts a (duration, offset) pair to Prometheus-
  63. // compatible strings in terms of days, hours, minutes, or seconds.
  64. func DurationOffsetStrings(duration, offset time.Duration) (string, string) {
  65. return DurationString(duration), DurationString(offset)
  66. }
  67. // FormatStoreResolution provides a clean notation for ETL store resolutions.
  68. // e.g. daily => 1d; hourly => 1h
  69. func FormatStoreResolution(dur time.Duration) string {
  70. if dur >= 24*time.Hour {
  71. return fmt.Sprintf("%dd", int(dur.Hours()/24.0))
  72. } else if dur >= time.Hour {
  73. return fmt.Sprintf("%dh", int(dur.Hours()))
  74. }
  75. return fmt.Sprint(dur)
  76. }
  77. // ParseDuration parses a duration string.
  78. // A duration string is a possibly signed sequence of
  79. // decimal numbers, each with optional fraction and a unit suffix,
  80. // such as "300ms", "-1.5h" or "2h45m".
  81. // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h", "d"
  82. func ParseDuration(duration string) (time.Duration, error) {
  83. duration = CleanDurationString(duration)
  84. return goParseDuration(duration)
  85. }
  86. // unitMap contains a list of units that can be parsed by ParseDuration
  87. var unitMap = map[string]int64{
  88. "ns": int64(time.Nanosecond),
  89. "us": int64(time.Microsecond),
  90. "µs": int64(time.Microsecond), // U+00B5 = micro symbol
  91. "μs": int64(time.Microsecond), // U+03BC = Greek letter mu
  92. "ms": int64(time.Millisecond),
  93. "s": int64(time.Second),
  94. "m": int64(time.Minute),
  95. "h": int64(time.Hour),
  96. "d": int64(Day),
  97. "w": int64(Week),
  98. }
  99. // goParseDuration is time.ParseDuration lifted from the go std library and enhanced with the ability to
  100. // handle the "d" (day) unit. The contents of the function itself are identical to the std library, it is
  101. // only the unitMap above that contains the added unit.
  102. func goParseDuration(s string) (time.Duration, error) {
  103. // [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+
  104. orig := s
  105. var d int64
  106. neg := false
  107. // Consume [-+]?
  108. if s != "" {
  109. c := s[0]
  110. if c == '-' || c == '+' {
  111. neg = c == '-'
  112. s = s[1:]
  113. }
  114. }
  115. // Special case: if all that is left is "0", this is zero.
  116. if s == "0" {
  117. return 0, nil
  118. }
  119. if s == "" {
  120. return 0, errors.New("time: invalid duration " + quote(orig))
  121. }
  122. for s != "" {
  123. var (
  124. v, f int64 // integers before, after decimal point
  125. scale float64 = 1 // value = v + f/scale
  126. )
  127. var err error
  128. // The next character must be [0-9.]
  129. if !(s[0] == '.' || '0' <= s[0] && s[0] <= '9') {
  130. return 0, errors.New("time: invalid duration " + quote(orig))
  131. }
  132. // Consume [0-9]*
  133. pl := len(s)
  134. v, s, err = leadingInt(s)
  135. if err != nil {
  136. return 0, errors.New("time: invalid duration " + quote(orig))
  137. }
  138. pre := pl != len(s) // whether we consumed anything before a period
  139. // Consume (\.[0-9]*)?
  140. post := false
  141. if s != "" && s[0] == '.' {
  142. s = s[1:]
  143. pl := len(s)
  144. f, scale, s = leadingFraction(s)
  145. post = pl != len(s)
  146. }
  147. if !pre && !post {
  148. // no digits (e.g. ".s" or "-.s")
  149. return 0, errors.New("time: invalid duration " + quote(orig))
  150. }
  151. // Consume unit.
  152. i := 0
  153. for ; i < len(s); i++ {
  154. c := s[i]
  155. if c == '.' || '0' <= c && c <= '9' {
  156. break
  157. }
  158. }
  159. if i == 0 {
  160. return 0, errors.New("time: missing unit in duration " + quote(orig))
  161. }
  162. u := s[:i]
  163. s = s[i:]
  164. unit, ok := unitMap[u]
  165. if !ok {
  166. return 0, errors.New("time: unknown unit " + quote(u) + " in duration " + quote(orig))
  167. }
  168. if v > (1<<63-1)/unit {
  169. // overflow
  170. return 0, errors.New("time: invalid duration " + quote(orig))
  171. }
  172. v *= unit
  173. if f > 0 {
  174. // float64 is needed to be nanosecond accurate for fractions of hours.
  175. // v >= 0 && (f*unit/scale) <= 3.6e+12 (ns/h, h is the largest unit)
  176. v += int64(float64(f) * (float64(unit) / scale))
  177. if v < 0 {
  178. // overflow
  179. return 0, errors.New("time: invalid duration " + quote(orig))
  180. }
  181. }
  182. d += v
  183. if d < 0 {
  184. // overflow
  185. return 0, errors.New("time: invalid duration " + quote(orig))
  186. }
  187. }
  188. if neg {
  189. d = -d
  190. }
  191. return time.Duration(d), nil
  192. }
  193. // CleanDurationString removes prometheus formatted prefix "offset " allong with leading a trailing whitespace
  194. // from duration string, leaving behind a string with format [0-9+](s|m|d|h)
  195. func CleanDurationString(duration string) string {
  196. duration = strings.TrimSpace(duration)
  197. duration = strings.TrimPrefix(duration, "offset ")
  198. return duration
  199. }
  200. // ParseTimeRange returns a start and end time, respectively, which are converted from
  201. // a duration and offset, defined as strings with Prometheus-style syntax.
  202. func ParseTimeRange(duration, offset time.Duration) (time.Time, time.Time) {
  203. // endTime defaults to the current time, unless an offset is explicitly declared,
  204. // in which case it shifts endTime back by given duration
  205. endTime := time.Now()
  206. if offset > 0 {
  207. endTime = endTime.Add(-1 * offset)
  208. }
  209. startTime := endTime.Add(-1 * duration)
  210. return startTime, endTime
  211. }
  212. // FormatDurationStringDaysToHours converts string from format [0-9+]d to [0-9+]h
  213. func FormatDurationStringDaysToHours(param string) (string, error) {
  214. //check that input matches format
  215. ok, err := regexp.MatchString("[0-9+]d", param)
  216. if !ok {
  217. return param, fmt.Errorf("FormatDurationStringDaysToHours: input string (%s) not formatted as [0-9+]d", param)
  218. }
  219. if err != nil {
  220. return "", err
  221. }
  222. // convert days to hours
  223. if param[len(param)-1:] == "d" {
  224. count := param[:len(param)-1]
  225. val, err := strconv.ParseInt(count, 10, 64)
  226. if err != nil {
  227. return "", err
  228. }
  229. val = val * 24
  230. param = fmt.Sprintf("%dh", val)
  231. }
  232. return param, nil
  233. }
  234. // RoundToStartOfWeek creates a new time.Time for the preceding Sunday 00:00 UTC
  235. func RoundToStartOfWeek(t time.Time) time.Time {
  236. date := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
  237. daysFromSunday := int(date.Weekday())
  238. return date.Add(-1 * time.Duration(daysFromSunday) * Day)
  239. }
  240. // RoundToStartOfFollowingWeek creates a new time.Time for the following Sunday 00:00 UTC
  241. func RoundToStartOfFollowingWeek(t time.Time) time.Time {
  242. date := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
  243. daysFromSunday := 7 - int(date.Weekday())
  244. return date.Add(time.Duration(daysFromSunday) * Day)
  245. }
  246. // JobTicker is a ticker used to synchronize the next run of a repeating
  247. // process. The designated use-case is for infinitely-looping selects,
  248. // where a timeout or an exit channel might cancel the process, but otherwise
  249. // the intent is to wait at the select for some amount of time until the
  250. // next run. This differs from a standard ticker, which ticks without
  251. // waiting and drops any missed ticks; rather, this ticker must be kicked
  252. // off manually for each tick, so that after the current run of the job
  253. // completes, the timer starts again.
  254. type JobTicker struct {
  255. Ch <-chan time.Time
  256. ch chan time.Time
  257. closed bool
  258. mx sync.Mutex
  259. }
  260. // NewJobTicker instantiates a new JobTicker.
  261. func NewJobTicker() *JobTicker {
  262. c := make(chan time.Time)
  263. return &JobTicker{
  264. Ch: c,
  265. ch: c,
  266. closed: false,
  267. }
  268. }
  269. // Close closes the JobTicker channels
  270. func (jt *JobTicker) Close() {
  271. jt.mx.Lock()
  272. defer jt.mx.Unlock()
  273. if jt.closed {
  274. return
  275. }
  276. jt.closed = true
  277. close(jt.ch)
  278. }
  279. // TickAt schedules the next tick of the ticker for the given time in the
  280. // future. If the time is not in the future, the ticker will tick immediately.
  281. func (jt *JobTicker) TickAt(t time.Time) {
  282. go func(t time.Time) {
  283. n := time.Now()
  284. if t.After(n) {
  285. time.Sleep(t.Sub(n))
  286. }
  287. jt.mx.Lock()
  288. defer jt.mx.Unlock()
  289. if !jt.closed {
  290. jt.ch <- time.Now()
  291. }
  292. }(t)
  293. }
  294. // TickIn schedules the next tick of the ticker for the given duration into
  295. // the future. If the duration is less than or equal to zero, the ticker will
  296. // tick immediately.
  297. func (jt *JobTicker) TickIn(d time.Duration) {
  298. go func(d time.Duration) {
  299. if d > 0 {
  300. time.Sleep(d)
  301. }
  302. jt.mx.Lock()
  303. defer jt.mx.Unlock()
  304. if !jt.closed {
  305. jt.ch <- time.Now()
  306. }
  307. }(d)
  308. }
  309. // NOTE: The following functions were lifted from the go std library to support the ParseDuration enhancement
  310. // NOTE: described above.
  311. const (
  312. lowerhex = "0123456789abcdef"
  313. runeSelf = 0x80
  314. runeError = '\uFFFD'
  315. )
  316. // quote is lifted from the go std library to support the custom ParseDuration enhancement
  317. func quote(s string) string {
  318. buf := make([]byte, 1, len(s)+2) // slice will be at least len(s) + quotes
  319. buf[0] = '"'
  320. for i, c := range s {
  321. if c >= runeSelf || c < ' ' {
  322. // This means you are asking us to parse a time.Duration or
  323. // time.Location with unprintable or non-ASCII characters in it.
  324. // We don't expect to hit this case very often. We could try to
  325. // reproduce strconv.Quote's behavior with full fidelity but
  326. // given how rarely we expect to hit these edge cases, speed and
  327. // conciseness are better.
  328. var width int
  329. if c == runeError {
  330. width = 1
  331. if i+2 < len(s) && s[i:i+3] == string(runeError) {
  332. width = 3
  333. }
  334. } else {
  335. width = len(string(c))
  336. }
  337. for j := 0; j < width; j++ {
  338. buf = append(buf, `\x`...)
  339. buf = append(buf, lowerhex[s[i+j]>>4])
  340. buf = append(buf, lowerhex[s[i+j]&0xF])
  341. }
  342. } else {
  343. if c == '"' || c == '\\' {
  344. buf = append(buf, '\\')
  345. }
  346. buf = append(buf, string(c)...)
  347. }
  348. }
  349. buf = append(buf, '"')
  350. return string(buf)
  351. }
  352. // leadingFraction consumes the leading [0-9]* from s.
  353. // It is used only for fractions, so does not return an error on overflow,
  354. // it just stops accumulating precision.
  355. func leadingFraction(s string) (x int64, scale float64, rem string) {
  356. i := 0
  357. scale = 1
  358. overflow := false
  359. for ; i < len(s); i++ {
  360. c := s[i]
  361. if c < '0' || c > '9' {
  362. break
  363. }
  364. if overflow {
  365. continue
  366. }
  367. if x > (1<<63-1)/10 {
  368. // It's possible for overflow to give a positive number, so take care.
  369. overflow = true
  370. continue
  371. }
  372. y := x*10 + int64(c) - '0'
  373. if y < 0 {
  374. overflow = true
  375. continue
  376. }
  377. x = y
  378. scale *= 10
  379. }
  380. return x, scale, s[i:]
  381. }
  382. var errLeadingInt = errors.New("time: bad [0-9]*") // never printed
  383. // leadingInt consumes the leading [0-9]* from s.
  384. func leadingInt(s string) (x int64, rem string, err error) {
  385. i := 0
  386. for ; i < len(s); i++ {
  387. c := s[i]
  388. if c < '0' || c > '9' {
  389. break
  390. }
  391. if x > (1<<63-1)/10 {
  392. // overflow
  393. return 0, "", errLeadingInt
  394. }
  395. x = x*10 + int64(c) - '0'
  396. if x < 0 {
  397. // overflow
  398. return 0, "", errLeadingInt
  399. }
  400. }
  401. return x, s[i:], nil
  402. }
  403. // EarlierOf returns the second time passed in if both are equal
  404. func EarlierOf(timeOne, timeTwo time.Time) time.Time {
  405. if timeOne.Before(timeTwo) {
  406. return timeOne
  407. }
  408. return timeTwo
  409. }
  410. // LaterOf returns the second time passed in if both are equal
  411. func LaterOf(timeOne, timeTwo time.Time) time.Time {
  412. if timeOne.After(timeTwo) {
  413. return timeOne
  414. }
  415. return timeTwo
  416. }