window.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. package kubecost
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "regexp"
  7. "strconv"
  8. "time"
  9. "github.com/kubecost/cost-model/pkg/util/timeutil"
  10. "github.com/kubecost/cost-model/pkg/env"
  11. "github.com/kubecost/cost-model/pkg/thanos"
  12. )
  13. const (
  14. minutesPerDay = 60 * 24
  15. minutesPerHour = 60
  16. hoursPerDay = 24
  17. )
  18. // RoundBack rounds the given time back to a multiple of the given resolution
  19. // in the given time's timezone.
  20. // e.g. 2020-01-01T12:37:48-0700, 24h = 2020-01-01T00:00:00-0700
  21. func RoundBack(t time.Time, resolution time.Duration) time.Time {
  22. _, offSec := t.Zone()
  23. return t.Add(time.Duration(offSec) * time.Second).Truncate(resolution).Add(-time.Duration(offSec) * time.Second)
  24. }
  25. // RoundForward rounds the given time forward to a multiple of the given resolution
  26. // in the given time's timezone.
  27. // e.g. 2020-01-01T12:37:48-0700, 24h = 2020-01-02T00:00:00-0700
  28. func RoundForward(t time.Time, resolution time.Duration) time.Time {
  29. back := RoundBack(t, resolution)
  30. if back.Equal(t) {
  31. // The given time is exactly a multiple of the given resolution
  32. return t
  33. }
  34. return back.Add(resolution)
  35. }
  36. // Window defines a period of time with a start and an end. If either start or
  37. // end are nil it indicates an open time period.
  38. type Window struct {
  39. start *time.Time
  40. end *time.Time
  41. }
  42. // NewWindow creates and returns a new Window instance from the given times
  43. func NewWindow(start, end *time.Time) Window {
  44. return Window{
  45. start: start,
  46. end: end,
  47. }
  48. }
  49. // NewClosedWindow creates and returns a new Window instance from the given
  50. // times, which cannot be nil, so they are value types.
  51. func NewClosedWindow(start, end time.Time) Window {
  52. return Window{
  53. start: &start,
  54. end: &end,
  55. }
  56. }
  57. // ParseWindowUTC attempts to parse the given string into a valid Window. It
  58. // accepts several formats, returning an error if the given string does not
  59. // match one of the following:
  60. // - named intervals: "today", "yesterday", "week", "month", "lastweek", "lastmonth"
  61. // - durations: "24h", "7d", etc.
  62. // - date ranges: "2020-04-01T00:00:00Z,2020-04-03T00:00:00Z", etc.
  63. // - timestamp ranges: "1586822400,1586908800", etc.
  64. func ParseWindowUTC(window string) (Window, error) {
  65. return parseWindow(window, time.Now().UTC())
  66. }
  67. // ParseWindowWithOffsetString parses the given window string within the context of
  68. // the timezone defined by the UTC offset string of format -07:00, +01:30, etc.
  69. func ParseWindowWithOffsetString(window string, offset string) (Window, error) {
  70. if offset == "UTC" || offset == "" {
  71. return ParseWindowUTC(window)
  72. }
  73. regex := regexp.MustCompile(`^(\+|-)(\d\d):(\d\d)$`)
  74. match := regex.FindStringSubmatch(offset)
  75. if match == nil {
  76. return Window{}, fmt.Errorf("illegal UTC offset: '%s'; should be of form '-07:00'", offset)
  77. }
  78. sig := 1
  79. if match[1] == "-" {
  80. sig = -1
  81. }
  82. hrs64, _ := strconv.ParseInt(match[2], 10, 64)
  83. hrs := sig * int(hrs64)
  84. mins64, _ := strconv.ParseInt(match[3], 10, 64)
  85. mins := sig * int(mins64)
  86. loc := time.FixedZone(fmt.Sprintf("UTC%s", offset), (hrs*60*60)+(mins*60))
  87. now := time.Now().In(loc)
  88. return parseWindow(window, now)
  89. }
  90. // ParseWindowWithOffset parses the given window string within the context of
  91. // the timezone defined by the UTC offset.
  92. func ParseWindowWithOffset(window string, offset time.Duration) (Window, error) {
  93. loc := time.FixedZone("", int(offset.Seconds()))
  94. now := time.Now().In(loc)
  95. return parseWindow(window, now)
  96. }
  97. // parseWindow generalizes the parsing of window strings, relative to a given
  98. // moment in time, defined as "now".
  99. func parseWindow(window string, now time.Time) (Window, error) {
  100. // compute UTC offset in terms of minutes
  101. offHr := now.UTC().Hour() - now.Hour()
  102. offMin := (now.UTC().Minute() - now.Minute()) + (offHr * 60)
  103. offset := time.Duration(offMin) * time.Minute
  104. if window == "today" {
  105. start := now
  106. start = start.Truncate(time.Hour * 24)
  107. start = start.Add(offset)
  108. end := start.Add(time.Hour * 24)
  109. return NewWindow(&start, &end), nil
  110. }
  111. if window == "yesterday" {
  112. start := now
  113. start = start.Truncate(time.Hour * 24)
  114. start = start.Add(offset)
  115. start = start.Add(time.Hour * -24)
  116. end := start.Add(time.Hour * 24)
  117. return NewWindow(&start, &end), nil
  118. }
  119. if window == "week" {
  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 the current week
  126. start = start.Add(-24 * time.Hour * time.Duration(start.Weekday()))
  127. end := now
  128. return NewWindow(&start, &end), nil
  129. }
  130. if window == "lastweek" {
  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 Sunday of last week
  137. start = start.Add(-24 * time.Hour * time.Duration(start.Weekday()+7))
  138. end := start.Add(7 * 24 * time.Hour)
  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 == "month" {
  153. // now
  154. start := now
  155. // 00:00 today, accounting for timezone offset
  156. start = start.Truncate(time.Hour * 24)
  157. start = start.Add(offset)
  158. // 00:00 1st of this month
  159. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  160. end := now
  161. return NewWindow(&start, &end), nil
  162. }
  163. if window == "lastmonth" {
  164. // now
  165. end := now
  166. // 00:00 today, accounting for timezone offset
  167. end = end.Truncate(time.Hour * 24)
  168. end = end.Add(offset)
  169. // 00:00 1st of this month
  170. end = end.Add(-24 * time.Hour * time.Duration(end.Day()-1))
  171. // 00:00 last day of last month
  172. start := end.Add(-24 * time.Hour)
  173. // 00:00 1st of last month
  174. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  175. return NewWindow(&start, &end), nil
  176. }
  177. // Match duration strings; e.g. "45m", "24h", "7d"
  178. regex := regexp.MustCompile(`^(\d+)(m|h|d)$`)
  179. match := regex.FindStringSubmatch(window)
  180. if match != nil {
  181. dur := time.Minute
  182. if match[2] == "h" {
  183. dur = time.Hour
  184. }
  185. if match[2] == "d" {
  186. dur = 24 * time.Hour
  187. }
  188. num, _ := strconv.ParseInt(match[1], 10, 64)
  189. end := now
  190. start := end.Add(-time.Duration(num) * dur)
  191. return NewWindow(&start, &end), nil
  192. }
  193. // Match duration strings with offset; e.g. "45m offset 15m", etc.
  194. regex = regexp.MustCompile(`^(\d+)(m|h|d) offset (\d+)(m|h|d)$`)
  195. match = regex.FindStringSubmatch(window)
  196. if match != nil {
  197. end := now
  198. offUnit := time.Minute
  199. if match[4] == "h" {
  200. offUnit = time.Hour
  201. }
  202. if match[4] == "d" {
  203. offUnit = 24 * time.Hour
  204. }
  205. offNum, _ := strconv.ParseInt(match[3], 10, 64)
  206. end = end.Add(-time.Duration(offNum) * offUnit)
  207. durUnit := time.Minute
  208. if match[2] == "h" {
  209. durUnit = time.Hour
  210. }
  211. if match[2] == "d" {
  212. durUnit = 24 * time.Hour
  213. }
  214. durNum, _ := strconv.ParseInt(match[1], 10, 64)
  215. start := end.Add(-time.Duration(durNum) * durUnit)
  216. return NewWindow(&start, &end), nil
  217. }
  218. // Match timestamp pairs, e.g. "1586822400,1586908800" or "1586822400-1586908800"
  219. regex = regexp.MustCompile(`^(\d+)[,|-](\d+)$`)
  220. match = regex.FindStringSubmatch(window)
  221. if match != nil {
  222. s, _ := strconv.ParseInt(match[1], 10, 64)
  223. e, _ := strconv.ParseInt(match[2], 10, 64)
  224. start := time.Unix(s, 0)
  225. end := time.Unix(e, 0)
  226. return NewWindow(&start, &end), nil
  227. }
  228. // Match RFC3339 pairs, e.g. "2020-04-01T00:00:00Z,2020-04-03T00:00:00Z"
  229. rfc3339 := `\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ`
  230. regex = regexp.MustCompile(fmt.Sprintf(`(%s),(%s)`, rfc3339, rfc3339))
  231. match = regex.FindStringSubmatch(window)
  232. if match != nil {
  233. start, _ := time.Parse(time.RFC3339, match[1])
  234. end, _ := time.Parse(time.RFC3339, match[2])
  235. return NewWindow(&start, &end), nil
  236. }
  237. return Window{nil, nil}, fmt.Errorf("illegal window: %s", window)
  238. }
  239. // ApproximatelyEqual returns true if the start and end times of the two windows,
  240. // respectively, are within the given threshold of each other.
  241. func (w Window) ApproximatelyEqual(that Window, threshold time.Duration) bool {
  242. return approxEqual(w.start, that.start, threshold) && approxEqual(w.end, that.end, threshold)
  243. }
  244. func approxEqual(x *time.Time, y *time.Time, threshold time.Duration) bool {
  245. // both times are nil, so they are equal
  246. if x == nil && y == nil {
  247. return true
  248. }
  249. // one time is nil, but the other is not, so they are not equal
  250. if x == nil || y == nil {
  251. return false
  252. }
  253. // neither time is nil, so they are approximately close if their times are
  254. // within the given threshold
  255. delta := math.Abs((*x).Sub(*y).Seconds())
  256. return delta < threshold.Seconds()
  257. }
  258. func (w Window) Clone() Window {
  259. var start, end *time.Time
  260. var s, e time.Time
  261. if w.start != nil {
  262. s = *w.start
  263. start = &s
  264. }
  265. if w.end != nil {
  266. e = *w.end
  267. end = &e
  268. }
  269. return NewWindow(start, end)
  270. }
  271. func (w Window) Contains(t time.Time) bool {
  272. if w.start != nil && t.Before(*w.start) {
  273. return false
  274. }
  275. if w.end != nil && t.After(*w.end) {
  276. return false
  277. }
  278. return true
  279. }
  280. func (w Window) Duration() time.Duration {
  281. if w.IsOpen() {
  282. // TODO test
  283. return time.Duration(math.Inf(1.0))
  284. }
  285. return w.end.Sub(*w.start)
  286. }
  287. func (w Window) End() *time.Time {
  288. return w.end
  289. }
  290. func (w Window) Equal(that Window) bool {
  291. if w.start != nil && that.start != nil && !w.start.Equal(*that.start) {
  292. // starts are not nil, but not equal
  293. return false
  294. }
  295. if w.end != nil && that.end != nil && !w.end.Equal(*that.end) {
  296. // ends are not nil, but not equal
  297. return false
  298. }
  299. if (w.start == nil && that.start != nil) || (w.start != nil && that.start == nil) {
  300. // one start is nil, the other is not
  301. return false
  302. }
  303. if (w.end == nil && that.end != nil) || (w.end != nil && that.end == nil) {
  304. // one end is nil, the other is not
  305. return false
  306. }
  307. // either both starts are nil, or they match; likewise for the ends
  308. return true
  309. }
  310. func (w Window) ExpandStart(start time.Time) Window {
  311. if w.start == nil || start.Before(*w.start) {
  312. w.start = &start
  313. }
  314. return w
  315. }
  316. func (w Window) ExpandEnd(end time.Time) Window {
  317. if w.end == nil || end.After(*w.end) {
  318. w.end = &end
  319. }
  320. return w
  321. }
  322. func (w Window) Expand(that Window) Window {
  323. if that.start == nil {
  324. w.start = nil
  325. } else {
  326. w = w.ExpandStart(*that.start)
  327. }
  328. if that.end == nil {
  329. w.end = nil
  330. } else {
  331. w = w.ExpandEnd(*that.end)
  332. }
  333. return w
  334. }
  335. func (w Window) ContractStart(start time.Time) Window {
  336. if w.start == nil || start.After(*w.start) {
  337. w.start = &start
  338. }
  339. return w
  340. }
  341. func (w Window) ContractEnd(end time.Time) Window {
  342. if w.end == nil || end.Before(*w.end) {
  343. w.end = &end
  344. }
  345. return w
  346. }
  347. func (w Window) Contract(that Window) Window {
  348. if that.start != nil {
  349. w = w.ContractStart(*that.start)
  350. }
  351. if that.end != nil {
  352. w = w.ContractEnd(*that.end)
  353. }
  354. return w
  355. }
  356. func (w Window) Hours() float64 {
  357. if w.IsOpen() {
  358. return math.Inf(1)
  359. }
  360. return w.end.Sub(*w.start).Hours()
  361. }
  362. func (w Window) IsEmpty() bool {
  363. return !w.IsOpen() && w.end.Equal(*w.Start())
  364. }
  365. func (w Window) IsNegative() bool {
  366. return !w.IsOpen() && w.end.Before(*w.Start())
  367. }
  368. func (w Window) IsOpen() bool {
  369. return w.start == nil || w.end == nil
  370. }
  371. // TODO:CLEANUP make this unmarshalable (make Start and End public)
  372. func (w Window) MarshalJSON() ([]byte, error) {
  373. buffer := bytes.NewBufferString("{")
  374. if w.start != nil {
  375. buffer.WriteString(fmt.Sprintf("\"start\":\"%s\",", w.start.Format(time.RFC3339)))
  376. } else {
  377. buffer.WriteString(fmt.Sprintf("\"start\":\"%s\",", "null"))
  378. }
  379. if w.end != nil {
  380. buffer.WriteString(fmt.Sprintf("\"end\":\"%s\"", w.end.Format(time.RFC3339)))
  381. } else {
  382. buffer.WriteString(fmt.Sprintf("\"end\":\"%s\"", "null"))
  383. }
  384. buffer.WriteString("}")
  385. return buffer.Bytes(), nil
  386. }
  387. func (w Window) Minutes() float64 {
  388. if w.IsOpen() {
  389. return math.Inf(1)
  390. }
  391. return w.end.Sub(*w.start).Minutes()
  392. }
  393. // Overlaps returns true iff the two given Windows share an amount of temporal
  394. // coverage.
  395. // TODO complete (with unit tests!) and then implement in AllocationSet.accumulate
  396. // TODO:CLEANUP
  397. // func (w Window) Overlaps(x Window) bool {
  398. // if (w.start == nil && w.end == nil) || (x.start == nil && x.end == nil) {
  399. // // one window is completely open, so overlap is guaranteed
  400. // // <---------->
  401. // // ?------?
  402. // return true
  403. // }
  404. // // Neither window is completely open (nil, nil), but one or the other might
  405. // // still be future- or past-open.
  406. // if w.start == nil {
  407. // // w is past-open, future-closed
  408. // // <------]
  409. // if x.start != nil && !x.start.Before(*w.end) {
  410. // // x starts after w ends (or eq)
  411. // // <------]
  412. // // [------?
  413. // return false
  414. // }
  415. // // <-----]
  416. // // ?-----?
  417. // return true
  418. // }
  419. // if w.end == nil {
  420. // // w is future-open, past-closed
  421. // // [------>
  422. // if x.end != nil && !x.end.After(*w.end) {
  423. // // x ends before w begins (or eq)
  424. // // [------>
  425. // // ?------]
  426. // return false
  427. // }
  428. // // [------>
  429. // // ?------?
  430. // return true
  431. // }
  432. // // Now we know w is closed, but we don't know about x
  433. // // [------]
  434. // // ?------?
  435. // if x.start == nil {
  436. // // TODO
  437. // }
  438. // if x.end == nil {
  439. // // TODO
  440. // }
  441. // // Both are closed.
  442. // if !x.start.Before(*w.end) && !x.end.Before(*w.end) {
  443. // // x starts and ends after w ends
  444. // // [------]
  445. // // [------]
  446. // return false
  447. // }
  448. // if !x.start.After(*w.start) && !x.end.After(*w.start) {
  449. // // x starts and ends before w starts
  450. // // [------]
  451. // // [------]
  452. // return false
  453. // }
  454. // // w and x must overlap
  455. // // [------]
  456. // // [------]
  457. // return true
  458. // }
  459. func (w Window) Set(start, end *time.Time) {
  460. w.start = start
  461. w.end = end
  462. }
  463. // Shift adds the given duration to both the start and end times of the window
  464. func (w Window) Shift(dur time.Duration) Window {
  465. if w.start != nil {
  466. s := w.start.Add(dur)
  467. w.start = &s
  468. }
  469. if w.end != nil {
  470. e := w.end.Add(dur)
  471. w.end = &e
  472. }
  473. return w
  474. }
  475. func (w Window) Start() *time.Time {
  476. return w.start
  477. }
  478. func (w Window) String() string {
  479. if w.start == nil && w.end == nil {
  480. return "[nil, nil)"
  481. }
  482. if w.start == nil {
  483. return fmt.Sprintf("[nil, %s)", w.end.Format("2006-01-02T15:04:05-0700"))
  484. }
  485. if w.end == nil {
  486. return fmt.Sprintf("[%s, nil)", w.start.Format("2006-01-02T15:04:05-0700"))
  487. }
  488. return fmt.Sprintf("[%s, %s)", w.start.Format("2006-01-02T15:04:05-0700"), w.end.Format("2006-01-02T15:04:05-0700"))
  489. }
  490. // DurationOffset returns durations representing the duration and offset of the
  491. // given window
  492. func (w Window) DurationOffset() (time.Duration, time.Duration, error) {
  493. if w.IsOpen() || w.IsNegative() {
  494. return 0, 0, fmt.Errorf("illegal window: %s", w)
  495. }
  496. duration := w.Duration()
  497. offset := time.Since(*w.End())
  498. return duration, offset, nil
  499. }
  500. // DurationOffsetForPrometheus returns strings representing durations for the
  501. // duration and offset of the given window, factoring in the Thanos offset if
  502. // necessary. Whereas duration is a simple duration string (e.g. "1d"), the
  503. // offset includes the word "offset" (e.g. " offset 2d") so that the values
  504. // returned can be used directly in the formatting string "some_metric[%s]%s"
  505. // to generate the query "some_metric[1d] offset 2d".
  506. func (w Window) DurationOffsetForPrometheus() (string, string, error) {
  507. duration, offset, err := w.DurationOffset()
  508. if err != nil {
  509. return "", "", err
  510. }
  511. // If using Thanos, increase offset to 3 hours, reducing the duration by
  512. // equal measure to maintain the same starting point.
  513. thanosDur := thanos.OffsetDuration()
  514. if offset < thanosDur && env.IsThanosEnabled() {
  515. diff := thanosDur - offset
  516. offset += diff
  517. duration -= diff
  518. }
  519. // If duration < 0, return an error
  520. if duration < 0 {
  521. return "", "", fmt.Errorf("negative duration: %s", duration)
  522. }
  523. // Negative offset means that the end time is in the future. Prometheus
  524. // fails for non-positive offset values, so shrink the duration and
  525. // remove the offset altogether.
  526. if offset < 0 {
  527. duration = duration + offset
  528. offset = 0
  529. }
  530. durStr, offStr := timeutil.DurationOffsetStrings(duration, offset)
  531. if offset < time.Minute {
  532. offStr = ""
  533. } else {
  534. offStr = " offset " + offStr
  535. }
  536. return durStr, offStr, nil
  537. }
  538. // DurationOffsetStrings returns formatted, Prometheus-compatible strings representing
  539. // the duration and offset of the window in terms of days, hours, minutes, or seconds;
  540. // e.g. ("7d", "1441m", "30m", "1s", "")
  541. func (w Window) DurationOffsetStrings() (string, string) {
  542. dur, off, err := w.DurationOffset()
  543. if err != nil {
  544. return "", ""
  545. }
  546. return timeutil.DurationOffsetStrings(dur, off)
  547. }
  548. type BoundaryError struct {
  549. Requested Window
  550. Supported Window
  551. Message string
  552. }
  553. func NewBoundaryError(req, sup Window, msg string) *BoundaryError {
  554. return &BoundaryError{
  555. Requested: req,
  556. Supported: sup,
  557. Message: msg,
  558. }
  559. }
  560. func (be *BoundaryError) Error() string {
  561. if be == nil {
  562. return "<nil>"
  563. }
  564. return fmt.Sprintf("boundary error: requested %s; supported %s: %s", be.Requested, be.Supported, be.Message)
  565. }