allocation.go 83 KB

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