allocation.go 61 KB

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