window.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. package kubecost
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "math"
  7. "regexp"
  8. "strconv"
  9. "time"
  10. "github.com/opencost/opencost/pkg/env"
  11. "github.com/opencost/opencost/pkg/log"
  12. "github.com/opencost/opencost/pkg/thanos"
  13. "github.com/opencost/opencost/pkg/util/timeutil"
  14. )
  15. const (
  16. minutesPerDay = 60 * 24
  17. minutesPerHour = 60
  18. hoursPerDay = 24
  19. )
  20. var (
  21. durationRegex = regexp.MustCompile(`^(\d+)(m|h|d)$`)
  22. durationOffsetRegex = regexp.MustCompile(`^(\d+)(m|h|d) offset (\d+)(m|h|d)$`)
  23. offesetRegex = regexp.MustCompile(`^(\+|-)(\d\d):(\d\d)$`)
  24. rfc3339 = `\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ`
  25. rfcRegex = regexp.MustCompile(fmt.Sprintf(`(%s),(%s)`, rfc3339, rfc3339))
  26. timestampPairRegex = regexp.MustCompile(`^(\d+)[,|-](\d+)$`)
  27. )
  28. // RoundBack rounds the given time back to a multiple of the given resolution
  29. // in the given time's timezone.
  30. // e.g. 2020-01-01T12:37:48-0700, 24h = 2020-01-01T00:00:00-0700
  31. func RoundBack(t time.Time, resolution time.Duration) time.Time {
  32. _, offSec := t.Zone()
  33. return t.Add(time.Duration(offSec) * time.Second).Truncate(resolution).Add(-time.Duration(offSec) * time.Second)
  34. }
  35. // RoundForward rounds the given time forward to a multiple of the given resolution
  36. // in the given time's timezone.
  37. // e.g. 2020-01-01T12:37:48-0700, 24h = 2020-01-02T00:00:00-0700
  38. func RoundForward(t time.Time, resolution time.Duration) time.Time {
  39. back := RoundBack(t, resolution)
  40. if back.Equal(t) {
  41. // The given time is exactly a multiple of the given resolution
  42. return t
  43. }
  44. return back.Add(resolution)
  45. }
  46. // Window defines a period of time with a start and an end. If either start or
  47. // end are nil it indicates an open time period.
  48. type Window struct {
  49. start *time.Time
  50. end *time.Time
  51. }
  52. // NewWindow creates and returns a new Window instance from the given times
  53. func NewWindow(start, end *time.Time) Window {
  54. return Window{
  55. start: start,
  56. end: end,
  57. }
  58. }
  59. // NewClosedWindow creates and returns a new Window instance from the given
  60. // times, which cannot be nil, so they are value types.
  61. func NewClosedWindow(start, end time.Time) Window {
  62. return Window{
  63. start: &start,
  64. end: &end,
  65. }
  66. }
  67. // ParseWindowUTC attempts to parse the given string into a valid Window. It
  68. // accepts several formats, returning an error if the given string does not
  69. // match one of the following:
  70. // - named intervals: "today", "yesterday", "week", "month", "lastweek", "lastmonth"
  71. // - durations: "24h", "7d", etc.
  72. // - date ranges: "2020-04-01T00:00:00Z,2020-04-03T00:00:00Z", etc.
  73. // - timestamp ranges: "1586822400,1586908800", etc.
  74. func ParseWindowUTC(window string) (Window, error) {
  75. return parseWindow(window, time.Now().UTC())
  76. }
  77. // ParseWindowWithOffsetString parses the given window string within the context of
  78. // the timezone defined by the UTC offset string of format -07:00, +01:30, etc.
  79. func ParseWindowWithOffsetString(window string, offset string) (Window, error) {
  80. if offset == "UTC" || offset == "" {
  81. return ParseWindowUTC(window)
  82. }
  83. match := offesetRegex.FindStringSubmatch(offset)
  84. if match == nil {
  85. return Window{}, fmt.Errorf("illegal UTC offset: '%s'; should be of form '-07:00'", offset)
  86. }
  87. sig := 1
  88. if match[1] == "-" {
  89. sig = -1
  90. }
  91. hrs64, _ := strconv.ParseInt(match[2], 10, 64)
  92. hrs := sig * int(hrs64)
  93. mins64, _ := strconv.ParseInt(match[3], 10, 64)
  94. mins := sig * int(mins64)
  95. loc := time.FixedZone(fmt.Sprintf("UTC%s", offset), (hrs*60*60)+(mins*60))
  96. now := time.Now().In(loc)
  97. return parseWindow(window, now)
  98. }
  99. // ParseWindowWithOffset parses the given window string within the context of
  100. // the timezone defined by the UTC offset.
  101. func ParseWindowWithOffset(window string, offset time.Duration) (Window, error) {
  102. loc := time.FixedZone("", int(offset.Seconds()))
  103. now := time.Now().In(loc)
  104. return parseWindow(window, now)
  105. }
  106. // parseWindow generalizes the parsing of window strings, relative to a given
  107. // moment in time, defined as "now".
  108. func parseWindow(window string, now time.Time) (Window, error) {
  109. // compute UTC offset in terms of minutes
  110. offHr := now.UTC().Hour() - now.Hour()
  111. offMin := (now.UTC().Minute() - now.Minute()) + (offHr * 60)
  112. offset := time.Duration(offMin) * time.Minute
  113. if window == "today" {
  114. start := now
  115. start = start.Truncate(time.Hour * 24)
  116. start = start.Add(offset)
  117. end := start.Add(time.Hour * 24)
  118. return NewWindow(&start, &end), nil
  119. }
  120. if window == "yesterday" {
  121. start := now
  122. start = start.Truncate(time.Hour * 24)
  123. start = start.Add(offset)
  124. start = start.Add(time.Hour * -24)
  125. end := start.Add(time.Hour * 24)
  126. return NewWindow(&start, &end), nil
  127. }
  128. if window == "week" {
  129. // now
  130. start := now
  131. // 00:00 today, accounting for timezone offset
  132. start = start.Truncate(time.Hour * 24)
  133. start = start.Add(offset)
  134. // 00:00 Sunday of the current week
  135. start = start.Add(-24 * time.Hour * time.Duration(start.Weekday()))
  136. end := now
  137. return NewWindow(&start, &end), nil
  138. }
  139. if window == "lastweek" {
  140. // now
  141. start := now
  142. // 00:00 today, accounting for timezone offset
  143. start = start.Truncate(time.Hour * 24)
  144. start = start.Add(offset)
  145. // 00:00 Sunday of last week
  146. start = start.Add(-24 * time.Hour * time.Duration(start.Weekday()+7))
  147. end := start.Add(7 * 24 * time.Hour)
  148. return NewWindow(&start, &end), nil
  149. }
  150. if window == "month" {
  151. // now
  152. start := now
  153. // 00:00 today, accounting for timezone offset
  154. start = start.Truncate(time.Hour * 24)
  155. start = start.Add(offset)
  156. // 00:00 1st of this month
  157. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  158. end := now
  159. return NewWindow(&start, &end), nil
  160. }
  161. if window == "month" {
  162. // now
  163. start := now
  164. // 00:00 today, accounting for timezone offset
  165. start = start.Truncate(time.Hour * 24)
  166. start = start.Add(offset)
  167. // 00:00 1st of this month
  168. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  169. end := now
  170. return NewWindow(&start, &end), nil
  171. }
  172. if window == "lastmonth" {
  173. // now
  174. end := now
  175. // 00:00 today, accounting for timezone offset
  176. end = end.Truncate(time.Hour * 24)
  177. end = end.Add(offset)
  178. // 00:00 1st of this month
  179. end = end.Add(-24 * time.Hour * time.Duration(end.Day()-1))
  180. // 00:00 last day of last month
  181. start := end.Add(-24 * time.Hour)
  182. // 00:00 1st of last month
  183. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  184. return NewWindow(&start, &end), nil
  185. }
  186. // Match duration strings; e.g. "45m", "24h", "7d"
  187. match := durationRegex.FindStringSubmatch(window)
  188. if match != nil {
  189. dur := time.Minute
  190. if match[2] == "h" {
  191. dur = time.Hour
  192. }
  193. if match[2] == "d" {
  194. dur = 24 * time.Hour
  195. }
  196. num, _ := strconv.ParseInt(match[1], 10, 64)
  197. end := now
  198. start := end.Add(-time.Duration(num) * dur)
  199. return NewWindow(&start, &end), nil
  200. }
  201. // Match duration strings with offset; e.g. "45m offset 15m", etc.
  202. match = durationOffsetRegex.FindStringSubmatch(window)
  203. if match != nil {
  204. end := now
  205. offUnit := time.Minute
  206. if match[4] == "h" {
  207. offUnit = time.Hour
  208. }
  209. if match[4] == "d" {
  210. offUnit = 24 * time.Hour
  211. }
  212. offNum, _ := strconv.ParseInt(match[3], 10, 64)
  213. end = end.Add(-time.Duration(offNum) * offUnit)
  214. durUnit := time.Minute
  215. if match[2] == "h" {
  216. durUnit = time.Hour
  217. }
  218. if match[2] == "d" {
  219. durUnit = 24 * time.Hour
  220. }
  221. durNum, _ := strconv.ParseInt(match[1], 10, 64)
  222. start := end.Add(-time.Duration(durNum) * durUnit)
  223. return NewWindow(&start, &end), nil
  224. }
  225. // Match timestamp pairs, e.g. "1586822400,1586908800" or "1586822400-1586908800"
  226. match = timestampPairRegex.FindStringSubmatch(window)
  227. if match != nil {
  228. s, _ := strconv.ParseInt(match[1], 10, 64)
  229. e, _ := strconv.ParseInt(match[2], 10, 64)
  230. start := time.Unix(s, 0).UTC()
  231. end := time.Unix(e, 0).UTC()
  232. return NewWindow(&start, &end), nil
  233. }
  234. // Match RFC3339 pairs, e.g. "2020-04-01T00:00:00Z,2020-04-03T00:00:00Z"
  235. match = rfcRegex.FindStringSubmatch(window)
  236. if match != nil {
  237. start, _ := time.Parse(time.RFC3339, match[1])
  238. end, _ := time.Parse(time.RFC3339, match[2])
  239. return NewWindow(&start, &end), nil
  240. }
  241. return Window{nil, nil}, fmt.Errorf("illegal window: %s", window)
  242. }
  243. // ApproximatelyEqual returns true if the start and end times of the two windows,
  244. // respectively, are within the given threshold of each other.
  245. func (w Window) ApproximatelyEqual(that Window, threshold time.Duration) bool {
  246. return approxEqual(w.start, that.start, threshold) && approxEqual(w.end, that.end, threshold)
  247. }
  248. func approxEqual(x *time.Time, y *time.Time, threshold time.Duration) bool {
  249. // both times are nil, so they are equal
  250. if x == nil && y == nil {
  251. return true
  252. }
  253. // one time is nil, but the other is not, so they are not equal
  254. if x == nil || y == nil {
  255. return false
  256. }
  257. // neither time is nil, so they are approximately close if their times are
  258. // within the given threshold
  259. delta := math.Abs((*x).Sub(*y).Seconds())
  260. return delta < threshold.Seconds()
  261. }
  262. func (w Window) Clone() Window {
  263. var start, end *time.Time
  264. var s, e time.Time
  265. if w.start != nil {
  266. s = *w.start
  267. start = &s
  268. }
  269. if w.end != nil {
  270. e = *w.end
  271. end = &e
  272. }
  273. return NewWindow(start, end)
  274. }
  275. func (w Window) Contains(t time.Time) bool {
  276. if w.start != nil && t.Before(*w.start) {
  277. return false
  278. }
  279. if w.end != nil && t.After(*w.end) {
  280. return false
  281. }
  282. return true
  283. }
  284. func (w Window) ContainsWindow(that Window) bool {
  285. // only support containing closed windows for now
  286. // could check if openness is compatible with closure
  287. if that.IsOpen() {
  288. return false
  289. }
  290. return w.Contains(*that.start) && w.Contains(*that.end)
  291. }
  292. func (w Window) Duration() time.Duration {
  293. if w.IsOpen() {
  294. // TODO test
  295. return time.Duration(math.Inf(1.0))
  296. }
  297. return w.end.Sub(*w.start)
  298. }
  299. func (w Window) End() *time.Time {
  300. return w.end
  301. }
  302. func (w Window) Equal(that Window) bool {
  303. if w.start != nil && that.start != nil && !w.start.Equal(*that.start) {
  304. // starts are not nil, but not equal
  305. return false
  306. }
  307. if w.end != nil && that.end != nil && !w.end.Equal(*that.end) {
  308. // ends are not nil, but not equal
  309. return false
  310. }
  311. if (w.start == nil && that.start != nil) || (w.start != nil && that.start == nil) {
  312. // one start is nil, the other is not
  313. return false
  314. }
  315. if (w.end == nil && that.end != nil) || (w.end != nil && that.end == nil) {
  316. // one end is nil, the other is not
  317. return false
  318. }
  319. // either both starts are nil, or they match; likewise for the ends
  320. return true
  321. }
  322. func (w Window) ExpandStart(start time.Time) Window {
  323. if w.start == nil || start.Before(*w.start) {
  324. w.start = &start
  325. }
  326. return w
  327. }
  328. func (w Window) ExpandEnd(end time.Time) Window {
  329. if w.end == nil || end.After(*w.end) {
  330. w.end = &end
  331. }
  332. return w
  333. }
  334. func (w Window) Expand(that Window) Window {
  335. if that.start == nil {
  336. w.start = nil
  337. } else {
  338. w = w.ExpandStart(*that.start)
  339. }
  340. if that.end == nil {
  341. w.end = nil
  342. } else {
  343. w = w.ExpandEnd(*that.end)
  344. }
  345. return w
  346. }
  347. func (w Window) ContractStart(start time.Time) Window {
  348. if w.start == nil || start.After(*w.start) {
  349. w.start = &start
  350. }
  351. return w
  352. }
  353. func (w Window) ContractEnd(end time.Time) Window {
  354. if w.end == nil || end.Before(*w.end) {
  355. w.end = &end
  356. }
  357. return w
  358. }
  359. func (w Window) Contract(that Window) Window {
  360. if that.start != nil {
  361. w = w.ContractStart(*that.start)
  362. }
  363. if that.end != nil {
  364. w = w.ContractEnd(*that.end)
  365. }
  366. return w
  367. }
  368. func (w Window) Hours() float64 {
  369. if w.IsOpen() {
  370. return math.Inf(1)
  371. }
  372. return w.end.Sub(*w.start).Hours()
  373. }
  374. // IsEmpty a Window is empty if it does not have a start and an end
  375. func (w Window) IsEmpty() bool {
  376. return w.start == nil && w.end == nil
  377. }
  378. // HasDuration a Window has duration if neither start and end are not nil and not equal
  379. func (w Window) HasDuration() bool {
  380. return !w.IsOpen() && !w.end.Equal(*w.Start())
  381. }
  382. // IsNegative a Window is negative if start and end are not null and end is before start
  383. func (w Window) IsNegative() bool {
  384. return !w.IsOpen() && w.end.Before(*w.Start())
  385. }
  386. // IsOpen a Window is open if it has a nil start or end
  387. func (w Window) IsOpen() bool {
  388. return w.start == nil || w.end == nil
  389. }
  390. func (w Window) MarshalJSON() ([]byte, error) {
  391. buffer := bytes.NewBufferString("{")
  392. if w.start != nil {
  393. buffer.WriteString(fmt.Sprintf("\"start\":\"%s\",", w.start.Format(time.RFC3339)))
  394. } else {
  395. buffer.WriteString(fmt.Sprintf("\"start\":\"%s\",", "null"))
  396. }
  397. if w.end != nil {
  398. buffer.WriteString(fmt.Sprintf("\"end\":\"%s\"", w.end.Format(time.RFC3339)))
  399. } else {
  400. buffer.WriteString(fmt.Sprintf("\"end\":\"%s\"", "null"))
  401. }
  402. buffer.WriteString("}")
  403. return buffer.Bytes(), nil
  404. }
  405. func (w *Window) UnmarshalJSON(bs []byte) error {
  406. // Due to the behavior of our custom MarshalJSON, we unmarshal as strings
  407. // and then manually handle the weird quoted "null" case.
  408. type PubWindow struct {
  409. Start string `json:"start"`
  410. End string `json:"end"`
  411. }
  412. var pw PubWindow
  413. err := json.Unmarshal(bs, &pw)
  414. if err != nil {
  415. return fmt.Errorf("half unmarshal: %w", err)
  416. }
  417. var start *time.Time
  418. var end *time.Time
  419. if pw.Start != "null" {
  420. t, err := time.Parse(time.RFC3339, pw.Start)
  421. if err != nil {
  422. return fmt.Errorf("parsing start as RFC3339: %w", err)
  423. }
  424. start = &t
  425. }
  426. if pw.End != "null" {
  427. t, err := time.Parse(time.RFC3339, pw.End)
  428. if err != nil {
  429. return fmt.Errorf("parsing end as RFC3339: %w", err)
  430. }
  431. end = &t
  432. }
  433. w.start = start
  434. w.end = end
  435. return nil
  436. }
  437. func (w Window) Minutes() float64 {
  438. if w.IsOpen() {
  439. return math.Inf(1)
  440. }
  441. return w.end.Sub(*w.start).Minutes()
  442. }
  443. // Overlaps returns true iff the two given Windows share an amount of temporal
  444. // coverage.
  445. // TODO complete (with unit tests!) and then implement in AllocationSet.accumulate
  446. // TODO:CLEANUP
  447. // func (w Window) Overlaps(x Window) bool {
  448. // if (w.start == nil && w.end == nil) || (x.start == nil && x.end == nil) {
  449. // // one window is completely open, so overlap is guaranteed
  450. // // <---------->
  451. // // ?------?
  452. // return true
  453. // }
  454. // // Neither window is completely open (nil, nil), but one or the other might
  455. // // still be future- or past-open.
  456. // if w.start == nil {
  457. // // w is past-open, future-closed
  458. // // <------]
  459. // if x.start != nil && !x.start.Before(*w.end) {
  460. // // x starts after w ends (or eq)
  461. // // <------]
  462. // // [------?
  463. // return false
  464. // }
  465. // // <-----]
  466. // // ?-----?
  467. // return true
  468. // }
  469. // if w.end == nil {
  470. // // w is future-open, past-closed
  471. // // [------>
  472. // if x.end != nil && !x.end.After(*w.end) {
  473. // // x ends before w begins (or eq)
  474. // // [------>
  475. // // ?------]
  476. // return false
  477. // }
  478. // // [------>
  479. // // ?------?
  480. // return true
  481. // }
  482. // // Now we know w is closed, but we don't know about x
  483. // // [------]
  484. // // ?------?
  485. // if x.start == nil {
  486. // // TODO
  487. // }
  488. // if x.end == nil {
  489. // // TODO
  490. // }
  491. // // Both are closed.
  492. // if !x.start.Before(*w.end) && !x.end.Before(*w.end) {
  493. // // x starts and ends after w ends
  494. // // [------]
  495. // // [------]
  496. // return false
  497. // }
  498. // if !x.start.After(*w.start) && !x.end.After(*w.start) {
  499. // // x starts and ends before w starts
  500. // // [------]
  501. // // [------]
  502. // return false
  503. // }
  504. // // w and x must overlap
  505. // // [------]
  506. // // [------]
  507. // return true
  508. // }
  509. func (w *Window) Set(start, end *time.Time) {
  510. w.start = start
  511. w.end = end
  512. }
  513. // Shift adds the given duration to both the start and end times of the window
  514. func (w Window) Shift(dur time.Duration) Window {
  515. if w.start != nil {
  516. s := w.start.Add(dur)
  517. w.start = &s
  518. }
  519. if w.end != nil {
  520. e := w.end.Add(dur)
  521. w.end = &e
  522. }
  523. return w
  524. }
  525. func (w Window) Start() *time.Time {
  526. return w.start
  527. }
  528. func (w Window) String() string {
  529. if w.start == nil && w.end == nil {
  530. return "[nil, nil)"
  531. }
  532. if w.start == nil {
  533. return fmt.Sprintf("[nil, %s)", w.end.Format("2006-01-02T15:04:05-0700"))
  534. }
  535. if w.end == nil {
  536. return fmt.Sprintf("[%s, nil)", w.start.Format("2006-01-02T15:04:05-0700"))
  537. }
  538. return fmt.Sprintf("[%s, %s)", w.start.Format("2006-01-02T15:04:05-0700"), w.end.Format("2006-01-02T15:04:05-0700"))
  539. }
  540. // DurationOffset returns durations representing the duration and offset of the
  541. // given window
  542. func (w Window) DurationOffset() (time.Duration, time.Duration, error) {
  543. if w.IsOpen() || w.IsNegative() {
  544. return 0, 0, fmt.Errorf("illegal window: %s", w)
  545. }
  546. duration := w.Duration()
  547. offset := time.Since(*w.End())
  548. return duration, offset, nil
  549. }
  550. // DurationOffsetForPrometheus returns strings representing durations for the
  551. // duration and offset of the given window, factoring in the Thanos offset if
  552. // necessary. Whereas duration is a simple duration string (e.g. "1d"), the
  553. // offset includes the word "offset" (e.g. " offset 2d") so that the values
  554. // returned can be used directly in the formatting string "some_metric[%s]%s"
  555. // to generate the query "some_metric[1d] offset 2d".
  556. func (w Window) DurationOffsetForPrometheus() (string, string, error) {
  557. duration, offset, err := w.DurationOffset()
  558. if err != nil {
  559. return "", "", err
  560. }
  561. // If using Thanos, increase offset to 3 hours, reducing the duration by
  562. // equal measure to maintain the same starting point.
  563. thanosDur := thanos.OffsetDuration()
  564. if offset < thanosDur && env.IsThanosEnabled() {
  565. diff := thanosDur - offset
  566. offset += diff
  567. duration -= diff
  568. }
  569. // If duration < 0, return an error
  570. if duration < 0 {
  571. return "", "", fmt.Errorf("negative duration: %s", duration)
  572. }
  573. // Negative offset means that the end time is in the future. Prometheus
  574. // fails for non-positive offset values, so shrink the duration and
  575. // remove the offset altogether.
  576. if offset < 0 {
  577. duration = duration + offset
  578. offset = 0
  579. }
  580. durStr, offStr := timeutil.DurationOffsetStrings(duration, offset)
  581. if offset < time.Minute {
  582. offStr = ""
  583. } else {
  584. offStr = " offset " + offStr
  585. }
  586. return durStr, offStr, nil
  587. }
  588. // DurationOffsetStrings returns formatted, Prometheus-compatible strings representing
  589. // the duration and offset of the window in terms of days, hours, minutes, or seconds;
  590. // e.g. ("7d", "1441m", "30m", "1s", "")
  591. func (w Window) DurationOffsetStrings() (string, string) {
  592. dur, off, err := w.DurationOffset()
  593. if err != nil {
  594. return "", ""
  595. }
  596. return timeutil.DurationOffsetStrings(dur, off)
  597. }
  598. // GetPercentInWindow Determine pct of item time contained the window.
  599. // determined by the overlap of the start/end with the given
  600. // window, which will be negative if there is no overlap. If
  601. // there is positive overlap, compare it with the total mins.
  602. //
  603. // e.g. here are the two possible scenarios as simplidied
  604. // 10m windows with dashes representing item's time running:
  605. //
  606. // 1. item falls entirely within one CloudCostItemSet window
  607. // | ---- | | |
  608. // totalMins = 4.0
  609. // pct := 4.0 / 4.0 = 1.0 for window 1
  610. // pct := 0.0 / 4.0 = 0.0 for window 2
  611. // pct := 0.0 / 4.0 = 0.0 for window 3
  612. //
  613. // 2. item overlaps multiple CloudCostItemSet windows
  614. // | ----|----------|-- |
  615. // totalMins = 16.0
  616. // pct := 4.0 / 16.0 = 0.250 for window 1
  617. // pct := 10.0 / 16.0 = 0.625 for window 2
  618. // pct := 2.0 / 16.0 = 0.125 for window 3
  619. func (w Window) GetPercentInWindow(that Window) float64 {
  620. if that.IsOpen() {
  621. log.Errorf("Window: GetPercentInWindow: invalid window %s", that.String())
  622. return 0
  623. }
  624. s := *that.Start()
  625. if s.Before(*w.Start()) {
  626. s = *w.Start()
  627. }
  628. e := *that.End()
  629. if e.After(*w.End()) {
  630. e = *w.End()
  631. }
  632. mins := e.Sub(s).Minutes()
  633. if mins <= 0.0 {
  634. return 0.0
  635. }
  636. totalMins := that.Duration().Minutes()
  637. pct := mins / totalMins
  638. return pct
  639. }
  640. // GetWindows returns a slice of Window with equal size between the given start and end. If windowSize does not evenly
  641. // divide the period between start and end, the last window is not added
  642. func GetWindows(start time.Time, end time.Time, windowSize time.Duration) ([]Window, error) {
  643. // Ensure the range is evenly divisible into windows of the given duration
  644. dur := end.Sub(start)
  645. if int(dur.Minutes())%int(windowSize.Minutes()) != 0 {
  646. return nil, fmt.Errorf("range not divisible by window: [%s, %s] by %s", start, end, windowSize)
  647. }
  648. // Ensure that provided times are multiples of the provided windowSize (e.g. midnight for daily windows, on the hour for hourly windows)
  649. if start != start.Truncate(windowSize) {
  650. return nil, fmt.Errorf("provided times are not divisible by provided window: [%s, %s] by %s", start, end, windowSize)
  651. }
  652. // Ensure timezones match
  653. _, sz := start.Zone()
  654. _, ez := end.Zone()
  655. if sz != ez {
  656. return nil, fmt.Errorf("range has mismatched timezones: %s, %s", start, end)
  657. }
  658. if sz != int(env.GetParsedUTCOffset().Seconds()) {
  659. return nil, fmt.Errorf("range timezone doesn't match configured timezone: expected %s; found %ds", env.GetParsedUTCOffset(), sz)
  660. }
  661. // Build array of windows to cover the CloudCostItemSetRange
  662. windows := []Window{}
  663. s, e := start, start.Add(windowSize)
  664. for !e.After(end) {
  665. ws := s
  666. we := e
  667. windows = append(windows, NewWindow(&ws, &we))
  668. s = s.Add(windowSize)
  669. e = e.Add(windowSize)
  670. }
  671. return windows, nil
  672. }
  673. // GetWindowsForQueryWindow breaks up a window into an array of windows with a max size of queryWindow
  674. func GetWindowsForQueryWindow(start time.Time, end time.Time, queryWindow time.Duration) ([]Window, error) {
  675. // Ensure timezones match
  676. _, sz := start.Zone()
  677. _, ez := end.Zone()
  678. if sz != ez {
  679. return nil, fmt.Errorf("range has mismatched timezones: %s, %s", start, end)
  680. }
  681. if sz != int(env.GetParsedUTCOffset().Seconds()) {
  682. return nil, fmt.Errorf("range timezone doesn't match configured timezone: expected %s; found %ds", env.GetParsedUTCOffset(), sz)
  683. }
  684. // Build array of windows to cover the CloudCostItemSetRange
  685. windows := []Window{}
  686. s, e := start, start.Add(queryWindow)
  687. for s.Before(end) {
  688. ws := s
  689. we := e
  690. windows = append(windows, NewWindow(&ws, &we))
  691. s = s.Add(queryWindow)
  692. e = e.Add(queryWindow)
  693. if e.After(end) {
  694. e = end
  695. }
  696. }
  697. return windows, nil
  698. }
  699. type BoundaryError struct {
  700. Requested Window
  701. Supported Window
  702. Message string
  703. }
  704. func NewBoundaryError(req, sup Window, msg string) *BoundaryError {
  705. return &BoundaryError{
  706. Requested: req,
  707. Supported: sup,
  708. Message: msg,
  709. }
  710. }
  711. func (be *BoundaryError) Error() string {
  712. if be == nil {
  713. return "<nil>"
  714. }
  715. return fmt.Sprintf("boundary error: requested %s; supported %s: %s", be.Requested, be.Supported, be.Message)
  716. }