allocation.go 112 KB

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