allocation.go 70 KB

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