allocation.go 60 KB

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