allocation.go 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  1. package kubecost
  2. import (
  3. "bytes"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/kubecost/cost-model/pkg/log"
  10. "github.com/kubecost/cost-model/pkg/util"
  11. "github.com/kubecost/cost-model/pkg/util/json"
  12. )
  13. // TODO Clean-up use of IsEmpty; nil checks should be separated for safety.
  14. // TODO Consider making Allocation an interface, which is fulfilled by structs
  15. // like KubernetesAllocation, IdleAllocation, and ExternalAllocation.
  16. // ExternalSuffix indicates an external allocation
  17. const ExternalSuffix = "__external__"
  18. // IdleSuffix indicates an idle allocation property
  19. const IdleSuffix = "__idle__"
  20. // SharedSuffix indicates an shared allocation property
  21. const SharedSuffix = "__shared__"
  22. // UnallocatedSuffix indicates an unallocated allocation property
  23. const UnallocatedSuffix = "__unallocated__"
  24. // UnmountedSuffix indicated allocation to an unmounted PV
  25. const UnmountedSuffix = "__unmounted__"
  26. // ShareWeighted indicates that a shared resource should be shared as a
  27. // proportion of the cost of the remaining allocations.
  28. const ShareWeighted = "__weighted__"
  29. // ShareEven indicates that a shared resource should be shared evenly across
  30. // all remaining allocations.
  31. const ShareEven = "__even__"
  32. // ShareNone indicates that a shareable resource should not be shared
  33. const ShareNone = "__none__"
  34. // Allocation is a unit of resource allocation and cost for a given window
  35. // of time and for a given kubernetes construct with its associated set of
  36. // properties.
  37. // TODO:CLEANUP consider dropping name in favor of just AllocationProperties and an
  38. // Assets-style key() function for AllocationSet.
  39. type Allocation struct {
  40. Name string `json:"name"`
  41. Properties *AllocationProperties `json:"properties,omitempty"`
  42. Window Window `json:"window"`
  43. Start time.Time `json:"start"`
  44. End time.Time `json:"end"`
  45. CPUCoreHours float64 `json:"cpuCoreHours"`
  46. CPUCoreRequestAverage float64 `json:"cpuCoreRequestAverage"`
  47. CPUCoreUsageAverage float64 `json:"cpuCoreUsageAverage"`
  48. CPUCost float64 `json:"cpuCost"`
  49. GPUHours float64 `json:"gpuHours"`
  50. GPUCost float64 `json:"gpuCost"`
  51. NetworkCost float64 `json:"networkCost"`
  52. LoadBalancerCost float64 `json:"loadBalancerCost"`
  53. PVByteHours float64 `json:"pvByteHours"`
  54. PVCost float64 `json:"pvCost"`
  55. RAMByteHours float64 `json:"ramByteHours"`
  56. RAMBytesRequestAverage float64 `json:"ramByteRequestAverage"`
  57. RAMBytesUsageAverage float64 `json:"ramByteUsageAverage"`
  58. RAMCost float64 `json:"ramCost"`
  59. SharedCost float64 `json:"sharedCost"`
  60. ExternalCost float64 `json:"externalCost"`
  61. }
  62. // AllocationMatchFunc is a function that can be used to match Allocations by
  63. // returning true for any given Allocation if a condition is met.
  64. type AllocationMatchFunc func(*Allocation) bool
  65. // Add returns the result of summing the two given Allocations, which sums the
  66. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  67. // the two original Allocations are mutated in the process.
  68. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  69. if a == nil {
  70. return that.Clone(), nil
  71. }
  72. if that == nil {
  73. return a.Clone(), nil
  74. }
  75. // Note: no need to clone "that", as add only mutates the receiver
  76. agg := a.Clone()
  77. agg.add(that)
  78. return agg, nil
  79. }
  80. // Clone returns a deep copy of the given Allocation
  81. func (a *Allocation) Clone() *Allocation {
  82. if a == nil {
  83. return nil
  84. }
  85. return &Allocation{
  86. Name: a.Name,
  87. Properties: a.Properties.Clone(),
  88. Window: a.Window.Clone(),
  89. Start: a.Start,
  90. End: a.End,
  91. CPUCoreHours: a.CPUCoreHours,
  92. CPUCoreRequestAverage: a.CPUCoreRequestAverage,
  93. CPUCoreUsageAverage: a.CPUCoreUsageAverage,
  94. CPUCost: a.CPUCost,
  95. GPUHours: a.GPUHours,
  96. GPUCost: a.GPUCost,
  97. NetworkCost: a.NetworkCost,
  98. LoadBalancerCost: a.LoadBalancerCost,
  99. PVByteHours: a.PVByteHours,
  100. PVCost: a.PVCost,
  101. RAMByteHours: a.RAMByteHours,
  102. RAMBytesRequestAverage: a.RAMBytesRequestAverage,
  103. RAMBytesUsageAverage: a.RAMBytesUsageAverage,
  104. RAMCost: a.RAMCost,
  105. SharedCost: a.SharedCost,
  106. ExternalCost: a.ExternalCost,
  107. }
  108. }
  109. // Equal returns true if the values held in the given Allocation precisely
  110. // match those of the receiving Allocation. nil does not match nil. Floating
  111. // point values need to match according to util.IsApproximately, which accounts
  112. // for small, reasonable floating point error margins.
  113. func (a *Allocation) Equal(that *Allocation) bool {
  114. if a == nil || that == nil {
  115. return false
  116. }
  117. if a.Name != that.Name {
  118. return false
  119. }
  120. if !a.Properties.Equal(that.Properties) {
  121. return false
  122. }
  123. if !a.Window.Equal(that.Window) {
  124. return false
  125. }
  126. if !a.Start.Equal(that.Start) {
  127. return false
  128. }
  129. if !a.End.Equal(that.End) {
  130. return false
  131. }
  132. if !util.IsApproximately(a.CPUCoreHours, that.CPUCoreHours) {
  133. return false
  134. }
  135. if !util.IsApproximately(a.CPUCost, that.CPUCost) {
  136. return false
  137. }
  138. if !util.IsApproximately(a.GPUHours, that.GPUHours) {
  139. return false
  140. }
  141. if !util.IsApproximately(a.GPUCost, that.GPUCost) {
  142. return false
  143. }
  144. if !util.IsApproximately(a.NetworkCost, that.NetworkCost) {
  145. return false
  146. }
  147. if !util.IsApproximately(a.LoadBalancerCost, that.LoadBalancerCost) {
  148. return false
  149. }
  150. if !util.IsApproximately(a.PVByteHours, that.PVByteHours) {
  151. return false
  152. }
  153. if !util.IsApproximately(a.PVCost, that.PVCost) {
  154. return false
  155. }
  156. if !util.IsApproximately(a.RAMByteHours, that.RAMByteHours) {
  157. return false
  158. }
  159. if !util.IsApproximately(a.RAMCost, that.RAMCost) {
  160. return false
  161. }
  162. if !util.IsApproximately(a.SharedCost, that.SharedCost) {
  163. return false
  164. }
  165. if !util.IsApproximately(a.ExternalCost, that.ExternalCost) {
  166. return false
  167. }
  168. return true
  169. }
  170. // TotalCost is the total cost of the Allocation
  171. func (a *Allocation) TotalCost() float64 {
  172. return a.CPUCost + a.GPUCost + a.RAMCost + a.PVCost + a.NetworkCost + a.SharedCost + a.ExternalCost + a.LoadBalancerCost
  173. }
  174. // CPUEfficiency is the ratio of usage to request. If there is no request and
  175. // no usage or cost, then efficiency is zero. If there is no request, but there
  176. // is usage or cost, then efficiency is 100%.
  177. func (a *Allocation) CPUEfficiency() float64 {
  178. if a.CPUCoreRequestAverage > 0 {
  179. return a.CPUCoreUsageAverage / a.CPUCoreRequestAverage
  180. }
  181. if a.CPUCoreUsageAverage == 0.0 || a.CPUCost == 0.0 {
  182. return 0.0
  183. }
  184. return 1.0
  185. }
  186. // RAMEfficiency is the ratio of usage to request. If there is no request and
  187. // no usage or cost, then efficiency is zero. If there is no request, but there
  188. // is usage or cost, then efficiency is 100%.
  189. func (a *Allocation) RAMEfficiency() float64 {
  190. if a.RAMBytesRequestAverage > 0 {
  191. return a.RAMBytesUsageAverage / a.RAMBytesRequestAverage
  192. }
  193. if a.RAMBytesUsageAverage == 0.0 || a.RAMCost == 0.0 {
  194. return 0.0
  195. }
  196. return 1.0
  197. }
  198. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  199. // there is no cost at all, then efficiency is zero.
  200. func (a *Allocation) TotalEfficiency() float64 {
  201. if a.CPUCost+a.RAMCost > 0 {
  202. ramCostEff := a.RAMEfficiency() * a.RAMCost
  203. cpuCostEff := a.CPUEfficiency() * a.CPUCost
  204. return (ramCostEff + cpuCostEff) / (a.CPUCost + a.RAMCost)
  205. }
  206. return 0.0
  207. }
  208. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  209. func (a *Allocation) CPUCores() float64 {
  210. if a.Minutes() <= 0.0 {
  211. return 0.0
  212. }
  213. return a.CPUCoreHours / (a.Minutes() / 60.0)
  214. }
  215. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  216. func (a *Allocation) RAMBytes() float64 {
  217. if a.Minutes() <= 0.0 {
  218. return 0.0
  219. }
  220. return a.RAMByteHours / (a.Minutes() / 60.0)
  221. }
  222. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  223. func (a *Allocation) PVBytes() float64 {
  224. if a.Minutes() <= 0.0 {
  225. return 0.0
  226. }
  227. return a.PVByteHours / (a.Minutes() / 60.0)
  228. }
  229. // MarshalJSON implements json.Marshaler interface
  230. func (a *Allocation) MarshalJSON() ([]byte, error) {
  231. buffer := bytes.NewBufferString("{")
  232. jsonEncodeString(buffer, "name", a.Name, ",")
  233. jsonEncode(buffer, "properties", a.Properties, ",")
  234. jsonEncode(buffer, "window", a.Window, ",")
  235. jsonEncodeString(buffer, "start", a.Start.Format(time.RFC3339), ",")
  236. jsonEncodeString(buffer, "end", a.End.Format(time.RFC3339), ",")
  237. jsonEncodeFloat64(buffer, "minutes", a.Minutes(), ",")
  238. jsonEncodeFloat64(buffer, "cpuCores", a.CPUCores(), ",")
  239. jsonEncodeFloat64(buffer, "cpuCoreRequestAverage", a.CPUCoreRequestAverage, ",")
  240. jsonEncodeFloat64(buffer, "cpuCoreUsageAverage", a.CPUCoreUsageAverage, ",")
  241. jsonEncodeFloat64(buffer, "cpuCoreHours", a.CPUCoreHours, ",")
  242. jsonEncodeFloat64(buffer, "cpuCost", a.CPUCost, ",")
  243. jsonEncodeFloat64(buffer, "cpuEfficiency", a.CPUEfficiency(), ",")
  244. jsonEncodeFloat64(buffer, "gpuHours", a.GPUHours, ",")
  245. jsonEncodeFloat64(buffer, "gpuCost", a.GPUCost, ",")
  246. jsonEncodeFloat64(buffer, "networkCost", a.NetworkCost, ",")
  247. jsonEncodeFloat64(buffer, "loadBalancerCost", a.LoadBalancerCost, ",")
  248. jsonEncodeFloat64(buffer, "pvBytes", a.PVBytes(), ",")
  249. jsonEncodeFloat64(buffer, "pvByteHours", a.PVByteHours, ",")
  250. jsonEncodeFloat64(buffer, "pvCost", a.PVCost, ",")
  251. jsonEncodeFloat64(buffer, "ramBytes", a.RAMBytes(), ",")
  252. jsonEncodeFloat64(buffer, "ramByteRequestAverage", a.RAMBytesRequestAverage, ",")
  253. jsonEncodeFloat64(buffer, "ramByteUsageAverage", a.RAMBytesUsageAverage, ",")
  254. jsonEncodeFloat64(buffer, "ramByteHours", a.RAMByteHours, ",")
  255. jsonEncodeFloat64(buffer, "ramCost", a.RAMCost, ",")
  256. jsonEncodeFloat64(buffer, "ramEfficiency", a.RAMEfficiency(), ",")
  257. jsonEncodeFloat64(buffer, "sharedCost", a.SharedCost, ",")
  258. jsonEncodeFloat64(buffer, "externalCost", a.ExternalCost, ",")
  259. jsonEncodeFloat64(buffer, "totalCost", a.TotalCost(), ",")
  260. jsonEncodeFloat64(buffer, "totalEfficiency", a.TotalEfficiency(), "")
  261. buffer.WriteString("}")
  262. return buffer.Bytes(), nil
  263. }
  264. // Resolution returns the duration of time covered by the Allocation
  265. func (a *Allocation) Resolution() time.Duration {
  266. return a.End.Sub(a.Start)
  267. }
  268. // IsAggregated is true if the given Allocation has been aggregated, which we
  269. // define by a lack of AllocationProperties.
  270. func (a *Allocation) IsAggregated() bool {
  271. return a == nil || a.Properties == nil
  272. }
  273. // IsExternal is true if the given Allocation represents external costs.
  274. func (a *Allocation) IsExternal() bool {
  275. return strings.Contains(a.Name, ExternalSuffix)
  276. }
  277. // IsIdle is true if the given Allocation represents idle costs.
  278. func (a *Allocation) IsIdle() bool {
  279. return strings.Contains(a.Name, IdleSuffix)
  280. }
  281. // IsUnallocated is true if the given Allocation represents unallocated costs.
  282. func (a *Allocation) IsUnallocated() bool {
  283. return strings.Contains(a.Name, UnallocatedSuffix)
  284. }
  285. // Minutes returns the number of minutes the Allocation represents, as defined
  286. // by the difference between the end and start times.
  287. func (a *Allocation) Minutes() float64 {
  288. return a.End.Sub(a.Start).Minutes()
  289. }
  290. // Share adds the TotalCost of the given Allocation to the SharedCost of the
  291. // receiving Allocation. No Start, End, Window, or AllocationProperties are considered.
  292. // Neither Allocation is mutated; a new Allocation is always returned.
  293. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  294. if that == nil {
  295. return a.Clone(), nil
  296. }
  297. if a == nil {
  298. return nil, fmt.Errorf("cannot share with nil Allocation")
  299. }
  300. agg := a.Clone()
  301. agg.SharedCost += that.TotalCost()
  302. return agg, nil
  303. }
  304. // String represents the given Allocation as a string
  305. func (a *Allocation) String() string {
  306. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost())
  307. }
  308. func (a *Allocation) add(that *Allocation) {
  309. if a == nil {
  310. log.Warningf("Allocation.AggregateBy: trying to add a nil receiver")
  311. return
  312. }
  313. if a.Properties != nil && that.Properties != nil {
  314. aCluster := a.Properties.Cluster
  315. thatCluster := that.Properties.Cluster
  316. aNode := a.Properties.Node
  317. thatNode := that.Properties.Node
  318. // reset properties
  319. a.Properties = nil
  320. // ensure that we carry cluster ID and/or node over if they're the same
  321. // required for idle/shared cost allocation
  322. if aCluster == thatCluster {
  323. a.Properties = &AllocationProperties{Cluster: aCluster}
  324. }
  325. if aNode == thatNode {
  326. if a.Properties == nil {
  327. a.Properties = &AllocationProperties{Node: aNode}
  328. } else {
  329. a.Properties.Node = aNode
  330. }
  331. }
  332. } else {
  333. a.Properties = nil
  334. }
  335. // Expand the window to encompass both Allocations
  336. a.Window = a.Window.Expand(that.Window)
  337. // Sum non-cumulative fields by turning them into cumulative, adding them,
  338. // and then converting them back into averages after minutes have been
  339. // combined (just below).
  340. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  341. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  342. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  343. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  344. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  345. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  346. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  347. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  348. // Expand Start and End to be the "max" of among the given Allocations
  349. if that.Start.Before(a.Start) {
  350. a.Start = that.Start
  351. }
  352. if that.End.After(a.End) {
  353. a.End = that.End
  354. }
  355. // Convert cumulative request and usage back into rates
  356. // TODO:TEST write a unit test that fails if this is done incorrectly
  357. if a.Minutes() > 0 {
  358. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  359. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  360. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  361. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  362. } else {
  363. a.CPUCoreRequestAverage = 0.0
  364. a.CPUCoreUsageAverage = 0.0
  365. a.RAMBytesRequestAverage = 0.0
  366. a.RAMBytesUsageAverage = 0.0
  367. }
  368. // Sum all cumulative resource fields
  369. a.CPUCoreHours += that.CPUCoreHours
  370. a.GPUHours += that.GPUHours
  371. a.RAMByteHours += that.RAMByteHours
  372. a.PVByteHours += that.PVByteHours
  373. // Sum all cumulative cost fields
  374. a.CPUCost += that.CPUCost
  375. a.GPUCost += that.GPUCost
  376. a.RAMCost += that.RAMCost
  377. a.PVCost += that.PVCost
  378. a.NetworkCost += that.NetworkCost
  379. a.LoadBalancerCost += that.LoadBalancerCost
  380. a.SharedCost += that.SharedCost
  381. a.ExternalCost += that.ExternalCost
  382. }
  383. // AllocationSet stores a set of Allocations, each with a unique name, that share
  384. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  385. type AllocationSet struct {
  386. sync.RWMutex
  387. allocations map[string]*Allocation
  388. externalKeys map[string]bool
  389. idleKeys map[string]bool
  390. Window Window
  391. Warnings []string
  392. Errors []string
  393. }
  394. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  395. // the given list of Allocations
  396. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  397. as := &AllocationSet{
  398. allocations: map[string]*Allocation{},
  399. externalKeys: map[string]bool{},
  400. idleKeys: map[string]bool{},
  401. Window: NewWindow(&start, &end),
  402. }
  403. for _, a := range allocs {
  404. as.Insert(a)
  405. }
  406. return as
  407. }
  408. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  409. // filtering results and sharing allocations. FilterFuncs are a list of match
  410. // functions such that, if any function fails, the allocation is ignored.
  411. // ShareFuncs are a list of match functions such that, if any function
  412. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  413. // simple flag for sharing idle resources.
  414. type AllocationAggregationOptions struct {
  415. FilterFuncs []AllocationMatchFunc
  416. SplitIdle bool
  417. MergeUnallocated bool
  418. ShareFuncs []AllocationMatchFunc
  419. ShareIdle string
  420. ShareSplit string
  421. SharedHourlyCosts map[string]float64
  422. }
  423. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  424. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  425. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  426. func (as *AllocationSet) AggregateBy(properties AllocationProperties, options *AllocationAggregationOptions) error {
  427. // The order of operations for aggregating allocations is as follows:
  428. // 1. Partition external, idle, and shared allocations into separate sets.
  429. // Also, create the aggSet into which the results will be aggregated.
  430. // 2. Compute sharing coefficients for idle and shared resources
  431. // a) if idle allocation is to be shared, compute idle coefficients
  432. // b) if idle allocation is NOT shared, but filters are present, compute
  433. // idle filtration coefficients for the purpose of only returning the
  434. // portion of idle allocation that would have been shared with the
  435. // unfiltered results. (See unit tests 5.a,b,c)
  436. // c) generate shared allocation for then given shared overhead, which
  437. // must happen after (2a) and (2b)
  438. // d) if there are shared resources, compute share coefficients
  439. // 3. Drop any allocation that fails any of the filters
  440. // 4. Distribute idle allocations according to the idle coefficients
  441. // 5. Generate aggregation key and insert allocation into the output set
  442. // 6. If idle is shared and resources are shared, some idle might be shared
  443. // with a shared resource. Distribute that to the shared resources
  444. // prior to sharing them with the aggregated results.
  445. // 7. Apply idle filtration coefficients from step (2b)
  446. // 8. Distribute shared allocations according to the share coefficients.
  447. // 9. If there are external allocations that can be aggregated into
  448. // the output (i.e. they can be used to generate a valid key for
  449. // the given properties) then aggregate; otherwise... ignore them?
  450. // 10. If the merge idle option is enabled, merge any remaining idle
  451. // allocations into a single idle allocation
  452. if options == nil {
  453. options = &AllocationAggregationOptions{}
  454. }
  455. if as.IsEmpty() {
  456. return nil
  457. }
  458. // aggSet will collect the aggregated allocations
  459. aggSet := &AllocationSet{
  460. Window: as.Window.Clone(),
  461. }
  462. // externalSet will collect external allocations
  463. externalSet := &AllocationSet{
  464. Window: as.Window.Clone(),
  465. }
  466. // idleSet will be shared among aggSet after initial aggregation
  467. // is complete
  468. idleSet := &AllocationSet{
  469. Window: as.Window.Clone(),
  470. }
  471. // shareSet will be shared among aggSet after initial aggregation
  472. // is complete
  473. shareSet := &AllocationSet{
  474. Window: as.Window.Clone(),
  475. }
  476. as.Lock()
  477. defer as.Unlock()
  478. // (1) Loop and find all of the external, idle, and shared allocations. Add
  479. // them to their respective sets, removing them from the set of allocations
  480. // to aggregate.
  481. for _, alloc := range as.allocations {
  482. // External allocations get aggregated post-hoc (see step 6) and do
  483. // not necessarily contain complete sets of properties, so they are
  484. // moved to a separate AllocationSet.
  485. if alloc.IsExternal() {
  486. delete(as.externalKeys, alloc.Name)
  487. delete(as.allocations, alloc.Name)
  488. externalSet.Insert(alloc)
  489. continue
  490. }
  491. // Idle allocations should be separated into idleSet if they are to be
  492. // shared later on. If they are not to be shared, then add them to the
  493. // aggSet like any other allocation.
  494. if alloc.IsIdle() {
  495. delete(as.idleKeys, alloc.Name)
  496. delete(as.allocations, alloc.Name)
  497. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  498. idleSet.Insert(alloc)
  499. } else {
  500. aggSet.Insert(alloc)
  501. }
  502. continue
  503. }
  504. // Shared allocations must be identified and separated prior to
  505. // aggregation and filtering. That is, if any of the ShareFuncs return
  506. // true for the allocation, then move it to shareSet.
  507. for _, sf := range options.ShareFuncs {
  508. if sf(alloc) {
  509. delete(as.idleKeys, alloc.Name)
  510. delete(as.allocations, alloc.Name)
  511. shareSet.Insert(alloc)
  512. break
  513. }
  514. }
  515. }
  516. // It's possible that no more un-shared, non-idle, non-external allocations
  517. // remain at this point. This always results in an emptySet, so return early.
  518. if len(as.allocations) == 0 {
  519. emptySet := &AllocationSet{
  520. Window: as.Window.Clone(),
  521. }
  522. as.allocations = emptySet.allocations
  523. return nil
  524. }
  525. // (2) In order to correctly share idle and shared costs, we first compute
  526. // sharing coefficients, which represent the proportion of each cost to
  527. // share with each allocation. Idle allocations are shared per-cluster,
  528. // per-allocation, and per-resource, while shared resources are shared per-
  529. // allocation only.
  530. //
  531. // For an idleCoefficient example, the entries:
  532. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  533. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  534. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  535. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  536. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  537. // RAM costs.
  538. //
  539. // For a shareCoefficient example, the entries:
  540. // [namespace2] = 0.666667
  541. // [__filtered__] = 0.333333
  542. // mean that the post-aggregation allocation "namespace2" will receive
  543. // 66.67% of the shared resource costs, while the remaining 33.33% will
  544. // be filtered out, as they were shared with allocations that did not pass
  545. // one of the given filters.
  546. //
  547. // In order to maintain stable results when multiple operations are being
  548. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  549. // coefficients are computed for the full set of allocaitons prior to
  550. // adding shared overhead and prior to applying filters.
  551. var err error
  552. // (2a) If there are idle costs to be shared, compute the coefficients for
  553. // sharing them among the non-idle, non-aggregated allocations (including
  554. // the shared allocations).
  555. var idleCoefficients map[string]map[string]map[string]float64
  556. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  557. idleCoefficients, err = computeIdleCoeffs(properties, options, as, shareSet)
  558. if err != nil {
  559. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  560. return fmt.Errorf("error computing idle coefficients: %s", err)
  561. }
  562. }
  563. // (2b) If idle costs are not to be shared, but there are filters, then we
  564. // need to track the amount of each idle allocation to "filter" in order to
  565. // maintain parity with the results when idle is shared. That is, we want
  566. // to return only the idle costs that would have been shared with the given
  567. // results, even if the filter had not been applied.
  568. //
  569. // For example, consider these results from aggregating by namespace with
  570. // two clusters:
  571. //
  572. // namespace1: 25.00
  573. // namespace2: 30.00
  574. // namespace3: 15.00
  575. // idle: 30.00
  576. //
  577. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  578. // reduced by the amount that existed on cluster2. Then, idle must also be
  579. // reduced by the relevant amount:
  580. //
  581. // namespace1: 25.00
  582. // namespace2: 15.00
  583. // idle: 20.00
  584. //
  585. // Note that this can happen for any field, not just cluster, so we again
  586. // need to track this on a per-cluster, per-allocation, per-resource basis.
  587. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  588. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  589. idleFiltrationCoefficients, err = computeIdleCoeffs(properties, options, as, shareSet)
  590. if err != nil {
  591. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  592. }
  593. }
  594. // (2c) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  595. // come after idle coefficients are computes so that allocations generated
  596. // by shared overhead do not skew the idle coefficient computation.
  597. for name, cost := range options.SharedHourlyCosts {
  598. if cost > 0.0 {
  599. hours := as.Resolution().Hours()
  600. // If set ends in the future, adjust hours accordingly
  601. diff := time.Now().Sub(as.End())
  602. if diff < 0.0 {
  603. hours += diff.Hours()
  604. }
  605. totalSharedCost := cost * hours
  606. shareSet.Insert(&Allocation{
  607. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  608. Start: as.Start(),
  609. End: as.End(),
  610. SharedCost: totalSharedCost,
  611. Properties: &AllocationProperties{Cluster: SharedSuffix}, // The allocation needs to belong to a cluster,but it really doesn't matter which one, so just make it clear.
  612. })
  613. }
  614. }
  615. // (2d) Compute share coefficients for shared resources. These are computed
  616. // after idle coefficients, and are computed for the aggregated allocations
  617. // of the main allocation set. See above for details and an example.
  618. var shareCoefficients map[string]float64
  619. if shareSet.Length() > 0 {
  620. shareCoefficients, err = computeShareCoeffs(properties, options, as)
  621. if err != nil {
  622. return fmt.Errorf("error computing share coefficients: %s", err)
  623. }
  624. }
  625. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  626. for _, alloc := range as.allocations {
  627. cluster := alloc.Properties.Cluster
  628. if cluster == "" {
  629. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  630. return fmt.Errorf("ClusterProp is not set")
  631. }
  632. skip := false
  633. // (3) If any of the filter funcs fail, immediately skip the allocation.
  634. for _, ff := range options.FilterFuncs {
  635. if !ff(alloc) {
  636. skip = true
  637. break
  638. }
  639. }
  640. if skip {
  641. // If we are tracking idle filtration coefficients, delete the
  642. // entry corresponding to the filtered allocation. (Deleting the
  643. // entry will result in that proportional amount being removed
  644. // from the idle allocation at the end of the process.)
  645. if idleFiltrationCoefficients != nil {
  646. if ifcc, ok := idleFiltrationCoefficients[cluster]; ok {
  647. delete(ifcc, alloc.Name)
  648. }
  649. }
  650. continue
  651. }
  652. // (4) Distribute idle allocations according to the idle coefficients
  653. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  654. // all idle allocations will be in the aggSet at this point, so idleSet
  655. // will be empty and we won't enter this block.
  656. if idleSet.Length() > 0 {
  657. // Distribute idle allocations by coefficient per-cluster, per-allocation
  658. for _, idleAlloc := range idleSet.allocations {
  659. // Only share idle if the cluster matches; i.e. the allocation
  660. // is from the same cluster as the idle costs
  661. idleCluster := idleAlloc.Properties.Cluster
  662. if idleCluster == "" {
  663. return fmt.Errorf("ClusterProp is not set")
  664. }
  665. if idleCluster != cluster {
  666. continue
  667. }
  668. // Make sure idle coefficients exist
  669. if _, ok := idleCoefficients[cluster]; !ok {
  670. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no cluster '%s' for '%s'", cluster, alloc.Name)
  671. continue
  672. }
  673. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  674. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  675. continue
  676. }
  677. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  678. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  679. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  680. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  681. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  682. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  683. alloc.CPUCost += idleCPUCost
  684. alloc.GPUCost += idleGPUCost
  685. alloc.RAMCost += idleRAMCost
  686. }
  687. }
  688. // (5) generate key to use for aggregation-by-key and allocation name
  689. key := alloc.generateKey(properties)
  690. alloc.Name = key
  691. if options.MergeUnallocated && alloc.IsUnallocated() {
  692. alloc.Name = UnallocatedSuffix
  693. }
  694. // Inserting the allocation with the generated key for a name will
  695. // perform the actual basic aggregation step.
  696. aggSet.Insert(alloc)
  697. }
  698. // (6) If idle is shared and resources are shared, it's possible that some
  699. // amount of idle cost will be shared with a shared resource. Distribute
  700. // that idle allocation, if it exists, to the respective shared allocations
  701. // before sharing with the aggregated allocations.
  702. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  703. for _, alloc := range shareSet.allocations {
  704. cluster := alloc.Properties.Cluster
  705. if cluster == "" {
  706. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  707. return err
  708. }
  709. // Distribute idle allocations by coefficient per-cluster, per-allocation
  710. for _, idleAlloc := range idleSet.allocations {
  711. // Only share idle if the cluster matches; i.e. the allocation
  712. // is from the same cluster as the idle costs
  713. idleCluster := idleAlloc.Properties.Cluster
  714. if idleCluster == "" {
  715. return fmt.Errorf("ClusterProp is not set")
  716. }
  717. if idleCluster != cluster {
  718. continue
  719. }
  720. // Make sure idle coefficients exist
  721. if _, ok := idleCoefficients[cluster]; !ok {
  722. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no cluster '%s' for '%s'", cluster, alloc.Name)
  723. continue
  724. }
  725. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  726. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  727. continue
  728. }
  729. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  730. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  731. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  732. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  733. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  734. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  735. alloc.CPUCost += idleCPUCost
  736. alloc.GPUCost += idleGPUCost
  737. alloc.RAMCost += idleRAMCost
  738. }
  739. }
  740. }
  741. // clusterIdleFiltrationCoeffs is used to track per-resource idle
  742. // coefficients on a cluster-by-cluster basis. It is, essentailly, an
  743. // aggregation of idleFiltrationCoefficients after they have been
  744. // filtered above (in step 3)
  745. var clusterIdleFiltrationCoeffs map[string]map[string]float64
  746. if idleFiltrationCoefficients != nil {
  747. clusterIdleFiltrationCoeffs = map[string]map[string]float64{}
  748. for cluster, m := range idleFiltrationCoefficients {
  749. if _, ok := clusterIdleFiltrationCoeffs[cluster]; !ok {
  750. clusterIdleFiltrationCoeffs[cluster] = map[string]float64{
  751. "cpu": 0.0,
  752. "gpu": 0.0,
  753. "ram": 0.0,
  754. }
  755. }
  756. for _, n := range m {
  757. for resource, val := range n {
  758. clusterIdleFiltrationCoeffs[cluster][resource] += val
  759. }
  760. }
  761. }
  762. }
  763. // (7) If we have both un-shared idle allocations and idle filtration
  764. // coefficients then apply those. See step (2b) for an example.
  765. if len(aggSet.idleKeys) > 0 && clusterIdleFiltrationCoeffs != nil {
  766. for idleKey := range aggSet.idleKeys {
  767. idleAlloc := aggSet.Get(idleKey)
  768. cluster := idleAlloc.Properties.Cluster
  769. if cluster == "" {
  770. log.Warningf("AllocationSet.AggregateBy: idle allocation without cluster: %s", idleAlloc)
  771. continue
  772. }
  773. if resourceCoeffs, ok := clusterIdleFiltrationCoeffs[cluster]; ok {
  774. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  775. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  776. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  777. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  778. }
  779. }
  780. }
  781. // (8) Distribute shared allocations according to the share coefficients.
  782. if shareSet.Length() > 0 {
  783. for _, alloc := range aggSet.allocations {
  784. for _, sharedAlloc := range shareSet.allocations {
  785. if _, ok := shareCoefficients[alloc.Name]; !ok {
  786. log.Warningf("AllocationSet.AggregateBy: error getting share coefficienct for '%s'", alloc.Name)
  787. continue
  788. }
  789. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  790. }
  791. }
  792. }
  793. // (9) Aggregate external allocations into aggregated allocations. This may
  794. // not be possible for every external allocation, but attempt to find an
  795. // exact key match, given each external allocation's proerties, and
  796. // aggregate if an exact match is found.
  797. for _, alloc := range externalSet.allocations {
  798. skip := false
  799. for _, ff := range options.FilterFuncs {
  800. if !ff(alloc) {
  801. skip = true
  802. break
  803. }
  804. }
  805. if !skip {
  806. key := alloc.generateKey(properties)
  807. alloc.Name = key
  808. aggSet.Insert(alloc)
  809. }
  810. }
  811. // (10) Combine all idle allocations into a single "__idle__" allocation
  812. if !options.SplitIdle {
  813. for _, idleAlloc := range aggSet.IdleAllocations() {
  814. aggSet.Delete(idleAlloc.Name)
  815. idleAlloc.Name = IdleSuffix
  816. aggSet.Insert(idleAlloc)
  817. }
  818. }
  819. as.allocations = aggSet.allocations
  820. return nil
  821. }
  822. func computeShareCoeffs(properties AllocationProperties, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  823. // Compute coeffs by totalling per-allocation, then dividing by the total.
  824. coeffs := map[string]float64{}
  825. // Compute totals for all allocations
  826. total := 0.0
  827. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  828. // counts each aggregation proportionally to its respective costs
  829. shareType := options.ShareSplit
  830. // Record allocation values first, then normalize by totals to get percentages
  831. for _, alloc := range as.allocations {
  832. if alloc.IsIdle() {
  833. // Skip idle allocations in coefficient calculation
  834. continue
  835. }
  836. // Determine the post-aggregation key under which the allocation will
  837. // be shared.
  838. name := alloc.generateKey(properties)
  839. // If the current allocation will be filtered out in step 3, contribute
  840. // its share of the shared coefficient to a "__filtered__" bin, which
  841. // will ultimately be dropped. This step ensures that the shared cost
  842. // of a non-filtered allocation will be conserved even when the filter
  843. // is removed. (Otherwise, all the shared cost will get redistributed
  844. // over the unfiltered results, inflating their shared costs.)
  845. filtered := false
  846. for _, ff := range options.FilterFuncs {
  847. if !ff(alloc) {
  848. filtered = true
  849. break
  850. }
  851. }
  852. if filtered {
  853. name = "__filtered__"
  854. }
  855. if shareType == ShareEven {
  856. // Even distribution is not additive - set to 1.0 for everything
  857. coeffs[name] = 1.0
  858. // Total for even distribution is always the number of coefficients
  859. total = float64(len(coeffs))
  860. } else {
  861. // Both are additive for weighted distribution, where each
  862. // cumulative coefficient will be divided by the total.
  863. coeffs[name] += alloc.TotalCost()
  864. total += alloc.TotalCost()
  865. }
  866. }
  867. // Normalize coefficients by totals
  868. for a := range coeffs {
  869. if coeffs[a] > 0 && total > 0 {
  870. coeffs[a] /= total
  871. } else {
  872. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  873. coeffs[a] = 0.0
  874. }
  875. }
  876. return coeffs, nil
  877. }
  878. func computeIdleCoeffs(properties AllocationProperties, options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, error) {
  879. types := []string{"cpu", "gpu", "ram"}
  880. // Compute idle coefficients, then save them in AllocationAggregationOptions
  881. coeffs := map[string]map[string]map[string]float64{}
  882. // Compute totals per resource for CPU, GPU, RAM, and PV
  883. totals := map[string]map[string]float64{}
  884. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  885. // counts each allocation proportionally to its respective costs
  886. shareType := options.ShareIdle
  887. // Record allocation values first, then normalize by totals to get percentages
  888. for _, alloc := range as.allocations {
  889. if alloc.IsIdle() {
  890. // Skip idle allocations in coefficient calculation
  891. continue
  892. }
  893. // We need to key the allocations by cluster id
  894. clusterID := alloc.Properties.Cluster
  895. if clusterID == "" {
  896. return nil, fmt.Errorf("ClusterProp is not set")
  897. }
  898. // get the name key for the allocation
  899. name := alloc.Name
  900. // Create cluster based tables if they don't exist
  901. if _, ok := coeffs[clusterID]; !ok {
  902. coeffs[clusterID] = map[string]map[string]float64{}
  903. }
  904. if _, ok := totals[clusterID]; !ok {
  905. totals[clusterID] = map[string]float64{}
  906. }
  907. if _, ok := coeffs[clusterID][name]; !ok {
  908. coeffs[clusterID][name] = map[string]float64{}
  909. }
  910. if shareType == ShareEven {
  911. for _, r := range types {
  912. // Not additive - hard set to 1.0
  913. coeffs[clusterID][name][r] = 1.0
  914. // totals are additive
  915. totals[clusterID][r] += 1.0
  916. }
  917. } else {
  918. coeffs[clusterID][name]["cpu"] += alloc.CPUCost
  919. coeffs[clusterID][name]["gpu"] += alloc.GPUCost
  920. coeffs[clusterID][name]["ram"] += alloc.RAMCost
  921. totals[clusterID]["cpu"] += alloc.CPUCost
  922. totals[clusterID]["gpu"] += alloc.GPUCost
  923. totals[clusterID]["ram"] += alloc.RAMCost
  924. }
  925. }
  926. // Do the same for shared allocations
  927. for _, alloc := range shareSet.allocations {
  928. if alloc.IsIdle() {
  929. // Skip idle allocations in coefficient calculation
  930. continue
  931. }
  932. // We need to key the allocations by cluster id
  933. clusterID := alloc.Properties.Cluster
  934. if clusterID == ""{
  935. return nil, fmt.Errorf("ClusterProp is not set")
  936. }
  937. // get the name key for the allocation
  938. name := alloc.Name
  939. // Create cluster based tables if they don't exist
  940. if _, ok := coeffs[clusterID]; !ok {
  941. coeffs[clusterID] = map[string]map[string]float64{}
  942. }
  943. if _, ok := totals[clusterID]; !ok {
  944. totals[clusterID] = map[string]float64{}
  945. }
  946. if _, ok := coeffs[clusterID][name]; !ok {
  947. coeffs[clusterID][name] = map[string]float64{}
  948. }
  949. if shareType == ShareEven {
  950. for _, r := range types {
  951. // Not additive - hard set to 1.0
  952. coeffs[clusterID][name][r] = 1.0
  953. // totals are additive
  954. totals[clusterID][r] += 1.0
  955. }
  956. } else {
  957. coeffs[clusterID][name]["cpu"] += alloc.CPUCost
  958. coeffs[clusterID][name]["gpu"] += alloc.GPUCost
  959. coeffs[clusterID][name]["ram"] += alloc.RAMCost
  960. totals[clusterID]["cpu"] += alloc.CPUCost
  961. totals[clusterID]["gpu"] += alloc.GPUCost
  962. totals[clusterID]["ram"] += alloc.RAMCost
  963. }
  964. }
  965. // Normalize coefficients by totals
  966. for c := range coeffs {
  967. for a := range coeffs[c] {
  968. for _, r := range types {
  969. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  970. coeffs[c][a][r] /= totals[c][r]
  971. }
  972. }
  973. }
  974. }
  975. return coeffs, nil
  976. }
  977. func (a *Allocation) generateKey(properties AllocationProperties) string {
  978. if a == nil {
  979. return ""
  980. }
  981. // Names will ultimately be joined into a single name, which uniquely
  982. // identifies allocations.
  983. names := []string{}
  984. if properties.Cluster != "" {
  985. cluster := a.Properties.Cluster
  986. names = append(names, cluster)
  987. }
  988. if properties.Node != "" {
  989. node := a.Properties.Node
  990. names = append(names, node)
  991. }
  992. if properties.Namespace != "" {
  993. namespace := a.Properties.Namespace
  994. names = append(names, namespace)
  995. }
  996. if properties.ControllerKind != "" {
  997. controllerKind := a.Properties.ControllerKind
  998. if controllerKind == "" {
  999. // Indicate that allocation has no controller
  1000. controllerKind = UnallocatedSuffix
  1001. }
  1002. // TODO figure out if the is functional, refactor breaks this
  1003. //if prop := properties.ControllerKind; prop != "" && prop != controllerKind {
  1004. // // The allocation does not have the specified controller kind
  1005. // controllerKind = UnallocatedSuffix
  1006. //}
  1007. names = append(names, controllerKind)
  1008. }
  1009. if properties.Controller != "" {
  1010. if properties.ControllerKind == "" {
  1011. controllerKind := a.Properties.ControllerKind
  1012. if controllerKind != "" {
  1013. names = append(names, controllerKind)
  1014. }
  1015. }
  1016. controller := a.Properties.Controller
  1017. if controller == "" {
  1018. // Indicate that allocation has no controller
  1019. controller = UnallocatedSuffix
  1020. }
  1021. names = append(names, controller)
  1022. }
  1023. if properties.Pod != "" {
  1024. pod := a.Properties.Pod
  1025. names = append(names, pod)
  1026. }
  1027. if properties.Container != "" {
  1028. container := a.Properties.Container
  1029. names = append(names, container)
  1030. }
  1031. if properties.Services != nil {
  1032. services := a.Properties.Services
  1033. if services == nil {
  1034. // Indicate that allocation has no services
  1035. names = append(names, UnallocatedSuffix)
  1036. }
  1037. if services != nil && len(services) > 0 {
  1038. for _, service := range services {
  1039. names = append(names, service)
  1040. break
  1041. }
  1042. } else {
  1043. // Indicate that allocation has no services
  1044. names = append(names, UnallocatedSuffix)
  1045. }
  1046. }
  1047. if properties.Annotations != nil {
  1048. annotations:= a.Properties.Annotations
  1049. if annotations == nil {
  1050. // Indicate that allocation has no annotations
  1051. names = append(names, UnallocatedSuffix)
  1052. }
  1053. annotationNames := []string{}
  1054. aggAnnotations := properties.Annotations
  1055. for annotationName := range aggAnnotations {
  1056. if val, ok := annotations[annotationName]; ok {
  1057. annotationNames = append(annotationNames, fmt.Sprintf("%s=%s", annotationName, val))
  1058. } else if indexOf(UnallocatedSuffix, annotationNames) == -1 { // if UnallocatedSuffix not already in names
  1059. annotationNames = append(annotationNames, UnallocatedSuffix)
  1060. }
  1061. }
  1062. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1063. if len(annotationNames) > 1 {
  1064. sort.Strings(annotationNames)
  1065. }
  1066. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, annotationNames)
  1067. // suffix should be at index 0 if it exists b/c of underscores
  1068. if unallocatedSuffixIndex != -1 {
  1069. annotationNames = append(annotationNames[:unallocatedSuffixIndex], annotationNames[unallocatedSuffixIndex+1:]...)
  1070. annotationNames = append(annotationNames, UnallocatedSuffix) // append to end
  1071. }
  1072. names = append(names, annotationNames...)
  1073. }
  1074. if properties.Labels != nil {
  1075. labels := a.Properties.Labels
  1076. if labels == nil {
  1077. // Indicate that allocation has no labels
  1078. names = append(names, UnallocatedSuffix)
  1079. }
  1080. labelNames := []string{}
  1081. aggLabels:= properties.Labels
  1082. for labelName := range aggLabels {
  1083. if val, ok := labels[labelName]; ok {
  1084. labelNames = append(labelNames, fmt.Sprintf("%s=%s", labelName, val))
  1085. } else if indexOf(UnallocatedSuffix, labelNames) == -1 { // if UnallocatedSuffix not already in names
  1086. labelNames = append(labelNames, UnallocatedSuffix)
  1087. }
  1088. }
  1089. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1090. if len(labelNames) > 1 {
  1091. sort.Strings(labelNames)
  1092. }
  1093. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, labelNames)
  1094. // suffix should be at index 0 if it exists b/c of underscores
  1095. if unallocatedSuffixIndex != -1 {
  1096. labelNames = append(labelNames[:unallocatedSuffixIndex], labelNames[unallocatedSuffixIndex+1:]...)
  1097. labelNames = append(labelNames, UnallocatedSuffix) // append to end
  1098. }
  1099. names = append(names, labelNames...)
  1100. }
  1101. return strings.Join(names, "/")
  1102. }
  1103. // TODO:CLEANUP get rid of this
  1104. // Helper function to check for slice membership. Not sure if repeated elsewhere in our codebase.
  1105. func indexOf(v string, arr []string) int {
  1106. for i, s := range arr {
  1107. // This is caseless equivalence
  1108. if strings.EqualFold(v, s) {
  1109. return i
  1110. }
  1111. }
  1112. return -1
  1113. }
  1114. // Clone returns a new AllocationSet with a deep copy of the given
  1115. // AllocationSet's allocations.
  1116. func (as *AllocationSet) Clone() *AllocationSet {
  1117. if as == nil {
  1118. return nil
  1119. }
  1120. as.RLock()
  1121. defer as.RUnlock()
  1122. allocs := map[string]*Allocation{}
  1123. for k, v := range as.allocations {
  1124. allocs[k] = v.Clone()
  1125. }
  1126. externalKeys := map[string]bool{}
  1127. for k, v := range as.externalKeys {
  1128. externalKeys[k] = v
  1129. }
  1130. idleKeys := map[string]bool{}
  1131. for k, v := range as.idleKeys {
  1132. idleKeys[k] = v
  1133. }
  1134. return &AllocationSet{
  1135. allocations: allocs,
  1136. externalKeys: externalKeys,
  1137. idleKeys: idleKeys,
  1138. Window: as.Window.Clone(),
  1139. }
  1140. }
  1141. // ComputeIdleAllocations computes the idle allocations for the AllocationSet,
  1142. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1143. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1144. // considered for idle allocation. If the Nodes have adjustments, then apply
  1145. // the adjustments proportionally to each of the resources so that total
  1146. // allocation with idle reflects the adjusted node costs. One idle allocation
  1147. // per-cluster will be computed and returned, keyed by cluster_id.
  1148. func (as *AllocationSet) ComputeIdleAllocations(assetSet *AssetSet) (map[string]*Allocation, error) {
  1149. if as == nil {
  1150. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1151. }
  1152. if assetSet == nil {
  1153. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1154. }
  1155. if !as.Window.Equal(assetSet.Window) {
  1156. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1157. }
  1158. window := as.Window
  1159. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1160. // cluster-to-{cpu|gpu|ram}-to-cost.
  1161. assetClusterResourceCosts := map[string]map[string]float64{}
  1162. assetSet.Each(func(key string, a Asset) {
  1163. if node, ok := a.(*Node); ok {
  1164. if _, ok := assetClusterResourceCosts[node.Properties().Cluster]; !ok {
  1165. assetClusterResourceCosts[node.Properties().Cluster] = map[string]float64{}
  1166. }
  1167. // adjustmentRate is used to scale resource costs proportionally
  1168. // by the adjustment. This is necessary because we only get one
  1169. // adjustment per Node, not one per-resource-per-Node.
  1170. //
  1171. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1172. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1173. // e.g. total cost = $150, adjustment = $50 => 1.5
  1174. adjustmentRate := 1.0
  1175. if node.TotalCost()-node.Adjustment() == 0 {
  1176. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1177. // the entire node cost and we should make everything 0
  1178. // without dividing by 0.
  1179. adjustmentRate = 0.0
  1180. } else if node.Adjustment() != 0.0 {
  1181. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1182. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1183. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1184. }
  1185. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1186. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1187. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1188. assetClusterResourceCosts[node.Properties().Cluster]["cpu"] += cpuCost
  1189. assetClusterResourceCosts[node.Properties().Cluster]["gpu"] += gpuCost
  1190. assetClusterResourceCosts[node.Properties().Cluster]["ram"] += ramCost
  1191. }
  1192. })
  1193. // Determine start, end on a per-cluster basis
  1194. clusterStarts := map[string]time.Time{}
  1195. clusterEnds := map[string]time.Time{}
  1196. // Subtract allocated costs from asset costs, leaving only the remaining
  1197. // idle costs.
  1198. as.Each(func(name string, a *Allocation) {
  1199. cluster := a.Properties.Cluster
  1200. if cluster == "" {
  1201. // Failed to find allocation's cluster
  1202. return
  1203. }
  1204. if _, ok := assetClusterResourceCosts[cluster]; !ok {
  1205. // Failed to find assets for allocation's cluster
  1206. return
  1207. }
  1208. // Set cluster (start, end) if they are either not currently set,
  1209. // or if the detected (start, end) of the current allocation falls
  1210. // before or after, respectively, the current values.
  1211. if s, ok := clusterStarts[cluster]; !ok || a.Start.Before(s) {
  1212. clusterStarts[cluster] = a.Start
  1213. }
  1214. if e, ok := clusterEnds[cluster]; !ok || a.End.After(e) {
  1215. clusterEnds[cluster] = a.End
  1216. }
  1217. assetClusterResourceCosts[cluster]["cpu"] -= a.CPUCost
  1218. assetClusterResourceCosts[cluster]["gpu"] -= a.GPUCost
  1219. assetClusterResourceCosts[cluster]["ram"] -= a.RAMCost
  1220. })
  1221. // Turn remaining un-allocated asset costs into idle allocations
  1222. idleAllocs := map[string]*Allocation{}
  1223. for cluster, resources := range assetClusterResourceCosts {
  1224. // Default start and end to the (start, end) of the given window, but
  1225. // use the actual, detected (start, end) pair if they are available.
  1226. start := *window.Start()
  1227. if s, ok := clusterStarts[cluster]; ok && window.Contains(s) {
  1228. start = s
  1229. }
  1230. end := *window.End()
  1231. if e, ok := clusterEnds[cluster]; ok && window.Contains(e) {
  1232. end = e
  1233. }
  1234. idleAlloc := &Allocation{
  1235. Name: fmt.Sprintf("%s/%s", cluster, IdleSuffix),
  1236. Window: window.Clone(),
  1237. Properties: &AllocationProperties{Cluster: cluster},
  1238. Start: start,
  1239. End: end,
  1240. CPUCost: resources["cpu"],
  1241. GPUCost: resources["gpu"],
  1242. RAMCost: resources["ram"],
  1243. }
  1244. // Do not continue if multiple idle allocations are computed for a
  1245. // single cluster.
  1246. if _, ok := idleAllocs[cluster]; ok {
  1247. return nil, fmt.Errorf("duplicate idle allocations for cluster %s", cluster)
  1248. }
  1249. idleAllocs[cluster] = idleAlloc
  1250. }
  1251. return idleAllocs, nil
  1252. }
  1253. // Delete removes the allocation with the given name from the set
  1254. func (as *AllocationSet) Delete(name string) {
  1255. if as == nil {
  1256. return
  1257. }
  1258. as.Lock()
  1259. defer as.Unlock()
  1260. delete(as.externalKeys, name)
  1261. delete(as.idleKeys, name)
  1262. delete(as.allocations, name)
  1263. }
  1264. // Each invokes the given function for each Allocation in the set
  1265. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  1266. if as == nil {
  1267. return
  1268. }
  1269. for k, a := range as.allocations {
  1270. f(k, a)
  1271. }
  1272. }
  1273. // End returns the End time of the AllocationSet window
  1274. func (as *AllocationSet) End() time.Time {
  1275. if as == nil {
  1276. log.Warningf("Allocation ETL: calling End on nil AllocationSet")
  1277. return time.Unix(0, 0)
  1278. }
  1279. if as.Window.End() == nil {
  1280. log.Warningf("Allocation ETL: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  1281. return time.Unix(0, 0)
  1282. }
  1283. return *as.Window.End()
  1284. }
  1285. // Get returns the Allocation at the given key in the AllocationSet
  1286. func (as *AllocationSet) Get(key string) *Allocation {
  1287. as.RLock()
  1288. defer as.RUnlock()
  1289. if alloc, ok := as.allocations[key]; ok {
  1290. return alloc
  1291. }
  1292. return nil
  1293. }
  1294. // ExternalAllocations returns a map of the external allocations in the set.
  1295. // Returns clones of the actual Allocations, so mutability is not a problem.
  1296. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1297. externals := map[string]*Allocation{}
  1298. if as.IsEmpty() {
  1299. return externals
  1300. }
  1301. as.RLock()
  1302. defer as.RUnlock()
  1303. for key := range as.externalKeys {
  1304. if alloc, ok := as.allocations[key]; ok {
  1305. externals[key] = alloc.Clone()
  1306. }
  1307. }
  1308. return externals
  1309. }
  1310. // ExternalCost returns the total aggregated external costs of the set
  1311. func (as *AllocationSet) ExternalCost() float64 {
  1312. if as.IsEmpty() {
  1313. return 0.0
  1314. }
  1315. as.RLock()
  1316. defer as.RUnlock()
  1317. externalCost := 0.0
  1318. for _, alloc := range as.allocations {
  1319. externalCost += alloc.ExternalCost
  1320. }
  1321. return externalCost
  1322. }
  1323. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1324. // Returns clones of the actual Allocations, so mutability is not a problem.
  1325. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1326. idles := map[string]*Allocation{}
  1327. if as.IsEmpty() {
  1328. return idles
  1329. }
  1330. as.RLock()
  1331. defer as.RUnlock()
  1332. for key := range as.idleKeys {
  1333. if alloc, ok := as.allocations[key]; ok {
  1334. idles[key] = alloc.Clone()
  1335. }
  1336. }
  1337. return idles
  1338. }
  1339. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1340. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1341. // there is no existing entry, one is created. Nil error response indicates success.
  1342. func (as *AllocationSet) Insert(that *Allocation) error {
  1343. return as.insert(that)
  1344. }
  1345. func (as *AllocationSet) insert(that *Allocation) error {
  1346. if as == nil {
  1347. return fmt.Errorf("cannot insert into nil AllocationSet")
  1348. }
  1349. as.Lock()
  1350. defer as.Unlock()
  1351. if as.allocations == nil {
  1352. as.allocations = map[string]*Allocation{}
  1353. }
  1354. if as.externalKeys == nil {
  1355. as.externalKeys = map[string]bool{}
  1356. }
  1357. if as.idleKeys == nil {
  1358. as.idleKeys = map[string]bool{}
  1359. }
  1360. // Add the given Allocation to the existing entry, if there is one;
  1361. // otherwise just set directly into allocations
  1362. if _, ok := as.allocations[that.Name]; !ok {
  1363. as.allocations[that.Name] = that
  1364. } else {
  1365. as.allocations[that.Name].add(that)
  1366. }
  1367. // If the given Allocation is an external one, record that
  1368. if that.IsExternal() {
  1369. as.externalKeys[that.Name] = true
  1370. }
  1371. // If the given Allocation is an idle one, record that
  1372. if that.IsIdle() {
  1373. as.idleKeys[that.Name] = true
  1374. }
  1375. return nil
  1376. }
  1377. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  1378. // zero allocations.
  1379. func (as *AllocationSet) IsEmpty() bool {
  1380. if as == nil || len(as.allocations) == 0 {
  1381. return true
  1382. }
  1383. as.RLock()
  1384. defer as.RUnlock()
  1385. return as.allocations == nil || len(as.allocations) == 0
  1386. }
  1387. // Length returns the number of Allocations in the set
  1388. func (as *AllocationSet) Length() int {
  1389. if as == nil {
  1390. return 0
  1391. }
  1392. as.RLock()
  1393. defer as.RUnlock()
  1394. return len(as.allocations)
  1395. }
  1396. // Map clones and returns a map of the AllocationSet's Allocations
  1397. func (as *AllocationSet) Map() map[string]*Allocation {
  1398. if as.IsEmpty() {
  1399. return map[string]*Allocation{}
  1400. }
  1401. return as.Clone().allocations
  1402. }
  1403. // MarshalJSON JSON-encodes the AllocationSet
  1404. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  1405. as.RLock()
  1406. defer as.RUnlock()
  1407. return json.Marshal(as.allocations)
  1408. }
  1409. // Resolution returns the AllocationSet's window duration
  1410. func (as *AllocationSet) Resolution() time.Duration {
  1411. return as.Window.Duration()
  1412. }
  1413. // Set uses the given Allocation to overwrite the existing entry in the
  1414. // AllocationSet under the Allocation's name.
  1415. func (as *AllocationSet) Set(alloc *Allocation) error {
  1416. if as.IsEmpty() {
  1417. as.Lock()
  1418. as.allocations = map[string]*Allocation{}
  1419. as.externalKeys = map[string]bool{}
  1420. as.idleKeys = map[string]bool{}
  1421. as.Unlock()
  1422. }
  1423. as.Lock()
  1424. defer as.Unlock()
  1425. as.allocations[alloc.Name] = alloc
  1426. // If the given Allocation is an external one, record that
  1427. if alloc.IsExternal() {
  1428. as.externalKeys[alloc.Name] = true
  1429. }
  1430. // If the given Allocation is an idle one, record that
  1431. if alloc.IsIdle() {
  1432. as.idleKeys[alloc.Name] = true
  1433. }
  1434. return nil
  1435. }
  1436. // Start returns the Start time of the AllocationSet window
  1437. func (as *AllocationSet) Start() time.Time {
  1438. if as == nil {
  1439. log.Warningf("Allocation ETL: calling Start on nil AllocationSet")
  1440. return time.Unix(0, 0)
  1441. }
  1442. if as.Window.Start() == nil {
  1443. log.Warningf("Allocation ETL: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1444. return time.Unix(0, 0)
  1445. }
  1446. return *as.Window.Start()
  1447. }
  1448. // String represents the given Allocation as a string
  1449. func (as *AllocationSet) String() string {
  1450. if as == nil {
  1451. return "<nil>"
  1452. }
  1453. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1454. as.Length(), as.Window, as.TotalCost())
  1455. }
  1456. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1457. func (as *AllocationSet) TotalCost() float64 {
  1458. if as.IsEmpty() {
  1459. return 0.0
  1460. }
  1461. as.RLock()
  1462. defer as.RUnlock()
  1463. tc := 0.0
  1464. for _, a := range as.allocations {
  1465. tc += a.TotalCost()
  1466. }
  1467. return tc
  1468. }
  1469. // UTCOffset returns the AllocationSet's configured UTCOffset.
  1470. func (as *AllocationSet) UTCOffset() time.Duration {
  1471. _, zone := as.Start().Zone()
  1472. return time.Duration(zone) * time.Second
  1473. }
  1474. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1475. if as.IsEmpty() {
  1476. return that, nil
  1477. }
  1478. if that.IsEmpty() {
  1479. return as, nil
  1480. }
  1481. // Set start, end to min(start), max(end)
  1482. start := as.Start()
  1483. end := as.End()
  1484. if that.Start().Before(start) {
  1485. start = that.Start()
  1486. }
  1487. if that.End().After(end) {
  1488. end = that.End()
  1489. }
  1490. acc := NewAllocationSet(start, end)
  1491. as.RLock()
  1492. defer as.RUnlock()
  1493. that.RLock()
  1494. defer that.RUnlock()
  1495. for _, alloc := range as.allocations {
  1496. err := acc.insert(alloc)
  1497. if err != nil {
  1498. return nil, err
  1499. }
  1500. }
  1501. for _, alloc := range that.allocations {
  1502. err := acc.insert(alloc)
  1503. if err != nil {
  1504. return nil, err
  1505. }
  1506. }
  1507. return acc, nil
  1508. }
  1509. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  1510. // be used such that the AllocationSets held are consecutive and coherent with
  1511. // respect to using the same aggregation properties, UTC offset, and
  1512. // resolution. However these rules are not necessarily enforced, so use wisely.
  1513. type AllocationSetRange struct {
  1514. sync.RWMutex
  1515. allocations []*AllocationSet
  1516. }
  1517. // NewAllocationSetRange instantiates a new range composed of the given
  1518. // AllocationSets in the order provided.
  1519. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1520. return &AllocationSetRange{
  1521. allocations: allocs,
  1522. }
  1523. }
  1524. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1525. // AllocationSet for the entire range.
  1526. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1527. var allocSet *AllocationSet
  1528. var err error
  1529. asr.RLock()
  1530. defer asr.RUnlock()
  1531. for _, as := range asr.allocations {
  1532. allocSet, err = allocSet.accumulate(as)
  1533. if err != nil {
  1534. return nil, err
  1535. }
  1536. }
  1537. return allocSet, nil
  1538. }
  1539. // TODO niko/etl accumulate into lower-resolution chunks of the given resolution
  1540. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1541. // AggregateBy aggregates each AllocationSet in the range by the given
  1542. // properties and options.
  1543. func (asr *AllocationSetRange) AggregateBy(properties AllocationProperties, options *AllocationAggregationOptions) error {
  1544. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1545. asr.Lock()
  1546. defer asr.Unlock()
  1547. for _, as := range asr.allocations {
  1548. err := as.AggregateBy(properties, options)
  1549. if err != nil {
  1550. return err
  1551. }
  1552. aggRange.allocations = append(aggRange.allocations, as)
  1553. }
  1554. asr.allocations = aggRange.allocations
  1555. return nil
  1556. }
  1557. // Append appends the given AllocationSet to the end of the range. It does not
  1558. // validate whether or not that violates window continuity.
  1559. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1560. asr.Lock()
  1561. defer asr.Unlock()
  1562. asr.allocations = append(asr.allocations, that)
  1563. }
  1564. // Each invokes the given function for each AllocationSet in the range
  1565. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1566. if asr == nil {
  1567. return
  1568. }
  1569. for i, as := range asr.allocations {
  1570. f(i, as)
  1571. }
  1572. }
  1573. // Get retrieves the AllocationSet at the given index of the range.
  1574. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  1575. if i < 0 || i >= len(asr.allocations) {
  1576. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  1577. }
  1578. asr.RLock()
  1579. defer asr.RUnlock()
  1580. return asr.allocations[i], nil
  1581. }
  1582. // InsertRange merges the given AllocationSetRange into the receiving one by
  1583. // lining up sets with matching windows, then inserting each allocation from
  1584. // the given ASR into the respective set in the receiving ASR. If the given
  1585. // ASR contains an AllocationSet from a window that does not exist in the
  1586. // receiving ASR, then an error is returned. However, the given ASR does not
  1587. // need to cover the full range of the receiver.
  1588. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  1589. if asr == nil {
  1590. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  1591. }
  1592. // keys maps window to index in asr
  1593. keys := map[string]int{}
  1594. asr.Each(func(i int, as *AllocationSet) {
  1595. if as == nil {
  1596. return
  1597. }
  1598. keys[as.Window.String()] = i
  1599. })
  1600. // Nothing to merge, so simply return
  1601. if len(keys) == 0 {
  1602. return nil
  1603. }
  1604. var err error
  1605. that.Each(func(j int, thatAS *AllocationSet) {
  1606. if thatAS == nil || err != nil {
  1607. return
  1608. }
  1609. // Find matching AllocationSet in asr
  1610. i, ok := keys[thatAS.Window.String()]
  1611. if !ok {
  1612. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  1613. return
  1614. }
  1615. as, err := asr.Get(i)
  1616. if err != nil {
  1617. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  1618. return
  1619. }
  1620. // Insert each Allocation from the given set
  1621. thatAS.Each(func(k string, alloc *Allocation) {
  1622. err = as.Insert(alloc)
  1623. if err != nil {
  1624. err = fmt.Errorf("error inserting allocation: %s", err)
  1625. return
  1626. }
  1627. })
  1628. })
  1629. // err might be nil
  1630. return err
  1631. }
  1632. // Length returns the length of the range, which is zero if nil
  1633. func (asr *AllocationSetRange) Length() int {
  1634. if asr == nil || asr.allocations == nil {
  1635. return 0
  1636. }
  1637. asr.RLock()
  1638. defer asr.RUnlock()
  1639. return len(asr.allocations)
  1640. }
  1641. // MarshalJSON JSON-encodes the range
  1642. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  1643. asr.RLock()
  1644. asr.RUnlock()
  1645. return json.Marshal(asr.allocations)
  1646. }
  1647. // Slice copies the underlying slice of AllocationSets, maintaining order,
  1648. // and returns the copied slice.
  1649. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  1650. if asr == nil || asr.allocations == nil {
  1651. return nil
  1652. }
  1653. asr.RLock()
  1654. defer asr.RUnlock()
  1655. copy := []*AllocationSet{}
  1656. for _, as := range asr.allocations {
  1657. copy = append(copy, as.Clone())
  1658. }
  1659. return copy
  1660. }
  1661. // String represents the given AllocationSetRange as a string
  1662. func (asr *AllocationSetRange) String() string {
  1663. if asr == nil {
  1664. return "<nil>"
  1665. }
  1666. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  1667. }
  1668. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  1669. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  1670. // are sets with conflicting UTCOffsets (just returns the first).
  1671. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  1672. if asr.Length() == 0 {
  1673. return 0
  1674. }
  1675. as, err := asr.Get(0)
  1676. if err != nil {
  1677. return 0
  1678. }
  1679. return as.UTCOffset()
  1680. }
  1681. // Window returns the full window that the AllocationSetRange spans, from the
  1682. // start of the first AllocationSet to the end of the last one.
  1683. func (asr *AllocationSetRange) Window() Window {
  1684. if asr == nil || asr.Length() == 0 {
  1685. return NewWindow(nil, nil)
  1686. }
  1687. start := asr.allocations[0].Start()
  1688. end := asr.allocations[asr.Length()-1].End()
  1689. return NewWindow(&start, &end)
  1690. }