allocation.go 111 KB

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