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