timeutil.go 13 KB

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