allocation.go 61 KB

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