2
0

allocation.go 121 KB

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