summaryallocation.go 55 KB

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