summaryallocation.go 57 KB

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