allocation.go 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331
  1. package kubecost
  2. import (
  3. "bytes"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/kubecost/cost-model/pkg/log"
  10. "github.com/kubecost/cost-model/pkg/util"
  11. "github.com/kubecost/cost-model/pkg/util/json"
  12. )
  13. // TODO Clean-up use of IsEmpty; nil checks should be separated for safety.
  14. // TODO Consider making Allocation an interface, which is fulfilled by structs
  15. // like KubernetesAllocation, IdleAllocation, and ExternalAllocation.
  16. // ExternalSuffix indicates an external allocation
  17. const ExternalSuffix = "__external__"
  18. // IdleSuffix indicates an idle allocation property
  19. const IdleSuffix = "__idle__"
  20. // SharedSuffix indicates an shared allocation property
  21. const SharedSuffix = "__shared__"
  22. // UnallocatedSuffix indicates an unallocated allocation property
  23. const UnallocatedSuffix = "__unallocated__"
  24. // UnmountedSuffix indicated allocation to an unmounted PV
  25. const UnmountedSuffix = "__unmounted__"
  26. // ShareWeighted indicates that a shared resource should be shared as a
  27. // proportion of the cost of the remaining allocations.
  28. const ShareWeighted = "__weighted__"
  29. // ShareEven indicates that a shared resource should be shared evenly across
  30. // all remaining allocations.
  31. const ShareEven = "__even__"
  32. // ShareNone indicates that a shareable resource should not be shared
  33. const ShareNone = "__none__"
  34. // Allocation is a unit of resource allocation and cost for a given window
  35. // of time and for a given kubernetes construct with its associated set of
  36. // properties.
  37. // TODO:CLEANUP consider dropping name in favor of just Allocation and an
  38. // Assets-style key() function for AllocationSet.
  39. type Allocation struct {
  40. Name string `json:"name"`
  41. Properties *AllocationProperties `json:"properties,omitempty"`
  42. Window Window `json:"window"`
  43. Start time.Time `json:"start"`
  44. End time.Time `json:"end"`
  45. CPUCoreHours float64 `json:"cpuCoreHours"`
  46. CPUCoreRequestAverage float64 `json:"cpuCoreRequestAverage"`
  47. CPUCoreUsageAverage float64 `json:"cpuCoreUsageAverage"`
  48. CPUCost float64 `json:"cpuCost"`
  49. CPUCostAdjustment float64 `json:"cpuCostAdjustment"`
  50. GPUHours float64 `json:"gpuHours"`
  51. GPUCost float64 `json:"gpuCost"`
  52. GPUCostAdjustment float64 `json:"gpuCostAdjustment"`
  53. NetworkCost float64 `json:"networkCost"`
  54. NetworkCostAdjustment float64 `json:"networkCostAdjustment"`
  55. LoadBalancerCost float64 `json:"loadBalancerCost"`
  56. LoadBalancerCostAdjustment float64 `json:"loadBalancerCostAdjustment"`
  57. PVs PVAllocations `json:"-"`
  58. PVCostAdjustment float64 `json:"pvCostAdjustment"`
  59. RAMByteHours float64 `json:"ramByteHours"`
  60. RAMBytesRequestAverage float64 `json:"ramByteRequestAverage"`
  61. RAMBytesUsageAverage float64 `json:"ramByteUsageAverage"`
  62. RAMCost float64 `json:"ramCost"`
  63. RAMCostAdjustment float64 `json:"ramCostAdjustment"`
  64. SharedCost float64 `json:"sharedCost"`
  65. ExternalCost float64 `json:"externalCost"`
  66. // RawAllocationOnly is a pointer so if it is not present it will be
  67. // marshalled as null rather than as an object with Go default values.
  68. RawAllocationOnly *RawAllocationOnlyData `json:"rawAllocationOnly"`
  69. }
  70. // RawAllocationOnlyData is information that only belong in "raw" Allocations,
  71. // those which have not undergone aggregation, accumulation, or any other form
  72. // of combination to produce a new Allocation from other Allocations.
  73. //
  74. // Max usage data belongs here because computing the overall maximum from two
  75. // or more Allocations is a non-trivial operation that cannot be defined without
  76. // maintaining a large amount of state. Consider the following example:
  77. // _______________________________________________
  78. //
  79. // A1 Using 3 CPU ---- ----- ------
  80. // A2 Using 2 CPU ---- ----- ----
  81. // A3 Using 1 CPU --- --
  82. // _______________________________________________
  83. // Time ---->
  84. //
  85. // The logical maximum CPU usage is 5, but this cannot be calculated iteratively,
  86. // which is how we calculate aggregations and accumulations of Allocations currently.
  87. // This becomes a problem I could call "maximum sum of overlapping intervals" and is
  88. // essentially a variant of an interval scheduling algorithm.
  89. //
  90. // If we had types to differentiate between regular Allocations and AggregatedAllocations
  91. // then this type would be unnecessary and its fields would go into the regular Allocation
  92. // and not in the AggregatedAllocation.
  93. type RawAllocationOnlyData struct {
  94. CPUCoreUsageMax float64 `json:"cpuCoreUsageMax"`
  95. RAMBytesUsageMax float64 `json:"ramByteUsageMax"`
  96. }
  97. // PVAllocations is a map of Disk Asset Identifiers to the
  98. // usage of them by an Allocation as recorded in a PVAllocation
  99. type PVAllocations map[PVKey]*PVAllocation
  100. // Clone creates a deep copy of a PVAllocations
  101. func (pv *PVAllocations) Clone() PVAllocations {
  102. if pv == nil || *pv == nil {
  103. return nil
  104. }
  105. apv := *pv
  106. clonePV := PVAllocations{}
  107. for k, v := range apv {
  108. clonePV[k] = &PVAllocation{
  109. ByteHours: v.ByteHours,
  110. Cost: v.Cost,
  111. }
  112. }
  113. return clonePV
  114. }
  115. // Add adds contents of that to the calling PVAllocations
  116. func (pv *PVAllocations) Add(that PVAllocations) PVAllocations {
  117. apv := pv.Clone()
  118. if that != nil {
  119. if apv == nil {
  120. apv = PVAllocations{}
  121. }
  122. for pvKey, thatPVAlloc := range that {
  123. apvAlloc, ok := apv[pvKey]
  124. if !ok {
  125. apvAlloc = &PVAllocation{}
  126. }
  127. apvAlloc.Cost += thatPVAlloc.Cost
  128. apvAlloc.ByteHours += thatPVAlloc.ByteHours
  129. apv[pvKey] = apvAlloc
  130. }
  131. }
  132. return apv
  133. }
  134. // PVKey for identifying Disk type assets
  135. type PVKey struct {
  136. Cluster string `json:"cluster"`
  137. Name string `json:"name"`
  138. }
  139. // PVAllocation contains the byte hour usage
  140. // and cost of an Allocation for a single PV
  141. type PVAllocation struct {
  142. ByteHours float64 `json:"byteHours"`
  143. Cost float64 `json:"cost"`
  144. }
  145. // AllocationMatchFunc is a function that can be used to match Allocations by
  146. // returning true for any given Allocation if a condition is met.
  147. type AllocationMatchFunc func(*Allocation) bool
  148. // Add returns the result of summing the two given Allocations, which sums the
  149. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  150. // the two original Allocations are mutated in the process.
  151. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  152. if a == nil {
  153. return that.Clone(), nil
  154. }
  155. if that == nil {
  156. return a.Clone(), nil
  157. }
  158. // Note: no need to clone "that", as add only mutates the receiver
  159. agg := a.Clone()
  160. agg.add(that)
  161. return agg, nil
  162. }
  163. // Clone returns a deep copy of the given Allocation
  164. func (a *Allocation) Clone() *Allocation {
  165. if a == nil {
  166. return nil
  167. }
  168. return &Allocation{
  169. Name: a.Name,
  170. Properties: a.Properties.Clone(),
  171. Window: a.Window.Clone(),
  172. Start: a.Start,
  173. End: a.End,
  174. CPUCoreHours: a.CPUCoreHours,
  175. CPUCoreRequestAverage: a.CPUCoreRequestAverage,
  176. CPUCoreUsageAverage: a.CPUCoreUsageAverage,
  177. CPUCost: a.CPUCost,
  178. CPUCostAdjustment: a.CPUCostAdjustment,
  179. GPUHours: a.GPUHours,
  180. GPUCost: a.GPUCost,
  181. GPUCostAdjustment: a.GPUCostAdjustment,
  182. NetworkCost: a.NetworkCost,
  183. NetworkCostAdjustment: a.NetworkCostAdjustment,
  184. LoadBalancerCost: a.LoadBalancerCost,
  185. LoadBalancerCostAdjustment: a.LoadBalancerCostAdjustment,
  186. PVs: a.PVs.Clone(),
  187. PVCostAdjustment: a.PVCostAdjustment,
  188. RAMByteHours: a.RAMByteHours,
  189. RAMBytesRequestAverage: a.RAMBytesRequestAverage,
  190. RAMBytesUsageAverage: a.RAMBytesUsageAverage,
  191. RAMCost: a.RAMCost,
  192. RAMCostAdjustment: a.RAMCostAdjustment,
  193. SharedCost: a.SharedCost,
  194. ExternalCost: a.ExternalCost,
  195. RawAllocationOnly: a.RawAllocationOnly.Clone(),
  196. }
  197. }
  198. // Clone returns a deep copy of the given RawAllocationOnlyData
  199. func (r *RawAllocationOnlyData) Clone() *RawAllocationOnlyData {
  200. if r == nil {
  201. return nil
  202. }
  203. return &RawAllocationOnlyData{
  204. CPUCoreUsageMax: r.CPUCoreUsageMax,
  205. RAMBytesUsageMax: r.RAMBytesUsageMax,
  206. }
  207. }
  208. // Equal returns true if the values held in the given Allocation precisely
  209. // match those of the receiving Allocation. nil does not match nil. Floating
  210. // point values need to match according to util.IsApproximately, which accounts
  211. // for small, reasonable floating point error margins.
  212. func (a *Allocation) Equal(that *Allocation) bool {
  213. if a == nil || that == nil {
  214. return false
  215. }
  216. if a.Name != that.Name {
  217. return false
  218. }
  219. if !a.Properties.Equal(that.Properties) {
  220. return false
  221. }
  222. if !a.Window.Equal(that.Window) {
  223. return false
  224. }
  225. if !a.Start.Equal(that.Start) {
  226. return false
  227. }
  228. if !a.End.Equal(that.End) {
  229. return false
  230. }
  231. if !util.IsApproximately(a.CPUCoreHours, that.CPUCoreHours) {
  232. return false
  233. }
  234. if !util.IsApproximately(a.CPUCost, that.CPUCost) {
  235. return false
  236. }
  237. if !util.IsApproximately(a.CPUCostAdjustment, that.CPUCostAdjustment) {
  238. return false
  239. }
  240. if !util.IsApproximately(a.GPUHours, that.GPUHours) {
  241. return false
  242. }
  243. if !util.IsApproximately(a.GPUCost, that.GPUCost) {
  244. return false
  245. }
  246. if !util.IsApproximately(a.GPUCostAdjustment, that.GPUCostAdjustment) {
  247. return false
  248. }
  249. if !util.IsApproximately(a.NetworkCost, that.NetworkCost) {
  250. return false
  251. }
  252. if !util.IsApproximately(a.NetworkCostAdjustment, that.NetworkCostAdjustment) {
  253. return false
  254. }
  255. if !util.IsApproximately(a.LoadBalancerCost, that.LoadBalancerCost) {
  256. return false
  257. }
  258. if !util.IsApproximately(a.LoadBalancerCostAdjustment, that.LoadBalancerCostAdjustment) {
  259. return false
  260. }
  261. if !util.IsApproximately(a.PVCostAdjustment, that.PVCostAdjustment) {
  262. return false
  263. }
  264. if !util.IsApproximately(a.RAMByteHours, that.RAMByteHours) {
  265. return false
  266. }
  267. if !util.IsApproximately(a.RAMCost, that.RAMCost) {
  268. return false
  269. }
  270. if !util.IsApproximately(a.RAMCostAdjustment, that.RAMCostAdjustment) {
  271. return false
  272. }
  273. if !util.IsApproximately(a.SharedCost, that.SharedCost) {
  274. return false
  275. }
  276. if !util.IsApproximately(a.ExternalCost, that.ExternalCost) {
  277. return false
  278. }
  279. if a.RawAllocationOnly == nil && that.RawAllocationOnly != nil {
  280. return false
  281. }
  282. if a.RawAllocationOnly != nil && that.RawAllocationOnly == nil {
  283. return false
  284. }
  285. if a.RawAllocationOnly != nil && that.RawAllocationOnly != nil {
  286. if !util.IsApproximately(a.RawAllocationOnly.CPUCoreUsageMax, that.RawAllocationOnly.CPUCoreUsageMax) {
  287. return false
  288. }
  289. if !util.IsApproximately(a.RawAllocationOnly.RAMBytesUsageMax, that.RawAllocationOnly.RAMBytesUsageMax) {
  290. return false
  291. }
  292. }
  293. aPVs := a.PVs
  294. thatPVs := that.PVs
  295. if len(aPVs) == len(thatPVs) {
  296. for k, pv := range aPVs {
  297. tv, ok := thatPVs[k]
  298. if !ok || *tv != *pv {
  299. return false
  300. }
  301. }
  302. } else {
  303. return false
  304. }
  305. return true
  306. }
  307. // TotalCost is the total cost of the Allocation including adjustments
  308. func (a *Allocation) TotalCost() float64 {
  309. return a.CPUTotalCost() + a.GPUTotalCost() + a.RAMTotalCost() + a.PVTotalCost() + a.NetworkTotalCost() + a.LBTotalCost() + a.SharedTotalCost() + a.ExternalCost
  310. }
  311. // CPUTotalCost calculates total CPU cost of Allocation including adjustment
  312. func (a *Allocation) CPUTotalCost() float64 {
  313. return a.CPUCost + a.CPUCostAdjustment
  314. }
  315. // GPUTotalCost calculates total GPU cost of Allocation including adjustment
  316. func (a *Allocation) GPUTotalCost() float64 {
  317. return a.GPUCost + a.GPUCostAdjustment
  318. }
  319. // RAMTotalCost calculates total RAM cost of Allocation including adjustment
  320. func (a *Allocation) RAMTotalCost() float64 {
  321. return a.RAMCost + a.RAMCostAdjustment
  322. }
  323. // PVTotalCost calculates total PV cost of Allocation including adjustment
  324. func (a *Allocation) PVTotalCost() float64 {
  325. return a.PVCost() + a.PVCostAdjustment
  326. }
  327. // NetworkTotalCost calculates total Network cost of Allocation including adjustment
  328. func (a *Allocation) NetworkTotalCost() float64 {
  329. return a.NetworkCost + a.NetworkCostAdjustment
  330. }
  331. // LBTotalCost calculates total LB cost of Allocation including adjustment
  332. func (a *Allocation) LBTotalCost() float64 {
  333. return a.LoadBalancerCost + a.LoadBalancerCostAdjustment
  334. }
  335. // SharedTotalCost calculates total shared cost of Allocation including adjustment
  336. func (a *Allocation) SharedTotalCost() float64 {
  337. return a.SharedCost
  338. }
  339. // PVCost calculate cumulative cost of all PVs that Allocation is attached to
  340. func (a *Allocation) PVCost() float64 {
  341. cost := 0.0
  342. for _, pv := range a.PVs {
  343. cost += pv.Cost
  344. }
  345. return cost
  346. }
  347. // PVByteHours calculate cumulative ByteHours of all PVs that Allocation is attached to
  348. func (a *Allocation) PVByteHours() float64 {
  349. byteHours := 0.0
  350. for _, pv := range a.PVs {
  351. byteHours += pv.ByteHours
  352. }
  353. return byteHours
  354. }
  355. // CPUEfficiency is the ratio of usage to request. If there is no request and
  356. // no usage or cost, then efficiency is zero. If there is no request, but there
  357. // is usage or cost, then efficiency is 100%.
  358. func (a *Allocation) CPUEfficiency() float64 {
  359. if a.CPUCoreRequestAverage > 0 {
  360. return a.CPUCoreUsageAverage / a.CPUCoreRequestAverage
  361. }
  362. if a.CPUCoreUsageAverage == 0.0 || a.CPUCost == 0.0 {
  363. return 0.0
  364. }
  365. return 1.0
  366. }
  367. // RAMEfficiency is the ratio of usage to request. If there is no request and
  368. // no usage or cost, then efficiency is zero. If there is no request, but there
  369. // is usage or cost, then efficiency is 100%.
  370. func (a *Allocation) RAMEfficiency() float64 {
  371. if a.RAMBytesRequestAverage > 0 {
  372. return a.RAMBytesUsageAverage / a.RAMBytesRequestAverage
  373. }
  374. if a.RAMBytesUsageAverage == 0.0 || a.RAMCost == 0.0 {
  375. return 0.0
  376. }
  377. return 1.0
  378. }
  379. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  380. // there is no cost at all, then efficiency is zero.
  381. func (a *Allocation) TotalEfficiency() float64 {
  382. if a.RAMTotalCost()+a.CPUTotalCost() > 0 {
  383. ramCostEff := a.RAMEfficiency() * a.RAMTotalCost()
  384. cpuCostEff := a.CPUEfficiency() * a.CPUTotalCost()
  385. return (ramCostEff + cpuCostEff) / (a.CPUTotalCost() + a.RAMTotalCost())
  386. }
  387. return 0.0
  388. }
  389. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  390. func (a *Allocation) CPUCores() float64 {
  391. if a.Minutes() <= 0.0 {
  392. return 0.0
  393. }
  394. return a.CPUCoreHours / (a.Minutes() / 60.0)
  395. }
  396. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  397. func (a *Allocation) RAMBytes() float64 {
  398. if a.Minutes() <= 0.0 {
  399. return 0.0
  400. }
  401. return a.RAMByteHours / (a.Minutes() / 60.0)
  402. }
  403. // GPUs converts the Allocation's GPUHours into average GPUs
  404. func (a *Allocation) GPUs() float64 {
  405. if a.Minutes() <= 0.0 {
  406. return 0.0
  407. }
  408. return a.GPUHours / (a.Minutes() / 60.0)
  409. }
  410. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  411. func (a *Allocation) PVBytes() float64 {
  412. if a.Minutes() <= 0.0 {
  413. return 0.0
  414. }
  415. return a.PVByteHours() / (a.Minutes() / 60.0)
  416. }
  417. // ResetAdjustments sets all cost adjustment fields to zero
  418. func (a *Allocation) ResetAdjustments() {
  419. a.CPUCostAdjustment = 0.0
  420. a.GPUCostAdjustment = 0.0
  421. a.RAMCostAdjustment = 0.0
  422. a.PVCostAdjustment = 0.0
  423. a.NetworkCostAdjustment = 0.0
  424. a.LoadBalancerCostAdjustment = 0.0
  425. }
  426. // MarshalJSON implements json.Marshaler interface
  427. func (a *Allocation) MarshalJSON() ([]byte, error) {
  428. buffer := bytes.NewBufferString("{")
  429. jsonEncodeString(buffer, "name", a.Name, ",")
  430. jsonEncode(buffer, "properties", a.Properties, ",")
  431. jsonEncode(buffer, "window", a.Window, ",")
  432. jsonEncodeString(buffer, "start", a.Start.Format(time.RFC3339), ",")
  433. jsonEncodeString(buffer, "end", a.End.Format(time.RFC3339), ",")
  434. jsonEncodeFloat64(buffer, "minutes", a.Minutes(), ",")
  435. jsonEncodeFloat64(buffer, "cpuCores", a.CPUCores(), ",")
  436. jsonEncodeFloat64(buffer, "cpuCoreRequestAverage", a.CPUCoreRequestAverage, ",")
  437. jsonEncodeFloat64(buffer, "cpuCoreUsageAverage", a.CPUCoreUsageAverage, ",")
  438. jsonEncodeFloat64(buffer, "cpuCoreHours", a.CPUCoreHours, ",")
  439. jsonEncodeFloat64(buffer, "cpuCost", a.CPUCost, ",")
  440. jsonEncodeFloat64(buffer, "cpuCostAdjustment", a.CPUCostAdjustment, ",")
  441. jsonEncodeFloat64(buffer, "cpuEfficiency", a.CPUEfficiency(), ",")
  442. jsonEncodeFloat64(buffer, "gpuCount", a.GPUs(), ",")
  443. jsonEncodeFloat64(buffer, "gpuHours", a.GPUHours, ",")
  444. jsonEncodeFloat64(buffer, "gpuCost", a.GPUCost, ",")
  445. jsonEncodeFloat64(buffer, "gpuCostAdjustment", a.GPUCostAdjustment, ",")
  446. jsonEncodeFloat64(buffer, "networkCost", a.NetworkCost, ",")
  447. jsonEncodeFloat64(buffer, "networkCostAdjustment", a.NetworkCostAdjustment, ",")
  448. jsonEncodeFloat64(buffer, "loadBalancerCost", a.LoadBalancerCost, ",")
  449. jsonEncodeFloat64(buffer, "loadBalancerCostAdjustment", a.LoadBalancerCostAdjustment, ",")
  450. jsonEncodeFloat64(buffer, "pvBytes", a.PVBytes(), ",")
  451. jsonEncodeFloat64(buffer, "pvByteHours", a.PVByteHours(), ",")
  452. jsonEncodeFloat64(buffer, "pvCost", a.PVCost(), ",")
  453. jsonEncode(buffer, "pvs", a.PVs, ",") // Todo Sean: this does not work properly
  454. jsonEncodeFloat64(buffer, "pvCostAdjustment", a.PVCostAdjustment, ",")
  455. jsonEncodeFloat64(buffer, "ramBytes", a.RAMBytes(), ",")
  456. jsonEncodeFloat64(buffer, "ramByteRequestAverage", a.RAMBytesRequestAverage, ",")
  457. jsonEncodeFloat64(buffer, "ramByteUsageAverage", a.RAMBytesUsageAverage, ",")
  458. jsonEncodeFloat64(buffer, "ramByteHours", a.RAMByteHours, ",")
  459. jsonEncodeFloat64(buffer, "ramCost", a.RAMCost, ",")
  460. jsonEncodeFloat64(buffer, "ramCostAdjustment", a.RAMCostAdjustment, ",")
  461. jsonEncodeFloat64(buffer, "ramEfficiency", a.RAMEfficiency(), ",")
  462. jsonEncodeFloat64(buffer, "sharedCost", a.SharedCost, ",")
  463. jsonEncodeFloat64(buffer, "externalCost", a.ExternalCost, ",")
  464. jsonEncodeFloat64(buffer, "totalCost", a.TotalCost(), ",")
  465. jsonEncodeFloat64(buffer, "totalEfficiency", a.TotalEfficiency(), ",")
  466. jsonEncode(buffer, "rawAllocationOnly", a.RawAllocationOnly, "")
  467. buffer.WriteString("}")
  468. return buffer.Bytes(), nil
  469. }
  470. // Resolution returns the duration of time covered by the Allocation
  471. func (a *Allocation) Resolution() time.Duration {
  472. return a.End.Sub(a.Start)
  473. }
  474. // IsAggregated is true if the given Allocation has been aggregated, which we
  475. // define by a lack of AllocationProperties.
  476. func (a *Allocation) IsAggregated() bool {
  477. return a == nil || a.Properties == nil
  478. }
  479. // IsExternal is true if the given Allocation represents external costs.
  480. func (a *Allocation) IsExternal() bool {
  481. return strings.Contains(a.Name, ExternalSuffix)
  482. }
  483. // IsIdle is true if the given Allocation represents idle costs.
  484. func (a *Allocation) IsIdle() bool {
  485. return strings.Contains(a.Name, IdleSuffix)
  486. }
  487. // IsUnallocated is true if the given Allocation represents unallocated costs.
  488. func (a *Allocation) IsUnallocated() bool {
  489. return strings.Contains(a.Name, UnallocatedSuffix)
  490. }
  491. // Minutes returns the number of minutes the Allocation represents, as defined
  492. // by the difference between the end and start times.
  493. func (a *Allocation) Minutes() float64 {
  494. return a.End.Sub(a.Start).Minutes()
  495. }
  496. // Share adds the TotalCost of the given Allocation to the SharedCost of the
  497. // receiving Allocation. No Start, End, Window, or AllocationProperties are considered.
  498. // Neither Allocation is mutated; a new Allocation is always returned.
  499. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  500. if that == nil {
  501. return a.Clone(), nil
  502. }
  503. if a == nil {
  504. return nil, fmt.Errorf("cannot share with nil Allocation")
  505. }
  506. agg := a.Clone()
  507. agg.SharedCost += that.TotalCost()
  508. return agg, nil
  509. }
  510. // String represents the given Allocation as a string
  511. func (a *Allocation) String() string {
  512. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost())
  513. }
  514. func (a *Allocation) add(that *Allocation) {
  515. if a == nil {
  516. log.Warningf("Allocation.AggregateBy: trying to add a nil receiver")
  517. return
  518. }
  519. // Preserve string properties that are matching between the two allocations
  520. a.Properties = a.Properties.Intersection(that.Properties)
  521. // Expand the window to encompass both Allocations
  522. a.Window = a.Window.Expand(that.Window)
  523. // Sum non-cumulative fields by turning them into cumulative, adding them,
  524. // and then converting them back into averages after minutes have been
  525. // combined (just below).
  526. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  527. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  528. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  529. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  530. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  531. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  532. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  533. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  534. // Expand Start and End to be the "max" of among the given Allocations
  535. if that.Start.Before(a.Start) {
  536. a.Start = that.Start
  537. }
  538. if that.End.After(a.End) {
  539. a.End = that.End
  540. }
  541. // Convert cumulative request and usage back into rates
  542. // TODO:TEST write a unit test that fails if this is done incorrectly
  543. if a.Minutes() > 0 {
  544. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  545. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  546. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  547. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  548. } else {
  549. a.CPUCoreRequestAverage = 0.0
  550. a.CPUCoreUsageAverage = 0.0
  551. a.RAMBytesRequestAverage = 0.0
  552. a.RAMBytesUsageAverage = 0.0
  553. }
  554. // Sum all cumulative resource fields
  555. a.CPUCoreHours += that.CPUCoreHours
  556. a.GPUHours += that.GPUHours
  557. a.RAMByteHours += that.RAMByteHours
  558. // Sum all cumulative cost fields
  559. a.CPUCost += that.CPUCost
  560. a.GPUCost += that.GPUCost
  561. a.RAMCost += that.RAMCost
  562. a.NetworkCost += that.NetworkCost
  563. a.LoadBalancerCost += that.LoadBalancerCost
  564. a.SharedCost += that.SharedCost
  565. a.ExternalCost += that.ExternalCost
  566. // Sum PVAllocations
  567. a.PVs = a.PVs.Add(that.PVs)
  568. // Sum all cumulative adjustment fields
  569. a.CPUCostAdjustment += that.CPUCostAdjustment
  570. a.RAMCostAdjustment += that.RAMCostAdjustment
  571. a.GPUCostAdjustment += that.GPUCostAdjustment
  572. a.PVCostAdjustment += that.PVCostAdjustment
  573. a.NetworkCostAdjustment += that.NetworkCostAdjustment
  574. a.LoadBalancerCostAdjustment += that.LoadBalancerCostAdjustment
  575. // Any data that is in a "raw allocation only" is not valid in any
  576. // sort of cumulative Allocation (like one that is added).
  577. a.RawAllocationOnly = nil
  578. }
  579. // AllocationSet stores a set of Allocations, each with a unique name, that share
  580. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  581. type AllocationSet struct {
  582. sync.RWMutex
  583. allocations map[string]*Allocation
  584. externalKeys map[string]bool
  585. idleKeys map[string]bool
  586. FromSource string // stores the name of the source used to compute the data
  587. Window Window
  588. Warnings []string
  589. Errors []string
  590. }
  591. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  592. // the given list of Allocations
  593. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  594. as := &AllocationSet{
  595. allocations: map[string]*Allocation{},
  596. externalKeys: map[string]bool{},
  597. idleKeys: map[string]bool{},
  598. Window: NewWindow(&start, &end),
  599. }
  600. for _, a := range allocs {
  601. as.Insert(a)
  602. }
  603. return as
  604. }
  605. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  606. // filtering results and sharing allocations. FilterFuncs are a list of match
  607. // functions such that, if any function fails, the allocation is ignored.
  608. // ShareFuncs are a list of match functions such that, if any function
  609. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  610. // simple flag for sharing idle resources.
  611. type AllocationAggregationOptions struct {
  612. FilterFuncs []AllocationMatchFunc
  613. SplitIdle bool
  614. IdleByNode bool
  615. MergeUnallocated bool
  616. ShareFuncs []AllocationMatchFunc
  617. ShareIdle string
  618. ShareSplit string
  619. SharedHourlyCosts map[string]float64
  620. }
  621. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  622. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  623. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  624. func (as *AllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  625. // The order of operations for aggregating allocations is as follows:
  626. // 1. Partition external, idle, and shared allocations into separate sets.
  627. // Also, create the aggSet into which the results will be aggregated.
  628. // 2. Compute sharing coefficients for idle and shared resources
  629. // a) if idle allocation is to be shared, compute idle coefficients
  630. // b) if idle allocation is NOT shared, but filters are present, compute
  631. // idle filtration coefficients for the purpose of only returning the
  632. // portion of idle allocation that would have been shared with the
  633. // unfiltered results. (See unit tests 5.a,b,c)
  634. // c) generate shared allocation for then given shared overhead, which
  635. // must happen after (2a) and (2b)
  636. // d) if there are shared resources, compute share coefficients
  637. // 3. Drop any allocation that fails any of the filters
  638. // 4. Distribute idle allocations according to the idle coefficients
  639. // 5. Generate aggregation key and insert allocation into the output set
  640. // 6. If idle is shared and resources are shared, some idle might be shared
  641. // with a shared resource. Distribute that to the shared resources
  642. // prior to sharing them with the aggregated results.
  643. // 7. Apply idle filtration coefficients from step (2b)
  644. // 8. Distribute shared allocations according to the share coefficients.
  645. // 9. If there are external allocations that can be aggregated into
  646. // the output (i.e. they can be used to generate a valid key for
  647. // the given properties) then aggregate; otherwise... ignore them?
  648. // 10. If the merge idle option is enabled, merge any remaining idle
  649. // allocations into a single idle allocation
  650. if options == nil {
  651. options = &AllocationAggregationOptions{}
  652. }
  653. if as.IsEmpty() {
  654. return nil
  655. }
  656. // aggSet will collect the aggregated allocations
  657. aggSet := &AllocationSet{
  658. Window: as.Window.Clone(),
  659. }
  660. // externalSet will collect external allocations
  661. externalSet := &AllocationSet{
  662. Window: as.Window.Clone(),
  663. }
  664. // idleSet will be shared among aggSet after initial aggregation
  665. // is complete
  666. idleSet := &AllocationSet{
  667. Window: as.Window.Clone(),
  668. }
  669. // shareSet will be shared among aggSet after initial aggregation
  670. // is complete
  671. shareSet := &AllocationSet{
  672. Window: as.Window.Clone(),
  673. }
  674. as.Lock()
  675. defer as.Unlock()
  676. // (1) Loop and find all of the external, idle, and shared allocations. Add
  677. // them to their respective sets, removing them from the set of allocations
  678. // to aggregate.
  679. for _, alloc := range as.allocations {
  680. // External allocations get aggregated post-hoc (see step 6) and do
  681. // not necessarily contain complete sets of properties, so they are
  682. // moved to a separate AllocationSet.
  683. if alloc.IsExternal() {
  684. delete(as.externalKeys, alloc.Name)
  685. delete(as.allocations, alloc.Name)
  686. externalSet.Insert(alloc)
  687. continue
  688. }
  689. // Idle allocations should be separated into idleSet if they are to be
  690. // shared later on. If they are not to be shared, then add them to the
  691. // aggSet like any other allocation.
  692. if alloc.IsIdle() {
  693. delete(as.idleKeys, alloc.Name)
  694. delete(as.allocations, alloc.Name)
  695. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  696. idleSet.Insert(alloc)
  697. } else {
  698. aggSet.Insert(alloc)
  699. }
  700. continue
  701. }
  702. // Shared allocations must be identified and separated prior to
  703. // aggregation and filtering. That is, if any of the ShareFuncs return
  704. // true for the allocation, then move it to shareSet.
  705. for _, sf := range options.ShareFuncs {
  706. if sf(alloc) {
  707. delete(as.idleKeys, alloc.Name)
  708. delete(as.allocations, alloc.Name)
  709. shareSet.Insert(alloc)
  710. break
  711. }
  712. }
  713. }
  714. // It's possible that no more un-shared, non-idle, non-external allocations
  715. // remain at this point. This always results in an emptySet, so return early.
  716. if len(as.allocations) == 0 {
  717. emptySet := &AllocationSet{
  718. Window: as.Window.Clone(),
  719. }
  720. as.allocations = emptySet.allocations
  721. return nil
  722. }
  723. // (2) In order to correctly share idle and shared costs, we first compute
  724. // sharing coefficients, which represent the proportion of each cost to
  725. // share with each allocation. Idle allocations are shared per-cluster or per-node,
  726. // per-allocation, and per-resource, while shared resources are shared per-
  727. // allocation only.
  728. //
  729. // For an idleCoefficient example, the entries:
  730. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  731. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  732. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  733. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  734. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  735. // RAM costs.
  736. //
  737. // For a shareCoefficient example, the entries:
  738. // [namespace2] = 0.666667
  739. // [__filtered__] = 0.333333
  740. // mean that the post-aggregation allocation "namespace2" will receive
  741. // 66.67% of the shared resource costs, while the remaining 33.33% will
  742. // be filtered out, as they were shared with allocations that did not pass
  743. // one of the given filters.
  744. //
  745. // In order to maintain stable results when multiple operations are being
  746. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  747. // coefficients are computed for the full set of allocations prior to
  748. // adding shared overhead and prior to applying filters.
  749. var err error
  750. // (2a) If there are idle costs to be shared, compute the coefficients for
  751. // sharing them among the non-idle, non-aggregated allocations (including
  752. // the shared allocations).
  753. var idleCoefficients map[string]map[string]map[string]float64
  754. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  755. idleCoefficients, err = computeIdleCoeffs(options, as, shareSet)
  756. if err != nil {
  757. log.Warningf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  758. return fmt.Errorf("error computing idle coefficients: %s", err)
  759. }
  760. }
  761. // (2b) If idle costs are not to be shared, but there are filters, then we
  762. // need to track the amount of each idle allocation to "filter" in order to
  763. // maintain parity with the results when idle is shared. That is, we want
  764. // to return only the idle costs that would have been shared with the given
  765. // results, even if the filter had not been applied.
  766. //
  767. // For example, consider these results from aggregating by namespace with
  768. // two clusters:
  769. //
  770. // namespace1: 25.00
  771. // namespace2: 30.00
  772. // namespace3: 15.00
  773. // idle: 30.00
  774. //
  775. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  776. // reduced by the amount that existed on cluster2. Then, idle must also be
  777. // reduced by the relevant amount:
  778. //
  779. // namespace1: 25.00
  780. // namespace2: 15.00
  781. // idle: 20.00
  782. //
  783. // Note that this can happen for any field, not just cluster, so we again
  784. // need to track this on a per-cluster or per-node, per-allocation, per-resource basis.
  785. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  786. if len(options.FilterFuncs) > 0 && options.ShareIdle == ShareNone {
  787. idleFiltrationCoefficients, err = computeIdleCoeffs(options, as, shareSet)
  788. if err != nil {
  789. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  790. }
  791. }
  792. // (2c) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  793. // come after idle coefficients are computes so that allocations generated
  794. // by shared overhead do not skew the idle coefficient computation.
  795. for name, cost := range options.SharedHourlyCosts {
  796. if cost > 0.0 {
  797. hours := as.Resolution().Hours()
  798. // If set ends in the future, adjust hours accordingly
  799. diff := time.Now().Sub(as.End())
  800. if diff < 0.0 {
  801. hours += diff.Hours()
  802. }
  803. totalSharedCost := cost * hours
  804. shareSet.Insert(&Allocation{
  805. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  806. Start: as.Start(),
  807. End: as.End(),
  808. SharedCost: totalSharedCost,
  809. Properties: &AllocationProperties{Cluster: SharedSuffix}, // The allocation needs to belong to a cluster,but it really doesn't matter which one, so just make it clear.
  810. })
  811. }
  812. }
  813. // (2d) Compute share coefficients for shared resources. These are computed
  814. // after idle coefficients, and are computed for the aggregated allocations
  815. // of the main allocation set. See above for details and an example.
  816. var shareCoefficients map[string]float64
  817. if shareSet.Length() > 0 {
  818. shareCoefficients, err = computeShareCoeffs(aggregateBy, options, as)
  819. if err != nil {
  820. return fmt.Errorf("error computing share coefficients: %s", err)
  821. }
  822. }
  823. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  824. for _, alloc := range as.allocations {
  825. idleId, err := alloc.getIdleId(options)
  826. if err != nil {
  827. log.DedupedWarningf(3,"AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  828. }
  829. skip := false
  830. // (3) If any of the filter funcs fail, immediately skip the allocation.
  831. for _, ff := range options.FilterFuncs {
  832. if !ff(alloc) {
  833. skip = true
  834. break
  835. }
  836. }
  837. if skip {
  838. // If we are tracking idle filtration coefficients, delete the
  839. // entry corresponding to the filtered allocation. (Deleting the
  840. // entry will result in that proportional amount being removed
  841. // from the idle allocation at the end of the process.)
  842. if idleFiltrationCoefficients != nil {
  843. if ifcc, ok := idleFiltrationCoefficients[idleId]; ok {
  844. delete(ifcc, alloc.Name)
  845. }
  846. }
  847. continue
  848. }
  849. // (4) Distribute idle allocations according to the idle coefficients
  850. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  851. // all idle allocations will be in the aggSet at this point, so idleSet
  852. // will be empty and we won't enter this block.
  853. if idleSet.Length() > 0 {
  854. // Distribute idle allocations by coefficient per-idleId, per-allocation
  855. for _, idleAlloc := range idleSet.allocations {
  856. // Only share idle if the idleId matches; i.e. the allocation
  857. // is from the same idleId as the idle costs
  858. iaidleId, err := idleAlloc.getIdleId(options)
  859. if err != nil {
  860. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  861. return err
  862. }
  863. if iaidleId != idleId {
  864. continue
  865. }
  866. // Make sure idle coefficients exist
  867. if _, ok := idleCoefficients[idleId]; !ok {
  868. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  869. continue
  870. }
  871. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  872. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  873. continue
  874. }
  875. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  876. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  877. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  878. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  879. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  880. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  881. alloc.CPUCost += idleCPUCost
  882. alloc.GPUCost += idleGPUCost
  883. alloc.RAMCost += idleRAMCost
  884. }
  885. }
  886. // (5) generate key to use for aggregation-by-key and allocation name
  887. key := alloc.generateKey(aggregateBy)
  888. alloc.Name = key
  889. if options.MergeUnallocated && alloc.IsUnallocated() {
  890. alloc.Name = UnallocatedSuffix
  891. }
  892. // Inserting the allocation with the generated key for a name will
  893. // perform the actual basic aggregation step.
  894. aggSet.Insert(alloc)
  895. }
  896. // (6) If idle is shared and resources are shared, it's possible that some
  897. // amount of idle cost will be shared with a shared resource. Distribute
  898. // that idle allocation, if it exists, to the respective shared allocations
  899. // before sharing with the aggregated allocations.
  900. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  901. for _, alloc := range shareSet.allocations {
  902. idleId, err := alloc.getIdleId(options)
  903. if err != nil {
  904. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  905. }
  906. // Distribute idle allocations by coefficient per-idleId, per-allocation
  907. for _, idleAlloc := range idleSet.allocations {
  908. // Only share idle if the idleId matches; i.e. the allocation
  909. // is from the same idleId as the idle costs
  910. iaidleId, _ := idleAlloc.getIdleId(options)
  911. if iaidleId != idleId {
  912. continue
  913. }
  914. // Make sure idle coefficients exist
  915. if _, ok := idleCoefficients[idleId]; !ok {
  916. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  917. continue
  918. }
  919. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  920. log.Warningf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  921. continue
  922. }
  923. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  924. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  925. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  926. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  927. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  928. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  929. alloc.CPUCost += idleCPUCost
  930. alloc.GPUCost += idleGPUCost
  931. alloc.RAMCost += idleRAMCost
  932. }
  933. }
  934. }
  935. // groupingIdleFiltrationCoeffs is used to track per-resource idle
  936. // coefficients on a cluster-by-cluster or node-by-node basis depending
  937. // on the IdleByNode option. It is, essentailly, an aggregation of
  938. // idleFiltrationCoefficients after they have been
  939. // filtered above (in step 3)
  940. var groupingIdleFiltrationCoeffs map[string]map[string]float64
  941. if idleFiltrationCoefficients != nil {
  942. groupingIdleFiltrationCoeffs = map[string]map[string]float64{}
  943. for idleId, m := range idleFiltrationCoefficients {
  944. if _, ok := groupingIdleFiltrationCoeffs[idleId]; !ok {
  945. groupingIdleFiltrationCoeffs[idleId] = map[string]float64{
  946. "cpu": 0.0,
  947. "gpu": 0.0,
  948. "ram": 0.0,
  949. }
  950. }
  951. for _, n := range m {
  952. for resource, val := range n {
  953. groupingIdleFiltrationCoeffs[idleId][resource] += val
  954. }
  955. }
  956. }
  957. }
  958. // (7) If we have both un-shared idle allocations and idle filtration
  959. // coefficients then apply those. See step (2b) for an example.
  960. if len(aggSet.idleKeys) > 0 && groupingIdleFiltrationCoeffs != nil {
  961. for idleKey := range aggSet.idleKeys {
  962. idleAlloc := aggSet.Get(idleKey)
  963. iaidleId, err := idleAlloc.getIdleId(options)
  964. if err != nil {
  965. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  966. return err
  967. }
  968. if resourceCoeffs, ok := groupingIdleFiltrationCoeffs[iaidleId]; ok {
  969. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  970. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  971. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  972. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  973. }
  974. }
  975. }
  976. // (8) Distribute shared allocations according to the share coefficients.
  977. if shareSet.Length() > 0 {
  978. for _, alloc := range aggSet.allocations {
  979. for _, sharedAlloc := range shareSet.allocations {
  980. if _, ok := shareCoefficients[alloc.Name]; !ok {
  981. log.Warningf("AllocationSet.AggregateBy: error getting share coefficienct for '%s'", alloc.Name)
  982. continue
  983. }
  984. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  985. }
  986. }
  987. }
  988. // (9) Aggregate external allocations into aggregated allocations. This may
  989. // not be possible for every external allocation, but attempt to find an
  990. // exact key match, given each external allocation's proerties, and
  991. // aggregate if an exact match is found.
  992. for _, alloc := range externalSet.allocations {
  993. skip := false
  994. for _, ff := range options.FilterFuncs {
  995. if !ff(alloc) {
  996. skip = true
  997. break
  998. }
  999. }
  1000. if !skip {
  1001. key := alloc.generateKey(aggregateBy)
  1002. alloc.Name = key
  1003. aggSet.Insert(alloc)
  1004. }
  1005. }
  1006. // (10) Combine all idle allocations into a single "__idle__" allocation
  1007. if !options.SplitIdle {
  1008. for _, idleAlloc := range aggSet.IdleAllocations() {
  1009. aggSet.Delete(idleAlloc.Name)
  1010. idleAlloc.Name = IdleSuffix
  1011. aggSet.Insert(idleAlloc)
  1012. }
  1013. }
  1014. as.allocations = aggSet.allocations
  1015. return nil
  1016. }
  1017. func computeShareCoeffs(aggregateBy []string, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  1018. // Compute coeffs by totalling per-allocation, then dividing by the total.
  1019. coeffs := map[string]float64{}
  1020. // Compute totals for all allocations
  1021. total := 0.0
  1022. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  1023. // counts each aggregation proportionally to its respective costs
  1024. shareType := options.ShareSplit
  1025. // Record allocation values first, then normalize by totals to get percentages
  1026. for _, alloc := range as.allocations {
  1027. if alloc.IsIdle() {
  1028. // Skip idle allocations in coefficient calculation
  1029. continue
  1030. }
  1031. // Determine the post-aggregation key under which the allocation will
  1032. // be shared.
  1033. name := alloc.generateKey(aggregateBy)
  1034. // If the current allocation will be filtered out in step 3, contribute
  1035. // its share of the shared coefficient to a "__filtered__" bin, which
  1036. // will ultimately be dropped. This step ensures that the shared cost
  1037. // of a non-filtered allocation will be conserved even when the filter
  1038. // is removed. (Otherwise, all the shared cost will get redistributed
  1039. // over the unfiltered results, inflating their shared costs.)
  1040. filtered := false
  1041. for _, ff := range options.FilterFuncs {
  1042. if !ff(alloc) {
  1043. filtered = true
  1044. break
  1045. }
  1046. }
  1047. if filtered {
  1048. name = "__filtered__"
  1049. }
  1050. if shareType == ShareEven {
  1051. // Even distribution is not additive - set to 1.0 for everything
  1052. coeffs[name] = 1.0
  1053. // Total for even distribution is always the number of coefficients
  1054. total = float64(len(coeffs))
  1055. } else {
  1056. // Both are additive for weighted distribution, where each
  1057. // cumulative coefficient will be divided by the total.
  1058. coeffs[name] += alloc.TotalCost()
  1059. total += alloc.TotalCost()
  1060. }
  1061. }
  1062. // Normalize coefficients by totals
  1063. for a := range coeffs {
  1064. if coeffs[a] > 0 && total > 0 {
  1065. coeffs[a] /= total
  1066. } else {
  1067. log.Warningf("ETL: invalid values for shared coefficients: %d, %d", coeffs[a], total)
  1068. coeffs[a] = 0.0
  1069. }
  1070. }
  1071. return coeffs, nil
  1072. }
  1073. func computeIdleCoeffs(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, error) {
  1074. types := []string{"cpu", "gpu", "ram"}
  1075. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1076. coeffs := map[string]map[string]map[string]float64{}
  1077. // Compute totals per resource for CPU, GPU, RAM, and PV
  1078. totals := map[string]map[string]float64{}
  1079. // ShareEven counts each allocation with even weight, whereas ShareWeighted
  1080. // counts each allocation proportionally to its respective costs
  1081. shareType := options.ShareIdle
  1082. // Record allocation values first, then normalize by totals to get percentages
  1083. for _, alloc := range as.allocations {
  1084. if alloc.IsIdle() {
  1085. // Skip idle allocations in coefficient calculation
  1086. continue
  1087. }
  1088. idleId, err := alloc.getIdleId(options)
  1089. if err != nil {
  1090. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  1091. }
  1092. // get the name key for the allocation
  1093. name := alloc.Name
  1094. // Create key based tables if they don't exist
  1095. if _, ok := coeffs[idleId]; !ok {
  1096. coeffs[idleId] = map[string]map[string]float64{}
  1097. }
  1098. if _, ok := totals[idleId]; !ok {
  1099. totals[idleId] = map[string]float64{}
  1100. }
  1101. if _, ok := coeffs[idleId][name]; !ok {
  1102. coeffs[idleId][name] = map[string]float64{}
  1103. }
  1104. if shareType == ShareEven {
  1105. for _, r := range types {
  1106. // Not additive - hard set to 1.0
  1107. coeffs[idleId][name][r] = 1.0
  1108. // totals are additive
  1109. totals[idleId][r] += 1.0
  1110. }
  1111. } else {
  1112. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1113. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1114. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1115. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1116. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1117. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1118. }
  1119. }
  1120. // Do the same for shared allocations
  1121. for _, alloc := range shareSet.allocations {
  1122. if alloc.IsIdle() {
  1123. // Skip idle allocations in coefficient calculation
  1124. continue
  1125. }
  1126. // idleId will be providerId or cluster
  1127. idleId, err := alloc.getIdleId(options)
  1128. if err != nil {
  1129. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  1130. }
  1131. // get the name key for the allocation
  1132. name := alloc.Name
  1133. // Create idleId based tables if they don't exist
  1134. if _, ok := coeffs[idleId]; !ok {
  1135. coeffs[idleId] = map[string]map[string]float64{}
  1136. }
  1137. if _, ok := totals[idleId]; !ok {
  1138. totals[idleId] = map[string]float64{}
  1139. }
  1140. if _, ok := coeffs[idleId][name]; !ok {
  1141. coeffs[idleId][name] = map[string]float64{}
  1142. }
  1143. if shareType == ShareEven {
  1144. for _, r := range types {
  1145. // Not additive - hard set to 1.0
  1146. coeffs[idleId][name][r] = 1.0
  1147. // totals are additive
  1148. totals[idleId][r] += 1.0
  1149. }
  1150. } else {
  1151. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1152. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1153. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1154. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1155. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1156. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1157. }
  1158. }
  1159. // Normalize coefficients by totals
  1160. for c := range coeffs {
  1161. for a := range coeffs[c] {
  1162. for _, r := range types {
  1163. if coeffs[c][a][r] > 0 && totals[c][r] > 0 {
  1164. coeffs[c][a][r] /= totals[c][r]
  1165. }
  1166. }
  1167. }
  1168. }
  1169. return coeffs, nil
  1170. }
  1171. // getIdleId returns the providerId or cluster of an Allocation depending on the IdleByNode
  1172. // option in the AllocationAggregationOptions and an error if the respective field is missing
  1173. func (a *Allocation) getIdleId(options *AllocationAggregationOptions) (string, error) {
  1174. var idleId string
  1175. if options.IdleByNode {
  1176. // Key allocations to ProviderId to match against node
  1177. idleId = a.Properties.ProviderID
  1178. if idleId == "" {
  1179. return idleId, fmt.Errorf("ProviderId is not set")
  1180. }
  1181. } else {
  1182. // key the allocations by cluster id
  1183. idleId = a.Properties.Cluster
  1184. if idleId == "" {
  1185. return idleId, fmt.Errorf("ClusterProp is not set")
  1186. }
  1187. }
  1188. return idleId, nil
  1189. }
  1190. func (a *Allocation) generateKey(aggregateBy []string) string {
  1191. if a == nil {
  1192. return ""
  1193. }
  1194. // Names will ultimately be joined into a single name, which uniquely
  1195. // identifies allocations.
  1196. names := []string{}
  1197. for _, agg := range aggregateBy {
  1198. switch true {
  1199. case agg == AllocationClusterProp:
  1200. names = append(names, a.Properties.Cluster)
  1201. case agg == AllocationNodeProp:
  1202. names = append(names, a.Properties.Node)
  1203. case agg == AllocationNamespaceProp:
  1204. names = append(names, a.Properties.Namespace)
  1205. case agg == AllocationControllerKindProp:
  1206. controllerKind := a.Properties.ControllerKind
  1207. if controllerKind == "" {
  1208. // Indicate that allocation has no controller
  1209. controllerKind = UnallocatedSuffix
  1210. }
  1211. names = append(names, controllerKind)
  1212. case agg == AllocationDaemonSetProp || agg == AllocationStatefulSetProp || agg == AllocationDeploymentProp || agg == AllocationJobProp:
  1213. controller := a.Properties.Controller
  1214. if agg != a.Properties.ControllerKind || controller == "" {
  1215. // The allocation does not have the specified controller kind
  1216. controller = UnallocatedSuffix
  1217. }
  1218. names = append(names, controller)
  1219. case agg == AllocationControllerProp:
  1220. controller := a.Properties.Controller
  1221. if controller == "" {
  1222. // Indicate that allocation has no controller
  1223. controller = UnallocatedSuffix
  1224. } else if a.Properties.ControllerKind != "" {
  1225. controller = fmt.Sprintf("%s:%s", a.Properties.ControllerKind, controller)
  1226. }
  1227. names = append(names, controller)
  1228. case agg == AllocationPodProp:
  1229. names = append(names, a.Properties.Pod)
  1230. case agg == AllocationContainerProp:
  1231. names = append(names, a.Properties.Container)
  1232. case agg == AllocationServiceProp:
  1233. services := a.Properties.Services
  1234. if services == nil || len(services) == 0 {
  1235. // Indicate that allocation has no services
  1236. names = append(names, UnallocatedSuffix)
  1237. } else {
  1238. // This just uses the first service
  1239. for _, service := range services {
  1240. names = append(names, service)
  1241. break
  1242. }
  1243. }
  1244. case strings.HasPrefix(agg, "label:"):
  1245. labels := a.Properties.Labels
  1246. if labels == nil {
  1247. // Indicate that allocation has no labels
  1248. names = append(names, UnallocatedSuffix)
  1249. } else {
  1250. labelNames := []string{}
  1251. aggLabels := strings.Split(strings.TrimPrefix(agg, "label:"), ";")
  1252. for _, labelName := range aggLabels {
  1253. if val, ok := labels[labelName]; ok {
  1254. labelNames = append(labelNames, fmt.Sprintf("%s=%s", labelName, val))
  1255. } else if indexOf(UnallocatedSuffix, labelNames) == -1 { // if UnallocatedSuffix not already in names
  1256. labelNames = append(labelNames, UnallocatedSuffix)
  1257. }
  1258. }
  1259. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1260. if len(labelNames) > 1 {
  1261. sort.Strings(labelNames)
  1262. }
  1263. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, labelNames)
  1264. // suffix should be at index 0 if it exists b/c of underscores
  1265. if unallocatedSuffixIndex != -1 {
  1266. labelNames = append(labelNames[:unallocatedSuffixIndex], labelNames[unallocatedSuffixIndex+1:]...)
  1267. labelNames = append(labelNames, UnallocatedSuffix) // append to end
  1268. }
  1269. names = append(names, labelNames...)
  1270. }
  1271. case strings.HasPrefix(agg, "annotation:"):
  1272. annotations := a.Properties.Annotations
  1273. if annotations == nil {
  1274. // Indicate that allocation has no annotations
  1275. names = append(names, UnallocatedSuffix)
  1276. } else {
  1277. annotationNames := []string{}
  1278. aggAnnotations := strings.Split(strings.TrimPrefix(agg, "annotation:"), ";")
  1279. for _, annotationName := range aggAnnotations {
  1280. if val, ok := annotations[annotationName]; ok {
  1281. annotationNames = append(annotationNames, fmt.Sprintf("%s=%s", annotationName, val))
  1282. } else if indexOf(UnallocatedSuffix, annotationNames) == -1 { // if UnallocatedSuffix not already in names
  1283. annotationNames = append(annotationNames, UnallocatedSuffix)
  1284. }
  1285. }
  1286. // resolve arbitrary ordering. e.g., app=app0/env=env0 is the same agg as env=env0/app=app0
  1287. if len(annotationNames) > 1 {
  1288. sort.Strings(annotationNames)
  1289. }
  1290. unallocatedSuffixIndex := indexOf(UnallocatedSuffix, annotationNames)
  1291. // suffix should be at index 0 if it exists b/c of underscores
  1292. if unallocatedSuffixIndex != -1 {
  1293. annotationNames = append(annotationNames[:unallocatedSuffixIndex], annotationNames[unallocatedSuffixIndex+1:]...)
  1294. annotationNames = append(annotationNames, UnallocatedSuffix) // append to end
  1295. }
  1296. names = append(names, annotationNames...)
  1297. }
  1298. }
  1299. }
  1300. return strings.Join(names, "/")
  1301. }
  1302. // TODO:CLEANUP get rid of this
  1303. // Helper function to check for slice membership. Not sure if repeated elsewhere in our codebase.
  1304. func indexOf(v string, arr []string) int {
  1305. for i, s := range arr {
  1306. // This is caseless equivalence
  1307. if strings.EqualFold(v, s) {
  1308. return i
  1309. }
  1310. }
  1311. return -1
  1312. }
  1313. // Clone returns a new AllocationSet with a deep copy of the given
  1314. // AllocationSet's allocations.
  1315. func (as *AllocationSet) Clone() *AllocationSet {
  1316. if as == nil {
  1317. return nil
  1318. }
  1319. as.RLock()
  1320. defer as.RUnlock()
  1321. allocs := map[string]*Allocation{}
  1322. for k, v := range as.allocations {
  1323. allocs[k] = v.Clone()
  1324. }
  1325. externalKeys := map[string]bool{}
  1326. for k, v := range as.externalKeys {
  1327. externalKeys[k] = v
  1328. }
  1329. idleKeys := map[string]bool{}
  1330. for k, v := range as.idleKeys {
  1331. idleKeys[k] = v
  1332. }
  1333. return &AllocationSet{
  1334. allocations: allocs,
  1335. externalKeys: externalKeys,
  1336. idleKeys: idleKeys,
  1337. Window: as.Window.Clone(),
  1338. }
  1339. }
  1340. // ComputeIdleAllocations computes the idle allocations for the AllocationSet,
  1341. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1342. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1343. // considered for idle allocation. If the Nodes have adjustments, then apply
  1344. // the adjustments proportionally to each of the resources so that total
  1345. // allocation with idle reflects the adjusted node costs. One idle allocation
  1346. // per-cluster will be computed and returned, keyed by cluster_id.
  1347. func (as *AllocationSet) ComputeIdleAllocations(assetSet *AssetSet) (map[string]*Allocation, error) {
  1348. if as == nil {
  1349. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1350. }
  1351. if assetSet == nil {
  1352. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1353. }
  1354. if !as.Window.Equal(assetSet.Window) {
  1355. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1356. }
  1357. window := as.Window
  1358. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1359. // cluster-to-{cpu|gpu|ram}-to-cost.
  1360. assetClusterResourceCosts := map[string]map[string]float64{}
  1361. assetSet.Each(func(key string, a Asset) {
  1362. if node, ok := a.(*Node); ok {
  1363. if _, ok := assetClusterResourceCosts[node.Properties().Cluster]; !ok {
  1364. assetClusterResourceCosts[node.Properties().Cluster] = map[string]float64{}
  1365. }
  1366. // adjustmentRate is used to scale resource costs proportionally
  1367. // by the adjustment. This is necessary because we only get one
  1368. // adjustment per Node, not one per-resource-per-Node.
  1369. //
  1370. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1371. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1372. // e.g. total cost = $150, adjustment = $50 => 1.5
  1373. adjustmentRate := 1.0
  1374. if node.TotalCost()-node.Adjustment() == 0 {
  1375. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1376. // the entire node cost and we should make everything 0
  1377. // without dividing by 0.
  1378. adjustmentRate = 0.0
  1379. log.DedupedWarningf(5, "Compute Idle Allocations: Node Cost Adjusted to $0.00 for %s", node.properties.Name)
  1380. } else if node.Adjustment() != 0.0 {
  1381. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1382. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1383. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1384. }
  1385. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1386. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1387. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1388. assetClusterResourceCosts[node.Properties().Cluster]["cpu"] += cpuCost
  1389. assetClusterResourceCosts[node.Properties().Cluster]["gpu"] += gpuCost
  1390. assetClusterResourceCosts[node.Properties().Cluster]["ram"] += ramCost
  1391. }
  1392. })
  1393. // Determine start, end on a per-cluster basis
  1394. clusterStarts := map[string]time.Time{}
  1395. clusterEnds := map[string]time.Time{}
  1396. // Subtract allocated costs from asset costs, leaving only the remaining
  1397. // idle costs.
  1398. as.Each(func(name string, a *Allocation) {
  1399. cluster := a.Properties.Cluster
  1400. if cluster == "" {
  1401. // Failed to find allocation's cluster
  1402. return
  1403. }
  1404. if _, ok := assetClusterResourceCosts[cluster]; !ok {
  1405. // Failed to find assets for allocation's cluster
  1406. return
  1407. }
  1408. // Set cluster (start, end) if they are either not currently set,
  1409. // or if the detected (start, end) of the current allocation falls
  1410. // before or after, respectively, the current values.
  1411. if s, ok := clusterStarts[cluster]; !ok || a.Start.Before(s) {
  1412. clusterStarts[cluster] = a.Start
  1413. }
  1414. if e, ok := clusterEnds[cluster]; !ok || a.End.After(e) {
  1415. clusterEnds[cluster] = a.End
  1416. }
  1417. assetClusterResourceCosts[cluster]["cpu"] -= a.CPUTotalCost()
  1418. assetClusterResourceCosts[cluster]["gpu"] -= a.GPUTotalCost()
  1419. assetClusterResourceCosts[cluster]["ram"] -= a.RAMTotalCost()
  1420. })
  1421. // Turn remaining un-allocated asset costs into idle allocations
  1422. idleAllocs := map[string]*Allocation{}
  1423. for cluster, resources := range assetClusterResourceCosts {
  1424. // Default start and end to the (start, end) of the given window, but
  1425. // use the actual, detected (start, end) pair if they are available.
  1426. start := *window.Start()
  1427. if s, ok := clusterStarts[cluster]; ok && window.Contains(s) {
  1428. start = s
  1429. }
  1430. end := *window.End()
  1431. if e, ok := clusterEnds[cluster]; ok && window.Contains(e) {
  1432. end = e
  1433. }
  1434. idleAlloc := &Allocation{
  1435. Name: fmt.Sprintf("%s/%s", cluster, IdleSuffix),
  1436. Window: window.Clone(),
  1437. Properties: &AllocationProperties{Cluster: cluster},
  1438. Start: start,
  1439. End: end,
  1440. CPUCost: resources["cpu"],
  1441. GPUCost: resources["gpu"],
  1442. RAMCost: resources["ram"],
  1443. }
  1444. // Do not continue if multiple idle allocations are computed for a
  1445. // single cluster.
  1446. if _, ok := idleAllocs[cluster]; ok {
  1447. return nil, fmt.Errorf("duplicate idle allocations for cluster %s", cluster)
  1448. }
  1449. idleAllocs[cluster] = idleAlloc
  1450. }
  1451. return idleAllocs, nil
  1452. }
  1453. // ComputeIdleAllocationsByNode computes the idle allocations for the AllocationSet,
  1454. // given a set of Assets. Ideally, assetSet should contain only Nodes, but if
  1455. // it contains other Assets, they will be ignored; only CPU, GPU and RAM are
  1456. // considered for idle allocation. If the Nodes have adjustments, then apply
  1457. // the adjustments proportionally to each of the resources so that total
  1458. // allocation with idle reflects the adjusted node costs. One idle allocation
  1459. // per-node will be computed and returned, keyed by cluster_id.
  1460. func (as *AllocationSet) ComputeIdleAllocationsByNode(assetSet *AssetSet) (map[string]*Allocation, error) {
  1461. if as == nil {
  1462. return nil, fmt.Errorf("cannot compute idle allocation for nil AllocationSet")
  1463. }
  1464. if assetSet == nil {
  1465. return nil, fmt.Errorf("cannot compute idle allocation with nil AssetSet")
  1466. }
  1467. if !as.Window.Equal(assetSet.Window) {
  1468. return nil, fmt.Errorf("cannot compute idle allocation for sets with mismatched windows: %s != %s", as.Window, assetSet.Window)
  1469. }
  1470. window := as.Window
  1471. // Build a map of cumulative cluster asset costs, per resource; i.e.
  1472. // cluster-to-{cpu|gpu|ram}-to-cost.
  1473. assetNodeResourceCosts := map[string]map[string]float64{}
  1474. nodesByProviderId := map[string]*Node{}
  1475. assetSet.Each(func(key string, a Asset) {
  1476. if node, ok := a.(*Node); ok {
  1477. if _, ok := assetNodeResourceCosts[node.Properties().ProviderID]; ok || node.Properties().ProviderID == "" {
  1478. log.DedupedWarningf(5, "Compute Idle Allocations By Node: Node missing providerId: %s", node.properties.Name)
  1479. return
  1480. }
  1481. nodesByProviderId[node.Properties().ProviderID] = node
  1482. assetNodeResourceCosts[node.Properties().ProviderID] = map[string]float64{}
  1483. // adjustmentRate is used to scale resource costs proportionally
  1484. // by the adjustment. This is necessary because we only get one
  1485. // adjustment per Node, not one per-resource-per-Node.
  1486. //
  1487. // e.g. total cost = $90, adjustment = -$10 => 0.9
  1488. // e.g. total cost = $150, adjustment = -$300 => 0.3333
  1489. // e.g. total cost = $150, adjustment = $50 => 1.5
  1490. adjustmentRate := 1.0
  1491. if node.TotalCost()-node.Adjustment() == 0 {
  1492. // If (totalCost - adjustment) is 0.0 then adjustment cancels
  1493. // the entire node cost and we should make everything 0
  1494. // without dividing by 0.
  1495. adjustmentRate = 0.0
  1496. log.DedupedWarningf(5, "Compute Idle Allocations: Node Cost Adjusted to $0.00 for %s", node.properties.Name)
  1497. } else if node.Adjustment() != 0.0 {
  1498. // adjustmentRate is the ratio of cost-with-adjustment (i.e. TotalCost)
  1499. // to cost-without-adjustment (i.e. TotalCost - Adjustment).
  1500. adjustmentRate = node.TotalCost() / (node.TotalCost() - node.Adjustment())
  1501. }
  1502. cpuCost := node.CPUCost * (1.0 - node.Discount) * adjustmentRate
  1503. gpuCost := node.GPUCost * (1.0 - node.Discount) * adjustmentRate
  1504. ramCost := node.RAMCost * (1.0 - node.Discount) * adjustmentRate
  1505. assetNodeResourceCosts[node.Properties().ProviderID]["cpu"] += cpuCost
  1506. assetNodeResourceCosts[node.Properties().ProviderID]["gpu"] += gpuCost
  1507. assetNodeResourceCosts[node.Properties().ProviderID]["ram"] += ramCost
  1508. }
  1509. })
  1510. // Determine start, end on a per-cluster basis
  1511. nodeStarts := map[string]time.Time{}
  1512. nodeEnds := map[string]time.Time{}
  1513. // Subtract allocated costs from asset costs, leaving only the remaining
  1514. // idle costs.
  1515. as.Each(func(name string, a *Allocation) {
  1516. providerId := a.Properties.ProviderID
  1517. if providerId == "" {
  1518. // Failed to find allocation's node
  1519. log.DedupedWarningf(5, "Compute Idle Allocations By Node: Allocation missing providerId: %s", a.Name)
  1520. return
  1521. }
  1522. if _, ok := assetNodeResourceCosts[providerId]; !ok {
  1523. // Failed to find assets for allocation's node
  1524. return
  1525. }
  1526. // Set cluster (start, end) if they are either not currently set,
  1527. // or if the detected (start, end) of the current allocation falls
  1528. // before or after, respectively, the current values.
  1529. if s, ok := nodeStarts[providerId]; !ok || a.Start.Before(s) {
  1530. nodeStarts[providerId] = a.Start
  1531. }
  1532. if e, ok := nodeEnds[providerId]; !ok || a.End.After(e) {
  1533. nodeEnds[providerId] = a.End
  1534. }
  1535. assetNodeResourceCosts[providerId]["cpu"] -= a.CPUTotalCost()
  1536. assetNodeResourceCosts[providerId]["gpu"] -= a.GPUTotalCost()
  1537. assetNodeResourceCosts[providerId]["ram"] -= a.RAMTotalCost()
  1538. })
  1539. // Turn remaining un-allocated asset costs into idle allocations
  1540. idleAllocs := map[string]*Allocation{}
  1541. for providerId, resources := range assetNodeResourceCosts {
  1542. // Default start and end to the (start, end) of the given window, but
  1543. // use the actual, detected (start, end) pair if they are available.
  1544. start := *window.Start()
  1545. if s, ok := nodeStarts[providerId]; ok && window.Contains(s) {
  1546. start = s
  1547. }
  1548. end := *window.End()
  1549. if e, ok := nodeEnds[providerId]; ok && window.Contains(e) {
  1550. end = e
  1551. }
  1552. node := nodesByProviderId[providerId]
  1553. idleAlloc := &Allocation{
  1554. Name: fmt.Sprintf("%s/%s", node.properties.Name, IdleSuffix),
  1555. Window: window.Clone(),
  1556. Properties: &AllocationProperties{
  1557. Cluster: node.properties.Cluster,
  1558. Node: node.properties.Name,
  1559. ProviderID: providerId,
  1560. },
  1561. Start: start,
  1562. End: end,
  1563. CPUCost: resources["cpu"],
  1564. GPUCost: resources["gpu"],
  1565. RAMCost: resources["ram"],
  1566. }
  1567. // Do not continue if multiple idle allocations are computed for a
  1568. // single node.
  1569. if _, ok := idleAllocs[providerId]; ok {
  1570. return nil, fmt.Errorf("duplicate idle allocations for node Provider ID: %s", providerId)
  1571. }
  1572. idleAllocs[providerId] = idleAlloc
  1573. }
  1574. return idleAllocs, nil
  1575. }
  1576. // Delete removes the allocation with the given name from the set
  1577. func (as *AllocationSet) Delete(name string) {
  1578. if as == nil {
  1579. return
  1580. }
  1581. as.Lock()
  1582. defer as.Unlock()
  1583. delete(as.externalKeys, name)
  1584. delete(as.idleKeys, name)
  1585. delete(as.allocations, name)
  1586. }
  1587. // Each invokes the given function for each Allocation in the set
  1588. func (as *AllocationSet) Each(f func(string, *Allocation)) {
  1589. if as == nil {
  1590. return
  1591. }
  1592. for k, a := range as.allocations {
  1593. f(k, a)
  1594. }
  1595. }
  1596. // End returns the End time of the AllocationSet window
  1597. func (as *AllocationSet) End() time.Time {
  1598. if as == nil {
  1599. log.Warningf("AllocationSet: calling End on nil AllocationSet")
  1600. return time.Unix(0, 0)
  1601. }
  1602. if as.Window.End() == nil {
  1603. log.Warningf("AllocationSet: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.allocations))
  1604. return time.Unix(0, 0)
  1605. }
  1606. return *as.Window.End()
  1607. }
  1608. // Get returns the Allocation at the given key in the AllocationSet
  1609. func (as *AllocationSet) Get(key string) *Allocation {
  1610. as.RLock()
  1611. defer as.RUnlock()
  1612. if alloc, ok := as.allocations[key]; ok {
  1613. return alloc
  1614. }
  1615. return nil
  1616. }
  1617. // ExternalAllocations returns a map of the external allocations in the set.
  1618. // Returns clones of the actual Allocations, so mutability is not a problem.
  1619. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1620. externals := map[string]*Allocation{}
  1621. if as.IsEmpty() {
  1622. return externals
  1623. }
  1624. as.RLock()
  1625. defer as.RUnlock()
  1626. for key := range as.externalKeys {
  1627. if alloc, ok := as.allocations[key]; ok {
  1628. externals[key] = alloc.Clone()
  1629. }
  1630. }
  1631. return externals
  1632. }
  1633. // ExternalCost returns the total aggregated external costs of the set
  1634. func (as *AllocationSet) ExternalCost() float64 {
  1635. if as.IsEmpty() {
  1636. return 0.0
  1637. }
  1638. as.RLock()
  1639. defer as.RUnlock()
  1640. externalCost := 0.0
  1641. for _, alloc := range as.allocations {
  1642. externalCost += alloc.ExternalCost
  1643. }
  1644. return externalCost
  1645. }
  1646. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1647. // Returns clones of the actual Allocations, so mutability is not a problem.
  1648. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1649. idles := map[string]*Allocation{}
  1650. if as.IsEmpty() {
  1651. return idles
  1652. }
  1653. as.RLock()
  1654. defer as.RUnlock()
  1655. for key := range as.idleKeys {
  1656. if alloc, ok := as.allocations[key]; ok {
  1657. idles[key] = alloc.Clone()
  1658. }
  1659. }
  1660. return idles
  1661. }
  1662. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1663. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1664. // there is no existing entry, one is created. Nil error response indicates success.
  1665. func (as *AllocationSet) Insert(that *Allocation) error {
  1666. return as.insert(that)
  1667. }
  1668. func (as *AllocationSet) insert(that *Allocation) error {
  1669. if as == nil {
  1670. return fmt.Errorf("cannot insert into nil AllocationSet")
  1671. }
  1672. as.Lock()
  1673. defer as.Unlock()
  1674. if as.allocations == nil {
  1675. as.allocations = map[string]*Allocation{}
  1676. }
  1677. if as.externalKeys == nil {
  1678. as.externalKeys = map[string]bool{}
  1679. }
  1680. if as.idleKeys == nil {
  1681. as.idleKeys = map[string]bool{}
  1682. }
  1683. // Add the given Allocation to the existing entry, if there is one;
  1684. // otherwise just set directly into allocations
  1685. if _, ok := as.allocations[that.Name]; !ok {
  1686. as.allocations[that.Name] = that
  1687. } else {
  1688. as.allocations[that.Name].add(that)
  1689. }
  1690. // If the given Allocation is an external one, record that
  1691. if that.IsExternal() {
  1692. as.externalKeys[that.Name] = true
  1693. }
  1694. // If the given Allocation is an idle one, record that
  1695. if that.IsIdle() {
  1696. as.idleKeys[that.Name] = true
  1697. }
  1698. return nil
  1699. }
  1700. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  1701. // zero allocations.
  1702. func (as *AllocationSet) IsEmpty() bool {
  1703. if as == nil || len(as.allocations) == 0 {
  1704. return true
  1705. }
  1706. as.RLock()
  1707. defer as.RUnlock()
  1708. return as.allocations == nil || len(as.allocations) == 0
  1709. }
  1710. // Length returns the number of Allocations in the set
  1711. func (as *AllocationSet) Length() int {
  1712. if as == nil {
  1713. return 0
  1714. }
  1715. as.RLock()
  1716. defer as.RUnlock()
  1717. return len(as.allocations)
  1718. }
  1719. // Map clones and returns a map of the AllocationSet's Allocations
  1720. func (as *AllocationSet) Map() map[string]*Allocation {
  1721. if as.IsEmpty() {
  1722. return map[string]*Allocation{}
  1723. }
  1724. return as.Clone().allocations
  1725. }
  1726. // MarshalJSON JSON-encodes the AllocationSet
  1727. func (as *AllocationSet) MarshalJSON() ([]byte, error) {
  1728. as.RLock()
  1729. defer as.RUnlock()
  1730. return json.Marshal(as.allocations)
  1731. }
  1732. // Resolution returns the AllocationSet's window duration
  1733. func (as *AllocationSet) Resolution() time.Duration {
  1734. return as.Window.Duration()
  1735. }
  1736. // Set uses the given Allocation to overwrite the existing entry in the
  1737. // AllocationSet under the Allocation's name.
  1738. func (as *AllocationSet) Set(alloc *Allocation) error {
  1739. if as.IsEmpty() {
  1740. as.Lock()
  1741. as.allocations = map[string]*Allocation{}
  1742. as.externalKeys = map[string]bool{}
  1743. as.idleKeys = map[string]bool{}
  1744. as.Unlock()
  1745. }
  1746. as.Lock()
  1747. defer as.Unlock()
  1748. as.allocations[alloc.Name] = alloc
  1749. // If the given Allocation is an external one, record that
  1750. if alloc.IsExternal() {
  1751. as.externalKeys[alloc.Name] = true
  1752. }
  1753. // If the given Allocation is an idle one, record that
  1754. if alloc.IsIdle() {
  1755. as.idleKeys[alloc.Name] = true
  1756. }
  1757. return nil
  1758. }
  1759. // Start returns the Start time of the AllocationSet window
  1760. func (as *AllocationSet) Start() time.Time {
  1761. if as == nil {
  1762. log.Warningf("AllocationSet: calling Start on nil AllocationSet")
  1763. return time.Unix(0, 0)
  1764. }
  1765. if as.Window.Start() == nil {
  1766. log.Warningf("AllocationSet: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.allocations))
  1767. return time.Unix(0, 0)
  1768. }
  1769. return *as.Window.Start()
  1770. }
  1771. // String represents the given Allocation as a string
  1772. func (as *AllocationSet) String() string {
  1773. if as == nil {
  1774. return "<nil>"
  1775. }
  1776. return fmt.Sprintf("AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  1777. as.Length(), as.Window, as.TotalCost())
  1778. }
  1779. // TotalCost returns the sum of all TotalCosts of the allocations contained
  1780. func (as *AllocationSet) TotalCost() float64 {
  1781. if as.IsEmpty() {
  1782. return 0.0
  1783. }
  1784. as.RLock()
  1785. defer as.RUnlock()
  1786. tc := 0.0
  1787. for _, a := range as.allocations {
  1788. tc += a.TotalCost()
  1789. }
  1790. return tc
  1791. }
  1792. // UTCOffset returns the AllocationSet's configured UTCOffset.
  1793. func (as *AllocationSet) UTCOffset() time.Duration {
  1794. _, zone := as.Start().Zone()
  1795. return time.Duration(zone) * time.Second
  1796. }
  1797. func (as *AllocationSet) accumulate(that *AllocationSet) (*AllocationSet, error) {
  1798. if as.IsEmpty() {
  1799. return that.Clone(), nil
  1800. }
  1801. if that.IsEmpty() {
  1802. return as.Clone(), nil
  1803. }
  1804. // Set start, end to min(start), max(end)
  1805. start := as.Start()
  1806. end := as.End()
  1807. if that.Start().Before(start) {
  1808. start = that.Start()
  1809. }
  1810. if that.End().After(end) {
  1811. end = that.End()
  1812. }
  1813. acc := NewAllocationSet(start, end)
  1814. as.RLock()
  1815. defer as.RUnlock()
  1816. that.RLock()
  1817. defer that.RUnlock()
  1818. for _, alloc := range as.allocations {
  1819. err := acc.insert(alloc)
  1820. if err != nil {
  1821. return nil, err
  1822. }
  1823. }
  1824. for _, alloc := range that.allocations {
  1825. err := acc.insert(alloc)
  1826. if err != nil {
  1827. return nil, err
  1828. }
  1829. }
  1830. return acc, nil
  1831. }
  1832. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  1833. // be used such that the AllocationSets held are consecutive and coherent with
  1834. // respect to using the same aggregation properties, UTC offset, and
  1835. // resolution. However these rules are not necessarily enforced, so use wisely.
  1836. type AllocationSetRange struct {
  1837. sync.RWMutex
  1838. allocations []*AllocationSet
  1839. FromStore string // stores the name of the store used to retrieve the data
  1840. }
  1841. // NewAllocationSetRange instantiates a new range composed of the given
  1842. // AllocationSets in the order provided.
  1843. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  1844. return &AllocationSetRange{
  1845. allocations: allocs,
  1846. }
  1847. }
  1848. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  1849. // AllocationSet for the entire range.
  1850. func (asr *AllocationSetRange) Accumulate() (*AllocationSet, error) {
  1851. var allocSet *AllocationSet
  1852. var err error
  1853. asr.RLock()
  1854. defer asr.RUnlock()
  1855. for _, as := range asr.allocations {
  1856. allocSet, err = allocSet.accumulate(as)
  1857. if err != nil {
  1858. return nil, err
  1859. }
  1860. }
  1861. return allocSet, nil
  1862. }
  1863. // TODO accumulate into lower-resolution chunks of the given resolution
  1864. // func (asr *AllocationSetRange) AccumulateBy(resolution time.Duration) *AllocationSetRange
  1865. // AggregateBy aggregates each AllocationSet in the range by the given
  1866. // properties and options.
  1867. func (asr *AllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  1868. aggRange := &AllocationSetRange{allocations: []*AllocationSet{}}
  1869. asr.Lock()
  1870. defer asr.Unlock()
  1871. for _, as := range asr.allocations {
  1872. err := as.AggregateBy(aggregateBy, options)
  1873. if err != nil {
  1874. return err
  1875. }
  1876. aggRange.allocations = append(aggRange.allocations, as)
  1877. }
  1878. asr.allocations = aggRange.allocations
  1879. return nil
  1880. }
  1881. // Append appends the given AllocationSet to the end of the range. It does not
  1882. // validate whether or not that violates window continuity.
  1883. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  1884. asr.Lock()
  1885. defer asr.Unlock()
  1886. asr.allocations = append(asr.allocations, that)
  1887. }
  1888. // Each invokes the given function for each AllocationSet in the range
  1889. func (asr *AllocationSetRange) Each(f func(int, *AllocationSet)) {
  1890. if asr == nil {
  1891. return
  1892. }
  1893. for i, as := range asr.allocations {
  1894. f(i, as)
  1895. }
  1896. }
  1897. // Get retrieves the AllocationSet at the given index of the range.
  1898. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  1899. if i < 0 || i >= len(asr.allocations) {
  1900. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  1901. }
  1902. asr.RLock()
  1903. defer asr.RUnlock()
  1904. return asr.allocations[i], nil
  1905. }
  1906. // InsertRange merges the given AllocationSetRange into the receiving one by
  1907. // lining up sets with matching windows, then inserting each allocation from
  1908. // the given ASR into the respective set in the receiving ASR. If the given
  1909. // ASR contains an AllocationSet from a window that does not exist in the
  1910. // receiving ASR, then an error is returned. However, the given ASR does not
  1911. // need to cover the full range of the receiver.
  1912. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  1913. if asr == nil {
  1914. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  1915. }
  1916. // keys maps window to index in asr
  1917. keys := map[string]int{}
  1918. asr.Each(func(i int, as *AllocationSet) {
  1919. if as == nil {
  1920. return
  1921. }
  1922. keys[as.Window.String()] = i
  1923. })
  1924. // Nothing to merge, so simply return
  1925. if len(keys) == 0 {
  1926. return nil
  1927. }
  1928. var err error
  1929. that.Each(func(j int, thatAS *AllocationSet) {
  1930. if thatAS == nil || err != nil {
  1931. return
  1932. }
  1933. // Find matching AllocationSet in asr
  1934. i, ok := keys[thatAS.Window.String()]
  1935. if !ok {
  1936. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  1937. return
  1938. }
  1939. as, err := asr.Get(i)
  1940. if err != nil {
  1941. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  1942. return
  1943. }
  1944. // Insert each Allocation from the given set
  1945. thatAS.Each(func(k string, alloc *Allocation) {
  1946. err = as.Insert(alloc)
  1947. if err != nil {
  1948. err = fmt.Errorf("error inserting allocation: %s", err)
  1949. return
  1950. }
  1951. })
  1952. })
  1953. // err might be nil
  1954. return err
  1955. }
  1956. // Length returns the length of the range, which is zero if nil
  1957. func (asr *AllocationSetRange) Length() int {
  1958. if asr == nil || asr.allocations == nil {
  1959. return 0
  1960. }
  1961. asr.RLock()
  1962. defer asr.RUnlock()
  1963. return len(asr.allocations)
  1964. }
  1965. // MarshalJSON JSON-encodes the range
  1966. func (asr *AllocationSetRange) MarshalJSON() ([]byte, error) {
  1967. asr.RLock()
  1968. asr.RUnlock()
  1969. return json.Marshal(asr.allocations)
  1970. }
  1971. // Slice copies the underlying slice of AllocationSets, maintaining order,
  1972. // and returns the copied slice.
  1973. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  1974. if asr == nil || asr.allocations == nil {
  1975. return nil
  1976. }
  1977. asr.RLock()
  1978. defer asr.RUnlock()
  1979. copy := []*AllocationSet{}
  1980. for _, as := range asr.allocations {
  1981. copy = append(copy, as.Clone())
  1982. }
  1983. return copy
  1984. }
  1985. // String represents the given AllocationSetRange as a string
  1986. func (asr *AllocationSetRange) String() string {
  1987. if asr == nil {
  1988. return "<nil>"
  1989. }
  1990. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  1991. }
  1992. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  1993. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  1994. // are sets with conflicting UTCOffsets (just returns the first).
  1995. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  1996. if asr.Length() == 0 {
  1997. return 0
  1998. }
  1999. as, err := asr.Get(0)
  2000. if err != nil {
  2001. return 0
  2002. }
  2003. return as.UTCOffset()
  2004. }
  2005. // Window returns the full window that the AllocationSetRange spans, from the
  2006. // start of the first AllocationSet to the end of the last one.
  2007. func (asr *AllocationSetRange) Window() Window {
  2008. if asr == nil || asr.Length() == 0 {
  2009. return NewWindow(nil, nil)
  2010. }
  2011. start := asr.allocations[0].Start()
  2012. end := asr.allocations[asr.Length()-1].End()
  2013. return NewWindow(&start, &end)
  2014. }