summaryallocation.go 43 KB

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