allocation.go 55 KB

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