2
0

allocation.go 55 KB

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