allocation.go 110 KB

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