allocation.go 117 KB

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