allocation.go 109 KB

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