summaryallocation.go 55 KB

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