allocation.go 70 KB

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