summaryallocation.go 56 KB

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