allocation.go 58 KB

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