allocation.go 111 KB

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