allocation.go 61 KB

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