allocation.go 122 KB

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