allocation.go 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504
  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 Allocation and an
  38. // Assets-style key() function for AllocationSet.
  39. type Allocation struct {
  40. Name string `json:"name"`
  41. Properties *AllocationProperties `json:"properties,omitempty"`
  42. Window Window `json:"window"`
  43. Start time.Time `json:"start"`
  44. End time.Time `json:"end"`
  45. CPUCoreHours float64 `json:"cpuCoreHours"`
  46. CPUCoreRequestAverage float64 `json:"cpuCoreRequestAverage"`
  47. CPUCoreUsageAverage float64 `json:"cpuCoreUsageAverage"`
  48. CPUCost float64 `json:"cpuCost"`
  49. CPUCostAdjustment float64 `json:"cpuCostAdjustment"`
  50. GPUHours float64 `json:"gpuHours"`
  51. GPUCost float64 `json:"gpuCost"`
  52. GPUCostAdjustment float64 `json:"gpuCostAdjustment"`
  53. NetworkTransferBytes float64 `json:"networkTransferBytes"`
  54. NetworkReceiveBytes float64 `json:"networkReceiveBytes"`
  55. NetworkCost float64 `json:"networkCost"`
  56. NetworkCostAdjustment float64 `json:"networkCostAdjustment"`
  57. LoadBalancerCost float64 `json:"loadBalancerCost"`
  58. LoadBalancerCostAdjustment float64 `json:"loadBalancerCostAdjustment"`
  59. PVs PVAllocations `json:"-"`
  60. PVCostAdjustment float64 `json:"pvCostAdjustment"`
  61. RAMByteHours float64 `json:"ramByteHours"`
  62. RAMBytesRequestAverage float64 `json:"ramByteRequestAverage"`
  63. RAMBytesUsageAverage float64 `json:"ramByteUsageAverage"`
  64. RAMCost float64 `json:"ramCost"`
  65. RAMCostAdjustment float64 `json:"ramCostAdjustment"`
  66. SharedCost float64 `json:"sharedCost"`
  67. ExternalCost float64 `json:"externalCost"`
  68. // RawAllocationOnly is a pointer so if it is not present it will be
  69. // marshalled as null rather than as an object with Go default values.
  70. RawAllocationOnly *RawAllocationOnlyData `json:"rawAllocationOnly"`
  71. }
  72. // RawAllocationOnlyData is information that only belong in "raw" Allocations,
  73. // those which have not undergone aggregation, accumulation, or any other form
  74. // of combination to produce a new Allocation from other Allocations.
  75. //
  76. // Max usage data belongs here because computing the overall maximum from two
  77. // or more Allocations is a non-trivial operation that cannot be defined without
  78. // maintaining a large amount of state. Consider the following example:
  79. // _______________________________________________
  80. //
  81. // A1 Using 3 CPU ---- ----- ------
  82. // A2 Using 2 CPU ---- ----- ----
  83. // A3 Using 1 CPU --- --
  84. // _______________________________________________
  85. // Time ---->
  86. //
  87. // The logical maximum CPU usage is 5, but this cannot be calculated iteratively,
  88. // which is how we calculate aggregations and accumulations of Allocations currently.
  89. // This becomes a problem I could call "maximum sum of overlapping intervals" and is
  90. // essentially a variant of an interval scheduling algorithm.
  91. //
  92. // If we had types to differentiate between regular Allocations and AggregatedAllocations
  93. // then this type would be unnecessary and its fields would go into the regular Allocation
  94. // and not in the AggregatedAllocation.
  95. type RawAllocationOnlyData struct {
  96. CPUCoreUsageMax float64 `json:"cpuCoreUsageMax"`
  97. RAMBytesUsageMax float64 `json:"ramByteUsageMax"`
  98. }
  99. // PVAllocations is a map of Disk Asset Identifiers to the
  100. // usage of them by an Allocation as recorded in a PVAllocation
  101. type PVAllocations map[PVKey]*PVAllocation
  102. // Clone creates a deep copy of a PVAllocations
  103. func (pv *PVAllocations) Clone() PVAllocations {
  104. if pv == nil || *pv == nil {
  105. return nil
  106. }
  107. apv := *pv
  108. clonePV := PVAllocations{}
  109. for k, v := range apv {
  110. clonePV[k] = &PVAllocation{
  111. ByteHours: v.ByteHours,
  112. Cost: v.Cost,
  113. }
  114. }
  115. return clonePV
  116. }
  117. // Add adds contents of that to the calling PVAllocations
  118. func (pv *PVAllocations) Add(that PVAllocations) PVAllocations {
  119. apv := pv.Clone()
  120. if that != nil {
  121. if apv == nil {
  122. apv = PVAllocations{}
  123. }
  124. for pvKey, thatPVAlloc := range that {
  125. apvAlloc, ok := apv[pvKey]
  126. if !ok {
  127. apvAlloc = &PVAllocation{}
  128. }
  129. apvAlloc.Cost += thatPVAlloc.Cost
  130. apvAlloc.ByteHours += thatPVAlloc.ByteHours
  131. apv[pvKey] = apvAlloc
  132. }
  133. }
  134. return apv
  135. }
  136. // PVKey for identifying Disk type assets
  137. type PVKey struct {
  138. Cluster string `json:"cluster"`
  139. Name string `json:"name"`
  140. }
  141. // PVAllocation contains the byte hour usage
  142. // and cost of an Allocation for a single PV
  143. type PVAllocation struct {
  144. ByteHours float64 `json:"byteHours"`
  145. Cost float64 `json:"cost"`
  146. }
  147. // AllocationMatchFunc is a function that can be used to match Allocations by
  148. // returning true for any given Allocation if a condition is met.
  149. type AllocationMatchFunc func(*Allocation) bool
  150. // Add returns the result of summing the two given Allocations, which sums the
  151. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  152. // the two original Allocations are mutated in the process.
  153. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  154. if a == nil {
  155. return that.Clone(), nil
  156. }
  157. if that == nil {
  158. return a.Clone(), nil
  159. }
  160. // Note: no need to clone "that", as add only mutates the receiver
  161. agg := a.Clone()
  162. agg.add(that)
  163. return agg, nil
  164. }
  165. // Clone returns a deep copy of the given Allocation
  166. func (a *Allocation) Clone() *Allocation {
  167. if a == nil {
  168. return nil
  169. }
  170. return &Allocation{
  171. Name: a.Name,
  172. Properties: a.Properties.Clone(),
  173. Window: a.Window.Clone(),
  174. Start: a.Start,
  175. End: a.End,
  176. CPUCoreHours: a.CPUCoreHours,
  177. CPUCoreRequestAverage: a.CPUCoreRequestAverage,
  178. CPUCoreUsageAverage: a.CPUCoreUsageAverage,
  179. CPUCost: a.CPUCost,
  180. CPUCostAdjustment: a.CPUCostAdjustment,
  181. GPUHours: a.GPUHours,
  182. GPUCost: a.GPUCost,
  183. GPUCostAdjustment: a.GPUCostAdjustment,
  184. NetworkTransferBytes: a.NetworkTransferBytes,
  185. NetworkReceiveBytes: a.NetworkReceiveBytes,
  186. NetworkCost: a.NetworkCost,
  187. NetworkCostAdjustment: a.NetworkCostAdjustment,
  188. LoadBalancerCost: a.LoadBalancerCost,
  189. LoadBalancerCostAdjustment: a.LoadBalancerCostAdjustment,
  190. PVs: a.PVs.Clone(),
  191. PVCostAdjustment: a.PVCostAdjustment,
  192. RAMByteHours: a.RAMByteHours,
  193. RAMBytesRequestAverage: a.RAMBytesRequestAverage,
  194. RAMBytesUsageAverage: a.RAMBytesUsageAverage,
  195. RAMCost: a.RAMCost,
  196. RAMCostAdjustment: a.RAMCostAdjustment,
  197. SharedCost: a.SharedCost,
  198. ExternalCost: a.ExternalCost,
  199. RawAllocationOnly: a.RawAllocationOnly.Clone(),
  200. }
  201. }
  202. // Clone returns a deep copy of the given RawAllocationOnlyData
  203. func (r *RawAllocationOnlyData) Clone() *RawAllocationOnlyData {
  204. if r == nil {
  205. return nil
  206. }
  207. return &RawAllocationOnlyData{
  208. CPUCoreUsageMax: r.CPUCoreUsageMax,
  209. RAMBytesUsageMax: r.RAMBytesUsageMax,
  210. }
  211. }
  212. // Equal returns true if the values held in the given Allocation precisely
  213. // match those of the receiving Allocation. nil does not match nil. Floating
  214. // point values need to match according to util.IsApproximately, which accounts
  215. // for small, reasonable floating point error margins.
  216. func (a *Allocation) Equal(that *Allocation) bool {
  217. if a == nil || that == nil {
  218. return false
  219. }
  220. if a.Name != that.Name {
  221. return false
  222. }
  223. if !a.Properties.Equal(that.Properties) {
  224. return false
  225. }
  226. if !a.Window.Equal(that.Window) {
  227. return false
  228. }
  229. if !a.Start.Equal(that.Start) {
  230. return false
  231. }
  232. if !a.End.Equal(that.End) {
  233. return false
  234. }
  235. if !util.IsApproximately(a.CPUCoreHours, that.CPUCoreHours) {
  236. return false
  237. }
  238. if !util.IsApproximately(a.CPUCost, that.CPUCost) {
  239. return false
  240. }
  241. if !util.IsApproximately(a.CPUCostAdjustment, that.CPUCostAdjustment) {
  242. return false
  243. }
  244. if !util.IsApproximately(a.GPUHours, that.GPUHours) {
  245. return false
  246. }
  247. if !util.IsApproximately(a.GPUCost, that.GPUCost) {
  248. return false
  249. }
  250. if !util.IsApproximately(a.GPUCostAdjustment, that.GPUCostAdjustment) {
  251. return false
  252. }
  253. if !util.IsApproximately(a.NetworkTransferBytes, that.NetworkTransferBytes) {
  254. return false
  255. }
  256. if !util.IsApproximately(a.NetworkReceiveBytes, that.NetworkReceiveBytes) {
  257. return false
  258. }
  259. if !util.IsApproximately(a.NetworkCost, that.NetworkCost) {
  260. return false
  261. }
  262. if !util.IsApproximately(a.NetworkCostAdjustment, that.NetworkCostAdjustment) {
  263. return false
  264. }
  265. if !util.IsApproximately(a.LoadBalancerCost, that.LoadBalancerCost) {
  266. return false
  267. }
  268. if !util.IsApproximately(a.LoadBalancerCostAdjustment, that.LoadBalancerCostAdjustment) {
  269. return false
  270. }
  271. if !util.IsApproximately(a.PVCostAdjustment, that.PVCostAdjustment) {
  272. return false
  273. }
  274. if !util.IsApproximately(a.RAMByteHours, that.RAMByteHours) {
  275. return false
  276. }
  277. if !util.IsApproximately(a.RAMCost, that.RAMCost) {
  278. return false
  279. }
  280. if !util.IsApproximately(a.RAMCostAdjustment, that.RAMCostAdjustment) {
  281. return false
  282. }
  283. if !util.IsApproximately(a.SharedCost, that.SharedCost) {
  284. return false
  285. }
  286. if !util.IsApproximately(a.ExternalCost, that.ExternalCost) {
  287. return false
  288. }
  289. if a.RawAllocationOnly == nil && that.RawAllocationOnly != nil {
  290. return false
  291. }
  292. if a.RawAllocationOnly != nil && that.RawAllocationOnly == nil {
  293. return false
  294. }
  295. if a.RawAllocationOnly != nil && that.RawAllocationOnly != nil {
  296. if !util.IsApproximately(a.RawAllocationOnly.CPUCoreUsageMax, that.RawAllocationOnly.CPUCoreUsageMax) {
  297. return false
  298. }
  299. if !util.IsApproximately(a.RawAllocationOnly.RAMBytesUsageMax, that.RawAllocationOnly.RAMBytesUsageMax) {
  300. return false
  301. }
  302. }
  303. aPVs := a.PVs
  304. thatPVs := that.PVs
  305. if len(aPVs) == len(thatPVs) {
  306. for k, pv := range aPVs {
  307. tv, ok := thatPVs[k]
  308. if !ok || *tv != *pv {
  309. return false
  310. }
  311. }
  312. } else {
  313. return false
  314. }
  315. return true
  316. }
  317. // TotalCost is the total cost of the Allocation including adjustments
  318. func (a *Allocation) TotalCost() float64 {
  319. return a.CPUTotalCost() + a.GPUTotalCost() + a.RAMTotalCost() + a.PVTotalCost() + a.NetworkTotalCost() + a.LBTotalCost() + a.SharedTotalCost() + a.ExternalCost
  320. }
  321. // CPUTotalCost calculates total CPU cost of Allocation including adjustment
  322. func (a *Allocation) CPUTotalCost() float64 {
  323. return a.CPUCost + a.CPUCostAdjustment
  324. }
  325. // GPUTotalCost calculates total GPU cost of Allocation including adjustment
  326. func (a *Allocation) GPUTotalCost() float64 {
  327. return a.GPUCost + a.GPUCostAdjustment
  328. }
  329. // RAMTotalCost calculates total RAM cost of Allocation including adjustment
  330. func (a *Allocation) RAMTotalCost() float64 {
  331. return a.RAMCost + a.RAMCostAdjustment
  332. }
  333. // PVTotalCost calculates total PV cost of Allocation including adjustment
  334. func (a *Allocation) PVTotalCost() float64 {
  335. return a.PVCost() + a.PVCostAdjustment
  336. }
  337. // NetworkTotalCost calculates total Network cost of Allocation including adjustment
  338. func (a *Allocation) NetworkTotalCost() float64 {
  339. return a.NetworkCost + a.NetworkCostAdjustment
  340. }
  341. // LBTotalCost calculates total LB cost of Allocation including adjustment
  342. func (a *Allocation) LBTotalCost() float64 {
  343. return a.LoadBalancerCost + a.LoadBalancerCostAdjustment
  344. }
  345. // SharedTotalCost calculates total shared cost of Allocation including adjustment
  346. func (a *Allocation) SharedTotalCost() float64 {
  347. return a.SharedCost
  348. }
  349. // PVCost calculate cumulative cost of all PVs that Allocation is attached to
  350. func (a *Allocation) PVCost() float64 {
  351. cost := 0.0
  352. for _, pv := range a.PVs {
  353. cost += pv.Cost
  354. }
  355. return cost
  356. }
  357. // PVByteHours calculate cumulative ByteHours of all PVs that Allocation is attached to
  358. func (a *Allocation) PVByteHours() float64 {
  359. byteHours := 0.0
  360. for _, pv := range a.PVs {
  361. byteHours += pv.ByteHours
  362. }
  363. return byteHours
  364. }
  365. // CPUEfficiency is the ratio of usage to request. If there is no request and
  366. // no usage or cost, then efficiency is zero. If there is no request, but there
  367. // is usage or cost, then efficiency is 100%.
  368. func (a *Allocation) CPUEfficiency() float64 {
  369. if a.CPUCoreRequestAverage > 0 {
  370. return a.CPUCoreUsageAverage / a.CPUCoreRequestAverage
  371. }
  372. if a.CPUCoreUsageAverage == 0.0 || a.CPUCost == 0.0 {
  373. return 0.0
  374. }
  375. return 1.0
  376. }
  377. // RAMEfficiency is the ratio of usage to request. If there is no request and
  378. // no usage or cost, then efficiency is zero. If there is no request, but there
  379. // is usage or cost, then efficiency is 100%.
  380. func (a *Allocation) RAMEfficiency() float64 {
  381. if a.RAMBytesRequestAverage > 0 {
  382. return a.RAMBytesUsageAverage / a.RAMBytesRequestAverage
  383. }
  384. if a.RAMBytesUsageAverage == 0.0 || a.RAMCost == 0.0 {
  385. return 0.0
  386. }
  387. return 1.0
  388. }
  389. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  390. // there is no cost at all, then efficiency is zero.
  391. func (a *Allocation) TotalEfficiency() float64 {
  392. if a.RAMTotalCost()+a.CPUTotalCost() > 0 {
  393. ramCostEff := a.RAMEfficiency() * a.RAMTotalCost()
  394. cpuCostEff := a.CPUEfficiency() * a.CPUTotalCost()
  395. return (ramCostEff + cpuCostEff) / (a.CPUTotalCost() + a.RAMTotalCost())
  396. }
  397. return 0.0
  398. }
  399. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  400. func (a *Allocation) CPUCores() float64 {
  401. if a.Minutes() <= 0.0 {
  402. return 0.0
  403. }
  404. return a.CPUCoreHours / (a.Minutes() / 60.0)
  405. }
  406. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  407. func (a *Allocation) RAMBytes() float64 {
  408. if a.Minutes() <= 0.0 {
  409. return 0.0
  410. }
  411. return a.RAMByteHours / (a.Minutes() / 60.0)
  412. }
  413. // GPUs converts the Allocation's GPUHours into average GPUs
  414. func (a *Allocation) GPUs() float64 {
  415. if a.Minutes() <= 0.0 {
  416. return 0.0
  417. }
  418. return a.GPUHours / (a.Minutes() / 60.0)
  419. }
  420. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  421. func (a *Allocation) PVBytes() float64 {
  422. if a.Minutes() <= 0.0 {
  423. return 0.0
  424. }
  425. return a.PVByteHours() / (a.Minutes() / 60.0)
  426. }
  427. // ResetAdjustments sets all cost adjustment fields to zero
  428. func (a *Allocation) ResetAdjustments() {
  429. a.CPUCostAdjustment = 0.0
  430. a.GPUCostAdjustment = 0.0
  431. a.RAMCostAdjustment = 0.0
  432. a.PVCostAdjustment = 0.0
  433. a.NetworkCostAdjustment = 0.0
  434. a.LoadBalancerCostAdjustment = 0.0
  435. }
  436. // MarshalJSON implements json.Marshaler interface
  437. func (a *Allocation) MarshalJSON() ([]byte, error) {
  438. buffer := bytes.NewBufferString("{")
  439. jsonEncodeString(buffer, "name", a.Name, ",")
  440. jsonEncode(buffer, "properties", a.Properties, ",")
  441. jsonEncode(buffer, "window", a.Window, ",")
  442. jsonEncodeString(buffer, "start", a.Start.Format(time.RFC3339), ",")
  443. jsonEncodeString(buffer, "end", a.End.Format(time.RFC3339), ",")
  444. jsonEncodeFloat64(buffer, "minutes", a.Minutes(), ",")
  445. jsonEncodeFloat64(buffer, "cpuCores", a.CPUCores(), ",")
  446. jsonEncodeFloat64(buffer, "cpuCoreRequestAverage", a.CPUCoreRequestAverage, ",")
  447. jsonEncodeFloat64(buffer, "cpuCoreUsageAverage", a.CPUCoreUsageAverage, ",")
  448. jsonEncodeFloat64(buffer, "cpuCoreHours", a.CPUCoreHours, ",")
  449. jsonEncodeFloat64(buffer, "cpuCost", a.CPUCost, ",")
  450. jsonEncodeFloat64(buffer, "cpuCostAdjustment", a.CPUCostAdjustment, ",")
  451. jsonEncodeFloat64(buffer, "cpuEfficiency", a.CPUEfficiency(), ",")
  452. jsonEncodeFloat64(buffer, "gpuCount", a.GPUs(), ",")
  453. jsonEncodeFloat64(buffer, "gpuHours", a.GPUHours, ",")
  454. jsonEncodeFloat64(buffer, "gpuCost", a.GPUCost, ",")
  455. jsonEncodeFloat64(buffer, "gpuCostAdjustment", a.GPUCostAdjustment, ",")
  456. jsonEncodeFloat64(buffer, "networkTransferBytes", a.NetworkTransferBytes, ",")
  457. jsonEncodeFloat64(buffer, "networkReceiveBytes", a.NetworkReceiveBytes, ",")
  458. jsonEncodeFloat64(buffer, "networkCost", a.NetworkCost, ",")
  459. jsonEncodeFloat64(buffer, "networkCostAdjustment", a.NetworkCostAdjustment, ",")
  460. jsonEncodeFloat64(buffer, "loadBalancerCost", a.LoadBalancerCost, ",")
  461. jsonEncodeFloat64(buffer, "loadBalancerCostAdjustment", a.LoadBalancerCostAdjustment, ",")
  462. jsonEncodeFloat64(buffer, "pvBytes", a.PVBytes(), ",")
  463. jsonEncodeFloat64(buffer, "pvByteHours", a.PVByteHours(), ",")
  464. jsonEncodeFloat64(buffer, "pvCost", a.PVCost(), ",")
  465. jsonEncode(buffer, "pvs", a.PVs, ",") // Todo Sean: this does not work properly
  466. jsonEncodeFloat64(buffer, "pvCostAdjustment", a.PVCostAdjustment, ",")
  467. jsonEncodeFloat64(buffer, "ramBytes", a.RAMBytes(), ",")
  468. jsonEncodeFloat64(buffer, "ramByteRequestAverage", a.RAMBytesRequestAverage, ",")
  469. jsonEncodeFloat64(buffer, "ramByteUsageAverage", a.RAMBytesUsageAverage, ",")
  470. jsonEncodeFloat64(buffer, "ramByteHours", a.RAMByteHours, ",")
  471. jsonEncodeFloat64(buffer, "ramCost", a.RAMCost, ",")
  472. jsonEncodeFloat64(buffer, "ramCostAdjustment", a.RAMCostAdjustment, ",")
  473. jsonEncodeFloat64(buffer, "ramEfficiency", a.RAMEfficiency(), ",")
  474. jsonEncodeFloat64(buffer, "sharedCost", a.SharedCost, ",")
  475. jsonEncodeFloat64(buffer, "externalCost", a.ExternalCost, ",")
  476. jsonEncodeFloat64(buffer, "totalCost", a.TotalCost(), ",")
  477. jsonEncodeFloat64(buffer, "totalEfficiency", a.TotalEfficiency(), ",")
  478. jsonEncode(buffer, "rawAllocationOnly", a.RawAllocationOnly, "")
  479. buffer.WriteString("}")
  480. return buffer.Bytes(), nil
  481. }
  482. // Resolution returns the duration of time covered by the Allocation
  483. func (a *Allocation) Resolution() time.Duration {
  484. return a.End.Sub(a.Start)
  485. }
  486. // IsAggregated is true if the given Allocation has been aggregated, which we
  487. // define by a lack of AllocationProperties.
  488. func (a *Allocation) IsAggregated() bool {
  489. return a == nil || a.Properties == nil
  490. }
  491. // IsExternal is true if the given Allocation represents external costs.
  492. func (a *Allocation) IsExternal() bool {
  493. return strings.Contains(a.Name, ExternalSuffix)
  494. }
  495. // IsIdle is true if the given Allocation represents idle costs.
  496. func (a *Allocation) IsIdle() bool {
  497. return strings.Contains(a.Name, IdleSuffix)
  498. }
  499. // IsUnallocated is true if the given Allocation represents unallocated costs.
  500. func (a *Allocation) IsUnallocated() bool {
  501. return strings.Contains(a.Name, UnallocatedSuffix)
  502. }
  503. // IsUnmounted is true if the given Allocation represents unmounted volume costs.
  504. func (a *Allocation) IsUnmounted() bool {
  505. return strings.Contains(a.Name, UnmountedSuffix)
  506. }
  507. // Minutes returns the number of minutes the Allocation represents, as defined
  508. // by the difference between the end and start times.
  509. func (a *Allocation) Minutes() float64 {
  510. return a.End.Sub(a.Start).Minutes()
  511. }
  512. // Share adds the TotalCost of the given Allocation to the SharedCost of the
  513. // receiving Allocation. No Start, End, Window, or AllocationProperties are considered.
  514. // Neither Allocation is mutated; a new Allocation is always returned.
  515. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  516. if that == nil {
  517. return a.Clone(), nil
  518. }
  519. if a == nil {
  520. return nil, fmt.Errorf("cannot share with nil Allocation")
  521. }
  522. agg := a.Clone()
  523. agg.SharedCost += that.TotalCost()
  524. return agg, nil
  525. }
  526. // String represents the given Allocation as a string
  527. func (a *Allocation) String() string {
  528. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost())
  529. }
  530. func (a *Allocation) add(that *Allocation) {
  531. if a == nil {
  532. log.Warningf("Allocation.AggregateBy: trying to add a nil receiver")
  533. return
  534. }
  535. // Generate keys for each allocation to allow for special logic to set the controller
  536. // in the case of keys matching but controllers not matching.
  537. aggByForKey := []string{"cluster", "node", "namespace", "pod", "container"}
  538. leftKey := a.generateKey(aggByForKey, nil)
  539. rightKey := a.generateKey(aggByForKey, nil)
  540. leftProperties := a.Properties
  541. rightProperties := that.Properties
  542. // Preserve string properties that are matching between the two allocations
  543. a.Properties = a.Properties.Intersection(that.Properties)
  544. // Overwrite regular intersection logic for the controller name property in the
  545. // case that the Allocation keys are the same but the controllers are not.
  546. if leftKey == rightKey &&
  547. leftProperties != nil &&
  548. rightProperties != nil &&
  549. leftProperties.Controller != rightProperties.Controller {
  550. if leftProperties.Controller == "" {
  551. a.Properties.Controller = rightProperties.Controller
  552. } else if rightProperties.Controller == "" {
  553. a.Properties.Controller = leftProperties.Controller
  554. } else {
  555. controllers := []string{
  556. leftProperties.Controller,
  557. rightProperties.Controller,
  558. }
  559. sort.Strings(controllers)
  560. a.Properties.Controller = controllers[0]
  561. }
  562. }
  563. // Expand the window to encompass both Allocations
  564. a.Window = a.Window.Expand(that.Window)
  565. // Sum non-cumulative fields by turning them into cumulative, adding them,
  566. // and then converting them back into averages after minutes have been
  567. // combined (just below).
  568. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  569. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  570. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  571. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  572. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  573. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  574. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  575. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  576. // Expand Start and End to be the "max" of among the given Allocations
  577. if that.Start.Before(a.Start) {
  578. a.Start = that.Start
  579. }
  580. if that.End.After(a.End) {
  581. a.End = that.End
  582. }
  583. // Convert cumulative request and usage back into rates
  584. // TODO:TEST write a unit test that fails if this is done incorrectly
  585. if a.Minutes() > 0 {
  586. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  587. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  588. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  589. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  590. } else {
  591. a.CPUCoreRequestAverage = 0.0
  592. a.CPUCoreUsageAverage = 0.0
  593. a.RAMBytesRequestAverage = 0.0
  594. a.RAMBytesUsageAverage = 0.0
  595. }
  596. // Sum all cumulative resource fields
  597. a.CPUCoreHours += that.CPUCoreHours
  598. a.GPUHours += that.GPUHours
  599. a.RAMByteHours += that.RAMByteHours
  600. a.NetworkTransferBytes += that.NetworkTransferBytes
  601. a.NetworkReceiveBytes += that.NetworkReceiveBytes
  602. // Sum all cumulative cost fields
  603. a.CPUCost += that.CPUCost
  604. a.GPUCost += that.GPUCost
  605. a.RAMCost += that.RAMCost
  606. a.NetworkCost += that.NetworkCost
  607. a.LoadBalancerCost += that.LoadBalancerCost
  608. a.SharedCost += that.SharedCost
  609. a.ExternalCost += that.ExternalCost
  610. // Sum PVAllocations
  611. a.PVs = a.PVs.Add(that.PVs)
  612. // Sum all cumulative adjustment fields
  613. a.CPUCostAdjustment += that.CPUCostAdjustment
  614. a.RAMCostAdjustment += that.RAMCostAdjustment
  615. a.GPUCostAdjustment += that.GPUCostAdjustment
  616. a.PVCostAdjustment += that.PVCostAdjustment
  617. a.NetworkCostAdjustment += that.NetworkCostAdjustment
  618. a.LoadBalancerCostAdjustment += that.LoadBalancerCostAdjustment
  619. // Any data that is in a "raw allocation only" is not valid in any
  620. // sort of cumulative Allocation (like one that is added).
  621. a.RawAllocationOnly = nil
  622. }
  623. // AllocationSet stores a set of Allocations, each with a unique name, that share
  624. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  625. type AllocationSet struct {
  626. sync.RWMutex
  627. allocations map[string]*Allocation
  628. externalKeys map[string]bool
  629. idleKeys map[string]bool
  630. FromSource string // stores the name of the source used to compute the data
  631. Window Window
  632. Warnings []string
  633. Errors []string
  634. }
  635. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  636. // the given list of Allocations
  637. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  638. as := &AllocationSet{
  639. allocations: map[string]*Allocation{},
  640. externalKeys: map[string]bool{},
  641. idleKeys: map[string]bool{},
  642. Window: NewWindow(&start, &end),
  643. }
  644. for _, a := range allocs {
  645. as.Insert(a)
  646. }
  647. return as
  648. }
  649. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  650. // filtering results and sharing allocations. FilterFuncs are a list of match
  651. // functions such that, if any function fails, the allocation is ignored.
  652. // ShareFuncs are a list of match functions such that, if any function
  653. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  654. // simple flag for sharing idle resources.
  655. type AllocationAggregationOptions struct {
  656. FilterFuncs []AllocationMatchFunc
  657. IdleByNode bool
  658. LabelConfig *LabelConfig
  659. MergeUnallocated bool
  660. SharedHourlyCosts map[string]float64
  661. ShareFuncs []AllocationMatchFunc
  662. ShareIdle string
  663. ShareSplit string
  664. SplitIdle bool
  665. }
  666. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  667. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  668. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  669. func (as *AllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  670. // The order of operations for aggregating allocations is as follows:
  671. // 1. Partition external, idle, and shared allocations into separate sets.
  672. // Also, create the aggSet into which the results will be aggregated.
  673. // 2. Compute sharing coefficients for idle and shared resources
  674. // a) if idle allocation is to be shared, compute idle coefficients
  675. // b) if idle allocation is NOT shared, but filters are present, compute
  676. // idle filtration coefficients for the purpose of only returning the
  677. // portion of idle allocation that would have been shared with the
  678. // unfiltered results. (See unit tests 5.a,b,c)
  679. // c) generate shared allocation for then given shared overhead, which
  680. // must happen after (2a) and (2b)
  681. // d) if there are shared resources, compute share coefficients
  682. // 3. Drop any allocation that fails any of the filters
  683. // 4. Distribute idle allocations according to the idle coefficients
  684. // 5. Generate aggregation key and insert allocation into the output set
  685. // 6. If idle is shared and resources are shared, some idle might be shared
  686. // with a shared resource. Distribute that to the shared resources
  687. // prior to sharing them with the aggregated results.
  688. // 7. Apply idle filtration coefficients from step (2b)
  689. // 8. Distribute shared allocations according to the share coefficients.
  690. // 9. If there are external allocations that can be aggregated into
  691. // the output (i.e. they can be used to generate a valid key for
  692. // the given properties) then aggregate; otherwise... ignore them?
  693. // 10. If the merge idle option is enabled, merge any remaining idle
  694. // allocations into a single idle allocation
  695. if as.IsEmpty() {
  696. return nil
  697. }
  698. if options == nil {
  699. options = &AllocationAggregationOptions{}
  700. }
  701. if options.LabelConfig == nil {
  702. options.LabelConfig = NewLabelConfig()
  703. }
  704. // If aggregateBy is nil, we don't aggregate anything. On the other hand,
  705. // an empty slice implies that we should aggregate everything. See
  706. // generateKey for why that makes sense.
  707. shouldAggregate := aggregateBy != nil
  708. shouldFilter := len(options.FilterFuncs) > 0
  709. shouldShare := len(options.SharedHourlyCosts) > 0 || len(options.ShareFuncs) > 0
  710. if !shouldAggregate && !shouldFilter && !shouldShare {
  711. // There is nothing for AggregateBy to do, so simply return nil
  712. return nil
  713. }
  714. // aggSet will collect the aggregated allocations
  715. aggSet := &AllocationSet{
  716. Window: as.Window.Clone(),
  717. }
  718. // externalSet will collect external allocations
  719. externalSet := &AllocationSet{
  720. Window: as.Window.Clone(),
  721. }
  722. // idleSet will be shared among aggSet after initial aggregation
  723. // is complete
  724. idleSet := &AllocationSet{
  725. Window: as.Window.Clone(),
  726. }
  727. // shareSet will be shared among aggSet after initial aggregation
  728. // is complete
  729. shareSet := &AllocationSet{
  730. Window: as.Window.Clone(),
  731. }
  732. as.Lock()
  733. defer as.Unlock()
  734. // (1) Loop and find all of the external, idle, and shared allocations. Add
  735. // them to their respective sets, removing them from the set of allocations
  736. // to aggregate.
  737. for _, alloc := range as.allocations {
  738. // External allocations get aggregated post-hoc (see step 6) and do
  739. // not necessarily contain complete sets of properties, so they are
  740. // moved to a separate AllocationSet.
  741. if alloc.IsExternal() {
  742. delete(as.externalKeys, alloc.Name)
  743. delete(as.allocations, alloc.Name)
  744. externalSet.Insert(alloc)
  745. continue
  746. }
  747. // Idle allocations should be separated into idleSet if they are to be
  748. // shared later on. If they are not to be shared, then add them to the
  749. // aggSet like any other allocation.
  750. if alloc.IsIdle() {
  751. delete(as.idleKeys, alloc.Name)
  752. delete(as.allocations, alloc.Name)
  753. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  754. idleSet.Insert(alloc)
  755. } else {
  756. aggSet.Insert(alloc)
  757. }
  758. continue
  759. }
  760. // Shared allocations must be identified and separated prior to
  761. // aggregation and filtering. That is, if any of the ShareFuncs return
  762. // true for the allocation, then move it to shareSet.
  763. for _, sf := range options.ShareFuncs {
  764. if sf(alloc) {
  765. delete(as.idleKeys, alloc.Name)
  766. delete(as.allocations, alloc.Name)
  767. shareSet.Insert(alloc)
  768. break
  769. }
  770. }
  771. }
  772. // It's possible that no more un-shared, non-idle, non-external allocations
  773. // remain at this point. This always results in an emptySet, so return early.
  774. if len(as.allocations) == 0 {
  775. emptySet := &AllocationSet{
  776. Window: as.Window.Clone(),
  777. }
  778. as.allocations = emptySet.allocations
  779. return nil
  780. }
  781. // (2) In order to correctly share idle and shared costs, we first compute
  782. // sharing coefficients, which represent the proportion of each cost to
  783. // share with each allocation. Idle allocations are shared per-cluster or per-node,
  784. // per-allocation, and per-resource, while shared resources are shared per-
  785. // allocation only.
  786. //
  787. // For an idleCoefficient example, the entries:
  788. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  789. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  790. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  791. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  792. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  793. // RAM costs.
  794. //
  795. // For a shareCoefficient example, the entries:
  796. // [namespace2] = 0.666667
  797. // [__filtered__] = 0.333333
  798. // mean that the post-aggregation allocation "namespace2" will receive
  799. // 66.67% of the shared resource costs, while the remaining 33.33% will
  800. // be filtered out, as they were shared with allocations that did not pass
  801. // one of the given filters.
  802. //
  803. // In order to maintain stable results when multiple operations are being
  804. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  805. // coefficients are computed for the full set of allocations prior to
  806. // adding shared overhead and prior to applying filters.
  807. var err error
  808. // (2a) If there are idle costs to be shared, compute the coefficients for
  809. // sharing them among the non-idle, non-aggregated allocations (including
  810. // the shared allocations).
  811. var idleCoefficients map[string]map[string]map[string]float64
  812. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  813. idleCoefficients, err = computeIdleCoeffs(options, as, shareSet)
  814. if err != nil {
  815. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  816. return fmt.Errorf("error computing idle coefficients: %s", err)
  817. }
  818. }
  819. // (2b) If idle costs are not to be shared, but there are filters, then we
  820. // need to track the amount of each idle allocation to "filter" in order to
  821. // maintain parity with the results when idle is shared. That is, we want
  822. // to return only the idle costs that would have been shared with the given
  823. // results, even if the filter had not been applied.
  824. //
  825. // For example, consider these results from aggregating by namespace with
  826. // two clusters:
  827. //
  828. // namespace1: 25.00
  829. // namespace2: 30.00
  830. // namespace3: 15.00
  831. // idle: 30.00
  832. //
  833. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  834. // reduced by the amount that existed on cluster2. Then, idle must also be
  835. // reduced by the relevant amount:
  836. //
  837. // namespace1: 25.00
  838. // namespace2: 15.00
  839. // idle: 20.00
  840. //
  841. // Note that this can happen for any field, not just cluster, so we again
  842. // need to track this on a per-cluster or per-node, per-allocation, per-resource basis.
  843. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  844. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  845. idleFiltrationCoefficients, err = computeIdleCoeffs(options, as, shareSet)
  846. if err != nil {
  847. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  848. }
  849. }
  850. // (2c) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  851. // come after idle coefficients are computes so that allocations generated
  852. // by shared overhead do not skew the idle coefficient computation.
  853. for name, cost := range options.SharedHourlyCosts {
  854. if cost > 0.0 {
  855. hours := as.Resolution().Hours()
  856. // If set ends in the future, adjust hours accordingly
  857. diff := time.Since(as.End())
  858. if diff < 0.0 {
  859. hours += diff.Hours()
  860. }
  861. totalSharedCost := cost * hours
  862. shareSet.Insert(&Allocation{
  863. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  864. Start: as.Start(),
  865. End: as.End(),
  866. SharedCost: totalSharedCost,
  867. Properties: &AllocationProperties{Cluster: SharedSuffix}, // The allocation needs to belong to a cluster,but it really doesn't matter which one, so just make it clear.
  868. })
  869. }
  870. }
  871. // (2d) Compute share coefficients for shared resources. These are computed
  872. // after idle coefficients, and are computed for the aggregated allocations
  873. // of the main allocation set. See above for details and an example.
  874. var shareCoefficients map[string]float64
  875. if shareSet.Length() > 0 {
  876. shareCoefficients, err = computeShareCoeffs(aggregateBy, options, as)
  877. if err != nil {
  878. return fmt.Errorf("error computing share coefficients: %s", err)
  879. }
  880. }
  881. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  882. for _, alloc := range as.allocations {
  883. idleId, err := alloc.getIdleId(options)
  884. if err != nil {
  885. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  886. }
  887. skip := false
  888. // (3) If any of the filter funcs fail, immediately skip the allocation.
  889. for _, ff := range options.FilterFuncs {
  890. if !ff(alloc) {
  891. skip = true
  892. break
  893. }
  894. }
  895. if skip {
  896. // If we are tracking idle filtration coefficients, delete the
  897. // entry corresponding to the filtered allocation. (Deleting the
  898. // entry will result in that proportional amount being removed
  899. // from the idle allocation at the end of the process.)
  900. if idleFiltrationCoefficients != nil {
  901. if ifcc, ok := idleFiltrationCoefficients[idleId]; ok {
  902. delete(ifcc, alloc.Name)
  903. }
  904. }
  905. continue
  906. }
  907. // (4) Distribute idle allocations according to the idle coefficients
  908. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  909. // all idle allocations will be in the aggSet at this point, so idleSet
  910. // will be empty and we won't enter this block.
  911. if idleSet.Length() > 0 {
  912. // Distribute idle allocations by coefficient per-idleId, per-allocation
  913. for _, idleAlloc := range idleSet.allocations {
  914. // Only share idle if the idleId matches; i.e. the allocation
  915. // is from the same idleId as the idle costs
  916. iaidleId, err := idleAlloc.getIdleId(options)
  917. if err != nil {
  918. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  919. return err
  920. }
  921. if iaidleId != idleId {
  922. continue
  923. }
  924. // Make sure idle coefficients exist
  925. if _, ok := idleCoefficients[idleId]; !ok {
  926. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  927. continue
  928. }
  929. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  930. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  931. continue
  932. }
  933. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  934. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  935. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  936. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  937. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  938. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  939. alloc.CPUCost += idleCPUCost
  940. alloc.GPUCost += idleGPUCost
  941. alloc.RAMCost += idleRAMCost
  942. }
  943. }
  944. // (5) generate key to use for aggregation-by-key and allocation name
  945. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  946. alloc.Name = key
  947. if options.MergeUnallocated && alloc.IsUnallocated() {
  948. alloc.Name = UnallocatedSuffix
  949. }
  950. // Inserting the allocation with the generated key for a name will
  951. // perform the actual basic aggregation step.
  952. aggSet.Insert(alloc)
  953. }
  954. // (6) If idle is shared and resources are shared, it's possible that some
  955. // amount of idle cost will be shared with a shared resource. Distribute
  956. // that idle allocation, if it exists, to the respective shared allocations
  957. // before sharing with the aggregated allocations.
  958. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  959. for _, alloc := range shareSet.allocations {
  960. idleId, err := alloc.getIdleId(options)
  961. if err != nil {
  962. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  963. }
  964. // Distribute idle allocations by coefficient per-idleId, per-allocation
  965. for _, idleAlloc := range idleSet.allocations {
  966. // Only share idle if the idleId matches; i.e. the allocation
  967. // is from the same idleId as the idle costs
  968. iaidleId, _ := idleAlloc.getIdleId(options)
  969. if iaidleId != idleId {
  970. continue
  971. }
  972. // Make sure idle coefficients exist
  973. if _, ok := idleCoefficients[idleId]; !ok {
  974. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  975. continue
  976. }
  977. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  978. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  979. continue
  980. }
  981. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  982. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  983. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  984. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  985. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  986. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  987. alloc.CPUCost += idleCPUCost
  988. alloc.GPUCost += idleGPUCost
  989. alloc.RAMCost += idleRAMCost
  990. }
  991. }
  992. }
  993. // groupingIdleFiltrationCoeffs is used to track per-resource idle
  994. // coefficients on a cluster-by-cluster or node-by-node basis depending
  995. // on the IdleByNode option. It is, essentailly, an aggregation of
  996. // idleFiltrationCoefficients after they have been
  997. // filtered above (in step 3)
  998. var groupingIdleFiltrationCoeffs map[string]map[string]float64
  999. if idleFiltrationCoefficients != nil {
  1000. groupingIdleFiltrationCoeffs = map[string]map[string]float64{}
  1001. for idleId, m := range idleFiltrationCoefficients {
  1002. if _, ok := groupingIdleFiltrationCoeffs[idleId]; !ok {
  1003. groupingIdleFiltrationCoeffs[idleId] = map[string]float64{
  1004. "cpu": 0.0,
  1005. "gpu": 0.0,
  1006. "ram": 0.0,
  1007. }
  1008. }
  1009. for _, n := range m {
  1010. for resource, val := range n {
  1011. groupingIdleFiltrationCoeffs[idleId][resource] += val
  1012. }
  1013. }
  1014. }
  1015. }
  1016. // (7) If we have both un-shared idle allocations and idle filtration
  1017. // coefficients then apply those. See step (2b) for an example.
  1018. if len(aggSet.idleKeys) > 0 && groupingIdleFiltrationCoeffs != nil {
  1019. for idleKey := range aggSet.idleKeys {
  1020. idleAlloc := aggSet.Get(idleKey)
  1021. iaidleId, err := idleAlloc.getIdleId(options)
  1022. if err != nil {
  1023. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  1024. return err
  1025. }
  1026. if resourceCoeffs, ok := groupingIdleFiltrationCoeffs[iaidleId]; ok {
  1027. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  1028. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  1029. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  1030. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  1031. }
  1032. }
  1033. }
  1034. // (8) Distribute shared allocations according to the share coefficients.
  1035. if shareSet.Length() > 0 {
  1036. for _, alloc := range aggSet.allocations {
  1037. for _, sharedAlloc := range shareSet.allocations {
  1038. if _, ok := shareCoefficients[alloc.Name]; !ok {
  1039. if !alloc.IsIdle() {
  1040. log.Warningf("AllocationSet.AggregateBy: error getting share coefficienct for '%s'", alloc.Name)
  1041. }
  1042. continue
  1043. }
  1044. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  1045. }
  1046. }
  1047. }
  1048. // (9) Aggregate external allocations into aggregated allocations. This may
  1049. // not be possible for every external allocation, but attempt to find an
  1050. // exact key match, given each external allocation's proerties, and
  1051. // aggregate if an exact match is found.
  1052. for _, alloc := range externalSet.allocations {
  1053. skip := false
  1054. for _, ff := range options.FilterFuncs {
  1055. if !ff(alloc) {
  1056. skip = true
  1057. break
  1058. }
  1059. }
  1060. if !skip {
  1061. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  1062. alloc.Name = key
  1063. aggSet.Insert(alloc)
  1064. }
  1065. }
  1066. // (10) Combine all idle allocations into a single "__idle__" allocation
  1067. if !options.SplitIdle {
  1068. for _, idleAlloc := range aggSet.IdleAllocations() {
  1069. aggSet.Delete(idleAlloc.Name)
  1070. idleAlloc.Name = IdleSuffix
  1071. aggSet.Insert(idleAlloc)
  1072. }
  1073. }
  1074. as.allocations = aggSet.allocations
  1075. return nil
  1076. }
  1077. func computeShareCoeffs(aggregateBy []string, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  1078. // Compute coeffs by totalling per-allocation, then dividing by the total.
  1079. coeffs := map[string]float64{}
  1080. // Compute totals for all allocations
  1081. total := 0.0
  1082. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  1083. // counts each aggregation proportionally to its respective costs
  1084. shareType := options.ShareSplit
  1085. // Record allocation values first, then normalize by totals to get percentages
  1086. for _, alloc := range as.allocations {
  1087. if alloc.IsIdle() {
  1088. // Skip idle allocations in coefficient calculation
  1089. continue
  1090. }
  1091. if alloc.IsUnmounted() {
  1092. // Skip unmounted allocations in coefficient calculation
  1093. continue
  1094. }
  1095. // Determine the post-aggregation key under which the allocation will
  1096. // be shared.
  1097. name := alloc.generateKey(aggregateBy, options.LabelConfig)
  1098. // If the current allocation will be filtered out in step 3, contribute
  1099. // its share of the shared coefficient to a "__filtered__" bin, which
  1100. // will ultimately be dropped. This step ensures that the shared cost
  1101. // of a non-filtered allocation will be conserved even when the filter
  1102. // is removed. (Otherwise, all the shared cost will get redistributed
  1103. // over the unfiltered results, inflating their shared costs.)
  1104. filtered := false
  1105. for _, ff := range options.FilterFuncs {
  1106. if !ff(alloc) {
  1107. filtered = true
  1108. break
  1109. }
  1110. }
  1111. if filtered {
  1112. name = "__filtered__"
  1113. }
  1114. if shareType == ShareEven {
  1115. // Even distribution is not additive - set to 1.0 for everything
  1116. coeffs[name] = 1.0
  1117. // Total for even distribution is always the number of coefficients
  1118. total = float64(len(coeffs))
  1119. } else {
  1120. // Both are additive for weighted distribution, where each
  1121. // cumulative coefficient will be divided by the total.
  1122. coeffs[name] += alloc.TotalCost()
  1123. total += alloc.TotalCost()
  1124. }
  1125. }
  1126. // Normalize coefficients by totals
  1127. for a := range coeffs {
  1128. if coeffs[a] > 0 && total > 0 {
  1129. coeffs[a] /= total
  1130. } else {
  1131. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  1132. coeffs[a] = 0.0
  1133. }
  1134. }
  1135. return coeffs, nil
  1136. }
  1137. func computeIdleCoeffs(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, error) {
  1138. types := []string{"cpu", "gpu", "ram"}
  1139. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1140. coeffs := map[string]map[string]map[string]float64{}
  1141. // Compute totals per resource for CPU, GPU, RAM, and PV
  1142. totals := map[string]map[string]float64{}
  1143. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  1144. // counts each allocation proportionally to its respective costs
  1145. shareType := options.ShareIdle
  1146. // Record allocation values first, then normalize by totals to get percentages
  1147. for _, alloc := range as.allocations {
  1148. if alloc.IsIdle() {
  1149. // Skip idle allocations in coefficient calculation
  1150. continue
  1151. }
  1152. idleId, err := alloc.getIdleId(options)
  1153. if err != nil {
  1154. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  1155. }
  1156. // get the name key for the allocation
  1157. name := alloc.Name
  1158. // Create key based tables if they don't exist
  1159. if _, ok := coeffs[idleId]; !ok {
  1160. coeffs[idleId] = map[string]map[string]float64{}
  1161. }
  1162. if _, ok := totals[idleId]; !ok {
  1163. totals[idleId] = map[string]float64{}
  1164. }
  1165. if _, ok := coeffs[idleId][name]; !ok {
  1166. coeffs[idleId][name] = map[string]float64{}
  1167. }
  1168. if shareType == ShareEven {
  1169. for _, r := range types {
  1170. // Not additive - hard set to 1.0
  1171. coeffs[idleId][name][r] = 1.0
  1172. // totals are additive
  1173. totals[idleId][r] += 1.0
  1174. }
  1175. } else {
  1176. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1177. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1178. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1179. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1180. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1181. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1182. }
  1183. }
  1184. // Do the same for shared allocations
  1185. for _, alloc := range shareSet.allocations {
  1186. if alloc.IsIdle() {
  1187. // Skip idle allocations in coefficient calculation
  1188. continue
  1189. }
  1190. // idleId will be providerId or cluster
  1191. idleId, err := alloc.getIdleId(options)
  1192. if err != nil {
  1193. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  1194. }
  1195. // get the name key for the allocation
  1196. name := alloc.Name
  1197. // Create idleId based tables if they don't exist
  1198. if _, ok := coeffs[idleId]; !ok {
  1199. coeffs[idleId] = map[string]map[string]float64{}
  1200. }
  1201. if _, ok := totals[idleId]; !ok {
  1202. totals[idleId] = map[string]float64{}
  1203. }
  1204. if _, ok := coeffs[idleId][name]; !ok {
  1205. coeffs[idleId][name] = map[string]float64{}
  1206. }
  1207. if shareType == ShareEven {
  1208. for _, r := range types {
  1209. // Not additive - hard set to 1.0
  1210. coeffs[idleId][name][r] = 1.0
  1211. // totals are additive
  1212. totals[idleId][r] += 1.0
  1213. }
  1214. } else {
  1215. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1216. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1217. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1218. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1219. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1220. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1221. }
  1222. }
  1223. // Normalize coefficients by totals
  1224. for c := range coeffs {
  1225. for a := range coeffs[c] {
  1226. for _, r := range types {
  1227. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  1228. coeffs[c][a][r] /= totals[c][r]
  1229. }
  1230. }
  1231. }
  1232. }
  1233. return coeffs, nil
  1234. }
  1235. // getIdleId returns the providerId or cluster of an Allocation depending on the IdleByNode
  1236. // option in the AllocationAggregationOptions and an error if the respective field is missing
  1237. func (a *Allocation) getIdleId(options *AllocationAggregationOptions) (string, error) {
  1238. var idleId string
  1239. if options.IdleByNode {
  1240. // Key allocations to ProviderId to match against node
  1241. idleId = a.Properties.ProviderID
  1242. if idleId == "" {
  1243. return idleId, fmt.Errorf("ProviderId is not set")
  1244. }
  1245. } else {
  1246. // key the allocations by cluster id
  1247. idleId = a.Properties.Cluster
  1248. if idleId == "" {
  1249. return idleId, fmt.Errorf("ClusterProp is not set")
  1250. }
  1251. }
  1252. return idleId, nil
  1253. }
  1254. func (a *Allocation) generateKey(aggregateBy []string, labelConfig *LabelConfig) string {
  1255. if a == nil {
  1256. return ""
  1257. }
  1258. if labelConfig == nil {
  1259. labelConfig = NewLabelConfig()
  1260. }
  1261. // Names will ultimately be joined into a single name, which uniquely
  1262. // identifies allocations.
  1263. names := []string{}
  1264. for _, agg := range aggregateBy {
  1265. switch true {
  1266. case agg == AllocationClusterProp:
  1267. names = append(names, a.Properties.Cluster)
  1268. case agg == AllocationNodeProp:
  1269. names = append(names, a.Properties.Node)
  1270. case agg == AllocationNamespaceProp:
  1271. names = append(names, a.Properties.Namespace)
  1272. case agg == AllocationControllerKindProp:
  1273. controllerKind := a.Properties.ControllerKind
  1274. if controllerKind == "" {
  1275. // Indicate that allocation has no controller
  1276. controllerKind = UnallocatedSuffix
  1277. }
  1278. names = append(names, controllerKind)
  1279. case agg == AllocationDaemonSetProp || agg == AllocationStatefulSetProp || agg == AllocationDeploymentProp || agg == AllocationJobProp:
  1280. controller := a.Properties.Controller
  1281. if agg != a.Properties.ControllerKind || controller == "" {
  1282. // The allocation does not have the specified controller kind
  1283. controller = UnallocatedSuffix
  1284. }
  1285. names = append(names, controller)
  1286. case agg == AllocationControllerProp:
  1287. controller := a.Properties.Controller
  1288. if controller == "" {
  1289. // Indicate that allocation has no controller
  1290. controller = UnallocatedSuffix
  1291. } else if a.Properties.ControllerKind != "" {
  1292. controller = fmt.Sprintf("%s:%s", a.Properties.ControllerKind, controller)
  1293. }
  1294. names = append(names, controller)
  1295. case agg == AllocationPodProp:
  1296. names = append(names, a.Properties.Pod)
  1297. case agg == AllocationContainerProp:
  1298. names = append(names, a.Properties.Container)
  1299. case agg == AllocationServiceProp:
  1300. services := a.Properties.Services
  1301. if len(services) == 0 {
  1302. // Indicate that allocation has no services
  1303. names = append(names, UnallocatedSuffix)
  1304. } else {
  1305. // This just uses the first service
  1306. for _, service := range services {
  1307. names = append(names, service)
  1308. break
  1309. }
  1310. }
  1311. case strings.HasPrefix(agg, "label:"):
  1312. labels := a.Properties.Labels
  1313. if labels == nil {
  1314. names = append(names, UnallocatedSuffix)
  1315. } else {
  1316. labelName := labelConfig.Sanitize(strings.TrimPrefix(agg, "label:"))
  1317. if labelValue, ok := labels[labelName]; ok {
  1318. names = append(names, fmt.Sprintf("%s=%s", labelName, labelValue))
  1319. } else {
  1320. names = append(names, UnallocatedSuffix)
  1321. }
  1322. }
  1323. case strings.HasPrefix(agg, "annotation:"):
  1324. annotations := a.Properties.Annotations
  1325. if annotations == nil {
  1326. names = append(names, UnallocatedSuffix)
  1327. } else {
  1328. annotationName := labelConfig.Sanitize(strings.TrimPrefix(agg, "annotation:"))
  1329. if annotationValue, ok := annotations[annotationName]; ok {
  1330. names = append(names, fmt.Sprintf("%s=%s", annotationName, annotationValue))
  1331. } else {
  1332. names = append(names, UnallocatedSuffix)
  1333. }
  1334. }
  1335. case agg == AllocationDepartmentProp:
  1336. labels := a.Properties.Labels
  1337. if labels == nil {
  1338. names = append(names, UnallocatedSuffix)
  1339. } else {
  1340. labelNames := strings.Split(labelConfig.DepartmentLabel, ",")
  1341. for _, labelName := range labelNames {
  1342. labelName = labelConfig.Sanitize(labelName)
  1343. if labelValue, ok := labels[labelName]; ok {
  1344. names = append(names, labelValue)
  1345. } else {
  1346. names = append(names, UnallocatedSuffix)
  1347. }
  1348. }
  1349. }
  1350. case agg == AllocationEnvironmentProp:
  1351. labels := a.Properties.Labels
  1352. if labels == nil {
  1353. names = append(names, UnallocatedSuffix)
  1354. } else {
  1355. labelNames := strings.Split(labelConfig.EnvironmentLabel, ",")
  1356. for _, labelName := range labelNames {
  1357. labelName = labelConfig.Sanitize(labelName)
  1358. if labelValue, ok := labels[labelName]; ok {
  1359. names = append(names, labelValue)
  1360. } else {
  1361. names = append(names, UnallocatedSuffix)
  1362. }
  1363. }
  1364. }
  1365. case agg == AllocationOwnerProp:
  1366. labels := a.Properties.Labels
  1367. if labels == nil {
  1368. names = append(names, UnallocatedSuffix)
  1369. } else {
  1370. labelNames := strings.Split(labelConfig.OwnerLabel, ",")
  1371. for _, labelName := range labelNames {
  1372. labelName = labelConfig.Sanitize(labelName)
  1373. if labelValue, ok := labels[labelName]; ok {
  1374. names = append(names, labelValue)
  1375. } else {
  1376. names = append(names, UnallocatedSuffix)
  1377. }
  1378. }
  1379. }
  1380. case agg == AllocationProductProp:
  1381. labels := a.Properties.Labels
  1382. if labels == nil {
  1383. names = append(names, UnallocatedSuffix)
  1384. } else {
  1385. labelNames := strings.Split(labelConfig.ProductLabel, ",")
  1386. for _, labelName := range labelNames {
  1387. labelName = labelConfig.Sanitize(labelName)
  1388. if labelValue, ok := labels[labelName]; ok {
  1389. names = append(names, labelValue)
  1390. } else {
  1391. names = append(names, UnallocatedSuffix)
  1392. }
  1393. }
  1394. }
  1395. case agg == AllocationTeamProp:
  1396. labels := a.Properties.Labels
  1397. if labels == nil {
  1398. names = append(names, UnallocatedSuffix)
  1399. } else {
  1400. labelNames := strings.Split(labelConfig.TeamLabel, ",")
  1401. for _, labelName := range labelNames {
  1402. labelName = labelConfig.Sanitize(labelName)
  1403. if labelValue, ok := labels[labelName]; ok {
  1404. names = append(names, labelValue)
  1405. } else {
  1406. names = append(names, UnallocatedSuffix)
  1407. }
  1408. }
  1409. }
  1410. default:
  1411. // This case should never be reached, as input up until this point
  1412. // should be checked and rejected if invalid. But if we do get a
  1413. // value we don't recognize, log a warning.
  1414. log.Warningf("AggregateBy: illegal aggregation parameter: %s", agg)
  1415. }
  1416. }
  1417. return strings.Join(names, "/")
  1418. }
  1419. // Clone returns a new AllocationSet with a deep copy of the given
  1420. // AllocationSet's allocations.
  1421. func (as *AllocationSet) Clone() *AllocationSet {
  1422. if as == nil {
  1423. return nil
  1424. }
  1425. as.RLock()
  1426. defer as.RUnlock()
  1427. allocs := map[string]*Allocation{}
  1428. for k, v := range as.allocations {
  1429. allocs[k] = v.Clone()
  1430. }
  1431. externalKeys := map[string]bool{}
  1432. for k, v := range as.externalKeys {
  1433. externalKeys[k] = v
  1434. }
  1435. idleKeys := map[string]bool{}
  1436. for k, v := range as.idleKeys {
  1437. idleKeys[k] = v
  1438. }
  1439. return &AllocationSet{
  1440. allocations: allocs,
  1441. externalKeys: externalKeys,
  1442. idleKeys: idleKeys,
  1443. Window: as.Window.Clone(),
  1444. }
  1445. }
  1446. // ComputeIdleAllocations computes the idle allocations for the AllocationSet,
  1447. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1448. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1449. // considered for idle allocation. If the Nodes have adjustments, then apply
  1450. // the adjustments proportionally to each of the resources so that total
  1451. // allocation with idle reflects the adjusted node costs. One idle allocation
  1452. // per-cluster will be computed and returned, keyed by cluster_id.
  1453. func (as *AllocationSet) ComputeIdleAllocations(assetSet *AssetSet) (map[string]*Allocation, error) {
  1454. if as == nil {
  1455. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1456. }
  1457. if assetSet == nil {
  1458. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1459. }
  1460. if !as.Window.Equal(assetSet.Window) {
  1461. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1462. }
  1463. window := as.Window
  1464. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1465. // cluster-to-{cpu|gpu|ram}-to-cost.
  1466. assetClusterResourceCosts := map[string]map[string]float64{}
  1467. assetSet.Each(func(key string, a Asset) {
  1468. if node, ok := a.(*Node); ok {
  1469. if _, ok := assetClusterResourceCosts[node.Properties().Cluster]; !ok {
  1470. assetClusterResourceCosts[node.Properties().Cluster] = map[string]float64{}
  1471. }
  1472. // adjustmentRate is used to scale resource costs proportionally
  1473. // by the adjustment. This is necessary because we only get one
  1474. // adjustment per Node, not one per-resource-per-Node.
  1475. //
  1476. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1477. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1478. // e.g. total cost = $150, adjustment = $50 => 1.5
  1479. adjustmentRate := 1.0
  1480. if node.TotalCost()-node.Adjustment() == 0 {
  1481. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1482. // the entire node cost and we should make everything 0
  1483. // without dividing by 0.
  1484. adjustmentRate = 0.0
  1485. log.DedupedWarningf(5, "Compute Idle Allocations: Node Cost Adjusted to $0.00 for %s", node.properties.Name)
  1486. } else if node.Adjustment() != 0.0 {
  1487. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1488. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1489. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1490. }
  1491. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1492. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1493. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1494. assetClusterResourceCosts[node.Properties().Cluster]["cpu"] += cpuCost
  1495. assetClusterResourceCosts[node.Properties().Cluster]["gpu"] += gpuCost
  1496. assetClusterResourceCosts[node.Properties().Cluster]["ram"] += ramCost
  1497. }
  1498. })
  1499. // Determine start, end on a per-cluster basis
  1500. clusterStarts := map[string]time.Time{}
  1501. clusterEnds := map[string]time.Time{}
  1502. // Subtract allocated costs from asset costs, leaving only the remaining
  1503. // idle costs.
  1504. as.Each(func(name string, a *Allocation) {
  1505. cluster := a.Properties.Cluster
  1506. if cluster == "" {
  1507. // Failed to find allocation's cluster
  1508. return
  1509. }
  1510. if _, ok := assetClusterResourceCosts[cluster]; !ok {
  1511. // Failed to find assets for allocation's cluster
  1512. return
  1513. }
  1514. // Set cluster (start, end) if they are either not currently set,
  1515. // or if the detected (start, end) of the current allocation falls
  1516. // before or after, respectively, the current values.
  1517. if s, ok := clusterStarts[cluster]; !ok || a.Start.Before(s) {
  1518. clusterStarts[cluster] = a.Start
  1519. }
  1520. if e, ok := clusterEnds[cluster]; !ok || a.End.After(e) {
  1521. clusterEnds[cluster] = a.End
  1522. }
  1523. assetClusterResourceCosts[cluster]["cpu"] -= a.CPUTotalCost()
  1524. assetClusterResourceCosts[cluster]["gpu"] -= a.GPUTotalCost()
  1525. assetClusterResourceCosts[cluster]["ram"] -= a.RAMTotalCost()
  1526. })
  1527. // Turn remaining un-allocated asset costs into idle allocations
  1528. idleAllocs := map[string]*Allocation{}
  1529. for cluster, resources := range assetClusterResourceCosts {
  1530. // Default start and end to the (start, end) of the given window, but
  1531. // use the actual, detected (start, end) pair if they are available.
  1532. start := *window.Start()
  1533. if s, ok := clusterStarts[cluster]; ok && window.Contains(s) {
  1534. start = s
  1535. }
  1536. end := *window.End()
  1537. if e, ok := clusterEnds[cluster]; ok && window.Contains(e) {
  1538. end = e
  1539. }
  1540. idleAlloc := &Allocation{
  1541. Name: fmt.Sprintf("%s/%s", cluster, IdleSuffix),
  1542. Window: window.Clone(),
  1543. Properties: &AllocationProperties{Cluster: cluster},
  1544. Start: start,
  1545. End: end,
  1546. CPUCost: resources["cpu"],
  1547. GPUCost: resources["gpu"],
  1548. RAMCost: resources["ram"],
  1549. }
  1550. // Do not continue if multiple idle allocations are computed for a
  1551. // single cluster.
  1552. if _, ok := idleAllocs[cluster]; ok {
  1553. return nil, fmt.Errorf("duplicate idle allocations for cluster %s", cluster)
  1554. }
  1555. idleAllocs[cluster] = idleAlloc
  1556. }
  1557. return idleAllocs, nil
  1558. }
  1559. // ComputeIdleAllocationsByNode computes the idle allocations for the AllocationSet,
  1560. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1561. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1562. // considered for idle allocation. If the Nodes have adjustments, then apply
  1563. // the adjustments proportionally to each of the resources so that total
  1564. // allocation with idle reflects the adjusted node costs. One idle allocation
  1565. // per-node will be computed and returned, keyed by cluster_id.
  1566. func (as *AllocationSet) ComputeIdleAllocationsByNode(assetSet *AssetSet) (map[string]*Allocation, error) {
  1567. if as == nil {
  1568. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1569. }
  1570. if assetSet == nil {
  1571. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1572. }
  1573. if !as.Window.Equal(assetSet.Window) {
  1574. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1575. }
  1576. window := as.Window
  1577. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1578. // cluster-to-{cpu|gpu|ram}-to-cost.
  1579. assetNodeResourceCosts := map[string]map[string]float64{}
  1580. nodesByProviderId := map[string]*Node{}
  1581. assetSet.Each(func(key string, a Asset) {
  1582. if node, ok := a.(*Node); ok {
  1583. if _, ok := assetNodeResourceCosts[node.Properties().ProviderID]; ok || node.Properties().ProviderID == "" {
  1584. log.DedupedWarningf(5, "Compute Idle Allocations By Node: Node missing providerId: %s", node.properties.Name)
  1585. return
  1586. }
  1587. nodesByProviderId[node.Properties().ProviderID] = node
  1588. assetNodeResourceCosts[node.Properties().ProviderID] = map[string]float64{}
  1589. // adjustmentRate is used to scale resource costs proportionally
  1590. // by the adjustment. This is necessary because we only get one
  1591. // adjustment per Node, not one per-resource-per-Node.
  1592. //
  1593. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1594. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1595. // e.g. total cost = $150, adjustment = $50 => 1.5
  1596. adjustmentRate := 1.0
  1597. if node.TotalCost()-node.Adjustment() == 0 {
  1598. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1599. // the entire node cost and we should make everything 0
  1600. // without dividing by 0.
  1601. adjustmentRate = 0.0
  1602. log.DedupedWarningf(5, "Compute Idle Allocations: Node Cost Adjusted to $0.00 for %s", node.properties.Name)
  1603. } else if node.Adjustment() != 0.0 {
  1604. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1605. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1606. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1607. }
  1608. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1609. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1610. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1611. assetNodeResourceCosts[node.Properties().ProviderID]["cpu"] += cpuCost
  1612. assetNodeResourceCosts[node.Properties().ProviderID]["gpu"] += gpuCost
  1613. assetNodeResourceCosts[node.Properties().ProviderID]["ram"] += ramCost
  1614. }
  1615. })
  1616. // Determine start, end on a per-cluster basis
  1617. nodeStarts := map[string]time.Time{}
  1618. nodeEnds := map[string]time.Time{}
  1619. // Subtract allocated costs from asset costs, leaving only the remaining
  1620. // idle costs.
  1621. as.Each(func(name string, a *Allocation) {
  1622. providerId := a.Properties.ProviderID
  1623. if providerId == "" {
  1624. // Failed to find allocation's node
  1625. log.DedupedWarningf(5, "Compute Idle Allocations By Node: Allocation missing providerId: %s", a.Name)
  1626. return
  1627. }
  1628. if _, ok := assetNodeResourceCosts[providerId]; !ok {
  1629. // Failed to find assets for allocation's node
  1630. return
  1631. }
  1632. // Set cluster (start, end) if they are either not currently set,
  1633. // or if the detected (start, end) of the current allocation falls
  1634. // before or after, respectively, the current values.
  1635. if s, ok := nodeStarts[providerId]; !ok || a.Start.Before(s) {
  1636. nodeStarts[providerId] = a.Start
  1637. }
  1638. if e, ok := nodeEnds[providerId]; !ok || a.End.After(e) {
  1639. nodeEnds[providerId] = a.End
  1640. }
  1641. assetNodeResourceCosts[providerId]["cpu"] -= a.CPUTotalCost()
  1642. assetNodeResourceCosts[providerId]["gpu"] -= a.GPUTotalCost()
  1643. assetNodeResourceCosts[providerId]["ram"] -= a.RAMTotalCost()
  1644. })
  1645. // Turn remaining un-allocated asset costs into idle allocations
  1646. idleAllocs := map[string]*Allocation{}
  1647. for providerId, resources := range assetNodeResourceCosts {
  1648. // Default start and end to the (start, end) of the given window, but
  1649. // use the actual, detected (start, end) pair if they are available.
  1650. start := *window.Start()
  1651. if s, ok := nodeStarts[providerId]; ok && window.Contains(s) {
  1652. start = s
  1653. }
  1654. end := *window.End()
  1655. if e, ok := nodeEnds[providerId]; ok && window.Contains(e) {
  1656. end = e
  1657. }
  1658. node := nodesByProviderId[providerId]
  1659. idleAlloc := &Allocation{
  1660. Name: fmt.Sprintf("%s/%s", node.properties.Name, IdleSuffix),
  1661. Window: window.Clone(),
  1662. Properties: &AllocationProperties{
  1663. Cluster: node.properties.Cluster,
  1664. Node: node.properties.Name,
  1665. ProviderID: providerId,
  1666. },
  1667. Start: start,
  1668. End: end,
  1669. CPUCost: resources["cpu"],
  1670. GPUCost: resources["gpu"],
  1671. RAMCost: resources["ram"],
  1672. }
  1673. // Do not continue if multiple idle allocations are computed for a
  1674. // single node.
  1675. if _, ok := idleAllocs[providerId]; ok {
  1676. return nil, fmt.Errorf("duplicate idle allocations for node Provider ID: %s", providerId)
  1677. }
  1678. idleAllocs[providerId] = idleAlloc
  1679. }
  1680. return idleAllocs, nil
  1681. }
  1682. // Delete removes the allocation with the given name from the set
  1683. func (as *AllocationSet) Delete(name string) {
  1684. if as == nil {
  1685. return
  1686. }
  1687. as.Lock()
  1688. defer as.Unlock()
  1689. delete(as.externalKeys, name)
  1690. delete(as.idleKeys, name)
  1691. delete(as.allocations, name)
  1692. }
  1693. // Each invokes the given function for each Allocation in the set
  1694. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  1695. if as == nil {
  1696. return
  1697. }
  1698. for k, a := range as.allocations {
  1699. f(k, a)
  1700. }
  1701. }
  1702. // End returns the End time of the AllocationSet window
  1703. func (as *AllocationSet) End() time.Time {
  1704. if as == nil {
  1705. log.Warningf("AllocationSet: calling End on nil AllocationSet")
  1706. return time.Unix(0, 0)
  1707. }
  1708. if as.Window.End() == nil {
  1709. log.Warningf("AllocationSet: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  1710. return time.Unix(0, 0)
  1711. }
  1712. return *as.Window.End()
  1713. }
  1714. // Get returns the Allocation at the given key in the AllocationSet
  1715. func (as *AllocationSet) Get(key string) *Allocation {
  1716. as.RLock()
  1717. defer as.RUnlock()
  1718. if alloc, ok := as.allocations[key]; ok {
  1719. return alloc
  1720. }
  1721. return nil
  1722. }
  1723. // ExternalAllocations returns a map of the external allocations in the set.
  1724. // Returns clones of the actual Allocations, so mutability is not a problem.
  1725. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1726. externals := map[string]*Allocation{}
  1727. if as.IsEmpty() {
  1728. return externals
  1729. }
  1730. as.RLock()
  1731. defer as.RUnlock()
  1732. for key := range as.externalKeys {
  1733. if alloc, ok := as.allocations[key]; ok {
  1734. externals[key] = alloc.Clone()
  1735. }
  1736. }
  1737. return externals
  1738. }
  1739. // ExternalCost returns the total aggregated external costs of the set
  1740. func (as *AllocationSet) ExternalCost() float64 {
  1741. if as.IsEmpty() {
  1742. return 0.0
  1743. }
  1744. as.RLock()
  1745. defer as.RUnlock()
  1746. externalCost := 0.0
  1747. for _, alloc := range as.allocations {
  1748. externalCost += alloc.ExternalCost
  1749. }
  1750. return externalCost
  1751. }
  1752. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1753. // Returns clones of the actual Allocations, so mutability is not a problem.
  1754. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1755. idles := map[string]*Allocation{}
  1756. if as.IsEmpty() {
  1757. return idles
  1758. }
  1759. as.RLock()
  1760. defer as.RUnlock()
  1761. for key := range as.idleKeys {
  1762. if alloc, ok := as.allocations[key]; ok {
  1763. idles[key] = alloc.Clone()
  1764. }
  1765. }
  1766. return idles
  1767. }
  1768. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1769. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1770. // there is no existing entry, one is created. Nil error response indicates success.
  1771. func (as *AllocationSet) Insert(that *Allocation) error {
  1772. return as.insert(that)
  1773. }
  1774. func (as *AllocationSet) insert(that *Allocation) error {
  1775. if as == nil {
  1776. return fmt.Errorf("cannot insert into nil AllocationSet")
  1777. }
  1778. as.Lock()
  1779. defer as.Unlock()
  1780. if as.allocations == nil {
  1781. as.allocations = map[string]*Allocation{}
  1782. }
  1783. if as.externalKeys == nil {
  1784. as.externalKeys = map[string]bool{}
  1785. }
  1786. if as.idleKeys == nil {
  1787. as.idleKeys = map[string]bool{}
  1788. }
  1789. // Add the given Allocation to the existing entry, if there is one;
  1790. // otherwise just set directly into allocations
  1791. if _, ok := as.allocations[that.Name]; !ok {
  1792. as.allocations[that.Name] = that
  1793. } else {
  1794. as.allocations[that.Name].add(that)
  1795. }
  1796. // If the given Allocation is an external one, record that
  1797. if that.IsExternal() {
  1798. as.externalKeys[that.Name] = true
  1799. }
  1800. // If the given Allocation is an idle one, record that
  1801. if that.IsIdle() {
  1802. as.idleKeys[that.Name] = true
  1803. }
  1804. return nil
  1805. }
  1806. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  1807. // zero allocations.
  1808. func (as *AllocationSet) IsEmpty() bool {
  1809. if as == nil || len(as.allocations) == 0 {
  1810. return true
  1811. }
  1812. as.RLock()
  1813. defer as.RUnlock()
  1814. return as.allocations == nil || len(as.allocations) == 0
  1815. }
  1816. // Length returns the number of Allocations in the set
  1817. func (as *AllocationSet) Length() int {
  1818. if as == nil {
  1819. return 0
  1820. }
  1821. as.RLock()
  1822. defer as.RUnlock()
  1823. return len(as.allocations)
  1824. }
  1825. // Map clones and returns a map of the AllocationSet's Allocations
  1826. func (as *AllocationSet) Map() map[string]*Allocation {
  1827. if as.IsEmpty() {
  1828. return map[string]*Allocation{}
  1829. }
  1830. return as.Clone().allocations
  1831. }
  1832. // MarshalJSON JSON-encodes the AllocationSet
  1833. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  1834. as.RLock()
  1835. defer as.RUnlock()
  1836. return json.Marshal(as.allocations)
  1837. }
  1838. // Resolution returns the AllocationSet's window duration
  1839. func (as *AllocationSet) Resolution() time.Duration {
  1840. return as.Window.Duration()
  1841. }
  1842. // Set uses the given Allocation to overwrite the existing entry in the
  1843. // AllocationSet under the Allocation's name.
  1844. func (as *AllocationSet) Set(alloc *Allocation) error {
  1845. if as.IsEmpty() {
  1846. as.Lock()
  1847. as.allocations = map[string]*Allocation{}
  1848. as.externalKeys = map[string]bool{}
  1849. as.idleKeys = map[string]bool{}
  1850. as.Unlock()
  1851. }
  1852. as.Lock()
  1853. defer as.Unlock()
  1854. as.allocations[alloc.Name] = alloc
  1855. // If the given Allocation is an external one, record that
  1856. if alloc.IsExternal() {
  1857. as.externalKeys[alloc.Name] = true
  1858. }
  1859. // If the given Allocation is an idle one, record that
  1860. if alloc.IsIdle() {
  1861. as.idleKeys[alloc.Name] = true
  1862. }
  1863. return nil
  1864. }
  1865. // Start returns the Start time of the AllocationSet window
  1866. func (as *AllocationSet) Start() time.Time {
  1867. if as == nil {
  1868. log.Warningf("AllocationSet: calling Start on nil AllocationSet")
  1869. return time.Unix(0, 0)
  1870. }
  1871. if as.Window.Start() == nil {
  1872. log.Warningf("AllocationSet: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1873. return time.Unix(0, 0)
  1874. }
  1875. return *as.Window.Start()
  1876. }
  1877. // String represents the given Allocation as a string
  1878. func (as *AllocationSet) String() string {
  1879. if as == nil {
  1880. return "<nil>"
  1881. }
  1882. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1883. as.Length(), as.Window, as.TotalCost())
  1884. }
  1885. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1886. func (as *AllocationSet) TotalCost() float64 {
  1887. if as.IsEmpty() {
  1888. return 0.0
  1889. }
  1890. as.RLock()
  1891. defer as.RUnlock()
  1892. tc := 0.0
  1893. for _, a := range as.allocations {
  1894. tc += a.TotalCost()
  1895. }
  1896. return tc
  1897. }
  1898. // UTCOffset returns the AllocationSet's configured UTCOffset.
  1899. func (as *AllocationSet) UTCOffset() time.Duration {
  1900. _, zone := as.Start().Zone()
  1901. return time.Duration(zone) * time.Second
  1902. }
  1903. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1904. if as.IsEmpty() {
  1905. return that.Clone(), nil
  1906. }
  1907. if that.IsEmpty() {
  1908. return as.Clone(), nil
  1909. }
  1910. // Set start, end to min(start), max(end)
  1911. start := as.Start()
  1912. end := as.End()
  1913. if that.Start().Before(start) {
  1914. start = that.Start()
  1915. }
  1916. if that.End().After(end) {
  1917. end = that.End()
  1918. }
  1919. acc := NewAllocationSet(start, end)
  1920. as.RLock()
  1921. defer as.RUnlock()
  1922. that.RLock()
  1923. defer that.RUnlock()
  1924. for _, alloc := range as.allocations {
  1925. err := acc.insert(alloc)
  1926. if err != nil {
  1927. return nil, err
  1928. }
  1929. }
  1930. for _, alloc := range that.allocations {
  1931. err := acc.insert(alloc)
  1932. if err != nil {
  1933. return nil, err
  1934. }
  1935. }
  1936. return acc, nil
  1937. }
  1938. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  1939. // be used such that the AllocationSets held are consecutive and coherent with
  1940. // respect to using the same aggregation properties, UTC offset, and
  1941. // resolution. However these rules are not necessarily enforced, so use wisely.
  1942. type AllocationSetRange struct {
  1943. sync.RWMutex
  1944. allocations []*AllocationSet
  1945. FromStore string // stores the name of the store used to retrieve the data
  1946. }
  1947. // NewAllocationSetRange instantiates a new range composed of the given
  1948. // AllocationSets in the order provided.
  1949. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1950. return &AllocationSetRange{
  1951. allocations: allocs,
  1952. }
  1953. }
  1954. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1955. // AllocationSet for the entire range.
  1956. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1957. var allocSet *AllocationSet
  1958. var err error
  1959. asr.RLock()
  1960. defer asr.RUnlock()
  1961. for _, as := range asr.allocations {
  1962. allocSet, err = allocSet.accumulate(as)
  1963. if err != nil {
  1964. return nil, err
  1965. }
  1966. }
  1967. return allocSet, nil
  1968. }
  1969. // TODO accumulate into lower-resolution chunks of the given resolution
  1970. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1971. // AggregateBy aggregates each AllocationSet in the range by the given
  1972. // properties and options.
  1973. func (asr *AllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  1974. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1975. asr.Lock()
  1976. defer asr.Unlock()
  1977. for _, as := range asr.allocations {
  1978. err := as.AggregateBy(aggregateBy, options)
  1979. if err != nil {
  1980. return err
  1981. }
  1982. aggRange.allocations = append(aggRange.allocations, as)
  1983. }
  1984. asr.allocations = aggRange.allocations
  1985. return nil
  1986. }
  1987. // Append appends the given AllocationSet to the end of the range. It does not
  1988. // validate whether or not that violates window continuity.
  1989. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1990. asr.Lock()
  1991. defer asr.Unlock()
  1992. asr.allocations = append(asr.allocations, that)
  1993. }
  1994. // Each invokes the given function for each AllocationSet in the range
  1995. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1996. if asr == nil {
  1997. return
  1998. }
  1999. for i, as := range asr.allocations {
  2000. f(i, as)
  2001. }
  2002. }
  2003. // Get retrieves the AllocationSet at the given index of the range.
  2004. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  2005. if i < 0 || i >= len(asr.allocations) {
  2006. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  2007. }
  2008. asr.RLock()
  2009. defer asr.RUnlock()
  2010. return asr.allocations[i], nil
  2011. }
  2012. // InsertRange merges the given AllocationSetRange into the receiving one by
  2013. // lining up sets with matching windows, then inserting each allocation from
  2014. // the given ASR into the respective set in the receiving ASR. If the given
  2015. // ASR contains an AllocationSet from a window that does not exist in the
  2016. // receiving ASR, then an error is returned. However, the given ASR does not
  2017. // need to cover the full range of the receiver.
  2018. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  2019. if asr == nil {
  2020. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  2021. }
  2022. // keys maps window to index in asr
  2023. keys := map[string]int{}
  2024. asr.Each(func(i int, as *AllocationSet) {
  2025. if as == nil {
  2026. return
  2027. }
  2028. keys[as.Window.String()] = i
  2029. })
  2030. // Nothing to merge, so simply return
  2031. if len(keys) == 0 {
  2032. return nil
  2033. }
  2034. var err error
  2035. that.Each(func(j int, thatAS *AllocationSet) {
  2036. if thatAS == nil || err != nil {
  2037. return
  2038. }
  2039. // Find matching AllocationSet in asr
  2040. i, ok := keys[thatAS.Window.String()]
  2041. if !ok {
  2042. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  2043. return
  2044. }
  2045. as, err := asr.Get(i)
  2046. if err != nil {
  2047. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  2048. return
  2049. }
  2050. // Insert each Allocation from the given set
  2051. thatAS.Each(func(k string, alloc *Allocation) {
  2052. err = as.Insert(alloc)
  2053. if err != nil {
  2054. err = fmt.Errorf("error inserting allocation: %s", err)
  2055. return
  2056. }
  2057. })
  2058. })
  2059. // err might be nil
  2060. return err
  2061. }
  2062. // Length returns the length of the range, which is zero if nil
  2063. func (asr *AllocationSetRange) Length() int {
  2064. if asr == nil || asr.allocations == nil {
  2065. return 0
  2066. }
  2067. asr.RLock()
  2068. defer asr.RUnlock()
  2069. return len(asr.allocations)
  2070. }
  2071. // MarshalJSON JSON-encodes the range
  2072. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  2073. asr.RLock()
  2074. defer asr.RUnlock()
  2075. return json.Marshal(asr.allocations)
  2076. }
  2077. // Slice copies the underlying slice of AllocationSets, maintaining order,
  2078. // and returns the copied slice.
  2079. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  2080. if asr == nil || asr.allocations == nil {
  2081. return nil
  2082. }
  2083. asr.RLock()
  2084. defer asr.RUnlock()
  2085. copy := []*AllocationSet{}
  2086. for _, as := range asr.allocations {
  2087. copy = append(copy, as.Clone())
  2088. }
  2089. return copy
  2090. }
  2091. // String represents the given AllocationSetRange as a string
  2092. func (asr *AllocationSetRange) String() string {
  2093. if asr == nil {
  2094. return "<nil>"
  2095. }
  2096. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  2097. }
  2098. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  2099. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  2100. // are sets with conflicting UTCOffsets (just returns the first).
  2101. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  2102. if asr.Length() == 0 {
  2103. return 0
  2104. }
  2105. as, err := asr.Get(0)
  2106. if err != nil {
  2107. return 0
  2108. }
  2109. return as.UTCOffset()
  2110. }
  2111. // Window returns the full window that the AllocationSetRange spans, from the
  2112. // start of the first AllocationSet to the end of the last one.
  2113. func (asr *AllocationSetRange) Window() Window {
  2114. if asr == nil || asr.Length() == 0 {
  2115. return NewWindow(nil, nil)
  2116. }
  2117. start := asr.allocations[0].Start()
  2118. end := asr.allocations[asr.Length()-1].End()
  2119. return NewWindow(&start, &end)
  2120. }
  2121. // Start returns the earliest start of all Allocations in the AllocationSetRange.
  2122. // It returns an error if there are no allocations.
  2123. func (asr *AllocationSetRange) Start() (time.Time, error) {
  2124. start := time.Time{}
  2125. firstStartNotSet := true
  2126. asr.Each(func(i int, as *AllocationSet) {
  2127. as.Each(func(s string, a *Allocation) {
  2128. if firstStartNotSet {
  2129. start = a.Start
  2130. firstStartNotSet = false
  2131. }
  2132. if a.Start.Before(start) {
  2133. start = a.Start
  2134. }
  2135. })
  2136. })
  2137. if firstStartNotSet {
  2138. return start, fmt.Errorf("had no data to compute a start from")
  2139. }
  2140. return start, nil
  2141. }
  2142. // End returns the latest end of all Allocations in the AllocationSetRange.
  2143. // It returns an error if there are no allocations.
  2144. func (asr *AllocationSetRange) End() (time.Time, error) {
  2145. end := time.Time{}
  2146. firstEndNotSet := true
  2147. asr.Each(func(i int, as *AllocationSet) {
  2148. as.Each(func(s string, a *Allocation) {
  2149. if firstEndNotSet {
  2150. end = a.End
  2151. firstEndNotSet = false
  2152. }
  2153. if a.End.After(end) {
  2154. end = a.End
  2155. }
  2156. })
  2157. })
  2158. if firstEndNotSet {
  2159. return end, fmt.Errorf("had no data to compute an end from")
  2160. }
  2161. return end, nil
  2162. }
  2163. // Minutes returns the duration, in minutes, between the earliest start
  2164. // and the latest end of all allocations in the AllocationSetRange.
  2165. func (asr *AllocationSetRange) Minutes() float64 {
  2166. start, err := asr.Start()
  2167. if err != nil {
  2168. return 0
  2169. }
  2170. end, err := asr.End()
  2171. if err != nil {
  2172. return 0
  2173. }
  2174. duration := end.Sub(start)
  2175. return duration.Minutes()
  2176. }