allocation.go 73 KB

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