allocation.go 110 KB

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