allocation.go 63 KB

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