allocation.go 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572
  1. package opencost
  2. import (
  3. "fmt"
  4. "math"
  5. "sort"
  6. "strings"
  7. "time"
  8. "github.com/opencost/opencost/core/pkg/filter"
  9. "github.com/opencost/opencost/core/pkg/filter/ast"
  10. "github.com/opencost/opencost/core/pkg/filter/matcher"
  11. "github.com/opencost/opencost/core/pkg/log"
  12. "github.com/opencost/opencost/core/pkg/util"
  13. "github.com/opencost/opencost/core/pkg/util/timeutil"
  14. "golang.org/x/exp/slices"
  15. )
  16. // TODO Clean-up use of IsEmpty; nil checks should be separated for safety.
  17. // TODO Consider making Allocation an interface, which is fulfilled by structs
  18. // like KubernetesAllocation, IdleAllocation, and ExternalAllocation.
  19. // ExternalSuffix indicates an external allocation
  20. const ExternalSuffix = "__external__"
  21. // IdleSuffix indicates an idle allocation property
  22. const IdleSuffix = "__idle__"
  23. // SharedSuffix indicates an shared allocation property
  24. const SharedSuffix = "__shared__"
  25. // UnallocatedSuffix indicates an unallocated allocation property
  26. const UnallocatedSuffix = "__unallocated__"
  27. // UnmountedSuffix indicated allocation to an unmounted resource (PV or LB)
  28. const UnmountedSuffix = "__unmounted__"
  29. // ShareWeighted indicates that a shared resource should be shared as a
  30. // proportion of the cost of the remaining allocations.
  31. const ShareWeighted = "__weighted__"
  32. // ShareEven indicates that a shared resource should be shared evenly across
  33. // all remaining allocations.
  34. const ShareEven = "__even__"
  35. // ShareNone indicates that a shareable resource should not be shared
  36. const ShareNone = "__none__"
  37. // Allocation is a unit of resource allocation and cost for a given window
  38. // of time and for a given kubernetes construct with its associated set of
  39. // properties.
  40. // TODO:CLEANUP consider dropping name in favor of just Allocation and an
  41. // Assets-style key() function for AllocationSet.
  42. type Allocation struct {
  43. Name string `json:"name"`
  44. Properties *AllocationProperties `json:"properties,omitempty"`
  45. Window Window `json:"window"`
  46. Start time.Time `json:"start"`
  47. End time.Time `json:"end"`
  48. CPUCoreHours float64 `json:"cpuCoreHours"`
  49. CPUCoreRequestAverage float64 `json:"cpuCoreRequestAverage"`
  50. CPUCoreUsageAverage float64 `json:"cpuCoreUsageAverage"`
  51. CPUCost float64 `json:"cpuCost"`
  52. CPUCostAdjustment float64 `json:"cpuCostAdjustment"`
  53. CPUCostIdle float64 `json:"cpuCostIdle"` //@bingen:field[ignore]
  54. GPUHours float64 `json:"gpuHours"`
  55. GPUCost float64 `json:"gpuCost"`
  56. GPUCostAdjustment float64 `json:"gpuCostAdjustment"`
  57. GPUCostIdle float64 `json:"gpuCostIdle"` //@bingen:field[ignore]
  58. NetworkTransferBytes float64 `json:"networkTransferBytes"`
  59. NetworkReceiveBytes float64 `json:"networkReceiveBytes"`
  60. NetworkCost float64 `json:"networkCost"`
  61. NetworkCrossZoneCost float64 `json:"networkCrossZoneCost"` // @bingen:field[version=16]
  62. NetworkCrossRegionCost float64 `json:"networkCrossRegionCost"` // @bingen:field[version=16]
  63. NetworkInternetCost float64 `json:"networkInternetCost"` // @bingen:field[version=16]
  64. NetworkCostAdjustment float64 `json:"networkCostAdjustment"`
  65. LoadBalancerCost float64 `json:"loadBalancerCost"`
  66. LoadBalancerCostAdjustment float64 `json:"loadBalancerCostAdjustment"`
  67. PVs PVAllocations `json:"pvs"`
  68. PVCostAdjustment float64 `json:"pvCostAdjustment"`
  69. RAMByteHours float64 `json:"ramByteHours"`
  70. RAMBytesRequestAverage float64 `json:"ramByteRequestAverage"`
  71. RAMBytesUsageAverage float64 `json:"ramByteUsageAverage"`
  72. RAMCost float64 `json:"ramCost"`
  73. RAMCostAdjustment float64 `json:"ramCostAdjustment"`
  74. RAMCostIdle float64 `json:"ramCostIdle"` //@bingen:field[ignore]
  75. SharedCost float64 `json:"sharedCost"`
  76. ExternalCost float64 `json:"externalCost"`
  77. // RawAllocationOnly is a pointer so if it is not present it will be
  78. // marshalled as null rather than as an object with Go default values.
  79. RawAllocationOnly *RawAllocationOnlyData `json:"rawAllocationOnly"`
  80. // ProportionalAssetResourceCost represents the per-resource costs of the
  81. // allocation as a percentage of the per-resource total cost of the
  82. // asset on which the allocation was run. It is optionally computed
  83. // and appended to an Allocation, and so by default is is nil.
  84. ProportionalAssetResourceCosts ProportionalAssetResourceCosts `json:"proportionalAssetResourceCosts"` //@bingen:field[ignore]
  85. SharedCostBreakdown SharedCostBreakdowns `json:"sharedCostBreakdown"` //@bingen:field[ignore]
  86. LoadBalancers LbAllocations `json:"LoadBalancers"` //@bingen:field[version=18]
  87. // UnmountedPVCost is used to track how much of the cost in PVs is for an
  88. // unmounted PV. It is not additive of PVCost() and need not be sent in API
  89. // responses.
  90. UnmountedPVCost float64 `json:"-"` //@bingen:field[ignore]
  91. GPURequestAverage float64 `json:"gpuRequestAverage"` //@bingen:field[version=22]
  92. GPUUsageAverage float64 `json:"gpuUsageAverage"` //@bingen:field[version=22]
  93. }
  94. type LbAllocations map[string]*LbAllocation
  95. func (orig LbAllocations) Clone() LbAllocations {
  96. if orig == nil {
  97. return nil
  98. }
  99. newAllocs := LbAllocations{}
  100. for key, lbAlloc := range orig {
  101. newAllocs[key] = &LbAllocation{
  102. Service: lbAlloc.Service,
  103. Cost: lbAlloc.Cost,
  104. Private: lbAlloc.Private,
  105. Ip: lbAlloc.Ip,
  106. Hours: lbAlloc.Hours,
  107. }
  108. }
  109. return newAllocs
  110. }
  111. type LbAllocation struct {
  112. Service string `json:"service"`
  113. Cost float64 `json:"cost"`
  114. Private bool `json:"private"`
  115. Ip string `json:"ip"` //@bingen:field[version=19]
  116. Hours float64 `json:"hours"` //@bingen:field[version=21]
  117. Adjustment float64 `json:"adjustment"` //@bingen:field[ignore]
  118. }
  119. func (lba *LbAllocation) SanitizeNaN() {
  120. if lba == nil {
  121. return
  122. }
  123. if math.IsNaN(lba.Cost) {
  124. log.DedupedWarningf(5, "LBAllocation: Unexpected NaN found for Cost service:%s", lba.Service)
  125. lba.Cost = 0
  126. }
  127. if math.IsNaN(lba.Hours) {
  128. log.DedupedWarningf(5, "LBAllocation: Unexpected NaN found for Hours service:%s", lba.Service)
  129. lba.Hours = 0
  130. }
  131. }
  132. // RawAllocationOnlyData is information that only belong in "raw" Allocations,
  133. // those which have not undergone aggregation, accumulation, or any other form
  134. // of combination to produce a new Allocation from other Allocations.
  135. //
  136. // Max usage data belongs here because computing the overall maximum from two
  137. // or more Allocations is a non-trivial operation that cannot be defined without
  138. // maintaining a large amount of state. Consider the following example:
  139. // _______________________________________________
  140. //
  141. // A1 Using 3 CPU ---- ----- ------
  142. // A2 Using 2 CPU ---- ----- ----
  143. // A3 Using 1 CPU --- --
  144. // _______________________________________________
  145. //
  146. // Time ---->
  147. //
  148. // The logical maximum CPU usage is 5, but this cannot be calculated iteratively,
  149. // which is how we calculate aggregations and accumulations of Allocations currently.
  150. // This becomes a problem I could call "maximum sum of overlapping intervals" and is
  151. // essentially a variant of an interval scheduling algorithm.
  152. //
  153. // If we had types to differentiate between regular Allocations and AggregatedAllocations
  154. // then this type would be unnecessary and its fields would go into the regular Allocation
  155. // and not in the AggregatedAllocation.
  156. type RawAllocationOnlyData struct {
  157. CPUCoreUsageMax float64 `json:"cpuCoreUsageMax"`
  158. RAMBytesUsageMax float64 `json:"ramByteUsageMax"`
  159. }
  160. // Clone returns a deep copy of the given RawAllocationOnlyData
  161. func (r *RawAllocationOnlyData) Clone() *RawAllocationOnlyData {
  162. if r == nil {
  163. return nil
  164. }
  165. return &RawAllocationOnlyData{
  166. CPUCoreUsageMax: r.CPUCoreUsageMax,
  167. RAMBytesUsageMax: r.RAMBytesUsageMax,
  168. }
  169. }
  170. // Equal returns true if the RawAllocationOnlyData is approximately equal
  171. func (r *RawAllocationOnlyData) Equal(that *RawAllocationOnlyData) bool {
  172. if r == nil && that == nil {
  173. return true
  174. }
  175. if r == nil || that == nil {
  176. return false
  177. }
  178. return util.IsApproximately(r.CPUCoreUsageMax, that.CPUCoreUsageMax) &&
  179. util.IsApproximately(r.RAMBytesUsageMax, that.RAMBytesUsageMax)
  180. }
  181. func (r *RawAllocationOnlyData) SanitizeNaN() {
  182. if r == nil {
  183. return
  184. }
  185. if math.IsNaN(r.CPUCoreUsageMax) {
  186. log.DedupedWarningf(5, "RawAllocationOnlyData: Unexpected NaN found for CPUCoreUsageMax")
  187. r.CPUCoreUsageMax = 0
  188. }
  189. if math.IsNaN(r.RAMBytesUsageMax) {
  190. log.DedupedWarningf(5, "RawAllocationOnlyData: Unexpected NaN found for RAMBytesUsageMax")
  191. r.RAMBytesUsageMax = 0
  192. }
  193. }
  194. // PVAllocations is a map of Disk Asset Identifiers to the
  195. // usage of them by an Allocation as recorded in a PVAllocation
  196. type PVAllocations map[PVKey]*PVAllocation
  197. // Clone creates a deep copy of a PVAllocations
  198. func (pv PVAllocations) Clone() PVAllocations {
  199. if pv == nil {
  200. return nil
  201. }
  202. clonePV := make(map[PVKey]*PVAllocation, len(pv))
  203. for k, v := range pv {
  204. clonePV[k] = &PVAllocation{
  205. ByteHours: v.ByteHours,
  206. Cost: v.Cost,
  207. ProviderID: v.ProviderID,
  208. }
  209. }
  210. return clonePV
  211. }
  212. // Add adds contents of that to the calling PVAllocations
  213. func (pv PVAllocations) Add(that PVAllocations) PVAllocations {
  214. apv := pv.Clone()
  215. if that != nil {
  216. if apv == nil {
  217. apv = PVAllocations{}
  218. }
  219. for pvKey, thatPVAlloc := range that {
  220. apvAlloc, ok := apv[pvKey]
  221. if !ok {
  222. apvAlloc = &PVAllocation{}
  223. }
  224. apvAlloc.Cost += thatPVAlloc.Cost
  225. apvAlloc.ByteHours += thatPVAlloc.ByteHours
  226. apv[pvKey] = apvAlloc
  227. if apvAlloc.ProviderID == thatPVAlloc.ProviderID {
  228. apv[pvKey].ProviderID = apvAlloc.ProviderID
  229. } else {
  230. apv[pvKey].ProviderID = ""
  231. }
  232. }
  233. }
  234. return apv
  235. }
  236. // Equal returns true if the two PVAllocations are equal in length and contain the same keys
  237. // and values.
  238. func (this PVAllocations) Equal(that PVAllocations) bool {
  239. if this == nil && that == nil {
  240. return true
  241. }
  242. if this == nil || that == nil {
  243. return false
  244. }
  245. if len(this) != len(that) {
  246. return false
  247. }
  248. for k, pv := range this {
  249. tv, ok := that[k]
  250. if !ok || !pv.Equal(tv) {
  251. return false
  252. }
  253. }
  254. return true
  255. }
  256. func (pvs PVAllocations) SanitizeNaN() {
  257. for _, pv := range pvs {
  258. pv.SanitizeNaN()
  259. }
  260. }
  261. // PVKey for identifying Disk type assets
  262. type PVKey struct {
  263. Cluster string `json:"cluster"`
  264. Name string `json:"name"`
  265. }
  266. func (pvk *PVKey) String() string {
  267. return fmt.Sprintf("cluster=%s:name=%s", pvk.Cluster, pvk.Name)
  268. }
  269. // FromString populates PVKey fields from string
  270. func (pvk *PVKey) FromString(key string) error {
  271. splitKey := strings.Split(key, ":")
  272. if len(splitKey) != 2 {
  273. return fmt.Errorf("PVKey string '%s' has the incorrect format", key)
  274. }
  275. pvk.Cluster = strings.TrimPrefix(splitKey[0], "cluster=")
  276. pvk.Name = strings.TrimPrefix(splitKey[1], "name=")
  277. return nil
  278. }
  279. // PVAllocation contains the byte hour usage
  280. // and cost of an Allocation for a single PV
  281. type PVAllocation struct {
  282. ByteHours float64 `json:"byteHours"`
  283. Cost float64 `json:"cost"`
  284. ProviderID string `json:"providerID"` // @bingen:field[version=20]
  285. Adjustment float64 `json:"adjustment"` //@bingen:field[ignore]
  286. }
  287. // Equal returns true if the two PVAllocation instances contain approximately the same
  288. // values.
  289. func (pva *PVAllocation) Equal(that *PVAllocation) bool {
  290. if pva == nil && that == nil {
  291. return true
  292. }
  293. if pva == nil || that == nil {
  294. return false
  295. }
  296. return util.IsApproximately(pva.ByteHours, that.ByteHours) &&
  297. util.IsApproximately(pva.Cost, that.Cost)
  298. }
  299. func (pva *PVAllocation) SanitizeNaN() {
  300. if pva == nil {
  301. return
  302. }
  303. if math.IsNaN(pva.ByteHours) {
  304. log.DedupedWarningf(5, "PVAllocation: Unexpected NaN found for ByteHours")
  305. pva.ByteHours = 0
  306. }
  307. if math.IsNaN(pva.Cost) {
  308. log.DedupedWarningf(5, "PVAllocation: Unexpected NaN found for Cost")
  309. pva.Cost = 0
  310. }
  311. }
  312. type ProportionalAssetResourceCost struct {
  313. Cluster string `json:"cluster"`
  314. Name string `json:"name,omitempty"`
  315. Type string `json:"type,omitempty"`
  316. ProviderID string `json:"providerID,omitempty"`
  317. CPUPercentage float64 `json:"cpuPercentage"`
  318. GPUPercentage float64 `json:"gpuPercentage"`
  319. RAMPercentage float64 `json:"ramPercentage"`
  320. LoadBalancerPercentage float64 `json:"loadBalancerPercentage"`
  321. PVPercentage float64 `json:"pvPercentage"`
  322. NodeResourceCostPercentage float64 `json:"nodeResourceCostPercentage"`
  323. GPUTotalCost float64 `json:"-"`
  324. GPUProportionalCost float64 `json:"-"`
  325. CPUTotalCost float64 `json:"-"`
  326. CPUProportionalCost float64 `json:"-"`
  327. RAMTotalCost float64 `json:"-"`
  328. RAMProportionalCost float64 `json:"-"`
  329. LoadBalancerProportionalCost float64 `json:"-"`
  330. LoadBalancerTotalCost float64 `json:"-"`
  331. PVProportionalCost float64 `json:"-"`
  332. PVTotalCost float64 `json:"-"`
  333. }
  334. func (parc ProportionalAssetResourceCost) Key(insertByName bool) string {
  335. if insertByName {
  336. return parc.Cluster + "," + parc.Name
  337. } else {
  338. return parc.Cluster
  339. }
  340. }
  341. type ProportionalAssetResourceCosts map[string]ProportionalAssetResourceCost
  342. func (parcs ProportionalAssetResourceCosts) Clone() ProportionalAssetResourceCosts {
  343. cloned := ProportionalAssetResourceCosts{}
  344. for key, parc := range parcs {
  345. cloned[key] = parc
  346. }
  347. return cloned
  348. }
  349. func (parcs ProportionalAssetResourceCosts) Insert(parc ProportionalAssetResourceCost, insertByName bool) {
  350. if !insertByName {
  351. parc.Name = ""
  352. parc.Type = ""
  353. parc.ProviderID = ""
  354. }
  355. if curr, ok := parcs[parc.Key(insertByName)]; ok {
  356. toInsert := ProportionalAssetResourceCost{
  357. Name: curr.Name,
  358. Type: curr.Type,
  359. Cluster: curr.Cluster,
  360. ProviderID: curr.ProviderID,
  361. CPUProportionalCost: curr.CPUProportionalCost + parc.CPUProportionalCost,
  362. RAMProportionalCost: curr.RAMProportionalCost + parc.RAMProportionalCost,
  363. GPUProportionalCost: curr.GPUProportionalCost + parc.GPUProportionalCost,
  364. PVProportionalCost: curr.PVProportionalCost + parc.PVProportionalCost,
  365. LoadBalancerProportionalCost: curr.LoadBalancerProportionalCost + parc.LoadBalancerProportionalCost,
  366. }
  367. ComputePercentages(&toInsert)
  368. parcs[parc.Key(insertByName)] = toInsert
  369. } else {
  370. ComputePercentages(&parc)
  371. parcs[parc.Key(insertByName)] = parc
  372. }
  373. }
  374. func ComputePercentages(toInsert *ProportionalAssetResourceCost) {
  375. totalNodeCost := toInsert.RAMTotalCost + toInsert.CPUTotalCost + toInsert.GPUTotalCost
  376. if toInsert.CPUTotalCost > 0 {
  377. toInsert.CPUPercentage = toInsert.CPUProportionalCost / toInsert.CPUTotalCost
  378. }
  379. if toInsert.GPUTotalCost > 0 {
  380. toInsert.GPUPercentage = toInsert.GPUProportionalCost / toInsert.GPUTotalCost
  381. }
  382. if toInsert.LoadBalancerTotalCost > 0 {
  383. toInsert.LoadBalancerPercentage = toInsert.LoadBalancerProportionalCost / toInsert.LoadBalancerTotalCost
  384. }
  385. if toInsert.RAMTotalCost > 0 {
  386. toInsert.RAMPercentage = toInsert.RAMProportionalCost / toInsert.RAMTotalCost
  387. }
  388. if toInsert.PVTotalCost > 0 {
  389. toInsert.PVPercentage = toInsert.PVProportionalCost / toInsert.PVTotalCost
  390. }
  391. ramFraction := toInsert.RAMTotalCost / totalNodeCost
  392. if ramFraction != ramFraction || ramFraction < 0 {
  393. ramFraction = 0
  394. }
  395. cpuFraction := toInsert.CPUTotalCost / totalNodeCost
  396. if cpuFraction != cpuFraction || cpuFraction < 0 {
  397. cpuFraction = 0
  398. }
  399. gpuFraction := toInsert.GPUTotalCost / totalNodeCost
  400. if gpuFraction != gpuFraction || gpuFraction < 0 {
  401. gpuFraction = 0
  402. }
  403. toInsert.NodeResourceCostPercentage = (toInsert.RAMPercentage * ramFraction) +
  404. (toInsert.CPUPercentage * cpuFraction) + (toInsert.GPUPercentage * gpuFraction)
  405. }
  406. func (parcs ProportionalAssetResourceCosts) Add(that ProportionalAssetResourceCosts) {
  407. for _, parc := range that {
  408. // if name field is empty, we know this is a cluster level PARC aggregation
  409. insertByName := true
  410. if parc.Name == "" {
  411. insertByName = false
  412. }
  413. parcs.Insert(parc, insertByName)
  414. }
  415. }
  416. func (parcs ProportionalAssetResourceCosts) SanitizeNaN() {
  417. for key, parc := range parcs {
  418. if math.IsNaN(parc.CPUPercentage) {
  419. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for CPUPercentage name:%s", parc.Name)
  420. parc.CPUPercentage = 0
  421. }
  422. if math.IsNaN(parc.GPUPercentage) {
  423. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for GPUPercentage name:%s", parc.Name)
  424. parc.GPUPercentage = 0
  425. }
  426. if math.IsNaN(parc.RAMPercentage) {
  427. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for RAMPercentage name:%s", parc.Name)
  428. parc.RAMPercentage = 0
  429. }
  430. if math.IsNaN(parc.LoadBalancerPercentage) {
  431. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for LoadBalancerPercentage name:%s", parc.Name)
  432. parc.LoadBalancerPercentage = 0
  433. }
  434. if math.IsNaN(parc.PVPercentage) {
  435. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for PVPercentage name:%s", parc.Name)
  436. parc.PVPercentage = 0
  437. }
  438. if math.IsNaN(parc.NodeResourceCostPercentage) {
  439. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for NodeResourceCostPercentage name:%s", parc.Name)
  440. parc.NodeResourceCostPercentage = 0
  441. }
  442. if math.IsNaN(parc.GPUTotalCost) {
  443. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for GPUTotalCost name:%s", parc.Name)
  444. parc.GPUTotalCost = 0
  445. }
  446. if math.IsNaN(parc.GPUProportionalCost) {
  447. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for GPUProportionalCost name:%s", parc.Name)
  448. parc.GPUProportionalCost = 0
  449. }
  450. if math.IsNaN(parc.CPUTotalCost) {
  451. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for CPUTotalCost name:%s", parc.Name)
  452. parc.CPUTotalCost = 0
  453. }
  454. if math.IsNaN(parc.CPUProportionalCost) {
  455. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for CPUProportionalCost name:%s", parc.Name)
  456. parc.CPUProportionalCost = 0
  457. }
  458. if math.IsNaN(parc.RAMTotalCost) {
  459. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for RAMTotalCost name:%s", parc.Name)
  460. parc.RAMTotalCost = 0
  461. }
  462. if math.IsNaN(parc.RAMProportionalCost) {
  463. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for RAMProportionalCost name:%s", parc.Name)
  464. parc.RAMProportionalCost = 0
  465. }
  466. if math.IsNaN(parc.LoadBalancerProportionalCost) {
  467. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for LoadBalancerProportionalCost name:%s", parc.Name)
  468. parc.LoadBalancerProportionalCost = 0
  469. }
  470. if math.IsNaN(parc.LoadBalancerTotalCost) {
  471. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for LoadBalancerTotalCost name:%s", parc.Name)
  472. parc.LoadBalancerTotalCost = 0
  473. }
  474. if math.IsNaN(parc.PVProportionalCost) {
  475. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for PVProportionalCost name:%s", parc.Name)
  476. parc.PVProportionalCost = 0
  477. }
  478. if math.IsNaN(parc.PVTotalCost) {
  479. log.DedupedWarningf(5, "ProportionalAssetResourceCosts: Unexpected NaN found for PVTotalCost name:%s", parc.Name)
  480. parc.PVTotalCost = 0
  481. }
  482. parcs[key] = parc
  483. }
  484. }
  485. type SharedCostBreakdown struct {
  486. Name string `json:"name"`
  487. TotalCost float64 `json:"totalCost"`
  488. CPUCost float64 `json:"cpuCost,omitempty"`
  489. GPUCost float64 `json:"gpuCost,omitempty"`
  490. RAMCost float64 `json:"ramCost,omitempty"`
  491. PVCost float64 `json:"pvCost,omitempty"`
  492. NetworkCost float64 `json:"networkCost,omitempty"`
  493. LBCost float64 `json:"loadBalancerCost,omitempty"`
  494. ExternalCost float64 `json:"externalCost,omitempty"`
  495. }
  496. type SharedCostBreakdowns map[string]SharedCostBreakdown
  497. func (scbs SharedCostBreakdowns) Clone() SharedCostBreakdowns {
  498. cloned := SharedCostBreakdowns{}
  499. for key, scb := range scbs {
  500. cloned[key] = scb
  501. }
  502. return cloned
  503. }
  504. func (scbs SharedCostBreakdowns) Insert(scb SharedCostBreakdown) {
  505. if curr, ok := scbs[scb.Name]; ok {
  506. scbs[scb.Name] = SharedCostBreakdown{
  507. Name: curr.Name,
  508. TotalCost: curr.TotalCost + scb.TotalCost,
  509. CPUCost: curr.CPUCost + scb.CPUCost,
  510. GPUCost: curr.GPUCost + scb.GPUCost,
  511. RAMCost: curr.RAMCost + scb.RAMCost,
  512. PVCost: curr.PVCost + scb.PVCost,
  513. NetworkCost: curr.NetworkCost + scb.NetworkCost,
  514. LBCost: curr.LBCost + scb.LBCost,
  515. ExternalCost: curr.ExternalCost + scb.ExternalCost,
  516. }
  517. } else {
  518. scbs[scb.Name] = scb
  519. }
  520. }
  521. func (scbs SharedCostBreakdowns) Add(that SharedCostBreakdowns) {
  522. for _, scb := range that {
  523. scbs.Insert(scb)
  524. }
  525. }
  526. func (scbs SharedCostBreakdowns) SanitizeNaN() {
  527. for key, scb := range scbs {
  528. if math.IsNaN(scb.CPUCost) {
  529. log.DedupedWarningf(5, "SharedCostBreakdown: Unexpected NaN found for CPUCost name:%s", scb.Name)
  530. scb.CPUCost = 0
  531. }
  532. if math.IsNaN(scb.GPUCost) {
  533. log.DedupedWarningf(5, "SharedCostBreakdown: Unexpected NaN found for GPUCost name:%s", scb.Name)
  534. scb.GPUCost = 0
  535. }
  536. if math.IsNaN(scb.RAMCost) {
  537. log.DedupedWarningf(5, "SharedCostBreakdown: Unexpected NaN found for RAMCost name:%s", scb.Name)
  538. scb.RAMCost = 0
  539. }
  540. if math.IsNaN(scb.PVCost) {
  541. log.DedupedWarningf(5, "SharedCostBreakdown: Unexpected NaN found for PVCost name:%s", scb.Name)
  542. scb.PVCost = 0
  543. }
  544. if math.IsNaN(scb.NetworkCost) {
  545. log.DedupedWarningf(5, "SharedCostBreakdown: Unexpected NaN found for NetworkCost name:%s", scb.Name)
  546. scb.NetworkCost = 0
  547. }
  548. if math.IsNaN(scb.LBCost) {
  549. log.DedupedWarningf(5, "SharedCostBreakdown: Unexpected NaN found for LBCost name:%s", scb.Name)
  550. scb.LBCost = 0
  551. }
  552. if math.IsNaN(scb.ExternalCost) {
  553. log.DedupedWarningf(5, "SharedCostBreakdown: Unexpected NaN found for ExternalCost name:%s", scb.Name)
  554. scb.ExternalCost = 0
  555. }
  556. if math.IsNaN(scb.TotalCost) {
  557. log.DedupedWarningf(5, "SharedCostBreakdown: Unexpected NaN found for TotalCost name:%s", scb.Name)
  558. scb.TotalCost = 0
  559. }
  560. scbs[key] = scb
  561. }
  562. }
  563. // GetWindow returns the window of the struct
  564. func (a *Allocation) GetWindow() Window {
  565. return a.Window
  566. }
  567. // AllocationMatchFunc is a function that can be used to match Allocations by
  568. // returning true for any given Allocation if a condition is met.
  569. type AllocationMatchFunc func(*Allocation) bool
  570. // Add returns the result of summing the two given Allocations, which sums the
  571. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  572. // the two original Allocations are mutated in the process.
  573. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  574. if a == nil {
  575. return that.Clone(), nil
  576. }
  577. if that == nil {
  578. return a.Clone(), nil
  579. }
  580. // Note: no need to clone "that", as add only mutates the receiver
  581. agg := a.Clone()
  582. agg.add(that)
  583. return agg, nil
  584. }
  585. // Clone returns a deep copy of the given Allocation
  586. func (a *Allocation) Clone() *Allocation {
  587. if a == nil {
  588. return nil
  589. }
  590. return &Allocation{
  591. Name: a.Name,
  592. Properties: a.Properties.Clone(),
  593. Window: a.Window.Clone(),
  594. Start: a.Start,
  595. End: a.End,
  596. CPUCoreHours: a.CPUCoreHours,
  597. CPUCoreRequestAverage: a.CPUCoreRequestAverage,
  598. CPUCoreUsageAverage: a.CPUCoreUsageAverage,
  599. CPUCost: a.CPUCost,
  600. CPUCostIdle: a.CPUCostIdle,
  601. CPUCostAdjustment: a.CPUCostAdjustment,
  602. GPUHours: a.GPUHours,
  603. GPURequestAverage: a.GPURequestAverage,
  604. GPUUsageAverage: a.GPUUsageAverage,
  605. GPUCost: a.GPUCost,
  606. GPUCostIdle: a.GPUCostIdle,
  607. GPUCostAdjustment: a.GPUCostAdjustment,
  608. NetworkTransferBytes: a.NetworkTransferBytes,
  609. NetworkReceiveBytes: a.NetworkReceiveBytes,
  610. NetworkCost: a.NetworkCost,
  611. NetworkCrossZoneCost: a.NetworkCrossZoneCost,
  612. NetworkCrossRegionCost: a.NetworkCrossRegionCost,
  613. NetworkInternetCost: a.NetworkInternetCost,
  614. NetworkCostAdjustment: a.NetworkCostAdjustment,
  615. LoadBalancerCost: a.LoadBalancerCost,
  616. LoadBalancerCostAdjustment: a.LoadBalancerCostAdjustment,
  617. PVs: a.PVs.Clone(),
  618. PVCostAdjustment: a.PVCostAdjustment,
  619. RAMByteHours: a.RAMByteHours,
  620. RAMBytesRequestAverage: a.RAMBytesRequestAverage,
  621. RAMBytesUsageAverage: a.RAMBytesUsageAverage,
  622. RAMCost: a.RAMCost,
  623. RAMCostIdle: a.RAMCostIdle,
  624. RAMCostAdjustment: a.RAMCostAdjustment,
  625. SharedCost: a.SharedCost,
  626. ExternalCost: a.ExternalCost,
  627. RawAllocationOnly: a.RawAllocationOnly.Clone(),
  628. ProportionalAssetResourceCosts: a.ProportionalAssetResourceCosts.Clone(),
  629. SharedCostBreakdown: a.SharedCostBreakdown.Clone(),
  630. LoadBalancers: a.LoadBalancers.Clone(),
  631. UnmountedPVCost: a.UnmountedPVCost,
  632. }
  633. }
  634. // Equal returns true if the values held in the given Allocation precisely
  635. // match those of the receiving Allocation. nil does not match nil. Floating
  636. // point values need to match according to util.IsApproximately, which accounts
  637. // for small, reasonable floating point error margins.
  638. func (a *Allocation) Equal(that *Allocation) bool {
  639. if a == nil || that == nil {
  640. return false
  641. }
  642. if a.Name != that.Name {
  643. return false
  644. }
  645. if !a.Properties.Equal(that.Properties) {
  646. return false
  647. }
  648. if !a.Window.Equal(that.Window) {
  649. return false
  650. }
  651. if !a.Start.Equal(that.Start) {
  652. return false
  653. }
  654. if !a.End.Equal(that.End) {
  655. return false
  656. }
  657. if !util.IsApproximately(a.CPUCoreHours, that.CPUCoreHours) {
  658. return false
  659. }
  660. if !util.IsApproximately(a.CPUCost, that.CPUCost) {
  661. return false
  662. }
  663. if !util.IsApproximately(a.CPUCostIdle, that.CPUCostIdle) {
  664. return false
  665. }
  666. if !util.IsApproximately(a.CPUCostAdjustment, that.CPUCostAdjustment) {
  667. return false
  668. }
  669. if !util.IsApproximately(a.GPUHours, that.GPUHours) {
  670. return false
  671. }
  672. if !util.IsApproximately(a.GPUCost, that.GPUCost) {
  673. return false
  674. }
  675. if !util.IsApproximately(a.GPUCostIdle, that.GPUCostIdle) {
  676. return false
  677. }
  678. if !util.IsApproximately(a.GPUCostAdjustment, that.GPUCostAdjustment) {
  679. return false
  680. }
  681. if !util.IsApproximately(a.NetworkTransferBytes, that.NetworkTransferBytes) {
  682. return false
  683. }
  684. if !util.IsApproximately(a.NetworkReceiveBytes, that.NetworkReceiveBytes) {
  685. return false
  686. }
  687. if !util.IsApproximately(a.NetworkCost, that.NetworkCost) {
  688. return false
  689. }
  690. if !util.IsApproximately(a.NetworkCrossZoneCost, that.NetworkCrossZoneCost) {
  691. return false
  692. }
  693. if !util.IsApproximately(a.NetworkCrossRegionCost, that.NetworkCrossRegionCost) {
  694. return false
  695. }
  696. if !util.IsApproximately(a.NetworkInternetCost, that.NetworkInternetCost) {
  697. return false
  698. }
  699. if !util.IsApproximately(a.NetworkCostAdjustment, that.NetworkCostAdjustment) {
  700. return false
  701. }
  702. if !util.IsApproximately(a.LoadBalancerCost, that.LoadBalancerCost) {
  703. return false
  704. }
  705. if !util.IsApproximately(a.LoadBalancerCostAdjustment, that.LoadBalancerCostAdjustment) {
  706. return false
  707. }
  708. if !util.IsApproximately(a.PVCostAdjustment, that.PVCostAdjustment) {
  709. return false
  710. }
  711. if !util.IsApproximately(a.RAMByteHours, that.RAMByteHours) {
  712. return false
  713. }
  714. if !util.IsApproximately(a.RAMCost, that.RAMCost) {
  715. return false
  716. }
  717. if !util.IsApproximately(a.RAMCostIdle, that.RAMCostIdle) {
  718. return false
  719. }
  720. if !util.IsApproximately(a.RAMCostAdjustment, that.RAMCostAdjustment) {
  721. return false
  722. }
  723. if !util.IsApproximately(a.SharedCost, that.SharedCost) {
  724. return false
  725. }
  726. if !util.IsApproximately(a.ExternalCost, that.ExternalCost) {
  727. return false
  728. }
  729. if !a.RawAllocationOnly.Equal(that.RawAllocationOnly) {
  730. return false
  731. }
  732. if !a.PVs.Equal(that.PVs) {
  733. return false
  734. }
  735. if !util.IsApproximately(a.UnmountedPVCost, that.UnmountedPVCost) {
  736. return false
  737. }
  738. return true
  739. }
  740. // TotalCost is the total cost of the Allocation including adjustments
  741. func (a *Allocation) TotalCost() float64 {
  742. if a == nil {
  743. return 0.0
  744. }
  745. return a.CPUTotalCost() + a.GPUTotalCost() + a.RAMTotalCost() + a.PVTotalCost() + a.NetworkTotalCost() + a.LBTotalCost() + a.SharedTotalCost() + a.ExternalCost
  746. }
  747. // CPUTotalCost calculates total CPU cost of Allocation including adjustment
  748. func (a *Allocation) CPUTotalCost() float64 {
  749. if a == nil {
  750. return 0.0
  751. }
  752. return a.CPUCost + a.CPUCostAdjustment
  753. }
  754. // GPUTotalCost calculates total GPU cost of Allocation including adjustment
  755. func (a *Allocation) GPUTotalCost() float64 {
  756. if a == nil {
  757. return 0.0
  758. }
  759. return a.GPUCost + a.GPUCostAdjustment
  760. }
  761. // RAMTotalCost calculates total RAM cost of Allocation including adjustment
  762. func (a *Allocation) RAMTotalCost() float64 {
  763. if a == nil {
  764. return 0.0
  765. }
  766. return a.RAMCost + a.RAMCostAdjustment
  767. }
  768. // PVTotalCost calculates total PV cost of Allocation including adjustment
  769. func (a *Allocation) PVTotalCost() float64 {
  770. if a == nil {
  771. return 0.0
  772. }
  773. return a.PVCost() + a.PVCostAdjustment
  774. }
  775. // NetworkTotalCost calculates total Network cost of Allocation including adjustment
  776. func (a *Allocation) NetworkTotalCost() float64 {
  777. if a == nil {
  778. return 0.0
  779. }
  780. return a.NetworkCost + a.NetworkCostAdjustment
  781. }
  782. // LBTotalCost calculates total LB cost of Allocation including adjustment
  783. // TODO deprecate
  784. func (a *Allocation) LBTotalCost() float64 {
  785. return a.LoadBalancerTotalCost()
  786. }
  787. // LoadBalancerTotalCost calculates total LB cost of Allocation including adjustment
  788. func (a *Allocation) LoadBalancerTotalCost() float64 {
  789. if a == nil {
  790. return 0.0
  791. }
  792. return a.LoadBalancerCost + a.LoadBalancerCostAdjustment
  793. }
  794. // SharedTotalCost calculates total shared cost of Allocation including adjustment
  795. func (a *Allocation) SharedTotalCost() float64 {
  796. if a == nil {
  797. return 0.0
  798. }
  799. return a.SharedCost
  800. }
  801. // PVCost calculate cumulative cost of all PVs that Allocation is attached to
  802. func (a *Allocation) PVCost() float64 {
  803. if a == nil {
  804. return 0.0
  805. }
  806. cost := 0.0
  807. for _, pv := range a.PVs {
  808. cost += pv.Cost
  809. }
  810. return cost
  811. }
  812. // PVByteHours calculate cumulative ByteHours of all PVs that Allocation is attached to
  813. func (a *Allocation) PVByteHours() float64 {
  814. if a == nil {
  815. return 0.0
  816. }
  817. byteHours := 0.0
  818. for _, pv := range a.PVs {
  819. byteHours += pv.ByteHours
  820. }
  821. return byteHours
  822. }
  823. // CPUEfficiency is the ratio of usage to request. If there is no request and
  824. // no usage or cost, then efficiency is zero. If there is no request, but there
  825. // is usage or cost, then efficiency is 100%.
  826. func (a *Allocation) CPUEfficiency() float64 {
  827. if a == nil {
  828. return 0.0
  829. }
  830. if a.CPUCoreRequestAverage > 0 {
  831. return a.CPUCoreUsageAverage / a.CPUCoreRequestAverage
  832. }
  833. if a.CPUCoreUsageAverage == 0.0 || a.CPUTotalCost() == 0.0 {
  834. return 0.0
  835. }
  836. return 1.0
  837. }
  838. // RAMEfficiency is the ratio of usage to request. If there is no request and
  839. // no usage or cost, then efficiency is zero. If there is no request, but there
  840. // is usage or cost, then efficiency is 100%.
  841. func (a *Allocation) RAMEfficiency() float64 {
  842. if a == nil {
  843. return 0.0
  844. }
  845. if a.RAMBytesRequestAverage > 0 {
  846. return a.RAMBytesUsageAverage / a.RAMBytesRequestAverage
  847. }
  848. if a.RAMBytesUsageAverage == 0.0 || a.RAMTotalCost() == 0.0 {
  849. return 0.0
  850. }
  851. return 1.0
  852. }
  853. // GPUEfficiency is the ratio of usage to request. Note that, without the NVIDIA
  854. // DCGM exporter providing Prometheus with usage metrics, this will always be
  855. // zero, as GPUUsageAverage will be zero (the default value).
  856. func (a *Allocation) GPUEfficiency() float64 {
  857. if a == nil {
  858. return 0.0
  859. }
  860. if a.GPURequestAverage > 0 && a.GPUUsageAverage > 0 {
  861. return a.GPUUsageAverage / a.GPURequestAverage
  862. }
  863. if a.GPUUsageAverage == 0.0 || a.GPUTotalCost() == 0.0 {
  864. return 0.0
  865. }
  866. return 1.0
  867. }
  868. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  869. // there is no cost at all, then efficiency is zero.
  870. func (a *Allocation) TotalEfficiency() float64 {
  871. if a == nil {
  872. return 0.0
  873. }
  874. if a.RAMTotalCost()+a.CPUTotalCost() > 0 {
  875. ramCostEff := a.RAMEfficiency() * a.RAMTotalCost()
  876. cpuCostEff := a.CPUEfficiency() * a.CPUTotalCost()
  877. return (ramCostEff + cpuCostEff) / (a.CPUTotalCost() + a.RAMTotalCost())
  878. }
  879. return 0.0
  880. }
  881. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  882. func (a *Allocation) CPUCores() float64 {
  883. if a.Minutes() <= 0.0 {
  884. return 0.0
  885. }
  886. return a.CPUCoreHours / (a.Minutes() / 60.0)
  887. }
  888. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  889. func (a *Allocation) RAMBytes() float64 {
  890. if a.Minutes() <= 0.0 {
  891. return 0.0
  892. }
  893. return a.RAMByteHours / (a.Minutes() / 60.0)
  894. }
  895. // GPUs converts the Allocation's GPUHours into average GPUs
  896. func (a *Allocation) GPUs() float64 {
  897. if a.Minutes() <= 0.0 {
  898. return 0.0
  899. }
  900. return a.GPUHours / (a.Minutes() / 60.0)
  901. }
  902. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  903. func (a *Allocation) PVBytes() float64 {
  904. if a.Minutes() <= 0.0 {
  905. return 0.0
  906. }
  907. return a.PVByteHours() / (a.Minutes() / 60.0)
  908. }
  909. // ResetAdjustments sets all cost adjustment fields to zero
  910. func (a *Allocation) ResetAdjustments() {
  911. if a == nil {
  912. return
  913. }
  914. a.CPUCostAdjustment = 0.0
  915. a.GPUCostAdjustment = 0.0
  916. a.RAMCostAdjustment = 0.0
  917. a.PVCostAdjustment = 0.0
  918. a.NetworkCostAdjustment = 0.0
  919. a.LoadBalancerCostAdjustment = 0.0
  920. }
  921. // Resolution returns the duration of time covered by the Allocation
  922. func (a *Allocation) Resolution() time.Duration {
  923. return a.End.Sub(a.Start)
  924. }
  925. // IsAggregated is true if the given Allocation has been aggregated, which we
  926. // define by a lack of AllocationProperties.
  927. func (a *Allocation) IsAggregated() bool {
  928. return a == nil || a.Properties == nil
  929. }
  930. // IsExternal is true if the given Allocation represents external costs.
  931. func (a *Allocation) IsExternal() bool {
  932. if a == nil {
  933. return false
  934. }
  935. return strings.Contains(a.Name, ExternalSuffix)
  936. }
  937. // IsIdle is true if the given Allocation represents idle costs.
  938. func (a *Allocation) IsIdle() bool {
  939. if a == nil {
  940. return false
  941. }
  942. return strings.Contains(a.Name, IdleSuffix)
  943. }
  944. // IsUnallocated is true if the given Allocation represents unallocated costs.
  945. func (a *Allocation) IsUnallocated() bool {
  946. if a == nil {
  947. return false
  948. }
  949. return strings.Contains(a.Name, UnallocatedSuffix)
  950. }
  951. // IsUnmounted is true if the given Allocation represents unmounted volume costs.
  952. func (a *Allocation) IsUnmounted() bool {
  953. if a == nil {
  954. return false
  955. }
  956. return strings.Contains(a.Name, UnmountedSuffix)
  957. }
  958. // Minutes returns the number of minutes the Allocation represents, as defined
  959. // by the difference between the end and start times.
  960. func (a *Allocation) Minutes() float64 {
  961. if a == nil {
  962. return 0.0
  963. }
  964. return a.End.Sub(a.Start).Minutes()
  965. }
  966. // SetUnmountedPVCost determines if the Allocation is unmounted and, if so, it
  967. // sets the UnmountedPVCost field appropriately.
  968. func (a *Allocation) SetUnmountedPVCost() float64 {
  969. if a == nil {
  970. return 0.0
  971. }
  972. if a.IsUnmounted() {
  973. a.UnmountedPVCost = a.PVTotalCost()
  974. return a.UnmountedPVCost
  975. }
  976. return 0.0
  977. }
  978. // Share adds the TotalCost of the given Allocation to the SharedCost of the
  979. // receiving Allocation. No Start, End, Window, or AllocationProperties are considered.
  980. // Neither Allocation is mutated; a new Allocation is always returned.
  981. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  982. if that == nil {
  983. return a.Clone(), nil
  984. }
  985. if a == nil {
  986. return nil, fmt.Errorf("cannot share with nil Allocation")
  987. }
  988. agg := a.Clone()
  989. agg.SharedCost += that.TotalCost()
  990. return agg, nil
  991. }
  992. // String represents the given Allocation as a string
  993. func (a *Allocation) String() string {
  994. if a == nil {
  995. return "<nil>"
  996. }
  997. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost())
  998. }
  999. func (a *Allocation) add(that *Allocation) {
  1000. if a == nil {
  1001. log.Warnf("Allocation.AggregateBy: trying to add a nil receiver")
  1002. return
  1003. }
  1004. // Generate keys for each allocation to allow for special logic to set the controller
  1005. // in the case of keys matching but controllers not matching.
  1006. aggByForKey := []string{"cluster", "node", "namespace", "pod", "container"}
  1007. leftKey := a.generateKey(aggByForKey, nil)
  1008. rightKey := that.generateKey(aggByForKey, nil)
  1009. leftProperties := a.Properties
  1010. rightProperties := that.Properties
  1011. // Preserve string properties that are matching between the two allocations
  1012. a.Properties = a.Properties.Intersection(that.Properties)
  1013. // If both Allocations have ProportionalAssetResourceCosts, then
  1014. // add those from the given Allocation into the receiver.
  1015. if a.ProportionalAssetResourceCosts != nil || that.ProportionalAssetResourceCosts != nil {
  1016. // init empty PARCs if either operand has nil PARCs
  1017. if a.ProportionalAssetResourceCosts == nil {
  1018. a.ProportionalAssetResourceCosts = ProportionalAssetResourceCosts{}
  1019. }
  1020. if that.ProportionalAssetResourceCosts == nil {
  1021. that.ProportionalAssetResourceCosts = ProportionalAssetResourceCosts{}
  1022. }
  1023. a.ProportionalAssetResourceCosts.Add(that.ProportionalAssetResourceCosts)
  1024. }
  1025. // If both Allocations have SharedCostBreakdowns, then
  1026. // add those from the given Allocation into the receiver.
  1027. if a.SharedCostBreakdown != nil || that.SharedCostBreakdown != nil {
  1028. if a.SharedCostBreakdown == nil {
  1029. a.SharedCostBreakdown = SharedCostBreakdowns{}
  1030. }
  1031. if that.SharedCostBreakdown == nil {
  1032. that.SharedCostBreakdown = SharedCostBreakdowns{}
  1033. }
  1034. a.SharedCostBreakdown.Add(that.SharedCostBreakdown)
  1035. }
  1036. // Overwrite regular intersection logic for the controller name property in the
  1037. // case that the Allocation keys are the same but the controllers are not.
  1038. if leftKey == rightKey &&
  1039. leftProperties != nil &&
  1040. rightProperties != nil &&
  1041. leftProperties.Controller != rightProperties.Controller {
  1042. if leftProperties.Controller == "" {
  1043. a.Properties.Controller = rightProperties.Controller
  1044. } else if rightProperties.Controller == "" {
  1045. a.Properties.Controller = leftProperties.Controller
  1046. } else {
  1047. controllers := []string{
  1048. leftProperties.Controller,
  1049. rightProperties.Controller,
  1050. }
  1051. sort.Strings(controllers)
  1052. a.Properties.Controller = controllers[0]
  1053. }
  1054. }
  1055. // Expand the window to encompass both Allocations
  1056. a.Window = a.Window.Expand(that.Window)
  1057. // Sum non-cumulative fields by turning them into cumulative, adding them,
  1058. // and then converting them back into averages after minutes have been
  1059. // combined (just below).
  1060. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  1061. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  1062. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  1063. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  1064. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  1065. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  1066. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  1067. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  1068. gpuReqMins := a.GPURequestAverage * a.Minutes()
  1069. gpuReqMins += that.GPURequestAverage * that.Minutes()
  1070. gpuUseMins := a.GPUUsageAverage * a.Minutes()
  1071. gpuUseMins += that.GPUUsageAverage * that.Minutes()
  1072. // Expand Start and End to be the "max" of among the given Allocations
  1073. if that.Start.Before(a.Start) {
  1074. a.Start = that.Start
  1075. }
  1076. if that.End.After(a.End) {
  1077. a.End = that.End
  1078. }
  1079. // Convert cumulative request and usage back into rates
  1080. // TODO:TEST write a unit test that fails if this is done incorrectly
  1081. if a.Minutes() > 0 {
  1082. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  1083. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  1084. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  1085. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  1086. a.GPURequestAverage = gpuReqMins / a.Minutes()
  1087. a.GPUUsageAverage = gpuUseMins / a.Minutes()
  1088. } else {
  1089. a.CPUCoreRequestAverage = 0.0
  1090. a.CPUCoreUsageAverage = 0.0
  1091. a.RAMBytesRequestAverage = 0.0
  1092. a.RAMBytesUsageAverage = 0.0
  1093. a.GPURequestAverage = 0.0
  1094. a.GPUUsageAverage = 0.0
  1095. }
  1096. // Sum all cumulative resource fields
  1097. a.CPUCoreHours += that.CPUCoreHours
  1098. a.GPUHours += that.GPUHours
  1099. a.RAMByteHours += that.RAMByteHours
  1100. a.NetworkTransferBytes += that.NetworkTransferBytes
  1101. a.NetworkReceiveBytes += that.NetworkReceiveBytes
  1102. // Sum all cumulative cost fields
  1103. a.CPUCost += that.CPUCost
  1104. a.GPUCost += that.GPUCost
  1105. a.RAMCost += that.RAMCost
  1106. a.CPUCostIdle += that.CPUCostIdle
  1107. a.GPUCostIdle += that.GPUCostIdle
  1108. a.RAMCostIdle += that.RAMCostIdle
  1109. a.NetworkCost += that.NetworkCost
  1110. a.NetworkCrossZoneCost += that.NetworkCrossZoneCost
  1111. a.NetworkCrossRegionCost += that.NetworkCrossRegionCost
  1112. a.NetworkInternetCost += that.NetworkInternetCost
  1113. a.LoadBalancerCost += that.LoadBalancerCost
  1114. a.SharedCost += that.SharedCost
  1115. a.ExternalCost += that.ExternalCost
  1116. a.UnmountedPVCost += that.UnmountedPVCost
  1117. // Sum PVAllocations
  1118. a.PVs = a.PVs.Add(that.PVs)
  1119. // Sum all cumulative adjustment fields
  1120. a.CPUCostAdjustment += that.CPUCostAdjustment
  1121. a.RAMCostAdjustment += that.RAMCostAdjustment
  1122. a.GPUCostAdjustment += that.GPUCostAdjustment
  1123. a.PVCostAdjustment += that.PVCostAdjustment
  1124. a.NetworkCostAdjustment += that.NetworkCostAdjustment
  1125. a.LoadBalancerCostAdjustment += that.LoadBalancerCostAdjustment
  1126. // Sum LoadBalancer Allocations
  1127. a.LoadBalancers = a.LoadBalancers.Add(that.LoadBalancers)
  1128. // Any data that is in a "raw allocation only" is not valid in any
  1129. // sort of cumulative Allocation (like one that is added).
  1130. a.RawAllocationOnly = nil
  1131. }
  1132. func (thisLbAllocs LbAllocations) Add(thatLbAllocs LbAllocations) LbAllocations {
  1133. // loop through both sets of LB allocations, building a new LBAllocations that has the summed set
  1134. mergedLbAllocs := thisLbAllocs.Clone()
  1135. if thatLbAllocs != nil {
  1136. if mergedLbAllocs == nil {
  1137. mergedLbAllocs = LbAllocations{}
  1138. }
  1139. for lbKey, thatlbAlloc := range thatLbAllocs {
  1140. thisLbAlloc, ok := mergedLbAllocs[lbKey]
  1141. if !ok {
  1142. thisLbAlloc = &LbAllocation{
  1143. Service: thatlbAlloc.Service,
  1144. Cost: thatlbAlloc.Cost,
  1145. Hours: thatlbAlloc.Hours,
  1146. }
  1147. mergedLbAllocs[lbKey] = thisLbAlloc
  1148. } else {
  1149. thisLbAlloc.Cost += thatlbAlloc.Cost
  1150. thisLbAlloc.Hours += thatlbAlloc.Hours
  1151. }
  1152. }
  1153. }
  1154. return mergedLbAllocs
  1155. }
  1156. func (thisLbAllocs LbAllocations) SanitizeNaN() {
  1157. for _, lba := range thisLbAllocs {
  1158. lba.SanitizeNaN()
  1159. }
  1160. }
  1161. // AllocationSet stores a set of Allocations, each with a unique name, that share
  1162. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  1163. type AllocationSet struct {
  1164. Allocations map[string]*Allocation
  1165. ExternalKeys map[string]bool
  1166. IdleKeys map[string]bool
  1167. FromSource string // stores the name of the source used to compute the data
  1168. Window Window
  1169. Warnings []string
  1170. Errors []string
  1171. }
  1172. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  1173. // the given list of Allocations
  1174. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  1175. as := &AllocationSet{
  1176. Allocations: map[string]*Allocation{},
  1177. ExternalKeys: map[string]bool{},
  1178. IdleKeys: map[string]bool{},
  1179. Window: NewWindow(&start, &end),
  1180. }
  1181. for _, a := range allocs {
  1182. as.Insert(a)
  1183. }
  1184. return as
  1185. }
  1186. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  1187. // filtering results and sharing allocations. FilterFuncs are a list of match
  1188. // functions such that, if any function fails, the allocation is ignored.
  1189. // ShareFuncs are a list of match functions such that, if any function
  1190. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  1191. // simple flag for sharing idle resources.
  1192. type AllocationAggregationOptions struct {
  1193. AllocationTotalsStore AllocationTotalsStore
  1194. Filter filter.Filter
  1195. IdleByNode bool
  1196. IncludeProportionalAssetResourceCosts bool
  1197. LabelConfig *LabelConfig
  1198. MergeUnallocated bool
  1199. Reconcile bool
  1200. ReconcileNetwork bool
  1201. Share filter.Filter
  1202. SharedNamespaces []string
  1203. SharedLabels map[string][]string
  1204. ShareIdle string
  1205. ShareSplit string
  1206. SharedHourlyCosts map[string]float64
  1207. IncludeSharedCostBreakdown bool
  1208. SplitIdle bool
  1209. IncludeAggregatedMetadata bool
  1210. }
  1211. func isFilterEmpty(filter AllocationMatcher) bool {
  1212. if _, isAllPass := filter.(*matcher.AllPass[*Allocation]); isAllPass {
  1213. return true
  1214. }
  1215. return false
  1216. }
  1217. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  1218. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  1219. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  1220. func (as *AllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  1221. // The order of operations for aggregating allocations is as follows:
  1222. //
  1223. // 1. Partition external, idle, and shared allocations into separate sets.
  1224. // Also, create the aggSet into which the results will be aggregated.
  1225. //
  1226. // 2. Compute sharing coefficients for idle and shared resources
  1227. // a) if idle allocation is to be shared, or if proportional asset
  1228. // resource costs are to be included, then compute idle coefficients
  1229. // (proportional asset resource costs are derived from idle coefficients)
  1230. // b) if proportional asset costs are to be included, derive them from
  1231. // idle coefficients and add them to the allocations.
  1232. // c) if idle allocation is NOT shared, but filters are present, compute
  1233. // idle filtration coefficients for the purpose of only returning the
  1234. // portion of idle allocation that would have been shared with the
  1235. // unfiltered results. (See unit tests 5.a,b,c)
  1236. // d) generate shared allocation for them given shared overhead, which
  1237. // must happen after (2a) and (2b)
  1238. // e) if there are shared resources, compute share coefficients
  1239. //
  1240. // 3. Drop any allocation that fails any of the filters
  1241. //
  1242. // 4. Distribute idle allocations according to the idle coefficients
  1243. //
  1244. // 5. Generate aggregation key and insert allocation into the output set
  1245. //
  1246. // 6. If idle is shared and resources are shared, some idle might be shared
  1247. // with a shared resource. Distribute that to the shared resources
  1248. // prior to sharing them with the aggregated results.
  1249. //
  1250. // 7. Apply idle filtration coefficients from step (2b)
  1251. //
  1252. // 8. Distribute shared allocations according to the share coefficients.
  1253. //
  1254. // 9. If there are external allocations that can be aggregated into
  1255. // the output (i.e. they can be used to generate a valid key for
  1256. // the given properties) then aggregate; otherwise... ignore them?
  1257. //
  1258. // 10. Distribute any undistributed idle, in the case that idle
  1259. // coefficients end up being zero and some idle is not shared.
  1260. //
  1261. // 11. If the merge idle option is enabled, merge any remaining idle
  1262. // allocations into a single idle allocation. If there was any idle
  1263. // whose costs were not distributed because there was no usage of a
  1264. // specific resource type, re-add the idle to the aggregation with
  1265. // only that type.
  1266. if as.IsEmpty() {
  1267. return nil
  1268. }
  1269. if options == nil {
  1270. options = &AllocationAggregationOptions{}
  1271. }
  1272. if options.LabelConfig == nil {
  1273. options.LabelConfig = NewLabelConfig()
  1274. }
  1275. // idleFiltrationCoefficients relies on this being explicitly set
  1276. if options.ShareIdle != ShareWeighted {
  1277. options.ShareIdle = ShareNone
  1278. }
  1279. var filter AllocationMatcher
  1280. if options.Filter == nil {
  1281. filter = &matcher.AllPass[*Allocation]{}
  1282. } else {
  1283. compiler := NewAllocationMatchCompiler(options.LabelConfig)
  1284. var err error
  1285. filter, err = compiler.Compile(options.Filter)
  1286. if err != nil {
  1287. return fmt.Errorf("compiling filter '%s': %w", ast.ToPreOrderShortString(options.Filter), err)
  1288. }
  1289. }
  1290. if filter == nil {
  1291. return fmt.Errorf("unexpected nil filter")
  1292. }
  1293. var sharer AllocationMatcher
  1294. if options.Share != nil {
  1295. compiler := NewAllocationMatchCompiler(options.LabelConfig)
  1296. var err error
  1297. sharer, err = compiler.Compile(options.Share)
  1298. if err != nil {
  1299. return fmt.Errorf("compiling sharer '%s': %w", ast.ToPreOrderShortString(options.Filter), err)
  1300. }
  1301. }
  1302. var allocatedTotalsMap map[string]map[string]float64
  1303. // If aggregateBy is nil, we don't aggregate anything. On the other hand,
  1304. // an empty slice implies that we should aggregate everything. See
  1305. // generateKey for why that makes sense.
  1306. shouldAggregate := aggregateBy != nil
  1307. shouldFilter := !isFilterEmpty(filter)
  1308. shouldShare := len(options.SharedHourlyCosts) > 0 || sharer != nil
  1309. if !shouldAggregate && !shouldFilter && !shouldShare && options.ShareIdle == ShareNone && !options.IncludeProportionalAssetResourceCosts {
  1310. // There is nothing for AggregateBy to do, so simply return nil
  1311. // before returning, set aggregated metadata inclusion in properties
  1312. if options.IncludeAggregatedMetadata {
  1313. for index := range as.Allocations {
  1314. as.Allocations[index].Properties.AggregatedMetadata = true
  1315. }
  1316. }
  1317. return nil
  1318. }
  1319. // aggSet will collect the aggregated allocations
  1320. aggSet := &AllocationSet{
  1321. Window: as.Window.Clone(),
  1322. }
  1323. // externalSet will collect external allocations
  1324. externalSet := &AllocationSet{
  1325. Window: as.Window.Clone(),
  1326. }
  1327. // idleSet will be shared among aggSet after initial aggregation
  1328. // is complete
  1329. idleSet := &AllocationSet{
  1330. Window: as.Window.Clone(),
  1331. }
  1332. // parcSet is used to compute proportionalAssetResourceCosts
  1333. // for surfacing in the API
  1334. parcSet := &AllocationSet{
  1335. Window: as.Window.Clone(),
  1336. }
  1337. // shareSet will be shared among aggSet after initial aggregation
  1338. // is complete
  1339. shareSet := &AllocationSet{
  1340. Window: as.Window.Clone(),
  1341. }
  1342. // (1) Loop and find all of the external, idle, and shared allocations. Add
  1343. // them to their respective sets, removing them from the set of allocations
  1344. // to aggregate.
  1345. for _, alloc := range as.Allocations {
  1346. alloc.Properties.AggregatedMetadata = options.IncludeAggregatedMetadata
  1347. // build a parallel set of allocations to only be used
  1348. // for computing PARCs
  1349. if options.IncludeProportionalAssetResourceCosts {
  1350. parcSet.Insert(alloc.Clone())
  1351. }
  1352. // External allocations get aggregated post-hoc (see step 6) and do
  1353. // not necessarily contain complete sets of properties, so they are
  1354. // moved to a separate AllocationSet.
  1355. if alloc.IsExternal() {
  1356. delete(as.ExternalKeys, alloc.Name)
  1357. delete(as.Allocations, alloc.Name)
  1358. externalSet.Insert(alloc)
  1359. continue
  1360. }
  1361. // Idle allocations should be separated into idleSet if they are to be
  1362. // shared later on. If they are not to be shared, then add them to the
  1363. // aggSet like any other allocation.
  1364. if alloc.IsIdle() {
  1365. delete(as.IdleKeys, alloc.Name)
  1366. delete(as.Allocations, alloc.Name)
  1367. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  1368. idleSet.Insert(alloc)
  1369. } else {
  1370. aggSet.Insert(alloc)
  1371. }
  1372. continue
  1373. }
  1374. // Shared allocations must be identified and separated prior to
  1375. // aggregation and filtering. That is, if any of the ShareFuncs return
  1376. // true for the allocation, then move it to shareSet.
  1377. if sharer != nil && sharer.Matches(alloc) {
  1378. delete(as.IdleKeys, alloc.Name)
  1379. delete(as.Allocations, alloc.Name)
  1380. shareSet.Insert(alloc)
  1381. continue
  1382. }
  1383. }
  1384. // It's possible that no more un-shared, non-idle, non-external allocations
  1385. // remain at this point. This always results in an emptySet, so return early.
  1386. if len(as.Allocations) == 0 {
  1387. emptySet := &AllocationSet{
  1388. Window: as.Window.Clone(),
  1389. }
  1390. as.Allocations = emptySet.Allocations
  1391. return nil
  1392. }
  1393. // (2) In order to correctly share idle and shared costs, we first compute
  1394. // sharing coefficients, which represent the proportion of each cost to
  1395. // share with each allocation. Idle allocations are shared per-cluster or per-node,
  1396. // per-allocation, and per-resource, while shared resources are shared per-
  1397. // allocation only.
  1398. //
  1399. // For an idleCoefficient example, the entries:
  1400. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  1401. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  1402. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  1403. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  1404. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  1405. // RAM costs.
  1406. //
  1407. // For a shareCoefficient example, the entries:
  1408. // [namespace2] = 0.666667
  1409. // [__filtered__] = 0.333333
  1410. // mean that the post-aggregation allocation "namespace2" will receive
  1411. // 66.67% of the shared resource costs, while the remaining 33.33% will
  1412. // be filtered out, as they were shared with allocations that did not pass
  1413. // one of the given filters.
  1414. //
  1415. // In order to maintain stable results when multiple operations are being
  1416. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  1417. // coefficients are computed for the full set of allocations prior to
  1418. // adding shared overhead and prior to applying filters.
  1419. var err error
  1420. // (2a) If there are idle costs to be shared, compute the coefficients for
  1421. // sharing them among the non-idle, non-aggregated allocations (including
  1422. // the shared allocations).
  1423. var idleCoefficients map[string]map[string]map[string]float64
  1424. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  1425. idleCoefficients, allocatedTotalsMap, err = computeIdleCoeffs(options, as, shareSet)
  1426. if err != nil {
  1427. log.Warnf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  1428. return fmt.Errorf("error computing idle coefficients: %s", err)
  1429. }
  1430. }
  1431. // (2b) If proportional asset resource costs are to be included, compute them
  1432. // and add them to the allocations.
  1433. if options.IncludeProportionalAssetResourceCosts {
  1434. err := deriveProportionalAssetResourceCosts(options, as, shareSet, parcSet)
  1435. if err != nil {
  1436. log.Debugf("AggregateBy: failed to derive proportional asset resource costs from idle coefficients: %s", err)
  1437. return fmt.Errorf("AggregateBy: failed to derive proportional asset resource costs from idle coefficients: %s", err)
  1438. }
  1439. }
  1440. // (2c) If idle costs are not to be shared, but there are filters, then we
  1441. // need to track the amount of each idle allocation to "filter" in order to
  1442. // maintain parity with the results when idle is shared. That is, we want
  1443. // to return only the idle costs that would have been shared with the given
  1444. // results, even if the filter had not been applied.
  1445. //
  1446. // For example, consider these results from aggregating by namespace with
  1447. // two clusters:
  1448. //
  1449. // namespace1: 25.00
  1450. // namespace2: 30.00
  1451. // namespace3: 15.00
  1452. // idle: 30.00
  1453. //
  1454. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  1455. // reduced by the amount that existed on cluster2. Then, idle must also be
  1456. // reduced by the relevant amount:
  1457. //
  1458. // namespace1: 25.00
  1459. // namespace2: 15.00
  1460. // idle: 20.00
  1461. //
  1462. // Note that this can happen for any field, not just cluster, so we again
  1463. // need to track this on a per-cluster or per-node, per-allocation, per-resource basis.
  1464. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  1465. if shouldFilter && options.ShareIdle == ShareNone {
  1466. idleFiltrationCoefficients, _, err = computeIdleCoeffs(options, as, shareSet)
  1467. if err != nil {
  1468. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  1469. }
  1470. }
  1471. // (2d) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  1472. // come after idle coefficients are computed so that allocations generated
  1473. // by shared overhead do not skew the idle coefficient computation.
  1474. for name, cost := range options.SharedHourlyCosts {
  1475. if cost > 0.0 {
  1476. hours := as.Resolution().Hours()
  1477. // If set ends in the future, adjust hours accordingly
  1478. diff := time.Since(as.End())
  1479. if diff < 0.0 {
  1480. hours += diff.Hours()
  1481. }
  1482. totalSharedCost := cost * hours
  1483. shareSet.Insert(&Allocation{
  1484. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  1485. Start: as.Start(),
  1486. End: as.End(),
  1487. SharedCost: totalSharedCost,
  1488. 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.
  1489. })
  1490. }
  1491. }
  1492. // (2e) Compute share coefficients for shared resources. These are computed
  1493. // after idle coefficients, and are computed for the aggregated allocations
  1494. // of the main allocation set. See above for details and an example.
  1495. var shareCoefficients map[string]float64
  1496. if shareSet.Length() > 0 {
  1497. shareCoefficients, err = computeShareCoeffs(aggregateBy, options, as)
  1498. if err != nil {
  1499. return fmt.Errorf("error computing share coefficients: %s", err)
  1500. }
  1501. }
  1502. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  1503. for _, alloc := range as.Allocations {
  1504. idleId, err := alloc.getIdleId(options)
  1505. if err != nil {
  1506. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  1507. }
  1508. // (3) If the allocation does not match the filter, immediately skip the
  1509. // allocation.
  1510. if !filter.Matches(alloc) {
  1511. // If we are tracking idle filtration coefficients, delete the
  1512. // entry corresponding to the filtered allocation. (Deleting the
  1513. // entry will result in that proportional amount being removed
  1514. // from the idle allocation at the end of the process.)
  1515. if idleFiltrationCoefficients != nil {
  1516. if ifcc, ok := idleFiltrationCoefficients[idleId]; ok {
  1517. delete(ifcc, alloc.Name)
  1518. }
  1519. }
  1520. continue
  1521. }
  1522. // (4) Distribute idle allocations according to the idle coefficients
  1523. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  1524. // all idle allocations will be in the aggSet at this point, so idleSet
  1525. // will be empty and we won't enter this block.
  1526. if idleSet.Length() > 0 {
  1527. // Distribute idle allocations by coefficient per-idleId, per-allocation
  1528. for _, idleAlloc := range idleSet.Allocations {
  1529. // Only share idle if the idleId matches; i.e. the allocation
  1530. // is from the same idleId as the idle costs
  1531. iaidleId, err := idleAlloc.getIdleId(options)
  1532. if err != nil {
  1533. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  1534. return err
  1535. }
  1536. if iaidleId != idleId {
  1537. continue
  1538. }
  1539. // Make sure idle coefficients exist
  1540. if _, ok := idleCoefficients[idleId]; !ok {
  1541. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  1542. continue
  1543. }
  1544. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  1545. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  1546. continue
  1547. }
  1548. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  1549. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  1550. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  1551. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  1552. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  1553. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  1554. alloc.CPUCost += idleCPUCost
  1555. alloc.GPUCost += idleGPUCost
  1556. alloc.RAMCost += idleRAMCost
  1557. }
  1558. }
  1559. // (5) generate key to use for aggregation-by-key and allocation name
  1560. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  1561. alloc.Name = key
  1562. if options.MergeUnallocated && alloc.IsUnallocated() {
  1563. alloc.Name = UnallocatedSuffix
  1564. }
  1565. // Inserting the allocation with the generated key for a name will
  1566. // perform the actual basic aggregation step.
  1567. aggSet.Insert(alloc)
  1568. }
  1569. // (6) If idle is shared and resources are shared, it's possible that some
  1570. // amount of idle cost will be shared with a shared resource. Distribute
  1571. // that idle allocation, if it exists, to the respective shared allocations
  1572. // before sharing with the aggregated allocations.
  1573. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  1574. for _, alloc := range shareSet.Allocations {
  1575. idleId, err := alloc.getIdleId(options)
  1576. if err != nil {
  1577. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  1578. }
  1579. // Distribute idle allocations by coefficient per-idleId, per-allocation
  1580. for _, idleAlloc := range idleSet.Allocations {
  1581. // Only share idle if the idleId matches; i.e. the allocation
  1582. // is from the same idleId as the idle costs
  1583. iaidleId, _ := idleAlloc.getIdleId(options)
  1584. if iaidleId != idleId {
  1585. continue
  1586. }
  1587. // Make sure idle coefficients exist
  1588. if _, ok := idleCoefficients[idleId]; !ok {
  1589. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  1590. continue
  1591. }
  1592. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  1593. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  1594. continue
  1595. }
  1596. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  1597. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  1598. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  1599. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  1600. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  1601. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  1602. alloc.CPUCost += idleCPUCost
  1603. alloc.GPUCost += idleGPUCost
  1604. alloc.RAMCost += idleRAMCost
  1605. }
  1606. }
  1607. }
  1608. // groupingIdleFiltrationCoeffs is used to track per-resource idle
  1609. // coefficients on a cluster-by-cluster or node-by-node basis depending
  1610. // on the IdleByNode option. It is, essentially, an aggregation of
  1611. // idleFiltrationCoefficients after they have been
  1612. // filtered above (in step 3)
  1613. var groupingIdleFiltrationCoeffs map[string]map[string]float64
  1614. if idleFiltrationCoefficients != nil {
  1615. groupingIdleFiltrationCoeffs = map[string]map[string]float64{}
  1616. for idleId, m := range idleFiltrationCoefficients {
  1617. if _, ok := groupingIdleFiltrationCoeffs[idleId]; !ok {
  1618. groupingIdleFiltrationCoeffs[idleId] = map[string]float64{
  1619. "cpu": 0.0,
  1620. "gpu": 0.0,
  1621. "ram": 0.0,
  1622. }
  1623. }
  1624. for _, n := range m {
  1625. for resource, val := range n {
  1626. groupingIdleFiltrationCoeffs[idleId][resource] += val
  1627. }
  1628. }
  1629. }
  1630. }
  1631. // (7) If we have both un-shared idle allocations and idle filtration
  1632. // coefficients then apply those. See step (2b) for an example.
  1633. if len(aggSet.IdleKeys) > 0 && groupingIdleFiltrationCoeffs != nil {
  1634. for idleKey := range aggSet.IdleKeys {
  1635. idleAlloc := aggSet.Get(idleKey)
  1636. iaidleId, err := idleAlloc.getIdleId(options)
  1637. if err != nil {
  1638. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  1639. return err
  1640. }
  1641. if resourceCoeffs, ok := groupingIdleFiltrationCoeffs[iaidleId]; ok {
  1642. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  1643. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  1644. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  1645. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  1646. idleAlloc.GPUCost *= resourceCoeffs["gpu"]
  1647. idleAlloc.GPUHours *= resourceCoeffs["gpu"]
  1648. }
  1649. }
  1650. }
  1651. // (8) Distribute shared allocations according to the share coefficients.
  1652. if shareSet.Length() > 0 {
  1653. for _, alloc := range aggSet.Allocations {
  1654. for _, sharedAlloc := range shareSet.Allocations {
  1655. if _, ok := shareCoefficients[alloc.Name]; !ok {
  1656. if !alloc.IsIdle() && !alloc.IsUnmounted() {
  1657. log.Warnf("AllocationSet.AggregateBy: error getting share coefficient for '%s'", alloc.Name)
  1658. }
  1659. continue
  1660. }
  1661. if options.IncludeSharedCostBreakdown {
  1662. if alloc.SharedCostBreakdown == nil {
  1663. alloc.SharedCostBreakdown = map[string]SharedCostBreakdown{}
  1664. }
  1665. sharedCostName, err := sharedAlloc.determineSharingName(options)
  1666. if err != nil {
  1667. return fmt.Errorf("failed to group shared costs: %s", err)
  1668. }
  1669. // check if current allocation is a shared flat overhead cost
  1670. if strings.Contains(sharedAlloc.Name, SharedSuffix) {
  1671. sharedCostName = "overheadCost"
  1672. }
  1673. scb := SharedCostBreakdown{
  1674. Name: sharedCostName,
  1675. TotalCost: sharedAlloc.TotalCost() * shareCoefficients[alloc.Name],
  1676. CPUCost: sharedAlloc.CPUTotalCost() * shareCoefficients[alloc.Name],
  1677. GPUCost: sharedAlloc.GPUTotalCost() * shareCoefficients[alloc.Name],
  1678. RAMCost: sharedAlloc.RAMTotalCost() * shareCoefficients[alloc.Name],
  1679. PVCost: sharedAlloc.PVCost() * shareCoefficients[alloc.Name],
  1680. NetworkCost: sharedAlloc.NetworkTotalCost() * shareCoefficients[alloc.Name],
  1681. LBCost: sharedAlloc.LBTotalCost() * shareCoefficients[alloc.Name],
  1682. ExternalCost: sharedAlloc.ExternalCost * shareCoefficients[alloc.Name],
  1683. }
  1684. // fmt.Printf("shared cost: %+v", scb)
  1685. alloc.SharedCostBreakdown.Insert(scb)
  1686. }
  1687. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  1688. }
  1689. }
  1690. }
  1691. // (9) Aggregate external allocations into aggregated allocations. This may
  1692. // not be possible for every external allocation, but attempt to find an
  1693. // exact key match, given each external allocation's proerties, and
  1694. // aggregate if an exact match is found.
  1695. for _, alloc := range externalSet.Allocations {
  1696. if filter.Matches(alloc) {
  1697. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  1698. alloc.Name = key
  1699. aggSet.Insert(alloc)
  1700. }
  1701. }
  1702. // (10) In the edge case that some idle has not been distributed because
  1703. // there is no usage of that resource type, add idle back to
  1704. // aggregations with only that cost applied.
  1705. // E.g. in the case where we have a result that looks like this on the
  1706. // frontend:
  1707. // Name CPU GPU RAM
  1708. // __idle__ $10 $12 $6
  1709. // kubecost $2 $0 $1
  1710. // Sharing idle weighted would result in no idle GPU cost being
  1711. // distributed, because the coefficient for the kubecost GPU cost would
  1712. // be zero. Thus, instead we re-add idle to the aggSet with distributed
  1713. // costs zeroed out but the undistributed costs left in.
  1714. // Name CPU GPU RAM
  1715. // __idle__ $0 $12 $0
  1716. // kubecost $12 $0 $7
  1717. if idleSet.Length() > 0 {
  1718. for _, idleAlloc := range idleSet.Allocations {
  1719. // if the idle does not apply to the non-filtered values, skip it
  1720. if !filter.Matches(idleAlloc) {
  1721. continue
  1722. }
  1723. idleId, err := idleAlloc.getIdleId(options)
  1724. if err != nil {
  1725. log.Errorf("AllocationSet.AggregateBy: idle allocation is missing idleId %s", idleAlloc.Name)
  1726. continue
  1727. }
  1728. hasUndistributableCost := false
  1729. if idleAlloc.CPUCost > 0 && allocatedTotalsMap[idleId]["cpu"] == 0 {
  1730. hasUndistributableCost = true
  1731. } else {
  1732. idleAlloc.CPUCost = 0
  1733. }
  1734. if idleAlloc.GPUCost > 0 && allocatedTotalsMap[idleId]["gpu"] == 0 {
  1735. hasUndistributableCost = true
  1736. } else {
  1737. idleAlloc.GPUCost = 0
  1738. }
  1739. if idleAlloc.RAMCost > 0 && allocatedTotalsMap[idleId]["ram"] == 0 {
  1740. hasUndistributableCost = true
  1741. } else {
  1742. idleAlloc.RAMCost = 0
  1743. }
  1744. if hasUndistributableCost {
  1745. idleAlloc.Name = fmt.Sprintf("%s/%s", idleId, IdleSuffix)
  1746. aggSet.Insert(idleAlloc)
  1747. }
  1748. }
  1749. }
  1750. // (11) Combine all idle allocations into a single "__idle__" allocation
  1751. if !options.SplitIdle {
  1752. for _, idleAlloc := range aggSet.IdleAllocations() {
  1753. aggSet.Delete(idleAlloc.Name)
  1754. idleAlloc.Name = IdleSuffix
  1755. aggSet.Insert(idleAlloc)
  1756. }
  1757. }
  1758. // TODO revisit this (ideally we just remove sharing from this function!)
  1759. // If filters and shared resources and shared idle are all enabled then
  1760. // we will over-count idle by exactly the portion that gets shared with the
  1761. // filtered allocations -- and idle filtration will miss this because it
  1762. // only filters the non-idle filtered costs.
  1763. //
  1764. // Consider the following example, from unit tests:
  1765. // - namespace1 28.000
  1766. // - namespace2 36.000
  1767. // - namespace3 18.000
  1768. // - cluster1/idle 20.000
  1769. // - cluster2/idle 10.000
  1770. //
  1771. // Now, we want to share namespace1, filter namespace2, and share idle:
  1772. //
  1773. // 1. Distribute idle
  1774. // ns1 ns2 ns3
  1775. // non-idle 28.000 36.000 18.000
  1776. // idle 14.688 10.312 5.000
  1777. //
  1778. // 2. Share namespace1
  1779. //
  1780. // ns2 ns3
  1781. // non-idle 36.000 18.000
  1782. // idle 10.312 5.000
  1783. // shared non-idle 18.667 9.333
  1784. // shared idle 9.792 4.896 (***)
  1785. //
  1786. // 3. Filter out all but namespace2
  1787. //
  1788. // ns2 = 36.000 + 10.312 + 18.667 + 9.792 = 74.771
  1789. //
  1790. // So, if we had NOT shared idle, we would expect something like this:
  1791. //
  1792. // ns2 = 36.000 + 18.667 = 54.667
  1793. // idle = 10.312 + 9.792 = 20.104
  1794. //
  1795. // But we will instead get this:
  1796. //
  1797. // ns2 = 36.000 + 18.667 = 54.667
  1798. // idle = 10.312 + 14.688 = 25.000
  1799. //
  1800. // Which over-shoots idle by 4.896 (***), i.e. precisely the amount of idle
  1801. // cost corresponding to namespace1 AND shared with namespace3. Phew.
  1802. //
  1803. // I originally wanted to fix this, but after 2 days, I'm punting with the
  1804. // recommendation that we rewrite this function soon. Too difficult.
  1805. // - Niko
  1806. as.Allocations = aggSet.Allocations
  1807. return nil
  1808. }
  1809. func computeShareCoeffs(aggregateBy []string, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  1810. // Compute coeffs by totalling per-allocation, then dividing by the total.
  1811. coeffs := map[string]float64{}
  1812. // Compute totals for all allocations
  1813. total := 0.0
  1814. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  1815. // counts each aggregation proportionally to its respective costs
  1816. shareType := options.ShareSplit
  1817. var filter AllocationMatcher
  1818. if options.Filter == nil {
  1819. filter = &matcher.AllPass[*Allocation]{}
  1820. } else {
  1821. compiler := NewAllocationMatchCompiler(options.LabelConfig)
  1822. var err error
  1823. filter, err = compiler.Compile(options.Filter)
  1824. if err != nil {
  1825. return nil, fmt.Errorf("compiling filter '%s': %w", ast.ToPreOrderShortString(options.Filter), err)
  1826. }
  1827. }
  1828. if filter == nil {
  1829. return nil, fmt.Errorf("unexpected nil filter")
  1830. }
  1831. // Record allocation values first, then normalize by totals to get percentages
  1832. for _, alloc := range as.Allocations {
  1833. if alloc.IsIdle() {
  1834. // Skip idle allocations in coefficient calculation
  1835. continue
  1836. }
  1837. if alloc.IsUnmounted() {
  1838. // Skip unmounted allocations in coefficient calculation
  1839. continue
  1840. }
  1841. // Determine the post-aggregation key under which the allocation will
  1842. // be shared.
  1843. name := alloc.generateKey(aggregateBy, options.LabelConfig)
  1844. // If the current allocation will be filtered out in step 3, contribute
  1845. // its share of the shared coefficient to a "__filtered__" bin, which
  1846. // will ultimately be dropped. This step ensures that the shared cost
  1847. // of a non-filtered allocation will be conserved even when the filter
  1848. // is removed. (Otherwise, all the shared cost will get redistributed
  1849. // over the unfiltered results, inflating their shared costs.)
  1850. if !filter.Matches(alloc) {
  1851. name = "__filtered__"
  1852. }
  1853. if shareType == ShareEven {
  1854. // Even distribution is not additive - set to 1.0 for everything
  1855. coeffs[name] = 1.0
  1856. // Total for even distribution is always the number of coefficients
  1857. total = float64(len(coeffs))
  1858. } else {
  1859. // Both are additive for weighted distribution, where each
  1860. // cumulative coefficient will be divided by the total.
  1861. coeffs[name] += alloc.TotalCost() - alloc.SharedCost - alloc.UnmountedPVCost
  1862. total += alloc.TotalCost() - alloc.SharedCost - alloc.UnmountedPVCost
  1863. }
  1864. }
  1865. // Normalize coefficients by totals
  1866. for a := range coeffs {
  1867. if coeffs[a] > 0 && total > 0 {
  1868. coeffs[a] /= total
  1869. } else {
  1870. log.Warnf("ETL: invalid values for shared coefficients: %v, %v", coeffs[a], total)
  1871. coeffs[a] = 0.0
  1872. }
  1873. }
  1874. return coeffs, nil
  1875. }
  1876. func computeIdleCoeffs(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, map[string]map[string]float64, error) {
  1877. types := []string{"cpu", "gpu", "ram"}
  1878. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1879. // [idle_id][allocation name][resource] = [coeff]
  1880. coeffs := map[string]map[string]map[string]float64{}
  1881. // Compute totals per resource for CPU, GPU, RAM, and PV
  1882. // [idle_id][resource] = [total]
  1883. totals := map[string]map[string]float64{}
  1884. // Record allocation values first, then normalize by totals to get percentages
  1885. for _, alloc := range as.Allocations {
  1886. if alloc.IsIdle() {
  1887. // Skip idle allocations in coefficient calculation
  1888. continue
  1889. }
  1890. idleId, err := alloc.getIdleId(options)
  1891. if err != nil {
  1892. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  1893. }
  1894. // get the name key for the allocation
  1895. name := alloc.Name
  1896. // Create key based tables if they don't exist
  1897. if _, ok := coeffs[idleId]; !ok {
  1898. coeffs[idleId] = map[string]map[string]float64{}
  1899. }
  1900. if _, ok := totals[idleId]; !ok {
  1901. totals[idleId] = map[string]float64{}
  1902. }
  1903. if _, ok := coeffs[idleId][name]; !ok {
  1904. coeffs[idleId][name] = map[string]float64{}
  1905. }
  1906. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1907. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1908. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1909. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1910. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1911. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1912. }
  1913. // Do the same for shared allocations
  1914. for _, alloc := range shareSet.Allocations {
  1915. if alloc.IsIdle() {
  1916. // Skip idle allocations in coefficient calculation
  1917. continue
  1918. }
  1919. // idleId will be providerId or cluster
  1920. idleId, err := alloc.getIdleId(options)
  1921. if err != nil {
  1922. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  1923. }
  1924. // get the name key for the allocation
  1925. name := alloc.Name
  1926. // Create idleId based tables if they don't exist
  1927. if _, ok := coeffs[idleId]; !ok {
  1928. coeffs[idleId] = map[string]map[string]float64{}
  1929. }
  1930. if _, ok := totals[idleId]; !ok {
  1931. totals[idleId] = map[string]float64{}
  1932. }
  1933. if _, ok := coeffs[idleId][name]; !ok {
  1934. coeffs[idleId][name] = map[string]float64{}
  1935. }
  1936. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1937. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1938. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1939. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1940. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1941. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1942. }
  1943. // Normalize coefficients by totals
  1944. for id := range coeffs {
  1945. for a := range coeffs[id] {
  1946. for _, r := range types {
  1947. if coeffs[id][a][r] > 0 && totals[id][r] > 0 {
  1948. coeffs[id][a][r] /= totals[id][r]
  1949. }
  1950. }
  1951. }
  1952. }
  1953. return coeffs, totals, nil
  1954. }
  1955. func deriveProportionalAssetResourceCosts(options *AllocationAggregationOptions, as *AllocationSet, shareSet, parcsSet *AllocationSet) error {
  1956. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1957. // [idle_id][allocation name][resource] = [coeff]
  1958. coeffs := map[string]map[string]map[string]float64{}
  1959. // Compute totals per resource for CPU, GPU, RAM, and PV
  1960. // [idle_id][resource] = [total]
  1961. totals := map[string]map[string]float64{}
  1962. // Record allocation values first, then normalize by totals to get percentages
  1963. for _, alloc := range parcsSet.Allocations {
  1964. idleId, err := alloc.getIdleId(options)
  1965. if err != nil {
  1966. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  1967. }
  1968. // get the name key for the allocation
  1969. name := alloc.Name
  1970. // Create key based tables if they don't exist
  1971. if _, ok := coeffs[idleId]; !ok {
  1972. coeffs[idleId] = map[string]map[string]float64{}
  1973. }
  1974. if _, ok := totals[idleId]; !ok {
  1975. totals[idleId] = map[string]float64{}
  1976. }
  1977. if _, ok := coeffs[idleId][name]; !ok {
  1978. coeffs[idleId][name] = map[string]float64{}
  1979. }
  1980. // idle IDs for load balancers are their services
  1981. for key := range alloc.LoadBalancers {
  1982. if _, ok := totals[key]; !ok {
  1983. totals[key] = map[string]float64{}
  1984. }
  1985. if _, ok := coeffs[key]; !ok {
  1986. coeffs[key] = map[string]map[string]float64{}
  1987. }
  1988. if _, ok := coeffs[key][name]; !ok {
  1989. coeffs[key][name] = map[string]float64{}
  1990. }
  1991. coeffs[key][name]["loadbalancer"] += alloc.LoadBalancerTotalCost()
  1992. totals[key]["loadbalancer"] += alloc.LoadBalancerTotalCost()
  1993. }
  1994. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1995. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1996. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1997. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1998. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1999. totals[idleId]["ram"] += alloc.RAMTotalCost()
  2000. }
  2001. // Do the same for shared allocations
  2002. for _, alloc := range shareSet.Allocations {
  2003. if alloc.IsIdle() {
  2004. // Skip idle allocations in coefficient calculation
  2005. continue
  2006. }
  2007. // idleId will be providerId or cluster
  2008. idleId, err := alloc.getIdleId(options)
  2009. if err != nil {
  2010. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  2011. }
  2012. // get the name key for the allocation
  2013. name := alloc.Name
  2014. // Create idleId based tables if they don't exist
  2015. if _, ok := coeffs[idleId]; !ok {
  2016. coeffs[idleId] = map[string]map[string]float64{}
  2017. }
  2018. if _, ok := totals[idleId]; !ok {
  2019. totals[idleId] = map[string]float64{}
  2020. }
  2021. if _, ok := coeffs[idleId][name]; !ok {
  2022. coeffs[idleId][name] = map[string]float64{}
  2023. }
  2024. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  2025. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  2026. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  2027. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  2028. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  2029. totals[idleId]["ram"] += alloc.RAMTotalCost()
  2030. // idle IDs for load balancers are their services
  2031. for key := range alloc.LoadBalancers {
  2032. if _, ok := totals[key]; !ok {
  2033. totals[key] = map[string]float64{}
  2034. }
  2035. if _, ok := coeffs[key]; !ok {
  2036. coeffs[key] = map[string]map[string]float64{}
  2037. }
  2038. if _, ok := coeffs[key][name]; !ok {
  2039. coeffs[key][name] = map[string]float64{}
  2040. }
  2041. coeffs[key][name]["loadbalancer"] += alloc.LoadBalancerTotalCost()
  2042. totals[key]["loadbalancer"] += alloc.LoadBalancerTotalCost()
  2043. }
  2044. }
  2045. // after totals are computed, loop through and set parcs on allocations
  2046. for _, alloc := range as.Allocations {
  2047. idleId, err := alloc.getIdleId(options)
  2048. if err != nil {
  2049. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  2050. }
  2051. alloc.ProportionalAssetResourceCosts = ProportionalAssetResourceCosts{}
  2052. alloc.ProportionalAssetResourceCosts.Insert(ProportionalAssetResourceCost{
  2053. Cluster: alloc.Properties.Cluster,
  2054. Name: alloc.Properties.Node,
  2055. Type: "Node",
  2056. ProviderID: alloc.Properties.ProviderID,
  2057. GPUProportionalCost: coeffs[idleId][alloc.Name]["gpu"],
  2058. CPUProportionalCost: coeffs[idleId][alloc.Name]["cpu"],
  2059. RAMProportionalCost: coeffs[idleId][alloc.Name]["ram"],
  2060. }, options.IdleByNode)
  2061. // insert a separate PARC for the load balancer
  2062. if alloc.LoadBalancerCost != 0 {
  2063. for key, svc := range alloc.LoadBalancers {
  2064. alloc.ProportionalAssetResourceCosts.Insert(ProportionalAssetResourceCost{
  2065. Cluster: alloc.Properties.Cluster,
  2066. Name: svc.Service,
  2067. Type: "LoadBalancer",
  2068. LoadBalancerProportionalCost: coeffs[key][alloc.Name]["loadbalancer"],
  2069. }, options.IdleByNode)
  2070. }
  2071. }
  2072. for name, pvAlloc := range alloc.PVs {
  2073. // insert a separate PARC for each PV attached
  2074. alloc.ProportionalAssetResourceCosts.Insert(ProportionalAssetResourceCost{
  2075. Cluster: name.Cluster,
  2076. Name: name.Name,
  2077. Type: "PV",
  2078. ProviderID: pvAlloc.ProviderID,
  2079. PVProportionalCost: pvAlloc.Cost,
  2080. }, options.IdleByNode)
  2081. }
  2082. }
  2083. return nil
  2084. }
  2085. func (a *Allocation) determineSharingName(options *AllocationAggregationOptions) (string, error) {
  2086. if a == nil {
  2087. return "", fmt.Errorf("determineSharingName called on nil Allocation")
  2088. } else if options == nil {
  2089. return "unknown", nil
  2090. }
  2091. // grab SharedLabels keys and sort them, to keep this function deterministic
  2092. var labelKeys []string
  2093. for labelKey := range options.SharedLabels {
  2094. labelKeys = append(labelKeys, labelKey)
  2095. }
  2096. slices.Sort(labelKeys)
  2097. var sharedAggregateBy []string
  2098. var sharedLabels [][]string
  2099. for _, labelKey := range labelKeys {
  2100. sharedAgg := fmt.Sprintf("label:%s", labelKey)
  2101. if !slices.Contains(sharedAggregateBy, sharedAgg) {
  2102. sharedAggregateBy = append(sharedAggregateBy, sharedAgg)
  2103. }
  2104. sharedLabels = append(sharedLabels, options.SharedLabels[labelKey])
  2105. }
  2106. if len(options.SharedNamespaces) > 0 {
  2107. sharedAggregateBy = append(sharedAggregateBy, "namespace")
  2108. }
  2109. sharedCostName := a.generateKey(sharedAggregateBy, options.LabelConfig)
  2110. // get each value in the generated key, then reset the name
  2111. sharedCostNameValues := strings.Split(sharedCostName, "/")
  2112. sharedCostName = ""
  2113. // if we don't have as many values as aggregateBys, something went wrong in generateKey
  2114. if len(sharedCostNameValues) != len(sharedAggregateBy) {
  2115. log.Warnf("Unable to determine share cost group for allocation \"%s\"", a.Name)
  2116. } else {
  2117. // try to match to the first label
  2118. for i, sharedLabelValues := range sharedLabels {
  2119. allocLabel := sharedCostNameValues[i]
  2120. if slices.Contains(sharedLabelValues, allocLabel) {
  2121. return allocLabel, nil
  2122. }
  2123. }
  2124. // if we didn't match to a label, try to match to a namespace
  2125. if len(options.SharedNamespaces) > 0 {
  2126. // namespace will always be the last value, if SharedNamespaces is set
  2127. allocNamespace := sharedCostNameValues[len(sharedCostNameValues)-1]
  2128. if slices.Contains(options.SharedNamespaces, allocNamespace) {
  2129. return allocNamespace, nil
  2130. }
  2131. }
  2132. // if neither the labels nor the namespaces matched, we log a warning and mark this allocation
  2133. // as unknown
  2134. if len(sharedCostName) == 0 {
  2135. log.Warnf("Failed to determine shared cost grouping for allocation \"%s\"", a.Name)
  2136. }
  2137. }
  2138. return "unknown", nil
  2139. }
  2140. // getIdleId returns the providerId or cluster of an Allocation depending on the IdleByNode
  2141. // option in the AllocationAggregationOptions and an error if the respective field is missing
  2142. func (a *Allocation) getIdleId(options *AllocationAggregationOptions) (string, error) {
  2143. var idleId string
  2144. if options.IdleByNode {
  2145. // Key allocations to ProviderId to match against node
  2146. idleId = fmt.Sprintf("%s/%s", a.Properties.Cluster, a.Properties.Node)
  2147. if idleId == "" {
  2148. return idleId, fmt.Errorf("ProviderId is not set")
  2149. }
  2150. } else {
  2151. // key the allocations by cluster id
  2152. idleId = a.Properties.Cluster
  2153. if idleId == "" {
  2154. return idleId, fmt.Errorf("ClusterProp is not set")
  2155. }
  2156. }
  2157. return idleId, nil
  2158. }
  2159. func (a *Allocation) generateKey(aggregateBy []string, labelConfig *LabelConfig) string {
  2160. if a == nil {
  2161. return ""
  2162. }
  2163. return a.Properties.GenerateKey(aggregateBy, labelConfig)
  2164. }
  2165. func (a *Allocation) StringProperty(property string) (string, error) {
  2166. switch property {
  2167. case AllocationClusterProp:
  2168. if a.Properties == nil {
  2169. return "", nil
  2170. }
  2171. return a.Properties.Cluster, nil
  2172. case AllocationNodeProp:
  2173. if a.Properties == nil {
  2174. return "", nil
  2175. }
  2176. return a.Properties.Node, nil
  2177. case AllocationContainerProp:
  2178. if a.Properties == nil {
  2179. return "", nil
  2180. }
  2181. return a.Properties.Container, nil
  2182. case AllocationControllerProp:
  2183. if a.Properties == nil {
  2184. return "", nil
  2185. }
  2186. return a.Properties.Controller, nil
  2187. case AllocationControllerKindProp:
  2188. if a.Properties == nil {
  2189. return "", nil
  2190. }
  2191. return a.Properties.ControllerKind, nil
  2192. case AllocationNamespaceProp:
  2193. if a.Properties == nil {
  2194. return "", nil
  2195. }
  2196. return a.Properties.Namespace, nil
  2197. case AllocationPodProp:
  2198. if a.Properties == nil {
  2199. return "", nil
  2200. }
  2201. return a.Properties.Pod, nil
  2202. case AllocationProviderIDProp:
  2203. if a.Properties == nil {
  2204. return "", nil
  2205. }
  2206. return a.Properties.ProviderID, nil
  2207. default:
  2208. return "", fmt.Errorf("Allocation: StringProperty: invalid property name: %s", property)
  2209. }
  2210. }
  2211. func (a *Allocation) StringSliceProperty(property string) ([]string, error) {
  2212. switch property {
  2213. case AllocationServiceProp:
  2214. if a.Properties == nil {
  2215. return nil, nil
  2216. }
  2217. return a.Properties.Services, nil
  2218. default:
  2219. return nil, fmt.Errorf("Allocation: StringSliceProperty: invalid property name: %s", property)
  2220. }
  2221. }
  2222. func (a *Allocation) StringMapProperty(property string) (map[string]string, error) {
  2223. switch property {
  2224. case AllocationLabelProp:
  2225. if a.Properties == nil {
  2226. return nil, nil
  2227. }
  2228. return a.Properties.Labels, nil
  2229. case AllocationAnnotationProp:
  2230. if a.Properties == nil {
  2231. return nil, nil
  2232. }
  2233. return a.Properties.Annotations, nil
  2234. default:
  2235. return nil, fmt.Errorf("Allocation: StringMapProperty: invalid property name: %s", property)
  2236. }
  2237. }
  2238. func (a *Allocation) SanitizeNaN() {
  2239. if a == nil {
  2240. return
  2241. }
  2242. if math.IsNaN(a.CPUCost) {
  2243. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCost: name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2244. a.CPUCost = 0
  2245. }
  2246. if math.IsNaN(a.CPUCostIdle) {
  2247. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCostIdle: name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2248. a.CPUCostIdle = 0
  2249. }
  2250. if math.IsNaN(a.CPUCoreRequestAverage) {
  2251. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCoreRequestAverage: name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2252. a.CPUCoreRequestAverage = 0
  2253. }
  2254. if math.IsNaN(a.CPUCoreHours) {
  2255. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCoreHours: name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2256. a.CPUCoreHours = 0
  2257. }
  2258. if math.IsNaN(a.CPUCoreUsageAverage) {
  2259. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCoreUsageAverage name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2260. a.CPUCoreUsageAverage = 0
  2261. }
  2262. if math.IsNaN(a.CPUCostAdjustment) {
  2263. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2264. a.CPUCostAdjustment = 0
  2265. }
  2266. if math.IsNaN(a.GPUHours) {
  2267. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUHours name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2268. a.GPUHours = 0
  2269. }
  2270. if math.IsNaN(a.GPURequestAverage) {
  2271. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPURequestAverage name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2272. a.GPURequestAverage = 0
  2273. }
  2274. if math.IsNaN(a.GPUUsageAverage) {
  2275. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUUsageAverage name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2276. a.GPUUsageAverage = 0
  2277. }
  2278. if math.IsNaN(a.GPUCost) {
  2279. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2280. a.GPUCost = 0
  2281. }
  2282. if math.IsNaN(a.GPUCostIdle) {
  2283. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUCostIdle name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2284. a.GPUCostIdle = 0
  2285. }
  2286. if math.IsNaN(a.GPUCostAdjustment) {
  2287. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2288. a.GPUCostAdjustment = 0
  2289. }
  2290. if math.IsNaN(a.NetworkTransferBytes) {
  2291. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkTransferBytes name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2292. a.NetworkTransferBytes = 0
  2293. }
  2294. if math.IsNaN(a.NetworkReceiveBytes) {
  2295. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkReceiveBytes name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2296. a.NetworkReceiveBytes = 0
  2297. }
  2298. if math.IsNaN(a.NetworkCost) {
  2299. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2300. a.NetworkCost = 0
  2301. }
  2302. if math.IsNaN(a.NetworkCrossZoneCost) {
  2303. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkCrossZoneCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2304. a.NetworkCrossZoneCost = 0
  2305. }
  2306. if math.IsNaN(a.NetworkCrossRegionCost) {
  2307. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkCrossRegionCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2308. a.NetworkCrossRegionCost = 0
  2309. }
  2310. if math.IsNaN(a.NetworkInternetCost) {
  2311. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkInternetCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2312. a.NetworkInternetCost = 0
  2313. }
  2314. if math.IsNaN(a.NetworkCostAdjustment) {
  2315. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2316. a.NetworkCostAdjustment = 0
  2317. }
  2318. if math.IsNaN(a.LoadBalancerCost) {
  2319. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for LoadBalancerCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2320. a.LoadBalancerCost = 0
  2321. }
  2322. if math.IsNaN(a.LoadBalancerCostAdjustment) {
  2323. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for LoadBalancerCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2324. a.LoadBalancerCostAdjustment = 0
  2325. }
  2326. if math.IsNaN(a.PVCostAdjustment) {
  2327. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for PVCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2328. a.PVCostAdjustment = 0
  2329. }
  2330. if math.IsNaN(a.RAMByteHours) {
  2331. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMByteHours name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2332. a.RAMByteHours = 0
  2333. }
  2334. if math.IsNaN(a.RAMBytesRequestAverage) {
  2335. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMBytesRequestAverage name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2336. a.RAMBytesRequestAverage = 0
  2337. }
  2338. if math.IsNaN(a.RAMBytesUsageAverage) {
  2339. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMBytesUsageAverage name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2340. a.RAMBytesUsageAverage = 0
  2341. }
  2342. if math.IsNaN(a.RAMCost) {
  2343. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2344. a.RAMCost = 0
  2345. }
  2346. if math.IsNaN(a.RAMCostIdle) {
  2347. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMCostIdle name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2348. a.RAMCostIdle = 0
  2349. }
  2350. if math.IsNaN(a.RAMCostAdjustment) {
  2351. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2352. a.RAMCostAdjustment = 0
  2353. }
  2354. if math.IsNaN(a.SharedCost) {
  2355. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for SharedCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2356. a.SharedCost = 0
  2357. }
  2358. if math.IsNaN(a.ExternalCost) {
  2359. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for ExternalCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2360. a.ExternalCost = 0
  2361. }
  2362. a.PVs.SanitizeNaN()
  2363. a.RawAllocationOnly.SanitizeNaN()
  2364. a.ProportionalAssetResourceCosts.SanitizeNaN()
  2365. a.SharedCostBreakdown.SanitizeNaN()
  2366. a.LoadBalancers.SanitizeNaN()
  2367. }
  2368. // Clone returns a new AllocationSet with a deep copy of the given
  2369. // AllocationSet's allocations.
  2370. func (as *AllocationSet) Clone() *AllocationSet {
  2371. if as == nil {
  2372. return nil
  2373. }
  2374. allocs := make(map[string]*Allocation, len(as.Allocations))
  2375. for k, v := range as.Allocations {
  2376. allocs[k] = v.Clone()
  2377. }
  2378. externalKeys := make(map[string]bool, len(as.ExternalKeys))
  2379. for k, v := range as.ExternalKeys {
  2380. externalKeys[k] = v
  2381. }
  2382. idleKeys := make(map[string]bool, len(as.IdleKeys))
  2383. for k, v := range as.IdleKeys {
  2384. idleKeys[k] = v
  2385. }
  2386. var errors []string
  2387. var warnings []string
  2388. if as.Errors != nil {
  2389. errors = make([]string, len(as.Errors))
  2390. copy(errors, as.Errors)
  2391. } else {
  2392. errors = nil
  2393. }
  2394. if as.Warnings != nil {
  2395. warnings := make([]string, len(as.Warnings))
  2396. copy(warnings, as.Warnings)
  2397. } else {
  2398. warnings = nil
  2399. }
  2400. return &AllocationSet{
  2401. Allocations: allocs,
  2402. ExternalKeys: externalKeys,
  2403. IdleKeys: idleKeys,
  2404. Window: as.Window.Clone(),
  2405. Errors: errors,
  2406. Warnings: warnings,
  2407. }
  2408. }
  2409. // Delete removes the allocation with the given name from the set
  2410. func (as *AllocationSet) Delete(name string) {
  2411. if as == nil {
  2412. return
  2413. }
  2414. delete(as.ExternalKeys, name)
  2415. delete(as.IdleKeys, name)
  2416. delete(as.Allocations, name)
  2417. }
  2418. // End returns the End time of the AllocationSet window
  2419. func (as *AllocationSet) End() time.Time {
  2420. if as == nil {
  2421. log.Warnf("AllocationSet: calling End on nil AllocationSet")
  2422. return time.Unix(0, 0)
  2423. }
  2424. if as.Window.End() == nil {
  2425. log.Warnf("AllocationSet: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.Allocations))
  2426. return time.Unix(0, 0)
  2427. }
  2428. return *as.Window.End()
  2429. }
  2430. // Get returns the Allocation at the given key in the AllocationSet
  2431. func (as *AllocationSet) Get(key string) *Allocation {
  2432. if alloc, ok := as.Allocations[key]; ok {
  2433. return alloc
  2434. }
  2435. return nil
  2436. }
  2437. // ExternalAllocations returns a map of the external allocations in the set.
  2438. // Returns clones of the actual Allocations, so mutability is not a problem.
  2439. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  2440. externals := map[string]*Allocation{}
  2441. if as.IsEmpty() {
  2442. return externals
  2443. }
  2444. for key := range as.ExternalKeys {
  2445. if alloc, ok := as.Allocations[key]; ok {
  2446. externals[key] = alloc.Clone()
  2447. }
  2448. }
  2449. return externals
  2450. }
  2451. // ExternalCost returns the total aggregated external costs of the set
  2452. func (as *AllocationSet) ExternalCost() float64 {
  2453. if as.IsEmpty() {
  2454. return 0.0
  2455. }
  2456. externalCost := 0.0
  2457. for _, alloc := range as.Allocations {
  2458. externalCost += alloc.ExternalCost
  2459. }
  2460. return externalCost
  2461. }
  2462. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  2463. // Returns clones of the actual Allocations, so mutability is not a problem.
  2464. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  2465. idles := map[string]*Allocation{}
  2466. if as.IsEmpty() {
  2467. return idles
  2468. }
  2469. for key := range as.IdleKeys {
  2470. if alloc, ok := as.Allocations[key]; ok {
  2471. idles[key] = alloc.Clone()
  2472. }
  2473. }
  2474. return idles
  2475. }
  2476. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  2477. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  2478. // there is no existing entry, one is created. Nil error response indicates success.
  2479. func (as *AllocationSet) Insert(that *Allocation) error {
  2480. if as == nil {
  2481. return fmt.Errorf("cannot insert into nil AllocationSet")
  2482. }
  2483. if as.Allocations == nil {
  2484. as.Allocations = map[string]*Allocation{}
  2485. }
  2486. if as.ExternalKeys == nil {
  2487. as.ExternalKeys = map[string]bool{}
  2488. }
  2489. if as.IdleKeys == nil {
  2490. as.IdleKeys = map[string]bool{}
  2491. }
  2492. // Add the given Allocation to the existing entry, if there is one;
  2493. // otherwise just set directly into allocations
  2494. if _, ok := as.Allocations[that.Name]; !ok {
  2495. as.Allocations[that.Name] = that
  2496. } else {
  2497. as.Allocations[that.Name].add(that)
  2498. }
  2499. // If the given Allocation is an external one, record that
  2500. if that.IsExternal() {
  2501. as.ExternalKeys[that.Name] = true
  2502. }
  2503. // If the given Allocation is an idle one, record that
  2504. if that.IsIdle() {
  2505. as.IdleKeys[that.Name] = true
  2506. }
  2507. // Expand the window, just to be safe. It's possible that the Allocation will
  2508. // be set into the map without expanding it to the AllocationSet's window.
  2509. as.Allocations[that.Name].Window = as.Allocations[that.Name].Window.Expand(as.Window)
  2510. return nil
  2511. }
  2512. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  2513. // zero allocations.
  2514. func (as *AllocationSet) IsEmpty() bool {
  2515. if as == nil || len(as.Allocations) == 0 {
  2516. return true
  2517. }
  2518. return false
  2519. }
  2520. // Length returns the number of Allocations in the set
  2521. func (as *AllocationSet) Length() int {
  2522. if as == nil {
  2523. return 0
  2524. }
  2525. return len(as.Allocations)
  2526. }
  2527. // ResetAdjustments sets all cost adjustment fields to zero
  2528. func (as *AllocationSet) ResetAdjustments() {
  2529. if as == nil {
  2530. return
  2531. }
  2532. for _, a := range as.Allocations {
  2533. a.ResetAdjustments()
  2534. }
  2535. }
  2536. // Resolution returns the AllocationSet's window duration
  2537. func (as *AllocationSet) Resolution() time.Duration {
  2538. return as.Window.Duration()
  2539. }
  2540. // GetWindow returns the AllocationSet's window
  2541. func (as *AllocationSet) GetWindow() Window {
  2542. return as.Window
  2543. }
  2544. // Set uses the given Allocation to overwrite the existing entry in the
  2545. // AllocationSet under the Allocation's name.
  2546. func (as *AllocationSet) Set(alloc *Allocation) error {
  2547. if as.IsEmpty() {
  2548. as.Allocations = map[string]*Allocation{}
  2549. as.ExternalKeys = map[string]bool{}
  2550. as.IdleKeys = map[string]bool{}
  2551. }
  2552. as.Allocations[alloc.Name] = alloc
  2553. // If the given Allocation is an external one, record that
  2554. if alloc.IsExternal() {
  2555. as.ExternalKeys[alloc.Name] = true
  2556. }
  2557. // If the given Allocation is an idle one, record that
  2558. if alloc.IsIdle() {
  2559. as.IdleKeys[alloc.Name] = true
  2560. }
  2561. return nil
  2562. }
  2563. // GetUnmountedPVCost returns the sum of all UnmountedPVCost fields across all
  2564. // allocations in the set.
  2565. func (as *AllocationSet) GetUnmountedPVCost() float64 {
  2566. upvc := 0.0
  2567. for _, a := range as.Allocations {
  2568. upvc += a.UnmountedPVCost
  2569. }
  2570. return upvc
  2571. }
  2572. // SetUnmountedPVCost sets the UnmountedPVCost field for all allocations in the
  2573. // set.
  2574. func (as *AllocationSet) SetUnmountedPVCost() float64 {
  2575. upvc := 0.0
  2576. for _, a := range as.Allocations {
  2577. upvc += a.SetUnmountedPVCost()
  2578. }
  2579. return upvc
  2580. }
  2581. // Start returns the Start time of the AllocationSet window
  2582. func (as *AllocationSet) Start() time.Time {
  2583. if as == nil {
  2584. log.Warnf("AllocationSet: calling Start on nil AllocationSet")
  2585. return time.Unix(0, 0)
  2586. }
  2587. if as.Window.Start() == nil {
  2588. log.Warnf("AllocationSet: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.Allocations))
  2589. return time.Unix(0, 0)
  2590. }
  2591. return *as.Window.Start()
  2592. }
  2593. // String represents the given Allocation as a string
  2594. func (as *AllocationSet) String() string {
  2595. if as == nil {
  2596. return "<nil>"
  2597. }
  2598. return fmt.Sprintf(
  2599. "AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  2600. as.Length(),
  2601. as.Window,
  2602. as.TotalCost())
  2603. }
  2604. // TotalCost returns the sum of all TotalCosts of the allocations contained
  2605. func (as *AllocationSet) TotalCost() float64 {
  2606. if as.IsEmpty() {
  2607. return 0.0
  2608. }
  2609. tc := 0.0
  2610. for _, a := range as.Allocations {
  2611. tc += a.TotalCost()
  2612. }
  2613. return tc
  2614. }
  2615. // UTCOffset returns the AllocationSet's configured UTCOffset.
  2616. func (as *AllocationSet) UTCOffset() time.Duration {
  2617. _, zone := as.Start().Zone()
  2618. return time.Duration(zone) * time.Second
  2619. }
  2620. func (as *AllocationSet) Accumulate(that *AllocationSet) (*AllocationSet, error) {
  2621. if as.IsEmpty() {
  2622. return that.Clone(), nil
  2623. }
  2624. if that.IsEmpty() {
  2625. return as.Clone(), nil
  2626. }
  2627. // Set start, end to min(start), max(end)
  2628. start := as.Start()
  2629. end := as.End()
  2630. if that.Start().Before(start) {
  2631. start = that.Start()
  2632. }
  2633. if that.End().After(end) {
  2634. end = that.End()
  2635. }
  2636. acc := NewAllocationSet(start, end)
  2637. for _, alloc := range as.Allocations {
  2638. err := acc.Insert(alloc)
  2639. if err != nil {
  2640. return nil, err
  2641. }
  2642. }
  2643. for _, alloc := range that.Allocations {
  2644. err := acc.Insert(alloc)
  2645. if err != nil {
  2646. return nil, err
  2647. }
  2648. }
  2649. return acc, nil
  2650. }
  2651. func (as *AllocationSet) SanitizeNaN() {
  2652. if as == nil {
  2653. return
  2654. }
  2655. for _, a := range as.Allocations {
  2656. a.SanitizeNaN()
  2657. }
  2658. }
  2659. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  2660. // be used such that the AllocationSets held are consecutive and coherent with
  2661. // respect to using the same aggregation properties, UTC offset, and
  2662. // resolution. However these rules are not necessarily enforced, so use wisely.
  2663. type AllocationSetRange struct {
  2664. Allocations []*AllocationSet
  2665. FromStore string // stores the name of the store used to retrieve the data
  2666. }
  2667. // NewAllocationSetRange instantiates a new range composed of the given
  2668. // AllocationSets in the order provided.
  2669. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  2670. return &AllocationSetRange{
  2671. Allocations: allocs,
  2672. }
  2673. }
  2674. // Get safely retrieves the AllocationSet at the given index of the range.
  2675. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  2676. if i < 0 || i >= len(asr.Allocations) {
  2677. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  2678. }
  2679. return asr.Allocations[i], nil
  2680. }
  2681. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  2682. // AllocationSet for the entire range.
  2683. func (asr *AllocationSetRange) accumulate() (*AllocationSet, error) {
  2684. var allocSet *AllocationSet
  2685. var err error
  2686. for _, as := range asr.Allocations {
  2687. allocSet, err = allocSet.Accumulate(as)
  2688. if err != nil {
  2689. return nil, err
  2690. }
  2691. }
  2692. return allocSet, nil
  2693. }
  2694. // newAccumulation clones the first available AllocationSet to use as the data structure to
  2695. // Accumulate the remaining data. This leaves the original AllocationSetRange intact.
  2696. func (asr *AllocationSetRange) newAccumulation() (*AllocationSet, error) {
  2697. // NOTE: Adding this API for consistency across SummaryAllocation and Assets, but this
  2698. // NOTE: implementation is almost identical to regular Accumulate(). The Accumulate() method
  2699. // NOTE: for Allocation returns Clone() of the input, which is required for Accumulate
  2700. // NOTE: support (unit tests are great for verifying this information).
  2701. var allocSet *AllocationSet
  2702. var err error
  2703. if asr == nil {
  2704. return nil, fmt.Errorf("nil AllocationSetRange in accumulation")
  2705. }
  2706. if len(asr.Allocations) == 0 {
  2707. return nil, fmt.Errorf("AllocationSetRange has empty AssetSet in accumulation")
  2708. }
  2709. for _, as := range asr.Allocations {
  2710. if allocSet == nil {
  2711. allocSet = as.Clone()
  2712. continue
  2713. }
  2714. var allocSetCopy *AllocationSet = nil
  2715. if as != nil {
  2716. allocSetCopy = as.Clone()
  2717. }
  2718. allocSet, err = allocSet.Accumulate(allocSetCopy)
  2719. if err != nil {
  2720. return nil, err
  2721. }
  2722. }
  2723. return allocSet, nil
  2724. }
  2725. // Accumulate sums AllocationSets based on the AccumulateOption (calendar week or calendar month).
  2726. // The accumulated set is determined by the start of the window of the allocation set.
  2727. func (asr *AllocationSetRange) Accumulate(accumulateBy AccumulateOption) (*AllocationSetRange, error) {
  2728. switch accumulateBy {
  2729. case AccumulateOptionNone:
  2730. return asr.accumulateByNone()
  2731. case AccumulateOptionAll:
  2732. return asr.accumulateByAll()
  2733. case AccumulateOptionHour:
  2734. return asr.accumulateByHour()
  2735. case AccumulateOptionDay:
  2736. return asr.accumulateByDay()
  2737. case AccumulateOptionWeek:
  2738. return asr.accumulateByWeek()
  2739. case AccumulateOptionMonth:
  2740. return asr.accumulateByMonth()
  2741. default:
  2742. // ideally, this should never happen
  2743. return nil, fmt.Errorf("unexpected error, invalid accumulateByType: %s", accumulateBy)
  2744. }
  2745. }
  2746. func (asr *AllocationSetRange) accumulateByAll() (*AllocationSetRange, error) {
  2747. var err error
  2748. var as *AllocationSet
  2749. as, err = asr.newAccumulation()
  2750. if err != nil {
  2751. return nil, fmt.Errorf("error accumulating all:%s", err)
  2752. }
  2753. accumulated := NewAllocationSetRange(as)
  2754. return accumulated, nil
  2755. }
  2756. func (asr *AllocationSetRange) accumulateByNone() (*AllocationSetRange, error) {
  2757. return asr.Clone(), nil
  2758. }
  2759. func (asr *AllocationSetRange) accumulateByHour() (*AllocationSetRange, error) {
  2760. // ensure that the summary allocation sets have a 1-hour window, if a set exists
  2761. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() != time.Hour {
  2762. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", asr.Allocations[0].Window.Duration())
  2763. }
  2764. return asr.Clone(), nil
  2765. }
  2766. func (asr *AllocationSetRange) accumulateByDay() (*AllocationSetRange, error) {
  2767. // if the allocation set window is 1-day, just return the existing allocation set range
  2768. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() == time.Hour*24 {
  2769. return asr, nil
  2770. }
  2771. var toAccumulate *AllocationSetRange
  2772. result := NewAllocationSetRange()
  2773. for i, as := range asr.Allocations {
  2774. if as.Window.Duration() != time.Hour {
  2775. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", as.Window.Duration())
  2776. }
  2777. hour := as.Window.Start().Hour()
  2778. if toAccumulate == nil {
  2779. toAccumulate = NewAllocationSetRange()
  2780. as = as.Clone()
  2781. }
  2782. toAccumulate.Append(as)
  2783. asAccumulated, err := toAccumulate.accumulate()
  2784. if err != nil {
  2785. return nil, fmt.Errorf("error accumulating result: %s", err)
  2786. }
  2787. toAccumulate = NewAllocationSetRange(asAccumulated)
  2788. if hour == 23 || i == len(asr.Allocations)-1 {
  2789. if length := len(toAccumulate.Allocations); length != 1 {
  2790. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2791. }
  2792. result.Append(toAccumulate.Allocations[0])
  2793. toAccumulate = nil
  2794. }
  2795. }
  2796. return result, nil
  2797. }
  2798. func (asr *AllocationSetRange) accumulateByMonth() (*AllocationSetRange, error) {
  2799. var toAccumulate *AllocationSetRange
  2800. result := NewAllocationSetRange()
  2801. for i, as := range asr.Allocations {
  2802. if as.Window.Duration() != time.Hour*24 {
  2803. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  2804. }
  2805. _, month, _ := as.Window.Start().Date()
  2806. _, nextDayMonth, _ := as.Window.Start().Add(time.Hour * 24).Date()
  2807. if toAccumulate == nil {
  2808. toAccumulate = NewAllocationSetRange()
  2809. as = as.Clone()
  2810. }
  2811. toAccumulate.Append(as)
  2812. asAccumulated, err := toAccumulate.accumulate()
  2813. if err != nil {
  2814. return nil, fmt.Errorf("error accumulating result: %s", err)
  2815. }
  2816. toAccumulate = NewAllocationSetRange(asAccumulated)
  2817. // either the month has ended, or there are no more allocation sets
  2818. if month != nextDayMonth || i == len(asr.Allocations)-1 {
  2819. if length := len(toAccumulate.Allocations); length != 1 {
  2820. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2821. }
  2822. result.Append(toAccumulate.Allocations[0])
  2823. toAccumulate = nil
  2824. }
  2825. }
  2826. return result, nil
  2827. }
  2828. func (asr *AllocationSetRange) accumulateByWeek() (*AllocationSetRange, error) {
  2829. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() == timeutil.Week {
  2830. return asr, nil
  2831. }
  2832. var toAccumulate *AllocationSetRange
  2833. result := NewAllocationSetRange()
  2834. for i, as := range asr.Allocations {
  2835. if as.Window.Duration() != time.Hour*24 {
  2836. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  2837. }
  2838. dayOfWeek := as.Window.Start().Weekday()
  2839. if toAccumulate == nil {
  2840. toAccumulate = NewAllocationSetRange()
  2841. as = as.Clone()
  2842. }
  2843. toAccumulate.Append(as)
  2844. asAccumulated, err := toAccumulate.accumulate()
  2845. if err != nil {
  2846. return nil, fmt.Errorf("error accumulating result: %s", err)
  2847. }
  2848. toAccumulate = NewAllocationSetRange(asAccumulated)
  2849. // current assumption is the week always ends on Saturday, or there are no more allocation sets
  2850. if dayOfWeek == time.Saturday || i == len(asr.Allocations)-1 {
  2851. if length := len(toAccumulate.Allocations); length != 1 {
  2852. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2853. }
  2854. result.Append(toAccumulate.Allocations[0])
  2855. toAccumulate = nil
  2856. }
  2857. }
  2858. return result, nil
  2859. }
  2860. // AggregateBy aggregates each AllocationSet in the range by the given
  2861. // properties and options.
  2862. func (asr *AllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  2863. aggRange := &AllocationSetRange{Allocations: []*AllocationSet{}}
  2864. for _, as := range asr.Allocations {
  2865. err := as.AggregateBy(aggregateBy, options)
  2866. if err != nil {
  2867. return err
  2868. }
  2869. aggRange.Allocations = append(aggRange.Allocations, as)
  2870. }
  2871. asr.Allocations = aggRange.Allocations
  2872. return nil
  2873. }
  2874. // Append appends the given AllocationSet to the end of the range. It does not
  2875. // validate whether or not that violates window continuity.
  2876. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  2877. asr.Allocations = append(asr.Allocations, that)
  2878. }
  2879. // InsertRange merges the given AllocationSetRange into the receiving one by
  2880. // lining up sets with matching windows, then inserting each allocation from
  2881. // the given ASR into the respective set in the receiving ASR. If the given
  2882. // ASR contains an AllocationSet from a window that does not exist in the
  2883. // receiving ASR, then an error is returned. However, the given ASR does not
  2884. // need to cover the full range of the receiver.
  2885. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  2886. if asr == nil {
  2887. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  2888. }
  2889. // Providing an empty or nil set range is a no-op
  2890. if that == nil {
  2891. return nil
  2892. }
  2893. // keys maps window to index in asr
  2894. keys := map[string]int{}
  2895. for i, as := range asr.Allocations {
  2896. if as == nil {
  2897. continue
  2898. }
  2899. keys[as.Window.String()] = i
  2900. }
  2901. // Nothing to merge, so simply return
  2902. if len(keys) == 0 {
  2903. return nil
  2904. }
  2905. var err error
  2906. for _, thatAS := range that.Allocations {
  2907. if thatAS == nil || err != nil {
  2908. continue
  2909. }
  2910. // Find matching AllocationSet in asr
  2911. i, ok := keys[thatAS.Window.String()]
  2912. if !ok {
  2913. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  2914. continue
  2915. }
  2916. as, err := asr.Get(i)
  2917. if err != nil {
  2918. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  2919. continue
  2920. }
  2921. // Insert each Allocation from the given set
  2922. for _, alloc := range thatAS.Allocations {
  2923. err = as.Insert(alloc)
  2924. if err != nil {
  2925. err = fmt.Errorf("error inserting allocation: %s", err)
  2926. continue
  2927. }
  2928. }
  2929. }
  2930. // err might be nil
  2931. return err
  2932. }
  2933. // Length returns the length of the range, which is zero if nil
  2934. func (asr *AllocationSetRange) Length() int {
  2935. if asr == nil || asr.Allocations == nil {
  2936. return 0
  2937. }
  2938. return len(asr.Allocations)
  2939. }
  2940. // Slice copies the underlying slice of AllocationSets, maintaining order,
  2941. // and returns the copied slice.
  2942. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  2943. if asr == nil || asr.Allocations == nil {
  2944. return nil
  2945. }
  2946. copy := []*AllocationSet{}
  2947. for _, as := range asr.Allocations {
  2948. copy = append(copy, as.Clone())
  2949. }
  2950. return copy
  2951. }
  2952. // String represents the given AllocationSetRange as a string
  2953. func (asr *AllocationSetRange) String() string {
  2954. if asr == nil {
  2955. return "<nil>"
  2956. }
  2957. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  2958. }
  2959. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  2960. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  2961. // are sets with conflicting UTCOffsets (just returns the first).
  2962. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  2963. if asr.Length() == 0 {
  2964. return 0
  2965. }
  2966. as, err := asr.Get(0)
  2967. if err != nil {
  2968. return 0
  2969. }
  2970. return as.UTCOffset()
  2971. }
  2972. // Window returns the full window that the AllocationSetRange spans, from the
  2973. // start of the first AllocationSet to the end of the last one.
  2974. func (asr *AllocationSetRange) Window() Window {
  2975. if asr == nil || asr.Length() == 0 {
  2976. return NewWindow(nil, nil)
  2977. }
  2978. start := asr.Allocations[0].Start()
  2979. end := asr.Allocations[asr.Length()-1].End()
  2980. return NewWindow(&start, &end)
  2981. }
  2982. // Start returns the earliest start of all Allocations in the AllocationSetRange.
  2983. // It returns an error if there are no allocations.
  2984. func (asr *AllocationSetRange) Start() (time.Time, error) {
  2985. start := time.Time{}
  2986. if asr == nil {
  2987. return start, fmt.Errorf("had no data to compute a start from")
  2988. }
  2989. firstStartNotSet := true
  2990. for _, as := range asr.Allocations {
  2991. for _, a := range as.Allocations {
  2992. if firstStartNotSet {
  2993. start = a.Start
  2994. firstStartNotSet = false
  2995. }
  2996. if a.Start.Before(start) {
  2997. start = a.Start
  2998. }
  2999. }
  3000. }
  3001. if firstStartNotSet {
  3002. return start, fmt.Errorf("had no data to compute a start from")
  3003. }
  3004. return start, nil
  3005. }
  3006. // End returns the latest end of all Allocations in the AllocationSetRange.
  3007. // It returns an error if there are no allocations.
  3008. func (asr *AllocationSetRange) End() (time.Time, error) {
  3009. end := time.Time{}
  3010. if asr == nil {
  3011. return end, fmt.Errorf("had no data to compute an end from")
  3012. }
  3013. firstEndNotSet := true
  3014. for _, as := range asr.Allocations {
  3015. for _, a := range as.Allocations {
  3016. if firstEndNotSet {
  3017. end = a.End
  3018. firstEndNotSet = false
  3019. }
  3020. if a.End.After(end) {
  3021. end = a.End
  3022. }
  3023. }
  3024. }
  3025. if firstEndNotSet {
  3026. return end, fmt.Errorf("had no data to compute an end from")
  3027. }
  3028. return end, nil
  3029. }
  3030. // StartAndEnd iterates over all AssetSets in the AssetSetRange and returns the earliest start and
  3031. // latest end over the entire range
  3032. func (asr *AllocationSetRange) StartAndEnd() (time.Time, time.Time, error) {
  3033. start := time.Time{}
  3034. end := time.Time{}
  3035. if asr == nil {
  3036. return start, end, fmt.Errorf("had no data to compute a start and end from")
  3037. }
  3038. firstStartNotSet := true
  3039. firstEndNotSet := true
  3040. for _, as := range asr.Allocations {
  3041. for _, a := range as.Allocations {
  3042. if firstStartNotSet {
  3043. start = a.Start
  3044. firstStartNotSet = false
  3045. }
  3046. if a.Start.Before(start) {
  3047. start = a.Start
  3048. }
  3049. if firstEndNotSet {
  3050. end = a.End
  3051. firstEndNotSet = false
  3052. }
  3053. if a.End.After(end) {
  3054. end = a.End
  3055. }
  3056. }
  3057. }
  3058. if firstStartNotSet {
  3059. return start, end, fmt.Errorf("had no data to compute a start from")
  3060. }
  3061. if firstEndNotSet {
  3062. return start, end, fmt.Errorf("had no data to compute an end from")
  3063. }
  3064. return start, end, nil
  3065. }
  3066. // Minutes returns the duration, in minutes, between the earliest start
  3067. // and the latest end of all assets in the AllocationSetRange.
  3068. func (asr *AllocationSetRange) Minutes() float64 {
  3069. if asr == nil {
  3070. return 0
  3071. }
  3072. start, end, err := asr.StartAndEnd()
  3073. if err != nil {
  3074. return 0
  3075. }
  3076. duration := end.Sub(start)
  3077. return duration.Minutes()
  3078. }
  3079. // TotalCost returns the sum of all TotalCosts of the allocations contained
  3080. func (asr *AllocationSetRange) TotalCost() float64 {
  3081. if asr == nil || len(asr.Allocations) == 0 {
  3082. return 0.0
  3083. }
  3084. tc := 0.0
  3085. for _, as := range asr.Allocations {
  3086. tc += as.TotalCost()
  3087. }
  3088. return tc
  3089. }
  3090. // Clone returns a new AllocationSetRange cloned from the existing ASR
  3091. func (asr *AllocationSetRange) Clone() *AllocationSetRange {
  3092. sasrClone := NewAllocationSetRange()
  3093. sasrClone.FromStore = asr.FromStore
  3094. for _, as := range asr.Allocations {
  3095. asClone := as.Clone()
  3096. sasrClone.Append(asClone)
  3097. }
  3098. return sasrClone
  3099. }