allocation.go 82 KB

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