allocation.go 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575
  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 := PVAllocations{}
  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. return a.CPUTotalCost() + a.GPUTotalCost() + a.RAMTotalCost() + a.PVTotalCost() + a.NetworkTotalCost() + a.LBTotalCost() + a.SharedTotalCost() + a.ExternalCost
  320. }
  321. // CPUTotalCost calculates total CPU cost of Allocation including adjustment
  322. func (a *Allocation) CPUTotalCost() float64 {
  323. return a.CPUCost + a.CPUCostAdjustment
  324. }
  325. // GPUTotalCost calculates total GPU cost of Allocation including adjustment
  326. func (a *Allocation) GPUTotalCost() float64 {
  327. return a.GPUCost + a.GPUCostAdjustment
  328. }
  329. // RAMTotalCost calculates total RAM cost of Allocation including adjustment
  330. func (a *Allocation) RAMTotalCost() float64 {
  331. return a.RAMCost + a.RAMCostAdjustment
  332. }
  333. // PVTotalCost calculates total PV cost of Allocation including adjustment
  334. func (a *Allocation) PVTotalCost() float64 {
  335. return a.PVCost() + a.PVCostAdjustment
  336. }
  337. // NetworkTotalCost calculates total Network cost of Allocation including adjustment
  338. func (a *Allocation) NetworkTotalCost() float64 {
  339. return a.NetworkCost + a.NetworkCostAdjustment
  340. }
  341. // LBTotalCost calculates total LB cost of Allocation including adjustment
  342. func (a *Allocation) LBTotalCost() float64 {
  343. return a.LoadBalancerCost + a.LoadBalancerCostAdjustment
  344. }
  345. // SharedTotalCost calculates total shared cost of Allocation including adjustment
  346. func (a *Allocation) SharedTotalCost() float64 {
  347. return a.SharedCost
  348. }
  349. // PVCost calculate cumulative cost of all PVs that Allocation is attached to
  350. func (a *Allocation) PVCost() float64 {
  351. cost := 0.0
  352. for _, pv := range a.PVs {
  353. cost += pv.Cost
  354. }
  355. return cost
  356. }
  357. // PVByteHours calculate cumulative ByteHours of all PVs that Allocation is attached to
  358. func (a *Allocation) PVByteHours() float64 {
  359. byteHours := 0.0
  360. for _, pv := range a.PVs {
  361. byteHours += pv.ByteHours
  362. }
  363. return byteHours
  364. }
  365. // CPUEfficiency is the ratio of usage to request. If there is no request and
  366. // no usage or cost, then efficiency is zero. If there is no request, but there
  367. // is usage or cost, then efficiency is 100%.
  368. func (a *Allocation) CPUEfficiency() float64 {
  369. if a.CPUCoreRequestAverage > 0 {
  370. return a.CPUCoreUsageAverage / a.CPUCoreRequestAverage
  371. }
  372. if a.CPUCoreUsageAverage == 0.0 || a.CPUCost == 0.0 {
  373. return 0.0
  374. }
  375. return 1.0
  376. }
  377. // RAMEfficiency is the ratio of usage to request. If there is no request and
  378. // no usage or cost, then efficiency is zero. If there is no request, but there
  379. // is usage or cost, then efficiency is 100%.
  380. func (a *Allocation) RAMEfficiency() float64 {
  381. if a.RAMBytesRequestAverage > 0 {
  382. return a.RAMBytesUsageAverage / a.RAMBytesRequestAverage
  383. }
  384. if a.RAMBytesUsageAverage == 0.0 || a.RAMCost == 0.0 {
  385. return 0.0
  386. }
  387. return 1.0
  388. }
  389. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  390. // there is no cost at all, then efficiency is zero.
  391. func (a *Allocation) TotalEfficiency() float64 {
  392. if a.RAMTotalCost()+a.CPUTotalCost() > 0 {
  393. ramCostEff := a.RAMEfficiency() * a.RAMTotalCost()
  394. cpuCostEff := a.CPUEfficiency() * a.CPUTotalCost()
  395. return (ramCostEff + cpuCostEff) / (a.CPUTotalCost() + a.RAMTotalCost())
  396. }
  397. return 0.0
  398. }
  399. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  400. func (a *Allocation) CPUCores() float64 {
  401. if a.Minutes() <= 0.0 {
  402. return 0.0
  403. }
  404. return a.CPUCoreHours / (a.Minutes() / 60.0)
  405. }
  406. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  407. func (a *Allocation) RAMBytes() float64 {
  408. if a.Minutes() <= 0.0 {
  409. return 0.0
  410. }
  411. return a.RAMByteHours / (a.Minutes() / 60.0)
  412. }
  413. // GPUs converts the Allocation's GPUHours into average GPUs
  414. func (a *Allocation) GPUs() float64 {
  415. if a.Minutes() <= 0.0 {
  416. return 0.0
  417. }
  418. return a.GPUHours / (a.Minutes() / 60.0)
  419. }
  420. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  421. func (a *Allocation) PVBytes() float64 {
  422. if a.Minutes() <= 0.0 {
  423. return 0.0
  424. }
  425. return a.PVByteHours() / (a.Minutes() / 60.0)
  426. }
  427. // ResetAdjustments sets all cost adjustment fields to zero
  428. func (a *Allocation) ResetAdjustments() {
  429. a.CPUCostAdjustment = 0.0
  430. a.GPUCostAdjustment = 0.0
  431. a.RAMCostAdjustment = 0.0
  432. a.PVCostAdjustment = 0.0
  433. a.NetworkCostAdjustment = 0.0
  434. a.LoadBalancerCostAdjustment = 0.0
  435. }
  436. // MarshalJSON implements json.Marshaler interface
  437. func (a *Allocation) MarshalJSON() ([]byte, error) {
  438. buffer := bytes.NewBufferString("{")
  439. jsonEncodeString(buffer, "name", a.Name, ",")
  440. jsonEncode(buffer, "properties", a.Properties, ",")
  441. jsonEncode(buffer, "window", a.Window, ",")
  442. jsonEncodeString(buffer, "start", a.Start.Format(time.RFC3339), ",")
  443. jsonEncodeString(buffer, "end", a.End.Format(time.RFC3339), ",")
  444. jsonEncodeFloat64(buffer, "minutes", a.Minutes(), ",")
  445. jsonEncodeFloat64(buffer, "cpuCores", a.CPUCores(), ",")
  446. jsonEncodeFloat64(buffer, "cpuCoreRequestAverage", a.CPUCoreRequestAverage, ",")
  447. jsonEncodeFloat64(buffer, "cpuCoreUsageAverage", a.CPUCoreUsageAverage, ",")
  448. jsonEncodeFloat64(buffer, "cpuCoreHours", a.CPUCoreHours, ",")
  449. jsonEncodeFloat64(buffer, "cpuCost", a.CPUCost, ",")
  450. jsonEncodeFloat64(buffer, "cpuCostAdjustment", a.CPUCostAdjustment, ",")
  451. jsonEncodeFloat64(buffer, "cpuEfficiency", a.CPUEfficiency(), ",")
  452. jsonEncodeFloat64(buffer, "gpuCount", a.GPUs(), ",")
  453. jsonEncodeFloat64(buffer, "gpuHours", a.GPUHours, ",")
  454. jsonEncodeFloat64(buffer, "gpuCost", a.GPUCost, ",")
  455. jsonEncodeFloat64(buffer, "gpuCostAdjustment", a.GPUCostAdjustment, ",")
  456. jsonEncodeFloat64(buffer, "networkTransferBytes", a.NetworkTransferBytes, ",")
  457. jsonEncodeFloat64(buffer, "networkReceiveBytes", a.NetworkReceiveBytes, ",")
  458. jsonEncodeFloat64(buffer, "networkCost", a.NetworkCost, ",")
  459. jsonEncodeFloat64(buffer, "networkCostAdjustment", a.NetworkCostAdjustment, ",")
  460. jsonEncodeFloat64(buffer, "loadBalancerCost", a.LoadBalancerCost, ",")
  461. jsonEncodeFloat64(buffer, "loadBalancerCostAdjustment", a.LoadBalancerCostAdjustment, ",")
  462. jsonEncodeFloat64(buffer, "pvBytes", a.PVBytes(), ",")
  463. jsonEncodeFloat64(buffer, "pvByteHours", a.PVByteHours(), ",")
  464. jsonEncodeFloat64(buffer, "pvCost", a.PVCost(), ",")
  465. jsonEncode(buffer, "pvs", a.PVs, ",") // Todo Sean: this does not work properly
  466. jsonEncodeFloat64(buffer, "pvCostAdjustment", a.PVCostAdjustment, ",")
  467. jsonEncodeFloat64(buffer, "ramBytes", a.RAMBytes(), ",")
  468. jsonEncodeFloat64(buffer, "ramByteRequestAverage", a.RAMBytesRequestAverage, ",")
  469. jsonEncodeFloat64(buffer, "ramByteUsageAverage", a.RAMBytesUsageAverage, ",")
  470. jsonEncodeFloat64(buffer, "ramByteHours", a.RAMByteHours, ",")
  471. jsonEncodeFloat64(buffer, "ramCost", a.RAMCost, ",")
  472. jsonEncodeFloat64(buffer, "ramCostAdjustment", a.RAMCostAdjustment, ",")
  473. jsonEncodeFloat64(buffer, "ramEfficiency", a.RAMEfficiency(), ",")
  474. jsonEncodeFloat64(buffer, "sharedCost", a.SharedCost, ",")
  475. jsonEncodeFloat64(buffer, "externalCost", a.ExternalCost, ",")
  476. jsonEncodeFloat64(buffer, "totalCost", a.TotalCost(), ",")
  477. jsonEncodeFloat64(buffer, "totalEfficiency", a.TotalEfficiency(), ",")
  478. jsonEncode(buffer, "rawAllocationOnly", a.RawAllocationOnly, "")
  479. buffer.WriteString("}")
  480. return buffer.Bytes(), nil
  481. }
  482. // Resolution returns the duration of time covered by the Allocation
  483. func (a *Allocation) Resolution() time.Duration {
  484. return a.End.Sub(a.Start)
  485. }
  486. // IsAggregated is true if the given Allocation has been aggregated, which we
  487. // define by a lack of AllocationProperties.
  488. func (a *Allocation) IsAggregated() bool {
  489. return a == nil || a.Properties == nil
  490. }
  491. // IsExternal is true if the given Allocation represents external costs.
  492. func (a *Allocation) IsExternal() bool {
  493. return strings.Contains(a.Name, ExternalSuffix)
  494. }
  495. // IsIdle is true if the given Allocation represents idle costs.
  496. func (a *Allocation) IsIdle() bool {
  497. return strings.Contains(a.Name, IdleSuffix)
  498. }
  499. // IsUnallocated is true if the given Allocation represents unallocated costs.
  500. func (a *Allocation) IsUnallocated() bool {
  501. return strings.Contains(a.Name, UnallocatedSuffix)
  502. }
  503. // IsUnmounted is true if the given Allocation represents unmounted volume costs.
  504. func (a *Allocation) IsUnmounted() bool {
  505. return strings.Contains(a.Name, UnmountedSuffix)
  506. }
  507. // Minutes returns the number of minutes the Allocation represents, as defined
  508. // by the difference between the end and start times.
  509. func (a *Allocation) Minutes() float64 {
  510. return a.End.Sub(a.Start).Minutes()
  511. }
  512. // Share adds the TotalCost of the given Allocation to the SharedCost of the
  513. // receiving Allocation. No Start, End, Window, or AllocationProperties are considered.
  514. // Neither Allocation is mutated; a new Allocation is always returned.
  515. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  516. if that == nil {
  517. return a.Clone(), nil
  518. }
  519. if a == nil {
  520. return nil, fmt.Errorf("cannot share with nil Allocation")
  521. }
  522. agg := a.Clone()
  523. agg.SharedCost += that.TotalCost()
  524. return agg, nil
  525. }
  526. // String represents the given Allocation as a string
  527. func (a *Allocation) String() string {
  528. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost())
  529. }
  530. func (a *Allocation) add(that *Allocation) {
  531. if a == nil {
  532. log.Warningf("Allocation.AggregateBy: trying to add a nil receiver")
  533. return
  534. }
  535. // Generate keys for each allocation to allow for special logic to set the controller
  536. // in the case of keys matching but controllers not matching.
  537. aggByForKey := []string{"cluster", "node", "namespace", "pod", "container"}
  538. leftKey := a.generateKey(aggByForKey, nil)
  539. rightKey := a.generateKey(aggByForKey, nil)
  540. leftProperties := a.Properties
  541. rightProperties := that.Properties
  542. // Preserve string properties that are matching between the two allocations
  543. a.Properties = a.Properties.Intersection(that.Properties)
  544. // Overwrite regular intersection logic for the controller name property in the
  545. // case that the Allocation keys are the same but the controllers are not.
  546. if leftKey == rightKey &&
  547. leftProperties != nil &&
  548. rightProperties != nil &&
  549. leftProperties.Controller != rightProperties.Controller {
  550. if leftProperties.Controller == "" {
  551. a.Properties.Controller = rightProperties.Controller
  552. } else if rightProperties.Controller == "" {
  553. a.Properties.Controller = leftProperties.Controller
  554. } else {
  555. controllers := []string{
  556. leftProperties.Controller,
  557. rightProperties.Controller,
  558. }
  559. sort.Strings(controllers)
  560. a.Properties.Controller = controllers[0]
  561. }
  562. }
  563. // Expand the window to encompass both Allocations
  564. a.Window = a.Window.Expand(that.Window)
  565. // Sum non-cumulative fields by turning them into cumulative, adding them,
  566. // and then converting them back into averages after minutes have been
  567. // combined (just below).
  568. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  569. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  570. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  571. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  572. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  573. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  574. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  575. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  576. // Expand Start and End to be the "max" of among the given Allocations
  577. if that.Start.Before(a.Start) {
  578. a.Start = that.Start
  579. }
  580. if that.End.After(a.End) {
  581. a.End = that.End
  582. }
  583. // Convert cumulative request and usage back into rates
  584. // TODO:TEST write a unit test that fails if this is done incorrectly
  585. if a.Minutes() > 0 {
  586. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  587. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  588. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  589. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  590. } else {
  591. a.CPUCoreRequestAverage = 0.0
  592. a.CPUCoreUsageAverage = 0.0
  593. a.RAMBytesRequestAverage = 0.0
  594. a.RAMBytesUsageAverage = 0.0
  595. }
  596. // Sum all cumulative resource fields
  597. a.CPUCoreHours += that.CPUCoreHours
  598. a.GPUHours += that.GPUHours
  599. a.RAMByteHours += that.RAMByteHours
  600. a.NetworkTransferBytes += that.NetworkTransferBytes
  601. a.NetworkReceiveBytes += that.NetworkReceiveBytes
  602. // Sum all cumulative cost fields
  603. a.CPUCost += that.CPUCost
  604. a.GPUCost += that.GPUCost
  605. a.RAMCost += that.RAMCost
  606. a.NetworkCost += that.NetworkCost
  607. a.LoadBalancerCost += that.LoadBalancerCost
  608. a.SharedCost += that.SharedCost
  609. a.ExternalCost += that.ExternalCost
  610. // Sum PVAllocations
  611. a.PVs = a.PVs.Add(that.PVs)
  612. // Sum all cumulative adjustment fields
  613. a.CPUCostAdjustment += that.CPUCostAdjustment
  614. a.RAMCostAdjustment += that.RAMCostAdjustment
  615. a.GPUCostAdjustment += that.GPUCostAdjustment
  616. a.PVCostAdjustment += that.PVCostAdjustment
  617. a.NetworkCostAdjustment += that.NetworkCostAdjustment
  618. a.LoadBalancerCostAdjustment += that.LoadBalancerCostAdjustment
  619. // Any data that is in a "raw allocation only" is not valid in any
  620. // sort of cumulative Allocation (like one that is added).
  621. a.RawAllocationOnly = nil
  622. }
  623. // AllocationSet stores a set of Allocations, each with a unique name, that share
  624. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  625. type AllocationSet struct {
  626. sync.RWMutex
  627. allocations map[string]*Allocation
  628. externalKeys map[string]bool
  629. idleKeys map[string]bool
  630. FromSource string // stores the name of the source used to compute the data
  631. Window Window
  632. Warnings []string
  633. Errors []string
  634. }
  635. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  636. // the given list of Allocations
  637. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  638. as := &AllocationSet{
  639. allocations: map[string]*Allocation{},
  640. externalKeys: map[string]bool{},
  641. idleKeys: map[string]bool{},
  642. Window: NewWindow(&start, &end),
  643. }
  644. for _, a := range allocs {
  645. as.Insert(a)
  646. }
  647. return as
  648. }
  649. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  650. // filtering results and sharing allocations. FilterFuncs are a list of match
  651. // functions such that, if any function fails, the allocation is ignored.
  652. // ShareFuncs are a list of match functions such that, if any function
  653. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  654. // simple flag for sharing idle resources.
  655. type AllocationAggregationOptions struct {
  656. FilterFuncs []AllocationMatchFunc
  657. IdleByNode bool
  658. LabelConfig *LabelConfig
  659. MergeUnallocated bool
  660. SharedHourlyCosts map[string]float64
  661. ShareFuncs []AllocationMatchFunc
  662. ShareIdle string
  663. ShareSplit string
  664. SplitIdle bool
  665. }
  666. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  667. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  668. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  669. func (as *AllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  670. // The order of operations for aggregating allocations is as follows:
  671. // 1. Partition external, idle, and shared allocations into separate sets.
  672. // Also, create the aggSet into which the results will be aggregated.
  673. // 2. Compute sharing coefficients for idle and shared resources
  674. // a) if idle allocation is to be shared, compute idle coefficients
  675. // b) if idle allocation is NOT shared, but filters are present, compute
  676. // idle filtration coefficients for the purpose of only returning the
  677. // portion of idle allocation that would have been shared with the
  678. // unfiltered results. (See unit tests 5.a,b,c)
  679. // c) generate shared allocation for then given shared overhead, which
  680. // must happen after (2a) and (2b)
  681. // d) if there are shared resources, compute share coefficients
  682. // 3. Drop any allocation that fails any of the filters
  683. // 4. Distribute idle allocations according to the idle coefficients
  684. // 5. Generate aggregation key and insert allocation into the output set
  685. // 6. If idle is shared and resources are shared, some idle might be shared
  686. // with a shared resource. Distribute that to the shared resources
  687. // prior to sharing them with the aggregated results.
  688. // 7. Apply idle filtration coefficients from step (2b)
  689. // 8. Distribute shared allocations according to the share coefficients.
  690. // 9. If there are external allocations that can be aggregated into
  691. // the output (i.e. they can be used to generate a valid key for
  692. // the given properties) then aggregate; otherwise... ignore them?
  693. // 10. If the merge idle option is enabled, merge any remaining idle
  694. // allocations into a single idle allocation. If there was any idle
  695. // whose costs were not distributed because there was no usage of a
  696. // specific resource type, re-add the idle to the aggregation with
  697. // only that type.
  698. if as.IsEmpty() {
  699. return nil
  700. }
  701. if options == nil {
  702. options = &AllocationAggregationOptions{}
  703. }
  704. if options.LabelConfig == nil {
  705. options.LabelConfig = NewLabelConfig()
  706. }
  707. var undistributedIdleMap map[string]bool
  708. // If aggregateBy is nil, we don't aggregate anything. On the other hand,
  709. // an empty slice implies that we should aggregate everything. See
  710. // generateKey for why that makes sense.
  711. shouldAggregate := aggregateBy != nil
  712. shouldFilter := len(options.FilterFuncs) > 0
  713. shouldShare := len(options.SharedHourlyCosts) > 0 || len(options.ShareFuncs) > 0
  714. if !shouldAggregate && !shouldFilter && !shouldShare {
  715. // There is nothing for AggregateBy to do, so simply return nil
  716. return nil
  717. }
  718. // aggSet will collect the aggregated allocations
  719. aggSet := &AllocationSet{
  720. Window: as.Window.Clone(),
  721. }
  722. // externalSet will collect external allocations
  723. externalSet := &AllocationSet{
  724. Window: as.Window.Clone(),
  725. }
  726. // idleSet will be shared among aggSet after initial aggregation
  727. // is complete
  728. idleSet := &AllocationSet{
  729. Window: as.Window.Clone(),
  730. }
  731. // shareSet will be shared among aggSet after initial aggregation
  732. // is complete
  733. shareSet := &AllocationSet{
  734. Window: as.Window.Clone(),
  735. }
  736. as.Lock()
  737. defer as.Unlock()
  738. // (1) Loop and find all of the external, idle, and shared allocations. Add
  739. // them to their respective sets, removing them from the set of allocations
  740. // to aggregate.
  741. for _, alloc := range as.allocations {
  742. // External allocations get aggregated post-hoc (see step 6) and do
  743. // not necessarily contain complete sets of properties, so they are
  744. // moved to a separate AllocationSet.
  745. if alloc.IsExternal() {
  746. delete(as.externalKeys, alloc.Name)
  747. delete(as.allocations, alloc.Name)
  748. externalSet.Insert(alloc)
  749. continue
  750. }
  751. // Idle allocations should be separated into idleSet if they are to be
  752. // shared later on. If they are not to be shared, then add them to the
  753. // aggSet like any other allocation.
  754. if alloc.IsIdle() {
  755. delete(as.idleKeys, alloc.Name)
  756. delete(as.allocations, alloc.Name)
  757. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  758. idleSet.Insert(alloc)
  759. } else {
  760. aggSet.Insert(alloc)
  761. }
  762. continue
  763. }
  764. // Shared allocations must be identified and separated prior to
  765. // aggregation and filtering. That is, if any of the ShareFuncs return
  766. // true for the allocation, then move it to shareSet.
  767. for _, sf := range options.ShareFuncs {
  768. if sf(alloc) {
  769. delete(as.idleKeys, alloc.Name)
  770. delete(as.allocations, alloc.Name)
  771. shareSet.Insert(alloc)
  772. break
  773. }
  774. }
  775. }
  776. // It's possible that no more un-shared, non-idle, non-external allocations
  777. // remain at this point. This always results in an emptySet, so return early.
  778. if len(as.allocations) == 0 {
  779. emptySet := &AllocationSet{
  780. Window: as.Window.Clone(),
  781. }
  782. as.allocations = emptySet.allocations
  783. return nil
  784. }
  785. // (2) In order to correctly share idle and shared costs, we first compute
  786. // sharing coefficients, which represent the proportion of each cost to
  787. // share with each allocation. Idle allocations are shared per-cluster or per-node,
  788. // per-allocation, and per-resource, while shared resources are shared per-
  789. // allocation only.
  790. //
  791. // For an idleCoefficient example, the entries:
  792. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  793. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  794. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  795. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  796. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  797. // RAM costs.
  798. //
  799. // For a shareCoefficient example, the entries:
  800. // [namespace2] = 0.666667
  801. // [__filtered__] = 0.333333
  802. // mean that the post-aggregation allocation "namespace2" will receive
  803. // 66.67% of the shared resource costs, while the remaining 33.33% will
  804. // be filtered out, as they were shared with allocations that did not pass
  805. // one of the given filters.
  806. //
  807. // In order to maintain stable results when multiple operations are being
  808. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  809. // coefficients are computed for the full set of allocations prior to
  810. // adding shared overhead and prior to applying filters.
  811. var err error
  812. // (2a) If there are idle costs to be shared, compute the coefficients for
  813. // sharing them among the non-idle, non-aggregated allocations (including
  814. // the shared allocations).
  815. var idleCoefficients map[string]map[string]map[string]float64
  816. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  817. idleCoefficients, undistributedIdleMap, err = computeIdleCoeffs(options, as, shareSet)
  818. if err != nil {
  819. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  820. return fmt.Errorf("error computing idle coefficients: %s", err)
  821. }
  822. }
  823. // (2b) If idle costs are not to be shared, but there are filters, then we
  824. // need to track the amount of each idle allocation to "filter" in order to
  825. // maintain parity with the results when idle is shared. That is, we want
  826. // to return only the idle costs that would have been shared with the given
  827. // results, even if the filter had not been applied.
  828. //
  829. // For example, consider these results from aggregating by namespace with
  830. // two clusters:
  831. //
  832. // namespace1: 25.00
  833. // namespace2: 30.00
  834. // namespace3: 15.00
  835. // idle: 30.00
  836. //
  837. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  838. // reduced by the amount that existed on cluster2. Then, idle must also be
  839. // reduced by the relevant amount:
  840. //
  841. // namespace1: 25.00
  842. // namespace2: 15.00
  843. // idle: 20.00
  844. //
  845. // Note that this can happen for any field, not just cluster, so we again
  846. // need to track this on a per-cluster or per-node, per-allocation, per-resource basis.
  847. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  848. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  849. idleFiltrationCoefficients, _, err = computeIdleCoeffs(options, as, shareSet)
  850. if err != nil {
  851. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  852. }
  853. }
  854. // (2c) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  855. // come after idle coefficients are computes so that allocations generated
  856. // by shared overhead do not skew the idle coefficient computation.
  857. for name, cost := range options.SharedHourlyCosts {
  858. if cost > 0.0 {
  859. hours := as.Resolution().Hours()
  860. // If set ends in the future, adjust hours accordingly
  861. diff := time.Since(as.End())
  862. if diff < 0.0 {
  863. hours += diff.Hours()
  864. }
  865. totalSharedCost := cost * hours
  866. shareSet.Insert(&Allocation{
  867. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  868. Start: as.Start(),
  869. End: as.End(),
  870. SharedCost: totalSharedCost,
  871. 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.
  872. })
  873. }
  874. }
  875. // (2d) Compute share coefficients for shared resources. These are computed
  876. // after idle coefficients, and are computed for the aggregated allocations
  877. // of the main allocation set. See above for details and an example.
  878. var shareCoefficients map[string]float64
  879. if shareSet.Length() > 0 {
  880. shareCoefficients, err = computeShareCoeffs(aggregateBy, options, as)
  881. if err != nil {
  882. return fmt.Errorf("error computing share coefficients: %s", err)
  883. }
  884. }
  885. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  886. for _, alloc := range as.allocations {
  887. idleId, err := alloc.getIdleId(options)
  888. if err != nil {
  889. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  890. }
  891. skip := false
  892. // (3) If any of the filter funcs fail, immediately skip the allocation.
  893. for _, ff := range options.FilterFuncs {
  894. if !ff(alloc) {
  895. skip = true
  896. break
  897. }
  898. }
  899. if skip {
  900. // If we are tracking idle filtration coefficients, delete the
  901. // entry corresponding to the filtered allocation. (Deleting the
  902. // entry will result in that proportional amount being removed
  903. // from the idle allocation at the end of the process.)
  904. if idleFiltrationCoefficients != nil {
  905. if ifcc, ok := idleFiltrationCoefficients[idleId]; ok {
  906. delete(ifcc, alloc.Name)
  907. }
  908. }
  909. continue
  910. }
  911. // (4) Distribute idle allocations according to the idle coefficients
  912. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  913. // all idle allocations will be in the aggSet at this point, so idleSet
  914. // will be empty and we won't enter this block.
  915. if idleSet.Length() > 0 {
  916. // Distribute idle allocations by coefficient per-idleId, per-allocation
  917. for _, idleAlloc := range idleSet.allocations {
  918. // Only share idle if the idleId matches; i.e. the allocation
  919. // is from the same idleId as the idle costs
  920. iaidleId, err := idleAlloc.getIdleId(options)
  921. if err != nil {
  922. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  923. return err
  924. }
  925. if iaidleId != idleId {
  926. continue
  927. }
  928. // Make sure idle coefficients exist
  929. if _, ok := idleCoefficients[idleId]; !ok {
  930. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  931. continue
  932. }
  933. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  934. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  935. continue
  936. }
  937. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  938. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  939. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  940. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  941. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  942. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  943. alloc.CPUCost += idleCPUCost
  944. alloc.GPUCost += idleGPUCost
  945. alloc.RAMCost += idleRAMCost
  946. }
  947. }
  948. // (5) generate key to use for aggregation-by-key and allocation name
  949. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  950. alloc.Name = key
  951. if options.MergeUnallocated && alloc.IsUnallocated() {
  952. alloc.Name = UnallocatedSuffix
  953. }
  954. // Inserting the allocation with the generated key for a name will
  955. // perform the actual basic aggregation step.
  956. aggSet.Insert(alloc)
  957. }
  958. // (6) If idle is shared and resources are shared, it's possible that some
  959. // amount of idle cost will be shared with a shared resource. Distribute
  960. // that idle allocation, if it exists, to the respective shared allocations
  961. // before sharing with the aggregated allocations.
  962. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  963. for _, alloc := range shareSet.allocations {
  964. idleId, err := alloc.getIdleId(options)
  965. if err != nil {
  966. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  967. }
  968. // Distribute idle allocations by coefficient per-idleId, per-allocation
  969. for _, idleAlloc := range idleSet.allocations {
  970. // Only share idle if the idleId matches; i.e. the allocation
  971. // is from the same idleId as the idle costs
  972. iaidleId, _ := idleAlloc.getIdleId(options)
  973. if iaidleId != idleId {
  974. continue
  975. }
  976. // Make sure idle coefficients exist
  977. if _, ok := idleCoefficients[idleId]; !ok {
  978. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  979. continue
  980. }
  981. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  982. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  983. continue
  984. }
  985. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  986. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  987. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  988. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  989. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  990. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  991. alloc.CPUCost += idleCPUCost
  992. alloc.GPUCost += idleGPUCost
  993. alloc.RAMCost += idleRAMCost
  994. }
  995. }
  996. }
  997. // groupingIdleFiltrationCoeffs is used to track per-resource idle
  998. // coefficients on a cluster-by-cluster or node-by-node basis depending
  999. // on the IdleByNode option. It is, essentailly, an aggregation of
  1000. // idleFiltrationCoefficients after they have been
  1001. // filtered above (in step 3)
  1002. var groupingIdleFiltrationCoeffs map[string]map[string]float64
  1003. if idleFiltrationCoefficients != nil {
  1004. groupingIdleFiltrationCoeffs = map[string]map[string]float64{}
  1005. for idleId, m := range idleFiltrationCoefficients {
  1006. if _, ok := groupingIdleFiltrationCoeffs[idleId]; !ok {
  1007. groupingIdleFiltrationCoeffs[idleId] = map[string]float64{
  1008. "cpu": 0.0,
  1009. "gpu": 0.0,
  1010. "ram": 0.0,
  1011. }
  1012. }
  1013. for _, n := range m {
  1014. for resource, val := range n {
  1015. groupingIdleFiltrationCoeffs[idleId][resource] += val
  1016. }
  1017. }
  1018. }
  1019. }
  1020. // (7) If we have both un-shared idle allocations and idle filtration
  1021. // coefficients then apply those. See step (2b) for an example.
  1022. if len(aggSet.idleKeys) > 0 && groupingIdleFiltrationCoeffs != nil {
  1023. for idleKey := range aggSet.idleKeys {
  1024. idleAlloc := aggSet.Get(idleKey)
  1025. iaidleId, err := idleAlloc.getIdleId(options)
  1026. if err != nil {
  1027. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  1028. return err
  1029. }
  1030. if resourceCoeffs, ok := groupingIdleFiltrationCoeffs[iaidleId]; ok {
  1031. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  1032. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  1033. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  1034. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  1035. }
  1036. }
  1037. }
  1038. // (8) Distribute shared allocations according to the share coefficients.
  1039. if shareSet.Length() > 0 {
  1040. for _, alloc := range aggSet.allocations {
  1041. for _, sharedAlloc := range shareSet.allocations {
  1042. if _, ok := shareCoefficients[alloc.Name]; !ok {
  1043. if !alloc.IsIdle() {
  1044. log.Warningf("AllocationSet.AggregateBy: error getting share coefficienct for '%s'", alloc.Name)
  1045. }
  1046. continue
  1047. }
  1048. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  1049. }
  1050. }
  1051. }
  1052. // (9) Aggregate external allocations into aggregated allocations. This may
  1053. // not be possible for every external allocation, but attempt to find an
  1054. // exact key match, given each external allocation's proerties, and
  1055. // aggregate if an exact match is found.
  1056. for _, alloc := range externalSet.allocations {
  1057. skip := false
  1058. for _, ff := range options.FilterFuncs {
  1059. if !ff(alloc) {
  1060. skip = true
  1061. break
  1062. }
  1063. }
  1064. if !skip {
  1065. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  1066. alloc.Name = key
  1067. aggSet.Insert(alloc)
  1068. }
  1069. }
  1070. // (10) Combine all idle allocations into a single "__idle__" allocation
  1071. if !options.SplitIdle {
  1072. for _, idleAlloc := range aggSet.IdleAllocations() {
  1073. aggSet.Delete(idleAlloc.Name)
  1074. idleAlloc.Name = IdleSuffix
  1075. aggSet.Insert(idleAlloc)
  1076. }
  1077. }
  1078. // In the edge case that some idle has not been distributed because
  1079. // there is no usage of that resource type, add idle back to
  1080. // aggregations with only that cost applied.
  1081. // E.g. in the case where we have a result that looks like this on the
  1082. // frontend:
  1083. // Name CPU GPU RAM
  1084. // __idle__ $10 $12 $6
  1085. // kubecost $2 $0 $1
  1086. // Sharing idle weighted would result in no idle GPU cost being
  1087. // distributed, because the coefficient for the kubecost GPU cost would
  1088. // be zero. Thus, instead we re-add idle to the aggSet with distributed
  1089. // costs zeroed out but the undistributed costs left in.
  1090. // Name CPU GPU RAM
  1091. // __idle__ $0 $12 $0
  1092. // kubecost $12 $0 $7
  1093. if idleSet.Length() > 0 && !options.SplitIdle {
  1094. if undistributedIdleMap["cpu"] || undistributedIdleMap["gpu"] || undistributedIdleMap["ram"] {
  1095. for _, idleAlloc := range idleSet.allocations {
  1096. skip := false
  1097. // if the idle does not apply to the non-filtered values, skip it
  1098. for _, ff := range options.FilterFuncs {
  1099. if !ff(idleAlloc) {
  1100. skip = true
  1101. break
  1102. }
  1103. }
  1104. if skip {
  1105. continue
  1106. }
  1107. // if the idle doesn't have a cost to be shared, also skip it
  1108. if idleAlloc.CPUCost != 0 && idleAlloc.GPUCost != 0 && idleAlloc.RAMCost != 0 {
  1109. // artificially set the already shared costs to zero
  1110. if !undistributedIdleMap["cpu"] {
  1111. idleAlloc.CPUCost = 0
  1112. }
  1113. if !undistributedIdleMap["gpu"] {
  1114. idleAlloc.GPUCost = 0
  1115. }
  1116. if !undistributedIdleMap["ram"] {
  1117. idleAlloc.RAMCost = 0
  1118. }
  1119. idleAlloc.Name = IdleSuffix
  1120. aggSet.Insert(idleAlloc)
  1121. }
  1122. }
  1123. }
  1124. }
  1125. as.allocations = aggSet.allocations
  1126. return nil
  1127. }
  1128. func computeShareCoeffs(aggregateBy []string, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  1129. // Compute coeffs by totalling per-allocation, then dividing by the total.
  1130. coeffs := map[string]float64{}
  1131. // Compute totals for all allocations
  1132. total := 0.0
  1133. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  1134. // counts each aggregation proportionally to its respective costs
  1135. shareType := options.ShareSplit
  1136. // Record allocation values first, then normalize by totals to get percentages
  1137. for _, alloc := range as.allocations {
  1138. if alloc.IsIdle() {
  1139. // Skip idle allocations in coefficient calculation
  1140. continue
  1141. }
  1142. if alloc.IsUnmounted() {
  1143. // Skip unmounted allocations in coefficient calculation
  1144. continue
  1145. }
  1146. // Determine the post-aggregation key under which the allocation will
  1147. // be shared.
  1148. name := alloc.generateKey(aggregateBy, options.LabelConfig)
  1149. // If the current allocation will be filtered out in step 3, contribute
  1150. // its share of the shared coefficient to a "__filtered__" bin, which
  1151. // will ultimately be dropped. This step ensures that the shared cost
  1152. // of a non-filtered allocation will be conserved even when the filter
  1153. // is removed. (Otherwise, all the shared cost will get redistributed
  1154. // over the unfiltered results, inflating their shared costs.)
  1155. filtered := false
  1156. for _, ff := range options.FilterFuncs {
  1157. if !ff(alloc) {
  1158. filtered = true
  1159. break
  1160. }
  1161. }
  1162. if filtered {
  1163. name = "__filtered__"
  1164. }
  1165. if shareType == ShareEven {
  1166. // Even distribution is not additive - set to 1.0 for everything
  1167. coeffs[name] = 1.0
  1168. // Total for even distribution is always the number of coefficients
  1169. total = float64(len(coeffs))
  1170. } else {
  1171. // Both are additive for weighted distribution, where each
  1172. // cumulative coefficient will be divided by the total.
  1173. coeffs[name] += alloc.TotalCost()
  1174. total += alloc.TotalCost()
  1175. }
  1176. }
  1177. // Normalize coefficients by totals
  1178. for a := range coeffs {
  1179. if coeffs[a] > 0 && total > 0 {
  1180. coeffs[a] /= total
  1181. } else {
  1182. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  1183. coeffs[a] = 0.0
  1184. }
  1185. }
  1186. return coeffs, nil
  1187. }
  1188. func computeIdleCoeffs(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, map[string]bool, error) {
  1189. types := []string{"cpu", "gpu", "ram"}
  1190. undistributedIdleMap := map[string]bool{
  1191. "cpu": true,
  1192. "gpu": true,
  1193. "ram": true,
  1194. }
  1195. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1196. coeffs := map[string]map[string]map[string]float64{}
  1197. // Compute totals per resource for CPU, GPU, RAM, and PV
  1198. totals := map[string]map[string]float64{}
  1199. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  1200. // counts each allocation proportionally to its respective costs
  1201. shareType := options.ShareIdle
  1202. // Record allocation values first, then normalize by totals to get percentages
  1203. for _, alloc := range as.allocations {
  1204. if alloc.IsIdle() {
  1205. // Skip idle allocations in coefficient calculation
  1206. continue
  1207. }
  1208. idleId, err := alloc.getIdleId(options)
  1209. if err != nil {
  1210. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  1211. }
  1212. // get the name key for the allocation
  1213. name := alloc.Name
  1214. // Create key based tables if they don't exist
  1215. if _, ok := coeffs[idleId]; !ok {
  1216. coeffs[idleId] = map[string]map[string]float64{}
  1217. }
  1218. if _, ok := totals[idleId]; !ok {
  1219. totals[idleId] = map[string]float64{}
  1220. }
  1221. if _, ok := coeffs[idleId][name]; !ok {
  1222. coeffs[idleId][name] = map[string]float64{}
  1223. }
  1224. if shareType == ShareEven {
  1225. for _, r := range types {
  1226. // Not additive - hard set to 1.0
  1227. coeffs[idleId][name][r] = 1.0
  1228. // totals are additive
  1229. totals[idleId][r] += 1.0
  1230. }
  1231. } else {
  1232. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1233. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1234. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1235. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1236. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1237. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1238. }
  1239. }
  1240. // Do the same for shared allocations
  1241. for _, alloc := range shareSet.allocations {
  1242. if alloc.IsIdle() {
  1243. // Skip idle allocations in coefficient calculation
  1244. continue
  1245. }
  1246. // idleId will be providerId or cluster
  1247. idleId, err := alloc.getIdleId(options)
  1248. if err != nil {
  1249. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  1250. }
  1251. // get the name key for the allocation
  1252. name := alloc.Name
  1253. // Create idleId based tables if they don't exist
  1254. if _, ok := coeffs[idleId]; !ok {
  1255. coeffs[idleId] = map[string]map[string]float64{}
  1256. }
  1257. if _, ok := totals[idleId]; !ok {
  1258. totals[idleId] = map[string]float64{}
  1259. }
  1260. if _, ok := coeffs[idleId][name]; !ok {
  1261. coeffs[idleId][name] = map[string]float64{}
  1262. }
  1263. if shareType == ShareEven {
  1264. for _, r := range types {
  1265. // Not additive - hard set to 1.0
  1266. coeffs[idleId][name][r] = 1.0
  1267. // totals are additive
  1268. totals[idleId][r] += 1.0
  1269. }
  1270. } else {
  1271. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1272. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1273. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1274. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1275. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1276. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1277. }
  1278. }
  1279. // Normalize coefficients by totals
  1280. for c := range coeffs {
  1281. for a := range coeffs[c] {
  1282. for _, r := range types {
  1283. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  1284. coeffs[c][a][r] /= totals[c][r]
  1285. undistributedIdleMap[r] = false
  1286. }
  1287. }
  1288. }
  1289. }
  1290. return coeffs, undistributedIdleMap, nil
  1291. }
  1292. // getIdleId returns the providerId or cluster of an Allocation depending on the IdleByNode
  1293. // option in the AllocationAggregationOptions and an error if the respective field is missing
  1294. func (a *Allocation) getIdleId(options *AllocationAggregationOptions) (string, error) {
  1295. var idleId string
  1296. if options.IdleByNode {
  1297. // Key allocations to ProviderId to match against node
  1298. idleId = a.Properties.ProviderID
  1299. if idleId == "" {
  1300. return idleId, fmt.Errorf("ProviderId is not set")
  1301. }
  1302. } else {
  1303. // key the allocations by cluster id
  1304. idleId = a.Properties.Cluster
  1305. if idleId == "" {
  1306. return idleId, fmt.Errorf("ClusterProp is not set")
  1307. }
  1308. }
  1309. return idleId, nil
  1310. }
  1311. func (a *Allocation) generateKey(aggregateBy []string, labelConfig *LabelConfig) string {
  1312. if a == nil {
  1313. return ""
  1314. }
  1315. if labelConfig == nil {
  1316. labelConfig = NewLabelConfig()
  1317. }
  1318. // Names will ultimately be joined into a single name, which uniquely
  1319. // identifies allocations.
  1320. names := []string{}
  1321. for _, agg := range aggregateBy {
  1322. switch true {
  1323. case agg == AllocationClusterProp:
  1324. names = append(names, a.Properties.Cluster)
  1325. case agg == AllocationNodeProp:
  1326. names = append(names, a.Properties.Node)
  1327. case agg == AllocationNamespaceProp:
  1328. names = append(names, a.Properties.Namespace)
  1329. case agg == AllocationControllerKindProp:
  1330. controllerKind := a.Properties.ControllerKind
  1331. if controllerKind == "" {
  1332. // Indicate that allocation has no controller
  1333. controllerKind = UnallocatedSuffix
  1334. }
  1335. names = append(names, controllerKind)
  1336. case agg == AllocationDaemonSetProp || agg == AllocationStatefulSetProp || agg == AllocationDeploymentProp || agg == AllocationJobProp:
  1337. controller := a.Properties.Controller
  1338. if agg != a.Properties.ControllerKind || controller == "" {
  1339. // The allocation does not have the specified controller kind
  1340. controller = UnallocatedSuffix
  1341. }
  1342. names = append(names, controller)
  1343. case agg == AllocationControllerProp:
  1344. controller := a.Properties.Controller
  1345. if controller == "" {
  1346. // Indicate that allocation has no controller
  1347. controller = UnallocatedSuffix
  1348. } else if a.Properties.ControllerKind != "" {
  1349. controller = fmt.Sprintf("%s:%s", a.Properties.ControllerKind, controller)
  1350. }
  1351. names = append(names, controller)
  1352. case agg == AllocationPodProp:
  1353. names = append(names, a.Properties.Pod)
  1354. case agg == AllocationContainerProp:
  1355. names = append(names, a.Properties.Container)
  1356. case agg == AllocationServiceProp:
  1357. services := a.Properties.Services
  1358. if len(services) == 0 {
  1359. // Indicate that allocation has no services
  1360. names = append(names, UnallocatedSuffix)
  1361. } else {
  1362. // This just uses the first service
  1363. for _, service := range services {
  1364. names = append(names, service)
  1365. break
  1366. }
  1367. }
  1368. case strings.HasPrefix(agg, "label:"):
  1369. labels := a.Properties.Labels
  1370. if labels == nil {
  1371. names = append(names, UnallocatedSuffix)
  1372. } else {
  1373. labelName := labelConfig.Sanitize(strings.TrimPrefix(agg, "label:"))
  1374. if labelValue, ok := labels[labelName]; ok {
  1375. names = append(names, fmt.Sprintf("%s=%s", labelName, labelValue))
  1376. } else {
  1377. names = append(names, UnallocatedSuffix)
  1378. }
  1379. }
  1380. case strings.HasPrefix(agg, "annotation:"):
  1381. annotations := a.Properties.Annotations
  1382. if annotations == nil {
  1383. names = append(names, UnallocatedSuffix)
  1384. } else {
  1385. annotationName := labelConfig.Sanitize(strings.TrimPrefix(agg, "annotation:"))
  1386. if annotationValue, ok := annotations[annotationName]; ok {
  1387. names = append(names, fmt.Sprintf("%s=%s", annotationName, annotationValue))
  1388. } else {
  1389. names = append(names, UnallocatedSuffix)
  1390. }
  1391. }
  1392. case agg == AllocationDepartmentProp:
  1393. labels := a.Properties.Labels
  1394. if labels == nil {
  1395. names = append(names, UnallocatedSuffix)
  1396. } else {
  1397. labelNames := strings.Split(labelConfig.DepartmentLabel, ",")
  1398. for _, labelName := range labelNames {
  1399. labelName = labelConfig.Sanitize(labelName)
  1400. if labelValue, ok := labels[labelName]; ok {
  1401. names = append(names, labelValue)
  1402. } else {
  1403. names = append(names, UnallocatedSuffix)
  1404. }
  1405. }
  1406. }
  1407. case agg == AllocationEnvironmentProp:
  1408. labels := a.Properties.Labels
  1409. if labels == nil {
  1410. names = append(names, UnallocatedSuffix)
  1411. } else {
  1412. labelNames := strings.Split(labelConfig.EnvironmentLabel, ",")
  1413. for _, labelName := range labelNames {
  1414. labelName = labelConfig.Sanitize(labelName)
  1415. if labelValue, ok := labels[labelName]; ok {
  1416. names = append(names, labelValue)
  1417. } else {
  1418. names = append(names, UnallocatedSuffix)
  1419. }
  1420. }
  1421. }
  1422. case agg == AllocationOwnerProp:
  1423. labels := a.Properties.Labels
  1424. if labels == nil {
  1425. names = append(names, UnallocatedSuffix)
  1426. } else {
  1427. labelNames := strings.Split(labelConfig.OwnerLabel, ",")
  1428. for _, labelName := range labelNames {
  1429. labelName = labelConfig.Sanitize(labelName)
  1430. if labelValue, ok := labels[labelName]; ok {
  1431. names = append(names, labelValue)
  1432. } else {
  1433. names = append(names, UnallocatedSuffix)
  1434. }
  1435. }
  1436. }
  1437. case agg == AllocationProductProp:
  1438. labels := a.Properties.Labels
  1439. if labels == nil {
  1440. names = append(names, UnallocatedSuffix)
  1441. } else {
  1442. labelNames := strings.Split(labelConfig.ProductLabel, ",")
  1443. for _, labelName := range labelNames {
  1444. labelName = labelConfig.Sanitize(labelName)
  1445. if labelValue, ok := labels[labelName]; ok {
  1446. names = append(names, labelValue)
  1447. } else {
  1448. names = append(names, UnallocatedSuffix)
  1449. }
  1450. }
  1451. }
  1452. case agg == AllocationTeamProp:
  1453. labels := a.Properties.Labels
  1454. if labels == nil {
  1455. names = append(names, UnallocatedSuffix)
  1456. } else {
  1457. labelNames := strings.Split(labelConfig.TeamLabel, ",")
  1458. for _, labelName := range labelNames {
  1459. labelName = labelConfig.Sanitize(labelName)
  1460. if labelValue, ok := labels[labelName]; ok {
  1461. names = append(names, labelValue)
  1462. } else {
  1463. names = append(names, UnallocatedSuffix)
  1464. }
  1465. }
  1466. }
  1467. default:
  1468. // This case should never be reached, as input up until this point
  1469. // should be checked and rejected if invalid. But if we do get a
  1470. // value we don't recognize, log a warning.
  1471. log.Warningf("AggregateBy: illegal aggregation parameter: %s", agg)
  1472. }
  1473. }
  1474. return strings.Join(names, "/")
  1475. }
  1476. // Clone returns a new AllocationSet with a deep copy of the given
  1477. // AllocationSet's allocations.
  1478. func (as *AllocationSet) Clone() *AllocationSet {
  1479. if as == nil {
  1480. return nil
  1481. }
  1482. as.RLock()
  1483. defer as.RUnlock()
  1484. allocs := map[string]*Allocation{}
  1485. for k, v := range as.allocations {
  1486. allocs[k] = v.Clone()
  1487. }
  1488. externalKeys := map[string]bool{}
  1489. for k, v := range as.externalKeys {
  1490. externalKeys[k] = v
  1491. }
  1492. idleKeys := map[string]bool{}
  1493. for k, v := range as.idleKeys {
  1494. idleKeys[k] = v
  1495. }
  1496. return &AllocationSet{
  1497. allocations: allocs,
  1498. externalKeys: externalKeys,
  1499. idleKeys: idleKeys,
  1500. Window: as.Window.Clone(),
  1501. }
  1502. }
  1503. // ComputeIdleAllocations computes the idle allocations for the AllocationSet,
  1504. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1505. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1506. // considered for idle allocation. If the Nodes have adjustments, then apply
  1507. // the adjustments proportionally to each of the resources so that total
  1508. // allocation with idle reflects the adjusted node costs. One idle allocation
  1509. // per-cluster will be computed and returned, keyed by cluster_id.
  1510. func (as *AllocationSet) ComputeIdleAllocations(assetSet *AssetSet) (map[string]*Allocation, error) {
  1511. if as == nil {
  1512. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1513. }
  1514. if assetSet == nil {
  1515. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1516. }
  1517. if !as.Window.Equal(assetSet.Window) {
  1518. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1519. }
  1520. window := as.Window
  1521. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1522. // cluster-to-{cpu|gpu|ram}-to-cost.
  1523. assetClusterResourceCosts := map[string]map[string]float64{}
  1524. assetSet.Each(func(key string, a Asset) {
  1525. if node, ok := a.(*Node); ok {
  1526. if _, ok := assetClusterResourceCosts[node.Properties().Cluster]; !ok {
  1527. assetClusterResourceCosts[node.Properties().Cluster] = map[string]float64{}
  1528. }
  1529. // adjustmentRate is used to scale resource costs proportionally
  1530. // by the adjustment. This is necessary because we only get one
  1531. // adjustment per Node, not one per-resource-per-Node.
  1532. //
  1533. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1534. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1535. // e.g. total cost = $150, adjustment = $50 => 1.5
  1536. adjustmentRate := 1.0
  1537. if node.TotalCost()-node.Adjustment() == 0 {
  1538. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1539. // the entire node cost and we should make everything 0
  1540. // without dividing by 0.
  1541. adjustmentRate = 0.0
  1542. log.DedupedWarningf(5, "Compute Idle Allocations: Node Cost Adjusted to $0.00 for %s", node.properties.Name)
  1543. } else if node.Adjustment() != 0.0 {
  1544. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1545. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1546. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1547. }
  1548. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1549. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1550. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1551. assetClusterResourceCosts[node.Properties().Cluster]["cpu"] += cpuCost
  1552. assetClusterResourceCosts[node.Properties().Cluster]["gpu"] += gpuCost
  1553. assetClusterResourceCosts[node.Properties().Cluster]["ram"] += ramCost
  1554. }
  1555. })
  1556. // Determine start, end on a per-cluster basis
  1557. clusterStarts := map[string]time.Time{}
  1558. clusterEnds := map[string]time.Time{}
  1559. // Subtract allocated costs from asset costs, leaving only the remaining
  1560. // idle costs.
  1561. as.Each(func(name string, a *Allocation) {
  1562. cluster := a.Properties.Cluster
  1563. if cluster == "" {
  1564. // Failed to find allocation's cluster
  1565. return
  1566. }
  1567. if _, ok := assetClusterResourceCosts[cluster]; !ok {
  1568. // Failed to find assets for allocation's cluster
  1569. return
  1570. }
  1571. // Set cluster (start, end) if they are either not currently set,
  1572. // or if the detected (start, end) of the current allocation falls
  1573. // before or after, respectively, the current values.
  1574. if s, ok := clusterStarts[cluster]; !ok || a.Start.Before(s) {
  1575. clusterStarts[cluster] = a.Start
  1576. }
  1577. if e, ok := clusterEnds[cluster]; !ok || a.End.After(e) {
  1578. clusterEnds[cluster] = a.End
  1579. }
  1580. assetClusterResourceCosts[cluster]["cpu"] -= a.CPUTotalCost()
  1581. assetClusterResourceCosts[cluster]["gpu"] -= a.GPUTotalCost()
  1582. assetClusterResourceCosts[cluster]["ram"] -= a.RAMTotalCost()
  1583. })
  1584. // Turn remaining un-allocated asset costs into idle allocations
  1585. idleAllocs := map[string]*Allocation{}
  1586. for cluster, resources := range assetClusterResourceCosts {
  1587. // Default start and end to the (start, end) of the given window, but
  1588. // use the actual, detected (start, end) pair if they are available.
  1589. start := *window.Start()
  1590. if s, ok := clusterStarts[cluster]; ok && window.Contains(s) {
  1591. start = s
  1592. }
  1593. end := *window.End()
  1594. if e, ok := clusterEnds[cluster]; ok && window.Contains(e) {
  1595. end = e
  1596. }
  1597. idleAlloc := &Allocation{
  1598. Name: fmt.Sprintf("%s/%s", cluster, IdleSuffix),
  1599. Window: window.Clone(),
  1600. Properties: &AllocationProperties{Cluster: cluster},
  1601. Start: start,
  1602. End: end,
  1603. CPUCost: resources["cpu"],
  1604. GPUCost: resources["gpu"],
  1605. RAMCost: resources["ram"],
  1606. }
  1607. // Do not continue if multiple idle allocations are computed for a
  1608. // single cluster.
  1609. if _, ok := idleAllocs[cluster]; ok {
  1610. return nil, fmt.Errorf("duplicate idle allocations for cluster %s", cluster)
  1611. }
  1612. idleAllocs[cluster] = idleAlloc
  1613. }
  1614. return idleAllocs, nil
  1615. }
  1616. // ComputeIdleAllocationsByNode computes the idle allocations for the AllocationSet,
  1617. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1618. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1619. // considered for idle allocation. If the Nodes have adjustments, then apply
  1620. // the adjustments proportionally to each of the resources so that total
  1621. // allocation with idle reflects the adjusted node costs. One idle allocation
  1622. // per-node will be computed and returned, keyed by cluster_id.
  1623. func (as *AllocationSet) ComputeIdleAllocationsByNode(assetSet *AssetSet) (map[string]*Allocation, error) {
  1624. if as == nil {
  1625. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1626. }
  1627. if assetSet == nil {
  1628. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1629. }
  1630. if !as.Window.Equal(assetSet.Window) {
  1631. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1632. }
  1633. window := as.Window
  1634. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1635. // cluster-to-{cpu|gpu|ram}-to-cost.
  1636. assetNodeResourceCosts := map[string]map[string]float64{}
  1637. nodesByProviderId := map[string]*Node{}
  1638. assetSet.Each(func(key string, a Asset) {
  1639. if node, ok := a.(*Node); ok {
  1640. if _, ok := assetNodeResourceCosts[node.Properties().ProviderID]; ok || node.Properties().ProviderID == "" {
  1641. log.DedupedWarningf(5, "Compute Idle Allocations By Node: Node missing providerId: %s", node.properties.Name)
  1642. return
  1643. }
  1644. nodesByProviderId[node.Properties().ProviderID] = node
  1645. assetNodeResourceCosts[node.Properties().ProviderID] = map[string]float64{}
  1646. // adjustmentRate is used to scale resource costs proportionally
  1647. // by the adjustment. This is necessary because we only get one
  1648. // adjustment per Node, not one per-resource-per-Node.
  1649. //
  1650. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1651. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1652. // e.g. total cost = $150, adjustment = $50 => 1.5
  1653. adjustmentRate := 1.0
  1654. if node.TotalCost()-node.Adjustment() == 0 {
  1655. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1656. // the entire node cost and we should make everything 0
  1657. // without dividing by 0.
  1658. adjustmentRate = 0.0
  1659. log.DedupedWarningf(5, "Compute Idle Allocations: Node Cost Adjusted to $0.00 for %s", node.properties.Name)
  1660. } else if node.Adjustment() != 0.0 {
  1661. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1662. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1663. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1664. }
  1665. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1666. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1667. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1668. assetNodeResourceCosts[node.Properties().ProviderID]["cpu"] += cpuCost
  1669. assetNodeResourceCosts[node.Properties().ProviderID]["gpu"] += gpuCost
  1670. assetNodeResourceCosts[node.Properties().ProviderID]["ram"] += ramCost
  1671. }
  1672. })
  1673. // Determine start, end on a per-cluster basis
  1674. nodeStarts := map[string]time.Time{}
  1675. nodeEnds := map[string]time.Time{}
  1676. // Subtract allocated costs from asset costs, leaving only the remaining
  1677. // idle costs.
  1678. as.Each(func(name string, a *Allocation) {
  1679. providerId := a.Properties.ProviderID
  1680. if providerId == "" {
  1681. // Failed to find allocation's node
  1682. log.DedupedWarningf(5, "Compute Idle Allocations By Node: Allocation missing providerId: %s", a.Name)
  1683. return
  1684. }
  1685. if _, ok := assetNodeResourceCosts[providerId]; !ok {
  1686. // Failed to find assets for allocation's node
  1687. return
  1688. }
  1689. // Set cluster (start, end) if they are either not currently set,
  1690. // or if the detected (start, end) of the current allocation falls
  1691. // before or after, respectively, the current values.
  1692. if s, ok := nodeStarts[providerId]; !ok || a.Start.Before(s) {
  1693. nodeStarts[providerId] = a.Start
  1694. }
  1695. if e, ok := nodeEnds[providerId]; !ok || a.End.After(e) {
  1696. nodeEnds[providerId] = a.End
  1697. }
  1698. assetNodeResourceCosts[providerId]["cpu"] -= a.CPUTotalCost()
  1699. assetNodeResourceCosts[providerId]["gpu"] -= a.GPUTotalCost()
  1700. assetNodeResourceCosts[providerId]["ram"] -= a.RAMTotalCost()
  1701. })
  1702. // Turn remaining un-allocated asset costs into idle allocations
  1703. idleAllocs := map[string]*Allocation{}
  1704. for providerId, resources := range assetNodeResourceCosts {
  1705. // Default start and end to the (start, end) of the given window, but
  1706. // use the actual, detected (start, end) pair if they are available.
  1707. start := *window.Start()
  1708. if s, ok := nodeStarts[providerId]; ok && window.Contains(s) {
  1709. start = s
  1710. }
  1711. end := *window.End()
  1712. if e, ok := nodeEnds[providerId]; ok && window.Contains(e) {
  1713. end = e
  1714. }
  1715. node := nodesByProviderId[providerId]
  1716. idleAlloc := &Allocation{
  1717. Name: fmt.Sprintf("%s/%s", node.properties.Name, IdleSuffix),
  1718. Window: window.Clone(),
  1719. Properties: &AllocationProperties{
  1720. Cluster: node.properties.Cluster,
  1721. Node: node.properties.Name,
  1722. ProviderID: providerId,
  1723. },
  1724. Start: start,
  1725. End: end,
  1726. CPUCost: resources["cpu"],
  1727. GPUCost: resources["gpu"],
  1728. RAMCost: resources["ram"],
  1729. }
  1730. // Do not continue if multiple idle allocations are computed for a
  1731. // single node.
  1732. if _, ok := idleAllocs[providerId]; ok {
  1733. return nil, fmt.Errorf("duplicate idle allocations for node Provider ID: %s", providerId)
  1734. }
  1735. idleAllocs[providerId] = idleAlloc
  1736. }
  1737. return idleAllocs, nil
  1738. }
  1739. // Delete removes the allocation with the given name from the set
  1740. func (as *AllocationSet) Delete(name string) {
  1741. if as == nil {
  1742. return
  1743. }
  1744. as.Lock()
  1745. defer as.Unlock()
  1746. delete(as.externalKeys, name)
  1747. delete(as.idleKeys, name)
  1748. delete(as.allocations, name)
  1749. }
  1750. // Each invokes the given function for each Allocation in the set
  1751. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  1752. if as == nil {
  1753. return
  1754. }
  1755. for k, a := range as.allocations {
  1756. f(k, a)
  1757. }
  1758. }
  1759. // End returns the End time of the AllocationSet window
  1760. func (as *AllocationSet) End() time.Time {
  1761. if as == nil {
  1762. log.Warningf("AllocationSet: calling End on nil AllocationSet")
  1763. return time.Unix(0, 0)
  1764. }
  1765. if as.Window.End() == nil {
  1766. log.Warningf("AllocationSet: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  1767. return time.Unix(0, 0)
  1768. }
  1769. return *as.Window.End()
  1770. }
  1771. // Get returns the Allocation at the given key in the AllocationSet
  1772. func (as *AllocationSet) Get(key string) *Allocation {
  1773. as.RLock()
  1774. defer as.RUnlock()
  1775. if alloc, ok := as.allocations[key]; ok {
  1776. return alloc
  1777. }
  1778. return nil
  1779. }
  1780. // ExternalAllocations returns a map of the external allocations in the set.
  1781. // Returns clones of the actual Allocations, so mutability is not a problem.
  1782. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1783. externals := map[string]*Allocation{}
  1784. if as.IsEmpty() {
  1785. return externals
  1786. }
  1787. as.RLock()
  1788. defer as.RUnlock()
  1789. for key := range as.externalKeys {
  1790. if alloc, ok := as.allocations[key]; ok {
  1791. externals[key] = alloc.Clone()
  1792. }
  1793. }
  1794. return externals
  1795. }
  1796. // ExternalCost returns the total aggregated external costs of the set
  1797. func (as *AllocationSet) ExternalCost() float64 {
  1798. if as.IsEmpty() {
  1799. return 0.0
  1800. }
  1801. as.RLock()
  1802. defer as.RUnlock()
  1803. externalCost := 0.0
  1804. for _, alloc := range as.allocations {
  1805. externalCost += alloc.ExternalCost
  1806. }
  1807. return externalCost
  1808. }
  1809. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1810. // Returns clones of the actual Allocations, so mutability is not a problem.
  1811. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1812. idles := map[string]*Allocation{}
  1813. if as.IsEmpty() {
  1814. return idles
  1815. }
  1816. as.RLock()
  1817. defer as.RUnlock()
  1818. for key := range as.idleKeys {
  1819. if alloc, ok := as.allocations[key]; ok {
  1820. idles[key] = alloc.Clone()
  1821. }
  1822. }
  1823. return idles
  1824. }
  1825. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1826. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1827. // there is no existing entry, one is created. Nil error response indicates success.
  1828. func (as *AllocationSet) Insert(that *Allocation) error {
  1829. return as.insert(that)
  1830. }
  1831. func (as *AllocationSet) insert(that *Allocation) error {
  1832. if as == nil {
  1833. return fmt.Errorf("cannot insert into nil AllocationSet")
  1834. }
  1835. as.Lock()
  1836. defer as.Unlock()
  1837. if as.allocations == nil {
  1838. as.allocations = map[string]*Allocation{}
  1839. }
  1840. if as.externalKeys == nil {
  1841. as.externalKeys = map[string]bool{}
  1842. }
  1843. if as.idleKeys == nil {
  1844. as.idleKeys = map[string]bool{}
  1845. }
  1846. // Add the given Allocation to the existing entry, if there is one;
  1847. // otherwise just set directly into allocations
  1848. if _, ok := as.allocations[that.Name]; !ok {
  1849. as.allocations[that.Name] = that
  1850. } else {
  1851. as.allocations[that.Name].add(that)
  1852. }
  1853. // If the given Allocation is an external one, record that
  1854. if that.IsExternal() {
  1855. as.externalKeys[that.Name] = true
  1856. }
  1857. // If the given Allocation is an idle one, record that
  1858. if that.IsIdle() {
  1859. as.idleKeys[that.Name] = true
  1860. }
  1861. return nil
  1862. }
  1863. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  1864. // zero allocations.
  1865. func (as *AllocationSet) IsEmpty() bool {
  1866. if as == nil || len(as.allocations) == 0 {
  1867. return true
  1868. }
  1869. as.RLock()
  1870. defer as.RUnlock()
  1871. return as.allocations == nil || len(as.allocations) == 0
  1872. }
  1873. // Length returns the number of Allocations in the set
  1874. func (as *AllocationSet) Length() int {
  1875. if as == nil {
  1876. return 0
  1877. }
  1878. as.RLock()
  1879. defer as.RUnlock()
  1880. return len(as.allocations)
  1881. }
  1882. // Map clones and returns a map of the AllocationSet's Allocations
  1883. func (as *AllocationSet) Map() map[string]*Allocation {
  1884. if as.IsEmpty() {
  1885. return map[string]*Allocation{}
  1886. }
  1887. return as.Clone().allocations
  1888. }
  1889. // MarshalJSON JSON-encodes the AllocationSet
  1890. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  1891. as.RLock()
  1892. defer as.RUnlock()
  1893. return json.Marshal(as.allocations)
  1894. }
  1895. // Resolution returns the AllocationSet's window duration
  1896. func (as *AllocationSet) Resolution() time.Duration {
  1897. return as.Window.Duration()
  1898. }
  1899. // Set uses the given Allocation to overwrite the existing entry in the
  1900. // AllocationSet under the Allocation's name.
  1901. func (as *AllocationSet) Set(alloc *Allocation) error {
  1902. if as.IsEmpty() {
  1903. as.Lock()
  1904. as.allocations = map[string]*Allocation{}
  1905. as.externalKeys = map[string]bool{}
  1906. as.idleKeys = map[string]bool{}
  1907. as.Unlock()
  1908. }
  1909. as.Lock()
  1910. defer as.Unlock()
  1911. as.allocations[alloc.Name] = alloc
  1912. // If the given Allocation is an external one, record that
  1913. if alloc.IsExternal() {
  1914. as.externalKeys[alloc.Name] = true
  1915. }
  1916. // If the given Allocation is an idle one, record that
  1917. if alloc.IsIdle() {
  1918. as.idleKeys[alloc.Name] = true
  1919. }
  1920. return nil
  1921. }
  1922. // Start returns the Start time of the AllocationSet window
  1923. func (as *AllocationSet) Start() time.Time {
  1924. if as == nil {
  1925. log.Warningf("AllocationSet: calling Start on nil AllocationSet")
  1926. return time.Unix(0, 0)
  1927. }
  1928. if as.Window.Start() == nil {
  1929. log.Warningf("AllocationSet: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1930. return time.Unix(0, 0)
  1931. }
  1932. return *as.Window.Start()
  1933. }
  1934. // String represents the given Allocation as a string
  1935. func (as *AllocationSet) String() string {
  1936. if as == nil {
  1937. return "<nil>"
  1938. }
  1939. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1940. as.Length(), as.Window, as.TotalCost())
  1941. }
  1942. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1943. func (as *AllocationSet) TotalCost() float64 {
  1944. if as.IsEmpty() {
  1945. return 0.0
  1946. }
  1947. as.RLock()
  1948. defer as.RUnlock()
  1949. tc := 0.0
  1950. for _, a := range as.allocations {
  1951. tc += a.TotalCost()
  1952. }
  1953. return tc
  1954. }
  1955. // UTCOffset returns the AllocationSet's configured UTCOffset.
  1956. func (as *AllocationSet) UTCOffset() time.Duration {
  1957. _, zone := as.Start().Zone()
  1958. return time.Duration(zone) * time.Second
  1959. }
  1960. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1961. if as.IsEmpty() {
  1962. return that.Clone(), nil
  1963. }
  1964. if that.IsEmpty() {
  1965. return as.Clone(), nil
  1966. }
  1967. // Set start, end to min(start), max(end)
  1968. start := as.Start()
  1969. end := as.End()
  1970. if that.Start().Before(start) {
  1971. start = that.Start()
  1972. }
  1973. if that.End().After(end) {
  1974. end = that.End()
  1975. }
  1976. acc := NewAllocationSet(start, end)
  1977. as.RLock()
  1978. defer as.RUnlock()
  1979. that.RLock()
  1980. defer that.RUnlock()
  1981. for _, alloc := range as.allocations {
  1982. err := acc.insert(alloc)
  1983. if err != nil {
  1984. return nil, err
  1985. }
  1986. }
  1987. for _, alloc := range that.allocations {
  1988. err := acc.insert(alloc)
  1989. if err != nil {
  1990. return nil, err
  1991. }
  1992. }
  1993. return acc, nil
  1994. }
  1995. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  1996. // be used such that the AllocationSets held are consecutive and coherent with
  1997. // respect to using the same aggregation properties, UTC offset, and
  1998. // resolution. However these rules are not necessarily enforced, so use wisely.
  1999. type AllocationSetRange struct {
  2000. sync.RWMutex
  2001. allocations []*AllocationSet
  2002. FromStore string // stores the name of the store used to retrieve the data
  2003. }
  2004. // NewAllocationSetRange instantiates a new range composed of the given
  2005. // AllocationSets in the order provided.
  2006. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  2007. return &AllocationSetRange{
  2008. allocations: allocs,
  2009. }
  2010. }
  2011. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  2012. // AllocationSet for the entire range.
  2013. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  2014. var allocSet *AllocationSet
  2015. var err error
  2016. asr.RLock()
  2017. defer asr.RUnlock()
  2018. for _, as := range asr.allocations {
  2019. allocSet, err = allocSet.accumulate(as)
  2020. if err != nil {
  2021. return nil, err
  2022. }
  2023. }
  2024. return allocSet, nil
  2025. }
  2026. // TODO accumulate into lower-resolution chunks of the given resolution
  2027. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  2028. // AggregateBy aggregates each AllocationSet in the range by the given
  2029. // properties and options.
  2030. func (asr *AllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  2031. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  2032. asr.Lock()
  2033. defer asr.Unlock()
  2034. for _, as := range asr.allocations {
  2035. err := as.AggregateBy(aggregateBy, options)
  2036. if err != nil {
  2037. return err
  2038. }
  2039. aggRange.allocations = append(aggRange.allocations, as)
  2040. }
  2041. asr.allocations = aggRange.allocations
  2042. return nil
  2043. }
  2044. // Append appends the given AllocationSet to the end of the range. It does not
  2045. // validate whether or not that violates window continuity.
  2046. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  2047. asr.Lock()
  2048. defer asr.Unlock()
  2049. asr.allocations = append(asr.allocations, that)
  2050. }
  2051. // Each invokes the given function for each AllocationSet in the range
  2052. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  2053. if asr == nil {
  2054. return
  2055. }
  2056. for i, as := range asr.allocations {
  2057. f(i, as)
  2058. }
  2059. }
  2060. // Get retrieves the AllocationSet at the given index of the range.
  2061. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  2062. if i < 0 || i >= len(asr.allocations) {
  2063. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  2064. }
  2065. asr.RLock()
  2066. defer asr.RUnlock()
  2067. return asr.allocations[i], nil
  2068. }
  2069. // InsertRange merges the given AllocationSetRange into the receiving one by
  2070. // lining up sets with matching windows, then inserting each allocation from
  2071. // the given ASR into the respective set in the receiving ASR. If the given
  2072. // ASR contains an AllocationSet from a window that does not exist in the
  2073. // receiving ASR, then an error is returned. However, the given ASR does not
  2074. // need to cover the full range of the receiver.
  2075. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  2076. if asr == nil {
  2077. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  2078. }
  2079. // keys maps window to index in asr
  2080. keys := map[string]int{}
  2081. asr.Each(func(i int, as *AllocationSet) {
  2082. if as == nil {
  2083. return
  2084. }
  2085. keys[as.Window.String()] = i
  2086. })
  2087. // Nothing to merge, so simply return
  2088. if len(keys) == 0 {
  2089. return nil
  2090. }
  2091. var err error
  2092. that.Each(func(j int, thatAS *AllocationSet) {
  2093. if thatAS == nil || err != nil {
  2094. return
  2095. }
  2096. // Find matching AllocationSet in asr
  2097. i, ok := keys[thatAS.Window.String()]
  2098. if !ok {
  2099. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  2100. return
  2101. }
  2102. as, err := asr.Get(i)
  2103. if err != nil {
  2104. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  2105. return
  2106. }
  2107. // Insert each Allocation from the given set
  2108. thatAS.Each(func(k string, alloc *Allocation) {
  2109. err = as.Insert(alloc)
  2110. if err != nil {
  2111. err = fmt.Errorf("error inserting allocation: %s", err)
  2112. return
  2113. }
  2114. })
  2115. })
  2116. // err might be nil
  2117. return err
  2118. }
  2119. // Length returns the length of the range, which is zero if nil
  2120. func (asr *AllocationSetRange) Length() int {
  2121. if asr == nil || asr.allocations == nil {
  2122. return 0
  2123. }
  2124. asr.RLock()
  2125. defer asr.RUnlock()
  2126. return len(asr.allocations)
  2127. }
  2128. // MarshalJSON JSON-encodes the range
  2129. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  2130. asr.RLock()
  2131. defer asr.RUnlock()
  2132. return json.Marshal(asr.allocations)
  2133. }
  2134. // Slice copies the underlying slice of AllocationSets, maintaining order,
  2135. // and returns the copied slice.
  2136. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  2137. if asr == nil || asr.allocations == nil {
  2138. return nil
  2139. }
  2140. asr.RLock()
  2141. defer asr.RUnlock()
  2142. copy := []*AllocationSet{}
  2143. for _, as := range asr.allocations {
  2144. copy = append(copy, as.Clone())
  2145. }
  2146. return copy
  2147. }
  2148. // String represents the given AllocationSetRange as a string
  2149. func (asr *AllocationSetRange) String() string {
  2150. if asr == nil {
  2151. return "<nil>"
  2152. }
  2153. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  2154. }
  2155. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  2156. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  2157. // are sets with conflicting UTCOffsets (just returns the first).
  2158. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  2159. if asr.Length() == 0 {
  2160. return 0
  2161. }
  2162. as, err := asr.Get(0)
  2163. if err != nil {
  2164. return 0
  2165. }
  2166. return as.UTCOffset()
  2167. }
  2168. // Window returns the full window that the AllocationSetRange spans, from the
  2169. // start of the first AllocationSet to the end of the last one.
  2170. func (asr *AllocationSetRange) Window() Window {
  2171. if asr == nil || asr.Length() == 0 {
  2172. return NewWindow(nil, nil)
  2173. }
  2174. start := asr.allocations[0].Start()
  2175. end := asr.allocations[asr.Length()-1].End()
  2176. return NewWindow(&start, &end)
  2177. }
  2178. // Start returns the earliest start of all Allocations in the AllocationSetRange.
  2179. // It returns an error if there are no allocations.
  2180. func (asr *AllocationSetRange) Start() (time.Time, error) {
  2181. start := time.Time{}
  2182. firstStartNotSet := true
  2183. asr.Each(func(i int, as *AllocationSet) {
  2184. as.Each(func(s string, a *Allocation) {
  2185. if firstStartNotSet {
  2186. start = a.Start
  2187. firstStartNotSet = false
  2188. }
  2189. if a.Start.Before(start) {
  2190. start = a.Start
  2191. }
  2192. })
  2193. })
  2194. if firstStartNotSet {
  2195. return start, fmt.Errorf("had no data to compute a start from")
  2196. }
  2197. return start, nil
  2198. }
  2199. // End returns the latest end of all Allocations in the AllocationSetRange.
  2200. // It returns an error if there are no allocations.
  2201. func (asr *AllocationSetRange) End() (time.Time, error) {
  2202. end := time.Time{}
  2203. firstEndNotSet := true
  2204. asr.Each(func(i int, as *AllocationSet) {
  2205. as.Each(func(s string, a *Allocation) {
  2206. if firstEndNotSet {
  2207. end = a.End
  2208. firstEndNotSet = false
  2209. }
  2210. if a.End.After(end) {
  2211. end = a.End
  2212. }
  2213. })
  2214. })
  2215. if firstEndNotSet {
  2216. return end, fmt.Errorf("had no data to compute an end from")
  2217. }
  2218. return end, nil
  2219. }
  2220. // Minutes returns the duration, in minutes, between the earliest start
  2221. // and the latest end of all allocations in the AllocationSetRange.
  2222. func (asr *AllocationSetRange) Minutes() float64 {
  2223. start, err := asr.Start()
  2224. if err != nil {
  2225. return 0
  2226. }
  2227. end, err := asr.End()
  2228. if err != nil {
  2229. return 0
  2230. }
  2231. duration := end.Sub(start)
  2232. return duration.Minutes()
  2233. }