summaryallocation.go 54 KB

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