allocation.go 121 KB

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