allocation.go 92 KB

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