allocation.go 90 KB

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