window.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. package kubecost
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "regexp"
  7. "strconv"
  8. "time"
  9. )
  10. const (
  11. minutesPerDay = 60 * 24
  12. minutesPerHour = 60
  13. hoursPerDay = 24
  14. )
  15. // RoundBack rounds the given time back to a multiple of the given resolution
  16. // in the given time's timezone.
  17. // e.g. 2020-01-01T12:37:48-0700, 24h = 2020-01-01T00:00:00-0700
  18. func RoundBack(t time.Time, resolution time.Duration) time.Time {
  19. _, offSec := t.Zone()
  20. return t.Add(time.Duration(offSec) * time.Second).Truncate(resolution).Add(-time.Duration(offSec) * time.Second)
  21. }
  22. // RoundForward rounds the given time forward to a multiple of the given resolution
  23. // in the given time's timezone.
  24. // e.g. 2020-01-01T12:37:48-0700, 24h = 2020-01-02T00:00:00-0700
  25. func RoundForward(t time.Time, resolution time.Duration) time.Time {
  26. back := RoundBack(t, resolution)
  27. if back.Equal(t) {
  28. // The given time is exactly a multiple of the given resolution
  29. return t
  30. }
  31. return back.Add(resolution)
  32. }
  33. // Window defines a period of time with a start and an end. If either start or
  34. // end are nil it indicates an open time period.
  35. type Window struct {
  36. start *time.Time
  37. end *time.Time
  38. }
  39. // NewWindow creates and returns a new Window instance from the given times
  40. func NewWindow(start, end *time.Time) Window {
  41. return Window{
  42. start: start,
  43. end: end,
  44. }
  45. }
  46. // ParseWindowUTC attempts to parse the given string into a valid Window. It
  47. // accepts several formats, returning an error if the given string does not
  48. // match one of the following:
  49. // - named intervals: "today", "yesterday", "week", "month", "lastweek", "lastmonth"
  50. // - durations: "24h", "7d", etc.
  51. // - date ranges: "2020-04-01T00:00:00Z,2020-04-03T00:00:00Z", etc.
  52. // - timestamp ranges: "1586822400,1586908800", etc.
  53. func ParseWindowUTC(window string) (Window, error) {
  54. return parseWindow(window, time.Now().UTC())
  55. }
  56. // ParseWindowWithOffsetString parses the given window string within the context of
  57. // the timezone defined by the UTC offset string of format -07:00, +01:30, etc.
  58. func ParseWindowWithOffsetString(window string, offset string) (Window, error) {
  59. if offset == "UTC" || offset == "" {
  60. return ParseWindowUTC(window)
  61. }
  62. regex := regexp.MustCompile(`^(\+|-)(\d\d):(\d\d)$`)
  63. match := regex.FindStringSubmatch(offset)
  64. if match == nil {
  65. return Window{}, fmt.Errorf("illegal UTC offset: '%s'; should be of form '-07:00'", offset)
  66. }
  67. sig := 1
  68. if match[1] == "-" {
  69. sig = -1
  70. }
  71. hrs64, _ := strconv.ParseInt(match[2], 10, 64)
  72. hrs := sig * int(hrs64)
  73. mins64, _ := strconv.ParseInt(match[3], 10, 64)
  74. mins := sig * int(mins64)
  75. loc := time.FixedZone(fmt.Sprintf("UTC%s", offset), (hrs*60*60)+(mins*60))
  76. now := time.Now().In(loc)
  77. return parseWindow(window, now)
  78. }
  79. // ParseWindowWithOffset parses the given window string within the context of
  80. // the timezone defined by the UTC offset.
  81. func ParseWindowWithOffset(window string, offset time.Duration) (Window, error) {
  82. loc := time.FixedZone("", int(offset.Seconds()))
  83. now := time.Now().In(loc)
  84. return parseWindow(window, now)
  85. }
  86. // parseWindow generalizes the parsing of window strings, relative to a given
  87. // moment in time, defined as "now".
  88. func parseWindow(window string, now time.Time) (Window, error) {
  89. // compute UTC offset in terms of minutes
  90. offHr := now.UTC().Hour() - now.Hour()
  91. offMin := (now.UTC().Minute() - now.Minute()) + (offHr * 60)
  92. offset := time.Duration(offMin) * time.Minute
  93. if window == "today" {
  94. start := now
  95. start = start.Truncate(time.Hour * 24)
  96. start = start.Add(offset)
  97. end := start.Add(time.Hour * 24)
  98. return NewWindow(&start, &end), nil
  99. }
  100. if window == "yesterday" {
  101. start := now
  102. start = start.Truncate(time.Hour * 24)
  103. start = start.Add(offset)
  104. start = start.Add(time.Hour * -24)
  105. end := start.Add(time.Hour * 24)
  106. return NewWindow(&start, &end), nil
  107. }
  108. if window == "week" {
  109. // now
  110. start := now
  111. // 00:00 today, accounting for timezone offset
  112. start = start.Truncate(time.Hour * 24)
  113. start = start.Add(offset)
  114. // 00:00 Sunday of the current week
  115. start = start.Add(-24 * time.Hour * time.Duration(start.Weekday()))
  116. end := now
  117. return NewWindow(&start, &end), nil
  118. }
  119. if window == "lastweek" {
  120. // now
  121. start := now
  122. // 00:00 today, accounting for timezone offset
  123. start = start.Truncate(time.Hour * 24)
  124. start = start.Add(offset)
  125. // 00:00 Sunday of last week
  126. start = start.Add(-24 * time.Hour * time.Duration(start.Weekday()+7))
  127. end := start.Add(7 * 24 * time.Hour)
  128. return NewWindow(&start, &end), nil
  129. }
  130. if window == "month" {
  131. // now
  132. start := now
  133. // 00:00 today, accounting for timezone offset
  134. start = start.Truncate(time.Hour * 24)
  135. start = start.Add(offset)
  136. // 00:00 1st of this month
  137. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  138. end := now
  139. return NewWindow(&start, &end), nil
  140. }
  141. if window == "month" {
  142. // now
  143. start := now
  144. // 00:00 today, accounting for timezone offset
  145. start = start.Truncate(time.Hour * 24)
  146. start = start.Add(offset)
  147. // 00:00 1st of this month
  148. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  149. end := now
  150. return NewWindow(&start, &end), nil
  151. }
  152. if window == "lastmonth" {
  153. // now
  154. end := now
  155. // 00:00 today, accounting for timezone offset
  156. end = end.Truncate(time.Hour * 24)
  157. end = end.Add(offset)
  158. // 00:00 1st of this month
  159. end = end.Add(-24 * time.Hour * time.Duration(end.Day()-1))
  160. // 00:00 last day of last month
  161. start := end.Add(-24 * time.Hour)
  162. // 00:00 1st of last month
  163. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  164. return NewWindow(&start, &end), nil
  165. }
  166. // Match duration strings; e.g. "45m", "24h", "7d"
  167. regex := regexp.MustCompile(`^(\d+)(m|h|d)$`)
  168. match := regex.FindStringSubmatch(window)
  169. if match != nil {
  170. dur := time.Minute
  171. if match[2] == "h" {
  172. dur = time.Hour
  173. }
  174. if match[2] == "d" {
  175. dur = 24 * time.Hour
  176. }
  177. num, _ := strconv.ParseInt(match[1], 10, 64)
  178. end := now
  179. start := end.Add(-time.Duration(num) * dur)
  180. return NewWindow(&start, &end), nil
  181. }
  182. // Match duration strings with offset; e.g. "45m offset 15m", etc.
  183. regex = regexp.MustCompile(`^(\d+)(m|h|d) offset (\d+)(m|h|d)$`)
  184. match = regex.FindStringSubmatch(window)
  185. if match != nil {
  186. end := now
  187. offUnit := time.Minute
  188. if match[4] == "h" {
  189. offUnit = time.Hour
  190. }
  191. if match[4] == "d" {
  192. offUnit = 24 * time.Hour
  193. }
  194. offNum, _ := strconv.ParseInt(match[3], 10, 64)
  195. end = end.Add(-time.Duration(offNum) * offUnit)
  196. durUnit := time.Minute
  197. if match[2] == "h" {
  198. durUnit = time.Hour
  199. }
  200. if match[2] == "d" {
  201. durUnit = 24 * time.Hour
  202. }
  203. durNum, _ := strconv.ParseInt(match[1], 10, 64)
  204. start := end.Add(-time.Duration(durNum) * durUnit)
  205. return NewWindow(&start, &end), nil
  206. }
  207. // Match timestamp pairs, e.g. "1586822400,1586908800" or "1586822400-1586908800"
  208. regex = regexp.MustCompile(`^(\d+)[,|-](\d+)$`)
  209. match = regex.FindStringSubmatch(window)
  210. if match != nil {
  211. s, _ := strconv.ParseInt(match[1], 10, 64)
  212. e, _ := strconv.ParseInt(match[2], 10, 64)
  213. start := time.Unix(s, 0)
  214. end := time.Unix(e, 0)
  215. return NewWindow(&start, &end), nil
  216. }
  217. // Match RFC3339 pairs, e.g. "2020-04-01T00:00:00Z,2020-04-03T00:00:00Z"
  218. rfc3339 := `\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ`
  219. regex = regexp.MustCompile(fmt.Sprintf(`(%s),(%s)`, rfc3339, rfc3339))
  220. match = regex.FindStringSubmatch(window)
  221. if match != nil {
  222. start, _ := time.Parse(time.RFC3339, match[1])
  223. end, _ := time.Parse(time.RFC3339, match[2])
  224. return NewWindow(&start, &end), nil
  225. }
  226. return Window{nil, nil}, fmt.Errorf("illegal window: %s", window)
  227. }
  228. // ApproximatelyEqual returns true if the start and end times of the two windows,
  229. // respectively, are within the given threshold of each other.
  230. func (w Window) ApproximatelyEqual(that Window, threshold time.Duration) bool {
  231. return approxEqual(w.start, that.start, threshold) && approxEqual(w.end, that.end, threshold)
  232. }
  233. func approxEqual(x *time.Time, y *time.Time, threshold time.Duration) bool {
  234. // both times are nil, so they are equal
  235. if x == nil && y == nil {
  236. return true
  237. }
  238. // one time is nil, but the other is not, so they are not equal
  239. if x == nil || y == nil {
  240. return false
  241. }
  242. // neither time is nil, so they are approximately close if their times are
  243. // within the given threshold
  244. delta := math.Abs((*x).Sub(*y).Seconds())
  245. return delta < threshold.Seconds()
  246. }
  247. func (w Window) Clone() Window {
  248. var start, end *time.Time
  249. var s, e time.Time
  250. if w.start != nil {
  251. s = *w.start
  252. start = &s
  253. }
  254. if w.end != nil {
  255. e = *w.end
  256. end = &e
  257. }
  258. return NewWindow(start, end)
  259. }
  260. func (w Window) Contains(t time.Time) bool {
  261. if w.start != nil && t.Before(*w.start) {
  262. return false
  263. }
  264. if w.end != nil && t.After(*w.end) {
  265. return false
  266. }
  267. return true
  268. }
  269. func (w Window) Duration() time.Duration {
  270. if w.start != nil && w.end != nil {
  271. return w.end.Sub(*w.start)
  272. }
  273. return 0
  274. }
  275. func (w Window) End() *time.Time {
  276. return w.end
  277. }
  278. func (w Window) Equal(that Window) bool {
  279. if w.start != nil && that.start != nil && !w.start.Equal(*that.start) {
  280. // starts are not nil, but not equal
  281. return false
  282. }
  283. if w.end != nil && that.end != nil && !w.end.Equal(*that.end) {
  284. // ends are not nil, but not equal
  285. return false
  286. }
  287. if (w.start == nil && that.start != nil) || (w.start != nil && that.start == nil) {
  288. // one start is nil, the other is not
  289. return false
  290. }
  291. if (w.end == nil && that.end != nil) || (w.end != nil && that.end == nil) {
  292. // one end is nil, the other is not
  293. return false
  294. }
  295. // either both starts are nil, or they match; likewise for the ends
  296. return true
  297. }
  298. func (w Window) ExpandStart(start time.Time) Window {
  299. if w.start == nil || start.Before(*w.start) {
  300. w.start = &start
  301. }
  302. return w
  303. }
  304. func (w Window) ExpandEnd(end time.Time) Window {
  305. if w.end == nil || end.After(*w.end) {
  306. w.end = &end
  307. }
  308. return w
  309. }
  310. func (w Window) Expand(that Window) Window {
  311. return w.ExpandStart(*that.start).ExpandEnd(*that.end)
  312. }
  313. func (w Window) MarshalJSON() ([]byte, error) {
  314. buffer := bytes.NewBufferString("{")
  315. buffer.WriteString(fmt.Sprintf("\"start\":\"%s\",", w.start.Format("2006-01-02T15:04:05-0700")))
  316. buffer.WriteString(fmt.Sprintf("\"end\":\"%s\"", w.end.Format("2006-01-02T15:04:05-0700")))
  317. buffer.WriteString("}")
  318. return buffer.Bytes(), nil
  319. }
  320. func (w Window) Minutes() float64 {
  321. if w.start == nil || w.end == nil {
  322. return math.Inf(1)
  323. }
  324. return w.end.Sub(*w.start).Minutes()
  325. }
  326. // Shift adds the given duration to both the start and end times of the window
  327. func (w Window) Shift(dur time.Duration) Window {
  328. if w.start != nil {
  329. s := w.start.Add(dur)
  330. w.start = &s
  331. }
  332. if w.end != nil {
  333. e := w.end.Add(dur)
  334. w.end = &e
  335. }
  336. return w
  337. }
  338. func (w Window) Start() *time.Time {
  339. return w.start
  340. }
  341. func (w Window) String() string {
  342. if w.start == nil && w.end == nil {
  343. return "[nil, nil)"
  344. }
  345. if w.start == nil {
  346. return fmt.Sprintf("[nil, %s)", w.end.Format("2006-01-02T15:04:05-0700"))
  347. }
  348. if w.end == nil {
  349. return fmt.Sprintf("[%s, nil)", w.start.Format("2006-01-02T15:04:05-0700"))
  350. }
  351. return fmt.Sprintf("[%s, %s)", w.start.Format("2006-01-02T15:04:05-0700"), w.end.Format("2006-01-02T15:04:05-0700"))
  352. }
  353. // ToDurationOffset returns formatted strings representing the duration and
  354. // offset of the window in terms of minutes; e.g. ("30m", "1m")
  355. func (w Window) ToDurationOffset() (string, string) {
  356. durMins := int(w.Duration().Minutes())
  357. offStr := ""
  358. if w.End() != nil {
  359. offMins := int(time.Now().Sub(*w.End()).Minutes())
  360. if offMins > 1 {
  361. offStr = fmt.Sprintf("%dm", int(offMins))
  362. } else if offMins < -1 {
  363. durMins += offMins
  364. }
  365. }
  366. // default to formatting in terms of minutes
  367. durStr := fmt.Sprintf("%dm", durMins)
  368. if (durMins >= minutesPerDay) && (durMins%minutesPerDay == 0) {
  369. // convert to days
  370. durStr = fmt.Sprintf("%dd", durMins/minutesPerDay)
  371. } else if (durMins >= minutesPerHour) && (durMins%minutesPerHour == 0) {
  372. // convert to hours
  373. durStr = fmt.Sprintf("%dh", durMins/minutesPerHour)
  374. }
  375. return durStr, offStr
  376. }
  377. type BoundaryError struct {
  378. Requested Window
  379. Supported Window
  380. Message string
  381. }
  382. func NewBoundaryError(req, sup Window, msg string) *BoundaryError {
  383. return &BoundaryError{
  384. Requested: req,
  385. Supported: sup,
  386. Message: msg,
  387. }
  388. }
  389. func (be *BoundaryError) Error() string {
  390. if be == nil {
  391. return "<nil>"
  392. }
  393. return fmt.Sprintf("boundary error: requested %s; supported %s: %s", be.Requested, be.Supported, be.Message)
  394. }