allocation.go 83 KB

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