timeutil.go 12 KB

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