allocation.go 80 KB

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