summaryallocation.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  1. package kubecost
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/opencost/opencost/pkg/filter21/ast"
  9. "github.com/opencost/opencost/pkg/filter21/matcher"
  10. "github.com/opencost/opencost/pkg/log"
  11. "github.com/opencost/opencost/pkg/util/timeutil"
  12. )
  13. // SummaryAllocation summarizes an Allocation, keeping only fields necessary
  14. // for providing a high-level view of identifying the Allocation over a period
  15. // of time (Start, End) over which it ran, and inspecting the associated per-
  16. // resource costs (subtotaled with adjustments), total cost, and efficiency.
  17. //
  18. // SummaryAllocation does not have a concept of Window (i.e. the time period
  19. // within which it is defined, as opposed to the Start and End times). That
  20. // context must be provided by a SummaryAllocationSet.
  21. type SummaryAllocation struct {
  22. Name string `json:"name"`
  23. Properties *AllocationProperties `json:"-"`
  24. Start time.Time `json:"start"`
  25. End time.Time `json:"end"`
  26. CPUCoreRequestAverage float64 `json:"cpuCoreRequestAverage"`
  27. CPUCoreUsageAverage float64 `json:"cpuCoreUsageAverage"`
  28. CPUCost float64 `json:"cpuCost"`
  29. GPUCost float64 `json:"gpuCost"`
  30. NetworkCost float64 `json:"networkCost"`
  31. LoadBalancerCost float64 `json:"loadBalancerCost"`
  32. PVCost float64 `json:"pvCost"`
  33. RAMBytesRequestAverage float64 `json:"ramByteRequestAverage"`
  34. RAMBytesUsageAverage float64 `json:"ramByteUsageAverage"`
  35. RAMCost float64 `json:"ramCost"`
  36. SharedCost float64 `json:"sharedCost"`
  37. ExternalCost float64 `json:"externalCost"`
  38. Share bool `json:"-"`
  39. }
  40. // NewSummaryAllocation converts an Allocation to a SummaryAllocation by
  41. // dropping unnecessary fields and consolidating others (e.g. adjustments).
  42. // Reconciliation happens here because that process is synonymous with the
  43. // consolidation of adjustment fields.
  44. func NewSummaryAllocation(alloc *Allocation, reconcile, reconcileNetwork bool) *SummaryAllocation {
  45. if alloc == nil {
  46. return nil
  47. }
  48. sa := &SummaryAllocation{
  49. Name: alloc.Name,
  50. Properties: alloc.Properties,
  51. Start: alloc.Start,
  52. End: alloc.End,
  53. CPUCoreRequestAverage: alloc.CPUCoreRequestAverage,
  54. CPUCoreUsageAverage: alloc.CPUCoreUsageAverage,
  55. CPUCost: alloc.CPUCost + alloc.CPUCostAdjustment,
  56. GPUCost: alloc.GPUCost + alloc.GPUCostAdjustment,
  57. NetworkCost: alloc.NetworkCost + alloc.NetworkCostAdjustment,
  58. LoadBalancerCost: alloc.LoadBalancerCost + alloc.LoadBalancerCostAdjustment,
  59. PVCost: alloc.PVCost() + alloc.PVCostAdjustment,
  60. RAMBytesRequestAverage: alloc.RAMBytesRequestAverage,
  61. RAMBytesUsageAverage: alloc.RAMBytesUsageAverage,
  62. RAMCost: alloc.RAMCost + alloc.RAMCostAdjustment,
  63. SharedCost: alloc.SharedCost,
  64. ExternalCost: alloc.ExternalCost,
  65. }
  66. // Revert adjustments if reconciliation is off. If only network
  67. // reconciliation is off, only revert network adjustment.
  68. if !reconcile {
  69. sa.CPUCost -= alloc.CPUCostAdjustment
  70. sa.GPUCost -= alloc.GPUCostAdjustment
  71. sa.NetworkCost -= alloc.NetworkCostAdjustment
  72. sa.LoadBalancerCost -= alloc.LoadBalancerCostAdjustment
  73. sa.PVCost -= alloc.PVCostAdjustment
  74. sa.RAMCost -= alloc.RAMCostAdjustment
  75. } else if !reconcileNetwork {
  76. sa.NetworkCost -= alloc.NetworkCostAdjustment
  77. }
  78. return sa
  79. }
  80. // Add sums two SummaryAllocations, adding the given SummaryAllocation to the
  81. // receiving one, thus mutating the receiver. For performance reasons, it
  82. // simply drops Properties, so a SummaryAllocation can only be Added once.
  83. func (sa *SummaryAllocation) Add(that *SummaryAllocation) error {
  84. if sa == nil || that == nil {
  85. return errors.New("cannot Add a nil SummaryAllocation")
  86. }
  87. // Once Added, a SummaryAllocation has no Properties. This saves us from
  88. // having to compute the intersection of two sets of Properties, which is
  89. // expensive.
  90. sa.Properties = nil
  91. // Sum non-cumulative fields by turning them into cumulative, adding them,
  92. // and then converting them back into averages after minutes have been
  93. // combined (just below).
  94. cpuReqCoreMins := sa.CPUCoreRequestAverage * sa.Minutes()
  95. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  96. cpuUseCoreMins := sa.CPUCoreUsageAverage * sa.Minutes()
  97. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  98. ramReqByteMins := sa.RAMBytesRequestAverage * sa.Minutes()
  99. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  100. ramUseByteMins := sa.RAMBytesUsageAverage * sa.Minutes()
  101. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  102. // Expand Start and End to be the "max" of among the given Allocations
  103. if that.Start.Before(sa.Start) {
  104. sa.Start = that.Start
  105. }
  106. if that.End.After(sa.End) {
  107. sa.End = that.End
  108. }
  109. // Convert cumulative request and usage back into rates
  110. if sa.Minutes() > 0 {
  111. sa.CPUCoreRequestAverage = cpuReqCoreMins / sa.Minutes()
  112. sa.CPUCoreUsageAverage = cpuUseCoreMins / sa.Minutes()
  113. sa.RAMBytesRequestAverage = ramReqByteMins / sa.Minutes()
  114. sa.RAMBytesUsageAverage = ramUseByteMins / sa.Minutes()
  115. } else {
  116. sa.CPUCoreRequestAverage = 0.0
  117. sa.CPUCoreUsageAverage = 0.0
  118. sa.RAMBytesRequestAverage = 0.0
  119. sa.RAMBytesUsageAverage = 0.0
  120. }
  121. // Sum all cumulative cost fields
  122. sa.CPUCost += that.CPUCost
  123. sa.ExternalCost += that.ExternalCost
  124. sa.GPUCost += that.GPUCost
  125. sa.LoadBalancerCost += that.LoadBalancerCost
  126. sa.NetworkCost += that.NetworkCost
  127. sa.PVCost += that.PVCost
  128. sa.RAMCost += that.RAMCost
  129. sa.SharedCost += that.SharedCost
  130. return nil
  131. }
  132. // Clone copies the SummaryAllocation and returns the copy
  133. func (sa *SummaryAllocation) Clone() *SummaryAllocation {
  134. return &SummaryAllocation{
  135. Name: sa.Name,
  136. Properties: sa.Properties.Clone(),
  137. Start: sa.Start,
  138. End: sa.End,
  139. CPUCoreRequestAverage: sa.CPUCoreRequestAverage,
  140. CPUCoreUsageAverage: sa.CPUCoreUsageAverage,
  141. CPUCost: sa.CPUCost,
  142. GPUCost: sa.GPUCost,
  143. NetworkCost: sa.NetworkCost,
  144. LoadBalancerCost: sa.LoadBalancerCost,
  145. PVCost: sa.PVCost,
  146. RAMBytesRequestAverage: sa.RAMBytesRequestAverage,
  147. RAMBytesUsageAverage: sa.RAMBytesUsageAverage,
  148. RAMCost: sa.RAMCost,
  149. SharedCost: sa.SharedCost,
  150. ExternalCost: sa.ExternalCost,
  151. }
  152. }
  153. // CPUEfficiency is the ratio of usage to request. If there is no request and
  154. // no usage or cost, then efficiency is zero. If there is no request, but there
  155. // is usage or cost, then efficiency is 100%.
  156. func (sa *SummaryAllocation) CPUEfficiency() float64 {
  157. if sa == nil || sa.IsIdle() {
  158. return 0.0
  159. }
  160. if sa.CPUCoreRequestAverage > 0 {
  161. return sa.CPUCoreUsageAverage / sa.CPUCoreRequestAverage
  162. }
  163. if sa.CPUCoreUsageAverage == 0.0 || sa.CPUCost == 0.0 {
  164. return 0.0
  165. }
  166. return 1.0
  167. }
  168. func (sa *SummaryAllocation) Equal(that *SummaryAllocation) bool {
  169. if sa == nil || that == nil {
  170. return false
  171. }
  172. if sa.Name != that.Name {
  173. return false
  174. }
  175. if sa.Start != that.Start {
  176. return false
  177. }
  178. if sa.End != that.End {
  179. return false
  180. }
  181. if sa.CPUCoreRequestAverage != that.CPUCoreRequestAverage {
  182. return false
  183. }
  184. if sa.CPUCoreUsageAverage != that.CPUCoreUsageAverage {
  185. return false
  186. }
  187. if sa.CPUCost != that.CPUCost {
  188. return false
  189. }
  190. if sa.GPUCost != that.GPUCost {
  191. return false
  192. }
  193. if sa.NetworkCost != that.NetworkCost {
  194. return false
  195. }
  196. if sa.LoadBalancerCost != that.LoadBalancerCost {
  197. return false
  198. }
  199. if sa.PVCost != that.PVCost {
  200. return false
  201. }
  202. if sa.RAMBytesRequestAverage != that.RAMBytesRequestAverage {
  203. return false
  204. }
  205. if sa.RAMBytesUsageAverage != that.RAMBytesUsageAverage {
  206. return false
  207. }
  208. if sa.RAMCost != that.RAMCost {
  209. return false
  210. }
  211. if sa.SharedCost != that.SharedCost {
  212. return false
  213. }
  214. if sa.ExternalCost != that.ExternalCost {
  215. return false
  216. }
  217. return true
  218. }
  219. func (sa *SummaryAllocation) generateKey(aggregateBy []string, labelConfig *LabelConfig) string {
  220. if sa == nil {
  221. return ""
  222. }
  223. return sa.Properties.GenerateKey(aggregateBy, labelConfig)
  224. }
  225. // IsExternal is true if the given SummaryAllocation represents external costs.
  226. func (sa *SummaryAllocation) IsExternal() bool {
  227. if sa == nil {
  228. return false
  229. }
  230. return strings.Contains(sa.Name, ExternalSuffix)
  231. }
  232. // IsIdle is true if the given SummaryAllocation represents idle costs.
  233. func (sa *SummaryAllocation) IsIdle() bool {
  234. if sa == nil {
  235. return false
  236. }
  237. return strings.Contains(sa.Name, IdleSuffix)
  238. }
  239. // IsUnallocated is true if the given SummaryAllocation represents unallocated
  240. // costs.
  241. func (sa *SummaryAllocation) IsUnallocated() bool {
  242. if sa == nil {
  243. return false
  244. }
  245. return strings.Contains(sa.Name, UnallocatedSuffix)
  246. }
  247. // IsUnmounted is true if the given SummaryAllocation represents unmounted
  248. // volume costs.
  249. func (sa *SummaryAllocation) IsUnmounted() bool {
  250. if sa == nil {
  251. return false
  252. }
  253. return strings.Contains(sa.Name, UnmountedSuffix)
  254. }
  255. // Minutes returns the number of minutes the SummaryAllocation represents, as
  256. // defined by the difference between the end and start times.
  257. func (sa *SummaryAllocation) Minutes() float64 {
  258. if sa == nil {
  259. return 0.0
  260. }
  261. return sa.End.Sub(sa.Start).Minutes()
  262. }
  263. // RAMEfficiency is the ratio of usage to request. If there is no request and
  264. // no usage or cost, then efficiency is zero. If there is no request, but there
  265. // is usage or cost, then efficiency is 100%.
  266. func (sa *SummaryAllocation) RAMEfficiency() float64 {
  267. if sa == nil || sa.IsIdle() {
  268. return 0.0
  269. }
  270. if sa.RAMBytesRequestAverage > 0 {
  271. return sa.RAMBytesUsageAverage / sa.RAMBytesRequestAverage
  272. }
  273. if sa.RAMBytesUsageAverage == 0.0 || sa.RAMCost == 0.0 {
  274. return 0.0
  275. }
  276. return 1.0
  277. }
  278. // TotalCost is the total cost of the SummaryAllocation
  279. func (sa *SummaryAllocation) TotalCost() float64 {
  280. if sa == nil {
  281. return 0.0
  282. }
  283. return sa.CPUCost + sa.GPUCost + sa.RAMCost + sa.PVCost + sa.NetworkCost + sa.LoadBalancerCost + sa.SharedCost + sa.ExternalCost
  284. }
  285. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  286. // there is no cost at all, then efficiency is zero.
  287. func (sa *SummaryAllocation) TotalEfficiency() float64 {
  288. if sa == nil || sa.IsIdle() {
  289. return 0.0
  290. }
  291. if sa.RAMCost+sa.CPUCost > 0 {
  292. ramCostEff := sa.RAMEfficiency() * sa.RAMCost
  293. cpuCostEff := sa.CPUEfficiency() * sa.CPUCost
  294. return (ramCostEff + cpuCostEff) / (sa.CPUCost + sa.RAMCost)
  295. }
  296. return 0.0
  297. }
  298. // SummaryAllocationSet stores a set of SummaryAllocations, each with a unique
  299. // name, that share a window. An AllocationSet is mutable, so treat it like a
  300. // threadsafe map.
  301. type SummaryAllocationSet struct {
  302. sync.RWMutex
  303. externalKeys map[string]bool
  304. idleKeys map[string]bool
  305. SummaryAllocations map[string]*SummaryAllocation `json:"allocations"`
  306. Window Window `json:"window"`
  307. }
  308. // NewSummaryAllocationSet converts an AllocationSet to a SummaryAllocationSet.
  309. // Filter functions, keep functions, and reconciliation parameters are
  310. // required for unfortunate reasons to do with performance and legacy order-of-
  311. // operations details, as well as the fact that reconciliation has been
  312. // pushed down to the conversion step between Allocation and SummaryAllocation.
  313. //
  314. // This filter is an AllocationMatcher, not an AST, because at this point we
  315. // already have the data and want to make sure that the filter has already
  316. // gone through a compile step to deal with things like aliases.
  317. func NewSummaryAllocationSet(as *AllocationSet, filter AllocationMatcher, kfs []AllocationMatchFunc, reconcile, reconcileNetwork bool) *SummaryAllocationSet {
  318. if as == nil {
  319. return nil
  320. }
  321. // If we can know the exact size of the map, use it. If filters or sharing
  322. // functions are present, we can't know the size, so we make a default map.
  323. var sasMap map[string]*SummaryAllocation
  324. if filter == nil && len(kfs) == 0 {
  325. // No filters, so make the map of summary allocations exactly the size
  326. // of the origin allocation set.
  327. sasMap = make(map[string]*SummaryAllocation, len(as.Allocations))
  328. } else {
  329. // There are filters, so start with a standard map
  330. sasMap = make(map[string]*SummaryAllocation)
  331. }
  332. sas := &SummaryAllocationSet{
  333. SummaryAllocations: sasMap,
  334. Window: as.Window.Clone(),
  335. }
  336. for _, alloc := range as.Allocations {
  337. // First, detect if the allocation should be kept. If so, mark it as
  338. // such, insert it, and continue.
  339. shouldKeep := false
  340. for _, kf := range kfs {
  341. if kf(alloc) {
  342. shouldKeep = true
  343. break
  344. }
  345. }
  346. if shouldKeep {
  347. sa := NewSummaryAllocation(alloc, reconcile, reconcileNetwork)
  348. sa.Share = true
  349. sas.Insert(sa)
  350. continue
  351. }
  352. // If the allocation does not pass any of the given filter functions,
  353. // do not insert it into the set.
  354. if filter != nil && !filter.Matches(alloc) {
  355. continue
  356. }
  357. err := sas.Insert(NewSummaryAllocation(alloc, reconcile, reconcileNetwork))
  358. if err != nil {
  359. log.Errorf("SummaryAllocation: error inserting summary of %s", alloc.Name)
  360. }
  361. }
  362. for key := range as.ExternalKeys {
  363. sas.externalKeys[key] = true
  364. }
  365. for key := range as.IdleKeys {
  366. sas.idleKeys[key] = true
  367. }
  368. return sas
  369. }
  370. // Clone creates a deep copy of the SummaryAllocationSet
  371. func (sas *SummaryAllocationSet) Clone() *SummaryAllocationSet {
  372. sas.RLock()
  373. defer sas.RUnlock()
  374. externalKeys := make(map[string]bool, len(sas.externalKeys))
  375. for k, v := range sas.externalKeys {
  376. externalKeys[k] = v
  377. }
  378. idleKeys := make(map[string]bool, len(sas.idleKeys))
  379. for k, v := range sas.idleKeys {
  380. idleKeys[k] = v
  381. }
  382. summaryAllocations := make(map[string]*SummaryAllocation, len(sas.SummaryAllocations))
  383. for k, v := range sas.SummaryAllocations {
  384. summaryAllocations[k] = v.Clone()
  385. }
  386. return &SummaryAllocationSet{
  387. externalKeys: externalKeys,
  388. idleKeys: idleKeys,
  389. SummaryAllocations: summaryAllocations,
  390. Window: sas.Window.Clone(),
  391. }
  392. }
  393. // Add sums two SummaryAllocationSets, which Adds all SummaryAllocations in the
  394. // given SummaryAllocationSet to their counterparts in the receiving set. Add
  395. // also expands the Window to include both constituent Windows, in the case
  396. // that Add is being used from accumulating (as opposed to aggregating). For
  397. // performance reasons, the function may return either a new set, or an
  398. // unmodified original, so it should not be assumed that the original sets are
  399. // safeuly usable after calling Add.
  400. func (sas *SummaryAllocationSet) Add(that *SummaryAllocationSet) (*SummaryAllocationSet, error) {
  401. if sas == nil || len(sas.SummaryAllocations) == 0 {
  402. return that, nil
  403. }
  404. if that == nil || len(that.SummaryAllocations) == 0 {
  405. return sas, nil
  406. }
  407. if sas.Window.IsOpen() {
  408. return nil, errors.New("cannot add a SummaryAllocationSet with an open window")
  409. }
  410. // Set start, end to min(start), max(end)
  411. start := *sas.Window.Start()
  412. end := *sas.Window.End()
  413. if that.Window.Start().Before(start) {
  414. start = *that.Window.Start()
  415. }
  416. if that.Window.End().After(end) {
  417. end = *that.Window.End()
  418. }
  419. acc := &SummaryAllocationSet{
  420. SummaryAllocations: make(map[string]*SummaryAllocation, len(sas.SummaryAllocations)),
  421. Window: NewClosedWindow(start, end),
  422. }
  423. sas.RLock()
  424. defer sas.RUnlock()
  425. that.RLock()
  426. defer that.RUnlock()
  427. for _, alloc := range sas.SummaryAllocations {
  428. err := acc.Insert(alloc)
  429. if err != nil {
  430. return nil, err
  431. }
  432. }
  433. for _, alloc := range that.SummaryAllocations {
  434. err := acc.Insert(alloc)
  435. if err != nil {
  436. return nil, err
  437. }
  438. }
  439. return acc, nil
  440. }
  441. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  442. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  443. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  444. func (sas *SummaryAllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  445. if sas == nil || len(sas.SummaryAllocations) == 0 {
  446. return nil
  447. }
  448. if sas.Window.IsOpen() {
  449. return errors.New("cannot aggregate a SummaryAllocationSet with an open window")
  450. }
  451. if options == nil {
  452. options = &AllocationAggregationOptions{}
  453. }
  454. if options.LabelConfig == nil {
  455. options.LabelConfig = NewLabelConfig()
  456. }
  457. var filter AllocationMatcher
  458. if options.Filter == nil {
  459. filter = &matcher.AllPass[*Allocation]{}
  460. } else {
  461. compiler := NewAllocationMatchCompiler(options.LabelConfig)
  462. var err error
  463. filter, err = compiler.Compile(options.Filter)
  464. if err != nil {
  465. return fmt.Errorf("compiling filter '%s': %w", ast.ToPreOrderShortString(options.Filter), err)
  466. }
  467. }
  468. if filter == nil {
  469. return fmt.Errorf("unexpected nil filter")
  470. }
  471. // Check if we have any work to do; if not, then early return. If
  472. // aggregateBy is nil, we don't aggregate anything. On the other hand,
  473. // an empty slice implies that we should aggregate everything. (See
  474. // generateKey for why that makes sense.)
  475. shouldAggregate := aggregateBy != nil
  476. shouldKeep := len(options.SharedHourlyCosts) > 0 || len(options.ShareFuncs) > 0
  477. if !shouldAggregate && !shouldKeep {
  478. return nil
  479. }
  480. // The order of operations for aggregating a SummaryAllotionSet is as
  481. // follows:
  482. //
  483. // 1. Partition external, idle, and shared allocations into separate sets.
  484. // Also, create the resultSet into which the results will be aggregated.
  485. //
  486. // 2. Record resource totals for shared costs and unmounted volumes so
  487. // that we can account for them in computing idle coefficients.
  488. //
  489. // 3. Retrieve pre-computed allocation resource totals, which will be used
  490. // to compute idle sharing coefficients.
  491. //
  492. // 4. Convert shared hourly cost into a cumulative allocation to share,
  493. // and insert it into the share set.
  494. //
  495. // 5. Compute sharing coefficients per-aggregation, if sharing resources.
  496. //
  497. // 6. Distribute idle allocations according to the idle coefficients.
  498. //
  499. // 7. Record allocation resource totals (after filtration) if filters have
  500. // been applied. (Used for filtering proportional amount of idle.)
  501. //
  502. // 8. Generate aggregation key and insert allocation into the output set
  503. //
  504. // 9. If idle is shared and resources are shared, it's probable that some
  505. // amount of idle cost will be shared with a shared resource.
  506. // Distribute that idle cost, if it exists, among the respective shared
  507. // allocations before sharing them with the aggregated allocations.
  508. //
  509. // 10. Apply idle filtration, which "filters" the idle cost, or scales it
  510. // by the proportion of allocation resources remaining after filters
  511. // have been applied.
  512. //
  513. // 11. Distribute shared resources according to sharing coefficients.
  514. //
  515. // 12. Insert external allocations into the result set.
  516. //
  517. // 13. Insert any undistributed idle, in the case that idle
  518. // coefficients end up being zero and some idle is not shared.
  519. //
  520. // 14. Combine all idle allocations into a single idle allocation, unless
  521. // the option to keep idle split by cluster or node is enabled.
  522. // 1. Partition external, idle, and shared allocations into separate sets.
  523. // Also, create the resultSet into which the results will be aggregated.
  524. // resultSet will collect the aggregated allocations
  525. resultSet := &SummaryAllocationSet{
  526. Window: sas.Window.Clone(),
  527. }
  528. // externalSet will collect external allocations
  529. externalSet := &SummaryAllocationSet{
  530. Window: sas.Window.Clone(),
  531. }
  532. // idleSet will be shared among resultSet after initial aggregation
  533. // is complete
  534. idleSet := &SummaryAllocationSet{
  535. Window: sas.Window.Clone(),
  536. }
  537. // shareSet will be shared among resultSet after initial aggregation
  538. // is complete
  539. shareSet := &SummaryAllocationSet{
  540. Window: sas.Window.Clone(),
  541. }
  542. sas.Lock()
  543. defer sas.Unlock()
  544. // 2. Record resource totals for shared costs, aggregating by cluster or by
  545. // node (depending on if idle is partitioned by cluster or node) so that we
  546. // can account for them in computing idle coefficients. Do the same for
  547. // unmounted volume costs, which only require a total cost.
  548. sharedResourceTotals := map[string]*AllocationTotals{}
  549. totalUnmountedCost := 0.0
  550. // 1 & 2. Identify set membership and aggregate aforementioned totals.
  551. for _, sa := range sas.SummaryAllocations {
  552. if sa.Share {
  553. var key string
  554. if options.IdleByNode {
  555. key = fmt.Sprintf("%s/%s", sa.Properties.Cluster, sa.Properties.Node)
  556. } else {
  557. key = sa.Properties.Cluster
  558. }
  559. if _, ok := sharedResourceTotals[key]; !ok {
  560. sharedResourceTotals[key] = &AllocationTotals{}
  561. }
  562. sharedResourceTotals[key].CPUCost += sa.CPUCost
  563. sharedResourceTotals[key].GPUCost += sa.GPUCost
  564. sharedResourceTotals[key].LoadBalancerCost += sa.LoadBalancerCost
  565. sharedResourceTotals[key].NetworkCost += sa.NetworkCost
  566. sharedResourceTotals[key].PersistentVolumeCost += sa.PVCost
  567. sharedResourceTotals[key].RAMCost += sa.RAMCost
  568. shareSet.Insert(sa)
  569. delete(sas.SummaryAllocations, sa.Name)
  570. continue
  571. }
  572. // External allocations get aggregated post-hoc (see step 6) and do
  573. // not necessarily contain complete sets of properties, so they are
  574. // moved to a separate AllocationSet.
  575. if sa.IsExternal() {
  576. delete(sas.externalKeys, sa.Name)
  577. delete(sas.SummaryAllocations, sa.Name)
  578. externalSet.Insert(sa)
  579. continue
  580. }
  581. // Idle allocations should be separated into idleSet if they are to be
  582. // shared later on. If they are not to be shared, then add them to the
  583. // resultSet like any other allocation.
  584. if sa.IsIdle() {
  585. delete(sas.idleKeys, sa.Name)
  586. delete(sas.SummaryAllocations, sa.Name)
  587. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  588. idleSet.Insert(sa)
  589. } else {
  590. resultSet.Insert(sa)
  591. }
  592. continue
  593. }
  594. // Track total unmounted cost because it must be taken out of total
  595. // allocated costs for sharing coefficients.
  596. if sa.IsUnmounted() {
  597. totalUnmountedCost += sa.TotalCost()
  598. }
  599. }
  600. // It's possible that no more un-shared, non-idle, non-external allocations
  601. // remain at this point. This always results in an emptySet, so return early.
  602. if len(sas.SummaryAllocations) == 0 {
  603. sas.SummaryAllocations = map[string]*SummaryAllocation{}
  604. return nil
  605. }
  606. // 3. Retrieve pre-computed allocation resource totals, which will be used
  607. // to compute idle coefficients, based on the ratio of an allocation's per-
  608. // resource cost to the per-resource totals of that allocation's cluster or
  609. // node. Whether to perform this operation based on cluster or node is an
  610. // option. (See IdleByNode documentation; defaults to idle-by-cluster.)
  611. var allocTotals map[string]*AllocationTotals
  612. var ok bool
  613. if options.AllocationTotalsStore != nil {
  614. if options.IdleByNode {
  615. allocTotals, ok = options.AllocationTotalsStore.GetAllocationTotalsByNode(*sas.Window.Start(), *sas.Window.End())
  616. if !ok {
  617. return fmt.Errorf("nil allocation resource totals by node for %s", sas.Window)
  618. }
  619. } else {
  620. allocTotals, ok = options.AllocationTotalsStore.GetAllocationTotalsByCluster(*sas.Window.Start(), *sas.Window.End())
  621. if !ok {
  622. return fmt.Errorf("nil allocation resource totals by cluster for %s", sas.Window)
  623. }
  624. }
  625. }
  626. // If reconciliation has been fully or partially disabled, clear the
  627. // relevant adjustments from the alloc totals
  628. if allocTotals != nil && (!options.Reconcile || !options.ReconcileNetwork) {
  629. if !options.Reconcile {
  630. for _, tot := range allocTotals {
  631. tot.ClearAdjustments()
  632. }
  633. } else if !options.ReconcileNetwork {
  634. for _, tot := range allocTotals {
  635. tot.NetworkCostAdjustment = 0.0
  636. }
  637. }
  638. }
  639. // If filters have been applied, then we need to record allocation resource
  640. // totals after filtration (i.e. the allocations that are present) so that
  641. // we can identify the proportion of idle cost to keep. That is, we should
  642. // only return the idle cost that would be shared with the remaining
  643. // allocations, even if we're keeping idle separate. The totals should be
  644. // recorded by idle-key (cluster or node, depending on the IdleByNode
  645. // option). Instantiating this map is a signal to record the totals.
  646. var allocTotalsAfterFilters map[string]*AllocationTotals
  647. if len(resultSet.idleKeys) > 0 && options.Filter != nil {
  648. allocTotalsAfterFilters = make(map[string]*AllocationTotals, len(resultSet.idleKeys))
  649. }
  650. // If we're recording allocTotalsAfterFilters and there are shared costs,
  651. // then record those resource totals here so that idle for those shared
  652. // resources gets included.
  653. if allocTotalsAfterFilters != nil {
  654. for key, rt := range sharedResourceTotals {
  655. if _, ok := allocTotalsAfterFilters[key]; !ok {
  656. allocTotalsAfterFilters[key] = &AllocationTotals{}
  657. }
  658. // Record only those fields required for computing idle
  659. allocTotalsAfterFilters[key].CPUCost += rt.CPUCost
  660. allocTotalsAfterFilters[key].GPUCost += rt.GPUCost
  661. allocTotalsAfterFilters[key].RAMCost += rt.RAMCost
  662. }
  663. }
  664. // 4. Convert shared hourly cost into a cumulative allocation to share,
  665. // and insert it into the share set.
  666. for name, cost := range options.SharedHourlyCosts {
  667. if cost > 0.0 {
  668. hours := sas.Window.Hours()
  669. // If set ends in the future, adjust hours accordingly
  670. diff := time.Since(*sas.Window.End())
  671. if diff < 0.0 {
  672. hours += diff.Hours()
  673. }
  674. totalSharedCost := cost * hours
  675. shareSet.Insert(&SummaryAllocation{
  676. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  677. Properties: &AllocationProperties{},
  678. Start: *sas.Window.Start(),
  679. End: *sas.Window.End(),
  680. SharedCost: totalSharedCost,
  681. })
  682. }
  683. }
  684. // Sharing coefficients are recorded by post-aggregation-key (e.g. if
  685. // aggregating by namespace, then the key will be the namespace) and only
  686. // need to be recorded if there are shared resources. Instantiating this
  687. // map is the signal to record sharing coefficients.
  688. var sharingCoeffs map[string]float64
  689. if len(shareSet.SummaryAllocations) > 0 {
  690. sharingCoeffs = map[string]float64{}
  691. }
  692. // Loop over all remaining SummaryAllocations (after filters, sharing, &c.)
  693. // doing the following, in this order:
  694. // 5. Compute sharing coefficients, if there are shared resources
  695. // 6. Distribute idle cost, if sharing idle
  696. // 7. Record allocTotalsAfterFiltration, if filters have been applied
  697. // 8. Aggregate by key
  698. for _, sa := range sas.SummaryAllocations {
  699. // Generate key to use for aggregation-by-key and allocation name
  700. key := sa.generateKey(aggregateBy, options.LabelConfig)
  701. // 5. Incrementally add to sharing coefficients before adding idle
  702. // cost, which would skew the coefficients. These coefficients will be
  703. // later divided by a total, turning them into a coefficient between
  704. // 0.0 and 1.0.
  705. // NOTE: SummaryAllocation does not support ShareEven, so only record
  706. // by cost for cost-weighted distribution.
  707. if sharingCoeffs != nil {
  708. sharingCoeffs[key] += sa.TotalCost() - sa.SharedCost
  709. }
  710. // 6. Distribute idle allocations according to the idle coefficients.
  711. // NOTE: if idle allocation is off (i.e. options.ShareIdle: ShareNone)
  712. // then all idle allocations will be in the resultSet at this point, so
  713. // idleSet will be empty and we won't enter this block.
  714. if len(idleSet.SummaryAllocations) > 0 {
  715. for _, idle := range idleSet.SummaryAllocations {
  716. // Idle key is either cluster or node, as determined by the
  717. // IdleByNode option.
  718. var key string
  719. // Only share idle allocation with current allocation (sa) if
  720. // the relevant properties match (i.e. cluster and/or node)
  721. if idle.Properties.Cluster != sa.Properties.Cluster {
  722. continue
  723. }
  724. key = idle.Properties.Cluster
  725. if options.IdleByNode {
  726. if idle.Properties.Node != sa.Properties.Node {
  727. continue
  728. }
  729. key = fmt.Sprintf("%s/%s", idle.Properties.Cluster, idle.Properties.Node)
  730. }
  731. cpuCoeff, gpuCoeff, ramCoeff := ComputeIdleCoefficients(options.ShareIdle, key, sa.CPUCost, sa.GPUCost, sa.RAMCost, allocTotals)
  732. sa.CPUCost += idle.CPUCost * cpuCoeff
  733. sa.GPUCost += idle.GPUCost * gpuCoeff
  734. sa.RAMCost += idle.RAMCost * ramCoeff
  735. }
  736. }
  737. // The key becomes the allocation's name, which is used as the key by
  738. // which the allocation is inserted into the set.
  739. sa.Name = key
  740. // If merging unallocated allocations, rename all unallocated
  741. // allocations as simply __unallocated__
  742. if options.MergeUnallocated && sa.IsUnallocated() {
  743. sa.Name = UnallocatedSuffix
  744. }
  745. // 7. Record filtered resource totals for idle allocation filtration,
  746. // only if necessary.
  747. if allocTotalsAfterFilters != nil {
  748. key := sa.Properties.Cluster
  749. if options.IdleByNode {
  750. key = fmt.Sprintf("%s/%s", sa.Properties.Cluster, sa.Properties.Node)
  751. }
  752. if _, ok := allocTotalsAfterFilters[key]; !ok {
  753. allocTotalsAfterFilters[key] = &AllocationTotals{}
  754. }
  755. allocTotalsAfterFilters[key].CPUCost += sa.CPUCost
  756. allocTotalsAfterFilters[key].GPUCost += sa.GPUCost
  757. allocTotalsAfterFilters[key].RAMCost += sa.RAMCost
  758. }
  759. // 8. Inserting the allocation with the generated key for a name
  760. // performs the actual aggregation step.
  761. resultSet.Insert(sa)
  762. }
  763. // 9. If idle is shared and resources are shared, it's probable that some
  764. // amount of idle cost will be shared with a shared resource. Distribute
  765. // that idle cost, if it exists, among the respective shared allocations
  766. // before sharing them with the aggregated allocations.
  767. if len(idleSet.SummaryAllocations) > 0 && len(shareSet.SummaryAllocations) > 0 {
  768. for _, sa := range shareSet.SummaryAllocations {
  769. for _, idle := range idleSet.SummaryAllocations {
  770. var key string
  771. // Only share idle allocation with current allocation (sa) if
  772. // the relevant property matches (i.e. Cluster or Node,
  773. // depending on which idle sharing option is selected)
  774. if options.IdleByNode {
  775. if idle.Properties.Cluster != sa.Properties.Cluster || idle.Properties.Node != sa.Properties.Node {
  776. continue
  777. }
  778. key = fmt.Sprintf("%s/%s", idle.Properties.Cluster, idle.Properties.Node)
  779. } else {
  780. if idle.Properties.Cluster != sa.Properties.Cluster {
  781. continue
  782. }
  783. key = idle.Properties.Cluster
  784. }
  785. cpuCoeff, gpuCoeff, ramCoeff := ComputeIdleCoefficients(options.ShareIdle, key, sa.CPUCost, sa.GPUCost, sa.RAMCost, allocTotals)
  786. sa.CPUCost += idle.CPUCost * cpuCoeff
  787. sa.GPUCost += idle.GPUCost * gpuCoeff
  788. sa.RAMCost += idle.RAMCost * ramCoeff
  789. }
  790. }
  791. }
  792. // 10. Apply idle filtration, which "filters" the idle cost, i.e. scales
  793. // idle allocation costs per-resource by the proportion of allocation
  794. // resources remaining after filtering. In effect, this returns only the
  795. // idle costs that would have been shared with the remaining allocations,
  796. // even if idle is kept separated.
  797. if allocTotalsAfterFilters != nil {
  798. for idleKey := range resultSet.idleKeys {
  799. ia := resultSet.SummaryAllocations[idleKey]
  800. var key string
  801. if options.IdleByNode {
  802. key = fmt.Sprintf("%s/%s", ia.Properties.Cluster, ia.Properties.Node)
  803. } else {
  804. key = ia.Properties.Cluster
  805. }
  806. // Percentage of idle that should remain after filters are applied,
  807. // which equals the proportion of filtered-to-actual cost.
  808. cpuFilterCoeff := 0.0
  809. if allocTotals[key].TotalCPUCost() > 0.0 {
  810. filteredAlloc, ok := allocTotalsAfterFilters[key]
  811. if ok {
  812. cpuFilterCoeff = filteredAlloc.TotalCPUCost() / allocTotals[key].TotalCPUCost()
  813. } else {
  814. cpuFilterCoeff = 0.0
  815. }
  816. }
  817. gpuFilterCoeff := 0.0
  818. if allocTotals[key].TotalGPUCost() > 0.0 {
  819. filteredAlloc, ok := allocTotalsAfterFilters[key]
  820. if ok {
  821. gpuFilterCoeff = filteredAlloc.TotalGPUCost() / allocTotals[key].TotalGPUCost()
  822. } else {
  823. gpuFilterCoeff = 0.0
  824. }
  825. }
  826. ramFilterCoeff := 0.0
  827. if allocTotals[key].TotalRAMCost() > 0.0 {
  828. filteredAlloc, ok := allocTotalsAfterFilters[key]
  829. if ok {
  830. ramFilterCoeff = filteredAlloc.TotalRAMCost() / allocTotals[key].TotalRAMCost()
  831. } else {
  832. ramFilterCoeff = 0.0
  833. }
  834. }
  835. ia.CPUCost *= cpuFilterCoeff
  836. ia.GPUCost *= gpuFilterCoeff
  837. ia.RAMCost *= ramFilterCoeff
  838. }
  839. }
  840. // 11. Distribute shared resources according to sharing coefficients.
  841. // NOTE: ShareEven is not supported
  842. if len(shareSet.SummaryAllocations) > 0 {
  843. totalTotalCost := 0.0
  844. sharedTotalCost := 0.0
  845. sharingCoeffDenominator := 0.0
  846. for _, rt := range allocTotals {
  847. sharingCoeffDenominator += rt.TotalCost()
  848. totalTotalCost += rt.TotalCost()
  849. }
  850. // Do not include the shared costs, themselves, when determining
  851. // sharing coefficients.
  852. for _, rt := range sharedResourceTotals {
  853. sharingCoeffDenominator -= rt.TotalCost()
  854. sharedTotalCost += rt.TotalCost()
  855. }
  856. // Do not include the unmounted costs when determining sharing
  857. // coefficients because they do not receive shared costs.
  858. sharingCoeffDenominator -= totalUnmountedCost
  859. log.Infof("BD-152: sharingCoeffDenom=%f (total cost: %f; shared cost: %f; unmounted cost: %f)", sharingCoeffDenominator, totalTotalCost, sharedTotalCost, totalUnmountedCost)
  860. if sharingCoeffDenominator <= 0.0 {
  861. log.Warnf("SummaryAllocation: sharing coefficient denominator is %f", sharingCoeffDenominator)
  862. } else {
  863. // Needs to be 1.00000
  864. sumSharingCoeffs := 0.0
  865. // Compute sharing coeffs by dividing the thus-far accumulated
  866. // numerators by the now-finalized denominator.
  867. for key := range sharingCoeffs {
  868. if sharingCoeffs[key] > 0.0 {
  869. before := sharingCoeffs[key]
  870. sharingCoeffs[key] /= sharingCoeffDenominator
  871. log.Infof("BD152: sharingCoeff[%s]=%f ; numerator before=%f", key, sharingCoeffs[key], before)
  872. sumSharingCoeffs += sharingCoeffs[key]
  873. } else {
  874. log.Warnf("SummaryAllocation: detected illegal sharing coefficient for %s: %v (setting to zero)", key, sharingCoeffs[key])
  875. sharingCoeffs[key] = 0.0
  876. }
  877. }
  878. // HERE if you add all the sharingCoeffs, you should get 1.00000 exactly
  879. // "integration": 0.27
  880. // "ally": 0.13
  881. // ...
  882. // TOTAL : 1.000000
  883. log.Infof("BD152: sum of sharingCoeffs = %f", sumSharingCoeffs)
  884. for key, sa := range resultSet.SummaryAllocations {
  885. // Idle and unmounted allocations, by definition, do not
  886. // receive shared cost
  887. if sa.IsIdle() || sa.IsUnmounted() {
  888. continue
  889. }
  890. sharingCoeff := sharingCoeffs[key]
  891. // Distribute each shared cost with the current allocation on the
  892. // basis of the proportion of the allocation's cost (ShareWeighted)
  893. // or count (ShareEven) to the total aggregated cost or count. This
  894. // condition should hold in spite of filters because the sharing
  895. // coefficient denominator is held constant by pre-computed
  896. // resource totals and the post-aggregation total cost of the
  897. // remaining allocations will, by definition, not be affected.
  898. for _, shared := range shareSet.SummaryAllocations {
  899. sa.SharedCost += shared.TotalCost() * sharingCoeff
  900. }
  901. }
  902. }
  903. }
  904. // 12. Insert external allocations into the result set.
  905. for _, sa := range externalSet.SummaryAllocations {
  906. // Make an allocation with the same properties and test that
  907. // against the FilterFunc to see if the external allocation should
  908. // be filtered or not.
  909. // TODO:CLEANUP do something about external cost, this stinks
  910. ea := &Allocation{Properties: sa.Properties}
  911. if filter.Matches(ea) {
  912. key := sa.generateKey(aggregateBy, options.LabelConfig)
  913. sa.Name = key
  914. resultSet.Insert(sa)
  915. }
  916. }
  917. // 13. Distribute remaining, undistributed idle. Undistributed idle is any
  918. // per-resource idle cost for which there can be no idle coefficient
  919. // computed because there is zero usage across all allocations.
  920. for _, isa := range idleSet.SummaryAllocations {
  921. // Make an allocation with the same properties and test that
  922. // against the FilterFunc to see if the external allocation should
  923. // be filtered or not.
  924. // TODO:CLEANUP do something about external cost, this stinks
  925. ia := &Allocation{Properties: isa.Properties}
  926. // if the idle does not apply to the non-filtered values, skip it
  927. if !filter.Matches(ia) {
  928. continue
  929. }
  930. key := isa.Properties.Cluster
  931. if options.IdleByNode {
  932. key = fmt.Sprintf("%s/%s", isa.Properties.Cluster, isa.Properties.Node)
  933. }
  934. rt, ok := allocTotals[key]
  935. if !ok {
  936. log.Warnf("SummaryAllocation: AggregateBy: cannot handle undistributed idle for '%s'", key)
  937. continue
  938. }
  939. hasUndistributableCost := false
  940. if isa.CPUCost > 0.0 && rt.CPUCost == 0.0 {
  941. // There is idle CPU cost, but no allocated CPU cost, so that cost
  942. // is undistributable and must be inserted.
  943. hasUndistributableCost = true
  944. } else {
  945. // Cost was entirely distributed, so zero it out
  946. isa.CPUCost = 0.0
  947. }
  948. if isa.GPUCost > 0.0 && rt.GPUCost == 0.0 {
  949. // There is idle GPU cost, but no allocated GPU cost, so that cost
  950. // is undistributable and must be inserted.
  951. hasUndistributableCost = true
  952. } else {
  953. // Cost was entirely distributed, so zero it out
  954. isa.GPUCost = 0.0
  955. }
  956. if isa.RAMCost > 0.0 && rt.RAMCost == 0.0 {
  957. // There is idle CPU cost, but no allocated CPU cost, so that cost
  958. // is undistributable and must be inserted.
  959. hasUndistributableCost = true
  960. } else {
  961. // Cost was entirely distributed, so zero it out
  962. isa.RAMCost = 0.0
  963. }
  964. if hasUndistributableCost {
  965. isa.Name = fmt.Sprintf("%s/%s", key, IdleSuffix)
  966. resultSet.Insert(isa)
  967. }
  968. }
  969. // 14. Combine all idle allocations into a single idle allocation, unless
  970. // the option to keep idle split by cluster or node is enabled.
  971. if !options.SplitIdle {
  972. for _, ia := range resultSet.idleAllocations() {
  973. resultSet.Delete(ia.Name)
  974. ia.Name = IdleSuffix
  975. resultSet.Insert(ia)
  976. }
  977. }
  978. // Replace the existing set's data with the new, aggregated summary data
  979. sas.SummaryAllocations = resultSet.SummaryAllocations
  980. return nil
  981. }
  982. // Delete removes the allocation with the given name from the set
  983. func (sas *SummaryAllocationSet) Delete(name string) {
  984. if sas == nil {
  985. return
  986. }
  987. sas.Lock()
  988. defer sas.Unlock()
  989. delete(sas.externalKeys, name)
  990. delete(sas.idleKeys, name)
  991. delete(sas.SummaryAllocations, name)
  992. }
  993. // Each invokes the given function for each SummaryAllocation in the set
  994. func (sas *SummaryAllocationSet) Each(f func(string, *SummaryAllocation)) {
  995. if sas == nil {
  996. return
  997. }
  998. for k, a := range sas.SummaryAllocations {
  999. f(k, a)
  1000. }
  1001. }
  1002. func (sas *SummaryAllocationSet) Equal(that *SummaryAllocationSet) bool {
  1003. if sas == nil || that == nil {
  1004. return false
  1005. }
  1006. sas.RLock()
  1007. defer sas.RUnlock()
  1008. if !sas.Window.Equal(that.Window) {
  1009. return false
  1010. }
  1011. if len(sas.SummaryAllocations) != len(that.SummaryAllocations) {
  1012. return false
  1013. }
  1014. for name, sa := range sas.SummaryAllocations {
  1015. thatSA, ok := that.SummaryAllocations[name]
  1016. if !ok {
  1017. return false
  1018. }
  1019. if !sa.Equal(thatSA) {
  1020. return false
  1021. }
  1022. }
  1023. return true
  1024. }
  1025. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1026. func (sas *SummaryAllocationSet) idleAllocations() map[string]*SummaryAllocation {
  1027. idles := map[string]*SummaryAllocation{}
  1028. if sas == nil || len(sas.SummaryAllocations) == 0 {
  1029. return idles
  1030. }
  1031. sas.RLock()
  1032. defer sas.RUnlock()
  1033. for key := range sas.idleKeys {
  1034. if sa, ok := sas.SummaryAllocations[key]; ok {
  1035. idles[key] = sa
  1036. }
  1037. }
  1038. return idles
  1039. }
  1040. // Insert aggregates the current entry in the SummaryAllocationSet by the given Allocation,
  1041. // but only if the Allocation is valid, i.e. matches the SummaryAllocationSet's window. If
  1042. // there is no existing entry, one is created. Nil error response indicates success.
  1043. func (sas *SummaryAllocationSet) Insert(sa *SummaryAllocation) error {
  1044. if sas == nil {
  1045. return fmt.Errorf("cannot insert into nil SummaryAllocationSet")
  1046. }
  1047. if sa == nil {
  1048. return fmt.Errorf("cannot insert a nil SummaryAllocation")
  1049. }
  1050. sas.Lock()
  1051. defer sas.Unlock()
  1052. if sas.SummaryAllocations == nil {
  1053. sas.SummaryAllocations = map[string]*SummaryAllocation{}
  1054. }
  1055. if sas.externalKeys == nil {
  1056. sas.externalKeys = map[string]bool{}
  1057. }
  1058. if sas.idleKeys == nil {
  1059. sas.idleKeys = map[string]bool{}
  1060. }
  1061. // Add the given Allocation to the existing entry, if there is one;
  1062. // otherwise just set directly into allocations
  1063. if _, ok := sas.SummaryAllocations[sa.Name]; ok {
  1064. err := sas.SummaryAllocations[sa.Name].Add(sa)
  1065. if err != nil {
  1066. return fmt.Errorf("SummaryAllocationSet.Insert: error trying to Add: %s", err)
  1067. }
  1068. } else {
  1069. sas.SummaryAllocations[sa.Name] = sa
  1070. }
  1071. // If the given Allocation is an external one, record that
  1072. if sa.IsExternal() {
  1073. sas.externalKeys[sa.Name] = true
  1074. }
  1075. // If the given Allocation is an idle one, record that
  1076. if sa.IsIdle() {
  1077. sas.idleKeys[sa.Name] = true
  1078. }
  1079. return nil
  1080. }
  1081. func (sas *SummaryAllocationSet) TotalCost() float64 {
  1082. if sas == nil {
  1083. return 0.0
  1084. }
  1085. sas.RLock()
  1086. defer sas.RUnlock()
  1087. tc := 0.0
  1088. for _, sa := range sas.SummaryAllocations {
  1089. tc += sa.TotalCost()
  1090. }
  1091. return tc
  1092. }
  1093. // RAMEfficiency func to calculate average RAM efficiency over SummaryAllocationSet
  1094. func (sas *SummaryAllocationSet) RAMEfficiency() float64 {
  1095. if sas == nil {
  1096. return 0.0
  1097. }
  1098. sas.RLock()
  1099. defer sas.RUnlock()
  1100. totalRAMBytesMinutesUsage := 0.0
  1101. totalRAMBytesMinutesRequest := 0.0
  1102. totalRAMCost := 0.0
  1103. for _, sa := range sas.SummaryAllocations {
  1104. if sa.IsIdle() {
  1105. continue
  1106. }
  1107. totalRAMBytesMinutesUsage += sa.RAMBytesUsageAverage * sa.Minutes()
  1108. totalRAMBytesMinutesRequest += sa.RAMBytesRequestAverage * sa.Minutes()
  1109. totalRAMCost += sa.RAMCost
  1110. }
  1111. if totalRAMBytesMinutesRequest > 0 {
  1112. return totalRAMBytesMinutesUsage / totalRAMBytesMinutesRequest
  1113. }
  1114. if totalRAMBytesMinutesUsage == 0.0 || totalRAMCost == 0.0 {
  1115. return 0.0
  1116. }
  1117. return 1.0
  1118. }
  1119. // CPUEfficiency func to calculate average CPU efficiency over SummaryAllocationSet
  1120. func (sas *SummaryAllocationSet) CPUEfficiency() float64 {
  1121. if sas == nil {
  1122. return 0.0
  1123. }
  1124. sas.RLock()
  1125. defer sas.RUnlock()
  1126. totalCPUCoreMinutesUsage := 0.0
  1127. totalCPUCoreMinutesRequest := 0.0
  1128. totalCPUCost := 0.0
  1129. for _, sa := range sas.SummaryAllocations {
  1130. if sa.IsIdle() {
  1131. continue
  1132. }
  1133. totalCPUCoreMinutesUsage += sa.CPUCoreUsageAverage * sa.Minutes()
  1134. totalCPUCoreMinutesRequest += sa.CPUCoreRequestAverage * sa.Minutes()
  1135. totalCPUCost += sa.CPUCost
  1136. }
  1137. if totalCPUCoreMinutesRequest > 0 {
  1138. return totalCPUCoreMinutesUsage / totalCPUCoreMinutesRequest
  1139. }
  1140. if totalCPUCoreMinutesUsage == 0.0 || totalCPUCost == 0.0 {
  1141. return 0.0
  1142. }
  1143. return 1.0
  1144. }
  1145. // TotalEfficiency func to calculate average Total efficiency over SummaryAllocationSet
  1146. func (sas *SummaryAllocationSet) TotalEfficiency() float64 {
  1147. if sas == nil {
  1148. return 0.0
  1149. }
  1150. sas.RLock()
  1151. defer sas.RUnlock()
  1152. totalRAMCost := 0.0
  1153. totalCPUCost := 0.0
  1154. for _, sa := range sas.SummaryAllocations {
  1155. if sa.IsIdle() {
  1156. continue
  1157. }
  1158. totalRAMCost += sa.RAMCost
  1159. totalCPUCost += sa.CPUCost
  1160. }
  1161. if totalRAMCost+totalCPUCost > 0 {
  1162. return (totalRAMCost*sas.RAMEfficiency() + totalCPUCost*sas.CPUEfficiency()) / (totalRAMCost + totalCPUCost)
  1163. }
  1164. return 0.0
  1165. }
  1166. // SummaryAllocationSetRange is a thread-safe slice of SummaryAllocationSets.
  1167. type SummaryAllocationSetRange struct {
  1168. sync.RWMutex
  1169. Step time.Duration `json:"step"`
  1170. SummaryAllocationSets []*SummaryAllocationSet `json:"sets"`
  1171. Window Window `json:"window"`
  1172. Message string `json:"-"`
  1173. }
  1174. // NewSummaryAllocationSetRange instantiates a new range composed of the given
  1175. // SummaryAllocationSets in the order provided. The expectations about the
  1176. // SummaryAllocationSets are as follows:
  1177. // - window durations are all equal
  1178. // - sets are consecutive (i.e. chronologically sorted)
  1179. // - there are no gaps between sets
  1180. // - sets do not have overlapping windows
  1181. func NewSummaryAllocationSetRange(sass ...*SummaryAllocationSet) *SummaryAllocationSetRange {
  1182. var step time.Duration
  1183. window := NewWindow(nil, nil)
  1184. for _, sas := range sass {
  1185. if window.Start() == nil || (sas.Window.Start() != nil && sas.Window.Start().Before(*window.Start())) {
  1186. window.start = sas.Window.Start()
  1187. }
  1188. if window.End() == nil || (sas.Window.End() != nil && sas.Window.End().After(*window.End())) {
  1189. window.end = sas.Window.End()
  1190. }
  1191. if step == 0 {
  1192. step = sas.Window.Duration()
  1193. } else if step != sas.Window.Duration() {
  1194. log.Warnf("instantiating range with step %s using set of step %s is illegal", step, sas.Window.Duration())
  1195. }
  1196. }
  1197. return &SummaryAllocationSetRange{
  1198. Step: step,
  1199. SummaryAllocationSets: sass,
  1200. Window: window,
  1201. }
  1202. }
  1203. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1204. // AllocationSet for the entire range.
  1205. func (sasr *SummaryAllocationSetRange) accumulate() (*SummaryAllocationSet, error) {
  1206. var result *SummaryAllocationSet
  1207. var err error
  1208. sasr.RLock()
  1209. defer sasr.RUnlock()
  1210. for _, sas := range sasr.SummaryAllocationSets {
  1211. result, err = result.Add(sas)
  1212. if err != nil {
  1213. return nil, err
  1214. }
  1215. }
  1216. return result, nil
  1217. }
  1218. // newAccumulation clones the first available SummaryAllocationSet to use as the data structure to
  1219. // accumulate the remaining data. This leaves the original SummaryAllocationSetRange intact.
  1220. func (sasr *SummaryAllocationSetRange) newAccumulation() (*SummaryAllocationSet, error) {
  1221. var result *SummaryAllocationSet
  1222. var err error
  1223. sasr.RLock()
  1224. defer sasr.RUnlock()
  1225. for _, sas := range sasr.SummaryAllocationSets {
  1226. // we want to clone the first summary allocation set, then just Add the others
  1227. // to the clone. We will eventually use the clone to create the set range.
  1228. if result == nil {
  1229. result = sas.Clone()
  1230. continue
  1231. }
  1232. // Copy if sas is non-nil
  1233. var sasCopy *SummaryAllocationSet = nil
  1234. if sas != nil {
  1235. sasCopy = sas.Clone()
  1236. }
  1237. // nil is ok to pass into Add
  1238. result, err = result.Add(sasCopy)
  1239. if err != nil {
  1240. return nil, err
  1241. }
  1242. }
  1243. return result, nil
  1244. }
  1245. // AggregateBy aggregates each AllocationSet in the range by the given
  1246. // properties and options.
  1247. func (sasr *SummaryAllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  1248. sasr.Lock()
  1249. defer sasr.Unlock()
  1250. for _, sas := range sasr.SummaryAllocationSets {
  1251. err := sas.AggregateBy(aggregateBy, options)
  1252. if err != nil {
  1253. // Wipe out data so that corrupt data cannot be mistakenly used
  1254. sasr.SummaryAllocationSets = []*SummaryAllocationSet{}
  1255. return err
  1256. }
  1257. }
  1258. return nil
  1259. }
  1260. // Append appends the given AllocationSet to the end of the range. It does not
  1261. // validate whether or not that violates window continuity.
  1262. func (sasr *SummaryAllocationSetRange) Append(sas *SummaryAllocationSet) {
  1263. sasr.Lock()
  1264. defer sasr.Unlock()
  1265. // Append to list of sets
  1266. sasr.SummaryAllocationSets = append(sasr.SummaryAllocationSets, sas)
  1267. // Set step, if not set
  1268. if sasr.Step == 0 {
  1269. sasr.Step = sas.Window.Duration()
  1270. }
  1271. // Adjust window
  1272. if sasr.Window.Start() == nil || (sas.Window.Start() != nil && sas.Window.Start().Before(*sasr.Window.Start())) {
  1273. sasr.Window.start = sas.Window.Start()
  1274. }
  1275. if sasr.Window.End() == nil || (sas.Window.End() != nil && sas.Window.End().After(*sasr.Window.End())) {
  1276. sasr.Window.end = sas.Window.End()
  1277. }
  1278. }
  1279. // Each invokes the given function for each AllocationSet in the range
  1280. func (sasr *SummaryAllocationSetRange) Each(f func(int, *SummaryAllocationSet)) {
  1281. if sasr == nil {
  1282. return
  1283. }
  1284. for i, as := range sasr.SummaryAllocationSets {
  1285. f(i, as)
  1286. }
  1287. }
  1288. // InsertExternalAllocations takes all allocations in the given
  1289. // AllocationSetRange (they should all be considered "external") and inserts
  1290. // them into the receiving SummaryAllocationSetRange.
  1291. // TODO:CLEANUP replace this with a better idea (or get rid of external
  1292. // allocations, as such, altogether)
  1293. func (sasr *SummaryAllocationSetRange) InsertExternalAllocations(that *AllocationSetRange) error {
  1294. if sasr == nil {
  1295. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  1296. }
  1297. // keys maps window to index in range
  1298. keys := map[string]int{}
  1299. for i, as := range sasr.SummaryAllocationSets {
  1300. if as == nil {
  1301. continue
  1302. }
  1303. keys[as.Window.String()] = i
  1304. }
  1305. // Nothing to merge, so simply return
  1306. if len(keys) == 0 {
  1307. return nil
  1308. }
  1309. var err error
  1310. for _, thatAS := range that.Allocations {
  1311. if thatAS == nil || err != nil {
  1312. continue
  1313. }
  1314. // Find matching AllocationSet in asr
  1315. i, ok := keys[thatAS.Window.String()]
  1316. if !ok {
  1317. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  1318. continue
  1319. }
  1320. sas := sasr.SummaryAllocationSets[i]
  1321. // Insert each Allocation from the given set
  1322. for _, alloc := range thatAS.Allocations {
  1323. externalSA := NewSummaryAllocation(alloc, true, true)
  1324. // This error will be returned below
  1325. // TODO:CLEANUP should Each have early-error-return functionality?
  1326. err = sas.Insert(externalSA)
  1327. }
  1328. }
  1329. // err might be nil
  1330. return err
  1331. }
  1332. func (sasr *SummaryAllocationSetRange) TotalCost() float64 {
  1333. if sasr == nil {
  1334. return 0.0
  1335. }
  1336. sasr.RLock()
  1337. defer sasr.RUnlock()
  1338. tc := 0.0
  1339. for _, sas := range sasr.SummaryAllocationSets {
  1340. tc += sas.TotalCost()
  1341. }
  1342. return tc
  1343. }
  1344. // TODO remove after testing
  1345. func (sasr *SummaryAllocationSetRange) Print(verbose bool) {
  1346. fmt.Printf("%s (dur=%s, len=%d, cost=%.5f)\n", sasr.Window, sasr.Window.Duration(), len(sasr.SummaryAllocationSets), sasr.TotalCost())
  1347. for _, sas := range sasr.SummaryAllocationSets {
  1348. fmt.Printf(" > %s (dur=%s, len=%d, cost=%.5f) \n", sas.Window, sas.Window.Duration(), len(sas.SummaryAllocations), sas.TotalCost())
  1349. for key, sa := range sas.SummaryAllocations {
  1350. if verbose {
  1351. fmt.Printf(" {\"%s\", cpu: %.5f, gpu: %.5f, lb: %.5f, net: %.5f, pv: %.5f, ram: %.5f, shared: %.5f, external: %.5f}\n",
  1352. key, sa.CPUCost, sa.GPUCost, sa.LoadBalancerCost, sa.NetworkCost, sa.PVCost, sa.RAMCost, sa.SharedCost, sa.ExternalCost)
  1353. } else {
  1354. fmt.Printf(" - \"%s\": %.5f\n", key, sa.TotalCost())
  1355. }
  1356. }
  1357. }
  1358. }
  1359. func (sasr *SummaryAllocationSetRange) Accumulate(accumulateBy AccumulateOption) (*SummaryAllocationSetRange, error) {
  1360. switch accumulateBy {
  1361. case AccumulateOptionNone:
  1362. return sasr.accumulateByNone()
  1363. case AccumulateOptionAll:
  1364. return sasr.accumulateByAll()
  1365. case AccumulateOptionHour:
  1366. return sasr.accumulateByHour()
  1367. case AccumulateOptionDay:
  1368. return sasr.accumulateByDay()
  1369. case AccumulateOptionWeek:
  1370. return sasr.accumulateByWeek()
  1371. case AccumulateOptionMonth:
  1372. return sasr.accumulateByMonth()
  1373. default:
  1374. // this should never happen
  1375. return nil, fmt.Errorf("unexpected error, invalid accumulateByType: %s", accumulateBy)
  1376. }
  1377. }
  1378. func (sasr *SummaryAllocationSetRange) accumulateByNone() (*SummaryAllocationSetRange, error) {
  1379. return sasr.clone(), nil
  1380. }
  1381. func (sasr *SummaryAllocationSetRange) accumulateByAll() (*SummaryAllocationSetRange, error) {
  1382. var err error
  1383. var result *SummaryAllocationSet
  1384. result, err = sasr.newAccumulation()
  1385. if err != nil {
  1386. return nil, fmt.Errorf("error running accumulate: %s", err)
  1387. }
  1388. accumulated := NewSummaryAllocationSetRange(result)
  1389. return accumulated, nil
  1390. }
  1391. func (sasr *SummaryAllocationSetRange) accumulateByHour() (*SummaryAllocationSetRange, error) {
  1392. // ensure that the summary allocation sets have a 1-hour window, if a set exists
  1393. if len(sasr.SummaryAllocationSets) > 0 && sasr.SummaryAllocationSets[0].Window.Duration() != time.Hour {
  1394. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", sasr.SummaryAllocationSets[0].Window.Duration())
  1395. }
  1396. result := sasr.clone()
  1397. return result, nil
  1398. }
  1399. func (sasr *SummaryAllocationSetRange) accumulateByDay() (*SummaryAllocationSetRange, error) {
  1400. // if the summary allocation set window is 1-day, just return the existing summary allocation set range
  1401. if len(sasr.SummaryAllocationSets) > 0 && sasr.SummaryAllocationSets[0].Window.Duration() == time.Hour*24 {
  1402. return sasr, nil
  1403. }
  1404. var toAccumulate *SummaryAllocationSetRange
  1405. result := NewSummaryAllocationSetRange()
  1406. for i, as := range sasr.SummaryAllocationSets {
  1407. if as.Window.Duration() != time.Hour {
  1408. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", as.Window.Duration())
  1409. }
  1410. hour := as.Window.Start().Hour()
  1411. if toAccumulate == nil {
  1412. toAccumulate = NewSummaryAllocationSetRange()
  1413. as = as.Clone()
  1414. }
  1415. toAccumulate.Append(as)
  1416. sas, err := toAccumulate.accumulate()
  1417. if err != nil {
  1418. return nil, fmt.Errorf("error accumulating result: %s", err)
  1419. }
  1420. toAccumulate = NewSummaryAllocationSetRange(sas)
  1421. if hour == 23 || i == len(sasr.SummaryAllocationSets)-1 {
  1422. if length := len(toAccumulate.SummaryAllocationSets); length != 1 {
  1423. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  1424. }
  1425. result.Append(toAccumulate.SummaryAllocationSets[0])
  1426. toAccumulate = nil
  1427. }
  1428. }
  1429. return result, nil
  1430. }
  1431. func (sasr *SummaryAllocationSetRange) accumulateByMonth() (*SummaryAllocationSetRange, error) {
  1432. var toAccumulate *SummaryAllocationSetRange
  1433. result := NewSummaryAllocationSetRange()
  1434. for i, as := range sasr.SummaryAllocationSets {
  1435. if as.Window.Duration() != time.Hour*24 {
  1436. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  1437. }
  1438. _, month, _ := as.Window.Start().Date()
  1439. _, nextDayMonth, _ := as.Window.Start().Add(time.Hour * 24).Date()
  1440. if toAccumulate == nil {
  1441. toAccumulate = NewSummaryAllocationSetRange()
  1442. as = as.Clone()
  1443. }
  1444. toAccumulate.Append(as)
  1445. sas, err := toAccumulate.accumulate()
  1446. if err != nil {
  1447. return nil, fmt.Errorf("error building monthly accumulation: %s", err)
  1448. }
  1449. toAccumulate = NewSummaryAllocationSetRange(sas)
  1450. // either the month has ended, or there are no more summary allocation sets
  1451. if month != nextDayMonth || i == len(sasr.SummaryAllocationSets)-1 {
  1452. if length := len(toAccumulate.SummaryAllocationSets); length != 1 {
  1453. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  1454. }
  1455. result.Append(toAccumulate.SummaryAllocationSets[0])
  1456. toAccumulate = nil
  1457. }
  1458. }
  1459. return result, nil
  1460. }
  1461. func (sasr *SummaryAllocationSetRange) accumulateByWeek() (*SummaryAllocationSetRange, error) {
  1462. if len(sasr.SummaryAllocationSets) > 0 && sasr.SummaryAllocationSets[0].Window.Duration() == timeutil.Week {
  1463. return sasr, nil
  1464. }
  1465. var toAccumulate *SummaryAllocationSetRange
  1466. result := NewSummaryAllocationSetRange()
  1467. for i, as := range sasr.SummaryAllocationSets {
  1468. if as.Window.Duration() != time.Hour*24 {
  1469. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  1470. }
  1471. dayOfWeek := as.Window.Start().Weekday()
  1472. if toAccumulate == nil {
  1473. toAccumulate = NewSummaryAllocationSetRange()
  1474. as = as.Clone()
  1475. }
  1476. toAccumulate.Append(as)
  1477. sas, err := toAccumulate.accumulate()
  1478. if err != nil {
  1479. return nil, fmt.Errorf("error accumulating result: %s", err)
  1480. }
  1481. toAccumulate = NewSummaryAllocationSetRange(sas)
  1482. // current assumption is the week always ends on Saturday, or when there are no more summary allocation sets
  1483. if dayOfWeek == time.Saturday || i == len(sasr.SummaryAllocationSets)-1 {
  1484. if length := len(toAccumulate.SummaryAllocationSets); length != 1 {
  1485. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  1486. }
  1487. result.Append(toAccumulate.SummaryAllocationSets[0])
  1488. toAccumulate = nil
  1489. }
  1490. }
  1491. return result, nil
  1492. }
  1493. func (sasr *SummaryAllocationSetRange) Clone() *SummaryAllocationSetRange {
  1494. return sasr.clone()
  1495. }
  1496. // clone returns a new SummaryAllocationSetRange cloned from the existing SASR
  1497. func (sasr *SummaryAllocationSetRange) clone() *SummaryAllocationSetRange {
  1498. sasrSource := NewSummaryAllocationSetRange()
  1499. sasrSource.Window = sasr.Window.Clone()
  1500. sasrSource.Step = sasr.Step
  1501. sasrSource.Message = sasr.Message
  1502. for _, sas := range sasr.SummaryAllocationSets {
  1503. var sasClone *SummaryAllocationSet = nil
  1504. if sas != nil {
  1505. sasClone = sas.Clone()
  1506. }
  1507. sasrSource.Append(sasClone)
  1508. }
  1509. return sasrSource
  1510. }