timeutil.go 13 KB

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