allocation.go 110 KB

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