allocation.go 110 KB

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