allocation.go 88 KB

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