allocation.go 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  1. package kubecost
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/kubecost/cost-model/pkg/log"
  11. "github.com/kubecost/cost-model/pkg/util"
  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 Properties and an
  38. // Assets-style key() function for AllocationSet.
  39. type Allocation struct {
  40. Name string `json:"name"`
  41. Properties Properties `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. GPUHours float64 `json:"gpuHours"`
  50. GPUCost float64 `json:"gpuCost"`
  51. NetworkCost float64 `json:"networkCost"`
  52. PVByteHours float64 `json:"pvByteHours"`
  53. PVCost float64 `json:"pvCost"`
  54. RAMByteHours float64 `json:"ramByteHours"`
  55. RAMBytesRequestAverage float64 `json:"ramByteRequestAverage"`
  56. RAMBytesUsageAverage float64 `json:"ramByteUsageAverage"`
  57. RAMCost float64 `json:"ramCost"`
  58. SharedCost float64 `json:"sharedCost"`
  59. ExternalCost float64 `json:"externalCost"`
  60. }
  61. // AllocationMatchFunc is a function that can be used to match Allocations by
  62. // returning true for any given Allocation if a condition is met.
  63. type AllocationMatchFunc func(*Allocation) bool
  64. // Add returns the result of summing the two given Allocations, which sums the
  65. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  66. // the two original Allocations are mutated in the process.
  67. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  68. if a == nil {
  69. return that.Clone(), nil
  70. }
  71. if that == nil {
  72. return a.Clone(), nil
  73. }
  74. // Note: no need to clone "that", as add only mutates the receiver
  75. agg := a.Clone()
  76. agg.add(that)
  77. return agg, nil
  78. }
  79. // Clone returns a deep copy of the given Allocation
  80. func (a *Allocation) Clone() *Allocation {
  81. if a == nil {
  82. return nil
  83. }
  84. return &Allocation{
  85. Name: a.Name,
  86. Properties: a.Properties.Clone(),
  87. Window: a.Window.Clone(),
  88. Start: a.Start,
  89. End: a.End,
  90. CPUCoreHours: a.CPUCoreHours,
  91. CPUCoreRequestAverage: a.CPUCoreRequestAverage,
  92. CPUCoreUsageAverage: a.CPUCoreUsageAverage,
  93. CPUCost: a.CPUCost,
  94. GPUHours: a.GPUHours,
  95. GPUCost: a.GPUCost,
  96. NetworkCost: a.NetworkCost,
  97. PVByteHours: a.PVByteHours,
  98. PVCost: a.PVCost,
  99. RAMByteHours: a.RAMByteHours,
  100. RAMBytesRequestAverage: a.RAMBytesRequestAverage,
  101. RAMBytesUsageAverage: a.RAMBytesUsageAverage,
  102. RAMCost: a.RAMCost,
  103. SharedCost: a.SharedCost,
  104. ExternalCost: a.ExternalCost,
  105. }
  106. }
  107. // Equal returns true if the values held in the given Allocation precisely
  108. // match those of the receiving Allocation. nil does not match nil. Floating
  109. // point values need to match according to util.IsApproximately, which accounts
  110. // for small, reasonable floating point error margins.
  111. func (a *Allocation) Equal(that *Allocation) bool {
  112. if a == nil || that == nil {
  113. return false
  114. }
  115. if a.Name != that.Name {
  116. return false
  117. }
  118. if !a.Properties.Equal(&that.Properties) {
  119. return false
  120. }
  121. if !a.Window.Equal(that.Window) {
  122. return false
  123. }
  124. if !a.Start.Equal(that.Start) {
  125. return false
  126. }
  127. if !a.End.Equal(that.End) {
  128. return false
  129. }
  130. if !util.IsApproximately(a.CPUCoreHours, that.CPUCoreHours) {
  131. return false
  132. }
  133. if !util.IsApproximately(a.CPUCost, that.CPUCost) {
  134. return false
  135. }
  136. if !util.IsApproximately(a.GPUHours, that.GPUHours) {
  137. return false
  138. }
  139. if !util.IsApproximately(a.GPUCost, that.GPUCost) {
  140. return false
  141. }
  142. if !util.IsApproximately(a.NetworkCost, that.NetworkCost) {
  143. return false
  144. }
  145. if !util.IsApproximately(a.PVByteHours, that.PVByteHours) {
  146. return false
  147. }
  148. if !util.IsApproximately(a.PVCost, that.PVCost) {
  149. return false
  150. }
  151. if !util.IsApproximately(a.RAMByteHours, that.RAMByteHours) {
  152. return false
  153. }
  154. if !util.IsApproximately(a.RAMCost, that.RAMCost) {
  155. return false
  156. }
  157. if !util.IsApproximately(a.SharedCost, that.SharedCost) {
  158. return false
  159. }
  160. if !util.IsApproximately(a.ExternalCost, that.ExternalCost) {
  161. return false
  162. }
  163. return true
  164. }
  165. // TotalCost is the total cost of the Allocation
  166. func (a *Allocation) TotalCost() float64 {
  167. return a.CPUCost + a.GPUCost + a.RAMCost + a.PVCost + a.NetworkCost + a.SharedCost + a.ExternalCost
  168. }
  169. // CPUEfficiency is the ratio of usage to request. If there is no request and
  170. // no usage or cost, then efficiency is zero. If there is no request, but there
  171. // is usage or cost, then efficiency is 100%.
  172. func (a *Allocation) CPUEfficiency() float64 {
  173. if a.CPUCoreRequestAverage > 0 {
  174. return a.CPUCoreUsageAverage / a.CPUCoreRequestAverage
  175. }
  176. if a.CPUCoreUsageAverage == 0.0 || a.CPUCost == 0.0 {
  177. return 0.0
  178. }
  179. return 1.0
  180. }
  181. // RAMEfficiency is the ratio of usage to request. If there is no request and
  182. // no usage or cost, then efficiency is zero. If there is no request, but there
  183. // is usage or cost, then efficiency is 100%.
  184. func (a *Allocation) RAMEfficiency() float64 {
  185. if a.RAMBytesRequestAverage > 0 {
  186. return a.RAMBytesUsageAverage / a.RAMBytesRequestAverage
  187. }
  188. if a.RAMBytesUsageAverage == 0.0 || a.RAMCost == 0.0 {
  189. return 0.0
  190. }
  191. return 1.0
  192. }
  193. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  194. // there is no cost at all, then efficiency is zero.
  195. func (a *Allocation) TotalEfficiency() float64 {
  196. if a.CPUCost+a.RAMCost > 0 {
  197. ramCostEff := a.RAMEfficiency() * a.RAMCost
  198. cpuCostEff := a.CPUEfficiency() * a.CPUCost
  199. return (ramCostEff + cpuCostEff) / (a.CPUCost + a.RAMCost)
  200. }
  201. return 0.0
  202. }
  203. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  204. func (a *Allocation) CPUCores() float64 {
  205. if a.Minutes() <= 0.0 {
  206. return 0.0
  207. }
  208. return a.CPUCoreHours / (a.Minutes() / 60.0)
  209. }
  210. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  211. func (a *Allocation) RAMBytes() float64 {
  212. if a.Minutes() <= 0.0 {
  213. return 0.0
  214. }
  215. return a.RAMByteHours / (a.Minutes() / 60.0)
  216. }
  217. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  218. func (a *Allocation) PVBytes() float64 {
  219. if a.Minutes() <= 0.0 {
  220. return 0.0
  221. }
  222. return a.PVByteHours / (a.Minutes() / 60.0)
  223. }
  224. // MarshalJSON implements json.Marshal interface
  225. func (a *Allocation) MarshalJSON() ([]byte, error) {
  226. buffer := bytes.NewBufferString("{")
  227. jsonEncodeString(buffer, "name", a.Name, ",")
  228. jsonEncode(buffer, "properties", a.Properties, ",")
  229. jsonEncode(buffer, "window", a.Window, ",")
  230. jsonEncodeString(buffer, "start", a.Start.Format(time.RFC3339), ",")
  231. jsonEncodeString(buffer, "end", a.End.Format(time.RFC3339), ",")
  232. jsonEncodeFloat64(buffer, "minutes", a.Minutes(), ",")
  233. jsonEncodeFloat64(buffer, "cpuCores", a.CPUCores(), ",")
  234. jsonEncodeFloat64(buffer, "cpuCoreRequestAverage", a.CPUCoreRequestAverage, ",")
  235. jsonEncodeFloat64(buffer, "cpuCoreUsageAverage", a.CPUCoreUsageAverage, ",")
  236. jsonEncodeFloat64(buffer, "cpuCoreHours", a.CPUCoreHours, ",")
  237. jsonEncodeFloat64(buffer, "cpuCost", a.CPUCost, ",")
  238. jsonEncodeFloat64(buffer, "cpuEfficiency", a.CPUEfficiency(), ",")
  239. jsonEncodeFloat64(buffer, "gpuHours", a.GPUHours, ",")
  240. jsonEncodeFloat64(buffer, "gpuCost", a.GPUCost, ",")
  241. jsonEncodeFloat64(buffer, "networkCost", a.NetworkCost, ",")
  242. jsonEncodeFloat64(buffer, "pvBytes", a.PVBytes(), ",")
  243. jsonEncodeFloat64(buffer, "pvByteHours", a.PVByteHours, ",")
  244. jsonEncodeFloat64(buffer, "pvCost", a.PVCost, ",")
  245. jsonEncodeFloat64(buffer, "ramBytes", a.RAMBytes(), ",")
  246. jsonEncodeFloat64(buffer, "ramByteRequestAverage", a.RAMBytesRequestAverage, ",")
  247. jsonEncodeFloat64(buffer, "ramByteUsageAverage", a.RAMBytesUsageAverage, ",")
  248. jsonEncodeFloat64(buffer, "ramByteHours", a.RAMByteHours, ",")
  249. jsonEncodeFloat64(buffer, "ramCost", a.RAMCost, ",")
  250. jsonEncodeFloat64(buffer, "ramEfficiency", a.RAMEfficiency(), ",")
  251. jsonEncodeFloat64(buffer, "sharedCost", a.SharedCost, ",")
  252. jsonEncodeFloat64(buffer, "externalCost", a.ExternalCost, ",")
  253. jsonEncodeFloat64(buffer, "totalCost", a.TotalCost(), ",")
  254. jsonEncodeFloat64(buffer, "totalEfficiency", a.TotalEfficiency(), "")
  255. buffer.WriteString("}")
  256. return buffer.Bytes(), nil
  257. }
  258. // Resolution returns the duration of time covered by the Allocation
  259. func (a *Allocation) Resolution() time.Duration {
  260. return a.End.Sub(a.Start)
  261. }
  262. // IsAggregated is true if the given Allocation has been aggregated, which we
  263. // define by a lack of Properties.
  264. func (a *Allocation) IsAggregated() bool {
  265. return a == nil || a.Properties == nil
  266. }
  267. // IsExternal is true if the given Allocation represents external costs.
  268. func (a *Allocation) IsExternal() bool {
  269. return strings.Contains(a.Name, ExternalSuffix)
  270. }
  271. // IsIdle is true if the given Allocation represents idle costs.
  272. func (a *Allocation) IsIdle() bool {
  273. return strings.Contains(a.Name, IdleSuffix)
  274. }
  275. // IsUnallocated is true if the given Allocation represents unallocated costs.
  276. func (a *Allocation) IsUnallocated() bool {
  277. return strings.Contains(a.Name, UnallocatedSuffix)
  278. }
  279. // Minutes returns the number of minutes the Allocation represents, as defined
  280. // by the difference between the end and start times.
  281. func (a *Allocation) Minutes() float64 {
  282. return a.End.Sub(a.Start).Minutes()
  283. }
  284. // Share adds the TotalCost of the given Allocation to the SharedCost of the
  285. // receiving Allocation. No Start, End, Window, or Properties are considered.
  286. // Neither Allocation is mutated; a new Allocation is always returned.
  287. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  288. if that == nil {
  289. return a.Clone(), nil
  290. }
  291. if a == nil {
  292. return nil, fmt.Errorf("cannot share with nil Allocation")
  293. }
  294. agg := a.Clone()
  295. agg.SharedCost += that.TotalCost()
  296. return agg, nil
  297. }
  298. // String represents the given Allocation as a string
  299. func (a *Allocation) String() string {
  300. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost())
  301. }
  302. func (a *Allocation) add(that *Allocation) {
  303. if a == nil {
  304. log.Warningf("Allocation.AggregateBy: trying to add a nil receiver")
  305. return
  306. }
  307. aCluster, _ := a.Properties.GetCluster()
  308. thatCluster, _ := that.Properties.GetCluster()
  309. aNode, _ := a.Properties.GetNode()
  310. thatNode, _ := that.Properties.GetNode()
  311. // reset properties
  312. a.Properties = nil
  313. // ensure that we carry cluster ID and/or node over if they're the same
  314. // required for idle/shared cost allocation
  315. if aCluster == thatCluster {
  316. a.Properties = Properties{ClusterProp: aCluster}
  317. }
  318. if aNode == thatNode {
  319. if a.Properties == nil {
  320. a.Properties = Properties{NodeProp: aNode}
  321. } else {
  322. a.Properties.SetNode(aNode)
  323. }
  324. }
  325. // Expand the window to encompass both Allocations
  326. a.Window = a.Window.Expand(that.Window)
  327. // Sum non-cumulative fields by turning them into cumulative, adding them,
  328. // and then converting them back into averages after minutes have been
  329. // combined (just below).
  330. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  331. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  332. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  333. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  334. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  335. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  336. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  337. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  338. // Expand Start and End to be the "max" of among the given Allocations
  339. if that.Start.Before(a.Start) {
  340. a.Start = that.Start
  341. }
  342. if that.End.After(a.End) {
  343. a.End = that.End
  344. }
  345. // Convert cumulative request and usage back into rates
  346. // TODO:TEST write a unit test that fails if this is done incorrectly
  347. if a.Minutes() > 0 {
  348. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  349. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  350. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  351. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  352. } else {
  353. a.CPUCoreRequestAverage = 0.0
  354. a.CPUCoreUsageAverage = 0.0
  355. a.RAMBytesRequestAverage = 0.0
  356. a.RAMBytesUsageAverage = 0.0
  357. }
  358. // Sum all cumulative resource fields
  359. a.CPUCoreHours += that.CPUCoreHours
  360. a.GPUHours += that.GPUHours
  361. a.RAMByteHours += that.RAMByteHours
  362. a.PVByteHours += that.PVByteHours
  363. // Sum all cumulative cost fields
  364. a.CPUCost += that.CPUCost
  365. a.GPUCost += that.GPUCost
  366. a.RAMCost += that.RAMCost
  367. a.PVCost += that.PVCost
  368. a.NetworkCost += that.NetworkCost
  369. a.SharedCost += that.SharedCost
  370. a.ExternalCost += that.ExternalCost
  371. }
  372. // AllocationSet stores a set of Allocations, each with a unique name, that share
  373. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  374. type AllocationSet struct {
  375. sync.RWMutex
  376. allocations map[string]*Allocation
  377. externalKeys map[string]bool
  378. idleKeys map[string]bool
  379. Window Window
  380. Warnings []string
  381. Errors []string
  382. }
  383. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  384. // the given list of Allocations
  385. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  386. as := &AllocationSet{
  387. allocations: map[string]*Allocation{},
  388. externalKeys: map[string]bool{},
  389. idleKeys: map[string]bool{},
  390. Window: NewWindow(&start, &end),
  391. }
  392. for _, a := range allocs {
  393. as.Insert(a)
  394. }
  395. return as
  396. }
  397. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  398. // filtering results and sharing allocations. FilterFuncs are a list of match
  399. // functions such that, if any function fails, the allocation is ignored.
  400. // ShareFuncs are a list of match functions such that, if any function
  401. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  402. // simple flag for sharing idle resources.
  403. type AllocationAggregationOptions struct {
  404. FilterFuncs []AllocationMatchFunc
  405. SplitIdle bool
  406. MergeUnallocated bool
  407. ShareFuncs []AllocationMatchFunc
  408. ShareIdle string
  409. ShareSplit string
  410. SharedHourlyCosts map[string]float64
  411. }
  412. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  413. // Property. This will only be legal if the AllocationSet is divisible by the
  414. // given Property; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  415. func (as *AllocationSet) AggregateBy(properties Properties, options *AllocationAggregationOptions) error {
  416. // The order of operations for aggregating allocations is as follows:
  417. // 1. Partition external, idle, and shared allocations into separate sets.
  418. // Also, create the aggSet into which the results will be aggregated.
  419. // 2. Compute sharing coefficients for idle and shared resources
  420. // a) if idle allocation is to be shared, compute idle coefficients
  421. // b) if idle allocation is NOT shared, but filters are present, compute
  422. // idle filtration coefficients for the purpose of only returning the
  423. // portion of idle allocation that would have been shared with the
  424. // unfiltered results. (See unit tests 5.a,b,c)
  425. // c) generate shared allocation for then given shared overhead, which
  426. // must happen after (2a) and (2b)
  427. // d) if there are shared resources, compute share coefficients
  428. // 3. Drop any allocation that fails any of the filters
  429. // 4. Distribute idle allocations according to the idle coefficients
  430. // 5. Generate aggregation key and insert allocation into the output set
  431. // 6. If idle is shared and resources are shared, some idle might be shared
  432. // with a shared resource. Distribute that to the shared resources
  433. // prior to sharing them with the aggregated results.
  434. // 7. Apply idle filtration coefficients from step (2b)
  435. // 8. Distribute shared allocations according to the share coefficients.
  436. // 9. If there are external allocations that can be aggregated into
  437. // the output (i.e. they can be used to generate a valid key for
  438. // the given properties) then aggregate; otherwise... ignore them?
  439. // 10. If the merge idle option is enabled, merge any remaining idle
  440. // allocations into a single idle allocation
  441. if options == nil {
  442. options = &AllocationAggregationOptions{}
  443. }
  444. if as.IsEmpty() {
  445. return nil
  446. }
  447. // aggSet will collect the aggregated allocations
  448. aggSet := &AllocationSet{
  449. Window: as.Window.Clone(),
  450. }
  451. // externalSet will collect external allocations
  452. externalSet := &AllocationSet{
  453. Window: as.Window.Clone(),
  454. }
  455. // idleSet will be shared among aggSet after initial aggregation
  456. // is complete
  457. idleSet := &AllocationSet{
  458. Window: as.Window.Clone(),
  459. }
  460. // shareSet will be shared among aggSet after initial aggregation
  461. // is complete
  462. shareSet := &AllocationSet{
  463. Window: as.Window.Clone(),
  464. }
  465. as.Lock()
  466. defer as.Unlock()
  467. // (1) Loop and find all of the external, idle, and shared allocations. Add
  468. // them to their respective sets, removing them from the set of allocations
  469. // to aggregate.
  470. for _, alloc := range as.allocations {
  471. // External allocations get aggregated post-hoc (see step 6) and do
  472. // not necessarily contain complete sets of properties, so they are
  473. // moved to a separate AllocationSet.
  474. if alloc.IsExternal() {
  475. delete(as.externalKeys, alloc.Name)
  476. delete(as.allocations, alloc.Name)
  477. externalSet.Insert(alloc)
  478. continue
  479. }
  480. // Idle allocations should be separated into idleSet if they are to be
  481. // shared later on. If they are not to be shared, then add them to the
  482. // aggSet like any other allocation.
  483. if alloc.IsIdle() {
  484. delete(as.idleKeys, alloc.Name)
  485. delete(as.allocations, alloc.Name)
  486. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  487. idleSet.Insert(alloc)
  488. } else {
  489. aggSet.Insert(alloc)
  490. }
  491. continue
  492. }
  493. // Shared allocations must be identified and separated prior to
  494. // aggregation and filtering. That is, if any of the ShareFuncs return
  495. // true for the allocation, then move it to shareSet.
  496. for _, sf := range options.ShareFuncs {
  497. if sf(alloc) {
  498. delete(as.idleKeys, alloc.Name)
  499. delete(as.allocations, alloc.Name)
  500. shareSet.Insert(alloc)
  501. break
  502. }
  503. }
  504. }
  505. // It's possible that no more un-shared, non-idle, non-external allocations
  506. // remain at this point. This always results in an emptySet, so return early.
  507. if len(as.allocations) == 0 {
  508. emptySet := &AllocationSet{
  509. Window: as.Window.Clone(),
  510. }
  511. as.allocations = emptySet.allocations
  512. return nil
  513. }
  514. // (2) In order to correctly share idle and shared costs, we first compute
  515. // sharing coefficients, which represent the proportion of each cost to
  516. // share with each allocation. Idle allocations are shared per-cluster,
  517. // per-allocation, and per-resource, while shared resources are shared per-
  518. // allocation only.
  519. //
  520. // For an idleCoefficient example, the entries:
  521. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  522. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  523. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  524. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  525. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  526. // RAM costs.
  527. //
  528. // For a shareCoefficient example, the entries:
  529. // [namespace2] = 0.666667
  530. // [__filtered__] = 0.333333
  531. // mean that the post-aggregation allocation "namespace2" will receive
  532. // 66.67% of the shared resource costs, while the remaining 33.33% will
  533. // be filtered out, as they were shared with allocations that did not pass
  534. // one of the given filters.
  535. //
  536. // In order to maintain stable results when multiple operations are being
  537. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  538. // coefficients are computed for the full set of allocaitons prior to
  539. // adding shared overhead and prior to applying filters.
  540. var err error
  541. // (2a) If there are idle costs to be shared, compute the coefficients for
  542. // sharing them among the non-idle, non-aggregated allocations (including
  543. // the shared allocations).
  544. var idleCoefficients map[string]map[string]map[string]float64
  545. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  546. idleCoefficients, err = computeIdleCoeffs(properties, options, as, shareSet)
  547. if err != nil {
  548. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  549. return fmt.Errorf("error computing idle coefficients: %s", err)
  550. }
  551. }
  552. // (2b) If idle costs are not to be shared, but there are filters, then we
  553. // need to track the amount of each idle allocation to "filter" in order to
  554. // maintain parity with the results when idle is shared. That is, we want
  555. // to return only the idle costs that would have been shared with the given
  556. // results, even if the filter had not been applied.
  557. //
  558. // For example, consider these results from aggregating by namespace with
  559. // two clusters:
  560. //
  561. // namespace1: 25.00
  562. // namespace2: 30.00
  563. // namespace3: 15.00
  564. // idle: 30.00
  565. //
  566. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  567. // reduced by the amount that existed on cluster2. Then, idle must also be
  568. // reduced by the relevant amount:
  569. //
  570. // namespace1: 25.00
  571. // namespace2: 15.00
  572. // idle: 20.00
  573. //
  574. // Note that this can happen for any field, not just cluster, so we again
  575. // need to track this on a per-cluster, per-allocation, per-resource basis.
  576. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  577. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  578. idleFiltrationCoefficients, err = computeIdleCoeffs(properties, options, as, shareSet)
  579. if err != nil {
  580. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  581. }
  582. }
  583. // (2c) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  584. // come after idle coefficients are computes so that allocations generated
  585. // by shared overhead do not skew the idle coefficient computation.
  586. for name, cost := range options.SharedHourlyCosts {
  587. if cost > 0.0 {
  588. hours := as.Resolution().Hours()
  589. // If set ends in the future, adjust hours accordingly
  590. diff := time.Now().Sub(as.End())
  591. if diff < 0.0 {
  592. hours += diff.Hours()
  593. }
  594. totalSharedCost := cost * hours
  595. shareSet.Insert(&Allocation{
  596. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  597. Start: as.Start(),
  598. End: as.End(),
  599. SharedCost: totalSharedCost,
  600. Properties: Properties{ClusterProp: SharedSuffix}, // The allocation needs to belong to a cluster,but it really doesn't matter which one, so just make it clear.
  601. })
  602. }
  603. }
  604. // (2d) Compute share coefficients for shared resources. These are computed
  605. // after idle coefficients, and are computed for the aggregated allocations
  606. // of the main allocation set. See above for details and an example.
  607. var shareCoefficients map[string]float64
  608. if shareSet.Length() > 0 {
  609. shareCoefficients, err = computeShareCoeffs(properties, options, as)
  610. if err != nil {
  611. return fmt.Errorf("error computing share coefficients: %s", err)
  612. }
  613. }
  614. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  615. for _, alloc := range as.allocations {
  616. cluster, err := alloc.Properties.GetCluster()
  617. if err != nil {
  618. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  619. return err
  620. }
  621. skip := false
  622. // (3) If any of the filter funcs fail, immediately skip the allocation.
  623. for _, ff := range options.FilterFuncs {
  624. if !ff(alloc) {
  625. skip = true
  626. break
  627. }
  628. }
  629. if skip {
  630. // If we are tracking idle filtration coefficients, delete the
  631. // entry corresponding to the filtered allocation. (Deleting the
  632. // entry will result in that proportional amount being removed
  633. // from the idle allocation at the end of the process.)
  634. if idleFiltrationCoefficients != nil {
  635. if ifcc, ok := idleFiltrationCoefficients[cluster]; ok {
  636. delete(ifcc, alloc.Name)
  637. }
  638. }
  639. continue
  640. }
  641. // (4) Distribute idle allocations according to the idle coefficients
  642. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  643. // all idle allocations will be in the aggSet at this point, so idleSet
  644. // will be empty and we won't enter this block.
  645. if idleSet.Length() > 0 {
  646. // Distribute idle allocations by coefficient per-cluster, per-allocation
  647. for _, idleAlloc := range idleSet.allocations {
  648. // Only share idle if the cluster matches; i.e. the allocation
  649. // is from the same cluster as the idle costs
  650. idleCluster, err := idleAlloc.Properties.GetCluster()
  651. if err != nil {
  652. return err
  653. }
  654. if idleCluster != cluster {
  655. continue
  656. }
  657. // Make sure idle coefficients exist
  658. if _, ok := idleCoefficients[cluster]; !ok {
  659. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no cluster '%s' for '%s'", cluster, alloc.Name)
  660. continue
  661. }
  662. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  663. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  664. continue
  665. }
  666. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  667. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  668. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  669. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  670. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  671. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  672. alloc.CPUCost += idleCPUCost
  673. alloc.GPUCost += idleGPUCost
  674. alloc.RAMCost += idleRAMCost
  675. }
  676. }
  677. // (5) generate key to use for aggregation-by-key and allocation name
  678. key, err := alloc.generateKey(properties)
  679. if err != nil {
  680. return err
  681. }
  682. alloc.Name = key
  683. if options.MergeUnallocated && alloc.IsUnallocated() {
  684. alloc.Name = UnallocatedSuffix
  685. }
  686. // Inserting the allocation with the generated key for a name will
  687. // perform the actual basic aggregation step.
  688. aggSet.Insert(alloc)
  689. }
  690. // (6) If idle is shared and resources are shared, it's possible that some
  691. // amount of idle cost will be shared with a shared resource. Distribute
  692. // that idle allocation, if it exists, to the respective shared allocations
  693. // before sharing with the aggregated allocations.
  694. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  695. for _, alloc := range shareSet.allocations {
  696. cluster, err := alloc.Properties.GetCluster()
  697. if err != nil {
  698. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  699. return err
  700. }
  701. // Distribute idle allocations by coefficient per-cluster, per-allocation
  702. for _, idleAlloc := range idleSet.allocations {
  703. // Only share idle if the cluster matches; i.e. the allocation
  704. // is from the same cluster as the idle costs
  705. idleCluster, err := idleAlloc.Properties.GetCluster()
  706. if err != nil {
  707. return err
  708. }
  709. if idleCluster != cluster {
  710. continue
  711. }
  712. // Make sure idle coefficients exist
  713. if _, ok := idleCoefficients[cluster]; !ok {
  714. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no cluster '%s' for '%s'", cluster, alloc.Name)
  715. continue
  716. }
  717. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  718. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  719. continue
  720. }
  721. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  722. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  723. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  724. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  725. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  726. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  727. alloc.CPUCost += idleCPUCost
  728. alloc.GPUCost += idleGPUCost
  729. alloc.RAMCost += idleRAMCost
  730. }
  731. }
  732. }
  733. // clusterIdleFiltrationCoeffs is used to track per-resource idle
  734. // coefficients on a cluster-by-cluster basis. It is, essentailly, an
  735. // aggregation of idleFiltrationCoefficients after they have been
  736. // filtered above (in step 3)
  737. var clusterIdleFiltrationCoeffs map[string]map[string]float64
  738. if idleFiltrationCoefficients != nil {
  739. clusterIdleFiltrationCoeffs = map[string]map[string]float64{}
  740. for cluster, m := range idleFiltrationCoefficients {
  741. if _, ok := clusterIdleFiltrationCoeffs[cluster]; !ok {
  742. clusterIdleFiltrationCoeffs[cluster] = map[string]float64{
  743. "cpu": 0.0,
  744. "gpu": 0.0,
  745. "ram": 0.0,
  746. }
  747. }
  748. for _, n := range m {
  749. for resource, val := range n {
  750. clusterIdleFiltrationCoeffs[cluster][resource] += val
  751. }
  752. }
  753. }
  754. }
  755. // (7) If we have both un-shared idle allocations and idle filtration
  756. // coefficients then apply those. See step (2b) for an example.
  757. if len(aggSet.idleKeys) > 0 && clusterIdleFiltrationCoeffs != nil {
  758. for idleKey := range aggSet.idleKeys {
  759. idleAlloc := aggSet.Get(idleKey)
  760. cluster, err := idleAlloc.Properties.GetCluster()
  761. if err != nil {
  762. log.Warningf("AllocationSet.AggregateBy: idle allocation without cluster: %s", idleAlloc)
  763. continue
  764. }
  765. if resourceCoeffs, ok := clusterIdleFiltrationCoeffs[cluster]; ok {
  766. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  767. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  768. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  769. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  770. }
  771. }
  772. }
  773. // (8) Distribute shared allocations according to the share coefficients.
  774. if shareSet.Length() > 0 {
  775. for _, alloc := range aggSet.allocations {
  776. for _, sharedAlloc := range shareSet.allocations {
  777. if _, ok := shareCoefficients[alloc.Name]; !ok {
  778. log.Warningf("AllocationSet.AggregateBy: error getting share coefficienct for '%s'", alloc.Name)
  779. continue
  780. }
  781. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  782. }
  783. }
  784. }
  785. // (9) Aggregate external allocations into aggregated allocations. This may
  786. // not be possible for every external allocation, but attempt to find an
  787. // exact key match, given each external allocation's proerties, and
  788. // aggregate if an exact match is found.
  789. for _, alloc := range externalSet.allocations {
  790. skip := false
  791. for _, ff := range options.FilterFuncs {
  792. if !ff(alloc) {
  793. skip = true
  794. break
  795. }
  796. }
  797. if !skip {
  798. key, err := alloc.generateKey(properties)
  799. if err != nil {
  800. continue
  801. }
  802. alloc.Name = key
  803. aggSet.Insert(alloc)
  804. }
  805. }
  806. // (10) Combine all idle allocations into a single "__idle__" allocation
  807. if !options.SplitIdle {
  808. for _, idleAlloc := range aggSet.IdleAllocations() {
  809. aggSet.Delete(idleAlloc.Name)
  810. idleAlloc.Name = IdleSuffix
  811. aggSet.Insert(idleAlloc)
  812. }
  813. }
  814. as.allocations = aggSet.allocations
  815. return nil
  816. }
  817. func computeShareCoeffs(properties Properties, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  818. // Compute coeffs by totalling per-allocation, then dividing by the total.
  819. coeffs := map[string]float64{}
  820. // Compute totals for all allocations
  821. total := 0.0
  822. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  823. // counts each aggregation proportionally to its respective costs
  824. shareType := options.ShareSplit
  825. // Record allocation values first, then normalize by totals to get percentages
  826. for n, alloc := range as.allocations {
  827. if alloc.IsIdle() {
  828. // Skip idle allocations in coefficient calculation
  829. continue
  830. }
  831. // Determine the post-aggregation key under which the allocation will
  832. // be shared.
  833. name, err := alloc.generateKey(properties)
  834. if err != nil {
  835. return nil, fmt.Errorf(`failed to generate key for shared allocation "%s": %s`, n, err)
  836. }
  837. // If the current allocation will be filtered out in step 3, contribute
  838. // its share of the shared coefficient to a "__filtered__" bin, which
  839. // will ultimately be dropped. This step ensures that the shared cost
  840. // of a non-filtered allocation will be conserved even when the filter
  841. // is removed. (Otherwise, all the shared cost will get redistributed
  842. // over the unfiltered results, inflating their shared costs.)
  843. filtered := false
  844. for _, ff := range options.FilterFuncs {
  845. if !ff(alloc) {
  846. filtered = true
  847. break
  848. }
  849. }
  850. if filtered {
  851. name = "__filtered__"
  852. }
  853. if shareType == ShareEven {
  854. // Even distribution is not additive - set to 1.0 for everything
  855. coeffs[name] = 1.0
  856. // Total for even distribution is always the number of coefficients
  857. total = float64(len(coeffs))
  858. } else {
  859. // Both are additive for weighted distribution, where each
  860. // cumulative coefficient will be divided by the total.
  861. coeffs[name] += alloc.TotalCost()
  862. total += alloc.TotalCost()
  863. }
  864. }
  865. // Normalize coefficients by totals
  866. for a := range coeffs {
  867. if coeffs[a] > 0 && total > 0 {
  868. coeffs[a] /= total
  869. } else {
  870. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  871. coeffs[a] = 0.0
  872. }
  873. }
  874. return coeffs, nil
  875. }
  876. func computeIdleCoeffs(properties Properties, options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, error) {
  877. types := []string{"cpu", "gpu", "ram"}
  878. // Compute idle coefficients, then save them in AllocationAggregationOptions
  879. coeffs := map[string]map[string]map[string]float64{}
  880. // Compute totals per resource for CPU, GPU, RAM, and PV
  881. totals := map[string]map[string]float64{}
  882. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  883. // counts each allocation proportionally to its respective costs
  884. shareType := options.ShareIdle
  885. // Record allocation values first, then normalize by totals to get percentages
  886. for _, alloc := range as.allocations {
  887. if alloc.IsIdle() {
  888. // Skip idle allocations in coefficient calculation
  889. continue
  890. }
  891. // We need to key the allocations by cluster id
  892. clusterID, err := alloc.Properties.GetCluster()
  893. if err != nil {
  894. return nil, err
  895. }
  896. // get the name key for the allocation
  897. name := alloc.Name
  898. // Create cluster based tables if they don't exist
  899. if _, ok := coeffs[clusterID]; !ok {
  900. coeffs[clusterID] = map[string]map[string]float64{}
  901. }
  902. if _, ok := totals[clusterID]; !ok {
  903. totals[clusterID] = map[string]float64{}
  904. }
  905. if _, ok := coeffs[clusterID][name]; !ok {
  906. coeffs[clusterID][name] = map[string]float64{}
  907. }
  908. if shareType == ShareEven {
  909. for _, r := range types {
  910. // Not additive - hard set to 1.0
  911. coeffs[clusterID][name][r] = 1.0
  912. // totals are additive
  913. totals[clusterID][r] += 1.0
  914. }
  915. } else {
  916. coeffs[clusterID][name]["cpu"] += alloc.CPUCost
  917. coeffs[clusterID][name]["gpu"] += alloc.GPUCost
  918. coeffs[clusterID][name]["ram"] += alloc.RAMCost
  919. totals[clusterID]["cpu"] += alloc.CPUCost
  920. totals[clusterID]["gpu"] += alloc.GPUCost
  921. totals[clusterID]["ram"] += alloc.RAMCost
  922. }
  923. }
  924. // Do the same for shared allocations
  925. for _, alloc := range shareSet.allocations {
  926. if alloc.IsIdle() {
  927. // Skip idle allocations in coefficient calculation
  928. continue
  929. }
  930. // We need to key the allocations by cluster id
  931. clusterID, err := alloc.Properties.GetCluster()
  932. if err != nil {
  933. return nil, err
  934. }
  935. // get the name key for the allocation
  936. name := alloc.Name
  937. // Create cluster based tables if they don't exist
  938. if _, ok := coeffs[clusterID]; !ok {
  939. coeffs[clusterID] = map[string]map[string]float64{}
  940. }
  941. if _, ok := totals[clusterID]; !ok {
  942. totals[clusterID] = map[string]float64{}
  943. }
  944. if _, ok := coeffs[clusterID][name]; !ok {
  945. coeffs[clusterID][name] = map[string]float64{}
  946. }
  947. if shareType == ShareEven {
  948. for _, r := range types {
  949. // Not additive - hard set to 1.0
  950. coeffs[clusterID][name][r] = 1.0
  951. // totals are additive
  952. totals[clusterID][r] += 1.0
  953. }
  954. } else {
  955. coeffs[clusterID][name]["cpu"] += alloc.CPUCost
  956. coeffs[clusterID][name]["gpu"] += alloc.GPUCost
  957. coeffs[clusterID][name]["ram"] += alloc.RAMCost
  958. totals[clusterID]["cpu"] += alloc.CPUCost
  959. totals[clusterID]["gpu"] += alloc.GPUCost
  960. totals[clusterID]["ram"] += alloc.RAMCost
  961. }
  962. }
  963. // Normalize coefficients by totals
  964. for c := range coeffs {
  965. for a := range coeffs[c] {
  966. for _, r := range types {
  967. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  968. coeffs[c][a][r] /= totals[c][r]
  969. }
  970. }
  971. }
  972. }
  973. return coeffs, nil
  974. }
  975. func (a *Allocation) generateKey(properties Properties) (string, error) {
  976. // Names will ultimately be joined into a single name, which uniquely
  977. // identifies allocations.
  978. names := []string{}
  979. if properties.HasCluster() {
  980. cluster, err := a.Properties.GetCluster()
  981. if err != nil {
  982. return "", err
  983. }
  984. names = append(names, cluster)
  985. }
  986. if properties.HasNode() {
  987. node, err := a.Properties.GetNode()
  988. if err != nil {
  989. return "", err
  990. }
  991. names = append(names, node)
  992. }
  993. if properties.HasNamespace() {
  994. namespace, err := a.Properties.GetNamespace()
  995. if err != nil {
  996. return "", err
  997. }
  998. names = append(names, namespace)
  999. }
  1000. if properties.HasControllerKind() {
  1001. controllerKind, err := a.Properties.GetControllerKind()
  1002. if err != nil {
  1003. // Indicate that allocation has no controller
  1004. controllerKind = UnallocatedSuffix
  1005. }
  1006. if prop, _ := properties.GetControllerKind(); prop != "" && prop != controllerKind {
  1007. // The allocation does not have the specified controller kind
  1008. controllerKind = UnallocatedSuffix
  1009. }
  1010. names = append(names, controllerKind)
  1011. }
  1012. if properties.HasController() {
  1013. if !properties.HasControllerKind() {
  1014. controllerKind, err := a.Properties.GetControllerKind()
  1015. if err == nil {
  1016. names = append(names, controllerKind)
  1017. }
  1018. }
  1019. controller, err := a.Properties.GetController()
  1020. if err != nil {
  1021. // Indicate that allocation has no controller
  1022. controller = UnallocatedSuffix
  1023. }
  1024. names = append(names, controller)
  1025. }
  1026. if properties.HasPod() {
  1027. pod, err := a.Properties.GetPod()
  1028. if err != nil {
  1029. return "", err
  1030. }
  1031. names = append(names, pod)
  1032. }
  1033. if properties.HasContainer() {
  1034. container, err := a.Properties.GetContainer()
  1035. if err != nil {
  1036. return "", err
  1037. }
  1038. names = append(names, container)
  1039. }
  1040. if properties.HasService() {
  1041. services, err := a.Properties.GetServices()
  1042. if err != nil {
  1043. // Indicate that allocation has no services
  1044. names = append(names, UnallocatedSuffix)
  1045. } else {
  1046. if len(services) > 0 {
  1047. for _, service := range services {
  1048. names = append(names, service)
  1049. break
  1050. }
  1051. } else {
  1052. // Indicate that allocation has no services
  1053. names = append(names, UnallocatedSuffix)
  1054. }
  1055. }
  1056. }
  1057. if properties.HasAnnotations() {
  1058. annotations, err := a.Properties.GetAnnotations() // annotations that the individual allocation possesses
  1059. if err != nil {
  1060. // Indicate that allocation has no annotations
  1061. names = append(names, UnallocatedSuffix)
  1062. } else {
  1063. annotationNames := []string{}
  1064. aggAnnotations, err := properties.GetAnnotations() // potential annotations to aggregate on supplied by the API caller
  1065. if err != nil {
  1066. // We've already checked HasAnnotation, so this should never occur
  1067. return "", err
  1068. }
  1069. // calvin - support multi-annotation aggregation
  1070. for annotationName := range aggAnnotations {
  1071. if val, ok := annotations[annotationName]; ok {
  1072. annotationNames = append(annotationNames, fmt.Sprintf("%s=%s", annotationName, val))
  1073. } else if indexOf(UnallocatedSuffix, annotationNames) == -1 { // if UnallocatedSuffix not already in names
  1074. annotationNames = append(annotationNames, UnallocatedSuffix)
  1075. }
  1076. }
  1077. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1078. if len(annotationNames) > 1 {
  1079. sort.Strings(annotationNames)
  1080. }
  1081. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, annotationNames)
  1082. // suffix should be at index 0 if it exists b/c of underscores
  1083. if unallocatedSuffixIndex != -1 {
  1084. annotationNames = append(annotationNames[:unallocatedSuffixIndex], annotationNames[unallocatedSuffixIndex+1:]...)
  1085. annotationNames = append(annotationNames, UnallocatedSuffix) // append to end
  1086. }
  1087. names = append(names, annotationNames...)
  1088. }
  1089. }
  1090. if properties.HasLabel() {
  1091. labels, err := a.Properties.GetLabels() // labels that the individual allocation possesses
  1092. if err != nil {
  1093. // Indicate that allocation has no labels
  1094. names = append(names, UnallocatedSuffix)
  1095. } else {
  1096. labelNames := []string{}
  1097. aggLabels, err := properties.GetLabels() // potential labels to aggregate on supplied by the API caller
  1098. if err != nil {
  1099. // We've already checked HasLabel, so this should never occur
  1100. return "", err
  1101. }
  1102. // calvin - support multi-label aggregation
  1103. for labelName := range aggLabels {
  1104. if val, ok := labels[labelName]; ok {
  1105. labelNames = append(labelNames, fmt.Sprintf("%s=%s", labelName, val))
  1106. } else if indexOf(UnallocatedSuffix, labelNames) == -1 { // if UnallocatedSuffix not already in names
  1107. labelNames = append(labelNames, UnallocatedSuffix)
  1108. }
  1109. }
  1110. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1111. if len(labelNames) > 1 {
  1112. sort.Strings(labelNames)
  1113. }
  1114. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, labelNames)
  1115. // suffix should be at index 0 if it exists b/c of underscores
  1116. if unallocatedSuffixIndex != -1 {
  1117. labelNames = append(labelNames[:unallocatedSuffixIndex], labelNames[unallocatedSuffixIndex+1:]...)
  1118. labelNames = append(labelNames, UnallocatedSuffix) // append to end
  1119. }
  1120. names = append(names, labelNames...)
  1121. }
  1122. }
  1123. return strings.Join(names, "/"), nil
  1124. }
  1125. // TODO:CLEANUP get rid of this
  1126. // Helper function to check for slice membership. Not sure if repeated elsewhere in our codebase.
  1127. func indexOf(v string, arr []string) int {
  1128. for i, s := range arr {
  1129. // This is caseless equivalence
  1130. if strings.EqualFold(v, s) {
  1131. return i
  1132. }
  1133. }
  1134. return -1
  1135. }
  1136. // Clone returns a new AllocationSet with a deep copy of the given
  1137. // AllocationSet's allocations.
  1138. func (as *AllocationSet) Clone() *AllocationSet {
  1139. if as == nil {
  1140. return nil
  1141. }
  1142. as.RLock()
  1143. defer as.RUnlock()
  1144. allocs := map[string]*Allocation{}
  1145. for k, v := range as.allocations {
  1146. allocs[k] = v.Clone()
  1147. }
  1148. externalKeys := map[string]bool{}
  1149. for k, v := range as.externalKeys {
  1150. externalKeys[k] = v
  1151. }
  1152. idleKeys := map[string]bool{}
  1153. for k, v := range as.idleKeys {
  1154. idleKeys[k] = v
  1155. }
  1156. return &AllocationSet{
  1157. allocations: allocs,
  1158. externalKeys: externalKeys,
  1159. idleKeys: idleKeys,
  1160. Window: as.Window.Clone(),
  1161. }
  1162. }
  1163. // ComputeIdleAllocations computes the idle allocations for the AllocationSet,
  1164. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1165. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1166. // considered for idle allocation. If the Nodes have adjustments, then apply
  1167. // the adjustments proportionally to each of the resources so that total
  1168. // allocation with idle reflects the adjusted node costs. One idle allocation
  1169. // per-cluster will be computed and returned, keyed by cluster_id.
  1170. func (as *AllocationSet) ComputeIdleAllocations(assetSet *AssetSet) (map[string]*Allocation, error) {
  1171. if as == nil {
  1172. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1173. }
  1174. if assetSet == nil {
  1175. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1176. }
  1177. if !as.Window.Equal(assetSet.Window) {
  1178. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1179. }
  1180. window := as.Window
  1181. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1182. // cluster-to-{cpu|gpu|ram}-to-cost.
  1183. assetClusterResourceCosts := map[string]map[string]float64{}
  1184. assetSet.Each(func(key string, a Asset) {
  1185. if node, ok := a.(*Node); ok {
  1186. if _, ok := assetClusterResourceCosts[node.Properties().Cluster]; !ok {
  1187. assetClusterResourceCosts[node.Properties().Cluster] = map[string]float64{}
  1188. }
  1189. // adjustmentRate is used to scale resource costs proportionally
  1190. // by the adjustment. This is necessary because we only get one
  1191. // adjustment per Node, not one per-resource-per-Node.
  1192. //
  1193. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1194. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1195. // e.g. total cost = $150, adjustment = $50 => 1.5
  1196. adjustmentRate := 1.0
  1197. if node.TotalCost()-node.Adjustment() == 0 {
  1198. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1199. // the entire node cost and we should make everything 0
  1200. // without dividing by 0.
  1201. adjustmentRate = 0.0
  1202. } else if node.Adjustment() != 0.0 {
  1203. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1204. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1205. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1206. }
  1207. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1208. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1209. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1210. assetClusterResourceCosts[node.Properties().Cluster]["cpu"] += cpuCost
  1211. assetClusterResourceCosts[node.Properties().Cluster]["gpu"] += gpuCost
  1212. assetClusterResourceCosts[node.Properties().Cluster]["ram"] += ramCost
  1213. }
  1214. })
  1215. // Determine start, end on a per-cluster basis
  1216. clusterStarts := map[string]time.Time{}
  1217. clusterEnds := map[string]time.Time{}
  1218. // Subtract allocated costs from asset costs, leaving only the remaining
  1219. // idle costs.
  1220. as.Each(func(name string, a *Allocation) {
  1221. cluster, err := a.Properties.GetCluster()
  1222. if err != nil {
  1223. // Failed to find allocation's cluster
  1224. return
  1225. }
  1226. if _, ok := assetClusterResourceCosts[cluster]; !ok {
  1227. // Failed to find assets for allocation's cluster
  1228. return
  1229. }
  1230. // Set cluster (start, end) if they are either not currently set,
  1231. // or if the detected (start, end) of the current allocation falls
  1232. // before or after, respectively, the current values.
  1233. if s, ok := clusterStarts[cluster]; !ok || a.Start.Before(s) {
  1234. clusterStarts[cluster] = a.Start
  1235. }
  1236. if e, ok := clusterEnds[cluster]; !ok || a.End.After(e) {
  1237. clusterEnds[cluster] = a.End
  1238. }
  1239. assetClusterResourceCosts[cluster]["cpu"] -= a.CPUCost
  1240. assetClusterResourceCosts[cluster]["gpu"] -= a.GPUCost
  1241. assetClusterResourceCosts[cluster]["ram"] -= a.RAMCost
  1242. })
  1243. // Turn remaining un-allocated asset costs into idle allocations
  1244. idleAllocs := map[string]*Allocation{}
  1245. for cluster, resources := range assetClusterResourceCosts {
  1246. // Default start and end to the (start, end) of the given window, but
  1247. // use the actual, detected (start, end) pair if they are available.
  1248. start := *window.Start()
  1249. if s, ok := clusterStarts[cluster]; ok && window.Contains(s) {
  1250. start = s
  1251. }
  1252. end := *window.End()
  1253. if e, ok := clusterEnds[cluster]; ok && window.Contains(e) {
  1254. end = e
  1255. }
  1256. idleAlloc := &Allocation{
  1257. Name: fmt.Sprintf("%s/%s", cluster, IdleSuffix),
  1258. Window: window.Clone(),
  1259. Properties: Properties{ClusterProp: cluster},
  1260. Start: start,
  1261. End: end,
  1262. CPUCost: resources["cpu"],
  1263. GPUCost: resources["gpu"],
  1264. RAMCost: resources["ram"],
  1265. }
  1266. // Do not continue if multiple idle allocations are computed for a
  1267. // single cluster.
  1268. if _, ok := idleAllocs[cluster]; ok {
  1269. return nil, fmt.Errorf("duplicate idle allocations for cluster %s", cluster)
  1270. }
  1271. idleAllocs[cluster] = idleAlloc
  1272. }
  1273. return idleAllocs, nil
  1274. }
  1275. // Delete removes the allocation with the given name from the set
  1276. func (as *AllocationSet) Delete(name string) {
  1277. if as == nil {
  1278. return
  1279. }
  1280. as.Lock()
  1281. defer as.Unlock()
  1282. delete(as.externalKeys, name)
  1283. delete(as.idleKeys, name)
  1284. delete(as.allocations, name)
  1285. }
  1286. // Each invokes the given function for each Allocation in the set
  1287. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  1288. if as == nil {
  1289. return
  1290. }
  1291. for k, a := range as.allocations {
  1292. f(k, a)
  1293. }
  1294. }
  1295. // End returns the End time of the AllocationSet window
  1296. func (as *AllocationSet) End() time.Time {
  1297. if as == nil {
  1298. log.Warningf("Allocation ETL: calling End on nil AllocationSet")
  1299. return time.Unix(0, 0)
  1300. }
  1301. if as.Window.End() == nil {
  1302. log.Warningf("Allocation ETL: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  1303. return time.Unix(0, 0)
  1304. }
  1305. return *as.Window.End()
  1306. }
  1307. // Get returns the Allocation at the given key in the AllocationSet
  1308. func (as *AllocationSet) Get(key string) *Allocation {
  1309. as.RLock()
  1310. defer as.RUnlock()
  1311. if alloc, ok := as.allocations[key]; ok {
  1312. return alloc
  1313. }
  1314. return nil
  1315. }
  1316. // ExternalAllocations returns a map of the external allocations in the set.
  1317. // Returns clones of the actual Allocations, so mutability is not a problem.
  1318. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1319. externals := map[string]*Allocation{}
  1320. if as.IsEmpty() {
  1321. return externals
  1322. }
  1323. as.RLock()
  1324. defer as.RUnlock()
  1325. for key := range as.externalKeys {
  1326. if alloc, ok := as.allocations[key]; ok {
  1327. externals[key] = alloc.Clone()
  1328. }
  1329. }
  1330. return externals
  1331. }
  1332. // ExternalCost returns the total aggregated external costs of the set
  1333. func (as *AllocationSet) ExternalCost() float64 {
  1334. if as.IsEmpty() {
  1335. return 0.0
  1336. }
  1337. as.RLock()
  1338. defer as.RUnlock()
  1339. externalCost := 0.0
  1340. for _, alloc := range as.allocations {
  1341. externalCost += alloc.ExternalCost
  1342. }
  1343. return externalCost
  1344. }
  1345. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1346. // Returns clones of the actual Allocations, so mutability is not a problem.
  1347. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1348. idles := map[string]*Allocation{}
  1349. if as.IsEmpty() {
  1350. return idles
  1351. }
  1352. as.RLock()
  1353. defer as.RUnlock()
  1354. for key := range as.idleKeys {
  1355. if alloc, ok := as.allocations[key]; ok {
  1356. idles[key] = alloc.Clone()
  1357. }
  1358. }
  1359. return idles
  1360. }
  1361. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1362. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1363. // there is no existing entry, one is created. Nil error response indicates success.
  1364. func (as *AllocationSet) Insert(that *Allocation) error {
  1365. return as.insert(that)
  1366. }
  1367. func (as *AllocationSet) insert(that *Allocation) error {
  1368. if as == nil {
  1369. return fmt.Errorf("cannot insert into nil AllocationSet")
  1370. }
  1371. as.Lock()
  1372. defer as.Unlock()
  1373. if as.allocations == nil {
  1374. as.allocations = map[string]*Allocation{}
  1375. }
  1376. if as.externalKeys == nil {
  1377. as.externalKeys = map[string]bool{}
  1378. }
  1379. if as.idleKeys == nil {
  1380. as.idleKeys = map[string]bool{}
  1381. }
  1382. // Add the given Allocation to the existing entry, if there is one;
  1383. // otherwise just set directly into allocations
  1384. if _, ok := as.allocations[that.Name]; !ok {
  1385. as.allocations[that.Name] = that
  1386. } else {
  1387. as.allocations[that.Name].add(that)
  1388. }
  1389. // If the given Allocation is an external one, record that
  1390. if that.IsExternal() {
  1391. as.externalKeys[that.Name] = true
  1392. }
  1393. // If the given Allocation is an idle one, record that
  1394. if that.IsIdle() {
  1395. as.idleKeys[that.Name] = true
  1396. }
  1397. return nil
  1398. }
  1399. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  1400. // zero allocations.
  1401. func (as *AllocationSet) IsEmpty() bool {
  1402. if as == nil || len(as.allocations) == 0 {
  1403. return true
  1404. }
  1405. as.RLock()
  1406. defer as.RUnlock()
  1407. return as.allocations == nil || len(as.allocations) == 0
  1408. }
  1409. // Length returns the number of Allocations in the set
  1410. func (as *AllocationSet) Length() int {
  1411. if as == nil {
  1412. return 0
  1413. }
  1414. as.RLock()
  1415. defer as.RUnlock()
  1416. return len(as.allocations)
  1417. }
  1418. // Map clones and returns a map of the AllocationSet's Allocations
  1419. func (as *AllocationSet) Map() map[string]*Allocation {
  1420. if as.IsEmpty() {
  1421. return map[string]*Allocation{}
  1422. }
  1423. return as.Clone().allocations
  1424. }
  1425. // MarshalJSON JSON-encodes the AllocationSet
  1426. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  1427. as.RLock()
  1428. defer as.RUnlock()
  1429. return json.Marshal(as.allocations)
  1430. }
  1431. // Resolution returns the AllocationSet's window duration
  1432. func (as *AllocationSet) Resolution() time.Duration {
  1433. return as.Window.Duration()
  1434. }
  1435. // Set uses the given Allocation to overwrite the existing entry in the
  1436. // AllocationSet under the Allocation's name.
  1437. func (as *AllocationSet) Set(alloc *Allocation) error {
  1438. if as.IsEmpty() {
  1439. as.Lock()
  1440. as.allocations = map[string]*Allocation{}
  1441. as.externalKeys = map[string]bool{}
  1442. as.idleKeys = map[string]bool{}
  1443. as.Unlock()
  1444. }
  1445. as.Lock()
  1446. defer as.Unlock()
  1447. as.allocations[alloc.Name] = alloc
  1448. // If the given Allocation is an external one, record that
  1449. if alloc.IsExternal() {
  1450. as.externalKeys[alloc.Name] = true
  1451. }
  1452. // If the given Allocation is an idle one, record that
  1453. if alloc.IsIdle() {
  1454. as.idleKeys[alloc.Name] = true
  1455. }
  1456. return nil
  1457. }
  1458. // Start returns the Start time of the AllocationSet window
  1459. func (as *AllocationSet) Start() time.Time {
  1460. if as == nil {
  1461. log.Warningf("Allocation ETL: calling Start on nil AllocationSet")
  1462. return time.Unix(0, 0)
  1463. }
  1464. if as.Window.Start() == nil {
  1465. log.Warningf("Allocation ETL: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1466. return time.Unix(0, 0)
  1467. }
  1468. return *as.Window.Start()
  1469. }
  1470. // String represents the given Allocation as a string
  1471. func (as *AllocationSet) String() string {
  1472. if as == nil {
  1473. return "<nil>"
  1474. }
  1475. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1476. as.Length(), as.Window, as.TotalCost())
  1477. }
  1478. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1479. func (as *AllocationSet) TotalCost() float64 {
  1480. if as.IsEmpty() {
  1481. return 0.0
  1482. }
  1483. as.RLock()
  1484. defer as.RUnlock()
  1485. tc := 0.0
  1486. for _, a := range as.allocations {
  1487. tc += a.TotalCost()
  1488. }
  1489. return tc
  1490. }
  1491. // UTCOffset returns the AllocationSet's configured UTCOffset.
  1492. func (as *AllocationSet) UTCOffset() time.Duration {
  1493. _, zone := as.Start().Zone()
  1494. return time.Duration(zone) * time.Second
  1495. }
  1496. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1497. if as.IsEmpty() {
  1498. return that, nil
  1499. }
  1500. if that.IsEmpty() {
  1501. return as, nil
  1502. }
  1503. // Set start, end to min(start), max(end)
  1504. start := as.Start()
  1505. end := as.End()
  1506. if that.Start().Before(start) {
  1507. start = that.Start()
  1508. }
  1509. if that.End().After(end) {
  1510. end = that.End()
  1511. }
  1512. acc := NewAllocationSet(start, end)
  1513. as.RLock()
  1514. defer as.RUnlock()
  1515. that.RLock()
  1516. defer that.RUnlock()
  1517. for _, alloc := range as.allocations {
  1518. err := acc.insert(alloc)
  1519. if err != nil {
  1520. return nil, err
  1521. }
  1522. }
  1523. for _, alloc := range that.allocations {
  1524. err := acc.insert(alloc)
  1525. if err != nil {
  1526. return nil, err
  1527. }
  1528. }
  1529. return acc, nil
  1530. }
  1531. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  1532. // be used such that the AllocationSets held are consecutive and coherent with
  1533. // respect to using the same aggregation properties, UTC offset, and
  1534. // resolution. However these rules are not necessarily enforced, so use wisely.
  1535. type AllocationSetRange struct {
  1536. sync.RWMutex
  1537. allocations []*AllocationSet
  1538. }
  1539. // NewAllocationSetRange instantiates a new range composed of the given
  1540. // AllocationSets in the order provided.
  1541. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1542. return &AllocationSetRange{
  1543. allocations: allocs,
  1544. }
  1545. }
  1546. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1547. // AllocationSet for the entire range.
  1548. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1549. var allocSet *AllocationSet
  1550. var err error
  1551. asr.RLock()
  1552. defer asr.RUnlock()
  1553. for _, as := range asr.allocations {
  1554. allocSet, err = allocSet.accumulate(as)
  1555. if err != nil {
  1556. return nil, err
  1557. }
  1558. }
  1559. return allocSet, nil
  1560. }
  1561. // TODO niko/etl accumulate into lower-resolution chunks of the given resolution
  1562. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1563. // AggregateBy aggregates each AllocationSet in the range by the given
  1564. // properties and options.
  1565. func (asr *AllocationSetRange) AggregateBy(properties Properties, options *AllocationAggregationOptions) error {
  1566. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1567. asr.Lock()
  1568. defer asr.Unlock()
  1569. for _, as := range asr.allocations {
  1570. err := as.AggregateBy(properties, options)
  1571. if err != nil {
  1572. return err
  1573. }
  1574. aggRange.allocations = append(aggRange.allocations, as)
  1575. }
  1576. asr.allocations = aggRange.allocations
  1577. return nil
  1578. }
  1579. // Append appends the given AllocationSet to the end of the range. It does not
  1580. // validate whether or not that violates window continuity.
  1581. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1582. asr.Lock()
  1583. defer asr.Unlock()
  1584. asr.allocations = append(asr.allocations, that)
  1585. }
  1586. // Each invokes the given function for each AllocationSet in the range
  1587. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1588. if asr == nil {
  1589. return
  1590. }
  1591. for i, as := range asr.allocations {
  1592. f(i, as)
  1593. }
  1594. }
  1595. // Get retrieves the AllocationSet at the given index of the range.
  1596. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  1597. if i < 0 || i >= len(asr.allocations) {
  1598. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  1599. }
  1600. asr.RLock()
  1601. defer asr.RUnlock()
  1602. return asr.allocations[i], nil
  1603. }
  1604. // InsertRange merges the given AllocationSetRange into the receiving one by
  1605. // lining up sets with matching windows, then inserting each allocation from
  1606. // the given ASR into the respective set in the receiving ASR. If the given
  1607. // ASR contains an AllocationSet from a window that does not exist in the
  1608. // receiving ASR, then an error is returned. However, the given ASR does not
  1609. // need to cover the full range of the receiver.
  1610. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  1611. if asr == nil {
  1612. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  1613. }
  1614. // keys maps window to index in asr
  1615. keys := map[string]int{}
  1616. asr.Each(func(i int, as *AllocationSet) {
  1617. if as == nil {
  1618. return
  1619. }
  1620. keys[as.Window.String()] = i
  1621. })
  1622. // Nothing to merge, so simply return
  1623. if len(keys) == 0 {
  1624. return nil
  1625. }
  1626. var err error
  1627. that.Each(func(j int, thatAS *AllocationSet) {
  1628. if thatAS == nil || err != nil {
  1629. return
  1630. }
  1631. // Find matching AllocationSet in asr
  1632. i, ok := keys[thatAS.Window.String()]
  1633. if !ok {
  1634. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  1635. return
  1636. }
  1637. as, err := asr.Get(i)
  1638. if err != nil {
  1639. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  1640. return
  1641. }
  1642. // Insert each Allocation from the given set
  1643. thatAS.Each(func(k string, alloc *Allocation) {
  1644. err = as.Insert(alloc)
  1645. if err != nil {
  1646. err = fmt.Errorf("error inserting allocation: %s", err)
  1647. return
  1648. }
  1649. })
  1650. })
  1651. // err might be nil
  1652. return err
  1653. }
  1654. // Length returns the length of the range, which is zero if nil
  1655. func (asr *AllocationSetRange) Length() int {
  1656. if asr == nil || asr.allocations == nil {
  1657. return 0
  1658. }
  1659. asr.RLock()
  1660. defer asr.RUnlock()
  1661. return len(asr.allocations)
  1662. }
  1663. // MarshalJSON JSON-encodes the range
  1664. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  1665. asr.RLock()
  1666. asr.RUnlock()
  1667. return json.Marshal(asr.allocations)
  1668. }
  1669. // Slice copies the underlying slice of AllocationSets, maintaining order,
  1670. // and returns the copied slice.
  1671. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  1672. if asr == nil || asr.allocations == nil {
  1673. return nil
  1674. }
  1675. asr.RLock()
  1676. defer asr.RUnlock()
  1677. copy := []*AllocationSet{}
  1678. for _, as := range asr.allocations {
  1679. copy = append(copy, as.Clone())
  1680. }
  1681. return copy
  1682. }
  1683. // String represents the given AllocationSetRange as a string
  1684. func (asr *AllocationSetRange) String() string {
  1685. if asr == nil {
  1686. return "<nil>"
  1687. }
  1688. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  1689. }
  1690. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  1691. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  1692. // are sets with conflicting UTCOffsets (just returns the first).
  1693. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  1694. if asr.Length() == 0 {
  1695. return 0
  1696. }
  1697. as, err := asr.Get(0)
  1698. if err != nil {
  1699. return 0
  1700. }
  1701. return as.UTCOffset()
  1702. }
  1703. // Window returns the full window that the AllocationSetRange spans, from the
  1704. // start of the first AllocationSet to the end of the last one.
  1705. func (asr *AllocationSetRange) Window() Window {
  1706. if asr == nil || asr.Length() == 0 {
  1707. return NewWindow(nil, nil)
  1708. }
  1709. start := asr.allocations[0].Start()
  1710. end := asr.allocations[asr.Length()-1].End()
  1711. return NewWindow(&start, &end)
  1712. }