allocation.go 55 KB

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