allocation.go 69 KB

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