allocation.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  1. package kubecost
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/kubecost/cost-model/pkg/log"
  10. )
  11. // IdleSuffix indicates an idle allocation property
  12. const IdleSuffix = "__idle__"
  13. // SharedSuffix indicates an shared allocation property
  14. const SharedSuffix = "__shared__"
  15. // UnallocatedSuffix indicates an unallocated allocation property
  16. const UnallocatedSuffix = "__unallocated__"
  17. // ShareWeighted indicates that a shared resource should be shared as a
  18. // proportion of the cost of the remaining allocations.
  19. const ShareWeighted = "__weighted__"
  20. // ShareEven indicates that a shared resource should be shared evenly across
  21. // all remaining allocations.
  22. const ShareEven = "__even__"
  23. // ShareNone indicates that a shareable resource should not be shared
  24. const ShareNone = "__none__"
  25. // Allocation is a unit of resource allocation and cost for a given window
  26. // of time and for a given kubernetes construct with its associated set of
  27. // properties.
  28. type Allocation struct {
  29. Name string `json:"name"`
  30. Properties Properties `json:"properties,omitempty"`
  31. Start time.Time `json:"start"`
  32. End time.Time `json:"end"`
  33. Minutes float64 `json:"minutes"`
  34. ActiveStart time.Time `json:"-"`
  35. CPUCoreHours float64 `json:"cpuCoreHours"`
  36. CPUCost float64 `json:"cpuCost"`
  37. CPUEfficiency float64 `json:"cpuEfficiency"`
  38. GPUHours float64 `json:"gpuHours"`
  39. GPUCost float64 `json:"gpuCost"`
  40. NetworkCost float64 `json:"networkCost"`
  41. PVByteHours float64 `json:"pvByteHours"`
  42. PVCost float64 `json:"pvCost"`
  43. RAMByteHours float64 `json:"ramByteHours"`
  44. RAMCost float64 `json:"ramCost"`
  45. RAMEfficiency float64 `json:"ramEfficiency"`
  46. SharedCost float64 `json:"sharedCost"`
  47. TotalCost float64 `json:"totalCost"`
  48. TotalEfficiency float64 `json:"totalEfficiency"`
  49. // Profiler *log.Profiler `json:"-"`
  50. }
  51. // AllocationMatchFunc is a function that can be used to match Allocations by
  52. // returning true for any given Allocation if a condition is met.
  53. type AllocationMatchFunc func(*Allocation) bool
  54. // Add returns the result of summing the two given Allocations, which sums the
  55. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  56. // the two original Allocations are mutated in the process.
  57. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  58. if a == nil {
  59. return that.Clone(), nil
  60. }
  61. if !a.Start.Equal(that.Start) || !a.End.Equal(that.End) {
  62. return nil, fmt.Errorf("error adding Allocations: mismatched windows")
  63. }
  64. agg := a.Clone()
  65. // agg.Profiler = a.Profiler
  66. agg.add(that, false, false)
  67. return agg, nil
  68. }
  69. // Clone returns a deep copy of the given Allocation
  70. func (a *Allocation) Clone() *Allocation {
  71. if a == nil {
  72. return nil
  73. }
  74. return &Allocation{
  75. Name: a.Name,
  76. Properties: a.Properties.Clone(),
  77. Start: a.Start,
  78. End: a.End,
  79. Minutes: a.Minutes,
  80. ActiveStart: a.ActiveStart,
  81. CPUCoreHours: a.CPUCoreHours,
  82. CPUCost: a.CPUCost,
  83. CPUEfficiency: a.CPUEfficiency,
  84. GPUHours: a.GPUHours,
  85. GPUCost: a.GPUCost,
  86. NetworkCost: a.NetworkCost,
  87. PVByteHours: a.PVByteHours,
  88. PVCost: a.PVCost,
  89. RAMByteHours: a.RAMByteHours,
  90. RAMCost: a.RAMCost,
  91. RAMEfficiency: a.RAMEfficiency,
  92. SharedCost: a.SharedCost,
  93. TotalCost: a.TotalCost,
  94. TotalEfficiency: a.TotalEfficiency,
  95. }
  96. }
  97. func (a *Allocation) Equal(that *Allocation) bool {
  98. if a == nil || that == nil {
  99. return false
  100. }
  101. if a.Name != that.Name {
  102. return false
  103. }
  104. if !a.Start.Equal(that.Start) {
  105. return false
  106. }
  107. if !a.End.Equal(that.End) {
  108. return false
  109. }
  110. if a.Minutes != that.Minutes {
  111. return false
  112. }
  113. if !a.ActiveStart.Equal(that.ActiveStart) {
  114. return false
  115. }
  116. if a.CPUCoreHours != that.CPUCoreHours {
  117. return false
  118. }
  119. if a.CPUCost != that.CPUCost {
  120. return false
  121. }
  122. if a.CPUEfficiency != that.CPUEfficiency {
  123. return false
  124. }
  125. if a.GPUHours != that.GPUHours {
  126. return false
  127. }
  128. if a.GPUCost != that.GPUCost {
  129. return false
  130. }
  131. if a.NetworkCost != that.NetworkCost {
  132. return false
  133. }
  134. if a.PVByteHours != that.PVByteHours {
  135. return false
  136. }
  137. if a.PVCost != that.PVCost {
  138. return false
  139. }
  140. if a.RAMByteHours != that.RAMByteHours {
  141. return false
  142. }
  143. if a.RAMCost != that.RAMCost {
  144. return false
  145. }
  146. if a.RAMEfficiency != that.RAMEfficiency {
  147. return false
  148. }
  149. if a.SharedCost != that.SharedCost {
  150. return false
  151. }
  152. if a.TotalCost != that.TotalCost {
  153. return false
  154. }
  155. if a.TotalEfficiency != that.TotalEfficiency {
  156. return false
  157. }
  158. if !a.Properties.Equal(&that.Properties) {
  159. return false
  160. }
  161. return true
  162. }
  163. // Resolution returns the duration of time covered by the Allocation
  164. func (a *Allocation) Resolution() time.Duration {
  165. return a.End.Sub(a.Start)
  166. }
  167. // IsAggregated is true if the given Allocation has been aggregated, which we
  168. // define by a lack of Properties.
  169. func (a *Allocation) IsAggregated() bool {
  170. return a == nil || a.Properties == nil
  171. }
  172. // IsIdle is true if the given Allocation represents idle costs.
  173. func (a *Allocation) IsIdle() bool {
  174. return strings.Contains(a.Name, IdleSuffix)
  175. }
  176. // IsUnallocated is true if the given Allocation represents unallocated costs.
  177. func (a *Allocation) IsUnallocated() bool {
  178. return strings.Contains(a.Name, UnallocatedSuffix)
  179. }
  180. // MatchesFilter returns true if the Allocation passes the given AllocationFilter
  181. func (a *Allocation) MatchesFilter(f AllocationMatchFunc) bool {
  182. return f(a)
  183. }
  184. // MatchesAll takes a variadic list of Properties, returning true iff the
  185. // Allocation matches each set of Properties.
  186. func (a *Allocation) MatchesAll(ps ...Properties) bool {
  187. // nil Allocation don't match any Properties
  188. if a == nil {
  189. return false
  190. }
  191. for _, p := range ps {
  192. if !a.Properties.Matches(p) {
  193. return false
  194. }
  195. }
  196. return true
  197. }
  198. // MatchesOne takes a variadic list of Properties, returning true iff the
  199. // Allocation matches at least one of the set of Properties.
  200. func (a *Allocation) MatchesOne(ps ...Properties) bool {
  201. // nil Allocation don't match any Properties
  202. if a == nil {
  203. return false
  204. }
  205. for _, p := range ps {
  206. if a.Properties.Matches(p) {
  207. return true
  208. }
  209. }
  210. return false
  211. }
  212. // Share works like Add, but converts the entire cost of the given Allocation
  213. // to SharedCost, rather than adding to the individual resource costs.
  214. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  215. if a == nil {
  216. return that.Clone(), nil
  217. }
  218. if !a.Start.Equal(that.Start) {
  219. return nil, fmt.Errorf("mismatched start time: expected %s, received %s", a.Start, that.Start)
  220. }
  221. if !a.End.Equal(that.End) {
  222. return nil, fmt.Errorf("mismatched start time: expected %s, received %s", a.End, that.End)
  223. }
  224. agg := a.Clone()
  225. agg.add(that, true, false)
  226. return agg, nil
  227. }
  228. // String represents the given Allocation as a string
  229. func (a *Allocation) String() string {
  230. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost)
  231. }
  232. func (a *Allocation) add(that *Allocation, isShared, isAccumulating bool) {
  233. if a == nil {
  234. a = that
  235. // reset properties
  236. thatCluster, _ := that.Properties.GetCluster()
  237. thatNode, _ := that.Properties.GetNode()
  238. a.Properties = Properties{ClusterProp: thatCluster, NodeProp: thatNode}
  239. return
  240. }
  241. aCluster, _ := a.Properties.GetCluster()
  242. thatCluster, _ := that.Properties.GetCluster()
  243. aNode, _ := a.Properties.GetNode()
  244. thatNode, _ := that.Properties.GetNode()
  245. // reset properties
  246. a.Properties = nil
  247. // ensure that we carry cluster ID and/or node over if they're the same
  248. // required for idle/shared cost allocation
  249. if aCluster == thatCluster {
  250. a.Properties = Properties{ClusterProp: aCluster}
  251. }
  252. if aNode == thatNode {
  253. if a.Properties == nil {
  254. a.Properties = Properties{NodeProp: aNode}
  255. } else {
  256. a.Properties.SetNode(aNode)
  257. }
  258. }
  259. if that.ActiveStart.Before(a.ActiveStart) {
  260. a.ActiveStart = that.ActiveStart
  261. }
  262. if isAccumulating {
  263. if a.Start.After(that.Start) {
  264. a.Start = that.Start
  265. }
  266. if a.End.Before(that.End) {
  267. a.End = that.End
  268. }
  269. a.Minutes += that.Minutes
  270. } else if that.Minutes > a.Minutes {
  271. a.Minutes = that.Minutes
  272. }
  273. // isShared determines whether the given allocation should be spread evenly
  274. // across resources (e.g. sharing idle allocation) or lumped into a shared
  275. // cost category (e.g. sharing namespace, labels).
  276. if isShared {
  277. a.SharedCost += that.TotalCost
  278. } else {
  279. a.CPUCoreHours += that.CPUCoreHours
  280. a.GPUHours += that.GPUHours
  281. a.RAMByteHours += that.RAMByteHours
  282. a.PVByteHours += that.PVByteHours
  283. aggCPUCost := a.CPUCost + that.CPUCost
  284. if aggCPUCost > 0 {
  285. a.CPUEfficiency = (a.CPUEfficiency*a.CPUCost + that.CPUEfficiency*that.CPUCost) / aggCPUCost
  286. } else {
  287. a.CPUEfficiency = 0.0
  288. }
  289. aggRAMCost := a.RAMCost + that.RAMCost
  290. if aggRAMCost > 0 {
  291. a.RAMEfficiency = (a.RAMEfficiency*a.RAMCost + that.RAMEfficiency*that.RAMCost) / aggRAMCost
  292. } else {
  293. a.RAMEfficiency = 0.0
  294. }
  295. aggTotalCost := a.TotalCost + that.TotalCost
  296. if aggTotalCost > 0 {
  297. a.TotalEfficiency = (a.TotalEfficiency*a.TotalCost + that.TotalEfficiency*that.TotalCost) / aggTotalCost
  298. } else {
  299. aggTotalCost = 0.0
  300. }
  301. a.SharedCost += that.SharedCost
  302. a.CPUCost += that.CPUCost
  303. a.GPUCost += that.GPUCost
  304. a.NetworkCost += that.NetworkCost
  305. a.RAMCost += that.RAMCost
  306. a.PVCost += that.PVCost
  307. }
  308. a.TotalCost += that.TotalCost
  309. }
  310. // AllocationSet stores a set of Allocations, each with a unique name, that share
  311. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  312. type AllocationSet struct {
  313. sync.RWMutex
  314. // Profiler *log.Profiler
  315. allocations map[string]*Allocation
  316. idleKeys map[string]bool
  317. Window Window
  318. Warnings []string
  319. Errors []string
  320. }
  321. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  322. // the given list of Allocations
  323. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  324. as := &AllocationSet{
  325. allocations: map[string]*Allocation{},
  326. Window: NewWindow(&start, &end),
  327. }
  328. for _, a := range allocs {
  329. as.Insert(a)
  330. }
  331. return as
  332. }
  333. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  334. // filtering results and sharing allocations. FilterFuncs are a list of match
  335. // functions such that, if any function fails, the allocation is ignored.
  336. // ShareFuncs are a list of match functions such that, if any function
  337. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  338. // simple flag for sharing idle resources.
  339. type AllocationAggregationOptions struct {
  340. FilterFuncs []AllocationMatchFunc
  341. SplitIdle bool
  342. MergeUnallocated bool
  343. ShareFuncs []AllocationMatchFunc
  344. ShareIdle string
  345. ShareSplit string
  346. SharedHourlyCosts map[string]float64
  347. }
  348. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  349. // Property. This will only be legal if the AllocationSet is divisible by the
  350. // given Property; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  351. func (as *AllocationSet) AggregateBy(properties Properties, options *AllocationAggregationOptions) error {
  352. // The order of operations for aggregating allocations is as follows:
  353. // 1. move shared and/or idle allocations to separate sets if options
  354. // indicate that they should be shared
  355. // 2. idle coefficients
  356. // 2.a) if idle allocation is to be shared, compute idle coefficients
  357. // (do not compute shared coefficients here, see step 5)
  358. // 2.b) if idle allocation is NOT shared, but filters are present, compute
  359. // idle filtration coefficients for the purpose of only returning the
  360. // portion of idle allocation that would have been shared with the
  361. // unfiltered results set. (See unit tests 5.a,b,c)
  362. // 3. ignore allocation if it fails any of the FilterFuncs
  363. // 4. generate aggregation key and insert allocation into the output set
  364. // 5. if there are shared allocations, compute sharing coefficients on
  365. // the aggregated set, then share allocation accordingly
  366. // 6. if the merge idle option is enabled, merge any remaining idle
  367. // allocations into a single idle allocation
  368. // TODO niko/etl revisit (ShareIdle: ShareEven) case, which is probably wrong
  369. // (and, frankly, ill-defined; i.e. evenly across clusters? within clusters?)
  370. if options == nil {
  371. options = &AllocationAggregationOptions{}
  372. }
  373. if as.IsEmpty() {
  374. return nil
  375. }
  376. // aggSet will collect the aggregated allocations
  377. aggSet := &AllocationSet{
  378. // Profiler: as.Profiler,
  379. Window: as.Window.Clone(),
  380. }
  381. // idleSet will be shared among aggSet after initial aggregation
  382. // is complete
  383. idleSet := &AllocationSet{
  384. // Profiler: as.Profiler,
  385. Window: as.Window.Clone(),
  386. }
  387. // shareSet will be shared among aggSet after initial aggregation
  388. // is complete
  389. shareSet := &AllocationSet{
  390. // Profiler: as.Profiler
  391. Window: as.Window.Clone(),
  392. }
  393. for name, cost := range options.SharedHourlyCosts {
  394. if cost > 0.0 {
  395. hours := as.Resolution().Hours()
  396. // If set ends in the future, adjust hours accordingly
  397. diff := time.Now().Sub(as.End())
  398. if diff < 0.0 {
  399. hours += diff.Hours()
  400. }
  401. totalSharedCost := cost * hours
  402. shareSet.Insert(&Allocation{
  403. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  404. Start: as.Start(),
  405. End: as.End(),
  406. SharedCost: totalSharedCost,
  407. TotalCost: totalSharedCost,
  408. })
  409. }
  410. }
  411. as.Lock()
  412. defer as.Unlock()
  413. // Loop and find all of the idle and shared allocations initially. Add
  414. // them to their respective sets, removing them from the set of
  415. // allocations to aggregate.
  416. for _, alloc := range as.allocations {
  417. cluster, err := alloc.Properties.GetCluster()
  418. if err != nil {
  419. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  420. return err
  421. }
  422. // Idle allocation doesn't get aggregated, so it can be passed through,
  423. // whether or not it is shared. If it is shared, it is put in idleSet
  424. // because shareSet may be split by different rules (even/weighted).
  425. if alloc.IsIdle() {
  426. // Can't recursively call Delete() due to lock acquisition
  427. delete(as.idleKeys, alloc.Name)
  428. delete(as.allocations, alloc.Name)
  429. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  430. idleSet.Insert(alloc)
  431. } else {
  432. aggSet.Insert(alloc)
  433. }
  434. }
  435. // If any of the share funcs succeed, share the allocation. Do this
  436. // prior to filtering so that shared namespaces, etc do not get
  437. // filtered out before we have a chance to share them.
  438. for _, sf := range options.ShareFuncs {
  439. if sf(alloc) {
  440. // Can't recursively call Delete() due to lock acquisition
  441. delete(as.idleKeys, alloc.Name)
  442. delete(as.allocations, alloc.Name)
  443. alloc.Name = fmt.Sprintf("%s/%s", cluster, SharedSuffix)
  444. shareSet.Insert(alloc)
  445. break
  446. }
  447. }
  448. }
  449. if len(as.allocations) == 0 {
  450. log.Warningf("ETL: AggregateBy: no allocations to aggregate")
  451. emptySet := &AllocationSet{
  452. Window: as.Window.Clone(),
  453. }
  454. as.allocations = emptySet.allocations
  455. return nil
  456. }
  457. // In order to correctly apply idle and shared resource coefficients appropriately,
  458. // we need to determine the coefficients for the full set of data. The ensures that
  459. // the ratios are maintained through filtering.
  460. // idleCoefficients are organized by [cluster][allocation][resource]=coeff
  461. var idleCoefficients map[string]map[string]map[string]float64
  462. // shareCoefficients are organized by [allocation][resource]=coeff (no cluster)
  463. var shareCoefficients map[string]float64
  464. var err error
  465. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  466. idleCoefficients, err = computeIdleCoeffs(properties, options, as)
  467. if err != nil {
  468. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  469. return err
  470. }
  471. }
  472. // If we're not sharing idle and we're filtering, we need to track the
  473. // amount of each idle allocation to "delete" in order to maintain parity
  474. // with the idle-allocated results. That is, we want to return only the
  475. // idle cost that would have been shared with the unfiltered portion of
  476. // the results, not the full idle cost.
  477. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  478. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  479. idleFiltrationCoefficients, err = computeIdleCoeffs(properties, options, as)
  480. if err != nil {
  481. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  482. return err
  483. }
  484. }
  485. for _, alloc := range as.allocations {
  486. cluster, err := alloc.Properties.GetCluster()
  487. if err != nil {
  488. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  489. return err
  490. }
  491. skip := false
  492. // If any of the filter funcs fail, immediately skip the allocation.
  493. for _, ff := range options.FilterFuncs {
  494. if !ff(alloc) {
  495. skip = true
  496. break
  497. }
  498. }
  499. if skip {
  500. // If we are tracking idle filtration coefficients, delete the
  501. // entry corresponding to the filtered allocation. (Deleting the
  502. // entry will result in that proportional amount being removed
  503. // from the idle allocation at the end of the process.)
  504. if idleFiltrationCoefficients != nil {
  505. if ifcc, ok := idleFiltrationCoefficients[cluster]; ok {
  506. delete(ifcc, alloc.Name)
  507. }
  508. }
  509. continue
  510. }
  511. // Split idle allocations and distribute among aggregated allocations
  512. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then all
  513. // idle allocations will be in the aggSet at this point.
  514. if idleSet.Length() > 0 {
  515. // Distribute idle allocations by coefficient per-cluster, per-allocation
  516. for _, idleAlloc := range idleSet.allocations {
  517. // Only share idle if the cluster matches; i.e. the allocation
  518. // is from the same cluster as the idle costs
  519. idleCluster, err := idleAlloc.Properties.GetCluster()
  520. if err != nil {
  521. return err
  522. }
  523. if idleCluster != cluster {
  524. continue
  525. }
  526. // Make sure idle coefficients exist
  527. if _, ok := idleCoefficients[cluster]; !ok {
  528. log.Errorf("ETL: share (idle) allocation: error getting allocation coefficient [no cluster: '%s' in coefficients] for '%s'", cluster, alloc.Name)
  529. continue
  530. }
  531. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  532. log.Errorf("ETL: share (idle) allocation: error getting allocation coefficienct for '%s'", alloc.Name)
  533. continue
  534. }
  535. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  536. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  537. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  538. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  539. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  540. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  541. alloc.CPUCost += idleCPUCost
  542. alloc.GPUCost += idleGPUCost
  543. alloc.RAMCost += idleRAMCost
  544. alloc.TotalCost += idleCPUCost + idleGPUCost + idleRAMCost
  545. }
  546. }
  547. key, err := alloc.generateKey(properties)
  548. if err != nil {
  549. return err
  550. }
  551. alloc.Name = key
  552. if options.MergeUnallocated && alloc.IsUnallocated() {
  553. alloc.Name = UnallocatedSuffix
  554. }
  555. aggSet.Insert(alloc)
  556. }
  557. var clusterIdleFiltrationCoeffs map[string]map[string]float64
  558. if idleFiltrationCoefficients != nil {
  559. clusterIdleFiltrationCoeffs = map[string]map[string]float64{}
  560. for cluster, m := range idleFiltrationCoefficients {
  561. if _, ok := clusterIdleFiltrationCoeffs[cluster]; !ok {
  562. clusterIdleFiltrationCoeffs[cluster] = map[string]float64{
  563. "cpu": 0.0,
  564. "gpu": 0.0,
  565. "ram": 0.0,
  566. }
  567. }
  568. for _, n := range m {
  569. for resource, val := range n {
  570. clusterIdleFiltrationCoeffs[cluster][resource] += val
  571. }
  572. }
  573. }
  574. }
  575. // If we have filters, and so have computed coefficients for scaling idle
  576. // allocation costs by cluster, then use those coefficients to scale down
  577. // each idle coefficient in the aggSet.
  578. if len(aggSet.idleKeys) > 0 && clusterIdleFiltrationCoeffs != nil {
  579. for idleKey := range aggSet.idleKeys {
  580. idleAlloc := aggSet.Get(idleKey)
  581. cluster, err := idleAlloc.Properties.GetCluster()
  582. if err != nil {
  583. log.Warningf("AggregateBy: idle allocation without cluster: %s", idleAlloc)
  584. }
  585. if resourceCoeffs, ok := clusterIdleFiltrationCoeffs[cluster]; ok {
  586. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  587. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  588. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  589. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  590. idleAlloc.TotalCost = idleAlloc.CPUCost + idleAlloc.RAMCost
  591. }
  592. }
  593. }
  594. // Split shared allocations and distribute among aggregated allocations
  595. if shareSet.Length() > 0 {
  596. shareCoefficients, err = computeShareCoeffs(properties, options, aggSet)
  597. if err != nil {
  598. log.Warningf("AllocationSet.AggregateBy: compute shared coeff: missing cluster ID: %s", err)
  599. return err
  600. }
  601. for _, alloc := range aggSet.allocations {
  602. if alloc.IsIdle() {
  603. // Skip idle allocations (they do not receive shared allocation)
  604. continue
  605. }
  606. // Distribute shared allocations by coefficient per-allocation
  607. // NOTE: share coefficients do not partition by cluster, like
  608. // idle coefficients do.
  609. for _, sharedAlloc := range shareSet.allocations {
  610. if _, ok := shareCoefficients[alloc.Name]; !ok {
  611. log.Errorf("ETL: share allocation: error getting allocation coefficienct for '%s'", alloc.Name)
  612. continue
  613. }
  614. alloc.SharedCost += sharedAlloc.TotalCost * shareCoefficients[alloc.Name]
  615. alloc.TotalCost += sharedAlloc.TotalCost * shareCoefficients[alloc.Name]
  616. }
  617. }
  618. }
  619. // Combine all idle allocations into a single "__idle__" allocation
  620. if !options.SplitIdle {
  621. for _, idleAlloc := range aggSet.IdleAllocations() {
  622. aggSet.Delete(idleAlloc.Name)
  623. idleAlloc.Name = IdleSuffix
  624. aggSet.Insert(idleAlloc)
  625. }
  626. }
  627. as.allocations = aggSet.allocations
  628. return nil
  629. }
  630. // TODO niko/etl deprecate the use of a map of resources here, we only use totals
  631. func computeShareCoeffs(properties Properties, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  632. // Compute coeffs by totalling per-allocation, then dividing by the total.
  633. coeffs := map[string]float64{}
  634. // Compute totals for all allocations
  635. total := 0.0
  636. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  637. // counts each aggregation proportionally to its respective costs
  638. shareType := options.ShareSplit
  639. // Record allocation values first, then normalize by totals to get percentages
  640. for name, alloc := range as.allocations {
  641. if alloc.IsIdle() {
  642. // Skip idle allocations in coefficient calculation
  643. continue
  644. }
  645. if shareType == ShareEven {
  646. // Not additive - set to 1.0 for even distribution
  647. coeffs[name] = 1.0
  648. // Total is always additive
  649. total += 1.0
  650. } else {
  651. // Both are additive for weighted distribution
  652. coeffs[name] += alloc.TotalCost
  653. total += alloc.TotalCost
  654. }
  655. }
  656. // Normalize coefficients by totals
  657. for a := range coeffs {
  658. if coeffs[a] > 0 && total > 0 {
  659. coeffs[a] /= total
  660. } else {
  661. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  662. coeffs[a] = 0.0
  663. }
  664. }
  665. return coeffs, nil
  666. }
  667. func computeIdleCoeffs(properties Properties, options *AllocationAggregationOptions, as *AllocationSet) (map[string]map[string]map[string]float64, error) {
  668. types := []string{"cpu", "gpu", "ram"}
  669. // Compute idle coefficients, then save them in AllocationAggregationOptions
  670. coeffs := map[string]map[string]map[string]float64{}
  671. // Compute totals per resource for CPU, GPU, RAM, and PV
  672. totals := map[string]map[string]float64{}
  673. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  674. // counts each allocation proportionally to its respective costs
  675. shareType := options.ShareIdle
  676. // Record allocation values first, then normalize by totals to get percentages
  677. for _, alloc := range as.allocations {
  678. if alloc.IsIdle() {
  679. // Skip idle allocations in coefficient calculation
  680. continue
  681. }
  682. // If any of the share funcs succeed, share the allocation. Do this
  683. // prior to filtering so that shared namespaces, etc do not get
  684. // filtered out before we have a chance to share them.
  685. skip := false
  686. for _, sf := range options.ShareFuncs {
  687. if sf(alloc) {
  688. skip = true
  689. break
  690. }
  691. }
  692. if skip {
  693. continue
  694. }
  695. // We need to key the allocations by cluster id
  696. clusterID, err := alloc.Properties.GetCluster()
  697. if err != nil {
  698. return nil, err
  699. }
  700. // get the name key for the allocation
  701. name := alloc.Name
  702. // Create cluster based tables if they don't exist
  703. if _, ok := coeffs[clusterID]; !ok {
  704. coeffs[clusterID] = map[string]map[string]float64{}
  705. }
  706. if _, ok := totals[clusterID]; !ok {
  707. totals[clusterID] = map[string]float64{}
  708. }
  709. if _, ok := coeffs[clusterID][name]; !ok {
  710. coeffs[clusterID][name] = map[string]float64{}
  711. }
  712. if shareType == ShareEven {
  713. for _, r := range types {
  714. // Not additive - hard set to 1.0
  715. coeffs[clusterID][name][r] = 1.0
  716. // totals are additive
  717. totals[clusterID][r] += 1.0
  718. }
  719. } else {
  720. coeffs[clusterID][name]["cpu"] += alloc.CPUCost
  721. coeffs[clusterID][name]["gpu"] += alloc.GPUCost
  722. coeffs[clusterID][name]["ram"] += alloc.RAMCost
  723. totals[clusterID]["cpu"] += alloc.CPUCost
  724. totals[clusterID]["gpu"] += alloc.GPUCost
  725. totals[clusterID]["ram"] += alloc.RAMCost
  726. }
  727. }
  728. // Normalize coefficients by totals
  729. for c := range coeffs {
  730. for a := range coeffs[c] {
  731. for _, r := range types {
  732. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  733. coeffs[c][a][r] /= totals[c][r]
  734. }
  735. }
  736. }
  737. }
  738. return coeffs, nil
  739. }
  740. func (alloc *Allocation) generateKey(properties Properties) (string, error) {
  741. // Names will ultimately be joined into a single name, which uniquely
  742. // identifies allocations.
  743. names := []string{}
  744. if properties.HasCluster() {
  745. cluster, err := alloc.Properties.GetCluster()
  746. if err != nil {
  747. return "", err
  748. }
  749. names = append(names, cluster)
  750. }
  751. if properties.HasNode() {
  752. node, err := alloc.Properties.GetNode()
  753. if err != nil {
  754. return "", err
  755. }
  756. names = append(names, node)
  757. }
  758. if properties.HasNamespace() {
  759. namespace, err := alloc.Properties.GetNamespace()
  760. if err != nil {
  761. return "", err
  762. }
  763. names = append(names, namespace)
  764. }
  765. if properties.HasControllerKind() {
  766. controllerKind, err := alloc.Properties.GetControllerKind()
  767. if err != nil {
  768. // Indicate that allocation has no controller
  769. controllerKind = UnallocatedSuffix
  770. }
  771. if prop, _ := properties.GetControllerKind(); prop != "" && prop != controllerKind {
  772. // The allocation does not have the specified controller kind
  773. controllerKind = UnallocatedSuffix
  774. }
  775. names = append(names, controllerKind)
  776. }
  777. if properties.HasController() {
  778. if !properties.HasControllerKind() {
  779. controllerKind, err := alloc.Properties.GetControllerKind()
  780. if err == nil {
  781. names = append(names, controllerKind)
  782. }
  783. }
  784. controller, err := alloc.Properties.GetController()
  785. if err != nil {
  786. // Indicate that allocation has no controller
  787. controller = UnallocatedSuffix
  788. }
  789. names = append(names, controller)
  790. }
  791. if properties.HasPod() {
  792. pod, err := alloc.Properties.GetPod()
  793. if err != nil {
  794. return "", err
  795. }
  796. names = append(names, pod)
  797. }
  798. if properties.HasContainer() {
  799. container, err := alloc.Properties.GetContainer()
  800. if err != nil {
  801. return "", err
  802. }
  803. names = append(names, container)
  804. }
  805. if properties.HasService() {
  806. services, err := alloc.Properties.GetServices()
  807. if err != nil {
  808. // Indicate that allocation has no services
  809. names = append(names, UnallocatedSuffix)
  810. } else {
  811. // TODO niko/etl support multi-service aggregation
  812. if len(services) > 0 {
  813. for _, service := range services {
  814. names = append(names, service)
  815. break
  816. }
  817. } else {
  818. // Indicate that allocation has no services
  819. names = append(names, UnallocatedSuffix)
  820. }
  821. }
  822. }
  823. if properties.HasLabel() {
  824. labels, err := alloc.Properties.GetLabels() // labels that the individual allocation possesses
  825. if err != nil {
  826. // Indicate that allocation has no labels
  827. names = append(names, UnallocatedSuffix)
  828. } else {
  829. labelNames := []string{}
  830. aggLabels, err := properties.GetLabels() // potential labels to aggregate on supplied by the API caller
  831. if err != nil {
  832. // We've already checked HasLabel, so this should never occur
  833. return "", err
  834. }
  835. // calvin - support multi-label aggregation
  836. for labelName := range aggLabels {
  837. if val, ok := labels[labelName]; ok {
  838. labelNames = append(labelNames, fmt.Sprintf("%s=%s", labelName, val))
  839. } else if indexOf(UnallocatedSuffix, labelNames) == -1 { // if UnallocatedSuffix not already in names
  840. labelNames = append(labelNames, UnallocatedSuffix)
  841. }
  842. }
  843. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  844. if len(labelNames) > 1 {
  845. sort.Strings(labelNames)
  846. }
  847. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, labelNames)
  848. // suffix should be at index 0 if it exists b/c of underscores
  849. if unallocatedSuffixIndex != -1 {
  850. labelNames = append(labelNames[:unallocatedSuffixIndex], labelNames[unallocatedSuffixIndex+1:]...)
  851. labelNames = append(labelNames, UnallocatedSuffix) // append to end
  852. }
  853. names = append(names, labelNames...)
  854. }
  855. }
  856. return strings.Join(names, "/"), nil
  857. }
  858. // Helper function to check for slice membership. Not sure if repeated elsewhere in our codebase.
  859. func indexOf(v string, arr []string) int {
  860. for i, s := range arr {
  861. // This is caseless equivalence
  862. if strings.EqualFold(v, s) {
  863. return i
  864. }
  865. }
  866. return -1
  867. }
  868. // Clone returns a new AllocationSet with a deep copy of the given
  869. // AllocationSet's allocations.
  870. func (as *AllocationSet) Clone() *AllocationSet {
  871. if as == nil {
  872. return nil
  873. }
  874. as.RLock()
  875. defer as.RUnlock()
  876. allocs := map[string]*Allocation{}
  877. for k, v := range as.allocations {
  878. allocs[k] = v.Clone()
  879. }
  880. return &AllocationSet{
  881. allocations: allocs,
  882. Window: as.Window.Clone(),
  883. }
  884. }
  885. // Delete removes the allocation with the given name from the set
  886. func (as *AllocationSet) Delete(name string) {
  887. if as == nil {
  888. return
  889. }
  890. as.Lock()
  891. defer as.Unlock()
  892. delete(as.idleKeys, name)
  893. delete(as.allocations, name)
  894. }
  895. // Each invokes the given function for each Allocation in the set
  896. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  897. if as == nil {
  898. return
  899. }
  900. for k, a := range as.allocations {
  901. f(k, a)
  902. }
  903. }
  904. // End returns the End time of the AllocationSet window
  905. func (as *AllocationSet) End() time.Time {
  906. if as == nil {
  907. log.Warningf("Allocation ETL: calling End on nil AllocationSet")
  908. return time.Unix(0, 0)
  909. }
  910. if as.Window.End() == nil {
  911. log.Warningf("Allocation ETL: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  912. return time.Unix(0, 0)
  913. }
  914. return *as.Window.End()
  915. }
  916. // Get returns the Allocation at the given key in the AllocationSet
  917. func (as *AllocationSet) Get(key string) *Allocation {
  918. as.RLock()
  919. defer as.RUnlock()
  920. if alloc, ok := as.allocations[key]; ok {
  921. return alloc
  922. }
  923. return nil
  924. }
  925. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  926. // Returns clones of the actual Allocations, so mutability is not a problem.
  927. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  928. idles := map[string]*Allocation{}
  929. if as.IsEmpty() {
  930. return idles
  931. }
  932. as.RLock()
  933. defer as.RUnlock()
  934. for key := range as.idleKeys {
  935. if alloc, ok := as.allocations[key]; ok {
  936. idles[key] = alloc.Clone()
  937. }
  938. }
  939. return idles
  940. }
  941. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  942. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  943. // there is no existing entry, one is created. Nil error response indicates success.
  944. func (as *AllocationSet) Insert(that *Allocation) error {
  945. return as.insert(that, false)
  946. }
  947. func (as *AllocationSet) insert(that *Allocation, accumulate bool) error {
  948. if as.IsEmpty() {
  949. as.Lock()
  950. as.allocations = map[string]*Allocation{}
  951. as.idleKeys = map[string]bool{}
  952. as.Unlock()
  953. }
  954. as.Lock()
  955. defer as.Unlock()
  956. // Add the given Allocation to the existing entry, if there is one;
  957. // otherwise just set directly into allocations
  958. if _, ok := as.allocations[that.Name]; !ok {
  959. as.allocations[that.Name] = that
  960. } else {
  961. as.allocations[that.Name].add(that, false, accumulate)
  962. }
  963. // If the given Allocation is an idle one, record that
  964. if that.IsIdle() {
  965. as.idleKeys[that.Name] = true
  966. }
  967. return nil
  968. }
  969. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  970. // zero allocations.
  971. func (as *AllocationSet) IsEmpty() bool {
  972. if as == nil || len(as.allocations) == 0 {
  973. return true
  974. }
  975. as.RLock()
  976. defer as.RUnlock()
  977. return as.allocations == nil || len(as.allocations) == 0
  978. }
  979. // Length returns the number of Allocations in the set
  980. func (as *AllocationSet) Length() int {
  981. if as == nil {
  982. return 0
  983. }
  984. as.RLock()
  985. defer as.RUnlock()
  986. return len(as.allocations)
  987. }
  988. // Map clones and returns a map of the AllocationSet's Allocations
  989. func (as *AllocationSet) Map() map[string]*Allocation {
  990. if as.IsEmpty() {
  991. return map[string]*Allocation{}
  992. }
  993. return as.Clone().allocations
  994. }
  995. // MarshalJSON JSON-encodes the AllocationSet
  996. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  997. as.RLock()
  998. defer as.RUnlock()
  999. return json.Marshal(as.allocations)
  1000. }
  1001. // Resolution returns the AllocationSet's window duration
  1002. func (as *AllocationSet) Resolution() time.Duration {
  1003. return as.Window.Duration()
  1004. }
  1005. func (as *AllocationSet) Set(alloc *Allocation) error {
  1006. if as.IsEmpty() {
  1007. as.Lock()
  1008. as.allocations = map[string]*Allocation{}
  1009. as.idleKeys = map[string]bool{}
  1010. as.Unlock()
  1011. }
  1012. as.Lock()
  1013. defer as.Unlock()
  1014. as.allocations[alloc.Name] = alloc
  1015. // If the given Allocation is an idle one, record that
  1016. if alloc.IsIdle() {
  1017. as.idleKeys[alloc.Name] = true
  1018. }
  1019. return nil
  1020. }
  1021. // Start returns the Start time of the AllocationSet window
  1022. func (as *AllocationSet) Start() time.Time {
  1023. if as == nil {
  1024. log.Warningf("Allocation ETL: calling Start on nil AllocationSet")
  1025. return time.Unix(0, 0)
  1026. }
  1027. if as.Window.Start() == nil {
  1028. log.Warningf("Allocation ETL: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1029. return time.Unix(0, 0)
  1030. }
  1031. return *as.Window.Start()
  1032. }
  1033. // String represents the given Allocation as a string
  1034. func (as *AllocationSet) String() string {
  1035. if as == nil {
  1036. return "<nil>"
  1037. }
  1038. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1039. as.Length(), as.Window, as.TotalCost())
  1040. }
  1041. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1042. func (as *AllocationSet) TotalCost() float64 {
  1043. if as.IsEmpty() {
  1044. return 0.0
  1045. }
  1046. as.RLock()
  1047. defer as.RUnlock()
  1048. tc := 0.0
  1049. for _, a := range as.allocations {
  1050. tc += a.TotalCost
  1051. }
  1052. return tc
  1053. }
  1054. func (as *AllocationSet) UTCOffset() time.Duration {
  1055. _, zone := as.Start().Zone()
  1056. return time.Duration(zone) * time.Second
  1057. }
  1058. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1059. if as.IsEmpty() {
  1060. return that, nil
  1061. }
  1062. if that.IsEmpty() {
  1063. return as, nil
  1064. }
  1065. if that.Start().Before(as.End()) {
  1066. timefmt := "2006-01-02T15:04:05"
  1067. err := fmt.Sprintf("that [%s, %s); that [%s, %s)\n", as.Start().Format(timefmt), as.End().Format(timefmt), that.Start().Format(timefmt), that.End().Format(timefmt))
  1068. return nil, fmt.Errorf("error accumulating AllocationSets: overlapping windows: %s", err)
  1069. }
  1070. // Set start, end to min(start), max(end)
  1071. start := as.Start()
  1072. end := as.End()
  1073. if that.Start().Before(start) {
  1074. start = that.Start()
  1075. }
  1076. if that.End().After(end) {
  1077. end = that.End()
  1078. }
  1079. acc := NewAllocationSet(start, end)
  1080. as.RLock()
  1081. defer as.RUnlock()
  1082. that.RLock()
  1083. defer that.RUnlock()
  1084. for _, alloc := range as.allocations {
  1085. // Change Start and End to match the new window. However, do not
  1086. // change Minutes because that will be accounted for during the
  1087. // insert step, if in fact there are two allocations to add.
  1088. alloc.Start = start
  1089. alloc.End = end
  1090. err := acc.insert(alloc, true)
  1091. if err != nil {
  1092. return nil, err
  1093. }
  1094. }
  1095. for _, alloc := range that.allocations {
  1096. // Change Start and End to match the new window. However, do not
  1097. // change Minutes because that will be accounted for during the
  1098. // insert step, if in fact there are two allocations to add.
  1099. alloc.Start = start
  1100. alloc.End = end
  1101. err := acc.insert(alloc, true)
  1102. if err != nil {
  1103. return nil, err
  1104. }
  1105. }
  1106. return acc, nil
  1107. }
  1108. type AllocationSetRange struct {
  1109. sync.RWMutex
  1110. allocations []*AllocationSet
  1111. }
  1112. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1113. return &AllocationSetRange{
  1114. allocations: allocs,
  1115. }
  1116. }
  1117. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1118. // AllocationSet for the entire range.
  1119. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1120. var allocSet *AllocationSet
  1121. var err error
  1122. asr.RLock()
  1123. defer asr.RUnlock()
  1124. for _, as := range asr.allocations {
  1125. allocSet, err = allocSet.accumulate(as)
  1126. if err != nil {
  1127. return nil, err
  1128. }
  1129. }
  1130. return allocSet, nil
  1131. }
  1132. // TODO niko/etl accumulate into lower-resolution chunks of the given resolution
  1133. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1134. func (asr *AllocationSetRange) AggregateBy(properties Properties, options *AllocationAggregationOptions) error {
  1135. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1136. asr.Lock()
  1137. defer asr.Unlock()
  1138. for _, as := range asr.allocations {
  1139. err := as.AggregateBy(properties, options)
  1140. if err != nil {
  1141. return err
  1142. }
  1143. aggRange.allocations = append(aggRange.allocations, as)
  1144. }
  1145. asr.allocations = aggRange.allocations
  1146. return nil
  1147. }
  1148. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1149. asr.Lock()
  1150. defer asr.Unlock()
  1151. asr.allocations = append(asr.allocations, that)
  1152. }
  1153. // Each invokes the given function for each AllocationSet in the range
  1154. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1155. if asr == nil {
  1156. return
  1157. }
  1158. for i, as := range asr.allocations {
  1159. f(i, as)
  1160. }
  1161. }
  1162. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  1163. if i < 0 || i >= len(asr.allocations) {
  1164. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  1165. }
  1166. asr.RLock()
  1167. defer asr.RUnlock()
  1168. return asr.allocations[i], nil
  1169. }
  1170. func (asr *AllocationSetRange) Length() int {
  1171. if asr == nil || asr.allocations == nil {
  1172. return 0
  1173. }
  1174. asr.RLock()
  1175. defer asr.RUnlock()
  1176. return len(asr.allocations)
  1177. }
  1178. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  1179. asr.RLock()
  1180. asr.RUnlock()
  1181. return json.Marshal(asr.allocations)
  1182. }
  1183. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  1184. if asr == nil || asr.allocations == nil {
  1185. return nil
  1186. }
  1187. asr.RLock()
  1188. defer asr.RUnlock()
  1189. copy := []*AllocationSet{}
  1190. for _, as := range asr.allocations {
  1191. copy = append(copy, as.Clone())
  1192. }
  1193. return copy
  1194. }
  1195. // String represents the given AllocationSetRange as a string
  1196. func (asr *AllocationSetRange) String() string {
  1197. if asr == nil {
  1198. return "<nil>"
  1199. }
  1200. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  1201. }
  1202. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  1203. if asr.Length() == 0 {
  1204. return 0
  1205. }
  1206. as, err := asr.Get(0)
  1207. if err != nil {
  1208. return 0
  1209. }
  1210. return as.UTCOffset()
  1211. }
  1212. // Window returns the full window that the AllocationSetRange spans, from the
  1213. // start of the first AllocationSet to the end of the last one.
  1214. func (asr *AllocationSetRange) Window() Window {
  1215. if asr == nil || asr.Length() == 0 {
  1216. return NewWindow(nil, nil)
  1217. }
  1218. start := asr.allocations[0].Start()
  1219. end := asr.allocations[asr.Length()-1].End()
  1220. return NewWindow(&start, &end)
  1221. }