summaryallocation.go 56 KB

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