summaryallocation.go 53 KB

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