summaryallocation.go 56 KB

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