allocation.go 72 KB

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