allocation.go 73 KB

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