summaryallocation.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  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) error {
  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. return nil
  1187. }
  1188. // Each invokes the given function for each AllocationSet in the range
  1189. func (sasr *SummaryAllocationSetRange) Each(f func(int, *SummaryAllocationSet)) {
  1190. if sasr == nil {
  1191. return
  1192. }
  1193. for i, as := range sasr.SummaryAllocationSets {
  1194. f(i, as)
  1195. }
  1196. }
  1197. // InsertExternalAllocations takes all allocations in the given
  1198. // AllocationSetRange (they should all be considered "external") and inserts
  1199. // them into the receiving SummaryAllocationSetRange.
  1200. // TODO:CLEANUP replace this with a better idea (or get rid of external
  1201. // allocations, as such, altogether)
  1202. func (sasr *SummaryAllocationSetRange) InsertExternalAllocations(that *AllocationSetRange) error {
  1203. if sasr == nil {
  1204. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  1205. }
  1206. // keys maps window to index in range
  1207. keys := map[string]int{}
  1208. for i, as := range sasr.SummaryAllocationSets {
  1209. if as == nil {
  1210. continue
  1211. }
  1212. keys[as.Window.String()] = i
  1213. }
  1214. // Nothing to merge, so simply return
  1215. if len(keys) == 0 {
  1216. return nil
  1217. }
  1218. var err error
  1219. for _, thatAS := range that.Allocations {
  1220. if thatAS == nil || err != nil {
  1221. continue
  1222. }
  1223. // Find matching AllocationSet in asr
  1224. i, ok := keys[thatAS.Window.String()]
  1225. if !ok {
  1226. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  1227. continue
  1228. }
  1229. sas := sasr.SummaryAllocationSets[i]
  1230. // Insert each Allocation from the given set
  1231. for _, alloc := range thatAS.Allocations {
  1232. externalSA := NewSummaryAllocation(alloc, true, true)
  1233. // This error will be returned below
  1234. // TODO:CLEANUP should Each have early-error-return functionality?
  1235. err = sas.Insert(externalSA)
  1236. }
  1237. }
  1238. // err might be nil
  1239. return err
  1240. }
  1241. func (sasr *SummaryAllocationSetRange) TotalCost() float64 {
  1242. if sasr == nil {
  1243. return 0.0
  1244. }
  1245. sasr.RLock()
  1246. defer sasr.RUnlock()
  1247. tc := 0.0
  1248. for _, sas := range sasr.SummaryAllocationSets {
  1249. tc += sas.TotalCost()
  1250. }
  1251. return tc
  1252. }
  1253. // TODO remove after testing
  1254. func (sasr *SummaryAllocationSetRange) Print(verbose bool) {
  1255. fmt.Printf("%s (dur=%s, len=%d, cost=%.5f)\n", sasr.Window, sasr.Window.Duration(), len(sasr.SummaryAllocationSets), sasr.TotalCost())
  1256. for _, sas := range sasr.SummaryAllocationSets {
  1257. fmt.Printf(" > %s (dur=%s, len=%d, cost=%.5f) \n", sas.Window, sas.Window.Duration(), len(sas.SummaryAllocations), sas.TotalCost())
  1258. for key, sa := range sas.SummaryAllocations {
  1259. if verbose {
  1260. fmt.Printf(" {\"%s\", cpu: %.5f, gpu: %.5f, lb: %.5f, net: %.5f, pv: %.5f, ram: %.5f, shared: %.5f, external: %.5f}\n",
  1261. key, sa.CPUCost, sa.GPUCost, sa.LoadBalancerCost, sa.NetworkCost, sa.PVCost, sa.RAMCost, sa.SharedCost, sa.ExternalCost)
  1262. } else {
  1263. fmt.Printf(" - \"%s\": %.5f\n", key, sa.TotalCost())
  1264. }
  1265. }
  1266. }
  1267. }
  1268. func (sasr *SummaryAllocationSetRange) Accumulate(accumulateBy AccumulateOption) (*SummaryAllocationSetRange, error) {
  1269. switch accumulateBy {
  1270. case AccumulateOptionNone:
  1271. return sasr.accumulateByNone()
  1272. case AccumulateOptionAll:
  1273. return sasr.accumulateByAll()
  1274. case AccumulateOptionHour:
  1275. return sasr.accumulateByHour()
  1276. case AccumulateOptionDay:
  1277. return sasr.accumulateByDay()
  1278. case AccumulateOptionWeek:
  1279. return sasr.accumulateByWeek()
  1280. case AccumulateOptionMonth:
  1281. return sasr.accumulateByMonth()
  1282. default:
  1283. // this should never happen
  1284. return nil, fmt.Errorf("unexpected error, invalid accumulateByType: %s", accumulateBy)
  1285. }
  1286. }
  1287. func (sasr *SummaryAllocationSetRange) accumulateByNone() (*SummaryAllocationSetRange, error) {
  1288. result, err := sasr.clone()
  1289. return result, err
  1290. }
  1291. func (sasr *SummaryAllocationSetRange) accumulateByAll() (*SummaryAllocationSetRange, error) {
  1292. var err error
  1293. var result *SummaryAllocationSet
  1294. result, err = sasr.newAccumulation()
  1295. if err != nil {
  1296. return nil, fmt.Errorf("error running accumulate: %s", err)
  1297. }
  1298. accumulated := NewSummaryAllocationSetRange(result)
  1299. return accumulated, nil
  1300. }
  1301. func (sasr *SummaryAllocationSetRange) accumulateByHour() (*SummaryAllocationSetRange, error) {
  1302. // ensure that the summary allocation sets have a 1-hour window, if a set exists
  1303. if len(sasr.SummaryAllocationSets) > 0 && sasr.SummaryAllocationSets[0].Window.Duration() != time.Hour {
  1304. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", sasr.SummaryAllocationSets[0].Window.Duration())
  1305. }
  1306. result, err := sasr.clone()
  1307. return result, err
  1308. }
  1309. func (sasr *SummaryAllocationSetRange) accumulateByDay() (*SummaryAllocationSetRange, error) {
  1310. // if the summary allocation set window is 1-day, just return the existing summary allocation set range
  1311. if len(sasr.SummaryAllocationSets) > 0 && sasr.SummaryAllocationSets[0].Window.Duration() == time.Hour*24 {
  1312. return sasr, nil
  1313. }
  1314. var toAccumulate *SummaryAllocationSetRange
  1315. result := NewSummaryAllocationSetRange()
  1316. for i, as := range sasr.SummaryAllocationSets {
  1317. if as.Window.Duration() != time.Hour {
  1318. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", as.Window.Duration())
  1319. }
  1320. hour := as.Window.Start().Hour()
  1321. if toAccumulate == nil {
  1322. toAccumulate = NewSummaryAllocationSetRange()
  1323. as = as.Clone()
  1324. }
  1325. err := toAccumulate.Append(as)
  1326. if err != nil {
  1327. return nil, fmt.Errorf("error building accumulation: %s", err)
  1328. }
  1329. sas, err := toAccumulate.accumulate()
  1330. if err != nil {
  1331. return nil, fmt.Errorf("error accumulating result: %s", err)
  1332. }
  1333. toAccumulate = NewSummaryAllocationSetRange(sas)
  1334. if hour == 23 || i == len(sasr.SummaryAllocationSets)-1 {
  1335. if length := len(toAccumulate.SummaryAllocationSets); length != 1 {
  1336. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  1337. }
  1338. err = result.Append(toAccumulate.SummaryAllocationSets[0])
  1339. if err != nil {
  1340. return nil, fmt.Errorf("error building result accumulation: %s", err)
  1341. }
  1342. toAccumulate = nil
  1343. }
  1344. }
  1345. return result, nil
  1346. }
  1347. func (sasr *SummaryAllocationSetRange) accumulateByMonth() (*SummaryAllocationSetRange, error) {
  1348. var toAccumulate *SummaryAllocationSetRange
  1349. result := NewSummaryAllocationSetRange()
  1350. for i, as := range sasr.SummaryAllocationSets {
  1351. if as.Window.Duration() != time.Hour*24 {
  1352. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  1353. }
  1354. _, month, _ := as.Window.Start().Date()
  1355. _, nextDayMonth, _ := as.Window.Start().Add(time.Hour * 24).Date()
  1356. if toAccumulate == nil {
  1357. toAccumulate = NewSummaryAllocationSetRange()
  1358. as = as.Clone()
  1359. }
  1360. err := toAccumulate.Append(as)
  1361. if err != nil {
  1362. return nil, fmt.Errorf("error building monthly accumulation: %s", err)
  1363. }
  1364. sas, err := toAccumulate.accumulate()
  1365. if err != nil {
  1366. return nil, fmt.Errorf("error building monthly accumulation: %s", err)
  1367. }
  1368. toAccumulate = NewSummaryAllocationSetRange(sas)
  1369. // either the month has ended, or there are no more summary allocation sets
  1370. if month != nextDayMonth || i == len(sasr.SummaryAllocationSets)-1 {
  1371. if length := len(toAccumulate.SummaryAllocationSets); length != 1 {
  1372. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  1373. }
  1374. err = result.Append(toAccumulate.SummaryAllocationSets[0])
  1375. if err != nil {
  1376. return nil, fmt.Errorf("error building result accumulation: %s", err)
  1377. }
  1378. toAccumulate = nil
  1379. }
  1380. }
  1381. return result, nil
  1382. }
  1383. func (sasr *SummaryAllocationSetRange) accumulateByWeek() (*SummaryAllocationSetRange, error) {
  1384. if len(sasr.SummaryAllocationSets) > 0 && sasr.SummaryAllocationSets[0].Window.Duration() == timeutil.Week {
  1385. return sasr, nil
  1386. }
  1387. var toAccumulate *SummaryAllocationSetRange
  1388. result := NewSummaryAllocationSetRange()
  1389. for i, as := range sasr.SummaryAllocationSets {
  1390. if as.Window.Duration() != time.Hour*24 {
  1391. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  1392. }
  1393. dayOfWeek := as.Window.Start().Weekday()
  1394. if toAccumulate == nil {
  1395. toAccumulate = NewSummaryAllocationSetRange()
  1396. as = as.Clone()
  1397. }
  1398. err := toAccumulate.Append(as)
  1399. if err != nil {
  1400. return nil, fmt.Errorf("error building accumulation: %s", err)
  1401. }
  1402. sas, err := toAccumulate.accumulate()
  1403. if err != nil {
  1404. return nil, fmt.Errorf("error accumulating result: %s", err)
  1405. }
  1406. toAccumulate = NewSummaryAllocationSetRange(sas)
  1407. // current assumption is the week always ends on Saturday, or when there are no more summary allocation sets
  1408. if dayOfWeek == time.Saturday || i == len(sasr.SummaryAllocationSets)-1 {
  1409. if length := len(toAccumulate.SummaryAllocationSets); length != 1 {
  1410. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  1411. }
  1412. err = result.Append(toAccumulate.SummaryAllocationSets[0])
  1413. if err != nil {
  1414. return nil, fmt.Errorf("error building result accumulation: %s", err)
  1415. }
  1416. toAccumulate = nil
  1417. }
  1418. }
  1419. return result, nil
  1420. }
  1421. // clone returns a new SummaryAllocationSetRange cloned from the existing SASR
  1422. func (sasr *SummaryAllocationSetRange) clone() (*SummaryAllocationSetRange, error) {
  1423. sasrSource := NewSummaryAllocationSetRange()
  1424. sasrSource.Window = sasr.Window.Clone()
  1425. sasrSource.Step = sasr.Step
  1426. sasrSource.Message = sasr.Message
  1427. for _, sas := range sasr.SummaryAllocationSets {
  1428. var sasClone *SummaryAllocationSet = nil
  1429. if sas != nil {
  1430. sasClone = sas.Clone()
  1431. }
  1432. err := sasrSource.Append(sasClone)
  1433. if err != nil {
  1434. return nil, err
  1435. }
  1436. }
  1437. return sasrSource, nil
  1438. }