allocation.go 109 KB

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