allocation.go 87 KB

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