allocation.go 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  1. package kubecost
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/kubecost/cost-model/pkg/log"
  11. )
  12. // TODO Clean-up use of IsEmpty; nil checks should be separated for safety.
  13. // TODO Consider making Allocation an interface, which is fulfilled by structs
  14. // like KubernetesAllocation, IdleAllocation, and ExternalAllocation.
  15. // ExternalSuffix indicates an external allocation
  16. const ExternalSuffix = "__external__"
  17. // IdleSuffix indicates an idle allocation property
  18. const IdleSuffix = "__idle__"
  19. // SharedSuffix indicates an shared allocation property
  20. const SharedSuffix = "__shared__"
  21. // UnallocatedSuffix indicates an unallocated allocation property
  22. const UnallocatedSuffix = "__unallocated__"
  23. // ShareWeighted indicates that a shared resource should be shared as a
  24. // proportion of the cost of the remaining allocations.
  25. const ShareWeighted = "__weighted__"
  26. // ShareEven indicates that a shared resource should be shared evenly across
  27. // all remaining allocations.
  28. const ShareEven = "__even__"
  29. // ShareNone indicates that a shareable resource should not be shared
  30. const ShareNone = "__none__"
  31. // Allocation is a unit of resource allocation and cost for a given window
  32. // of time and for a given kubernetes construct with its associated set of
  33. // properties.
  34. // TODO niko/computeallocation compute efficiency on the fly?
  35. type Allocation struct {
  36. Name string `json:"name"`
  37. Properties Properties `json:"properties,omitempty"`
  38. Window Window `json:"window"`
  39. Start time.Time `json:"start"`
  40. End time.Time `json:"end"`
  41. CPUCoreHours float64 `json:"cpuCoreHours"`
  42. CPUCoreRequestAverage float64 `json:"cpuCoreRequestAverage"`
  43. CPUCoreUsageAverage float64 `json:"cpuCoreUsageAverage"`
  44. CPUCost float64 `json:"cpuCost"`
  45. CPUEfficiency float64 `json:"cpuEfficiency"`
  46. GPUHours float64 `json:"gpuHours"`
  47. GPUCost float64 `json:"gpuCost"`
  48. NetworkCost float64 `json:"networkCost"`
  49. PVByteHours float64 `json:"pvByteHours"`
  50. PVCost float64 `json:"pvCost"`
  51. RAMByteHours float64 `json:"ramByteHours"`
  52. RAMBytesRequestAverage float64 `json:"ramBytesRequestAverage"`
  53. RAMBytesUsageAverage float64 `json:"ramBytesUsageAverage"`
  54. RAMCost float64 `json:"ramCost"`
  55. RAMEfficiency float64 `json:"ramEfficiency"`
  56. SharedCost float64 `json:"sharedCost"`
  57. ExternalCost float64 `json:"externalCost"`
  58. TotalCost float64 `json:"totalCost"`
  59. TotalEfficiency float64 `json:"totalEfficiency"`
  60. }
  61. // AllocationMatchFunc is a function that can be used to match Allocations by
  62. // returning true for any given Allocation if a condition is met.
  63. type AllocationMatchFunc func(*Allocation) bool
  64. // Add returns the result of summing the two given Allocations, which sums the
  65. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  66. // the two original Allocations are mutated in the process.
  67. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  68. if a == nil {
  69. return that.Clone(), nil
  70. }
  71. if that == nil {
  72. return a.Clone(), nil
  73. }
  74. // Note: no need to clone "that", as add only mutates the receiver
  75. agg := a.Clone()
  76. agg.add(that)
  77. return agg, nil
  78. }
  79. // Clone returns a deep copy of the given Allocation
  80. func (a *Allocation) Clone() *Allocation {
  81. if a == nil {
  82. return nil
  83. }
  84. return &Allocation{
  85. Name: a.Name,
  86. Properties: a.Properties.Clone(),
  87. Window: a.Window.Clone(),
  88. Start: a.Start,
  89. End: a.End,
  90. CPUCoreHours: a.CPUCoreHours,
  91. CPUCost: a.CPUCost,
  92. CPUEfficiency: a.CPUEfficiency,
  93. GPUHours: a.GPUHours,
  94. GPUCost: a.GPUCost,
  95. NetworkCost: a.NetworkCost,
  96. PVByteHours: a.PVByteHours,
  97. PVCost: a.PVCost,
  98. RAMByteHours: a.RAMByteHours,
  99. RAMCost: a.RAMCost,
  100. RAMEfficiency: a.RAMEfficiency,
  101. SharedCost: a.SharedCost,
  102. ExternalCost: a.ExternalCost,
  103. TotalCost: a.TotalCost,
  104. TotalEfficiency: a.TotalEfficiency,
  105. }
  106. }
  107. // Equal returns true if the values held in the given Allocation precisely
  108. // match those of the receiving Allocation. nil does not match nil.
  109. func (a *Allocation) Equal(that *Allocation) bool {
  110. if a == nil || that == nil {
  111. return false
  112. }
  113. if a.Name != that.Name {
  114. return false
  115. }
  116. if !a.Properties.Equal(&that.Properties) {
  117. return false
  118. }
  119. if !a.Window.Equal(that.Window) {
  120. return false
  121. }
  122. if !a.Start.Equal(that.Start) {
  123. return false
  124. }
  125. if !a.End.Equal(that.End) {
  126. return false
  127. }
  128. if a.CPUCoreHours != that.CPUCoreHours {
  129. return false
  130. }
  131. if a.CPUCost != that.CPUCost {
  132. return false
  133. }
  134. if a.CPUEfficiency != that.CPUEfficiency {
  135. return false
  136. }
  137. if a.GPUHours != that.GPUHours {
  138. return false
  139. }
  140. if a.GPUCost != that.GPUCost {
  141. return false
  142. }
  143. if a.NetworkCost != that.NetworkCost {
  144. return false
  145. }
  146. if a.PVByteHours != that.PVByteHours {
  147. return false
  148. }
  149. if a.PVCost != that.PVCost {
  150. return false
  151. }
  152. if a.RAMByteHours != that.RAMByteHours {
  153. return false
  154. }
  155. if a.RAMCost != that.RAMCost {
  156. return false
  157. }
  158. if a.RAMEfficiency != that.RAMEfficiency {
  159. return false
  160. }
  161. if a.SharedCost != that.SharedCost {
  162. return false
  163. }
  164. if a.ExternalCost != that.ExternalCost {
  165. return false
  166. }
  167. if a.TotalCost != that.TotalCost {
  168. return false
  169. }
  170. if a.TotalEfficiency != that.TotalEfficiency {
  171. return false
  172. }
  173. return true
  174. }
  175. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  176. func (a *Allocation) CPUCores() float64 {
  177. if a.Minutes() <= 0.0 {
  178. return 0.0
  179. }
  180. return a.CPUCoreHours / (a.Minutes() / 60.0)
  181. }
  182. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  183. func (a *Allocation) RAMBytes() float64 {
  184. if a.Minutes() <= 0.0 {
  185. return 0.0
  186. }
  187. return a.RAMByteHours / (a.Minutes() / 60.0)
  188. }
  189. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  190. func (a *Allocation) PVBytes() float64 {
  191. if a.Minutes() <= 0.0 {
  192. return 0.0
  193. }
  194. return a.PVByteHours / (a.Minutes() / 60.0)
  195. }
  196. // MarshalJSON implements json.Marshal interface
  197. func (a *Allocation) MarshalJSON() ([]byte, error) {
  198. buffer := bytes.NewBufferString("{")
  199. jsonEncodeString(buffer, "name", a.Name, ",")
  200. jsonEncode(buffer, "properties", a.Properties, ",")
  201. jsonEncode(buffer, "window", a.Window, ",")
  202. jsonEncodeString(buffer, "start", a.Start.Format(timeFmt), ",")
  203. jsonEncodeString(buffer, "end", a.End.Format(timeFmt), ",")
  204. jsonEncodeFloat64(buffer, "minutes", a.Minutes(), ",")
  205. jsonEncodeFloat64(buffer, "cpuCores", a.CPUCores(), ",")
  206. jsonEncodeFloat64(buffer, "cpuCoreRequestAverage", a.CPUCoreRequestAverage, ",")
  207. jsonEncodeFloat64(buffer, "cpuCoreUsageAverage", a.CPUCoreUsageAverage, ",")
  208. jsonEncodeFloat64(buffer, "cpuCoreHours", a.CPUCoreHours, ",")
  209. jsonEncodeFloat64(buffer, "cpuCost", a.CPUCost, ",")
  210. jsonEncodeFloat64(buffer, "cpuEfficiency", a.CPUEfficiency, ",")
  211. jsonEncodeFloat64(buffer, "gpuHours", a.GPUHours, ",")
  212. jsonEncodeFloat64(buffer, "gpuCost", a.GPUCost, ",")
  213. jsonEncodeFloat64(buffer, "networkCost", a.NetworkCost, ",")
  214. jsonEncodeFloat64(buffer, "pvBytes", a.PVBytes(), ",")
  215. jsonEncodeFloat64(buffer, "pvByteHours", a.PVByteHours, ",")
  216. jsonEncodeFloat64(buffer, "pvCost", a.PVCost, ",")
  217. jsonEncodeFloat64(buffer, "ramBytes", a.RAMBytes(), ",")
  218. jsonEncodeFloat64(buffer, "ramByteRequestAverage", a.RAMBytesRequestAverage, ",")
  219. jsonEncodeFloat64(buffer, "ramByteUsageAverage", a.RAMBytesUsageAverage, ",")
  220. jsonEncodeFloat64(buffer, "ramByteHours", a.RAMByteHours, ",")
  221. jsonEncodeFloat64(buffer, "ramCost", a.RAMCost, ",")
  222. jsonEncodeFloat64(buffer, "ramEfficiency", a.RAMEfficiency, ",")
  223. jsonEncodeFloat64(buffer, "sharedCost", a.SharedCost, ",")
  224. jsonEncodeFloat64(buffer, "totalCost", a.TotalCost, ",")
  225. jsonEncodeFloat64(buffer, "totalEfficiency", a.TotalEfficiency, "")
  226. buffer.WriteString("}")
  227. return buffer.Bytes(), nil
  228. }
  229. // TODO niko/computeallocation
  230. // func (a *Allocation)UnmarshalJSON()
  231. // Resolution returns the duration of time covered by the Allocation
  232. func (a *Allocation) Resolution() time.Duration {
  233. return a.End.Sub(a.Start)
  234. }
  235. // IsAggregated is true if the given Allocation has been aggregated, which we
  236. // define by a lack of Properties.
  237. func (a *Allocation) IsAggregated() bool {
  238. return a == nil || a.Properties == nil
  239. }
  240. // IsExternal is true if the given Allocation represents external costs.
  241. func (a *Allocation) IsExternal() bool {
  242. return strings.Contains(a.Name, ExternalSuffix)
  243. }
  244. // IsIdle is true if the given Allocation represents idle costs.
  245. func (a *Allocation) IsIdle() bool {
  246. return strings.Contains(a.Name, IdleSuffix)
  247. }
  248. // IsUnallocated is true if the given Allocation represents unallocated costs.
  249. func (a *Allocation) IsUnallocated() bool {
  250. return strings.Contains(a.Name, UnallocatedSuffix)
  251. }
  252. // Minutes returns the number of minutes the Allocation represents, as defined
  253. // by the difference between the end and start times.
  254. func (a *Allocation) Minutes() float64 {
  255. return a.End.Sub(a.Start).Minutes()
  256. }
  257. // Share works like Add, but converts the entire cost of the given Allocation
  258. // to SharedCost, rather than adding to the individual resource costs.
  259. // TODO niko/computeallocation unit test changes!!!
  260. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  261. if that == nil {
  262. return a.Clone(), nil
  263. }
  264. // Convert all costs of shared Allocation to SharedCost, zero out all
  265. // non-shared costs, then add.
  266. share := that.Clone()
  267. share.SharedCost += share.TotalCost
  268. share.TotalEfficiency = 1.0
  269. share.CPUCost = 0
  270. share.CPUCoreHours = 0
  271. share.CPUEfficiency = 0
  272. share.RAMCost = 0
  273. share.RAMByteHours = 0
  274. share.RAMEfficiency = 0
  275. share.GPUCost = 0
  276. share.GPUHours = 0
  277. share.PVCost = 0
  278. share.PVByteHours = 0
  279. share.NetworkCost = 0
  280. share.ExternalCost = 0
  281. if a == nil {
  282. return share, nil
  283. }
  284. agg := a.Clone()
  285. agg.add(that)
  286. return agg, nil
  287. }
  288. // String represents the given Allocation as a string
  289. func (a *Allocation) String() string {
  290. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost)
  291. }
  292. func (a *Allocation) add(that *Allocation) {
  293. if a == nil {
  294. log.Warningf("Allocation.AggregateBy: trying to add a nil receiver")
  295. return
  296. }
  297. aCluster, _ := a.Properties.GetCluster()
  298. thatCluster, _ := that.Properties.GetCluster()
  299. aNode, _ := a.Properties.GetNode()
  300. thatNode, _ := that.Properties.GetNode()
  301. // reset properties
  302. a.Properties = nil
  303. // ensure that we carry cluster ID and/or node over if they're the same
  304. // required for idle/shared cost allocation
  305. if aCluster == thatCluster {
  306. a.Properties = Properties{ClusterProp: aCluster}
  307. }
  308. if aNode == thatNode {
  309. if a.Properties == nil {
  310. a.Properties = Properties{NodeProp: aNode}
  311. } else {
  312. a.Properties.SetNode(aNode)
  313. }
  314. }
  315. // Expand Window, Start, and End to be the "max" of each between the two
  316. // given Allocations.
  317. a.Window = a.Window.Expand(that.Window)
  318. if that.Start.Before(a.Start) {
  319. a.Start = that.Start
  320. }
  321. if that.End.After(a.End) {
  322. a.End = that.End
  323. }
  324. // Note: efficiency numbers are computed the cost-weighted sum of each
  325. // Allocation's efficiency.
  326. // e.g. ($10 @ 25%) + ($10 @ 75%) = (2.5+7.5)/20 = 50%
  327. // e.g. ($90 @ 10%) + ($10 @ 100%) = (9.0+10.0)/100 = 19%
  328. // e.g. ($100 @ 0%) + ($100 @ 0%) = (0.0+0.0)/200 = 0%
  329. // e.g. ($10 @ 150%) + ($10 @ 50%) = (15.0+5.0)/20 = 100%
  330. // e.g. ($0 @ 100%) + ($0 @ 50%) = 0% (no div by 0)
  331. // Compute CPU efficiency (see note above for methodology)
  332. aggCPUCost := a.CPUCost + that.CPUCost
  333. if aggCPUCost > 0 {
  334. a.CPUEfficiency = (a.CPUEfficiency*a.CPUCost + that.CPUEfficiency*that.CPUCost) / aggCPUCost
  335. } else {
  336. a.CPUEfficiency = 0.0
  337. }
  338. // Compute RAM efficiency (see note above for methodology)
  339. aggRAMCost := a.RAMCost + that.RAMCost
  340. if aggRAMCost > 0 {
  341. a.RAMEfficiency = (a.RAMEfficiency*a.RAMCost + that.RAMEfficiency*that.RAMCost) / aggRAMCost
  342. } else {
  343. a.RAMEfficiency = 0.0
  344. }
  345. // Compute total efficiency (see note above for methodology)
  346. aggTotalCost := a.TotalCost + that.TotalCost
  347. if aggTotalCost > 0 {
  348. a.TotalEfficiency = (a.TotalEfficiency*a.TotalCost + that.TotalEfficiency*that.TotalCost) / aggTotalCost
  349. } else {
  350. aggTotalCost = 0.0
  351. }
  352. // Sum all cumulative resource fields
  353. a.CPUCoreHours += that.CPUCoreHours
  354. a.GPUHours += that.GPUHours
  355. a.RAMByteHours += that.RAMByteHours
  356. a.PVByteHours += that.PVByteHours
  357. // Sum all cumulative cost fields
  358. a.CPUCost += that.CPUCost
  359. a.GPUCost += that.GPUCost
  360. a.RAMCost += that.RAMCost
  361. a.PVCost += that.PVCost
  362. a.NetworkCost += that.NetworkCost
  363. a.SharedCost += that.SharedCost
  364. a.ExternalCost += that.ExternalCost
  365. a.TotalCost += that.TotalCost
  366. }
  367. // AllocationSet stores a set of Allocations, each with a unique name, that share
  368. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  369. type AllocationSet struct {
  370. sync.RWMutex
  371. allocations map[string]*Allocation
  372. externalKeys map[string]bool
  373. idleKeys map[string]bool
  374. Window Window
  375. Warnings []string
  376. Errors []string
  377. }
  378. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  379. // the given list of Allocations
  380. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  381. as := &AllocationSet{
  382. allocations: map[string]*Allocation{},
  383. externalKeys: map[string]bool{},
  384. idleKeys: map[string]bool{},
  385. Window: NewWindow(&start, &end),
  386. }
  387. for _, a := range allocs {
  388. as.Insert(a)
  389. }
  390. return as
  391. }
  392. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  393. // filtering results and sharing allocations. FilterFuncs are a list of match
  394. // functions such that, if any function fails, the allocation is ignored.
  395. // ShareFuncs are a list of match functions such that, if any function
  396. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  397. // simple flag for sharing idle resources.
  398. type AllocationAggregationOptions struct {
  399. FilterFuncs []AllocationMatchFunc
  400. SplitIdle bool
  401. MergeUnallocated bool
  402. ShareFuncs []AllocationMatchFunc
  403. ShareIdle string
  404. ShareSplit string
  405. SharedHourlyCosts map[string]float64
  406. }
  407. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  408. // Property. This will only be legal if the AllocationSet is divisible by the
  409. // given Property; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  410. func (as *AllocationSet) AggregateBy(properties Properties, options *AllocationAggregationOptions) error {
  411. // The order of operations for aggregating allocations is as follows:
  412. // 1. Partition external, idle, and shared allocations into separate sets
  413. // 2. Compute idle coefficients (if necessary)
  414. // a) if idle allocation is to be shared, compute idle coefficients
  415. // (do not compute shared coefficients here, see step 5)
  416. // b) if idle allocation is NOT shared, but filters are present, compute
  417. // idle filtration coefficients for the purpose of only returning the
  418. // portion of idle allocation that would have been shared with the
  419. // unfiltered results set. (See unit tests 5.a,b,c)
  420. // 3. Ignore allocation if it fails any of the FilterFuncs
  421. // 4. Distribute idle allocations among remaining non-idle, non-external
  422. // allocations
  423. // 5. Generate aggregation key and insert allocation into the output set
  424. // 6. Scale un-aggregated idle coefficients by filtration coefficient
  425. // 7. If there are shared allocations, compute sharing coefficients on
  426. // the aggregated set, then share allocation accordingly
  427. // 8. If there are external allocations that can be aggregated into
  428. // the output (i.e. they can be used to generate a valid key for
  429. // the given properties) then aggregate; otherwise... ignore them?
  430. // 9. If the merge idle option is enabled, merge any remaining idle
  431. // allocations into a single idle allocation
  432. // TODO niko/etl revisit (ShareIdle: ShareEven) case, which is probably wrong
  433. // (and, frankly, ill-defined; i.e. evenly across clusters? within clusters?)
  434. if options == nil {
  435. options = &AllocationAggregationOptions{}
  436. }
  437. if as.IsEmpty() {
  438. return nil
  439. }
  440. // aggSet will collect the aggregated allocations
  441. aggSet := &AllocationSet{
  442. Window: as.Window.Clone(),
  443. }
  444. // externalSet will collect external allocations
  445. externalSet := &AllocationSet{
  446. Window: as.Window.Clone(),
  447. }
  448. // idleSet will be shared among aggSet after initial aggregation
  449. // is complete
  450. idleSet := &AllocationSet{
  451. Window: as.Window.Clone(),
  452. }
  453. // shareSet will be shared among aggSet after initial aggregation
  454. // is complete
  455. shareSet := &AllocationSet{
  456. Window: as.Window.Clone(),
  457. }
  458. // Convert SharedHourlyCosts to Allocations in the shareSet
  459. for name, cost := range options.SharedHourlyCosts {
  460. if cost > 0.0 {
  461. hours := as.Resolution().Hours()
  462. // If set ends in the future, adjust hours accordingly
  463. diff := time.Now().Sub(as.End())
  464. if diff < 0.0 {
  465. hours += diff.Hours()
  466. }
  467. totalSharedCost := cost * hours
  468. shareSet.Insert(&Allocation{
  469. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  470. Start: as.Start(),
  471. End: as.End(),
  472. SharedCost: totalSharedCost,
  473. TotalCost: totalSharedCost,
  474. })
  475. }
  476. }
  477. as.Lock()
  478. defer as.Unlock()
  479. // (1) Loop and find all of the external, idle, and shared allocations. Add
  480. // them to their respective sets, removing them from the set of allocations
  481. // to aggregate.
  482. for _, alloc := range as.allocations {
  483. // External allocations get aggregated post-hoc (see step 6) and do
  484. // not necessarily contain complete sets of properties, so they are
  485. // moved to a separate AllocationSet.
  486. if alloc.IsExternal() {
  487. delete(as.externalKeys, alloc.Name)
  488. delete(as.allocations, alloc.Name)
  489. externalSet.Insert(alloc)
  490. continue
  491. }
  492. cluster, err := alloc.Properties.GetCluster()
  493. if err != nil {
  494. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  495. return err
  496. }
  497. // Idle allocations should be separated into idleSet if they are to be
  498. // shared later on. If they are not to be shared, then aggregate them.
  499. if alloc.IsIdle() {
  500. delete(as.idleKeys, alloc.Name)
  501. delete(as.allocations, alloc.Name)
  502. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  503. idleSet.Insert(alloc)
  504. } else {
  505. aggSet.Insert(alloc)
  506. }
  507. continue
  508. }
  509. // Shared allocations must be identified and separated prior to
  510. // aggregation and filtering. That is, if any of the ShareFuncs
  511. // return true, then move the allocation to shareSet.
  512. for _, sf := range options.ShareFuncs {
  513. if sf(alloc) {
  514. delete(as.idleKeys, alloc.Name)
  515. delete(as.allocations, alloc.Name)
  516. alloc.Name = fmt.Sprintf("%s/%s", cluster, SharedSuffix)
  517. shareSet.Insert(alloc)
  518. break
  519. }
  520. }
  521. }
  522. // It's possible that no more un-shared, non-idle, non-external allocations
  523. // remain at this point. This always results in an emptySet.
  524. if len(as.allocations) == 0 {
  525. log.Warningf("ETL: AggregateBy: no allocations to aggregate")
  526. emptySet := &AllocationSet{
  527. Window: as.Window.Clone(),
  528. }
  529. as.allocations = emptySet.allocations
  530. return nil
  531. }
  532. // (2) In order to correctly apply idle and shared resource coefficients
  533. // appropriately, we need to determine the coefficients for the full set
  534. // of data. The ensures that the ratios are maintained through filtering.
  535. // idleCoefficients are organized by [cluster][allocation][resource]=coeff
  536. var idleCoefficients map[string]map[string]map[string]float64
  537. // shareCoefficients are organized by [allocation][resource]=coeff (no cluster)
  538. var shareCoefficients map[string]float64
  539. var err error
  540. // (2a) If there are idle costs and we intend to share them, compute the
  541. // coefficients for sharing the cost among the non-idle, non-aggregated
  542. // allocations.
  543. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  544. idleCoefficients, err = computeIdleCoeffs(properties, options, as)
  545. if err != nil {
  546. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  547. return fmt.Errorf("error computing idle coefficients: %s", err)
  548. }
  549. }
  550. // (2b) If we're not sharing idle and we're filtering, we need to track the
  551. // amount of each idle allocation to "delete" in order to maintain parity
  552. // with the idle-allocated results. That is, we want to return only the
  553. // idle cost that would have been shared with the unfiltered portion of
  554. // the results, not the full idle cost.
  555. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  556. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  557. idleFiltrationCoefficients, err = computeIdleCoeffs(properties, options, as)
  558. if err != nil {
  559. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  560. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  561. }
  562. }
  563. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  564. for _, alloc := range as.allocations {
  565. cluster, err := alloc.Properties.GetCluster()
  566. if err != nil {
  567. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  568. return err
  569. }
  570. skip := false
  571. // (3) If any of the filter funcs fail, immediately skip the allocation.
  572. for _, ff := range options.FilterFuncs {
  573. if !ff(alloc) {
  574. skip = true
  575. break
  576. }
  577. }
  578. if skip {
  579. // If we are tracking idle filtration coefficients, delete the
  580. // entry corresponding to the filtered allocation. (Deleting the
  581. // entry will result in that proportional amount being removed
  582. // from the idle allocation at the end of the process.)
  583. if idleFiltrationCoefficients != nil {
  584. if ifcc, ok := idleFiltrationCoefficients[cluster]; ok {
  585. delete(ifcc, alloc.Name)
  586. }
  587. }
  588. continue
  589. }
  590. // (4) Split idle allocations and distribute among remaining
  591. // un-aggregated allocations.
  592. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  593. // all idle allocations will be in the aggSet at this point, so idleSet
  594. // will be empty and we won't enter this block.
  595. if idleSet.Length() > 0 {
  596. // Distribute idle allocations by coefficient per-cluster, per-allocation
  597. for _, idleAlloc := range idleSet.allocations {
  598. // Only share idle if the cluster matches; i.e. the allocation
  599. // is from the same cluster as the idle costs
  600. idleCluster, err := idleAlloc.Properties.GetCluster()
  601. if err != nil {
  602. return err
  603. }
  604. if idleCluster != cluster {
  605. continue
  606. }
  607. // Make sure idle coefficients exist
  608. if _, ok := idleCoefficients[cluster]; !ok {
  609. log.Errorf("ETL: share (idle) allocation: error getting allocation coefficient [no cluster: '%s' in coefficients] for '%s'", cluster, alloc.Name)
  610. continue
  611. }
  612. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  613. log.Errorf("ETL: share (idle) allocation: error getting allocation coefficienct for '%s'", alloc.Name)
  614. continue
  615. }
  616. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  617. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  618. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  619. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  620. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  621. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  622. alloc.CPUCost += idleCPUCost
  623. alloc.GPUCost += idleGPUCost
  624. alloc.RAMCost += idleRAMCost
  625. alloc.TotalCost += idleCPUCost + idleGPUCost + idleRAMCost
  626. }
  627. }
  628. // (5) generate key to use for aggregation-by-key and allocation name
  629. key, err := alloc.generateKey(properties)
  630. if err != nil {
  631. return err
  632. }
  633. alloc.Name = key
  634. if options.MergeUnallocated && alloc.IsUnallocated() {
  635. alloc.Name = UnallocatedSuffix
  636. }
  637. // Inserting the allocation with the generated key for a name will
  638. // perform the actual basic aggregation step.
  639. aggSet.Insert(alloc)
  640. }
  641. // clusterIdleFiltrationCoeffs is used to track per-resource idle
  642. // coefficients on a cluster-by-cluster basis. It is, essentailly, an
  643. // aggregation of idleFiltrationCoefficients after they have been
  644. // filtered above (in step 3)
  645. var clusterIdleFiltrationCoeffs map[string]map[string]float64
  646. if idleFiltrationCoefficients != nil {
  647. clusterIdleFiltrationCoeffs = map[string]map[string]float64{}
  648. for cluster, m := range idleFiltrationCoefficients {
  649. if _, ok := clusterIdleFiltrationCoeffs[cluster]; !ok {
  650. clusterIdleFiltrationCoeffs[cluster] = map[string]float64{
  651. "cpu": 0.0,
  652. "gpu": 0.0,
  653. "ram": 0.0,
  654. }
  655. }
  656. for _, n := range m {
  657. for resource, val := range n {
  658. clusterIdleFiltrationCoeffs[cluster][resource] += val
  659. }
  660. }
  661. }
  662. }
  663. // (6) If we have both un-shared idle allocations and idle filtration
  664. // coefficients (i.e. we have computed coefficients for scaling idle
  665. // allocation costs by cluster) then use those coefficients to scale down
  666. // each idle allocation.
  667. if len(aggSet.idleKeys) > 0 && clusterIdleFiltrationCoeffs != nil {
  668. for idleKey := range aggSet.idleKeys {
  669. idleAlloc := aggSet.Get(idleKey)
  670. cluster, err := idleAlloc.Properties.GetCluster()
  671. if err != nil {
  672. log.Warningf("AggregateBy: idle allocation without cluster: %s", idleAlloc)
  673. }
  674. if resourceCoeffs, ok := clusterIdleFiltrationCoeffs[cluster]; ok {
  675. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  676. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  677. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  678. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  679. idleAlloc.TotalCost = idleAlloc.CPUCost + idleAlloc.RAMCost
  680. }
  681. }
  682. }
  683. // (7) Split shared allocations and distribute among aggregated allocations
  684. if shareSet.Length() > 0 {
  685. shareCoefficients, err = computeShareCoeffs(properties, options, aggSet)
  686. if err != nil {
  687. log.Warningf("AllocationSet.AggregateBy: compute shared coeff: missing cluster ID: %s", err)
  688. return err
  689. }
  690. for _, alloc := range aggSet.allocations {
  691. if alloc.IsIdle() {
  692. // Skip idle allocations (they do not receive shared allocation)
  693. continue
  694. }
  695. // Distribute shared allocations by coefficient per-allocation
  696. // NOTE: share coefficients do not partition by cluster, like
  697. // idle coefficients do.
  698. for _, sharedAlloc := range shareSet.allocations {
  699. if _, ok := shareCoefficients[alloc.Name]; !ok {
  700. log.Errorf("ETL: share allocation: error getting allocation coefficienct for '%s'", alloc.Name)
  701. continue
  702. }
  703. alloc.SharedCost += sharedAlloc.TotalCost * shareCoefficients[alloc.Name]
  704. alloc.TotalCost += sharedAlloc.TotalCost * shareCoefficients[alloc.Name]
  705. }
  706. }
  707. }
  708. // (8) Aggregate external allocations into aggregated allocations. This may
  709. // not be possible for every external allocation, but attempt to find an
  710. // exact key match, given each external allocation's proerties, and
  711. // aggregate if an exact match is found.
  712. for _, alloc := range externalSet.allocations {
  713. key, err := alloc.generateKey(properties)
  714. if err != nil {
  715. continue
  716. }
  717. alloc.Name = key
  718. aggSet.Insert(alloc)
  719. }
  720. // (9) Combine all idle allocations into a single "__idle__" allocation
  721. if !options.SplitIdle {
  722. for _, idleAlloc := range aggSet.IdleAllocations() {
  723. aggSet.Delete(idleAlloc.Name)
  724. idleAlloc.Name = IdleSuffix
  725. aggSet.Insert(idleAlloc)
  726. }
  727. }
  728. as.allocations = aggSet.allocations
  729. return nil
  730. }
  731. // TODO niko/etl deprecate the use of a map of resources here, we only use totals
  732. func computeShareCoeffs(properties Properties, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  733. // Compute coeffs by totalling per-allocation, then dividing by the total.
  734. coeffs := map[string]float64{}
  735. // Compute totals for all allocations
  736. total := 0.0
  737. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  738. // counts each aggregation proportionally to its respective costs
  739. shareType := options.ShareSplit
  740. // Record allocation values first, then normalize by totals to get percentages
  741. for name, alloc := range as.allocations {
  742. if alloc.IsIdle() {
  743. // Skip idle allocations in coefficient calculation
  744. continue
  745. }
  746. if shareType == ShareEven {
  747. // Not additive - set to 1.0 for even distribution
  748. coeffs[name] = 1.0
  749. // Total is always additive
  750. total += 1.0
  751. } else {
  752. // Both are additive for weighted distribution
  753. coeffs[name] += alloc.TotalCost
  754. total += alloc.TotalCost
  755. }
  756. }
  757. // Normalize coefficients by totals
  758. for a := range coeffs {
  759. if coeffs[a] > 0 && total > 0 {
  760. coeffs[a] /= total
  761. } else {
  762. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  763. coeffs[a] = 0.0
  764. }
  765. }
  766. return coeffs, nil
  767. }
  768. func computeIdleCoeffs(properties Properties, options *AllocationAggregationOptions, as *AllocationSet) (map[string]map[string]map[string]float64, error) {
  769. types := []string{"cpu", "gpu", "ram"}
  770. // Compute idle coefficients, then save them in AllocationAggregationOptions
  771. coeffs := map[string]map[string]map[string]float64{}
  772. // Compute totals per resource for CPU, GPU, RAM, and PV
  773. totals := map[string]map[string]float64{}
  774. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  775. // counts each allocation proportionally to its respective costs
  776. shareType := options.ShareIdle
  777. // Record allocation values first, then normalize by totals to get percentages
  778. for _, alloc := range as.allocations {
  779. if alloc.IsIdle() {
  780. // Skip idle allocations in coefficient calculation
  781. continue
  782. }
  783. // If any of the share funcs succeed, share the allocation. Do this
  784. // prior to filtering so that shared namespaces, etc do not get
  785. // filtered out before we have a chance to share them.
  786. skip := false
  787. for _, sf := range options.ShareFuncs {
  788. if sf(alloc) {
  789. skip = true
  790. break
  791. }
  792. }
  793. if skip {
  794. continue
  795. }
  796. // We need to key the allocations by cluster id
  797. clusterID, err := alloc.Properties.GetCluster()
  798. if err != nil {
  799. return nil, err
  800. }
  801. // get the name key for the allocation
  802. name := alloc.Name
  803. // Create cluster based tables if they don't exist
  804. if _, ok := coeffs[clusterID]; !ok {
  805. coeffs[clusterID] = map[string]map[string]float64{}
  806. }
  807. if _, ok := totals[clusterID]; !ok {
  808. totals[clusterID] = map[string]float64{}
  809. }
  810. if _, ok := coeffs[clusterID][name]; !ok {
  811. coeffs[clusterID][name] = map[string]float64{}
  812. }
  813. if shareType == ShareEven {
  814. for _, r := range types {
  815. // Not additive - hard set to 1.0
  816. coeffs[clusterID][name][r] = 1.0
  817. // totals are additive
  818. totals[clusterID][r] += 1.0
  819. }
  820. } else {
  821. coeffs[clusterID][name]["cpu"] += alloc.CPUCost
  822. coeffs[clusterID][name]["gpu"] += alloc.GPUCost
  823. coeffs[clusterID][name]["ram"] += alloc.RAMCost
  824. totals[clusterID]["cpu"] += alloc.CPUCost
  825. totals[clusterID]["gpu"] += alloc.GPUCost
  826. totals[clusterID]["ram"] += alloc.RAMCost
  827. }
  828. }
  829. // Normalize coefficients by totals
  830. for c := range coeffs {
  831. for a := range coeffs[c] {
  832. for _, r := range types {
  833. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  834. coeffs[c][a][r] /= totals[c][r]
  835. }
  836. }
  837. }
  838. }
  839. return coeffs, nil
  840. }
  841. func (alloc *Allocation) generateKey(properties Properties) (string, error) {
  842. // Names will ultimately be joined into a single name, which uniquely
  843. // identifies allocations.
  844. names := []string{}
  845. if properties.HasCluster() {
  846. cluster, err := alloc.Properties.GetCluster()
  847. if err != nil {
  848. return "", err
  849. }
  850. names = append(names, cluster)
  851. }
  852. if properties.HasNode() {
  853. node, err := alloc.Properties.GetNode()
  854. if err != nil {
  855. return "", err
  856. }
  857. names = append(names, node)
  858. }
  859. if properties.HasNamespace() {
  860. namespace, err := alloc.Properties.GetNamespace()
  861. if err != nil {
  862. return "", err
  863. }
  864. names = append(names, namespace)
  865. }
  866. if properties.HasControllerKind() {
  867. controllerKind, err := alloc.Properties.GetControllerKind()
  868. if err != nil {
  869. // Indicate that allocation has no controller
  870. controllerKind = UnallocatedSuffix
  871. }
  872. if prop, _ := properties.GetControllerKind(); prop != "" && prop != controllerKind {
  873. // The allocation does not have the specified controller kind
  874. controllerKind = UnallocatedSuffix
  875. }
  876. names = append(names, controllerKind)
  877. }
  878. if properties.HasController() {
  879. if !properties.HasControllerKind() {
  880. controllerKind, err := alloc.Properties.GetControllerKind()
  881. if err == nil {
  882. names = append(names, controllerKind)
  883. }
  884. }
  885. controller, err := alloc.Properties.GetController()
  886. if err != nil {
  887. // Indicate that allocation has no controller
  888. controller = UnallocatedSuffix
  889. }
  890. names = append(names, controller)
  891. }
  892. if properties.HasPod() {
  893. pod, err := alloc.Properties.GetPod()
  894. if err != nil {
  895. return "", err
  896. }
  897. names = append(names, pod)
  898. }
  899. if properties.HasContainer() {
  900. container, err := alloc.Properties.GetContainer()
  901. if err != nil {
  902. return "", err
  903. }
  904. names = append(names, container)
  905. }
  906. if properties.HasService() {
  907. services, err := alloc.Properties.GetServices()
  908. if err != nil {
  909. // Indicate that allocation has no services
  910. names = append(names, UnallocatedSuffix)
  911. } else {
  912. // TODO niko/etl support multi-service aggregation
  913. if len(services) > 0 {
  914. for _, service := range services {
  915. names = append(names, service)
  916. break
  917. }
  918. } else {
  919. // Indicate that allocation has no services
  920. names = append(names, UnallocatedSuffix)
  921. }
  922. }
  923. }
  924. if properties.HasAnnotations() {
  925. annotations, err := alloc.Properties.GetAnnotations() // annotations that the individual allocation possesses
  926. if err != nil {
  927. // Indicate that allocation has no annotations
  928. names = append(names, UnallocatedSuffix)
  929. } else {
  930. annotationNames := []string{}
  931. aggAnnotations, err := properties.GetAnnotations() // potential annotations to aggregate on supplied by the API caller
  932. if err != nil {
  933. // We've already checked HasAnnotation, so this should never occur
  934. return "", err
  935. }
  936. // calvin - support multi-annotation aggregation
  937. for annotationName := range aggAnnotations {
  938. if val, ok := annotations[annotationName]; ok {
  939. annotationNames = append(annotationNames, fmt.Sprintf("%s=%s", annotationName, val))
  940. } else if indexOf(UnallocatedSuffix, annotationNames) == -1 { // if UnallocatedSuffix not already in names
  941. annotationNames = append(annotationNames, UnallocatedSuffix)
  942. }
  943. }
  944. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  945. if len(annotationNames) > 1 {
  946. sort.Strings(annotationNames)
  947. }
  948. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, annotationNames)
  949. // suffix should be at index 0 if it exists b/c of underscores
  950. if unallocatedSuffixIndex != -1 {
  951. annotationNames = append(annotationNames[:unallocatedSuffixIndex], annotationNames[unallocatedSuffixIndex+1:]...)
  952. annotationNames = append(annotationNames, UnallocatedSuffix) // append to end
  953. }
  954. names = append(names, annotationNames...)
  955. }
  956. }
  957. if properties.HasLabel() {
  958. labels, err := alloc.Properties.GetLabels() // labels that the individual allocation possesses
  959. if err != nil {
  960. // Indicate that allocation has no labels
  961. names = append(names, UnallocatedSuffix)
  962. } else {
  963. labelNames := []string{}
  964. aggLabels, err := properties.GetLabels() // potential labels to aggregate on supplied by the API caller
  965. if err != nil {
  966. // We've already checked HasLabel, so this should never occur
  967. return "", err
  968. }
  969. // calvin - support multi-label aggregation
  970. for labelName := range aggLabels {
  971. if val, ok := labels[labelName]; ok {
  972. labelNames = append(labelNames, fmt.Sprintf("%s=%s", labelName, val))
  973. } else if indexOf(UnallocatedSuffix, labelNames) == -1 { // if UnallocatedSuffix not already in names
  974. labelNames = append(labelNames, UnallocatedSuffix)
  975. }
  976. }
  977. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  978. if len(labelNames) > 1 {
  979. sort.Strings(labelNames)
  980. }
  981. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, labelNames)
  982. // suffix should be at index 0 if it exists b/c of underscores
  983. if unallocatedSuffixIndex != -1 {
  984. labelNames = append(labelNames[:unallocatedSuffixIndex], labelNames[unallocatedSuffixIndex+1:]...)
  985. labelNames = append(labelNames, UnallocatedSuffix) // append to end
  986. }
  987. names = append(names, labelNames...)
  988. }
  989. }
  990. return strings.Join(names, "/"), nil
  991. }
  992. // TODO clean up
  993. // Helper function to check for slice membership. Not sure if repeated elsewhere in our codebase.
  994. func indexOf(v string, arr []string) int {
  995. for i, s := range arr {
  996. // This is caseless equivalence
  997. if strings.EqualFold(v, s) {
  998. return i
  999. }
  1000. }
  1001. return -1
  1002. }
  1003. // Clone returns a new AllocationSet with a deep copy of the given
  1004. // AllocationSet's allocations.
  1005. func (as *AllocationSet) Clone() *AllocationSet {
  1006. if as == nil {
  1007. return nil
  1008. }
  1009. as.RLock()
  1010. defer as.RUnlock()
  1011. allocs := map[string]*Allocation{}
  1012. for k, v := range as.allocations {
  1013. allocs[k] = v.Clone()
  1014. }
  1015. externalKeys := map[string]bool{}
  1016. for k, v := range as.externalKeys {
  1017. externalKeys[k] = v
  1018. }
  1019. idleKeys := map[string]bool{}
  1020. for k, v := range as.idleKeys {
  1021. idleKeys[k] = v
  1022. }
  1023. return &AllocationSet{
  1024. allocations: allocs,
  1025. externalKeys: externalKeys,
  1026. idleKeys: idleKeys,
  1027. Window: as.Window.Clone(),
  1028. }
  1029. }
  1030. // ComputeIdleAllocations computes the idle allocations for the AllocationSet,
  1031. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1032. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1033. // considered for idle allocation. If the Nodes have adjustments, then apply
  1034. // the adjustments proportionally to each of the resources so that total
  1035. // allocation with idle reflects the adjusted node costs. One idle allocation
  1036. // per-cluster will be computed and returned, keyed by cluster_id.
  1037. func (as *AllocationSet) ComputeIdleAllocations(assetSet *AssetSet) (map[string]*Allocation, error) {
  1038. if as == nil {
  1039. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1040. }
  1041. if assetSet == nil {
  1042. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1043. }
  1044. if !as.Window.Equal(assetSet.Window) {
  1045. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1046. }
  1047. window := as.Window
  1048. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1049. // cluster-to-{cpu|gpu|ram}-to-cost.
  1050. assetClusterResourceCosts := map[string]map[string]float64{}
  1051. assetSet.Each(func(key string, a Asset) {
  1052. if node, ok := a.(*Node); ok {
  1053. if _, ok := assetClusterResourceCosts[node.Properties().Cluster]; !ok {
  1054. assetClusterResourceCosts[node.Properties().Cluster] = map[string]float64{}
  1055. }
  1056. // adjustmentRate is used to scale resource costs proportionally
  1057. // by the adjustment. This is necessary because we only get one
  1058. // adjustment per Node, not one per-resource-per-Node.
  1059. //
  1060. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1061. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1062. // e.g. total cost = $150, adjustment = $50 => 1.5
  1063. adjustmentRate := 1.0
  1064. if node.TotalCost()-node.Adjustment() == 0 {
  1065. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1066. // the entire node cost and we should make everything 0
  1067. // without dividing by 0.
  1068. adjustmentRate = 0.0
  1069. } else if node.Adjustment() != 0.0 {
  1070. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1071. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1072. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1073. }
  1074. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1075. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1076. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1077. assetClusterResourceCosts[node.Properties().Cluster]["cpu"] += cpuCost
  1078. assetClusterResourceCosts[node.Properties().Cluster]["gpu"] += gpuCost
  1079. assetClusterResourceCosts[node.Properties().Cluster]["ram"] += ramCost
  1080. }
  1081. })
  1082. // Determine start, end on a per-cluster basis
  1083. clusterStarts := map[string]time.Time{}
  1084. clusterEnds := map[string]time.Time{}
  1085. // Subtract allocated costs from asset costs, leaving only the remaining
  1086. // idle costs.
  1087. as.Each(func(name string, a *Allocation) {
  1088. cluster, err := a.Properties.GetCluster()
  1089. if err != nil {
  1090. // Failed to find allocation's cluster
  1091. return
  1092. }
  1093. if _, ok := assetClusterResourceCosts[cluster]; !ok {
  1094. // Failed to find assets for allocation's cluster
  1095. return
  1096. }
  1097. // Set cluster (start, end) if they are either not currently set,
  1098. // or if the detected (start, end) of the current allocation falls
  1099. // before or after, respectively, the current values.
  1100. if s, ok := clusterStarts[cluster]; !ok || a.Start.Before(s) {
  1101. clusterStarts[cluster] = a.Start
  1102. }
  1103. if e, ok := clusterEnds[cluster]; !ok || a.End.Before(e) {
  1104. clusterEnds[cluster] = a.End
  1105. }
  1106. assetClusterResourceCosts[cluster]["cpu"] -= a.CPUCost
  1107. assetClusterResourceCosts[cluster]["gpu"] -= a.GPUCost
  1108. assetClusterResourceCosts[cluster]["ram"] -= a.RAMCost
  1109. })
  1110. // Turn remaining un-allocated asset costs into idle allocations
  1111. idleAllocs := map[string]*Allocation{}
  1112. for cluster, resources := range assetClusterResourceCosts {
  1113. // Default start and end to the (start, end) of the given window, but
  1114. // use the actual, detected (start, end) pair if they are available.
  1115. start := *window.Start()
  1116. if s, ok := clusterStarts[cluster]; ok && window.Contains(s) {
  1117. start = s
  1118. }
  1119. end := *window.End()
  1120. if e, ok := clusterEnds[cluster]; ok && window.Contains(e) {
  1121. end = e
  1122. }
  1123. idleAlloc := &Allocation{
  1124. Name: fmt.Sprintf("%s/%s", cluster, IdleSuffix),
  1125. Window: window.Clone(),
  1126. Properties: Properties{ClusterProp: cluster},
  1127. Start: start,
  1128. End: end,
  1129. CPUCost: resources["cpu"],
  1130. GPUCost: resources["gpu"],
  1131. RAMCost: resources["ram"],
  1132. }
  1133. idleAlloc.TotalCost = idleAlloc.CPUCost + idleAlloc.GPUCost + idleAlloc.RAMCost
  1134. // Do not continue if multiple idle allocations are computed for a
  1135. // single cluster.
  1136. if _, ok := idleAllocs[cluster]; ok {
  1137. return nil, fmt.Errorf("duplicate idle allocations for cluster %s", cluster)
  1138. }
  1139. idleAllocs[cluster] = idleAlloc
  1140. }
  1141. return idleAllocs, nil
  1142. }
  1143. // Delete removes the allocation with the given name from the set
  1144. func (as *AllocationSet) Delete(name string) {
  1145. if as == nil {
  1146. return
  1147. }
  1148. as.Lock()
  1149. defer as.Unlock()
  1150. delete(as.externalKeys, name)
  1151. delete(as.idleKeys, name)
  1152. delete(as.allocations, name)
  1153. }
  1154. // Each invokes the given function for each Allocation in the set
  1155. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  1156. if as == nil {
  1157. return
  1158. }
  1159. for k, a := range as.allocations {
  1160. f(k, a)
  1161. }
  1162. }
  1163. // End returns the End time of the AllocationSet window
  1164. func (as *AllocationSet) End() time.Time {
  1165. if as == nil {
  1166. log.Warningf("Allocation ETL: calling End on nil AllocationSet")
  1167. return time.Unix(0, 0)
  1168. }
  1169. if as.Window.End() == nil {
  1170. log.Warningf("Allocation ETL: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  1171. return time.Unix(0, 0)
  1172. }
  1173. return *as.Window.End()
  1174. }
  1175. // Get returns the Allocation at the given key in the AllocationSet
  1176. func (as *AllocationSet) Get(key string) *Allocation {
  1177. as.RLock()
  1178. defer as.RUnlock()
  1179. if alloc, ok := as.allocations[key]; ok {
  1180. return alloc
  1181. }
  1182. return nil
  1183. }
  1184. // ExternalAllocations returns a map of the external allocations in the set.
  1185. // Returns clones of the actual Allocations, so mutability is not a problem.
  1186. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1187. externals := map[string]*Allocation{}
  1188. if as.IsEmpty() {
  1189. return externals
  1190. }
  1191. as.RLock()
  1192. defer as.RUnlock()
  1193. for key := range as.externalKeys {
  1194. if alloc, ok := as.allocations[key]; ok {
  1195. externals[key] = alloc.Clone()
  1196. }
  1197. }
  1198. return externals
  1199. }
  1200. // ExternalCost returns the total aggregated external costs of the set
  1201. func (as *AllocationSet) ExternalCost() float64 {
  1202. if as.IsEmpty() {
  1203. return 0.0
  1204. }
  1205. as.RLock()
  1206. defer as.RUnlock()
  1207. externalCost := 0.0
  1208. for _, alloc := range as.allocations {
  1209. externalCost += alloc.ExternalCost
  1210. }
  1211. return externalCost
  1212. }
  1213. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1214. // Returns clones of the actual Allocations, so mutability is not a problem.
  1215. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1216. idles := map[string]*Allocation{}
  1217. if as.IsEmpty() {
  1218. return idles
  1219. }
  1220. as.RLock()
  1221. defer as.RUnlock()
  1222. for key := range as.idleKeys {
  1223. if alloc, ok := as.allocations[key]; ok {
  1224. idles[key] = alloc.Clone()
  1225. }
  1226. }
  1227. return idles
  1228. }
  1229. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1230. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1231. // there is no existing entry, one is created. Nil error response indicates success.
  1232. func (as *AllocationSet) Insert(that *Allocation) error {
  1233. return as.insert(that)
  1234. }
  1235. func (as *AllocationSet) insert(that *Allocation) error {
  1236. if as == nil {
  1237. return fmt.Errorf("cannot insert into nil AllocationSet")
  1238. }
  1239. as.Lock()
  1240. defer as.Unlock()
  1241. if as.allocations == nil {
  1242. as.allocations = map[string]*Allocation{}
  1243. }
  1244. if as.externalKeys == nil {
  1245. as.externalKeys = map[string]bool{}
  1246. }
  1247. if as.idleKeys == nil {
  1248. as.idleKeys = map[string]bool{}
  1249. }
  1250. // Add the given Allocation to the existing entry, if there is one;
  1251. // otherwise just set directly into allocations
  1252. if _, ok := as.allocations[that.Name]; !ok {
  1253. as.allocations[that.Name] = that
  1254. } else {
  1255. as.allocations[that.Name].add(that)
  1256. }
  1257. // If the given Allocation is an external one, record that
  1258. if that.IsExternal() {
  1259. as.externalKeys[that.Name] = true
  1260. }
  1261. // If the given Allocation is an idle one, record that
  1262. if that.IsIdle() {
  1263. as.idleKeys[that.Name] = true
  1264. }
  1265. return nil
  1266. }
  1267. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  1268. // zero allocations.
  1269. func (as *AllocationSet) IsEmpty() bool {
  1270. if as == nil || len(as.allocations) == 0 {
  1271. return true
  1272. }
  1273. as.RLock()
  1274. defer as.RUnlock()
  1275. return as.allocations == nil || len(as.allocations) == 0
  1276. }
  1277. // Length returns the number of Allocations in the set
  1278. func (as *AllocationSet) Length() int {
  1279. if as == nil {
  1280. return 0
  1281. }
  1282. as.RLock()
  1283. defer as.RUnlock()
  1284. return len(as.allocations)
  1285. }
  1286. // Map clones and returns a map of the AllocationSet's Allocations
  1287. func (as *AllocationSet) Map() map[string]*Allocation {
  1288. if as.IsEmpty() {
  1289. return map[string]*Allocation{}
  1290. }
  1291. return as.Clone().allocations
  1292. }
  1293. // MarshalJSON JSON-encodes the AllocationSet
  1294. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  1295. as.RLock()
  1296. defer as.RUnlock()
  1297. return json.Marshal(as.allocations)
  1298. }
  1299. // Resolution returns the AllocationSet's window duration
  1300. func (as *AllocationSet) Resolution() time.Duration {
  1301. return as.Window.Duration()
  1302. }
  1303. // Set uses the given Allocation to overwrite the existing entry in the
  1304. // AllocationSet under the Allocation's name.
  1305. func (as *AllocationSet) Set(alloc *Allocation) error {
  1306. if as.IsEmpty() {
  1307. as.Lock()
  1308. as.allocations = map[string]*Allocation{}
  1309. as.externalKeys = map[string]bool{}
  1310. as.idleKeys = map[string]bool{}
  1311. as.Unlock()
  1312. }
  1313. as.Lock()
  1314. defer as.Unlock()
  1315. as.allocations[alloc.Name] = alloc
  1316. // If the given Allocation is an external one, record that
  1317. if alloc.IsExternal() {
  1318. as.externalKeys[alloc.Name] = true
  1319. }
  1320. // If the given Allocation is an idle one, record that
  1321. if alloc.IsIdle() {
  1322. as.idleKeys[alloc.Name] = true
  1323. }
  1324. return nil
  1325. }
  1326. // Start returns the Start time of the AllocationSet window
  1327. func (as *AllocationSet) Start() time.Time {
  1328. if as == nil {
  1329. log.Warningf("Allocation ETL: calling Start on nil AllocationSet")
  1330. return time.Unix(0, 0)
  1331. }
  1332. if as.Window.Start() == nil {
  1333. log.Warningf("Allocation ETL: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1334. return time.Unix(0, 0)
  1335. }
  1336. return *as.Window.Start()
  1337. }
  1338. // String represents the given Allocation as a string
  1339. func (as *AllocationSet) String() string {
  1340. if as == nil {
  1341. return "<nil>"
  1342. }
  1343. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1344. as.Length(), as.Window, as.TotalCost())
  1345. }
  1346. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1347. func (as *AllocationSet) TotalCost() float64 {
  1348. if as.IsEmpty() {
  1349. return 0.0
  1350. }
  1351. as.RLock()
  1352. defer as.RUnlock()
  1353. tc := 0.0
  1354. for _, a := range as.allocations {
  1355. tc += a.TotalCost
  1356. }
  1357. return tc
  1358. }
  1359. // UTCOffset returns the AllocationSet's configured UTCOffset.
  1360. func (as *AllocationSet) UTCOffset() time.Duration {
  1361. _, zone := as.Start().Zone()
  1362. return time.Duration(zone) * time.Second
  1363. }
  1364. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1365. if as.IsEmpty() {
  1366. return that, nil
  1367. }
  1368. if that.IsEmpty() {
  1369. return as, nil
  1370. }
  1371. // TODO niko/computeallocation implement first
  1372. // if that.Window.Overlaps(as.Window) {
  1373. // return nil, fmt.Errorf("AllocationSet.accumulate: overlapping windows: %s", that.Window, as.Window)
  1374. // }
  1375. // Set start, end to min(start), max(end)
  1376. start := as.Start()
  1377. end := as.End()
  1378. if that.Start().Before(start) {
  1379. start = that.Start()
  1380. }
  1381. if that.End().After(end) {
  1382. end = that.End()
  1383. }
  1384. acc := NewAllocationSet(start, end)
  1385. as.RLock()
  1386. defer as.RUnlock()
  1387. that.RLock()
  1388. defer that.RUnlock()
  1389. for _, alloc := range as.allocations {
  1390. err := acc.insert(alloc)
  1391. if err != nil {
  1392. return nil, err
  1393. }
  1394. }
  1395. for _, alloc := range that.allocations {
  1396. err := acc.insert(alloc)
  1397. if err != nil {
  1398. return nil, err
  1399. }
  1400. }
  1401. return acc, nil
  1402. }
  1403. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  1404. // be used such that the AllocationSets held are consecutive and coherent with
  1405. // respect to using the same aggregation properties, UTC offset, and
  1406. // resolution. However these rules are not necessarily enforced, so use wisely.
  1407. type AllocationSetRange struct {
  1408. sync.RWMutex
  1409. allocations []*AllocationSet
  1410. }
  1411. // NewAllocationSetRange instantiates a new range composed of the given
  1412. // AllocationSets in the order provided.
  1413. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1414. return &AllocationSetRange{
  1415. allocations: allocs,
  1416. }
  1417. }
  1418. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1419. // AllocationSet for the entire range.
  1420. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1421. var allocSet *AllocationSet
  1422. var err error
  1423. asr.RLock()
  1424. defer asr.RUnlock()
  1425. for _, as := range asr.allocations {
  1426. allocSet, err = allocSet.accumulate(as)
  1427. if err != nil {
  1428. return nil, err
  1429. }
  1430. }
  1431. return allocSet, nil
  1432. }
  1433. // TODO niko/etl accumulate into lower-resolution chunks of the given resolution
  1434. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1435. // AggregateBy aggregates each AllocationSet in the range by the given
  1436. // properties and options.
  1437. func (asr *AllocationSetRange) AggregateBy(properties Properties, options *AllocationAggregationOptions) error {
  1438. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1439. asr.Lock()
  1440. defer asr.Unlock()
  1441. for _, as := range asr.allocations {
  1442. err := as.AggregateBy(properties, options)
  1443. if err != nil {
  1444. return err
  1445. }
  1446. aggRange.allocations = append(aggRange.allocations, as)
  1447. }
  1448. asr.allocations = aggRange.allocations
  1449. return nil
  1450. }
  1451. // Append appends the given AllocationSet to the end of the range. It does not
  1452. // validate whether or not that violates window continuity.
  1453. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1454. asr.Lock()
  1455. defer asr.Unlock()
  1456. asr.allocations = append(asr.allocations, that)
  1457. }
  1458. // Each invokes the given function for each AllocationSet in the range
  1459. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1460. if asr == nil {
  1461. return
  1462. }
  1463. for i, as := range asr.allocations {
  1464. f(i, as)
  1465. }
  1466. }
  1467. // Get retrieves the AllocationSet at the given index of the range.
  1468. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  1469. if i < 0 || i >= len(asr.allocations) {
  1470. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  1471. }
  1472. asr.RLock()
  1473. defer asr.RUnlock()
  1474. return asr.allocations[i], nil
  1475. }
  1476. // InsertRange merges the given AllocationSetRange into the receiving one by
  1477. // lining up sets with matching windows, then inserting each allocation from
  1478. // the given ASR into the respective set in the receiving ASR. If the given
  1479. // ASR contains an AllocationSet from a window that does not exist in the
  1480. // receiving ASR, then an error is returned. However, the given ASR does not
  1481. // need to cover the full range of the receiver.
  1482. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  1483. if asr == nil {
  1484. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  1485. }
  1486. // keys maps window to index in asr
  1487. keys := map[string]int{}
  1488. asr.Each(func(i int, as *AllocationSet) {
  1489. if as == nil {
  1490. return
  1491. }
  1492. keys[as.Window.String()] = i
  1493. })
  1494. // Nothing to merge, so simply return
  1495. if len(keys) == 0 {
  1496. return nil
  1497. }
  1498. var err error
  1499. that.Each(func(j int, thatAS *AllocationSet) {
  1500. if thatAS == nil || err != nil {
  1501. return
  1502. }
  1503. // Find matching AllocationSet in asr
  1504. i, ok := keys[thatAS.Window.String()]
  1505. if !ok {
  1506. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  1507. return
  1508. }
  1509. as, err := asr.Get(i)
  1510. if err != nil {
  1511. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  1512. return
  1513. }
  1514. // Insert each Allocation from the given set
  1515. thatAS.Each(func(k string, alloc *Allocation) {
  1516. err = as.Insert(alloc)
  1517. if err != nil {
  1518. err = fmt.Errorf("error inserting allocation: %s", err)
  1519. return
  1520. }
  1521. })
  1522. })
  1523. // err might be nil
  1524. return err
  1525. }
  1526. // Length returns the length of the range, which is zero if nil
  1527. func (asr *AllocationSetRange) Length() int {
  1528. if asr == nil || asr.allocations == nil {
  1529. return 0
  1530. }
  1531. asr.RLock()
  1532. defer asr.RUnlock()
  1533. return len(asr.allocations)
  1534. }
  1535. // MarshalJSON JSON-encodes the range
  1536. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  1537. asr.RLock()
  1538. asr.RUnlock()
  1539. return json.Marshal(asr.allocations)
  1540. }
  1541. // Slice copies the underlying slice of AllocationSets, maintaining order,
  1542. // and returns the copied slice.
  1543. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  1544. if asr == nil || asr.allocations == nil {
  1545. return nil
  1546. }
  1547. asr.RLock()
  1548. defer asr.RUnlock()
  1549. copy := []*AllocationSet{}
  1550. for _, as := range asr.allocations {
  1551. copy = append(copy, as.Clone())
  1552. }
  1553. return copy
  1554. }
  1555. // String represents the given AllocationSetRange as a string
  1556. func (asr *AllocationSetRange) String() string {
  1557. if asr == nil {
  1558. return "<nil>"
  1559. }
  1560. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  1561. }
  1562. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  1563. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  1564. // are sets with conflicting UTCOffsets (just returns the first).
  1565. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  1566. if asr.Length() == 0 {
  1567. return 0
  1568. }
  1569. as, err := asr.Get(0)
  1570. if err != nil {
  1571. return 0
  1572. }
  1573. return as.UTCOffset()
  1574. }
  1575. // Window returns the full window that the AllocationSetRange spans, from the
  1576. // start of the first AllocationSet to the end of the last one.
  1577. func (asr *AllocationSetRange) Window() Window {
  1578. if asr == nil || asr.Length() == 0 {
  1579. return NewWindow(nil, nil)
  1580. }
  1581. start := asr.allocations[0].Start()
  1582. end := asr.allocations[asr.Length()-1].End()
  1583. return NewWindow(&start, &end)
  1584. }