allocation.go 84 KB

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