allocation.go 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356
  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. // Preserve string properties that are matching between the two allocations
  536. a.Properties = a.Properties.Intersection(that.Properties)
  537. // Expand the window to encompass both Allocations
  538. a.Window = a.Window.Expand(that.Window)
  539. // Sum non-cumulative fields by turning them into cumulative, adding them,
  540. // and then converting them back into averages after minutes have been
  541. // combined (just below).
  542. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  543. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  544. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  545. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  546. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  547. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  548. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  549. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  550. // Expand Start and End to be the "max" of among the given Allocations
  551. if that.Start.Before(a.Start) {
  552. a.Start = that.Start
  553. }
  554. if that.End.After(a.End) {
  555. a.End = that.End
  556. }
  557. // Convert cumulative request and usage back into rates
  558. // TODO:TEST write a unit test that fails if this is done incorrectly
  559. if a.Minutes() > 0 {
  560. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  561. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  562. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  563. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  564. } else {
  565. a.CPUCoreRequestAverage = 0.0
  566. a.CPUCoreUsageAverage = 0.0
  567. a.RAMBytesRequestAverage = 0.0
  568. a.RAMBytesUsageAverage = 0.0
  569. }
  570. // Sum all cumulative resource fields
  571. a.CPUCoreHours += that.CPUCoreHours
  572. a.GPUHours += that.GPUHours
  573. a.RAMByteHours += that.RAMByteHours
  574. a.NetworkTransferBytes += that.NetworkTransferBytes
  575. a.NetworkReceiveBytes += that.NetworkReceiveBytes
  576. // Sum all cumulative cost fields
  577. a.CPUCost += that.CPUCost
  578. a.GPUCost += that.GPUCost
  579. a.RAMCost += that.RAMCost
  580. a.NetworkCost += that.NetworkCost
  581. a.LoadBalancerCost += that.LoadBalancerCost
  582. a.SharedCost += that.SharedCost
  583. a.ExternalCost += that.ExternalCost
  584. // Sum PVAllocations
  585. a.PVs = a.PVs.Add(that.PVs)
  586. // Sum all cumulative adjustment fields
  587. a.CPUCostAdjustment += that.CPUCostAdjustment
  588. a.RAMCostAdjustment += that.RAMCostAdjustment
  589. a.GPUCostAdjustment += that.GPUCostAdjustment
  590. a.PVCostAdjustment += that.PVCostAdjustment
  591. a.NetworkCostAdjustment += that.NetworkCostAdjustment
  592. a.LoadBalancerCostAdjustment += that.LoadBalancerCostAdjustment
  593. // Any data that is in a "raw allocation only" is not valid in any
  594. // sort of cumulative Allocation (like one that is added).
  595. a.RawAllocationOnly = nil
  596. }
  597. // AllocationSet stores a set of Allocations, each with a unique name, that share
  598. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  599. type AllocationSet struct {
  600. sync.RWMutex
  601. allocations map[string]*Allocation
  602. externalKeys map[string]bool
  603. idleKeys map[string]bool
  604. FromSource string // stores the name of the source used to compute the data
  605. Window Window
  606. Warnings []string
  607. Errors []string
  608. }
  609. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  610. // the given list of Allocations
  611. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  612. as := &AllocationSet{
  613. allocations: map[string]*Allocation{},
  614. externalKeys: map[string]bool{},
  615. idleKeys: map[string]bool{},
  616. Window: NewWindow(&start, &end),
  617. }
  618. for _, a := range allocs {
  619. as.Insert(a)
  620. }
  621. return as
  622. }
  623. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  624. // filtering results and sharing allocations. FilterFuncs are a list of match
  625. // functions such that, if any function fails, the allocation is ignored.
  626. // ShareFuncs are a list of match functions such that, if any function
  627. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  628. // simple flag for sharing idle resources.
  629. type AllocationAggregationOptions struct {
  630. FilterFuncs []AllocationMatchFunc
  631. SplitIdle bool
  632. IdleByNode bool
  633. MergeUnallocated bool
  634. ShareFuncs []AllocationMatchFunc
  635. ShareIdle string
  636. ShareSplit string
  637. SharedHourlyCosts map[string]float64
  638. }
  639. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  640. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  641. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  642. func (as *AllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  643. // The order of operations for aggregating allocations is as follows:
  644. // 1. Partition external, idle, and shared allocations into separate sets.
  645. // Also, create the aggSet into which the results will be aggregated.
  646. // 2. Compute sharing coefficients for idle and shared resources
  647. // a) if idle allocation is to be shared, compute idle coefficients
  648. // b) if idle allocation is NOT shared, but filters are present, compute
  649. // idle filtration coefficients for the purpose of only returning the
  650. // portion of idle allocation that would have been shared with the
  651. // unfiltered results. (See unit tests 5.a,b,c)
  652. // c) generate shared allocation for then given shared overhead, which
  653. // must happen after (2a) and (2b)
  654. // d) if there are shared resources, compute share coefficients
  655. // 3. Drop any allocation that fails any of the filters
  656. // 4. Distribute idle allocations according to the idle coefficients
  657. // 5. Generate aggregation key and insert allocation into the output set
  658. // 6. If idle is shared and resources are shared, some idle might be shared
  659. // with a shared resource. Distribute that to the shared resources
  660. // prior to sharing them with the aggregated results.
  661. // 7. Apply idle filtration coefficients from step (2b)
  662. // 8. Distribute shared allocations according to the share coefficients.
  663. // 9. If there are external allocations that can be aggregated into
  664. // the output (i.e. they can be used to generate a valid key for
  665. // the given properties) then aggregate; otherwise... ignore them?
  666. // 10. If the merge idle option is enabled, merge any remaining idle
  667. // allocations into a single idle allocation
  668. if options == nil {
  669. options = &AllocationAggregationOptions{}
  670. }
  671. if as.IsEmpty() {
  672. return nil
  673. }
  674. // aggSet will collect the aggregated allocations
  675. aggSet := &AllocationSet{
  676. Window: as.Window.Clone(),
  677. }
  678. // externalSet will collect external allocations
  679. externalSet := &AllocationSet{
  680. Window: as.Window.Clone(),
  681. }
  682. // idleSet will be shared among aggSet after initial aggregation
  683. // is complete
  684. idleSet := &AllocationSet{
  685. Window: as.Window.Clone(),
  686. }
  687. // shareSet will be shared among aggSet after initial aggregation
  688. // is complete
  689. shareSet := &AllocationSet{
  690. Window: as.Window.Clone(),
  691. }
  692. as.Lock()
  693. defer as.Unlock()
  694. // (1) Loop and find all of the external, idle, and shared allocations. Add
  695. // them to their respective sets, removing them from the set of allocations
  696. // to aggregate.
  697. for _, alloc := range as.allocations {
  698. // External allocations get aggregated post-hoc (see step 6) and do
  699. // not necessarily contain complete sets of properties, so they are
  700. // moved to a separate AllocationSet.
  701. if alloc.IsExternal() {
  702. delete(as.externalKeys, alloc.Name)
  703. delete(as.allocations, alloc.Name)
  704. externalSet.Insert(alloc)
  705. continue
  706. }
  707. // Idle allocations should be separated into idleSet if they are to be
  708. // shared later on. If they are not to be shared, then add them to the
  709. // aggSet like any other allocation.
  710. if alloc.IsIdle() {
  711. delete(as.idleKeys, alloc.Name)
  712. delete(as.allocations, alloc.Name)
  713. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  714. idleSet.Insert(alloc)
  715. } else {
  716. aggSet.Insert(alloc)
  717. }
  718. continue
  719. }
  720. // Shared allocations must be identified and separated prior to
  721. // aggregation and filtering. That is, if any of the ShareFuncs return
  722. // true for the allocation, then move it to shareSet.
  723. for _, sf := range options.ShareFuncs {
  724. if sf(alloc) {
  725. delete(as.idleKeys, alloc.Name)
  726. delete(as.allocations, alloc.Name)
  727. shareSet.Insert(alloc)
  728. break
  729. }
  730. }
  731. }
  732. // It's possible that no more un-shared, non-idle, non-external allocations
  733. // remain at this point. This always results in an emptySet, so return early.
  734. if len(as.allocations) == 0 {
  735. emptySet := &AllocationSet{
  736. Window: as.Window.Clone(),
  737. }
  738. as.allocations = emptySet.allocations
  739. return nil
  740. }
  741. // (2) In order to correctly share idle and shared costs, we first compute
  742. // sharing coefficients, which represent the proportion of each cost to
  743. // share with each allocation. Idle allocations are shared per-cluster or per-node,
  744. // per-allocation, and per-resource, while shared resources are shared per-
  745. // allocation only.
  746. //
  747. // For an idleCoefficient example, the entries:
  748. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  749. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  750. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  751. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  752. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  753. // RAM costs.
  754. //
  755. // For a shareCoefficient example, the entries:
  756. // [namespace2] = 0.666667
  757. // [__filtered__] = 0.333333
  758. // mean that the post-aggregation allocation "namespace2" will receive
  759. // 66.67% of the shared resource costs, while the remaining 33.33% will
  760. // be filtered out, as they were shared with allocations that did not pass
  761. // one of the given filters.
  762. //
  763. // In order to maintain stable results when multiple operations are being
  764. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  765. // coefficients are computed for the full set of allocations prior to
  766. // adding shared overhead and prior to applying filters.
  767. var err error
  768. // (2a) If there are idle costs to be shared, compute the coefficients for
  769. // sharing them among the non-idle, non-aggregated allocations (including
  770. // the shared allocations).
  771. var idleCoefficients map[string]map[string]map[string]float64
  772. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  773. idleCoefficients, err = computeIdleCoeffs(options, as, shareSet)
  774. if err != nil {
  775. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  776. return fmt.Errorf("error computing idle coefficients: %s", err)
  777. }
  778. }
  779. // (2b) If idle costs are not to be shared, but there are filters, then we
  780. // need to track the amount of each idle allocation to "filter" in order to
  781. // maintain parity with the results when idle is shared. That is, we want
  782. // to return only the idle costs that would have been shared with the given
  783. // results, even if the filter had not been applied.
  784. //
  785. // For example, consider these results from aggregating by namespace with
  786. // two clusters:
  787. //
  788. // namespace1: 25.00
  789. // namespace2: 30.00
  790. // namespace3: 15.00
  791. // idle: 30.00
  792. //
  793. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  794. // reduced by the amount that existed on cluster2. Then, idle must also be
  795. // reduced by the relevant amount:
  796. //
  797. // namespace1: 25.00
  798. // namespace2: 15.00
  799. // idle: 20.00
  800. //
  801. // Note that this can happen for any field, not just cluster, so we again
  802. // need to track this on a per-cluster or per-node, per-allocation, per-resource basis.
  803. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  804. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  805. idleFiltrationCoefficients, err = computeIdleCoeffs(options, as, shareSet)
  806. if err != nil {
  807. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  808. }
  809. }
  810. // (2c) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  811. // come after idle coefficients are computes so that allocations generated
  812. // by shared overhead do not skew the idle coefficient computation.
  813. for name, cost := range options.SharedHourlyCosts {
  814. if cost > 0.0 {
  815. hours := as.Resolution().Hours()
  816. // If set ends in the future, adjust hours accordingly
  817. diff := time.Now().Sub(as.End())
  818. if diff < 0.0 {
  819. hours += diff.Hours()
  820. }
  821. totalSharedCost := cost * hours
  822. shareSet.Insert(&Allocation{
  823. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  824. Start: as.Start(),
  825. End: as.End(),
  826. SharedCost: totalSharedCost,
  827. 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.
  828. })
  829. }
  830. }
  831. // (2d) Compute share coefficients for shared resources. These are computed
  832. // after idle coefficients, and are computed for the aggregated allocations
  833. // of the main allocation set. See above for details and an example.
  834. var shareCoefficients map[string]float64
  835. if shareSet.Length() > 0 {
  836. shareCoefficients, err = computeShareCoeffs(aggregateBy, options, as)
  837. if err != nil {
  838. return fmt.Errorf("error computing share coefficients: %s", err)
  839. }
  840. }
  841. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  842. for _, alloc := range as.allocations {
  843. idleId, err := alloc.getIdleId(options)
  844. if err != nil {
  845. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  846. }
  847. skip := false
  848. // (3) If any of the filter funcs fail, immediately skip the allocation.
  849. for _, ff := range options.FilterFuncs {
  850. if !ff(alloc) {
  851. skip = true
  852. break
  853. }
  854. }
  855. if skip {
  856. // If we are tracking idle filtration coefficients, delete the
  857. // entry corresponding to the filtered allocation. (Deleting the
  858. // entry will result in that proportional amount being removed
  859. // from the idle allocation at the end of the process.)
  860. if idleFiltrationCoefficients != nil {
  861. if ifcc, ok := idleFiltrationCoefficients[idleId]; ok {
  862. delete(ifcc, alloc.Name)
  863. }
  864. }
  865. continue
  866. }
  867. // (4) Distribute idle allocations according to the idle coefficients
  868. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  869. // all idle allocations will be in the aggSet at this point, so idleSet
  870. // will be empty and we won't enter this block.
  871. if idleSet.Length() > 0 {
  872. // Distribute idle allocations by coefficient per-idleId, per-allocation
  873. for _, idleAlloc := range idleSet.allocations {
  874. // Only share idle if the idleId matches; i.e. the allocation
  875. // is from the same idleId as the idle costs
  876. iaidleId, err := idleAlloc.getIdleId(options)
  877. if err != nil {
  878. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  879. return err
  880. }
  881. if iaidleId != idleId {
  882. continue
  883. }
  884. // Make sure idle coefficients exist
  885. if _, ok := idleCoefficients[idleId]; !ok {
  886. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  887. continue
  888. }
  889. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  890. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  891. continue
  892. }
  893. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  894. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  895. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  896. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  897. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  898. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  899. alloc.CPUCost += idleCPUCost
  900. alloc.GPUCost += idleGPUCost
  901. alloc.RAMCost += idleRAMCost
  902. }
  903. }
  904. // (5) generate key to use for aggregation-by-key and allocation name
  905. key := alloc.generateKey(aggregateBy)
  906. alloc.Name = key
  907. if options.MergeUnallocated && alloc.IsUnallocated() {
  908. alloc.Name = UnallocatedSuffix
  909. }
  910. // Inserting the allocation with the generated key for a name will
  911. // perform the actual basic aggregation step.
  912. aggSet.Insert(alloc)
  913. }
  914. // (6) If idle is shared and resources are shared, it's possible that some
  915. // amount of idle cost will be shared with a shared resource. Distribute
  916. // that idle allocation, if it exists, to the respective shared allocations
  917. // before sharing with the aggregated allocations.
  918. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  919. for _, alloc := range shareSet.allocations {
  920. idleId, err := alloc.getIdleId(options)
  921. if err != nil {
  922. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  923. }
  924. // Distribute idle allocations by coefficient per-idleId, per-allocation
  925. for _, idleAlloc := range idleSet.allocations {
  926. // Only share idle if the idleId matches; i.e. the allocation
  927. // is from the same idleId as the idle costs
  928. iaidleId, _ := idleAlloc.getIdleId(options)
  929. if iaidleId != idleId {
  930. continue
  931. }
  932. // Make sure idle coefficients exist
  933. if _, ok := idleCoefficients[idleId]; !ok {
  934. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  935. continue
  936. }
  937. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  938. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  939. continue
  940. }
  941. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  942. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  943. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  944. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  945. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  946. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  947. alloc.CPUCost += idleCPUCost
  948. alloc.GPUCost += idleGPUCost
  949. alloc.RAMCost += idleRAMCost
  950. }
  951. }
  952. }
  953. // groupingIdleFiltrationCoeffs is used to track per-resource idle
  954. // coefficients on a cluster-by-cluster or node-by-node basis depending
  955. // on the IdleByNode option. It is, essentailly, an aggregation of
  956. // idleFiltrationCoefficients after they have been
  957. // filtered above (in step 3)
  958. var groupingIdleFiltrationCoeffs map[string]map[string]float64
  959. if idleFiltrationCoefficients != nil {
  960. groupingIdleFiltrationCoeffs = map[string]map[string]float64{}
  961. for idleId, m := range idleFiltrationCoefficients {
  962. if _, ok := groupingIdleFiltrationCoeffs[idleId]; !ok {
  963. groupingIdleFiltrationCoeffs[idleId] = map[string]float64{
  964. "cpu": 0.0,
  965. "gpu": 0.0,
  966. "ram": 0.0,
  967. }
  968. }
  969. for _, n := range m {
  970. for resource, val := range n {
  971. groupingIdleFiltrationCoeffs[idleId][resource] += val
  972. }
  973. }
  974. }
  975. }
  976. // (7) If we have both un-shared idle allocations and idle filtration
  977. // coefficients then apply those. See step (2b) for an example.
  978. if len(aggSet.idleKeys) > 0 && groupingIdleFiltrationCoeffs != nil {
  979. for idleKey := range aggSet.idleKeys {
  980. idleAlloc := aggSet.Get(idleKey)
  981. iaidleId, err := idleAlloc.getIdleId(options)
  982. if err != nil {
  983. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  984. return err
  985. }
  986. if resourceCoeffs, ok := groupingIdleFiltrationCoeffs[iaidleId]; ok {
  987. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  988. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  989. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  990. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  991. }
  992. }
  993. }
  994. // (8) Distribute shared allocations according to the share coefficients.
  995. if shareSet.Length() > 0 {
  996. for _, alloc := range aggSet.allocations {
  997. for _, sharedAlloc := range shareSet.allocations {
  998. if _, ok := shareCoefficients[alloc.Name]; !ok {
  999. if !alloc.IsIdle() {
  1000. log.Warningf("AllocationSet.AggregateBy: error getting share coefficienct for '%s'", alloc.Name)
  1001. }
  1002. continue
  1003. }
  1004. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  1005. }
  1006. }
  1007. }
  1008. // (9) Aggregate external allocations into aggregated allocations. This may
  1009. // not be possible for every external allocation, but attempt to find an
  1010. // exact key match, given each external allocation's proerties, and
  1011. // aggregate if an exact match is found.
  1012. for _, alloc := range externalSet.allocations {
  1013. skip := false
  1014. for _, ff := range options.FilterFuncs {
  1015. if !ff(alloc) {
  1016. skip = true
  1017. break
  1018. }
  1019. }
  1020. if !skip {
  1021. key := alloc.generateKey(aggregateBy)
  1022. alloc.Name = key
  1023. aggSet.Insert(alloc)
  1024. }
  1025. }
  1026. // (10) Combine all idle allocations into a single "__idle__" allocation
  1027. if !options.SplitIdle {
  1028. for _, idleAlloc := range aggSet.IdleAllocations() {
  1029. aggSet.Delete(idleAlloc.Name)
  1030. idleAlloc.Name = IdleSuffix
  1031. aggSet.Insert(idleAlloc)
  1032. }
  1033. }
  1034. as.allocations = aggSet.allocations
  1035. return nil
  1036. }
  1037. func computeShareCoeffs(aggregateBy []string, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  1038. // Compute coeffs by totalling per-allocation, then dividing by the total.
  1039. coeffs := map[string]float64{}
  1040. // Compute totals for all allocations
  1041. total := 0.0
  1042. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  1043. // counts each aggregation proportionally to its respective costs
  1044. shareType := options.ShareSplit
  1045. // Record allocation values first, then normalize by totals to get percentages
  1046. for _, alloc := range as.allocations {
  1047. if alloc.IsIdle() {
  1048. // Skip idle allocations in coefficient calculation
  1049. continue
  1050. }
  1051. if alloc.IsUnmounted() {
  1052. // Skip unmounted allocations in coefficient calculation
  1053. continue
  1054. }
  1055. // Determine the post-aggregation key under which the allocation will
  1056. // be shared.
  1057. name := alloc.generateKey(aggregateBy)
  1058. // If the current allocation will be filtered out in step 3, contribute
  1059. // its share of the shared coefficient to a "__filtered__" bin, which
  1060. // will ultimately be dropped. This step ensures that the shared cost
  1061. // of a non-filtered allocation will be conserved even when the filter
  1062. // is removed. (Otherwise, all the shared cost will get redistributed
  1063. // over the unfiltered results, inflating their shared costs.)
  1064. filtered := false
  1065. for _, ff := range options.FilterFuncs {
  1066. if !ff(alloc) {
  1067. filtered = true
  1068. break
  1069. }
  1070. }
  1071. if filtered {
  1072. name = "__filtered__"
  1073. }
  1074. if shareType == ShareEven {
  1075. // Even distribution is not additive - set to 1.0 for everything
  1076. coeffs[name] = 1.0
  1077. // Total for even distribution is always the number of coefficients
  1078. total = float64(len(coeffs))
  1079. } else {
  1080. // Both are additive for weighted distribution, where each
  1081. // cumulative coefficient will be divided by the total.
  1082. coeffs[name] += alloc.TotalCost()
  1083. total += alloc.TotalCost()
  1084. }
  1085. }
  1086. // Normalize coefficients by totals
  1087. for a := range coeffs {
  1088. if coeffs[a] > 0 && total > 0 {
  1089. coeffs[a] /= total
  1090. } else {
  1091. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  1092. coeffs[a] = 0.0
  1093. }
  1094. }
  1095. return coeffs, nil
  1096. }
  1097. func computeIdleCoeffs(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, error) {
  1098. types := []string{"cpu", "gpu", "ram"}
  1099. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1100. coeffs := map[string]map[string]map[string]float64{}
  1101. // Compute totals per resource for CPU, GPU, RAM, and PV
  1102. totals := map[string]map[string]float64{}
  1103. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  1104. // counts each allocation proportionally to its respective costs
  1105. shareType := options.ShareIdle
  1106. // Record allocation values first, then normalize by totals to get percentages
  1107. for _, alloc := range as.allocations {
  1108. if alloc.IsIdle() {
  1109. // Skip idle allocations in coefficient calculation
  1110. continue
  1111. }
  1112. idleId, err := alloc.getIdleId(options)
  1113. if err != nil {
  1114. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  1115. }
  1116. // get the name key for the allocation
  1117. name := alloc.Name
  1118. // Create key based tables if they don't exist
  1119. if _, ok := coeffs[idleId]; !ok {
  1120. coeffs[idleId] = map[string]map[string]float64{}
  1121. }
  1122. if _, ok := totals[idleId]; !ok {
  1123. totals[idleId] = map[string]float64{}
  1124. }
  1125. if _, ok := coeffs[idleId][name]; !ok {
  1126. coeffs[idleId][name] = map[string]float64{}
  1127. }
  1128. if shareType == ShareEven {
  1129. for _, r := range types {
  1130. // Not additive - hard set to 1.0
  1131. coeffs[idleId][name][r] = 1.0
  1132. // totals are additive
  1133. totals[idleId][r] += 1.0
  1134. }
  1135. } else {
  1136. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1137. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1138. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1139. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1140. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1141. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1142. }
  1143. }
  1144. // Do the same for shared allocations
  1145. for _, alloc := range shareSet.allocations {
  1146. if alloc.IsIdle() {
  1147. // Skip idle allocations in coefficient calculation
  1148. continue
  1149. }
  1150. // idleId will be providerId or cluster
  1151. idleId, err := alloc.getIdleId(options)
  1152. if err != nil {
  1153. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  1154. }
  1155. // get the name key for the allocation
  1156. name := alloc.Name
  1157. // Create idleId based tables if they don't exist
  1158. if _, ok := coeffs[idleId]; !ok {
  1159. coeffs[idleId] = map[string]map[string]float64{}
  1160. }
  1161. if _, ok := totals[idleId]; !ok {
  1162. totals[idleId] = map[string]float64{}
  1163. }
  1164. if _, ok := coeffs[idleId][name]; !ok {
  1165. coeffs[idleId][name] = map[string]float64{}
  1166. }
  1167. if shareType == ShareEven {
  1168. for _, r := range types {
  1169. // Not additive - hard set to 1.0
  1170. coeffs[idleId][name][r] = 1.0
  1171. // totals are additive
  1172. totals[idleId][r] += 1.0
  1173. }
  1174. } else {
  1175. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1176. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1177. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1178. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1179. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1180. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1181. }
  1182. }
  1183. // Normalize coefficients by totals
  1184. for c := range coeffs {
  1185. for a := range coeffs[c] {
  1186. for _, r := range types {
  1187. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  1188. coeffs[c][a][r] /= totals[c][r]
  1189. }
  1190. }
  1191. }
  1192. }
  1193. return coeffs, nil
  1194. }
  1195. // getIdleId returns the providerId or cluster of an Allocation depending on the IdleByNode
  1196. // option in the AllocationAggregationOptions and an error if the respective field is missing
  1197. func (a *Allocation) getIdleId(options *AllocationAggregationOptions) (string, error) {
  1198. var idleId string
  1199. if options.IdleByNode {
  1200. // Key allocations to ProviderId to match against node
  1201. idleId = a.Properties.ProviderID
  1202. if idleId == "" {
  1203. return idleId, fmt.Errorf("ProviderId is not set")
  1204. }
  1205. } else {
  1206. // key the allocations by cluster id
  1207. idleId = a.Properties.Cluster
  1208. if idleId == "" {
  1209. return idleId, fmt.Errorf("ClusterProp is not set")
  1210. }
  1211. }
  1212. return idleId, nil
  1213. }
  1214. func (a *Allocation) generateKey(aggregateBy []string) string {
  1215. if a == nil {
  1216. return ""
  1217. }
  1218. // Names will ultimately be joined into a single name, which uniquely
  1219. // identifies allocations.
  1220. names := []string{}
  1221. for _, agg := range aggregateBy {
  1222. switch true {
  1223. case agg == AllocationClusterProp:
  1224. names = append(names, a.Properties.Cluster)
  1225. case agg == AllocationNodeProp:
  1226. names = append(names, a.Properties.Node)
  1227. case agg == AllocationNamespaceProp:
  1228. names = append(names, a.Properties.Namespace)
  1229. case agg == AllocationControllerKindProp:
  1230. controllerKind := a.Properties.ControllerKind
  1231. if controllerKind == "" {
  1232. // Indicate that allocation has no controller
  1233. controllerKind = UnallocatedSuffix
  1234. }
  1235. names = append(names, controllerKind)
  1236. case agg == AllocationDaemonSetProp || agg == AllocationStatefulSetProp || agg == AllocationDeploymentProp || agg == AllocationJobProp:
  1237. controller := a.Properties.Controller
  1238. if agg != a.Properties.ControllerKind || controller == "" {
  1239. // The allocation does not have the specified controller kind
  1240. controller = UnallocatedSuffix
  1241. }
  1242. names = append(names, controller)
  1243. case agg == AllocationControllerProp:
  1244. controller := a.Properties.Controller
  1245. if controller == "" {
  1246. // Indicate that allocation has no controller
  1247. controller = UnallocatedSuffix
  1248. } else if a.Properties.ControllerKind != "" {
  1249. controller = fmt.Sprintf("%s:%s", a.Properties.ControllerKind, controller)
  1250. }
  1251. names = append(names, controller)
  1252. case agg == AllocationPodProp:
  1253. names = append(names, a.Properties.Pod)
  1254. case agg == AllocationContainerProp:
  1255. names = append(names, a.Properties.Container)
  1256. case agg == AllocationServiceProp:
  1257. services := a.Properties.Services
  1258. if services == nil || len(services) == 0 {
  1259. // Indicate that allocation has no services
  1260. names = append(names, UnallocatedSuffix)
  1261. } else {
  1262. // This just uses the first service
  1263. for _, service := range services {
  1264. names = append(names, service)
  1265. break
  1266. }
  1267. }
  1268. case strings.HasPrefix(agg, "label:"):
  1269. labels := a.Properties.Labels
  1270. if labels == nil {
  1271. // Indicate that allocation has no labels
  1272. names = append(names, UnallocatedSuffix)
  1273. } else {
  1274. labelNames := []string{}
  1275. aggLabels := strings.Split(strings.TrimPrefix(agg, "label:"), ";")
  1276. for _, labelName := range aggLabels {
  1277. if val, ok := labels[labelName]; ok {
  1278. labelNames = append(labelNames, fmt.Sprintf("%s=%s", labelName, val))
  1279. } else if indexOf(UnallocatedSuffix, labelNames) == -1 { // if UnallocatedSuffix not already in names
  1280. labelNames = append(labelNames, UnallocatedSuffix)
  1281. }
  1282. }
  1283. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1284. if len(labelNames) > 1 {
  1285. sort.Strings(labelNames)
  1286. }
  1287. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, labelNames)
  1288. // suffix should be at index 0 if it exists b/c of underscores
  1289. if unallocatedSuffixIndex != -1 {
  1290. labelNames = append(labelNames[:unallocatedSuffixIndex], labelNames[unallocatedSuffixIndex+1:]...)
  1291. labelNames = append(labelNames, UnallocatedSuffix) // append to end
  1292. }
  1293. names = append(names, labelNames...)
  1294. }
  1295. case strings.HasPrefix(agg, "annotation:"):
  1296. annotations := a.Properties.Annotations
  1297. if annotations == nil {
  1298. // Indicate that allocation has no annotations
  1299. names = append(names, UnallocatedSuffix)
  1300. } else {
  1301. annotationNames := []string{}
  1302. aggAnnotations := strings.Split(strings.TrimPrefix(agg, "annotation:"), ";")
  1303. for _, annotationName := range aggAnnotations {
  1304. if val, ok := annotations[annotationName]; ok {
  1305. annotationNames = append(annotationNames, fmt.Sprintf("%s=%s", annotationName, val))
  1306. } else if indexOf(UnallocatedSuffix, annotationNames) == -1 { // if UnallocatedSuffix not already in names
  1307. annotationNames = append(annotationNames, UnallocatedSuffix)
  1308. }
  1309. }
  1310. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1311. if len(annotationNames) > 1 {
  1312. sort.Strings(annotationNames)
  1313. }
  1314. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, annotationNames)
  1315. // suffix should be at index 0 if it exists b/c of underscores
  1316. if unallocatedSuffixIndex != -1 {
  1317. annotationNames = append(annotationNames[:unallocatedSuffixIndex], annotationNames[unallocatedSuffixIndex+1:]...)
  1318. annotationNames = append(annotationNames, UnallocatedSuffix) // append to end
  1319. }
  1320. names = append(names, annotationNames...)
  1321. }
  1322. }
  1323. }
  1324. return strings.Join(names, "/")
  1325. }
  1326. // TODO:CLEANUP get rid of this
  1327. // Helper function to check for slice membership. Not sure if repeated elsewhere in our codebase.
  1328. func indexOf(v string, arr []string) int {
  1329. for i, s := range arr {
  1330. // This is caseless equivalence
  1331. if strings.EqualFold(v, s) {
  1332. return i
  1333. }
  1334. }
  1335. return -1
  1336. }
  1337. // Clone returns a new AllocationSet with a deep copy of the given
  1338. // AllocationSet's allocations.
  1339. func (as *AllocationSet) Clone() *AllocationSet {
  1340. if as == nil {
  1341. return nil
  1342. }
  1343. as.RLock()
  1344. defer as.RUnlock()
  1345. allocs := map[string]*Allocation{}
  1346. for k, v := range as.allocations {
  1347. allocs[k] = v.Clone()
  1348. }
  1349. externalKeys := map[string]bool{}
  1350. for k, v := range as.externalKeys {
  1351. externalKeys[k] = v
  1352. }
  1353. idleKeys := map[string]bool{}
  1354. for k, v := range as.idleKeys {
  1355. idleKeys[k] = v
  1356. }
  1357. return &AllocationSet{
  1358. allocations: allocs,
  1359. externalKeys: externalKeys,
  1360. idleKeys: idleKeys,
  1361. Window: as.Window.Clone(),
  1362. }
  1363. }
  1364. // ComputeIdleAllocations computes the idle allocations for the AllocationSet,
  1365. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1366. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1367. // considered for idle allocation. If the Nodes have adjustments, then apply
  1368. // the adjustments proportionally to each of the resources so that total
  1369. // allocation with idle reflects the adjusted node costs. One idle allocation
  1370. // per-cluster will be computed and returned, keyed by cluster_id.
  1371. func (as *AllocationSet) ComputeIdleAllocations(assetSet *AssetSet) (map[string]*Allocation, error) {
  1372. if as == nil {
  1373. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1374. }
  1375. if assetSet == nil {
  1376. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1377. }
  1378. if !as.Window.Equal(assetSet.Window) {
  1379. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1380. }
  1381. window := as.Window
  1382. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1383. // cluster-to-{cpu|gpu|ram}-to-cost.
  1384. assetClusterResourceCosts := map[string]map[string]float64{}
  1385. assetSet.Each(func(key string, a Asset) {
  1386. if node, ok := a.(*Node); ok {
  1387. if _, ok := assetClusterResourceCosts[node.Properties().Cluster]; !ok {
  1388. assetClusterResourceCosts[node.Properties().Cluster] = map[string]float64{}
  1389. }
  1390. // adjustmentRate is used to scale resource costs proportionally
  1391. // by the adjustment. This is necessary because we only get one
  1392. // adjustment per Node, not one per-resource-per-Node.
  1393. //
  1394. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1395. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1396. // e.g. total cost = $150, adjustment = $50 => 1.5
  1397. adjustmentRate := 1.0
  1398. if node.TotalCost()-node.Adjustment() == 0 {
  1399. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1400. // the entire node cost and we should make everything 0
  1401. // without dividing by 0.
  1402. adjustmentRate = 0.0
  1403. log.DedupedWarningf(5, "Compute Idle Allocations: Node Cost Adjusted to $0.00 for %s", node.properties.Name)
  1404. } else if node.Adjustment() != 0.0 {
  1405. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1406. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1407. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1408. }
  1409. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1410. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1411. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1412. assetClusterResourceCosts[node.Properties().Cluster]["cpu"] += cpuCost
  1413. assetClusterResourceCosts[node.Properties().Cluster]["gpu"] += gpuCost
  1414. assetClusterResourceCosts[node.Properties().Cluster]["ram"] += ramCost
  1415. }
  1416. })
  1417. // Determine start, end on a per-cluster basis
  1418. clusterStarts := map[string]time.Time{}
  1419. clusterEnds := map[string]time.Time{}
  1420. // Subtract allocated costs from asset costs, leaving only the remaining
  1421. // idle costs.
  1422. as.Each(func(name string, a *Allocation) {
  1423. cluster := a.Properties.Cluster
  1424. if cluster == "" {
  1425. // Failed to find allocation's cluster
  1426. return
  1427. }
  1428. if _, ok := assetClusterResourceCosts[cluster]; !ok {
  1429. // Failed to find assets for allocation's cluster
  1430. return
  1431. }
  1432. // Set cluster (start, end) if they are either not currently set,
  1433. // or if the detected (start, end) of the current allocation falls
  1434. // before or after, respectively, the current values.
  1435. if s, ok := clusterStarts[cluster]; !ok || a.Start.Before(s) {
  1436. clusterStarts[cluster] = a.Start
  1437. }
  1438. if e, ok := clusterEnds[cluster]; !ok || a.End.After(e) {
  1439. clusterEnds[cluster] = a.End
  1440. }
  1441. assetClusterResourceCosts[cluster]["cpu"] -= a.CPUTotalCost()
  1442. assetClusterResourceCosts[cluster]["gpu"] -= a.GPUTotalCost()
  1443. assetClusterResourceCosts[cluster]["ram"] -= a.RAMTotalCost()
  1444. })
  1445. // Turn remaining un-allocated asset costs into idle allocations
  1446. idleAllocs := map[string]*Allocation{}
  1447. for cluster, resources := range assetClusterResourceCosts {
  1448. // Default start and end to the (start, end) of the given window, but
  1449. // use the actual, detected (start, end) pair if they are available.
  1450. start := *window.Start()
  1451. if s, ok := clusterStarts[cluster]; ok && window.Contains(s) {
  1452. start = s
  1453. }
  1454. end := *window.End()
  1455. if e, ok := clusterEnds[cluster]; ok && window.Contains(e) {
  1456. end = e
  1457. }
  1458. idleAlloc := &Allocation{
  1459. Name: fmt.Sprintf("%s/%s", cluster, IdleSuffix),
  1460. Window: window.Clone(),
  1461. Properties: &AllocationProperties{Cluster: cluster},
  1462. Start: start,
  1463. End: end,
  1464. CPUCost: resources["cpu"],
  1465. GPUCost: resources["gpu"],
  1466. RAMCost: resources["ram"],
  1467. }
  1468. // Do not continue if multiple idle allocations are computed for a
  1469. // single cluster.
  1470. if _, ok := idleAllocs[cluster]; ok {
  1471. return nil, fmt.Errorf("duplicate idle allocations for cluster %s", cluster)
  1472. }
  1473. idleAllocs[cluster] = idleAlloc
  1474. }
  1475. return idleAllocs, nil
  1476. }
  1477. // ComputeIdleAllocationsByNode computes the idle allocations for the AllocationSet,
  1478. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1479. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1480. // considered for idle allocation. If the Nodes have adjustments, then apply
  1481. // the adjustments proportionally to each of the resources so that total
  1482. // allocation with idle reflects the adjusted node costs. One idle allocation
  1483. // per-node will be computed and returned, keyed by cluster_id.
  1484. func (as *AllocationSet) ComputeIdleAllocationsByNode(assetSet *AssetSet) (map[string]*Allocation, error) {
  1485. if as == nil {
  1486. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1487. }
  1488. if assetSet == nil {
  1489. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1490. }
  1491. if !as.Window.Equal(assetSet.Window) {
  1492. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1493. }
  1494. window := as.Window
  1495. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1496. // cluster-to-{cpu|gpu|ram}-to-cost.
  1497. assetNodeResourceCosts := map[string]map[string]float64{}
  1498. nodesByProviderId := map[string]*Node{}
  1499. assetSet.Each(func(key string, a Asset) {
  1500. if node, ok := a.(*Node); ok {
  1501. if _, ok := assetNodeResourceCosts[node.Properties().ProviderID]; ok || node.Properties().ProviderID == "" {
  1502. log.DedupedWarningf(5, "Compute Idle Allocations By Node: Node missing providerId: %s", node.properties.Name)
  1503. return
  1504. }
  1505. nodesByProviderId[node.Properties().ProviderID] = node
  1506. assetNodeResourceCosts[node.Properties().ProviderID] = map[string]float64{}
  1507. // adjustmentRate is used to scale resource costs proportionally
  1508. // by the adjustment. This is necessary because we only get one
  1509. // adjustment per Node, not one per-resource-per-Node.
  1510. //
  1511. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1512. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1513. // e.g. total cost = $150, adjustment = $50 => 1.5
  1514. adjustmentRate := 1.0
  1515. if node.TotalCost()-node.Adjustment() == 0 {
  1516. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1517. // the entire node cost and we should make everything 0
  1518. // without dividing by 0.
  1519. adjustmentRate = 0.0
  1520. log.DedupedWarningf(5, "Compute Idle Allocations: Node Cost Adjusted to $0.00 for %s", node.properties.Name)
  1521. } else if node.Adjustment() != 0.0 {
  1522. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1523. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1524. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1525. }
  1526. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1527. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1528. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1529. assetNodeResourceCosts[node.Properties().ProviderID]["cpu"] += cpuCost
  1530. assetNodeResourceCosts[node.Properties().ProviderID]["gpu"] += gpuCost
  1531. assetNodeResourceCosts[node.Properties().ProviderID]["ram"] += ramCost
  1532. }
  1533. })
  1534. // Determine start, end on a per-cluster basis
  1535. nodeStarts := map[string]time.Time{}
  1536. nodeEnds := map[string]time.Time{}
  1537. // Subtract allocated costs from asset costs, leaving only the remaining
  1538. // idle costs.
  1539. as.Each(func(name string, a *Allocation) {
  1540. providerId := a.Properties.ProviderID
  1541. if providerId == "" {
  1542. // Failed to find allocation's node
  1543. log.DedupedWarningf(5, "Compute Idle Allocations By Node: Allocation missing providerId: %s", a.Name)
  1544. return
  1545. }
  1546. if _, ok := assetNodeResourceCosts[providerId]; !ok {
  1547. // Failed to find assets for allocation's node
  1548. return
  1549. }
  1550. // Set cluster (start, end) if they are either not currently set,
  1551. // or if the detected (start, end) of the current allocation falls
  1552. // before or after, respectively, the current values.
  1553. if s, ok := nodeStarts[providerId]; !ok || a.Start.Before(s) {
  1554. nodeStarts[providerId] = a.Start
  1555. }
  1556. if e, ok := nodeEnds[providerId]; !ok || a.End.After(e) {
  1557. nodeEnds[providerId] = a.End
  1558. }
  1559. assetNodeResourceCosts[providerId]["cpu"] -= a.CPUTotalCost()
  1560. assetNodeResourceCosts[providerId]["gpu"] -= a.GPUTotalCost()
  1561. assetNodeResourceCosts[providerId]["ram"] -= a.RAMTotalCost()
  1562. })
  1563. // Turn remaining un-allocated asset costs into idle allocations
  1564. idleAllocs := map[string]*Allocation{}
  1565. for providerId, resources := range assetNodeResourceCosts {
  1566. // Default start and end to the (start, end) of the given window, but
  1567. // use the actual, detected (start, end) pair if they are available.
  1568. start := *window.Start()
  1569. if s, ok := nodeStarts[providerId]; ok && window.Contains(s) {
  1570. start = s
  1571. }
  1572. end := *window.End()
  1573. if e, ok := nodeEnds[providerId]; ok && window.Contains(e) {
  1574. end = e
  1575. }
  1576. node := nodesByProviderId[providerId]
  1577. idleAlloc := &Allocation{
  1578. Name: fmt.Sprintf("%s/%s", node.properties.Name, IdleSuffix),
  1579. Window: window.Clone(),
  1580. Properties: &AllocationProperties{
  1581. Cluster: node.properties.Cluster,
  1582. Node: node.properties.Name,
  1583. ProviderID: providerId,
  1584. },
  1585. Start: start,
  1586. End: end,
  1587. CPUCost: resources["cpu"],
  1588. GPUCost: resources["gpu"],
  1589. RAMCost: resources["ram"],
  1590. }
  1591. // Do not continue if multiple idle allocations are computed for a
  1592. // single node.
  1593. if _, ok := idleAllocs[providerId]; ok {
  1594. return nil, fmt.Errorf("duplicate idle allocations for node Provider ID: %s", providerId)
  1595. }
  1596. idleAllocs[providerId] = idleAlloc
  1597. }
  1598. return idleAllocs, nil
  1599. }
  1600. // Delete removes the allocation with the given name from the set
  1601. func (as *AllocationSet) Delete(name string) {
  1602. if as == nil {
  1603. return
  1604. }
  1605. as.Lock()
  1606. defer as.Unlock()
  1607. delete(as.externalKeys, name)
  1608. delete(as.idleKeys, name)
  1609. delete(as.allocations, name)
  1610. }
  1611. // Each invokes the given function for each Allocation in the set
  1612. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  1613. if as == nil {
  1614. return
  1615. }
  1616. for k, a := range as.allocations {
  1617. f(k, a)
  1618. }
  1619. }
  1620. // End returns the End time of the AllocationSet window
  1621. func (as *AllocationSet) End() time.Time {
  1622. if as == nil {
  1623. log.Warningf("AllocationSet: calling End on nil AllocationSet")
  1624. return time.Unix(0, 0)
  1625. }
  1626. if as.Window.End() == nil {
  1627. log.Warningf("AllocationSet: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  1628. return time.Unix(0, 0)
  1629. }
  1630. return *as.Window.End()
  1631. }
  1632. // Get returns the Allocation at the given key in the AllocationSet
  1633. func (as *AllocationSet) Get(key string) *Allocation {
  1634. as.RLock()
  1635. defer as.RUnlock()
  1636. if alloc, ok := as.allocations[key]; ok {
  1637. return alloc
  1638. }
  1639. return nil
  1640. }
  1641. // ExternalAllocations returns a map of the external allocations in the set.
  1642. // Returns clones of the actual Allocations, so mutability is not a problem.
  1643. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1644. externals := map[string]*Allocation{}
  1645. if as.IsEmpty() {
  1646. return externals
  1647. }
  1648. as.RLock()
  1649. defer as.RUnlock()
  1650. for key := range as.externalKeys {
  1651. if alloc, ok := as.allocations[key]; ok {
  1652. externals[key] = alloc.Clone()
  1653. }
  1654. }
  1655. return externals
  1656. }
  1657. // ExternalCost returns the total aggregated external costs of the set
  1658. func (as *AllocationSet) ExternalCost() float64 {
  1659. if as.IsEmpty() {
  1660. return 0.0
  1661. }
  1662. as.RLock()
  1663. defer as.RUnlock()
  1664. externalCost := 0.0
  1665. for _, alloc := range as.allocations {
  1666. externalCost += alloc.ExternalCost
  1667. }
  1668. return externalCost
  1669. }
  1670. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1671. // Returns clones of the actual Allocations, so mutability is not a problem.
  1672. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1673. idles := map[string]*Allocation{}
  1674. if as.IsEmpty() {
  1675. return idles
  1676. }
  1677. as.RLock()
  1678. defer as.RUnlock()
  1679. for key := range as.idleKeys {
  1680. if alloc, ok := as.allocations[key]; ok {
  1681. idles[key] = alloc.Clone()
  1682. }
  1683. }
  1684. return idles
  1685. }
  1686. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1687. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1688. // there is no existing entry, one is created. Nil error response indicates success.
  1689. func (as *AllocationSet) Insert(that *Allocation) error {
  1690. return as.insert(that)
  1691. }
  1692. func (as *AllocationSet) insert(that *Allocation) error {
  1693. if as == nil {
  1694. return fmt.Errorf("cannot insert into nil AllocationSet")
  1695. }
  1696. as.Lock()
  1697. defer as.Unlock()
  1698. if as.allocations == nil {
  1699. as.allocations = map[string]*Allocation{}
  1700. }
  1701. if as.externalKeys == nil {
  1702. as.externalKeys = map[string]bool{}
  1703. }
  1704. if as.idleKeys == nil {
  1705. as.idleKeys = map[string]bool{}
  1706. }
  1707. // Add the given Allocation to the existing entry, if there is one;
  1708. // otherwise just set directly into allocations
  1709. if _, ok := as.allocations[that.Name]; !ok {
  1710. as.allocations[that.Name] = that
  1711. } else {
  1712. as.allocations[that.Name].add(that)
  1713. }
  1714. // If the given Allocation is an external one, record that
  1715. if that.IsExternal() {
  1716. as.externalKeys[that.Name] = true
  1717. }
  1718. // If the given Allocation is an idle one, record that
  1719. if that.IsIdle() {
  1720. as.idleKeys[that.Name] = true
  1721. }
  1722. return nil
  1723. }
  1724. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  1725. // zero allocations.
  1726. func (as *AllocationSet) IsEmpty() bool {
  1727. if as == nil || len(as.allocations) == 0 {
  1728. return true
  1729. }
  1730. as.RLock()
  1731. defer as.RUnlock()
  1732. return as.allocations == nil || len(as.allocations) == 0
  1733. }
  1734. // Length returns the number of Allocations in the set
  1735. func (as *AllocationSet) Length() int {
  1736. if as == nil {
  1737. return 0
  1738. }
  1739. as.RLock()
  1740. defer as.RUnlock()
  1741. return len(as.allocations)
  1742. }
  1743. // Map clones and returns a map of the AllocationSet's Allocations
  1744. func (as *AllocationSet) Map() map[string]*Allocation {
  1745. if as.IsEmpty() {
  1746. return map[string]*Allocation{}
  1747. }
  1748. return as.Clone().allocations
  1749. }
  1750. // MarshalJSON JSON-encodes the AllocationSet
  1751. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  1752. as.RLock()
  1753. defer as.RUnlock()
  1754. return json.Marshal(as.allocations)
  1755. }
  1756. // Resolution returns the AllocationSet's window duration
  1757. func (as *AllocationSet) Resolution() time.Duration {
  1758. return as.Window.Duration()
  1759. }
  1760. // Set uses the given Allocation to overwrite the existing entry in the
  1761. // AllocationSet under the Allocation's name.
  1762. func (as *AllocationSet) Set(alloc *Allocation) error {
  1763. if as.IsEmpty() {
  1764. as.Lock()
  1765. as.allocations = map[string]*Allocation{}
  1766. as.externalKeys = map[string]bool{}
  1767. as.idleKeys = map[string]bool{}
  1768. as.Unlock()
  1769. }
  1770. as.Lock()
  1771. defer as.Unlock()
  1772. as.allocations[alloc.Name] = alloc
  1773. // If the given Allocation is an external one, record that
  1774. if alloc.IsExternal() {
  1775. as.externalKeys[alloc.Name] = true
  1776. }
  1777. // If the given Allocation is an idle one, record that
  1778. if alloc.IsIdle() {
  1779. as.idleKeys[alloc.Name] = true
  1780. }
  1781. return nil
  1782. }
  1783. // Start returns the Start time of the AllocationSet window
  1784. func (as *AllocationSet) Start() time.Time {
  1785. if as == nil {
  1786. log.Warningf("AllocationSet: calling Start on nil AllocationSet")
  1787. return time.Unix(0, 0)
  1788. }
  1789. if as.Window.Start() == nil {
  1790. log.Warningf("AllocationSet: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1791. return time.Unix(0, 0)
  1792. }
  1793. return *as.Window.Start()
  1794. }
  1795. // String represents the given Allocation as a string
  1796. func (as *AllocationSet) String() string {
  1797. if as == nil {
  1798. return "<nil>"
  1799. }
  1800. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1801. as.Length(), as.Window, as.TotalCost())
  1802. }
  1803. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1804. func (as *AllocationSet) TotalCost() float64 {
  1805. if as.IsEmpty() {
  1806. return 0.0
  1807. }
  1808. as.RLock()
  1809. defer as.RUnlock()
  1810. tc := 0.0
  1811. for _, a := range as.allocations {
  1812. tc += a.TotalCost()
  1813. }
  1814. return tc
  1815. }
  1816. // UTCOffset returns the AllocationSet's configured UTCOffset.
  1817. func (as *AllocationSet) UTCOffset() time.Duration {
  1818. _, zone := as.Start().Zone()
  1819. return time.Duration(zone) * time.Second
  1820. }
  1821. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1822. if as.IsEmpty() {
  1823. return that.Clone(), nil
  1824. }
  1825. if that.IsEmpty() {
  1826. return as.Clone(), nil
  1827. }
  1828. // Set start, end to min(start), max(end)
  1829. start := as.Start()
  1830. end := as.End()
  1831. if that.Start().Before(start) {
  1832. start = that.Start()
  1833. }
  1834. if that.End().After(end) {
  1835. end = that.End()
  1836. }
  1837. acc := NewAllocationSet(start, end)
  1838. as.RLock()
  1839. defer as.RUnlock()
  1840. that.RLock()
  1841. defer that.RUnlock()
  1842. for _, alloc := range as.allocations {
  1843. err := acc.insert(alloc)
  1844. if err != nil {
  1845. return nil, err
  1846. }
  1847. }
  1848. for _, alloc := range that.allocations {
  1849. err := acc.insert(alloc)
  1850. if err != nil {
  1851. return nil, err
  1852. }
  1853. }
  1854. return acc, nil
  1855. }
  1856. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  1857. // be used such that the AllocationSets held are consecutive and coherent with
  1858. // respect to using the same aggregation properties, UTC offset, and
  1859. // resolution. However these rules are not necessarily enforced, so use wisely.
  1860. type AllocationSetRange struct {
  1861. sync.RWMutex
  1862. allocations []*AllocationSet
  1863. FromStore string // stores the name of the store used to retrieve the data
  1864. }
  1865. // NewAllocationSetRange instantiates a new range composed of the given
  1866. // AllocationSets in the order provided.
  1867. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1868. return &AllocationSetRange{
  1869. allocations: allocs,
  1870. }
  1871. }
  1872. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1873. // AllocationSet for the entire range.
  1874. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1875. var allocSet *AllocationSet
  1876. var err error
  1877. asr.RLock()
  1878. defer asr.RUnlock()
  1879. for _, as := range asr.allocations {
  1880. allocSet, err = allocSet.accumulate(as)
  1881. if err != nil {
  1882. return nil, err
  1883. }
  1884. }
  1885. return allocSet, nil
  1886. }
  1887. // TODO accumulate into lower-resolution chunks of the given resolution
  1888. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1889. // AggregateBy aggregates each AllocationSet in the range by the given
  1890. // properties and options.
  1891. func (asr *AllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  1892. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1893. asr.Lock()
  1894. defer asr.Unlock()
  1895. for _, as := range asr.allocations {
  1896. err := as.AggregateBy(aggregateBy, options)
  1897. if err != nil {
  1898. return err
  1899. }
  1900. aggRange.allocations = append(aggRange.allocations, as)
  1901. }
  1902. asr.allocations = aggRange.allocations
  1903. return nil
  1904. }
  1905. // Append appends the given AllocationSet to the end of the range. It does not
  1906. // validate whether or not that violates window continuity.
  1907. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1908. asr.Lock()
  1909. defer asr.Unlock()
  1910. asr.allocations = append(asr.allocations, that)
  1911. }
  1912. // Each invokes the given function for each AllocationSet in the range
  1913. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1914. if asr == nil {
  1915. return
  1916. }
  1917. for i, as := range asr.allocations {
  1918. f(i, as)
  1919. }
  1920. }
  1921. // Get retrieves the AllocationSet at the given index of the range.
  1922. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  1923. if i < 0 || i >= len(asr.allocations) {
  1924. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  1925. }
  1926. asr.RLock()
  1927. defer asr.RUnlock()
  1928. return asr.allocations[i], nil
  1929. }
  1930. // InsertRange merges the given AllocationSetRange into the receiving one by
  1931. // lining up sets with matching windows, then inserting each allocation from
  1932. // the given ASR into the respective set in the receiving ASR. If the given
  1933. // ASR contains an AllocationSet from a window that does not exist in the
  1934. // receiving ASR, then an error is returned. However, the given ASR does not
  1935. // need to cover the full range of the receiver.
  1936. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  1937. if asr == nil {
  1938. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  1939. }
  1940. // keys maps window to index in asr
  1941. keys := map[string]int{}
  1942. asr.Each(func(i int, as *AllocationSet) {
  1943. if as == nil {
  1944. return
  1945. }
  1946. keys[as.Window.String()] = i
  1947. })
  1948. // Nothing to merge, so simply return
  1949. if len(keys) == 0 {
  1950. return nil
  1951. }
  1952. var err error
  1953. that.Each(func(j int, thatAS *AllocationSet) {
  1954. if thatAS == nil || err != nil {
  1955. return
  1956. }
  1957. // Find matching AllocationSet in asr
  1958. i, ok := keys[thatAS.Window.String()]
  1959. if !ok {
  1960. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  1961. return
  1962. }
  1963. as, err := asr.Get(i)
  1964. if err != nil {
  1965. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  1966. return
  1967. }
  1968. // Insert each Allocation from the given set
  1969. thatAS.Each(func(k string, alloc *Allocation) {
  1970. err = as.Insert(alloc)
  1971. if err != nil {
  1972. err = fmt.Errorf("error inserting allocation: %s", err)
  1973. return
  1974. }
  1975. })
  1976. })
  1977. // err might be nil
  1978. return err
  1979. }
  1980. // Length returns the length of the range, which is zero if nil
  1981. func (asr *AllocationSetRange) Length() int {
  1982. if asr == nil || asr.allocations == nil {
  1983. return 0
  1984. }
  1985. asr.RLock()
  1986. defer asr.RUnlock()
  1987. return len(asr.allocations)
  1988. }
  1989. // MarshalJSON JSON-encodes the range
  1990. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  1991. asr.RLock()
  1992. asr.RUnlock()
  1993. return json.Marshal(asr.allocations)
  1994. }
  1995. // Slice copies the underlying slice of AllocationSets, maintaining order,
  1996. // and returns the copied slice.
  1997. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  1998. if asr == nil || asr.allocations == nil {
  1999. return nil
  2000. }
  2001. asr.RLock()
  2002. defer asr.RUnlock()
  2003. copy := []*AllocationSet{}
  2004. for _, as := range asr.allocations {
  2005. copy = append(copy, as.Clone())
  2006. }
  2007. return copy
  2008. }
  2009. // String represents the given AllocationSetRange as a string
  2010. func (asr *AllocationSetRange) String() string {
  2011. if asr == nil {
  2012. return "<nil>"
  2013. }
  2014. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  2015. }
  2016. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  2017. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  2018. // are sets with conflicting UTCOffsets (just returns the first).
  2019. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  2020. if asr.Length() == 0 {
  2021. return 0
  2022. }
  2023. as, err := asr.Get(0)
  2024. if err != nil {
  2025. return 0
  2026. }
  2027. return as.UTCOffset()
  2028. }
  2029. // Window returns the full window that the AllocationSetRange spans, from the
  2030. // start of the first AllocationSet to the end of the last one.
  2031. func (asr *AllocationSetRange) Window() Window {
  2032. if asr == nil || asr.Length() == 0 {
  2033. return NewWindow(nil, nil)
  2034. }
  2035. start := asr.allocations[0].Start()
  2036. end := asr.allocations[asr.Length()-1].End()
  2037. return NewWindow(&start, &end)
  2038. }