allocation.go 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717
  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. // Sum GPU Allocations
  1236. if that.GPUAllocation != nil {
  1237. if a.GPUAllocation == nil {
  1238. a.GPUAllocation = that.GPUAllocation.Clone()
  1239. } else {
  1240. if a.GPUAllocation.GPUUsageAverage != nil && that.GPUAllocation.GPUUsageAverage != nil {
  1241. *a.GPUAllocation.GPUUsageAverage += *that.GPUAllocation.GPUUsageAverage
  1242. }
  1243. if a.GPUAllocation.GPURequestAverage != nil && that.GPUAllocation.GPURequestAverage != nil {
  1244. *a.GPUAllocation.GPURequestAverage += *that.GPUAllocation.GPURequestAverage
  1245. }
  1246. }
  1247. }
  1248. // Any data that is in a "raw allocation only" is not valid in any
  1249. // sort of cumulative Allocation (like one that is added).
  1250. a.RawAllocationOnly = nil
  1251. }
  1252. func (thisLbAllocs LbAllocations) Add(thatLbAllocs LbAllocations) LbAllocations {
  1253. // loop through both sets of LB allocations, building a new LBAllocations that has the summed set
  1254. mergedLbAllocs := thisLbAllocs.Clone()
  1255. if thatLbAllocs != nil {
  1256. if mergedLbAllocs == nil {
  1257. mergedLbAllocs = LbAllocations{}
  1258. }
  1259. for lbKey, thatlbAlloc := range thatLbAllocs {
  1260. thisLbAlloc, ok := mergedLbAllocs[lbKey]
  1261. if !ok {
  1262. thisLbAlloc = &LbAllocation{
  1263. Service: thatlbAlloc.Service,
  1264. Cost: thatlbAlloc.Cost,
  1265. Hours: thatlbAlloc.Hours,
  1266. }
  1267. mergedLbAllocs[lbKey] = thisLbAlloc
  1268. } else {
  1269. thisLbAlloc.Cost += thatlbAlloc.Cost
  1270. thisLbAlloc.Hours += thatlbAlloc.Hours
  1271. }
  1272. }
  1273. }
  1274. return mergedLbAllocs
  1275. }
  1276. func (thisLbAllocs LbAllocations) SanitizeNaN() {
  1277. for _, lba := range thisLbAllocs {
  1278. lba.SanitizeNaN()
  1279. }
  1280. }
  1281. // AllocationSet stores a set of Allocations, each with a unique name, that share
  1282. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  1283. type AllocationSet struct {
  1284. Allocations map[string]*Allocation
  1285. ExternalKeys map[string]bool
  1286. IdleKeys map[string]bool
  1287. FromSource string // stores the name of the source used to compute the data
  1288. Window Window
  1289. Warnings []string
  1290. Errors []string
  1291. }
  1292. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  1293. // the given list of Allocations
  1294. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  1295. as := &AllocationSet{
  1296. Allocations: map[string]*Allocation{},
  1297. ExternalKeys: map[string]bool{},
  1298. IdleKeys: map[string]bool{},
  1299. Window: NewWindow(&start, &end),
  1300. }
  1301. for _, a := range allocs {
  1302. as.Insert(a)
  1303. }
  1304. return as
  1305. }
  1306. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  1307. // filtering results and sharing allocations. FilterFuncs are a list of match
  1308. // functions such that, if any function fails, the allocation is ignored.
  1309. // ShareFuncs are a list of match functions such that, if any function
  1310. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  1311. // simple flag for sharing idle resources.
  1312. type AllocationAggregationOptions struct {
  1313. AllocationTotalsStore AllocationTotalsStore
  1314. Filter filter.Filter
  1315. IdleByNode bool
  1316. IncludeProportionalAssetResourceCosts bool
  1317. LabelConfig *LabelConfig
  1318. MergeUnallocated bool
  1319. Reconcile bool
  1320. ReconcileNetwork bool
  1321. Share filter.Filter
  1322. SharedNamespaces []string
  1323. SharedLabels map[string][]string
  1324. ShareIdle string
  1325. ShareSplit string
  1326. SharedHourlyCosts map[string]float64
  1327. IncludeSharedCostBreakdown bool
  1328. SplitIdle bool
  1329. IncludeAggregatedMetadata bool
  1330. }
  1331. func isFilterEmpty(filter AllocationMatcher) bool {
  1332. if _, isAllPass := filter.(*matcher.AllPass[*Allocation]); isAllPass {
  1333. return true
  1334. }
  1335. return false
  1336. }
  1337. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  1338. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  1339. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  1340. func (as *AllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  1341. // The order of operations for aggregating allocations is as follows:
  1342. //
  1343. // 1. Partition external, idle, and shared allocations into separate sets.
  1344. // Also, create the aggSet into which the results will be aggregated.
  1345. //
  1346. // 2. Compute sharing coefficients for idle and shared resources
  1347. // a) if idle allocation is to be shared, or if proportional asset
  1348. // resource costs are to be included, then compute idle coefficients
  1349. // (proportional asset resource costs are derived from idle coefficients)
  1350. // b) if proportional asset costs are to be included, derive them from
  1351. // idle coefficients and add them to the allocations.
  1352. // c) if idle allocation is NOT shared, but filters are present, compute
  1353. // idle filtration coefficients for the purpose of only returning the
  1354. // portion of idle allocation that would have been shared with the
  1355. // unfiltered results. (See unit tests 5.a,b,c)
  1356. // d) generate shared allocation for them given shared overhead, which
  1357. // must happen after (2a) and (2b)
  1358. // e) if there are shared resources, compute share coefficients
  1359. //
  1360. // 3. Drop any allocation that fails any of the filters
  1361. //
  1362. // 4. Distribute idle allocations according to the idle coefficients
  1363. //
  1364. // 5. Generate aggregation key and insert allocation into the output set
  1365. //
  1366. // 6. If idle is shared and resources are shared, some idle might be shared
  1367. // with a shared resource. Distribute that to the shared resources
  1368. // prior to sharing them with the aggregated results.
  1369. //
  1370. // 7. Apply idle filtration coefficients from step (2b)
  1371. //
  1372. // 8. Distribute shared allocations according to the share coefficients.
  1373. //
  1374. // 9. If there are external allocations that can be aggregated into
  1375. // the output (i.e. they can be used to generate a valid key for
  1376. // the given properties) then aggregate; otherwise... ignore them?
  1377. //
  1378. // 10. Distribute any undistributed idle, in the case that idle
  1379. // coefficients end up being zero and some idle is not shared.
  1380. //
  1381. // 11. If the merge idle option is enabled, merge any remaining idle
  1382. // allocations into a single idle allocation. If there was any idle
  1383. // whose costs were not distributed because there was no usage of a
  1384. // specific resource type, re-add the idle to the aggregation with
  1385. // only that type.
  1386. if as.IsEmpty() {
  1387. return nil
  1388. }
  1389. if options == nil {
  1390. options = &AllocationAggregationOptions{}
  1391. }
  1392. if options.LabelConfig == nil {
  1393. options.LabelConfig = NewLabelConfig()
  1394. }
  1395. // idleFiltrationCoefficients relies on this being explicitly set
  1396. if options.ShareIdle != ShareWeighted {
  1397. options.ShareIdle = ShareNone
  1398. }
  1399. var filter AllocationMatcher
  1400. if options.Filter == nil {
  1401. filter = &matcher.AllPass[*Allocation]{}
  1402. } else {
  1403. compiler := NewAllocationMatchCompiler(options.LabelConfig)
  1404. var err error
  1405. filter, err = compiler.Compile(options.Filter)
  1406. if err != nil {
  1407. return fmt.Errorf("compiling filter '%s': %w", ast.ToPreOrderShortString(options.Filter), err)
  1408. }
  1409. }
  1410. if filter == nil {
  1411. return fmt.Errorf("unexpected nil filter")
  1412. }
  1413. var sharer AllocationMatcher
  1414. if options.Share != nil {
  1415. compiler := NewAllocationMatchCompiler(options.LabelConfig)
  1416. var err error
  1417. sharer, err = compiler.Compile(options.Share)
  1418. if err != nil {
  1419. return fmt.Errorf("compiling sharer '%s': %w", ast.ToPreOrderShortString(options.Filter), err)
  1420. }
  1421. }
  1422. var allocatedTotalsMap map[string]map[string]float64
  1423. // If aggregateBy is nil, we don't aggregate anything. On the other hand,
  1424. // an empty slice implies that we should aggregate everything. See
  1425. // generateKey for why that makes sense.
  1426. shouldAggregate := aggregateBy != nil
  1427. shouldFilter := !isFilterEmpty(filter)
  1428. shouldShare := len(options.SharedHourlyCosts) > 0 || sharer != nil
  1429. if !shouldAggregate && !shouldFilter && !shouldShare && options.ShareIdle == ShareNone && !options.IncludeProportionalAssetResourceCosts {
  1430. // There is nothing for AggregateBy to do, so simply return nil
  1431. // before returning, set aggregated metadata inclusion in properties
  1432. if options.IncludeAggregatedMetadata {
  1433. for index := range as.Allocations {
  1434. as.Allocations[index].Properties.AggregatedMetadata = true
  1435. }
  1436. }
  1437. return nil
  1438. }
  1439. // aggSet will collect the aggregated allocations
  1440. aggSet := &AllocationSet{
  1441. Window: as.Window.Clone(),
  1442. }
  1443. // externalSet will collect external allocations
  1444. externalSet := &AllocationSet{
  1445. Window: as.Window.Clone(),
  1446. }
  1447. // idleSet will be shared among aggSet after initial aggregation
  1448. // is complete
  1449. idleSet := &AllocationSet{
  1450. Window: as.Window.Clone(),
  1451. }
  1452. // parcSet is used to compute proportionalAssetResourceCosts
  1453. // for surfacing in the API
  1454. parcSet := &AllocationSet{
  1455. Window: as.Window.Clone(),
  1456. }
  1457. // shareSet will be shared among aggSet after initial aggregation
  1458. // is complete
  1459. shareSet := &AllocationSet{
  1460. Window: as.Window.Clone(),
  1461. }
  1462. // (1) Loop and find all of the external, idle, and shared allocations. Add
  1463. // them to their respective sets, removing them from the set of allocations
  1464. // to aggregate.
  1465. for _, alloc := range as.Allocations {
  1466. alloc.Properties.AggregatedMetadata = options.IncludeAggregatedMetadata
  1467. // build a parallel set of allocations to only be used
  1468. // for computing PARCs
  1469. if options.IncludeProportionalAssetResourceCosts {
  1470. parcSet.Insert(alloc.Clone())
  1471. }
  1472. // External allocations get aggregated post-hoc (see step 6) and do
  1473. // not necessarily contain complete sets of properties, so they are
  1474. // moved to a separate AllocationSet.
  1475. if alloc.IsExternal() {
  1476. delete(as.ExternalKeys, alloc.Name)
  1477. delete(as.Allocations, alloc.Name)
  1478. externalSet.Insert(alloc)
  1479. continue
  1480. }
  1481. // Idle allocations should be separated into idleSet if they are to be
  1482. // shared later on. If they are not to be shared, then add them to the
  1483. // aggSet like any other allocation.
  1484. if alloc.IsIdle() {
  1485. delete(as.IdleKeys, alloc.Name)
  1486. delete(as.Allocations, alloc.Name)
  1487. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  1488. idleSet.Insert(alloc)
  1489. } else {
  1490. aggSet.Insert(alloc)
  1491. }
  1492. continue
  1493. }
  1494. // Shared allocations must be identified and separated prior to
  1495. // aggregation and filtering. That is, if any of the ShareFuncs return
  1496. // true for the allocation, then move it to shareSet.
  1497. if sharer != nil && sharer.Matches(alloc) {
  1498. delete(as.IdleKeys, alloc.Name)
  1499. delete(as.Allocations, alloc.Name)
  1500. shareSet.Insert(alloc)
  1501. continue
  1502. }
  1503. }
  1504. // It's possible that no more un-shared, non-idle, non-external allocations
  1505. // remain at this point. This always results in an emptySet, so return early.
  1506. if len(as.Allocations) == 0 {
  1507. emptySet := &AllocationSet{
  1508. Window: as.Window.Clone(),
  1509. }
  1510. as.Allocations = emptySet.Allocations
  1511. return nil
  1512. }
  1513. // (2) In order to correctly share idle and shared costs, we first compute
  1514. // sharing coefficients, which represent the proportion of each cost to
  1515. // share with each allocation. Idle allocations are shared per-cluster or per-node,
  1516. // per-allocation, and per-resource, while shared resources are shared per-
  1517. // allocation only.
  1518. //
  1519. // For an idleCoefficient example, the entries:
  1520. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  1521. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  1522. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  1523. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  1524. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  1525. // RAM costs.
  1526. //
  1527. // For a shareCoefficient example, the entries:
  1528. // [namespace2] = 0.666667
  1529. // [__filtered__] = 0.333333
  1530. // mean that the post-aggregation allocation "namespace2" will receive
  1531. // 66.67% of the shared resource costs, while the remaining 33.33% will
  1532. // be filtered out, as they were shared with allocations that did not pass
  1533. // one of the given filters.
  1534. //
  1535. // In order to maintain stable results when multiple operations are being
  1536. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  1537. // coefficients are computed for the full set of allocations prior to
  1538. // adding shared overhead and prior to applying filters.
  1539. var err error
  1540. // (2a) If there are idle costs to be shared, compute the coefficients for
  1541. // sharing them among the non-idle, non-aggregated allocations (including
  1542. // the shared allocations).
  1543. var idleCoefficients map[string]map[string]map[string]float64
  1544. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  1545. idleCoefficients, allocatedTotalsMap, err = computeIdleCoeffs(options, as, shareSet)
  1546. if err != nil {
  1547. log.Warnf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  1548. return fmt.Errorf("error computing idle coefficients: %s", err)
  1549. }
  1550. }
  1551. // (2b) If proportional asset resource costs are to be included, compute them
  1552. // and add them to the allocations.
  1553. if options.IncludeProportionalAssetResourceCosts {
  1554. err := deriveProportionalAssetResourceCosts(options, as, shareSet, parcSet)
  1555. if err != nil {
  1556. log.Debugf("AggregateBy: failed to derive proportional asset resource costs from idle coefficients: %s", err)
  1557. return fmt.Errorf("AggregateBy: failed to derive proportional asset resource costs from idle coefficients: %s", err)
  1558. }
  1559. }
  1560. // (2c) If idle costs are not to be shared, but there are filters, then we
  1561. // need to track the amount of each idle allocation to "filter" in order to
  1562. // maintain parity with the results when idle is shared. That is, we want
  1563. // to return only the idle costs that would have been shared with the given
  1564. // results, even if the filter had not been applied.
  1565. //
  1566. // For example, consider these results from aggregating by namespace with
  1567. // two clusters:
  1568. //
  1569. // namespace1: 25.00
  1570. // namespace2: 30.00
  1571. // namespace3: 15.00
  1572. // idle: 30.00
  1573. //
  1574. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  1575. // reduced by the amount that existed on cluster2. Then, idle must also be
  1576. // reduced by the relevant amount:
  1577. //
  1578. // namespace1: 25.00
  1579. // namespace2: 15.00
  1580. // idle: 20.00
  1581. //
  1582. // Note that this can happen for any field, not just cluster, so we again
  1583. // need to track this on a per-cluster or per-node, per-allocation, per-resource basis.
  1584. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  1585. if shouldFilter && options.ShareIdle == ShareNone {
  1586. idleFiltrationCoefficients, _, err = computeIdleCoeffs(options, as, shareSet)
  1587. if err != nil {
  1588. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  1589. }
  1590. }
  1591. // (2d) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  1592. // come after idle coefficients are computed so that allocations generated
  1593. // by shared overhead do not skew the idle coefficient computation.
  1594. for name, cost := range options.SharedHourlyCosts {
  1595. if cost > 0.0 {
  1596. hours := as.Resolution().Hours()
  1597. // If set ends in the future, adjust hours accordingly
  1598. diff := time.Since(as.End())
  1599. if diff < 0.0 {
  1600. hours += diff.Hours()
  1601. }
  1602. totalSharedCost := cost * hours
  1603. shareSet.Insert(&Allocation{
  1604. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  1605. Start: as.Start(),
  1606. End: as.End(),
  1607. SharedCost: totalSharedCost,
  1608. 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.
  1609. })
  1610. }
  1611. }
  1612. // (2e) Compute share coefficients for shared resources. These are computed
  1613. // after idle coefficients, and are computed for the aggregated allocations
  1614. // of the main allocation set. See above for details and an example.
  1615. var shareCoefficients map[string]float64
  1616. if shareSet.Length() > 0 {
  1617. shareCoefficients, err = computeShareCoeffs(aggregateBy, options, as)
  1618. if err != nil {
  1619. return fmt.Errorf("error computing share coefficients: %s", err)
  1620. }
  1621. }
  1622. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  1623. for _, alloc := range as.Allocations {
  1624. idleId, err := alloc.getIdleId(options)
  1625. if err != nil {
  1626. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  1627. }
  1628. // (3) If the allocation does not match the filter, immediately skip the
  1629. // allocation.
  1630. if !filter.Matches(alloc) {
  1631. // If we are tracking idle filtration coefficients, delete the
  1632. // entry corresponding to the filtered allocation. (Deleting the
  1633. // entry will result in that proportional amount being removed
  1634. // from the idle allocation at the end of the process.)
  1635. if idleFiltrationCoefficients != nil {
  1636. if ifcc, ok := idleFiltrationCoefficients[idleId]; ok {
  1637. delete(ifcc, alloc.Name)
  1638. }
  1639. }
  1640. continue
  1641. }
  1642. // (4) Distribute idle allocations according to the idle coefficients
  1643. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  1644. // all idle allocations will be in the aggSet at this point, so idleSet
  1645. // will be empty and we won't enter this block.
  1646. if idleSet.Length() > 0 {
  1647. // Distribute idle allocations by coefficient per-idleId, per-allocation
  1648. for _, idleAlloc := range idleSet.Allocations {
  1649. // Only share idle if the idleId matches; i.e. the allocation
  1650. // is from the same idleId as the idle costs
  1651. iaidleId, err := idleAlloc.getIdleId(options)
  1652. if err != nil {
  1653. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  1654. return err
  1655. }
  1656. if iaidleId != idleId {
  1657. continue
  1658. }
  1659. // Make sure idle coefficients exist
  1660. if _, ok := idleCoefficients[idleId]; !ok {
  1661. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  1662. continue
  1663. }
  1664. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  1665. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  1666. continue
  1667. }
  1668. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  1669. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  1670. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  1671. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  1672. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  1673. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  1674. alloc.CPUCost += idleCPUCost
  1675. alloc.GPUCost += idleGPUCost
  1676. alloc.RAMCost += idleRAMCost
  1677. }
  1678. }
  1679. // (5) generate key to use for aggregation-by-key and allocation name
  1680. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  1681. alloc.Name = key
  1682. if options.MergeUnallocated && alloc.IsUnallocated() {
  1683. alloc.Name = UnallocatedSuffix
  1684. }
  1685. // Inserting the allocation with the generated key for a name will
  1686. // perform the actual basic aggregation step.
  1687. aggSet.Insert(alloc)
  1688. }
  1689. // (6) If idle is shared and resources are shared, it's possible that some
  1690. // amount of idle cost will be shared with a shared resource. Distribute
  1691. // that idle allocation, if it exists, to the respective shared allocations
  1692. // before sharing with the aggregated allocations.
  1693. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  1694. for _, alloc := range shareSet.Allocations {
  1695. idleId, err := alloc.getIdleId(options)
  1696. if err != nil {
  1697. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  1698. }
  1699. // Distribute idle allocations by coefficient per-idleId, per-allocation
  1700. for _, idleAlloc := range idleSet.Allocations {
  1701. // Only share idle if the idleId matches; i.e. the allocation
  1702. // is from the same idleId as the idle costs
  1703. iaidleId, _ := idleAlloc.getIdleId(options)
  1704. if iaidleId != idleId {
  1705. continue
  1706. }
  1707. // Make sure idle coefficients exist
  1708. if _, ok := idleCoefficients[idleId]; !ok {
  1709. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  1710. continue
  1711. }
  1712. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  1713. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  1714. continue
  1715. }
  1716. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  1717. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  1718. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  1719. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  1720. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  1721. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  1722. alloc.CPUCost += idleCPUCost
  1723. alloc.GPUCost += idleGPUCost
  1724. alloc.RAMCost += idleRAMCost
  1725. }
  1726. }
  1727. }
  1728. // groupingIdleFiltrationCoeffs is used to track per-resource idle
  1729. // coefficients on a cluster-by-cluster or node-by-node basis depending
  1730. // on the IdleByNode option. It is, essentially, an aggregation of
  1731. // idleFiltrationCoefficients after they have been
  1732. // filtered above (in step 3)
  1733. var groupingIdleFiltrationCoeffs map[string]map[string]float64
  1734. if idleFiltrationCoefficients != nil {
  1735. groupingIdleFiltrationCoeffs = map[string]map[string]float64{}
  1736. for idleId, m := range idleFiltrationCoefficients {
  1737. if _, ok := groupingIdleFiltrationCoeffs[idleId]; !ok {
  1738. groupingIdleFiltrationCoeffs[idleId] = map[string]float64{
  1739. "cpu": 0.0,
  1740. "gpu": 0.0,
  1741. "ram": 0.0,
  1742. }
  1743. }
  1744. for _, n := range m {
  1745. for resource, val := range n {
  1746. groupingIdleFiltrationCoeffs[idleId][resource] += val
  1747. }
  1748. }
  1749. }
  1750. }
  1751. // (7) If we have both un-shared idle allocations and idle filtration
  1752. // coefficients then apply those. See step (2b) for an example.
  1753. if len(aggSet.IdleKeys) > 0 && groupingIdleFiltrationCoeffs != nil {
  1754. for idleKey := range aggSet.IdleKeys {
  1755. idleAlloc := aggSet.Get(idleKey)
  1756. iaidleId, err := idleAlloc.getIdleId(options)
  1757. if err != nil {
  1758. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  1759. return err
  1760. }
  1761. if resourceCoeffs, ok := groupingIdleFiltrationCoeffs[iaidleId]; ok {
  1762. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  1763. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  1764. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  1765. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  1766. idleAlloc.GPUCost *= resourceCoeffs["gpu"]
  1767. idleAlloc.GPUHours *= resourceCoeffs["gpu"]
  1768. }
  1769. }
  1770. }
  1771. // (8) Distribute shared allocations according to the share coefficients.
  1772. if shareSet.Length() > 0 {
  1773. for _, alloc := range aggSet.Allocations {
  1774. for _, sharedAlloc := range shareSet.Allocations {
  1775. if _, ok := shareCoefficients[alloc.Name]; !ok {
  1776. if !alloc.IsIdle() && !alloc.IsUnmounted() {
  1777. log.Warnf("AllocationSet.AggregateBy: error getting share coefficient for '%s'", alloc.Name)
  1778. }
  1779. continue
  1780. }
  1781. if options.IncludeSharedCostBreakdown {
  1782. if alloc.SharedCostBreakdown == nil {
  1783. alloc.SharedCostBreakdown = map[string]SharedCostBreakdown{}
  1784. }
  1785. sharedCostName, err := sharedAlloc.determineSharingName(options)
  1786. if err != nil {
  1787. return fmt.Errorf("failed to group shared costs: %s", err)
  1788. }
  1789. // check if current allocation is a shared flat overhead cost
  1790. if strings.Contains(sharedAlloc.Name, SharedSuffix) {
  1791. sharedCostName = "overheadCost"
  1792. }
  1793. scb := SharedCostBreakdown{
  1794. Name: sharedCostName,
  1795. TotalCost: sharedAlloc.TotalCost() * shareCoefficients[alloc.Name],
  1796. CPUCost: sharedAlloc.CPUTotalCost() * shareCoefficients[alloc.Name],
  1797. GPUCost: sharedAlloc.GPUTotalCost() * shareCoefficients[alloc.Name],
  1798. RAMCost: sharedAlloc.RAMTotalCost() * shareCoefficients[alloc.Name],
  1799. PVCost: sharedAlloc.PVCost() * shareCoefficients[alloc.Name],
  1800. NetworkCost: sharedAlloc.NetworkTotalCost() * shareCoefficients[alloc.Name],
  1801. LBCost: sharedAlloc.LBTotalCost() * shareCoefficients[alloc.Name],
  1802. ExternalCost: sharedAlloc.ExternalCost * shareCoefficients[alloc.Name],
  1803. }
  1804. // fmt.Printf("shared cost: %+v", scb)
  1805. alloc.SharedCostBreakdown.Insert(scb)
  1806. }
  1807. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  1808. }
  1809. }
  1810. }
  1811. // (9) Aggregate external allocations into aggregated allocations. This may
  1812. // not be possible for every external allocation, but attempt to find an
  1813. // exact key match, given each external allocation's proerties, and
  1814. // aggregate if an exact match is found.
  1815. for _, alloc := range externalSet.Allocations {
  1816. if filter.Matches(alloc) {
  1817. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  1818. alloc.Name = key
  1819. aggSet.Insert(alloc)
  1820. }
  1821. }
  1822. // (10) In the edge case that some idle has not been distributed because
  1823. // there is no usage of that resource type, add idle back to
  1824. // aggregations with only that cost applied.
  1825. // E.g. in the case where we have a result that looks like this on the
  1826. // frontend:
  1827. // Name CPU GPU RAM
  1828. // __idle__ $10 $12 $6
  1829. // kubecost $2 $0 $1
  1830. // Sharing idle weighted would result in no idle GPU cost being
  1831. // distributed, because the coefficient for the kubecost GPU cost would
  1832. // be zero. Thus, instead we re-add idle to the aggSet with distributed
  1833. // costs zeroed out but the undistributed costs left in.
  1834. // Name CPU GPU RAM
  1835. // __idle__ $0 $12 $0
  1836. // kubecost $12 $0 $7
  1837. if idleSet.Length() > 0 {
  1838. for _, idleAlloc := range idleSet.Allocations {
  1839. // if the idle does not apply to the non-filtered values, skip it
  1840. if !filter.Matches(idleAlloc) {
  1841. continue
  1842. }
  1843. idleId, err := idleAlloc.getIdleId(options)
  1844. if err != nil {
  1845. log.Errorf("AllocationSet.AggregateBy: idle allocation is missing idleId %s", idleAlloc.Name)
  1846. continue
  1847. }
  1848. hasUndistributableCost := false
  1849. if idleAlloc.CPUCost > 0 && allocatedTotalsMap[idleId]["cpu"] == 0 {
  1850. hasUndistributableCost = true
  1851. } else {
  1852. idleAlloc.CPUCost = 0
  1853. }
  1854. if idleAlloc.GPUCost > 0 && allocatedTotalsMap[idleId]["gpu"] == 0 {
  1855. hasUndistributableCost = true
  1856. } else {
  1857. idleAlloc.GPUCost = 0
  1858. }
  1859. if idleAlloc.RAMCost > 0 && allocatedTotalsMap[idleId]["ram"] == 0 {
  1860. hasUndistributableCost = true
  1861. } else {
  1862. idleAlloc.RAMCost = 0
  1863. }
  1864. if hasUndistributableCost {
  1865. idleAlloc.Name = fmt.Sprintf("%s/%s", idleId, IdleSuffix)
  1866. aggSet.Insert(idleAlloc)
  1867. }
  1868. }
  1869. }
  1870. // (11) Combine all idle allocations into a single "__idle__" allocation
  1871. if !options.SplitIdle {
  1872. for _, idleAlloc := range aggSet.IdleAllocations() {
  1873. aggSet.Delete(idleAlloc.Name)
  1874. idleAlloc.Name = IdleSuffix
  1875. aggSet.Insert(idleAlloc)
  1876. }
  1877. }
  1878. // TODO revisit this (ideally we just remove sharing from this function!)
  1879. // If filters and shared resources and shared idle are all enabled then
  1880. // we will over-count idle by exactly the portion that gets shared with the
  1881. // filtered allocations -- and idle filtration will miss this because it
  1882. // only filters the non-idle filtered costs.
  1883. //
  1884. // Consider the following example, from unit tests:
  1885. // - namespace1 28.000
  1886. // - namespace2 36.000
  1887. // - namespace3 18.000
  1888. // - cluster1/idle 20.000
  1889. // - cluster2/idle 10.000
  1890. //
  1891. // Now, we want to share namespace1, filter namespace2, and share idle:
  1892. //
  1893. // 1. Distribute idle
  1894. // ns1 ns2 ns3
  1895. // non-idle 28.000 36.000 18.000
  1896. // idle 14.688 10.312 5.000
  1897. //
  1898. // 2. Share namespace1
  1899. //
  1900. // ns2 ns3
  1901. // non-idle 36.000 18.000
  1902. // idle 10.312 5.000
  1903. // shared non-idle 18.667 9.333
  1904. // shared idle 9.792 4.896 (***)
  1905. //
  1906. // 3. Filter out all but namespace2
  1907. //
  1908. // ns2 = 36.000 + 10.312 + 18.667 + 9.792 = 74.771
  1909. //
  1910. // So, if we had NOT shared idle, we would expect something like this:
  1911. //
  1912. // ns2 = 36.000 + 18.667 = 54.667
  1913. // idle = 10.312 + 9.792 = 20.104
  1914. //
  1915. // But we will instead get this:
  1916. //
  1917. // ns2 = 36.000 + 18.667 = 54.667
  1918. // idle = 10.312 + 14.688 = 25.000
  1919. //
  1920. // Which over-shoots idle by 4.896 (***), i.e. precisely the amount of idle
  1921. // cost corresponding to namespace1 AND shared with namespace3. Phew.
  1922. //
  1923. // I originally wanted to fix this, but after 2 days, I'm punting with the
  1924. // recommendation that we rewrite this function soon. Too difficult.
  1925. // - Niko
  1926. as.Allocations = aggSet.Allocations
  1927. return nil
  1928. }
  1929. func computeShareCoeffs(aggregateBy []string, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  1930. // Compute coeffs by totalling per-allocation, then dividing by the total.
  1931. coeffs := map[string]float64{}
  1932. // Compute totals for all allocations
  1933. total := 0.0
  1934. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  1935. // counts each aggregation proportionally to its respective costs
  1936. shareType := options.ShareSplit
  1937. var filter AllocationMatcher
  1938. if options.Filter == nil {
  1939. filter = &matcher.AllPass[*Allocation]{}
  1940. } else {
  1941. compiler := NewAllocationMatchCompiler(options.LabelConfig)
  1942. var err error
  1943. filter, err = compiler.Compile(options.Filter)
  1944. if err != nil {
  1945. return nil, fmt.Errorf("compiling filter '%s': %w", ast.ToPreOrderShortString(options.Filter), err)
  1946. }
  1947. }
  1948. if filter == nil {
  1949. return nil, fmt.Errorf("unexpected nil filter")
  1950. }
  1951. // Record allocation values first, then normalize by totals to get percentages
  1952. for _, alloc := range as.Allocations {
  1953. if alloc.IsIdle() {
  1954. // Skip idle allocations in coefficient calculation
  1955. continue
  1956. }
  1957. if alloc.IsUnmounted() {
  1958. // Skip unmounted allocations in coefficient calculation
  1959. continue
  1960. }
  1961. // Determine the post-aggregation key under which the allocation will
  1962. // be shared.
  1963. name := alloc.generateKey(aggregateBy, options.LabelConfig)
  1964. // If the current allocation will be filtered out in step 3, contribute
  1965. // its share of the shared coefficient to a "__filtered__" bin, which
  1966. // will ultimately be dropped. This step ensures that the shared cost
  1967. // of a non-filtered allocation will be conserved even when the filter
  1968. // is removed. (Otherwise, all the shared cost will get redistributed
  1969. // over the unfiltered results, inflating their shared costs.)
  1970. if !filter.Matches(alloc) {
  1971. name = "__filtered__"
  1972. }
  1973. if shareType == ShareEven {
  1974. // Even distribution is not additive - set to 1.0 for everything
  1975. coeffs[name] = 1.0
  1976. // Total for even distribution is always the number of coefficients
  1977. total = float64(len(coeffs))
  1978. } else {
  1979. // Both are additive for weighted distribution, where each
  1980. // cumulative coefficient will be divided by the total.
  1981. coeffs[name] += alloc.TotalCost() - alloc.SharedCost - alloc.UnmountedPVCost
  1982. total += alloc.TotalCost() - alloc.SharedCost - alloc.UnmountedPVCost
  1983. }
  1984. }
  1985. // Normalize coefficients by totals
  1986. for a := range coeffs {
  1987. if coeffs[a] > 0 && total > 0 {
  1988. coeffs[a] /= total
  1989. } else {
  1990. log.Warnf("ETL: invalid values for shared coefficients: %v, %v", coeffs[a], total)
  1991. coeffs[a] = 0.0
  1992. }
  1993. }
  1994. return coeffs, nil
  1995. }
  1996. func computeIdleCoeffs(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, map[string]map[string]float64, error) {
  1997. types := []string{"cpu", "gpu", "ram"}
  1998. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1999. // [idle_id][allocation name][resource] = [coeff]
  2000. coeffs := map[string]map[string]map[string]float64{}
  2001. // Compute totals per resource for CPU, GPU, RAM, and PV
  2002. // [idle_id][resource] = [total]
  2003. totals := map[string]map[string]float64{}
  2004. // Record allocation values first, then normalize by totals to get percentages
  2005. for _, alloc := range as.Allocations {
  2006. if alloc.IsIdle() {
  2007. // Skip idle allocations in coefficient calculation
  2008. continue
  2009. }
  2010. idleId, err := alloc.getIdleId(options)
  2011. if err != nil {
  2012. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  2013. }
  2014. // get the name key for the allocation
  2015. name := alloc.Name
  2016. // Create key based tables if they don't exist
  2017. if _, ok := coeffs[idleId]; !ok {
  2018. coeffs[idleId] = map[string]map[string]float64{}
  2019. }
  2020. if _, ok := totals[idleId]; !ok {
  2021. totals[idleId] = map[string]float64{}
  2022. }
  2023. if _, ok := coeffs[idleId][name]; !ok {
  2024. coeffs[idleId][name] = map[string]float64{}
  2025. }
  2026. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  2027. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  2028. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  2029. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  2030. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  2031. totals[idleId]["ram"] += alloc.RAMTotalCost()
  2032. }
  2033. // Do the same for shared allocations
  2034. for _, alloc := range shareSet.Allocations {
  2035. if alloc.IsIdle() {
  2036. // Skip idle allocations in coefficient calculation
  2037. continue
  2038. }
  2039. // idleId will be providerId or cluster
  2040. idleId, err := alloc.getIdleId(options)
  2041. if err != nil {
  2042. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  2043. }
  2044. // get the name key for the allocation
  2045. name := alloc.Name
  2046. // Create idleId based tables if they don't exist
  2047. if _, ok := coeffs[idleId]; !ok {
  2048. coeffs[idleId] = map[string]map[string]float64{}
  2049. }
  2050. if _, ok := totals[idleId]; !ok {
  2051. totals[idleId] = map[string]float64{}
  2052. }
  2053. if _, ok := coeffs[idleId][name]; !ok {
  2054. coeffs[idleId][name] = map[string]float64{}
  2055. }
  2056. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  2057. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  2058. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  2059. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  2060. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  2061. totals[idleId]["ram"] += alloc.RAMTotalCost()
  2062. }
  2063. // Normalize coefficients by totals
  2064. for id := range coeffs {
  2065. for a := range coeffs[id] {
  2066. for _, r := range types {
  2067. if coeffs[id][a][r] > 0 && totals[id][r] > 0 {
  2068. coeffs[id][a][r] /= totals[id][r]
  2069. }
  2070. }
  2071. }
  2072. }
  2073. return coeffs, totals, nil
  2074. }
  2075. func deriveProportionalAssetResourceCosts(options *AllocationAggregationOptions, as *AllocationSet, shareSet, parcsSet *AllocationSet) error {
  2076. // Compute idle coefficients, then save them in AllocationAggregationOptions
  2077. // [idle_id][allocation name][resource] = [coeff]
  2078. coeffs := map[string]map[string]map[string]float64{}
  2079. // Compute totals per resource for CPU, GPU, RAM, and PV
  2080. // [idle_id][resource] = [total]
  2081. totals := map[string]map[string]float64{}
  2082. // Record allocation values first, then normalize by totals to get percentages
  2083. for _, alloc := range parcsSet.Allocations {
  2084. idleId, err := alloc.getIdleId(options)
  2085. if err != nil {
  2086. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  2087. }
  2088. // get the name key for the allocation
  2089. name := alloc.Name
  2090. // Create key based tables if they don't exist
  2091. if _, ok := coeffs[idleId]; !ok {
  2092. coeffs[idleId] = map[string]map[string]float64{}
  2093. }
  2094. if _, ok := totals[idleId]; !ok {
  2095. totals[idleId] = map[string]float64{}
  2096. }
  2097. if _, ok := coeffs[idleId][name]; !ok {
  2098. coeffs[idleId][name] = map[string]float64{}
  2099. }
  2100. // idle IDs for load balancers are their services
  2101. for key := range alloc.LoadBalancers {
  2102. if _, ok := totals[key]; !ok {
  2103. totals[key] = map[string]float64{}
  2104. }
  2105. if _, ok := coeffs[key]; !ok {
  2106. coeffs[key] = map[string]map[string]float64{}
  2107. }
  2108. if _, ok := coeffs[key][name]; !ok {
  2109. coeffs[key][name] = map[string]float64{}
  2110. }
  2111. coeffs[key][name]["loadbalancer"] += alloc.LoadBalancerTotalCost()
  2112. totals[key]["loadbalancer"] += alloc.LoadBalancerTotalCost()
  2113. }
  2114. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  2115. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  2116. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  2117. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  2118. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  2119. totals[idleId]["ram"] += alloc.RAMTotalCost()
  2120. }
  2121. // Do the same for shared allocations
  2122. for _, alloc := range shareSet.Allocations {
  2123. if alloc.IsIdle() {
  2124. // Skip idle allocations in coefficient calculation
  2125. continue
  2126. }
  2127. // idleId will be providerId or cluster
  2128. idleId, err := alloc.getIdleId(options)
  2129. if err != nil {
  2130. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  2131. }
  2132. // get the name key for the allocation
  2133. name := alloc.Name
  2134. // Create idleId based tables if they don't exist
  2135. if _, ok := coeffs[idleId]; !ok {
  2136. coeffs[idleId] = map[string]map[string]float64{}
  2137. }
  2138. if _, ok := totals[idleId]; !ok {
  2139. totals[idleId] = map[string]float64{}
  2140. }
  2141. if _, ok := coeffs[idleId][name]; !ok {
  2142. coeffs[idleId][name] = map[string]float64{}
  2143. }
  2144. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  2145. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  2146. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  2147. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  2148. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  2149. totals[idleId]["ram"] += alloc.RAMTotalCost()
  2150. // idle IDs for load balancers are their services
  2151. for key := range alloc.LoadBalancers {
  2152. if _, ok := totals[key]; !ok {
  2153. totals[key] = map[string]float64{}
  2154. }
  2155. if _, ok := coeffs[key]; !ok {
  2156. coeffs[key] = map[string]map[string]float64{}
  2157. }
  2158. if _, ok := coeffs[key][name]; !ok {
  2159. coeffs[key][name] = map[string]float64{}
  2160. }
  2161. coeffs[key][name]["loadbalancer"] += alloc.LoadBalancerTotalCost()
  2162. totals[key]["loadbalancer"] += alloc.LoadBalancerTotalCost()
  2163. }
  2164. }
  2165. // after totals are computed, loop through and set parcs on allocations
  2166. for _, alloc := range as.Allocations {
  2167. idleId, err := alloc.getIdleId(options)
  2168. if err != nil {
  2169. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  2170. }
  2171. alloc.ProportionalAssetResourceCosts = ProportionalAssetResourceCosts{}
  2172. alloc.ProportionalAssetResourceCosts.Insert(ProportionalAssetResourceCost{
  2173. Cluster: alloc.Properties.Cluster,
  2174. Name: alloc.Properties.Node,
  2175. Type: "Node",
  2176. ProviderID: alloc.Properties.ProviderID,
  2177. GPUProportionalCost: coeffs[idleId][alloc.Name]["gpu"],
  2178. CPUProportionalCost: coeffs[idleId][alloc.Name]["cpu"],
  2179. RAMProportionalCost: coeffs[idleId][alloc.Name]["ram"],
  2180. }, options.IdleByNode)
  2181. // insert a separate PARC for the load balancer
  2182. if alloc.LoadBalancerCost != 0 {
  2183. for key, svc := range alloc.LoadBalancers {
  2184. alloc.ProportionalAssetResourceCosts.Insert(ProportionalAssetResourceCost{
  2185. Cluster: alloc.Properties.Cluster,
  2186. Name: svc.Service,
  2187. Type: "LoadBalancer",
  2188. LoadBalancerProportionalCost: coeffs[key][alloc.Name]["loadbalancer"],
  2189. }, options.IdleByNode)
  2190. }
  2191. }
  2192. for name, pvAlloc := range alloc.PVs {
  2193. // insert a separate PARC for each PV attached
  2194. alloc.ProportionalAssetResourceCosts.Insert(ProportionalAssetResourceCost{
  2195. Cluster: name.Cluster,
  2196. Name: name.Name,
  2197. Type: "PV",
  2198. ProviderID: pvAlloc.ProviderID,
  2199. PVProportionalCost: pvAlloc.Cost,
  2200. }, options.IdleByNode)
  2201. }
  2202. }
  2203. return nil
  2204. }
  2205. func (a *Allocation) determineSharingName(options *AllocationAggregationOptions) (string, error) {
  2206. if a == nil {
  2207. return "", fmt.Errorf("determineSharingName called on nil Allocation")
  2208. } else if options == nil {
  2209. return "unknown", nil
  2210. }
  2211. // grab SharedLabels keys and sort them, to keep this function deterministic
  2212. var labelKeys []string
  2213. for labelKey := range options.SharedLabels {
  2214. labelKeys = append(labelKeys, labelKey)
  2215. }
  2216. slices.Sort(labelKeys)
  2217. var sharedAggregateBy []string
  2218. var sharedLabels [][]string
  2219. for _, labelKey := range labelKeys {
  2220. sharedAgg := fmt.Sprintf("label:%s", labelKey)
  2221. if !slices.Contains(sharedAggregateBy, sharedAgg) {
  2222. sharedAggregateBy = append(sharedAggregateBy, sharedAgg)
  2223. }
  2224. sharedLabels = append(sharedLabels, options.SharedLabels[labelKey])
  2225. }
  2226. if len(options.SharedNamespaces) > 0 {
  2227. sharedAggregateBy = append(sharedAggregateBy, "namespace")
  2228. }
  2229. sharedCostName := a.generateKey(sharedAggregateBy, options.LabelConfig)
  2230. // get each value in the generated key, then reset the name
  2231. sharedCostNameValues := strings.Split(sharedCostName, "/")
  2232. sharedCostName = ""
  2233. // if we don't have as many values as aggregateBys, something went wrong in generateKey
  2234. if len(sharedCostNameValues) != len(sharedAggregateBy) {
  2235. log.Warnf("Unable to determine share cost group for allocation \"%s\"", a.Name)
  2236. } else {
  2237. // try to match to the first label
  2238. for i, sharedLabelValues := range sharedLabels {
  2239. allocLabel := sharedCostNameValues[i]
  2240. if slices.Contains(sharedLabelValues, allocLabel) {
  2241. return allocLabel, nil
  2242. }
  2243. }
  2244. // if we didn't match to a label, try to match to a namespace
  2245. if len(options.SharedNamespaces) > 0 {
  2246. // namespace will always be the last value, if SharedNamespaces is set
  2247. allocNamespace := sharedCostNameValues[len(sharedCostNameValues)-1]
  2248. if slices.Contains(options.SharedNamespaces, allocNamespace) {
  2249. return allocNamespace, nil
  2250. }
  2251. }
  2252. // if neither the labels nor the namespaces matched, we log a warning and mark this allocation
  2253. // as unknown
  2254. if len(sharedCostName) == 0 {
  2255. log.Warnf("Failed to determine shared cost grouping for allocation \"%s\"", a.Name)
  2256. }
  2257. }
  2258. return "unknown", nil
  2259. }
  2260. // getIdleId returns the providerId or cluster of an Allocation depending on the IdleByNode
  2261. // option in the AllocationAggregationOptions and an error if the respective field is missing
  2262. func (a *Allocation) getIdleId(options *AllocationAggregationOptions) (string, error) {
  2263. var idleId string
  2264. if options.IdleByNode {
  2265. // Key allocations to ProviderId to match against node
  2266. idleId = fmt.Sprintf("%s/%s", a.Properties.Cluster, a.Properties.Node)
  2267. if idleId == "" {
  2268. return idleId, fmt.Errorf("ProviderId is not set")
  2269. }
  2270. } else {
  2271. // key the allocations by cluster id
  2272. idleId = a.Properties.Cluster
  2273. if idleId == "" {
  2274. return idleId, fmt.Errorf("ClusterProp is not set")
  2275. }
  2276. }
  2277. return idleId, nil
  2278. }
  2279. func (a *Allocation) generateKey(aggregateBy []string, labelConfig *LabelConfig) string {
  2280. if a == nil {
  2281. return ""
  2282. }
  2283. return a.Properties.GenerateKey(aggregateBy, labelConfig)
  2284. }
  2285. func (a *Allocation) StringProperty(property string) (string, error) {
  2286. switch property {
  2287. case AllocationClusterProp:
  2288. if a.Properties == nil {
  2289. return "", nil
  2290. }
  2291. return a.Properties.Cluster, nil
  2292. case AllocationNodeProp:
  2293. if a.Properties == nil {
  2294. return "", nil
  2295. }
  2296. return a.Properties.Node, nil
  2297. case AllocationContainerProp:
  2298. if a.Properties == nil {
  2299. return "", nil
  2300. }
  2301. return a.Properties.Container, nil
  2302. case AllocationControllerProp:
  2303. if a.Properties == nil {
  2304. return "", nil
  2305. }
  2306. return a.Properties.Controller, nil
  2307. case AllocationControllerKindProp:
  2308. if a.Properties == nil {
  2309. return "", nil
  2310. }
  2311. return a.Properties.ControllerKind, nil
  2312. case AllocationNamespaceProp:
  2313. if a.Properties == nil {
  2314. return "", nil
  2315. }
  2316. return a.Properties.Namespace, nil
  2317. case AllocationPodProp:
  2318. if a.Properties == nil {
  2319. return "", nil
  2320. }
  2321. return a.Properties.Pod, nil
  2322. case AllocationProviderIDProp:
  2323. if a.Properties == nil {
  2324. return "", nil
  2325. }
  2326. return a.Properties.ProviderID, nil
  2327. default:
  2328. return "", fmt.Errorf("Allocation: StringProperty: invalid property name: %s", property)
  2329. }
  2330. }
  2331. func (a *Allocation) StringSliceProperty(property string) ([]string, error) {
  2332. switch property {
  2333. case AllocationServiceProp:
  2334. if a.Properties == nil {
  2335. return nil, nil
  2336. }
  2337. return a.Properties.Services, nil
  2338. default:
  2339. return nil, fmt.Errorf("Allocation: StringSliceProperty: invalid property name: %s", property)
  2340. }
  2341. }
  2342. func (a *Allocation) StringMapProperty(property string) (map[string]string, error) {
  2343. switch property {
  2344. case AllocationLabelProp:
  2345. if a.Properties == nil {
  2346. return nil, nil
  2347. }
  2348. return a.Properties.Labels, nil
  2349. case AllocationAnnotationProp:
  2350. if a.Properties == nil {
  2351. return nil, nil
  2352. }
  2353. return a.Properties.Annotations, nil
  2354. default:
  2355. return nil, fmt.Errorf("Allocation: StringMapProperty: invalid property name: %s", property)
  2356. }
  2357. }
  2358. func (a *Allocation) SanitizeNaN() {
  2359. if a == nil {
  2360. return
  2361. }
  2362. if math.IsNaN(a.CPUCost) {
  2363. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCost: name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2364. a.CPUCost = 0
  2365. }
  2366. if math.IsNaN(a.CPUCostIdle) {
  2367. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCostIdle: name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2368. a.CPUCostIdle = 0
  2369. }
  2370. if math.IsNaN(a.CPUCoreRequestAverage) {
  2371. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCoreRequestAverage: name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2372. a.CPUCoreRequestAverage = 0
  2373. }
  2374. if math.IsNaN(a.CPUCoreHours) {
  2375. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCoreHours: name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2376. a.CPUCoreHours = 0
  2377. }
  2378. if math.IsNaN(a.CPUCoreUsageAverage) {
  2379. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCoreUsageAverage name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2380. a.CPUCoreUsageAverage = 0
  2381. }
  2382. if math.IsNaN(a.CPUCostAdjustment) {
  2383. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for CPUCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2384. a.CPUCostAdjustment = 0
  2385. }
  2386. if math.IsNaN(a.GPUHours) {
  2387. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUHours name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2388. a.GPUHours = 0
  2389. }
  2390. if math.IsNaN(a.GPUCost) {
  2391. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2392. a.GPUCost = 0
  2393. }
  2394. if math.IsNaN(a.GPUCostIdle) {
  2395. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUCostIdle name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2396. a.GPUCostIdle = 0
  2397. }
  2398. if math.IsNaN(a.GPUCostAdjustment) {
  2399. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for GPUCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2400. a.GPUCostAdjustment = 0
  2401. }
  2402. if math.IsNaN(a.NetworkTransferBytes) {
  2403. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkTransferBytes name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2404. a.NetworkTransferBytes = 0
  2405. }
  2406. if math.IsNaN(a.NetworkReceiveBytes) {
  2407. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkReceiveBytes name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2408. a.NetworkReceiveBytes = 0
  2409. }
  2410. if math.IsNaN(a.NetworkCost) {
  2411. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2412. a.NetworkCost = 0
  2413. }
  2414. if math.IsNaN(a.NetworkCrossZoneCost) {
  2415. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkCrossZoneCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2416. a.NetworkCrossZoneCost = 0
  2417. }
  2418. if math.IsNaN(a.NetworkCrossRegionCost) {
  2419. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkCrossRegionCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2420. a.NetworkCrossRegionCost = 0
  2421. }
  2422. if math.IsNaN(a.NetworkInternetCost) {
  2423. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkInternetCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2424. a.NetworkInternetCost = 0
  2425. }
  2426. if math.IsNaN(a.NetworkCostAdjustment) {
  2427. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for NetworkCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2428. a.NetworkCostAdjustment = 0
  2429. }
  2430. if math.IsNaN(a.LoadBalancerCost) {
  2431. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for LoadBalancerCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2432. a.LoadBalancerCost = 0
  2433. }
  2434. if math.IsNaN(a.LoadBalancerCostAdjustment) {
  2435. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for LoadBalancerCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2436. a.LoadBalancerCostAdjustment = 0
  2437. }
  2438. if math.IsNaN(a.PVCostAdjustment) {
  2439. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for PVCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2440. a.PVCostAdjustment = 0
  2441. }
  2442. if math.IsNaN(a.RAMByteHours) {
  2443. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMByteHours name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2444. a.RAMByteHours = 0
  2445. }
  2446. if math.IsNaN(a.RAMBytesRequestAverage) {
  2447. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMBytesRequestAverage name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2448. a.RAMBytesRequestAverage = 0
  2449. }
  2450. if math.IsNaN(a.RAMBytesUsageAverage) {
  2451. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMBytesUsageAverage name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2452. a.RAMBytesUsageAverage = 0
  2453. }
  2454. if math.IsNaN(a.RAMCost) {
  2455. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2456. a.RAMCost = 0
  2457. }
  2458. if math.IsNaN(a.RAMCostIdle) {
  2459. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMCostIdle name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2460. a.RAMCostIdle = 0
  2461. }
  2462. if math.IsNaN(a.RAMCostAdjustment) {
  2463. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for RAMCostAdjustment name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2464. a.RAMCostAdjustment = 0
  2465. }
  2466. if math.IsNaN(a.SharedCost) {
  2467. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for SharedCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2468. a.SharedCost = 0
  2469. }
  2470. if math.IsNaN(a.ExternalCost) {
  2471. log.DedupedWarningf(5, "Allocation: Unexpected NaN found for ExternalCost name:%s, window:%s, properties:%s", a.Name, a.Window.String(), a.Properties.String())
  2472. a.ExternalCost = 0
  2473. }
  2474. a.PVs.SanitizeNaN()
  2475. a.RawAllocationOnly.SanitizeNaN()
  2476. a.GPUAllocation.SanitizeNaN()
  2477. a.ProportionalAssetResourceCosts.SanitizeNaN()
  2478. a.SharedCostBreakdown.SanitizeNaN()
  2479. a.LoadBalancers.SanitizeNaN()
  2480. }
  2481. // Clone returns a new AllocationSet with a deep copy of the given
  2482. // AllocationSet's allocations.
  2483. func (as *AllocationSet) Clone() *AllocationSet {
  2484. if as == nil {
  2485. return nil
  2486. }
  2487. allocs := make(map[string]*Allocation, len(as.Allocations))
  2488. for k, v := range as.Allocations {
  2489. allocs[k] = v.Clone()
  2490. }
  2491. externalKeys := make(map[string]bool, len(as.ExternalKeys))
  2492. for k, v := range as.ExternalKeys {
  2493. externalKeys[k] = v
  2494. }
  2495. idleKeys := make(map[string]bool, len(as.IdleKeys))
  2496. for k, v := range as.IdleKeys {
  2497. idleKeys[k] = v
  2498. }
  2499. var errors []string
  2500. var warnings []string
  2501. if as.Errors != nil {
  2502. errors = make([]string, len(as.Errors))
  2503. copy(errors, as.Errors)
  2504. } else {
  2505. errors = nil
  2506. }
  2507. if as.Warnings != nil {
  2508. warnings := make([]string, len(as.Warnings))
  2509. copy(warnings, as.Warnings)
  2510. } else {
  2511. warnings = nil
  2512. }
  2513. return &AllocationSet{
  2514. Allocations: allocs,
  2515. ExternalKeys: externalKeys,
  2516. IdleKeys: idleKeys,
  2517. Window: as.Window.Clone(),
  2518. Errors: errors,
  2519. Warnings: warnings,
  2520. }
  2521. }
  2522. // Delete removes the allocation with the given name from the set
  2523. func (as *AllocationSet) Delete(name string) {
  2524. if as == nil {
  2525. return
  2526. }
  2527. delete(as.ExternalKeys, name)
  2528. delete(as.IdleKeys, name)
  2529. delete(as.Allocations, name)
  2530. }
  2531. // End returns the End time of the AllocationSet window
  2532. func (as *AllocationSet) End() time.Time {
  2533. if as == nil {
  2534. log.Warnf("AllocationSet: calling End on nil AllocationSet")
  2535. return time.Unix(0, 0)
  2536. }
  2537. if as.Window.End() == nil {
  2538. log.Warnf("AllocationSet: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.Allocations))
  2539. return time.Unix(0, 0)
  2540. }
  2541. return *as.Window.End()
  2542. }
  2543. // Get returns the Allocation at the given key in the AllocationSet
  2544. func (as *AllocationSet) Get(key string) *Allocation {
  2545. if alloc, ok := as.Allocations[key]; ok {
  2546. return alloc
  2547. }
  2548. return nil
  2549. }
  2550. // ExternalAllocations returns a map of the external allocations in the set.
  2551. // Returns clones of the actual Allocations, so mutability is not a problem.
  2552. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  2553. externals := map[string]*Allocation{}
  2554. if as.IsEmpty() {
  2555. return externals
  2556. }
  2557. for key := range as.ExternalKeys {
  2558. if alloc, ok := as.Allocations[key]; ok {
  2559. externals[key] = alloc.Clone()
  2560. }
  2561. }
  2562. return externals
  2563. }
  2564. // ExternalCost returns the total aggregated external costs of the set
  2565. func (as *AllocationSet) ExternalCost() float64 {
  2566. if as.IsEmpty() {
  2567. return 0.0
  2568. }
  2569. externalCost := 0.0
  2570. for _, alloc := range as.Allocations {
  2571. externalCost += alloc.ExternalCost
  2572. }
  2573. return externalCost
  2574. }
  2575. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  2576. // Returns clones of the actual Allocations, so mutability is not a problem.
  2577. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  2578. idles := map[string]*Allocation{}
  2579. if as.IsEmpty() {
  2580. return idles
  2581. }
  2582. for key := range as.IdleKeys {
  2583. if alloc, ok := as.Allocations[key]; ok {
  2584. idles[key] = alloc.Clone()
  2585. }
  2586. }
  2587. return idles
  2588. }
  2589. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  2590. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  2591. // there is no existing entry, one is created. Nil error response indicates success.
  2592. func (as *AllocationSet) Insert(that *Allocation) error {
  2593. if as == nil {
  2594. return fmt.Errorf("cannot insert into nil AllocationSet")
  2595. }
  2596. if as.Allocations == nil {
  2597. as.Allocations = map[string]*Allocation{}
  2598. }
  2599. if as.ExternalKeys == nil {
  2600. as.ExternalKeys = map[string]bool{}
  2601. }
  2602. if as.IdleKeys == nil {
  2603. as.IdleKeys = map[string]bool{}
  2604. }
  2605. // Add the given Allocation to the existing entry, if there is one;
  2606. // otherwise just set directly into allocations
  2607. if _, ok := as.Allocations[that.Name]; !ok {
  2608. as.Allocations[that.Name] = that
  2609. } else {
  2610. as.Allocations[that.Name].add(that)
  2611. }
  2612. // If the given Allocation is an external one, record that
  2613. if that.IsExternal() {
  2614. as.ExternalKeys[that.Name] = true
  2615. }
  2616. // If the given Allocation is an idle one, record that
  2617. if that.IsIdle() {
  2618. as.IdleKeys[that.Name] = true
  2619. }
  2620. // Expand the window, just to be safe. It's possible that the Allocation will
  2621. // be set into the map without expanding it to the AllocationSet's window.
  2622. as.Allocations[that.Name].Window = as.Allocations[that.Name].Window.Expand(as.Window)
  2623. return nil
  2624. }
  2625. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  2626. // zero allocations.
  2627. func (as *AllocationSet) IsEmpty() bool {
  2628. if as == nil || len(as.Allocations) == 0 {
  2629. return true
  2630. }
  2631. return false
  2632. }
  2633. // Length returns the number of Allocations in the set
  2634. func (as *AllocationSet) Length() int {
  2635. if as == nil {
  2636. return 0
  2637. }
  2638. return len(as.Allocations)
  2639. }
  2640. // ResetAdjustments sets all cost adjustment fields to zero
  2641. func (as *AllocationSet) ResetAdjustments() {
  2642. if as == nil {
  2643. return
  2644. }
  2645. for _, a := range as.Allocations {
  2646. a.ResetAdjustments()
  2647. }
  2648. }
  2649. // Resolution returns the AllocationSet's window duration
  2650. func (as *AllocationSet) Resolution() time.Duration {
  2651. return as.Window.Duration()
  2652. }
  2653. // GetWindow returns the AllocationSet's window
  2654. func (as *AllocationSet) GetWindow() Window {
  2655. return as.Window
  2656. }
  2657. // Set uses the given Allocation to overwrite the existing entry in the
  2658. // AllocationSet under the Allocation's name.
  2659. func (as *AllocationSet) Set(alloc *Allocation) error {
  2660. if as.IsEmpty() {
  2661. as.Allocations = map[string]*Allocation{}
  2662. as.ExternalKeys = map[string]bool{}
  2663. as.IdleKeys = map[string]bool{}
  2664. }
  2665. as.Allocations[alloc.Name] = alloc
  2666. // If the given Allocation is an external one, record that
  2667. if alloc.IsExternal() {
  2668. as.ExternalKeys[alloc.Name] = true
  2669. }
  2670. // If the given Allocation is an idle one, record that
  2671. if alloc.IsIdle() {
  2672. as.IdleKeys[alloc.Name] = true
  2673. }
  2674. return nil
  2675. }
  2676. // GetUnmountedPVCost returns the sum of all UnmountedPVCost fields across all
  2677. // allocations in the set.
  2678. func (as *AllocationSet) GetUnmountedPVCost() float64 {
  2679. upvc := 0.0
  2680. for _, a := range as.Allocations {
  2681. upvc += a.UnmountedPVCost
  2682. }
  2683. return upvc
  2684. }
  2685. // SetUnmountedPVCost sets the UnmountedPVCost field for all allocations in the
  2686. // set.
  2687. func (as *AllocationSet) SetUnmountedPVCost() float64 {
  2688. upvc := 0.0
  2689. for _, a := range as.Allocations {
  2690. upvc += a.SetUnmountedPVCost()
  2691. }
  2692. return upvc
  2693. }
  2694. // Start returns the Start time of the AllocationSet window
  2695. func (as *AllocationSet) Start() time.Time {
  2696. if as == nil {
  2697. log.Warnf("AllocationSet: calling Start on nil AllocationSet")
  2698. return time.Unix(0, 0)
  2699. }
  2700. if as.Window.Start() == nil {
  2701. log.Warnf("AllocationSet: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.Allocations))
  2702. return time.Unix(0, 0)
  2703. }
  2704. return *as.Window.Start()
  2705. }
  2706. // String represents the given Allocation as a string
  2707. func (as *AllocationSet) String() string {
  2708. if as == nil {
  2709. return "<nil>"
  2710. }
  2711. return fmt.Sprintf(
  2712. "AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  2713. as.Length(),
  2714. as.Window,
  2715. as.TotalCost())
  2716. }
  2717. // TotalCost returns the sum of all TotalCosts of the allocations contained
  2718. func (as *AllocationSet) TotalCost() float64 {
  2719. if as.IsEmpty() {
  2720. return 0.0
  2721. }
  2722. tc := 0.0
  2723. for _, a := range as.Allocations {
  2724. tc += a.TotalCost()
  2725. }
  2726. return tc
  2727. }
  2728. // UTCOffset returns the AllocationSet's configured UTCOffset.
  2729. func (as *AllocationSet) UTCOffset() time.Duration {
  2730. _, zone := as.Start().Zone()
  2731. return time.Duration(zone) * time.Second
  2732. }
  2733. func (as *AllocationSet) Accumulate(that *AllocationSet) (*AllocationSet, error) {
  2734. if as.IsEmpty() {
  2735. return that.Clone(), nil
  2736. }
  2737. if that.IsEmpty() {
  2738. return as.Clone(), nil
  2739. }
  2740. // Set start, end to min(start), max(end)
  2741. start := as.Start()
  2742. end := as.End()
  2743. if that.Start().Before(start) {
  2744. start = that.Start()
  2745. }
  2746. if that.End().After(end) {
  2747. end = that.End()
  2748. }
  2749. acc := NewAllocationSet(start, end)
  2750. for _, alloc := range as.Allocations {
  2751. err := acc.Insert(alloc)
  2752. if err != nil {
  2753. return nil, err
  2754. }
  2755. }
  2756. for _, alloc := range that.Allocations {
  2757. err := acc.Insert(alloc)
  2758. if err != nil {
  2759. return nil, err
  2760. }
  2761. }
  2762. return acc, nil
  2763. }
  2764. func (as *AllocationSet) SanitizeNaN() {
  2765. if as == nil {
  2766. return
  2767. }
  2768. for _, a := range as.Allocations {
  2769. a.SanitizeNaN()
  2770. }
  2771. }
  2772. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  2773. // be used such that the AllocationSets held are consecutive and coherent with
  2774. // respect to using the same aggregation properties, UTC offset, and
  2775. // resolution. However these rules are not necessarily enforced, so use wisely.
  2776. type AllocationSetRange struct {
  2777. Allocations []*AllocationSet
  2778. FromStore string // stores the name of the store used to retrieve the data
  2779. }
  2780. // NewAllocationSetRange instantiates a new range composed of the given
  2781. // AllocationSets in the order provided.
  2782. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  2783. return &AllocationSetRange{
  2784. Allocations: allocs,
  2785. }
  2786. }
  2787. // Get safely retrieves the AllocationSet at the given index of the range.
  2788. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  2789. if i < 0 || i >= len(asr.Allocations) {
  2790. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  2791. }
  2792. return asr.Allocations[i], nil
  2793. }
  2794. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  2795. // AllocationSet for the entire range.
  2796. func (asr *AllocationSetRange) accumulate() (*AllocationSet, error) {
  2797. var allocSet *AllocationSet
  2798. var err error
  2799. for _, as := range asr.Allocations {
  2800. allocSet, err = allocSet.Accumulate(as)
  2801. if err != nil {
  2802. return nil, err
  2803. }
  2804. }
  2805. return allocSet, nil
  2806. }
  2807. // newAccumulation clones the first available AllocationSet to use as the data structure to
  2808. // Accumulate the remaining data. This leaves the original AllocationSetRange intact.
  2809. func (asr *AllocationSetRange) newAccumulation() (*AllocationSet, error) {
  2810. // NOTE: Adding this API for consistency across SummaryAllocation and Assets, but this
  2811. // NOTE: implementation is almost identical to regular Accumulate(). The Accumulate() method
  2812. // NOTE: for Allocation returns Clone() of the input, which is required for Accumulate
  2813. // NOTE: support (unit tests are great for verifying this information).
  2814. var allocSet *AllocationSet
  2815. var err error
  2816. if asr == nil {
  2817. return nil, fmt.Errorf("nil AllocationSetRange in accumulation")
  2818. }
  2819. if len(asr.Allocations) == 0 {
  2820. return nil, fmt.Errorf("AllocationSetRange has empty AssetSet in accumulation")
  2821. }
  2822. for _, as := range asr.Allocations {
  2823. if allocSet == nil {
  2824. allocSet = as.Clone()
  2825. continue
  2826. }
  2827. var allocSetCopy *AllocationSet = nil
  2828. if as != nil {
  2829. allocSetCopy = as.Clone()
  2830. }
  2831. allocSet, err = allocSet.Accumulate(allocSetCopy)
  2832. if err != nil {
  2833. return nil, err
  2834. }
  2835. }
  2836. return allocSet, nil
  2837. }
  2838. // Accumulate sums AllocationSets based on the AccumulateOption (calendar week or calendar month).
  2839. // The accumulated set is determined by the start of the window of the allocation set.
  2840. func (asr *AllocationSetRange) Accumulate(accumulateBy AccumulateOption) (*AllocationSetRange, error) {
  2841. switch accumulateBy {
  2842. case AccumulateOptionNone:
  2843. return asr.accumulateByNone()
  2844. case AccumulateOptionAll:
  2845. return asr.accumulateByAll()
  2846. case AccumulateOptionHour:
  2847. return asr.accumulateByHour()
  2848. case AccumulateOptionDay:
  2849. return asr.accumulateByDay()
  2850. case AccumulateOptionWeek:
  2851. return asr.accumulateByWeek()
  2852. case AccumulateOptionMonth:
  2853. return asr.accumulateByMonth()
  2854. default:
  2855. // ideally, this should never happen
  2856. return nil, fmt.Errorf("unexpected error, invalid accumulateByType: %s", accumulateBy)
  2857. }
  2858. }
  2859. func (asr *AllocationSetRange) accumulateByAll() (*AllocationSetRange, error) {
  2860. var err error
  2861. var as *AllocationSet
  2862. as, err = asr.newAccumulation()
  2863. if err != nil {
  2864. return nil, fmt.Errorf("error accumulating all:%s", err)
  2865. }
  2866. accumulated := NewAllocationSetRange(as)
  2867. return accumulated, nil
  2868. }
  2869. func (asr *AllocationSetRange) accumulateByNone() (*AllocationSetRange, error) {
  2870. return asr.Clone(), nil
  2871. }
  2872. func (asr *AllocationSetRange) accumulateByHour() (*AllocationSetRange, error) {
  2873. // ensure that the summary allocation sets have a 1-hour window, if a set exists
  2874. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() != time.Hour {
  2875. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", asr.Allocations[0].Window.Duration())
  2876. }
  2877. return asr.Clone(), nil
  2878. }
  2879. func (asr *AllocationSetRange) accumulateByDay() (*AllocationSetRange, error) {
  2880. // if the allocation set window is 1-day, just return the existing allocation set range
  2881. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() == time.Hour*24 {
  2882. return asr, nil
  2883. }
  2884. var toAccumulate *AllocationSetRange
  2885. result := NewAllocationSetRange()
  2886. for i, as := range asr.Allocations {
  2887. if as.Window.Duration() != time.Hour {
  2888. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", as.Window.Duration())
  2889. }
  2890. hour := as.Window.Start().Hour()
  2891. if toAccumulate == nil {
  2892. toAccumulate = NewAllocationSetRange()
  2893. as = as.Clone()
  2894. }
  2895. toAccumulate.Append(as)
  2896. asAccumulated, err := toAccumulate.accumulate()
  2897. if err != nil {
  2898. return nil, fmt.Errorf("error accumulating result: %s", err)
  2899. }
  2900. toAccumulate = NewAllocationSetRange(asAccumulated)
  2901. if hour == 23 || i == len(asr.Allocations)-1 {
  2902. if length := len(toAccumulate.Allocations); length != 1 {
  2903. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2904. }
  2905. result.Append(toAccumulate.Allocations[0])
  2906. toAccumulate = nil
  2907. }
  2908. }
  2909. return result, nil
  2910. }
  2911. func (asr *AllocationSetRange) accumulateByMonth() (*AllocationSetRange, error) {
  2912. var toAccumulate *AllocationSetRange
  2913. result := NewAllocationSetRange()
  2914. for i, as := range asr.Allocations {
  2915. if as.Window.Duration() != time.Hour*24 {
  2916. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  2917. }
  2918. _, month, _ := as.Window.Start().Date()
  2919. _, nextDayMonth, _ := as.Window.Start().Add(time.Hour * 24).Date()
  2920. if toAccumulate == nil {
  2921. toAccumulate = NewAllocationSetRange()
  2922. as = as.Clone()
  2923. }
  2924. toAccumulate.Append(as)
  2925. asAccumulated, err := toAccumulate.accumulate()
  2926. if err != nil {
  2927. return nil, fmt.Errorf("error accumulating result: %s", err)
  2928. }
  2929. toAccumulate = NewAllocationSetRange(asAccumulated)
  2930. // either the month has ended, or there are no more allocation sets
  2931. if month != nextDayMonth || i == len(asr.Allocations)-1 {
  2932. if length := len(toAccumulate.Allocations); length != 1 {
  2933. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2934. }
  2935. result.Append(toAccumulate.Allocations[0])
  2936. toAccumulate = nil
  2937. }
  2938. }
  2939. return result, nil
  2940. }
  2941. func (asr *AllocationSetRange) accumulateByWeek() (*AllocationSetRange, error) {
  2942. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() == timeutil.Week {
  2943. return asr, nil
  2944. }
  2945. var toAccumulate *AllocationSetRange
  2946. result := NewAllocationSetRange()
  2947. for i, as := range asr.Allocations {
  2948. if as.Window.Duration() != time.Hour*24 {
  2949. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  2950. }
  2951. dayOfWeek := as.Window.Start().Weekday()
  2952. if toAccumulate == nil {
  2953. toAccumulate = NewAllocationSetRange()
  2954. as = as.Clone()
  2955. }
  2956. toAccumulate.Append(as)
  2957. asAccumulated, err := toAccumulate.accumulate()
  2958. if err != nil {
  2959. return nil, fmt.Errorf("error accumulating result: %s", err)
  2960. }
  2961. toAccumulate = NewAllocationSetRange(asAccumulated)
  2962. // current assumption is the week always ends on Saturday, or there are no more allocation sets
  2963. if dayOfWeek == time.Saturday || i == len(asr.Allocations)-1 {
  2964. if length := len(toAccumulate.Allocations); length != 1 {
  2965. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2966. }
  2967. result.Append(toAccumulate.Allocations[0])
  2968. toAccumulate = nil
  2969. }
  2970. }
  2971. return result, nil
  2972. }
  2973. // AggregateBy aggregates each AllocationSet in the range by the given
  2974. // properties and options.
  2975. func (asr *AllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  2976. aggRange := &AllocationSetRange{Allocations: []*AllocationSet{}}
  2977. for _, as := range asr.Allocations {
  2978. err := as.AggregateBy(aggregateBy, options)
  2979. if err != nil {
  2980. return err
  2981. }
  2982. aggRange.Allocations = append(aggRange.Allocations, as)
  2983. }
  2984. asr.Allocations = aggRange.Allocations
  2985. return nil
  2986. }
  2987. // Append appends the given AllocationSet to the end of the range. It does not
  2988. // validate whether or not that violates window continuity.
  2989. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  2990. asr.Allocations = append(asr.Allocations, that)
  2991. }
  2992. // InsertRange merges the given AllocationSetRange into the receiving one by
  2993. // lining up sets with matching windows, then inserting each allocation from
  2994. // the given ASR into the respective set in the receiving ASR. If the given
  2995. // ASR contains an AllocationSet from a window that does not exist in the
  2996. // receiving ASR, then an error is returned. However, the given ASR does not
  2997. // need to cover the full range of the receiver.
  2998. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  2999. if asr == nil {
  3000. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  3001. }
  3002. // Providing an empty or nil set range is a no-op
  3003. if that == nil {
  3004. return nil
  3005. }
  3006. // keys maps window to index in asr
  3007. keys := map[string]int{}
  3008. for i, as := range asr.Allocations {
  3009. if as == nil {
  3010. continue
  3011. }
  3012. keys[as.Window.String()] = i
  3013. }
  3014. // Nothing to merge, so simply return
  3015. if len(keys) == 0 {
  3016. return nil
  3017. }
  3018. var err error
  3019. for _, thatAS := range that.Allocations {
  3020. if thatAS == nil || err != nil {
  3021. continue
  3022. }
  3023. // Find matching AllocationSet in asr
  3024. i, ok := keys[thatAS.Window.String()]
  3025. if !ok {
  3026. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  3027. continue
  3028. }
  3029. as, err := asr.Get(i)
  3030. if err != nil {
  3031. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  3032. continue
  3033. }
  3034. // Insert each Allocation from the given set
  3035. for _, alloc := range thatAS.Allocations {
  3036. err = as.Insert(alloc)
  3037. if err != nil {
  3038. err = fmt.Errorf("error inserting allocation: %s", err)
  3039. continue
  3040. }
  3041. }
  3042. }
  3043. // err might be nil
  3044. return err
  3045. }
  3046. // Length returns the length of the range, which is zero if nil
  3047. func (asr *AllocationSetRange) Length() int {
  3048. if asr == nil || asr.Allocations == nil {
  3049. return 0
  3050. }
  3051. return len(asr.Allocations)
  3052. }
  3053. // Slice copies the underlying slice of AllocationSets, maintaining order,
  3054. // and returns the copied slice.
  3055. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  3056. if asr == nil || asr.Allocations == nil {
  3057. return nil
  3058. }
  3059. copy := []*AllocationSet{}
  3060. for _, as := range asr.Allocations {
  3061. copy = append(copy, as.Clone())
  3062. }
  3063. return copy
  3064. }
  3065. // String represents the given AllocationSetRange as a string
  3066. func (asr *AllocationSetRange) String() string {
  3067. if asr == nil {
  3068. return "<nil>"
  3069. }
  3070. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  3071. }
  3072. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  3073. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  3074. // are sets with conflicting UTCOffsets (just returns the first).
  3075. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  3076. if asr.Length() == 0 {
  3077. return 0
  3078. }
  3079. as, err := asr.Get(0)
  3080. if err != nil {
  3081. return 0
  3082. }
  3083. return as.UTCOffset()
  3084. }
  3085. // Window returns the full window that the AllocationSetRange spans, from the
  3086. // start of the first AllocationSet to the end of the last one.
  3087. func (asr *AllocationSetRange) Window() Window {
  3088. if asr == nil || asr.Length() == 0 {
  3089. return NewWindow(nil, nil)
  3090. }
  3091. start := asr.Allocations[0].Start()
  3092. end := asr.Allocations[asr.Length()-1].End()
  3093. return NewWindow(&start, &end)
  3094. }
  3095. // Start returns the earliest start of all Allocations in the AllocationSetRange.
  3096. // It returns an error if there are no allocations.
  3097. func (asr *AllocationSetRange) Start() (time.Time, error) {
  3098. start := time.Time{}
  3099. if asr == nil {
  3100. return start, fmt.Errorf("had no data to compute a start from")
  3101. }
  3102. firstStartNotSet := true
  3103. for _, as := range asr.Allocations {
  3104. for _, a := range as.Allocations {
  3105. if firstStartNotSet {
  3106. start = a.Start
  3107. firstStartNotSet = false
  3108. }
  3109. if a.Start.Before(start) {
  3110. start = a.Start
  3111. }
  3112. }
  3113. }
  3114. if firstStartNotSet {
  3115. return start, fmt.Errorf("had no data to compute a start from")
  3116. }
  3117. return start, nil
  3118. }
  3119. // End returns the latest end of all Allocations in the AllocationSetRange.
  3120. // It returns an error if there are no allocations.
  3121. func (asr *AllocationSetRange) End() (time.Time, error) {
  3122. end := time.Time{}
  3123. if asr == nil {
  3124. return end, fmt.Errorf("had no data to compute an end from")
  3125. }
  3126. firstEndNotSet := true
  3127. for _, as := range asr.Allocations {
  3128. for _, a := range as.Allocations {
  3129. if firstEndNotSet {
  3130. end = a.End
  3131. firstEndNotSet = false
  3132. }
  3133. if a.End.After(end) {
  3134. end = a.End
  3135. }
  3136. }
  3137. }
  3138. if firstEndNotSet {
  3139. return end, fmt.Errorf("had no data to compute an end from")
  3140. }
  3141. return end, nil
  3142. }
  3143. // StartAndEnd iterates over all AssetSets in the AssetSetRange and returns the earliest start and
  3144. // latest end over the entire range
  3145. func (asr *AllocationSetRange) StartAndEnd() (time.Time, time.Time, error) {
  3146. start := time.Time{}
  3147. end := time.Time{}
  3148. if asr == nil {
  3149. return start, end, fmt.Errorf("had no data to compute a start and end from")
  3150. }
  3151. firstStartNotSet := true
  3152. firstEndNotSet := true
  3153. for _, as := range asr.Allocations {
  3154. for _, a := range as.Allocations {
  3155. if firstStartNotSet {
  3156. start = a.Start
  3157. firstStartNotSet = false
  3158. }
  3159. if a.Start.Before(start) {
  3160. start = a.Start
  3161. }
  3162. if firstEndNotSet {
  3163. end = a.End
  3164. firstEndNotSet = false
  3165. }
  3166. if a.End.After(end) {
  3167. end = a.End
  3168. }
  3169. }
  3170. }
  3171. if firstStartNotSet {
  3172. return start, end, fmt.Errorf("had no data to compute a start from")
  3173. }
  3174. if firstEndNotSet {
  3175. return start, end, fmt.Errorf("had no data to compute an end from")
  3176. }
  3177. return start, end, nil
  3178. }
  3179. // Minutes returns the duration, in minutes, between the earliest start
  3180. // and the latest end of all assets in the AllocationSetRange.
  3181. func (asr *AllocationSetRange) Minutes() float64 {
  3182. if asr == nil {
  3183. return 0
  3184. }
  3185. start, end, err := asr.StartAndEnd()
  3186. if err != nil {
  3187. return 0
  3188. }
  3189. duration := end.Sub(start)
  3190. return duration.Minutes()
  3191. }
  3192. // TotalCost returns the sum of all TotalCosts of the allocations contained
  3193. func (asr *AllocationSetRange) TotalCost() float64 {
  3194. if asr == nil || len(asr.Allocations) == 0 {
  3195. return 0.0
  3196. }
  3197. tc := 0.0
  3198. for _, as := range asr.Allocations {
  3199. tc += as.TotalCost()
  3200. }
  3201. return tc
  3202. }
  3203. // Clone returns a new AllocationSetRange cloned from the existing ASR
  3204. func (asr *AllocationSetRange) Clone() *AllocationSetRange {
  3205. sasrClone := NewAllocationSetRange()
  3206. sasrClone.FromStore = asr.FromStore
  3207. for _, as := range asr.Allocations {
  3208. asClone := as.Clone()
  3209. sasrClone.Append(asClone)
  3210. }
  3211. return sasrClone
  3212. }
  3213. func migrateAllocation(as *Allocation, fromVersion uint8, toVersion uint8) {
  3214. if fromVersion == toVersion {
  3215. return
  3216. }
  3217. if fromVersion == 22 && toVersion >= 23 {
  3218. as.GPUAllocation = &GPUAllocation{}
  3219. as.GPUAllocation.GPUUsageAverage = &as.deprecatedGPUUsageAverage
  3220. as.GPUAllocation.GPURequestAverage = &as.deprecatedGPURequestAverage
  3221. }
  3222. }