allocation.go 56 KB

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