allocation.go 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297
  1. package kubecost
  2. import (
  3. "bytes"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/kubecost/cost-model/pkg/log"
  10. "github.com/kubecost/cost-model/pkg/util"
  11. "github.com/kubecost/cost-model/pkg/util/json"
  12. )
  13. // TODO Clean-up use of IsEmpty; nil checks should be separated for safety.
  14. // TODO Consider making Allocation an interface, which is fulfilled by structs
  15. // like KubernetesAllocation, IdleAllocation, and ExternalAllocation.
  16. // ExternalSuffix indicates an external allocation
  17. const ExternalSuffix = "__external__"
  18. // IdleSuffix indicates an idle allocation property
  19. const IdleSuffix = "__idle__"
  20. // SharedSuffix indicates an shared allocation property
  21. const SharedSuffix = "__shared__"
  22. // UnallocatedSuffix indicates an unallocated allocation property
  23. const UnallocatedSuffix = "__unallocated__"
  24. // UnmountedSuffix indicated allocation to an unmounted PV
  25. const UnmountedSuffix = "__unmounted__"
  26. // ShareWeighted indicates that a shared resource should be shared as a
  27. // proportion of the cost of the remaining allocations.
  28. const ShareWeighted = "__weighted__"
  29. // ShareEven indicates that a shared resource should be shared evenly across
  30. // all remaining allocations.
  31. const ShareEven = "__even__"
  32. // ShareNone indicates that a shareable resource should not be shared
  33. const ShareNone = "__none__"
  34. // Allocation is a unit of resource allocation and cost for a given window
  35. // of time and for a given kubernetes construct with its associated set of
  36. // properties.
  37. // TODO:CLEANUP consider dropping name in favor of just Allocation and an
  38. // Assets-style key() function for AllocationSet.
  39. type Allocation struct {
  40. Name string `json:"name"`
  41. Properties *AllocationProperties `json:"properties,omitempty"`
  42. Window Window `json:"window"`
  43. Start time.Time `json:"start"`
  44. End time.Time `json:"end"`
  45. CPUCoreHours float64 `json:"cpuCoreHours"`
  46. CPUCoreRequestAverage float64 `json:"cpuCoreRequestAverage"`
  47. CPUCoreUsageAverage float64 `json:"cpuCoreUsageAverage"`
  48. CPUCost float64 `json:"cpuCost"`
  49. CPUCostAdjustment float64 `json:"cpuCostAdjustment"`
  50. GPUHours float64 `json:"gpuHours"`
  51. GPUCost float64 `json:"gpuCost"`
  52. GPUCostAdjustment float64 `json:"gpuCostAdjustment"`
  53. NetworkCost float64 `json:"networkCost"`
  54. NetworkCostAdjustment float64 `json:"networkCostAdjustment"`
  55. LoadBalancerCost float64 `json:"loadBalancerCost"`
  56. LoadBalancerCostAdjustment float64 `json:"loadBalancerCostAdjustment"`
  57. PVs PVAllocations `json:"-"`
  58. PVCostAdjustment float64 `json:"pvCostAdjustment"`
  59. RAMByteHours float64 `json:"ramByteHours"`
  60. RAMBytesRequestAverage float64 `json:"ramByteRequestAverage"`
  61. RAMBytesUsageAverage float64 `json:"ramByteUsageAverage"`
  62. RAMCost float64 `json:"ramCost"`
  63. RAMCostAdjustment float64 `json:"ramCostAdjustment"`
  64. SharedCost float64 `json:"sharedCost"`
  65. SharedCostAdjustment float64 `json:"sharedCostAdjustment"`
  66. ExternalCost float64 `json:"externalCost"`
  67. // RawAllocationOnly is a pointer so if it is not present it will be
  68. // marshalled as null rather than as an object with Go default values.
  69. RawAllocationOnly *RawAllocationOnlyData `json:"rawAllocationOnly"`
  70. }
  71. // RawAllocationOnlyData is information that only belong in "raw" Allocations,
  72. // those which have not undergone aggregation, accumulation, or any other form
  73. // of combination to produce a new Allocation from other Allocations.
  74. //
  75. // Max usage data belongs here because computing the overall maximum from two
  76. // or more Allocations is a non-trivial operation that cannot be defined without
  77. // maintaining a large amount of state. Consider the following example:
  78. // _______________________________________________
  79. //
  80. // A1 Using 3 CPU ---- ----- ------
  81. // A2 Using 2 CPU ---- ----- ----
  82. // A3 Using 1 CPU --- --
  83. // _______________________________________________
  84. // Time ---->
  85. //
  86. // The logical maximum CPU usage is 5, but this cannot be calculated iteratively,
  87. // which is how we calculate aggregations and accumulations of Allocations currently.
  88. // This becomes a problem I could call "maximum sum of overlapping intervals" and is
  89. // essentially a variant of an interval scheduling algorithm.
  90. //
  91. // If we had types to differentiate between regular Allocations and AggregatedAllocations
  92. // then this type would be unnecessary and its fields would go into the regular Allocation
  93. // and not in the AggregatedAllocation.
  94. type RawAllocationOnlyData struct {
  95. CPUCoreUsageMax float64 `json:"cpuCoreUsageMax"`
  96. RAMBytesUsageMax float64 `json:"ramByteUsageMax"`
  97. }
  98. // PVAllocations is a map of Disk Asset Identifiers to the
  99. // usage of them by an Allocation as recorded in a PVAllocation
  100. type PVAllocations map[PVKey]*PVAllocation
  101. // Clone creates a deep copy of a PVAllocations
  102. func (pv *PVAllocations) Clone() PVAllocations {
  103. if pv == nil || *pv == nil {
  104. return nil
  105. }
  106. apv := *pv
  107. clonePV := PVAllocations{}
  108. for k, v := range apv {
  109. clonePV[k] = &PVAllocation{
  110. ByteHours: v.ByteHours,
  111. Cost: v.Cost,
  112. }
  113. }
  114. return clonePV
  115. }
  116. // Add adds contents of that to the calling PVAllocations
  117. func (pv *PVAllocations) Add(that PVAllocations) PVAllocations {
  118. apv := pv.Clone()
  119. if that != nil {
  120. if apv == nil {
  121. apv = PVAllocations{}
  122. }
  123. for pvKey, thatPVAlloc := range that {
  124. apvAlloc, ok := apv[pvKey]
  125. if !ok {
  126. apvAlloc = &PVAllocation{}
  127. }
  128. apvAlloc.Cost += thatPVAlloc.Cost
  129. apvAlloc.ByteHours += thatPVAlloc.ByteHours
  130. apv[pvKey] = apvAlloc
  131. }
  132. }
  133. return apv
  134. }
  135. // PVKey for identifying Disk type assets
  136. type PVKey struct {
  137. Cluster string `json:"cluster"`
  138. Name string `json:"name"`
  139. }
  140. // PVAllocation contains the byte hour usage
  141. // and cost of an Allocation for a single PV
  142. type PVAllocation struct {
  143. ByteHours float64 `json:"byteHours"`
  144. Cost float64 `json:"cost"`
  145. }
  146. // AllocationMatchFunc is a function that can be used to match Allocations by
  147. // returning true for any given Allocation if a condition is met.
  148. type AllocationMatchFunc func(*Allocation) bool
  149. // Add returns the result of summing the two given Allocations, which sums the
  150. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  151. // the two original Allocations are mutated in the process.
  152. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  153. if a == nil {
  154. return that.Clone(), nil
  155. }
  156. if that == nil {
  157. return a.Clone(), nil
  158. }
  159. // Note: no need to clone "that", as add only mutates the receiver
  160. agg := a.Clone()
  161. agg.add(that)
  162. return agg, nil
  163. }
  164. // Clone returns a deep copy of the given Allocation
  165. func (a *Allocation) Clone() *Allocation {
  166. if a == nil {
  167. return nil
  168. }
  169. return &Allocation{
  170. Name: a.Name,
  171. Properties: a.Properties.Clone(),
  172. Window: a.Window.Clone(),
  173. Start: a.Start,
  174. End: a.End,
  175. CPUCoreHours: a.CPUCoreHours,
  176. CPUCoreRequestAverage: a.CPUCoreRequestAverage,
  177. CPUCoreUsageAverage: a.CPUCoreUsageAverage,
  178. CPUCost: a.CPUCost,
  179. CPUCostAdjustment: a.CPUCostAdjustment,
  180. GPUHours: a.GPUHours,
  181. GPUCost: a.GPUCost,
  182. GPUCostAdjustment: a.GPUCostAdjustment,
  183. NetworkCost: a.NetworkCost,
  184. NetworkCostAdjustment: a.NetworkCostAdjustment,
  185. LoadBalancerCost: a.LoadBalancerCost,
  186. LoadBalancerCostAdjustment: a.LoadBalancerCostAdjustment,
  187. PVs: a.PVs.Clone(),
  188. PVCostAdjustment: a.PVCostAdjustment,
  189. RAMByteHours: a.RAMByteHours,
  190. RAMBytesRequestAverage: a.RAMBytesRequestAverage,
  191. RAMBytesUsageAverage: a.RAMBytesUsageAverage,
  192. RAMCost: a.RAMCost,
  193. RAMCostAdjustment: a.RAMCostAdjustment,
  194. SharedCost: a.SharedCost,
  195. SharedCostAdjustment: a.SharedCostAdjustment,
  196. ExternalCost: a.ExternalCost,
  197. RawAllocationOnly: a.RawAllocationOnly.Clone(),
  198. }
  199. }
  200. // Clone returns a deep copy of the given RawAllocationOnlyData
  201. func (r *RawAllocationOnlyData) Clone() *RawAllocationOnlyData {
  202. if r == nil {
  203. return nil
  204. }
  205. return &RawAllocationOnlyData{
  206. CPUCoreUsageMax: r.CPUCoreUsageMax,
  207. RAMBytesUsageMax: r.RAMBytesUsageMax,
  208. }
  209. }
  210. // Equal returns true if the values held in the given Allocation precisely
  211. // match those of the receiving Allocation. nil does not match nil. Floating
  212. // point values need to match according to util.IsApproximately, which accounts
  213. // for small, reasonable floating point error margins.
  214. func (a *Allocation) Equal(that *Allocation) bool {
  215. if a == nil || that == nil {
  216. return false
  217. }
  218. if a.Name != that.Name {
  219. return false
  220. }
  221. if !a.Properties.Equal(that.Properties) {
  222. return false
  223. }
  224. if !a.Window.Equal(that.Window) {
  225. return false
  226. }
  227. if !a.Start.Equal(that.Start) {
  228. return false
  229. }
  230. if !a.End.Equal(that.End) {
  231. return false
  232. }
  233. if !util.IsApproximately(a.CPUCoreHours, that.CPUCoreHours) {
  234. return false
  235. }
  236. if !util.IsApproximately(a.CPUCost, that.CPUCost) {
  237. return false
  238. }
  239. if !util.IsApproximately(a.CPUCostAdjustment, that.CPUCostAdjustment) {
  240. return false
  241. }
  242. if !util.IsApproximately(a.GPUHours, that.GPUHours) {
  243. return false
  244. }
  245. if !util.IsApproximately(a.GPUCost, that.GPUCost) {
  246. return false
  247. }
  248. if !util.IsApproximately(a.GPUCostAdjustment, that.GPUCostAdjustment) {
  249. return false
  250. }
  251. if !util.IsApproximately(a.NetworkCost, that.NetworkCost) {
  252. return false
  253. }
  254. if !util.IsApproximately(a.NetworkCostAdjustment, that.NetworkCostAdjustment) {
  255. return false
  256. }
  257. if !util.IsApproximately(a.LoadBalancerCost, that.LoadBalancerCost) {
  258. return false
  259. }
  260. if !util.IsApproximately(a.LoadBalancerCostAdjustment, that.LoadBalancerCostAdjustment) {
  261. return false
  262. }
  263. if !util.IsApproximately(a.PVCostAdjustment, that.PVCostAdjustment) {
  264. return false
  265. }
  266. if !util.IsApproximately(a.RAMByteHours, that.RAMByteHours) {
  267. return false
  268. }
  269. if !util.IsApproximately(a.RAMCost, that.RAMCost) {
  270. return false
  271. }
  272. if !util.IsApproximately(a.RAMCostAdjustment, that.RAMCostAdjustment) {
  273. return false
  274. }
  275. if !util.IsApproximately(a.SharedCost, that.SharedCost) {
  276. return false
  277. }
  278. if !util.IsApproximately(a.SharedCostAdjustment, that.SharedCostAdjustment) {
  279. return false
  280. }
  281. if !util.IsApproximately(a.ExternalCost, that.ExternalCost) {
  282. return false
  283. }
  284. if a.RawAllocationOnly == nil && that.RawAllocationOnly != nil {
  285. return false
  286. }
  287. if a.RawAllocationOnly != nil && that.RawAllocationOnly == nil {
  288. return false
  289. }
  290. if a.RawAllocationOnly != nil && that.RawAllocationOnly != nil {
  291. if !util.IsApproximately(a.RawAllocationOnly.CPUCoreUsageMax, that.RawAllocationOnly.CPUCoreUsageMax) {
  292. return false
  293. }
  294. if !util.IsApproximately(a.RawAllocationOnly.RAMBytesUsageMax, that.RawAllocationOnly.RAMBytesUsageMax) {
  295. return false
  296. }
  297. }
  298. aPVs := a.PVs
  299. thatPVs := that.PVs
  300. if len(aPVs) == len(thatPVs) {
  301. for k, pv := range aPVs {
  302. tv, ok := thatPVs[k]
  303. if !ok || *tv != *pv {
  304. return false
  305. }
  306. }
  307. } else {
  308. return false
  309. }
  310. return true
  311. }
  312. // TotalCost is the total cost of the Allocation including adjustments
  313. func (a *Allocation) TotalCost() float64 {
  314. return a.CPUTotalCost() + a.GPUTotalCost() + a.RAMTotalCost() + a.PVTotalCost() + a.NetworkTotalCost() + a.LBTotalCost() + a.SharedTotalCost() + a.ExternalCost
  315. }
  316. // CPUTotalCost calculates total CPU cost of Allocation including adjustment
  317. func (a *Allocation) CPUTotalCost() float64 {
  318. return a.CPUCost + a.CPUCostAdjustment
  319. }
  320. // GPUTotalCost calculates total GPU cost of Allocation including adjustment
  321. func (a *Allocation) GPUTotalCost() float64 {
  322. return a.GPUCost + a.GPUCostAdjustment
  323. }
  324. // RAMTotalCost calculates total RAM cost of Allocation including adjustment
  325. func (a *Allocation) RAMTotalCost() float64 {
  326. return a.RAMCost + a.RAMCostAdjustment
  327. }
  328. // PVTotalCost calculates total PV cost of Allocation including adjustment
  329. func (a *Allocation) PVTotalCost() float64 {
  330. return a.PVCost() + a.PVCostAdjustment
  331. }
  332. // NetworkTotalCost calculates total Network cost of Allocation including adjustment
  333. func (a *Allocation) NetworkTotalCost() float64 {
  334. return a.NetworkCost + a.NetworkCostAdjustment
  335. }
  336. // LBTotalCost calculates total LB cost of Allocation including adjustment
  337. func (a *Allocation) LBTotalCost() float64 {
  338. return a.LoadBalancerCost + a.LoadBalancerCostAdjustment
  339. }
  340. // SharedTotalCost calculates total shared cost of Allocation including adjustment
  341. func (a *Allocation) SharedTotalCost() float64 {
  342. return a.SharedCost + a.SharedCostAdjustment
  343. }
  344. // PVCost calculate cumulative cost of all PVs that Allocation is attached to
  345. func (a *Allocation) PVCost() float64 {
  346. cost := 0.0
  347. for _, pv := range a.PVs {
  348. cost += pv.Cost
  349. }
  350. return cost
  351. }
  352. // PVByteHours calculate cumulative ByteHours of all PVs that Allocation is attached to
  353. func (a *Allocation) PVByteHours() float64 {
  354. byteHours := 0.0
  355. for _, pv := range a.PVs {
  356. byteHours += pv.ByteHours
  357. }
  358. return byteHours
  359. }
  360. // CPUEfficiency is the ratio of usage to request. If there is no request and
  361. // no usage or cost, then efficiency is zero. If there is no request, but there
  362. // is usage or cost, then efficiency is 100%.
  363. func (a *Allocation) CPUEfficiency() float64 {
  364. if a.CPUCoreRequestAverage > 0 {
  365. return a.CPUCoreUsageAverage / a.CPUCoreRequestAverage
  366. }
  367. if a.CPUCoreUsageAverage == 0.0 || a.CPUCost == 0.0 {
  368. return 0.0
  369. }
  370. return 1.0
  371. }
  372. // RAMEfficiency is the ratio of usage to request. If there is no request and
  373. // no usage or cost, then efficiency is zero. If there is no request, but there
  374. // is usage or cost, then efficiency is 100%.
  375. func (a *Allocation) RAMEfficiency() float64 {
  376. if a.RAMBytesRequestAverage > 0 {
  377. return a.RAMBytesUsageAverage / a.RAMBytesRequestAverage
  378. }
  379. if a.RAMBytesUsageAverage == 0.0 || a.RAMCost == 0.0 {
  380. return 0.0
  381. }
  382. return 1.0
  383. }
  384. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  385. // there is no cost at all, then efficiency is zero.
  386. func (a *Allocation) TotalEfficiency() float64 {
  387. if a.RAMTotalCost()+a.CPUTotalCost() > 0 {
  388. ramCostEff := a.RAMEfficiency() * a.RAMTotalCost()
  389. cpuCostEff := a.CPUEfficiency() * a.CPUTotalCost()
  390. return (ramCostEff + cpuCostEff) / (a.CPUTotalCost() + a.RAMTotalCost())
  391. }
  392. return 0.0
  393. }
  394. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  395. func (a *Allocation) CPUCores() float64 {
  396. if a.Minutes() <= 0.0 {
  397. return 0.0
  398. }
  399. return a.CPUCoreHours / (a.Minutes() / 60.0)
  400. }
  401. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  402. func (a *Allocation) RAMBytes() float64 {
  403. if a.Minutes() <= 0.0 {
  404. return 0.0
  405. }
  406. return a.RAMByteHours / (a.Minutes() / 60.0)
  407. }
  408. // GPUs converts the Allocation's GPUHours into average GPUs
  409. func (a *Allocation) GPUs() float64 {
  410. if a.Minutes() <= 0.0 {
  411. return 0.0
  412. }
  413. return a.GPUHours / (a.Minutes() / 60.0)
  414. }
  415. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  416. func (a *Allocation) PVBytes() float64 {
  417. if a.Minutes() <= 0.0 {
  418. return 0.0
  419. }
  420. return a.PVByteHours() / (a.Minutes() / 60.0)
  421. }
  422. // MarshalJSON implements json.Marshaler interface
  423. func (a *Allocation) MarshalJSON() ([]byte, error) {
  424. buffer := bytes.NewBufferString("{")
  425. jsonEncodeString(buffer, "name", a.Name, ",")
  426. jsonEncode(buffer, "properties", a.Properties, ",")
  427. jsonEncode(buffer, "window", a.Window, ",")
  428. jsonEncodeString(buffer, "start", a.Start.Format(time.RFC3339), ",")
  429. jsonEncodeString(buffer, "end", a.End.Format(time.RFC3339), ",")
  430. jsonEncodeFloat64(buffer, "minutes", a.Minutes(), ",")
  431. jsonEncodeFloat64(buffer, "cpuCores", a.CPUCores(), ",")
  432. jsonEncodeFloat64(buffer, "cpuCoreRequestAverage", a.CPUCoreRequestAverage, ",")
  433. jsonEncodeFloat64(buffer, "cpuCoreUsageAverage", a.CPUCoreUsageAverage, ",")
  434. jsonEncodeFloat64(buffer, "cpuCoreHours", a.CPUCoreHours, ",")
  435. jsonEncodeFloat64(buffer, "cpuCost", a.CPUCost, ",")
  436. jsonEncodeFloat64(buffer, "cpuCostAdjustment", a.CPUCostAdjustment, ",")
  437. jsonEncodeFloat64(buffer, "cpuEfficiency", a.CPUEfficiency(), ",")
  438. jsonEncodeFloat64(buffer, "gpuCount", a.GPUs(), ",")
  439. jsonEncodeFloat64(buffer, "gpuHours", a.GPUHours, ",")
  440. jsonEncodeFloat64(buffer, "gpuCost", a.GPUCost, ",")
  441. jsonEncodeFloat64(buffer, "gpuCostAdjustment", a.GPUCostAdjustment, ",")
  442. jsonEncodeFloat64(buffer, "networkCost", a.NetworkCost, ",")
  443. jsonEncodeFloat64(buffer, "networkCostAdjustment", a.NetworkCostAdjustment, ",")
  444. jsonEncodeFloat64(buffer, "loadBalancerCost", a.LoadBalancerCost, ",")
  445. jsonEncodeFloat64(buffer, "loadBalancerCostAdjustment", a.LoadBalancerCostAdjustment, ",")
  446. jsonEncodeFloat64(buffer, "pvBytes", a.PVBytes(), ",")
  447. jsonEncodeFloat64(buffer, "pvByteHours", a.PVByteHours(), ",")
  448. jsonEncodeFloat64(buffer, "pvCost", a.PVCost(), ",")
  449. jsonEncode(buffer, "pvs", a.PVs, ",") // Todo Sean: this does not work properly
  450. jsonEncodeFloat64(buffer, "pvCostAdjustment", a.PVCostAdjustment, ",")
  451. jsonEncodeFloat64(buffer, "ramBytes", a.RAMBytes(), ",")
  452. jsonEncodeFloat64(buffer, "ramByteRequestAverage", a.RAMBytesRequestAverage, ",")
  453. jsonEncodeFloat64(buffer, "ramByteUsageAverage", a.RAMBytesUsageAverage, ",")
  454. jsonEncodeFloat64(buffer, "ramByteHours", a.RAMByteHours, ",")
  455. jsonEncodeFloat64(buffer, "ramCost", a.RAMCost, ",")
  456. jsonEncodeFloat64(buffer, "ramCostAdjustment", a.RAMCostAdjustment, ",")
  457. jsonEncodeFloat64(buffer, "ramEfficiency", a.RAMEfficiency(), ",")
  458. jsonEncodeFloat64(buffer, "sharedCost", a.SharedCost, ",")
  459. jsonEncodeFloat64(buffer, "sharedCostAdjustment", a.SharedCostAdjustment, ",")
  460. jsonEncodeFloat64(buffer, "externalCost", a.ExternalCost, ",")
  461. jsonEncodeFloat64(buffer, "totalCost", a.TotalCost(), ",")
  462. jsonEncodeFloat64(buffer, "totalEfficiency", a.TotalEfficiency(), ",")
  463. jsonEncode(buffer, "rawAllocationOnly", a.RawAllocationOnly, "")
  464. buffer.WriteString("}")
  465. return buffer.Bytes(), nil
  466. }
  467. // Resolution returns the duration of time covered by the Allocation
  468. func (a *Allocation) Resolution() time.Duration {
  469. return a.End.Sub(a.Start)
  470. }
  471. // IsAggregated is true if the given Allocation has been aggregated, which we
  472. // define by a lack of AllocationProperties.
  473. func (a *Allocation) IsAggregated() bool {
  474. return a == nil || a.Properties == nil
  475. }
  476. // IsExternal is true if the given Allocation represents external costs.
  477. func (a *Allocation) IsExternal() bool {
  478. return strings.Contains(a.Name, ExternalSuffix)
  479. }
  480. // IsIdle is true if the given Allocation represents idle costs.
  481. func (a *Allocation) IsIdle() bool {
  482. return strings.Contains(a.Name, IdleSuffix)
  483. }
  484. // IsUnallocated is true if the given Allocation represents unallocated costs.
  485. func (a *Allocation) IsUnallocated() bool {
  486. return strings.Contains(a.Name, UnallocatedSuffix)
  487. }
  488. // Minutes returns the number of minutes the Allocation represents, as defined
  489. // by the difference between the end and start times.
  490. func (a *Allocation) Minutes() float64 {
  491. return a.End.Sub(a.Start).Minutes()
  492. }
  493. // Share adds the TotalCost of the given Allocation to the SharedCost of the
  494. // receiving Allocation. No Start, End, Window, or AllocationProperties are considered.
  495. // Neither Allocation is mutated; a new Allocation is always returned.
  496. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  497. if that == nil {
  498. return a.Clone(), nil
  499. }
  500. if a == nil {
  501. return nil, fmt.Errorf("cannot share with nil Allocation")
  502. }
  503. agg := a.Clone()
  504. agg.SharedCost += that.TotalCost()
  505. return agg, nil
  506. }
  507. // String represents the given Allocation as a string
  508. func (a *Allocation) String() string {
  509. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost())
  510. }
  511. func (a *Allocation) add(that *Allocation) {
  512. if a == nil {
  513. log.Warningf("Allocation.AggregateBy: trying to add a nil receiver")
  514. return
  515. }
  516. // Preserve string properties that are matching between the two allocations
  517. a.Properties = a.Properties.Intersection(that.Properties)
  518. // Expand the window to encompass both Allocations
  519. a.Window = a.Window.Expand(that.Window)
  520. // Sum non-cumulative fields by turning them into cumulative, adding them,
  521. // and then converting them back into averages after minutes have been
  522. // combined (just below).
  523. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  524. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  525. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  526. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  527. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  528. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  529. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  530. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  531. // Expand Start and End to be the "max" of among the given Allocations
  532. if that.Start.Before(a.Start) {
  533. a.Start = that.Start
  534. }
  535. if that.End.After(a.End) {
  536. a.End = that.End
  537. }
  538. // Convert cumulative request and usage back into rates
  539. // TODO:TEST write a unit test that fails if this is done incorrectly
  540. if a.Minutes() > 0 {
  541. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  542. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  543. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  544. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  545. } else {
  546. a.CPUCoreRequestAverage = 0.0
  547. a.CPUCoreUsageAverage = 0.0
  548. a.RAMBytesRequestAverage = 0.0
  549. a.RAMBytesUsageAverage = 0.0
  550. }
  551. // Sum all cumulative resource fields
  552. a.CPUCoreHours += that.CPUCoreHours
  553. a.GPUHours += that.GPUHours
  554. a.RAMByteHours += that.RAMByteHours
  555. // Sum all cumulative cost fields
  556. a.CPUCost += that.CPUCost
  557. a.GPUCost += that.GPUCost
  558. a.RAMCost += that.RAMCost
  559. a.NetworkCost += that.NetworkCost
  560. a.LoadBalancerCost += that.LoadBalancerCost
  561. a.SharedCost += that.SharedCost
  562. a.ExternalCost += that.ExternalCost
  563. // Sum PVAllocations
  564. a.PVs = a.PVs.Add(that.PVs)
  565. // Sum all cumulative adjustment fields
  566. a.CPUCostAdjustment += that.CPUCostAdjustment
  567. a.RAMCostAdjustment += that.RAMCostAdjustment
  568. a.GPUCostAdjustment += that.GPUCostAdjustment
  569. a.PVCostAdjustment += that.PVCostAdjustment
  570. a.NetworkCostAdjustment += that.NetworkCostAdjustment
  571. a.LoadBalancerCostAdjustment += that.LoadBalancerCostAdjustment
  572. a.SharedCostAdjustment += that.SharedCostAdjustment
  573. // Any data that is in a "raw allocation only" is not valid in any
  574. // sort of cumulative Allocation (like one that is added).
  575. a.RawAllocationOnly = nil
  576. }
  577. // AllocationSet stores a set of Allocations, each with a unique name, that share
  578. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  579. type AllocationSet struct {
  580. sync.RWMutex
  581. allocations map[string]*Allocation
  582. externalKeys map[string]bool
  583. idleKeys map[string]bool
  584. Window Window
  585. Warnings []string
  586. Errors []string
  587. }
  588. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  589. // the given list of Allocations
  590. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  591. as := &AllocationSet{
  592. allocations: map[string]*Allocation{},
  593. externalKeys: map[string]bool{},
  594. idleKeys: map[string]bool{},
  595. Window: NewWindow(&start, &end),
  596. }
  597. for _, a := range allocs {
  598. as.Insert(a)
  599. }
  600. return as
  601. }
  602. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  603. // filtering results and sharing allocations. FilterFuncs are a list of match
  604. // functions such that, if any function fails, the allocation is ignored.
  605. // ShareFuncs are a list of match functions such that, if any function
  606. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  607. // simple flag for sharing idle resources.
  608. type AllocationAggregationOptions struct {
  609. FilterFuncs []AllocationMatchFunc
  610. SplitIdle bool
  611. MergeUnallocated bool
  612. ShareFuncs []AllocationMatchFunc
  613. ShareIdle string
  614. ShareSplit string
  615. SharedHourlyCosts map[string]float64
  616. }
  617. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  618. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  619. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  620. func (as *AllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  621. // The order of operations for aggregating allocations is as follows:
  622. // 1. Partition external, idle, and shared allocations into separate sets.
  623. // Also, create the aggSet into which the results will be aggregated.
  624. // 2. Compute sharing coefficients for idle and shared resources
  625. // a) if idle allocation is to be shared, compute idle coefficients
  626. // b) if idle allocation is NOT shared, but filters are present, compute
  627. // idle filtration coefficients for the purpose of only returning the
  628. // portion of idle allocation that would have been shared with the
  629. // unfiltered results. (See unit tests 5.a,b,c)
  630. // c) generate shared allocation for then given shared overhead, which
  631. // must happen after (2a) and (2b)
  632. // d) if there are shared resources, compute share coefficients
  633. // 3. Drop any allocation that fails any of the filters
  634. // 4. Distribute idle allocations according to the idle coefficients
  635. // 5. Generate aggregation key and insert allocation into the output set
  636. // 6. If idle is shared and resources are shared, some idle might be shared
  637. // with a shared resource. Distribute that to the shared resources
  638. // prior to sharing them with the aggregated results.
  639. // 7. Apply idle filtration coefficients from step (2b)
  640. // 8. Distribute shared allocations according to the share coefficients.
  641. // 9. If there are external allocations that can be aggregated into
  642. // the output (i.e. they can be used to generate a valid key for
  643. // the given properties) then aggregate; otherwise... ignore them?
  644. // 10. If the merge idle option is enabled, merge any remaining idle
  645. // allocations into a single idle allocation
  646. if options == nil {
  647. options = &AllocationAggregationOptions{}
  648. }
  649. if as.IsEmpty() {
  650. return nil
  651. }
  652. // aggSet will collect the aggregated allocations
  653. aggSet := &AllocationSet{
  654. Window: as.Window.Clone(),
  655. }
  656. // externalSet will collect external allocations
  657. externalSet := &AllocationSet{
  658. Window: as.Window.Clone(),
  659. }
  660. // idleSet will be shared among aggSet after initial aggregation
  661. // is complete
  662. idleSet := &AllocationSet{
  663. Window: as.Window.Clone(),
  664. }
  665. // shareSet will be shared among aggSet after initial aggregation
  666. // is complete
  667. shareSet := &AllocationSet{
  668. Window: as.Window.Clone(),
  669. }
  670. as.Lock()
  671. defer as.Unlock()
  672. // (1) Loop and find all of the external, idle, and shared allocations. Add
  673. // them to their respective sets, removing them from the set of allocations
  674. // to aggregate.
  675. for _, alloc := range as.allocations {
  676. // External allocations get aggregated post-hoc (see step 6) and do
  677. // not necessarily contain complete sets of properties, so they are
  678. // moved to a separate AllocationSet.
  679. if alloc.IsExternal() {
  680. delete(as.externalKeys, alloc.Name)
  681. delete(as.allocations, alloc.Name)
  682. externalSet.Insert(alloc)
  683. continue
  684. }
  685. // Idle allocations should be separated into idleSet if they are to be
  686. // shared later on. If they are not to be shared, then add them to the
  687. // aggSet like any other allocation.
  688. if alloc.IsIdle() {
  689. delete(as.idleKeys, alloc.Name)
  690. delete(as.allocations, alloc.Name)
  691. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  692. idleSet.Insert(alloc)
  693. } else {
  694. aggSet.Insert(alloc)
  695. }
  696. continue
  697. }
  698. // Shared allocations must be identified and separated prior to
  699. // aggregation and filtering. That is, if any of the ShareFuncs return
  700. // true for the allocation, then move it to shareSet.
  701. for _, sf := range options.ShareFuncs {
  702. if sf(alloc) {
  703. delete(as.idleKeys, alloc.Name)
  704. delete(as.allocations, alloc.Name)
  705. shareSet.Insert(alloc)
  706. break
  707. }
  708. }
  709. }
  710. // It's possible that no more un-shared, non-idle, non-external allocations
  711. // remain at this point. This always results in an emptySet, so return early.
  712. if len(as.allocations) == 0 {
  713. emptySet := &AllocationSet{
  714. Window: as.Window.Clone(),
  715. }
  716. as.allocations = emptySet.allocations
  717. return nil
  718. }
  719. // (2) In order to correctly share idle and shared costs, we first compute
  720. // sharing coefficients, which represent the proportion of each cost to
  721. // share with each allocation. Idle allocations are shared per-cluster,
  722. // per-allocation, and per-resource, while shared resources are shared per-
  723. // allocation only.
  724. //
  725. // For an idleCoefficient example, the entries:
  726. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  727. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  728. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  729. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  730. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  731. // RAM costs.
  732. //
  733. // For a shareCoefficient example, the entries:
  734. // [namespace2] = 0.666667
  735. // [__filtered__] = 0.333333
  736. // mean that the post-aggregation allocation "namespace2" will receive
  737. // 66.67% of the shared resource costs, while the remaining 33.33% will
  738. // be filtered out, as they were shared with allocations that did not pass
  739. // one of the given filters.
  740. //
  741. // In order to maintain stable results when multiple operations are being
  742. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  743. // coefficients are computed for the full set of allocations prior to
  744. // adding shared overhead and prior to applying filters.
  745. var err error
  746. // (2a) If there are idle costs to be shared, compute the coefficients for
  747. // sharing them among the non-idle, non-aggregated allocations (including
  748. // the shared allocations).
  749. var idleCoefficients map[string]map[string]map[string]float64
  750. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  751. idleCoefficients, err = computeIdleCoeffs(options, as, shareSet)
  752. if err != nil {
  753. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  754. return fmt.Errorf("error computing idle coefficients: %s", err)
  755. }
  756. }
  757. // (2b) If idle costs are not to be shared, but there are filters, then we
  758. // need to track the amount of each idle allocation to "filter" in order to
  759. // maintain parity with the results when idle is shared. That is, we want
  760. // to return only the idle costs that would have been shared with the given
  761. // results, even if the filter had not been applied.
  762. //
  763. // For example, consider these results from aggregating by namespace with
  764. // two clusters:
  765. //
  766. // namespace1: 25.00
  767. // namespace2: 30.00
  768. // namespace3: 15.00
  769. // idle: 30.00
  770. //
  771. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  772. // reduced by the amount that existed on cluster2. Then, idle must also be
  773. // reduced by the relevant amount:
  774. //
  775. // namespace1: 25.00
  776. // namespace2: 15.00
  777. // idle: 20.00
  778. //
  779. // Note that this can happen for any field, not just cluster, so we again
  780. // need to track this on a per-cluster, per-allocation, per-resource basis.
  781. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  782. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  783. idleFiltrationCoefficients, err = computeIdleCoeffs(options, as, shareSet)
  784. if err != nil {
  785. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  786. }
  787. }
  788. // (2c) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  789. // come after idle coefficients are computes so that allocations generated
  790. // by shared overhead do not skew the idle coefficient computation.
  791. for name, cost := range options.SharedHourlyCosts {
  792. if cost > 0.0 {
  793. hours := as.Resolution().Hours()
  794. // If set ends in the future, adjust hours accordingly
  795. diff := time.Now().Sub(as.End())
  796. if diff < 0.0 {
  797. hours += diff.Hours()
  798. }
  799. totalSharedCost := cost * hours
  800. shareSet.Insert(&Allocation{
  801. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  802. Start: as.Start(),
  803. End: as.End(),
  804. SharedCost: totalSharedCost,
  805. Properties: &AllocationProperties{Cluster: SharedSuffix}, // The allocation needs to belong to a cluster,but it really doesn't matter which one, so just make it clear.
  806. })
  807. }
  808. }
  809. // (2d) Compute share coefficients for shared resources. These are computed
  810. // after idle coefficients, and are computed for the aggregated allocations
  811. // of the main allocation set. See above for details and an example.
  812. var shareCoefficients map[string]float64
  813. if shareSet.Length() > 0 {
  814. shareCoefficients, err = computeShareCoeffs(aggregateBy, options, as)
  815. if err != nil {
  816. return fmt.Errorf("error computing share coefficients: %s", err)
  817. }
  818. }
  819. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  820. for _, alloc := range as.allocations {
  821. cluster := alloc.Properties.Cluster
  822. if cluster == "" {
  823. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  824. return fmt.Errorf("ClusterProp is not set")
  825. }
  826. skip := false
  827. // (3) If any of the filter funcs fail, immediately skip the allocation.
  828. for _, ff := range options.FilterFuncs {
  829. if !ff(alloc) {
  830. skip = true
  831. break
  832. }
  833. }
  834. if skip {
  835. // If we are tracking idle filtration coefficients, delete the
  836. // entry corresponding to the filtered allocation. (Deleting the
  837. // entry will result in that proportional amount being removed
  838. // from the idle allocation at the end of the process.)
  839. if idleFiltrationCoefficients != nil {
  840. if ifcc, ok := idleFiltrationCoefficients[cluster]; ok {
  841. delete(ifcc, alloc.Name)
  842. }
  843. }
  844. continue
  845. }
  846. // (4) Distribute idle allocations according to the idle coefficients
  847. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  848. // all idle allocations will be in the aggSet at this point, so idleSet
  849. // will be empty and we won't enter this block.
  850. if idleSet.Length() > 0 {
  851. // Distribute idle allocations by coefficient per-cluster, per-allocation
  852. for _, idleAlloc := range idleSet.allocations {
  853. // Only share idle if the cluster matches; i.e. the allocation
  854. // is from the same cluster as the idle costs
  855. idleCluster := idleAlloc.Properties.Cluster
  856. if idleCluster == "" {
  857. return fmt.Errorf("ClusterProp is not set")
  858. }
  859. if idleCluster != cluster {
  860. continue
  861. }
  862. // Make sure idle coefficients exist
  863. if _, ok := idleCoefficients[cluster]; !ok {
  864. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no cluster '%s' for '%s'", cluster, alloc.Name)
  865. continue
  866. }
  867. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  868. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  869. continue
  870. }
  871. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  872. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  873. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  874. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  875. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  876. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  877. alloc.CPUCost += idleCPUCost
  878. alloc.GPUCost += idleGPUCost
  879. alloc.RAMCost += idleRAMCost
  880. }
  881. }
  882. // (5) generate key to use for aggregation-by-key and allocation name
  883. key := alloc.generateKey(aggregateBy)
  884. alloc.Name = key
  885. if options.MergeUnallocated && alloc.IsUnallocated() {
  886. alloc.Name = UnallocatedSuffix
  887. }
  888. // Inserting the allocation with the generated key for a name will
  889. // perform the actual basic aggregation step.
  890. aggSet.Insert(alloc)
  891. }
  892. // (6) If idle is shared and resources are shared, it's possible that some
  893. // amount of idle cost will be shared with a shared resource. Distribute
  894. // that idle allocation, if it exists, to the respective shared allocations
  895. // before sharing with the aggregated allocations.
  896. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  897. for _, alloc := range shareSet.allocations {
  898. cluster := alloc.Properties.Cluster
  899. if cluster == "" {
  900. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  901. return err
  902. }
  903. // Distribute idle allocations by coefficient per-cluster, per-allocation
  904. for _, idleAlloc := range idleSet.allocations {
  905. // Only share idle if the cluster matches; i.e. the allocation
  906. // is from the same cluster as the idle costs
  907. idleCluster := idleAlloc.Properties.Cluster
  908. if idleCluster == "" {
  909. return fmt.Errorf("ClusterProp is not set")
  910. }
  911. if idleCluster != cluster {
  912. continue
  913. }
  914. // Make sure idle coefficients exist
  915. if _, ok := idleCoefficients[cluster]; !ok {
  916. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no cluster '%s' for '%s'", cluster, alloc.Name)
  917. continue
  918. }
  919. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  920. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  921. continue
  922. }
  923. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  924. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  925. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  926. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  927. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  928. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  929. alloc.CPUCost += idleCPUCost
  930. alloc.GPUCost += idleGPUCost
  931. alloc.RAMCost += idleRAMCost
  932. }
  933. }
  934. }
  935. // clusterIdleFiltrationCoeffs is used to track per-resource idle
  936. // coefficients on a cluster-by-cluster basis. It is, essentailly, an
  937. // aggregation of idleFiltrationCoefficients after they have been
  938. // filtered above (in step 3)
  939. var clusterIdleFiltrationCoeffs map[string]map[string]float64
  940. if idleFiltrationCoefficients != nil {
  941. clusterIdleFiltrationCoeffs = map[string]map[string]float64{}
  942. for cluster, m := range idleFiltrationCoefficients {
  943. if _, ok := clusterIdleFiltrationCoeffs[cluster]; !ok {
  944. clusterIdleFiltrationCoeffs[cluster] = map[string]float64{
  945. "cpu": 0.0,
  946. "gpu": 0.0,
  947. "ram": 0.0,
  948. }
  949. }
  950. for _, n := range m {
  951. for resource, val := range n {
  952. clusterIdleFiltrationCoeffs[cluster][resource] += val
  953. }
  954. }
  955. }
  956. }
  957. // (7) If we have both un-shared idle allocations and idle filtration
  958. // coefficients then apply those. See step (2b) for an example.
  959. if len(aggSet.idleKeys) > 0 && clusterIdleFiltrationCoeffs != nil {
  960. for idleKey := range aggSet.idleKeys {
  961. idleAlloc := aggSet.Get(idleKey)
  962. cluster := idleAlloc.Properties.Cluster
  963. if cluster == "" {
  964. log.Warningf("AllocationSet.AggregateBy: idle allocation without cluster: %s", idleAlloc)
  965. continue
  966. }
  967. if resourceCoeffs, ok := clusterIdleFiltrationCoeffs[cluster]; ok {
  968. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  969. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  970. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  971. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  972. }
  973. }
  974. }
  975. // (8) Distribute shared allocations according to the share coefficients.
  976. if shareSet.Length() > 0 {
  977. for _, alloc := range aggSet.allocations {
  978. for _, sharedAlloc := range shareSet.allocations {
  979. if _, ok := shareCoefficients[alloc.Name]; !ok {
  980. log.Warningf("AllocationSet.AggregateBy: error getting share coefficienct for '%s'", alloc.Name)
  981. continue
  982. }
  983. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  984. }
  985. }
  986. }
  987. // (9) Aggregate external allocations into aggregated allocations. This may
  988. // not be possible for every external allocation, but attempt to find an
  989. // exact key match, given each external allocation's proerties, and
  990. // aggregate if an exact match is found.
  991. for _, alloc := range externalSet.allocations {
  992. skip := false
  993. for _, ff := range options.FilterFuncs {
  994. if !ff(alloc) {
  995. skip = true
  996. break
  997. }
  998. }
  999. if !skip {
  1000. key := alloc.generateKey(aggregateBy)
  1001. alloc.Name = key
  1002. aggSet.Insert(alloc)
  1003. }
  1004. }
  1005. // (10) Combine all idle allocations into a single "__idle__" allocation
  1006. if !options.SplitIdle {
  1007. for _, idleAlloc := range aggSet.IdleAllocations() {
  1008. aggSet.Delete(idleAlloc.Name)
  1009. idleAlloc.Name = IdleSuffix
  1010. aggSet.Insert(idleAlloc)
  1011. }
  1012. }
  1013. as.allocations = aggSet.allocations
  1014. return nil
  1015. }
  1016. func computeShareCoeffs(aggregateBy []string, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  1017. // Compute coeffs by totalling per-allocation, then dividing by the total.
  1018. coeffs := map[string]float64{}
  1019. // Compute totals for all allocations
  1020. total := 0.0
  1021. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  1022. // counts each aggregation proportionally to its respective costs
  1023. shareType := options.ShareSplit
  1024. // Record allocation values first, then normalize by totals to get percentages
  1025. for _, alloc := range as.allocations {
  1026. if alloc.IsIdle() {
  1027. // Skip idle allocations in coefficient calculation
  1028. continue
  1029. }
  1030. // Determine the post-aggregation key under which the allocation will
  1031. // be shared.
  1032. name := alloc.generateKey(aggregateBy)
  1033. // If the current allocation will be filtered out in step 3, contribute
  1034. // its share of the shared coefficient to a "__filtered__" bin, which
  1035. // will ultimately be dropped. This step ensures that the shared cost
  1036. // of a non-filtered allocation will be conserved even when the filter
  1037. // is removed. (Otherwise, all the shared cost will get redistributed
  1038. // over the unfiltered results, inflating their shared costs.)
  1039. filtered := false
  1040. for _, ff := range options.FilterFuncs {
  1041. if !ff(alloc) {
  1042. filtered = true
  1043. break
  1044. }
  1045. }
  1046. if filtered {
  1047. name = "__filtered__"
  1048. }
  1049. if shareType == ShareEven {
  1050. // Even distribution is not additive - set to 1.0 for everything
  1051. coeffs[name] = 1.0
  1052. // Total for even distribution is always the number of coefficients
  1053. total = float64(len(coeffs))
  1054. } else {
  1055. // Both are additive for weighted distribution, where each
  1056. // cumulative coefficient will be divided by the total.
  1057. coeffs[name] += alloc.TotalCost()
  1058. total += alloc.TotalCost()
  1059. }
  1060. }
  1061. // Normalize coefficients by totals
  1062. for a := range coeffs {
  1063. if coeffs[a] > 0 && total > 0 {
  1064. coeffs[a] /= total
  1065. } else {
  1066. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  1067. coeffs[a] = 0.0
  1068. }
  1069. }
  1070. return coeffs, nil
  1071. }
  1072. func computeIdleCoeffs(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, error) {
  1073. types := []string{"cpu", "gpu", "ram"}
  1074. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1075. coeffs := map[string]map[string]map[string]float64{}
  1076. // Compute totals per resource for CPU, GPU, RAM, and PV
  1077. totals := map[string]map[string]float64{}
  1078. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  1079. // counts each allocation proportionally to its respective costs
  1080. shareType := options.ShareIdle
  1081. // Record allocation values first, then normalize by totals to get percentages
  1082. for _, alloc := range as.allocations {
  1083. if alloc.IsIdle() {
  1084. // Skip idle allocations in coefficient calculation
  1085. continue
  1086. }
  1087. // We need to key the allocations by cluster id
  1088. clusterID := alloc.Properties.Cluster
  1089. if clusterID == "" {
  1090. return nil, fmt.Errorf("ClusterProp is not set")
  1091. }
  1092. // get the name key for the allocation
  1093. name := alloc.Name
  1094. // Create cluster based tables if they don't exist
  1095. if _, ok := coeffs[clusterID]; !ok {
  1096. coeffs[clusterID] = map[string]map[string]float64{}
  1097. }
  1098. if _, ok := totals[clusterID]; !ok {
  1099. totals[clusterID] = map[string]float64{}
  1100. }
  1101. if _, ok := coeffs[clusterID][name]; !ok {
  1102. coeffs[clusterID][name] = map[string]float64{}
  1103. }
  1104. if shareType == ShareEven {
  1105. for _, r := range types {
  1106. // Not additive - hard set to 1.0
  1107. coeffs[clusterID][name][r] = 1.0
  1108. // totals are additive
  1109. totals[clusterID][r] += 1.0
  1110. }
  1111. } else {
  1112. coeffs[clusterID][name]["cpu"] += alloc.CPUTotalCost()
  1113. coeffs[clusterID][name]["gpu"] += alloc.GPUTotalCost()
  1114. coeffs[clusterID][name]["ram"] += alloc.RAMTotalCost()
  1115. totals[clusterID]["cpu"] += alloc.CPUTotalCost()
  1116. totals[clusterID]["gpu"] += alloc.GPUTotalCost()
  1117. totals[clusterID]["ram"] += alloc.RAMTotalCost()
  1118. }
  1119. }
  1120. // Do the same for shared allocations
  1121. for _, alloc := range shareSet.allocations {
  1122. if alloc.IsIdle() {
  1123. // Skip idle allocations in coefficient calculation
  1124. continue
  1125. }
  1126. // We need to key the allocations by cluster id
  1127. clusterID := alloc.Properties.Cluster
  1128. if clusterID == "" {
  1129. return nil, fmt.Errorf("ClusterProp is not set")
  1130. }
  1131. // get the name key for the allocation
  1132. name := alloc.Name
  1133. // Create cluster based tables if they don't exist
  1134. if _, ok := coeffs[clusterID]; !ok {
  1135. coeffs[clusterID] = map[string]map[string]float64{}
  1136. }
  1137. if _, ok := totals[clusterID]; !ok {
  1138. totals[clusterID] = map[string]float64{}
  1139. }
  1140. if _, ok := coeffs[clusterID][name]; !ok {
  1141. coeffs[clusterID][name] = map[string]float64{}
  1142. }
  1143. if shareType == ShareEven {
  1144. for _, r := range types {
  1145. // Not additive - hard set to 1.0
  1146. coeffs[clusterID][name][r] = 1.0
  1147. // totals are additive
  1148. totals[clusterID][r] += 1.0
  1149. }
  1150. } else {
  1151. coeffs[clusterID][name]["cpu"] += alloc.CPUTotalCost()
  1152. coeffs[clusterID][name]["gpu"] += alloc.GPUTotalCost()
  1153. coeffs[clusterID][name]["ram"] += alloc.RAMTotalCost()
  1154. totals[clusterID]["cpu"] += alloc.CPUTotalCost()
  1155. totals[clusterID]["gpu"] += alloc.GPUTotalCost()
  1156. totals[clusterID]["ram"] += alloc.RAMTotalCost()
  1157. }
  1158. }
  1159. // Normalize coefficients by totals
  1160. for c := range coeffs {
  1161. for a := range coeffs[c] {
  1162. for _, r := range types {
  1163. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  1164. coeffs[c][a][r] /= totals[c][r]
  1165. }
  1166. }
  1167. }
  1168. }
  1169. return coeffs, nil
  1170. }
  1171. func (a *Allocation) generateKey(aggregateBy []string) string {
  1172. if a == nil {
  1173. return ""
  1174. }
  1175. // Names will ultimately be joined into a single name, which uniquely
  1176. // identifies allocations.
  1177. names := []string{}
  1178. for _, agg := range aggregateBy {
  1179. switch true {
  1180. case agg == AllocationClusterProp:
  1181. names = append(names, a.Properties.Cluster)
  1182. case agg == AllocationNodeProp:
  1183. names = append(names, a.Properties.Node)
  1184. case agg == AllocationNamespaceProp:
  1185. names = append(names, a.Properties.Namespace)
  1186. case agg == AllocationControllerKindProp:
  1187. controllerKind := a.Properties.ControllerKind
  1188. if controllerKind == "" {
  1189. // Indicate that allocation has no controller
  1190. controllerKind = UnallocatedSuffix
  1191. }
  1192. names = append(names, controllerKind)
  1193. case agg == AllocationDaemonSetProp || agg == AllocationStatefulSetProp || agg == AllocationDeploymentProp || agg == AllocationJobProp:
  1194. controller := a.Properties.Controller
  1195. if agg != a.Properties.ControllerKind || controller == "" {
  1196. // The allocation does not have the specified controller kind
  1197. controller = UnallocatedSuffix
  1198. }
  1199. names = append(names, controller)
  1200. case agg == AllocationControllerProp:
  1201. controller := a.Properties.Controller
  1202. if controller == "" {
  1203. // Indicate that allocation has no controller
  1204. controller = UnallocatedSuffix
  1205. } else if a.Properties.ControllerKind != "" {
  1206. controller = fmt.Sprintf("%s:%s", a.Properties.ControllerKind, controller)
  1207. }
  1208. names = append(names, controller)
  1209. case agg == AllocationPodProp:
  1210. names = append(names, a.Properties.Pod)
  1211. case agg == AllocationContainerProp:
  1212. names = append(names, a.Properties.Container)
  1213. case agg == AllocationServiceProp:
  1214. services := a.Properties.Services
  1215. if services == nil || len(services) == 0 {
  1216. // Indicate that allocation has no services
  1217. names = append(names, UnallocatedSuffix)
  1218. } else {
  1219. // This just uses the first service
  1220. for _, service := range services {
  1221. names = append(names, service)
  1222. break
  1223. }
  1224. }
  1225. case strings.HasPrefix(agg, "label:"):
  1226. labels := a.Properties.Labels
  1227. if labels == nil {
  1228. // Indicate that allocation has no labels
  1229. names = append(names, UnallocatedSuffix)
  1230. } else {
  1231. labelNames := []string{}
  1232. aggLabels := strings.Split(strings.TrimPrefix(agg, "label:"), ";")
  1233. for _, labelName := range aggLabels {
  1234. if val, ok := labels[labelName]; ok {
  1235. labelNames = append(labelNames, fmt.Sprintf("%s=%s", labelName, val))
  1236. } else if indexOf(UnallocatedSuffix, labelNames) == -1 { // if UnallocatedSuffix not already in names
  1237. labelNames = append(labelNames, UnallocatedSuffix)
  1238. }
  1239. }
  1240. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1241. if len(labelNames) > 1 {
  1242. sort.Strings(labelNames)
  1243. }
  1244. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, labelNames)
  1245. // suffix should be at index 0 if it exists b/c of underscores
  1246. if unallocatedSuffixIndex != -1 {
  1247. labelNames = append(labelNames[:unallocatedSuffixIndex], labelNames[unallocatedSuffixIndex+1:]...)
  1248. labelNames = append(labelNames, UnallocatedSuffix) // append to end
  1249. }
  1250. names = append(names, labelNames...)
  1251. }
  1252. case strings.HasPrefix(agg, "annotation:"):
  1253. annotations := a.Properties.Annotations
  1254. if annotations == nil {
  1255. // Indicate that allocation has no annotations
  1256. names = append(names, UnallocatedSuffix)
  1257. } else {
  1258. annotationNames := []string{}
  1259. aggAnnotations := strings.Split(strings.TrimPrefix(agg, "annotation:"), ";")
  1260. for _, annotationName := range aggAnnotations {
  1261. if val, ok := annotations[annotationName]; ok {
  1262. annotationNames = append(annotationNames, fmt.Sprintf("%s=%s", annotationName, val))
  1263. } else if indexOf(UnallocatedSuffix, annotationNames) == -1 { // if UnallocatedSuffix not already in names
  1264. annotationNames = append(annotationNames, UnallocatedSuffix)
  1265. }
  1266. }
  1267. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1268. if len(annotationNames) > 1 {
  1269. sort.Strings(annotationNames)
  1270. }
  1271. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, annotationNames)
  1272. // suffix should be at index 0 if it exists b/c of underscores
  1273. if unallocatedSuffixIndex != -1 {
  1274. annotationNames = append(annotationNames[:unallocatedSuffixIndex], annotationNames[unallocatedSuffixIndex+1:]...)
  1275. annotationNames = append(annotationNames, UnallocatedSuffix) // append to end
  1276. }
  1277. names = append(names, annotationNames...)
  1278. }
  1279. }
  1280. }
  1281. return strings.Join(names, "/")
  1282. }
  1283. // TODO:CLEANUP get rid of this
  1284. // Helper function to check for slice membership. Not sure if repeated elsewhere in our codebase.
  1285. func indexOf(v string, arr []string) int {
  1286. for i, s := range arr {
  1287. // This is caseless equivalence
  1288. if strings.EqualFold(v, s) {
  1289. return i
  1290. }
  1291. }
  1292. return -1
  1293. }
  1294. // Clone returns a new AllocationSet with a deep copy of the given
  1295. // AllocationSet's allocations.
  1296. func (as *AllocationSet) Clone() *AllocationSet {
  1297. if as == nil {
  1298. return nil
  1299. }
  1300. as.RLock()
  1301. defer as.RUnlock()
  1302. allocs := map[string]*Allocation{}
  1303. for k, v := range as.allocations {
  1304. allocs[k] = v.Clone()
  1305. }
  1306. externalKeys := map[string]bool{}
  1307. for k, v := range as.externalKeys {
  1308. externalKeys[k] = v
  1309. }
  1310. idleKeys := map[string]bool{}
  1311. for k, v := range as.idleKeys {
  1312. idleKeys[k] = v
  1313. }
  1314. return &AllocationSet{
  1315. allocations: allocs,
  1316. externalKeys: externalKeys,
  1317. idleKeys: idleKeys,
  1318. Window: as.Window.Clone(),
  1319. }
  1320. }
  1321. // ComputeIdleAllocations computes the idle allocations for the AllocationSet,
  1322. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1323. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1324. // considered for idle allocation. If the Nodes have adjustments, then apply
  1325. // the adjustments proportionally to each of the resources so that total
  1326. // allocation with idle reflects the adjusted node costs. One idle allocation
  1327. // per-cluster will be computed and returned, keyed by cluster_id.
  1328. func (as *AllocationSet) ComputeIdleAllocations(assetSet *AssetSet) (map[string]*Allocation, error) {
  1329. if as == nil {
  1330. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1331. }
  1332. if assetSet == nil {
  1333. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1334. }
  1335. if !as.Window.Equal(assetSet.Window) {
  1336. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1337. }
  1338. window := as.Window
  1339. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1340. // cluster-to-{cpu|gpu|ram}-to-cost.
  1341. assetClusterResourceCosts := map[string]map[string]float64{}
  1342. assetSet.Each(func(key string, a Asset) {
  1343. if node, ok := a.(*Node); ok {
  1344. if _, ok := assetClusterResourceCosts[node.Properties().Cluster]; !ok {
  1345. assetClusterResourceCosts[node.Properties().Cluster] = map[string]float64{}
  1346. }
  1347. // adjustmentRate is used to scale resource costs proportionally
  1348. // by the adjustment. This is necessary because we only get one
  1349. // adjustment per Node, not one per-resource-per-Node.
  1350. //
  1351. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1352. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1353. // e.g. total cost = $150, adjustment = $50 => 1.5
  1354. adjustmentRate := 1.0
  1355. if node.TotalCost()-node.Adjustment() == 0 {
  1356. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1357. // the entire node cost and we should make everything 0
  1358. // without dividing by 0.
  1359. adjustmentRate = 0.0
  1360. } else if node.Adjustment() != 0.0 {
  1361. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1362. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1363. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1364. }
  1365. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1366. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1367. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1368. assetClusterResourceCosts[node.Properties().Cluster]["cpu"] += cpuCost
  1369. assetClusterResourceCosts[node.Properties().Cluster]["gpu"] += gpuCost
  1370. assetClusterResourceCosts[node.Properties().Cluster]["ram"] += ramCost
  1371. }
  1372. })
  1373. // Determine start, end on a per-cluster basis
  1374. clusterStarts := map[string]time.Time{}
  1375. clusterEnds := map[string]time.Time{}
  1376. // Subtract allocated costs from asset costs, leaving only the remaining
  1377. // idle costs.
  1378. as.Each(func(name string, a *Allocation) {
  1379. cluster := a.Properties.Cluster
  1380. if cluster == "" {
  1381. // Failed to find allocation's cluster
  1382. return
  1383. }
  1384. if _, ok := assetClusterResourceCosts[cluster]; !ok {
  1385. // Failed to find assets for allocation's cluster
  1386. return
  1387. }
  1388. // Set cluster (start, end) if they are either not currently set,
  1389. // or if the detected (start, end) of the current allocation falls
  1390. // before or after, respectively, the current values.
  1391. if s, ok := clusterStarts[cluster]; !ok || a.Start.Before(s) {
  1392. clusterStarts[cluster] = a.Start
  1393. }
  1394. if e, ok := clusterEnds[cluster]; !ok || a.End.After(e) {
  1395. clusterEnds[cluster] = a.End
  1396. }
  1397. assetClusterResourceCosts[cluster]["cpu"] -= a.CPUTotalCost()
  1398. assetClusterResourceCosts[cluster]["gpu"] -= a.GPUTotalCost()
  1399. assetClusterResourceCosts[cluster]["ram"] -= a.RAMTotalCost()
  1400. })
  1401. // Turn remaining un-allocated asset costs into idle allocations
  1402. idleAllocs := map[string]*Allocation{}
  1403. for cluster, resources := range assetClusterResourceCosts {
  1404. // Default start and end to the (start, end) of the given window, but
  1405. // use the actual, detected (start, end) pair if they are available.
  1406. start := *window.Start()
  1407. if s, ok := clusterStarts[cluster]; ok && window.Contains(s) {
  1408. start = s
  1409. }
  1410. end := *window.End()
  1411. if e, ok := clusterEnds[cluster]; ok && window.Contains(e) {
  1412. end = e
  1413. }
  1414. idleAlloc := &Allocation{
  1415. Name: fmt.Sprintf("%s/%s", cluster, IdleSuffix),
  1416. Window: window.Clone(),
  1417. Properties: &AllocationProperties{Cluster: cluster},
  1418. Start: start,
  1419. End: end,
  1420. CPUCost: resources["cpu"],
  1421. GPUCost: resources["gpu"],
  1422. RAMCost: resources["ram"],
  1423. }
  1424. // Do not continue if multiple idle allocations are computed for a
  1425. // single cluster.
  1426. if _, ok := idleAllocs[cluster]; ok {
  1427. return nil, fmt.Errorf("duplicate idle allocations for cluster %s", cluster)
  1428. }
  1429. idleAllocs[cluster] = idleAlloc
  1430. }
  1431. return idleAllocs, nil
  1432. }
  1433. // Reconcile calculate the exact cost of Allocation by resource(cpu, ram, gpu etc) based on Asset(s) on which
  1434. // the Allocation depends.
  1435. func (as *AllocationSet) Reconcile(assetSet *AssetSet) error {
  1436. if as == nil {
  1437. return fmt.Errorf("cannot reconcile allocation for nil AllocationSet")
  1438. }
  1439. if assetSet == nil {
  1440. return fmt.Errorf("cannot reconcile allocation with nil AssetSet")
  1441. }
  1442. if !as.Window.Equal(assetSet.Window) {
  1443. return fmt.Errorf("cannot reconcile allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1444. }
  1445. // Build map of Assets with type Node by their ProviderId so that they can be matched to Allocations to determine
  1446. // proper CPU GPU and RAM prices
  1447. nodeByProviderID := map[string]*Node{}
  1448. diskByName := map[string]*Disk{}
  1449. assetSet.Each(func(key string, a Asset) {
  1450. if node, ok := a.(*Node); ok && node.properties.ProviderID != "" {
  1451. nodeByProviderID[node.properties.ProviderID] = node
  1452. }
  1453. if disk, ok := a.(*Disk); ok {
  1454. diskByName[disk.properties.Name] = disk
  1455. }
  1456. })
  1457. // Match Assets against allocations and adjust allocation cost based on the proportion of the asset that they used
  1458. as.Each(func(name string, a *Allocation) {
  1459. a.reconcileNodes(nodeByProviderID)
  1460. a.reconcileDisks(diskByName)
  1461. })
  1462. return nil
  1463. }
  1464. func (a *Allocation) reconcileNodes(nodeByProviderID map[string]*Node) {
  1465. providerId := a.Properties.ProviderID
  1466. // Reconcile with node Assets
  1467. node, ok := nodeByProviderID[providerId]
  1468. if !ok {
  1469. // Failed to find node for allocation
  1470. return
  1471. }
  1472. // adjustmentRate is used to scale resource costs proportionally
  1473. // by the adjustment. This is necessary because we only get one
  1474. // adjustment per Node, not one per-resource-per-Node.
  1475. //
  1476. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1477. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1478. // e.g. total cost = $150, adjustment = $50 => 1.5
  1479. adjustmentRate := 1.0
  1480. if node.TotalCost()-node.Adjustment() == 0 {
  1481. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1482. // the entire node cost and we should make everything 0
  1483. // without dividing by 0.
  1484. adjustmentRate = 0.0
  1485. } else if node.Adjustment() != 0.0 {
  1486. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1487. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1488. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1489. }
  1490. // Find total cost of each node resource for the window
  1491. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1492. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1493. gpuCost := node.GPUCost * adjustmentRate
  1494. // Find the proportion of resource hours used by the allocation, checking for 0 denominators
  1495. cpuUsageProportion := 0.0
  1496. if node.CPUCoreHours != 0 {
  1497. cpuUsageProportion = a.CPUCoreHours / node.CPUCoreHours
  1498. } else {
  1499. log.Warningf("Missing CPU Hours for node Provider ID: %s", providerId)
  1500. }
  1501. ramUsageProportion := 0.0
  1502. if node.RAMByteHours != 0 {
  1503. ramUsageProportion = a.RAMByteHours / node.RAMByteHours
  1504. } else {
  1505. log.Warningf("Missing Ram Byte Hours for node Provider ID: %s", providerId)
  1506. }
  1507. gpuUsageProportion := 0.0
  1508. if node.GPUHours != 0 {
  1509. gpuUsageProportion = a.GPUHours / node.GPUHours
  1510. }
  1511. // No log for GPU because not all nodes have GPU
  1512. // Calculate the allocation's resource costs by the proportion of resources used and total costs
  1513. allocCPUCost := cpuUsageProportion * cpuCost
  1514. allocRAMCost := ramUsageProportion * ramCost
  1515. allocGPUCost := gpuUsageProportion * gpuCost
  1516. a.CPUCostAdjustment = allocCPUCost - a.CPUCost
  1517. a.RAMCostAdjustment = allocRAMCost - a.RAMCost
  1518. a.GPUCostAdjustment = allocGPUCost - a.GPUCost
  1519. }
  1520. func (a *Allocation) reconcileDisks(diskByName map[string]*Disk) {
  1521. pvs := a.PVs
  1522. if pvs == nil {
  1523. // No PV usage to reconcile
  1524. return
  1525. }
  1526. // Set PV Adjustment for allocation to 0 for idempotency
  1527. a.PVCostAdjustment = 0.0
  1528. for pvKey, pvUsage := range pvs {
  1529. disk, ok := diskByName[pvKey.Name]
  1530. if !ok {
  1531. // Failed to find disk in assets
  1532. continue
  1533. }
  1534. // Check the proportion of disk that is being used by
  1535. pvUsageProportion := 0.0
  1536. if disk.ByteHours != 0 {
  1537. pvUsageProportion = pvUsage.ByteHours / disk.ByteHours
  1538. } else {
  1539. log.Warningf("Missing Byte Hours for disk: %s", pvKey)
  1540. }
  1541. // take proportion of disk adjusted cost
  1542. allocPVCost := pvUsageProportion * disk.TotalCost()
  1543. // PVCostAdjustment is cumulative as there can be many PVs for each Allocation
  1544. a.PVCostAdjustment += allocPVCost - pvUsage.Cost
  1545. }
  1546. }
  1547. // Delete removes the allocation with the given name from the set
  1548. func (as *AllocationSet) Delete(name string) {
  1549. if as == nil {
  1550. return
  1551. }
  1552. as.Lock()
  1553. defer as.Unlock()
  1554. delete(as.externalKeys, name)
  1555. delete(as.idleKeys, name)
  1556. delete(as.allocations, name)
  1557. }
  1558. // Each invokes the given function for each Allocation in the set
  1559. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  1560. if as == nil {
  1561. return
  1562. }
  1563. for k, a := range as.allocations {
  1564. f(k, a)
  1565. }
  1566. }
  1567. // End returns the End time of the AllocationSet window
  1568. func (as *AllocationSet) End() time.Time {
  1569. if as == nil {
  1570. log.Warningf("Allocation ETL: calling End on nil AllocationSet")
  1571. return time.Unix(0, 0)
  1572. }
  1573. if as.Window.End() == nil {
  1574. log.Warningf("Allocation ETL: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  1575. return time.Unix(0, 0)
  1576. }
  1577. return *as.Window.End()
  1578. }
  1579. // Get returns the Allocation at the given key in the AllocationSet
  1580. func (as *AllocationSet) Get(key string) *Allocation {
  1581. as.RLock()
  1582. defer as.RUnlock()
  1583. if alloc, ok := as.allocations[key]; ok {
  1584. return alloc
  1585. }
  1586. return nil
  1587. }
  1588. // ExternalAllocations returns a map of the external allocations in the set.
  1589. // Returns clones of the actual Allocations, so mutability is not a problem.
  1590. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1591. externals := map[string]*Allocation{}
  1592. if as.IsEmpty() {
  1593. return externals
  1594. }
  1595. as.RLock()
  1596. defer as.RUnlock()
  1597. for key := range as.externalKeys {
  1598. if alloc, ok := as.allocations[key]; ok {
  1599. externals[key] = alloc.Clone()
  1600. }
  1601. }
  1602. return externals
  1603. }
  1604. // ExternalCost returns the total aggregated external costs of the set
  1605. func (as *AllocationSet) ExternalCost() float64 {
  1606. if as.IsEmpty() {
  1607. return 0.0
  1608. }
  1609. as.RLock()
  1610. defer as.RUnlock()
  1611. externalCost := 0.0
  1612. for _, alloc := range as.allocations {
  1613. externalCost += alloc.ExternalCost
  1614. }
  1615. return externalCost
  1616. }
  1617. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1618. // Returns clones of the actual Allocations, so mutability is not a problem.
  1619. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1620. idles := map[string]*Allocation{}
  1621. if as.IsEmpty() {
  1622. return idles
  1623. }
  1624. as.RLock()
  1625. defer as.RUnlock()
  1626. for key := range as.idleKeys {
  1627. if alloc, ok := as.allocations[key]; ok {
  1628. idles[key] = alloc.Clone()
  1629. }
  1630. }
  1631. return idles
  1632. }
  1633. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1634. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1635. // there is no existing entry, one is created. Nil error response indicates success.
  1636. func (as *AllocationSet) Insert(that *Allocation) error {
  1637. return as.insert(that)
  1638. }
  1639. func (as *AllocationSet) insert(that *Allocation) error {
  1640. if as == nil {
  1641. return fmt.Errorf("cannot insert into nil AllocationSet")
  1642. }
  1643. as.Lock()
  1644. defer as.Unlock()
  1645. if as.allocations == nil {
  1646. as.allocations = map[string]*Allocation{}
  1647. }
  1648. if as.externalKeys == nil {
  1649. as.externalKeys = map[string]bool{}
  1650. }
  1651. if as.idleKeys == nil {
  1652. as.idleKeys = map[string]bool{}
  1653. }
  1654. // Add the given Allocation to the existing entry, if there is one;
  1655. // otherwise just set directly into allocations
  1656. if _, ok := as.allocations[that.Name]; !ok {
  1657. as.allocations[that.Name] = that
  1658. } else {
  1659. as.allocations[that.Name].add(that)
  1660. }
  1661. // If the given Allocation is an external one, record that
  1662. if that.IsExternal() {
  1663. as.externalKeys[that.Name] = true
  1664. }
  1665. // If the given Allocation is an idle one, record that
  1666. if that.IsIdle() {
  1667. as.idleKeys[that.Name] = true
  1668. }
  1669. return nil
  1670. }
  1671. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  1672. // zero allocations.
  1673. func (as *AllocationSet) IsEmpty() bool {
  1674. if as == nil || len(as.allocations) == 0 {
  1675. return true
  1676. }
  1677. as.RLock()
  1678. defer as.RUnlock()
  1679. return as.allocations == nil || len(as.allocations) == 0
  1680. }
  1681. // Length returns the number of Allocations in the set
  1682. func (as *AllocationSet) Length() int {
  1683. if as == nil {
  1684. return 0
  1685. }
  1686. as.RLock()
  1687. defer as.RUnlock()
  1688. return len(as.allocations)
  1689. }
  1690. // Map clones and returns a map of the AllocationSet's Allocations
  1691. func (as *AllocationSet) Map() map[string]*Allocation {
  1692. if as.IsEmpty() {
  1693. return map[string]*Allocation{}
  1694. }
  1695. return as.Clone().allocations
  1696. }
  1697. // MarshalJSON JSON-encodes the AllocationSet
  1698. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  1699. as.RLock()
  1700. defer as.RUnlock()
  1701. return json.Marshal(as.allocations)
  1702. }
  1703. // Resolution returns the AllocationSet's window duration
  1704. func (as *AllocationSet) Resolution() time.Duration {
  1705. return as.Window.Duration()
  1706. }
  1707. // Set uses the given Allocation to overwrite the existing entry in the
  1708. // AllocationSet under the Allocation's name.
  1709. func (as *AllocationSet) Set(alloc *Allocation) error {
  1710. if as.IsEmpty() {
  1711. as.Lock()
  1712. as.allocations = map[string]*Allocation{}
  1713. as.externalKeys = map[string]bool{}
  1714. as.idleKeys = map[string]bool{}
  1715. as.Unlock()
  1716. }
  1717. as.Lock()
  1718. defer as.Unlock()
  1719. as.allocations[alloc.Name] = alloc
  1720. // If the given Allocation is an external one, record that
  1721. if alloc.IsExternal() {
  1722. as.externalKeys[alloc.Name] = true
  1723. }
  1724. // If the given Allocation is an idle one, record that
  1725. if alloc.IsIdle() {
  1726. as.idleKeys[alloc.Name] = true
  1727. }
  1728. return nil
  1729. }
  1730. // Start returns the Start time of the AllocationSet window
  1731. func (as *AllocationSet) Start() time.Time {
  1732. if as == nil {
  1733. log.Warningf("Allocation ETL: calling Start on nil AllocationSet")
  1734. return time.Unix(0, 0)
  1735. }
  1736. if as.Window.Start() == nil {
  1737. log.Warningf("Allocation ETL: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1738. return time.Unix(0, 0)
  1739. }
  1740. return *as.Window.Start()
  1741. }
  1742. // String represents the given Allocation as a string
  1743. func (as *AllocationSet) String() string {
  1744. if as == nil {
  1745. return "<nil>"
  1746. }
  1747. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1748. as.Length(), as.Window, as.TotalCost())
  1749. }
  1750. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1751. func (as *AllocationSet) TotalCost() float64 {
  1752. if as.IsEmpty() {
  1753. return 0.0
  1754. }
  1755. as.RLock()
  1756. defer as.RUnlock()
  1757. tc := 0.0
  1758. for _, a := range as.allocations {
  1759. tc += a.TotalCost()
  1760. }
  1761. return tc
  1762. }
  1763. // UTCOffset returns the AllocationSet's configured UTCOffset.
  1764. func (as *AllocationSet) UTCOffset() time.Duration {
  1765. _, zone := as.Start().Zone()
  1766. return time.Duration(zone) * time.Second
  1767. }
  1768. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1769. if as.IsEmpty() {
  1770. return that, nil
  1771. }
  1772. if that.IsEmpty() {
  1773. return as, nil
  1774. }
  1775. // Set start, end to min(start), max(end)
  1776. start := as.Start()
  1777. end := as.End()
  1778. if that.Start().Before(start) {
  1779. start = that.Start()
  1780. }
  1781. if that.End().After(end) {
  1782. end = that.End()
  1783. }
  1784. acc := NewAllocationSet(start, end)
  1785. as.RLock()
  1786. defer as.RUnlock()
  1787. that.RLock()
  1788. defer that.RUnlock()
  1789. for _, alloc := range as.allocations {
  1790. err := acc.insert(alloc)
  1791. if err != nil {
  1792. return nil, err
  1793. }
  1794. }
  1795. for _, alloc := range that.allocations {
  1796. err := acc.insert(alloc)
  1797. if err != nil {
  1798. return nil, err
  1799. }
  1800. }
  1801. return acc, nil
  1802. }
  1803. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  1804. // be used such that the AllocationSets held are consecutive and coherent with
  1805. // respect to using the same aggregation properties, UTC offset, and
  1806. // resolution. However these rules are not necessarily enforced, so use wisely.
  1807. type AllocationSetRange struct {
  1808. sync.RWMutex
  1809. allocations []*AllocationSet
  1810. }
  1811. // NewAllocationSetRange instantiates a new range composed of the given
  1812. // AllocationSets in the order provided.
  1813. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1814. return &AllocationSetRange{
  1815. allocations: allocs,
  1816. }
  1817. }
  1818. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1819. // AllocationSet for the entire range.
  1820. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1821. var allocSet *AllocationSet
  1822. var err error
  1823. asr.RLock()
  1824. defer asr.RUnlock()
  1825. for _, as := range asr.allocations {
  1826. allocSet, err = allocSet.accumulate(as)
  1827. if err != nil {
  1828. return nil, err
  1829. }
  1830. }
  1831. return allocSet, nil
  1832. }
  1833. // TODO niko/etl accumulate into lower-resolution chunks of the given resolution
  1834. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1835. // AggregateBy aggregates each AllocationSet in the range by the given
  1836. // properties and options.
  1837. func (asr *AllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  1838. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1839. asr.Lock()
  1840. defer asr.Unlock()
  1841. for _, as := range asr.allocations {
  1842. err := as.AggregateBy(aggregateBy, options)
  1843. if err != nil {
  1844. return err
  1845. }
  1846. aggRange.allocations = append(aggRange.allocations, as)
  1847. }
  1848. asr.allocations = aggRange.allocations
  1849. return nil
  1850. }
  1851. // Append appends the given AllocationSet to the end of the range. It does not
  1852. // validate whether or not that violates window continuity.
  1853. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1854. asr.Lock()
  1855. defer asr.Unlock()
  1856. asr.allocations = append(asr.allocations, that)
  1857. }
  1858. // Each invokes the given function for each AllocationSet in the range
  1859. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1860. if asr == nil {
  1861. return
  1862. }
  1863. for i, as := range asr.allocations {
  1864. f(i, as)
  1865. }
  1866. }
  1867. // Get retrieves the AllocationSet at the given index of the range.
  1868. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  1869. if i < 0 || i >= len(asr.allocations) {
  1870. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  1871. }
  1872. asr.RLock()
  1873. defer asr.RUnlock()
  1874. return asr.allocations[i], nil
  1875. }
  1876. // InsertRange merges the given AllocationSetRange into the receiving one by
  1877. // lining up sets with matching windows, then inserting each allocation from
  1878. // the given ASR into the respective set in the receiving ASR. If the given
  1879. // ASR contains an AllocationSet from a window that does not exist in the
  1880. // receiving ASR, then an error is returned. However, the given ASR does not
  1881. // need to cover the full range of the receiver.
  1882. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  1883. if asr == nil {
  1884. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  1885. }
  1886. // keys maps window to index in asr
  1887. keys := map[string]int{}
  1888. asr.Each(func(i int, as *AllocationSet) {
  1889. if as == nil {
  1890. return
  1891. }
  1892. keys[as.Window.String()] = i
  1893. })
  1894. // Nothing to merge, so simply return
  1895. if len(keys) == 0 {
  1896. return nil
  1897. }
  1898. var err error
  1899. that.Each(func(j int, thatAS *AllocationSet) {
  1900. if thatAS == nil || err != nil {
  1901. return
  1902. }
  1903. // Find matching AllocationSet in asr
  1904. i, ok := keys[thatAS.Window.String()]
  1905. if !ok {
  1906. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  1907. return
  1908. }
  1909. as, err := asr.Get(i)
  1910. if err != nil {
  1911. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  1912. return
  1913. }
  1914. // Insert each Allocation from the given set
  1915. thatAS.Each(func(k string, alloc *Allocation) {
  1916. err = as.Insert(alloc)
  1917. if err != nil {
  1918. err = fmt.Errorf("error inserting allocation: %s", err)
  1919. return
  1920. }
  1921. })
  1922. })
  1923. // err might be nil
  1924. return err
  1925. }
  1926. // Length returns the length of the range, which is zero if nil
  1927. func (asr *AllocationSetRange) Length() int {
  1928. if asr == nil || asr.allocations == nil {
  1929. return 0
  1930. }
  1931. asr.RLock()
  1932. defer asr.RUnlock()
  1933. return len(asr.allocations)
  1934. }
  1935. // MarshalJSON JSON-encodes the range
  1936. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  1937. asr.RLock()
  1938. asr.RUnlock()
  1939. return json.Marshal(asr.allocations)
  1940. }
  1941. // Slice copies the underlying slice of AllocationSets, maintaining order,
  1942. // and returns the copied slice.
  1943. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  1944. if asr == nil || asr.allocations == nil {
  1945. return nil
  1946. }
  1947. asr.RLock()
  1948. defer asr.RUnlock()
  1949. copy := []*AllocationSet{}
  1950. for _, as := range asr.allocations {
  1951. copy = append(copy, as.Clone())
  1952. }
  1953. return copy
  1954. }
  1955. // String represents the given AllocationSetRange as a string
  1956. func (asr *AllocationSetRange) String() string {
  1957. if asr == nil {
  1958. return "<nil>"
  1959. }
  1960. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  1961. }
  1962. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  1963. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  1964. // are sets with conflicting UTCOffsets (just returns the first).
  1965. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  1966. if asr.Length() == 0 {
  1967. return 0
  1968. }
  1969. as, err := asr.Get(0)
  1970. if err != nil {
  1971. return 0
  1972. }
  1973. return as.UTCOffset()
  1974. }
  1975. // Window returns the full window that the AllocationSetRange spans, from the
  1976. // start of the first AllocationSet to the end of the last one.
  1977. func (asr *AllocationSetRange) Window() Window {
  1978. if asr == nil || asr.Length() == 0 {
  1979. return NewWindow(nil, nil)
  1980. }
  1981. start := asr.allocations[0].Start()
  1982. end := asr.allocations[asr.Length()-1].End()
  1983. return NewWindow(&start, &end)
  1984. }