allocation.go 79 KB

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