window.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. package opencost
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "math"
  7. "regexp"
  8. "strconv"
  9. "sync"
  10. "time"
  11. "github.com/opencost/opencost/core/pkg/env"
  12. "github.com/opencost/opencost/core/pkg/log"
  13. "github.com/opencost/opencost/core/pkg/util/timeutil"
  14. )
  15. var (
  16. durationRegex = regexp.MustCompile(`^(\d+)(m|h|d|w)$`)
  17. durationOffsetRegex = regexp.MustCompile(`^(\d+)(m|h|d|w) offset (\d+)(m|h|d|w)$`)
  18. offesetRegex = regexp.MustCompile(`^(\+|-)(\d\d):(\d\d)$`)
  19. rfc3339 = `\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ`
  20. rfcRegex = regexp.MustCompile(fmt.Sprintf(`(%s),(%s)`, rfc3339, rfc3339))
  21. timestampPairRegex = regexp.MustCompile(`^(\d+)[,|-](\d+)$`)
  22. utcOffsetLock sync.Mutex
  23. utcOffsetDur *time.Duration
  24. )
  25. // returns the configured utc offset as a duration
  26. // TODO: Same as the above options -- we should provide a one-time initialization configuration
  27. // TODO: for these values, or deprecate their use.
  28. func utcOffset() time.Duration {
  29. utcOffsetLock.Lock()
  30. defer utcOffsetLock.Unlock()
  31. if utcOffsetDur == nil {
  32. utcOff, err := timeutil.ParseUTCOffset(env.Get("UTC_OFFSET", ""))
  33. if err != nil {
  34. utcOff = time.Duration(0)
  35. }
  36. utcOffsetDur = &utcOff
  37. }
  38. return *utcOffsetDur
  39. }
  40. // RoundBack rounds the given time back to a multiple of the given resolution
  41. // in the given time's timezone.
  42. // e.g. 2020-01-01T12:37:48-0700, 24h = 2020-01-01T00:00:00-0700
  43. func RoundBack(t time.Time, resolution time.Duration) time.Time {
  44. // if the duration is a week - roll back to the following Sunday
  45. if resolution == timeutil.Week {
  46. return timeutil.RoundToStartOfWeek(t)
  47. }
  48. _, offSec := t.Zone()
  49. return t.Add(time.Duration(offSec) * time.Second).Truncate(resolution).Add(-time.Duration(offSec) * time.Second)
  50. }
  51. // RoundForward rounds the given time forward to a multiple of the given resolution
  52. // in the given time's timezone.
  53. // e.g. 2020-01-01T12:37:48-0700, 24h = 2020-01-02T00:00:00-0700
  54. func RoundForward(t time.Time, resolution time.Duration) time.Time {
  55. back := RoundBack(t, resolution)
  56. if back.Equal(t) {
  57. // The given time is exactly a multiple of the given resolution
  58. return t
  59. }
  60. return back.Add(resolution)
  61. }
  62. // Window defines a period of time with a start and an end. If either start or
  63. // end are nil it indicates an open time period.
  64. type Window struct {
  65. start *time.Time
  66. end *time.Time
  67. }
  68. // NewWindow creates and returns a new Window instance from the given times
  69. func NewWindow(start, end *time.Time) Window {
  70. return Window{
  71. start: start,
  72. end: end,
  73. }
  74. }
  75. // NewClosedWindow creates and returns a new Window instance from the given
  76. // times, which cannot be nil, so they are value types.
  77. func NewClosedWindow(start, end time.Time) Window {
  78. return Window{
  79. start: &start,
  80. end: &end,
  81. }
  82. }
  83. // ParseWindowUTC attempts to parse the given string into a valid Window. It
  84. // accepts several formats, returning an error if the given string does not
  85. // match one of the following:
  86. // - named intervals: "today", "yesterday", "week", "month", "lastweek", "lastmonth"
  87. // - durations: "24h", "7d", etc.
  88. // - date ranges: "2020-04-01T00:00:00Z,2020-04-03T00:00:00Z", etc.
  89. // - timestamp ranges: "1586822400,1586908800", etc.
  90. func ParseWindowUTC(window string) (Window, error) {
  91. return parseWindow(window, time.Now().UTC())
  92. }
  93. // ParseWindowWithOffsetString parses the given window string within the context of
  94. // the timezone defined by the UTC offset string of format -07:00, +01:30, etc.
  95. func ParseWindowWithOffsetString(window string, offset string) (Window, error) {
  96. if offset == "UTC" || offset == "" {
  97. return ParseWindowUTC(window)
  98. }
  99. match := offesetRegex.FindStringSubmatch(offset)
  100. if match == nil {
  101. return Window{}, fmt.Errorf("illegal UTC offset: '%s'; should be of form '-07:00'", offset)
  102. }
  103. sig := 1
  104. if match[1] == "-" {
  105. sig = -1
  106. }
  107. hrs64, _ := strconv.ParseInt(match[2], 10, 64)
  108. hrs := sig * int(hrs64)
  109. mins64, _ := strconv.ParseInt(match[3], 10, 64)
  110. mins := sig * int(mins64)
  111. loc := time.FixedZone(fmt.Sprintf("UTC%s", offset), (hrs*60*60)+(mins*60))
  112. now := time.Now().In(loc)
  113. return parseWindow(window, now)
  114. }
  115. // ParseWindowWithOffset parses the given window string within the context of
  116. // the timezone defined by the UTC offset.
  117. func ParseWindowWithOffset(window string, offset time.Duration) (Window, error) {
  118. loc := time.FixedZone("", int(offset.Seconds()))
  119. now := time.Now().In(loc)
  120. return parseWindow(window, now)
  121. }
  122. // parseWindow generalizes the parsing of window strings, relative to a given
  123. // moment in time, defined as "now".
  124. func parseWindow(window string, now time.Time) (Window, error) {
  125. // compute UTC offset in terms of minutes
  126. offHr := now.UTC().Hour() - now.Hour()
  127. offMin := (now.UTC().Minute() - now.Minute()) + (offHr * 60)
  128. offset := time.Duration(offMin) * time.Minute
  129. if window == "today" {
  130. start := now
  131. start = start.Truncate(time.Hour * 24)
  132. start = start.Add(offset)
  133. end := start.Add(time.Hour * 24)
  134. return NewWindow(&start, &end), nil
  135. }
  136. if window == "yesterday" {
  137. start := now
  138. start = start.Truncate(time.Hour * 24)
  139. start = start.Add(offset)
  140. start = start.Add(time.Hour * -24)
  141. end := start.Add(time.Hour * 24)
  142. return NewWindow(&start, &end), nil
  143. }
  144. if window == "week" {
  145. // now
  146. start := now
  147. // 00:00 today, accounting for timezone offset
  148. start = start.Truncate(time.Hour * 24)
  149. start = start.Add(offset)
  150. // 00:00 Sunday of the current week
  151. start = start.Add(-24 * time.Hour * time.Duration(start.Weekday()))
  152. end := now
  153. return NewWindow(&start, &end), nil
  154. }
  155. if window == "lastweek" {
  156. // now
  157. start := now
  158. // 00:00 today, accounting for timezone offset
  159. start = start.Truncate(time.Hour * 24)
  160. start = start.Add(offset)
  161. // 00:00 Sunday of last week
  162. start = start.Add(-24 * time.Hour * time.Duration(start.Weekday()+7))
  163. end := start.Add(7 * 24 * time.Hour)
  164. return NewWindow(&start, &end), nil
  165. }
  166. if window == "month" {
  167. // now
  168. start := now
  169. // 00:00 today, accounting for timezone offset
  170. start = start.Truncate(time.Hour * 24)
  171. start = start.Add(offset)
  172. // 00:00 1st of this month
  173. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  174. end := now
  175. return NewWindow(&start, &end), nil
  176. }
  177. if window == "month" {
  178. // now
  179. start := now
  180. // 00:00 today, accounting for timezone offset
  181. start = start.Truncate(time.Hour * 24)
  182. start = start.Add(offset)
  183. // 00:00 1st of this month
  184. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  185. end := now
  186. return NewWindow(&start, &end), nil
  187. }
  188. if window == "lastmonth" {
  189. // now
  190. end := now
  191. // 00:00 today, accounting for timezone offset
  192. end = end.Truncate(time.Hour * 24)
  193. end = end.Add(offset)
  194. // 00:00 1st of this month
  195. end = end.Add(-24 * time.Hour * time.Duration(end.Day()-1))
  196. // 00:00 last day of last month
  197. start := end.Add(-24 * time.Hour)
  198. // 00:00 1st of last month
  199. start = start.Add(-24 * time.Hour * time.Duration(start.Day()-1))
  200. return NewWindow(&start, &end), nil
  201. }
  202. // Match duration strings; e.g. "45m", "24h", "7d"
  203. match := durationRegex.FindStringSubmatch(window)
  204. if match != nil {
  205. dur := time.Minute
  206. if match[2] == "h" {
  207. dur = time.Hour
  208. }
  209. if match[2] == "d" {
  210. dur = 24 * time.Hour
  211. }
  212. if match[2] == "w" {
  213. dur = timeutil.Week
  214. }
  215. num, _ := strconv.ParseInt(match[1], 10, 64)
  216. end := now
  217. start := end.Add(-time.Duration(num) * dur)
  218. // when using windows such as "7d", "1w", and "2h" we have to have a definition for what "the past X days/hours" means.
  219. // let "the past X days" be defined as the entirety of today plus the entirety of the past X-1 days, where
  220. // "entirety" is defined as midnight to midnight, UTC. given this definition, we round forward the calculated
  221. // start and end times to the nearest day to align with midnight boundaries
  222. // an analogous definition applies to "the past X weeks" and "the past X hours"
  223. if match[2] == "w" {
  224. // special case - with a week, we say the week ends today
  225. end = end.Truncate(timeutil.Day).Add(timeutil.Day)
  226. start = start.Truncate(timeutil.Day).Add(timeutil.Day)
  227. } else {
  228. end = now.Truncate(dur).Add(dur)
  229. start = end.Add(-time.Duration(num) * dur)
  230. }
  231. return NewWindow(&start, &end), nil
  232. }
  233. // Match duration strings with offset; e.g. "45m offset 15m", etc.
  234. match = durationOffsetRegex.FindStringSubmatch(window)
  235. if match != nil {
  236. end := now
  237. offUnit := time.Minute
  238. if match[4] == "h" {
  239. offUnit = time.Hour
  240. }
  241. if match[4] == "d" {
  242. offUnit = 24 * time.Hour
  243. }
  244. if match[4] == "w" {
  245. offUnit = 24 * timeutil.Week
  246. }
  247. offNum, _ := strconv.ParseInt(match[3], 10, 64)
  248. end = end.Add(-time.Duration(offNum) * offUnit)
  249. durUnit := time.Minute
  250. if match[2] == "h" {
  251. durUnit = time.Hour
  252. }
  253. if match[2] == "d" {
  254. durUnit = 24 * time.Hour
  255. }
  256. if match[2] == "w" {
  257. durUnit = timeutil.Week
  258. }
  259. durNum, _ := strconv.ParseInt(match[1], 10, 64)
  260. start := end.Add(-time.Duration(durNum) * durUnit)
  261. return NewWindow(&start, &end), nil
  262. }
  263. // Match timestamp pairs, e.g. "1586822400,1586908800" or "1586822400-1586908800"
  264. match = timestampPairRegex.FindStringSubmatch(window)
  265. if match != nil {
  266. s, _ := strconv.ParseInt(match[1], 10, 64)
  267. e, _ := strconv.ParseInt(match[2], 10, 64)
  268. start := time.Unix(s, 0).UTC()
  269. end := time.Unix(e, 0).UTC()
  270. return NewWindow(&start, &end), nil
  271. }
  272. // Match RFC3339 pairs, e.g. "2020-04-01T00:00:00Z,2020-04-03T00:00:00Z"
  273. match = rfcRegex.FindStringSubmatch(window)
  274. if match != nil {
  275. start, _ := time.Parse(time.RFC3339, match[1])
  276. end, _ := time.Parse(time.RFC3339, match[2])
  277. return NewWindow(&start, &end), nil
  278. }
  279. return Window{nil, nil}, fmt.Errorf("illegal window: %s", window)
  280. }
  281. // ApproximatelyEqual returns true if the start and end times of the two windows,
  282. // respectively, are within the given threshold of each other.
  283. func (w Window) ApproximatelyEqual(that Window, threshold time.Duration) bool {
  284. return approxEqual(w.start, that.start, threshold) && approxEqual(w.end, that.end, threshold)
  285. }
  286. func approxEqual(x *time.Time, y *time.Time, threshold time.Duration) bool {
  287. // both times are nil, so they are equal
  288. if x == nil && y == nil {
  289. return true
  290. }
  291. // one time is nil, but the other is not, so they are not equal
  292. if x == nil || y == nil {
  293. return false
  294. }
  295. // neither time is nil, so they are approximately close if their times are
  296. // within the given threshold
  297. delta := math.Abs((*x).Sub(*y).Seconds())
  298. return delta < threshold.Seconds()
  299. }
  300. func (w Window) Clone() Window {
  301. var start, end *time.Time
  302. var s, e time.Time
  303. if w.start != nil {
  304. s = *w.start
  305. start = &s
  306. }
  307. if w.end != nil {
  308. e = *w.end
  309. end = &e
  310. }
  311. return NewWindow(start, end)
  312. }
  313. func (w Window) Contains(t time.Time) bool {
  314. if w.start != nil && t.Before(*w.start) {
  315. return false
  316. }
  317. if w.end != nil && t.After(*w.end) {
  318. return false
  319. }
  320. return true
  321. }
  322. func (w Window) ContainsWindow(that Window) bool {
  323. // only support containing closed windows for now
  324. // could check if openness is compatible with closure
  325. if that.IsOpen() {
  326. return false
  327. }
  328. return w.Contains(*that.start) && w.Contains(*that.end)
  329. }
  330. func (w Window) Duration() time.Duration {
  331. if w.IsOpen() {
  332. // TODO test
  333. return time.Duration(math.Inf(1.0))
  334. }
  335. return w.end.Sub(*w.start)
  336. }
  337. func (w Window) End() *time.Time {
  338. return w.end
  339. }
  340. func (w Window) Equal(that Window) bool {
  341. if w.start != nil && that.start != nil && !w.start.Equal(*that.start) {
  342. // starts are not nil, but not equal
  343. return false
  344. }
  345. if w.end != nil && that.end != nil && !w.end.Equal(*that.end) {
  346. // ends are not nil, but not equal
  347. return false
  348. }
  349. if (w.start == nil && that.start != nil) || (w.start != nil && that.start == nil) {
  350. // one start is nil, the other is not
  351. return false
  352. }
  353. if (w.end == nil && that.end != nil) || (w.end != nil && that.end == nil) {
  354. // one end is nil, the other is not
  355. return false
  356. }
  357. // either both starts are nil, or they match; likewise for the ends
  358. return true
  359. }
  360. func (w Window) ExpandStart(start time.Time) Window {
  361. if w.start == nil || start.Before(*w.start) {
  362. w.start = &start
  363. }
  364. return w
  365. }
  366. func (w Window) ExpandEnd(end time.Time) Window {
  367. if w.end == nil || end.After(*w.end) {
  368. w.end = &end
  369. }
  370. return w
  371. }
  372. func (w Window) Expand(that Window) Window {
  373. if that.start == nil {
  374. w.start = nil
  375. } else {
  376. w = w.ExpandStart(*that.start)
  377. }
  378. if that.end == nil {
  379. w.end = nil
  380. } else {
  381. w = w.ExpandEnd(*that.end)
  382. }
  383. return w
  384. }
  385. func (w Window) ContractStart(start time.Time) Window {
  386. if w.start == nil || start.After(*w.start) {
  387. w.start = &start
  388. }
  389. return w
  390. }
  391. func (w Window) ContractEnd(end time.Time) Window {
  392. if w.end == nil || end.Before(*w.end) {
  393. w.end = &end
  394. }
  395. return w
  396. }
  397. func (w Window) Contract(that Window) Window {
  398. if that.start != nil {
  399. w = w.ContractStart(*that.start)
  400. }
  401. if that.end != nil {
  402. w = w.ContractEnd(*that.end)
  403. }
  404. return w
  405. }
  406. func (w Window) Hours() float64 {
  407. if w.IsOpen() {
  408. return math.Inf(1)
  409. }
  410. return w.end.Sub(*w.start).Hours()
  411. }
  412. // IsEmpty a Window is empty if it does not have a start and an end
  413. func (w Window) IsEmpty() bool {
  414. return w.start == nil && w.end == nil
  415. }
  416. // HasDuration a Window has duration if neither start and end are not nil and not equal
  417. func (w Window) HasDuration() bool {
  418. return !w.IsOpen() && !w.end.Equal(*w.Start())
  419. }
  420. // IsNegative a Window is negative if start and end are not null and end is before start
  421. func (w Window) IsNegative() bool {
  422. return !w.IsOpen() && w.end.Before(*w.Start())
  423. }
  424. // IsOpen a Window is open if it has a nil start or end
  425. func (w Window) IsOpen() bool {
  426. return w.start == nil || w.end == nil
  427. }
  428. func (w Window) MarshalJSON() ([]byte, error) {
  429. buffer := bytes.NewBufferString("{")
  430. if w.start != nil {
  431. buffer.WriteString(fmt.Sprintf("\"start\":\"%s\",", w.start.Format(time.RFC3339)))
  432. } else {
  433. buffer.WriteString(fmt.Sprintf("\"start\":\"%s\",", "null"))
  434. }
  435. if w.end != nil {
  436. buffer.WriteString(fmt.Sprintf("\"end\":\"%s\"", w.end.Format(time.RFC3339)))
  437. } else {
  438. buffer.WriteString(fmt.Sprintf("\"end\":\"%s\"", "null"))
  439. }
  440. buffer.WriteString("}")
  441. return buffer.Bytes(), nil
  442. }
  443. func (w *Window) UnmarshalJSON(bs []byte) error {
  444. // Due to the behavior of our custom MarshalJSON, we unmarshal as strings
  445. // and then manually handle the weird quoted "null" case.
  446. type PubWindow struct {
  447. Start string `json:"start"`
  448. End string `json:"end"`
  449. }
  450. var pw PubWindow
  451. err := json.Unmarshal(bs, &pw)
  452. if err != nil {
  453. return fmt.Errorf("half unmarshal: %w", err)
  454. }
  455. var start *time.Time
  456. var end *time.Time
  457. if pw.Start != "null" {
  458. t, err := time.Parse(time.RFC3339, pw.Start)
  459. if err != nil {
  460. return fmt.Errorf("parsing start as RFC3339: %w", err)
  461. }
  462. start = &t
  463. }
  464. if pw.End != "null" {
  465. t, err := time.Parse(time.RFC3339, pw.End)
  466. if err != nil {
  467. return fmt.Errorf("parsing end as RFC3339: %w", err)
  468. }
  469. end = &t
  470. }
  471. w.start = start
  472. w.end = end
  473. return nil
  474. }
  475. func (w Window) Minutes() float64 {
  476. if w.IsOpen() {
  477. return math.Inf(1)
  478. }
  479. return w.end.Sub(*w.start).Minutes()
  480. }
  481. // Overlaps returns true iff the two given Windows share an amount of temporal
  482. // coverage.
  483. func (w Window) Overlaps(x Window) bool {
  484. if (w.start == nil && w.end == nil) || (x.start == nil && x.end == nil) {
  485. // one window is completely open, so overlap is guaranteed
  486. // <---------->
  487. // ?------?
  488. return true
  489. }
  490. // Neither window is completely open (nil, nil), but one or the other might
  491. // still be future- or past-open.
  492. if w.start == nil {
  493. // w is past-open, future-closed
  494. // <------]
  495. if x.start != nil && !x.start.Before(*w.end) {
  496. // x starts after w ends (or eq)
  497. // <------]
  498. // [------?
  499. return false
  500. }
  501. // <-----]
  502. // ?-----?
  503. return true
  504. }
  505. if w.end == nil {
  506. // w is future-open, past-closed
  507. // [------>
  508. if x.end != nil && !x.end.After(*w.start) {
  509. // x ends before w begins (or eq)
  510. // [------>
  511. // ?------]
  512. return false
  513. }
  514. // [------>
  515. // ?------?
  516. return true
  517. }
  518. // Now we know w is closed, but we don't know about x
  519. // [------]
  520. // ?------?
  521. if x.start == nil {
  522. // x is past-open, future-closed
  523. // <------]
  524. // [------]
  525. if !x.end.Before(*w.start) {
  526. // x ends after w starts (or eq)
  527. // <------]
  528. // [------]
  529. return true
  530. }
  531. // x ends before w starts
  532. // <------]
  533. // [------]
  534. return false
  535. }
  536. if x.end == nil {
  537. // x is future-open, past-closed
  538. // [------>
  539. // [------]
  540. if !x.start.After(*w.end) {
  541. // x starts before w ends (or eq)
  542. // [------>
  543. // [------]
  544. return true
  545. }
  546. // x starts after w ends
  547. // [------>
  548. // [------]
  549. return false
  550. }
  551. // Both are closed.
  552. if !x.start.Before(*w.end) && !x.end.Before(*w.end) {
  553. // x starts and ends after w ends
  554. // [------]
  555. // [------]
  556. return false
  557. }
  558. if !x.start.After(*w.start) && !x.end.After(*w.start) {
  559. // x starts and ends before w starts
  560. // [------]
  561. // [------]
  562. return false
  563. }
  564. // w and x must overlap
  565. // [------]
  566. // [------]
  567. return true
  568. }
  569. func (w *Window) Set(start, end *time.Time) {
  570. w.start = start
  571. w.end = end
  572. }
  573. // Shift adds the given duration to both the start and end times of the window
  574. func (w Window) Shift(dur time.Duration) Window {
  575. if w.start != nil {
  576. s := w.start.Add(dur)
  577. w.start = &s
  578. }
  579. if w.end != nil {
  580. e := w.end.Add(dur)
  581. w.end = &e
  582. }
  583. return w
  584. }
  585. func (w Window) Start() *time.Time {
  586. return w.start
  587. }
  588. func (w Window) String() string {
  589. if w.start == nil && w.end == nil {
  590. return "[nil, nil)"
  591. }
  592. if w.start == nil {
  593. return fmt.Sprintf("[nil, %s)", w.end.Format("2006-01-02T15:04:05-0700"))
  594. }
  595. if w.end == nil {
  596. return fmt.Sprintf("[%s, nil)", w.start.Format("2006-01-02T15:04:05-0700"))
  597. }
  598. return fmt.Sprintf("[%s, %s)", w.start.Format("2006-01-02T15:04:05-0700"), w.end.Format("2006-01-02T15:04:05-0700"))
  599. }
  600. // DurationOffset returns durations representing the duration and offset of the
  601. // given window
  602. func (w Window) DurationOffset() (time.Duration, time.Duration, error) {
  603. if w.IsOpen() || w.IsNegative() {
  604. return 0, 0, fmt.Errorf("illegal window: %s", w)
  605. }
  606. duration := w.Duration()
  607. offset := time.Since(*w.End())
  608. return duration, offset, nil
  609. }
  610. // DurationOffsetStrings returns formatted, Prometheus-compatible strings representing
  611. // the duration and offset of the window in terms of days, hours, minutes, or seconds;
  612. // e.g. ("7d", "1441m", "30m", "1s", "")
  613. func (w Window) DurationOffsetStrings() (string, string) {
  614. dur, off, err := w.DurationOffset()
  615. if err != nil {
  616. return "", ""
  617. }
  618. return timeutil.DurationOffsetStrings(dur, off)
  619. }
  620. // GetPercentInWindow Determine pct of item time contained the window.
  621. // determined by the overlap of the start/end with the given
  622. // window, which will be negative if there is no overlap. If
  623. // there is positive overlap, compare it with the total mins.
  624. //
  625. // e.g. here are the two possible scenarios as simplidied
  626. // 10m windows with dashes representing item's time running:
  627. //
  628. // 1. item falls entirely within one CloudCostSet window
  629. // | ---- | | |
  630. // totalMins = 4.0
  631. // pct := 4.0 / 4.0 = 1.0 for window 1
  632. // pct := 0.0 / 4.0 = 0.0 for window 2
  633. // pct := 0.0 / 4.0 = 0.0 for window 3
  634. //
  635. // 2. item overlaps multiple CloudCostSet windows
  636. // | ----|----------|-- |
  637. // totalMins = 16.0
  638. // pct := 4.0 / 16.0 = 0.250 for window 1
  639. // pct := 10.0 / 16.0 = 0.625 for window 2
  640. // pct := 2.0 / 16.0 = 0.125 for window 3
  641. func (w Window) GetPercentInWindow(that Window) float64 {
  642. if that.IsOpen() {
  643. log.Errorf("Window: GetPercentInWindow: invalid window %s", that.String())
  644. return 0
  645. }
  646. s := *that.Start()
  647. if s.Before(*w.Start()) {
  648. s = *w.Start()
  649. }
  650. e := *that.End()
  651. if e.After(*w.End()) {
  652. e = *w.End()
  653. }
  654. mins := e.Sub(s).Minutes()
  655. if mins <= 0.0 {
  656. return 0.0
  657. }
  658. totalMins := that.Duration().Minutes()
  659. pct := mins / totalMins
  660. return pct
  661. }
  662. // GetAccumulateWindow rounds the start and end of the window to the given accumulation option
  663. func (w Window) GetAccumulateWindow(accumOpt AccumulateOption) (Window, error) {
  664. if w.IsOpen() {
  665. return w, fmt.Errorf("could not get accumlate window for open window")
  666. }
  667. switch accumOpt {
  668. case AccumulateOptionAll:
  669. // just return the entire window
  670. return w.Clone(), nil
  671. case AccumulateOptionHour:
  672. return w.getHourlyWindow(), nil
  673. case AccumulateOptionDay:
  674. return w.getDailyWindow(), nil
  675. case AccumulateOptionWeek:
  676. return w.getWeeklyWindow(), nil
  677. case AccumulateOptionMonth:
  678. return w.getMonthlyWindow(), nil
  679. case AccumulateOptionQuarter:
  680. return w.getQuarterlyWindow(), nil
  681. case AccumulateOptionNone:
  682. // the default behavior of the app currently is to return the highest resolution steps
  683. // possible
  684. fallthrough
  685. default:
  686. // if we are here, it means someone wants a window older than what we can query for
  687. return w, fmt.Errorf("cannot round window to given accumulation option %s", string(accumOpt))
  688. }
  689. }
  690. // GetAccumulateWindows breaks provided window into a []Window with each window having the resolution of the provided AccumulateOption
  691. func (w Window) GetAccumulateWindows(accumOpt AccumulateOption) ([]Window, error) {
  692. if w.IsOpen() {
  693. return nil, fmt.Errorf("could not get accumlate window for open window")
  694. }
  695. switch accumOpt {
  696. case AccumulateOptionAll:
  697. // just return the entire window
  698. return []Window{w.Clone()}, nil
  699. case AccumulateOptionDay:
  700. wins := w.getDailyWindows()
  701. return wins, nil
  702. case AccumulateOptionWeek:
  703. wins := w.getWeeklyWindows()
  704. return wins, nil
  705. case AccumulateOptionMonth:
  706. wins := w.getMonthlyWindows()
  707. return wins, nil
  708. case AccumulateOptionHour:
  709. // our maximum resolution is hourly
  710. wins := w.getHourlyWindows()
  711. return wins, nil
  712. case AccumulateOptionQuarter:
  713. wins := w.getQuarterlyWindows()
  714. return wins, nil
  715. case AccumulateOptionNone:
  716. // the default behavior of the app currently is to return the highest resolution steps
  717. // possible
  718. fallthrough
  719. default:
  720. // if we are here, it means someone wants a window older than what we can query for
  721. return nil, fmt.Errorf("store does not have coverage window starting at %v", w.Start())
  722. }
  723. }
  724. func (w Window) getHourlyWindow() Window {
  725. origStart := w.Start()
  726. origEnd := w.End()
  727. // round the start and end windows to the calendar hour start and ends, respectively
  728. roundedStart := time.Date(origStart.Year(), origStart.Month(), origStart.Day(), origStart.Hour(), 0, 0, 0, origStart.Location())
  729. roundedEnd := time.Date(origEnd.Year(), origEnd.Month(), origEnd.Day(), origEnd.Hour()+1, 0, 0, 0, origEnd.Location())
  730. // edge case - if user has exactly specified first instant of new hour, does not need rounding
  731. if origEnd.Minute() == 0 && origEnd.Second() == 0 {
  732. roundedEnd = *origEnd
  733. }
  734. return NewClosedWindow(roundedStart, roundedEnd)
  735. }
  736. // getHourlyWindows breaks up a window into hours
  737. func (w Window) getHourlyWindows() []Window {
  738. wins := []Window{}
  739. roundedWindow := w.getHourlyWindow()
  740. roundedStart := *roundedWindow.Start()
  741. roundedEnd := *roundedWindow.End()
  742. currStart := roundedStart
  743. currEnd := time.Date(currStart.Year(), currStart.Month(), currStart.Day(), currStart.Hour()+1, 0, 0, 0, currStart.Location())
  744. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  745. wins = append(wins, NewClosedWindow(currStart, currEnd))
  746. currStart = currEnd
  747. currEnd = time.Date(currEnd.Year(), currEnd.Month(), currEnd.Day(), currEnd.Hour()+1, 0, 0, 0, currStart.Location())
  748. }
  749. return wins
  750. }
  751. func (w Window) getDailyWindow() Window {
  752. origStart := w.Start()
  753. origEnd := w.End()
  754. // round the start and end windows to the calendar day start and ends, respectively
  755. roundedStart := time.Date(origStart.Year(), origStart.Month(), origStart.Day(), 0, 0, 0, 0, origStart.Location())
  756. roundedEnd := time.Date(origEnd.Year(), origEnd.Month(), origEnd.Day()+1, 0, 0, 0, 0, origEnd.Location())
  757. // edge case - if user has exactly specified first instant of new day, does not need rounding
  758. if origEnd.Minute() == 0 && origEnd.Second() == 0 && origEnd.Hour() == 0 {
  759. roundedEnd = *origEnd
  760. }
  761. return NewClosedWindow(roundedStart, roundedEnd)
  762. }
  763. // getDailyWindows breaks up a window into days
  764. func (w Window) getDailyWindows() []Window {
  765. wins := []Window{}
  766. roundedWindow := w.getDailyWindow()
  767. roundedStart := *roundedWindow.Start()
  768. roundedEnd := *roundedWindow.End()
  769. currStart := roundedStart
  770. currEnd := time.Date(currStart.Year(), currStart.Month(), currStart.Day()+1, 0, 0, 0, 0, currStart.Location())
  771. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  772. wins = append(wins, NewClosedWindow(currStart, currEnd))
  773. currStart = currEnd
  774. currEnd = time.Date(currEnd.Year(), currEnd.Month(), currEnd.Day()+1, 0, 0, 0, 0, currStart.Location())
  775. }
  776. return wins
  777. }
  778. func (w Window) getWeeklyWindow() Window {
  779. origStart := w.Start()
  780. origEnd := w.End()
  781. // round the start and end windows to the calendar month start and ends, respectively
  782. roundedStart := origStart.Add(-1 * time.Duration(origStart.Weekday()) * time.Hour * 24)
  783. roundedStart = time.Date(roundedStart.Year(), roundedStart.Month(), roundedStart.Day(), 0, 0, 0, 0, origEnd.Location())
  784. roundedEnd := origEnd.Add(time.Duration(6-origEnd.Weekday()) * time.Hour * 24)
  785. roundedEnd = time.Date(roundedEnd.Year(), roundedEnd.Month(), roundedEnd.Day()+1, 0, 0, 0, 0, origEnd.Location())
  786. // edge case - if user has exactly specified first instant of new day, does not need rounding
  787. if origEnd.Weekday() == 0 && origEnd.Second() == 0 && origEnd.Hour() == 0 {
  788. roundedEnd = *origEnd
  789. }
  790. return NewClosedWindow(roundedStart, roundedEnd)
  791. }
  792. // getWeeklyWindows breaks up a window into weeks, with weeks starting on Sunday
  793. func (w Window) getWeeklyWindows() []Window {
  794. wins := []Window{}
  795. roundedWindow := w.getWeeklyWindow()
  796. roundedStart := *roundedWindow.Start()
  797. roundedEnd := *roundedWindow.End()
  798. currStart := roundedStart
  799. currEnd := time.Date(currStart.Year(), currStart.Month(), currStart.Day()+7, 0, 0, 0, 0, currStart.Location())
  800. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  801. wins = append(wins, NewClosedWindow(currStart, currEnd))
  802. currStart = currEnd
  803. currEnd = time.Date(currEnd.Year(), currEnd.Month(), currEnd.Day()+7, 0, 0, 0, 0, currStart.Location())
  804. }
  805. return wins
  806. }
  807. func (w Window) getMonthlyWindow() Window {
  808. origStart := w.Start()
  809. origEnd := w.End()
  810. // round the start and end windows to the calendar month start and ends, respectively
  811. roundedStart := time.Date(origStart.Year(), origStart.Month(), 1, 0, 0, 0, 0, origStart.Location())
  812. roundedEnd := time.Date(origEnd.Year(), origEnd.Month()+1, 1, 0, 0, 0, 0, origEnd.Location())
  813. // edge case - if user has exactly specified first instant of new month, does not need rounding
  814. if origEnd.Day() == 1 && origEnd.Hour() == 0 && origEnd.Minute() == 0 && origEnd.Second() == 0 {
  815. roundedEnd = *origEnd
  816. }
  817. return NewClosedWindow(roundedStart, roundedEnd)
  818. }
  819. // getMonthlyWindows breaks up a window into calendar months
  820. func (w Window) getMonthlyWindows() []Window {
  821. wins := []Window{}
  822. roundedWindow := w.getMonthlyWindow()
  823. roundedStart := *roundedWindow.Start()
  824. roundedEnd := *roundedWindow.End()
  825. currStart := roundedStart
  826. currEnd := time.Date(currStart.Year(), currStart.Month()+1, 1, 0, 0, 0, 0, currStart.Location())
  827. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  828. wins = append(wins, NewClosedWindow(currStart, currEnd))
  829. currStart = currEnd
  830. currEnd = time.Date(currEnd.Year(), currEnd.Month()+1, 1, 0, 0, 0, 0, currStart.Location())
  831. }
  832. return wins
  833. }
  834. func (w Window) getQuarterlyWindow() Window {
  835. origStart := w.Start()
  836. origEnd := w.End()
  837. // round the start and end windows to the calendar quarter start and ends, respectively
  838. // get quarter fraction from month
  839. startQuarterNum := int(math.Ceil(float64(origStart.Month()) / 3.0))
  840. endQuarterNum := int(math.Ceil(float64(origEnd.Month()) / 3.0))
  841. roundedStart := time.Date(origStart.Year(), time.Month((startQuarterNum*3)-2), 1, 0, 0, 0, 0, origStart.Location())
  842. roundedEnd := time.Date(origEnd.Year(), time.Month(((endQuarterNum+1)*3)-2), 1, 0, 0, 0, 0, origEnd.Location())
  843. // edge case - if user has exactly specified first instant of new quarter, does not need rounding
  844. if origEnd.Month() == time.Month(((endQuarterNum)*3)-2) && origEnd.Day() == 1 && origEnd.Hour() == 0 && origEnd.Minute() == 0 && origEnd.Second() == 0 {
  845. roundedEnd = *origEnd
  846. }
  847. return NewClosedWindow(roundedStart, roundedEnd)
  848. }
  849. // getQuarterlyWindows breaks up a window into calendar months
  850. func (w Window) getQuarterlyWindows() []Window {
  851. wins := []Window{}
  852. roundedWindow := w.getQuarterlyWindow()
  853. roundedStart := *roundedWindow.Start()
  854. roundedEnd := *roundedWindow.End()
  855. currStart := roundedStart
  856. currEnd := time.Date(currStart.Year(), currStart.Month()+3, 1, 0, 0, 0, 0, currStart.Location())
  857. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  858. wins = append(wins, NewClosedWindow(currStart, currEnd))
  859. currStart = currEnd
  860. currEnd = time.Date(currEnd.Year(), currEnd.Month()+3, 1, 0, 0, 0, 0, currStart.Location())
  861. }
  862. return wins
  863. }
  864. // GetWindows returns a slice of Window with equal size between the given start and end. If windowSize does not evenly
  865. // divide the period between start and end, the last window is not added
  866. // Deprecated: in v1.107 use Window.GetWindows() instead
  867. func GetWindows(start time.Time, end time.Time, windowSize time.Duration) ([]Window, error) {
  868. // Ensure the range is evenly divisible into windows of the given duration
  869. dur := end.Sub(start)
  870. if int(dur.Minutes())%int(windowSize.Minutes()) != 0 {
  871. return nil, fmt.Errorf("range not divisible by window: [%s, %s] by %s", start, end, windowSize)
  872. }
  873. // Ensure that provided times are multiples of the provided windowSize (e.g. midnight for daily windows, on the hour for hourly windows)
  874. if start != RoundBack(start, windowSize) {
  875. return nil, fmt.Errorf("provided times are not divisible by provided window: [%s, %s] by %s", start, end, windowSize)
  876. }
  877. // Ensure timezones match
  878. _, sz := start.Zone()
  879. _, ez := end.Zone()
  880. if sz != ez {
  881. return nil, fmt.Errorf("range has mismatched timezones: %s, %s", start, end)
  882. }
  883. if sz != int(utcOffset().Seconds()) {
  884. return nil, fmt.Errorf("range timezone doesn't match configured timezone: expected %s; found %ds", utcOffset(), sz)
  885. }
  886. // Build array of windows to cover the CloudCostSetRange
  887. windows := []Window{}
  888. s, e := start, start.Add(windowSize)
  889. for !e.After(end) {
  890. ws := s
  891. we := e
  892. windows = append(windows, NewWindow(&ws, &we))
  893. s = s.Add(windowSize)
  894. e = e.Add(windowSize)
  895. }
  896. return windows, nil
  897. }
  898. // GetWindowsForQueryWindow breaks up a window into an array of windows with a max size of queryWindow
  899. func GetWindowsForQueryWindow(start time.Time, end time.Time, queryWindow time.Duration) ([]Window, error) {
  900. // Ensure timezones match
  901. _, sz := start.Zone()
  902. _, ez := end.Zone()
  903. if sz != ez {
  904. return nil, fmt.Errorf("range has mismatched timezones: %s, %s", start, end)
  905. }
  906. if sz != int(utcOffset().Seconds()) {
  907. return nil, fmt.Errorf("range timezone doesn't match configured timezone: expected %s; found %ds", utcOffset(), sz)
  908. }
  909. // Build array of windows to cover the CloudCostSetRange
  910. windows := []Window{}
  911. s, e := start, start.Add(queryWindow)
  912. for s.Before(end) {
  913. ws := s
  914. we := e
  915. windows = append(windows, NewWindow(&ws, &we))
  916. s = s.Add(queryWindow)
  917. e = e.Add(queryWindow)
  918. if e.After(end) {
  919. e = end
  920. }
  921. }
  922. return windows, nil
  923. }
  924. type BoundaryError struct {
  925. Requested Window
  926. Supported Window
  927. Message string
  928. }
  929. func NewBoundaryError(req, sup Window, msg string) *BoundaryError {
  930. return &BoundaryError{
  931. Requested: req,
  932. Supported: sup,
  933. Message: msg,
  934. }
  935. }
  936. func (be *BoundaryError) Error() string {
  937. if be == nil {
  938. return "<nil>"
  939. }
  940. return fmt.Sprintf("boundary error: requested %s; supported %s: %s", be.Requested, be.Supported, be.Message)
  941. }
  942. func (be *BoundaryError) Is(target error) bool {
  943. if _, ok := target.(*BoundaryError); ok {
  944. return true
  945. }
  946. return false
  947. }