allocation.go 109 KB

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