window.go 17 KB

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