allocation.go 60 KB

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