allocation.go 53 KB

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