allocation.go 119 KB

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