timeutil.go 13 KB

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