summaryallocation.go 55 KB

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