window.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. // TODO complete (with unit tests!) and then implement in AllocationSet.accumulate
  484. // TODO:CLEANUP
  485. // func (w Window) Overlaps(x Window) bool {
  486. // if (w.start == nil && w.end == nil) || (x.start == nil && x.end == nil) {
  487. // // one window is completely open, so overlap is guaranteed
  488. // // <---------->
  489. // // ?------?
  490. // return true
  491. // }
  492. // // Neither window is completely open (nil, nil), but one or the other might
  493. // // still be future- or past-open.
  494. // if w.start == nil {
  495. // // w is past-open, future-closed
  496. // // <------]
  497. // if x.start != nil && !x.start.Before(*w.end) {
  498. // // x starts after w ends (or eq)
  499. // // <------]
  500. // // [------?
  501. // return false
  502. // }
  503. // // <-----]
  504. // // ?-----?
  505. // return true
  506. // }
  507. // if w.end == nil {
  508. // // w is future-open, past-closed
  509. // // [------>
  510. // if x.end != nil && !x.end.After(*w.end) {
  511. // // x ends before w begins (or eq)
  512. // // [------>
  513. // // ?------]
  514. // return false
  515. // }
  516. // // [------>
  517. // // ?------?
  518. // return true
  519. // }
  520. // // Now we know w is closed, but we don't know about x
  521. // // [------]
  522. // // ?------?
  523. // if x.start == nil {
  524. // // TODO
  525. // }
  526. // if x.end == nil {
  527. // // TODO
  528. // }
  529. // // Both are closed.
  530. // if !x.start.Before(*w.end) && !x.end.Before(*w.end) {
  531. // // x starts and ends after w ends
  532. // // [------]
  533. // // [------]
  534. // return false
  535. // }
  536. // if !x.start.After(*w.start) && !x.end.After(*w.start) {
  537. // // x starts and ends before w starts
  538. // // [------]
  539. // // [------]
  540. // return false
  541. // }
  542. // // w and x must overlap
  543. // // [------]
  544. // // [------]
  545. // return true
  546. // }
  547. func (w *Window) Set(start, end *time.Time) {
  548. w.start = start
  549. w.end = end
  550. }
  551. // Shift adds the given duration to both the start and end times of the window
  552. func (w Window) Shift(dur time.Duration) Window {
  553. if w.start != nil {
  554. s := w.start.Add(dur)
  555. w.start = &s
  556. }
  557. if w.end != nil {
  558. e := w.end.Add(dur)
  559. w.end = &e
  560. }
  561. return w
  562. }
  563. func (w Window) Start() *time.Time {
  564. return w.start
  565. }
  566. func (w Window) String() string {
  567. if w.start == nil && w.end == nil {
  568. return "[nil, nil)"
  569. }
  570. if w.start == nil {
  571. return fmt.Sprintf("[nil, %s)", w.end.Format("2006-01-02T15:04:05-0700"))
  572. }
  573. if w.end == nil {
  574. return fmt.Sprintf("[%s, nil)", w.start.Format("2006-01-02T15:04:05-0700"))
  575. }
  576. return fmt.Sprintf("[%s, %s)", w.start.Format("2006-01-02T15:04:05-0700"), w.end.Format("2006-01-02T15:04:05-0700"))
  577. }
  578. // DurationOffset returns durations representing the duration and offset of the
  579. // given window
  580. func (w Window) DurationOffset() (time.Duration, time.Duration, error) {
  581. if w.IsOpen() || w.IsNegative() {
  582. return 0, 0, fmt.Errorf("illegal window: %s", w)
  583. }
  584. duration := w.Duration()
  585. offset := time.Since(*w.End())
  586. return duration, offset, 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 CloudCostSet 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 CloudCostSet 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. // GetAccumulateWindow rounds the start and end of the window to the given accumulation option
  641. func (w Window) GetAccumulateWindow(accumOpt AccumulateOption) (Window, error) {
  642. if w.IsOpen() {
  643. return w, fmt.Errorf("could not get accumlate window for open window")
  644. }
  645. switch accumOpt {
  646. case AccumulateOptionAll:
  647. // just return the entire window
  648. return w.Clone(), nil
  649. case AccumulateOptionHour:
  650. return w.getHourlyWindow(), nil
  651. case AccumulateOptionDay:
  652. return w.getDailyWindow(), nil
  653. case AccumulateOptionWeek:
  654. return w.getWeeklyWindow(), nil
  655. case AccumulateOptionMonth:
  656. return w.getMonthlyWindow(), nil
  657. case AccumulateOptionQuarter:
  658. return w.getQuarterlyWindow(), nil
  659. case AccumulateOptionNone:
  660. // the default behavior of the app currently is to return the highest resolution steps
  661. // possible
  662. fallthrough
  663. default:
  664. // if we are here, it means someone wants a window older than what we can query for
  665. return w, fmt.Errorf("cannot round window to given accumulation option %s", string(accumOpt))
  666. }
  667. }
  668. // GetAccumulateWindows breaks provided window into a []Window with each window having the resolution of the provided AccumulateOption
  669. func (w Window) GetAccumulateWindows(accumOpt AccumulateOption) ([]Window, error) {
  670. if w.IsOpen() {
  671. return nil, fmt.Errorf("could not get accumlate window for open window")
  672. }
  673. switch accumOpt {
  674. case AccumulateOptionAll:
  675. // just return the entire window
  676. return []Window{w.Clone()}, nil
  677. case AccumulateOptionDay:
  678. wins := w.getDailyWindows()
  679. return wins, nil
  680. case AccumulateOptionWeek:
  681. wins := w.getWeeklyWindows()
  682. return wins, nil
  683. case AccumulateOptionMonth:
  684. wins := w.getMonthlyWindows()
  685. return wins, nil
  686. case AccumulateOptionHour:
  687. // our maximum resolution is hourly
  688. wins := w.getHourlyWindows()
  689. return wins, nil
  690. case AccumulateOptionQuarter:
  691. wins := w.getQuarterlyWindows()
  692. return wins, nil
  693. case AccumulateOptionNone:
  694. // the default behavior of the app currently is to return the highest resolution steps
  695. // possible
  696. fallthrough
  697. default:
  698. // if we are here, it means someone wants a window older than what we can query for
  699. return nil, fmt.Errorf("store does not have coverage window starting at %v", w.Start())
  700. }
  701. }
  702. func (w Window) getHourlyWindow() Window {
  703. origStart := w.Start()
  704. origEnd := w.End()
  705. // round the start and end windows to the calendar hour start and ends, respectively
  706. roundedStart := time.Date(origStart.Year(), origStart.Month(), origStart.Day(), origStart.Hour(), 0, 0, 0, origStart.Location())
  707. roundedEnd := time.Date(origEnd.Year(), origEnd.Month(), origEnd.Day(), origEnd.Hour()+1, 0, 0, 0, origEnd.Location())
  708. // edge case - if user has exactly specified first instant of new hour, does not need rounding
  709. if origEnd.Minute() == 0 && origEnd.Second() == 0 {
  710. roundedEnd = *origEnd
  711. }
  712. return NewClosedWindow(roundedStart, roundedEnd)
  713. }
  714. // getHourlyWindows breaks up a window into hours
  715. func (w Window) getHourlyWindows() []Window {
  716. wins := []Window{}
  717. roundedWindow := w.getHourlyWindow()
  718. roundedStart := *roundedWindow.Start()
  719. roundedEnd := *roundedWindow.End()
  720. currStart := roundedStart
  721. currEnd := time.Date(currStart.Year(), currStart.Month(), currStart.Day(), currStart.Hour()+1, 0, 0, 0, currStart.Location())
  722. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  723. wins = append(wins, NewClosedWindow(currStart, currEnd))
  724. currStart = currEnd
  725. currEnd = time.Date(currEnd.Year(), currEnd.Month(), currEnd.Day(), currEnd.Hour()+1, 0, 0, 0, currStart.Location())
  726. }
  727. return wins
  728. }
  729. func (w Window) getDailyWindow() Window {
  730. origStart := w.Start()
  731. origEnd := w.End()
  732. // round the start and end windows to the calendar day start and ends, respectively
  733. roundedStart := time.Date(origStart.Year(), origStart.Month(), origStart.Day(), 0, 0, 0, 0, origStart.Location())
  734. roundedEnd := time.Date(origEnd.Year(), origEnd.Month(), origEnd.Day()+1, 0, 0, 0, 0, origEnd.Location())
  735. // edge case - if user has exactly specified first instant of new day, does not need rounding
  736. if origEnd.Minute() == 0 && origEnd.Second() == 0 && origEnd.Hour() == 0 {
  737. roundedEnd = *origEnd
  738. }
  739. return NewClosedWindow(roundedStart, roundedEnd)
  740. }
  741. // getDailyWindows breaks up a window into days
  742. func (w Window) getDailyWindows() []Window {
  743. wins := []Window{}
  744. roundedWindow := w.getDailyWindow()
  745. roundedStart := *roundedWindow.Start()
  746. roundedEnd := *roundedWindow.End()
  747. currStart := roundedStart
  748. currEnd := time.Date(currStart.Year(), currStart.Month(), currStart.Day()+1, 0, 0, 0, 0, currStart.Location())
  749. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  750. wins = append(wins, NewClosedWindow(currStart, currEnd))
  751. currStart = currEnd
  752. currEnd = time.Date(currEnd.Year(), currEnd.Month(), currEnd.Day()+1, 0, 0, 0, 0, currStart.Location())
  753. }
  754. return wins
  755. }
  756. func (w Window) getWeeklyWindow() Window {
  757. origStart := w.Start()
  758. origEnd := w.End()
  759. // round the start and end windows to the calendar month start and ends, respectively
  760. roundedStart := origStart.Add(-1 * time.Duration(origStart.Weekday()) * time.Hour * 24)
  761. roundedStart = time.Date(roundedStart.Year(), roundedStart.Month(), roundedStart.Day(), 0, 0, 0, 0, origEnd.Location())
  762. roundedEnd := origEnd.Add(time.Duration(6-origEnd.Weekday()) * time.Hour * 24)
  763. roundedEnd = time.Date(roundedEnd.Year(), roundedEnd.Month(), roundedEnd.Day()+1, 0, 0, 0, 0, origEnd.Location())
  764. // edge case - if user has exactly specified first instant of new day, does not need rounding
  765. if origEnd.Weekday() == 0 && origEnd.Second() == 0 && origEnd.Hour() == 0 {
  766. roundedEnd = *origEnd
  767. }
  768. return NewClosedWindow(roundedStart, roundedEnd)
  769. }
  770. // getWeeklyWindows breaks up a window into weeks, with weeks starting on Sunday
  771. func (w Window) getWeeklyWindows() []Window {
  772. wins := []Window{}
  773. roundedWindow := w.getWeeklyWindow()
  774. roundedStart := *roundedWindow.Start()
  775. roundedEnd := *roundedWindow.End()
  776. currStart := roundedStart
  777. currEnd := time.Date(currStart.Year(), currStart.Month(), currStart.Day()+7, 0, 0, 0, 0, currStart.Location())
  778. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  779. wins = append(wins, NewClosedWindow(currStart, currEnd))
  780. currStart = currEnd
  781. currEnd = time.Date(currEnd.Year(), currEnd.Month(), currEnd.Day()+7, 0, 0, 0, 0, currStart.Location())
  782. }
  783. return wins
  784. }
  785. func (w Window) getMonthlyWindow() Window {
  786. origStart := w.Start()
  787. origEnd := w.End()
  788. // round the start and end windows to the calendar month start and ends, respectively
  789. roundedStart := time.Date(origStart.Year(), origStart.Month(), 1, 0, 0, 0, 0, origStart.Location())
  790. roundedEnd := time.Date(origEnd.Year(), origEnd.Month()+1, 1, 0, 0, 0, 0, origEnd.Location())
  791. // edge case - if user has exactly specified first instant of new month, does not need rounding
  792. if origEnd.Day() == 1 && origEnd.Hour() == 0 && origEnd.Minute() == 0 && origEnd.Second() == 0 {
  793. roundedEnd = *origEnd
  794. }
  795. return NewClosedWindow(roundedStart, roundedEnd)
  796. }
  797. // getMonthlyWindows breaks up a window into calendar months
  798. func (w Window) getMonthlyWindows() []Window {
  799. wins := []Window{}
  800. roundedWindow := w.getMonthlyWindow()
  801. roundedStart := *roundedWindow.Start()
  802. roundedEnd := *roundedWindow.End()
  803. currStart := roundedStart
  804. currEnd := time.Date(currStart.Year(), currStart.Month()+1, 1, 0, 0, 0, 0, currStart.Location())
  805. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  806. wins = append(wins, NewClosedWindow(currStart, currEnd))
  807. currStart = currEnd
  808. currEnd = time.Date(currEnd.Year(), currEnd.Month()+1, 1, 0, 0, 0, 0, currStart.Location())
  809. }
  810. return wins
  811. }
  812. func (w Window) getQuarterlyWindow() Window {
  813. origStart := w.Start()
  814. origEnd := w.End()
  815. // round the start and end windows to the calendar quarter start and ends, respectively
  816. // get quarter fraction from month
  817. startQuarterNum := int(math.Ceil(float64(origStart.Month()) / 3.0))
  818. endQuarterNum := int(math.Ceil(float64(origEnd.Month()) / 3.0))
  819. roundedStart := time.Date(origStart.Year(), time.Month((startQuarterNum*3)-2), 1, 0, 0, 0, 0, origStart.Location())
  820. roundedEnd := time.Date(origEnd.Year(), time.Month(((endQuarterNum+1)*3)-2), 1, 0, 0, 0, 0, origEnd.Location())
  821. // edge case - if user has exactly specified first instant of new quarter, does not need rounding
  822. if origEnd.Month() == time.Month(((endQuarterNum)*3)-2) && origEnd.Day() == 1 && origEnd.Hour() == 0 && origEnd.Minute() == 0 && origEnd.Second() == 0 {
  823. roundedEnd = *origEnd
  824. }
  825. return NewClosedWindow(roundedStart, roundedEnd)
  826. }
  827. // getQuarterlyWindows breaks up a window into calendar months
  828. func (w Window) getQuarterlyWindows() []Window {
  829. wins := []Window{}
  830. roundedWindow := w.getQuarterlyWindow()
  831. roundedStart := *roundedWindow.Start()
  832. roundedEnd := *roundedWindow.End()
  833. currStart := roundedStart
  834. currEnd := time.Date(currStart.Year(), currStart.Month()+3, 1, 0, 0, 0, 0, currStart.Location())
  835. for currEnd.Before(roundedEnd) || currEnd.Equal(roundedEnd) {
  836. wins = append(wins, NewClosedWindow(currStart, currEnd))
  837. currStart = currEnd
  838. currEnd = time.Date(currEnd.Year(), currEnd.Month()+3, 1, 0, 0, 0, 0, currStart.Location())
  839. }
  840. return wins
  841. }
  842. // GetWindows returns a slice of Window with equal size between the given start and end. If windowSize does not evenly
  843. // divide the period between start and end, the last window is not added
  844. // Deprecated: in v1.107 use Window.GetWindows() instead
  845. func GetWindows(start time.Time, end time.Time, windowSize time.Duration) ([]Window, error) {
  846. // Ensure the range is evenly divisible into windows of the given duration
  847. dur := end.Sub(start)
  848. if int(dur.Minutes())%int(windowSize.Minutes()) != 0 {
  849. return nil, fmt.Errorf("range not divisible by window: [%s, %s] by %s", start, end, windowSize)
  850. }
  851. // Ensure that provided times are multiples of the provided windowSize (e.g. midnight for daily windows, on the hour for hourly windows)
  852. if start != RoundBack(start, windowSize) {
  853. return nil, fmt.Errorf("provided times are not divisible by provided window: [%s, %s] by %s", start, end, windowSize)
  854. }
  855. // Ensure timezones match
  856. _, sz := start.Zone()
  857. _, ez := end.Zone()
  858. if sz != ez {
  859. return nil, fmt.Errorf("range has mismatched timezones: %s, %s", start, end)
  860. }
  861. if sz != int(utcOffset().Seconds()) {
  862. return nil, fmt.Errorf("range timezone doesn't match configured timezone: expected %s; found %ds", utcOffset(), sz)
  863. }
  864. // Build array of windows to cover the CloudCostSetRange
  865. windows := []Window{}
  866. s, e := start, start.Add(windowSize)
  867. for !e.After(end) {
  868. ws := s
  869. we := e
  870. windows = append(windows, NewWindow(&ws, &we))
  871. s = s.Add(windowSize)
  872. e = e.Add(windowSize)
  873. }
  874. return windows, nil
  875. }
  876. // GetWindowsForQueryWindow breaks up a window into an array of windows with a max size of queryWindow
  877. func GetWindowsForQueryWindow(start time.Time, end time.Time, queryWindow time.Duration) ([]Window, error) {
  878. // Ensure timezones match
  879. _, sz := start.Zone()
  880. _, ez := end.Zone()
  881. if sz != ez {
  882. return nil, fmt.Errorf("range has mismatched timezones: %s, %s", start, end)
  883. }
  884. if sz != int(utcOffset().Seconds()) {
  885. return nil, fmt.Errorf("range timezone doesn't match configured timezone: expected %s; found %ds", utcOffset(), sz)
  886. }
  887. // Build array of windows to cover the CloudCostSetRange
  888. windows := []Window{}
  889. s, e := start, start.Add(queryWindow)
  890. for s.Before(end) {
  891. ws := s
  892. we := e
  893. windows = append(windows, NewWindow(&ws, &we))
  894. s = s.Add(queryWindow)
  895. e = e.Add(queryWindow)
  896. if e.After(end) {
  897. e = end
  898. }
  899. }
  900. return windows, nil
  901. }
  902. type BoundaryError struct {
  903. Requested Window
  904. Supported Window
  905. Message string
  906. }
  907. func NewBoundaryError(req, sup Window, msg string) *BoundaryError {
  908. return &BoundaryError{
  909. Requested: req,
  910. Supported: sup,
  911. Message: msg,
  912. }
  913. }
  914. func (be *BoundaryError) Error() string {
  915. if be == nil {
  916. return "<nil>"
  917. }
  918. return fmt.Sprintf("boundary error: requested %s; supported %s: %s", be.Requested, be.Supported, be.Message)
  919. }
  920. func (be *BoundaryError) Is(target error) bool {
  921. if _, ok := target.(*BoundaryError); ok {
  922. return true
  923. }
  924. return false
  925. }