allocation.go 120 KB

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