allocation.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  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. }
  319. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  320. // the given list of Allocations
  321. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  322. as := &AllocationSet{
  323. allocations: map[string]*Allocation{},
  324. Window: NewWindow(&start, &end),
  325. }
  326. for _, a := range allocs {
  327. as.Insert(a)
  328. }
  329. return as
  330. }
  331. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  332. // filtering results and sharing allocations. FilterFuncs are a list of match
  333. // functions such that, if any function fails, the allocation is ignored.
  334. // ShareFuncs are a list of match functions such that, if any function
  335. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  336. // simple flag for sharing idle resources.
  337. type AllocationAggregationOptions struct {
  338. FilterFuncs []AllocationMatchFunc
  339. SplitIdle bool
  340. MergeUnallocated bool
  341. ShareFuncs []AllocationMatchFunc
  342. ShareIdle string
  343. ShareSplit string
  344. SharedHourlyCosts map[string]float64
  345. }
  346. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  347. // Property. This will only be legal if the AllocationSet is divisible by the
  348. // given Property; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  349. func (as *AllocationSet) AggregateBy(properties Properties, options *AllocationAggregationOptions) error {
  350. // The order of operations for aggregating allocations is as follows:
  351. // 1. move shared and/or idle allocations to separate sets if options
  352. // indicate that they should be shared
  353. // 2. idle coefficients
  354. // 2.a) if idle allocation is to be shared, compute idle coefficients
  355. // (do not compute shared coefficients here, see step 5)
  356. // 2.b) if idle allocation is NOT shared, but filters are present, compute
  357. // idle filtration coefficients for the purpose of only returning the
  358. // portion of idle allocation that would have been shared with the
  359. // unfiltered results set. (See unit tests 5.a,b,c)
  360. // 3. ignore allocation if it fails any of the FilterFuncs
  361. // 4. generate aggregation key and insert allocation into the output set
  362. // 5. if there are shared allocations, compute sharing coefficients on
  363. // the aggregated set, then share allocation accordingly
  364. // 6. if the merge idle option is enabled, merge any remaining idle
  365. // allocations into a single idle allocation
  366. // TODO niko/etl revisit (ShareIdle: ShareEven) case, which is probably wrong
  367. // (and, frankly, ill-defined; i.e. evenly across clusters? within clusters?)
  368. if options == nil {
  369. options = &AllocationAggregationOptions{}
  370. }
  371. if as.IsEmpty() {
  372. return nil
  373. }
  374. // aggSet will collect the aggregated allocations
  375. aggSet := &AllocationSet{
  376. // Profiler: as.Profiler,
  377. Window: as.Window.Clone(),
  378. }
  379. // idleSet will be shared among aggSet after initial aggregation
  380. // is complete
  381. idleSet := &AllocationSet{
  382. // Profiler: as.Profiler,
  383. Window: as.Window.Clone(),
  384. }
  385. // shareSet will be shared among aggSet after initial aggregation
  386. // is complete
  387. shareSet := &AllocationSet{
  388. // Profiler: as.Profiler
  389. Window: as.Window.Clone(),
  390. }
  391. for name, cost := range options.SharedHourlyCosts {
  392. if cost > 0.0 {
  393. hours := as.Resolution().Hours()
  394. // If set ends in the future, adjust hours accordingly
  395. diff := time.Now().Sub(as.End())
  396. if diff < 0.0 {
  397. hours += diff.Hours()
  398. }
  399. totalSharedCost := cost * hours
  400. shareSet.Insert(&Allocation{
  401. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  402. Start: as.Start(),
  403. End: as.End(),
  404. SharedCost: totalSharedCost,
  405. TotalCost: totalSharedCost,
  406. })
  407. }
  408. }
  409. as.Lock()
  410. defer as.Unlock()
  411. // Loop and find all of the idle and shared allocations initially. Add
  412. // them to their respective sets, removing them from the set of
  413. // allocations to aggregate.
  414. for _, alloc := range as.allocations {
  415. cluster, err := alloc.Properties.GetCluster()
  416. if err != nil {
  417. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  418. return err
  419. }
  420. // Idle allocation doesn't get aggregated, so it can be passed through,
  421. // whether or not it is shared. If it is shared, it is put in idleSet
  422. // because shareSet may be split by different rules (even/weighted).
  423. if alloc.IsIdle() {
  424. // Can't recursively call Delete() due to lock acquisition
  425. delete(as.idleKeys, alloc.Name)
  426. delete(as.allocations, alloc.Name)
  427. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  428. idleSet.Insert(alloc)
  429. } else {
  430. aggSet.Insert(alloc)
  431. }
  432. }
  433. // If any of the share funcs succeed, share the allocation. Do this
  434. // prior to filtering so that shared namespaces, etc do not get
  435. // filtered out before we have a chance to share them.
  436. for _, sf := range options.ShareFuncs {
  437. if sf(alloc) {
  438. // Can't recursively call Delete() due to lock acquisition
  439. delete(as.idleKeys, alloc.Name)
  440. delete(as.allocations, alloc.Name)
  441. alloc.Name = fmt.Sprintf("%s/%s", cluster, SharedSuffix)
  442. shareSet.Insert(alloc)
  443. break
  444. }
  445. }
  446. }
  447. if len(as.allocations) == 0 {
  448. log.Warningf("ETL: AggregateBy: no allocations to aggregate")
  449. emptySet := &AllocationSet{
  450. Window: as.Window.Clone(),
  451. }
  452. as.allocations = emptySet.allocations
  453. return nil
  454. }
  455. // In order to correctly apply idle and shared resource coefficients appropriately,
  456. // we need to determine the coefficients for the full set of data. The ensures that
  457. // the ratios are maintained through filtering.
  458. // idleCoefficients are organized by [cluster][allocation][resource]=coeff
  459. var idleCoefficients map[string]map[string]map[string]float64
  460. // shareCoefficients are organized by [allocation][resource]=coeff (no cluster)
  461. var shareCoefficients map[string]float64
  462. var err error
  463. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  464. idleCoefficients, err = computeIdleCoeffs(properties, options, as)
  465. if err != nil {
  466. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  467. return err
  468. }
  469. }
  470. // If we're not sharing idle and we're filtering, we need to track the
  471. // amount of each idle allocation to "delete" in order to maintain parity
  472. // with the idle-allocated results. That is, we want to return only the
  473. // idle cost that would have been shared with the unfiltered portion of
  474. // the results, not the full idle cost.
  475. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  476. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  477. idleFiltrationCoefficients, err = computeIdleCoeffs(properties, options, as)
  478. if err != nil {
  479. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  480. return err
  481. }
  482. }
  483. for _, alloc := range as.allocations {
  484. cluster, err := alloc.Properties.GetCluster()
  485. if err != nil {
  486. log.Warningf("AllocationSet.AggregateBy: missing cluster for allocation: %s", alloc.Name)
  487. return err
  488. }
  489. skip := false
  490. // If any of the filter funcs fail, immediately skip the allocation.
  491. for _, ff := range options.FilterFuncs {
  492. if !ff(alloc) {
  493. skip = true
  494. break
  495. }
  496. }
  497. if skip {
  498. // If we are tracking idle filtration coefficients, delete the
  499. // entry corresponding to the filtered allocation. (Deleting the
  500. // entry will result in that proportional amount being removed
  501. // from the idle allocation at the end of the process.)
  502. if idleFiltrationCoefficients != nil {
  503. if ifcc, ok := idleFiltrationCoefficients[cluster]; ok {
  504. delete(ifcc, alloc.Name)
  505. }
  506. }
  507. continue
  508. }
  509. // Split idle allocations and distribute among aggregated allocations
  510. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then all
  511. // idle allocations will be in the aggSet at this point.
  512. if idleSet.Length() > 0 {
  513. // Distribute idle allocations by coefficient per-cluster, per-allocation
  514. for _, idleAlloc := range idleSet.allocations {
  515. // Only share idle if the cluster matches; i.e. the allocation
  516. // is from the same cluster as the idle costs
  517. idleCluster, err := idleAlloc.Properties.GetCluster()
  518. if err != nil {
  519. return err
  520. }
  521. if idleCluster != cluster {
  522. continue
  523. }
  524. // Make sure idle coefficients exist
  525. if _, ok := idleCoefficients[cluster]; !ok {
  526. log.Errorf("ETL: share (idle) allocation: error getting allocation coefficient [no cluster: '%s' in coefficients] for '%s'", cluster, alloc.Name)
  527. continue
  528. }
  529. if _, ok := idleCoefficients[cluster][alloc.Name]; !ok {
  530. log.Errorf("ETL: share (idle) allocation: error getting allocation coefficienct for '%s'", alloc.Name)
  531. continue
  532. }
  533. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[cluster][alloc.Name]["cpu"]
  534. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[cluster][alloc.Name]["gpu"]
  535. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[cluster][alloc.Name]["ram"]
  536. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[cluster][alloc.Name]["cpu"]
  537. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[cluster][alloc.Name]["gpu"]
  538. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[cluster][alloc.Name]["ram"]
  539. alloc.CPUCost += idleCPUCost
  540. alloc.GPUCost += idleGPUCost
  541. alloc.RAMCost += idleRAMCost
  542. alloc.TotalCost += idleCPUCost + idleGPUCost + idleRAMCost
  543. }
  544. }
  545. key, err := alloc.generateKey(properties)
  546. if err != nil {
  547. return err
  548. }
  549. alloc.Name = key
  550. if options.MergeUnallocated && alloc.IsUnallocated() {
  551. alloc.Name = UnallocatedSuffix
  552. }
  553. aggSet.Insert(alloc)
  554. }
  555. var clusterIdleFiltrationCoeffs map[string]map[string]float64
  556. if idleFiltrationCoefficients != nil {
  557. clusterIdleFiltrationCoeffs = map[string]map[string]float64{}
  558. for cluster, m := range idleFiltrationCoefficients {
  559. if _, ok := clusterIdleFiltrationCoeffs[cluster]; !ok {
  560. clusterIdleFiltrationCoeffs[cluster] = map[string]float64{
  561. "cpu": 0.0,
  562. "gpu": 0.0,
  563. "ram": 0.0,
  564. }
  565. }
  566. for _, n := range m {
  567. for resource, val := range n {
  568. clusterIdleFiltrationCoeffs[cluster][resource] += val
  569. }
  570. }
  571. }
  572. }
  573. // If we have filters, and so have computed coefficients for scaling idle
  574. // allocation costs by cluster, then use those coefficients to scale down
  575. // each idle coefficient in the aggSet.
  576. if len(aggSet.idleKeys) > 0 && clusterIdleFiltrationCoeffs != nil {
  577. for idleKey := range aggSet.idleKeys {
  578. idleAlloc := aggSet.Get(idleKey)
  579. cluster, err := idleAlloc.Properties.GetCluster()
  580. if err != nil {
  581. log.Warningf("AggregateBy: idle allocation without cluster: %s", idleAlloc)
  582. }
  583. if resourceCoeffs, ok := clusterIdleFiltrationCoeffs[cluster]; ok {
  584. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  585. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  586. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  587. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  588. idleAlloc.TotalCost = idleAlloc.CPUCost + idleAlloc.RAMCost
  589. }
  590. }
  591. }
  592. // Split shared allocations and distribute among aggregated allocations
  593. if shareSet.Length() > 0 {
  594. shareCoefficients, err = computeShareCoeffs(properties, options, aggSet)
  595. if err != nil {
  596. log.Warningf("AllocationSet.AggregateBy: compute shared coeff: missing cluster ID: %s", err)
  597. return err
  598. }
  599. for _, alloc := range aggSet.allocations {
  600. if alloc.IsIdle() {
  601. // Skip idle allocations (they do not receive shared allocation)
  602. continue
  603. }
  604. // Distribute shared allocations by coefficient per-allocation
  605. // NOTE: share coefficients do not partition by cluster, like
  606. // idle coefficients do.
  607. for _, sharedAlloc := range shareSet.allocations {
  608. if _, ok := shareCoefficients[alloc.Name]; !ok {
  609. log.Errorf("ETL: share allocation: error getting allocation coefficienct for '%s'", alloc.Name)
  610. continue
  611. }
  612. alloc.SharedCost += sharedAlloc.TotalCost * shareCoefficients[alloc.Name]
  613. alloc.TotalCost += sharedAlloc.TotalCost * shareCoefficients[alloc.Name]
  614. }
  615. }
  616. }
  617. // Combine all idle allocations into a single "__idle__" allocation
  618. if !options.SplitIdle {
  619. for _, idleAlloc := range aggSet.IdleAllocations() {
  620. aggSet.Delete(idleAlloc.Name)
  621. idleAlloc.Name = IdleSuffix
  622. aggSet.Insert(idleAlloc)
  623. }
  624. }
  625. as.allocations = aggSet.allocations
  626. return nil
  627. }
  628. // TODO niko/etl deprecate the use of a map of resources here, we only use totals
  629. func computeShareCoeffs(properties Properties, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  630. // Compute coeffs by totalling per-allocation, then dividing by the total.
  631. coeffs := map[string]float64{}
  632. // Compute totals for all allocations
  633. total := 0.0
  634. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  635. // counts each aggregation proportionally to its respective costs
  636. shareType := options.ShareSplit
  637. // Record allocation values first, then normalize by totals to get percentages
  638. for name, alloc := range as.allocations {
  639. if alloc.IsIdle() {
  640. // Skip idle allocations in coefficient calculation
  641. continue
  642. }
  643. if shareType == ShareEven {
  644. // Not additive - set to 1.0 for even distribution
  645. coeffs[name] = 1.0
  646. // Total is always additive
  647. total += 1.0
  648. } else {
  649. // Both are additive for weighted distribution
  650. coeffs[name] += alloc.TotalCost
  651. total += alloc.TotalCost
  652. }
  653. }
  654. // Normalize coefficients by totals
  655. for a := range coeffs {
  656. if coeffs[a] > 0 && total > 0 {
  657. coeffs[a] /= total
  658. } else {
  659. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  660. coeffs[a] = 0.0
  661. }
  662. }
  663. return coeffs, nil
  664. }
  665. func computeIdleCoeffs(properties Properties, options *AllocationAggregationOptions, as *AllocationSet) (map[string]map[string]map[string]float64, error) {
  666. types := []string{"cpu", "gpu", "ram"}
  667. // Compute idle coefficients, then save them in AllocationAggregationOptions
  668. coeffs := map[string]map[string]map[string]float64{}
  669. // Compute totals per resource for CPU, GPU, RAM, and PV
  670. totals := map[string]map[string]float64{}
  671. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  672. // counts each allocation proportionally to its respective costs
  673. shareType := options.ShareIdle
  674. // Record allocation values first, then normalize by totals to get percentages
  675. for _, alloc := range as.allocations {
  676. if alloc.IsIdle() {
  677. // Skip idle allocations in coefficient calculation
  678. continue
  679. }
  680. // If any of the share funcs succeed, share the allocation. Do this
  681. // prior to filtering so that shared namespaces, etc do not get
  682. // filtered out before we have a chance to share them.
  683. skip := false
  684. for _, sf := range options.ShareFuncs {
  685. if sf(alloc) {
  686. skip = true
  687. break
  688. }
  689. }
  690. if skip {
  691. continue
  692. }
  693. // We need to key the allocations by cluster id
  694. clusterID, err := alloc.Properties.GetCluster()
  695. if err != nil {
  696. return nil, err
  697. }
  698. // get the name key for the allocation
  699. name := alloc.Name
  700. // Create cluster based tables if they don't exist
  701. if _, ok := coeffs[clusterID]; !ok {
  702. coeffs[clusterID] = map[string]map[string]float64{}
  703. }
  704. if _, ok := totals[clusterID]; !ok {
  705. totals[clusterID] = map[string]float64{}
  706. }
  707. if _, ok := coeffs[clusterID][name]; !ok {
  708. coeffs[clusterID][name] = map[string]float64{}
  709. }
  710. if shareType == ShareEven {
  711. for _, r := range types {
  712. // Not additive - hard set to 1.0
  713. coeffs[clusterID][name][r] = 1.0
  714. // totals are additive
  715. totals[clusterID][r] += 1.0
  716. }
  717. } else {
  718. coeffs[clusterID][name]["cpu"] += alloc.CPUCost
  719. coeffs[clusterID][name]["gpu"] += alloc.GPUCost
  720. coeffs[clusterID][name]["ram"] += alloc.RAMCost
  721. totals[clusterID]["cpu"] += alloc.CPUCost
  722. totals[clusterID]["gpu"] += alloc.GPUCost
  723. totals[clusterID]["ram"] += alloc.RAMCost
  724. }
  725. }
  726. // Normalize coefficients by totals
  727. for c := range coeffs {
  728. for a := range coeffs[c] {
  729. for _, r := range types {
  730. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  731. coeffs[c][a][r] /= totals[c][r]
  732. }
  733. }
  734. }
  735. }
  736. return coeffs, nil
  737. }
  738. func (alloc *Allocation) generateKey(properties Properties) (string, error) {
  739. // Names will ultimately be joined into a single name, which uniquely
  740. // identifies allocations.
  741. names := []string{}
  742. if properties.HasCluster() {
  743. cluster, err := alloc.Properties.GetCluster()
  744. if err != nil {
  745. return "", err
  746. }
  747. names = append(names, cluster)
  748. }
  749. if properties.HasNode() {
  750. node, err := alloc.Properties.GetNode()
  751. if err != nil {
  752. return "", err
  753. }
  754. names = append(names, node)
  755. }
  756. if properties.HasNamespace() {
  757. namespace, err := alloc.Properties.GetNamespace()
  758. if err != nil {
  759. return "", err
  760. }
  761. names = append(names, namespace)
  762. }
  763. if properties.HasControllerKind() {
  764. controllerKind, err := alloc.Properties.GetControllerKind()
  765. if err != nil {
  766. // Indicate that allocation has no controller
  767. controllerKind = UnallocatedSuffix
  768. }
  769. if prop, _ := properties.GetControllerKind(); prop != "" && prop != controllerKind {
  770. // The allocation does not have the specified controller kind
  771. controllerKind = UnallocatedSuffix
  772. }
  773. names = append(names, controllerKind)
  774. }
  775. if properties.HasController() {
  776. if !properties.HasControllerKind() {
  777. controllerKind, err := alloc.Properties.GetControllerKind()
  778. if err == nil {
  779. names = append(names, controllerKind)
  780. }
  781. }
  782. controller, err := alloc.Properties.GetController()
  783. if err != nil {
  784. // Indicate that allocation has no controller
  785. controller = UnallocatedSuffix
  786. }
  787. names = append(names, controller)
  788. }
  789. if properties.HasPod() {
  790. pod, err := alloc.Properties.GetPod()
  791. if err != nil {
  792. return "", err
  793. }
  794. names = append(names, pod)
  795. }
  796. if properties.HasContainer() {
  797. container, err := alloc.Properties.GetContainer()
  798. if err != nil {
  799. return "", err
  800. }
  801. names = append(names, container)
  802. }
  803. if properties.HasService() {
  804. services, err := alloc.Properties.GetServices()
  805. if err != nil {
  806. // Indicate that allocation has no services
  807. names = append(names, UnallocatedSuffix)
  808. } else {
  809. // TODO niko/etl support multi-service aggregation
  810. if len(services) > 0 {
  811. for _, service := range services {
  812. names = append(names, service)
  813. break
  814. }
  815. } else {
  816. // Indicate that allocation has no services
  817. names = append(names, UnallocatedSuffix)
  818. }
  819. }
  820. }
  821. if properties.HasLabel() {
  822. labels, err := alloc.Properties.GetLabels() // labels that the individual allocation possesses
  823. if err != nil {
  824. // Indicate that allocation has no labels
  825. names = append(names, UnallocatedSuffix)
  826. } else {
  827. labelNames := []string{}
  828. aggLabels, err := properties.GetLabels() // potential labels to aggregate on supplied by the API caller
  829. if err != nil {
  830. // We've already checked HasLabel, so this should never occur
  831. return "", err
  832. }
  833. // calvin - support multi-label aggregation
  834. for labelName := range aggLabels {
  835. if val, ok := labels[labelName]; ok {
  836. labelNames = append(labelNames, fmt.Sprintf("%s=%s", labelName, val))
  837. } else if indexOf(UnallocatedSuffix, labelNames) == -1 { // if UnallocatedSuffix not already in names
  838. labelNames = append(labelNames, UnallocatedSuffix)
  839. }
  840. }
  841. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  842. if len(labelNames) > 1 {
  843. sort.Strings(labelNames)
  844. }
  845. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, labelNames)
  846. // suffix should be at index 0 if it exists b/c of underscores
  847. if unallocatedSuffixIndex != -1 {
  848. labelNames = append(labelNames[:unallocatedSuffixIndex], labelNames[unallocatedSuffixIndex+1:]...)
  849. labelNames = append(labelNames, UnallocatedSuffix) // append to end
  850. }
  851. names = append(names, labelNames...)
  852. }
  853. }
  854. return strings.Join(names, "/"), nil
  855. }
  856. // Helper function to check for slice membership. Not sure if repeated elsewhere in our codebase.
  857. func indexOf(v string, arr []string) int {
  858. for i, s := range arr {
  859. // This is caseless equivalence
  860. if strings.EqualFold(v, s) {
  861. return i
  862. }
  863. }
  864. return -1
  865. }
  866. // Clone returns a new AllocationSet with a deep copy of the given
  867. // AllocationSet's allocations.
  868. func (as *AllocationSet) Clone() *AllocationSet {
  869. if as == nil {
  870. return nil
  871. }
  872. as.RLock()
  873. defer as.RUnlock()
  874. allocs := map[string]*Allocation{}
  875. for k, v := range as.allocations {
  876. allocs[k] = v.Clone()
  877. }
  878. return &AllocationSet{
  879. allocations: allocs,
  880. Window: as.Window.Clone(),
  881. }
  882. }
  883. // Delete removes the allocation with the given name from the set
  884. func (as *AllocationSet) Delete(name string) {
  885. if as == nil {
  886. return
  887. }
  888. as.Lock()
  889. defer as.Unlock()
  890. delete(as.idleKeys, name)
  891. delete(as.allocations, name)
  892. }
  893. // Each invokes the given function for each Allocation in the set
  894. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  895. if as == nil {
  896. return
  897. }
  898. for k, a := range as.allocations {
  899. f(k, a)
  900. }
  901. }
  902. // End returns the End time of the AllocationSet window
  903. func (as *AllocationSet) End() time.Time {
  904. if as == nil {
  905. log.Warningf("Allocation ETL: calling End on nil AllocationSet")
  906. return time.Unix(0, 0)
  907. }
  908. if as.Window.End() == nil {
  909. log.Warningf("Allocation ETL: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  910. return time.Unix(0, 0)
  911. }
  912. return *as.Window.End()
  913. }
  914. // Get returns the Allocation at the given key in the AllocationSet
  915. func (as *AllocationSet) Get(key string) *Allocation {
  916. as.RLock()
  917. defer as.RUnlock()
  918. if alloc, ok := as.allocations[key]; ok {
  919. return alloc
  920. }
  921. return nil
  922. }
  923. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  924. // Returns clones of the actual Allocations, so mutability is not a problem.
  925. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  926. idles := map[string]*Allocation{}
  927. if as.IsEmpty() {
  928. return idles
  929. }
  930. as.RLock()
  931. defer as.RUnlock()
  932. for key := range as.idleKeys {
  933. if alloc, ok := as.allocations[key]; ok {
  934. idles[key] = alloc.Clone()
  935. }
  936. }
  937. return idles
  938. }
  939. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  940. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  941. // there is no existing entry, one is created. Nil error response indicates success.
  942. func (as *AllocationSet) Insert(that *Allocation) error {
  943. return as.insert(that, false)
  944. }
  945. func (as *AllocationSet) insert(that *Allocation, accumulate bool) error {
  946. if as.IsEmpty() {
  947. as.Lock()
  948. as.allocations = map[string]*Allocation{}
  949. as.idleKeys = map[string]bool{}
  950. as.Unlock()
  951. }
  952. as.Lock()
  953. defer as.Unlock()
  954. // Add the given Allocation to the existing entry, if there is one;
  955. // otherwise just set directly into allocations
  956. if _, ok := as.allocations[that.Name]; !ok {
  957. as.allocations[that.Name] = that
  958. } else {
  959. as.allocations[that.Name].add(that, false, accumulate)
  960. }
  961. // If the given Allocation is an idle one, record that
  962. if that.IsIdle() {
  963. as.idleKeys[that.Name] = true
  964. }
  965. return nil
  966. }
  967. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  968. // zero allocations.
  969. func (as *AllocationSet) IsEmpty() bool {
  970. if as == nil || len(as.allocations) == 0 {
  971. return true
  972. }
  973. as.RLock()
  974. defer as.RUnlock()
  975. return as.allocations == nil || len(as.allocations) == 0
  976. }
  977. // Length returns the number of Allocations in the set
  978. func (as *AllocationSet) Length() int {
  979. if as == nil {
  980. return 0
  981. }
  982. as.RLock()
  983. defer as.RUnlock()
  984. return len(as.allocations)
  985. }
  986. // Map clones and returns a map of the AllocationSet's Allocations
  987. func (as *AllocationSet) Map() map[string]*Allocation {
  988. if as.IsEmpty() {
  989. return map[string]*Allocation{}
  990. }
  991. return as.Clone().allocations
  992. }
  993. // MarshalJSON JSON-encodes the AllocationSet
  994. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  995. as.RLock()
  996. defer as.RUnlock()
  997. return json.Marshal(as.allocations)
  998. }
  999. // Resolution returns the AllocationSet's window duration
  1000. func (as *AllocationSet) Resolution() time.Duration {
  1001. return as.Window.Duration()
  1002. }
  1003. func (as *AllocationSet) Set(alloc *Allocation) error {
  1004. if as.IsEmpty() {
  1005. as.Lock()
  1006. as.allocations = map[string]*Allocation{}
  1007. as.idleKeys = map[string]bool{}
  1008. as.Unlock()
  1009. }
  1010. as.Lock()
  1011. defer as.Unlock()
  1012. as.allocations[alloc.Name] = alloc
  1013. // If the given Allocation is an idle one, record that
  1014. if alloc.IsIdle() {
  1015. as.idleKeys[alloc.Name] = true
  1016. }
  1017. return nil
  1018. }
  1019. // Start returns the Start time of the AllocationSet window
  1020. func (as *AllocationSet) Start() time.Time {
  1021. if as == nil {
  1022. log.Warningf("Allocation ETL: calling Start on nil AllocationSet")
  1023. return time.Unix(0, 0)
  1024. }
  1025. if as.Window.Start() == nil {
  1026. log.Warningf("Allocation ETL: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1027. return time.Unix(0, 0)
  1028. }
  1029. return *as.Window.Start()
  1030. }
  1031. // String represents the given Allocation as a string
  1032. func (as *AllocationSet) String() string {
  1033. if as == nil {
  1034. return "<nil>"
  1035. }
  1036. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1037. as.Length(), as.Window, as.TotalCost())
  1038. }
  1039. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1040. func (as *AllocationSet) TotalCost() float64 {
  1041. if as.IsEmpty() {
  1042. return 0.0
  1043. }
  1044. as.RLock()
  1045. defer as.RUnlock()
  1046. tc := 0.0
  1047. for _, a := range as.allocations {
  1048. tc += a.TotalCost
  1049. }
  1050. return tc
  1051. }
  1052. func (as *AllocationSet) UTCOffset() time.Duration {
  1053. _, zone := as.Start().Zone()
  1054. return time.Duration(zone) * time.Second
  1055. }
  1056. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1057. if as.IsEmpty() {
  1058. return that, nil
  1059. }
  1060. if that.IsEmpty() {
  1061. return as, nil
  1062. }
  1063. if that.Start().Before(as.End()) {
  1064. timefmt := "2006-01-02T15:04:05"
  1065. 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))
  1066. return nil, fmt.Errorf("error accumulating AllocationSets: overlapping windows: %s", err)
  1067. }
  1068. // Set start, end to min(start), max(end)
  1069. start := as.Start()
  1070. end := as.End()
  1071. if that.Start().Before(start) {
  1072. start = that.Start()
  1073. }
  1074. if that.End().After(end) {
  1075. end = that.End()
  1076. }
  1077. acc := NewAllocationSet(start, end)
  1078. as.RLock()
  1079. defer as.RUnlock()
  1080. that.RLock()
  1081. defer that.RUnlock()
  1082. for _, alloc := range as.allocations {
  1083. // Change Start and End to match the new window. However, do not
  1084. // change Minutes because that will be accounted for during the
  1085. // insert step, if in fact there are two allocations to add.
  1086. alloc.Start = start
  1087. alloc.End = end
  1088. err := acc.insert(alloc, true)
  1089. if err != nil {
  1090. return nil, err
  1091. }
  1092. }
  1093. for _, alloc := range that.allocations {
  1094. // Change Start and End to match the new window. However, do not
  1095. // change Minutes because that will be accounted for during the
  1096. // insert step, if in fact there are two allocations to add.
  1097. alloc.Start = start
  1098. alloc.End = end
  1099. err := acc.insert(alloc, true)
  1100. if err != nil {
  1101. return nil, err
  1102. }
  1103. }
  1104. return acc, nil
  1105. }
  1106. type AllocationSetRange struct {
  1107. sync.RWMutex
  1108. allocations []*AllocationSet
  1109. }
  1110. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1111. return &AllocationSetRange{
  1112. allocations: allocs,
  1113. }
  1114. }
  1115. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1116. // AllocationSet for the entire range.
  1117. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1118. var allocSet *AllocationSet
  1119. var err error
  1120. asr.RLock()
  1121. defer asr.RUnlock()
  1122. for _, as := range asr.allocations {
  1123. allocSet, err = allocSet.accumulate(as)
  1124. if err != nil {
  1125. return nil, err
  1126. }
  1127. }
  1128. return allocSet, nil
  1129. }
  1130. // TODO niko/etl accumulate into lower-resolution chunks of the given resolution
  1131. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1132. func (asr *AllocationSetRange) AggregateBy(properties Properties, options *AllocationAggregationOptions) error {
  1133. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1134. asr.Lock()
  1135. defer asr.Unlock()
  1136. for _, as := range asr.allocations {
  1137. err := as.AggregateBy(properties, options)
  1138. if err != nil {
  1139. return err
  1140. }
  1141. aggRange.allocations = append(aggRange.allocations, as)
  1142. }
  1143. asr.allocations = aggRange.allocations
  1144. return nil
  1145. }
  1146. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1147. asr.Lock()
  1148. defer asr.Unlock()
  1149. asr.allocations = append(asr.allocations, that)
  1150. }
  1151. // Each invokes the given function for each AllocationSet in the range
  1152. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1153. if asr == nil {
  1154. return
  1155. }
  1156. for i, as := range asr.allocations {
  1157. f(i, as)
  1158. }
  1159. }
  1160. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  1161. if i < 0 || i >= len(asr.allocations) {
  1162. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  1163. }
  1164. asr.RLock()
  1165. defer asr.RUnlock()
  1166. return asr.allocations[i], nil
  1167. }
  1168. func (asr *AllocationSetRange) Length() int {
  1169. if asr == nil || asr.allocations == nil {
  1170. return 0
  1171. }
  1172. asr.RLock()
  1173. defer asr.RUnlock()
  1174. return len(asr.allocations)
  1175. }
  1176. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  1177. asr.RLock()
  1178. asr.RUnlock()
  1179. return json.Marshal(asr.allocations)
  1180. }
  1181. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  1182. if asr == nil || asr.allocations == nil {
  1183. return nil
  1184. }
  1185. asr.RLock()
  1186. defer asr.RUnlock()
  1187. copy := []*AllocationSet{}
  1188. for _, as := range asr.allocations {
  1189. copy = append(copy, as.Clone())
  1190. }
  1191. return copy
  1192. }
  1193. // String represents the given AllocationSetRange as a string
  1194. func (asr *AllocationSetRange) String() string {
  1195. if asr == nil {
  1196. return "<nil>"
  1197. }
  1198. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  1199. }
  1200. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  1201. if asr.Length() == 0 {
  1202. return 0
  1203. }
  1204. as, err := asr.Get(0)
  1205. if err != nil {
  1206. return 0
  1207. }
  1208. return as.UTCOffset()
  1209. }
  1210. // Window returns the full window that the AllocationSetRange spans, from the
  1211. // start of the first AllocationSet to the end of the last one.
  1212. func (asr *AllocationSetRange) Window() Window {
  1213. if asr == nil || asr.Length() == 0 {
  1214. return NewWindow(nil, nil)
  1215. }
  1216. start := asr.allocations[0].Start()
  1217. end := asr.allocations[asr.Length()-1].End()
  1218. return NewWindow(&start, &end)
  1219. }