summaryallocation.go 55 KB

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