allocation.go 68 KB

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